Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7ec01e28bd | ||
|
|
2ade03788b |
No files matched your search
+2
-2
@@ -1,13 +1,13 @@
|
||||
# Scripts
|
||||
|
||||
- `bun run dev` — Starts contracts, server, and web in workspace dev mode.
|
||||
- `bun run dev` — Starts contracts, server, and web in `turbo watch` mode.
|
||||
- `bun run dev:server` — Starts just the WebSocket server (uses Bun TypeScript execution).
|
||||
- `bun run dev:web` — Starts just the Vite dev server for the web app.
|
||||
- Dev commands default `T3CODE_STATE_DIR` to `~/.t3/dev` to keep dev state isolated from desktop/prod state.
|
||||
- Override server CLI-equivalent flags from root dev commands with `--`, for example:
|
||||
`bun run dev -- --base-dir ~/.t3-2`
|
||||
- `bun run start` — Runs the production server (serves built web app as static files).
|
||||
- `bun run build` — Builds workspace packages and apps through Vite+ task running.
|
||||
- `bun run build` — Builds contracts, web app, and server through Turbo.
|
||||
- `bun run typecheck` — Strict TypeScript checks for all packages.
|
||||
- `bun run test` — Runs workspace tests.
|
||||
- `bun run dist:desktop:artifact -- --platform <mac|linux|win> --target <target> --arch <arch>` — Builds a desktop artifact for a specific platform/target/arch.
|
||||
|
||||
@@ -24,11 +24,13 @@ jobs:
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Cache Bun
|
||||
- name: Cache Bun and Turbo
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: ~/.bun/install/cache
|
||||
key: ${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}
|
||||
path: |
|
||||
~/.bun/install/cache
|
||||
.turbo
|
||||
key: ${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-${{ hashFiles('turbo.json') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-
|
||||
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxfmt/configuration_schema.json",
|
||||
"ignorePatterns": [
|
||||
".plans",
|
||||
"dist",
|
||||
"dist-electron",
|
||||
"node_modules",
|
||||
"bun.lock",
|
||||
"*.tsbuildinfo",
|
||||
"**/routeTree.gen.ts",
|
||||
"apps/web/public/mockServiceWorker.js"
|
||||
],
|
||||
"sortPackageJson": {}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"ignorePatterns": [
|
||||
"dist",
|
||||
"dist-electron",
|
||||
"node_modules",
|
||||
"bun.lock",
|
||||
"*.tsbuildinfo",
|
||||
"**/routeTree.gen.ts"
|
||||
],
|
||||
"plugins": ["eslint", "oxc", "react", "unicorn", "typescript"],
|
||||
"categories": {
|
||||
"correctness": "warn",
|
||||
"suspicious": "warn",
|
||||
"perf": "warn"
|
||||
},
|
||||
"rules": {
|
||||
"react-in-jsx-scope": "off",
|
||||
"eslint/no-shadow": "off",
|
||||
"eslint/no-await-in-loop": "off"
|
||||
}
|
||||
}
|
||||
@@ -5,12 +5,12 @@
|
||||
"main": "dist-electron/main.js",
|
||||
"scripts": {
|
||||
"dev": "bun run --parallel dev:bundle dev:electron",
|
||||
"dev:bundle": "vp pack --watch",
|
||||
"dev:bundle": "tsdown --watch",
|
||||
"dev:electron": "bun run scripts/dev-electron.mjs",
|
||||
"build": "vp pack",
|
||||
"build": "tsdown",
|
||||
"start": "bun run scripts/start-electron.mjs",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vp test run --passWithNoTests",
|
||||
"test": "vitest run --passWithNoTests",
|
||||
"smoke-test": "node scripts/smoke-test.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -22,8 +22,10 @@
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@types/node": "catalog:",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vite-plus": "catalog:"
|
||||
"vitest": "catalog:",
|
||||
"wait-on": "^8.0.2"
|
||||
},
|
||||
"productName": "T3 Code (Alpha)"
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { watch } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import waitOn from "wait-on";
|
||||
|
||||
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
||||
import { waitForResources } from "./wait-for-resources.mjs";
|
||||
|
||||
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733);
|
||||
const devServerUrl = `http://localhost:${port}`;
|
||||
@@ -20,10 +20,8 @@ const forcedShutdownTimeoutMs = 1_500;
|
||||
const restartDebounceMs = 120;
|
||||
const childTreeGracePeriodMs = 1_200;
|
||||
|
||||
await waitForResources({
|
||||
baseDir: desktopDir,
|
||||
files: requiredFiles,
|
||||
tcpPort: port,
|
||||
await waitOn({
|
||||
resources: [`tcp:${port}`, ...requiredFiles.map((filePath) => `file:${filePath}`)],
|
||||
});
|
||||
|
||||
const childEnv = { ...process.env };
|
||||
|
||||
@@ -1,119 +0,0 @@
|
||||
import * as FileSystem from "node:fs/promises";
|
||||
import * as Net from "node:net";
|
||||
import * as Path from "node:path";
|
||||
import * as Timers from "node:timers/promises";
|
||||
|
||||
const defaultTcpHosts = ["127.0.0.1", "localhost", "::1"];
|
||||
|
||||
async function fileExists(filePath) {
|
||||
try {
|
||||
await FileSystem.access(filePath);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function tcpPortIsReady({ host, port, connectTimeoutMs = 500 }) {
|
||||
return new Promise((resolveReady) => {
|
||||
const socket = Net.createConnection({ host, port });
|
||||
let settled = false;
|
||||
|
||||
const finish = (ready) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
|
||||
settled = true;
|
||||
socket.removeAllListeners();
|
||||
socket.destroy();
|
||||
resolveReady(ready);
|
||||
};
|
||||
|
||||
socket.once("connect", () => {
|
||||
finish(true);
|
||||
});
|
||||
socket.once("timeout", () => {
|
||||
finish(false);
|
||||
});
|
||||
socket.once("error", () => {
|
||||
finish(false);
|
||||
});
|
||||
socket.setTimeout(connectTimeoutMs);
|
||||
});
|
||||
}
|
||||
|
||||
async function resolvePendingResources({ baseDir, files, tcpPort, tcpHosts, connectTimeoutMs }) {
|
||||
const pendingFiles = [];
|
||||
|
||||
for (const relativeFilePath of files) {
|
||||
const ready = await fileExists(Path.resolve(baseDir, relativeFilePath));
|
||||
if (!ready) {
|
||||
pendingFiles.push(relativeFilePath);
|
||||
}
|
||||
}
|
||||
|
||||
let tcpReady = false;
|
||||
for (const host of tcpHosts) {
|
||||
tcpReady = await tcpPortIsReady({
|
||||
host,
|
||||
port: tcpPort,
|
||||
connectTimeoutMs,
|
||||
});
|
||||
if (tcpReady) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
pendingFiles,
|
||||
tcpReady,
|
||||
};
|
||||
}
|
||||
|
||||
export async function waitForResources({
|
||||
baseDir,
|
||||
files = [],
|
||||
intervalMs = 100,
|
||||
timeoutMs = 120_000,
|
||||
tcpHost,
|
||||
tcpPort,
|
||||
connectTimeoutMs = 500,
|
||||
}) {
|
||||
if (!Number.isInteger(tcpPort) || tcpPort <= 0) {
|
||||
throw new TypeError("waitForResources requires a positive integer tcpPort");
|
||||
}
|
||||
|
||||
const startedAt = Date.now();
|
||||
const tcpHosts = tcpHost ? [tcpHost] : defaultTcpHosts;
|
||||
|
||||
while (true) {
|
||||
const { pendingFiles, tcpReady } = await resolvePendingResources({
|
||||
baseDir,
|
||||
files,
|
||||
tcpPort,
|
||||
tcpHosts,
|
||||
connectTimeoutMs,
|
||||
});
|
||||
|
||||
if (pendingFiles.length === 0 && tcpReady) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (Date.now() - startedAt >= timeoutMs) {
|
||||
const pendingResources = [];
|
||||
if (!tcpReady) {
|
||||
pendingResources.push(tcpHost ? `tcp:${tcpHost}:${tcpPort}` : `tcp:${tcpPort}`);
|
||||
}
|
||||
for (const filePath of pendingFiles) {
|
||||
pendingResources.push(`file:${filePath}`);
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`Timed out waiting for desktop dev resources after ${timeoutMs}ms: ${pendingResources.join(", ")}`,
|
||||
);
|
||||
}
|
||||
|
||||
await Timers.setTimeout(intervalMs);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { BrowserWindow } from "electron";
|
||||
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const { showMessageBoxMock } = vi.hoisted(() => ({
|
||||
showMessageBoxMock: vi.fn(),
|
||||
|
||||
@@ -99,7 +99,7 @@ let destructiveMenuIconCache: Electron.NativeImage | null | undefined;
|
||||
const desktopRuntimeInfo = resolveDesktopRuntimeInfo({
|
||||
platform: process.platform,
|
||||
processArch: process.arch,
|
||||
runningUnderArm64Translation: app.runningUnderARM64Translation,
|
||||
runningUnderArm64Translation: app.runningUnderARM64Translation === true,
|
||||
});
|
||||
const initialUpdateState = (): DesktopUpdateState =>
|
||||
createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo);
|
||||
|
||||
@@ -3,7 +3,7 @@ import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { RotatingFileSink } from "@t3tools/shared/logging";
|
||||
import { afterEach, describe, expect, it } from "vite-plus/test";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
const tempRoots: string[] = [];
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { syncShellEnvironment } from "./syncShellEnvironment";
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
createInitialDesktopUpdateState,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { DesktopUpdateState } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
|
||||
@@ -5,6 +5,5 @@
|
||||
"types": ["node", "electron"],
|
||||
"lib": ["ES2023", "DOM", "esnext.disposable"]
|
||||
},
|
||||
"include": ["src", "vite.config.ts", "../../packages/contracts/src", "../../packages/shared/src"],
|
||||
"exclude": ["../../packages/contracts/src/**/*.test.ts", "../../packages/shared/src/**/*.test.ts"]
|
||||
"include": ["src", "tsdown.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { defineConfig } from "tsdown";
|
||||
|
||||
const shared = {
|
||||
format: "cjs" as const,
|
||||
outDir: "dist-electron",
|
||||
sourcemap: true,
|
||||
outExtensions: () => ({ js: ".js" }),
|
||||
};
|
||||
|
||||
export default defineConfig([
|
||||
{
|
||||
...shared,
|
||||
entry: ["src/main.ts"],
|
||||
clean: true,
|
||||
noExternal: (id) => id.startsWith("@t3tools/"),
|
||||
},
|
||||
{
|
||||
...shared,
|
||||
entry: ["src/preload.ts"],
|
||||
},
|
||||
]);
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"$schema": "https://turbo.build/schema.json",
|
||||
"extends": ["//"],
|
||||
"tasks": {
|
||||
"build": {
|
||||
"dependsOn": ["^build"],
|
||||
"outputs": ["dist-electron/**"],
|
||||
},
|
||||
"dev": {
|
||||
"dependsOn": ["t3#build"],
|
||||
"persistent": true,
|
||||
},
|
||||
"start": {
|
||||
"dependsOn": ["build", "@t3tools/web#build", "t3#build"],
|
||||
"cache": false,
|
||||
"persistent": true,
|
||||
},
|
||||
"smoke-test": {
|
||||
"dependsOn": ["build", "@t3tools/web#build", "t3#build"],
|
||||
"cache": false,
|
||||
"outputs": [],
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
import * as path from "node:path";
|
||||
|
||||
import { defineConfig } from "vite-plus";
|
||||
|
||||
const shared = {
|
||||
format: "cjs" as const,
|
||||
outDir: "dist-electron",
|
||||
sourcemap: true,
|
||||
outExtensions: () => ({ js: ".js" }),
|
||||
};
|
||||
|
||||
export default defineConfig({
|
||||
resolve: {
|
||||
tsconfigPaths: true,
|
||||
alias: [
|
||||
{
|
||||
find: /^@t3tools\/contracts$/,
|
||||
replacement: path.resolve(import.meta.dirname, "../../packages/contracts/src/index.ts"),
|
||||
},
|
||||
{
|
||||
find: /^@t3tools\/contracts\/settings$/,
|
||||
replacement: path.resolve(import.meta.dirname, "../../packages/contracts/src/settings.ts"),
|
||||
},
|
||||
{
|
||||
find: /^@t3tools\/shared\/(.*)$/,
|
||||
replacement: path.resolve(import.meta.dirname, "../../packages/shared/src/$1.ts"),
|
||||
},
|
||||
],
|
||||
},
|
||||
pack: [
|
||||
{
|
||||
...shared,
|
||||
entry: ["src/main.ts"],
|
||||
clean: true,
|
||||
noExternal: (id) => id.startsWith("@t3tools/"),
|
||||
},
|
||||
{
|
||||
...shared,
|
||||
entry: ["src/preload.ts"],
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -68,7 +68,6 @@ import {
|
||||
type TestProviderAdapterHarness,
|
||||
} from "./TestProviderAdapter.integration.ts";
|
||||
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
|
||||
import { WorkspaceEntriesLive } from "../src/workspace/Layers/WorkspaceEntries.ts";
|
||||
|
||||
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||
return execFileSync("git", args, {
|
||||
@@ -114,19 +113,19 @@ function waitFor<A, E>(
|
||||
predicate: (value: A) => boolean,
|
||||
description: string,
|
||||
timeoutMs?: number,
|
||||
): Effect.Effect<A>;
|
||||
): Effect.Effect<A, never>;
|
||||
function waitFor<A, B extends A, E>(
|
||||
read: Effect.Effect<A, E>,
|
||||
predicate: (value: A) => value is B,
|
||||
description: string,
|
||||
timeoutMs?: number,
|
||||
): Effect.Effect<B>;
|
||||
): Effect.Effect<B, never>;
|
||||
function waitFor<A, E>(
|
||||
read: Effect.Effect<A, E>,
|
||||
predicate: (value: A) => boolean,
|
||||
description: string,
|
||||
timeoutMs = 10_000,
|
||||
): Effect.Effect<A> {
|
||||
): Effect.Effect<A, never> {
|
||||
const RETRY_SIGNAL = "wait_for_retry";
|
||||
const retryIntervalMs = 10;
|
||||
const maxRetries = Math.max(0, Math.floor(timeoutMs / retryIntervalMs));
|
||||
@@ -175,11 +174,11 @@ export interface OrchestrationIntegrationHarness {
|
||||
threadId: string,
|
||||
predicate: (thread: OrchestrationThread) => boolean,
|
||||
timeoutMs?: number,
|
||||
) => Effect.Effect<OrchestrationThread>;
|
||||
) => Effect.Effect<OrchestrationThread, never>;
|
||||
readonly waitForDomainEvent: (
|
||||
predicate: (event: OrchestrationEvent) => boolean,
|
||||
timeoutMs?: number,
|
||||
) => Effect.Effect<ReadonlyArray<OrchestrationEvent>>;
|
||||
) => Effect.Effect<ReadonlyArray<OrchestrationEvent>, never>;
|
||||
readonly waitForPendingApproval: (
|
||||
requestId: string,
|
||||
predicate: (row: {
|
||||
@@ -188,22 +187,25 @@ export interface OrchestrationIntegrationHarness {
|
||||
readonly resolvedAt: string | null;
|
||||
}) => boolean,
|
||||
timeoutMs?: number,
|
||||
) => Effect.Effect<{
|
||||
readonly status: "pending" | "resolved";
|
||||
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
|
||||
readonly resolvedAt: string | null;
|
||||
}>;
|
||||
) => Effect.Effect<
|
||||
{
|
||||
readonly status: "pending" | "resolved";
|
||||
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
|
||||
readonly resolvedAt: string | null;
|
||||
},
|
||||
never
|
||||
>;
|
||||
readonly waitForReceipt: {
|
||||
(
|
||||
predicate: (receipt: OrchestrationRuntimeReceipt) => boolean,
|
||||
timeoutMs?: number,
|
||||
): Effect.Effect<OrchestrationRuntimeReceipt>;
|
||||
): Effect.Effect<OrchestrationRuntimeReceipt, never>;
|
||||
<Receipt extends OrchestrationRuntimeReceipt>(
|
||||
predicate: (receipt: OrchestrationRuntimeReceipt) => receipt is Receipt,
|
||||
timeoutMs?: number,
|
||||
): Effect.Effect<Receipt>;
|
||||
): Effect.Effect<Receipt, never>;
|
||||
};
|
||||
readonly dispose: Effect.Effect<void>;
|
||||
readonly dispose: Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
interface MakeOrchestrationIntegrationHarnessOptions {
|
||||
@@ -315,12 +317,6 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
);
|
||||
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(
|
||||
WorkspaceEntriesLive.pipe(
|
||||
Layer.provideMerge(gitCoreLayer),
|
||||
Layer.provide(NodeServices.layer),
|
||||
),
|
||||
),
|
||||
);
|
||||
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeIngestionLayer),
|
||||
@@ -388,7 +384,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
(thread): thread is OrchestrationThread => thread !== null && predicate(thread),
|
||||
`projected thread '${threadId}'`,
|
||||
timeoutMs,
|
||||
) as Effect.Effect<OrchestrationThread>;
|
||||
) as Effect.Effect<OrchestrationThread, never>;
|
||||
|
||||
const waitForDomainEvent: OrchestrationIntegrationHarness["waitForDomainEvent"] = (
|
||||
predicate,
|
||||
@@ -432,20 +428,23 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
} => row !== null && predicate(row),
|
||||
`pending approval '${requestId}'`,
|
||||
timeoutMs,
|
||||
) as Effect.Effect<{
|
||||
readonly status: "pending" | "resolved";
|
||||
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
|
||||
readonly resolvedAt: string | null;
|
||||
}>;
|
||||
) as Effect.Effect<
|
||||
{
|
||||
readonly status: "pending" | "resolved";
|
||||
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
|
||||
readonly resolvedAt: string | null;
|
||||
},
|
||||
never
|
||||
>;
|
||||
|
||||
function waitForReceipt(
|
||||
predicate: (receipt: OrchestrationRuntimeReceipt) => boolean,
|
||||
timeoutMs?: number,
|
||||
): Effect.Effect<OrchestrationRuntimeReceipt>;
|
||||
): Effect.Effect<OrchestrationRuntimeReceipt, never>;
|
||||
function waitForReceipt<Receipt extends OrchestrationRuntimeReceipt>(
|
||||
predicate: (receipt: OrchestrationRuntimeReceipt) => receipt is Receipt,
|
||||
timeoutMs?: number,
|
||||
): Effect.Effect<Receipt>;
|
||||
): Effect.Effect<Receipt, never>;
|
||||
function waitForReceipt(
|
||||
predicate: (receipt: OrchestrationRuntimeReceipt) => boolean,
|
||||
timeoutMs?: number,
|
||||
|
||||
@@ -30,7 +30,7 @@ export interface TestTurnResponse {
|
||||
readonly mutateWorkspace?: (input: {
|
||||
readonly cwd: string;
|
||||
readonly turnCount: number;
|
||||
}) => Effect.Effect<void>;
|
||||
}) => Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
export type FixtureProviderRuntimeEvent = {
|
||||
@@ -183,7 +183,9 @@ export interface TestProviderAdapterHarness {
|
||||
threadId: ThreadId,
|
||||
response: TestTurnResponse,
|
||||
) => Effect.Effect<void, ProviderAdapterSessionNotFoundError>;
|
||||
readonly queueTurnResponseForNextSession: (response: TestTurnResponse) => Effect.Effect<void>;
|
||||
readonly queueTurnResponseForNextSession: (
|
||||
response: TestTurnResponse,
|
||||
) => Effect.Effect<void, never>;
|
||||
readonly getStartCount: () => number;
|
||||
readonly getRollbackCalls: (threadId: ThreadId) => ReadonlyArray<number>;
|
||||
readonly getInterruptCalls: (threadId: ThreadId) => ReadonlyArray<TurnId | undefined>;
|
||||
@@ -335,7 +337,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
}
|
||||
|
||||
if (response.mutateWorkspace && state.session.cwd) {
|
||||
yield* response.mutateWorkspace({ cwd: state.session.cwd, turnCount });
|
||||
yield* response.mutateWorkspace({ cwd: state.session.cwd!, turnCount });
|
||||
}
|
||||
|
||||
const userItem = {
|
||||
@@ -503,7 +505,9 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
),
|
||||
);
|
||||
|
||||
const queueTurnResponseForNextSession = (response: TestTurnResponse): Effect.Effect<void> =>
|
||||
const queueTurnResponseForNextSession = (
|
||||
response: TestTurnResponse,
|
||||
): Effect.Effect<void, never> =>
|
||||
Effect.sync(() => {
|
||||
queuedResponsesForNextSession.push(response);
|
||||
});
|
||||
|
||||
@@ -58,7 +58,7 @@ function waitForSync<A>(
|
||||
predicate: (value: A) => boolean,
|
||||
description: string,
|
||||
timeoutMs = 3000,
|
||||
): Effect.Effect<A> {
|
||||
): Effect.Effect<A, never> {
|
||||
return Effect.gen(function* () {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
|
||||
@@ -226,7 +226,9 @@ it.live("runs a single turn end-to-end and persists checkpoint state in sqlite +
|
||||
THREAD_ID,
|
||||
(entry) =>
|
||||
entry.session?.status === "ready" &&
|
||||
entry.messages.some((message) => message.role === "assistant" && !message.streaming) &&
|
||||
entry.messages.some(
|
||||
(message) => message.role === "assistant" && message.streaming === false,
|
||||
) &&
|
||||
entry.checkpoints.length === 1,
|
||||
);
|
||||
assert.equal(thread.checkpoints[0]?.status, "ready");
|
||||
@@ -307,7 +309,9 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
||||
(entry) =>
|
||||
entry.session?.status === "ready" &&
|
||||
entry.session.providerName === "codex" &&
|
||||
entry.messages.some((message) => message.role === "assistant" && !message.streaming),
|
||||
entry.messages.some(
|
||||
(message) => message.role === "assistant" && message.streaming === false,
|
||||
),
|
||||
180_000,
|
||||
);
|
||||
assert.equal(firstThread.session?.threadId, "thread-1");
|
||||
|
||||
@@ -40,7 +40,7 @@ const makeWorkspaceDirectory = Effect.gen(function* () {
|
||||
interface IntegrationFixture {
|
||||
readonly cwd: string;
|
||||
readonly harness: TestProviderAdapterHarness;
|
||||
readonly layer: Layer.Layer<ProviderService, unknown>;
|
||||
readonly layer: Layer.Layer<ProviderService, unknown, never>;
|
||||
}
|
||||
|
||||
const makeIntegrationFixture = Effect.gen(function* () {
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
"start": "node dist/index.mjs",
|
||||
"prepare": "effect-language-service patch",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vp test run"
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.77",
|
||||
@@ -29,7 +29,6 @@
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"effect": "catalog:",
|
||||
"node-pty": "^1.1.0",
|
||||
"open": "^10.1.0",
|
||||
"ws": "^8.18.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -41,8 +40,9 @@
|
||||
"@types/bun": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
"@types/ws": "^8.5.13",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vite-plus": "catalog:"
|
||||
"vitest": "catalog:"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^22.16 || ^23.11 || >=24.10"
|
||||
|
||||
@@ -10,10 +10,7 @@ import {
|
||||
DEVELOPMENT_ICON_OVERRIDES,
|
||||
PUBLISH_ICON_OVERRIDES,
|
||||
} from "../../../scripts/lib/brand-assets.ts";
|
||||
import {
|
||||
getWorkspaceCatalog,
|
||||
resolveCatalogDependencies,
|
||||
} from "../../../scripts/lib/resolve-catalog.ts";
|
||||
import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";
|
||||
import rootPackageJson from "../../../package.json" with { type: "json" };
|
||||
import serverPackageJson from "../package.json" with { type: "json" };
|
||||
|
||||
@@ -25,7 +22,6 @@ class CliError extends Data.TaggedError("CliError")<{
|
||||
const RepoRoot = Effect.service(Path.Path).pipe(
|
||||
Effect.flatMap((path) => path.fromFileUrl(new URL("../../..", import.meta.url))),
|
||||
);
|
||||
const workspaceCatalog = getWorkspaceCatalog(rootPackageJson);
|
||||
|
||||
const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.Command) {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
@@ -133,7 +129,7 @@ const buildCmd = Command.make(
|
||||
const repoRoot = yield* RepoRoot;
|
||||
const serverDir = path.join(repoRoot, "apps/server");
|
||||
|
||||
yield* Effect.log("[cli] Running vp pack...");
|
||||
yield* Effect.log("[cli] Running tsdown...");
|
||||
yield* runCommand(
|
||||
ChildProcess.make({
|
||||
cwd: serverDir,
|
||||
@@ -141,7 +137,7 @@ const buildCmd = Command.make(
|
||||
stderr: "inherit",
|
||||
// Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
|
||||
shell: process.platform === "win32",
|
||||
})`vp pack`,
|
||||
})`bun tsdown`,
|
||||
);
|
||||
|
||||
const webDist = path.join(repoRoot, "apps/web/dist");
|
||||
@@ -155,7 +151,7 @@ const buildCmd = Command.make(
|
||||
yield* Effect.logWarning("[cli] Web dist not found — skipping client bundle.");
|
||||
}
|
||||
}),
|
||||
).pipe(Command.withDescription("Build the server package (vp pack + bundle web client)."));
|
||||
).pipe(Command.withDescription("Build the server package (tsdown + bundle web client)."));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// publish subcommand
|
||||
@@ -209,7 +205,7 @@ const publishCmd = Command.make(
|
||||
|
||||
pkg.dependencies = resolveCatalogDependencies(
|
||||
pkg.dependencies,
|
||||
workspaceCatalog,
|
||||
rootPackageJson.workspaces.catalog,
|
||||
"apps/server dependencies",
|
||||
);
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
createAttachmentId,
|
||||
|
||||
@@ -8,7 +8,7 @@ import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import { TestClock } from "effect/testing";
|
||||
import { vi } from "vite-plus/test";
|
||||
import { vi } from "vitest";
|
||||
|
||||
import { readBootstrapEnvelope, resolveFdPath } from "./bootstrap";
|
||||
import { assertNone, assertSome } from "@effect/vitest/utils";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseTurnDiffFilesFromUnifiedDiff } from "./Diffs.ts";
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
type OrchestrationReadModel,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { checkpointRefForThreadTurn } from "../Utils.ts";
|
||||
|
||||
@@ -3,7 +3,7 @@ import path from "node:path";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
|
||||
import { describe, expect } from "vite-plus/test";
|
||||
import { describe, expect } from "vitest";
|
||||
|
||||
import { checkpointRefForThreadTurn } from "../Utils.ts";
|
||||
import { CheckpointStoreLive } from "./CheckpointStore.ts";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import os from "node:os";
|
||||
|
||||
@@ -432,7 +432,7 @@ export interface CodexAppServerManagerEvents {
|
||||
export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEvents> {
|
||||
private readonly sessions = new Map<ThreadId, CodexSessionContext>();
|
||||
|
||||
private runPromise: (effect: Effect.Effect<unknown>) => Promise<unknown>;
|
||||
private runPromise: (effect: Effect.Effect<unknown, never>) => Promise<unknown>;
|
||||
constructor(services?: ServiceMap.ServiceMap<never>) {
|
||||
super();
|
||||
this.runPromise = services ? Effect.runPromiseWith(services) : Effect.runPromise;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
import { expect } from "vite-plus/test";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path, Result } from "effect";
|
||||
import { expect } from "vite-plus/test";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
|
||||
|
||||
@@ -82,7 +82,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
);
|
||||
};
|
||||
|
||||
const safeUnlink = (filePath: string): Effect.Effect<void> =>
|
||||
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
|
||||
fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
const materializeImageAttachments = (
|
||||
|
||||
@@ -4,7 +4,7 @@ import path from "node:path";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
|
||||
import { describe, expect, vi } from "vite-plus/test";
|
||||
import { describe, expect, vi } from "vitest";
|
||||
|
||||
import { GitCoreLive, makeGitCore } from "./GitCore.ts";
|
||||
import { GitCore, type GitCoreShape } from "../Services/GitCore.ts";
|
||||
@@ -138,13 +138,6 @@ function buildLargeText(lineCount = 20_000): string {
|
||||
.concat("\n");
|
||||
}
|
||||
|
||||
function splitNullSeparatedPaths(input: string): string[] {
|
||||
return input
|
||||
.split("\0")
|
||||
.map((value) => value.trim())
|
||||
.filter((value) => value.length > 0);
|
||||
}
|
||||
|
||||
// ── Tests ──
|
||||
|
||||
it.layer(TestLayer)("git integration", (it) => {
|
||||
@@ -188,55 +181,6 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
);
|
||||
});
|
||||
|
||||
describe("workspace helpers", () => {
|
||||
it.effect("filterIgnoredPaths chunks large path lists and preserves kept paths", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = "/virtual/repo";
|
||||
const relativePaths = Array.from({ length: 340 }, (_, index) => {
|
||||
const prefix = index % 3 === 0 ? "ignored" : "kept";
|
||||
return `${prefix}/segment-${String(index).padStart(4, "0")}/${"x".repeat(900)}.ts`;
|
||||
});
|
||||
const expectedPaths = relativePaths.filter(
|
||||
(relativePath) => !relativePath.startsWith("ignored/"),
|
||||
);
|
||||
|
||||
const seenChunks: string[][] = [];
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
if (input.args.join(" ") !== "check-ignore --no-index -z --stdin") {
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: `git ${input.args.join(" ")}`,
|
||||
cwd: input.cwd,
|
||||
detail: "unexpected git command in chunking test",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const chunkPaths = splitNullSeparatedPaths(input.stdin ?? "");
|
||||
seenChunks.push(chunkPaths);
|
||||
const ignoredPaths = chunkPaths.filter((relativePath) =>
|
||||
relativePath.startsWith("ignored/"),
|
||||
);
|
||||
|
||||
return Effect.succeed({
|
||||
code: ignoredPaths.length > 0 ? 0 : 1,
|
||||
stdout: ignoredPaths.length > 0 ? `${ignoredPaths.join("\0")}\0` : "",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
});
|
||||
|
||||
const result = yield* core.filterIgnoredPaths(cwd, relativePaths);
|
||||
|
||||
expect(seenChunks.length).toBeGreaterThan(1);
|
||||
expect(seenChunks.flat()).toEqual(relativePaths);
|
||||
expect(result).toEqual(expectedPaths);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// ── listGitBranches ──
|
||||
|
||||
describe("listGitBranches", () => {
|
||||
@@ -374,7 +318,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const result = yield* (yield* GitCore).listBranches({ cwd: tmp });
|
||||
expect(result.branches.every((b) => !b.isDefault)).toBe(true);
|
||||
expect(result.branches.every((b) => b.isDefault === false)).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -513,18 +457,12 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
yield* (yield* GitCore).checkoutBranch({ cwd: source, branch: featureBranch });
|
||||
const core = yield* GitCore;
|
||||
yield* Effect.promise(() =>
|
||||
vi.waitFor(
|
||||
async () => {
|
||||
const details = await runPromise(core.statusDetails(source));
|
||||
expect(details.branch).toBe(featureBranch);
|
||||
expect(details.aheadCount).toBe(0);
|
||||
expect(details.behindCount).toBe(1);
|
||||
},
|
||||
{
|
||||
timeout: 10_000,
|
||||
interval: 100,
|
||||
},
|
||||
),
|
||||
vi.waitFor(async () => {
|
||||
const details = await runPromise(core.statusDetails(source));
|
||||
expect(details.branch).toBe(featureBranch);
|
||||
expect(details.aheadCount).toBe(0);
|
||||
expect(details.behindCount).toBe(1);
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
@@ -603,13 +541,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
if (input.args[0] === "fetch") {
|
||||
fetchArgs = [...input.args];
|
||||
return Effect.succeed({
|
||||
code: 0,
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
return Effect.succeed({ code: 0, stdout: "", stderr: "" });
|
||||
}
|
||||
return realGitCore.execute(input);
|
||||
});
|
||||
@@ -662,13 +594,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
if (input.args[0] === "fetch") {
|
||||
fetchStarted = true;
|
||||
return Effect.promise(() =>
|
||||
waitForReleasePromise.then(() => ({
|
||||
code: 0,
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
})),
|
||||
waitForReleasePromise.then(() => ({ code: 0, stdout: "", stderr: "" })),
|
||||
);
|
||||
}
|
||||
return realGitCore.execute(input);
|
||||
|
||||
@@ -37,8 +37,6 @@ const PREPARED_COMMIT_PATCH_MAX_OUTPUT_BYTES = 49_000;
|
||||
const RANGE_COMMIT_SUMMARY_MAX_OUTPUT_BYTES = 19_000;
|
||||
const RANGE_DIFF_SUMMARY_MAX_OUTPUT_BYTES = 19_000;
|
||||
const RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES = 59_000;
|
||||
const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
|
||||
const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
|
||||
const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
|
||||
const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
|
||||
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
|
||||
@@ -57,7 +55,6 @@ class StatusUpstreamRefreshCacheKey extends Data.Class<{
|
||||
}> {}
|
||||
|
||||
interface ExecuteGitOptions {
|
||||
stdin?: string | undefined;
|
||||
timeoutMs?: number | undefined;
|
||||
allowNonZeroExit?: boolean | undefined;
|
||||
fallbackErrorMessage?: string | undefined;
|
||||
@@ -99,47 +96,6 @@ function parseNumstatEntries(
|
||||
return entries;
|
||||
}
|
||||
|
||||
function splitNullSeparatedPaths(input: string, truncated: boolean): string[] {
|
||||
const parts = input.split("\0");
|
||||
if (parts.length === 0) return [];
|
||||
|
||||
if (truncated && parts[parts.length - 1]?.length) {
|
||||
parts.pop();
|
||||
}
|
||||
|
||||
return parts.filter((value) => value.length > 0);
|
||||
}
|
||||
|
||||
function chunkPathsForGitCheckIgnore(relativePaths: readonly string[]): string[][] {
|
||||
const chunks: string[][] = [];
|
||||
let chunk: string[] = [];
|
||||
let chunkBytes = 0;
|
||||
|
||||
for (const relativePath of relativePaths) {
|
||||
const relativePathBytes = Buffer.byteLength(relativePath) + 1;
|
||||
if (chunk.length > 0 && chunkBytes + relativePathBytes > GIT_CHECK_IGNORE_MAX_STDIN_BYTES) {
|
||||
chunks.push(chunk);
|
||||
chunk = [];
|
||||
chunkBytes = 0;
|
||||
}
|
||||
|
||||
chunk.push(relativePath);
|
||||
chunkBytes += relativePathBytes;
|
||||
|
||||
if (chunkBytes >= GIT_CHECK_IGNORE_MAX_STDIN_BYTES) {
|
||||
chunks.push(chunk);
|
||||
chunk = [];
|
||||
chunkBytes = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (chunk.length > 0) {
|
||||
chunks.push(chunk);
|
||||
}
|
||||
|
||||
return chunks;
|
||||
}
|
||||
|
||||
function parsePorcelainPath(line: string): string | null {
|
||||
if (line.startsWith("? ") || line.startsWith("! ")) {
|
||||
const simple = line.slice(2).trim();
|
||||
@@ -324,7 +280,7 @@ function toGitCommandError(
|
||||
|
||||
interface Trace2Monitor {
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly flush: Effect.Effect<void>;
|
||||
readonly flush: Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
function trace2ChildKey(record: Record<string, unknown>): string | null {
|
||||
@@ -488,8 +444,8 @@ const collectOutput = Effect.fn("collectOutput")(function* <E>(
|
||||
stream: Stream.Stream<Uint8Array, E>,
|
||||
maxOutputBytes: number,
|
||||
truncateOutputAtMaxBytes: boolean,
|
||||
onLine: ((line: string) => Effect.Effect<void>) | undefined,
|
||||
): Effect.fn.Return<{ readonly text: string; readonly truncated: boolean }, GitCommandError> {
|
||||
onLine: ((line: string) => Effect.Effect<void, never>) | undefined,
|
||||
): Effect.fn.Return<string, GitCommandError> {
|
||||
const decoder = new TextDecoder();
|
||||
let bytes = 0;
|
||||
let text = "";
|
||||
@@ -551,10 +507,7 @@ const collectOutput = Effect.fn("collectOutput")(function* <E>(
|
||||
text += remainder;
|
||||
lineBuffer += remainder;
|
||||
yield* emitCompleteLines(true);
|
||||
return {
|
||||
text,
|
||||
truncated,
|
||||
};
|
||||
return truncated ? `${text}${OUTPUT_TRUNCATED_MARKER}` : text;
|
||||
});
|
||||
|
||||
export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
@@ -618,18 +571,13 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
Effect.map((value) => Number(value)),
|
||||
Effect.mapError(toGitCommandError(commandInput, "failed to report exit code.")),
|
||||
),
|
||||
input.stdin === undefined
|
||||
? Effect.void
|
||||
: Stream.run(Stream.encodeText(Stream.make(input.stdin)), child.stdin).pipe(
|
||||
Effect.mapError(toGitCommandError(commandInput, "failed to write stdin.")),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
).pipe(Effect.map(([stdout, stderr, exitCode]) => [stdout, stderr, exitCode] as const));
|
||||
);
|
||||
yield* trace2Monitor.flush;
|
||||
|
||||
if (!input.allowNonZeroExit && exitCode !== 0) {
|
||||
const trimmedStderr = stderr.text.trim();
|
||||
const trimmedStderr = stderr.trim();
|
||||
return yield* new GitCommandError({
|
||||
operation: commandInput.operation,
|
||||
command: quoteGitCommand(commandInput.args),
|
||||
@@ -641,13 +589,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
code: exitCode,
|
||||
stdout: stdout.text,
|
||||
stderr: stderr.text,
|
||||
stdoutTruncated: stdout.truncated,
|
||||
stderrTruncated: stderr.truncated,
|
||||
} satisfies ExecuteGitResult;
|
||||
return { code: exitCode, stdout, stderr } satisfies ExecuteGitResult;
|
||||
});
|
||||
|
||||
return yield* runGitCommand().pipe(
|
||||
@@ -676,12 +618,11 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
cwd: string,
|
||||
args: readonly string[],
|
||||
options: ExecuteGitOptions = {},
|
||||
): Effect.Effect<ExecuteGitResult, GitCommandError> =>
|
||||
): Effect.Effect<{ code: number; stdout: string; stderr: string }, GitCommandError> =>
|
||||
execute({
|
||||
operation,
|
||||
cwd,
|
||||
args,
|
||||
...(options.stdin !== undefined ? { stdin: options.stdin } : {}),
|
||||
allowNonZeroExit: true,
|
||||
...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
|
||||
...(options.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}),
|
||||
@@ -738,11 +679,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
args: readonly string[],
|
||||
options: ExecuteGitOptions = {},
|
||||
): Effect.Effect<string, GitCommandError> =>
|
||||
executeGit(operation, cwd, args, options).pipe(
|
||||
Effect.map((result) =>
|
||||
result.stdoutTruncated ? `${result.stdout}${OUTPUT_TRUNCATED_MARKER}` : result.stdout,
|
||||
),
|
||||
);
|
||||
executeGit(operation, cwd, args, options).pipe(Effect.map((result) => result.stdout));
|
||||
|
||||
const branchExists = (cwd: string, branch: string): Effect.Effect<boolean, GitCommandError> =>
|
||||
executeGit(
|
||||
@@ -1479,86 +1416,6 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)),
|
||||
);
|
||||
|
||||
const isInsideWorkTree: GitCoreShape["isInsideWorkTree"] = (cwd) =>
|
||||
executeGit("GitCore.isInsideWorkTree", cwd, ["rev-parse", "--is-inside-work-tree"], {
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 5_000,
|
||||
maxOutputBytes: 4_096,
|
||||
}).pipe(Effect.map((result) => result.code === 0 && result.stdout.trim() === "true"));
|
||||
|
||||
const listWorkspaceFiles: GitCoreShape["listWorkspaceFiles"] = (cwd) =>
|
||||
executeGit(
|
||||
"GitCore.listWorkspaceFiles",
|
||||
cwd,
|
||||
["ls-files", "--cached", "--others", "--exclude-standard", "-z"],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 20_000,
|
||||
maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
|
||||
truncateOutputAtMaxBytes: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result.code === 0
|
||||
? Effect.succeed({
|
||||
paths: splitNullSeparatedPaths(result.stdout, result.stdoutTruncated),
|
||||
truncated: result.stdoutTruncated,
|
||||
})
|
||||
: Effect.fail(
|
||||
createGitCommandError(
|
||||
"GitCore.listWorkspaceFiles",
|
||||
cwd,
|
||||
["ls-files", "--cached", "--others", "--exclude-standard", "-z"],
|
||||
result.stderr.trim().length > 0 ? result.stderr.trim() : "git ls-files failed",
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const filterIgnoredPaths: GitCoreShape["filterIgnoredPaths"] = (cwd, relativePaths) =>
|
||||
Effect.gen(function* () {
|
||||
if (relativePaths.length === 0) {
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
const ignoredPaths = new Set<string>();
|
||||
const chunks = chunkPathsForGitCheckIgnore(relativePaths);
|
||||
|
||||
for (const chunk of chunks) {
|
||||
const result = yield* executeGit(
|
||||
"GitCore.filterIgnoredPaths",
|
||||
cwd,
|
||||
["check-ignore", "--no-index", "-z", "--stdin"],
|
||||
{
|
||||
stdin: `${chunk.join("\0")}\0`,
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 20_000,
|
||||
maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
|
||||
truncateOutputAtMaxBytes: true,
|
||||
},
|
||||
);
|
||||
|
||||
if (result.code !== 0 && result.code !== 1) {
|
||||
return yield* createGitCommandError(
|
||||
"GitCore.filterIgnoredPaths",
|
||||
cwd,
|
||||
["check-ignore", "--no-index", "-z", "--stdin"],
|
||||
result.stderr.trim().length > 0 ? result.stderr.trim() : "git check-ignore failed",
|
||||
);
|
||||
}
|
||||
|
||||
for (const ignoredPath of splitNullSeparatedPaths(result.stdout, result.stdoutTruncated)) {
|
||||
ignoredPaths.add(ignoredPath);
|
||||
}
|
||||
}
|
||||
|
||||
if (ignoredPaths.size === 0) {
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath));
|
||||
});
|
||||
|
||||
const listBranches: GitCoreShape["listBranches"] = Effect.fn("listBranches")(function* (input) {
|
||||
const branchRecencyPromise = readBranchRecency(input.cwd).pipe(
|
||||
Effect.catch(() => Effect.succeed(new Map<string, number>())),
|
||||
@@ -1977,9 +1834,6 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
pullCurrentBranch,
|
||||
readRangeContext,
|
||||
readConfigValue,
|
||||
isInsideWorkTree,
|
||||
listWorkspaceFiles,
|
||||
filterIgnoredPaths,
|
||||
listBranches,
|
||||
createWorktree,
|
||||
fetchPullRequestBranch,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect } from "effect";
|
||||
import { afterEach, expect, vi } from "vite-plus/test";
|
||||
import { afterEach, expect, vi } from "vitest";
|
||||
|
||||
vi.mock("../../processRunner", () => ({
|
||||
runProcess: vi.fn(),
|
||||
|
||||
@@ -5,7 +5,7 @@ import { spawnSync } from "node:child_process";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
|
||||
import { expect } from "vite-plus/test";
|
||||
import { expect } from "vitest";
|
||||
import type { GitActionProgressEvent, ModelSelection } from "@t3tools/contracts";
|
||||
|
||||
import { GitCommandError, GitHubCliError, TextGenerationError } from "../Errors.ts";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
buildBranchNamePrompt,
|
||||
|
||||
@@ -28,7 +28,6 @@ export interface ExecuteGitInput {
|
||||
readonly operation: string;
|
||||
readonly cwd: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly stdin?: string;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
readonly allowNonZeroExit?: boolean;
|
||||
readonly timeoutMs?: number;
|
||||
@@ -41,8 +40,6 @@ export interface ExecuteGitResult {
|
||||
readonly code: number;
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly stdoutTruncated: boolean;
|
||||
readonly stderrTruncated: boolean;
|
||||
}
|
||||
|
||||
export interface GitStatusDetails extends Omit<GitStatusResult, "pr"> {
|
||||
@@ -55,27 +52,27 @@ export interface GitPreparedCommitContext {
|
||||
}
|
||||
|
||||
export interface ExecuteGitProgress {
|
||||
readonly onStdoutLine?: (line: string) => Effect.Effect<void>;
|
||||
readonly onStderrLine?: (line: string) => Effect.Effect<void>;
|
||||
readonly onHookStarted?: (hookName: string) => Effect.Effect<void>;
|
||||
readonly onStdoutLine?: (line: string) => Effect.Effect<void, never>;
|
||||
readonly onStderrLine?: (line: string) => Effect.Effect<void, never>;
|
||||
readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
|
||||
readonly onHookFinished?: (input: {
|
||||
hookName: string;
|
||||
exitCode: number | null;
|
||||
durationMs: number | null;
|
||||
}) => Effect.Effect<void>;
|
||||
}) => Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
export interface GitCommitProgress {
|
||||
readonly onOutputLine?: (input: {
|
||||
stream: "stdout" | "stderr";
|
||||
text: string;
|
||||
}) => Effect.Effect<void>;
|
||||
readonly onHookStarted?: (hookName: string) => Effect.Effect<void>;
|
||||
}) => Effect.Effect<void, never>;
|
||||
readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
|
||||
readonly onHookFinished?: (input: {
|
||||
hookName: string;
|
||||
exitCode: number | null;
|
||||
durationMs: number | null;
|
||||
}) => Effect.Effect<void>;
|
||||
}) => Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
export interface GitCommitOptions {
|
||||
@@ -96,11 +93,6 @@ export interface GitRangeContext {
|
||||
diffPatch: string;
|
||||
}
|
||||
|
||||
export interface GitListWorkspaceFilesResult {
|
||||
readonly paths: ReadonlyArray<string>;
|
||||
readonly truncated: boolean;
|
||||
}
|
||||
|
||||
export interface GitRenameBranchInput {
|
||||
cwd: string;
|
||||
oldBranch: string;
|
||||
@@ -198,26 +190,6 @@ export interface GitCoreShape {
|
||||
key: string,
|
||||
) => Effect.Effect<string | null, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Determine whether the provided cwd is inside a git work tree.
|
||||
*/
|
||||
readonly isInsideWorkTree: (cwd: string) => Effect.Effect<boolean, GitCommandError>;
|
||||
|
||||
/**
|
||||
* List tracked and untracked workspace file paths relative to cwd.
|
||||
*/
|
||||
readonly listWorkspaceFiles: (
|
||||
cwd: string,
|
||||
) => Effect.Effect<GitListWorkspaceFilesResult, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Remove gitignored paths from a relative path list.
|
||||
*/
|
||||
readonly filterIgnoredPaths: (
|
||||
cwd: string,
|
||||
relativePaths: ReadonlyArray<string>,
|
||||
) => Effect.Effect<ReadonlyArray<string>, GitCommandError>;
|
||||
|
||||
/**
|
||||
* List local + remote branches and branch metadata.
|
||||
*/
|
||||
|
||||
@@ -22,7 +22,7 @@ import type { Effect } from "effect";
|
||||
import type { GitManagerServiceError } from "../Errors.ts";
|
||||
|
||||
export interface GitActionProgressReporter {
|
||||
readonly publish: (event: GitActionProgressEvent) => Effect.Effect<void>;
|
||||
readonly publish: (event: GitActionProgressEvent) => Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
export interface GitRunStackedActionOptions {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { inferImageExtension, parseBase64DataUrl } from "./imageMime.ts";
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Command from "effect/unstable/cli/Command";
|
||||
import { FetchHttpClient } from "effect/unstable/http";
|
||||
import { beforeEach } from "vite-plus/test";
|
||||
import { beforeEach } from "vitest";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
|
||||
import { CliConfig, recordStartupHeartbeat, t3Cli, type CliConfigShape } from "./main";
|
||||
@@ -51,6 +51,8 @@ const testLayer = Layer.mergeAll(
|
||||
stopSignal: Effect.void,
|
||||
} satisfies ServerShape),
|
||||
Layer.succeed(Open, {
|
||||
getAvailableEditors: Effect.succeed([]),
|
||||
openExternal: () => Effect.void,
|
||||
openBrowser: (_target: string) => Effect.void,
|
||||
openInEditor: () => Effect.void,
|
||||
} satisfies OpenShape),
|
||||
|
||||
+536
-247
@@ -1,269 +1,558 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
|
||||
import * as NodePath from "@effect/platform-node/NodePath";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { assertSuccess } from "@effect/vitest/utils";
|
||||
import { FileSystem, Path, Effect } from "effect";
|
||||
|
||||
import {
|
||||
isCommandAvailable,
|
||||
launchDetached,
|
||||
resolveAvailableEditors,
|
||||
resolveEditorLaunch,
|
||||
} from "./open";
|
||||
Deferred,
|
||||
Effect,
|
||||
Exit,
|
||||
FileSystem,
|
||||
Layer,
|
||||
PlatformError,
|
||||
Scope,
|
||||
Sink,
|
||||
Stream,
|
||||
} from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
it.effect("returns commands for command-based editors", () =>
|
||||
Effect.gen(function* () {
|
||||
const antigravityLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "antigravity" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(antigravityLaunch, {
|
||||
command: "agy",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
import { makeOpenLayer, Open } from "./open";
|
||||
|
||||
const cursorLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "cursor" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(cursorLaunch, {
|
||||
command: "cursor",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
const vscodeLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "vscode" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodeLaunch, {
|
||||
command: "code",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
interface SpawnCall {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly detached?: boolean | undefined;
|
||||
readonly shell?: boolean | string | undefined;
|
||||
readonly stdin?: unknown;
|
||||
readonly stdout?: unknown;
|
||||
readonly stderr?: unknown;
|
||||
}
|
||||
|
||||
const vscodeInsidersLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "vscode-insiders" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodeInsidersLaunch, {
|
||||
command: "code-insiders",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
function decodePowerShellCommand(encoded: string): string {
|
||||
return Buffer.from(encoded, "base64").toString("utf16le");
|
||||
}
|
||||
|
||||
const vscodiumLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "vscodium" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodiumLaunch, {
|
||||
command: "codium",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
function platformSpawnError(message: string) {
|
||||
return PlatformError.systemError({
|
||||
_tag: "Unknown",
|
||||
module: "ChildProcess",
|
||||
method: "spawn",
|
||||
description: message,
|
||||
});
|
||||
}
|
||||
|
||||
const zedLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "zed" },
|
||||
"darwin",
|
||||
function spawnerLayer(
|
||||
calls: Array<SpawnCall>,
|
||||
handler: (call: SpawnCall) => {
|
||||
readonly code?: number;
|
||||
readonly fail?: string;
|
||||
readonly awaitExit?: Deferred.Deferred<void>;
|
||||
readonly onKill?: () => void;
|
||||
} = () => ({
|
||||
code: 0,
|
||||
}),
|
||||
) {
|
||||
return Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) => {
|
||||
const standardCommand = command as unknown as {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly options: {
|
||||
readonly detached?: boolean;
|
||||
readonly shell?: boolean | string;
|
||||
readonly stdin?: unknown;
|
||||
readonly stdout?: unknown;
|
||||
readonly stderr?: unknown;
|
||||
};
|
||||
};
|
||||
|
||||
const call: SpawnCall = {
|
||||
command: standardCommand.command,
|
||||
args: [...standardCommand.args],
|
||||
detached: standardCommand.options.detached,
|
||||
shell: standardCommand.options.shell,
|
||||
stdin: standardCommand.options.stdin,
|
||||
stdout: standardCommand.options.stdout,
|
||||
stderr: standardCommand.options.stderr,
|
||||
};
|
||||
calls.push(call);
|
||||
|
||||
const result = handler(call);
|
||||
if (result.fail) {
|
||||
return Effect.fail(platformSpawnError(result.fail));
|
||||
}
|
||||
|
||||
let exited = false;
|
||||
const exitCode = result.awaitExit
|
||||
? Deferred.await(result.awaitExit).pipe(
|
||||
Effect.tap(() =>
|
||||
Effect.sync(() => {
|
||||
exited = true;
|
||||
}),
|
||||
),
|
||||
Effect.andThen(Effect.succeed(ChildProcessSpawner.ExitCode(result.code ?? 0))),
|
||||
)
|
||||
: Effect.sync(() => {
|
||||
exited = true;
|
||||
return ChildProcessSpawner.ExitCode(result.code ?? 0);
|
||||
});
|
||||
|
||||
return Effect.succeed(
|
||||
ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(calls.length),
|
||||
exitCode,
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () =>
|
||||
Effect.sync(() => {
|
||||
if (!exited) {
|
||||
result.onKill?.();
|
||||
}
|
||||
}),
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.make(encoder.encode("")),
|
||||
stderr: Stream.make(encoder.encode("")),
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
}),
|
||||
);
|
||||
assert.deepEqual(zedLaunch, {
|
||||
command: "zed",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
it.effect("uses --goto when editor supports line/column suffixes", () =>
|
||||
Effect.gen(function* () {
|
||||
const lineOnly = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "cursor" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(lineOnly, {
|
||||
command: "cursor",
|
||||
args: ["--goto", "/tmp/workspace/AGENTS.md:48"],
|
||||
});
|
||||
|
||||
const lineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "cursor" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(lineAndColumn, {
|
||||
command: "cursor",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const vscodeLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodeLineAndColumn, {
|
||||
command: "code",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const vscodeInsidersLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode-insiders" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodeInsidersLineAndColumn, {
|
||||
command: "code-insiders",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const vscodiumLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscodium" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodiumLineAndColumn, {
|
||||
command: "codium",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const zedLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "zed" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(zedLineAndColumn, {
|
||||
command: "zed",
|
||||
args: ["/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
}),
|
||||
const provideOpen = (
|
||||
options: Parameters<typeof makeOpenLayer>[0],
|
||||
spawnLayer: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>,
|
||||
) =>
|
||||
makeOpenLayer(options).pipe(
|
||||
Layer.provide(Layer.mergeAll(NodeFileSystem.layer, NodePath.layer, spawnLayer)),
|
||||
);
|
||||
|
||||
it.effect("maps file-manager editor to OS open commands", () =>
|
||||
Effect.gen(function* () {
|
||||
const launch1 = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "file-manager" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(launch1, {
|
||||
command: "open",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
const runOpen = <A>(
|
||||
options: Parameters<typeof makeOpenLayer>[0],
|
||||
spawnLayer: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>,
|
||||
effect: Effect.Effect<A, Error, Open>,
|
||||
) => effect.pipe(Effect.provide(provideOpen(options, spawnLayer)));
|
||||
|
||||
const launch2 = yield* resolveEditorLaunch(
|
||||
{ cwd: "C:\\workspace", editor: "file-manager" },
|
||||
"win32",
|
||||
);
|
||||
assert.deepEqual(launch2, {
|
||||
command: "explorer",
|
||||
args: ["C:\\workspace"],
|
||||
});
|
||||
const readOpen = Effect.service(Open);
|
||||
|
||||
const launch3 = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "file-manager" },
|
||||
"linux",
|
||||
);
|
||||
assert.deepEqual(launch3, {
|
||||
command: "xdg-open",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("launchDetached", (it) => {
|
||||
it.effect("resolves when command can be spawned", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* launchDetached({
|
||||
command: process.execPath,
|
||||
args: ["-e", "process.exit(0)"],
|
||||
}).pipe(Effect.result);
|
||||
assertSuccess(result, undefined);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects when command does not exist", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* launchDetached({
|
||||
command: `t3code-no-such-command-${Date.now()}`,
|
||||
args: [],
|
||||
}).pipe(Effect.result);
|
||||
assert.equal(result._tag, "Failure");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("isCommandAvailable", (it) => {
|
||||
it.effect("resolves win32 commands with PATHEXT", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
|
||||
yield* fs.writeFileString(path.join(dir, "code.CMD"), "@echo off\r\n");
|
||||
const env = {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
|
||||
}),
|
||||
);
|
||||
|
||||
it("returns false when a command is not on PATH", () => {
|
||||
const env = {
|
||||
PATH: "",
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("definitely-not-installed", { platform: "win32", env }), false);
|
||||
const writeExecutable = (filePath: string) =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
yield* fs.writeFileString(filePath, "#!/bin/sh\nexit 0\n");
|
||||
yield* fs.chmod(filePath, 0o755);
|
||||
});
|
||||
|
||||
it.effect("does not treat bare files without executable extension as available on win32", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
|
||||
yield* fs.writeFileString(path.join(dir, "npm"), "echo nope\r\n");
|
||||
const env = {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("npm", { platform: "win32", env }), false);
|
||||
}),
|
||||
);
|
||||
it.effect("getAvailableEditors detects installed editors through the service", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-editors-" });
|
||||
yield* fs.writeFileString(`${dir}/code-insiders.CMD`, "@echo off\r\n");
|
||||
yield* fs.writeFileString(`${dir}/codium.CMD`, "@echo off\r\n");
|
||||
yield* fs.writeFileString(`${dir}/explorer.CMD`, "@echo off\r\n");
|
||||
|
||||
it.effect("appends PATHEXT for commands with non-executable extensions on win32", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
|
||||
yield* fs.writeFileString(path.join(dir, "my.tool.CMD"), "@echo off\r\n");
|
||||
const env = {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("my.tool", { platform: "win32", env }), true);
|
||||
}),
|
||||
);
|
||||
const calls: Array<SpawnCall> = [];
|
||||
const open = yield* runOpen(
|
||||
{
|
||||
platform: "win32",
|
||||
env: {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
},
|
||||
},
|
||||
spawnerLayer(calls),
|
||||
readOpen,
|
||||
);
|
||||
|
||||
it.effect("uses platform-specific PATH delimiter for platform overrides", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const firstDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
|
||||
const secondDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
|
||||
yield* fs.writeFileString(path.join(firstDir, "code.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(secondDir, "code.CMD"), "MZ");
|
||||
const env = {
|
||||
PATH: `${firstDir};${secondDir}`,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
|
||||
}),
|
||||
);
|
||||
});
|
||||
const editors = yield* open.getAvailableEditors;
|
||||
assert.deepEqual(editors, ["vscode-insiders", "vscodium", "file-manager"]);
|
||||
assert.deepEqual(calls, []);
|
||||
}).pipe(Effect.provide(NodeFileSystem.layer)),
|
||||
);
|
||||
|
||||
it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
|
||||
it.effect("returns installed editors for command launches", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editors-" });
|
||||
it.effect("getAvailableEditors does not advertise WSL file-manager from PowerShell alone", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-wsl-editors-" });
|
||||
yield* fs.makeDirectory(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`, {
|
||||
recursive: true,
|
||||
});
|
||||
yield* writeExecutable(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`);
|
||||
|
||||
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, "explorer.CMD"), "MZ");
|
||||
const editors = resolveAvailableEditors("win32", {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
});
|
||||
assert.deepEqual(editors, ["vscode-insiders", "vscodium", "file-manager"]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
const calls: Array<SpawnCall> = [];
|
||||
const open = yield* runOpen(
|
||||
{
|
||||
platform: "linux",
|
||||
env: {
|
||||
PATH: `${dir}:${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`,
|
||||
WSL_DISTRO_NAME: "Ubuntu",
|
||||
},
|
||||
isWsl: true,
|
||||
isInsideContainer: false,
|
||||
powerShellCommand: `${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,
|
||||
},
|
||||
spawnerLayer(calls),
|
||||
readOpen,
|
||||
);
|
||||
|
||||
const editors = yield* open.getAvailableEditors;
|
||||
assert.equal(editors.includes("file-manager"), false);
|
||||
assert.deepEqual(calls, []);
|
||||
}).pipe(Effect.provide(NodeFileSystem.layer)),
|
||||
);
|
||||
|
||||
it.effect("openInEditor uses --goto for editors that support it", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-cursor-" });
|
||||
yield* writeExecutable(`${dir}/cursor`);
|
||||
|
||||
const calls: Array<SpawnCall> = [];
|
||||
const open = yield* runOpen(
|
||||
{
|
||||
platform: "darwin",
|
||||
env: { PATH: dir },
|
||||
},
|
||||
spawnerLayer(calls),
|
||||
readOpen,
|
||||
);
|
||||
|
||||
yield* open.openInEditor({
|
||||
cwd: "/tmp/workspace/src/open.ts:71:5",
|
||||
editor: "cursor",
|
||||
});
|
||||
|
||||
assert.deepEqual(calls, [
|
||||
{
|
||||
command: `${dir}/cursor`,
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
detached: true,
|
||||
shell: false,
|
||||
stdin: "ignore",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(NodeFileSystem.layer)),
|
||||
);
|
||||
|
||||
it.effect("openInEditor launches Windows batch shims through cmd.exe without shell mode", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-vscode-win32-" });
|
||||
yield* fs.writeFileString(`${dir}/code.cmd`, "@echo off\r\n");
|
||||
|
||||
const calls: Array<SpawnCall> = [];
|
||||
const open = yield* runOpen(
|
||||
{
|
||||
platform: "win32",
|
||||
env: {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
},
|
||||
},
|
||||
spawnerLayer(calls),
|
||||
readOpen,
|
||||
);
|
||||
|
||||
yield* open.openInEditor({
|
||||
cwd: "C:\\work\\100% real\\file.ts:12:4",
|
||||
editor: "vscode",
|
||||
});
|
||||
|
||||
assert.equal(calls.length, 1);
|
||||
assert.equal(calls[0]?.command, "cmd.exe");
|
||||
assert.deepEqual(calls[0]?.args.slice(0, 4), ["/d", "/v:off", "/s", "/c"]);
|
||||
assert.equal(calls[0]?.args[4]?.toLowerCase().includes(`${dir}/code.cmd`.toLowerCase()), true);
|
||||
assert.equal(calls[0]?.args[4]?.includes('"--goto"'), true);
|
||||
assert.equal(calls[0]?.args[4]?.includes("100%% real"), true);
|
||||
assert.equal(calls[0]?.detached, true);
|
||||
assert.equal(calls[0]?.shell, false);
|
||||
assert.equal(calls[0]?.stdin, "ignore");
|
||||
assert.equal(calls[0]?.stdout, "ignore");
|
||||
assert.equal(calls[0]?.stderr, "ignore");
|
||||
}).pipe(Effect.provide(NodeFileSystem.layer)),
|
||||
);
|
||||
|
||||
it.effect("openInEditor detached launches survive service scope shutdown", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-zed-detached-" });
|
||||
yield* writeExecutable(`${dir}/zed`);
|
||||
|
||||
const calls: Array<SpawnCall> = [];
|
||||
const exitDeferred = yield* Deferred.make<void>();
|
||||
let killCount = 0;
|
||||
|
||||
yield* Effect.acquireUseRelease(
|
||||
Scope.make("sequential"),
|
||||
(scope) =>
|
||||
Effect.gen(function* () {
|
||||
const runtimeServices = yield* Layer.build(
|
||||
provideOpen(
|
||||
{
|
||||
platform: "darwin",
|
||||
env: { PATH: dir },
|
||||
},
|
||||
spawnerLayer(calls, () => ({
|
||||
awaitExit: exitDeferred,
|
||||
onKill: () => {
|
||||
killCount += 1;
|
||||
},
|
||||
})),
|
||||
),
|
||||
).pipe(Scope.provide(scope));
|
||||
|
||||
const open = yield* readOpen.pipe(Effect.provide(runtimeServices), Scope.provide(scope));
|
||||
yield* open.openInEditor({
|
||||
cwd: "/tmp/workspace",
|
||||
editor: "zed",
|
||||
});
|
||||
}),
|
||||
(scope) => Scope.close(scope, Exit.void),
|
||||
);
|
||||
|
||||
assert.equal(killCount, 0);
|
||||
assert.deepEqual(calls, [
|
||||
{
|
||||
command: `${dir}/zed`,
|
||||
args: ["/tmp/workspace"],
|
||||
detached: true,
|
||||
shell: false,
|
||||
stdin: "ignore",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
},
|
||||
]);
|
||||
|
||||
yield* Deferred.succeed(exitDeferred, void 0);
|
||||
yield* Effect.yieldNow;
|
||||
assert.equal(killCount, 0);
|
||||
}).pipe(Effect.provide(NodeFileSystem.layer)),
|
||||
);
|
||||
|
||||
it.effect("openInEditor uses the default opener for file-manager on macOS", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-macos-" });
|
||||
yield* writeExecutable(`${dir}/open`);
|
||||
|
||||
const calls: Array<SpawnCall> = [];
|
||||
const open = yield* runOpen(
|
||||
{
|
||||
platform: "darwin",
|
||||
env: { PATH: dir },
|
||||
},
|
||||
spawnerLayer(calls),
|
||||
readOpen,
|
||||
);
|
||||
|
||||
yield* open.openInEditor({
|
||||
cwd: "/tmp/workspace",
|
||||
editor: "file-manager",
|
||||
});
|
||||
|
||||
assert.deepEqual(calls, [
|
||||
{
|
||||
command: `${dir}/open`,
|
||||
args: ["/tmp/workspace"],
|
||||
detached: undefined,
|
||||
shell: false,
|
||||
stdin: undefined,
|
||||
stdout: undefined,
|
||||
stderr: undefined,
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(NodeFileSystem.layer)),
|
||||
);
|
||||
|
||||
it.effect("openBrowser uses macOS open flags and app arguments", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-browser-macos-" });
|
||||
yield* writeExecutable(`${dir}/open`);
|
||||
|
||||
const calls: Array<SpawnCall> = [];
|
||||
const open = yield* runOpen(
|
||||
{
|
||||
platform: "darwin",
|
||||
env: { PATH: dir },
|
||||
},
|
||||
spawnerLayer(calls),
|
||||
readOpen,
|
||||
);
|
||||
|
||||
yield* open.openBrowser("https://example.com", {
|
||||
wait: true,
|
||||
background: true,
|
||||
newInstance: true,
|
||||
app: {
|
||||
name: "google chrome",
|
||||
arguments: ["--profile-directory=Work"],
|
||||
},
|
||||
});
|
||||
|
||||
assert.deepEqual(calls, [
|
||||
{
|
||||
command: `${dir}/open`,
|
||||
args: [
|
||||
"--wait-apps",
|
||||
"--background",
|
||||
"--new",
|
||||
"-a",
|
||||
"google chrome",
|
||||
"https://example.com",
|
||||
"--args",
|
||||
"--profile-directory=Work",
|
||||
],
|
||||
detached: undefined,
|
||||
shell: false,
|
||||
stdin: undefined,
|
||||
stdout: undefined,
|
||||
stderr: undefined,
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(NodeFileSystem.layer)),
|
||||
);
|
||||
|
||||
it.effect("openBrowser uses PowerShell on win32", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-browser-win32-" });
|
||||
yield* fs.writeFileString(`${dir}/powershell.exe`, "MZ");
|
||||
|
||||
const calls: Array<SpawnCall> = [];
|
||||
const open = yield* runOpen(
|
||||
{
|
||||
platform: "win32",
|
||||
env: {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
},
|
||||
},
|
||||
spawnerLayer(calls),
|
||||
readOpen,
|
||||
);
|
||||
|
||||
yield* open.openBrowser("https://example.com");
|
||||
|
||||
assert.equal(calls.length, 1);
|
||||
assert.equal(calls[0]?.command, `${dir}/powershell.exe`);
|
||||
assert.equal(calls[0]?.args.at(-2), "-EncodedCommand");
|
||||
assert.equal(
|
||||
decodePowerShellCommand(calls[0]?.args.at(-1) ?? ""),
|
||||
"Start 'https://example.com'",
|
||||
);
|
||||
}).pipe(Effect.provide(NodeFileSystem.layer)),
|
||||
);
|
||||
|
||||
it.effect("openBrowser falls back from WSL PowerShell to xdg-open", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-browser-wsl-" });
|
||||
yield* fs.makeDirectory(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`, {
|
||||
recursive: true,
|
||||
});
|
||||
yield* writeExecutable(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`);
|
||||
yield* writeExecutable(`${dir}/xdg-open`);
|
||||
|
||||
const calls: Array<SpawnCall> = [];
|
||||
const open = yield* runOpen(
|
||||
{
|
||||
platform: "linux",
|
||||
env: {
|
||||
PATH: `${dir}:${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`,
|
||||
WSL_DISTRO_NAME: "Ubuntu",
|
||||
},
|
||||
isWsl: true,
|
||||
isInsideContainer: false,
|
||||
powerShellCommand: `${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,
|
||||
},
|
||||
spawnerLayer(calls, (call) =>
|
||||
call.command.includes("powershell")
|
||||
? { fail: "powershell unavailable" }
|
||||
: {
|
||||
code: 0,
|
||||
},
|
||||
),
|
||||
readOpen,
|
||||
);
|
||||
|
||||
yield* open.openBrowser("https://example.com");
|
||||
|
||||
assert.equal(calls[0]?.command.includes("powershell"), true);
|
||||
assert.equal(calls[1]?.command, `${dir}/xdg-open`);
|
||||
assert.deepEqual(calls[1]?.args, ["https://example.com"]);
|
||||
}).pipe(Effect.provide(NodeFileSystem.layer)),
|
||||
);
|
||||
|
||||
it.effect("openInEditor uses xdg-open first for WSL file-manager paths", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-wsl-file-manager-" });
|
||||
yield* fs.makeDirectory(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`, {
|
||||
recursive: true,
|
||||
});
|
||||
yield* writeExecutable(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`);
|
||||
yield* writeExecutable(`${dir}/xdg-open`);
|
||||
|
||||
const calls: Array<SpawnCall> = [];
|
||||
const open = yield* runOpen(
|
||||
{
|
||||
platform: "linux",
|
||||
env: {
|
||||
PATH: `${dir}:${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`,
|
||||
WSL_DISTRO_NAME: "Ubuntu",
|
||||
},
|
||||
isWsl: true,
|
||||
isInsideContainer: false,
|
||||
powerShellCommand: `${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,
|
||||
},
|
||||
spawnerLayer(calls),
|
||||
readOpen,
|
||||
);
|
||||
|
||||
yield* open.openInEditor({
|
||||
cwd: "/home/julius/workspace",
|
||||
editor: "file-manager",
|
||||
});
|
||||
|
||||
assert.deepEqual(calls, [
|
||||
{
|
||||
command: `${dir}/xdg-open`,
|
||||
args: ["/home/julius/workspace"],
|
||||
detached: true,
|
||||
shell: false,
|
||||
stdin: "ignore",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(NodeFileSystem.layer)),
|
||||
);
|
||||
|
||||
it.effect("openInEditor fails when the editor command is unavailable", () =>
|
||||
Effect.gen(function* () {
|
||||
const calls: Array<SpawnCall> = [];
|
||||
const open = yield* runOpen(
|
||||
{
|
||||
platform: "darwin",
|
||||
env: { PATH: "" },
|
||||
},
|
||||
spawnerLayer(calls),
|
||||
readOpen,
|
||||
);
|
||||
|
||||
const error = yield* open
|
||||
.openInEditor({
|
||||
cwd: "/tmp/workspace",
|
||||
editor: "cursor",
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.equal(error._tag, "OpenError");
|
||||
assert.equal(error.message, "Command not found: cursor");
|
||||
assert.deepEqual(calls, []);
|
||||
}),
|
||||
);
|
||||
+575
-171
@@ -1,21 +1,17 @@
|
||||
/**
|
||||
* Open - Browser/editor launch service interface.
|
||||
*
|
||||
* Owns process launch helpers for opening URLs in a browser and workspace
|
||||
* paths in a configured editor.
|
||||
* Owns process launch helpers for opening URLs in a browser, workspace paths in
|
||||
* a configured editor, and generic external targets through the platform's
|
||||
* default opener.
|
||||
*
|
||||
* @module Open
|
||||
*/
|
||||
import { spawn } from "node:child_process";
|
||||
import { accessSync, constants, statSync } from "node:fs";
|
||||
import { extname, join } from "node:path";
|
||||
import os from "node:os";
|
||||
|
||||
import { EDITORS, type EditorId } from "@t3tools/contracts";
|
||||
import { ServiceMap, Schema, Effect, Layer } from "effect";
|
||||
|
||||
// ==============================
|
||||
// Definitions
|
||||
// ==============================
|
||||
import { Effect, Exit, FileSystem, Layer, Option, Path, Schema, Scope, ServiceMap } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
export class OpenError extends Schema.TaggedErrorClass<OpenError>()("OpenError", {
|
||||
message: Schema.String,
|
||||
@@ -27,33 +23,66 @@ export interface OpenInEditorInput {
|
||||
readonly editor: EditorId;
|
||||
}
|
||||
|
||||
interface EditorLaunch {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
export interface OpenApplicationInput {
|
||||
readonly name: string | ReadonlyArray<string>;
|
||||
readonly arguments?: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
interface CommandAvailabilityOptions {
|
||||
export interface OpenExternalInput {
|
||||
readonly target: string;
|
||||
readonly wait?: boolean;
|
||||
readonly background?: boolean;
|
||||
readonly newInstance?: boolean;
|
||||
readonly allowNonzeroExitCode?: boolean;
|
||||
readonly app?: OpenApplicationInput | ReadonlyArray<OpenApplicationInput>;
|
||||
}
|
||||
|
||||
export interface OpenRuntimeOptions {
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
readonly isWsl?: boolean;
|
||||
readonly isInsideContainer?: boolean;
|
||||
readonly powerShellCommand?: string;
|
||||
}
|
||||
|
||||
interface OpenRuntime {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly isWsl: boolean;
|
||||
readonly isInsideContainer: boolean;
|
||||
readonly powerShellCandidates: ReadonlyArray<string>;
|
||||
readonly windowsPathExtensions: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
interface LaunchPlan {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly wait: boolean;
|
||||
readonly allowNonzeroExitCode: boolean;
|
||||
readonly detached?: boolean;
|
||||
readonly shell?: boolean;
|
||||
readonly stdio?: "ignore";
|
||||
}
|
||||
|
||||
interface ResolvedCommand {
|
||||
readonly path: string;
|
||||
readonly usesCmdWrapper: boolean;
|
||||
}
|
||||
|
||||
const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
|
||||
const WINDOWS_POWERSHELL_CANDIDATES = ["powershell.exe", "powershell", "pwsh.exe", "pwsh"] as const;
|
||||
const WSL_POWERSHELL_CANDIDATES = [
|
||||
"/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe",
|
||||
"/mnt/c/Program Files/PowerShell/7/pwsh.exe",
|
||||
"powershell.exe",
|
||||
"pwsh.exe",
|
||||
] as const;
|
||||
const WINDOWS_BATCH_EXTENSIONS = [".CMD", ".BAT"] as const;
|
||||
|
||||
function shouldUseGotoFlag(editor: (typeof EDITORS)[number], target: string): boolean {
|
||||
return editor.supportsGoto && LINE_COLUMN_SUFFIX_PATTERN.test(target);
|
||||
}
|
||||
|
||||
function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
|
||||
switch (platform) {
|
||||
case "darwin":
|
||||
return "open";
|
||||
case "win32":
|
||||
return "explorer";
|
||||
default:
|
||||
return "xdg-open";
|
||||
}
|
||||
}
|
||||
|
||||
function stripWrappingQuotes(value: string): string {
|
||||
return value.replace(/^"+|"+$/g, "");
|
||||
}
|
||||
@@ -72,19 +101,24 @@ function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<str
|
||||
.map((entry) => entry.trim())
|
||||
.filter((entry) => entry.length > 0)
|
||||
.map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`));
|
||||
|
||||
return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
|
||||
}
|
||||
|
||||
function resolveWindowsCommandShell(env: NodeJS.ProcessEnv): string {
|
||||
return env.ComSpec ?? env.COMSPEC ?? "cmd.exe";
|
||||
}
|
||||
|
||||
function resolveCommandCandidates(
|
||||
command: string,
|
||||
platform: NodeJS.Platform,
|
||||
windowsPathExtensions: ReadonlyArray<string>,
|
||||
runtime: OpenRuntime,
|
||||
pathService: Path.Path,
|
||||
): ReadonlyArray<string> {
|
||||
if (platform !== "win32") return [command];
|
||||
const extension = extname(command);
|
||||
if (runtime.platform !== "win32") return [command];
|
||||
const extension = pathService.extname(command);
|
||||
const normalizedExtension = extension.toUpperCase();
|
||||
|
||||
if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
|
||||
if (extension.length > 0 && runtime.windowsPathExtensions.includes(normalizedExtension)) {
|
||||
const commandWithoutExtension = command.slice(0, -extension.length);
|
||||
return Array.from(
|
||||
new Set([
|
||||
@@ -96,179 +130,549 @@ function resolveCommandCandidates(
|
||||
}
|
||||
|
||||
const candidates: string[] = [];
|
||||
for (const extension of windowsPathExtensions) {
|
||||
candidates.push(`${command}${extension}`);
|
||||
candidates.push(`${command}${extension.toLowerCase()}`);
|
||||
for (const extensionName of runtime.windowsPathExtensions) {
|
||||
candidates.push(`${command}${extensionName}`);
|
||||
candidates.push(`${command}${extensionName.toLowerCase()}`);
|
||||
}
|
||||
return Array.from(new Set(candidates));
|
||||
}
|
||||
|
||||
function isExecutableFile(
|
||||
filePath: string,
|
||||
platform: NodeJS.Platform,
|
||||
windowsPathExtensions: ReadonlyArray<string>,
|
||||
): boolean {
|
||||
try {
|
||||
const stat = statSync(filePath);
|
||||
if (!stat.isFile()) return false;
|
||||
if (platform === "win32") {
|
||||
const extension = extname(filePath);
|
||||
if (extension.length === 0) return false;
|
||||
return windowsPathExtensions.includes(extension.toUpperCase());
|
||||
}
|
||||
accessSync(filePath, constants.X_OK);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function resolvePathDelimiter(platform: NodeJS.Platform): string {
|
||||
return platform === "win32" ? ";" : ":";
|
||||
}
|
||||
|
||||
export function isCommandAvailable(
|
||||
command: string,
|
||||
options: CommandAvailabilityOptions = {},
|
||||
): boolean {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const env = options.env ?? process.env;
|
||||
const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
|
||||
const commandCandidates = resolveCommandCandidates(command, platform, windowsPathExtensions);
|
||||
function detectWsl(platform: NodeJS.Platform, env: NodeJS.ProcessEnv): boolean {
|
||||
if (platform !== "linux") return false;
|
||||
if (typeof env.WSL_DISTRO_NAME === "string" || typeof env.WSL_INTEROP === "string") {
|
||||
return true;
|
||||
}
|
||||
return os.release().toLowerCase().includes("microsoft");
|
||||
}
|
||||
|
||||
if (command.includes("/") || command.includes("\\")) {
|
||||
return commandCandidates.some((candidate) =>
|
||||
isExecutableFile(candidate, platform, windowsPathExtensions),
|
||||
);
|
||||
function quotePowerShellValue(value: string): string {
|
||||
return `'${value.replaceAll("'", "''")}'`;
|
||||
}
|
||||
|
||||
function encodePowerShellCommand(command: string): string {
|
||||
return Buffer.from(command, "utf16le").toString("base64");
|
||||
}
|
||||
|
||||
function normalizeAppCandidates(
|
||||
app: OpenExternalInput["app"],
|
||||
): ReadonlyArray<{ readonly name: string; readonly arguments: ReadonlyArray<string> } | undefined> {
|
||||
if (!app) return [undefined];
|
||||
|
||||
const apps = Array.isArray(app) ? app : [app];
|
||||
const candidates: Array<{ readonly name: string; readonly arguments: ReadonlyArray<string> }> =
|
||||
[];
|
||||
|
||||
for (const appDef of apps) {
|
||||
const names = Array.isArray(appDef.name) ? appDef.name : [appDef.name];
|
||||
for (const name of names) {
|
||||
candidates.push({ name, arguments: appDef.arguments ?? [] });
|
||||
}
|
||||
}
|
||||
|
||||
const pathValue = resolvePathEnvironmentVariable(env);
|
||||
if (pathValue.length === 0) return false;
|
||||
const pathEntries = pathValue
|
||||
.split(resolvePathDelimiter(platform))
|
||||
.map((entry) => stripWrappingQuotes(entry.trim()))
|
||||
.filter((entry) => entry.length > 0);
|
||||
return candidates;
|
||||
}
|
||||
|
||||
for (const pathEntry of pathEntries) {
|
||||
for (const candidate of commandCandidates) {
|
||||
if (isExecutableFile(join(pathEntry, candidate), platform, windowsPathExtensions)) {
|
||||
return true;
|
||||
function isUriLikeTarget(target: string): boolean {
|
||||
return /^[A-Za-z][A-Za-z\d+.-]*:/.test(target);
|
||||
}
|
||||
|
||||
function shouldPreferWindowsOpenerOnWsl(input: OpenExternalInput, runtime: OpenRuntime): boolean {
|
||||
return runtime.isWsl && !runtime.isInsideContainer && isUriLikeTarget(input.target);
|
||||
}
|
||||
|
||||
function makeLaunchPlan(
|
||||
command: string,
|
||||
args: ReadonlyArray<string>,
|
||||
options: {
|
||||
readonly wait: boolean;
|
||||
readonly allowNonzeroExitCode: boolean;
|
||||
readonly detached?: boolean;
|
||||
readonly shell?: boolean;
|
||||
readonly stdio?: "ignore";
|
||||
},
|
||||
): LaunchPlan {
|
||||
return {
|
||||
command,
|
||||
args,
|
||||
wait: options.wait,
|
||||
allowNonzeroExitCode: options.allowNonzeroExitCode,
|
||||
shell: options.shell ?? false,
|
||||
...(options.detached !== undefined ? { detached: options.detached } : {}),
|
||||
...(options.stdio !== undefined ? { stdio: options.stdio } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function makeDarwinDefaultPlan(input: OpenExternalInput): LaunchPlan {
|
||||
const args: string[] = [];
|
||||
const wait = input.wait ?? false;
|
||||
|
||||
if (wait) args.push("--wait-apps");
|
||||
if (input.background) args.push("--background");
|
||||
if (input.newInstance) args.push("--new");
|
||||
args.push(input.target);
|
||||
|
||||
return makeLaunchPlan("open", args, {
|
||||
wait,
|
||||
allowNonzeroExitCode: input.allowNonzeroExitCode ?? false,
|
||||
shell: false,
|
||||
});
|
||||
}
|
||||
|
||||
function makeDarwinApplicationPlan(
|
||||
input: OpenExternalInput,
|
||||
app: { readonly name: string; readonly arguments: ReadonlyArray<string> },
|
||||
): LaunchPlan {
|
||||
const args: string[] = [];
|
||||
const wait = input.wait ?? false;
|
||||
|
||||
if (wait) args.push("--wait-apps");
|
||||
if (input.background) args.push("--background");
|
||||
if (input.newInstance) args.push("--new");
|
||||
args.push("-a", app.name);
|
||||
args.push(input.target);
|
||||
if (app.arguments.length > 0) {
|
||||
args.push("--args", ...app.arguments);
|
||||
}
|
||||
|
||||
return makeLaunchPlan("open", args, {
|
||||
wait,
|
||||
allowNonzeroExitCode: input.allowNonzeroExitCode ?? false,
|
||||
shell: false,
|
||||
});
|
||||
}
|
||||
|
||||
function makePowerShellPlan(input: OpenExternalInput, powerShellCommand: string): LaunchPlan {
|
||||
const encodedParts = ["Start"];
|
||||
const wait = input.wait ?? false;
|
||||
|
||||
if (wait) encodedParts.push("-Wait");
|
||||
encodedParts.push(quotePowerShellValue(input.target));
|
||||
|
||||
return makeLaunchPlan(
|
||||
powerShellCommand,
|
||||
[
|
||||
"-NoProfile",
|
||||
"-NonInteractive",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-EncodedCommand",
|
||||
encodePowerShellCommand(encodedParts.join(" ")),
|
||||
],
|
||||
{
|
||||
wait,
|
||||
allowNonzeroExitCode: input.allowNonzeroExitCode ?? false,
|
||||
shell: false,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function makeLinuxDefaultPlan(input: OpenExternalInput): LaunchPlan {
|
||||
const wait = input.wait ?? false;
|
||||
return makeLaunchPlan("xdg-open", [input.target], {
|
||||
wait,
|
||||
allowNonzeroExitCode: input.allowNonzeroExitCode ?? false,
|
||||
detached: !wait,
|
||||
...(wait ? {} : { stdio: "ignore" as const }),
|
||||
shell: false,
|
||||
});
|
||||
}
|
||||
|
||||
function makeWindowsExplorerPlan(input: OpenExternalInput): LaunchPlan {
|
||||
return makeLaunchPlan("explorer", [input.target], {
|
||||
wait: false,
|
||||
allowNonzeroExitCode: false,
|
||||
shell: false,
|
||||
});
|
||||
}
|
||||
|
||||
function makeDirectApplicationPlan(
|
||||
input: OpenExternalInput,
|
||||
app: { readonly name: string; readonly arguments: ReadonlyArray<string> },
|
||||
): LaunchPlan {
|
||||
return makeLaunchPlan(app.name, [...app.arguments, input.target], {
|
||||
wait: input.wait ?? false,
|
||||
allowNonzeroExitCode: input.allowNonzeroExitCode ?? false,
|
||||
shell: false,
|
||||
});
|
||||
}
|
||||
|
||||
function resolveExternalPlans(
|
||||
input: OpenExternalInput,
|
||||
runtime: OpenRuntime,
|
||||
): ReadonlyArray<LaunchPlan> {
|
||||
const appCandidates = normalizeAppCandidates(input.app);
|
||||
const plans: LaunchPlan[] = [];
|
||||
const preferWindowsOpenerOnWsl = shouldPreferWindowsOpenerOnWsl(input, runtime);
|
||||
|
||||
for (const app of appCandidates) {
|
||||
if (app) {
|
||||
if (runtime.platform === "darwin") {
|
||||
plans.push(makeDarwinApplicationPlan(input, app));
|
||||
} else {
|
||||
plans.push(makeDirectApplicationPlan(input, app));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (runtime.platform === "darwin") {
|
||||
plans.push(makeDarwinDefaultPlan(input));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (runtime.platform === "win32" || preferWindowsOpenerOnWsl) {
|
||||
for (const powerShellCommand of runtime.powerShellCandidates) {
|
||||
plans.push(makePowerShellPlan(input, powerShellCommand));
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function resolveAvailableEditors(
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): ReadonlyArray<EditorId> {
|
||||
const available: EditorId[] = [];
|
||||
|
||||
for (const editor of EDITORS) {
|
||||
const command = editor.command ?? fileManagerCommandForPlatform(platform);
|
||||
if (isCommandAvailable(command, { platform, env })) {
|
||||
available.push(editor.id);
|
||||
if (runtime.platform === "win32") {
|
||||
if (!(input.wait ?? false)) {
|
||||
plans.push(makeWindowsExplorerPlan(input));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
plans.push(makeLinuxDefaultPlan(input));
|
||||
}
|
||||
|
||||
return available;
|
||||
return plans;
|
||||
}
|
||||
|
||||
/**
|
||||
* OpenShape - Service API for browser and editor launch actions.
|
||||
*/
|
||||
export interface OpenShape {
|
||||
/**
|
||||
* Open a URL target in the default browser.
|
||||
*/
|
||||
readonly openBrowser: (target: string) => Effect.Effect<void, OpenError>;
|
||||
function toOpenError(message: string, cause: unknown): OpenError {
|
||||
return new OpenError({ message, cause });
|
||||
}
|
||||
|
||||
/**
|
||||
* Open a workspace path in a selected editor integration.
|
||||
*
|
||||
* Launches the editor as a detached process so server startup is not blocked.
|
||||
*/
|
||||
function isWindowsBatchShim(pathService: Path.Path, filePath: string): boolean {
|
||||
return WINDOWS_BATCH_EXTENSIONS.includes(pathService.extname(filePath).toUpperCase() as never);
|
||||
}
|
||||
|
||||
function quoteForWindowsCmd(value: string): string {
|
||||
return `"${value.replaceAll("%", "%%").replaceAll('"', '""')}"`;
|
||||
}
|
||||
|
||||
function makeWindowsCmdCommandLine(commandPath: string, args: ReadonlyArray<string>): string {
|
||||
return `"${[commandPath, ...args].map(quoteForWindowsCmd).join(" ")}"`;
|
||||
}
|
||||
|
||||
export interface OpenShape {
|
||||
readonly getAvailableEditors: Effect.Effect<ReadonlyArray<EditorId>, OpenError>;
|
||||
readonly openExternal: (input: OpenExternalInput) => Effect.Effect<void, OpenError>;
|
||||
readonly openBrowser: (
|
||||
target: string,
|
||||
options?: Omit<OpenExternalInput, "target">,
|
||||
) => Effect.Effect<void, OpenError>;
|
||||
readonly openInEditor: (input: OpenInEditorInput) => Effect.Effect<void, OpenError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Open - Service tag for browser/editor launch operations.
|
||||
*/
|
||||
export class Open extends ServiceMap.Service<Open, OpenShape>()("t3/open") {}
|
||||
|
||||
// ==============================
|
||||
// Implementations
|
||||
// ==============================
|
||||
|
||||
export const resolveEditorLaunch = Effect.fnUntraced(function* (
|
||||
input: OpenInEditorInput,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): Effect.fn.Return<EditorLaunch, OpenError> {
|
||||
const editorDef = EDITORS.find((editor) => editor.id === input.editor);
|
||||
if (!editorDef) {
|
||||
return yield* new OpenError({ message: `Unknown editor: ${input.editor}` });
|
||||
}
|
||||
|
||||
if (editorDef.command) {
|
||||
return shouldUseGotoFlag(editorDef, input.cwd)
|
||||
? { command: editorDef.command, args: ["--goto", input.cwd] }
|
||||
: { command: editorDef.command, args: [input.cwd] };
|
||||
}
|
||||
|
||||
if (editorDef.id !== "file-manager") {
|
||||
return yield* new OpenError({ message: `Unsupported editor: ${input.editor}` });
|
||||
}
|
||||
|
||||
return { command: fileManagerCommandForPlatform(platform), args: [input.cwd] };
|
||||
});
|
||||
|
||||
export const launchDetached = (launch: EditorLaunch) =>
|
||||
const makeOpen = (options: OpenRuntimeOptions = {}) =>
|
||||
Effect.gen(function* () {
|
||||
if (!isCommandAvailable(launch.command)) {
|
||||
return yield* new OpenError({ message: `Editor command not found: ${launch.command}` });
|
||||
}
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const pathService = yield* Path.Path;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
yield* Effect.callback<void, OpenError>((resume) => {
|
||||
let child;
|
||||
try {
|
||||
child = spawn(launch.command, [...launch.args], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
} catch (error) {
|
||||
return resume(
|
||||
Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
|
||||
const isInsideContainer =
|
||||
options.isInsideContainer ??
|
||||
(typeof options.env?.CONTAINER === "string" ||
|
||||
typeof options.env?.container === "string" ||
|
||||
typeof options.env?.KUBERNETES_SERVICE_HOST === "string"
|
||||
? true
|
||||
: yield* fileSystem.exists("/.dockerenv").pipe(Effect.catch(() => Effect.succeed(false))));
|
||||
|
||||
const runtime: OpenRuntime = {
|
||||
platform: options.platform ?? process.platform,
|
||||
env: options.env ?? process.env,
|
||||
isWsl:
|
||||
options.isWsl ??
|
||||
detectWsl(options.platform ?? process.platform, options.env ?? process.env),
|
||||
isInsideContainer,
|
||||
powerShellCandidates:
|
||||
options.powerShellCommand !== undefined
|
||||
? [options.powerShellCommand]
|
||||
: (options.isWsl ??
|
||||
detectWsl(options.platform ?? process.platform, options.env ?? process.env))
|
||||
? WSL_POWERSHELL_CANDIDATES
|
||||
: WINDOWS_POWERSHELL_CANDIDATES,
|
||||
windowsPathExtensions: resolveWindowsPathExtensions(options.env ?? process.env),
|
||||
};
|
||||
|
||||
const resolveCommand = Effect.fn(function* (
|
||||
command: string,
|
||||
): Effect.fn.Return<Option.Option<ResolvedCommand>, never> {
|
||||
const candidates = resolveCommandCandidates(command, runtime, pathService);
|
||||
|
||||
const resolveExecutableFile = Effect.fn(function* (
|
||||
filePath: string,
|
||||
): Effect.fn.Return<Option.Option<ResolvedCommand>, never> {
|
||||
const info = yield* fileSystem.stat(filePath).pipe(Effect.option);
|
||||
if (Option.isNone(info) || info.value.type !== "File") return Option.none();
|
||||
|
||||
if (runtime.platform === "win32") {
|
||||
const extension = pathService.extname(filePath);
|
||||
if (
|
||||
extension.length === 0 ||
|
||||
!runtime.windowsPathExtensions.includes(extension.toUpperCase())
|
||||
) {
|
||||
return Option.none();
|
||||
}
|
||||
|
||||
return Option.some({
|
||||
path: filePath,
|
||||
usesCmdWrapper: isWindowsBatchShim(pathService, filePath),
|
||||
} satisfies ResolvedCommand);
|
||||
}
|
||||
|
||||
return (info.value.mode & 0o111) !== 0
|
||||
? Option.some({
|
||||
path: filePath,
|
||||
usesCmdWrapper: false,
|
||||
} satisfies ResolvedCommand)
|
||||
: Option.none();
|
||||
});
|
||||
|
||||
if (command.includes("/") || command.includes("\\")) {
|
||||
for (const candidate of candidates) {
|
||||
const resolved = yield* resolveExecutableFile(candidate);
|
||||
if (Option.isSome(resolved)) return resolved;
|
||||
}
|
||||
return Option.none();
|
||||
}
|
||||
|
||||
const pathValue = resolvePathEnvironmentVariable(runtime.env);
|
||||
if (pathValue.length === 0) return Option.none();
|
||||
|
||||
const pathEntries = pathValue
|
||||
.split(resolvePathDelimiter(runtime.platform))
|
||||
.map((entry) => stripWrappingQuotes(entry.trim()))
|
||||
.filter((entry) => entry.length > 0);
|
||||
|
||||
for (const pathEntry of pathEntries) {
|
||||
for (const candidate of candidates) {
|
||||
const resolved = yield* resolveExecutableFile(pathService.join(pathEntry, candidate));
|
||||
if (Option.isSome(resolved)) {
|
||||
return resolved;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Option.none();
|
||||
});
|
||||
|
||||
const commandAvailable = (command: string) =>
|
||||
resolveCommand(command).pipe(Effect.map(Option.isSome));
|
||||
|
||||
const fileManagerAvailable = Effect.gen(function* () {
|
||||
const candidates =
|
||||
runtime.platform === "darwin"
|
||||
? ["open"]
|
||||
: runtime.platform === "win32"
|
||||
? [...runtime.powerShellCandidates, "explorer"]
|
||||
: ["xdg-open"];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (yield* commandAvailable(candidate)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
});
|
||||
|
||||
const getAvailableEditors = Effect.gen(function* () {
|
||||
const available: EditorId[] = [];
|
||||
|
||||
for (const editor of EDITORS) {
|
||||
if (editor.id === "file-manager") {
|
||||
if (yield* fileManagerAvailable) {
|
||||
available.push(editor.id);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (editor.command && (yield* commandAvailable(editor.command))) {
|
||||
available.push(editor.id);
|
||||
}
|
||||
}
|
||||
|
||||
return available as ReadonlyArray<EditorId>;
|
||||
}).pipe(Effect.mapError((cause) => toOpenError("Failed to resolve available editors", cause)));
|
||||
|
||||
const spawnPlan = (
|
||||
plan: LaunchPlan,
|
||||
resolvedCommand: ResolvedCommand,
|
||||
failureMessage: string,
|
||||
) =>
|
||||
spawner
|
||||
.spawn(
|
||||
ChildProcess.make(
|
||||
resolvedCommand.usesCmdWrapper
|
||||
? resolveWindowsCommandShell(runtime.env)
|
||||
: resolvedCommand.path,
|
||||
resolvedCommand.usesCmdWrapper
|
||||
? [
|
||||
"/d",
|
||||
"/v:off",
|
||||
"/s",
|
||||
"/c",
|
||||
makeWindowsCmdCommandLine(resolvedCommand.path, plan.args),
|
||||
]
|
||||
: [...plan.args],
|
||||
{
|
||||
detached: plan.detached,
|
||||
shell: plan.shell,
|
||||
...(plan.stdio === "ignore"
|
||||
? {
|
||||
stdin: "ignore",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
),
|
||||
)
|
||||
.pipe(Effect.mapError((cause) => toOpenError(failureMessage, cause)));
|
||||
|
||||
const waitForExit = (
|
||||
plan: LaunchPlan,
|
||||
failureMessage: string,
|
||||
handle: ChildProcessSpawner.ChildProcessHandle,
|
||||
) =>
|
||||
handle.exitCode.pipe(
|
||||
Effect.flatMap((exitCode) =>
|
||||
!plan.allowNonzeroExitCode && (exitCode as number) !== 0
|
||||
? Effect.fail(
|
||||
new OpenError({
|
||||
message: `${failureMessage} (code=${exitCode as number})`,
|
||||
}),
|
||||
)
|
||||
: Effect.void,
|
||||
),
|
||||
Effect.mapError((cause) => toOpenError(failureMessage, cause)),
|
||||
);
|
||||
|
||||
const runWaitedPlan = (
|
||||
plan: LaunchPlan,
|
||||
resolvedCommand: ResolvedCommand,
|
||||
failureMessage: string,
|
||||
) =>
|
||||
Effect.acquireUseRelease(
|
||||
Scope.make("sequential"),
|
||||
(scope) =>
|
||||
Effect.gen(function* () {
|
||||
const handle = yield* spawnPlan(plan, resolvedCommand, failureMessage).pipe(
|
||||
Scope.provide(scope),
|
||||
);
|
||||
yield* waitForExit(plan, failureMessage, handle);
|
||||
}),
|
||||
(scope) => Scope.close(scope, Exit.void),
|
||||
);
|
||||
|
||||
const runDetachedPlan = (
|
||||
plan: LaunchPlan,
|
||||
resolvedCommand: ResolvedCommand,
|
||||
failureMessage: string,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const childScope = yield* Scope.make("sequential");
|
||||
const handle = yield* spawnPlan(plan, resolvedCommand, failureMessage).pipe(
|
||||
Scope.provide(childScope),
|
||||
Effect.catch((error) =>
|
||||
Scope.close(childScope, Exit.void).pipe(Effect.andThen(Effect.fail(error))),
|
||||
),
|
||||
);
|
||||
|
||||
const releaseOnExit: Effect.Effect<void, never> = handle.exitCode.pipe(
|
||||
Effect.ignoreCause,
|
||||
Effect.ensuring(Scope.close(childScope, Exit.void)),
|
||||
);
|
||||
|
||||
yield* Effect.forkDetach(releaseOnExit);
|
||||
});
|
||||
|
||||
const runPlan = (plan: LaunchPlan, resolvedCommand: ResolvedCommand, failureMessage: string) =>
|
||||
plan.wait
|
||||
? runWaitedPlan(plan, resolvedCommand, failureMessage)
|
||||
: runDetachedPlan(plan, resolvedCommand, failureMessage);
|
||||
|
||||
const runFirstAvailablePlan = (
|
||||
plans: ReadonlyArray<LaunchPlan>,
|
||||
failureMessage: string,
|
||||
): Effect.Effect<void, OpenError> => {
|
||||
const [first, ...rest] = plans;
|
||||
if (!first) {
|
||||
return Effect.fail(new OpenError({ message: failureMessage }));
|
||||
}
|
||||
|
||||
return resolveCommand(first.command).pipe(
|
||||
Effect.flatMap((resolvedCommand) => {
|
||||
if (Option.isNone(resolvedCommand)) {
|
||||
return rest.length === 0
|
||||
? Effect.fail(new OpenError({ message: `Command not found: ${first.command}` }))
|
||||
: runFirstAvailablePlan(rest, failureMessage);
|
||||
}
|
||||
|
||||
return runPlan(first, resolvedCommand.value, failureMessage).pipe(
|
||||
Effect.catch((error) =>
|
||||
rest.length === 0 ? Effect.fail(error) : runFirstAvailablePlan(rest, failureMessage),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const openExternal = (input: OpenExternalInput) => {
|
||||
if (input.target.trim().length === 0) {
|
||||
return Effect.fail(new OpenError({ message: "Open target must not be empty" }));
|
||||
}
|
||||
|
||||
return runFirstAvailablePlan(
|
||||
resolveExternalPlans(input, runtime),
|
||||
`Failed to open ${input.target}`,
|
||||
);
|
||||
};
|
||||
|
||||
const openInEditor = (input: OpenInEditorInput) => {
|
||||
const editor = EDITORS.find((candidate) => candidate.id === input.editor);
|
||||
if (!editor) {
|
||||
return Effect.fail(new OpenError({ message: `Unknown editor: ${input.editor}` }));
|
||||
}
|
||||
|
||||
if (editor.command) {
|
||||
return runFirstAvailablePlan(
|
||||
[
|
||||
makeLaunchPlan(
|
||||
editor.command,
|
||||
shouldUseGotoFlag(editor, input.cwd) ? ["--goto", input.cwd] : [input.cwd],
|
||||
{
|
||||
wait: false,
|
||||
allowNonzeroExitCode: false,
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
shell: false,
|
||||
},
|
||||
),
|
||||
],
|
||||
`Failed to open ${input.cwd} in ${input.editor}`,
|
||||
);
|
||||
}
|
||||
|
||||
const handleSpawn = () => {
|
||||
child.unref();
|
||||
resume(Effect.void);
|
||||
};
|
||||
return openExternal({ target: input.cwd });
|
||||
};
|
||||
|
||||
child.once("spawn", handleSpawn);
|
||||
child.once("error", (cause) =>
|
||||
resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
|
||||
);
|
||||
});
|
||||
return {
|
||||
getAvailableEditors,
|
||||
openExternal,
|
||||
openBrowser: (target, openOptions = {}) => openExternal({ ...openOptions, target }),
|
||||
openInEditor,
|
||||
} satisfies OpenShape;
|
||||
});
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const open = yield* Effect.tryPromise({
|
||||
try: () => import("open"),
|
||||
catch: (cause) => new OpenError({ message: "failed to load browser opener", cause }),
|
||||
});
|
||||
export const makeOpenLayer = (options: OpenRuntimeOptions = {}) =>
|
||||
Layer.effect(Open, makeOpen(options));
|
||||
|
||||
return {
|
||||
openBrowser: (target) =>
|
||||
Effect.tryPromise({
|
||||
try: () => open.default(target),
|
||||
catch: (cause) => new OpenError({ message: "Browser auto-open failed", cause }),
|
||||
}),
|
||||
openInEditor: (input) => Effect.flatMap(resolveEditorLaunch(input), launchDetached),
|
||||
} satisfies OpenShape;
|
||||
});
|
||||
|
||||
export const OpenLive = Layer.effect(Open, make);
|
||||
export const OpenLive = makeOpenLayer();
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { CheckpointStoreLive } from "../../checkpointing/Layers/CheckpointStore.ts";
|
||||
import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts";
|
||||
@@ -38,7 +38,6 @@ import {
|
||||
} from "../../provider/Services/ProviderService.ts";
|
||||
import { checkpointRefForThreadTurn } from "../../checkpointing/Utils.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { WorkspaceEntriesLive } from "../../workspace/Layers/WorkspaceEntries.ts";
|
||||
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
@@ -69,7 +68,7 @@ function createProviderServiceHarness(
|
||||
);
|
||||
|
||||
const unsupported = <A>() =>
|
||||
Effect.die(new Error("Unsupported provider call in test")) as Effect.Effect<A>;
|
||||
Effect.die(new Error("Unsupported provider call in test")) as Effect.Effect<A, never>;
|
||||
const listSessions = () =>
|
||||
hasSession
|
||||
? Effect.succeed([
|
||||
@@ -262,9 +261,7 @@ describe("CheckpointReactor", () => {
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(RuntimeReceiptBusLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||
Layer.provideMerge(CheckpointStoreLive),
|
||||
Layer.provideMerge(WorkspaceEntriesLive),
|
||||
Layer.provideMerge(GitCoreLive),
|
||||
Layer.provideMerge(CheckpointStoreLive.pipe(Layer.provide(GitCoreLive))),
|
||||
Layer.provideMerge(ServerConfigLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
checkpointRefForThreadTurn,
|
||||
resolveThreadWorkspaceCwd,
|
||||
} from "../../checkpointing/Utils.ts";
|
||||
import { clearWorkspaceIndexCache } from "../../workspaceEntries.ts";
|
||||
import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts";
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { CheckpointReactor, type CheckpointReactorShape } from "../Services/CheckpointReactor.ts";
|
||||
@@ -24,7 +25,6 @@ import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts";
|
||||
import { CheckpointStoreError } from "../../checkpointing/Errors.ts";
|
||||
import { OrchestrationDispatchError } from "../Errors.ts";
|
||||
import { isGitRepository } from "../../git/Utils.ts";
|
||||
import { WorkspaceEntries } from "../../workspace/Services/WorkspaceEntries.ts";
|
||||
|
||||
type ReactorInput =
|
||||
| {
|
||||
@@ -68,7 +68,6 @@ const make = Effect.gen(function* () {
|
||||
const providerService = yield* ProviderService;
|
||||
const checkpointStore = yield* CheckpointStore;
|
||||
const receiptBus = yield* RuntimeReceiptBus;
|
||||
const workspaceEntries = yield* WorkspaceEntries;
|
||||
|
||||
const appendRevertFailureActivity = (input: {
|
||||
readonly threadId: ThreadId;
|
||||
@@ -227,7 +226,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
// Invalidate the workspace entry cache so the @-mention file picker
|
||||
// reflects files created or deleted during this turn.
|
||||
yield* workspaceEntries.invalidate(input.cwd);
|
||||
clearWorkspaceIndexCache(input.cwd);
|
||||
|
||||
const files = yield* checkpointStore
|
||||
.diffCheckpoints({
|
||||
@@ -643,7 +642,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
// Invalidate the workspace entry cache so the @-mention file picker
|
||||
// reflects the reverted filesystem state.
|
||||
yield* workspaceEntries.invalidate(sessionRuntime.value.cwd);
|
||||
clearWorkspaceIndexCache(sessionRuntime.value.cwd);
|
||||
|
||||
const rolledBackTurns = Math.max(0, currentTurnCount - event.payload.turnCount);
|
||||
if (rolledBackTurns > 0) {
|
||||
@@ -748,7 +747,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
const processInput = (
|
||||
input: ReactorInput,
|
||||
): Effect.Effect<void, CheckpointStoreError | OrchestrationDispatchError> =>
|
||||
): Effect.Effect<void, CheckpointStoreError | OrchestrationDispatchError, never> =>
|
||||
input.source === "domain" ? processDomainEvent(input.event) : processRuntimeEvent(input.event);
|
||||
|
||||
const processInputSafely = (input: ReactorInput) =>
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
type OrchestrationEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer, ManagedRuntime, Queue, Stream } from "effect";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { PersistenceSqlError } from "../../persistence/Errors.ts";
|
||||
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Effect, Exit, Layer, ManagedRuntime, Scope } from "effect";
|
||||
import { afterEach, describe, expect, it } from "vite-plus/test";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
|
||||
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
|
||||
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { deriveServerPaths, ServerConfig } from "../../config.ts";
|
||||
import { TextGenerationError } from "../../git/Errors.ts";
|
||||
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
|
||||
import { afterEach, describe, expect, it } from "vite-plus/test";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
|
||||
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||
@@ -1626,7 +1626,8 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
event.payload.messageId === "assistant:item-complete-dedup" && !event.payload.streaming
|
||||
event.payload.messageId === "assistant:item-complete-dedup" &&
|
||||
event.payload.streaming === false
|
||||
);
|
||||
});
|
||||
expect(completionEvents).toHaveLength(1);
|
||||
|
||||
@@ -30,7 +30,7 @@ export interface OrchestrationEngineShape {
|
||||
*
|
||||
* @returns Effect containing the latest read model.
|
||||
*/
|
||||
readonly getReadModel: () => Effect.Effect<OrchestrationReadModel, never>;
|
||||
readonly getReadModel: () => Effect.Effect<OrchestrationReadModel, never, never>;
|
||||
|
||||
/**
|
||||
* Replay persisted orchestration events from an exclusive sequence cursor.
|
||||
@@ -40,7 +40,7 @@ export interface OrchestrationEngineShape {
|
||||
*/
|
||||
readonly readEvents: (
|
||||
fromSequenceExclusive: number,
|
||||
) => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError>;
|
||||
) => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError, never>;
|
||||
|
||||
/**
|
||||
* Dispatch a validated orchestration command.
|
||||
@@ -53,7 +53,7 @@ export interface OrchestrationEngineShape {
|
||||
*/
|
||||
readonly dispatch: (
|
||||
command: OrchestrationCommand,
|
||||
) => Effect.Effect<{ sequence: number }, OrchestrationDispatchError>;
|
||||
) => Effect.Effect<{ sequence: number }, OrchestrationDispatchError, never>;
|
||||
|
||||
/**
|
||||
* Stream persisted domain events in dispatch order.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
MessageId,
|
||||
CommandId,
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { Effect } from "effect";
|
||||
|
||||
import { decideOrchestrationCommand } from "./decider.ts";
|
||||
|
||||
@@ -679,7 +679,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
|
||||
default: {
|
||||
command satisfies never;
|
||||
const fallback = command as { type: string };
|
||||
const fallback = command as never as { type: string };
|
||||
return yield* new OrchestrationCommandInvariantError({
|
||||
commandType: fallback.type,
|
||||
detail: `Unknown command type: ${fallback.type}`,
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
type OrchestrationEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect } from "effect";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createEmptyReadModel, projectEvent } from "./projector.ts";
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { fixPath } from "./os-jank";
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { runProcess } from "./processRunner";
|
||||
|
||||
|
||||
@@ -1,74 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it, describe, expect } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
|
||||
import { ProjectFaviconResolver } from "../Services/ProjectFaviconResolver.ts";
|
||||
import { ProjectFaviconResolverLive } from "./ProjectFaviconResolver.ts";
|
||||
|
||||
const TestLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(ProjectFaviconResolverLive),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const makeTempDir = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
return yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3code-project-favicon-",
|
||||
});
|
||||
});
|
||||
|
||||
const writeTextFile = Effect.fn("writeTextFile")(function* (
|
||||
cwd: string,
|
||||
relativePath: string,
|
||||
contents: string,
|
||||
) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const absolutePath = path.join(cwd, relativePath);
|
||||
yield* fileSystem
|
||||
.makeDirectory(path.dirname(absolutePath), { recursive: true })
|
||||
.pipe(Effect.orDie);
|
||||
yield* fileSystem.writeFileString(absolutePath, contents).pipe(Effect.orDie);
|
||||
});
|
||||
|
||||
it.layer(TestLayer)("ProjectFaviconResolverLive", (it) => {
|
||||
describe("resolvePath", () => {
|
||||
it.effect("prefers well-known favicon files", () =>
|
||||
Effect.gen(function* () {
|
||||
const resolver = yield* ProjectFaviconResolver;
|
||||
const cwd = yield* makeTempDir;
|
||||
yield* writeTextFile(cwd, "favicon.svg", "<svg>favicon</svg>");
|
||||
|
||||
const resolved = yield* resolver.resolvePath(cwd);
|
||||
|
||||
expect(resolved).not.toBeNull();
|
||||
expect(resolved).toContain("favicon.svg");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("resolves icon hrefs from project source files", () =>
|
||||
Effect.gen(function* () {
|
||||
const resolver = yield* ProjectFaviconResolver;
|
||||
const cwd = yield* makeTempDir;
|
||||
yield* writeTextFile(cwd, "index.html", '<link rel="icon" href="/brand/logo.svg">');
|
||||
yield* writeTextFile(cwd, "public/brand/logo.svg", "<svg>brand</svg>");
|
||||
|
||||
const resolved = yield* resolver.resolvePath(cwd);
|
||||
|
||||
expect(resolved).not.toBeNull();
|
||||
expect(resolved).toContain("public/brand/logo.svg");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns null when no icon is present", () =>
|
||||
Effect.gen(function* () {
|
||||
const resolver = yield* ProjectFaviconResolver;
|
||||
const cwd = yield* makeTempDir;
|
||||
|
||||
const resolved = yield* resolver.resolvePath(cwd);
|
||||
|
||||
expect(resolved).toBeNull();
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,129 +0,0 @@
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
|
||||
import {
|
||||
ProjectFaviconResolver,
|
||||
type ProjectFaviconResolverShape,
|
||||
} from "../Services/ProjectFaviconResolver.ts";
|
||||
|
||||
// Well-known favicon paths checked in order.
|
||||
const FAVICON_CANDIDATES = [
|
||||
"favicon.svg",
|
||||
"favicon.ico",
|
||||
"favicon.png",
|
||||
"public/favicon.svg",
|
||||
"public/favicon.ico",
|
||||
"public/favicon.png",
|
||||
"app/favicon.ico",
|
||||
"app/favicon.png",
|
||||
"app/icon.svg",
|
||||
"app/icon.png",
|
||||
"app/icon.ico",
|
||||
"src/favicon.ico",
|
||||
"src/favicon.svg",
|
||||
"src/app/favicon.ico",
|
||||
"src/app/icon.svg",
|
||||
"src/app/icon.png",
|
||||
"assets/icon.svg",
|
||||
"assets/icon.png",
|
||||
"assets/logo.svg",
|
||||
"assets/logo.png",
|
||||
] as const;
|
||||
|
||||
// Files that may contain a <link rel="icon"> or icon metadata declaration.
|
||||
const ICON_SOURCE_FILES = [
|
||||
"index.html",
|
||||
"public/index.html",
|
||||
"app/routes/__root.tsx",
|
||||
"src/routes/__root.tsx",
|
||||
"app/root.tsx",
|
||||
"src/root.tsx",
|
||||
"src/index.html",
|
||||
] as const;
|
||||
|
||||
// Matches <link ...> tags or object-like icon metadata where rel/href can appear in any order.
|
||||
const LINK_ICON_HTML_RE =
|
||||
/<link\b(?=[^>]*\brel=["'](?:icon|shortcut icon)["'])(?=[^>]*\bhref=["']([^"'?]+))[^>]*>/i;
|
||||
const LINK_ICON_OBJ_RE =
|
||||
/(?=[^}]*\brel\s*:\s*["'](?:icon|shortcut icon)["'])(?=[^}]*\bhref\s*:\s*["']([^"'?]+))[^}]*/i;
|
||||
|
||||
function extractIconHref(source: string): string | null {
|
||||
const htmlMatch = source.match(LINK_ICON_HTML_RE);
|
||||
if (htmlMatch?.[1]) return htmlMatch[1];
|
||||
const objMatch = source.match(LINK_ICON_OBJ_RE);
|
||||
if (objMatch?.[1]) return objMatch[1];
|
||||
return null;
|
||||
}
|
||||
|
||||
export const makeProjectFaviconResolver = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
const resolveIconHref = (projectCwd: string, href: string): string[] => {
|
||||
const clean = href.replace(/^\//, "");
|
||||
return [path.join(projectCwd, "public", clean), path.join(projectCwd, clean)];
|
||||
};
|
||||
|
||||
const isPathWithinProject = (projectCwd: string, candidatePath: string): boolean => {
|
||||
const relative = path.relative(path.resolve(projectCwd), path.resolve(candidatePath));
|
||||
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
|
||||
};
|
||||
|
||||
const findExistingFile = Effect.fn("ProjectFaviconResolver.findExistingFile")(function* (
|
||||
projectCwd: string,
|
||||
candidates: ReadonlyArray<string>,
|
||||
): Effect.fn.Return<string | null> {
|
||||
for (const candidate of candidates) {
|
||||
if (!isPathWithinProject(projectCwd, candidate)) {
|
||||
continue;
|
||||
}
|
||||
const stats = yield* fileSystem
|
||||
.stat(candidate)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (stats?.type === "File") {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
const resolvePath: ProjectFaviconResolverShape["resolvePath"] = Effect.fn(
|
||||
"ProjectFaviconResolver.resolvePath",
|
||||
)(function* (cwd: string): Effect.fn.Return<string | null> {
|
||||
for (const candidate of FAVICON_CANDIDATES) {
|
||||
const resolved = path.join(cwd, candidate);
|
||||
const existing = yield* findExistingFile(cwd, [resolved]);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
}
|
||||
|
||||
for (const sourceFile of ICON_SOURCE_FILES) {
|
||||
const sourcePath = path.join(cwd, sourceFile);
|
||||
const source = yield* fileSystem
|
||||
.readFileString(sourcePath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!source) {
|
||||
continue;
|
||||
}
|
||||
const href = extractIconHref(source);
|
||||
if (!href) {
|
||||
continue;
|
||||
}
|
||||
const existing = yield* findExistingFile(cwd, resolveIconHref(cwd, href));
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
|
||||
return {
|
||||
resolvePath,
|
||||
} satisfies ProjectFaviconResolverShape;
|
||||
});
|
||||
|
||||
export const ProjectFaviconResolverLive = Layer.effect(
|
||||
ProjectFaviconResolver,
|
||||
makeProjectFaviconResolver,
|
||||
);
|
||||
@@ -1,30 +0,0 @@
|
||||
/**
|
||||
* ProjectFaviconResolver - Effect service contract for project icon discovery.
|
||||
*
|
||||
* Resolves a representative favicon or app icon file for a workspace by
|
||||
* checking common file locations and project source metadata.
|
||||
*
|
||||
* @module ProjectFaviconResolver
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
/**
|
||||
* ProjectFaviconResolverShape - Service API for project favicon lookup.
|
||||
*/
|
||||
export interface ProjectFaviconResolverShape {
|
||||
/**
|
||||
* Resolve a favicon or icon file path for the provided workspace root.
|
||||
*
|
||||
* Returns `null` when no candidate icon file can be found.
|
||||
*/
|
||||
readonly resolvePath: (cwd: string) => Effect.Effect<string | null>;
|
||||
}
|
||||
|
||||
/**
|
||||
* ProjectFaviconResolver - Service tag for project favicon resolution.
|
||||
*/
|
||||
export class ProjectFaviconResolver extends ServiceMap.Service<
|
||||
ProjectFaviconResolver,
|
||||
ProjectFaviconResolverShape
|
||||
>()("t3/project/Services/ProjectFaviconResolver") {}
|
||||
@@ -3,11 +3,7 @@ import http from "node:http";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Effect } from "effect";
|
||||
import { afterEach, describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { ProjectFaviconResolverLive } from "./project/Layers/ProjectFaviconResolver.ts";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
|
||||
|
||||
interface HttpResponse {
|
||||
@@ -27,25 +23,11 @@ function makeTempDir(prefix: string): string {
|
||||
async function withRouteServer(run: (baseUrl: string) => Promise<void>): Promise<void> {
|
||||
const server = http.createServer((req, res) => {
|
||||
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
||||
void Effect.runPromise(
|
||||
tryHandleProjectFaviconRequest(url, res).pipe(
|
||||
Effect.provide(ProjectFaviconResolverLive),
|
||||
Effect.provide(NodeServices.layer),
|
||||
Effect.flatMap((handled) =>
|
||||
handled
|
||||
? Effect.void
|
||||
: Effect.sync(() => {
|
||||
res.writeHead(404, { "Content-Type": "text/plain" });
|
||||
res.end("Not Found");
|
||||
}),
|
||||
),
|
||||
),
|
||||
).catch(() => {
|
||||
if (!res.headersSent) {
|
||||
res.writeHead(500, { "Content-Type": "text/plain" });
|
||||
res.end("Internal Server Error");
|
||||
}
|
||||
});
|
||||
if (tryHandleProjectFaviconRequest(url, res)) {
|
||||
return;
|
||||
}
|
||||
res.writeHead(404, { "Content-Type": "text/plain" });
|
||||
res.end("Not Found");
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import fs from "node:fs";
|
||||
import http from "node:http";
|
||||
import path from "node:path";
|
||||
import { Effect, FileSystem } from "effect";
|
||||
|
||||
import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver.ts";
|
||||
|
||||
const FAVICON_MIME_TYPES: Record<string, string> = {
|
||||
".png": "image/png",
|
||||
@@ -13,64 +11,161 @@ const FAVICON_MIME_TYPES: Record<string, string> = {
|
||||
|
||||
const FALLBACK_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;
|
||||
|
||||
export const tryHandleProjectFaviconRequest = Effect.fn("tryHandleProjectFaviconRequest")(
|
||||
function* (
|
||||
url: URL,
|
||||
res: http.ServerResponse,
|
||||
): Effect.fn.Return<boolean, never, ProjectFaviconResolver | FileSystem.FileSystem> {
|
||||
const respond = (
|
||||
statusCode: number,
|
||||
headers: Record<string, string>,
|
||||
body: string | Uint8Array,
|
||||
) => {
|
||||
res.writeHead(statusCode, headers);
|
||||
res.end(body);
|
||||
};
|
||||
// Well-known favicon paths checked in order.
|
||||
const FAVICON_CANDIDATES = [
|
||||
"favicon.svg",
|
||||
"favicon.ico",
|
||||
"favicon.png",
|
||||
"public/favicon.svg",
|
||||
"public/favicon.ico",
|
||||
"public/favicon.png",
|
||||
"app/favicon.ico",
|
||||
"app/favicon.png",
|
||||
"app/icon.svg",
|
||||
"app/icon.png",
|
||||
"app/icon.ico",
|
||||
"src/favicon.ico",
|
||||
"src/favicon.svg",
|
||||
"src/app/favicon.ico",
|
||||
"src/app/icon.svg",
|
||||
"src/app/icon.png",
|
||||
"assets/icon.svg",
|
||||
"assets/icon.png",
|
||||
"assets/logo.svg",
|
||||
"assets/logo.png",
|
||||
];
|
||||
|
||||
if (url.pathname !== "/api/project-favicon") {
|
||||
return false;
|
||||
// Files that may contain a <link rel="icon"> or icon metadata declaration.
|
||||
const ICON_SOURCE_FILES = [
|
||||
"index.html",
|
||||
"public/index.html",
|
||||
"app/routes/__root.tsx",
|
||||
"src/routes/__root.tsx",
|
||||
"app/root.tsx",
|
||||
"src/root.tsx",
|
||||
"src/index.html",
|
||||
];
|
||||
|
||||
// Matches <link ...> tags or object-like icon metadata where rel/href can appear in any order.
|
||||
const LINK_ICON_HTML_RE =
|
||||
/<link\b(?=[^>]*\brel=["'](?:icon|shortcut icon)["'])(?=[^>]*\bhref=["']([^"'?]+))[^>]*>/i;
|
||||
const LINK_ICON_OBJ_RE =
|
||||
/(?=[^}]*\brel\s*:\s*["'](?:icon|shortcut icon)["'])(?=[^}]*\bhref\s*:\s*["']([^"'?]+))[^}]*/i;
|
||||
|
||||
function extractIconHref(source: string): string | null {
|
||||
const htmlMatch = source.match(LINK_ICON_HTML_RE);
|
||||
if (htmlMatch?.[1]) return htmlMatch[1];
|
||||
const objMatch = source.match(LINK_ICON_OBJ_RE);
|
||||
if (objMatch?.[1]) return objMatch[1];
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveIconHref(projectCwd: string, href: string): string[] {
|
||||
const clean = href.replace(/^\//, "");
|
||||
return [path.join(projectCwd, "public", clean), path.join(projectCwd, clean)];
|
||||
}
|
||||
|
||||
function isPathWithinProject(projectCwd: string, candidatePath: string): boolean {
|
||||
const relative = path.relative(path.resolve(projectCwd), path.resolve(candidatePath));
|
||||
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
|
||||
}
|
||||
|
||||
function serveFaviconFile(filePath: string, res: http.ServerResponse): void {
|
||||
const ext = path.extname(filePath).toLowerCase();
|
||||
const contentType = FAVICON_MIME_TYPES[ext] ?? "application/octet-stream";
|
||||
fs.readFile(filePath, (readErr, data) => {
|
||||
if (readErr) {
|
||||
res.writeHead(500, { "Content-Type": "text/plain" });
|
||||
res.end("Read error");
|
||||
return;
|
||||
}
|
||||
res.writeHead(200, {
|
||||
"Content-Type": contentType,
|
||||
"Cache-Control": "public, max-age=3600",
|
||||
});
|
||||
res.end(data);
|
||||
});
|
||||
}
|
||||
|
||||
const projectCwd = url.searchParams.get("cwd");
|
||||
if (!projectCwd) {
|
||||
respond(400, { "Content-Type": "text/plain" }, "Missing cwd parameter");
|
||||
return true;
|
||||
}
|
||||
function serveFallbackFavicon(res: http.ServerResponse): void {
|
||||
res.writeHead(200, {
|
||||
"Content-Type": "image/svg+xml",
|
||||
"Cache-Control": "public, max-age=3600",
|
||||
});
|
||||
res.end(FALLBACK_FAVICON_SVG);
|
||||
}
|
||||
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const faviconResolver = yield* ProjectFaviconResolver;
|
||||
const resolvedPath = yield* faviconResolver.resolvePath(projectCwd);
|
||||
export function tryHandleProjectFaviconRequest(url: URL, res: http.ServerResponse): boolean {
|
||||
if (url.pathname !== "/api/project-favicon") {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!resolvedPath) {
|
||||
respond(
|
||||
200,
|
||||
{
|
||||
"Content-Type": "image/svg+xml",
|
||||
"Cache-Control": "public, max-age=3600",
|
||||
},
|
||||
FALLBACK_FAVICON_SVG,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
const data = yield* fileSystem
|
||||
.readFile(resolvedPath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!data) {
|
||||
respond(500, { "Content-Type": "text/plain" }, "Read error");
|
||||
return true;
|
||||
}
|
||||
|
||||
const ext = path.extname(resolvedPath).toLowerCase();
|
||||
const contentType = FAVICON_MIME_TYPES[ext] ?? "application/octet-stream";
|
||||
respond(
|
||||
200,
|
||||
{
|
||||
"Content-Type": contentType,
|
||||
"Cache-Control": "public, max-age=3600",
|
||||
},
|
||||
data,
|
||||
);
|
||||
const projectCwd = url.searchParams.get("cwd");
|
||||
if (!projectCwd) {
|
||||
res.writeHead(400, { "Content-Type": "text/plain" });
|
||||
res.end("Missing cwd parameter");
|
||||
return true;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const tryResolvedPaths = (paths: string[], index: number, onExhausted: () => void): void => {
|
||||
if (index >= paths.length) {
|
||||
onExhausted();
|
||||
return;
|
||||
}
|
||||
const candidate = paths[index]!;
|
||||
if (!isPathWithinProject(projectCwd, candidate)) {
|
||||
tryResolvedPaths(paths, index + 1, onExhausted);
|
||||
return;
|
||||
}
|
||||
fs.stat(candidate, (err, stats) => {
|
||||
if (err || !stats?.isFile()) {
|
||||
tryResolvedPaths(paths, index + 1, onExhausted);
|
||||
return;
|
||||
}
|
||||
serveFaviconFile(candidate, res);
|
||||
});
|
||||
};
|
||||
|
||||
const trySourceFiles = (index: number): void => {
|
||||
if (index >= ICON_SOURCE_FILES.length) {
|
||||
serveFallbackFavicon(res);
|
||||
return;
|
||||
}
|
||||
const sourceFile = path.join(projectCwd, ICON_SOURCE_FILES[index]!);
|
||||
fs.readFile(sourceFile, "utf8", (err, content) => {
|
||||
if (err) {
|
||||
trySourceFiles(index + 1);
|
||||
return;
|
||||
}
|
||||
const href = extractIconHref(content);
|
||||
if (!href) {
|
||||
trySourceFiles(index + 1);
|
||||
return;
|
||||
}
|
||||
const candidates = resolveIconHref(projectCwd, href);
|
||||
tryResolvedPaths(candidates, 0, () => trySourceFiles(index + 1));
|
||||
});
|
||||
};
|
||||
|
||||
const tryCandidates = (index: number): void => {
|
||||
if (index >= FAVICON_CANDIDATES.length) {
|
||||
trySourceFiles(0);
|
||||
return;
|
||||
}
|
||||
const candidate = path.join(projectCwd, FAVICON_CANDIDATES[index]!);
|
||||
if (!isPathWithinProject(projectCwd, candidate)) {
|
||||
tryCandidates(index + 1);
|
||||
return;
|
||||
}
|
||||
fs.stat(candidate, (err, stats) => {
|
||||
if (err || !stats?.isFile()) {
|
||||
tryCandidates(index + 1);
|
||||
return;
|
||||
}
|
||||
serveFaviconFile(candidate, res);
|
||||
});
|
||||
};
|
||||
|
||||
tryCandidates(0);
|
||||
return true;
|
||||
}
|
||||
@@ -2134,7 +2134,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
});
|
||||
|
||||
const permissionResult = yield* Effect.promise(() => permissionPromise);
|
||||
assert.equal(permissionResult.behavior, "allow");
|
||||
assert.equal((permissionResult as PermissionResult).behavior, "allow");
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
@@ -2623,7 +2623,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
});
|
||||
|
||||
const permissionResult = yield* Effect.promise(() => permissionPromise);
|
||||
assert.equal(permissionResult.behavior, "deny");
|
||||
assert.equal((permissionResult as PermissionResult).behavior, "deny");
|
||||
const deniedResult = permissionResult as PermissionResult & {
|
||||
message?: string;
|
||||
};
|
||||
@@ -2817,7 +2817,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
|
||||
// The canUseTool promise should resolve with the answers in SDK format.
|
||||
const permissionResult = yield* Effect.promise(() => permissionPromise);
|
||||
assert.equal(permissionResult.behavior, "allow");
|
||||
assert.equal((permissionResult as PermissionResult).behavior, "allow");
|
||||
const updatedInput = (permissionResult as { updatedInput: Record<string, unknown> })
|
||||
.updatedInput;
|
||||
assert.deepEqual(updatedInput.answers, { "Which framework?": "React" });
|
||||
@@ -2889,7 +2889,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
yield* Stream.runHead(adapter.streamEvents);
|
||||
|
||||
const permissionResult = yield* Effect.promise(() => permissionPromise);
|
||||
assert.equal(permissionResult.behavior, "allow");
|
||||
assert.equal((permissionResult as PermissionResult).behavior, "allow");
|
||||
const updatedInput = (permissionResult as { updatedInput: Record<string, unknown> })
|
||||
.updatedInput;
|
||||
assert.deepEqual(updatedInput.answers, { "Deploy to which env?": "Staging" });
|
||||
|
||||
@@ -261,7 +261,7 @@ function isInterruptedResult(result: SDKResultMessage): boolean {
|
||||
|
||||
return (
|
||||
result.subtype === "error_during_execution" &&
|
||||
!result.is_error &&
|
||||
result.is_error === false &&
|
||||
(errors.includes("request was aborted") ||
|
||||
errors.includes("interrupted by user") ||
|
||||
errors.includes("aborted"))
|
||||
@@ -2817,7 +2817,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
providerRefs: {},
|
||||
});
|
||||
|
||||
let streamFiber: Fiber.Fiber<void>;
|
||||
let streamFiber: Fiber.Fiber<void, never>;
|
||||
streamFiber = runFork(
|
||||
Effect.exit(runSdkStream(context)).pipe(
|
||||
Effect.flatMap((exit) => {
|
||||
|
||||
@@ -1345,7 +1345,7 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
if (options?.manager) {
|
||||
return options.manager;
|
||||
}
|
||||
const services = yield* Effect.services();
|
||||
const services = yield* Effect.services<never>();
|
||||
return options?.makeManager?.(services) ?? new CodexAppServerManager(services);
|
||||
});
|
||||
|
||||
@@ -1564,7 +1564,7 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
});
|
||||
|
||||
const registerListener = Effect.fn("registerListener")(function* () {
|
||||
const services = yield* Effect.services();
|
||||
const services = yield* Effect.services<never>();
|
||||
const listenerEffect = Effect.fn("listener")(function* (event: ProviderEvent) {
|
||||
yield* writeNativeEvent(event);
|
||||
const runtimeEvents = mapToRuntimeEvents(event, event.threadId);
|
||||
|
||||
@@ -34,10 +34,6 @@ import { GitHubCliLive } from "./git/Layers/GitHubCli";
|
||||
import { RoutingTextGenerationLive } from "./git/Layers/RoutingTextGeneration";
|
||||
import { PtyAdapter } from "./terminal/Services/PTY";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
|
||||
import { ProjectFaviconResolverLive } from "./project/Layers/ProjectFaviconResolver.ts";
|
||||
import { WorkspaceEntriesLive } from "./workspace/Layers/WorkspaceEntries.ts";
|
||||
import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem.ts";
|
||||
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";
|
||||
|
||||
type RuntimePtyAdapterLoader = {
|
||||
layer: Layer.Layer<PtyAdapter, never, FileSystem.FileSystem | Path.Path>;
|
||||
@@ -95,8 +91,7 @@ export function makeServerProviderLayer(): Layer.Layer<
|
||||
|
||||
export function makeServerRuntimeServicesLayer() {
|
||||
const textGenerationLayer = RoutingTextGenerationLive;
|
||||
const gitCoreLayer = GitCoreLive;
|
||||
const checkpointStoreLayer = CheckpointStoreLive;
|
||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
|
||||
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
@@ -121,11 +116,11 @@ export function makeServerRuntimeServicesLayer() {
|
||||
);
|
||||
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(GitCoreLive),
|
||||
Layer.provideMerge(textGenerationLayer),
|
||||
);
|
||||
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(WorkspaceEntriesLive),
|
||||
);
|
||||
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeIngestionLayer),
|
||||
@@ -136,26 +131,16 @@ export function makeServerRuntimeServicesLayer() {
|
||||
const terminalLayer = TerminalManagerLive.pipe(Layer.provide(makeRuntimePtyAdapterLayer()));
|
||||
|
||||
const gitManagerLayer = GitManagerLive.pipe(
|
||||
Layer.provideMerge(GitCoreLive),
|
||||
Layer.provideMerge(GitHubCliLive),
|
||||
Layer.provideMerge(textGenerationLayer),
|
||||
);
|
||||
|
||||
const workspacePathsLayer = WorkspacePathsLive;
|
||||
const workspaceEntriesLayer = WorkspaceEntriesLive;
|
||||
const workspaceFileSystemLayer = WorkspaceFileSystemLive.pipe(
|
||||
Layer.provide(workspacePathsLayer),
|
||||
Layer.provide(workspaceEntriesLayer),
|
||||
);
|
||||
const projectFaviconResolverLayer = ProjectFaviconResolverLive;
|
||||
|
||||
return Layer.mergeAll(
|
||||
orchestrationReactorLayer,
|
||||
workspacePathsLayer,
|
||||
workspaceEntriesLayer,
|
||||
workspaceFileSystemLayer,
|
||||
projectFaviconResolverLayer,
|
||||
GitCoreLive,
|
||||
gitManagerLayer,
|
||||
terminalLayer,
|
||||
KeybindingsLive,
|
||||
).pipe(Layer.provideMerge(gitCoreLayer), Layer.provideMerge(NodeServices.layer));
|
||||
).pipe(Layer.provideMerge(NodeServices.layer));
|
||||
}
|
||||
@@ -15,12 +15,12 @@ export interface AnalyticsServiceShape {
|
||||
readonly record: (
|
||||
event: string,
|
||||
properties?: Readonly<Record<string, unknown>>,
|
||||
) => Effect.Effect<void>;
|
||||
) => Effect.Effect<void, never>;
|
||||
|
||||
/**
|
||||
* Flush queued telemetry.
|
||||
*/
|
||||
readonly flush: Effect.Effect<void>;
|
||||
readonly flush: Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
export class AnalyticsService extends ServiceMap.Service<AnalyticsService, AnalyticsServiceShape>()(
|
||||
|
||||
@@ -22,7 +22,7 @@ import {
|
||||
Scope,
|
||||
} from "effect";
|
||||
import { TestClock } from "effect/testing";
|
||||
import { expect } from "vite-plus/test";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import type { TerminalManagerShape } from "../Services/Manager";
|
||||
import {
|
||||
@@ -483,7 +483,7 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
|
||||
hasRunningSubprocess = true;
|
||||
yield* waitFor(
|
||||
Effect.map(getEvents, (events) =>
|
||||
events.some((event) => event.type === "activity" && event.hasRunningSubprocess),
|
||||
events.some((event) => event.type === "activity" && event.hasRunningSubprocess === true),
|
||||
),
|
||||
"1200 millis",
|
||||
);
|
||||
@@ -491,7 +491,7 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
|
||||
hasRunningSubprocess = false;
|
||||
yield* waitFor(
|
||||
Effect.map(getEvents, (events) =>
|
||||
events.some((event) => event.type === "activity" && !event.hasRunningSubprocess),
|
||||
events.some((event) => event.type === "activity" && event.hasRunningSubprocess === false),
|
||||
),
|
||||
"1200 millis",
|
||||
);
|
||||
|
||||
@@ -130,7 +130,7 @@ type DrainProcessEventAction =
|
||||
|
||||
interface TerminalManagerState {
|
||||
sessions: Map<string, TerminalSessionState>;
|
||||
killFibers: Map<PtyProcess, Fiber.Fiber<void>>;
|
||||
killFibers: Map<PtyProcess, Fiber.Fiber<void, never>>;
|
||||
}
|
||||
|
||||
function snapshot(session: TerminalSessionState): TerminalSessionSnapshot {
|
||||
@@ -742,14 +742,14 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
process: PtyProcess | null,
|
||||
) {
|
||||
if (!process) return;
|
||||
const fiber: Option.Option<Fiber.Fiber<void>> = yield* modifyManagerState<
|
||||
Option.Option<Fiber.Fiber<void>>
|
||||
const fiber: Option.Option<Fiber.Fiber<void, never>> = yield* modifyManagerState<
|
||||
Option.Option<Fiber.Fiber<void, never>>
|
||||
>((state) => {
|
||||
const existing: Option.Option<Fiber.Fiber<void>> = Option.fromNullishOr(
|
||||
const existing: Option.Option<Fiber.Fiber<void, never>> = Option.fromNullishOr(
|
||||
state.killFibers.get(process),
|
||||
);
|
||||
if (Option.isNone(existing)) {
|
||||
return [Option.none<Fiber.Fiber<void>>(), state] as const;
|
||||
return [Option.none<Fiber.Fiber<void, never>>(), state] as const;
|
||||
}
|
||||
const killFibers = new Map(state.killFibers);
|
||||
killFibers.delete(process);
|
||||
@@ -762,7 +762,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
|
||||
const registerKillFiber = Effect.fn("terminal.registerKillFiber")(function* (
|
||||
process: PtyProcess,
|
||||
fiber: Fiber.Fiber<void>,
|
||||
fiber: Fiber.Fiber<void, never>,
|
||||
) {
|
||||
yield* modifyManagerState((state) => {
|
||||
const killFibers = new Map(state.killFibers);
|
||||
|
||||
@@ -1,264 +0,0 @@
|
||||
import fsPromises from "node:fs/promises";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it, afterEach, describe, expect, vi } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path, PlatformError } from "effect";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
|
||||
import { GitCore } from "../../git/Services/GitCore.ts";
|
||||
import { WorkspaceEntries } from "../Services/WorkspaceEntries.ts";
|
||||
import { WorkspaceEntriesLive } from "./WorkspaceEntries.ts";
|
||||
|
||||
const TestLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(WorkspaceEntriesLive),
|
||||
Layer.provideMerge(GitCoreLive),
|
||||
Layer.provide(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-workspace-entries-test-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const makeTempDir = Effect.fn(function* (opts?: { prefix?: string; git?: boolean }) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const gitCore = yield* GitCore;
|
||||
const dir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: opts?.prefix ?? "t3code-workspace-entries-",
|
||||
});
|
||||
if (opts?.git) {
|
||||
yield* gitCore.initRepo({ cwd: dir });
|
||||
}
|
||||
return dir;
|
||||
});
|
||||
|
||||
function writeTextFile(
|
||||
cwd: string,
|
||||
relativePath: string,
|
||||
contents = "",
|
||||
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem | Path.Path> {
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const absolutePath = path.join(cwd, relativePath);
|
||||
yield* fileSystem.makeDirectory(path.dirname(absolutePath), { recursive: true });
|
||||
yield* fileSystem.writeFileString(absolutePath, contents);
|
||||
});
|
||||
}
|
||||
|
||||
const git = (cwd: string, args: ReadonlyArray<string>, env?: NodeJS.ProcessEnv) =>
|
||||
Effect.gen(function* () {
|
||||
const gitCore = yield* GitCore;
|
||||
const result = yield* gitCore.execute({
|
||||
operation: "WorkspaceEntries.test.git",
|
||||
cwd,
|
||||
args,
|
||||
...(env ? { env } : {}),
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
return result.stdout.trim();
|
||||
});
|
||||
|
||||
const searchWorkspaceEntries = (input: { cwd: string; query: string; limit: number }) =>
|
||||
Effect.gen(function* () {
|
||||
const workspaceEntries = yield* WorkspaceEntries;
|
||||
return yield* workspaceEntries.search(input);
|
||||
});
|
||||
|
||||
it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("search", () => {
|
||||
it.effect("returns files and directories relative to cwd", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTempDir();
|
||||
yield* writeTextFile(cwd, "src/components/Composer.tsx");
|
||||
yield* writeTextFile(cwd, "src/index.ts");
|
||||
yield* writeTextFile(cwd, "README.md");
|
||||
yield* writeTextFile(cwd, ".git/HEAD");
|
||||
yield* writeTextFile(cwd, "node_modules/pkg/index.js");
|
||||
|
||||
const result = yield* searchWorkspaceEntries({ cwd, query: "", limit: 100 });
|
||||
const paths = result.entries.map((entry) => entry.path);
|
||||
|
||||
expect(paths).toContain("src");
|
||||
expect(paths).toContain("src/components");
|
||||
expect(paths).toContain("src/components/Composer.tsx");
|
||||
expect(paths).toContain("README.md");
|
||||
expect(paths.some((entryPath) => entryPath.startsWith(".git"))).toBe(false);
|
||||
expect(paths.some((entryPath) => entryPath.startsWith("node_modules"))).toBe(false);
|
||||
expect(result.truncated).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("filters and ranks entries by query", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-query-" });
|
||||
yield* writeTextFile(cwd, "src/components/Composer.tsx");
|
||||
yield* writeTextFile(cwd, "src/components/composePrompt.ts");
|
||||
yield* writeTextFile(cwd, "docs/composition.md");
|
||||
|
||||
const result = yield* searchWorkspaceEntries({ cwd, query: "compo", limit: 5 });
|
||||
|
||||
expect(result.entries.length).toBeGreaterThan(0);
|
||||
expect(result.entries.some((entry) => entry.path === "src/components")).toBe(true);
|
||||
expect(result.entries.every((entry) => entry.path.toLowerCase().includes("compo"))).toBe(
|
||||
true,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("supports fuzzy subsequence queries for composer path search", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-fuzzy-query-" });
|
||||
yield* writeTextFile(cwd, "src/components/Composer.tsx");
|
||||
yield* writeTextFile(cwd, "src/components/composePrompt.ts");
|
||||
yield* writeTextFile(cwd, "docs/composition.md");
|
||||
|
||||
const result = yield* searchWorkspaceEntries({ cwd, query: "cmp", limit: 10 });
|
||||
const paths = result.entries.map((entry) => entry.path);
|
||||
|
||||
expect(result.entries.length).toBeGreaterThan(0);
|
||||
expect(paths).toContain("src/components");
|
||||
expect(paths).toContain("src/components/Composer.tsx");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("tracks truncation without sorting every fuzzy match", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-fuzzy-limit-" });
|
||||
yield* writeTextFile(cwd, "src/components/Composer.tsx");
|
||||
yield* writeTextFile(cwd, "src/components/composePrompt.ts");
|
||||
yield* writeTextFile(cwd, "docs/composition.md");
|
||||
|
||||
const result = yield* searchWorkspaceEntries({ cwd, query: "cmp", limit: 1 });
|
||||
|
||||
expect(result.entries).toHaveLength(1);
|
||||
expect(result.truncated).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("excludes gitignored paths for git repositories", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-gitignore-", git: true });
|
||||
yield* writeTextFile(cwd, ".gitignore", ".convex/\nconvex/\nignored.txt\n");
|
||||
yield* writeTextFile(cwd, "src/keep.ts", "export {};");
|
||||
yield* writeTextFile(cwd, "ignored.txt", "ignore me");
|
||||
yield* writeTextFile(cwd, ".convex/local-storage/data.json", "{}");
|
||||
yield* writeTextFile(cwd, "convex/UOoS-l/convex_local_storage/modules/data.json", "{}");
|
||||
|
||||
const result = yield* searchWorkspaceEntries({ cwd, query: "", limit: 100 });
|
||||
const paths = result.entries.map((entry) => entry.path);
|
||||
|
||||
expect(paths).toContain("src");
|
||||
expect(paths).toContain("src/keep.ts");
|
||||
expect(paths).not.toContain("ignored.txt");
|
||||
expect(paths.some((entryPath) => entryPath.startsWith(".convex/"))).toBe(false);
|
||||
expect(paths.some((entryPath) => entryPath.startsWith("convex/"))).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("excludes tracked paths that match ignore rules", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTempDir({
|
||||
prefix: "t3code-workspace-tracked-gitignore-",
|
||||
git: true,
|
||||
});
|
||||
yield* writeTextFile(cwd, ".convex/local-storage/data.json", "{}");
|
||||
yield* writeTextFile(cwd, "src/keep.ts", "export {};");
|
||||
yield* git(cwd, ["add", ".convex/local-storage/data.json", "src/keep.ts"]);
|
||||
yield* writeTextFile(cwd, ".gitignore", ".convex/\n");
|
||||
|
||||
const result = yield* searchWorkspaceEntries({ cwd, query: "", limit: 100 });
|
||||
const paths = result.entries.map((entry) => entry.path);
|
||||
|
||||
expect(paths).toContain("src");
|
||||
expect(paths).toContain("src/keep.ts");
|
||||
expect(paths.some((entryPath) => entryPath.startsWith(".convex/"))).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("excludes .convex in non-git workspaces", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-non-git-convex-" });
|
||||
yield* writeTextFile(cwd, ".convex/local-storage/data.json", "{}");
|
||||
yield* writeTextFile(cwd, "src/keep.ts", "export {};");
|
||||
|
||||
const result = yield* searchWorkspaceEntries({ cwd, query: "", limit: 100 });
|
||||
const paths = result.entries.map((entry) => entry.path);
|
||||
|
||||
expect(paths).toContain("src");
|
||||
expect(paths).toContain("src/keep.ts");
|
||||
expect(paths.some((entryPath) => entryPath.startsWith(".convex/"))).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("deduplicates concurrent index builds for the same cwd", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-concurrent-build-" });
|
||||
yield* writeTextFile(cwd, "src/components/Composer.tsx");
|
||||
|
||||
let rootReadCount = 0;
|
||||
const originalReaddir = fsPromises.readdir.bind(fsPromises);
|
||||
vi.spyOn(fsPromises, "readdir").mockImplementation((async (
|
||||
...args: Parameters<typeof fsPromises.readdir>
|
||||
) => {
|
||||
if (args[0] === cwd) {
|
||||
rootReadCount += 1;
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
}
|
||||
return originalReaddir(...args);
|
||||
}) as typeof fsPromises.readdir);
|
||||
|
||||
yield* Effect.all(
|
||||
[
|
||||
searchWorkspaceEntries({ cwd, query: "", limit: 100 }),
|
||||
searchWorkspaceEntries({ cwd, query: "comp", limit: 100 }),
|
||||
searchWorkspaceEntries({ cwd, query: "src", limit: 100 }),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
expect(rootReadCount).toBe(1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("limits concurrent directory reads while walking the filesystem", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-read-concurrency-" });
|
||||
yield* Effect.forEach(
|
||||
Array.from({ length: 80 }, (_, index) => index),
|
||||
(index) => writeTextFile(cwd, `group-${index}/entry-${index}.ts`, "export {};"),
|
||||
{ discard: true },
|
||||
);
|
||||
|
||||
let activeReads = 0;
|
||||
let peakReads = 0;
|
||||
const originalReaddir = fsPromises.readdir.bind(fsPromises);
|
||||
vi.spyOn(fsPromises, "readdir").mockImplementation((async (
|
||||
...args: Parameters<typeof fsPromises.readdir>
|
||||
) => {
|
||||
const target = args[0];
|
||||
if (typeof target === "string" && target.startsWith(cwd)) {
|
||||
activeReads += 1;
|
||||
peakReads = Math.max(peakReads, activeReads);
|
||||
await new Promise((resolve) => setTimeout(resolve, 4));
|
||||
try {
|
||||
return await originalReaddir(...args);
|
||||
} finally {
|
||||
activeReads -= 1;
|
||||
}
|
||||
}
|
||||
return originalReaddir(...args);
|
||||
}) as typeof fsPromises.readdir);
|
||||
|
||||
yield* searchWorkspaceEntries({ cwd, query: "", limit: 200 });
|
||||
|
||||
expect(peakReads).toBeLessThanOrEqual(32);
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,476 +0,0 @@
|
||||
import fsPromises from "node:fs/promises";
|
||||
import type { Dirent } from "node:fs";
|
||||
|
||||
import { Cache, Duration, Effect, Exit, Layer, Option, Path } from "effect";
|
||||
|
||||
import { type ProjectEntry } from "@t3tools/contracts";
|
||||
|
||||
import { GitCore } from "../../git/Services/GitCore.ts";
|
||||
import {
|
||||
WorkspaceEntries,
|
||||
WorkspaceEntriesError,
|
||||
type WorkspaceEntriesShape,
|
||||
} from "../Services/WorkspaceEntries.ts";
|
||||
|
||||
const WORKSPACE_CACHE_TTL_MS = 15_000;
|
||||
const WORKSPACE_CACHE_MAX_KEYS = 4;
|
||||
const WORKSPACE_INDEX_MAX_ENTRIES = 25_000;
|
||||
const WORKSPACE_SCAN_READDIR_CONCURRENCY = 32;
|
||||
const IGNORED_DIRECTORY_NAMES = new Set([
|
||||
".git",
|
||||
".convex",
|
||||
"node_modules",
|
||||
".next",
|
||||
".turbo",
|
||||
".vite",
|
||||
"dist",
|
||||
"build",
|
||||
"out",
|
||||
".cache",
|
||||
]);
|
||||
|
||||
interface WorkspaceIndex {
|
||||
scannedAt: number;
|
||||
entries: SearchableWorkspaceEntry[];
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
interface SearchableWorkspaceEntry extends ProjectEntry {
|
||||
normalizedPath: string;
|
||||
normalizedName: string;
|
||||
}
|
||||
|
||||
interface RankedWorkspaceEntry {
|
||||
entry: SearchableWorkspaceEntry;
|
||||
score: number;
|
||||
}
|
||||
|
||||
function toPosixPath(input: string): string {
|
||||
return input.replaceAll("\\", "/");
|
||||
}
|
||||
|
||||
function parentPathOf(input: string): string | undefined {
|
||||
const separatorIndex = input.lastIndexOf("/");
|
||||
if (separatorIndex === -1) {
|
||||
return undefined;
|
||||
}
|
||||
return input.slice(0, separatorIndex);
|
||||
}
|
||||
|
||||
function basenameOf(input: string): string {
|
||||
const separatorIndex = input.lastIndexOf("/");
|
||||
if (separatorIndex === -1) {
|
||||
return input;
|
||||
}
|
||||
return input.slice(separatorIndex + 1);
|
||||
}
|
||||
|
||||
function toSearchableWorkspaceEntry(entry: ProjectEntry): SearchableWorkspaceEntry {
|
||||
const normalizedPath = entry.path.toLowerCase();
|
||||
return {
|
||||
...entry,
|
||||
normalizedPath,
|
||||
normalizedName: basenameOf(normalizedPath),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeQuery(input: string): string {
|
||||
return input
|
||||
.trim()
|
||||
.replace(/^[@./]+/, "")
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function scoreSubsequenceMatch(value: string, query: string): number | null {
|
||||
if (!query) return 0;
|
||||
|
||||
let queryIndex = 0;
|
||||
let firstMatchIndex = -1;
|
||||
let previousMatchIndex = -1;
|
||||
let gapPenalty = 0;
|
||||
|
||||
for (let valueIndex = 0; valueIndex < value.length; valueIndex += 1) {
|
||||
if (value[valueIndex] !== query[queryIndex]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (firstMatchIndex === -1) {
|
||||
firstMatchIndex = valueIndex;
|
||||
}
|
||||
if (previousMatchIndex !== -1) {
|
||||
gapPenalty += valueIndex - previousMatchIndex - 1;
|
||||
}
|
||||
|
||||
previousMatchIndex = valueIndex;
|
||||
queryIndex += 1;
|
||||
if (queryIndex === query.length) {
|
||||
const spanPenalty = valueIndex - firstMatchIndex + 1 - query.length;
|
||||
const lengthPenalty = Math.min(64, value.length - query.length);
|
||||
return firstMatchIndex * 2 + gapPenalty * 3 + spanPenalty + lengthPenalty;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function scoreEntry(entry: SearchableWorkspaceEntry, query: string): number | null {
|
||||
if (!query) {
|
||||
return entry.kind === "directory" ? 0 : 1;
|
||||
}
|
||||
|
||||
const { normalizedPath, normalizedName } = entry;
|
||||
|
||||
if (normalizedName === query) return 0;
|
||||
if (normalizedPath === query) return 1;
|
||||
if (normalizedName.startsWith(query)) return 2;
|
||||
if (normalizedPath.startsWith(query)) return 3;
|
||||
if (normalizedPath.includes(`/${query}`)) return 4;
|
||||
if (normalizedName.includes(query)) return 5;
|
||||
if (normalizedPath.includes(query)) return 6;
|
||||
|
||||
const nameFuzzyScore = scoreSubsequenceMatch(normalizedName, query);
|
||||
if (nameFuzzyScore !== null) {
|
||||
return 100 + nameFuzzyScore;
|
||||
}
|
||||
|
||||
const pathFuzzyScore = scoreSubsequenceMatch(normalizedPath, query);
|
||||
if (pathFuzzyScore !== null) {
|
||||
return 200 + pathFuzzyScore;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function compareRankedWorkspaceEntries(
|
||||
left: RankedWorkspaceEntry,
|
||||
right: RankedWorkspaceEntry,
|
||||
): number {
|
||||
const scoreDelta = left.score - right.score;
|
||||
if (scoreDelta !== 0) return scoreDelta;
|
||||
return left.entry.path.localeCompare(right.entry.path);
|
||||
}
|
||||
|
||||
function findInsertionIndex(
|
||||
rankedEntries: RankedWorkspaceEntry[],
|
||||
candidate: RankedWorkspaceEntry,
|
||||
): number {
|
||||
let low = 0;
|
||||
let high = rankedEntries.length;
|
||||
|
||||
while (low < high) {
|
||||
const middle = low + Math.floor((high - low) / 2);
|
||||
const current = rankedEntries[middle];
|
||||
if (!current) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (compareRankedWorkspaceEntries(candidate, current) < 0) {
|
||||
high = middle;
|
||||
} else {
|
||||
low = middle + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return low;
|
||||
}
|
||||
|
||||
function insertRankedEntry(
|
||||
rankedEntries: RankedWorkspaceEntry[],
|
||||
candidate: RankedWorkspaceEntry,
|
||||
limit: number,
|
||||
): void {
|
||||
if (limit <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const insertionIndex = findInsertionIndex(rankedEntries, candidate);
|
||||
if (rankedEntries.length < limit) {
|
||||
rankedEntries.splice(insertionIndex, 0, candidate);
|
||||
return;
|
||||
}
|
||||
|
||||
if (insertionIndex >= limit) {
|
||||
return;
|
||||
}
|
||||
|
||||
rankedEntries.splice(insertionIndex, 0, candidate);
|
||||
rankedEntries.pop();
|
||||
}
|
||||
|
||||
function isPathInIgnoredDirectory(relativePath: string): boolean {
|
||||
const firstSegment = relativePath.split("/")[0];
|
||||
if (!firstSegment) return false;
|
||||
return IGNORED_DIRECTORY_NAMES.has(firstSegment);
|
||||
}
|
||||
|
||||
function directoryAncestorsOf(relativePath: string): string[] {
|
||||
const segments = relativePath.split("/").filter((segment) => segment.length > 0);
|
||||
if (segments.length <= 1) return [];
|
||||
|
||||
const directories: string[] = [];
|
||||
for (let index = 1; index < segments.length; index += 1) {
|
||||
directories.push(segments.slice(0, index).join("/"));
|
||||
}
|
||||
return directories;
|
||||
}
|
||||
|
||||
const processErrorDetail = (cause: unknown): string =>
|
||||
cause instanceof Error ? cause.message : String(cause);
|
||||
|
||||
export const makeWorkspaceEntries = Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const gitOption = yield* Effect.serviceOption(GitCore);
|
||||
|
||||
const isInsideGitWorkTree = (cwd: string): Effect.Effect<boolean> =>
|
||||
Option.match(gitOption, {
|
||||
onSome: (git) => git.isInsideWorkTree(cwd).pipe(Effect.catch(() => Effect.succeed(false))),
|
||||
onNone: () => Effect.succeed(false),
|
||||
});
|
||||
|
||||
const filterGitIgnoredPaths = (cwd: string, relativePaths: string[]): Effect.Effect<string[]> =>
|
||||
Option.match(gitOption, {
|
||||
onSome: (git) =>
|
||||
git.filterIgnoredPaths(cwd, relativePaths).pipe(
|
||||
Effect.map((paths) => [...paths]),
|
||||
Effect.catch(() => Effect.succeed(relativePaths)),
|
||||
),
|
||||
onNone: () => Effect.succeed(relativePaths),
|
||||
});
|
||||
|
||||
const buildWorkspaceIndexFromGit = Effect.fn("WorkspaceEntries.buildWorkspaceIndexFromGit")(
|
||||
function* (cwd: string) {
|
||||
if (Option.isNone(gitOption)) {
|
||||
return null;
|
||||
}
|
||||
if (!(yield* isInsideGitWorkTree(cwd))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const listedFiles = yield* gitOption.value
|
||||
.listWorkspaceFiles(cwd)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
|
||||
if (!listedFiles) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const listedPaths = [...listedFiles.paths]
|
||||
.map((entry) => toPosixPath(entry))
|
||||
.filter((entry) => entry.length > 0 && !isPathInIgnoredDirectory(entry));
|
||||
const filePaths = yield* filterGitIgnoredPaths(cwd, listedPaths);
|
||||
|
||||
const directorySet = new Set<string>();
|
||||
for (const filePath of filePaths) {
|
||||
for (const directoryPath of directoryAncestorsOf(filePath)) {
|
||||
if (!isPathInIgnoredDirectory(directoryPath)) {
|
||||
directorySet.add(directoryPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const directoryEntries = [...directorySet]
|
||||
.toSorted((left, right) => left.localeCompare(right))
|
||||
.map(
|
||||
(directoryPath): ProjectEntry => ({
|
||||
path: directoryPath,
|
||||
kind: "directory",
|
||||
parentPath: parentPathOf(directoryPath),
|
||||
}),
|
||||
)
|
||||
.map(toSearchableWorkspaceEntry);
|
||||
const fileEntries = [...new Set(filePaths)]
|
||||
.toSorted((left, right) => left.localeCompare(right))
|
||||
.map(
|
||||
(filePath): ProjectEntry => ({
|
||||
path: filePath,
|
||||
kind: "file",
|
||||
parentPath: parentPathOf(filePath),
|
||||
}),
|
||||
)
|
||||
.map(toSearchableWorkspaceEntry);
|
||||
|
||||
const entries = [...directoryEntries, ...fileEntries];
|
||||
return {
|
||||
scannedAt: Date.now(),
|
||||
entries: entries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES),
|
||||
truncated: listedFiles.truncated || entries.length > WORKSPACE_INDEX_MAX_ENTRIES,
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
const readDirectoryEntries = Effect.fn("WorkspaceEntries.readDirectoryEntries")(function* (
|
||||
cwd: string,
|
||||
relativeDir: string,
|
||||
): Effect.fn.Return<
|
||||
{ readonly relativeDir: string; readonly dirents: Dirent[] | null },
|
||||
WorkspaceEntriesError
|
||||
> {
|
||||
return yield* Effect.tryPromise({
|
||||
try: async () => {
|
||||
const absoluteDir = relativeDir ? path.join(cwd, relativeDir) : cwd;
|
||||
const dirents = await fsPromises.readdir(absoluteDir, { withFileTypes: true });
|
||||
return { relativeDir, dirents };
|
||||
},
|
||||
catch: (cause) =>
|
||||
new WorkspaceEntriesError({
|
||||
cwd,
|
||||
operation: "workspaceEntries.readDirectoryEntries",
|
||||
detail: processErrorDetail(cause),
|
||||
cause,
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.catchIf(
|
||||
() => relativeDir.length > 0,
|
||||
() => Effect.succeed({ relativeDir, dirents: null }),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const buildWorkspaceIndexFromFilesystem = Effect.fn(
|
||||
"WorkspaceEntries.buildWorkspaceIndexFromFilesystem",
|
||||
)(function* (cwd: string): Effect.fn.Return<WorkspaceIndex, WorkspaceEntriesError> {
|
||||
const shouldFilterWithGitIgnore = yield* isInsideGitWorkTree(cwd);
|
||||
|
||||
let pendingDirectories: string[] = [""];
|
||||
const entries: SearchableWorkspaceEntry[] = [];
|
||||
let truncated = false;
|
||||
|
||||
while (pendingDirectories.length > 0 && !truncated) {
|
||||
const currentDirectories = pendingDirectories;
|
||||
pendingDirectories = [];
|
||||
|
||||
const directoryEntries = yield* Effect.forEach(
|
||||
currentDirectories,
|
||||
(relativeDir) => readDirectoryEntries(cwd, relativeDir),
|
||||
{ concurrency: WORKSPACE_SCAN_READDIR_CONCURRENCY },
|
||||
);
|
||||
|
||||
const candidateEntriesByDirectory = directoryEntries.map((directoryEntry) => {
|
||||
const { relativeDir, dirents } = directoryEntry;
|
||||
if (!dirents) return [] as Array<{ dirent: Dirent; relativePath: string }>;
|
||||
|
||||
dirents.sort((left, right) => left.name.localeCompare(right.name));
|
||||
const candidates: Array<{ dirent: Dirent; relativePath: string }> = [];
|
||||
for (const dirent of dirents) {
|
||||
if (!dirent.name || dirent.name === "." || dirent.name === "..") {
|
||||
continue;
|
||||
}
|
||||
if (dirent.isDirectory() && IGNORED_DIRECTORY_NAMES.has(dirent.name)) {
|
||||
continue;
|
||||
}
|
||||
if (!dirent.isDirectory() && !dirent.isFile()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const relativePath = toPosixPath(
|
||||
relativeDir ? path.join(relativeDir, dirent.name) : dirent.name,
|
||||
);
|
||||
if (isPathInIgnoredDirectory(relativePath)) {
|
||||
continue;
|
||||
}
|
||||
candidates.push({ dirent, relativePath });
|
||||
}
|
||||
return candidates;
|
||||
});
|
||||
|
||||
const candidatePaths = candidateEntriesByDirectory.flatMap((candidateEntries) =>
|
||||
candidateEntries.map((entry) => entry.relativePath),
|
||||
);
|
||||
const allowedPathSet = shouldFilterWithGitIgnore
|
||||
? new Set(yield* filterGitIgnoredPaths(cwd, candidatePaths))
|
||||
: null;
|
||||
|
||||
for (const candidateEntries of candidateEntriesByDirectory) {
|
||||
for (const candidate of candidateEntries) {
|
||||
if (allowedPathSet && !allowedPathSet.has(candidate.relativePath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const entry = toSearchableWorkspaceEntry({
|
||||
path: candidate.relativePath,
|
||||
kind: candidate.dirent.isDirectory() ? "directory" : "file",
|
||||
parentPath: parentPathOf(candidate.relativePath),
|
||||
});
|
||||
entries.push(entry);
|
||||
|
||||
if (candidate.dirent.isDirectory()) {
|
||||
pendingDirectories.push(candidate.relativePath);
|
||||
}
|
||||
|
||||
if (entries.length >= WORKSPACE_INDEX_MAX_ENTRIES) {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (truncated) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
scannedAt: Date.now(),
|
||||
entries,
|
||||
truncated,
|
||||
};
|
||||
});
|
||||
|
||||
const buildWorkspaceIndex = Effect.fn("WorkspaceEntries.buildWorkspaceIndex")(function* (
|
||||
cwd: string,
|
||||
): Effect.fn.Return<WorkspaceIndex, WorkspaceEntriesError> {
|
||||
const gitIndexed = yield* buildWorkspaceIndexFromGit(cwd);
|
||||
if (gitIndexed) {
|
||||
return gitIndexed;
|
||||
}
|
||||
return yield* buildWorkspaceIndexFromFilesystem(cwd);
|
||||
});
|
||||
|
||||
const workspaceIndexCache = yield* Cache.makeWith<string, WorkspaceIndex, WorkspaceEntriesError>({
|
||||
capacity: WORKSPACE_CACHE_MAX_KEYS,
|
||||
lookup: buildWorkspaceIndex,
|
||||
timeToLive: (exit) =>
|
||||
Exit.isSuccess(exit) ? Duration.millis(WORKSPACE_CACHE_TTL_MS) : Duration.zero,
|
||||
});
|
||||
|
||||
const invalidate: WorkspaceEntriesShape["invalidate"] = Effect.fn("WorkspaceEntries.invalidate")(
|
||||
function* (cwd) {
|
||||
return yield* Cache.invalidate(workspaceIndexCache, cwd);
|
||||
},
|
||||
);
|
||||
|
||||
const search: WorkspaceEntriesShape["search"] = Effect.fn("WorkspaceEntries.search")(
|
||||
function* (input) {
|
||||
return yield* Cache.get(workspaceIndexCache, input.cwd).pipe(
|
||||
Effect.map((index) => {
|
||||
const normalizedQuery = normalizeQuery(input.query);
|
||||
const limit = Math.max(0, Math.floor(input.limit));
|
||||
const rankedEntries: RankedWorkspaceEntry[] = [];
|
||||
let matchedEntryCount = 0;
|
||||
|
||||
for (const entry of index.entries) {
|
||||
const score = scoreEntry(entry, normalizedQuery);
|
||||
if (score === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
matchedEntryCount += 1;
|
||||
insertRankedEntry(rankedEntries, { entry, score }, limit);
|
||||
}
|
||||
|
||||
return {
|
||||
entries: rankedEntries.map((candidate) => candidate.entry),
|
||||
truncated: index.truncated || matchedEntryCount > limit,
|
||||
};
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
invalidate,
|
||||
search,
|
||||
} satisfies WorkspaceEntriesShape;
|
||||
});
|
||||
|
||||
export const WorkspaceEntriesLive = Layer.effect(WorkspaceEntries, makeWorkspaceEntries);
|
||||
@@ -1,135 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it, describe, expect } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
|
||||
import { WorkspaceEntries } from "../Services/WorkspaceEntries.ts";
|
||||
import { WorkspaceFileSystem } from "../Services/WorkspaceFileSystem.ts";
|
||||
import { WorkspaceEntriesLive } from "./WorkspaceEntries.ts";
|
||||
import { WorkspaceFileSystemLive } from "./WorkspaceFileSystem.ts";
|
||||
import { WorkspacePathsLive } from "./WorkspacePaths.ts";
|
||||
|
||||
const ProjectLayer = WorkspaceFileSystemLive.pipe(
|
||||
Layer.provide(WorkspacePathsLive),
|
||||
Layer.provide(WorkspaceEntriesLive),
|
||||
);
|
||||
|
||||
const TestLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(ProjectLayer),
|
||||
Layer.provideMerge(WorkspaceEntriesLive),
|
||||
Layer.provideMerge(GitCoreLive),
|
||||
Layer.provide(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-workspace-files-test-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const makeTempDir = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
return yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3code-workspace-files-",
|
||||
});
|
||||
});
|
||||
|
||||
const writeTextFile = Effect.fn("writeTextFile")(function* (
|
||||
cwd: string,
|
||||
relativePath: string,
|
||||
contents = "",
|
||||
) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const absolutePath = path.join(cwd, relativePath);
|
||||
yield* fileSystem
|
||||
.makeDirectory(path.dirname(absolutePath), { recursive: true })
|
||||
.pipe(Effect.orDie);
|
||||
yield* fileSystem.writeFileString(absolutePath, contents).pipe(Effect.orDie);
|
||||
});
|
||||
|
||||
it.layer(TestLayer)("WorkspaceFileSystemLive", (it) => {
|
||||
describe("writeFile", () => {
|
||||
it.effect("writes files relative to the workspace root", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspaceFileSystem = yield* WorkspaceFileSystem;
|
||||
const cwd = yield* makeTempDir;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const result = yield* workspaceFileSystem.writeFile({
|
||||
cwd,
|
||||
relativePath: "plans/effect-rpc.md",
|
||||
contents: "# Plan\n",
|
||||
});
|
||||
const saved = yield* fileSystem
|
||||
.readFileString(path.join(cwd, "plans/effect-rpc.md"))
|
||||
.pipe(Effect.orDie);
|
||||
|
||||
expect(result).toEqual({ relativePath: "plans/effect-rpc.md" });
|
||||
expect(saved).toBe("# Plan\n");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("invalidates workspace entry search cache after writes", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspaceEntries = yield* WorkspaceEntries;
|
||||
const workspaceFileSystem = yield* WorkspaceFileSystem;
|
||||
const cwd = yield* makeTempDir;
|
||||
yield* writeTextFile(cwd, "src/existing.ts", "export {};\n");
|
||||
|
||||
const beforeWrite = yield* workspaceEntries.search({
|
||||
cwd,
|
||||
query: "rpc",
|
||||
limit: 10,
|
||||
});
|
||||
expect(beforeWrite).toEqual({
|
||||
entries: [],
|
||||
truncated: false,
|
||||
});
|
||||
|
||||
yield* workspaceFileSystem.writeFile({
|
||||
cwd,
|
||||
relativePath: "plans/effect-rpc.md",
|
||||
contents: "# Plan\n",
|
||||
});
|
||||
|
||||
const afterWrite = yield* workspaceEntries.search({
|
||||
cwd,
|
||||
query: "rpc",
|
||||
limit: 10,
|
||||
});
|
||||
expect(afterWrite.entries).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ path: "plans/effect-rpc.md" })]),
|
||||
);
|
||||
expect(afterWrite.truncated).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects writes outside the workspace root", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspaceFileSystem = yield* WorkspaceFileSystem;
|
||||
const cwd = yield* makeTempDir;
|
||||
const path = yield* Path.Path;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
const error = yield* workspaceFileSystem
|
||||
.writeFile({
|
||||
cwd,
|
||||
relativePath: "../escape.md",
|
||||
contents: "# nope\n",
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error.message).toContain(
|
||||
"Workspace file path must be relative to the project root: ../escape.md",
|
||||
);
|
||||
|
||||
const escapedPath = path.resolve(cwd, "..", "escape.md");
|
||||
const escapedStat = yield* fileSystem
|
||||
.stat(escapedPath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
expect(escapedStat).toBeNull();
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,55 +0,0 @@
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
|
||||
import {
|
||||
WorkspaceFileSystem,
|
||||
WorkspaceFileSystemError,
|
||||
type WorkspaceFileSystemShape,
|
||||
} from "../Services/WorkspaceFileSystem.ts";
|
||||
import { WorkspaceEntries } from "../Services/WorkspaceEntries.ts";
|
||||
import { WorkspacePaths } from "../Services/WorkspacePaths.ts";
|
||||
|
||||
export const makeWorkspaceFileSystem = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const workspacePaths = yield* WorkspacePaths;
|
||||
const workspaceEntries = yield* WorkspaceEntries;
|
||||
|
||||
const writeFile: WorkspaceFileSystemShape["writeFile"] = Effect.fn(
|
||||
"WorkspaceFileSystem.writeFile",
|
||||
)(function* (input) {
|
||||
const target = yield* workspacePaths.resolveRelativePathWithinRoot({
|
||||
workspaceRoot: input.cwd,
|
||||
relativePath: input.relativePath,
|
||||
});
|
||||
|
||||
yield* fileSystem.makeDirectory(path.dirname(target.absolutePath), { recursive: true }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new WorkspaceFileSystemError({
|
||||
cwd: input.cwd,
|
||||
relativePath: input.relativePath,
|
||||
operation: "workspaceFileSystem.makeDirectory",
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* fileSystem.writeFileString(target.absolutePath, input.contents).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new WorkspaceFileSystemError({
|
||||
cwd: input.cwd,
|
||||
relativePath: input.relativePath,
|
||||
operation: "workspaceFileSystem.writeFile",
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* workspaceEntries.invalidate(input.cwd);
|
||||
return { relativePath: target.relativePath };
|
||||
});
|
||||
return { writeFile } satisfies WorkspaceFileSystemShape;
|
||||
});
|
||||
|
||||
export const WorkspaceFileSystemLive = Layer.effect(WorkspaceFileSystem, makeWorkspaceFileSystem);
|
||||
@@ -1,113 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it, describe, expect } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
|
||||
import { WorkspacePaths } from "../Services/WorkspacePaths.ts";
|
||||
import { WorkspacePathsLive } from "./WorkspacePaths.ts";
|
||||
|
||||
const TestLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(WorkspacePathsLive),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const makeTempDir = Effect.fn("makeTempDir")(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
return yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3code-project-paths-",
|
||||
});
|
||||
});
|
||||
|
||||
const writeTextFile = Effect.fn("writeTextFile")(function* (
|
||||
cwd: string,
|
||||
relativePath: string,
|
||||
contents = "",
|
||||
) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const absolutePath = path.join(cwd, relativePath);
|
||||
yield* fileSystem
|
||||
.makeDirectory(path.dirname(absolutePath), { recursive: true })
|
||||
.pipe(Effect.orDie);
|
||||
yield* fileSystem.writeFileString(absolutePath, contents).pipe(Effect.orDie);
|
||||
});
|
||||
|
||||
it.layer(TestLayer)("WorkspacePathsLive", (it) => {
|
||||
describe("normalizeWorkspaceRoot", () => {
|
||||
it.effect("resolves an existing directory", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspacePaths = yield* WorkspacePaths;
|
||||
const cwd = yield* makeTempDir();
|
||||
|
||||
const resolved = yield* workspacePaths.normalizeWorkspaceRoot(cwd);
|
||||
|
||||
expect(resolved).toBe(cwd);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects missing directories", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspacePaths = yield* WorkspacePaths;
|
||||
const cwd = yield* makeTempDir();
|
||||
const path = yield* Path.Path;
|
||||
|
||||
const error = yield* workspacePaths
|
||||
.normalizeWorkspaceRoot(path.join(cwd, "missing"))
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error.message).toContain("Workspace root does not exist:");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects file paths", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspacePaths = yield* WorkspacePaths;
|
||||
const cwd = yield* makeTempDir();
|
||||
const path = yield* Path.Path;
|
||||
const filePath = path.join(cwd, "README.md");
|
||||
yield* writeTextFile(cwd, "README.md", "# hi\n");
|
||||
|
||||
const error = yield* workspacePaths.normalizeWorkspaceRoot(filePath).pipe(Effect.flip);
|
||||
|
||||
expect(error.message).toContain("Workspace root is not a directory:");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("resolveRelativePathWithinRoot", () => {
|
||||
it.effect("resolves relative paths inside the workspace root", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspacePaths = yield* WorkspacePaths;
|
||||
const cwd = yield* makeTempDir();
|
||||
const path = yield* Path.Path;
|
||||
|
||||
const resolved = yield* workspacePaths.resolveRelativePathWithinRoot({
|
||||
workspaceRoot: cwd,
|
||||
relativePath: "plans/effect-rpc.md",
|
||||
});
|
||||
|
||||
expect(resolved).toEqual({
|
||||
absolutePath: path.join(cwd, "plans/effect-rpc.md"),
|
||||
relativePath: "plans/effect-rpc.md",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects paths that escape the workspace root", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspacePaths = yield* WorkspacePaths;
|
||||
const cwd = yield* makeTempDir();
|
||||
|
||||
const error = yield* workspacePaths
|
||||
.resolveRelativePathWithinRoot({
|
||||
workspaceRoot: cwd,
|
||||
relativePath: "../escape.md",
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error.message).toContain(
|
||||
"Workspace file path must be relative to the project root: ../escape.md",
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,89 +0,0 @@
|
||||
import * as OS from "node:os";
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
|
||||
import {
|
||||
WorkspacePaths,
|
||||
WorkspacePathOutsideRootError,
|
||||
WorkspaceRootNotDirectoryError,
|
||||
WorkspaceRootNotExistsError,
|
||||
type WorkspacePathsShape,
|
||||
} from "../Services/WorkspacePaths.ts";
|
||||
|
||||
function toPosixRelativePath(input: string): string {
|
||||
return input.replaceAll("\\", "/");
|
||||
}
|
||||
|
||||
function expandHomePath(input: string, path: Path.Path): string {
|
||||
if (input === "~") {
|
||||
return OS.homedir();
|
||||
}
|
||||
if (input.startsWith("~/") || input.startsWith("~\\")) {
|
||||
return path.join(OS.homedir(), input.slice(2));
|
||||
}
|
||||
return input;
|
||||
}
|
||||
|
||||
export const makeWorkspacePaths = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
const normalizeWorkspaceRoot: WorkspacePathsShape["normalizeWorkspaceRoot"] = Effect.fn(
|
||||
"WorkspacePaths.normalizeWorkspaceRoot",
|
||||
)(function* (workspaceRoot) {
|
||||
const normalizedWorkspaceRoot = path.resolve(expandHomePath(workspaceRoot.trim(), path));
|
||||
const workspaceStat = yield* fileSystem
|
||||
.stat(normalizedWorkspaceRoot)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!workspaceStat) {
|
||||
return yield* new WorkspaceRootNotExistsError({
|
||||
workspaceRoot,
|
||||
normalizedWorkspaceRoot,
|
||||
});
|
||||
}
|
||||
if (workspaceStat.type !== "Directory") {
|
||||
return yield* new WorkspaceRootNotDirectoryError({
|
||||
workspaceRoot,
|
||||
normalizedWorkspaceRoot,
|
||||
});
|
||||
}
|
||||
return normalizedWorkspaceRoot;
|
||||
});
|
||||
|
||||
const resolveRelativePathWithinRoot: WorkspacePathsShape["resolveRelativePathWithinRoot"] =
|
||||
Effect.fn("WorkspacePaths.resolveRelativePathWithinRoot")(function* (input) {
|
||||
const normalizedInputPath = input.relativePath.trim();
|
||||
if (path.isAbsolute(normalizedInputPath)) {
|
||||
return yield* new WorkspacePathOutsideRootError({
|
||||
workspaceRoot: input.workspaceRoot,
|
||||
relativePath: input.relativePath,
|
||||
});
|
||||
}
|
||||
|
||||
const absolutePath = path.resolve(input.workspaceRoot, normalizedInputPath);
|
||||
const relativeToRoot = toPosixRelativePath(path.relative(input.workspaceRoot, absolutePath));
|
||||
if (
|
||||
relativeToRoot.length === 0 ||
|
||||
relativeToRoot === "." ||
|
||||
relativeToRoot.startsWith("../") ||
|
||||
relativeToRoot === ".." ||
|
||||
path.isAbsolute(relativeToRoot)
|
||||
) {
|
||||
return yield* new WorkspacePathOutsideRootError({
|
||||
workspaceRoot: input.workspaceRoot,
|
||||
relativePath: input.relativePath,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
absolutePath,
|
||||
relativePath: relativeToRoot,
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
normalizeWorkspaceRoot,
|
||||
resolveRelativePathWithinRoot,
|
||||
} satisfies WorkspacePathsShape;
|
||||
});
|
||||
|
||||
export const WorkspacePathsLive = Layer.effect(WorkspacePaths, makeWorkspacePaths);
|
||||
@@ -1,48 +0,0 @@
|
||||
/**
|
||||
* WorkspaceEntries - Effect service contract for cached workspace entry search.
|
||||
*
|
||||
* Owns indexed workspace entry search plus cache invalidation for workspace
|
||||
* roots when the underlying filesystem changes.
|
||||
*
|
||||
* @module WorkspaceEntries
|
||||
*/
|
||||
import { Schema, ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { ProjectSearchEntriesInput, ProjectSearchEntriesResult } from "@t3tools/contracts";
|
||||
|
||||
export class WorkspaceEntriesError extends Schema.TaggedErrorClass<WorkspaceEntriesError>()(
|
||||
"WorkspaceEntriesError",
|
||||
{
|
||||
cwd: Schema.String,
|
||||
operation: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {}
|
||||
|
||||
/**
|
||||
* WorkspaceEntriesShape - Service API for workspace entry search and cache
|
||||
* invalidation.
|
||||
*/
|
||||
export interface WorkspaceEntriesShape {
|
||||
/**
|
||||
* Search indexed workspace entries for files and directories matching the
|
||||
* provided query.
|
||||
*/
|
||||
readonly search: (
|
||||
input: ProjectSearchEntriesInput,
|
||||
) => Effect.Effect<ProjectSearchEntriesResult, WorkspaceEntriesError>;
|
||||
|
||||
/**
|
||||
* Drop any cached workspace entries for the given workspace root.
|
||||
*/
|
||||
readonly invalidate: (cwd: string) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* WorkspaceEntries - Service tag for cached workspace entry search.
|
||||
*/
|
||||
export class WorkspaceEntries extends ServiceMap.Service<WorkspaceEntries, WorkspaceEntriesShape>()(
|
||||
"t3/workspace/Services/WorkspaceEntries",
|
||||
) {}
|
||||
@@ -1,50 +0,0 @@
|
||||
/**
|
||||
* WorkspaceFileSystem - Effect service contract for workspace file mutations.
|
||||
*
|
||||
* Owns workspace-root-relative file write operations and their associated
|
||||
* safety checks and cache invalidation hooks.
|
||||
*
|
||||
* @module WorkspaceFileSystem
|
||||
*/
|
||||
import { Schema, ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { ProjectWriteFileInput, ProjectWriteFileResult } from "@t3tools/contracts";
|
||||
import { WorkspacePathOutsideRootError } from "./WorkspacePaths.ts";
|
||||
|
||||
export class WorkspaceFileSystemError extends Schema.TaggedErrorClass<WorkspaceFileSystemError>()(
|
||||
"WorkspaceFileSystemError",
|
||||
{
|
||||
cwd: Schema.String,
|
||||
relativePath: Schema.optional(Schema.String),
|
||||
operation: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {}
|
||||
|
||||
/**
|
||||
* WorkspaceFileSystemShape - Service API for workspace-relative file operations.
|
||||
*/
|
||||
export interface WorkspaceFileSystemShape {
|
||||
/**
|
||||
* Write a file relative to the workspace root.
|
||||
*
|
||||
* Creates parent directories as needed and rejects paths that escape the
|
||||
* workspace root.
|
||||
*/
|
||||
readonly writeFile: (
|
||||
input: ProjectWriteFileInput,
|
||||
) => Effect.Effect<
|
||||
ProjectWriteFileResult,
|
||||
WorkspaceFileSystemError | WorkspacePathOutsideRootError
|
||||
>;
|
||||
}
|
||||
|
||||
/**
|
||||
* WorkspaceFileSystem - Service tag for workspace file operations.
|
||||
*/
|
||||
export class WorkspaceFileSystem extends ServiceMap.Service<
|
||||
WorkspaceFileSystem,
|
||||
WorkspaceFileSystemShape
|
||||
>()("t3/workspace/Services/WorkspaceFileSystem") {}
|
||||
@@ -1,85 +0,0 @@
|
||||
/**
|
||||
* WorkspacePaths - Effect service contract for workspace path handling.
|
||||
*
|
||||
* Owns normalization and validation of workspace roots plus safe resolution of
|
||||
* workspace-root-relative paths.
|
||||
*
|
||||
* @module WorkspacePaths
|
||||
*/
|
||||
import { Schema, ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
export class WorkspaceRootNotExistsError extends Schema.TaggedErrorClass<WorkspaceRootNotExistsError>()(
|
||||
"WorkspaceRootNotExistsError",
|
||||
{
|
||||
workspaceRoot: Schema.String,
|
||||
normalizedWorkspaceRoot: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Workspace root does not exist: ${this.normalizedWorkspaceRoot}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class WorkspaceRootNotDirectoryError extends Schema.TaggedErrorClass<WorkspaceRootNotDirectoryError>()(
|
||||
"WorkspaceRootNotDirectoryError",
|
||||
{
|
||||
workspaceRoot: Schema.String,
|
||||
normalizedWorkspaceRoot: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Workspace root is not a directory: ${this.normalizedWorkspaceRoot}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class WorkspacePathOutsideRootError extends Schema.TaggedErrorClass<WorkspacePathOutsideRootError>()(
|
||||
"WorkspacePathOutsideRootError",
|
||||
{
|
||||
workspaceRoot: Schema.String,
|
||||
relativePath: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Workspace file path must be relative to the project root: ${this.relativePath}`;
|
||||
}
|
||||
}
|
||||
|
||||
export const WorkspacePathsError = Schema.Union([
|
||||
WorkspaceRootNotExistsError,
|
||||
WorkspaceRootNotDirectoryError,
|
||||
WorkspacePathOutsideRootError,
|
||||
]);
|
||||
export type WorkspacePathsError = typeof WorkspacePathsError.Type;
|
||||
|
||||
/**
|
||||
* WorkspacePathsShape - Service API for workspace path normalization and guards.
|
||||
*/
|
||||
export interface WorkspacePathsShape {
|
||||
/**
|
||||
* Normalize a user-provided workspace root and verify it exists as a directory.
|
||||
*/
|
||||
readonly normalizeWorkspaceRoot: (
|
||||
workspaceRoot: string,
|
||||
) => Effect.Effect<string, WorkspaceRootNotExistsError | WorkspaceRootNotDirectoryError>;
|
||||
|
||||
/**
|
||||
* Resolve a relative path within a validated workspace root.
|
||||
*
|
||||
* Rejects absolute paths and traversal attempts outside the workspace root.
|
||||
*/
|
||||
readonly resolveRelativePathWithinRoot: (input: {
|
||||
workspaceRoot: string;
|
||||
relativePath: string;
|
||||
}) => Effect.Effect<
|
||||
{ absolutePath: string; relativePath: string },
|
||||
WorkspacePathOutsideRootError
|
||||
>;
|
||||
}
|
||||
|
||||
/**
|
||||
* WorkspacePaths - Service tag for workspace path normalization and resolution.
|
||||
*/
|
||||
export class WorkspacePaths extends ServiceMap.Service<WorkspacePaths, WorkspacePathsShape>()(
|
||||
"t3/workspace/Services/WorkspacePaths",
|
||||
) {}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { assert, beforeEach, describe, it, vi } from "vitest";
|
||||
import type { ProcessRunOptions, ProcessRunResult } from "./processRunner";
|
||||
|
||||
const { runProcessMock } = vi.hoisted(() => ({
|
||||
runProcessMock:
|
||||
vi.fn<
|
||||
(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options?: ProcessRunOptions,
|
||||
) => Promise<ProcessRunResult>
|
||||
>(),
|
||||
}));
|
||||
|
||||
vi.mock("./processRunner", () => ({
|
||||
runProcess: runProcessMock,
|
||||
}));
|
||||
|
||||
function processResult(
|
||||
overrides: Partial<ProcessRunResult> & Pick<ProcessRunResult, "stdout" | "code">,
|
||||
): ProcessRunResult {
|
||||
return {
|
||||
stdout: overrides.stdout,
|
||||
code: overrides.code,
|
||||
stderr: overrides.stderr ?? "",
|
||||
signal: overrides.signal ?? null,
|
||||
timedOut: overrides.timedOut ?? false,
|
||||
stdoutTruncated: overrides.stdoutTruncated ?? false,
|
||||
stderrTruncated: overrides.stderrTruncated ?? false,
|
||||
};
|
||||
}
|
||||
|
||||
describe("searchWorkspaceEntries git-ignore chunking", () => {
|
||||
beforeEach(() => {
|
||||
runProcessMock.mockReset();
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
it("chunks git check-ignore stdin to avoid building giant strings", async () => {
|
||||
const ignoredPaths = Array.from(
|
||||
{ length: 5000 },
|
||||
(_, index) => `ignored/${index.toString().padStart(5, "0")}/${"x".repeat(80)}.ts`,
|
||||
);
|
||||
const keptPaths = ["src/keep.ts", "docs/readme.md"];
|
||||
const listedPaths = [...ignoredPaths, ...keptPaths];
|
||||
let checkIgnoreCalls = 0;
|
||||
|
||||
runProcessMock.mockImplementation(async (_command, args, options) => {
|
||||
if (args[0] === "rev-parse") {
|
||||
return processResult({ code: 0, stdout: "true\n" });
|
||||
}
|
||||
|
||||
if (args[0] === "ls-files") {
|
||||
return processResult({ code: 0, stdout: `${listedPaths.join("\0")}\0` });
|
||||
}
|
||||
|
||||
if (args[0] === "check-ignore") {
|
||||
checkIgnoreCalls += 1;
|
||||
const chunkPaths = (options?.stdin ?? "").split("\0").filter((value) => value.length > 0);
|
||||
const chunkIgnored = chunkPaths.filter((value) => value.startsWith("ignored/"));
|
||||
return processResult({
|
||||
code: chunkIgnored.length > 0 ? 0 : 1,
|
||||
stdout: chunkIgnored.length > 0 ? `${chunkIgnored.join("\0")}\0` : "",
|
||||
});
|
||||
}
|
||||
|
||||
throw new Error(`Unexpected command: git ${args.join(" ")}`);
|
||||
});
|
||||
|
||||
const { searchWorkspaceEntries } = await import("./workspaceEntries");
|
||||
const result = await searchWorkspaceEntries({
|
||||
cwd: "/virtual/workspace",
|
||||
query: "",
|
||||
limit: 100,
|
||||
});
|
||||
|
||||
assert.isAbove(checkIgnoreCalls, 1);
|
||||
assert.isFalse(result.entries.some((entry) => entry.path.startsWith("ignored/")));
|
||||
assert.isTrue(result.entries.some((entry) => entry.path === "src/keep.ts"));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,202 @@
|
||||
import fs from "node:fs";
|
||||
import fsPromises from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
|
||||
import { afterEach, assert, describe, it, vi } from "vitest";
|
||||
|
||||
import { searchWorkspaceEntries } from "./workspaceEntries";
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
function makeTempDir(prefix: string): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
||||
tempDirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
function writeFile(cwd: string, relativePath: string, contents = ""): void {
|
||||
const absolutePath = path.join(cwd, relativePath);
|
||||
fs.mkdirSync(path.dirname(absolutePath), { recursive: true });
|
||||
fs.writeFileSync(absolutePath, contents, "utf8");
|
||||
}
|
||||
|
||||
function runGit(cwd: string, args: string[]): void {
|
||||
const result = spawnSync("git", args, { cwd, encoding: "utf8" });
|
||||
if (result.status !== 0) {
|
||||
throw new Error(result.stderr || `git ${args.join(" ")} failed`);
|
||||
}
|
||||
}
|
||||
|
||||
describe("searchWorkspaceEntries", () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
for (const dir of tempDirs.splice(0, tempDirs.length)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("returns files and directories relative to cwd", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-entries-");
|
||||
writeFile(cwd, "src/components/Composer.tsx");
|
||||
writeFile(cwd, "src/index.ts");
|
||||
writeFile(cwd, "README.md");
|
||||
writeFile(cwd, ".git/HEAD");
|
||||
writeFile(cwd, "node_modules/pkg/index.js");
|
||||
|
||||
const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 });
|
||||
const paths = result.entries.map((entry) => entry.path);
|
||||
|
||||
assert.include(paths, "src");
|
||||
assert.include(paths, "src/components");
|
||||
assert.include(paths, "src/components/Composer.tsx");
|
||||
assert.include(paths, "README.md");
|
||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".git")));
|
||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith("node_modules")));
|
||||
assert.isFalse(result.truncated);
|
||||
});
|
||||
|
||||
it("filters and ranks entries by query", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-query-");
|
||||
writeFile(cwd, "src/components/Composer.tsx");
|
||||
writeFile(cwd, "src/components/composePrompt.ts");
|
||||
writeFile(cwd, "docs/composition.md");
|
||||
|
||||
const result = await searchWorkspaceEntries({ cwd, query: "compo", limit: 5 });
|
||||
|
||||
assert.isAbove(result.entries.length, 0);
|
||||
assert.isTrue(result.entries.some((entry) => entry.path === "src/components"));
|
||||
assert.isTrue(result.entries.every((entry) => entry.path.toLowerCase().includes("compo")));
|
||||
});
|
||||
|
||||
it("supports fuzzy subsequence queries for composer path search", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-fuzzy-query-");
|
||||
writeFile(cwd, "src/components/Composer.tsx");
|
||||
writeFile(cwd, "src/components/composePrompt.ts");
|
||||
writeFile(cwd, "docs/composition.md");
|
||||
|
||||
const result = await searchWorkspaceEntries({ cwd, query: "cmp", limit: 10 });
|
||||
const paths = result.entries.map((entry) => entry.path);
|
||||
|
||||
assert.isAbove(result.entries.length, 0);
|
||||
assert.include(paths, "src/components");
|
||||
assert.include(paths, "src/components/Composer.tsx");
|
||||
});
|
||||
|
||||
it("tracks truncation without sorting every fuzzy match", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-fuzzy-limit-");
|
||||
writeFile(cwd, "src/components/Composer.tsx");
|
||||
writeFile(cwd, "src/components/composePrompt.ts");
|
||||
writeFile(cwd, "docs/composition.md");
|
||||
|
||||
const result = await searchWorkspaceEntries({ cwd, query: "cmp", limit: 1 });
|
||||
|
||||
assert.lengthOf(result.entries, 1);
|
||||
assert.isTrue(result.truncated);
|
||||
});
|
||||
|
||||
it("excludes gitignored paths for git repositories", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-gitignore-");
|
||||
runGit(cwd, ["init"]);
|
||||
writeFile(cwd, ".gitignore", ".convex/\nconvex/\nignored.txt\n");
|
||||
writeFile(cwd, "src/keep.ts", "export {};");
|
||||
writeFile(cwd, "ignored.txt", "ignore me");
|
||||
writeFile(cwd, ".convex/local-storage/data.json", "{}");
|
||||
writeFile(cwd, "convex/UOoS-l/convex_local_storage/modules/data.json", "{}");
|
||||
|
||||
const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 });
|
||||
const paths = result.entries.map((entry) => entry.path);
|
||||
|
||||
assert.include(paths, "src");
|
||||
assert.include(paths, "src/keep.ts");
|
||||
assert.notInclude(paths, "ignored.txt");
|
||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".convex/")));
|
||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith("convex/")));
|
||||
});
|
||||
|
||||
it("excludes tracked paths that match ignore rules", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-tracked-gitignore-");
|
||||
runGit(cwd, ["init"]);
|
||||
writeFile(cwd, ".convex/local-storage/data.json", "{}");
|
||||
writeFile(cwd, "src/keep.ts", "export {};");
|
||||
runGit(cwd, ["add", ".convex/local-storage/data.json", "src/keep.ts"]);
|
||||
writeFile(cwd, ".gitignore", ".convex/\n");
|
||||
|
||||
const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 });
|
||||
const paths = result.entries.map((entry) => entry.path);
|
||||
|
||||
assert.include(paths, "src");
|
||||
assert.include(paths, "src/keep.ts");
|
||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".convex/")));
|
||||
});
|
||||
|
||||
it("excludes .convex in non-git workspaces", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-non-git-convex-");
|
||||
writeFile(cwd, ".convex/local-storage/data.json", "{}");
|
||||
writeFile(cwd, "src/keep.ts", "export {};");
|
||||
|
||||
const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 });
|
||||
const paths = result.entries.map((entry) => entry.path);
|
||||
|
||||
assert.include(paths, "src");
|
||||
assert.include(paths, "src/keep.ts");
|
||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".convex/")));
|
||||
});
|
||||
|
||||
it("deduplicates concurrent index builds for the same cwd", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-concurrent-build-");
|
||||
writeFile(cwd, "src/components/Composer.tsx");
|
||||
|
||||
let rootReadCount = 0;
|
||||
const originalReaddir = fsPromises.readdir.bind(fsPromises);
|
||||
vi.spyOn(fsPromises, "readdir").mockImplementation((async (
|
||||
...args: Parameters<typeof fsPromises.readdir>
|
||||
) => {
|
||||
if (args[0] === cwd) {
|
||||
rootReadCount += 1;
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
}
|
||||
return originalReaddir(...args);
|
||||
}) as typeof fsPromises.readdir);
|
||||
|
||||
await Promise.all([
|
||||
searchWorkspaceEntries({ cwd, query: "", limit: 100 }),
|
||||
searchWorkspaceEntries({ cwd, query: "comp", limit: 100 }),
|
||||
searchWorkspaceEntries({ cwd, query: "src", limit: 100 }),
|
||||
]);
|
||||
|
||||
assert.equal(rootReadCount, 1);
|
||||
});
|
||||
|
||||
it("limits concurrent directory reads while walking the filesystem", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-read-concurrency-");
|
||||
for (let index = 0; index < 80; index += 1) {
|
||||
writeFile(cwd, `group-${index}/entry-${index}.ts`, "export {};");
|
||||
}
|
||||
|
||||
let activeReads = 0;
|
||||
let peakReads = 0;
|
||||
const originalReaddir = fsPromises.readdir.bind(fsPromises);
|
||||
vi.spyOn(fsPromises, "readdir").mockImplementation((async (
|
||||
...args: Parameters<typeof fsPromises.readdir>
|
||||
) => {
|
||||
const target = args[0];
|
||||
if (typeof target === "string" && target.startsWith(cwd)) {
|
||||
activeReads += 1;
|
||||
peakReads = Math.max(peakReads, activeReads);
|
||||
await new Promise((resolve) => setTimeout(resolve, 4));
|
||||
try {
|
||||
return await originalReaddir(...args);
|
||||
} finally {
|
||||
activeReads -= 1;
|
||||
}
|
||||
}
|
||||
return originalReaddir(...args);
|
||||
}) as typeof fsPromises.readdir);
|
||||
|
||||
await searchWorkspaceEntries({ cwd, query: "", limit: 200 });
|
||||
|
||||
assert.isAtMost(peakReads, 32);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,565 @@
|
||||
import fs from "node:fs/promises";
|
||||
import type { Dirent } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { runProcess } from "./processRunner";
|
||||
|
||||
import {
|
||||
ProjectEntry,
|
||||
ProjectSearchEntriesInput,
|
||||
ProjectSearchEntriesResult,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
const WORKSPACE_CACHE_TTL_MS = 15_000;
|
||||
const WORKSPACE_CACHE_MAX_KEYS = 4;
|
||||
const WORKSPACE_INDEX_MAX_ENTRIES = 25_000;
|
||||
const WORKSPACE_SCAN_READDIR_CONCURRENCY = 32;
|
||||
const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
|
||||
const IGNORED_DIRECTORY_NAMES = new Set([
|
||||
".git",
|
||||
".convex",
|
||||
"node_modules",
|
||||
".next",
|
||||
".turbo",
|
||||
"dist",
|
||||
"build",
|
||||
"out",
|
||||
".cache",
|
||||
]);
|
||||
|
||||
interface WorkspaceIndex {
|
||||
scannedAt: number;
|
||||
entries: SearchableWorkspaceEntry[];
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
interface SearchableWorkspaceEntry extends ProjectEntry {
|
||||
normalizedPath: string;
|
||||
normalizedName: string;
|
||||
}
|
||||
|
||||
interface RankedWorkspaceEntry {
|
||||
entry: SearchableWorkspaceEntry;
|
||||
score: number;
|
||||
}
|
||||
|
||||
const workspaceIndexCache = new Map<string, WorkspaceIndex>();
|
||||
const inFlightWorkspaceIndexBuilds = new Map<string, Promise<WorkspaceIndex>>();
|
||||
|
||||
function toPosixPath(input: string): string {
|
||||
return input.split(path.sep).join("/");
|
||||
}
|
||||
|
||||
function parentPathOf(input: string): string | undefined {
|
||||
const separatorIndex = input.lastIndexOf("/");
|
||||
if (separatorIndex === -1) {
|
||||
return undefined;
|
||||
}
|
||||
return input.slice(0, separatorIndex);
|
||||
}
|
||||
|
||||
function basenameOf(input: string): string {
|
||||
const separatorIndex = input.lastIndexOf("/");
|
||||
if (separatorIndex === -1) {
|
||||
return input;
|
||||
}
|
||||
return input.slice(separatorIndex + 1);
|
||||
}
|
||||
|
||||
function toSearchableWorkspaceEntry(entry: ProjectEntry): SearchableWorkspaceEntry {
|
||||
const normalizedPath = entry.path.toLowerCase();
|
||||
return {
|
||||
...entry,
|
||||
normalizedPath,
|
||||
normalizedName: basenameOf(normalizedPath),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeQuery(input: string): string {
|
||||
return input
|
||||
.trim()
|
||||
.replace(/^[@./]+/, "")
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function scoreSubsequenceMatch(value: string, query: string): number | null {
|
||||
if (!query) return 0;
|
||||
|
||||
let queryIndex = 0;
|
||||
let firstMatchIndex = -1;
|
||||
let previousMatchIndex = -1;
|
||||
let gapPenalty = 0;
|
||||
|
||||
for (let valueIndex = 0; valueIndex < value.length; valueIndex += 1) {
|
||||
if (value[valueIndex] !== query[queryIndex]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (firstMatchIndex === -1) {
|
||||
firstMatchIndex = valueIndex;
|
||||
}
|
||||
if (previousMatchIndex !== -1) {
|
||||
gapPenalty += valueIndex - previousMatchIndex - 1;
|
||||
}
|
||||
|
||||
previousMatchIndex = valueIndex;
|
||||
queryIndex += 1;
|
||||
if (queryIndex === query.length) {
|
||||
const spanPenalty = valueIndex - firstMatchIndex + 1 - query.length;
|
||||
const lengthPenalty = Math.min(64, value.length - query.length);
|
||||
return firstMatchIndex * 2 + gapPenalty * 3 + spanPenalty + lengthPenalty;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function scoreEntry(entry: SearchableWorkspaceEntry, query: string): number | null {
|
||||
if (!query) {
|
||||
return entry.kind === "directory" ? 0 : 1;
|
||||
}
|
||||
|
||||
const { normalizedPath, normalizedName } = entry;
|
||||
|
||||
if (normalizedName === query) return 0;
|
||||
if (normalizedPath === query) return 1;
|
||||
if (normalizedName.startsWith(query)) return 2;
|
||||
if (normalizedPath.startsWith(query)) return 3;
|
||||
if (normalizedPath.includes(`/${query}`)) return 4;
|
||||
if (normalizedName.includes(query)) return 5;
|
||||
if (normalizedPath.includes(query)) return 6;
|
||||
|
||||
const nameFuzzyScore = scoreSubsequenceMatch(normalizedName, query);
|
||||
if (nameFuzzyScore !== null) {
|
||||
return 100 + nameFuzzyScore;
|
||||
}
|
||||
|
||||
const pathFuzzyScore = scoreSubsequenceMatch(normalizedPath, query);
|
||||
if (pathFuzzyScore !== null) {
|
||||
return 200 + pathFuzzyScore;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function compareRankedWorkspaceEntries(
|
||||
left: RankedWorkspaceEntry,
|
||||
right: RankedWorkspaceEntry,
|
||||
): number {
|
||||
const scoreDelta = left.score - right.score;
|
||||
if (scoreDelta !== 0) return scoreDelta;
|
||||
return left.entry.path.localeCompare(right.entry.path);
|
||||
}
|
||||
|
||||
function findInsertionIndex(
|
||||
rankedEntries: RankedWorkspaceEntry[],
|
||||
candidate: RankedWorkspaceEntry,
|
||||
): number {
|
||||
let low = 0;
|
||||
let high = rankedEntries.length;
|
||||
|
||||
while (low < high) {
|
||||
const middle = low + Math.floor((high - low) / 2);
|
||||
const current = rankedEntries[middle];
|
||||
if (!current) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (compareRankedWorkspaceEntries(candidate, current) < 0) {
|
||||
high = middle;
|
||||
} else {
|
||||
low = middle + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return low;
|
||||
}
|
||||
|
||||
function insertRankedEntry(
|
||||
rankedEntries: RankedWorkspaceEntry[],
|
||||
candidate: RankedWorkspaceEntry,
|
||||
limit: number,
|
||||
): void {
|
||||
if (limit <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const insertionIndex = findInsertionIndex(rankedEntries, candidate);
|
||||
if (rankedEntries.length < limit) {
|
||||
rankedEntries.splice(insertionIndex, 0, candidate);
|
||||
return;
|
||||
}
|
||||
|
||||
if (insertionIndex >= limit) {
|
||||
return;
|
||||
}
|
||||
|
||||
rankedEntries.splice(insertionIndex, 0, candidate);
|
||||
rankedEntries.pop();
|
||||
}
|
||||
|
||||
function isPathInIgnoredDirectory(relativePath: string): boolean {
|
||||
const firstSegment = relativePath.split("/")[0];
|
||||
if (!firstSegment) return false;
|
||||
return IGNORED_DIRECTORY_NAMES.has(firstSegment);
|
||||
}
|
||||
|
||||
function splitNullSeparatedPaths(input: string, truncated: boolean): string[] {
|
||||
const parts = input.split("\0");
|
||||
if (parts.length === 0) return [];
|
||||
|
||||
// If output was truncated, the final token can be partial.
|
||||
if (truncated && parts[parts.length - 1]?.length) {
|
||||
parts.pop();
|
||||
}
|
||||
|
||||
return parts.filter((value) => value.length > 0);
|
||||
}
|
||||
|
||||
function directoryAncestorsOf(relativePath: string): string[] {
|
||||
const segments = relativePath.split("/").filter((segment) => segment.length > 0);
|
||||
if (segments.length <= 1) return [];
|
||||
const directories: string[] = [];
|
||||
for (let index = 1; index < segments.length; index += 1) {
|
||||
directories.push(segments.slice(0, index).join("/"));
|
||||
}
|
||||
return directories;
|
||||
}
|
||||
|
||||
async function mapWithConcurrency<TInput, TOutput>(
|
||||
items: readonly TInput[],
|
||||
concurrency: number,
|
||||
mapper: (item: TInput, index: number) => Promise<TOutput>,
|
||||
): Promise<TOutput[]> {
|
||||
if (items.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const boundedConcurrency = Math.max(1, Math.min(concurrency, items.length));
|
||||
const results = Array.from({ length: items.length }) as TOutput[];
|
||||
let nextIndex = 0;
|
||||
|
||||
const workers = Array.from({ length: boundedConcurrency }, async () => {
|
||||
while (nextIndex < items.length) {
|
||||
const currentIndex = nextIndex;
|
||||
nextIndex += 1;
|
||||
results[currentIndex] = await mapper(items[currentIndex] as TInput, currentIndex);
|
||||
}
|
||||
});
|
||||
|
||||
await Promise.all(workers);
|
||||
return results;
|
||||
}
|
||||
|
||||
async function isInsideGitWorkTree(cwd: string): Promise<boolean> {
|
||||
const insideWorkTree = await runProcess("git", ["rev-parse", "--is-inside-work-tree"], {
|
||||
cwd,
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 5_000,
|
||||
maxBufferBytes: 4_096,
|
||||
}).catch(() => null);
|
||||
return Boolean(
|
||||
insideWorkTree && insideWorkTree.code === 0 && insideWorkTree.stdout.trim() === "true",
|
||||
);
|
||||
}
|
||||
|
||||
async function filterGitIgnoredPaths(cwd: string, relativePaths: string[]): Promise<string[]> {
|
||||
if (relativePaths.length === 0) {
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
const ignoredPaths = new Set<string>();
|
||||
let chunk: string[] = [];
|
||||
let chunkBytes = 0;
|
||||
|
||||
const flushChunk = async (): Promise<boolean> => {
|
||||
if (chunk.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const checkIgnore = await runProcess("git", ["check-ignore", "--no-index", "-z", "--stdin"], {
|
||||
cwd,
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 20_000,
|
||||
maxBufferBytes: 16 * 1024 * 1024,
|
||||
outputMode: "truncate",
|
||||
stdin: `${chunk.join("\0")}\0`,
|
||||
}).catch(() => null);
|
||||
chunk = [];
|
||||
chunkBytes = 0;
|
||||
|
||||
if (!checkIgnore) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// git-check-ignore exits with 1 when no paths match.
|
||||
if (checkIgnore.code !== 0 && checkIgnore.code !== 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const matchedIgnoredPaths = splitNullSeparatedPaths(
|
||||
checkIgnore.stdout,
|
||||
Boolean(checkIgnore.stdoutTruncated),
|
||||
);
|
||||
for (const ignoredPath of matchedIgnoredPaths) {
|
||||
ignoredPaths.add(ignoredPath);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
for (const relativePath of relativePaths) {
|
||||
const relativePathBytes = Buffer.byteLength(relativePath) + 1;
|
||||
if (
|
||||
chunk.length > 0 &&
|
||||
chunkBytes + relativePathBytes > GIT_CHECK_IGNORE_MAX_STDIN_BYTES &&
|
||||
!(await flushChunk())
|
||||
) {
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
chunk.push(relativePath);
|
||||
chunkBytes += relativePathBytes;
|
||||
|
||||
if (chunkBytes >= GIT_CHECK_IGNORE_MAX_STDIN_BYTES && !(await flushChunk())) {
|
||||
return relativePaths;
|
||||
}
|
||||
}
|
||||
|
||||
if (!(await flushChunk())) {
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
if (ignoredPaths.size === 0) {
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath));
|
||||
}
|
||||
|
||||
async function buildWorkspaceIndexFromGit(cwd: string): Promise<WorkspaceIndex | null> {
|
||||
if (!(await isInsideGitWorkTree(cwd))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const listedFiles = await runProcess(
|
||||
"git",
|
||||
["ls-files", "--cached", "--others", "--exclude-standard", "-z"],
|
||||
{
|
||||
cwd,
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 20_000,
|
||||
maxBufferBytes: 16 * 1024 * 1024,
|
||||
outputMode: "truncate",
|
||||
},
|
||||
).catch(() => null);
|
||||
if (!listedFiles || listedFiles.code !== 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const listedPaths = splitNullSeparatedPaths(
|
||||
listedFiles.stdout,
|
||||
Boolean(listedFiles.stdoutTruncated),
|
||||
)
|
||||
.map((entry) => toPosixPath(entry))
|
||||
.filter((entry) => entry.length > 0 && !isPathInIgnoredDirectory(entry));
|
||||
const filePaths = await filterGitIgnoredPaths(cwd, listedPaths);
|
||||
|
||||
const directorySet = new Set<string>();
|
||||
for (const filePath of filePaths) {
|
||||
for (const directoryPath of directoryAncestorsOf(filePath)) {
|
||||
if (!isPathInIgnoredDirectory(directoryPath)) {
|
||||
directorySet.add(directoryPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const directoryEntries = [...directorySet]
|
||||
.toSorted((left, right) => left.localeCompare(right))
|
||||
.map(
|
||||
(directoryPath): ProjectEntry => ({
|
||||
path: directoryPath,
|
||||
kind: "directory",
|
||||
parentPath: parentPathOf(directoryPath),
|
||||
}),
|
||||
)
|
||||
.map(toSearchableWorkspaceEntry);
|
||||
const fileEntries = [...new Set(filePaths)]
|
||||
.toSorted((left, right) => left.localeCompare(right))
|
||||
.map(
|
||||
(filePath): ProjectEntry => ({
|
||||
path: filePath,
|
||||
kind: "file",
|
||||
parentPath: parentPathOf(filePath),
|
||||
}),
|
||||
)
|
||||
.map(toSearchableWorkspaceEntry);
|
||||
|
||||
const entries = [...directoryEntries, ...fileEntries];
|
||||
return {
|
||||
scannedAt: Date.now(),
|
||||
entries: entries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES),
|
||||
truncated: Boolean(listedFiles.stdoutTruncated) || entries.length > WORKSPACE_INDEX_MAX_ENTRIES,
|
||||
};
|
||||
}
|
||||
|
||||
async function buildWorkspaceIndex(cwd: string): Promise<WorkspaceIndex> {
|
||||
const gitIndexed = await buildWorkspaceIndexFromGit(cwd);
|
||||
if (gitIndexed) {
|
||||
return gitIndexed;
|
||||
}
|
||||
const shouldFilterWithGitIgnore = await isInsideGitWorkTree(cwd);
|
||||
|
||||
let pendingDirectories: string[] = [""];
|
||||
const entries: SearchableWorkspaceEntry[] = [];
|
||||
let truncated = false;
|
||||
|
||||
while (pendingDirectories.length > 0 && !truncated) {
|
||||
const currentDirectories = pendingDirectories;
|
||||
pendingDirectories = [];
|
||||
const directoryEntries = await mapWithConcurrency(
|
||||
currentDirectories,
|
||||
WORKSPACE_SCAN_READDIR_CONCURRENCY,
|
||||
async (relativeDir) => {
|
||||
const absoluteDir = relativeDir ? path.join(cwd, relativeDir) : cwd;
|
||||
try {
|
||||
const dirents = await fs.readdir(absoluteDir, { withFileTypes: true });
|
||||
return { relativeDir, dirents };
|
||||
} catch (error) {
|
||||
if (!relativeDir) {
|
||||
throw new Error(
|
||||
`Unable to scan workspace entries at '${cwd}': ${error instanceof Error ? error.message : "unknown error"}`,
|
||||
{ cause: error },
|
||||
);
|
||||
}
|
||||
return { relativeDir, dirents: null };
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const candidateEntriesByDirectory = directoryEntries.map((directoryEntry) => {
|
||||
const { relativeDir, dirents } = directoryEntry;
|
||||
if (!dirents) return [] as Array<{ dirent: Dirent; relativePath: string }>;
|
||||
|
||||
dirents.sort((left, right) => left.name.localeCompare(right.name));
|
||||
const candidates: Array<{ dirent: Dirent; relativePath: string }> = [];
|
||||
for (const dirent of dirents) {
|
||||
if (!dirent.name || dirent.name === "." || dirent.name === "..") {
|
||||
continue;
|
||||
}
|
||||
if (dirent.isDirectory() && IGNORED_DIRECTORY_NAMES.has(dirent.name)) {
|
||||
continue;
|
||||
}
|
||||
if (!dirent.isDirectory() && !dirent.isFile()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const relativePath = toPosixPath(
|
||||
relativeDir ? path.join(relativeDir, dirent.name) : dirent.name,
|
||||
);
|
||||
if (isPathInIgnoredDirectory(relativePath)) {
|
||||
continue;
|
||||
}
|
||||
candidates.push({ dirent, relativePath });
|
||||
}
|
||||
return candidates;
|
||||
});
|
||||
|
||||
const candidatePaths = candidateEntriesByDirectory.flatMap((candidateEntries) =>
|
||||
candidateEntries.map((entry) => entry.relativePath),
|
||||
);
|
||||
const allowedPathSet = shouldFilterWithGitIgnore
|
||||
? new Set(await filterGitIgnoredPaths(cwd, candidatePaths))
|
||||
: null;
|
||||
|
||||
for (const candidateEntries of candidateEntriesByDirectory) {
|
||||
for (const candidate of candidateEntries) {
|
||||
if (allowedPathSet && !allowedPathSet.has(candidate.relativePath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const entry = toSearchableWorkspaceEntry({
|
||||
path: candidate.relativePath,
|
||||
kind: candidate.dirent.isDirectory() ? "directory" : "file",
|
||||
parentPath: parentPathOf(candidate.relativePath),
|
||||
});
|
||||
entries.push(entry);
|
||||
|
||||
if (candidate.dirent.isDirectory()) {
|
||||
pendingDirectories.push(candidate.relativePath);
|
||||
}
|
||||
|
||||
if (entries.length >= WORKSPACE_INDEX_MAX_ENTRIES) {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (truncated) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
scannedAt: Date.now(),
|
||||
entries,
|
||||
truncated,
|
||||
};
|
||||
}
|
||||
|
||||
async function getWorkspaceIndex(cwd: string): Promise<WorkspaceIndex> {
|
||||
const cached = workspaceIndexCache.get(cwd);
|
||||
if (cached && Date.now() - cached.scannedAt < WORKSPACE_CACHE_TTL_MS) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
const inFlight = inFlightWorkspaceIndexBuilds.get(cwd);
|
||||
if (inFlight) {
|
||||
return inFlight;
|
||||
}
|
||||
|
||||
const nextPromise = buildWorkspaceIndex(cwd)
|
||||
.then((next) => {
|
||||
workspaceIndexCache.set(cwd, next);
|
||||
while (workspaceIndexCache.size > WORKSPACE_CACHE_MAX_KEYS) {
|
||||
const oldestKey = workspaceIndexCache.keys().next().value;
|
||||
if (!oldestKey) break;
|
||||
workspaceIndexCache.delete(oldestKey);
|
||||
}
|
||||
return next;
|
||||
})
|
||||
.finally(() => {
|
||||
inFlightWorkspaceIndexBuilds.delete(cwd);
|
||||
});
|
||||
inFlightWorkspaceIndexBuilds.set(cwd, nextPromise);
|
||||
return nextPromise;
|
||||
}
|
||||
|
||||
export function clearWorkspaceIndexCache(cwd: string): void {
|
||||
workspaceIndexCache.delete(cwd);
|
||||
inFlightWorkspaceIndexBuilds.delete(cwd);
|
||||
}
|
||||
|
||||
export async function searchWorkspaceEntries(
|
||||
input: ProjectSearchEntriesInput,
|
||||
): Promise<ProjectSearchEntriesResult> {
|
||||
const index = await getWorkspaceIndex(input.cwd);
|
||||
const normalizedQuery = normalizeQuery(input.query);
|
||||
const limit = Math.max(0, Math.floor(input.limit));
|
||||
const rankedEntries: RankedWorkspaceEntry[] = [];
|
||||
let matchedEntryCount = 0;
|
||||
|
||||
for (const entry of index.entries) {
|
||||
const score = scoreEntry(entry, normalizedQuery);
|
||||
if (score === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
matchedEntryCount += 1;
|
||||
insertRankedEntry(rankedEntries, { entry, score }, limit);
|
||||
}
|
||||
|
||||
return {
|
||||
entries: rankedEntries.map((candidate) => candidate.entry),
|
||||
truncated: index.truncated || matchedEntryCount > limit,
|
||||
};
|
||||
}
|
||||
@@ -4,18 +4,8 @@ import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import {
|
||||
Effect,
|
||||
Exit,
|
||||
Fiber,
|
||||
Layer,
|
||||
ManagedRuntime,
|
||||
PlatformError,
|
||||
PubSub,
|
||||
Scope,
|
||||
Stream,
|
||||
} from "effect";
|
||||
import { describe, expect, it, afterEach, vi } from "vite-plus/test";
|
||||
import { Effect, Exit, Fiber, Layer, PlatformError, PubSub, Scope, Stream } from "effect";
|
||||
import { describe, expect, it, afterEach, vi } from "vitest";
|
||||
import { createServer } from "./wsServer";
|
||||
import WebSocket from "ws";
|
||||
import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "./config";
|
||||
@@ -73,6 +63,8 @@ const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
|
||||
const defaultOpenService: OpenShape = {
|
||||
getAvailableEditors: Effect.succeed([]),
|
||||
openExternal: () => Effect.void,
|
||||
openBrowser: () => Effect.void,
|
||||
openInEditor: () => Effect.void,
|
||||
};
|
||||
@@ -281,7 +273,7 @@ function dequeue<T>(channel: MessageChannel<T>, timeoutMs: number): Promise<T> {
|
||||
const index = channel.waiters.indexOf(waiter);
|
||||
if (index >= 0) channel.waiters.splice(index, 1);
|
||||
reject(new Error(`Timed out waiting for WebSocket message after ${timeoutMs}ms`));
|
||||
}, timeoutMs),
|
||||
}, timeoutMs) as ReturnType<typeof setTimeout>,
|
||||
};
|
||||
channel.waiters.push(waiter);
|
||||
});
|
||||
@@ -485,7 +477,6 @@ function deriveServerPathsSync(baseDir: string, devUrl: URL | undefined) {
|
||||
describe("WebSocket Server", () => {
|
||||
let server: Http.Server | null = null;
|
||||
let serverScope: Scope.Closeable | null = null;
|
||||
let disposeServerRuntime: (() => Promise<void>) | null = null;
|
||||
const connections: WebSocket[] = [];
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
@@ -508,7 +499,7 @@ describe("WebSocket Server", () => {
|
||||
authToken?: string;
|
||||
baseDir?: string;
|
||||
staticDir?: string;
|
||||
providerLayer?: Layer.Layer<ProviderService>;
|
||||
providerLayer?: Layer.Layer<ProviderService, never>;
|
||||
providerRegistry?: ProviderRegistryShape;
|
||||
open?: OpenShape;
|
||||
gitManager?: GitManagerShape;
|
||||
@@ -532,12 +523,6 @@ describe("WebSocket Server", () => {
|
||||
options.providerRegistry ?? defaultProviderRegistryService,
|
||||
);
|
||||
const openLayer = Layer.succeed(Open, options.open ?? defaultOpenService);
|
||||
const nodeServicesLayer = NodeServices.layer;
|
||||
const serverSettingsLayer = ServerSettingsService.layerTest(options.serverSettings);
|
||||
const serverSettingsRuntimeLayer = serverSettingsLayer.pipe(
|
||||
Layer.provideMerge(nodeServicesLayer),
|
||||
);
|
||||
const analyticsLayer = AnalyticsService.layerTest;
|
||||
const serverConfigLayer = Layer.succeed(ServerConfig, {
|
||||
mode: "web",
|
||||
port: 0,
|
||||
@@ -553,11 +538,6 @@ describe("WebSocket Server", () => {
|
||||
logWebSocketEvents: options.logWebSocketEvents ?? Boolean(options.devUrl),
|
||||
} satisfies ServerConfigShape);
|
||||
const infrastructureLayer = providerLayer.pipe(Layer.provideMerge(persistenceLayer));
|
||||
const providerRuntimeLayer = infrastructureLayer.pipe(
|
||||
Layer.provideMerge(serverConfigLayer),
|
||||
Layer.provideMerge(serverSettingsRuntimeLayer),
|
||||
Layer.provideMerge(analyticsLayer),
|
||||
);
|
||||
const runtimeOverrides = Layer.mergeAll(
|
||||
options.gitManager ? Layer.succeed(GitManager, options.gitManager) : Layer.empty,
|
||||
options.gitCore
|
||||
@@ -570,49 +550,41 @@ describe("WebSocket Server", () => {
|
||||
|
||||
const runtimeLayer = Layer.merge(
|
||||
Layer.merge(
|
||||
makeServerRuntimeServicesLayer().pipe(
|
||||
Layer.provideMerge(providerRuntimeLayer),
|
||||
Layer.provideMerge(serverConfigLayer),
|
||||
Layer.provideMerge(serverSettingsRuntimeLayer),
|
||||
Layer.provideMerge(analyticsLayer),
|
||||
Layer.provideMerge(nodeServicesLayer),
|
||||
),
|
||||
Layer.mergeAll(providerRuntimeLayer, serverSettingsRuntimeLayer, analyticsLayer),
|
||||
makeServerRuntimeServicesLayer().pipe(Layer.provide(infrastructureLayer)),
|
||||
infrastructureLayer,
|
||||
),
|
||||
runtimeOverrides,
|
||||
);
|
||||
const dependenciesLayer = Layer.mergeAll(
|
||||
runtimeLayer,
|
||||
providerRegistryLayer,
|
||||
openLayer,
|
||||
serverConfigLayer,
|
||||
nodeServicesLayer,
|
||||
const dependenciesLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(runtimeLayer),
|
||||
Layer.provideMerge(providerRegistryLayer),
|
||||
Layer.provideMerge(openLayer),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest(options.serverSettings)),
|
||||
Layer.provideMerge(serverConfigLayer),
|
||||
Layer.provideMerge(AnalyticsService.layerTest),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
const runtime = ManagedRuntime.make(dependenciesLayer);
|
||||
const runtimeServices = await Effect.runPromise(
|
||||
Layer.build(dependenciesLayer).pipe(Scope.provide(scope)),
|
||||
);
|
||||
|
||||
try {
|
||||
const httpServer = await runtime.runPromise(createServer().pipe(Scope.provide(scope)));
|
||||
disposeServerRuntime = () => runtime.dispose();
|
||||
const runtime = await Effect.runPromise(
|
||||
createServer().pipe(Effect.provide(runtimeServices), Scope.provide(scope)),
|
||||
);
|
||||
serverScope = scope;
|
||||
return httpServer;
|
||||
return runtime;
|
||||
} catch (error) {
|
||||
await runtime.dispose();
|
||||
await Effect.runPromise(Scope.close(scope, Exit.void));
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function closeTestServer() {
|
||||
if (!serverScope && !disposeServerRuntime) return;
|
||||
if (!serverScope) return;
|
||||
const scope = serverScope;
|
||||
const disposeRuntime = disposeServerRuntime;
|
||||
serverScope = null;
|
||||
disposeServerRuntime = null;
|
||||
if (scope) {
|
||||
await Effect.runPromise(Scope.close(scope, Exit.void));
|
||||
}
|
||||
if (disposeRuntime) {
|
||||
await disposeRuntime();
|
||||
}
|
||||
await Effect.runPromise(Scope.close(scope, Exit.void));
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
@@ -1060,6 +1032,8 @@ describe("WebSocket Server", () => {
|
||||
it("routes shell.openInEditor through the injected open service", async () => {
|
||||
const openCalls: Array<{ cwd: string; editor: string }> = [];
|
||||
const openService: OpenShape = {
|
||||
getAvailableEditors: Effect.succeed([]),
|
||||
openExternal: () => Effect.void,
|
||||
openBrowser: () => Effect.void,
|
||||
openInEditor: (input) => {
|
||||
openCalls.push({ cwd: input.cwd, editor: input.editor });
|
||||
@@ -1285,32 +1259,6 @@ describe("WebSocket Server", () => {
|
||||
expect(response.error?.message).toContain("exceeds current turn count");
|
||||
});
|
||||
|
||||
it("rejects project.create when the workspace root does not exist", async () => {
|
||||
server = await createTestServer({ cwd: "/test" });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const [ws] = await connectAndAwaitWelcome(port);
|
||||
connections.push(ws);
|
||||
|
||||
const missingWorkspaceRoot = path.join(makeTempDir("t3code-ws-project-missing-"), "missing");
|
||||
const response = await sendRequest(ws, ORCHESTRATION_WS_METHODS.dispatchCommand, {
|
||||
type: "project.create",
|
||||
commandId: "cmd-ws-project-create-missing",
|
||||
projectId: "project-missing",
|
||||
title: "Missing Project",
|
||||
workspaceRoot: missingWorkspaceRoot,
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
|
||||
expect(response.result).toBeUndefined();
|
||||
expect(response.error?.message).toContain("Workspace root does not exist:");
|
||||
});
|
||||
|
||||
it("keeps orchestration domain push behavior for provider runtime events", async () => {
|
||||
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
||||
const emitRuntimeEvent = (event: ProviderRuntimeEvent) => {
|
||||
@@ -1505,7 +1453,7 @@ describe("WebSocket Server", () => {
|
||||
const push = await waitForPush(
|
||||
ws,
|
||||
WS_CHANNELS.terminalEvent,
|
||||
(candidate) => candidate.data.type === "output",
|
||||
(candidate) => (candidate.data as TerminalEvent).type === "output",
|
||||
);
|
||||
expect(push.type).toBe("push");
|
||||
expect(push.channel).toBe(WS_CHANNELS.terminalEvent);
|
||||
@@ -1587,6 +1535,8 @@ describe("WebSocket Server", () => {
|
||||
process.on("unhandledRejection", onUnhandledRejection);
|
||||
|
||||
const brokenOpenService: OpenShape = {
|
||||
getAvailableEditors: Effect.succeed([]),
|
||||
openExternal: () => Effect.void,
|
||||
openBrowser: () => Effect.void,
|
||||
openInEditor: () =>
|
||||
Effect.sync(() => BigInt(1)).pipe(Effect.map((result) => result as unknown as void)),
|
||||
@@ -1721,50 +1671,6 @@ describe("WebSocket Server", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("invalidates workspace entry search cache after projects.writeFile", async () => {
|
||||
const workspace = makeTempDir("t3code-ws-write-file-invalidate-");
|
||||
fs.mkdirSync(path.join(workspace, "src"), { recursive: true });
|
||||
fs.writeFileSync(path.join(workspace, "src", "existing.ts"), "export {};\n", "utf8");
|
||||
|
||||
server = await createTestServer({ cwd: "/test" });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const [ws] = await connectAndAwaitWelcome(port);
|
||||
connections.push(ws);
|
||||
|
||||
const beforeWrite = await sendRequest(ws, WS_METHODS.projectsSearchEntries, {
|
||||
cwd: workspace,
|
||||
query: "rpc",
|
||||
limit: 10,
|
||||
});
|
||||
expect(beforeWrite.error).toBeUndefined();
|
||||
expect(beforeWrite.result).toEqual({
|
||||
entries: [],
|
||||
truncated: false,
|
||||
});
|
||||
|
||||
const writeResponse = await sendRequest(ws, WS_METHODS.projectsWriteFile, {
|
||||
cwd: workspace,
|
||||
relativePath: "plans/effect-rpc.md",
|
||||
contents: "# Plan\n",
|
||||
});
|
||||
expect(writeResponse.error).toBeUndefined();
|
||||
|
||||
const afterWrite = await sendRequest(ws, WS_METHODS.projectsSearchEntries, {
|
||||
cwd: workspace,
|
||||
query: "rpc",
|
||||
limit: 10,
|
||||
});
|
||||
expect(afterWrite.error).toBeUndefined();
|
||||
expect(afterWrite.result).toEqual({
|
||||
entries: expect.arrayContaining([
|
||||
expect.objectContaining({ path: "plans/effect-rpc.md", kind: "file" }),
|
||||
]),
|
||||
truncated: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects projects.writeFile paths outside the workspace root", async () => {
|
||||
const workspace = makeTempDir("t3code-ws-write-file-reject-");
|
||||
|
||||
@@ -1783,7 +1689,7 @@ describe("WebSocket Server", () => {
|
||||
|
||||
expect(response.result).toBeUndefined();
|
||||
expect(response.error?.message).toContain(
|
||||
"Workspace file path must be relative to the project root: ../escape.md",
|
||||
"Workspace file path must stay within the project root.",
|
||||
);
|
||||
expect(fs.existsSync(path.join(workspace, "..", "escape.md"))).toBe(false);
|
||||
});
|
||||
|
||||
+97
-32
@@ -50,6 +50,7 @@ import { GitManager } from "./git/Services/GitManager.ts";
|
||||
import { TerminalManager } from "./terminal/Services/Manager.ts";
|
||||
import { Keybindings } from "./keybindings";
|
||||
import { ServerSettingsService } from "./serverSettings";
|
||||
import { searchWorkspaceEntries } from "./workspaceEntries";
|
||||
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
|
||||
import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReactor";
|
||||
@@ -57,7 +58,7 @@ import { ProviderService } from "./provider/Services/ProviderService";
|
||||
import { ProviderRegistry } from "./provider/Services/ProviderRegistry";
|
||||
import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery";
|
||||
import { clamp } from "effect/Number";
|
||||
import { Open, resolveAvailableEditors } from "./open";
|
||||
import { Open } from "./open";
|
||||
import { ServerConfig } from "./config";
|
||||
import { GitCore } from "./git/Services/GitCore.ts";
|
||||
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
|
||||
@@ -74,13 +75,10 @@ import {
|
||||
} from "./attachmentStore.ts";
|
||||
import { parseBase64DataUrl } from "./imageMime.ts";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";
|
||||
import { expandHomePath } from "./os-jank.ts";
|
||||
import { makeServerPushBus } from "./wsServer/pushBus.ts";
|
||||
import { makeServerReadiness } from "./wsServer/readiness.ts";
|
||||
import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson";
|
||||
import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver.ts";
|
||||
import { WorkspaceEntries } from "./workspace/Services/WorkspaceEntries.ts";
|
||||
import { WorkspaceFileSystem } from "./workspace/Services/WorkspaceFileSystem.ts";
|
||||
import { WorkspacePaths } from "./workspace/Services/WorkspacePaths.ts";
|
||||
|
||||
/**
|
||||
* ServerShape - Service API for server lifecycle control.
|
||||
@@ -98,7 +96,7 @@ export interface ServerShape {
|
||||
/**
|
||||
* Wait for process shutdown signals.
|
||||
*/
|
||||
readonly stopSignal: Effect.Effect<void>;
|
||||
readonly stopSignal: Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -156,6 +154,48 @@ function websocketRawToString(raw: unknown): string | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
function toPosixRelativePath(input: string): string {
|
||||
return input.replaceAll("\\", "/");
|
||||
}
|
||||
|
||||
function resolveWorkspaceWritePath(params: {
|
||||
workspaceRoot: string;
|
||||
relativePath: string;
|
||||
path: Path.Path;
|
||||
}): Effect.Effect<{ absolutePath: string; relativePath: string }, RouteRequestError> {
|
||||
const normalizedInputPath = params.relativePath.trim();
|
||||
if (params.path.isAbsolute(normalizedInputPath)) {
|
||||
return Effect.fail(
|
||||
new RouteRequestError({
|
||||
message: "Workspace file path must be relative to the project root.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const absolutePath = params.path.resolve(params.workspaceRoot, normalizedInputPath);
|
||||
const relativeToRoot = toPosixRelativePath(
|
||||
params.path.relative(params.workspaceRoot, absolutePath),
|
||||
);
|
||||
if (
|
||||
relativeToRoot.length === 0 ||
|
||||
relativeToRoot === "." ||
|
||||
relativeToRoot.startsWith("../") ||
|
||||
relativeToRoot === ".." ||
|
||||
params.path.isAbsolute(relativeToRoot)
|
||||
) {
|
||||
return Effect.fail(
|
||||
new RouteRequestError({
|
||||
message: "Workspace file path must stay within the project root.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.succeed({
|
||||
absolutePath,
|
||||
relativePath: relativeToRoot,
|
||||
});
|
||||
}
|
||||
|
||||
function stripRequestTag<T extends { _tag: string }>(body: T) {
|
||||
return Struct.omit(body, ["_tag"]);
|
||||
}
|
||||
@@ -178,10 +218,6 @@ export type ServerRuntimeServices =
|
||||
| TerminalManager
|
||||
| Keybindings
|
||||
| ServerSettingsService
|
||||
| ProjectFaviconResolver
|
||||
| WorkspaceEntries
|
||||
| WorkspaceFileSystem
|
||||
| WorkspacePaths
|
||||
| Open
|
||||
| AnalyticsService;
|
||||
|
||||
@@ -214,7 +250,10 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
logWebSocketEvents,
|
||||
autoBootstrapProjectFromCwd,
|
||||
} = serverConfig;
|
||||
const availableEditors = resolveAvailableEditors();
|
||||
const open = yield* Open;
|
||||
const availableEditors = yield* open.getAvailableEditors.pipe(
|
||||
Effect.mapError((cause) => new ServerLifecycleError({ operation: "availableEditors", cause })),
|
||||
);
|
||||
|
||||
const runtimeServices = yield* Effect.services<
|
||||
ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path
|
||||
@@ -227,9 +266,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
const serverSettingsManager = yield* ServerSettingsService;
|
||||
const providerRegistry = yield* ProviderRegistry;
|
||||
const git = yield* GitCore;
|
||||
const workspaceEntries = yield* WorkspaceEntries;
|
||||
const workspaceFileSystem = yield* WorkspaceFileSystem;
|
||||
const workspacePaths = yield* WorkspacePaths;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
@@ -279,21 +315,35 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
const normalizeDispatchCommand = Effect.fnUntraced(function* (input: {
|
||||
readonly command: ClientOrchestrationCommand;
|
||||
}) {
|
||||
const normalizeProjectWorkspaceRoot = Effect.fnUntraced(function* (workspaceRoot: string) {
|
||||
const normalizedWorkspaceRoot = path.resolve(yield* expandHomePath(workspaceRoot.trim()));
|
||||
const workspaceStat = yield* fileSystem
|
||||
.stat(normalizedWorkspaceRoot)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!workspaceStat) {
|
||||
return yield* new RouteRequestError({
|
||||
message: `Project directory does not exist: ${normalizedWorkspaceRoot}`,
|
||||
});
|
||||
}
|
||||
if (workspaceStat.type !== "Directory") {
|
||||
return yield* new RouteRequestError({
|
||||
message: `Project path is not a directory: ${normalizedWorkspaceRoot}`,
|
||||
});
|
||||
}
|
||||
return normalizedWorkspaceRoot;
|
||||
});
|
||||
|
||||
if (input.command.type === "project.create") {
|
||||
return {
|
||||
...input.command,
|
||||
workspaceRoot: yield* workspacePaths
|
||||
.normalizeWorkspaceRoot(input.command.workspaceRoot)
|
||||
.pipe(Effect.mapError((cause) => new RouteRequestError({ message: cause.message }))),
|
||||
workspaceRoot: yield* normalizeProjectWorkspaceRoot(input.command.workspaceRoot),
|
||||
} satisfies OrchestrationCommand;
|
||||
}
|
||||
|
||||
if (input.command.type === "project.meta.update" && input.command.workspaceRoot !== undefined) {
|
||||
return {
|
||||
...input.command,
|
||||
workspaceRoot: yield* workspacePaths
|
||||
.normalizeWorkspaceRoot(input.command.workspaceRoot)
|
||||
.pipe(Effect.mapError((cause) => new RouteRequestError({ message: cause.message }))),
|
||||
workspaceRoot: yield* normalizeProjectWorkspaceRoot(input.command.workspaceRoot),
|
||||
} satisfies OrchestrationCommand;
|
||||
}
|
||||
|
||||
@@ -390,7 +440,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
void runPromise(
|
||||
Effect.gen(function* () {
|
||||
const url = new URL(req.url ?? "/", `http://localhost:${port}`);
|
||||
if (yield* tryHandleProjectFaviconRequest(url, res)) {
|
||||
if (tryHandleProjectFaviconRequest(url, res)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -568,7 +618,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
const projectionReadModelQuery = yield* ProjectionSnapshotQuery;
|
||||
const checkpointDiffQuery = yield* CheckpointDiffQuery;
|
||||
const orchestrationReactor = yield* OrchestrationReactor;
|
||||
const { openInEditor } = yield* Open;
|
||||
const { openInEditor } = open;
|
||||
|
||||
const subscriptionsScope = yield* Scope.make("sequential");
|
||||
yield* Effect.addFinalizer(() => Scope.close(subscriptionsScope, Exit.void));
|
||||
@@ -721,26 +771,41 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
|
||||
case WS_METHODS.projectsSearchEntries: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* workspaceEntries.search(body).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new RouteRequestError({
|
||||
message: `Failed to search workspace entries: ${cause.detail}`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return yield* Effect.tryPromise({
|
||||
try: () => searchWorkspaceEntries(body),
|
||||
catch: (cause) =>
|
||||
new RouteRequestError({
|
||||
message: `Failed to search workspace entries: ${String(cause)}`,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
case WS_METHODS.projectsWriteFile: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* workspaceFileSystem.writeFile(body).pipe(
|
||||
const target = yield* resolveWorkspaceWritePath({
|
||||
workspaceRoot: body.cwd,
|
||||
relativePath: body.relativePath,
|
||||
path,
|
||||
});
|
||||
yield* fileSystem
|
||||
.makeDirectory(path.dirname(target.absolutePath), { recursive: true })
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new RouteRequestError({
|
||||
message: `Failed to prepare workspace path: ${String(cause)}`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* fileSystem.writeFileString(target.absolutePath, body.contents).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new RouteRequestError({
|
||||
message: `Failed to write workspace file: ${cause.message}`,
|
||||
message: `Failed to write workspace file: ${String(cause)}`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return { relativePath: target.relativePath };
|
||||
}
|
||||
|
||||
case WS_METHODS.shellOpenInEditor: {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { WebSocket } from "ws";
|
||||
import { it } from "@effect/vitest";
|
||||
import { describe, expect } from "vite-plus/test";
|
||||
import { describe, expect } from "vitest";
|
||||
import { Effect, Ref } from "effect";
|
||||
import { WS_CHANNELS } from "@t3tools/contracts";
|
||||
|
||||
|
||||
@@ -21,14 +21,5 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"include": [
|
||||
"src",
|
||||
"vite.config.ts",
|
||||
"scripts",
|
||||
"integration",
|
||||
"../../scripts/lib",
|
||||
"../../packages/contracts/src",
|
||||
"../../packages/shared/src"
|
||||
],
|
||||
"exclude": ["../../packages/contracts/src/**/*.test.ts", "../../packages/shared/src/**/*.test.ts"]
|
||||
"include": ["src", "tsdown.config.ts", "scripts", "integration", "../../scripts/lib"]
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { defineConfig } from "tsdown";
|
||||
|
||||
export default defineConfig({
|
||||
entry: ["src/index.ts"],
|
||||
format: ["esm", "cjs"],
|
||||
checks: {
|
||||
legacyCjs: false,
|
||||
},
|
||||
outDir: "dist",
|
||||
sourcemap: true,
|
||||
clean: true,
|
||||
noExternal: (id) => id.startsWith("@t3tools/"),
|
||||
inlineOnly: false,
|
||||
banner: {
|
||||
js: "#!/usr/bin/env node\n",
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"$schema": "https://turbo.build/schema.json",
|
||||
"extends": ["//"],
|
||||
"tasks": {
|
||||
"start": {
|
||||
"dependsOn": ["build"],
|
||||
"cache": false,
|
||||
"persistent": true,
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
import * as path from "node:path";
|
||||
|
||||
import { defineConfig } from "vite-plus";
|
||||
|
||||
export default defineConfig({
|
||||
resolve: {
|
||||
tsconfigPaths: true,
|
||||
alias: [
|
||||
{
|
||||
find: /^@t3tools\/contracts$/,
|
||||
replacement: path.resolve(import.meta.dirname, "../../packages/contracts/src/index.ts"),
|
||||
},
|
||||
{
|
||||
find: /^@t3tools\/contracts\/settings$/,
|
||||
replacement: path.resolve(import.meta.dirname, "../../packages/contracts/src/settings.ts"),
|
||||
},
|
||||
{
|
||||
find: /^@t3tools\/shared\/(.*)$/,
|
||||
replacement: path.resolve(import.meta.dirname, "../../packages/shared/src/$1.ts"),
|
||||
},
|
||||
],
|
||||
},
|
||||
pack: {
|
||||
entry: ["src/index.ts"],
|
||||
format: ["esm", "cjs"],
|
||||
checks: {
|
||||
legacyCjs: false,
|
||||
},
|
||||
outDir: "dist",
|
||||
sourcemap: true,
|
||||
clean: true,
|
||||
noExternal: (id) => id.startsWith("@t3tools/"),
|
||||
inlineOnly: false,
|
||||
banner: {
|
||||
js: "#!/usr/bin/env node\n",
|
||||
},
|
||||
},
|
||||
test: {
|
||||
testTimeout: 15_000,
|
||||
hookTimeout: 15_000,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
import { defineConfig, mergeConfig } from "vitest/config";
|
||||
|
||||
import baseConfig from "../../vitest.config";
|
||||
|
||||
export default mergeConfig(
|
||||
baseConfig,
|
||||
defineConfig({
|
||||
test: {
|
||||
testTimeout: 15_000,
|
||||
hookTimeout: 15_000,
|
||||
},
|
||||
}),
|
||||
);
|
||||
@@ -4,13 +4,13 @@
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vp dev",
|
||||
"build": "vp build",
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"prepare": "effect-language-service patch",
|
||||
"preview": "vp preview",
|
||||
"preview": "vite preview",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vp test run --passWithNoTests",
|
||||
"test:browser": "vp test run --config vitest.browser.config.ts",
|
||||
"test": "vitest run --passWithNoTests",
|
||||
"test:browser": "vitest run --config vitest.browser.config.ts",
|
||||
"test:browser:install": "playwright install --with-deps chromium"
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -50,12 +50,14 @@
|
||||
"@types/react": "^19.0.0",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
"@vitejs/plugin-react": "^6.0.0",
|
||||
"@vitest/browser-playwright": "^4.0.18",
|
||||
"babel-plugin-react-compiler": "^19.0.0-beta-e552027-20250112",
|
||||
"msw": "2.12.11",
|
||||
"playwright": "^1.58.2",
|
||||
"tailwindcss": "^4.0.0",
|
||||
"typescript": "catalog:",
|
||||
"vite-plus": "catalog:",
|
||||
"vite": "^8.0.0",
|
||||
"vitest": "catalog:",
|
||||
"vitest-browser-react": "^2.0.5"
|
||||
}
|
||||
}
|
||||
@@ -7,111 +7,114 @@
|
||||
* - Please do NOT modify this file.
|
||||
*/
|
||||
|
||||
const PACKAGE_VERSION = "2.12.11";
|
||||
const INTEGRITY_CHECKSUM = "4db4a41e972cec1b64cc569c66952d82";
|
||||
const IS_MOCKED_RESPONSE = Symbol("isMockedResponse");
|
||||
const activeClientIds = new Set();
|
||||
const PACKAGE_VERSION = '2.12.11'
|
||||
const INTEGRITY_CHECKSUM = '4db4a41e972cec1b64cc569c66952d82'
|
||||
const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
|
||||
const activeClientIds = new Set()
|
||||
|
||||
addEventListener("install", function () {
|
||||
self.skipWaiting();
|
||||
});
|
||||
addEventListener('install', function () {
|
||||
self.skipWaiting()
|
||||
})
|
||||
|
||||
addEventListener("activate", function (event) {
|
||||
event.waitUntil(self.clients.claim());
|
||||
});
|
||||
addEventListener('activate', function (event) {
|
||||
event.waitUntil(self.clients.claim())
|
||||
})
|
||||
|
||||
addEventListener("message", async function (event) {
|
||||
const clientId = Reflect.get(event.source || {}, "id");
|
||||
addEventListener('message', async function (event) {
|
||||
const clientId = Reflect.get(event.source || {}, 'id')
|
||||
|
||||
if (!clientId || !self.clients) {
|
||||
return;
|
||||
return
|
||||
}
|
||||
|
||||
const client = await self.clients.get(clientId);
|
||||
const client = await self.clients.get(clientId)
|
||||
|
||||
if (!client) {
|
||||
return;
|
||||
return
|
||||
}
|
||||
|
||||
const allClients = await self.clients.matchAll({
|
||||
type: "window",
|
||||
});
|
||||
type: 'window',
|
||||
})
|
||||
|
||||
switch (event.data) {
|
||||
case "KEEPALIVE_REQUEST": {
|
||||
case 'KEEPALIVE_REQUEST': {
|
||||
sendToClient(client, {
|
||||
type: "KEEPALIVE_RESPONSE",
|
||||
});
|
||||
break;
|
||||
type: 'KEEPALIVE_RESPONSE',
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case "INTEGRITY_CHECK_REQUEST": {
|
||||
case 'INTEGRITY_CHECK_REQUEST': {
|
||||
sendToClient(client, {
|
||||
type: "INTEGRITY_CHECK_RESPONSE",
|
||||
type: 'INTEGRITY_CHECK_RESPONSE',
|
||||
payload: {
|
||||
packageVersion: PACKAGE_VERSION,
|
||||
checksum: INTEGRITY_CHECKSUM,
|
||||
},
|
||||
});
|
||||
break;
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case "MOCK_ACTIVATE": {
|
||||
activeClientIds.add(clientId);
|
||||
case 'MOCK_ACTIVATE': {
|
||||
activeClientIds.add(clientId)
|
||||
|
||||
sendToClient(client, {
|
||||
type: "MOCKING_ENABLED",
|
||||
type: 'MOCKING_ENABLED',
|
||||
payload: {
|
||||
client: {
|
||||
id: client.id,
|
||||
frameType: client.frameType,
|
||||
},
|
||||
},
|
||||
});
|
||||
break;
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case "CLIENT_CLOSED": {
|
||||
activeClientIds.delete(clientId);
|
||||
case 'CLIENT_CLOSED': {
|
||||
activeClientIds.delete(clientId)
|
||||
|
||||
const remainingClients = allClients.filter((client) => {
|
||||
return client.id !== clientId;
|
||||
});
|
||||
return client.id !== clientId
|
||||
})
|
||||
|
||||
// Unregister itself when there are no more clients
|
||||
if (remainingClients.length === 0) {
|
||||
self.registration.unregister();
|
||||
self.registration.unregister()
|
||||
}
|
||||
|
||||
break;
|
||||
break
|
||||
}
|
||||
}
|
||||
});
|
||||
})
|
||||
|
||||
addEventListener("fetch", function (event) {
|
||||
const requestInterceptedAt = Date.now();
|
||||
addEventListener('fetch', function (event) {
|
||||
const requestInterceptedAt = Date.now()
|
||||
|
||||
// Bypass navigation requests.
|
||||
if (event.request.mode === "navigate") {
|
||||
return;
|
||||
if (event.request.mode === 'navigate') {
|
||||
return
|
||||
}
|
||||
|
||||
// Opening the DevTools triggers the "only-if-cached" request
|
||||
// that cannot be handled by the worker. Bypass such requests.
|
||||
if (event.request.cache === "only-if-cached" && event.request.mode !== "same-origin") {
|
||||
return;
|
||||
if (
|
||||
event.request.cache === 'only-if-cached' &&
|
||||
event.request.mode !== 'same-origin'
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
// Bypass all requests when there are no active clients.
|
||||
// Prevents the self-unregistered worked from handling requests
|
||||
// after it's been terminated (still remains active until the next reload).
|
||||
if (activeClientIds.size === 0) {
|
||||
return;
|
||||
return
|
||||
}
|
||||
|
||||
const requestId = crypto.randomUUID();
|
||||
event.respondWith(handleRequest(event, requestId, requestInterceptedAt));
|
||||
});
|
||||
const requestId = crypto.randomUUID()
|
||||
event.respondWith(handleRequest(event, requestId, requestInterceptedAt))
|
||||
})
|
||||
|
||||
/**
|
||||
* @param {FetchEvent} event
|
||||
@@ -119,23 +122,28 @@ addEventListener("fetch", function (event) {
|
||||
* @param {number} requestInterceptedAt
|
||||
*/
|
||||
async function handleRequest(event, requestId, requestInterceptedAt) {
|
||||
const client = await resolveMainClient(event);
|
||||
const requestCloneForEvents = event.request.clone();
|
||||
const response = await getResponse(event, client, requestId, requestInterceptedAt);
|
||||
const client = await resolveMainClient(event)
|
||||
const requestCloneForEvents = event.request.clone()
|
||||
const response = await getResponse(
|
||||
event,
|
||||
client,
|
||||
requestId,
|
||||
requestInterceptedAt,
|
||||
)
|
||||
|
||||
// Send back the response clone for the "response:*" life-cycle events.
|
||||
// Ensure MSW is active and ready to handle the message, otherwise
|
||||
// this message will pend indefinitely.
|
||||
if (client && activeClientIds.has(client.id)) {
|
||||
const serializedRequest = await serializeRequest(requestCloneForEvents);
|
||||
const serializedRequest = await serializeRequest(requestCloneForEvents)
|
||||
|
||||
// Clone the response so both the client and the library could consume it.
|
||||
const responseClone = response.clone();
|
||||
const responseClone = response.clone()
|
||||
|
||||
sendToClient(
|
||||
client,
|
||||
{
|
||||
type: "RESPONSE",
|
||||
type: 'RESPONSE',
|
||||
payload: {
|
||||
isMockedResponse: IS_MOCKED_RESPONSE in response,
|
||||
request: {
|
||||
@@ -152,10 +160,10 @@ async function handleRequest(event, requestId, requestInterceptedAt) {
|
||||
},
|
||||
},
|
||||
responseClone.body ? [serializedRequest.body, responseClone.body] : [],
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
return response;
|
||||
return response
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -167,30 +175,30 @@ async function handleRequest(event, requestId, requestInterceptedAt) {
|
||||
* @returns {Promise<Client | undefined>}
|
||||
*/
|
||||
async function resolveMainClient(event) {
|
||||
const client = await self.clients.get(event.clientId);
|
||||
const client = await self.clients.get(event.clientId)
|
||||
|
||||
if (activeClientIds.has(event.clientId)) {
|
||||
return client;
|
||||
return client
|
||||
}
|
||||
|
||||
if (client?.frameType === "top-level") {
|
||||
return client;
|
||||
if (client?.frameType === 'top-level') {
|
||||
return client
|
||||
}
|
||||
|
||||
const allClients = await self.clients.matchAll({
|
||||
type: "window",
|
||||
});
|
||||
type: 'window',
|
||||
})
|
||||
|
||||
return allClients
|
||||
.filter((client) => {
|
||||
// Get only those clients that are currently visible.
|
||||
return client.visibilityState === "visible";
|
||||
return client.visibilityState === 'visible'
|
||||
})
|
||||
.find((client) => {
|
||||
// Find the client ID that's recorded in the
|
||||
// set of clients that have registered the worker.
|
||||
return activeClientIds.has(client.id);
|
||||
});
|
||||
return activeClientIds.has(client.id)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -203,34 +211,36 @@ async function resolveMainClient(event) {
|
||||
async function getResponse(event, client, requestId, requestInterceptedAt) {
|
||||
// Clone the request because it might've been already used
|
||||
// (i.e. its body has been read and sent to the client).
|
||||
const requestClone = event.request.clone();
|
||||
const requestClone = event.request.clone()
|
||||
|
||||
function passthrough() {
|
||||
// Cast the request headers to a new Headers instance
|
||||
// so the headers can be manipulated with.
|
||||
const headers = new Headers(requestClone.headers);
|
||||
const headers = new Headers(requestClone.headers)
|
||||
|
||||
// Remove the "accept" header value that marked this request as passthrough.
|
||||
// This prevents request alteration and also keeps it compliant with the
|
||||
// user-defined CORS policies.
|
||||
const acceptHeader = headers.get("accept");
|
||||
const acceptHeader = headers.get('accept')
|
||||
if (acceptHeader) {
|
||||
const values = acceptHeader.split(",").map((value) => value.trim());
|
||||
const filteredValues = values.filter((value) => value !== "msw/passthrough");
|
||||
const values = acceptHeader.split(',').map((value) => value.trim())
|
||||
const filteredValues = values.filter(
|
||||
(value) => value !== 'msw/passthrough',
|
||||
)
|
||||
|
||||
if (filteredValues.length > 0) {
|
||||
headers.set("accept", filteredValues.join(", "));
|
||||
headers.set('accept', filteredValues.join(', '))
|
||||
} else {
|
||||
headers.delete("accept");
|
||||
headers.delete('accept')
|
||||
}
|
||||
}
|
||||
|
||||
return fetch(requestClone, { headers });
|
||||
return fetch(requestClone, { headers })
|
||||
}
|
||||
|
||||
// Bypass mocking when the client is not active.
|
||||
if (!client) {
|
||||
return passthrough();
|
||||
return passthrough()
|
||||
}
|
||||
|
||||
// Bypass initial page load requests (i.e. static assets).
|
||||
@@ -238,15 +248,15 @@ async function getResponse(event, client, requestId, requestInterceptedAt) {
|
||||
// means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
|
||||
// and is not ready to handle requests.
|
||||
if (!activeClientIds.has(client.id)) {
|
||||
return passthrough();
|
||||
return passthrough()
|
||||
}
|
||||
|
||||
// Notify the client that a request has been intercepted.
|
||||
const serializedRequest = await serializeRequest(event.request);
|
||||
const serializedRequest = await serializeRequest(event.request)
|
||||
const clientMessage = await sendToClient(
|
||||
client,
|
||||
{
|
||||
type: "REQUEST",
|
||||
type: 'REQUEST',
|
||||
payload: {
|
||||
id: requestId,
|
||||
interceptedAt: requestInterceptedAt,
|
||||
@@ -254,19 +264,19 @@ async function getResponse(event, client, requestId, requestInterceptedAt) {
|
||||
},
|
||||
},
|
||||
[serializedRequest.body],
|
||||
);
|
||||
)
|
||||
|
||||
switch (clientMessage.type) {
|
||||
case "MOCK_RESPONSE": {
|
||||
return respondWithMock(clientMessage.data);
|
||||
case 'MOCK_RESPONSE': {
|
||||
return respondWithMock(clientMessage.data)
|
||||
}
|
||||
|
||||
case "PASSTHROUGH": {
|
||||
return passthrough();
|
||||
case 'PASSTHROUGH': {
|
||||
return passthrough()
|
||||
}
|
||||
}
|
||||
|
||||
return passthrough();
|
||||
return passthrough()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -277,18 +287,21 @@ async function getResponse(event, client, requestId, requestInterceptedAt) {
|
||||
*/
|
||||
function sendToClient(client, message, transferrables = []) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const channel = new MessageChannel();
|
||||
const channel = new MessageChannel()
|
||||
|
||||
channel.port1.onmessage = (event) => {
|
||||
if (event.data && event.data.error) {
|
||||
return reject(event.data.error);
|
||||
return reject(event.data.error)
|
||||
}
|
||||
|
||||
resolve(event.data);
|
||||
};
|
||||
resolve(event.data)
|
||||
}
|
||||
|
||||
client.postMessage(message, [channel.port2, ...transferrables.filter(Boolean)]);
|
||||
});
|
||||
client.postMessage(message, [
|
||||
channel.port2,
|
||||
...transferrables.filter(Boolean),
|
||||
])
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -301,17 +314,17 @@ function respondWithMock(response) {
|
||||
// instance will have status code set to 0. Since it's not possible to create
|
||||
// a Response instance with status code 0, handle that use-case separately.
|
||||
if (response.status === 0) {
|
||||
return Response.error();
|
||||
return Response.error()
|
||||
}
|
||||
|
||||
const mockedResponse = new Response(response.body, response);
|
||||
const mockedResponse = new Response(response.body, response)
|
||||
|
||||
Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {
|
||||
value: true,
|
||||
enumerable: true,
|
||||
});
|
||||
})
|
||||
|
||||
return mockedResponse;
|
||||
return mockedResponse
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -332,5 +345,5 @@ async function serializeRequest(request) {
|
||||
referrerPolicy: request.referrerPolicy,
|
||||
body: await request.arrayBuffer(),
|
||||
keepalive: request.keepalive,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { AUTO_SCROLL_BOTTOM_THRESHOLD_PX, isScrollContainerNearBottom } from "./chat-scroll";
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { GitBranch } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
dedupeRemoteBranchesWithLocalMatches,
|
||||
deriveLocalBranchNameFromRemoteRef,
|
||||
|
||||
@@ -20,17 +20,8 @@ import {
|
||||
import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
|
||||
import { HttpResponse, http, ws } from "msw";
|
||||
import { setupWorker } from "msw/browser";
|
||||
import { page } from "vite-plus/test/browser";
|
||||
import {
|
||||
afterAll,
|
||||
afterEach,
|
||||
beforeAll,
|
||||
beforeEach,
|
||||
describe,
|
||||
expect,
|
||||
it,
|
||||
vi,
|
||||
} from "vite-plus/test";
|
||||
import { page } from "vitest/browser";
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { render } from "vitest-browser-react";
|
||||
|
||||
import { useComposerDraftStore } from "../composerDraftStore";
|
||||
@@ -766,30 +757,12 @@ async function triggerChatNewShortcutUntilPath(
|
||||
|
||||
async function waitForNewThreadShortcutLabel(): Promise<void> {
|
||||
const newThreadButton = page.getByTestId("new-thread-button");
|
||||
await waitForLocatorVisible(newThreadButton);
|
||||
await expect.element(newThreadButton).toBeInTheDocument();
|
||||
await newThreadButton.hover();
|
||||
const shortcutLabel = isMacPlatform(navigator.platform)
|
||||
? "New thread (⇧⌘O)"
|
||||
: "New thread (Ctrl+Shift+O)";
|
||||
await waitForLocatorVisible(page.getByText(shortcutLabel));
|
||||
}
|
||||
|
||||
async function waitForLocatorVisible(locator: {
|
||||
query: () => HTMLElement | SVGElement | null;
|
||||
}): Promise<void> {
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const element = locator.query();
|
||||
expect(element).not.toBeNull();
|
||||
if (!element) {
|
||||
return;
|
||||
}
|
||||
const style = getComputedStyle(element);
|
||||
expect(style.display).not.toBe("none");
|
||||
expect(style.visibility).not.toBe("hidden");
|
||||
},
|
||||
{ timeout: 4_000, interval: 16 },
|
||||
);
|
||||
await expect.element(page.getByText(shortcutLabel)).toBeInTheDocument();
|
||||
}
|
||||
|
||||
async function waitForImagesToLoad(scope: ParentNode): Promise<void> {
|
||||
@@ -1155,7 +1128,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
});
|
||||
|
||||
try {
|
||||
await waitForLocatorVisible(page.getByText("No threads yet"));
|
||||
await expect.element(page.getByText("No threads yet")).toBeInTheDocument();
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
@@ -1892,7 +1865,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
try {
|
||||
const threadRow = page.getByTestId(`thread-row-${THREAD_ID}`);
|
||||
|
||||
await waitForLocatorVisible(threadRow);
|
||||
await expect.element(threadRow).toBeInTheDocument();
|
||||
const archiveButton = await waitForElement(
|
||||
() =>
|
||||
document.querySelector<HTMLButtonElement>(`[data-testid="thread-archive-${THREAD_ID}"]`),
|
||||
@@ -1945,15 +1918,16 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
try {
|
||||
const threadRow = page.getByTestId(`thread-row-${THREAD_ID}`);
|
||||
|
||||
await waitForLocatorVisible(threadRow);
|
||||
await expect.element(threadRow).toBeInTheDocument();
|
||||
await threadRow.hover();
|
||||
|
||||
const archiveButton = page.getByTestId(`thread-archive-${THREAD_ID}`);
|
||||
await waitForLocatorVisible(archiveButton);
|
||||
await expect.element(archiveButton).toBeInTheDocument();
|
||||
await archiveButton.click();
|
||||
|
||||
const confirmButton = page.getByTestId(`thread-archive-confirm-${THREAD_ID}`);
|
||||
await waitForLocatorVisible(confirmButton);
|
||||
await expect.element(confirmButton).toBeInTheDocument();
|
||||
await expect.element(confirmButton).toBeVisible();
|
||||
} finally {
|
||||
localStorage.removeItem("t3code:client-settings:v1");
|
||||
await mounted.cleanup();
|
||||
@@ -1972,7 +1946,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
try {
|
||||
// Wait for the sidebar to render with the project.
|
||||
const newThreadButton = page.getByTestId("new-thread-button");
|
||||
await waitForLocatorVisible(newThreadButton);
|
||||
await expect.element(newThreadButton).toBeInTheDocument();
|
||||
|
||||
await newThreadButton.click();
|
||||
|
||||
@@ -2000,8 +1974,10 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
);
|
||||
|
||||
// The empty thread view and composer should still be visible.
|
||||
await waitForLocatorVisible(page.getByText("Send a message to start the conversation."));
|
||||
await waitForLocatorVisible(page.getByTestId("composer-editor"));
|
||||
await expect
|
||||
.element(page.getByText("Send a message to start the conversation."))
|
||||
.toBeInTheDocument();
|
||||
await expect.element(page.getByTestId("composer-editor")).toBeInTheDocument();
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
@@ -2032,7 +2008,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
|
||||
try {
|
||||
const newThreadButton = page.getByTestId("new-thread-button");
|
||||
await waitForLocatorVisible(newThreadButton);
|
||||
await expect.element(newThreadButton).toBeInTheDocument();
|
||||
|
||||
await newThreadButton.click();
|
||||
|
||||
@@ -2085,7 +2061,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
|
||||
try {
|
||||
const newThreadButton = page.getByTestId("new-thread-button");
|
||||
await waitForLocatorVisible(newThreadButton);
|
||||
await expect.element(newThreadButton).toBeInTheDocument();
|
||||
|
||||
await newThreadButton.click();
|
||||
|
||||
@@ -2125,7 +2101,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
|
||||
try {
|
||||
const newThreadButton = page.getByTestId("new-thread-button");
|
||||
await waitForLocatorVisible(newThreadButton);
|
||||
await expect.element(newThreadButton).toBeInTheDocument();
|
||||
|
||||
await newThreadButton.click();
|
||||
|
||||
@@ -2167,7 +2143,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
|
||||
try {
|
||||
const newThreadButton = page.getByTestId("new-thread-button");
|
||||
await waitForLocatorVisible(newThreadButton);
|
||||
await expect.element(newThreadButton).toBeInTheDocument();
|
||||
|
||||
await newThreadButton.click();
|
||||
|
||||
@@ -2304,7 +2280,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
|
||||
try {
|
||||
const newThreadButton = page.getByTestId("new-thread-button");
|
||||
await waitForLocatorVisible(newThreadButton);
|
||||
await expect.element(newThreadButton).toBeInTheDocument();
|
||||
await waitForNewThreadShortcutLabel();
|
||||
await waitForServerConfigToApply();
|
||||
await newThreadButton.click();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { useStore } from "../store";
|
||||
|
||||
import {
|
||||
|
||||
@@ -1812,7 +1812,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
handleInteractionModeChange(interactionMode === "plan" ? "default" : "plan");
|
||||
}, [handleInteractionModeChange, interactionMode]);
|
||||
const toggleRuntimeMode = useCallback(() => {
|
||||
handleRuntimeModeChange(runtimeMode === "full-access" ? "approval-required" : "full-access");
|
||||
void handleRuntimeModeChange(
|
||||
runtimeMode === "full-access" ? "approval-required" : "full-access",
|
||||
);
|
||||
}, [handleRuntimeModeChange, runtimeMode]);
|
||||
const togglePlanSidebar = useCallback(() => {
|
||||
setPlanSidebarOpen((open) => {
|
||||
@@ -3486,7 +3488,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}
|
||||
return;
|
||||
}
|
||||
handleInteractionModeChange(item.command === "plan" ? "plan" : "default");
|
||||
void handleInteractionModeChange(item.command === "plan" ? "plan" : "default");
|
||||
const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", {
|
||||
expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd),
|
||||
});
|
||||
@@ -4061,7 +4063,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
size="sm"
|
||||
type="button"
|
||||
onClick={() =>
|
||||
handleRuntimeModeChange(
|
||||
void handleRuntimeModeChange(
|
||||
runtimeMode === "full-access"
|
||||
? "approval-required"
|
||||
: "full-access",
|
||||
|
||||
@@ -597,7 +597,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
data-diff-file-path={filePath}
|
||||
className="diff-render-file mb-2 rounded-md first:mt-2 last:mb-0"
|
||||
onClickCapture={(event) => {
|
||||
const nativeEvent = event.nativeEvent;
|
||||
const nativeEvent = event.nativeEvent as MouseEvent;
|
||||
const composedPath = nativeEvent.composedPath?.() ?? [];
|
||||
const clickedHeader = composedPath.some((node) => {
|
||||
if (!(node instanceof Element)) return false;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { GitStatusResult } from "@t3tools/contracts";
|
||||
import { assert, describe, it } from "vite-plus/test";
|
||||
import { assert, describe, it } from "vitest";
|
||||
import {
|
||||
buildGitActionProgressStages,
|
||||
buildMenuItems,
|
||||
|
||||
@@ -14,16 +14,7 @@ import {
|
||||
import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
|
||||
import { ws, http, HttpResponse } from "msw";
|
||||
import { setupWorker } from "msw/browser";
|
||||
import {
|
||||
afterAll,
|
||||
afterEach,
|
||||
beforeAll,
|
||||
beforeEach,
|
||||
describe,
|
||||
expect,
|
||||
it,
|
||||
vi,
|
||||
} from "vite-plus/test";
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { render } from "vitest-browser-react";
|
||||
|
||||
import { useComposerDraftStore } from "../composerDraftStore";
|
||||
|
||||
Loaded 100 of 194 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user