Compare commits

..
Author SHA1 Message Date
Julius Marmingeandcodex 33b347391d Merge origin/main into t3code/viteplus-migrate
Co-authored-by: codex <[email protected]>
2026-04-01 00:17:19 -07:00
Julius Marminge e3404d1710 Migrate CI and web tests to vite-plus
- switch workspace checks and tests to `vp`
- fold Vitest browser config into `vite.config.ts`
- add `electron-builder` for desktop packaging
2026-03-31 15:52:01 -07:00
Julius Marminge 5abe2845ca rev 2026-03-31 15:30:48 -07:00
Julius Marminge 435a08b35a pin it 2026-03-31 15:24:12 -07:00
Julius Marminge b6227a4b67 rev 2026-03-31 15:16:05 -07:00
Julius Marminge c190e9f2b7 Migrate workspace to package exports
- Remove tsconfig path aliases and Vite aliases
- Point contracts/shared packages at source entrypoints
- Update dev runner imports to use package specifiers
2026-03-31 14:57:00 -07:00
Julius Marminge 881c64937a Migrate build and tests to vite-plus
- Replace tsdown and Turbo build wiring with vite-plus tasks
- Switch server, desktop, and web tests to vite-plus test imports
- Tighten related Effect types and update CI/docs for the new workflow
2026-03-31 13:50:19 -07:00
176 changed files with 1696 additions and 1379 deletions

No files matched your search

+2 -2
View File
@@ -1,13 +1,13 @@
# Scripts
- `bun run dev` — Starts contracts, server, and web in `turbo watch` mode.
- `bun run dev` — Starts contracts, server, and web in workspace dev 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 contracts, web app, and server through Turbo.
- `bun run build` — Builds workspace packages and apps through Vite+ task running.
- `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.
+15 -18
View File
@@ -19,18 +19,17 @@ jobs:
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
run-install: false
- name: Cache Bun and Turbo
- name: Cache Bun
uses: actions/cache@v5
with:
path: |
~/.bun/install/cache
.turbo
key: ${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-${{ hashFiles('turbo.json') }}
path: ~/.bun/install/cache
key: ${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}
restore-keys: |
${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-
@@ -45,22 +44,19 @@ jobs:
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Format
run: bun run fmt:check
- name: Check workspace (lint & fmt)
run: vp check
- name: Lint
run: bun run lint
- name: Typecheck
run: bun run typecheck
- name: Check workspace (typecheck)
run: vp run -r typecheck
- name: Test
run: bun run test
run: vp test
- name: Install browser test runtime
run: |
cd apps/web
bunx playwright install --with-deps chromium
vpx playwright install --with-deps chromium
- name: Browser test
run: bun run --cwd apps/web test:browser
@@ -85,10 +81,11 @@ jobs:
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
run-install: false
- name: Exercise release-only workflow steps
run: node scripts/release-smoke.ts
-15
View File
@@ -1,15 +0,0 @@
{
"$schema": "./node_modules/oxfmt/configuration_schema.json",
"ignorePatterns": [
".reference",
".plans",
"dist",
"dist-electron",
"node_modules",
"bun.lock",
"*.tsbuildinfo",
"**/routeTree.gen.ts",
"apps/web/public/mockServiceWorker.js"
],
"sortPackageJson": {}
}
-22
View File
@@ -1,22 +0,0 @@
{
"$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"
}
}
+2 -2
View File
@@ -2,8 +2,8 @@
## Task Completion Requirements
- All of `bun fmt`, `bun lint`, and `bun typecheck` must pass before considering tasks completed.
- NEVER run `bun test`. Always use `bun run test` (runs Vitest).
- `vp check` & `vp run typecheck` must pass before considering tasks completed.
- NEVER run `bun test`. Always use `vp test` (runs Vitest).
## Project Snapshot
+5 -5
View File
@@ -5,12 +5,12 @@
"main": "dist-electron/main.js",
"scripts": {
"dev": "bun run --parallel dev:bundle dev:electron",
"dev:bundle": "tsdown --watch",
"dev:bundle": "vp pack --watch",
"dev:electron": "bun run scripts/dev-electron.mjs",
"build": "tsdown",
"build": "vp pack",
"start": "bun run scripts/start-electron.mjs",
"typecheck": "tsc --noEmit",
"test": "vitest run --passWithNoTests",
"test": "vp test run --passWithNoTests",
"smoke-test": "node scripts/smoke-test.mjs"
},
"dependencies": {
@@ -22,9 +22,9 @@
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"@types/node": "catalog:",
"tsdown": "catalog:",
"electron-builder": "26.8.1",
"typescript": "catalog:",
"vitest": "catalog:"
"vite-plus": "catalog:"
},
"productName": "T3 Code (Alpha)"
}
+1 -1
View File
@@ -1,5 +1,5 @@
import type { BrowserWindow } from "electron";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
const { showMessageBoxMock } = vi.hoisted(() => ({
showMessageBoxMock: vi.fn(),
+1 -1
View File
@@ -104,7 +104,7 @@ let destructiveMenuIconCache: Electron.NativeImage | null | undefined;
const desktopRuntimeInfo = resolveDesktopRuntimeInfo({
platform: process.platform,
processArch: process.arch,
runningUnderArm64Translation: app.runningUnderARM64Translation === true,
runningUnderArm64Translation: app.runningUnderARM64Translation,
});
const initialUpdateState = (): DesktopUpdateState =>
createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo);
+1 -1
View File
@@ -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 "vitest";
import { afterEach, describe, expect, it } from "vite-plus/test";
const tempRoots: string[] = [];
+1 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it } from "vite-plus/test";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from "vitest";
import { describe, expect, it, vi } from "vite-plus/test";
import { syncShellEnvironment } from "./syncShellEnvironment";
+1 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it } from "vite-plus/test";
import {
createInitialDesktopUpdateState,
+1 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it } from "vite-plus/test";
import type { DesktopUpdateState } from "@t3tools/contracts";
import {
+1 -1
View File
@@ -5,5 +5,5 @@
"types": ["node", "electron"],
"lib": ["ES2023", "DOM", "esnext.disposable"]
},
"include": ["src", "tsdown.config.ts"]
"include": ["src", "vite.config.ts"]
}
-21
View File
@@ -1,21 +0,0 @@
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"],
},
]);
-24
View File
@@ -1,24 +0,0 @@
{
"$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": [],
},
},
}
+26
View File
@@ -0,0 +1,26 @@
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,
},
pack: [
{
...shared,
entry: ["src/main.ts"],
clean: true,
noExternal: (id) => id.startsWith("@t3tools/"),
},
{
...shared,
entry: ["src/preload.ts"],
},
],
});
@@ -115,19 +115,19 @@ function waitFor<A, E>(
predicate: (value: A) => boolean,
description: string,
timeoutMs?: number,
): Effect.Effect<A, never>;
): Effect.Effect<A>;
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, never>;
): Effect.Effect<B>;
function waitFor<A, E>(
read: Effect.Effect<A, E>,
predicate: (value: A) => boolean,
description: string,
timeoutMs = 40_000,
): Effect.Effect<A, never> {
): Effect.Effect<A> {
const RETRY_SIGNAL = "wait_for_retry";
const retryIntervalMs = 10;
const maxRetries = Math.max(0, Math.floor(timeoutMs / retryIntervalMs));
@@ -176,11 +176,11 @@ export interface OrchestrationIntegrationHarness {
threadId: string,
predicate: (thread: OrchestrationThread) => boolean,
timeoutMs?: number,
) => Effect.Effect<OrchestrationThread, never>;
) => Effect.Effect<OrchestrationThread>;
readonly waitForDomainEvent: (
predicate: (event: OrchestrationEvent) => boolean,
timeoutMs?: number,
) => Effect.Effect<ReadonlyArray<OrchestrationEvent>, never>;
) => Effect.Effect<ReadonlyArray<OrchestrationEvent>>;
readonly waitForPendingApproval: (
requestId: string,
predicate: (row: {
@@ -189,25 +189,22 @@ 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;
},
never
>;
) => Effect.Effect<{
readonly status: "pending" | "resolved";
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
readonly resolvedAt: string | null;
}>;
readonly waitForReceipt: {
(
predicate: (receipt: OrchestrationRuntimeReceipt) => boolean,
timeoutMs?: number,
): Effect.Effect<OrchestrationRuntimeReceipt, never>;
): Effect.Effect<OrchestrationRuntimeReceipt>;
<Receipt extends OrchestrationRuntimeReceipt>(
predicate: (receipt: OrchestrationRuntimeReceipt) => receipt is Receipt,
timeoutMs?: number,
): Effect.Effect<Receipt, never>;
): Effect.Effect<Receipt>;
};
readonly dispose: Effect.Effect<void, never>;
readonly dispose: Effect.Effect<void>;
}
interface MakeOrchestrationIntegrationHarnessOptions {
@@ -394,7 +391,7 @@ export const makeOrchestrationIntegrationHarness = (
(thread): thread is OrchestrationThread => thread !== null && predicate(thread),
`projected thread '${threadId}'`,
timeoutMs,
) as Effect.Effect<OrchestrationThread, never>;
) as Effect.Effect<OrchestrationThread>;
const waitForDomainEvent: OrchestrationIntegrationHarness["waitForDomainEvent"] = (
predicate,
@@ -438,23 +435,20 @@ 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;
},
never
>;
) as Effect.Effect<{
readonly status: "pending" | "resolved";
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
readonly resolvedAt: string | null;
}>;
function waitForReceipt(
predicate: (receipt: OrchestrationRuntimeReceipt) => boolean,
timeoutMs?: number,
): Effect.Effect<OrchestrationRuntimeReceipt, never>;
): Effect.Effect<OrchestrationRuntimeReceipt>;
function waitForReceipt<Receipt extends OrchestrationRuntimeReceipt>(
predicate: (receipt: OrchestrationRuntimeReceipt) => receipt is Receipt,
timeoutMs?: number,
): Effect.Effect<Receipt, never>;
): Effect.Effect<Receipt>;
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, never>;
}) => Effect.Effect<void>;
}
export type FixtureProviderRuntimeEvent = {
@@ -183,9 +183,7 @@ export interface TestProviderAdapterHarness {
threadId: ThreadId,
response: TestTurnResponse,
) => Effect.Effect<void, ProviderAdapterSessionNotFoundError>;
readonly queueTurnResponseForNextSession: (
response: TestTurnResponse,
) => Effect.Effect<void, never>;
readonly queueTurnResponseForNextSession: (response: TestTurnResponse) => Effect.Effect<void>;
readonly getStartCount: () => number;
readonly getRollbackCalls: (threadId: ThreadId) => ReadonlyArray<number>;
readonly getInterruptCalls: (threadId: ThreadId) => ReadonlyArray<TurnId | undefined>;
@@ -337,7 +335,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 = {
@@ -505,9 +503,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
),
);
const queueTurnResponseForNextSession = (
response: TestTurnResponse,
): Effect.Effect<void, never> =>
const queueTurnResponseForNextSession = (response: TestTurnResponse): Effect.Effect<void> =>
Effect.sync(() => {
queuedResponsesForNextSession.push(response);
});
@@ -58,7 +58,7 @@ function waitForSync<A>(
predicate: (value: A) => boolean,
description: string,
timeoutMs = 10_000,
): Effect.Effect<A, never> {
): Effect.Effect<A> {
return Effect.gen(function* () {
const deadline = Date.now() + timeoutMs;
@@ -226,9 +226,7 @@ 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 === false,
) &&
entry.messages.some((message) => message.role === "assistant" && !message.streaming) &&
entry.checkpoints.length === 1,
);
assert.equal(thread.checkpoints[0]?.status, "ready");
@@ -309,9 +307,7 @@ 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 === false,
),
entry.messages.some((message) => message.role === "assistant" && !message.streaming),
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, never>;
readonly layer: Layer.Layer<ProviderService, unknown>;
}
const makeIntegrationFixture = Effect.gen(function* () {
+2 -3
View File
@@ -20,7 +20,7 @@
"start": "node dist/bin.mjs",
"prepare": "effect-language-service patch",
"typecheck": "tsc --noEmit",
"test": "vitest run"
"test": "vp test run"
},
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.2.77",
@@ -40,9 +40,8 @@
"@t3tools/web": "workspace:*",
"@types/bun": "catalog:",
"@types/node": "catalog:",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
"vite-plus": "catalog:"
},
"engines": {
"node": "^22.16 || ^23.11 || >=24.10"
+103 -102
View File
@@ -122,35 +122,36 @@ const buildCmd = Command.make(
{
verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
},
Effect.fn("buildCmd")(function* (config) {
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
const repoRoot = yield* RepoRoot;
const serverDir = path.join(repoRoot, "apps/server");
(config) =>
Effect.gen(function* () {
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
const repoRoot = yield* RepoRoot;
const serverDir = path.join(repoRoot, "apps/server");
yield* Effect.log("[cli] Running tsdown...");
yield* runCommand(
ChildProcess.make({
cwd: serverDir,
stdout: config.verbose ? "inherit" : "ignore",
stderr: "inherit",
// Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
shell: process.platform === "win32",
})`bun tsdown`,
);
yield* Effect.log("[cli] Running vp pack...");
yield* runCommand(
ChildProcess.make({
cwd: serverDir,
stdout: config.verbose ? "inherit" : "ignore",
stderr: "inherit",
// Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
shell: process.platform === "win32",
})`vp pack`,
);
const webDist = path.join(repoRoot, "apps/web/dist");
const clientTarget = path.join(serverDir, "dist/client");
const webDist = path.join(repoRoot, "apps/web/dist");
const clientTarget = path.join(serverDir, "dist/client");
if (yield* fs.exists(webDist)) {
yield* fs.copy(webDist, clientTarget);
yield* applyDevelopmentIconOverrides(repoRoot, serverDir);
yield* Effect.log("[cli] Bundled web app into dist/client");
} else {
yield* Effect.logWarning("[cli] Web dist not found — skipping client bundle.");
}
}),
).pipe(Command.withDescription("Build the server package (tsdown + bundle web client)."));
if (yield* fs.exists(webDist)) {
yield* fs.copy(webDist, clientTarget);
yield* applyDevelopmentIconOverrides(repoRoot, serverDir);
yield* Effect.log("[cli] Bundled web app into dist/client");
} else {
yield* Effect.logWarning("[cli] Web dist not found — skipping client bundle.");
}
}),
).pipe(Command.withDescription("Build the server package (vp pack + bundle web client)."));
// ---------------------------------------------------------------------------
// publish subcommand
@@ -166,87 +167,87 @@ const publishCmd = Command.make(
dryRun: Flag.boolean("dry-run").pipe(Flag.withDefault(false)),
verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
},
Effect.fn("publishCmd")(function* (config) {
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
const repoRoot = yield* RepoRoot;
const serverDir = path.join(repoRoot, "apps/server");
const packageJsonPath = path.join(serverDir, "package.json");
const backupPath = `${packageJsonPath}.bak`;
(config) =>
Effect.gen(function* () {
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
const repoRoot = yield* RepoRoot;
const serverDir = path.join(repoRoot, "apps/server");
const packageJsonPath = path.join(serverDir, "package.json");
const backupPath = `${packageJsonPath}.bak`;
// Assert build assets exist
for (const relPath of ["dist/index.mjs", "dist/client/index.html"]) {
const abs = path.join(serverDir, relPath);
if (!(yield* fs.exists(abs))) {
return yield* new CliError({
message: `Missing build asset: ${abs}. Run the build subcommand first.`,
});
// Assert build assets exist
for (const relPath of ["dist/index.mjs", "dist/client/index.html"]) {
const abs = path.join(serverDir, relPath);
if (!(yield* fs.exists(abs))) {
return yield* new CliError({
message: `Missing build asset: ${abs}. Run the build subcommand first.`,
});
}
}
}
yield* Effect.acquireUseRelease(
// Acquire: backup package.json, resolve catalog: deps, strip devDependencies/scripts
Effect.fn("publishCmd.acquire")(function* () {
// Resolve catalog dependencies before any file mutations. If this throws,
// acquire fails and no release hook runs, so filesystem must still be untouched.
const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
const pkg = {
name: serverPackageJson.name,
repository: serverPackageJson.repository,
bin: serverPackageJson.bin,
type: serverPackageJson.type,
version,
engines: serverPackageJson.engines,
files: serverPackageJson.files,
dependencies: serverPackageJson.dependencies as Record<string, unknown>,
};
yield* Effect.acquireUseRelease(
// Acquire: backup package.json, resolve catalog: deps, strip devDependencies/scripts
Effect.gen(function* () {
// Resolve catalog dependencies before any file mutations. If this throws,
// acquire fails and no release hook runs, so filesystem must still be untouched.
const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
const pkg = {
name: serverPackageJson.name,
repository: serverPackageJson.repository,
bin: serverPackageJson.bin,
type: serverPackageJson.type,
version,
engines: serverPackageJson.engines,
files: serverPackageJson.files,
dependencies: serverPackageJson.dependencies as Record<string, unknown>,
};
pkg.dependencies = resolveCatalogDependencies(
pkg.dependencies,
rootPackageJson.workspaces.catalog,
"apps/server dependencies",
);
const original = yield* fs.readFileString(packageJsonPath);
yield* fs.writeFileString(backupPath, original);
yield* fs.writeFileString(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`);
yield* Effect.log("[cli] Resolved package.json for publish");
const iconBackups = yield* applyPublishIconOverrides(repoRoot, serverDir);
return { iconBackups };
})(),
// Use: npm publish
() =>
Effect.fn("publishCmd.use")(function* () {
const args = ["publish", "--access", config.access, "--tag", config.tag];
if (config.provenance) args.push("--provenance");
if (config.dryRun) args.push("--dry-run");
yield* Effect.log(`[cli] Running: npm ${args.join(" ")}`);
yield* runCommand(
ChildProcess.make("npm", [...args], {
cwd: serverDir,
stdout: config.verbose ? "inherit" : "ignore",
stderr: "inherit",
// Windows needs shell mode to resolve .cmd shims.
shell: process.platform === "win32",
}),
pkg.dependencies = resolveCatalogDependencies(
pkg.dependencies,
rootPackageJson.catalog,
"apps/server dependencies",
);
})(),
// Release: restore
Effect.fn("publishCmd.release")(function* (resource: {
readonly iconBackups: ReadonlyArray<PublishIconBackup>;
}) {
yield* restorePublishIconOverrides(resource.iconBackups).pipe(
Effect.catch((error) =>
Effect.logError(`[cli] Failed to restore publish icon overrides: ${String(error)}`),
),
);
yield* fs.rename(backupPath, packageJsonPath);
if (config.verbose) yield* Effect.log("[cli] Restored original package.json");
}),
);
}),
const original = yield* fs.readFileString(packageJsonPath);
yield* fs.writeFileString(backupPath, original);
yield* fs.writeFileString(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`);
yield* Effect.log("[cli] Resolved package.json for publish");
const iconBackups = yield* applyPublishIconOverrides(repoRoot, serverDir);
return { iconBackups };
}),
// Use: npm publish
() =>
Effect.gen(function* () {
const args = ["publish", "--access", config.access, "--tag", config.tag];
if (config.provenance) args.push("--provenance");
if (config.dryRun) args.push("--dry-run");
yield* Effect.log(`[cli] Running: npm ${args.join(" ")}`);
yield* runCommand(
ChildProcess.make("npm", [...args], {
cwd: serverDir,
stdout: config.verbose ? "inherit" : "ignore",
stderr: "inherit",
// Windows needs shell mode to resolve .cmd shims.
shell: process.platform === "win32",
}),
);
}),
// Release: restore
(resource: { readonly iconBackups: ReadonlyArray<PublishIconBackup> }) =>
Effect.gen(function* () {
yield* restorePublishIconOverrides(resource.iconBackups).pipe(
Effect.catch((error) =>
Effect.logError(`[cli] Failed to restore publish icon overrides: ${String(error)}`),
),
);
yield* fs.rename(backupPath, packageJsonPath);
if (config.verbose) yield* Effect.log("[cli] Restored original package.json");
}),
);
}),
).pipe(Command.withDescription("Publish the server package to npm."));
// ---------------------------------------------------------------------------
+1 -1
View File
@@ -2,7 +2,7 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { describe, expect, it } from "vite-plus/test";
import {
createAttachmentId,
+1 -1
View File
@@ -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 "vitest";
import { vi } from "vite-plus/test";
import { readBootstrapEnvelope, resolveFdPath } from "./bootstrap";
import { assertNone, assertSome } from "@effect/vitest/utils";
+1 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it } from "vite-plus/test";
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 "vitest";
import { describe, expect, it } from "vite-plus/test";
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
import { checkpointRefForThreadTurn } from "../Utils.ts";
@@ -21,8 +21,8 @@ const make = Effect.gen(function* () {
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const checkpointStore = yield* CheckpointStore;
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = Effect.fn("getTurnDiff")(
function* (input) {
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = (input) =>
Effect.gen(function* () {
const operation = "CheckpointDiffQuery.getTurnDiff";
if (input.fromTurnCount === input.toTurnCount) {
@@ -149,8 +149,7 @@ const make = Effect.gen(function* () {
}
return turnDiff;
},
);
});
const getFullThreadDiff: CheckpointDiffQueryShape["getFullThreadDiff"] = (
input: OrchestrationGetFullThreadDiffInput,
@@ -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 "vitest";
import { describe, expect } from "vite-plus/test";
import { checkpointRefForThreadTurn } from "../Utils.ts";
import { CheckpointStoreLive } from "./CheckpointStore.ts";
@@ -86,140 +86,139 @@ const makeCheckpointStore = Effect.gen(function* () {
Effect.catch(() => Effect.succeed(false)),
);
const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = Effect.fn(
"captureCheckpoint",
)(function* (input) {
const operation = "CheckpointStore.captureCheckpoint";
const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = (input) =>
Effect.gen(function* () {
const operation = "CheckpointStore.captureCheckpoint";
yield* Effect.acquireUseRelease(
fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }),
Effect.fn("captureCheckpoint.withTempDirectory")(function* (tempDir) {
const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
const commitEnv: NodeJS.ProcessEnv = {
...process.env,
GIT_INDEX_FILE: tempIndexPath,
GIT_AUTHOR_NAME: "T3 Code",
GIT_AUTHOR_EMAIL: "[email protected]",
GIT_COMMITTER_NAME: "T3 Code",
GIT_COMMITTER_EMAIL: "[email protected]",
};
yield* Effect.acquireUseRelease(
fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }),
(tempDir) =>
Effect.gen(function* () {
const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
const commitEnv: NodeJS.ProcessEnv = {
...process.env,
GIT_INDEX_FILE: tempIndexPath,
GIT_AUTHOR_NAME: "T3 Code",
GIT_AUTHOR_EMAIL: "[email protected]",
GIT_COMMITTER_NAME: "T3 Code",
GIT_COMMITTER_EMAIL: "[email protected]",
};
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* git.execute({
operation,
cwd: input.cwd,
args: ["read-tree", "HEAD"],
env: commitEnv,
});
}
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* git.execute({
operation,
cwd: input.cwd,
args: ["read-tree", "HEAD"],
env: commitEnv,
});
}
yield* git.execute({
operation,
cwd: input.cwd,
args: ["add", "-A", "--", "."],
env: commitEnv,
});
yield* git.execute({
operation,
cwd: input.cwd,
args: ["add", "-A", "--", "."],
env: commitEnv,
});
const writeTreeResult = yield* git.execute({
operation,
cwd: input.cwd,
args: ["write-tree"],
env: commitEnv,
});
const treeOid = writeTreeResult.stdout.trim();
if (treeOid.length === 0) {
return yield* new GitCommandError({
operation,
command: "git write-tree",
cwd: input.cwd,
detail: "git write-tree returned an empty tree oid.",
});
}
const writeTreeResult = yield* git.execute({
operation,
cwd: input.cwd,
args: ["write-tree"],
env: commitEnv,
});
const treeOid = writeTreeResult.stdout.trim();
if (treeOid.length === 0) {
return yield* new GitCommandError({
operation,
command: "git write-tree",
cwd: input.cwd,
detail: "git write-tree returned an empty tree oid.",
});
}
const message = `t3 checkpoint ref=${input.checkpointRef}`;
const commitTreeResult = yield* git.execute({
operation,
cwd: input.cwd,
args: ["commit-tree", treeOid, "-m", message],
env: commitEnv,
});
const commitOid = commitTreeResult.stdout.trim();
if (commitOid.length === 0) {
return yield* new GitCommandError({
operation,
command: "git commit-tree",
cwd: input.cwd,
detail: "git commit-tree returned an empty commit oid.",
});
}
const message = `t3 checkpoint ref=${input.checkpointRef}`;
const commitTreeResult = yield* git.execute({
operation,
cwd: input.cwd,
args: ["commit-tree", treeOid, "-m", message],
env: commitEnv,
});
const commitOid = commitTreeResult.stdout.trim();
if (commitOid.length === 0) {
return yield* new GitCommandError({
operation,
command: "git commit-tree",
cwd: input.cwd,
detail: "git commit-tree returned an empty commit oid.",
});
}
yield* git.execute({
operation,
cwd: input.cwd,
args: ["update-ref", input.checkpointRef, commitOid],
});
}),
(tempDir) => fs.remove(tempDir, { recursive: true }),
).pipe(
Effect.catchTags({
PlatformError: (error) =>
Effect.fail(
new CheckpointInvariantError({
operation: "CheckpointStore.captureCheckpoint",
detail: "Failed to capture checkpoint.",
cause: error,
}),
),
}),
);
});
yield* git.execute({
operation,
cwd: input.cwd,
args: ["update-ref", input.checkpointRef, commitOid],
});
}),
(tempDir) => fs.remove(tempDir, { recursive: true }),
).pipe(
Effect.catchTags({
PlatformError: (error) =>
Effect.fail(
new CheckpointInvariantError({
operation: "CheckpointStore.captureCheckpoint",
detail: "Failed to capture checkpoint.",
cause: error,
}),
),
}),
);
});
const hasCheckpointRef: CheckpointStoreShape["hasCheckpointRef"] = (input) =>
resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
Effect.map((commit) => commit !== null),
);
const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = Effect.fn(
"restoreCheckpoint",
)(function* (input) {
const operation = "CheckpointStore.restoreCheckpoint";
const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = (input) =>
Effect.gen(function* () {
const operation = "CheckpointStore.restoreCheckpoint";
let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
if (!commitOid && input.fallbackToHead === true) {
commitOid = yield* resolveHeadCommit(input.cwd);
}
if (!commitOid && input.fallbackToHead === true) {
commitOid = yield* resolveHeadCommit(input.cwd);
}
if (!commitOid) {
return false;
}
if (!commitOid) {
return false;
}
yield* git.execute({
operation,
cwd: input.cwd,
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
});
yield* git.execute({
operation,
cwd: input.cwd,
args: ["clean", "-fd", "--", "."],
});
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* git.execute({
operation,
cwd: input.cwd,
args: ["reset", "--quiet", "--", "."],
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
});
yield* git.execute({
operation,
cwd: input.cwd,
args: ["clean", "-fd", "--", "."],
});
}
return true;
});
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* git.execute({
operation,
cwd: input.cwd,
args: ["reset", "--quiet", "--", "."],
});
}
const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = Effect.fn("diffCheckpoints")(
function* (input) {
return true;
});
const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = (input) =>
Effect.gen(function* () {
const operation = "CheckpointStore.diffCheckpoints";
let fromCommitOid = yield* resolveCheckpointCommit(input.cwd, input.fromCheckpointRef);
@@ -248,26 +247,24 @@ const makeCheckpointStore = Effect.gen(function* () {
});
return result.stdout;
},
);
});
const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = Effect.fn(
"deleteCheckpointRefs",
)(function* (input) {
const operation = "CheckpointStore.deleteCheckpointRefs";
const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = (input) =>
Effect.gen(function* () {
const operation = "CheckpointStore.deleteCheckpointRefs";
yield* Effect.forEach(
input.checkpointRefs,
(checkpointRef) =>
git.execute({
operation,
cwd: input.cwd,
args: ["update-ref", "-d", checkpointRef],
allowNonZeroExit: true,
}),
{ discard: true },
);
});
yield* Effect.forEach(
input.checkpointRefs,
(checkpointRef) =>
git.execute({
operation,
cwd: input.cwd,
args: ["update-ref", "-d", checkpointRef],
allowNonZeroExit: true,
}),
{ discard: true },
);
});
return {
isGitRepository,
@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from "vitest";
import { describe, expect, it, vi } from "vite-plus/test";
import { randomUUID } from "node:crypto";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import os from "node:os";
+1 -1
View File
@@ -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, never>) => Promise<unknown>;
private runPromise: (effect: Effect.Effect<unknown>) => 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 "vitest";
import { expect } from "vite-plus/test";
import { ServerConfig } from "../../config.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
+116 -110
View File
@@ -66,7 +66,7 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
* Spawn the Claude CLI with structured JSON output and return the parsed,
* schema-validated result.
*/
const runClaudeJson = Effect.fn("runClaudeJson")(function* <S extends Schema.Top>({
const runClaudeJson = <S extends Schema.Top>({
operation,
cwd,
prompt,
@@ -82,126 +82,132 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
prompt: string;
outputSchemaJson: S;
modelSelection: ClaudeModelSelection;
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
const normalizedOptions = normalizeClaudeModelOptionsWithCapabilities(
getClaudeModelCapabilities(modelSelection.model),
modelSelection.options,
);
const settings = {
...(typeof normalizedOptions?.thinking === "boolean"
? { alwaysThinkingEnabled: normalizedOptions.thinking }
: {}),
...(normalizedOptions?.fastMode ? { fastMode: true } : {}),
};
const claudeSettings = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => settings.providers.claudeAgent,
).pipe(Effect.catch(() => Effect.undefined));
const runClaudeCommand = Effect.fn("runClaudeJson.runClaudeCommand")(function* () {
const command = ChildProcess.make(
claudeSettings?.binaryPath || "claude",
[
"-p",
"--output-format",
"json",
"--json-schema",
jsonSchemaStr,
"--model",
resolveApiModelId(modelSelection),
...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []),
...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []),
"--dangerously-skip-permissions",
],
{
cwd,
shell: process.platform === "win32",
stdin: {
stream: Stream.encodeText(Stream.make(prompt)),
},
},
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
Effect.gen(function* () {
const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
const normalizedOptions = normalizeClaudeModelOptionsWithCapabilities(
getClaudeModelCapabilities(modelSelection.model),
modelSelection.options,
);
const settings = {
...(typeof normalizedOptions?.thinking === "boolean"
? { alwaysThinkingEnabled: normalizedOptions.thinking }
: {}),
...(normalizedOptions?.fastMode ? { fastMode: true } : {}),
};
const child = yield* commandSpawner
.spawn(command)
.pipe(
Effect.mapError((cause) =>
normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"),
),
const claudeSettings = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => settings.providers.claudeAgent,
).pipe(Effect.catch(() => Effect.undefined));
const runClaudeCommand = Effect.gen(function* () {
const command = ChildProcess.make(
claudeSettings?.binaryPath || "claude",
[
"-p",
"--output-format",
"json",
"--json-schema",
jsonSchemaStr,
"--model",
resolveApiModelId(modelSelection),
...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []),
...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []),
"--dangerously-skip-permissions",
],
{
cwd,
shell: process.platform === "win32",
stdin: {
stream: Stream.encodeText(Stream.make(prompt)),
},
},
);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
readStreamAsString(operation, child.stdout),
readStreamAsString(operation, child.stderr),
child.exitCode.pipe(
const child = yield* commandSpawner
.spawn(command)
.pipe(
Effect.mapError((cause) =>
normalizeCliError("claude", operation, cause, "Failed to read Claude CLI exit code"),
normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"),
),
),
],
{ concurrency: "unbounded" },
);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
readStreamAsString(operation, child.stdout),
readStreamAsString(operation, child.stderr),
child.exitCode.pipe(
Effect.mapError((cause) =>
normalizeCliError(
"claude",
operation,
cause,
"Failed to read Claude CLI exit code",
),
),
),
],
{ concurrency: "unbounded" },
);
if (exitCode !== 0) {
const stderrDetail = stderr.trim();
const stdoutDetail = stdout.trim();
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
return yield* new TextGenerationError({
operation,
detail:
detail.length > 0
? `Claude CLI command failed: ${detail}`
: `Claude CLI command failed with code ${exitCode}.`,
});
}
return stdout;
});
const rawStdout = yield* runClaudeCommand.pipe(
Effect.scoped,
Effect.timeoutOption(CLAUDE_TIMEOUT_MS),
Effect.flatMap(
Option.match({
onNone: () =>
Effect.fail(
new TextGenerationError({ operation, detail: "Claude CLI request timed out." }),
),
onSome: (value) => Effect.succeed(value),
}),
),
);
if (exitCode !== 0) {
const stderrDetail = stderr.trim();
const stdoutDetail = stdout.trim();
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
return yield* new TextGenerationError({
operation,
detail:
detail.length > 0
? `Claude CLI command failed: ${detail}`
: `Claude CLI command failed with code ${exitCode}.`,
});
}
const envelope = yield* Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope))(
rawStdout,
).pipe(
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
operation,
detail: "Claude CLI returned unexpected output format.",
cause,
}),
),
),
);
return stdout;
return yield* Schema.decodeEffect(outputSchemaJson)(envelope.structured_output).pipe(
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
operation,
detail: "Claude returned invalid structured output.",
cause,
}),
),
),
);
});
const rawStdout = yield* runClaudeCommand().pipe(
Effect.scoped,
Effect.timeoutOption(CLAUDE_TIMEOUT_MS),
Effect.flatMap(
Option.match({
onNone: () =>
Effect.fail(
new TextGenerationError({ operation, detail: "Claude CLI request timed out." }),
),
onSome: (value) => Effect.succeed(value),
}),
),
);
const envelope = yield* Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope))(
rawStdout,
).pipe(
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
operation,
detail: "Claude CLI returned unexpected output format.",
cause,
}),
),
),
);
return yield* Schema.decodeEffect(outputSchemaJson)(envelope.structured_output).pipe(
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
operation,
detail: "Claude returned invalid structured output.",
cause,
}),
),
),
);
});
// ---------------------------------------------------------------------------
// TextGenerationShape methods
// ---------------------------------------------------------------------------
@@ -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 "vitest";
import { expect } from "vite-plus/test";
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, never> =>
const safeUnlink = (filePath: string): Effect.Effect<void> =>
fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
const materializeImageAttachments = (
+2 -2
View File
@@ -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 "vitest";
import { describe, expect, vi } from "vite-plus/test";
import { GitCoreLive, makeGitCore } from "./GitCore.ts";
import { GitCore, type GitCoreShape } from "../Services/GitCore.ts";
@@ -432,7 +432,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 === false)).toBe(true);
expect(result.branches.every((b) => !b.isDefault)).toBe(true);
}),
);
+2 -2
View File
@@ -324,7 +324,7 @@ function toGitCommandError(
interface Trace2Monitor {
readonly env: NodeJS.ProcessEnv;
readonly flush: Effect.Effect<void, never>;
readonly flush: Effect.Effect<void>;
}
function trace2ChildKey(record: Record<string, unknown>): string | null {
@@ -488,7 +488,7 @@ const collectOutput = Effect.fn("collectOutput")(function* <E>(
stream: Stream.Stream<Uint8Array, E>,
maxOutputBytes: number,
truncateOutputAtMaxBytes: boolean,
onLine: ((line: string) => Effect.Effect<void, never>) | undefined,
onLine: ((line: string) => Effect.Effect<void>) | undefined,
): Effect.fn.Return<{ readonly text: string; readonly truncated: boolean }, GitCommandError> {
const decoder = new TextDecoder();
let bytes = 0;
+1 -1
View File
@@ -1,6 +1,6 @@
import { assert, it } from "@effect/vitest";
import { Effect } from "effect";
import { afterEach, expect, vi } from "vitest";
import { afterEach, expect, vi } from "vite-plus/test";
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 "vitest";
import { expect } from "vite-plus/test";
import type { GitActionProgressEvent, ModelSelection } from "@t3tools/contracts";
import { GitCommandError, GitHubCliError, TextGenerationError } from "@t3tools/contracts";
+1 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it } from "vite-plus/test";
import {
buildBranchNamePrompt,
+7 -7
View File
@@ -55,27 +55,27 @@ export interface GitPreparedCommitContext {
}
export interface ExecuteGitProgress {
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 onStdoutLine?: (line: string) => Effect.Effect<void>;
readonly onStderrLine?: (line: string) => Effect.Effect<void>;
readonly onHookStarted?: (hookName: string) => Effect.Effect<void>;
readonly onHookFinished?: (input: {
hookName: string;
exitCode: number | null;
durationMs: number | null;
}) => Effect.Effect<void, never>;
}) => Effect.Effect<void>;
}
export interface GitCommitProgress {
readonly onOutputLine?: (input: {
stream: "stdout" | "stderr";
text: string;
}) => Effect.Effect<void, never>;
readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
}) => Effect.Effect<void>;
readonly onHookStarted?: (hookName: string) => Effect.Effect<void>;
readonly onHookFinished?: (input: {
hookName: string;
exitCode: number | null;
durationMs: number | null;
}) => Effect.Effect<void, never>;
}) => Effect.Effect<void>;
}
export interface GitCommitOptions {
+1 -1
View File
@@ -22,7 +22,7 @@ import type { Effect } from "effect";
import type { GitManagerServiceError } from "@t3tools/contracts";
export interface GitActionProgressReporter {
readonly publish: (event: GitActionProgressEvent) => Effect.Effect<void, never>;
readonly publish: (event: GitActionProgressEvent) => Effect.Effect<void>;
}
export interface GitRunStackedActionOptions {
+1 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it } from "vite-plus/test";
import { inferImageExtension, parseBase64DataUrl } from "./imageMime.ts";
+1 -20
View File
@@ -31,15 +31,6 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
args: ["/tmp/workspace"],
});
const traeLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "trae" },
"darwin",
);
assert.deepEqual(traeLaunch, {
command: "trae",
args: ["/tmp/workspace"],
});
const vscodeLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "vscode" },
"darwin",
@@ -98,15 +89,6 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
const traeLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "trae" },
"darwin",
);
assert.deepEqual(traeLineAndColumn, {
command: "trae",
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
const vscodeLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
"darwin",
@@ -274,7 +256,6 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editors-" });
yield* fs.writeFileString(path.join(dir, "trae.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "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");
@@ -282,7 +263,7 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
});
assert.deepEqual(editors, ["trae", "vscode-insiders", "vscodium", "file-manager"]);
assert.deepEqual(editors, ["vscode-insiders", "vscodium", "file-manager"]);
}),
);
});
@@ -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 "vitest";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { CheckpointStoreLive } from "../../checkpointing/Layers/CheckpointStore.ts";
import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts";
@@ -70,7 +70,7 @@ function createProviderServiceHarness(
);
const unsupported = <A>() =>
Effect.die(new Error("Unsupported provider call in test")) as Effect.Effect<A, never>;
Effect.die(new Error("Unsupported provider call in test")) as Effect.Effect<A>;
const listSessions = () =>
hasSession
? Effect.succeed([
@@ -748,7 +748,7 @@ const make = Effect.gen(function* () {
const processInput = (
input: ReactorInput,
): Effect.Effect<void, CheckpointStoreError | OrchestrationDispatchError, never> =>
): Effect.Effect<void, CheckpointStoreError | OrchestrationDispatchError> =>
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 "vitest";
import { describe, expect, it } from "vite-plus/test";
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 "vitest";
import { afterEach, describe, expect, it } from "vite-plus/test";
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 "vitest";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { deriveServerPaths, ServerConfig } from "../../config.ts";
import { TextGenerationError } from "@t3tools/contracts";
@@ -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 "vitest";
import { afterEach, describe, expect, it } from "vite-plus/test";
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
@@ -1626,8 +1626,7 @@ describe("ProviderRuntimeIngestion", () => {
return false;
}
return (
event.payload.messageId === "assistant:item-complete-dedup" &&
event.payload.streaming === false
event.payload.messageId === "assistant:item-complete-dedup" && !event.payload.streaming
);
});
expect(completionEvents).toHaveLength(1);
@@ -30,7 +30,7 @@ export interface OrchestrationEngineShape {
*
* @returns Effect containing the latest read model.
*/
readonly getReadModel: () => Effect.Effect<OrchestrationReadModel, never, never>;
readonly getReadModel: () => Effect.Effect<OrchestrationReadModel, 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, never>;
) => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError>;
/**
* Dispatch a validated orchestration command.
@@ -53,7 +53,7 @@ export interface OrchestrationEngineShape {
*/
readonly dispatch: (
command: OrchestrationCommand,
) => Effect.Effect<{ sequence: number }, OrchestrationDispatchError, never>;
) => Effect.Effect<{ sequence: number }, OrchestrationDispatchError>;
/**
* Stream persisted domain events in dispatch order.
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it } from "vite-plus/test";
import {
MessageId,
CommandId,
@@ -6,7 +6,7 @@ import {
ProjectId,
ThreadId,
} from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { describe, expect, it } from "vite-plus/test";
import { Effect } from "effect";
import { decideOrchestrationCommand } from "./decider.ts";
+1 -1
View File
@@ -679,7 +679,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
default: {
command satisfies never;
const fallback = command as never as { type: string };
const fallback = command 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 "vitest";
import { describe, expect, it } from "vite-plus/test";
import { createEmptyReadModel, projectEvent } from "./projector.ts";
+1 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from "vitest";
import { describe, expect, it, vi } from "vite-plus/test";
import { fixPath } from "./os-jank";
+13 -14
View File
@@ -92,20 +92,19 @@ export interface RunMigrationsOptions {
*
* @returns Effect containing array of executed migrations
*/
export const runMigrations = Effect.fn("runMigrations")(function* ({
toMigrationInclusive,
}: RunMigrationsOptions = {}) {
yield* Effect.log(
toMigrationInclusive === undefined
? "Running all migrations..."
: `Running migrations 1 through ${toMigrationInclusive}...`,
);
const executedMigrations = yield* run({ loader: makeMigrationLoader(toMigrationInclusive) });
yield* Effect.log("Migrations ran successfully").pipe(
Effect.annotateLogs({ migrations: executedMigrations.map(([id, name]) => `${id}_${name}`) }),
);
return executedMigrations;
});
export const runMigrations = ({ toMigrationInclusive }: RunMigrationsOptions = {}) =>
Effect.gen(function* () {
yield* Effect.log(
toMigrationInclusive === undefined
? "Running all migrations..."
: `Running migrations 1 through ${toMigrationInclusive}...`,
);
const executedMigrations = yield* run({ loader: makeMigrationLoader(toMigrationInclusive) });
yield* Effect.log("Migrations ran successfully").pipe(
Effect.annotateLogs({ migrations: executedMigrations.map(([id, name]) => `${id}_${name}`) }),
);
return executedMigrations;
});
/**
* Layer that runs migrations when the layer is built.
+1 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it } from "vite-plus/test";
import { runProcess } from "./processRunner";
@@ -2137,7 +2137,7 @@ describe("ClaudeAdapterLive", () => {
});
const permissionResult = yield* Effect.promise(() => permissionPromise);
assert.equal((permissionResult as PermissionResult).behavior, "allow");
assert.equal(permissionResult.behavior, "allow");
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
@@ -2626,7 +2626,7 @@ describe("ClaudeAdapterLive", () => {
});
const permissionResult = yield* Effect.promise(() => permissionPromise);
assert.equal((permissionResult as PermissionResult).behavior, "deny");
assert.equal(permissionResult.behavior, "deny");
const deniedResult = permissionResult as PermissionResult & {
message?: string;
};
@@ -2820,7 +2820,7 @@ describe("ClaudeAdapterLive", () => {
// The canUseTool promise should resolve with the answers in SDK format.
const permissionResult = yield* Effect.promise(() => permissionPromise);
assert.equal((permissionResult as PermissionResult).behavior, "allow");
assert.equal(permissionResult.behavior, "allow");
const updatedInput = (permissionResult as { updatedInput: Record<string, unknown> })
.updatedInput;
assert.deepEqual(updatedInput.answers, { "Which framework?": "React" });
@@ -2892,7 +2892,7 @@ describe("ClaudeAdapterLive", () => {
yield* Stream.runHead(adapter.streamEvents);
const permissionResult = yield* Effect.promise(() => permissionPromise);
assert.equal((permissionResult as PermissionResult).behavior, "allow");
assert.equal(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 === false &&
!result.is_error &&
(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, never>;
let streamFiber: Fiber.Fiber<void>;
streamFiber = runFork(
Effect.exit(runSdkStream(context)).pipe(
Effect.flatMap((exit) => {
@@ -1364,7 +1364,7 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
if (options?.manager) {
return options.manager;
}
const services = yield* Effect.services<never>();
const services = yield* Effect.services();
return options?.makeManager?.(services) ?? new CodexAppServerManager(services);
});
@@ -1583,7 +1583,7 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
});
const registerListener = Effect.fn("registerListener")(function* () {
const services = yield* Effect.services<never>();
const services = yield* Effect.services();
const listenerEffect = Effect.fn("listener")(function* (event: ProviderEvent) {
yield* writeNativeEvent(event);
const runtimeEvents = mapToRuntimeEvents(event, event.threadId);
@@ -15,12 +15,12 @@ export interface AnalyticsServiceShape {
readonly record: (
event: string,
properties?: Readonly<Record<string, unknown>>,
) => Effect.Effect<void, never>;
) => Effect.Effect<void>;
/**
* Flush queued telemetry.
*/
readonly flush: Effect.Effect<void, never>;
readonly flush: Effect.Effect<void>;
}
export class AnalyticsService extends ServiceMap.Service<AnalyticsService, AnalyticsServiceShape>()(
@@ -22,7 +22,7 @@ import {
Scope,
} from "effect";
import { TestClock } from "effect/testing";
import { expect } from "vitest";
import { expect } from "vite-plus/test";
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 === true),
events.some((event) => event.type === "activity" && event.hasRunningSubprocess),
),
"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 === false),
events.some((event) => event.type === "activity" && !event.hasRunningSubprocess),
),
"1200 millis",
);
+6 -6
View File
@@ -130,7 +130,7 @@ type DrainProcessEventAction =
interface TerminalManagerState {
sessions: Map<string, TerminalSessionState>;
killFibers: Map<PtyProcess, Fiber.Fiber<void, never>>;
killFibers: Map<PtyProcess, Fiber.Fiber<void>>;
}
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, never>> = yield* modifyManagerState<
Option.Option<Fiber.Fiber<void, never>>
const fiber: Option.Option<Fiber.Fiber<void>> = yield* modifyManagerState<
Option.Option<Fiber.Fiber<void>>
>((state) => {
const existing: Option.Option<Fiber.Fiber<void, never>> = Option.fromNullishOr(
const existing: Option.Option<Fiber.Fiber<void>> = Option.fromNullishOr(
state.killFibers.get(process),
);
if (Option.isNone(existing)) {
return [Option.none<Fiber.Fiber<void, never>>(), state] as const;
return [Option.none<Fiber.Fiber<void>>(), 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, never>,
fiber: Fiber.Fiber<void>,
) {
yield* modifyManagerState((state) => {
const killFibers = new Map(state.killFibers);
@@ -228,10 +228,7 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
onNone: () => Effect.succeed(false),
});
const filterGitIgnoredPaths = (
cwd: string,
relativePaths: string[],
): Effect.Effect<string[], never> =>
const filterGitIgnoredPaths = (cwd: string, relativePaths: string[]): Effect.Effect<string[]> =>
Option.match(gitOption, {
onSome: (git) =>
git.filterIgnoredPaths(cwd, relativePaths).pipe(
+1 -1
View File
@@ -21,5 +21,5 @@
}
]
},
"include": ["src", "tsdown.config.ts", "scripts", "integration", "../../scripts/lib"]
"include": ["src", "vite.config.ts", "scripts", "integration", "../../scripts/lib"]
}
-17
View File
@@ -1,17 +0,0 @@
import { defineConfig } from "tsdown";
export default defineConfig({
entry: ["src/bin.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",
},
});
-11
View File
@@ -1,11 +0,0 @@
{
"$schema": "https://turbo.build/schema.json",
"extends": ["//"],
"tasks": {
"start": {
"dependsOn": ["build"],
"cache": false,
"persistent": true,
},
},
}
+27
View File
@@ -0,0 +1,27 @@
import { defineConfig } from "vite-plus";
export default defineConfig({
resolve: {
tsconfigPaths: true,
},
pack: {
entry: ["src/bin.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: {
fileParallelism: false,
testTimeout: 60_000,
hookTimeout: 60_000,
},
});
-18
View File
@@ -1,18 +0,0 @@
import { defineConfig, mergeConfig } from "vitest/config";
import baseConfig from "../../vitest.config";
export default mergeConfig(
baseConfig,
defineConfig({
test: {
// The server suite exercises sqlite, git, temp worktrees, and orchestration
// runtimes heavily. Running files in parallel introduces load-sensitive flakes.
fileParallelism: false,
// Server integration tests exercise sqlite, git, and orchestration together.
// Under package-wide parallel runs they regularly exceed the default 15s budget.
testTimeout: 60_000,
hookTimeout: 60_000,
},
}),
);
+7 -8
View File
@@ -4,13 +4,14 @@
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"dev": "vp dev",
"build": "vp build",
"prepare": "effect-language-service patch",
"preview": "vite preview",
"preview": "vp preview",
"typecheck": "tsc --noEmit",
"test": "vitest run --passWithNoTests",
"test:browser": "vitest run --config vitest.browser.config.ts",
"test": "vp test run --passWithNoTests",
"test:browser": "vp test run --project browser",
"test:unit": "vp test run --project unit",
"test:browser:install": "playwright install --with-deps chromium"
},
"dependencies": {
@@ -51,14 +52,12 @@
"@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": "^8.0.0",
"vitest": "catalog:",
"vite-plus": "catalog:",
"vitest-browser-react": "^2.0.5"
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it } from "vite-plus/test";
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 "vitest";
import { describe, expect, it } from "vite-plus/test";
import {
dedupeRemoteBranchesWithLocalMatches,
deriveLocalBranchNameFromRemoteRef,
+44 -66
View File
@@ -19,8 +19,17 @@ import {
import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
import { HttpResponse, http, ws } from "msw";
import { setupWorker } from "msw/browser";
import { page } from "vitest/browser";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { page } from "vite-plus/test/browser";
import {
afterAll,
afterEach,
beforeAll,
beforeEach,
describe,
expect,
it,
vi,
} from "vite-plus/test";
import { render } from "vitest-browser-react";
import { useComposerDraftStore } from "../composerDraftStore";
@@ -905,12 +914,30 @@ async function triggerChatNewShortcutUntilPath(
async function waitForNewThreadShortcutLabel(): Promise<void> {
const newThreadButton = page.getByTestId("new-thread-button");
await expect.element(newThreadButton).toBeInTheDocument();
await waitForLocatorVisible(newThreadButton);
await newThreadButton.hover();
const shortcutLabel = isMacPlatform(navigator.platform)
? "New thread (⇧⌘O)"
: "New thread (Ctrl+Shift+O)";
await expect.element(page.getByText(shortcutLabel)).toBeInTheDocument();
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 },
);
}
async function waitForImagesToLoad(scope: ParentNode): Promise<void> {
@@ -1309,7 +1336,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
});
try {
await expect.element(page.getByText("No threads yet")).toBeInTheDocument();
await waitForLocatorVisible(page.getByText("No threads yet"));
} finally {
await mounted.cleanup();
}
@@ -1407,52 +1434,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("opens the project cwd with Trae when it is the only available editor", async () => {
setDraftThreadWithoutWorktree();
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createDraftOnlySnapshot(),
configureFixture: (nextFixture) => {
nextFixture.serverConfig = {
...nextFixture.serverConfig,
availableEditors: ["trae"],
};
},
});
try {
await waitForServerConfigToApply();
const openButton = await waitForElement(
() =>
Array.from(document.querySelectorAll("button")).find(
(button) => button.textContent?.trim() === "Open",
) as HTMLButtonElement | null,
"Unable to find Open button.",
);
await vi.waitFor(() => {
expect(openButton.disabled).toBe(false);
});
openButton.click();
await vi.waitFor(
() => {
const openRequest = wsRequests.find(
(request) => request._tag === WS_METHODS.shellOpenInEditor,
);
expect(openRequest).toMatchObject({
_tag: WS_METHODS.shellOpenInEditor,
cwd: "/repo/project",
editor: "trae",
});
},
{ timeout: 8_000, interval: 16 },
);
} finally {
await mounted.cleanup();
}
});
it("filters the open picker menu and opens VSCodium from the menu", async () => {
setDraftThreadWithoutWorktree();
@@ -2105,7 +2086,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
try {
const threadRow = page.getByTestId(`thread-row-${THREAD_ID}`);
await expect.element(threadRow).toBeInTheDocument();
await waitForLocatorVisible(threadRow);
const archiveButton = await waitForElement(
() =>
document.querySelector<HTMLButtonElement>(`[data-testid="thread-archive-${THREAD_ID}"]`),
@@ -2158,16 +2139,15 @@ describe("ChatView timeline estimator parity (full app)", () => {
try {
const threadRow = page.getByTestId(`thread-row-${THREAD_ID}`);
await expect.element(threadRow).toBeInTheDocument();
await waitForLocatorVisible(threadRow);
await threadRow.hover();
const archiveButton = page.getByTestId(`thread-archive-${THREAD_ID}`);
await expect.element(archiveButton).toBeInTheDocument();
await waitForLocatorVisible(archiveButton);
await archiveButton.click();
const confirmButton = page.getByTestId(`thread-archive-confirm-${THREAD_ID}`);
await expect.element(confirmButton).toBeInTheDocument();
await expect.element(confirmButton).toBeVisible();
await waitForLocatorVisible(confirmButton);
} finally {
localStorage.removeItem("t3code:client-settings:v1");
await mounted.cleanup();
@@ -2186,7 +2166,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 expect.element(newThreadButton).toBeInTheDocument();
await waitForLocatorVisible(newThreadButton);
await newThreadButton.click();
@@ -2214,10 +2194,8 @@ describe("ChatView timeline estimator parity (full app)", () => {
);
// The empty thread view and composer should still be visible.
await expect
.element(page.getByText("Send a message to start the conversation."))
.toBeInTheDocument();
await expect.element(page.getByTestId("composer-editor")).toBeInTheDocument();
await waitForLocatorVisible(page.getByText("Send a message to start the conversation."));
await waitForLocatorVisible(page.getByTestId("composer-editor"));
} finally {
await mounted.cleanup();
}
@@ -2248,7 +2226,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
try {
const newThreadButton = page.getByTestId("new-thread-button");
await expect.element(newThreadButton).toBeInTheDocument();
await waitForLocatorVisible(newThreadButton);
await newThreadButton.click();
@@ -2301,7 +2279,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
try {
const newThreadButton = page.getByTestId("new-thread-button");
await expect.element(newThreadButton).toBeInTheDocument();
await waitForLocatorVisible(newThreadButton);
await newThreadButton.click();
@@ -2341,7 +2319,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
try {
const newThreadButton = page.getByTestId("new-thread-button");
await expect.element(newThreadButton).toBeInTheDocument();
await waitForLocatorVisible(newThreadButton);
await newThreadButton.click();
@@ -2383,7 +2361,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
try {
const newThreadButton = page.getByTestId("new-thread-button");
await expect.element(newThreadButton).toBeInTheDocument();
await waitForLocatorVisible(newThreadButton);
await newThreadButton.click();
@@ -2520,7 +2498,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
try {
const newThreadButton = page.getByTestId("new-thread-button");
await expect.element(newThreadButton).toBeInTheDocument();
await waitForLocatorVisible(newThreadButton);
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 "vitest";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { useStore } from "../store";
import {
+3 -5
View File
@@ -1842,9 +1842,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
handleInteractionModeChange(interactionMode === "plan" ? "default" : "plan");
}, [handleInteractionModeChange, interactionMode]);
const toggleRuntimeMode = useCallback(() => {
void handleRuntimeModeChange(
runtimeMode === "full-access" ? "approval-required" : "full-access",
);
handleRuntimeModeChange(runtimeMode === "full-access" ? "approval-required" : "full-access");
}, [handleRuntimeModeChange, runtimeMode]);
const togglePlanSidebar = useCallback(() => {
setPlanSidebarOpen((open) => {
@@ -3560,7 +3558,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
}
return;
}
void handleInteractionModeChange(item.command === "plan" ? "plan" : "default");
handleInteractionModeChange(item.command === "plan" ? "plan" : "default");
const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", {
expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd),
});
@@ -4136,7 +4134,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
size="sm"
type="button"
onClick={() =>
void handleRuntimeModeChange(
handleRuntimeModeChange(
runtimeMode === "full-access"
? "approval-required"
: "full-access",
+1 -1
View File
@@ -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 as MouseEvent;
const nativeEvent = event.nativeEvent;
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 "vitest";
import { assert, describe, it } from "vite-plus/test";
import {
buildGitActionProgressStages,
buildMenuItems,
-14
View File
@@ -20,20 +20,6 @@ export const CursorIcon: Icon = (props) => (
</svg>
);
export const TraeIcon: Icon = (props) => (
<svg {...props} viewBox="0 0 24 24" fill="currentColor">
{/* Back rectangle: left strip + bottom strip drawn separately — empty bottom-left corner is the gap between them */}
<rect x="1" y="4" width="3" height="14" />
<rect x="4" y="18" width="18" height="3" />
{/* Front frame: top bar + right bar only — left and bottom are replaced by the back strips above */}
<rect x="4" y="4" width="18" height="3" />
<rect x="19" y="7" width="3" height="11" />
{/* Two diamonds, offset slightly to the right within the open area */}
<path d="M11 10L13 12L11 14L9 12Z" />
<path d="M16 10L18 12L16 14L14 12Z" />
</svg>
);
export const VisualStudioCode: Icon = (props) => {
const id = useId();
const maskId = `${id}-vscode-a`;
@@ -13,7 +13,16 @@ 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 "vitest";
import {
afterAll,
afterEach,
beforeAll,
beforeEach,
describe,
expect,
it,
vi,
} from "vite-plus/test";
import { render } from "vitest-browser-react";
import { useComposerDraftStore } from "../composerDraftStore";
@@ -1,4 +1,4 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import {
createThreadJumpHintVisibilityController,
+1 -1
View File
@@ -440,7 +440,7 @@ function getLatestUserMessageTimestamp(thread: SidebarThreadSortInput): number {
function getThreadSortTimestamp(
thread: SidebarThreadSortInput,
sortOrder: SidebarThreadSortOrder | Exclude<SidebarProjectSortOrder, "manual">,
sortOrder: SidebarThreadSortOrder,
): number {
if (sortOrder === "created_at") {
return toSortableTimestamp(thread.createdAt) ?? Number.NEGATIVE_INFINITY;
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it } from "vite-plus/test";
import {
resolveTerminalSelectionActionPosition,
@@ -1,8 +1,8 @@
import { DEFAULT_MODEL_BY_PROVIDER, ModelSelection, ThreadId } from "@t3tools/contracts";
import "../../index.css";
import { page } from "vitest/browser";
import { afterEach, describe, expect, it, vi } from "vitest";
import { page } from "vite-plus/test/browser";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { render } from "vitest-browser-react";
import { CompactComposerControlsMenu } from "./CompactComposerControlsMenu";
@@ -1,6 +1,6 @@
import { ThreadId } from "@t3tools/contracts";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import { describe, expect, it } from "vite-plus/test";
import { ComposerPendingTerminalContextChip } from "./ComposerPendingTerminalContexts";
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it } from "vite-plus/test";
import { computeMessageDurationStart, normalizeCompactToolLabel } from "./MessagesTimeline.logic";
describe("computeMessageDurationStart", () => {
@@ -1,6 +1,6 @@
import { MessageId } from "@t3tools/contracts";
import { renderToStaticMarkup } from "react-dom/server";
import { beforeAll, describe, expect, it, vi } from "vitest";
import { beforeAll, describe, expect, it, vi } from "vite-plus/test";
function matchMedia() {
return {
@@ -6,7 +6,7 @@ import { ChevronDownIcon, FolderClosedIcon } from "lucide-react";
import { Button } from "../ui/button";
import { Group, GroupSeparator } from "../ui/group";
import { Menu, MenuItem, MenuPopup, MenuShortcut, MenuTrigger } from "../ui/menu";
import { AntigravityIcon, CursorIcon, Icon, TraeIcon, VisualStudioCode, Zed } from "../Icons";
import { AntigravityIcon, CursorIcon, Icon, VisualStudioCode, Zed } from "../Icons";
import { isMacPlatform, isWindowsPlatform } from "~/lib/utils";
import { readNativeApi } from "~/nativeApi";
@@ -17,11 +17,6 @@ const resolveOptions = (platform: string, availableEditors: ReadonlyArray<Editor
Icon: CursorIcon,
value: "cursor",
},
{
label: "Trae",
Icon: TraeIcon,
value: "trae",
},
{
label: "VS Code",
Icon: VisualStudioCode,
@@ -198,7 +198,7 @@ export const ProposedPlanCard = memo(function ProposedPlanCard({
</Button>
<Button
size="sm"
onClick={() => void handleSaveToWorkspace()}
onClick={() => handleSaveToWorkspace()}
disabled={isSavingToWorkspace}
>
{isSavingToWorkspace ? "Saving..." : "Save"}
@@ -1,6 +1,6 @@
import { type ProviderKind, type ServerProvider } from "@t3tools/contracts";
import { page } from "vitest/browser";
import { afterEach, describe, expect, it, vi } from "vitest";
import { page } from "vite-plus/test/browser";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { render } from "vitest-browser-react";
import { ProviderModelPicker } from "./ProviderModelPicker";
@@ -10,9 +10,9 @@ import {
type ServerProvider,
ThreadId,
} from "@t3tools/contracts";
import { page } from "vitest/browser";
import { page } from "vite-plus/test/browser";
import { useCallback } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { render } from "vitest-browser-react";
import { TraitsPicker } from "./TraitsPicker";
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it } from "vite-plus/test";
import type { ServerProviderModel } from "@t3tools/contracts";
import { getComposerProviderState } from "./composerProviderRegistry";
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it } from "vite-plus/test";
import {
buildInlineTerminalContextText,
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it } from "vite-plus/test";
import {
COMPOSER_FOOTER_COMPACT_BREAKPOINT_PX,
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it } from "vite-plus/test";
import type { DesktopUpdateActionResult, DesktopUpdateState } from "@t3tools/contracts";
import {
@@ -1042,7 +1042,7 @@ export function GeneralSettingsPanel() {
variant="ghost"
className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"
disabled={isRefreshingProviders}
onClick={() => void refreshProviders()}
onClick={() => refreshProviders()}
aria-label="Refresh provider status"
>
{isRefreshingProviders ? (
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it } from "vite-plus/test";
import { appendTerminalContextsToPrompt } from "../lib/terminalContext";
import { buildInlineTerminalContextText } from "./chat/userMessageTerminalContexts";
+1 -1
View File
@@ -23,7 +23,7 @@ function AutocompleteInput({
size?: "sm" | "default" | "lg" | number;
ref?: React.Ref<HTMLInputElement>;
}) {
const sizeValue = (size ?? "default") as "sm" | "default" | "lg" | number;
const sizeValue = size ?? "default";
return (
<div className="relative not-has-[>*.w-full]:w-fit w-full text-foreground has-disabled:opacity-64">
+2 -2
View File
@@ -36,7 +36,7 @@ function ComboboxChipsInput({
size?: "sm" | "default" | "lg" | number;
ref?: React.Ref<HTMLInputElement>;
}) {
const sizeValue = (size ?? "default") as "sm" | "default" | "lg" | number;
const sizeValue = size ?? "default";
return (
<ComboboxPrimitive.Input
@@ -69,7 +69,7 @@ function ComboboxInput({
size?: "sm" | "default" | "lg" | number;
ref?: React.Ref<HTMLInputElement>;
}) {
const sizeValue = (size ?? "default") as "sm" | "default" | "lg" | number;
const sizeValue = size ?? "default";
return (
<div className="relative not-has-[>*.w-full]:w-fit w-full text-foreground has-disabled:opacity-64">
Loaded 100 of 176 files, more files were not shown because too many files have changed in this diff. Show more