Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
59d508ed52 | ||
|
|
d5c97faac5 | ||
|
|
531b12e192 | ||
|
|
b293b083fc | ||
|
|
b297e20f4e | ||
|
|
44be7f3ac3 | ||
|
|
ea5a100a74 | ||
|
|
6841fa17d4 | ||
|
|
5c03804bac | ||
|
|
d6ed393255 | ||
|
|
2d9139767a | ||
|
|
95fcc89074 | ||
|
|
eb59853596 | ||
|
|
a2682de421 | ||
|
|
325c0a3687 | ||
|
|
7c7fcf46c2 | ||
|
|
0c39733cbf | ||
|
|
a76413594e | ||
|
|
1100d5a6f7 | ||
|
|
9abf967700 | ||
|
|
cc83094bc6 | ||
|
|
f5bdc138f6 | ||
|
|
2d8ca48175 | ||
|
|
4ca4a1f99c | ||
|
|
5470801c4a | ||
|
|
2ad2d3e6f5 |
No files matched your search
@@ -8,7 +8,7 @@ on:
|
||||
|
||||
jobs:
|
||||
quality:
|
||||
name: Lint, Typecheck, Test, Build
|
||||
name: Lint, Typecheck, Test, Browser Test, Build
|
||||
runs-on: blacksmith-4vcpu-ubuntu-2404
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -34,6 +34,14 @@ jobs:
|
||||
restore-keys: |
|
||||
${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-
|
||||
|
||||
- name: Cache Playwright browsers
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/ms-playwright
|
||||
key: ${{ runner.os }}-playwright-${{ hashFiles('bun.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-playwright-
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
@@ -46,6 +54,14 @@ jobs:
|
||||
- name: Test
|
||||
run: bun run test
|
||||
|
||||
- name: Install browser test runtime
|
||||
run: |
|
||||
cd apps/web
|
||||
bunx playwright install --with-deps chromium
|
||||
|
||||
- name: Browser test
|
||||
run: bun run --cwd apps/web test:browser
|
||||
|
||||
- name: Build desktop pipeline
|
||||
run: bun run build:desktop
|
||||
|
||||
|
||||
@@ -22,12 +22,10 @@ jobs:
|
||||
outputs:
|
||||
version: ${{ steps.release_meta.outputs.version }}
|
||||
tag: ${{ steps.release_meta.outputs.tag }}
|
||||
ref: ${{ steps.release_ref.outputs.value }}
|
||||
ref: ${{ github.sha }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- id: release_meta
|
||||
name: Resolve release version
|
||||
@@ -58,32 +56,6 @@ jobs:
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Update version strings
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
env:
|
||||
RELEASE_VERSION: ${{ steps.release_meta.outputs.version }}
|
||||
run: |
|
||||
node --input-type=module -e '
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
|
||||
const files = [
|
||||
"apps/server/package.json",
|
||||
"apps/desktop/package.json",
|
||||
"apps/web/package.json",
|
||||
"packages/contracts/package.json",
|
||||
];
|
||||
|
||||
for (const file of files) {
|
||||
const packageJson = JSON.parse(readFileSync(file, "utf8"));
|
||||
packageJson.version = process.env.RELEASE_VERSION;
|
||||
writeFileSync(file, `${JSON.stringify(packageJson, null, 2)}\n`);
|
||||
}
|
||||
'
|
||||
|
||||
- name: Refresh lockfile
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
run: bun install
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
@@ -96,39 +68,6 @@ jobs:
|
||||
- name: Test
|
||||
run: bun run test
|
||||
|
||||
- name: Commit and push release version + tag
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
shell: bash
|
||||
env:
|
||||
RELEASE_TAG: ${{ steps.release_meta.outputs.tag }}
|
||||
run: |
|
||||
if git ls-remote --exit-code --tags origin "$RELEASE_TAG" >/dev/null 2>&1; then
|
||||
echo "Tag $RELEASE_TAG already exists on origin." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
|
||||
if ! git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock; then
|
||||
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock
|
||||
git commit -m "chore(release): prepare $RELEASE_TAG" -m "Co-authored-by: codex <[email protected]>"
|
||||
fi
|
||||
|
||||
git tag "$RELEASE_TAG"
|
||||
git push origin "HEAD:${GITHUB_REF_NAME}"
|
||||
git push origin "refs/tags/$RELEASE_TAG"
|
||||
|
||||
- id: release_ref
|
||||
name: Resolve source ref
|
||||
shell: bash
|
||||
run: |
|
||||
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
|
||||
echo "value=refs/tags/${{ steps.release_meta.outputs.tag }}" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "value=${GITHUB_SHA}" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
build:
|
||||
name: Build ${{ matrix.label }}
|
||||
needs: preflight
|
||||
@@ -318,8 +257,10 @@ jobs:
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ needs.preflight.outputs.tag }}
|
||||
target_commitish: ${{ needs.preflight.outputs.ref }}
|
||||
name: T3 Code v${{ needs.preflight.outputs.version }}
|
||||
generate_release_notes: true
|
||||
make_latest: true
|
||||
files: |
|
||||
release-assets/*.dmg
|
||||
release-assets/*.zip
|
||||
@@ -328,3 +269,82 @@ jobs:
|
||||
release-assets/*.blockmap
|
||||
release-assets/latest*.yml
|
||||
fail_on_unmatched_files: true
|
||||
|
||||
finalize:
|
||||
name: Finalize release
|
||||
needs: [preflight, release]
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: main
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- id: update_versions
|
||||
name: Update version strings
|
||||
env:
|
||||
RELEASE_VERSION: ${{ needs.preflight.outputs.version }}
|
||||
run: |
|
||||
node --input-type=module -e '
|
||||
import { appendFileSync, readFileSync, writeFileSync } from "node:fs";
|
||||
|
||||
const files = [
|
||||
"apps/server/package.json",
|
||||
"apps/desktop/package.json",
|
||||
"apps/web/package.json",
|
||||
"packages/contracts/package.json",
|
||||
];
|
||||
|
||||
let changed = false;
|
||||
for (const file of files) {
|
||||
const packageJson = JSON.parse(readFileSync(file, "utf8"));
|
||||
if (packageJson.version !== process.env.RELEASE_VERSION) {
|
||||
packageJson.version = process.env.RELEASE_VERSION;
|
||||
writeFileSync(file, `${JSON.stringify(packageJson, null, 2)}\n`);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!changed) {
|
||||
console.log("All package.json versions already match release version.");
|
||||
}
|
||||
|
||||
appendFileSync(process.env.GITHUB_OUTPUT, `changed=${changed}\n`);
|
||||
'
|
||||
|
||||
- name: Format package.json files
|
||||
if: steps.update_versions.outputs.changed == 'true'
|
||||
run: bunx oxfmt apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json
|
||||
|
||||
- name: Refresh lockfile
|
||||
if: steps.update_versions.outputs.changed == 'true'
|
||||
run: bun install
|
||||
|
||||
- name: Commit and push version bump
|
||||
if: steps.update_versions.outputs.changed == 'true'
|
||||
shell: bash
|
||||
env:
|
||||
RELEASE_TAG: ${{ needs.preflight.outputs.tag }}
|
||||
run: |
|
||||
if git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock; then
|
||||
echo "No version changes to commit."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
|
||||
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock
|
||||
git commit -m "chore(release): prepare $RELEASE_TAG"
|
||||
git push origin HEAD:main
|
||||
+4
-1
@@ -11,4 +11,7 @@ packages/*/dist
|
||||
build/
|
||||
.logs/
|
||||
release/
|
||||
.t3
|
||||
.t3
|
||||
apps/web/.playwright
|
||||
apps/web/playwright-report
|
||||
apps/web/src/components/__screenshots__
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.0-alpha.18",
|
||||
"version": "0.0.0-alpha.20",
|
||||
"private": true,
|
||||
"main": "dist-electron/main.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.0-alpha.18",
|
||||
"version": "0.0.0-alpha.20",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/pingdotgg/t3code",
|
||||
"directory": "apps/server"
|
||||
},
|
||||
"bin": {
|
||||
"t3": "./dist/index.mjs"
|
||||
},
|
||||
|
||||
@@ -111,6 +111,8 @@ const publishCmd = Command.make(
|
||||
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,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import { type ChildProcessWithoutNullStreams, spawn, spawnSync } from "node:child_process";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { EventEmitter } from "node:events";
|
||||
import readline from "node:readline";
|
||||
@@ -18,7 +18,6 @@ import {
|
||||
type ProviderSessionStartInput,
|
||||
type ProviderTurnStartResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { killProcessTree, spawnPipedProcess } from "./processRunner";
|
||||
|
||||
type PendingRequestKey = string;
|
||||
|
||||
@@ -105,6 +104,23 @@ const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
|
||||
"does not exist",
|
||||
];
|
||||
|
||||
/**
|
||||
* On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe`
|
||||
* wrapper, leaving the actual command running. Use `taskkill /T` to kill the
|
||||
* entire process tree instead.
|
||||
*/
|
||||
function killChildTree(child: ChildProcessWithoutNullStreams): void {
|
||||
if (process.platform === "win32" && child.pid !== undefined) {
|
||||
try {
|
||||
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
|
||||
return;
|
||||
} catch {
|
||||
// fallback to direct kill
|
||||
}
|
||||
}
|
||||
child.kill();
|
||||
}
|
||||
|
||||
export function normalizeCodexModelSlug(
|
||||
model: string | undefined | null,
|
||||
preferredId?: string,
|
||||
@@ -179,12 +195,14 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
|
||||
const codexBinaryPath = input.codexBinaryPath ?? "codex";
|
||||
const codexHomePath = input.codexHomePath;
|
||||
const child = spawnPipedProcess(codexBinaryPath, ["app-server"], {
|
||||
const child = spawn(codexBinaryPath, ["app-server"], {
|
||||
cwd: resolvedCwd,
|
||||
env: {
|
||||
...process.env,
|
||||
...(codexHomePath ? { CODEX_HOME: codexHomePath } : {}),
|
||||
},
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
const output = readline.createInterface({ input: child.stdout });
|
||||
|
||||
@@ -475,7 +493,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
context.output.close();
|
||||
|
||||
if (!context.child.killed) {
|
||||
killProcessTree(context.child);
|
||||
killChildTree(context.child);
|
||||
}
|
||||
|
||||
this.updateSession(context, {
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { Effect, FileSystem, Layer, Path, Schema } from "effect";
|
||||
import { Effect, FileSystem, Layer, Option, Path, Schema, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { runProcess } from "../../processRunner.ts";
|
||||
import { TextGenerationError } from "../Errors.ts";
|
||||
import {
|
||||
type BranchNameGenerationInput,
|
||||
@@ -98,12 +98,31 @@ function sanitizePrTitle(raw: string): string {
|
||||
const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const serverConfig = yield* Effect.service(ServerConfig);
|
||||
|
||||
type MaterializedImageAttachments = {
|
||||
readonly imagePaths: ReadonlyArray<string>;
|
||||
};
|
||||
|
||||
const readStreamAsString = <E>(
|
||||
operation: string,
|
||||
stream: Stream.Stream<Uint8Array, E>,
|
||||
): Effect.Effect<string, TextGenerationError> =>
|
||||
Effect.gen(function* () {
|
||||
let text = "";
|
||||
yield* Stream.runForEach(stream, (chunk) =>
|
||||
Effect.sync(() => {
|
||||
text += Buffer.from(chunk).toString("utf8");
|
||||
}),
|
||||
).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCodexError(operation, cause, "Failed to collect process output"),
|
||||
),
|
||||
);
|
||||
return text;
|
||||
});
|
||||
|
||||
const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
|
||||
|
||||
const writeTempFile = (
|
||||
@@ -184,59 +203,68 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
);
|
||||
const outputPath = yield* writeTempFile(operation, "codex-output", "");
|
||||
|
||||
const runCodexCommand = Effect.tryPromise({
|
||||
try: async () => {
|
||||
const result = await runProcess(
|
||||
"codex",
|
||||
[
|
||||
"exec",
|
||||
"--ephemeral",
|
||||
"-s",
|
||||
"read-only",
|
||||
"--model",
|
||||
CODEX_MODEL,
|
||||
"--config",
|
||||
`model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
|
||||
"--output-schema",
|
||||
schemaPath,
|
||||
"--output-last-message",
|
||||
outputPath,
|
||||
...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
|
||||
"-",
|
||||
],
|
||||
{
|
||||
cwd,
|
||||
stdin: prompt,
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: CODEX_TIMEOUT_MS,
|
||||
maxBufferBytes: 1_000_000,
|
||||
outputMode: "truncate",
|
||||
const runCodexCommand = Effect.gen(function* () {
|
||||
const command = ChildProcess.make(
|
||||
"codex",
|
||||
[
|
||||
"exec",
|
||||
"--ephemeral",
|
||||
"-s",
|
||||
"read-only",
|
||||
"--model",
|
||||
CODEX_MODEL,
|
||||
"--config",
|
||||
`model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
|
||||
"--output-schema",
|
||||
schemaPath,
|
||||
"--output-last-message",
|
||||
outputPath,
|
||||
...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
|
||||
"-",
|
||||
],
|
||||
{
|
||||
cwd,
|
||||
shell: process.platform === "win32",
|
||||
stdin: {
|
||||
stream: Stream.make(new TextEncoder().encode(prompt)),
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const child = yield* commandSpawner
|
||||
.spawn(command)
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCodexError(operation, cause, "Failed to spawn Codex CLI process"),
|
||||
),
|
||||
);
|
||||
|
||||
if (result.timedOut) {
|
||||
throw new TextGenerationError({ operation, detail: "Codex CLI request timed out." });
|
||||
}
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
readStreamAsString(operation, child.stdout),
|
||||
readStreamAsString(operation, child.stderr),
|
||||
child.exitCode.pipe(
|
||||
Effect.map((value) => Number(value)),
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCodexError(operation, cause, "Failed to read Codex CLI exit code"),
|
||||
),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
const stdout = result.stdout;
|
||||
const stderr = result.stderr;
|
||||
const exitCode = result.code ?? 0;
|
||||
|
||||
if (exitCode !== 0) {
|
||||
const stderrDetail = stderr.trim();
|
||||
const stdoutDetail = stdout.trim();
|
||||
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
|
||||
throw new TextGenerationError({
|
||||
operation,
|
||||
detail:
|
||||
detail.length > 0
|
||||
? `Codex CLI command failed: ${detail}`
|
||||
: `Codex CLI command failed with code ${exitCode}.`,
|
||||
});
|
||||
}
|
||||
},
|
||||
catch: (error) =>
|
||||
normalizeCodexError(operation, error, "Failed to execute Codex CLI process"),
|
||||
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
|
||||
? `Codex CLI command failed: ${detail}`
|
||||
: `Codex CLI command failed with code ${exitCode}.`,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const cleanup = Effect.all(
|
||||
@@ -247,7 +275,19 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
).pipe(Effect.asVoid);
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
yield* runCodexCommand;
|
||||
yield* runCodexCommand.pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(CODEX_TIMEOUT_MS),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
|
||||
),
|
||||
onSome: () => Effect.void,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return yield* fileSystem.readFileString(outputPath).pipe(
|
||||
Effect.mapError(
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
/**
|
||||
* Git process helpers - runtime-aware git execution with typed errors.
|
||||
* Git process helpers - Effect-native git execution with typed errors.
|
||||
*
|
||||
* Centralizes child-process git invocation for server modules. This module
|
||||
* only executes git commands and reports structured failures.
|
||||
*
|
||||
* @module GitServiceLive
|
||||
*/
|
||||
import { Effect, Layer, Schema } from "effect";
|
||||
import { runProcess } from "../../processRunner.ts";
|
||||
import { Effect, Layer, Option, Schema, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { GitCommandError } from "../Errors.ts";
|
||||
import {
|
||||
ExecuteGitInput,
|
||||
@@ -39,7 +39,37 @@ function toGitCommandError(
|
||||
});
|
||||
}
|
||||
|
||||
const makeGitService = Effect.sync(() => {
|
||||
const collectOutput = Effect.fn(function* <E>(
|
||||
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
|
||||
stream: Stream.Stream<Uint8Array, E>,
|
||||
maxOutputBytes: number,
|
||||
): Effect.fn.Return<string, GitCommandError> {
|
||||
const decoder = new TextDecoder();
|
||||
let bytes = 0;
|
||||
let text = "";
|
||||
|
||||
yield* Stream.runForEach(stream, (chunk) =>
|
||||
Effect.gen(function* () {
|
||||
bytes += chunk.byteLength;
|
||||
if (bytes > maxOutputBytes) {
|
||||
return yield* new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: quoteGitCommand(input.args),
|
||||
cwd: input.cwd,
|
||||
detail: `${quoteGitCommand(input.args)} output exceeded ${maxOutputBytes} bytes and was truncated.`,
|
||||
});
|
||||
}
|
||||
text += decoder.decode(chunk, { stream: true });
|
||||
}),
|
||||
).pipe(Effect.mapError(toGitCommandError(input, "output stream failed.")));
|
||||
|
||||
text += decoder.decode();
|
||||
return text;
|
||||
});
|
||||
|
||||
const makeGitService = Effect.gen(function* () {
|
||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
const execute: GitServiceShape["execute"] = Effect.fnUntraced(function* (input) {
|
||||
const commandInput = {
|
||||
...input,
|
||||
@@ -48,48 +78,62 @@ const makeGitService = Effect.sync(() => {
|
||||
const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
|
||||
|
||||
return yield* Effect.tryPromise({
|
||||
try: async () => {
|
||||
const result = await runProcess("git", commandInput.args, {
|
||||
const commandEffect = Effect.gen(function* () {
|
||||
const child = yield* commandSpawner
|
||||
.spawn(
|
||||
ChildProcess.make("git", commandInput.args, {
|
||||
cwd: commandInput.cwd,
|
||||
...(input.env ? { env: input.env } : {}),
|
||||
}),
|
||||
)
|
||||
.pipe(Effect.mapError(toGitCommandError(commandInput, "failed to spawn.")));
|
||||
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
collectOutput(commandInput, child.stdout, maxOutputBytes),
|
||||
collectOutput(commandInput, child.stderr, maxOutputBytes),
|
||||
child.exitCode.pipe(
|
||||
Effect.map((value) => Number(value)),
|
||||
Effect.mapError(toGitCommandError(commandInput, "failed to report exit code.")),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
if (!input.allowNonZeroExit && exitCode !== 0) {
|
||||
const trimmedStderr = stderr.trim();
|
||||
return yield* new GitCommandError({
|
||||
operation: commandInput.operation,
|
||||
command: quoteGitCommand(commandInput.args),
|
||||
cwd: commandInput.cwd,
|
||||
...(input.env ? { env: input.env } : {}),
|
||||
timeoutMs,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: maxOutputBytes,
|
||||
outputMode: "error",
|
||||
detail:
|
||||
trimmedStderr.length > 0
|
||||
? `${quoteGitCommand(commandInput.args)} failed: ${trimmedStderr}`
|
||||
: `${quoteGitCommand(commandInput.args)} failed with code ${exitCode}.`,
|
||||
});
|
||||
}
|
||||
|
||||
if (result.timedOut) {
|
||||
throw new GitCommandError({
|
||||
operation: commandInput.operation,
|
||||
command: quoteGitCommand(commandInput.args),
|
||||
cwd: commandInput.cwd,
|
||||
detail: `${quoteGitCommand(commandInput.args)} timed out.`,
|
||||
});
|
||||
}
|
||||
|
||||
const exitCode = result.code ?? 0;
|
||||
if (!input.allowNonZeroExit && exitCode !== 0) {
|
||||
const trimmedStderr = result.stderr.trim();
|
||||
throw new GitCommandError({
|
||||
operation: commandInput.operation,
|
||||
command: quoteGitCommand(commandInput.args),
|
||||
cwd: commandInput.cwd,
|
||||
detail:
|
||||
trimmedStderr.length > 0
|
||||
? `${quoteGitCommand(commandInput.args)} failed: ${trimmedStderr}`
|
||||
: `${quoteGitCommand(commandInput.args)} failed with code ${exitCode}.`,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
code: exitCode,
|
||||
stdout: result.stdout,
|
||||
stderr: result.stderr,
|
||||
} satisfies ExecuteGitResult;
|
||||
},
|
||||
catch: toGitCommandError(commandInput, "failed to run."),
|
||||
return { code: exitCode, stdout, stderr } satisfies ExecuteGitResult;
|
||||
});
|
||||
|
||||
return yield* commandEffect.pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(timeoutMs),
|
||||
Effect.flatMap((result) =>
|
||||
Option.match(result, {
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: commandInput.operation,
|
||||
command: quoteGitCommand(commandInput.args),
|
||||
cwd: commandInput.cwd,
|
||||
detail: `${quoteGitCommand(commandInput.args)} timed out.`,
|
||||
}),
|
||||
),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
|
||||
+13
-201
@@ -7,7 +7,6 @@ import { assert, describe, it } from "@effect/vitest";
|
||||
import {
|
||||
isCommandAvailable,
|
||||
launchDetached,
|
||||
resolveBrowserLaunch,
|
||||
resolveAvailableEditors,
|
||||
resolveEditorLaunch,
|
||||
} from "./open";
|
||||
@@ -19,7 +18,7 @@ describe("resolveEditorLaunch", () => {
|
||||
Effect.gen(function* () {
|
||||
const cursorLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "cursor" },
|
||||
{ platform: "darwin" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(cursorLaunch, {
|
||||
command: "cursor",
|
||||
@@ -28,7 +27,7 @@ describe("resolveEditorLaunch", () => {
|
||||
|
||||
const vscodeLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "vscode" },
|
||||
{ platform: "darwin" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodeLaunch, {
|
||||
command: "code",
|
||||
@@ -37,7 +36,7 @@ describe("resolveEditorLaunch", () => {
|
||||
|
||||
const zedLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "zed" },
|
||||
{ platform: "darwin" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(zedLaunch, {
|
||||
command: "zed",
|
||||
@@ -50,7 +49,7 @@ describe("resolveEditorLaunch", () => {
|
||||
Effect.gen(function* () {
|
||||
const lineOnly = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "cursor" },
|
||||
{ platform: "darwin" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(lineOnly, {
|
||||
command: "cursor",
|
||||
@@ -59,7 +58,7 @@ describe("resolveEditorLaunch", () => {
|
||||
|
||||
const lineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "cursor" },
|
||||
{ platform: "darwin" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(lineAndColumn, {
|
||||
command: "cursor",
|
||||
@@ -68,7 +67,7 @@ describe("resolveEditorLaunch", () => {
|
||||
|
||||
const vscodeLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
|
||||
{ platform: "darwin" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodeLineAndColumn, {
|
||||
command: "code",
|
||||
@@ -77,7 +76,7 @@ describe("resolveEditorLaunch", () => {
|
||||
|
||||
const zedLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "zed" },
|
||||
{ platform: "darwin" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(zedLineAndColumn, {
|
||||
command: "zed",
|
||||
@@ -90,7 +89,7 @@ describe("resolveEditorLaunch", () => {
|
||||
Effect.gen(function* () {
|
||||
const launch1 = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "file-manager" },
|
||||
{ platform: "darwin" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(launch1, {
|
||||
command: "open",
|
||||
@@ -99,7 +98,7 @@ describe("resolveEditorLaunch", () => {
|
||||
|
||||
const launch2 = yield* resolveEditorLaunch(
|
||||
{ cwd: "C:\\workspace", editor: "file-manager" },
|
||||
{ platform: "win32" },
|
||||
"win32",
|
||||
);
|
||||
assert.deepEqual(launch2, {
|
||||
command: "explorer",
|
||||
@@ -108,7 +107,7 @@ describe("resolveEditorLaunch", () => {
|
||||
|
||||
const launch3 = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "file-manager" },
|
||||
{ platform: "linux" },
|
||||
"linux",
|
||||
);
|
||||
assert.deepEqual(launch3, {
|
||||
command: "xdg-open",
|
||||
@@ -116,112 +115,6 @@ describe("resolveEditorLaunch", () => {
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prefers linux editor shims in wsl-hosted mode when available", () =>
|
||||
Effect.gen(function* () {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-open-wsl-linux-editor-"));
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "code"), "#!/bin/sh\n", { mode: 0o755 });
|
||||
const launch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/home/julius/project/src/open.ts:71:5", editor: "vscode" },
|
||||
{
|
||||
platform: "linux",
|
||||
runtimeEnvironment: {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
},
|
||||
env: {
|
||||
PATH: dir,
|
||||
},
|
||||
},
|
||||
);
|
||||
assert.deepEqual(launch, {
|
||||
command: "code",
|
||||
args: ["--goto", "/home/julius/project/src/open.ts:71:5"],
|
||||
});
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to windows editor executables in wsl-hosted mode", () =>
|
||||
Effect.gen(function* () {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-open-wsl-win-editor-"));
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "code.exe"), "MZ", { mode: 0o755 });
|
||||
const launch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/home/julius/project/src/open.ts:71:5", editor: "vscode" },
|
||||
{
|
||||
platform: "linux",
|
||||
runtimeEnvironment: {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
},
|
||||
env: {
|
||||
PATH: dir,
|
||||
},
|
||||
translateWslPathToWindows: (target) =>
|
||||
target.replace(
|
||||
"/home/julius/project",
|
||||
"\\\\wsl.localhost\\Ubuntu\\home\\julius\\project",
|
||||
),
|
||||
},
|
||||
);
|
||||
assert.deepEqual(launch, {
|
||||
command: "code.exe",
|
||||
args: [
|
||||
"--goto",
|
||||
"\\\\wsl.localhost\\Ubuntu\\home\\julius\\project/src/open.ts:71:5",
|
||||
],
|
||||
});
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("translates file-manager targets for wsl-hosted mode", () =>
|
||||
Effect.gen(function* () {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-open-wsl-file-manager-"));
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "explorer.exe"), "MZ", { mode: 0o755 });
|
||||
const launch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/home/julius/project/src/open.ts:71:5", editor: "file-manager" },
|
||||
{
|
||||
platform: "linux",
|
||||
runtimeEnvironment: {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
},
|
||||
env: {
|
||||
PATH: dir,
|
||||
},
|
||||
translateWslPathToWindows: (target) =>
|
||||
target.replace(
|
||||
"/home/julius/project",
|
||||
"\\\\wsl.localhost\\Ubuntu\\home\\julius\\project",
|
||||
),
|
||||
},
|
||||
);
|
||||
assert.deepEqual(launch, {
|
||||
command: "explorer.exe",
|
||||
args: ["\\\\wsl.localhost\\Ubuntu\\home\\julius\\project/src/open.ts"],
|
||||
});
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("launchDetached", () => {
|
||||
@@ -317,94 +210,13 @@ describe("resolveAvailableEditors", () => {
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "cursor.CMD"), "@echo off\r\n", "utf8");
|
||||
fs.writeFileSync(path.join(dir, "explorer.EXE"), "MZ", "utf8");
|
||||
const editors = resolveAvailableEditors({
|
||||
platform: "win32",
|
||||
env: {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
},
|
||||
const editors = resolveAvailableEditors("win32", {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
});
|
||||
assert.deepEqual(editors, ["cursor", "file-manager"]);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("accepts windows editor executables in wsl-hosted mode", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-editors-wsl-"));
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "code.exe"), "MZ", { mode: 0o755 });
|
||||
fs.writeFileSync(path.join(dir, "explorer.exe"), "MZ", { mode: 0o755 });
|
||||
const editors = resolveAvailableEditors({
|
||||
platform: "linux",
|
||||
runtimeEnvironment: {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
},
|
||||
env: {
|
||||
PATH: dir,
|
||||
},
|
||||
});
|
||||
assert.deepEqual(editors, ["vscode", "file-manager"]);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveBrowserLaunch", () => {
|
||||
it("prefers wslview in wsl-hosted mode", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-browser-wsl-"));
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "wslview"), "#!/bin/sh\n", { mode: 0o755 });
|
||||
const launch = resolveBrowserLaunch("http://localhost:3773", {
|
||||
platform: "linux",
|
||||
runtimeEnvironment: {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
},
|
||||
env: {
|
||||
PATH: dir,
|
||||
},
|
||||
});
|
||||
assert.deepEqual(launch, {
|
||||
command: "wslview",
|
||||
args: ["http://localhost:3773"],
|
||||
});
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("falls back to explorer.exe in wsl-hosted mode", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-browser-wsl-explorer-"));
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "explorer.exe"), "MZ", { mode: 0o755 });
|
||||
const launch = resolveBrowserLaunch("http://localhost:3773", {
|
||||
platform: "linux",
|
||||
runtimeEnvironment: {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
},
|
||||
env: {
|
||||
PATH: dir,
|
||||
},
|
||||
});
|
||||
assert.deepEqual(launch, {
|
||||
command: "explorer.exe",
|
||||
args: ["http://localhost:3773"],
|
||||
});
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
+43
-235
@@ -6,13 +6,12 @@
|
||||
*
|
||||
* @module Open
|
||||
*/
|
||||
import { spawn } from "node:child_process";
|
||||
import { accessSync, constants, statSync } from "node:fs";
|
||||
import { extname, join } from "node:path";
|
||||
|
||||
import { EDITORS, type EditorId, type ServerRuntimeEnvironment } from "@t3tools/contracts";
|
||||
import { EDITORS, type EditorId } from "@t3tools/contracts";
|
||||
import { ServiceMap, Schema, Effect, Layer } from "effect";
|
||||
import { spawnDetachedProcess, spawnProcessSync } from "./processRunner";
|
||||
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
|
||||
|
||||
// ==============================
|
||||
// Definitions
|
||||
@@ -38,24 +37,7 @@ interface CommandAvailabilityOptions {
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
}
|
||||
|
||||
interface ResolveOpenOptions extends CommandAvailabilityOptions {
|
||||
readonly runtimeEnvironment?: ServerRuntimeEnvironment;
|
||||
readonly translateWslPathToWindows?: (target: string) => string;
|
||||
}
|
||||
|
||||
const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
|
||||
const WINDOWS_ABSOLUTE_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
|
||||
const WINDOWS_UNC_PATH_PATTERN = /^\\\\/;
|
||||
|
||||
function detectRuntimeEnvironment(options: ResolveOpenOptions): ServerRuntimeEnvironment {
|
||||
return (
|
||||
options.runtimeEnvironment ??
|
||||
detectServerRuntimeEnvironment({
|
||||
...(options.platform !== undefined ? { platform: options.platform } : {}),
|
||||
...(options.env !== undefined ? { env: options.env } : {}),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
function shouldUseGotoFlag(editorId: EditorId, target: string): boolean {
|
||||
return (editorId === "cursor" || editorId === "vscode") && LINE_COLUMN_SUFFIX_PATTERN.test(target);
|
||||
@@ -178,20 +160,14 @@ export function isCommandAvailable(
|
||||
}
|
||||
|
||||
export function resolveAvailableEditors(
|
||||
options: ResolveOpenOptions = {},
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): ReadonlyArray<EditorId> {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const env = options.env ?? process.env;
|
||||
const runtimeEnvironment = detectRuntimeEnvironment({ ...options, platform, env });
|
||||
const available: EditorId[] = [];
|
||||
|
||||
for (const editor of EDITORS) {
|
||||
const launch = resolveOpenCommand(editor.id, {
|
||||
platform,
|
||||
env,
|
||||
runtimeEnvironment,
|
||||
});
|
||||
if (launch.some((entry) => isCommandAvailable(entry, { platform, env }))) {
|
||||
const command = editor.command ?? fileManagerCommandForPlatform(platform);
|
||||
if (isCommandAvailable(command, { platform, env })) {
|
||||
available.push(editor.id);
|
||||
}
|
||||
}
|
||||
@@ -225,223 +201,60 @@ export class Open extends ServiceMap.Service<Open, OpenShape>()("t3/open") {}
|
||||
// Implementations
|
||||
// ==============================
|
||||
|
||||
function splitPathAndPosition(value: string): {
|
||||
path: string;
|
||||
line: string | undefined;
|
||||
column: string | undefined;
|
||||
} {
|
||||
let path = value;
|
||||
let column: string | undefined;
|
||||
let line: string | undefined;
|
||||
|
||||
const columnMatch = path.match(/:(\d+)$/);
|
||||
if (!columnMatch?.[1]) {
|
||||
return { path, line: undefined, column: undefined };
|
||||
}
|
||||
|
||||
column = columnMatch[1];
|
||||
path = path.slice(0, -columnMatch[0].length);
|
||||
|
||||
const lineMatch = path.match(/:(\d+)$/);
|
||||
if (lineMatch?.[1]) {
|
||||
line = lineMatch[1];
|
||||
path = path.slice(0, -lineMatch[0].length);
|
||||
} else {
|
||||
line = column;
|
||||
column = undefined;
|
||||
}
|
||||
|
||||
return { path, line, column };
|
||||
}
|
||||
|
||||
function stripLineColumnSuffix(value: string): string {
|
||||
const { path } = splitPathAndPosition(value);
|
||||
return path;
|
||||
}
|
||||
|
||||
function formatPathWithPosition(input: {
|
||||
readonly path: string;
|
||||
readonly line?: string;
|
||||
readonly column?: string;
|
||||
}): string {
|
||||
if (!input.line) {
|
||||
return input.path;
|
||||
}
|
||||
return `${input.path}:${input.line}${input.column ? `:${input.column}` : ""}`;
|
||||
}
|
||||
|
||||
function isWindowsPath(value: string): boolean {
|
||||
return WINDOWS_ABSOLUTE_PATH_PATTERN.test(value) || WINDOWS_UNC_PATH_PATTERN.test(value);
|
||||
}
|
||||
|
||||
function defaultTranslateWslPathToWindows(target: string): string {
|
||||
const parsed = splitPathAndPosition(target);
|
||||
if (parsed.path.length === 0 || !parsed.path.startsWith("/") || isWindowsPath(parsed.path)) {
|
||||
return target;
|
||||
}
|
||||
|
||||
const result = spawnProcessSync("wslpath", ["-w", parsed.path], {
|
||||
encoding: "utf8",
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
if (result.error) {
|
||||
throw result.error;
|
||||
}
|
||||
if (result.status !== 0) {
|
||||
const detail = result.stderr.trim() || result.stdout.trim() || "wslpath failed";
|
||||
throw new Error(detail);
|
||||
}
|
||||
|
||||
const translatedPath = result.stdout.trim();
|
||||
if (translatedPath.length === 0) {
|
||||
throw new Error("wslpath returned an empty path");
|
||||
}
|
||||
|
||||
return formatPathWithPosition({
|
||||
path: translatedPath,
|
||||
...(parsed.line ? { line: parsed.line } : {}),
|
||||
...(parsed.column ? { column: parsed.column } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function resolveOpenCommand(
|
||||
editorId: EditorId,
|
||||
options: ResolveOpenOptions,
|
||||
): ReadonlyArray<string> {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const env = options.env ?? process.env;
|
||||
const runtimeEnvironment = detectRuntimeEnvironment({ ...options, platform, env });
|
||||
const editorDef = EDITORS.find((editor) => editor.id === editorId);
|
||||
if (!editorDef) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (editorId === "file-manager") {
|
||||
if (runtimeEnvironment.windowsInteropMode === "wsl-hosted") {
|
||||
return ["explorer.exe", "xdg-open"];
|
||||
}
|
||||
return [fileManagerCommandForPlatform(platform)];
|
||||
}
|
||||
|
||||
if (!editorDef.command) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (runtimeEnvironment.windowsInteropMode === "wsl-hosted") {
|
||||
return [editorDef.command, `${editorDef.command}.exe`];
|
||||
}
|
||||
|
||||
return [editorDef.command];
|
||||
}
|
||||
|
||||
export function resolveBrowserLaunch(
|
||||
target: string,
|
||||
options: ResolveOpenOptions = {},
|
||||
): EditorLaunch | null {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const env = options.env ?? process.env;
|
||||
const runtimeEnvironment = detectRuntimeEnvironment({ ...options, platform, env });
|
||||
|
||||
if (runtimeEnvironment.windowsInteropMode === "wsl-hosted") {
|
||||
if (isCommandAvailable("wslview", { platform, env })) {
|
||||
return { command: "wslview", args: [target] };
|
||||
}
|
||||
if (isCommandAvailable("explorer.exe", { platform, env })) {
|
||||
return { command: "explorer.exe", args: [target] };
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export const resolveEditorLaunch = Effect.fnUntraced(function* (
|
||||
input: OpenInEditorInput,
|
||||
options: ResolveOpenOptions = {},
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): Effect.fn.Return<EditorLaunch, OpenError> {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const env = options.env ?? process.env;
|
||||
const runtimeEnvironment = detectRuntimeEnvironment({ ...options, platform, env });
|
||||
const editorDef = EDITORS.find((editor) => editor.id === input.editor);
|
||||
if (!editorDef) {
|
||||
return yield* new OpenError({ message: `Unknown editor: ${input.editor}` });
|
||||
}
|
||||
|
||||
const translateWslPathToWindows = options.translateWslPathToWindows ?? defaultTranslateWslPathToWindows;
|
||||
|
||||
if (editorDef.command) {
|
||||
const candidateCommands = resolveOpenCommand(editorDef.id, {
|
||||
platform,
|
||||
env,
|
||||
runtimeEnvironment,
|
||||
});
|
||||
const command =
|
||||
candidateCommands.find((entry) => isCommandAvailable(entry, { platform, env })) ??
|
||||
candidateCommands[0];
|
||||
if (!command) {
|
||||
return yield* new OpenError({ message: `Editor command not found: ${editorDef.command}` });
|
||||
}
|
||||
|
||||
const usesWindowsPath = runtimeEnvironment.windowsInteropMode === "wsl-hosted" && command.endsWith(".exe");
|
||||
const target = usesWindowsPath
|
||||
? yield* Effect.try({
|
||||
try: () => translateWslPathToWindows(input.cwd),
|
||||
catch: (cause) =>
|
||||
new OpenError({
|
||||
message: "Failed to translate WSL path for Windows editor launch",
|
||||
cause,
|
||||
}),
|
||||
})
|
||||
: input.cwd;
|
||||
|
||||
return shouldUseGotoFlag(editorDef.id, target)
|
||||
? { command, args: ["--goto", target] }
|
||||
: { command, args: [target] };
|
||||
return shouldUseGotoFlag(editorDef.id, 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}` });
|
||||
}
|
||||
|
||||
const candidateCommands = resolveOpenCommand(editorDef.id, {
|
||||
platform,
|
||||
env,
|
||||
runtimeEnvironment,
|
||||
});
|
||||
const command =
|
||||
candidateCommands.find((entry) => isCommandAvailable(entry, { platform, env })) ??
|
||||
candidateCommands[0];
|
||||
if (!command) {
|
||||
return yield* new OpenError({ message: "Editor command not found: file-manager" });
|
||||
}
|
||||
|
||||
let target = stripLineColumnSuffix(input.cwd);
|
||||
if (runtimeEnvironment.windowsInteropMode === "wsl-hosted" && command === "explorer.exe") {
|
||||
target = yield* Effect.try({
|
||||
try: () => stripLineColumnSuffix(translateWslPathToWindows(target)),
|
||||
catch: (cause) =>
|
||||
new OpenError({
|
||||
message: "Failed to translate WSL path for Windows file manager launch",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
return { command, args: [target] };
|
||||
return { command: fileManagerCommandForPlatform(platform), args: [input.cwd] };
|
||||
});
|
||||
|
||||
export const launchDetached = (launch: EditorLaunch) =>
|
||||
Effect.tryPromise({
|
||||
try: async () => {
|
||||
if (!isCommandAvailable(launch.command)) {
|
||||
throw new OpenError({ message: `Editor command not found: ${launch.command}` });
|
||||
Effect.gen(function* () {
|
||||
if (!isCommandAvailable(launch.command)) {
|
||||
return yield* new OpenError({ message: `Editor command not found: ${launch.command}` });
|
||||
}
|
||||
|
||||
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 }),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
await spawnDetachedProcess(launch.command, [...launch.args]);
|
||||
},
|
||||
catch: (cause) =>
|
||||
Schema.is(OpenError)(cause)
|
||||
? cause
|
||||
: new OpenError({ message: "failed to spawn detached process", cause }),
|
||||
const handleSpawn = () => {
|
||||
child.unref();
|
||||
resume(Effect.void);
|
||||
};
|
||||
|
||||
child.once("spawn", handleSpawn);
|
||||
child.once("error", (cause) =>
|
||||
resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
@@ -451,16 +264,11 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
return {
|
||||
openBrowser: (target) => {
|
||||
const launch = resolveBrowserLaunch(target);
|
||||
if (launch) {
|
||||
return launchDetached(launch);
|
||||
}
|
||||
return Effect.tryPromise({
|
||||
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;
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { runProcess, spawnDetachedProcess, spawnProcessSync } from "./processRunner";
|
||||
import { runProcess } from "./processRunner";
|
||||
|
||||
describe("runProcess", () => {
|
||||
it("fails when output exceeds max buffer in default mode", async () => {
|
||||
@@ -20,20 +20,4 @@ describe("runProcess", () => {
|
||||
expect(result.stdoutTruncated).toBe(true);
|
||||
expect(result.stderrTruncated).toBe(false);
|
||||
});
|
||||
|
||||
it("runs sync commands through the shared spawn strategy", () => {
|
||||
const result = spawnProcessSync("node", ["-e", "process.stdout.write('ok')"], {
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
|
||||
expect(result.error).toBeUndefined();
|
||||
expect(result.status).toBe(0);
|
||||
expect(result.stdout).toBe("ok");
|
||||
});
|
||||
|
||||
it("spawns detached commands through the shared spawn strategy", async () => {
|
||||
await expect(
|
||||
spawnDetachedProcess(process.execPath, ["-e", "process.exit(0)"]),
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,33 +1,4 @@
|
||||
import {
|
||||
type ChildProcess as ChildProcessHandle,
|
||||
type ChildProcessWithoutNullStreams,
|
||||
spawn,
|
||||
spawnSync,
|
||||
type StdioOptions,
|
||||
} from "node:child_process";
|
||||
|
||||
import type { ServerRuntimeEnvironment } from "@t3tools/contracts";
|
||||
|
||||
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
|
||||
|
||||
interface ProcessSpawnBaseOptions {
|
||||
cwd?: string | undefined;
|
||||
env?: NodeJS.ProcessEnv | undefined;
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
|
||||
shell?: boolean | undefined;
|
||||
}
|
||||
|
||||
export interface ProcessSpawnOptions extends ProcessSpawnBaseOptions {
|
||||
stdio?: StdioOptions | undefined;
|
||||
detached?: boolean | undefined;
|
||||
}
|
||||
|
||||
export interface ProcessSpawnSyncOptions extends ProcessSpawnBaseOptions {
|
||||
stdio?: StdioOptions | undefined;
|
||||
detached?: boolean | undefined;
|
||||
encoding?: BufferEncoding | undefined;
|
||||
input?: string | undefined;
|
||||
}
|
||||
import { type ChildProcess as ChildProcessHandle, spawn, spawnSync } from "node:child_process";
|
||||
|
||||
export interface ProcessRunOptions {
|
||||
cwd?: string | undefined;
|
||||
@@ -37,8 +8,6 @@ export interface ProcessRunOptions {
|
||||
allowNonZeroExit?: boolean | undefined;
|
||||
maxBufferBytes?: number | undefined;
|
||||
outputMode?: "error" | "truncate" | undefined;
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
|
||||
shell?: boolean | undefined;
|
||||
}
|
||||
|
||||
export interface ProcessRunResult {
|
||||
@@ -55,89 +24,6 @@ function commandLabel(command: string, args: readonly string[]): string {
|
||||
return [command, ...args].join(" ");
|
||||
}
|
||||
|
||||
function resolveRuntimeEnvironment(
|
||||
runtimeEnvironment: ServerRuntimeEnvironment | undefined,
|
||||
): ServerRuntimeEnvironment {
|
||||
return runtimeEnvironment ?? detectServerRuntimeEnvironment();
|
||||
}
|
||||
|
||||
function shouldUseShell(options: ProcessSpawnBaseOptions): boolean {
|
||||
if (options.shell !== undefined) {
|
||||
return options.shell;
|
||||
}
|
||||
|
||||
return resolveRuntimeEnvironment(options.runtimeEnvironment).platform === "windows";
|
||||
}
|
||||
|
||||
function toSpawnOptions(options: ProcessSpawnOptions) {
|
||||
return {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
shell: shouldUseShell(options),
|
||||
...(options.stdio !== undefined ? { stdio: options.stdio } : {}),
|
||||
...(options.detached !== undefined ? { detached: options.detached } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function spawnProcess(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options: ProcessSpawnOptions = {},
|
||||
): ChildProcessHandle {
|
||||
return spawn(command, args, toSpawnOptions(options));
|
||||
}
|
||||
|
||||
export function spawnPipedProcess(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options: Omit<ProcessSpawnOptions, "stdio" | "detached"> = {},
|
||||
): ChildProcessWithoutNullStreams {
|
||||
return spawnProcess(command, args, {
|
||||
...options,
|
||||
stdio: "pipe",
|
||||
}) as ChildProcessWithoutNullStreams;
|
||||
}
|
||||
|
||||
export function spawnProcessSync(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options: ProcessSpawnSyncOptions = {},
|
||||
) {
|
||||
return spawnSync(command, args, {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
shell: shouldUseShell(options),
|
||||
encoding: options.encoding ?? "utf8",
|
||||
...(options.stdio !== undefined ? { stdio: options.stdio } : {}),
|
||||
...(options.detached !== undefined ? { detached: options.detached } : {}),
|
||||
...(options.input !== undefined ? { input: options.input } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
export function spawnDetachedProcess(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options: Omit<ProcessSpawnOptions, "stdio" | "detached"> = {},
|
||||
): Promise<void> {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const child = spawnProcess(command, args, {
|
||||
...options,
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
});
|
||||
|
||||
const handleSpawn = () => {
|
||||
child.unref();
|
||||
resolve();
|
||||
};
|
||||
|
||||
child.once("spawn", handleSpawn);
|
||||
child.once("error", (error) => {
|
||||
reject(normalizeSpawnError(command, args, error));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeSpawnError(command: string, args: readonly string[], error: unknown): Error {
|
||||
if (!(error instanceof Error)) {
|
||||
return new Error(`Failed to run ${commandLabel(command, args)}.`);
|
||||
@@ -151,12 +37,8 @@ function normalizeSpawnError(command: string, args: readonly string[], error: un
|
||||
return new Error(`Failed to run ${commandLabel(command, args)}: ${error.message}`);
|
||||
}
|
||||
|
||||
function isWindowsCommandNotFound(
|
||||
code: number | null,
|
||||
stderr: string,
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment,
|
||||
): boolean {
|
||||
if (resolveRuntimeEnvironment(runtimeEnvironment).platform !== "windows") return false;
|
||||
function isWindowsCommandNotFound(code: number | null, stderr: string): boolean {
|
||||
if (process.platform !== "win32") return false;
|
||||
if (code === 9009) return true;
|
||||
return /is not recognized as an internal or external command/i.test(stderr);
|
||||
}
|
||||
@@ -165,9 +47,8 @@ function normalizeExitError(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
result: ProcessRunResult,
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment,
|
||||
): Error {
|
||||
if (isWindowsCommandNotFound(result.code, result.stderr, runtimeEnvironment)) {
|
||||
if (isWindowsCommandNotFound(result.code, result.stderr)) {
|
||||
return new Error(`Command not found: ${command}`);
|
||||
}
|
||||
|
||||
@@ -204,30 +85,11 @@ const DEFAULT_MAX_BUFFER_BYTES = 8 * 1024 * 1024;
|
||||
* wrapper, leaving the actual command running. Use `taskkill /T` to kill the
|
||||
* entire process tree instead.
|
||||
*/
|
||||
export function killProcessTree(
|
||||
child: ChildProcessHandle,
|
||||
options: {
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
|
||||
signal?: NodeJS.Signals | undefined;
|
||||
} = {},
|
||||
): void {
|
||||
const signal = options.signal ?? "SIGTERM";
|
||||
if (
|
||||
resolveRuntimeEnvironment(options.runtimeEnvironment).platform === "windows" &&
|
||||
child.pid !== undefined
|
||||
) {
|
||||
function killChild(child: ChildProcessHandle, signal: NodeJS.Signals = "SIGTERM"): void {
|
||||
if (process.platform === "win32" && child.pid !== undefined) {
|
||||
try {
|
||||
const result = spawnProcessSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], {
|
||||
stdio: "ignore",
|
||||
shell: false,
|
||||
runtimeEnvironment: options.runtimeEnvironment,
|
||||
});
|
||||
if (!result.error && result.status === 0) {
|
||||
return;
|
||||
}
|
||||
if (result.error) {
|
||||
throw result.error;
|
||||
}
|
||||
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
|
||||
return;
|
||||
} catch {
|
||||
// fallback to direct kill
|
||||
}
|
||||
@@ -273,7 +135,12 @@ export async function runProcess(
|
||||
const outputMode = options.outputMode ?? "error";
|
||||
|
||||
return new Promise<ProcessRunResult>((resolve, reject) => {
|
||||
const child = spawnPipedProcess(command, args, options);
|
||||
const child = spawn(command, args, {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
stdio: "pipe",
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
@@ -287,15 +154,9 @@ export async function runProcess(
|
||||
|
||||
const timeoutTimer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
killProcessTree(child, {
|
||||
runtimeEnvironment: options.runtimeEnvironment,
|
||||
signal: "SIGTERM",
|
||||
});
|
||||
killChild(child, "SIGTERM");
|
||||
forceKillTimer = setTimeout(() => {
|
||||
killProcessTree(child, {
|
||||
runtimeEnvironment: options.runtimeEnvironment,
|
||||
signal: "SIGKILL",
|
||||
});
|
||||
killChild(child, "SIGKILL");
|
||||
}, 1_000);
|
||||
}, timeoutMs);
|
||||
|
||||
@@ -310,10 +171,7 @@ export async function runProcess(
|
||||
};
|
||||
|
||||
const fail = (error: Error): void => {
|
||||
killProcessTree(child, {
|
||||
runtimeEnvironment: options.runtimeEnvironment,
|
||||
signal: "SIGTERM",
|
||||
});
|
||||
killChild(child, "SIGTERM");
|
||||
finalize(() => {
|
||||
reject(error);
|
||||
});
|
||||
@@ -386,7 +244,7 @@ export async function runProcess(
|
||||
|
||||
finalize(() => {
|
||||
if (!options.allowNonZeroExit && (timedOut || (code !== null && code !== 0))) {
|
||||
reject(normalizeExitError(command, args, result, options.runtimeEnvironment));
|
||||
reject(normalizeExitError(command, args, result));
|
||||
return;
|
||||
}
|
||||
resolve(result);
|
||||
|
||||
@@ -1,63 +1,93 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect } from "effect";
|
||||
import { Effect, Layer, Sink, Stream } from "effect";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { checkCodexProviderStatus, parseAuthStatusFromOutput } from "./ProviderHealth";
|
||||
|
||||
// ── Test helpers ────────────────────────────────────────────────────
|
||||
|
||||
function mockRunner(
|
||||
handler: (args: ReadonlyArray<string>) => { stdout: string; stderr: string; code: number },
|
||||
) {
|
||||
return (args: ReadonlyArray<string>) => Promise.resolve(handler(args));
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
function mockHandle(result: { stdout: string; stderr: string; code: number }) {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.code)),
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () => Effect.void,
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.make(encoder.encode(result.stdout)),
|
||||
stderr: Stream.make(encoder.encode(result.stderr)),
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
});
|
||||
}
|
||||
|
||||
function failingRunner(description: string) {
|
||||
return () => Promise.reject(new Error(description));
|
||||
function mockSpawnerLayer(
|
||||
handler: (args: ReadonlyArray<string>) => { stdout: string; stderr: string; code: number },
|
||||
) {
|
||||
return Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) => {
|
||||
const cmd = command as unknown as { args: ReadonlyArray<string> };
|
||||
return Effect.succeed(mockHandle(handler(cmd.args)));
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function failingSpawnerLayer(description: string) {
|
||||
return Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "NotFound",
|
||||
module: "ChildProcess",
|
||||
method: "spawn",
|
||||
description,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// ── Tests ───────────────────────────────────────────────────────────
|
||||
|
||||
it.effect("returns ready when codex is installed and authenticated", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkCodexProviderStatus(
|
||||
mockRunner((args) => {
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.available, true);
|
||||
assert.strictEqual(status.authStatus, "authenticated");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
);
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.available, true);
|
||||
assert.strictEqual(status.authStatus, "authenticated");
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns unavailable when codex is missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkCodexProviderStatus(failingRunner("spawn codex ENOENT"));
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.available, false);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(status.message, "Codex CLI (`codex`) is not installed or not on PATH.");
|
||||
}),
|
||||
}).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))),
|
||||
);
|
||||
|
||||
it.effect("returns unauthenticated when auth probe reports login required", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkCodexProviderStatus(
|
||||
mockRunner((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status") {
|
||||
return { stdout: "", stderr: "Not logged in. Run codex login.", code: 1 };
|
||||
}
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
);
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.available, true);
|
||||
@@ -66,22 +96,25 @@ it.effect("returns unauthenticated when auth probe reports login required", () =
|
||||
status.message,
|
||||
"Codex CLI is not authenticated. Run `codex login` and try again.",
|
||||
);
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status") {
|
||||
return { stdout: "", stderr: "Not logged in. Run codex login.", code: 1 };
|
||||
}
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"returns unauthenticated when login status output includes 'not logged in'",
|
||||
"returns unauthenticated when login status output includes 'not logged in'",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkCodexProviderStatus(
|
||||
mockRunner((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status")
|
||||
return { stdout: "Not logged in\n", stderr: "", code: 1 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
);
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.available, true);
|
||||
@@ -90,21 +123,22 @@ it.effect(
|
||||
status.message,
|
||||
"Codex CLI is not authenticated. Run `codex login` and try again.",
|
||||
);
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status")
|
||||
return { stdout: "Not logged in\n", stderr: "", code: 1 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns warning when login status command is unsupported", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkCodexProviderStatus(
|
||||
mockRunner((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status") {
|
||||
return { stdout: "", stderr: "error: unknown command 'login'", code: 2 };
|
||||
}
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
);
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "warning");
|
||||
assert.strictEqual(status.available, true);
|
||||
@@ -113,7 +147,18 @@ it.effect("returns warning when login status command is unsupported", () =>
|
||||
status.message,
|
||||
"Codex CLI authentication status command is unavailable in this Codex version.",
|
||||
);
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status") {
|
||||
return { stdout: "", stderr: "error: unknown command 'login'", code: 2 };
|
||||
}
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
// ── Pure function tests ─────────────────────────────────────────────
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* Performs one-time provider readiness probes when the server starts and
|
||||
* keeps the resulting snapshot in memory for `server.getConfig`.
|
||||
*
|
||||
* Uses the shared process runner to run CLI probes natively.
|
||||
* Uses effect's ChildProcessSpawner to run CLI probes natively.
|
||||
*
|
||||
* @module ProviderHealthLive
|
||||
*/
|
||||
@@ -13,43 +13,20 @@ import type {
|
||||
ServerProviderStatus,
|
||||
ServerProviderStatusState,
|
||||
} from "@t3tools/contracts";
|
||||
import { Data, Effect, Layer, Result } from "effect";
|
||||
import { Effect, Layer, Option, Result, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { runProcess } from "../../processRunner";
|
||||
import { ProviderHealth, type ProviderHealthShape } from "../Services/ProviderHealth";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 4_000;
|
||||
const CODEX_PROVIDER = "codex" as const;
|
||||
|
||||
class ProviderHealthCommandError extends Data.TaggedError("ProviderHealthCommandError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
// ── Pure helpers ────────────────────────────────────────────────────
|
||||
|
||||
export interface CommandResult {
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly code: number;
|
||||
readonly timedOut?: boolean;
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
}
|
||||
|
||||
if (
|
||||
error &&
|
||||
typeof error === "object" &&
|
||||
"message" in error &&
|
||||
typeof (error as { message?: unknown }).message === "string"
|
||||
) {
|
||||
return (error as { message: string }).message;
|
||||
}
|
||||
|
||||
return String(error);
|
||||
}
|
||||
|
||||
function nonEmptyTrimmed(value: string | undefined): string | undefined {
|
||||
@@ -59,7 +36,8 @@ function nonEmptyTrimmed(value: string | undefined): string | undefined {
|
||||
}
|
||||
|
||||
function isCommandMissingCause(error: unknown): boolean {
|
||||
const lower = errorMessage(error).toLowerCase();
|
||||
if (!(error instanceof Error)) return false;
|
||||
const lower = error.message.toLowerCase();
|
||||
return (
|
||||
lower.includes("command not found: codex") ||
|
||||
lower.includes("spawn codex enoent") ||
|
||||
@@ -109,14 +87,6 @@ export function parseAuthStatusFromOutput(result: CommandResult): {
|
||||
readonly authStatus: ServerProviderAuthStatus;
|
||||
readonly message?: string;
|
||||
} {
|
||||
if (result.timedOut) {
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message: "Timed out while checking Codex authentication status.",
|
||||
};
|
||||
}
|
||||
|
||||
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
|
||||
|
||||
if (
|
||||
@@ -192,115 +162,140 @@ export function parseAuthStatusFromOutput(result: CommandResult): {
|
||||
};
|
||||
}
|
||||
|
||||
export type RunProviderHealthCommand = (
|
||||
args: ReadonlyArray<string>,
|
||||
) => Promise<CommandResult>;
|
||||
// ── Effect-native command execution ─────────────────────────────────
|
||||
|
||||
const defaultRunCodexCommand: RunProviderHealthCommand = async (args) => {
|
||||
const result = await runProcess("codex", [...args], {
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: DEFAULT_TIMEOUT_MS,
|
||||
maxBufferBytes: 262_144,
|
||||
outputMode: "truncate",
|
||||
});
|
||||
const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
|
||||
Stream.runFold(
|
||||
stream,
|
||||
() => "",
|
||||
(acc, chunk) => acc + new TextDecoder().decode(chunk),
|
||||
);
|
||||
|
||||
return {
|
||||
stdout: result.stdout,
|
||||
stderr: result.stderr,
|
||||
code: result.code ?? 0,
|
||||
timedOut: result.timedOut,
|
||||
} satisfies CommandResult;
|
||||
};
|
||||
const runCodexCommand = (args: ReadonlyArray<string>) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const command = ChildProcess.make("codex", [...args], {
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
|
||||
const child = yield* spawner.spawn(command);
|
||||
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
collectStreamAsString(child.stdout),
|
||||
collectStreamAsString(child.stderr),
|
||||
child.exitCode.pipe(Effect.map(Number)),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
return { stdout, stderr, code: exitCode } satisfies CommandResult;
|
||||
}).pipe(Effect.scoped);
|
||||
|
||||
// ── Health check ────────────────────────────────────────────────────
|
||||
|
||||
export const checkCodexProviderStatus = (
|
||||
runCodexCommand: RunProviderHealthCommand = defaultRunCodexCommand,
|
||||
): Effect.Effect<ServerProviderStatus> =>
|
||||
Effect.gen(function* () {
|
||||
const checkedAt = new Date().toISOString();
|
||||
export const checkCodexProviderStatus: Effect.Effect<
|
||||
ServerProviderStatus,
|
||||
never,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> = Effect.gen(function* () {
|
||||
const checkedAt = new Date().toISOString();
|
||||
|
||||
// Probe 1: `codex --version` — is the CLI reachable?
|
||||
const versionProbe = yield* Effect.tryPromise({
|
||||
try: () => runCodexCommand(["--version"]),
|
||||
catch: (error) =>
|
||||
new ProviderHealthCommandError({
|
||||
message: errorMessage(error),
|
||||
...(error !== undefined ? { cause: error } : {}),
|
||||
}),
|
||||
}).pipe(Effect.result);
|
||||
// Probe 1: `codex --version` — is the CLI reachable?
|
||||
const versionProbe = yield* runCodexCommand(["--version"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
if (Result.isFailure(versionProbe)) {
|
||||
const error = versionProbe.failure;
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "error" as const,
|
||||
available: false,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: isCommandMissingCause(error)
|
||||
? "Codex CLI (`codex`) is not installed or not on PATH."
|
||||
: `Failed to execute Codex CLI health check: ${errorMessage(error)}.`,
|
||||
};
|
||||
}
|
||||
|
||||
const version = versionProbe.success;
|
||||
if (version.timedOut || version.code !== 0) {
|
||||
const detail = detailFromResult(version);
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "error" as const,
|
||||
available: false,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: detail
|
||||
? `Codex CLI is installed but failed to run. ${detail}`
|
||||
: "Codex CLI is installed but failed to run.",
|
||||
};
|
||||
}
|
||||
|
||||
// Probe 2: `codex login status` — is the user authenticated?
|
||||
const authProbe = yield* Effect.tryPromise({
|
||||
try: () => runCodexCommand(["login", "status"]),
|
||||
catch: (error) =>
|
||||
new ProviderHealthCommandError({
|
||||
message: errorMessage(error),
|
||||
...(error !== undefined ? { cause: error } : {}),
|
||||
}),
|
||||
}).pipe(Effect.result);
|
||||
|
||||
if (Result.isFailure(authProbe)) {
|
||||
const error = authProbe.failure;
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "warning" as const,
|
||||
available: true,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message:
|
||||
errorMessage(error).length > 0
|
||||
? `Could not verify Codex authentication status: ${errorMessage(error)}.`
|
||||
: "Could not verify Codex authentication status.",
|
||||
};
|
||||
}
|
||||
|
||||
const parsed = parseAuthStatusFromOutput(authProbe.success);
|
||||
if (Result.isFailure(versionProbe)) {
|
||||
const error = versionProbe.failure;
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: parsed.status,
|
||||
available: true,
|
||||
authStatus: parsed.authStatus,
|
||||
status: "error" as const,
|
||||
available: false,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
...(parsed.message ? { message: parsed.message } : {}),
|
||||
} satisfies ServerProviderStatus;
|
||||
});
|
||||
message: isCommandMissingCause(error)
|
||||
? "Codex CLI (`codex`) is not installed or not on PATH."
|
||||
: `Failed to execute Codex CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
|
||||
};
|
||||
}
|
||||
|
||||
if (Option.isNone(versionProbe.success)) {
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "error" as const,
|
||||
available: false,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: "Codex CLI is installed but failed to run. Timed out while running command.",
|
||||
};
|
||||
}
|
||||
|
||||
const version = versionProbe.success.value;
|
||||
if (version.code !== 0) {
|
||||
const detail = detailFromResult(version);
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "error" as const,
|
||||
available: false,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: detail
|
||||
? `Codex CLI is installed but failed to run. ${detail}`
|
||||
: "Codex CLI is installed but failed to run.",
|
||||
};
|
||||
}
|
||||
|
||||
// Probe 2: `codex login status` — is the user authenticated?
|
||||
const authProbe = yield* runCodexCommand(["login", "status"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
if (Result.isFailure(authProbe)) {
|
||||
const error = authProbe.failure;
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "warning" as const,
|
||||
available: true,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message:
|
||||
error instanceof Error
|
||||
? `Could not verify Codex authentication status: ${error.message}.`
|
||||
: "Could not verify Codex authentication status.",
|
||||
};
|
||||
}
|
||||
|
||||
if (Option.isNone(authProbe.success)) {
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "warning" as const,
|
||||
available: true,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: "Could not verify Codex authentication status. Timed out while running command.",
|
||||
};
|
||||
}
|
||||
|
||||
const parsed = parseAuthStatusFromOutput(authProbe.success.value);
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: parsed.status,
|
||||
available: true,
|
||||
authStatus: parsed.authStatus,
|
||||
checkedAt,
|
||||
...(parsed.message ? { message: parsed.message } : {}),
|
||||
} satisfies ServerProviderStatus;
|
||||
});
|
||||
|
||||
// ── Layer ───────────────────────────────────────────────────────────
|
||||
|
||||
export const ProviderHealthLive = Layer.effect(
|
||||
ProviderHealth,
|
||||
Effect.gen(function* () {
|
||||
const codexStatus = yield* checkCodexProviderStatus();
|
||||
const codexStatus = yield* checkCodexProviderStatus;
|
||||
return {
|
||||
getStatuses: Effect.succeed([codexStatus]),
|
||||
} satisfies ProviderHealthShape;
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
|
||||
|
||||
describe("detectServerRuntimeEnvironment", () => {
|
||||
it("detects native windows mode", () => {
|
||||
expect(
|
||||
detectServerRuntimeEnvironment({
|
||||
platform: "win32",
|
||||
env: {},
|
||||
osRelease: "10.0.26100",
|
||||
}),
|
||||
).toEqual({
|
||||
platform: "windows",
|
||||
pathStyle: "windows",
|
||||
isWsl: false,
|
||||
windowsInteropMode: "windows-native",
|
||||
wslDistroName: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("detects wsl-hosted mode from environment variables", () => {
|
||||
expect(
|
||||
detectServerRuntimeEnvironment({
|
||||
platform: "linux",
|
||||
env: {
|
||||
WSL_DISTRO_NAME: "Ubuntu-24.04",
|
||||
WSL_INTEROP: "/run/WSL/123_interop",
|
||||
},
|
||||
osRelease: "6.6.87.2-microsoft-standard-WSL2",
|
||||
}),
|
||||
).toEqual({
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu-24.04",
|
||||
});
|
||||
});
|
||||
|
||||
it("detects wsl-hosted mode from os release when env is unavailable", () => {
|
||||
expect(
|
||||
detectServerRuntimeEnvironment({
|
||||
platform: "linux",
|
||||
env: {},
|
||||
osRelease: "5.15.167.4-microsoft-standard-WSL2",
|
||||
}),
|
||||
).toEqual({
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("leaves non-wsl posix hosts outside the windows interop modes", () => {
|
||||
expect(
|
||||
detectServerRuntimeEnvironment({
|
||||
platform: "darwin",
|
||||
env: {},
|
||||
osRelease: "24.3.0",
|
||||
}),
|
||||
).toEqual({
|
||||
platform: "macos",
|
||||
pathStyle: "posix",
|
||||
isWsl: false,
|
||||
windowsInteropMode: null,
|
||||
wslDistroName: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,54 +0,0 @@
|
||||
import os from "node:os";
|
||||
|
||||
import type { ServerRuntimeEnvironment } from "@t3tools/contracts";
|
||||
|
||||
interface DetectServerRuntimeEnvironmentOptions {
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
readonly osRelease?: string;
|
||||
}
|
||||
|
||||
function normalizePlatform(platform: NodeJS.Platform): ServerRuntimeEnvironment["platform"] {
|
||||
switch (platform) {
|
||||
case "win32":
|
||||
return "windows";
|
||||
case "darwin":
|
||||
return "macos";
|
||||
default:
|
||||
return "linux";
|
||||
}
|
||||
}
|
||||
|
||||
function detectWsl(options: {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly osRelease: string;
|
||||
}): boolean {
|
||||
if (options.platform !== "linux") {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (options.env.WSL_DISTRO_NAME || options.env.WSL_INTEROP) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return options.osRelease.toLowerCase().includes("microsoft");
|
||||
}
|
||||
|
||||
export function detectServerRuntimeEnvironment(
|
||||
options: DetectServerRuntimeEnvironmentOptions = {},
|
||||
): ServerRuntimeEnvironment {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const env = options.env ?? process.env;
|
||||
const osRelease = options.osRelease ?? os.release();
|
||||
const normalizedPlatform = normalizePlatform(platform);
|
||||
const isWsl = detectWsl({ platform, env, osRelease });
|
||||
|
||||
return {
|
||||
platform: normalizedPlatform,
|
||||
pathStyle: normalizedPlatform === "windows" ? "windows" : "posix",
|
||||
isWsl,
|
||||
windowsInteropMode: normalizedPlatform === "windows" ? "windows-native" : isWsl ? "wsl-hosted" : null,
|
||||
wslDistroName: isWsl ? env.WSL_DISTRO_NAME?.trim() || null : null,
|
||||
};
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import path from "node:path";
|
||||
|
||||
import {
|
||||
DEFAULT_TERMINAL_ID,
|
||||
type ServerRuntimeEnvironment,
|
||||
type TerminalEvent,
|
||||
type TerminalOpenInput,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -17,11 +16,7 @@ import {
|
||||
type PtyProcess,
|
||||
type PtySpawnInput,
|
||||
} from "../Services/PTY";
|
||||
import {
|
||||
resolveShellCandidates,
|
||||
TerminalManagerRuntime,
|
||||
validateTerminalCwdForRuntime,
|
||||
} from "./Manager";
|
||||
import { TerminalManagerRuntime } from "./Manager";
|
||||
import { Effect, Encoding } from "effect";
|
||||
|
||||
class FakePtyProcess implements PtyProcess {
|
||||
@@ -177,7 +172,6 @@ describe("TerminalManager", () => {
|
||||
options: {
|
||||
shellResolver?: () => string;
|
||||
subprocessChecker?: (terminalPid: number) => Promise<boolean>;
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment;
|
||||
subprocessPollIntervalMs?: number;
|
||||
processKillGraceMs?: number;
|
||||
maxRetainedInactiveSessions?: number;
|
||||
@@ -192,7 +186,6 @@ describe("TerminalManager", () => {
|
||||
ptyAdapter,
|
||||
historyLineLimit,
|
||||
shellResolver: options.shellResolver ?? (() => "/bin/bash"),
|
||||
...(options.runtimeEnvironment ? { runtimeEnvironment: options.runtimeEnvironment } : {}),
|
||||
...(options.subprocessChecker ? { subprocessChecker: options.subprocessChecker } : {}),
|
||||
...(options.subprocessPollIntervalMs
|
||||
? { subprocessPollIntervalMs: options.subprocessPollIntervalMs }
|
||||
@@ -676,93 +669,4 @@ describe("TerminalManager", () => {
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("resolves Windows shell candidates from runtime environment instead of host assumptions", () => {
|
||||
const runtimeEnvironment: ServerRuntimeEnvironment = {
|
||||
platform: "windows",
|
||||
pathStyle: "windows",
|
||||
isWsl: false,
|
||||
windowsInteropMode: "windows-native",
|
||||
wslDistroName: null,
|
||||
};
|
||||
|
||||
const candidates = resolveShellCandidates(() => "/bin/bash -l", runtimeEnvironment);
|
||||
|
||||
expect(candidates.map((candidate) => candidate.shell)).toContain("cmd.exe");
|
||||
expect(candidates.map((candidate) => candidate.shell)).toContain("powershell.exe");
|
||||
expect(candidates.map((candidate) => candidate.shell)).not.toContain("/bin/sh");
|
||||
});
|
||||
|
||||
it("resolves POSIX shell candidates for wsl-hosted runtime even when the requested shell is Windows-style", () => {
|
||||
const runtimeEnvironment: ServerRuntimeEnvironment = {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
};
|
||||
|
||||
const candidates = resolveShellCandidates(() => "powershell.exe", runtimeEnvironment);
|
||||
|
||||
expect(candidates.map((candidate) => candidate.shell)).toContain("powershell.exe");
|
||||
expect(candidates.map((candidate) => candidate.shell)).toContain("/bin/bash");
|
||||
expect(candidates.map((candidate) => candidate.shell)).toContain("sh");
|
||||
});
|
||||
|
||||
it("rejects POSIX cwd values for windows-native terminal runtimes", async () => {
|
||||
const runtimeEnvironment: ServerRuntimeEnvironment = {
|
||||
platform: "windows",
|
||||
pathStyle: "windows",
|
||||
isWsl: false,
|
||||
windowsInteropMode: "windows-native",
|
||||
wslDistroName: null,
|
||||
};
|
||||
const { manager, ptyAdapter } = makeManager(5, { runtimeEnvironment });
|
||||
|
||||
await expect(manager.open(openInput({ cwd: "/home/julius/project" }))).rejects.toThrow(
|
||||
"Terminal cwd does not match Windows runtime path style",
|
||||
);
|
||||
expect(ptyAdapter.spawnInputs).toHaveLength(0);
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("rejects Windows cwd values for wsl-hosted terminal runtimes", async () => {
|
||||
const runtimeEnvironment: ServerRuntimeEnvironment = {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
};
|
||||
const { manager, ptyAdapter } = makeManager(5, { runtimeEnvironment });
|
||||
|
||||
await expect(manager.open(openInput({ cwd: "C:\\Users\\julius\\project" }))).rejects.toThrow(
|
||||
"Terminal cwd does not match POSIX runtime path style",
|
||||
);
|
||||
expect(ptyAdapter.spawnInputs).toHaveLength(0);
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("validates cwd compatibility as a pure runtime helper", () => {
|
||||
expect(
|
||||
validateTerminalCwdForRuntime("/repo", {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
}),
|
||||
).toBeNull();
|
||||
expect(
|
||||
validateTerminalCwdForRuntime("\\\\wsl.localhost\\Ubuntu\\repo", {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
}),
|
||||
).toContain("POSIX runtime path style");
|
||||
});
|
||||
});
|
||||
@@ -9,14 +9,12 @@ import {
|
||||
TerminalOpenInput,
|
||||
TerminalResizeInput,
|
||||
TerminalWriteInput,
|
||||
type ServerRuntimeEnvironment,
|
||||
type TerminalEvent,
|
||||
type TerminalSessionSnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Encoding, Layer, Path, Schema } from "effect";
|
||||
|
||||
import { createLogger } from "../../logger";
|
||||
import { detectServerRuntimeEnvironment } from "../../runtimeEnvironment";
|
||||
import { PtyAdapter, PtyAdapterShape, type PtyExitEvent, type PtyProcess } from "../Services/PTY";
|
||||
import { runProcess } from "../../processRunner";
|
||||
import { ServerConfig } from "../../config";
|
||||
@@ -37,8 +35,6 @@ const DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS = 128;
|
||||
const DEFAULT_OPEN_COLS = 120;
|
||||
const DEFAULT_OPEN_ROWS = 30;
|
||||
const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECTRON_RUN_AS_NODE"]);
|
||||
const WINDOWS_ABSOLUTE_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
|
||||
const WINDOWS_UNC_PATH_PATTERN = /^\\\\/;
|
||||
|
||||
const decodeTerminalOpenInput = Schema.decodeUnknownSync(TerminalOpenInput);
|
||||
const decodeTerminalWriteInput = Schema.decodeUnknownSync(TerminalWriteInput);
|
||||
@@ -48,22 +44,19 @@ const decodeTerminalCloseInput = Schema.decodeUnknownSync(TerminalCloseInput);
|
||||
|
||||
type TerminalSubprocessChecker = (terminalPid: number) => Promise<boolean>;
|
||||
|
||||
function defaultShellResolver(runtimeEnvironment: ServerRuntimeEnvironment): string {
|
||||
if (runtimeEnvironment.platform === "windows") {
|
||||
function defaultShellResolver(): string {
|
||||
if (process.platform === "win32") {
|
||||
return process.env.ComSpec ?? "cmd.exe";
|
||||
}
|
||||
return process.env.SHELL ?? "bash";
|
||||
}
|
||||
|
||||
function normalizeShellCommand(
|
||||
value: string | undefined,
|
||||
runtimeEnvironment: ServerRuntimeEnvironment,
|
||||
): string | null {
|
||||
function normalizeShellCommand(value: string | undefined): string | null {
|
||||
if (!value) return null;
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.length === 0) return null;
|
||||
|
||||
if (runtimeEnvironment.platform === "windows") {
|
||||
if (process.platform === "win32") {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
@@ -72,13 +65,10 @@ function normalizeShellCommand(
|
||||
return firstToken.replace(/^['"]|['"]$/g, "");
|
||||
}
|
||||
|
||||
function shellCandidateFromCommand(
|
||||
command: string | null,
|
||||
runtimeEnvironment: ServerRuntimeEnvironment,
|
||||
): ShellCandidate | null {
|
||||
function shellCandidateFromCommand(command: string | null): ShellCandidate | null {
|
||||
if (!command || command.length === 0) return null;
|
||||
const shellName = path.basename(command).toLowerCase();
|
||||
if (runtimeEnvironment.platform !== "windows" && shellName === "zsh") {
|
||||
if (process.platform !== "win32" && shellName === "zsh") {
|
||||
return { shell: command, args: ["-o", "nopromptsp"] };
|
||||
}
|
||||
return { shell: command };
|
||||
@@ -102,36 +92,27 @@ function uniqueShellCandidates(candidates: Array<ShellCandidate | null>): ShellC
|
||||
return ordered;
|
||||
}
|
||||
|
||||
export function resolveShellCandidates(
|
||||
shellResolver: () => string,
|
||||
runtimeEnvironment: ServerRuntimeEnvironment = detectServerRuntimeEnvironment(),
|
||||
): ShellCandidate[] {
|
||||
const requested = shellCandidateFromCommand(
|
||||
normalizeShellCommand(shellResolver(), runtimeEnvironment),
|
||||
runtimeEnvironment,
|
||||
);
|
||||
function resolveShellCandidates(shellResolver: () => string): ShellCandidate[] {
|
||||
const requested = shellCandidateFromCommand(normalizeShellCommand(shellResolver()));
|
||||
|
||||
if (runtimeEnvironment.platform === "windows") {
|
||||
if (process.platform === "win32") {
|
||||
return uniqueShellCandidates([
|
||||
requested,
|
||||
shellCandidateFromCommand(process.env.ComSpec ?? null, runtimeEnvironment),
|
||||
shellCandidateFromCommand("powershell.exe", runtimeEnvironment),
|
||||
shellCandidateFromCommand("cmd.exe", runtimeEnvironment),
|
||||
shellCandidateFromCommand(process.env.ComSpec ?? null),
|
||||
shellCandidateFromCommand("powershell.exe"),
|
||||
shellCandidateFromCommand("cmd.exe"),
|
||||
]);
|
||||
}
|
||||
|
||||
return uniqueShellCandidates([
|
||||
requested,
|
||||
shellCandidateFromCommand(
|
||||
normalizeShellCommand(process.env.SHELL, runtimeEnvironment),
|
||||
runtimeEnvironment,
|
||||
),
|
||||
shellCandidateFromCommand("/bin/zsh", runtimeEnvironment),
|
||||
shellCandidateFromCommand("/bin/bash", runtimeEnvironment),
|
||||
shellCandidateFromCommand("/bin/sh", runtimeEnvironment),
|
||||
shellCandidateFromCommand("zsh", runtimeEnvironment),
|
||||
shellCandidateFromCommand("bash", runtimeEnvironment),
|
||||
shellCandidateFromCommand("sh", runtimeEnvironment),
|
||||
shellCandidateFromCommand(normalizeShellCommand(process.env.SHELL)),
|
||||
shellCandidateFromCommand("/bin/zsh"),
|
||||
shellCandidateFromCommand("/bin/bash"),
|
||||
shellCandidateFromCommand("/bin/sh"),
|
||||
shellCandidateFromCommand("zsh"),
|
||||
shellCandidateFromCommand("bash"),
|
||||
shellCandidateFromCommand("sh"),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -197,13 +178,6 @@ async function checkWindowsSubprocessActivity(terminalPid: number): Promise<bool
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: 32_768,
|
||||
outputMode: "truncate",
|
||||
runtimeEnvironment: {
|
||||
platform: "windows",
|
||||
pathStyle: "windows",
|
||||
isWsl: false,
|
||||
windowsInteropMode: "windows-native",
|
||||
wslDistroName: null,
|
||||
},
|
||||
},
|
||||
);
|
||||
return result.code === 0;
|
||||
@@ -256,37 +230,14 @@ async function checkPosixSubprocessActivity(terminalPid: number): Promise<boolea
|
||||
}
|
||||
}
|
||||
|
||||
function createDefaultSubprocessChecker(runtimeEnvironment: ServerRuntimeEnvironment) {
|
||||
return async (terminalPid: number): Promise<boolean> => {
|
||||
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
|
||||
return false;
|
||||
}
|
||||
if (runtimeEnvironment.platform === "windows") {
|
||||
return checkWindowsSubprocessActivity(terminalPid);
|
||||
}
|
||||
return checkPosixSubprocessActivity(terminalPid);
|
||||
};
|
||||
}
|
||||
|
||||
function isWindowsPath(value: string): boolean {
|
||||
return WINDOWS_ABSOLUTE_PATH_PATTERN.test(value) || WINDOWS_UNC_PATH_PATTERN.test(value);
|
||||
}
|
||||
|
||||
export function validateTerminalCwdForRuntime(
|
||||
cwd: string,
|
||||
runtimeEnvironment: ServerRuntimeEnvironment = detectServerRuntimeEnvironment(),
|
||||
): string | null {
|
||||
if (runtimeEnvironment.pathStyle === "windows") {
|
||||
if (cwd.startsWith("/")) {
|
||||
return `Terminal cwd does not match Windows runtime path style: ${cwd}`;
|
||||
}
|
||||
return null;
|
||||
async function defaultSubprocessChecker(terminalPid: number): Promise<boolean> {
|
||||
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isWindowsPath(cwd)) {
|
||||
return `Terminal cwd does not match POSIX runtime path style: ${cwd}`;
|
||||
if (process.platform === "win32") {
|
||||
return checkWindowsSubprocessActivity(terminalPid);
|
||||
}
|
||||
return null;
|
||||
return checkPosixSubprocessActivity(terminalPid);
|
||||
}
|
||||
|
||||
function capHistory(history: string, maxLines: number): string {
|
||||
@@ -365,7 +316,6 @@ interface TerminalManagerOptions {
|
||||
ptyAdapter: PtyAdapterShape;
|
||||
shellResolver?: () => string;
|
||||
subprocessChecker?: TerminalSubprocessChecker;
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment;
|
||||
subprocessPollIntervalMs?: number;
|
||||
processKillGraceMs?: number;
|
||||
maxRetainedInactiveSessions?: number;
|
||||
@@ -383,7 +333,6 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
||||
private readonly threadLocks = new Map<string, Promise<void>>();
|
||||
private readonly persistDebounceMs: number;
|
||||
private readonly subprocessChecker: TerminalSubprocessChecker;
|
||||
private readonly runtimeEnvironment: ServerRuntimeEnvironment;
|
||||
private readonly subprocessPollIntervalMs: number;
|
||||
private readonly processKillGraceMs: number;
|
||||
private readonly maxRetainedInactiveSessions: number;
|
||||
@@ -394,15 +343,12 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
||||
|
||||
constructor(options: TerminalManagerOptions) {
|
||||
super();
|
||||
this.runtimeEnvironment = options.runtimeEnvironment ?? detectServerRuntimeEnvironment();
|
||||
this.logsDir = options.logsDir ?? path.resolve(process.cwd(), ".logs", "terminals");
|
||||
this.historyLineLimit = options.historyLineLimit ?? DEFAULT_HISTORY_LINE_LIMIT;
|
||||
this.ptyAdapter = options.ptyAdapter;
|
||||
this.shellResolver =
|
||||
options.shellResolver ?? (() => defaultShellResolver(this.runtimeEnvironment));
|
||||
this.shellResolver = options.shellResolver ?? defaultShellResolver;
|
||||
this.persistDebounceMs = DEFAULT_PERSIST_DEBOUNCE_MS;
|
||||
this.subprocessChecker =
|
||||
options.subprocessChecker ?? createDefaultSubprocessChecker(this.runtimeEnvironment);
|
||||
this.subprocessChecker = options.subprocessChecker ?? defaultSubprocessChecker;
|
||||
this.subprocessPollIntervalMs =
|
||||
options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS;
|
||||
this.processKillGraceMs = options.processKillGraceMs ?? DEFAULT_PROCESS_KILL_GRACE_MS;
|
||||
@@ -643,7 +589,7 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
||||
let ptyProcess: PtyProcess | null = null;
|
||||
let startedShell: string | null = null;
|
||||
try {
|
||||
const shellCandidates = resolveShellCandidates(this.shellResolver, this.runtimeEnvironment);
|
||||
const shellCandidates = resolveShellCandidates(this.shellResolver);
|
||||
const terminalEnv = createTerminalSpawnEnv(process.env, session.runtimeEnv);
|
||||
let lastSpawnError: unknown = null;
|
||||
|
||||
@@ -1105,11 +1051,6 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
||||
}
|
||||
|
||||
private async assertValidCwd(cwd: string): Promise<void> {
|
||||
const runtimePathError = validateTerminalCwdForRuntime(cwd, this.runtimeEnvironment);
|
||||
if (runtimePathError) {
|
||||
throw new Error(runtimePathError);
|
||||
}
|
||||
|
||||
let stats: fs.Stats;
|
||||
try {
|
||||
stats = await fs.promises.stat(cwd);
|
||||
@@ -1232,11 +1173,10 @@ export const TerminalManagerLive = Layer.effect(
|
||||
const { stateDir } = yield* ServerConfig;
|
||||
const { join } = yield* Path.Path;
|
||||
const logsDir = join(stateDir, "logs", "terminals");
|
||||
const runtimeEnvironment = detectServerRuntimeEnvironment();
|
||||
|
||||
const ptyAdapter = yield* PtyAdapter;
|
||||
const runtime = yield* Effect.acquireRelease(
|
||||
Effect.sync(() => new TerminalManagerRuntime({ logsDir, ptyAdapter, runtimeEnvironment })),
|
||||
Effect.sync(() => new TerminalManagerRuntime({ logsDir, ptyAdapter })),
|
||||
(r) => Effect.sync(() => r.dispose()),
|
||||
);
|
||||
|
||||
|
||||
@@ -51,7 +51,6 @@ import type { GitCoreShape } from "./git/Services/GitCore.ts";
|
||||
import { GitCore } from "./git/Services/GitCore.ts";
|
||||
import { GitCommandError, GitManagerError } from "./git/Errors.ts";
|
||||
import { MigrationError } from "@effect/sql-sqlite-bun/SqliteMigrator";
|
||||
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
|
||||
|
||||
interface PendingMessages {
|
||||
queue: unknown[];
|
||||
@@ -86,8 +85,6 @@ const defaultProviderHealthService: ProviderHealthShape = {
|
||||
getStatuses: Effect.succeed(defaultProviderStatuses),
|
||||
};
|
||||
|
||||
const defaultRuntimeEnvironment = detectServerRuntimeEnvironment();
|
||||
|
||||
class MockTerminalManager implements TerminalManagerShape {
|
||||
private readonly sessions = new Map<string, TerminalSessionSnapshot>();
|
||||
private readonly listeners = new Set<(event: TerminalEvent) => void>();
|
||||
@@ -763,7 +760,6 @@ describe("WebSocket Server", () => {
|
||||
issues: [],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
runtimeEnvironment: defaultRuntimeEnvironment,
|
||||
});
|
||||
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
|
||||
});
|
||||
@@ -790,7 +786,6 @@ describe("WebSocket Server", () => {
|
||||
issues: [],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
runtimeEnvironment: defaultRuntimeEnvironment,
|
||||
});
|
||||
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
|
||||
|
||||
@@ -827,7 +822,6 @@ describe("WebSocket Server", () => {
|
||||
],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
runtimeEnvironment: defaultRuntimeEnvironment,
|
||||
});
|
||||
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
|
||||
expect(fs.readFileSync(keybindingsPath, "utf8")).toBe("{ not-json");
|
||||
@@ -863,7 +857,6 @@ describe("WebSocket Server", () => {
|
||||
issues: Array<{ kind: string; index?: number; message: string }>;
|
||||
providers: ReadonlyArray<ServerProviderStatus>;
|
||||
availableEditors: unknown;
|
||||
runtimeEnvironment: unknown;
|
||||
};
|
||||
expect(result.cwd).toBe("/my/workspace");
|
||||
expect(result.keybindingsConfigPath).toBe(keybindingsPath);
|
||||
@@ -884,7 +877,6 @@ describe("WebSocket Server", () => {
|
||||
expect(result.keybindings.some((entry) => entry.command === "terminal.new")).toBe(true);
|
||||
expect(result.providers).toEqual(defaultProviderStatuses);
|
||||
expectAvailableEditors(result.availableEditors);
|
||||
expect(result.runtimeEnvironment).toEqual(defaultRuntimeEnvironment);
|
||||
});
|
||||
|
||||
it("pushes server.configUpdated issues when keybindings file changes", async () => {
|
||||
@@ -985,7 +977,6 @@ describe("WebSocket Server", () => {
|
||||
issues: [],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
runtimeEnvironment: defaultRuntimeEnvironment,
|
||||
});
|
||||
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
|
||||
});
|
||||
@@ -1034,7 +1025,6 @@ describe("WebSocket Server", () => {
|
||||
issues: [],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
runtimeEnvironment: defaultRuntimeEnvironment,
|
||||
});
|
||||
expectAvailableEditors(
|
||||
(configResponse.result as { availableEditors: unknown }).availableEditors,
|
||||
|
||||
@@ -59,7 +59,6 @@ import { Open, resolveAvailableEditors } from "./open";
|
||||
import { ServerConfig } from "./config";
|
||||
import { GitCore } from "./git/Services/GitCore.ts";
|
||||
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
|
||||
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
|
||||
import {
|
||||
ATTACHMENTS_ROUTE_PREFIX,
|
||||
normalizeAttachmentRelativePath,
|
||||
@@ -197,7 +196,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
autoBootstrapProjectFromCwd,
|
||||
} = serverConfig;
|
||||
const availableEditors = resolveAvailableEditors();
|
||||
const runtimeEnvironment = detectServerRuntimeEnvironment();
|
||||
|
||||
const gitManager = yield* GitManager;
|
||||
const terminalManager = yield* TerminalManager;
|
||||
@@ -747,7 +745,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
issues: keybindingsConfig.issues,
|
||||
providers: providerStatuses,
|
||||
availableEditors,
|
||||
runtimeEnvironment,
|
||||
};
|
||||
|
||||
case WS_METHODS.serverUpsertKeybinding: {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/web",
|
||||
"version": "0.0.0-alpha.18",
|
||||
"version": "0.0.0-alpha.20",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
@@ -9,7 +9,9 @@
|
||||
"prepare": "effect-language-service patch",
|
||||
"preview": "vite preview",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run --passWithNoTests"
|
||||
"test": "vitest run --passWithNoTests",
|
||||
"test:browser": "vitest run --config vitest.browser.config.ts",
|
||||
"test:browser:install": "playwright install --with-deps chromium"
|
||||
},
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.2.0",
|
||||
@@ -41,10 +43,14 @@
|
||||
"@types/react": "^19.0.0",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
"@vitejs/plugin-react": "^5.1.4",
|
||||
"@vitest/browser-playwright": "^4.0.18",
|
||||
"babel-plugin-react-compiler": "^19.0.0-beta-e552027-20250112",
|
||||
"msw": "^2.12.10",
|
||||
"playwright": "^1.58.2",
|
||||
"tailwindcss": "^4.0.0",
|
||||
"typescript": "catalog:",
|
||||
"vite": "^8.0.0-beta.12",
|
||||
"vitest": "catalog:"
|
||||
"vitest": "catalog:",
|
||||
"vitest-browser-react": "^2.0.5"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
/* eslint-disable */
|
||||
/* tslint:disable */
|
||||
|
||||
/**
|
||||
* Mock Service Worker.
|
||||
* @see https://github.com/mswjs/msw
|
||||
* - Please do NOT modify this file.
|
||||
*/
|
||||
|
||||
const PACKAGE_VERSION = '2.12.10'
|
||||
const INTEGRITY_CHECKSUM = '4db4a41e972cec1b64cc569c66952d82'
|
||||
const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
|
||||
const activeClientIds = new Set()
|
||||
|
||||
addEventListener('install', function () {
|
||||
self.skipWaiting()
|
||||
})
|
||||
|
||||
addEventListener('activate', function (event) {
|
||||
event.waitUntil(self.clients.claim())
|
||||
})
|
||||
|
||||
addEventListener('message', async function (event) {
|
||||
const clientId = Reflect.get(event.source || {}, 'id')
|
||||
|
||||
if (!clientId || !self.clients) {
|
||||
return
|
||||
}
|
||||
|
||||
const client = await self.clients.get(clientId)
|
||||
|
||||
if (!client) {
|
||||
return
|
||||
}
|
||||
|
||||
const allClients = await self.clients.matchAll({
|
||||
type: 'window',
|
||||
})
|
||||
|
||||
switch (event.data) {
|
||||
case 'KEEPALIVE_REQUEST': {
|
||||
sendToClient(client, {
|
||||
type: 'KEEPALIVE_RESPONSE',
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case 'INTEGRITY_CHECK_REQUEST': {
|
||||
sendToClient(client, {
|
||||
type: 'INTEGRITY_CHECK_RESPONSE',
|
||||
payload: {
|
||||
packageVersion: PACKAGE_VERSION,
|
||||
checksum: INTEGRITY_CHECKSUM,
|
||||
},
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case 'MOCK_ACTIVATE': {
|
||||
activeClientIds.add(clientId)
|
||||
|
||||
sendToClient(client, {
|
||||
type: 'MOCKING_ENABLED',
|
||||
payload: {
|
||||
client: {
|
||||
id: client.id,
|
||||
frameType: client.frameType,
|
||||
},
|
||||
},
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case 'CLIENT_CLOSED': {
|
||||
activeClientIds.delete(clientId)
|
||||
|
||||
const remainingClients = allClients.filter((client) => {
|
||||
return client.id !== clientId
|
||||
})
|
||||
|
||||
// Unregister itself when there are no more clients
|
||||
if (remainingClients.length === 0) {
|
||||
self.registration.unregister()
|
||||
}
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
addEventListener('fetch', function (event) {
|
||||
const requestInterceptedAt = Date.now()
|
||||
|
||||
// Bypass navigation requests.
|
||||
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
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
const requestId = crypto.randomUUID()
|
||||
event.respondWith(handleRequest(event, requestId, requestInterceptedAt))
|
||||
})
|
||||
|
||||
/**
|
||||
* @param {FetchEvent} event
|
||||
* @param {string} requestId
|
||||
* @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,
|
||||
)
|
||||
|
||||
// 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)
|
||||
|
||||
// Clone the response so both the client and the library could consume it.
|
||||
const responseClone = response.clone()
|
||||
|
||||
sendToClient(
|
||||
client,
|
||||
{
|
||||
type: 'RESPONSE',
|
||||
payload: {
|
||||
isMockedResponse: IS_MOCKED_RESPONSE in response,
|
||||
request: {
|
||||
id: requestId,
|
||||
...serializedRequest,
|
||||
},
|
||||
response: {
|
||||
type: responseClone.type,
|
||||
status: responseClone.status,
|
||||
statusText: responseClone.statusText,
|
||||
headers: Object.fromEntries(responseClone.headers.entries()),
|
||||
body: responseClone.body,
|
||||
},
|
||||
},
|
||||
},
|
||||
responseClone.body ? [serializedRequest.body, responseClone.body] : [],
|
||||
)
|
||||
}
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the main client for the given event.
|
||||
* Client that issues a request doesn't necessarily equal the client
|
||||
* that registered the worker. It's with the latter the worker should
|
||||
* communicate with during the response resolving phase.
|
||||
* @param {FetchEvent} event
|
||||
* @returns {Promise<Client | undefined>}
|
||||
*/
|
||||
async function resolveMainClient(event) {
|
||||
const client = await self.clients.get(event.clientId)
|
||||
|
||||
if (activeClientIds.has(event.clientId)) {
|
||||
return client
|
||||
}
|
||||
|
||||
if (client?.frameType === 'top-level') {
|
||||
return client
|
||||
}
|
||||
|
||||
const allClients = await self.clients.matchAll({
|
||||
type: 'window',
|
||||
})
|
||||
|
||||
return allClients
|
||||
.filter((client) => {
|
||||
// Get only those clients that are currently 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)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {FetchEvent} event
|
||||
* @param {Client | undefined} client
|
||||
* @param {string} requestId
|
||||
* @param {number} requestInterceptedAt
|
||||
* @returns {Promise<Response>}
|
||||
*/
|
||||
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()
|
||||
|
||||
function passthrough() {
|
||||
// Cast the request headers to a new Headers instance
|
||||
// so the headers can be manipulated with.
|
||||
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')
|
||||
if (acceptHeader) {
|
||||
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(', '))
|
||||
} else {
|
||||
headers.delete('accept')
|
||||
}
|
||||
}
|
||||
|
||||
return fetch(requestClone, { headers })
|
||||
}
|
||||
|
||||
// Bypass mocking when the client is not active.
|
||||
if (!client) {
|
||||
return passthrough()
|
||||
}
|
||||
|
||||
// Bypass initial page load requests (i.e. static assets).
|
||||
// The absence of the immediate/parent client in the map of the active clients
|
||||
// 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()
|
||||
}
|
||||
|
||||
// Notify the client that a request has been intercepted.
|
||||
const serializedRequest = await serializeRequest(event.request)
|
||||
const clientMessage = await sendToClient(
|
||||
client,
|
||||
{
|
||||
type: 'REQUEST',
|
||||
payload: {
|
||||
id: requestId,
|
||||
interceptedAt: requestInterceptedAt,
|
||||
...serializedRequest,
|
||||
},
|
||||
},
|
||||
[serializedRequest.body],
|
||||
)
|
||||
|
||||
switch (clientMessage.type) {
|
||||
case 'MOCK_RESPONSE': {
|
||||
return respondWithMock(clientMessage.data)
|
||||
}
|
||||
|
||||
case 'PASSTHROUGH': {
|
||||
return passthrough()
|
||||
}
|
||||
}
|
||||
|
||||
return passthrough()
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Client} client
|
||||
* @param {any} message
|
||||
* @param {Array<Transferable>} transferrables
|
||||
* @returns {Promise<any>}
|
||||
*/
|
||||
function sendToClient(client, message, transferrables = []) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const channel = new MessageChannel()
|
||||
|
||||
channel.port1.onmessage = (event) => {
|
||||
if (event.data && event.data.error) {
|
||||
return reject(event.data.error)
|
||||
}
|
||||
|
||||
resolve(event.data)
|
||||
}
|
||||
|
||||
client.postMessage(message, [
|
||||
channel.port2,
|
||||
...transferrables.filter(Boolean),
|
||||
])
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Response} response
|
||||
* @returns {Response}
|
||||
*/
|
||||
function respondWithMock(response) {
|
||||
// Setting response status code to 0 is a no-op.
|
||||
// However, when responding with a "Response.error()", the produced 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()
|
||||
}
|
||||
|
||||
const mockedResponse = new Response(response.body, response)
|
||||
|
||||
Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {
|
||||
value: true,
|
||||
enumerable: true,
|
||||
})
|
||||
|
||||
return mockedResponse
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Request} request
|
||||
*/
|
||||
async function serializeRequest(request) {
|
||||
return {
|
||||
url: request.url,
|
||||
mode: request.mode,
|
||||
method: request.method,
|
||||
headers: Object.fromEntries(request.headers.entries()),
|
||||
cache: request.cache,
|
||||
credentials: request.credentials,
|
||||
destination: request.destination,
|
||||
integrity: request.integrity,
|
||||
redirect: request.redirect,
|
||||
referrer: request.referrer,
|
||||
referrerPolicy: request.referrerPolicy,
|
||||
body: await request.arrayBuffer(),
|
||||
keepalive: request.keepalive,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,713 @@
|
||||
// Production CSS is part of the behavior under test because row height depends on it.
|
||||
import "../index.css";
|
||||
|
||||
import {
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
type MessageId,
|
||||
type OrchestrationReadModel,
|
||||
type ProjectId,
|
||||
type ProviderSessionId,
|
||||
type ServerConfig,
|
||||
type ThreadId,
|
||||
type WsWelcomePayload,
|
||||
WS_CHANNELS,
|
||||
WS_METHODS,
|
||||
} from "@t3tools/contracts";
|
||||
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 { render } from "vitest-browser-react";
|
||||
|
||||
import { getRouter } from "../router";
|
||||
import { useStore } from "../store";
|
||||
import { estimateTimelineMessageHeight } from "./timelineHeight";
|
||||
|
||||
const THREAD_ID = "thread-browser-test" as ThreadId;
|
||||
const PROJECT_ID = "project-1" as ProjectId;
|
||||
const NOW_ISO = "2026-03-04T12:00:00.000Z";
|
||||
const BASE_TIME_MS = Date.parse(NOW_ISO);
|
||||
const ATTACHMENT_SVG = "<svg xmlns='http://www.w3.org/2000/svg' width='120' height='300'></svg>";
|
||||
|
||||
interface WsRequestEnvelope {
|
||||
id: string;
|
||||
body: {
|
||||
_tag: string;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
}
|
||||
|
||||
interface TestFixture {
|
||||
snapshot: OrchestrationReadModel;
|
||||
serverConfig: ServerConfig;
|
||||
welcome: WsWelcomePayload;
|
||||
}
|
||||
|
||||
let fixture: TestFixture;
|
||||
const wsLink = ws.link(/ws(s)?:\/\/.*/);
|
||||
|
||||
interface ViewportSpec {
|
||||
name: string;
|
||||
width: number;
|
||||
height: number;
|
||||
textTolerancePx: number;
|
||||
attachmentTolerancePx: number;
|
||||
}
|
||||
|
||||
const DEFAULT_VIEWPORT: ViewportSpec = {
|
||||
name: "desktop",
|
||||
width: 960,
|
||||
height: 1_100,
|
||||
textTolerancePx: 44,
|
||||
attachmentTolerancePx: 56,
|
||||
};
|
||||
const TEXT_VIEWPORT_MATRIX = [
|
||||
DEFAULT_VIEWPORT,
|
||||
{ name: "tablet", width: 720, height: 1_024, textTolerancePx: 44, attachmentTolerancePx: 56 },
|
||||
{ name: "mobile", width: 430, height: 932, textTolerancePx: 56, attachmentTolerancePx: 56 },
|
||||
{ name: "narrow", width: 320, height: 700, textTolerancePx: 84, attachmentTolerancePx: 56 },
|
||||
] as const satisfies readonly ViewportSpec[];
|
||||
const ATTACHMENT_VIEWPORT_MATRIX = [
|
||||
DEFAULT_VIEWPORT,
|
||||
{ name: "mobile", width: 430, height: 932, textTolerancePx: 56, attachmentTolerancePx: 56 },
|
||||
{ name: "narrow", width: 320, height: 700, textTolerancePx: 84, attachmentTolerancePx: 56 },
|
||||
] as const satisfies readonly ViewportSpec[];
|
||||
|
||||
interface UserRowMeasurement {
|
||||
measuredRowHeightPx: number;
|
||||
timelineWidthMeasuredPx: number;
|
||||
renderedInVirtualizedRegion: boolean;
|
||||
}
|
||||
|
||||
interface MountedChatView {
|
||||
cleanup: () => Promise<void>;
|
||||
measureUserRow: (targetMessageId: MessageId) => Promise<UserRowMeasurement>;
|
||||
setViewport: (viewport: ViewportSpec) => Promise<void>;
|
||||
}
|
||||
|
||||
function isoAt(offsetSeconds: number): string {
|
||||
return new Date(BASE_TIME_MS + offsetSeconds * 1_000).toISOString();
|
||||
}
|
||||
|
||||
function createBaseServerConfig(): ServerConfig {
|
||||
return {
|
||||
cwd: "/repo/project",
|
||||
keybindingsConfigPath: "/repo/project/.t3code-keybindings.json",
|
||||
keybindings: [],
|
||||
issues: [],
|
||||
providers: [
|
||||
{
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
available: true,
|
||||
authStatus: "authenticated",
|
||||
checkedAt: NOW_ISO,
|
||||
},
|
||||
],
|
||||
availableEditors: [],
|
||||
};
|
||||
}
|
||||
|
||||
function createUserMessage(options: {
|
||||
id: MessageId;
|
||||
text: string;
|
||||
offsetSeconds: number;
|
||||
attachments?: Array<{
|
||||
type: "image";
|
||||
id: string;
|
||||
name: string;
|
||||
mimeType: string;
|
||||
sizeBytes: number;
|
||||
}>;
|
||||
}) {
|
||||
return {
|
||||
id: options.id,
|
||||
role: "user" as const,
|
||||
text: options.text,
|
||||
...(options.attachments ? { attachments: options.attachments } : {}),
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: isoAt(options.offsetSeconds),
|
||||
updatedAt: isoAt(options.offsetSeconds + 1),
|
||||
};
|
||||
}
|
||||
|
||||
function createAssistantMessage(options: { id: MessageId; text: string; offsetSeconds: number }) {
|
||||
return {
|
||||
id: options.id,
|
||||
role: "assistant" as const,
|
||||
text: options.text,
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: isoAt(options.offsetSeconds),
|
||||
updatedAt: isoAt(options.offsetSeconds + 1),
|
||||
};
|
||||
}
|
||||
|
||||
function createSnapshotForTargetUser(options: {
|
||||
targetMessageId: MessageId;
|
||||
targetText: string;
|
||||
targetAttachmentCount?: number;
|
||||
}): OrchestrationReadModel {
|
||||
const messages: Array<OrchestrationReadModel["threads"][number]["messages"][number]> = [];
|
||||
|
||||
for (let index = 0; index < 22; index += 1) {
|
||||
const isTarget = index === 3;
|
||||
const userId = `msg-user-${index}` as MessageId;
|
||||
const assistantId = `msg-assistant-${index}` as MessageId;
|
||||
const attachments =
|
||||
isTarget && (options.targetAttachmentCount ?? 0) > 0
|
||||
? Array.from({ length: options.targetAttachmentCount ?? 0 }, (_, attachmentIndex) => ({
|
||||
type: "image" as const,
|
||||
id: `attachment-${attachmentIndex + 1}`,
|
||||
name: `attachment-${attachmentIndex + 1}.png`,
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 128,
|
||||
}))
|
||||
: undefined;
|
||||
|
||||
messages.push(
|
||||
createUserMessage({
|
||||
id: isTarget ? options.targetMessageId : userId,
|
||||
text: isTarget ? options.targetText : `filler user message ${index}`,
|
||||
offsetSeconds: messages.length * 3,
|
||||
...(attachments ? { attachments } : {}),
|
||||
}),
|
||||
);
|
||||
messages.push(
|
||||
createAssistantMessage({
|
||||
id: assistantId,
|
||||
text: `assistant filler ${index}`,
|
||||
offsetSeconds: messages.length * 3,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
snapshotSequence: 1,
|
||||
projects: [
|
||||
{
|
||||
id: PROJECT_ID,
|
||||
title: "Project",
|
||||
workspaceRoot: "/repo/project",
|
||||
defaultModel: "gpt-5",
|
||||
scripts: [],
|
||||
createdAt: NOW_ISO,
|
||||
updatedAt: NOW_ISO,
|
||||
deletedAt: null,
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Browser test thread",
|
||||
model: "gpt-5",
|
||||
branch: "main",
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: NOW_ISO,
|
||||
updatedAt: NOW_ISO,
|
||||
deletedAt: null,
|
||||
messages,
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
session: {
|
||||
threadId: THREAD_ID,
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
providerSessionId: "session-1" as ProviderSessionId,
|
||||
providerThreadId: null,
|
||||
approvalPolicy: "on-failure",
|
||||
sandboxMode: "workspace-write",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: NOW_ISO,
|
||||
},
|
||||
},
|
||||
],
|
||||
updatedAt: NOW_ISO,
|
||||
};
|
||||
}
|
||||
|
||||
function buildFixture(snapshot: OrchestrationReadModel): TestFixture {
|
||||
return {
|
||||
snapshot,
|
||||
serverConfig: createBaseServerConfig(),
|
||||
welcome: {
|
||||
cwd: "/repo/project",
|
||||
projectName: "Project",
|
||||
bootstrapProjectId: PROJECT_ID,
|
||||
bootstrapThreadId: THREAD_ID,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function resolveWsRpc(tag: string): unknown {
|
||||
if (tag === ORCHESTRATION_WS_METHODS.getSnapshot) {
|
||||
return fixture.snapshot;
|
||||
}
|
||||
if (tag === WS_METHODS.serverGetConfig) {
|
||||
return fixture.serverConfig;
|
||||
}
|
||||
if (tag === WS_METHODS.gitListBranches) {
|
||||
return {
|
||||
isRepo: true,
|
||||
branches: [
|
||||
{
|
||||
name: "main",
|
||||
current: true,
|
||||
isDefault: true,
|
||||
worktreePath: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (tag === WS_METHODS.gitStatus) {
|
||||
return {
|
||||
branch: "main",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
};
|
||||
}
|
||||
if (tag === WS_METHODS.projectsSearchEntries) {
|
||||
return {
|
||||
entries: [],
|
||||
truncated: false,
|
||||
};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
const worker = setupWorker(
|
||||
wsLink.addEventListener("connection", ({ client }) => {
|
||||
client.send(
|
||||
JSON.stringify({
|
||||
type: "push",
|
||||
channel: WS_CHANNELS.serverWelcome,
|
||||
data: fixture.welcome,
|
||||
}),
|
||||
);
|
||||
client.addEventListener("message", (event) => {
|
||||
const rawData = event.data;
|
||||
if (typeof rawData !== "string") return;
|
||||
let request: WsRequestEnvelope;
|
||||
try {
|
||||
request = JSON.parse(rawData) as WsRequestEnvelope;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const method = request.body?._tag;
|
||||
if (typeof method !== "string") return;
|
||||
client.send(
|
||||
JSON.stringify({
|
||||
id: request.id,
|
||||
result: resolveWsRpc(method),
|
||||
}),
|
||||
);
|
||||
});
|
||||
}),
|
||||
http.get("*/attachments/:attachmentId", () =>
|
||||
HttpResponse.text(ATTACHMENT_SVG, {
|
||||
headers: {
|
||||
"Content-Type": "image/svg+xml",
|
||||
},
|
||||
}),
|
||||
),
|
||||
http.get("*/api/project-favicon", () => new HttpResponse(null, { status: 204 })),
|
||||
);
|
||||
|
||||
async function nextFrame(): Promise<void> {
|
||||
await new Promise<void>((resolve) => {
|
||||
window.requestAnimationFrame(() => resolve());
|
||||
});
|
||||
}
|
||||
|
||||
async function waitForLayout(): Promise<void> {
|
||||
await nextFrame();
|
||||
await nextFrame();
|
||||
await nextFrame();
|
||||
}
|
||||
|
||||
async function setViewport(viewport: ViewportSpec): Promise<void> {
|
||||
await page.viewport(viewport.width, viewport.height);
|
||||
await waitForLayout();
|
||||
}
|
||||
|
||||
async function waitForProductionStyles(): Promise<void> {
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(getComputedStyle(document.documentElement).getPropertyValue("--background").trim()).not.toBe(
|
||||
"",
|
||||
);
|
||||
expect(getComputedStyle(document.body).marginTop).toBe("0px");
|
||||
},
|
||||
{
|
||||
timeout: 4_000,
|
||||
interval: 16,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async function waitForElement<T extends Element>(
|
||||
query: () => T | null,
|
||||
errorMessage: string,
|
||||
): Promise<T> {
|
||||
let element: T | null = null;
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
element = query();
|
||||
expect(element, errorMessage).toBeTruthy();
|
||||
},
|
||||
{
|
||||
timeout: 8_000,
|
||||
interval: 16,
|
||||
},
|
||||
);
|
||||
if (!element) {
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
return element;
|
||||
}
|
||||
|
||||
async function waitForImagesToLoad(scope: ParentNode): Promise<void> {
|
||||
const images = Array.from(scope.querySelectorAll("img"));
|
||||
if (images.length === 0) {
|
||||
return;
|
||||
}
|
||||
await Promise.all(
|
||||
images.map(
|
||||
(image) =>
|
||||
new Promise<void>((resolve) => {
|
||||
if (image.complete) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
image.addEventListener("load", () => resolve(), { once: true });
|
||||
image.addEventListener("error", () => resolve(), { once: true });
|
||||
}),
|
||||
),
|
||||
);
|
||||
await waitForLayout();
|
||||
}
|
||||
|
||||
async function measureUserRow(options: {
|
||||
host: HTMLElement;
|
||||
targetMessageId: MessageId;
|
||||
}): Promise<UserRowMeasurement> {
|
||||
const { host, targetMessageId } = options;
|
||||
const rowSelector = `[data-message-id="${targetMessageId}"][data-message-role="user"]`;
|
||||
|
||||
const scrollContainer = await waitForElement(
|
||||
() => host.querySelector<HTMLDivElement>("div.overflow-y-auto.overscroll-y-contain"),
|
||||
"Unable to find ChatView message scroll container.",
|
||||
);
|
||||
|
||||
let row: HTMLElement | null = null;
|
||||
await vi.waitFor(
|
||||
async () => {
|
||||
scrollContainer.scrollTop = 0;
|
||||
scrollContainer.dispatchEvent(new Event("scroll"));
|
||||
await waitForLayout();
|
||||
row = host.querySelector<HTMLElement>(rowSelector);
|
||||
expect(row, "Unable to locate targeted user message row.").toBeTruthy();
|
||||
},
|
||||
{
|
||||
timeout: 8_000,
|
||||
interval: 16,
|
||||
},
|
||||
);
|
||||
|
||||
await waitForImagesToLoad(row!);
|
||||
scrollContainer.scrollTop = 0;
|
||||
scrollContainer.dispatchEvent(new Event("scroll"));
|
||||
await nextFrame();
|
||||
|
||||
const timelineRoot =
|
||||
row!.closest<HTMLElement>('[data-timeline-root="true"]') ??
|
||||
host.querySelector<HTMLElement>('[data-timeline-root="true"]');
|
||||
if (!(timelineRoot instanceof HTMLElement)) {
|
||||
throw new Error("Unable to locate timeline root container.");
|
||||
}
|
||||
|
||||
let timelineWidthMeasuredPx = 0;
|
||||
let measuredRowHeightPx = 0;
|
||||
let renderedInVirtualizedRegion = false;
|
||||
await vi.waitFor(
|
||||
async () => {
|
||||
scrollContainer.scrollTop = 0;
|
||||
scrollContainer.dispatchEvent(new Event("scroll"));
|
||||
await nextFrame();
|
||||
const measuredRow = host.querySelector<HTMLElement>(rowSelector);
|
||||
expect(measuredRow, "Unable to measure targeted user row height.").toBeTruthy();
|
||||
timelineWidthMeasuredPx = timelineRoot.getBoundingClientRect().width;
|
||||
measuredRowHeightPx = measuredRow!.getBoundingClientRect().height;
|
||||
renderedInVirtualizedRegion = measuredRow!.closest("[data-index]") instanceof HTMLElement;
|
||||
expect(timelineWidthMeasuredPx, "Unable to measure timeline width.").toBeGreaterThan(0);
|
||||
expect(measuredRowHeightPx, "Unable to measure targeted user row height.").toBeGreaterThan(0);
|
||||
},
|
||||
{
|
||||
timeout: 4_000,
|
||||
interval: 16,
|
||||
},
|
||||
);
|
||||
|
||||
return { measuredRowHeightPx, timelineWidthMeasuredPx, renderedInVirtualizedRegion };
|
||||
}
|
||||
|
||||
async function mountChatView(options: {
|
||||
viewport: ViewportSpec;
|
||||
snapshot: OrchestrationReadModel;
|
||||
}): Promise<MountedChatView> {
|
||||
fixture = buildFixture(options.snapshot);
|
||||
await setViewport(options.viewport);
|
||||
await waitForProductionStyles();
|
||||
|
||||
const host = document.createElement("div");
|
||||
host.style.position = "fixed";
|
||||
host.style.inset = "0";
|
||||
host.style.width = "100vw";
|
||||
host.style.height = "100vh";
|
||||
host.style.display = "grid";
|
||||
host.style.overflow = "hidden";
|
||||
document.body.append(host);
|
||||
|
||||
const router = getRouter(
|
||||
createMemoryHistory({
|
||||
initialEntries: [`/${THREAD_ID}`],
|
||||
}),
|
||||
);
|
||||
|
||||
const screen = await render(<RouterProvider router={router} />, {
|
||||
container: host,
|
||||
});
|
||||
|
||||
await waitForLayout();
|
||||
|
||||
return {
|
||||
cleanup: async () => {
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
},
|
||||
measureUserRow: async (targetMessageId: MessageId) => measureUserRow({ host, targetMessageId }),
|
||||
setViewport: async (viewport: ViewportSpec) => {
|
||||
await setViewport(viewport);
|
||||
await waitForProductionStyles();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function measureUserRowAtViewport(options: {
|
||||
snapshot: OrchestrationReadModel;
|
||||
targetMessageId: MessageId;
|
||||
viewport: ViewportSpec;
|
||||
}): Promise<UserRowMeasurement> {
|
||||
const mounted = await mountChatView({
|
||||
viewport: options.viewport,
|
||||
snapshot: options.snapshot,
|
||||
});
|
||||
|
||||
try {
|
||||
return await mounted.measureUserRow(options.targetMessageId);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
describe("ChatView timeline estimator parity (full app)", () => {
|
||||
beforeAll(async () => {
|
||||
fixture = buildFixture(
|
||||
createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-bootstrap" as MessageId,
|
||||
targetText: "bootstrap",
|
||||
}),
|
||||
);
|
||||
await worker.start({
|
||||
onUnhandledRequest: "bypass",
|
||||
quiet: true,
|
||||
serviceWorker: {
|
||||
url: "/mockServiceWorker.js",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await worker.stop();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await setViewport(DEFAULT_VIEWPORT);
|
||||
localStorage.clear();
|
||||
document.body.innerHTML = "";
|
||||
useStore.setState({
|
||||
projects: [],
|
||||
threads: [],
|
||||
threadsHydrated: false,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
it.each(TEXT_VIEWPORT_MATRIX)(
|
||||
"keeps long user message estimate close at the $name viewport",
|
||||
async (viewport) => {
|
||||
const userText = "x".repeat(3_200);
|
||||
const targetMessageId = `msg-user-target-long-${viewport.name}` as MessageId;
|
||||
const mounted = await mountChatView({
|
||||
viewport,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId,
|
||||
targetText: userText,
|
||||
}),
|
||||
});
|
||||
|
||||
try {
|
||||
const { measuredRowHeightPx, timelineWidthMeasuredPx, renderedInVirtualizedRegion } =
|
||||
await mounted.measureUserRow(targetMessageId);
|
||||
|
||||
expect(renderedInVirtualizedRegion).toBe(true);
|
||||
|
||||
const estimatedHeightPx = estimateTimelineMessageHeight(
|
||||
{ role: "user", text: userText, attachments: [] },
|
||||
{ timelineWidthPx: timelineWidthMeasuredPx },
|
||||
);
|
||||
|
||||
expect(Math.abs(measuredRowHeightPx - estimatedHeightPx)).toBeLessThanOrEqual(
|
||||
viewport.textTolerancePx,
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("tracks wrapping parity while resizing an existing ChatView across the viewport matrix", async () => {
|
||||
const userText = "x".repeat(3_200);
|
||||
const targetMessageId = "msg-user-target-resize" as MessageId;
|
||||
const mounted = await mountChatView({
|
||||
viewport: TEXT_VIEWPORT_MATRIX[0],
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId,
|
||||
targetText: userText,
|
||||
}),
|
||||
});
|
||||
|
||||
try {
|
||||
const measurements: Array<UserRowMeasurement & { viewport: ViewportSpec; estimatedHeightPx: number }> = [];
|
||||
|
||||
for (const viewport of TEXT_VIEWPORT_MATRIX) {
|
||||
await mounted.setViewport(viewport);
|
||||
const measurement = await mounted.measureUserRow(targetMessageId);
|
||||
const estimatedHeightPx = estimateTimelineMessageHeight(
|
||||
{ role: "user", text: userText, attachments: [] },
|
||||
{ timelineWidthPx: measurement.timelineWidthMeasuredPx },
|
||||
);
|
||||
|
||||
expect(measurement.renderedInVirtualizedRegion).toBe(true);
|
||||
expect(Math.abs(measurement.measuredRowHeightPx - estimatedHeightPx)).toBeLessThanOrEqual(
|
||||
viewport.textTolerancePx,
|
||||
);
|
||||
measurements.push({ ...measurement, viewport, estimatedHeightPx });
|
||||
}
|
||||
|
||||
expect(new Set(measurements.map((measurement) => Math.round(measurement.timelineWidthMeasuredPx))).size).toBeGreaterThanOrEqual(3);
|
||||
|
||||
const byMeasuredWidth = measurements.toSorted(
|
||||
(left, right) => left.timelineWidthMeasuredPx - right.timelineWidthMeasuredPx,
|
||||
);
|
||||
const narrowest = byMeasuredWidth[0]!;
|
||||
const widest = byMeasuredWidth.at(-1)!;
|
||||
expect(narrowest.timelineWidthMeasuredPx).toBeLessThan(widest.timelineWidthMeasuredPx);
|
||||
expect(narrowest.measuredRowHeightPx).toBeGreaterThan(widest.measuredRowHeightPx);
|
||||
expect(narrowest.estimatedHeightPx).toBeGreaterThan(widest.estimatedHeightPx);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("tracks additional rendered wrapping when ChatView width narrows between desktop and mobile viewports", async () => {
|
||||
const userText = "x".repeat(2_400);
|
||||
const targetMessageId = "msg-user-target-wrap" as MessageId;
|
||||
const snapshot = createSnapshotForTargetUser({
|
||||
targetMessageId,
|
||||
targetText: userText,
|
||||
});
|
||||
const desktopMeasurement = await measureUserRowAtViewport({
|
||||
viewport: TEXT_VIEWPORT_MATRIX[0],
|
||||
snapshot,
|
||||
targetMessageId,
|
||||
});
|
||||
const mobileMeasurement = await measureUserRowAtViewport({
|
||||
viewport: TEXT_VIEWPORT_MATRIX[2],
|
||||
snapshot,
|
||||
targetMessageId,
|
||||
});
|
||||
|
||||
const estimatedDesktopPx = estimateTimelineMessageHeight(
|
||||
{ role: "user", text: userText, attachments: [] },
|
||||
{ timelineWidthPx: desktopMeasurement.timelineWidthMeasuredPx },
|
||||
);
|
||||
const estimatedMobilePx = estimateTimelineMessageHeight(
|
||||
{ role: "user", text: userText, attachments: [] },
|
||||
{ timelineWidthPx: mobileMeasurement.timelineWidthMeasuredPx },
|
||||
);
|
||||
|
||||
const measuredDeltaPx = mobileMeasurement.measuredRowHeightPx - desktopMeasurement.measuredRowHeightPx;
|
||||
const estimatedDeltaPx = estimatedMobilePx - estimatedDesktopPx;
|
||||
expect(measuredDeltaPx).toBeGreaterThan(0);
|
||||
expect(estimatedDeltaPx).toBeGreaterThan(0);
|
||||
const ratio = estimatedDeltaPx / measuredDeltaPx;
|
||||
expect(ratio).toBeGreaterThan(0.65);
|
||||
expect(ratio).toBeLessThan(1.35);
|
||||
});
|
||||
|
||||
it.each(ATTACHMENT_VIEWPORT_MATRIX)(
|
||||
"keeps user attachment estimate close at the $name viewport",
|
||||
async (viewport) => {
|
||||
const targetMessageId = `msg-user-target-attachments-${viewport.name}` as MessageId;
|
||||
const userText = "message with image attachments";
|
||||
const mounted = await mountChatView({
|
||||
viewport,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId,
|
||||
targetText: userText,
|
||||
targetAttachmentCount: 3,
|
||||
}),
|
||||
});
|
||||
|
||||
try {
|
||||
const { measuredRowHeightPx, timelineWidthMeasuredPx, renderedInVirtualizedRegion } =
|
||||
await mounted.measureUserRow(targetMessageId);
|
||||
|
||||
expect(renderedInVirtualizedRegion).toBe(true);
|
||||
|
||||
const estimatedHeightPx = estimateTimelineMessageHeight(
|
||||
{
|
||||
role: "user",
|
||||
text: userText,
|
||||
attachments: [{ id: "attachment-1" }, { id: "attachment-2" }, { id: "attachment-3" }],
|
||||
},
|
||||
{ timelineWidthPx: timelineWidthMeasuredPx },
|
||||
);
|
||||
|
||||
expect(Math.abs(measuredRowHeightPx - estimatedHeightPx)).toBeLessThanOrEqual(
|
||||
viewport.attachmentTolerancePx,
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -63,11 +63,17 @@ import {
|
||||
MAX_THREAD_TERMINAL_COUNT,
|
||||
type ChatMessage,
|
||||
type Thread,
|
||||
type TurnDiffFileChange,
|
||||
type TurnDiffSummary,
|
||||
} from "../types";
|
||||
import { basenameOfPath, getVscodeIconUrlForEntry } from "../vscode-icons";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||
import {
|
||||
buildTurnDiffTree,
|
||||
summarizeTurnDiffStats,
|
||||
type TurnDiffTreeNode,
|
||||
} from "../lib/turnDiffTree";
|
||||
import BranchToolbar from "./BranchToolbar";
|
||||
import GitActionsControl from "./GitActionsControl";
|
||||
import {
|
||||
@@ -131,6 +137,7 @@ import {
|
||||
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
|
||||
import { clamp } from "effect/Number";
|
||||
import { ComposerPromptEditor, type ComposerPromptEditorHandle } from "./ComposerPromptEditor";
|
||||
import { estimateTimelineMessageHeight } from "./timelineHeight";
|
||||
|
||||
function formatMessageMeta(createdAt: string, duration: string | null): string {
|
||||
if (!duration) return formatTimestamp(createdAt);
|
||||
@@ -333,6 +340,7 @@ const VscodeEntryIcon = memo(function VscodeEntryIcon(props: {
|
||||
pathValue: string;
|
||||
kind: "file" | "directory";
|
||||
theme: "light" | "dark";
|
||||
className?: string;
|
||||
}) {
|
||||
const [failedIconUrl, setFailedIconUrl] = useState<string | null>(null);
|
||||
const iconUrl = useMemo(
|
||||
@@ -343,9 +351,9 @@ const VscodeEntryIcon = memo(function VscodeEntryIcon(props: {
|
||||
|
||||
if (failed) {
|
||||
return props.kind === "directory" ? (
|
||||
<FolderIcon className="size-4 text-muted-foreground/80" />
|
||||
<FolderIcon className={cn("size-4 text-muted-foreground/80", props.className)} />
|
||||
) : (
|
||||
<FileIcon className="size-4 text-muted-foreground/80" />
|
||||
<FileIcon className={cn("size-4 text-muted-foreground/80", props.className)} />
|
||||
);
|
||||
}
|
||||
|
||||
@@ -354,7 +362,7 @@ const VscodeEntryIcon = memo(function VscodeEntryIcon(props: {
|
||||
src={iconUrl}
|
||||
alt=""
|
||||
aria-hidden="true"
|
||||
className="size-4 shrink-0"
|
||||
className={cn("size-4 shrink-0", props.className)}
|
||||
loading="lazy"
|
||||
onError={() => setFailedIconUrl(iconUrl)}
|
||||
/>
|
||||
@@ -2547,6 +2555,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
isRevertingCheckpoint={isRevertingCheckpoint}
|
||||
onImageExpand={onExpandTimelineImage}
|
||||
markdownCwd={gitCwd ?? undefined}
|
||||
resolvedTheme={resolvedTheme}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -3126,6 +3135,156 @@ const MessageCopyButton = memo(function MessageCopyButton({ text }: { text: stri
|
||||
);
|
||||
});
|
||||
|
||||
function hasNonZeroStat(stat: { additions: number; deletions: number }): boolean {
|
||||
return stat.additions > 0 || stat.deletions > 0;
|
||||
}
|
||||
|
||||
const DiffStatLabel = memo(function DiffStatLabel(props: {
|
||||
additions: number;
|
||||
deletions: number;
|
||||
showParentheses?: boolean;
|
||||
}) {
|
||||
const { additions, deletions, showParentheses = false } = props;
|
||||
return (
|
||||
<>
|
||||
{showParentheses && <span className="text-muted-foreground/70">(</span>}
|
||||
<span className="text-success">+{additions}</span>
|
||||
<span className="mx-0.5 text-muted-foreground/70">/</span>
|
||||
<span className="text-destructive">-{deletions}</span>
|
||||
{showParentheses && <span className="text-muted-foreground/70">)</span>}
|
||||
</>
|
||||
);
|
||||
});
|
||||
|
||||
function collectDirectoryPaths(nodes: ReadonlyArray<TurnDiffTreeNode>): string[] {
|
||||
const paths: string[] = [];
|
||||
for (const node of nodes) {
|
||||
if (node.kind !== "directory") continue;
|
||||
paths.push(node.path);
|
||||
paths.push(...collectDirectoryPaths(node.children));
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
|
||||
function buildDirectoryExpansionState(
|
||||
directoryPaths: ReadonlyArray<string>,
|
||||
expanded: boolean,
|
||||
): Record<string, boolean> {
|
||||
const expandedState: Record<string, boolean> = {};
|
||||
for (const directoryPath of directoryPaths) {
|
||||
expandedState[directoryPath] = expanded;
|
||||
}
|
||||
return expandedState;
|
||||
}
|
||||
|
||||
const ChangedFilesTree = memo(function ChangedFilesTree(props: {
|
||||
turnId: TurnId;
|
||||
files: ReadonlyArray<TurnDiffFileChange>;
|
||||
allDirectoriesExpanded: boolean;
|
||||
resolvedTheme: "light" | "dark";
|
||||
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
|
||||
}) {
|
||||
const { files, allDirectoriesExpanded, onOpenTurnDiff, resolvedTheme, turnId } = props;
|
||||
const treeNodes = useMemo(() => buildTurnDiffTree(files), [files]);
|
||||
const directoryPathsKey = useMemo(() => collectDirectoryPaths(treeNodes).join("\u0000"), [treeNodes]);
|
||||
const allDirectoryExpansionState = useMemo(
|
||||
() =>
|
||||
buildDirectoryExpansionState(
|
||||
directoryPathsKey ? directoryPathsKey.split("\u0000") : [],
|
||||
allDirectoriesExpanded,
|
||||
),
|
||||
[allDirectoriesExpanded, directoryPathsKey],
|
||||
);
|
||||
const [expandedDirectories, setExpandedDirectories] = useState<Record<string, boolean>>(
|
||||
() => buildDirectoryExpansionState((directoryPathsKey ? directoryPathsKey.split("\u0000") : []), true),
|
||||
);
|
||||
useEffect(() => {
|
||||
setExpandedDirectories(allDirectoryExpansionState);
|
||||
}, [allDirectoryExpansionState]);
|
||||
|
||||
const toggleDirectory = useCallback((pathValue: string, fallbackExpanded: boolean) => {
|
||||
setExpandedDirectories((current) => ({
|
||||
...current,
|
||||
[pathValue]: !(current[pathValue] ?? fallbackExpanded),
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const renderTreeNode = (node: TurnDiffTreeNode, depth: number) => {
|
||||
const leftPadding = 8 + depth * 14;
|
||||
if (node.kind === "directory") {
|
||||
const isExpanded = expandedDirectories[node.path] ?? depth === 0;
|
||||
return (
|
||||
<div key={`dir:${node.path}`}>
|
||||
<button
|
||||
type="button"
|
||||
className="group flex w-full items-center gap-1.5 rounded-md py-1 pr-2 text-left hover:bg-background/80"
|
||||
style={{ paddingLeft: `${leftPadding}px` }}
|
||||
onClick={() => toggleDirectory(node.path, depth === 0)}
|
||||
>
|
||||
<ChevronRightIcon
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
"size-3.5 shrink-0 text-muted-foreground/70 transition-transform group-hover:text-foreground/80",
|
||||
isExpanded && "rotate-90",
|
||||
)}
|
||||
/>
|
||||
{isExpanded ? (
|
||||
<FolderIcon className="size-3.5 shrink-0 text-muted-foreground/75" />
|
||||
) : (
|
||||
<FolderClosedIcon className="size-3.5 shrink-0 text-muted-foreground/75" />
|
||||
)}
|
||||
<span className="truncate font-mono text-[11px] text-muted-foreground/90 group-hover:text-foreground/90">
|
||||
{node.name}
|
||||
</span>
|
||||
{hasNonZeroStat(node.stat) && (
|
||||
<span className="ml-auto shrink-0 font-mono text-[10px] tabular-nums">
|
||||
<DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
{isExpanded && (
|
||||
<div className="space-y-0.5">
|
||||
{node.children.map((childNode) => renderTreeNode(childNode, depth + 1))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
key={`file:${node.path}`}
|
||||
type="button"
|
||||
className="group flex w-full items-center gap-1.5 rounded-md py-1 pr-2 text-left hover:bg-background/80"
|
||||
style={{ paddingLeft: `${leftPadding}px` }}
|
||||
onClick={() => onOpenTurnDiff(turnId, node.path)}
|
||||
>
|
||||
<span aria-hidden="true" className="size-3.5 shrink-0" />
|
||||
<VscodeEntryIcon
|
||||
pathValue={node.path}
|
||||
kind="file"
|
||||
theme={resolvedTheme}
|
||||
className="size-3.5 text-muted-foreground/70"
|
||||
/>
|
||||
<span className="truncate font-mono text-[11px] text-muted-foreground/80 group-hover:text-foreground/90">
|
||||
{node.name}
|
||||
</span>
|
||||
{node.stat && (
|
||||
<span className="ml-auto shrink-0 font-mono text-[10px] tabular-nums">
|
||||
<DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-0.5">
|
||||
{treeNodes.map((node) => renderTreeNode(node, 0))}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
interface MessagesTimelineProps {
|
||||
hasMessages: boolean;
|
||||
isWorking: boolean;
|
||||
@@ -3145,6 +3304,7 @@ interface MessagesTimelineProps {
|
||||
isRevertingCheckpoint: boolean;
|
||||
onImageExpand: (preview: ExpandedImagePreview) => void;
|
||||
markdownCwd: string | undefined;
|
||||
resolvedTheme: "light" | "dark";
|
||||
}
|
||||
|
||||
type TimelineEntry = ReturnType<typeof deriveTimelineEntries>[number];
|
||||
@@ -3166,20 +3326,6 @@ type TimelineRow =
|
||||
}
|
||||
| { kind: "working"; id: string; createdAt: string | null };
|
||||
|
||||
function estimateTimelineMessageHeight(message: TimelineMessage): number {
|
||||
const textLength = message.text.length;
|
||||
if (message.role === "assistant") {
|
||||
const estimatedLines = Math.max(1, Math.ceil(textLength / 72));
|
||||
return 78 + Math.min(estimatedLines * 22, 820);
|
||||
}
|
||||
|
||||
const estimatedLines = Math.max(1, Math.ceil(textLength / 56));
|
||||
const attachmentCount = message.attachments?.length ?? 0;
|
||||
const attachmentRows = Math.ceil(attachmentCount / 2);
|
||||
const attachmentHeight = attachmentRows * 124;
|
||||
return 96 + Math.min(estimatedLines * 22, 620) + attachmentHeight;
|
||||
}
|
||||
|
||||
const MessagesTimeline = memo(function MessagesTimeline({
|
||||
hasMessages,
|
||||
isWorking,
|
||||
@@ -3199,7 +3345,36 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
isRevertingCheckpoint,
|
||||
onImageExpand,
|
||||
markdownCwd,
|
||||
resolvedTheme,
|
||||
}: MessagesTimelineProps) {
|
||||
const timelineRootRef = useRef<HTMLDivElement | null>(null);
|
||||
const [timelineWidthPx, setTimelineWidthPx] = useState<number | null>(null);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const timelineRoot = timelineRootRef.current;
|
||||
if (!timelineRoot) return;
|
||||
|
||||
const updateWidth = (nextWidth: number) => {
|
||||
setTimelineWidthPx((previousWidth) => {
|
||||
if (previousWidth !== null && Math.abs(previousWidth - nextWidth) < 0.5) {
|
||||
return previousWidth;
|
||||
}
|
||||
return nextWidth;
|
||||
});
|
||||
};
|
||||
|
||||
updateWidth(timelineRoot.getBoundingClientRect().width);
|
||||
|
||||
if (typeof ResizeObserver === "undefined") return;
|
||||
const observer = new ResizeObserver(() => {
|
||||
updateWidth(timelineRoot.getBoundingClientRect().width);
|
||||
});
|
||||
observer.observe(timelineRoot);
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
};
|
||||
}, [hasMessages, isWorking]);
|
||||
|
||||
const rows = useMemo<TimelineRow[]>(() => {
|
||||
const nextRows: TimelineRow[] = [];
|
||||
|
||||
@@ -3303,12 +3478,16 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
if (!row) return 96;
|
||||
if (row.kind === "work") return 112;
|
||||
if (row.kind === "working") return 40;
|
||||
return estimateTimelineMessageHeight(row.message);
|
||||
return estimateTimelineMessageHeight(row.message, { timelineWidthPx });
|
||||
},
|
||||
measureElement: measureVirtualElement,
|
||||
useAnimationFrameWithResizeObserver: true,
|
||||
overscan: 8,
|
||||
});
|
||||
useEffect(() => {
|
||||
if (timelineWidthPx === null) return;
|
||||
rowVirtualizer.measure();
|
||||
}, [rowVirtualizer, timelineWidthPx]);
|
||||
useEffect(() => {
|
||||
rowVirtualizer.shouldAdjustScrollPositionOnItemSizeChange = (_item, _delta, instance) => {
|
||||
const viewportHeight = instance.scrollRect?.height ?? 0;
|
||||
@@ -3339,9 +3518,23 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
|
||||
const virtualRows = rowVirtualizer.getVirtualItems();
|
||||
const nonVirtualizedRows = rows.slice(virtualizedRowCount);
|
||||
const [allDirectoriesExpandedByTurnId, setAllDirectoriesExpandedByTurnId] = useState<
|
||||
Record<string, boolean>
|
||||
>({});
|
||||
const onToggleAllDirectories = useCallback((turnId: TurnId) => {
|
||||
setAllDirectoriesExpandedByTurnId((current) => ({
|
||||
...current,
|
||||
[turnId]: !(current[turnId] ?? true),
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const renderRowContent = (row: TimelineRow) => (
|
||||
<div className="pb-4">
|
||||
<div
|
||||
className="pb-4"
|
||||
data-timeline-row-kind={row.kind}
|
||||
data-message-id={row.kind === "message" ? row.message.id : undefined}
|
||||
data-message-role={row.kind === "message" ? row.message.role : undefined}
|
||||
>
|
||||
{row.kind === "work" &&
|
||||
(() => {
|
||||
const groupId = row.id;
|
||||
@@ -3507,81 +3700,54 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
if (!turnSummary) return null;
|
||||
const checkpointFiles = turnSummary.files;
|
||||
if (checkpointFiles.length === 0) return null;
|
||||
const summaryStat = checkpointFiles.reduce(
|
||||
(acc, file) => {
|
||||
if (
|
||||
typeof file.additions !== "number" ||
|
||||
typeof file.deletions !== "number"
|
||||
) {
|
||||
return acc;
|
||||
}
|
||||
return {
|
||||
additions: acc.additions + file.additions,
|
||||
deletions: acc.deletions + file.deletions,
|
||||
};
|
||||
},
|
||||
{ additions: 0, deletions: 0 },
|
||||
);
|
||||
const summaryStat = summarizeTurnDiffStats(checkpointFiles);
|
||||
const changedFileCountLabel = String(checkpointFiles.length);
|
||||
const allDirectoriesExpanded =
|
||||
allDirectoriesExpandedByTurnId[turnSummary.turnId] ?? true;
|
||||
return (
|
||||
<div className="mt-2 rounded-lg border border-border/80 bg-card/45 p-2.5">
|
||||
<div className="mb-1.5 flex items-center justify-between gap-2">
|
||||
<p className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/65">
|
||||
<span>Changed files ({changedFileCountLabel})</span>
|
||||
{(summaryStat.additions > 0 || summaryStat.deletions > 0) && (
|
||||
{hasNonZeroStat(summaryStat) && (
|
||||
<>
|
||||
<span className="mx-1">•</span>
|
||||
<span className="text-success">+{summaryStat.additions}</span>
|
||||
<span className="mx-0.5 text-muted-foreground/70">/</span>
|
||||
<span className="text-destructive">-{summaryStat.deletions}</span>
|
||||
<DiffStatLabel
|
||||
additions={summaryStat.additions}
|
||||
deletions={summaryStat.deletions}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
onOpenTurnDiff(turnSummary.turnId, checkpointFiles[0]?.path)
|
||||
}
|
||||
>
|
||||
View diff
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{checkpointFiles.map((file) => (
|
||||
<button
|
||||
key={`${turnSummary.turnId}:${file.path}`}
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Button
|
||||
type="button"
|
||||
className="rounded-md border border-border/70 bg-background/70 px-2 py-1 font-mono text-[11px] text-muted-foreground/80 transition-colors hover:border-border hover:text-foreground/90"
|
||||
onClick={() => onOpenTurnDiff(turnSummary.turnId, file.path)}
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() => onToggleAllDirectories(turnSummary.turnId)}
|
||||
>
|
||||
{(() => {
|
||||
const stat =
|
||||
typeof file.additions === "number" &&
|
||||
typeof file.deletions === "number"
|
||||
? {
|
||||
additions: file.additions,
|
||||
deletions: file.deletions,
|
||||
}
|
||||
: null;
|
||||
if (!stat) {
|
||||
return file.path;
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<span>{file.path}</span>
|
||||
<span className="ml-1 text-muted-foreground/70">(</span>
|
||||
<span className="text-success">+{stat.additions}</span>
|
||||
<span className="mx-0.5 text-muted-foreground/70">/</span>
|
||||
<span className="text-destructive">-{stat.deletions}</span>
|
||||
<span className="text-muted-foreground/70">)</span>
|
||||
</>
|
||||
);
|
||||
})()}
|
||||
</button>
|
||||
))}
|
||||
{allDirectoriesExpanded ? "Collapse all" : "Expand all"}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
onOpenTurnDiff(turnSummary.turnId, checkpointFiles[0]?.path)
|
||||
}
|
||||
>
|
||||
View diff
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<ChangedFilesTree
|
||||
key={`changed-files-tree:${turnSummary.turnId}`}
|
||||
turnId={turnSummary.turnId}
|
||||
files={checkpointFiles}
|
||||
allDirectoriesExpanded={allDirectoriesExpanded}
|
||||
resolvedTheme={resolvedTheme}
|
||||
onOpenTurnDiff={onOpenTurnDiff}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
@@ -3624,7 +3790,11 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto w-full min-w-0 max-w-3xl overflow-x-hidden">
|
||||
<div
|
||||
ref={timelineRootRef}
|
||||
data-timeline-root="true"
|
||||
className="mx-auto w-full min-w-0 max-w-3xl overflow-x-hidden"
|
||||
>
|
||||
{virtualizedRowCount > 0 && (
|
||||
<div className="relative" style={{ height: `${rowVirtualizer.getTotalSize()}px` }}>
|
||||
{virtualRows.map((virtualRow: VirtualItem) => {
|
||||
|
||||
@@ -50,6 +50,7 @@ import {
|
||||
type Ref,
|
||||
} from "react";
|
||||
|
||||
import { isCollapsedCursorAdjacentToMention } from "~/composer-logic";
|
||||
import { splitPromptIntoComposerSegments } from "~/composer-editor-mentions";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { basenameOfPath, getVscodeIconUrlForEntry } from "~/vscode-icons";
|
||||
@@ -469,16 +470,25 @@ function ComposerMentionArrowPlugin() {
|
||||
useEffect(() => {
|
||||
const unregisterLeft = editor.registerCommand(
|
||||
KEY_ARROW_LEFT_COMMAND,
|
||||
() => {
|
||||
let currentOffset = -1;
|
||||
(event) => {
|
||||
let nextOffset: number | null = null;
|
||||
editor.getEditorState().read(() => {
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection) || !selection.isCollapsed()) return;
|
||||
currentOffset = $readSelectionOffsetFromEditorState(0);
|
||||
const currentOffset = $readSelectionOffsetFromEditorState(0);
|
||||
if (currentOffset <= 0) return;
|
||||
const promptValue = $getRoot().getTextContent();
|
||||
if (!isCollapsedCursorAdjacentToMention(promptValue, currentOffset, "left")) {
|
||||
return;
|
||||
}
|
||||
nextOffset = currentOffset - 1;
|
||||
});
|
||||
if (currentOffset <= 0) return false;
|
||||
if (nextOffset === null) return false;
|
||||
const selectionOffset = nextOffset;
|
||||
event?.preventDefault();
|
||||
event?.stopPropagation();
|
||||
editor.update(() => {
|
||||
$setSelectionAtComposerOffset(currentOffset - 1);
|
||||
$setSelectionAtComposerOffset(selectionOffset);
|
||||
});
|
||||
return true;
|
||||
},
|
||||
@@ -486,18 +496,26 @@ function ComposerMentionArrowPlugin() {
|
||||
);
|
||||
const unregisterRight = editor.registerCommand(
|
||||
KEY_ARROW_RIGHT_COMMAND,
|
||||
() => {
|
||||
let currentOffset = -1;
|
||||
let composerLength = 0;
|
||||
(event) => {
|
||||
let nextOffset: number | null = null;
|
||||
editor.getEditorState().read(() => {
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection) || !selection.isCollapsed()) return;
|
||||
composerLength = $getComposerRootLength();
|
||||
currentOffset = $readSelectionOffsetFromEditorState(0);
|
||||
const currentOffset = $readSelectionOffsetFromEditorState(0);
|
||||
const composerLength = $getComposerRootLength();
|
||||
if (currentOffset >= composerLength) return;
|
||||
const promptValue = $getRoot().getTextContent();
|
||||
if (!isCollapsedCursorAdjacentToMention(promptValue, currentOffset, "right")) {
|
||||
return;
|
||||
}
|
||||
nextOffset = currentOffset + 1;
|
||||
});
|
||||
if (currentOffset < 0 || currentOffset >= composerLength) return false;
|
||||
if (nextOffset === null) return false;
|
||||
const selectionOffset = nextOffset;
|
||||
event?.preventDefault();
|
||||
event?.stopPropagation();
|
||||
editor.update(() => {
|
||||
$setSelectionAtComposerOffset(currentOffset + 1);
|
||||
$setSelectionAtComposerOffset(selectionOffset);
|
||||
});
|
||||
return true;
|
||||
},
|
||||
@@ -540,29 +558,6 @@ function ComposerMentionSelectionNormalizePlugin() {
|
||||
return null;
|
||||
}
|
||||
|
||||
function $isCursorAdjacentToMention(): boolean {
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection) || !selection.isCollapsed()) return false;
|
||||
const anchorNode = selection.anchor.getNode();
|
||||
|
||||
if (anchorNode instanceof ComposerMentionNode) return true;
|
||||
|
||||
if ($isElementNode(anchorNode)) {
|
||||
const childIndex = selection.anchor.offset - 1;
|
||||
if (childIndex >= 0) {
|
||||
const child = anchorNode.getChildAtIndex(childIndex);
|
||||
if (child instanceof ComposerMentionNode) return true;
|
||||
}
|
||||
}
|
||||
|
||||
if ($isTextNode(anchorNode) && selection.anchor.offset === 0) {
|
||||
const prev = anchorNode.getPreviousSibling();
|
||||
if (prev instanceof ComposerMentionNode) return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function ComposerMentionBackspacePlugin() {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
|
||||
@@ -738,7 +733,10 @@ function ComposerPromptEditorInner({
|
||||
value: nextValue,
|
||||
cursor: nextCursor,
|
||||
};
|
||||
onChangeRef.current(nextValue, nextCursor, $isCursorAdjacentToMention());
|
||||
const cursorAdjacentToMention =
|
||||
isCollapsedCursorAdjacentToMention(nextValue, nextCursor, "left") ||
|
||||
isCollapsedCursorAdjacentToMention(nextValue, nextCursor, "right");
|
||||
onChangeRef.current(nextValue, nextCursor, cursorAdjacentToMention);
|
||||
});
|
||||
}, []);
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
FolderIcon,
|
||||
GitPullRequestIcon,
|
||||
RocketIcon,
|
||||
SquarePenIcon,
|
||||
TerminalIcon,
|
||||
} from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
@@ -21,7 +22,7 @@ import { isElectron } from "../env";
|
||||
import { APP_STAGE_LABEL } from "../branding";
|
||||
import { newCommandId, newProjectId, newThreadId } from "../lib/utils";
|
||||
import { useStore } from "../store";
|
||||
import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";
|
||||
import { isChatNewLocalShortcut, isChatNewShortcut, shortcutLabelForCommand } from "../keybindings";
|
||||
import { type Thread } from "../types";
|
||||
import { derivePendingApprovals } from "../session-logic";
|
||||
import { gitRemoveWorktreeMutationOptions, gitStatusQueryOptions } from "../lib/gitReactQuery";
|
||||
@@ -46,6 +47,7 @@ import {
|
||||
SidebarFooter,
|
||||
SidebarGroup,
|
||||
SidebarHeader,
|
||||
SidebarMenuAction,
|
||||
SidebarMenu,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
@@ -59,6 +61,14 @@ import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "
|
||||
import { isNonEmpty as isNonEmptyString } from "effect/String";
|
||||
|
||||
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
|
||||
const THREAD_PREVIEW_LIMIT = 6;
|
||||
|
||||
async function copyTextToClipboard(text: string): Promise<void> {
|
||||
if (typeof navigator === "undefined" || navigator.clipboard?.writeText === undefined) {
|
||||
throw new Error("Clipboard API unavailable.");
|
||||
}
|
||||
await navigator.clipboard.writeText(text);
|
||||
}
|
||||
|
||||
function formatRelativeTime(iso: string): string {
|
||||
const diff = Date.now() - new Date(iso).getTime();
|
||||
@@ -284,6 +294,9 @@ export default function Sidebar() {
|
||||
const [isAddingProject, setIsAddingProject] = useState(false);
|
||||
const [renamingThreadId, setRenamingThreadId] = useState<ThreadId | null>(null);
|
||||
const [renamingTitle, setRenamingTitle] = useState("");
|
||||
const [expandedThreadListsByProject, setExpandedThreadListsByProject] = useState<
|
||||
ReadonlySet<ProjectId>
|
||||
>(() => new Set());
|
||||
const renamingCommittedRef = useRef(false);
|
||||
const renamingInputRef = useRef<HTMLInputElement | null>(null);
|
||||
const [desktopUpdateState, setDesktopUpdateState] = useState<DesktopUpdateState | null>(null);
|
||||
@@ -581,6 +594,7 @@ export default function Sidebar() {
|
||||
[
|
||||
{ id: "rename", label: "Rename thread" },
|
||||
{ id: "mark-unread", label: "Mark unread" },
|
||||
{ id: "copy-thread-id", label: "Copy Thread ID" },
|
||||
{ id: "delete", label: "Delete", destructive: true },
|
||||
],
|
||||
position,
|
||||
@@ -599,6 +613,23 @@ export default function Sidebar() {
|
||||
markThreadUnread(threadId);
|
||||
return;
|
||||
}
|
||||
if (clicked === "copy-thread-id") {
|
||||
try {
|
||||
await copyTextToClipboard(threadId);
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: "Thread ID copied",
|
||||
description: threadId,
|
||||
});
|
||||
} catch (error) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to copy thread ID",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (clicked !== "delete") return;
|
||||
if (appSettings.confirmThreadDelete) {
|
||||
const confirmed = await api.dialogs.confirm(
|
||||
@@ -832,15 +863,6 @@ export default function Sidebar() {
|
||||
};
|
||||
}, []);
|
||||
|
||||
const onCreateThreadClick = () => {
|
||||
if (projects.length === 0) {
|
||||
setAddingProject(true);
|
||||
return;
|
||||
}
|
||||
const firstProject = projects[0];
|
||||
if (firstProject) void handleNewThread(firstProject.id);
|
||||
};
|
||||
|
||||
const showDesktopUpdateButton = isElectron && shouldShowDesktopUpdateButton(desktopUpdateState);
|
||||
|
||||
const desktopUpdateTooltip = desktopUpdateState
|
||||
@@ -862,6 +884,12 @@ export default function Sidebar() {
|
||||
: shouldHighlightDesktopUpdateError(desktopUpdateState)
|
||||
? "text-rose-500 animate-pulse"
|
||||
: "text-amber-500 animate-pulse";
|
||||
const newThreadShortcutLabel = useMemo(
|
||||
() =>
|
||||
shortcutLabelForCommand(keybindings, "chat.newLocal") ??
|
||||
shortcutLabelForCommand(keybindings, "chat.new"),
|
||||
[keybindings],
|
||||
);
|
||||
|
||||
const handleDesktopUpdateButtonClick = useCallback(() => {
|
||||
const bridge = window.desktopBridge;
|
||||
@@ -921,6 +949,24 @@ export default function Sidebar() {
|
||||
}
|
||||
}, [desktopUpdateButtonAction, desktopUpdateButtonDisabled, desktopUpdateState]);
|
||||
|
||||
const expandThreadListForProject = useCallback((projectId: ProjectId) => {
|
||||
setExpandedThreadListsByProject((current) => {
|
||||
if (current.has(projectId)) return current;
|
||||
const next = new Set(current);
|
||||
next.add(projectId);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const collapseThreadListForProject = useCallback((projectId: ProjectId) => {
|
||||
setExpandedThreadListsByProject((current) => {
|
||||
if (!current.has(projectId)) return current;
|
||||
const next = new Set(current);
|
||||
next.delete(projectId);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const wordmark = (
|
||||
<div className="flex items-center gap-2">
|
||||
<SidebarTrigger className="shrink-0 md:hidden" />
|
||||
@@ -936,17 +982,6 @@ export default function Sidebar() {
|
||||
</div>
|
||||
);
|
||||
|
||||
const newThreadButton = (
|
||||
<button
|
||||
type="button"
|
||||
className="flex w-full items-center gap-2 rounded-lg border border-border bg-secondary px-3 py-2 text-xs text-muted-foreground transition-colors duration-150 hover:bg-accent"
|
||||
onClick={onCreateThreadClick}
|
||||
>
|
||||
<span className="text-foreground">+</span>
|
||||
New thread
|
||||
</button>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{isElectron ? (
|
||||
@@ -973,12 +1008,10 @@ export default function Sidebar() {
|
||||
</Tooltip>
|
||||
)}
|
||||
</SidebarHeader>
|
||||
<div className="px-4 py-2">{newThreadButton}</div>
|
||||
</>
|
||||
) : (
|
||||
<SidebarHeader className="gap-3 px-3 py-2 sm:gap-2.5 sm:px-4 sm:py-3">
|
||||
{wordmark}
|
||||
{newThreadButton}
|
||||
</SidebarHeader>
|
||||
)}
|
||||
|
||||
@@ -986,13 +1019,19 @@ export default function Sidebar() {
|
||||
<SidebarGroup className="px-2 py-2">
|
||||
<SidebarMenu>
|
||||
{projects.map((project) => {
|
||||
const visibleThreads = threads
|
||||
const projectThreads = threads
|
||||
.filter((thread) => thread.projectId === project.id)
|
||||
.toSorted((a, b) => {
|
||||
const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
|
||||
if (byDate !== 0) return byDate;
|
||||
return b.id.localeCompare(a.id);
|
||||
});
|
||||
const isThreadListExpanded = expandedThreadListsByProject.has(project.id);
|
||||
const hasHiddenThreads = projectThreads.length > THREAD_PREVIEW_LIMIT;
|
||||
const visibleThreads =
|
||||
hasHiddenThreads && !isThreadListExpanded
|
||||
? projectThreads.slice(0, THREAD_PREVIEW_LIMIT)
|
||||
: projectThreads;
|
||||
|
||||
return (
|
||||
<Collapsible
|
||||
@@ -1005,34 +1044,61 @@ export default function Sidebar() {
|
||||
}}
|
||||
>
|
||||
<SidebarMenuItem>
|
||||
<CollapsibleTrigger
|
||||
render={
|
||||
<SidebarMenuButton
|
||||
size="sm"
|
||||
className="gap-2 px-2 py-1.5 text-left hover:bg-accent"
|
||||
<div className="group/project-header relative">
|
||||
<CollapsibleTrigger
|
||||
render={
|
||||
<SidebarMenuButton
|
||||
size="sm"
|
||||
className="gap-2 px-2 py-1.5 text-left hover:bg-accent group-hover/project-header:bg-accent group-hover/project-header:text-sidebar-accent-foreground"
|
||||
/>
|
||||
}
|
||||
onContextMenu={(event) => {
|
||||
event.preventDefault();
|
||||
void handleProjectContextMenu(project.id, {
|
||||
x: event.clientX,
|
||||
y: event.clientY,
|
||||
});
|
||||
}}
|
||||
>
|
||||
<ChevronRightIcon
|
||||
className={`-ml-0.5 size-3.5 shrink-0 text-muted-foreground/70 transition-transform duration-150 ${
|
||||
project.expanded ? "rotate-90" : ""
|
||||
}`}
|
||||
/>
|
||||
}
|
||||
onContextMenu={(event) => {
|
||||
event.preventDefault();
|
||||
void handleProjectContextMenu(project.id, {
|
||||
x: event.clientX,
|
||||
y: event.clientY,
|
||||
});
|
||||
}}
|
||||
>
|
||||
<ChevronRightIcon
|
||||
className={`-ml-0.5 size-3.5 shrink-0 text-muted-foreground/70 transition-transform duration-150 ${
|
||||
project.expanded ? "rotate-90" : ""
|
||||
}`}
|
||||
/>
|
||||
<ProjectFavicon cwd={project.cwd} />
|
||||
<span className="flex-1 truncate text-xs font-medium text-foreground/90">
|
||||
{project.name}
|
||||
</span>
|
||||
<span className="text-[10px] text-muted-foreground/60">
|
||||
{visibleThreads.length}
|
||||
</span>
|
||||
</CollapsibleTrigger>
|
||||
<ProjectFavicon cwd={project.cwd} />
|
||||
<span className="flex-1 truncate text-xs font-medium text-foreground/90">
|
||||
{project.name}
|
||||
</span>
|
||||
</CollapsibleTrigger>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<SidebarMenuAction
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Create new thread in ${project.name}`}
|
||||
/>
|
||||
}
|
||||
showOnHover
|
||||
className="top-1 right-1 size-5 rounded-md p-0 text-muted-foreground/70 hover:bg-secondary hover:text-foreground"
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
void handleNewThread(project.id);
|
||||
}}
|
||||
>
|
||||
<SquarePenIcon className="size-3.5" />
|
||||
</SidebarMenuAction>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top">
|
||||
{newThreadShortcutLabel
|
||||
? `New thread (${newThreadShortcutLabel})`
|
||||
: "New thread"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
<CollapsibleContent>
|
||||
<SidebarMenuSub className="mx-1 my-0 w-full translate-x-0 gap-0 px-1.5 py-0">
|
||||
@@ -1176,19 +1242,34 @@ export default function Sidebar() {
|
||||
);
|
||||
})}
|
||||
|
||||
<SidebarMenuSubItem className="w-full">
|
||||
<SidebarMenuSubButton
|
||||
render={<button type="button" />}
|
||||
size="sm"
|
||||
className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80"
|
||||
onClick={() => {
|
||||
void handleNewThread(project.id);
|
||||
}}
|
||||
>
|
||||
<span>+</span>
|
||||
<span>New thread</span>
|
||||
</SidebarMenuSubButton>
|
||||
</SidebarMenuSubItem>
|
||||
{hasHiddenThreads && !isThreadListExpanded && (
|
||||
<SidebarMenuSubItem className="w-full">
|
||||
<SidebarMenuSubButton
|
||||
render={<button type="button" />}
|
||||
size="sm"
|
||||
className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80"
|
||||
onClick={() => {
|
||||
expandThreadListForProject(project.id);
|
||||
}}
|
||||
>
|
||||
<span>Show more</span>
|
||||
</SidebarMenuSubButton>
|
||||
</SidebarMenuSubItem>
|
||||
)}
|
||||
{hasHiddenThreads && isThreadListExpanded && (
|
||||
<SidebarMenuSubItem className="w-full">
|
||||
<SidebarMenuSubButton
|
||||
render={<button type="button" />}
|
||||
size="sm"
|
||||
className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80"
|
||||
onClick={() => {
|
||||
collapseThreadListForProject(project.id);
|
||||
}}
|
||||
>
|
||||
<span>Show less</span>
|
||||
</SidebarMenuSubButton>
|
||||
</SidebarMenuSubItem>
|
||||
)}
|
||||
</SidebarMenuSub>
|
||||
</CollapsibleContent>
|
||||
</SidebarMenuItem>
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { estimateTimelineMessageHeight } from "./timelineHeight";
|
||||
|
||||
describe("estimateTimelineMessageHeight", () => {
|
||||
it("uses assistant sizing rules for assistant messages", () => {
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "assistant",
|
||||
text: "a".repeat(144),
|
||||
}),
|
||||
).toBe(122);
|
||||
});
|
||||
|
||||
it("uses assistant sizing rules for system messages", () => {
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "system",
|
||||
text: "a".repeat(144),
|
||||
}),
|
||||
).toBe(122);
|
||||
});
|
||||
|
||||
it("adds one attachment row for one or two user attachments", () => {
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [{ id: "1" }],
|
||||
}),
|
||||
).toBe(346);
|
||||
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [{ id: "1" }, { id: "2" }],
|
||||
}),
|
||||
).toBe(346);
|
||||
});
|
||||
|
||||
it("adds a second attachment row for three or four user attachments", () => {
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [{ id: "1" }, { id: "2" }, { id: "3" }],
|
||||
}),
|
||||
).toBe(574);
|
||||
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [{ id: "1" }, { id: "2" }, { id: "3" }, { id: "4" }],
|
||||
}),
|
||||
).toBe(574);
|
||||
});
|
||||
|
||||
it("does not cap long user message estimates", () => {
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "user",
|
||||
text: "a".repeat(56 * 120),
|
||||
}),
|
||||
).toBe(2736);
|
||||
});
|
||||
|
||||
it("counts explicit newlines for user message estimates", () => {
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "user",
|
||||
text: "first\nsecond\nthird",
|
||||
}),
|
||||
).toBe(162);
|
||||
});
|
||||
|
||||
it("uses narrower width to increase user line wrapping", () => {
|
||||
const message = {
|
||||
role: "user" as const,
|
||||
text: "a".repeat(52),
|
||||
};
|
||||
|
||||
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 320 })).toBe(140);
|
||||
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 768 })).toBe(118);
|
||||
});
|
||||
|
||||
it("does not clamp user wrapping too aggressively on very narrow layouts", () => {
|
||||
const message = {
|
||||
role: "user" as const,
|
||||
text: "a".repeat(20),
|
||||
};
|
||||
|
||||
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 100 })).toBe(184);
|
||||
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 320 })).toBe(118);
|
||||
});
|
||||
|
||||
it("uses narrower width to increase assistant line wrapping", () => {
|
||||
const message = {
|
||||
role: "assistant" as const,
|
||||
text: "a".repeat(200),
|
||||
};
|
||||
|
||||
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 320 })).toBe(188);
|
||||
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 768 })).toBe(122);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
const ASSISTANT_CHARS_PER_LINE_FALLBACK = 72;
|
||||
const USER_CHARS_PER_LINE_FALLBACK = 56;
|
||||
const LINE_HEIGHT_PX = 22;
|
||||
const ASSISTANT_BASE_HEIGHT_PX = 78;
|
||||
const USER_BASE_HEIGHT_PX = 96;
|
||||
const ATTACHMENTS_PER_ROW = 2;
|
||||
// Attachment thumbnails render with `max-h-[220px]` plus ~8px row gap.
|
||||
const USER_ATTACHMENT_ROW_HEIGHT_PX = 228;
|
||||
const USER_BUBBLE_WIDTH_RATIO = 0.8;
|
||||
const USER_BUBBLE_HORIZONTAL_PADDING_PX = 32;
|
||||
const ASSISTANT_MESSAGE_HORIZONTAL_PADDING_PX = 8;
|
||||
const USER_MONO_AVG_CHAR_WIDTH_PX = 8.4;
|
||||
const ASSISTANT_AVG_CHAR_WIDTH_PX = 7.2;
|
||||
const MIN_USER_CHARS_PER_LINE = 4;
|
||||
const MIN_ASSISTANT_CHARS_PER_LINE = 20;
|
||||
|
||||
interface TimelineMessageHeightInput {
|
||||
role: "user" | "assistant" | "system";
|
||||
text: string;
|
||||
attachments?: ReadonlyArray<{ id: string }>;
|
||||
}
|
||||
|
||||
interface TimelineHeightEstimateLayout {
|
||||
timelineWidthPx: number | null;
|
||||
}
|
||||
|
||||
function estimateWrappedLineCount(text: string, charsPerLine: number): number {
|
||||
if (text.length === 0) return 1;
|
||||
|
||||
// Avoid allocating via split for long logs; iterate once and count wrapped lines.
|
||||
let lines = 0;
|
||||
let currentLineLength = 0;
|
||||
for (let index = 0; index < text.length; index += 1) {
|
||||
if (text.charCodeAt(index) === 10) {
|
||||
lines += Math.max(1, Math.ceil(currentLineLength / charsPerLine));
|
||||
currentLineLength = 0;
|
||||
continue;
|
||||
}
|
||||
currentLineLength += 1;
|
||||
}
|
||||
|
||||
lines += Math.max(1, Math.ceil(currentLineLength / charsPerLine));
|
||||
return lines;
|
||||
}
|
||||
|
||||
function isFinitePositiveNumber(value: number | null | undefined): value is number {
|
||||
return typeof value === "number" && Number.isFinite(value) && value > 0;
|
||||
}
|
||||
|
||||
function estimateCharsPerLineForUser(timelineWidthPx: number | null): number {
|
||||
if (!isFinitePositiveNumber(timelineWidthPx)) return USER_CHARS_PER_LINE_FALLBACK;
|
||||
const bubbleWidthPx = timelineWidthPx * USER_BUBBLE_WIDTH_RATIO;
|
||||
const textWidthPx = Math.max(bubbleWidthPx - USER_BUBBLE_HORIZONTAL_PADDING_PX, 0);
|
||||
return Math.max(MIN_USER_CHARS_PER_LINE, Math.floor(textWidthPx / USER_MONO_AVG_CHAR_WIDTH_PX));
|
||||
}
|
||||
|
||||
function estimateCharsPerLineForAssistant(timelineWidthPx: number | null): number {
|
||||
if (!isFinitePositiveNumber(timelineWidthPx)) return ASSISTANT_CHARS_PER_LINE_FALLBACK;
|
||||
const textWidthPx = Math.max(timelineWidthPx - ASSISTANT_MESSAGE_HORIZONTAL_PADDING_PX, 0);
|
||||
return Math.max(
|
||||
MIN_ASSISTANT_CHARS_PER_LINE,
|
||||
Math.floor(textWidthPx / ASSISTANT_AVG_CHAR_WIDTH_PX),
|
||||
);
|
||||
}
|
||||
|
||||
export function estimateTimelineMessageHeight(
|
||||
message: TimelineMessageHeightInput,
|
||||
layout: TimelineHeightEstimateLayout = { timelineWidthPx: null },
|
||||
): number {
|
||||
if (message.role === "assistant") {
|
||||
const charsPerLine = estimateCharsPerLineForAssistant(layout.timelineWidthPx);
|
||||
const estimatedLines = estimateWrappedLineCount(message.text, charsPerLine);
|
||||
return ASSISTANT_BASE_HEIGHT_PX + estimatedLines * LINE_HEIGHT_PX;
|
||||
}
|
||||
|
||||
if (message.role === "user") {
|
||||
const charsPerLine = estimateCharsPerLineForUser(layout.timelineWidthPx);
|
||||
const estimatedLines = estimateWrappedLineCount(message.text, charsPerLine);
|
||||
const attachmentCount = message.attachments?.length ?? 0;
|
||||
const attachmentRows = Math.ceil(attachmentCount / ATTACHMENTS_PER_ROW);
|
||||
const attachmentHeight = attachmentRows * USER_ATTACHMENT_ROW_HEIGHT_PX;
|
||||
return USER_BASE_HEIGHT_PX + estimatedLines * LINE_HEIGHT_PX + attachmentHeight;
|
||||
}
|
||||
|
||||
// `system` messages are not rendered in the chat timeline, but keep a stable
|
||||
// explicit branch in case they are present in timeline data.
|
||||
const charsPerLine = estimateCharsPerLineForAssistant(layout.timelineWidthPx);
|
||||
const estimatedLines = estimateWrappedLineCount(message.text, charsPerLine);
|
||||
return ASSISTANT_BASE_HEIGHT_PX + estimatedLines * LINE_HEIGHT_PX;
|
||||
}
|
||||
@@ -339,6 +339,7 @@ function SidebarRail({
|
||||
const sidebarInstance = React.useContext(SidebarInstanceContext);
|
||||
const railRef = React.useRef<HTMLButtonElement | null>(null);
|
||||
const suppressClickRef = React.useRef(false);
|
||||
const cleanupResizeListenersRef = React.useRef<(() => void) | null>(null);
|
||||
const resizeStateRef = React.useRef<{
|
||||
moved: boolean;
|
||||
pointerId: number;
|
||||
@@ -367,6 +368,8 @@ function SidebarRail({
|
||||
if (resizeState.rafId !== null) {
|
||||
window.cancelAnimationFrame(resizeState.rafId);
|
||||
}
|
||||
cleanupResizeListenersRef.current?.();
|
||||
cleanupResizeListenersRef.current = null;
|
||||
resizeState.transitionTargets.forEach((element) => {
|
||||
element.style.removeProperty("transition-duration");
|
||||
});
|
||||
@@ -429,12 +432,46 @@ function SidebarRail({
|
||||
width: initialWidth,
|
||||
wrapper,
|
||||
};
|
||||
const stopResizeFromWindowEvent = (nativeEvent: PointerEvent) => {
|
||||
const activeResizeState = resizeStateRef.current;
|
||||
if (!activeResizeState || nativeEvent.pointerId !== activeResizeState.pointerId) {
|
||||
return;
|
||||
}
|
||||
suppressClickRef.current = activeResizeState.moved;
|
||||
stopResize(nativeEvent.pointerId);
|
||||
};
|
||||
const stopResizeFromVisibilityChange = () => {
|
||||
const activeResizeState = resizeStateRef.current;
|
||||
if (!activeResizeState || document.visibilityState === "visible") {
|
||||
return;
|
||||
}
|
||||
suppressClickRef.current = activeResizeState.moved;
|
||||
stopResize(activeResizeState.pointerId);
|
||||
};
|
||||
const stopResizeFromBlur = () => {
|
||||
const activeResizeState = resizeStateRef.current;
|
||||
if (!activeResizeState) {
|
||||
return;
|
||||
}
|
||||
suppressClickRef.current = activeResizeState.moved;
|
||||
stopResize(activeResizeState.pointerId);
|
||||
};
|
||||
window.addEventListener("pointerup", stopResizeFromWindowEvent, true);
|
||||
window.addEventListener("pointercancel", stopResizeFromWindowEvent, true);
|
||||
window.addEventListener("blur", stopResizeFromBlur);
|
||||
document.addEventListener("visibilitychange", stopResizeFromVisibilityChange);
|
||||
cleanupResizeListenersRef.current = () => {
|
||||
window.removeEventListener("pointerup", stopResizeFromWindowEvent, true);
|
||||
window.removeEventListener("pointercancel", stopResizeFromWindowEvent, true);
|
||||
window.removeEventListener("blur", stopResizeFromBlur);
|
||||
document.removeEventListener("visibilitychange", stopResizeFromVisibilityChange);
|
||||
};
|
||||
wrapper.style.setProperty("--sidebar-width", `${initialWidth}px`);
|
||||
event.currentTarget.setPointerCapture(event.pointerId);
|
||||
document.body.style.cursor = "col-resize";
|
||||
document.body.style.userSelect = "none";
|
||||
},
|
||||
[onPointerDown, open, resolvedResizable, sidebarInstance?.side],
|
||||
[onPointerDown, open, resolvedResizable, sidebarInstance?.side, stopResize],
|
||||
);
|
||||
|
||||
const handlePointerMove = React.useCallback(
|
||||
@@ -516,6 +553,13 @@ function SidebarRail({
|
||||
[endResizeInteraction, onPointerCancel],
|
||||
);
|
||||
|
||||
const handleLostPointerCapture = React.useCallback(() => {
|
||||
const resizeState = resizeStateRef.current;
|
||||
if (!resizeState) return;
|
||||
suppressClickRef.current = resizeState.moved;
|
||||
stopResize(resizeState.pointerId);
|
||||
}, [stopResize]);
|
||||
|
||||
const handleClick = React.useCallback(
|
||||
(event: React.MouseEvent<HTMLButtonElement>) => {
|
||||
onClick?.(event);
|
||||
@@ -579,6 +623,7 @@ function SidebarRail({
|
||||
onClick={handleClick}
|
||||
onPointerCancel={handlePointerCancel}
|
||||
onPointerDown={handlePointerDown}
|
||||
onLostPointerCapture={handleLostPointerCapture}
|
||||
onPointerMove={handlePointerMove}
|
||||
onPointerUp={handlePointerUp}
|
||||
ref={railRef}
|
||||
|
||||
@@ -206,7 +206,10 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
|
||||
"data-[position*=top]:after:top-full",
|
||||
"data-[position*=bottom]:after:bottom-full",
|
||||
// Define some variables
|
||||
"[--toast-calc-height:var(--toast-frontmost-height,var(--toast-height))] [--toast-gap:--spacing(3)] [--toast-peek:--spacing(3)] [--toast-scale:calc(max(0,1-(var(--toast-index)*.1)))] [--toast-shrink:calc(1-var(--toast-scale))]",
|
||||
// Base UI exposes a shared front-most height for the collapsed stack.
|
||||
// If that shared measurement is briefly stale, long content can render
|
||||
// outside the card until hover expands the toast and swaps to its own height.
|
||||
"[--toast-calc-height:max(var(--toast-frontmost-height,var(--toast-height)),var(--toast-height))] [--toast-gap:--spacing(3)] [--toast-peek:--spacing(3)] [--toast-scale:calc(max(0,1-(var(--toast-index)*.1)))] [--toast-shrink:calc(1-var(--toast-scale))]",
|
||||
// Define offset-y variable
|
||||
"data-[position*=top]:[--toast-calc-offset-y:calc(var(--toast-offset-y)+var(--toast-index)*var(--toast-gap)+var(--toast-swipe-movement-y))]",
|
||||
"data-[position*=bottom]:[--toast-calc-offset-y:calc(var(--toast-offset-y)*-1+var(--toast-index)*var(--toast-gap)*-1+var(--toast-swipe-movement-y))]",
|
||||
@@ -258,7 +261,7 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
|
||||
"not-data-expanded:pointer-events-none not-data-expanded:opacity-0",
|
||||
)}
|
||||
>
|
||||
<div className="flex gap-2">
|
||||
<div className="flex min-w-0 flex-1 gap-2">
|
||||
{Icon && (
|
||||
<div
|
||||
className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"
|
||||
@@ -268,16 +271,22 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<Toast.Title className="font-medium" data-slot="toast-title" />
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<Toast.Title
|
||||
className="min-w-0 break-words font-medium"
|
||||
data-slot="toast-title"
|
||||
/>
|
||||
<Toast.Description
|
||||
className="text-muted-foreground"
|
||||
className="min-w-0 break-words text-muted-foreground"
|
||||
data-slot="toast-description"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{toast.actionProps && (
|
||||
<Toast.Action className={buttonVariants({ size: "xs" })} data-slot="toast-action">
|
||||
<Toast.Action
|
||||
className={cn(buttonVariants({ size: "xs" }), "shrink-0")}
|
||||
data-slot="toast-action"
|
||||
>
|
||||
{toast.actionProps.children}
|
||||
</Toast.Action>
|
||||
)}
|
||||
@@ -341,7 +350,7 @@ function AnchoredToasts() {
|
||||
</Toast.Content>
|
||||
) : (
|
||||
<Toast.Content className="pointer-events-auto flex items-center justify-between gap-1.5 overflow-hidden px-3.5 py-3 text-sm">
|
||||
<div className="flex gap-2">
|
||||
<div className="flex min-w-0 flex-1 gap-2">
|
||||
{Icon && (
|
||||
<div
|
||||
className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"
|
||||
@@ -351,17 +360,20 @@ function AnchoredToasts() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<Toast.Title className="font-medium" data-slot="toast-title" />
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<Toast.Title
|
||||
className="min-w-0 break-words font-medium"
|
||||
data-slot="toast-title"
|
||||
/>
|
||||
<Toast.Description
|
||||
className="text-muted-foreground"
|
||||
className="min-w-0 break-words text-muted-foreground"
|
||||
data-slot="toast-description"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{toast.actionProps && (
|
||||
<Toast.Action
|
||||
className={buttonVariants({ size: "xs" })}
|
||||
className={cn(buttonVariants({ size: "xs" }), "shrink-0")}
|
||||
data-slot="toast-action"
|
||||
>
|
||||
{toast.actionProps.children}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
detectComposerTrigger,
|
||||
expandCollapsedComposerCursor,
|
||||
isCollapsedCursorAdjacentToMention,
|
||||
replaceTextRange,
|
||||
} from "./composer-logic";
|
||||
|
||||
@@ -77,3 +78,36 @@ describe("expandCollapsedComposerCursor", () => {
|
||||
expect(detectComposerTrigger(text, expandedCursor)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("isCollapsedCursorAdjacentToMention", () => {
|
||||
it("returns false when no mention exists", () => {
|
||||
expect(isCollapsedCursorAdjacentToMention("plain text", 6, "left")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToMention("plain text", 6, "right")).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps @query typing non-adjacent while no mention pill exists", () => {
|
||||
const text = "hello @pac";
|
||||
expect(isCollapsedCursorAdjacentToMention(text, text.length, "left")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToMention(text, text.length, "right")).toBe(false);
|
||||
});
|
||||
|
||||
it("detects left adjacency only when cursor is directly after a mention", () => {
|
||||
const text = "open @AGENTS.md next";
|
||||
const mentionStart = "open ".length;
|
||||
const mentionEnd = mentionStart + 1;
|
||||
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionEnd, "left")).toBe(true);
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionStart, "left")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionEnd + 1, "left")).toBe(false);
|
||||
});
|
||||
|
||||
it("detects right adjacency only when cursor is directly before a mention", () => {
|
||||
const text = "open @AGENTS.md next";
|
||||
const mentionStart = "open ".length;
|
||||
const mentionEnd = mentionStart + 1;
|
||||
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionStart, "right")).toBe(true);
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionEnd, "right")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionStart - 1, "right")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -58,6 +58,52 @@ export function expandCollapsedComposerCursor(text: string, cursorInput: number)
|
||||
return expandedCursor;
|
||||
}
|
||||
|
||||
function collapsedSegmentLength(segment: { type: "text"; text: string } | { type: "mention" }): number {
|
||||
return segment.type === "mention" ? 1 : segment.text.length;
|
||||
}
|
||||
|
||||
function clampCollapsedComposerCursor(
|
||||
segments: ReadonlyArray<{ type: "text"; text: string } | { type: "mention" }>,
|
||||
cursorInput: number,
|
||||
): number {
|
||||
const collapsedLength = segments.reduce(
|
||||
(total, segment) => total + collapsedSegmentLength(segment),
|
||||
0,
|
||||
);
|
||||
if (!Number.isFinite(cursorInput)) {
|
||||
return collapsedLength;
|
||||
}
|
||||
return Math.max(0, Math.min(collapsedLength, Math.floor(cursorInput)));
|
||||
}
|
||||
|
||||
export function isCollapsedCursorAdjacentToMention(
|
||||
text: string,
|
||||
cursorInput: number,
|
||||
direction: "left" | "right",
|
||||
): boolean {
|
||||
const segments = splitPromptIntoComposerSegments(text);
|
||||
if (!segments.some((segment) => segment.type === "mention")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const cursor = clampCollapsedComposerCursor(segments, cursorInput);
|
||||
let collapsedOffset = 0;
|
||||
|
||||
for (const segment of segments) {
|
||||
if (segment.type === "mention") {
|
||||
if (direction === "left" && cursor === collapsedOffset + 1) {
|
||||
return true;
|
||||
}
|
||||
if (direction === "right" && cursor === collapsedOffset) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
collapsedOffset += collapsedSegmentLength(segment);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
export function detectComposerTrigger(text: string, cursorInput: number): ComposerTrigger | null {
|
||||
const cursor = clampCursor(text, cursorInput);
|
||||
const lineStart = text.lastIndexOf("\n", Math.max(0, cursor - 1)) + 1;
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildTurnDiffTree, summarizeTurnDiffStats } from "./turnDiffTree";
|
||||
|
||||
describe("summarizeTurnDiffStats", () => {
|
||||
it("sums only files with numeric additions/deletions", () => {
|
||||
const stat = summarizeTurnDiffStats([
|
||||
{ path: "README.md", additions: 3, deletions: 1 },
|
||||
{ path: "docs/notes.md" },
|
||||
{ path: "src/index.ts", additions: 5, deletions: 2 },
|
||||
]);
|
||||
|
||||
expect(stat).toEqual({ additions: 8, deletions: 3 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildTurnDiffTree", () => {
|
||||
it("builds nested directory nodes with aggregated stats", () => {
|
||||
const tree = buildTurnDiffTree([
|
||||
{ path: "src/index.ts", additions: 2, deletions: 1 },
|
||||
{ path: "src/components/Button.tsx", additions: 4, deletions: 2 },
|
||||
{ path: "README.md", additions: 1, deletions: 0 },
|
||||
]);
|
||||
|
||||
expect(tree).toEqual([
|
||||
{
|
||||
kind: "directory",
|
||||
name: "src",
|
||||
path: "src",
|
||||
stat: { additions: 6, deletions: 3 },
|
||||
children: [
|
||||
{
|
||||
kind: "directory",
|
||||
name: "components",
|
||||
path: "src/components",
|
||||
stat: { additions: 4, deletions: 2 },
|
||||
children: [
|
||||
{
|
||||
kind: "file",
|
||||
name: "Button.tsx",
|
||||
path: "src/components/Button.tsx",
|
||||
stat: { additions: 4, deletions: 2 },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
kind: "file",
|
||||
name: "index.ts",
|
||||
path: "src/index.ts",
|
||||
stat: { additions: 2, deletions: 1 },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
kind: "file",
|
||||
name: "README.md",
|
||||
path: "README.md",
|
||||
stat: { additions: 1, deletions: 0 },
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps files without stat values and excludes them from directory totals", () => {
|
||||
const tree = buildTurnDiffTree([
|
||||
{ path: "docs/notes.md" },
|
||||
{ path: "docs/todo.md", additions: 1, deletions: 1 },
|
||||
]);
|
||||
|
||||
expect(tree).toEqual([
|
||||
{
|
||||
kind: "directory",
|
||||
name: "docs",
|
||||
path: "docs",
|
||||
stat: { additions: 1, deletions: 1 },
|
||||
children: [
|
||||
{
|
||||
kind: "file",
|
||||
name: "notes.md",
|
||||
path: "docs/notes.md",
|
||||
stat: null,
|
||||
},
|
||||
{
|
||||
kind: "file",
|
||||
name: "todo.md",
|
||||
path: "docs/todo.md",
|
||||
stat: { additions: 1, deletions: 1 },
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("normalizes file paths with windows separators", () => {
|
||||
const tree = buildTurnDiffTree([{ path: "apps\\web\\src\\index.ts", additions: 2, deletions: 1 }]);
|
||||
|
||||
expect(tree).toEqual([
|
||||
{
|
||||
kind: "directory",
|
||||
name: "apps/web/src",
|
||||
path: "apps/web/src",
|
||||
stat: { additions: 2, deletions: 1 },
|
||||
children: [
|
||||
{
|
||||
kind: "file",
|
||||
name: "index.ts",
|
||||
path: "apps/web/src/index.ts",
|
||||
stat: { additions: 2, deletions: 1 },
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("compacts only single-directory chains and stops at branch points", () => {
|
||||
const tree = buildTurnDiffTree([
|
||||
{ path: "apps/server/src/index.ts", additions: 2, deletions: 1 },
|
||||
{ path: "apps/server/main.ts", additions: 4, deletions: 0 },
|
||||
]);
|
||||
|
||||
expect(tree).toEqual([
|
||||
{
|
||||
kind: "directory",
|
||||
name: "apps/server",
|
||||
path: "apps/server",
|
||||
stat: { additions: 6, deletions: 1 },
|
||||
children: [
|
||||
{
|
||||
kind: "directory",
|
||||
name: "src",
|
||||
path: "apps/server/src",
|
||||
stat: { additions: 2, deletions: 1 },
|
||||
children: [
|
||||
{
|
||||
kind: "file",
|
||||
name: "index.ts",
|
||||
path: "apps/server/src/index.ts",
|
||||
stat: { additions: 2, deletions: 1 },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
kind: "file",
|
||||
name: "main.ts",
|
||||
path: "apps/server/main.ts",
|
||||
stat: { additions: 4, deletions: 0 },
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("preserves leading/trailing whitespace in path segments", () => {
|
||||
const tree = buildTurnDiffTree([
|
||||
{ path: "a/file.ts", additions: 1, deletions: 0 },
|
||||
{ path: " a/file.ts", additions: 2, deletions: 0 },
|
||||
]);
|
||||
|
||||
expect(tree).toHaveLength(2);
|
||||
const directoryNodes = tree.filter(
|
||||
(node): node is Extract<(typeof tree)[number], { kind: "directory" }> => node.kind === "directory",
|
||||
);
|
||||
expect(directoryNodes.map((node) => node.name).toSorted()).toEqual([" a", "a"]);
|
||||
expect(directoryNodes.map((node) => node.path).toSorted()).toEqual([" a", "a"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,172 @@
|
||||
import type { TurnDiffFileChange } from "../types";
|
||||
|
||||
export interface TurnDiffStat {
|
||||
additions: number;
|
||||
deletions: number;
|
||||
}
|
||||
|
||||
export interface TurnDiffTreeDirectoryNode {
|
||||
kind: "directory";
|
||||
name: string;
|
||||
path: string;
|
||||
stat: TurnDiffStat;
|
||||
children: TurnDiffTreeNode[];
|
||||
}
|
||||
|
||||
export interface TurnDiffTreeFileNode {
|
||||
kind: "file";
|
||||
name: string;
|
||||
path: string;
|
||||
stat: TurnDiffStat | null;
|
||||
}
|
||||
|
||||
export type TurnDiffTreeNode = TurnDiffTreeDirectoryNode | TurnDiffTreeFileNode;
|
||||
|
||||
interface MutableDirectoryNode {
|
||||
name: string;
|
||||
path: string;
|
||||
stat: TurnDiffStat;
|
||||
directories: Map<string, MutableDirectoryNode>;
|
||||
files: TurnDiffTreeFileNode[];
|
||||
}
|
||||
|
||||
const SORT_LOCALE_OPTIONS: Intl.CollatorOptions = { numeric: true, sensitivity: "base" };
|
||||
|
||||
function normalizePathSegments(pathValue: string): string[] {
|
||||
return pathValue
|
||||
.replaceAll("\\", "/")
|
||||
.split("/")
|
||||
.filter((segment) => segment.length > 0);
|
||||
}
|
||||
|
||||
function compareByName(a: { name: string }, b: { name: string }): number {
|
||||
return a.name.localeCompare(b.name, undefined, SORT_LOCALE_OPTIONS);
|
||||
}
|
||||
|
||||
function readStat(file: TurnDiffFileChange): TurnDiffStat | null {
|
||||
if (typeof file.additions !== "number" || typeof file.deletions !== "number") {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
additions: file.additions,
|
||||
deletions: file.deletions,
|
||||
};
|
||||
}
|
||||
|
||||
function compactDirectoryNode(node: TurnDiffTreeDirectoryNode): TurnDiffTreeDirectoryNode {
|
||||
const compactedChildren = node.children.map((child) =>
|
||||
child.kind === "directory" ? compactDirectoryNode(child) : child,
|
||||
);
|
||||
|
||||
let compactedNode: TurnDiffTreeDirectoryNode = {
|
||||
...node,
|
||||
children: compactedChildren,
|
||||
};
|
||||
|
||||
while (compactedNode.children.length === 1 && compactedNode.children[0]?.kind === "directory") {
|
||||
const onlyChild = compactedNode.children[0];
|
||||
compactedNode = {
|
||||
kind: "directory",
|
||||
name: `${compactedNode.name}/${onlyChild.name}`,
|
||||
path: onlyChild.path,
|
||||
stat: onlyChild.stat,
|
||||
children: onlyChild.children,
|
||||
};
|
||||
}
|
||||
|
||||
return compactedNode;
|
||||
}
|
||||
|
||||
function toTreeNodes(directory: MutableDirectoryNode): TurnDiffTreeNode[] {
|
||||
const subdirectories: TurnDiffTreeDirectoryNode[] = Array.from(directory.directories.values())
|
||||
.toSorted(compareByName)
|
||||
.map<TurnDiffTreeDirectoryNode>((subdirectory) => ({
|
||||
kind: "directory",
|
||||
name: subdirectory.name,
|
||||
path: subdirectory.path,
|
||||
stat: {
|
||||
additions: subdirectory.stat.additions,
|
||||
deletions: subdirectory.stat.deletions,
|
||||
},
|
||||
children: toTreeNodes(subdirectory),
|
||||
}))
|
||||
.map((subdirectory) => compactDirectoryNode(subdirectory));
|
||||
|
||||
const files = directory.files.toSorted(compareByName);
|
||||
return [...subdirectories, ...files];
|
||||
}
|
||||
|
||||
export function summarizeTurnDiffStats(files: ReadonlyArray<TurnDiffFileChange>): TurnDiffStat {
|
||||
return files.reduce(
|
||||
(acc, file) => {
|
||||
const stat = readStat(file);
|
||||
if (!stat) return acc;
|
||||
return {
|
||||
additions: acc.additions + stat.additions,
|
||||
deletions: acc.deletions + stat.deletions,
|
||||
};
|
||||
},
|
||||
{ additions: 0, deletions: 0 },
|
||||
);
|
||||
}
|
||||
|
||||
export function buildTurnDiffTree(files: ReadonlyArray<TurnDiffFileChange>): TurnDiffTreeNode[] {
|
||||
const root: MutableDirectoryNode = {
|
||||
name: "",
|
||||
path: "",
|
||||
stat: { additions: 0, deletions: 0 },
|
||||
directories: new Map(),
|
||||
files: [],
|
||||
};
|
||||
|
||||
for (const file of files) {
|
||||
const segments = normalizePathSegments(file.path);
|
||||
if (segments.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const filePath = segments.join("/");
|
||||
const fileName = segments.at(-1);
|
||||
if (!fileName) {
|
||||
continue;
|
||||
}
|
||||
const stat = readStat(file);
|
||||
const ancestors: MutableDirectoryNode[] = [root];
|
||||
let currentDirectory = root;
|
||||
|
||||
for (const segment of segments.slice(0, -1)) {
|
||||
const nextPath = currentDirectory.path ? `${currentDirectory.path}/${segment}` : segment;
|
||||
const existing = currentDirectory.directories.get(segment);
|
||||
if (existing) {
|
||||
currentDirectory = existing;
|
||||
} else {
|
||||
const created: MutableDirectoryNode = {
|
||||
name: segment,
|
||||
path: nextPath,
|
||||
stat: { additions: 0, deletions: 0 },
|
||||
directories: new Map(),
|
||||
files: [],
|
||||
};
|
||||
currentDirectory.directories.set(segment, created);
|
||||
currentDirectory = created;
|
||||
}
|
||||
ancestors.push(currentDirectory);
|
||||
}
|
||||
|
||||
currentDirectory.files.push({
|
||||
kind: "file",
|
||||
name: fileName,
|
||||
path: filePath,
|
||||
stat,
|
||||
});
|
||||
|
||||
if (stat) {
|
||||
for (const ancestor of ancestors) {
|
||||
ancestor.stat.additions += stat.additions;
|
||||
ancestor.stat.deletions += stat.deletions;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return toTreeNodes(root);
|
||||
}
|
||||
+5
-25
@@ -1,41 +1,21 @@
|
||||
import React from "react";
|
||||
import ReactDOM from "react-dom/client";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { RouterProvider } from "@tanstack/react-router";
|
||||
import { createHashHistory, createRouter, createBrowserHistory } from "@tanstack/react-router";
|
||||
import { StoreProvider } from "./store";
|
||||
import { createHashHistory, createBrowserHistory } from "@tanstack/react-router";
|
||||
|
||||
import "@xterm/xterm/css/xterm.css";
|
||||
import "./index.css";
|
||||
|
||||
import { APP_DISPLAY_NAME } from "./branding";
|
||||
import { isElectron } from "./env";
|
||||
import { routeTree } from "./routeTree.gen";
|
||||
import { getRouter } from "./router";
|
||||
import { APP_DISPLAY_NAME } from "./branding";
|
||||
|
||||
const history = isElectron ? createHashHistory() : createBrowserHistory();
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
const router = getRouter(history);
|
||||
|
||||
document.title = APP_DISPLAY_NAME;
|
||||
|
||||
const router = createRouter({
|
||||
routeTree,
|
||||
history,
|
||||
context: {
|
||||
queryClient,
|
||||
},
|
||||
Wrap: ({ children }) => (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<StoreProvider>{children}</StoreProvider>
|
||||
</QueryClientProvider>
|
||||
),
|
||||
});
|
||||
|
||||
declare module "@tanstack/react-router" {
|
||||
interface Register {
|
||||
router: typeof router;
|
||||
}
|
||||
}
|
||||
|
||||
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
|
||||
<React.StrictMode>
|
||||
<RouterProvider router={router} />
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { createElement } from "react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { createRouter } from "@tanstack/react-router";
|
||||
|
||||
import { routeTree } from "./routeTree.gen";
|
||||
import { StoreProvider } from "./store";
|
||||
|
||||
type RouterHistory = NonNullable<Parameters<typeof createRouter>[0]["history"]>;
|
||||
|
||||
export function getRouter(history: RouterHistory) {
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
return createRouter({
|
||||
routeTree,
|
||||
history,
|
||||
context: {
|
||||
queryClient,
|
||||
},
|
||||
Wrap: ({ children }) =>
|
||||
createElement(
|
||||
QueryClientProvider,
|
||||
{ client: queryClient },
|
||||
createElement(StoreProvider, null, children),
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
export type AppRouter = ReturnType<typeof getRouter>;
|
||||
|
||||
declare module "@tanstack/react-router" {
|
||||
interface Register {
|
||||
router: AppRouter;
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,9 @@ export const Route = createRootRouteWithContext<{
|
||||
}>()({
|
||||
component: RootRouteView,
|
||||
errorComponent: RootRouteErrorView,
|
||||
head: () => ({
|
||||
meta: [{ name: "title", content: APP_DISPLAY_NAME }],
|
||||
}),
|
||||
});
|
||||
|
||||
function RootRouteView() {
|
||||
@@ -152,9 +155,7 @@ function EventRouter() {
|
||||
latestSequence = Math.max(latestSequence, snapshot.snapshotSequence);
|
||||
syncServerReadModel(snapshot);
|
||||
const activeThreadIds = new Set(
|
||||
snapshot.threads
|
||||
.filter((t) => t.deletedAt === null)
|
||||
.map((t) => t.id),
|
||||
snapshot.threads.filter((t) => t.deletedAt === null).map((t) => t.id),
|
||||
);
|
||||
removeOrphanedTerminalStates(activeThreadIds);
|
||||
if (pending) {
|
||||
@@ -195,11 +196,13 @@ function EventRouter() {
|
||||
if (hasRunningSubprocess === null) {
|
||||
return;
|
||||
}
|
||||
useTerminalStateStore.getState().setTerminalActivity(
|
||||
ThreadId.makeUnsafe(event.threadId),
|
||||
event.terminalId,
|
||||
hasRunningSubprocess,
|
||||
);
|
||||
useTerminalStateStore
|
||||
.getState()
|
||||
.setTerminalActivity(
|
||||
ThreadId.makeUnsafe(event.threadId),
|
||||
event.terminalId,
|
||||
hasRunningSubprocess,
|
||||
);
|
||||
});
|
||||
const unsubWelcome = onServerWelcome((payload) => {
|
||||
void (async () => {
|
||||
@@ -276,7 +279,13 @@ function EventRouter() {
|
||||
unsubWelcome();
|
||||
unsubServerConfigUpdated();
|
||||
};
|
||||
}, [navigate, queryClient, removeOrphanedTerminalStates, setProjectExpanded, syncServerReadModel]);
|
||||
}, [
|
||||
navigate,
|
||||
queryClient,
|
||||
removeOrphanedTerminalStates,
|
||||
setProjectExpanded,
|
||||
syncServerReadModel,
|
||||
]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -3,7 +3,11 @@ import { useEffect } from "react";
|
||||
|
||||
import { DiffWorkerPoolProvider } from "../components/DiffWorkerPoolProvider";
|
||||
import ThreadSidebar from "../components/Sidebar";
|
||||
import { Sidebar, SidebarProvider } from "~/components/ui/sidebar";
|
||||
import { Sidebar, SidebarProvider, SidebarRail } from "~/components/ui/sidebar";
|
||||
|
||||
const THREAD_SIDEBAR_WIDTH_STORAGE_KEY = "chat_thread_sidebar_width";
|
||||
const THREAD_SIDEBAR_MIN_WIDTH = 16 * 16;
|
||||
const THREAD_SIDEBAR_MAX_WIDTH = 40 * 16;
|
||||
|
||||
function ChatRouteLayout() {
|
||||
const navigate = useNavigate();
|
||||
@@ -30,8 +34,14 @@ function ChatRouteLayout() {
|
||||
side="left"
|
||||
collapsible="offcanvas"
|
||||
className="border-r border-border bg-card text-foreground"
|
||||
resizable={{
|
||||
maxWidth: THREAD_SIDEBAR_MAX_WIDTH,
|
||||
minWidth: THREAD_SIDEBAR_MIN_WIDTH,
|
||||
storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
|
||||
}}
|
||||
>
|
||||
<ThreadSidebar />
|
||||
<SidebarRail />
|
||||
</Sidebar>
|
||||
<DiffWorkerPoolProvider>
|
||||
<Outlet />
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export function truncateTitle(text: string, maxLength = 50): string {
|
||||
export function truncateTitle(text: string, maxLength = 300): string {
|
||||
const trimmed = text.trim();
|
||||
if (trimmed.length <= maxLength) {
|
||||
return trimmed;
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { playwright } from "@vitest/browser-playwright";
|
||||
import { defineConfig, mergeConfig } from "vitest/config";
|
||||
|
||||
import viteConfig from "./vite.config";
|
||||
|
||||
const srcPath = fileURLToPath(new URL("./src", import.meta.url));
|
||||
|
||||
export default mergeConfig(
|
||||
viteConfig,
|
||||
defineConfig({
|
||||
resolve: {
|
||||
alias: {
|
||||
"~": srcPath,
|
||||
},
|
||||
},
|
||||
test: {
|
||||
include: ["src/components/ChatView.browser.tsx"],
|
||||
browser: {
|
||||
enabled: true,
|
||||
provider: playwright(),
|
||||
instances: [{ browser: "chromium" }],
|
||||
headless: true,
|
||||
},
|
||||
testTimeout: 30_000,
|
||||
hookTimeout: 30_000,
|
||||
},
|
||||
}),
|
||||
);
|
||||
@@ -14,7 +14,7 @@
|
||||
},
|
||||
"apps/desktop": {
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.0-alpha.18",
|
||||
"version": "0.0.0-alpha.20",
|
||||
"dependencies": {
|
||||
"effect": "catalog:",
|
||||
"electron": "40.6.0",
|
||||
@@ -32,7 +32,7 @@
|
||||
},
|
||||
"apps/server": {
|
||||
"name": "t3",
|
||||
"version": "0.0.0-alpha.18",
|
||||
"version": "0.0.0-alpha.20",
|
||||
"bin": {
|
||||
"t3": "./dist/index.mjs",
|
||||
},
|
||||
@@ -61,7 +61,7 @@
|
||||
},
|
||||
"apps/web": {
|
||||
"name": "@t3tools/web",
|
||||
"version": "0.0.0-alpha.18",
|
||||
"version": "0.0.0-alpha.20",
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.2.0",
|
||||
"@lexical/react": "^0.41.0",
|
||||
@@ -92,16 +92,20 @@
|
||||
"@types/react": "^19.0.0",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
"@vitejs/plugin-react": "^5.1.4",
|
||||
"@vitest/browser-playwright": "^4.0.18",
|
||||
"babel-plugin-react-compiler": "^19.0.0-beta-e552027-20250112",
|
||||
"msw": "^2.12.10",
|
||||
"playwright": "^1.58.2",
|
||||
"tailwindcss": "^4.0.0",
|
||||
"typescript": "catalog:",
|
||||
"vite": "^8.0.0-beta.12",
|
||||
"vitest": "catalog:",
|
||||
"vitest-browser-react": "^2.0.5",
|
||||
},
|
||||
},
|
||||
"packages/contracts": {
|
||||
"name": "@t3tools/contracts",
|
||||
"version": "0.0.0-alpha.18",
|
||||
"version": "0.0.0-alpha.20",
|
||||
"dependencies": {
|
||||
"effect": "catalog:",
|
||||
},
|
||||
@@ -467,6 +471,8 @@
|
||||
|
||||
"@pierre/diffs": ["@pierre/[email protected]", "", { "dependencies": { "@shikijs/transformers": "^3.0.0", "diff": "8.0.3", "hast-util-to-html": "9.0.5", "lru_map": "0.4.1", "shiki": "^3.0.0" }, "peerDependencies": { "react": "^18.3.1 || ^19.0.0", "react-dom": "^18.3.1 || ^19.0.0" } }, "sha512-McjTuEPuacSIcXdoI2O9W6VSHIOs9ApEHnEUwONKZnKqIo2GGv1vNg9Pr8tgBOL7lgBWNEHX5ROJ5z1X74sENQ=="],
|
||||
|
||||
"@polka/url": ["@polka/[email protected]", "", {}, "sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww=="],
|
||||
|
||||
"@preact/signals-core": ["@preact/[email protected]", "", {}, "sha512-slT6XeTCAbdql61GVLlGU4x7XHI7kCZV5Um5uhE4zLX4ApgiiXc0UYFvVOKq06xcovzp7p+61l68oPi563ARKg=="],
|
||||
|
||||
"@quansync/fs": ["@quansync/[email protected]", "", { "dependencies": { "quansync": "^1.0.0" } }, "sha512-4TJ3DFtlf1L5LDMaM6CanJ/0lckGNtJcMjQ1NAV6zDmA0tEHKZtxNKin8EgPaVX1YzljbxckyT2tJrpQKAtngQ=="],
|
||||
@@ -699,6 +705,10 @@
|
||||
|
||||
"@vitejs/plugin-react": ["@vitejs/[email protected]", "", { "dependencies": { "@babel/core": "^7.29.0", "@babel/plugin-transform-react-jsx-self": "^7.27.1", "@babel/plugin-transform-react-jsx-source": "^7.27.1", "@rolldown/pluginutils": "1.0.0-rc.3", "@types/babel__core": "^7.20.5", "react-refresh": "^0.18.0" }, "peerDependencies": { "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" } }, "sha512-VIcFLdRi/VYRU8OL/puL7QXMYafHmqOnwTZY50U1JPlCNj30PxCMx65c494b1K9be9hX83KVt0+gTEwTWLqToA=="],
|
||||
|
||||
"@vitest/browser": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/mocker": "4.0.18", "@vitest/utils": "4.0.18", "magic-string": "^0.30.21", "pixelmatch": "7.1.0", "pngjs": "^7.0.0", "sirv": "^3.0.2", "tinyrainbow": "^3.0.3", "ws": "^8.18.3" }, "peerDependencies": { "vitest": "4.0.18" } }, "sha512-gVQqh7paBz3gC+ZdcCmNSWJMk70IUjDeVqi+5m5vYpEHsIwRgw3Y545jljtajhkekIpIp5Gg8oK7bctgY0E2Ng=="],
|
||||
|
||||
"@vitest/browser-playwright": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/browser": "4.0.18", "@vitest/mocker": "4.0.18", "tinyrainbow": "^3.0.3" }, "peerDependencies": { "playwright": "*", "vitest": "4.0.18" } }, "sha512-gfajTHVCiwpxRj1qh0Sh/5bbGLG4F/ZH/V9xvFVoFddpITfMta9YGow0W6ZpTTORv2vdJuz9TnrNSmjKvpOf4g=="],
|
||||
|
||||
"@vitest/expect": ["@vitest/[email protected]", "", { "dependencies": { "@standard-schema/spec": "^1.0.0", "@types/chai": "^5.2.2", "@vitest/spy": "4.0.18", "@vitest/utils": "4.0.18", "chai": "^6.2.1", "tinyrainbow": "^3.0.3" } }, "sha512-8sCWUyckXXYvx4opfzVY03EOiYVxyNrHS5QxX3DAIi5dpJAAkyJezHCP77VMX4HKA2LDT/Jpfo8i2r5BE3GnQQ=="],
|
||||
|
||||
"@vitest/mocker": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/spy": "4.0.18", "estree-walker": "^3.0.3", "magic-string": "^0.30.21" }, "peerDependencies": { "msw": "^2.4.9", "vite": "^6.0.0 || ^7.0.0-0" }, "optionalPeers": ["msw", "vite"] }, "sha512-HhVd0MDnzzsgevnOWCBj5Otnzobjy5wLBe4EdeeFGv8luMsGcYqDuFRMcttKWZA5vVO8RFjexVovXvAM4JoJDQ=="],
|
||||
@@ -919,7 +929,7 @@
|
||||
|
||||
"fs-extra": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ=="],
|
||||
|
||||
"fsevents": ["[email protected].3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
"fsevents": ["[email protected].2", "", { "os": "darwin" }, "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA=="],
|
||||
|
||||
"function-bind": ["[email protected]", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="],
|
||||
|
||||
@@ -1191,6 +1201,8 @@
|
||||
|
||||
"minimist": ["[email protected]", "", {}, "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA=="],
|
||||
|
||||
"mrmime": ["[email protected]", "", {}, "sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ=="],
|
||||
|
||||
"ms": ["[email protected]", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
|
||||
|
||||
"msgpackr": ["[email protected]", "", { "optionalDependencies": { "msgpackr-extract": "^3.0.2" } }, "sha512-bC4UGzHhVvgDNS7kn9tV8fAucIYUBuGojcaLiz7v+P63Lmtm0Xeji8B/8tYKddALXxJLpwIeBmUN3u64C4YkRA=="],
|
||||
@@ -1249,6 +1261,14 @@
|
||||
|
||||
"picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],
|
||||
|
||||
"pixelmatch": ["[email protected]", "", { "dependencies": { "pngjs": "^7.0.0" }, "bin": { "pixelmatch": "bin/pixelmatch" } }, "sha512-1wrVzJ2STrpmONHKBy228LM1b84msXDUoAzVEl0R8Mz4Ce6EPr+IVtxm8+yvrqLYMHswREkjYFaMxnyGnaY3Ng=="],
|
||||
|
||||
"playwright": ["[email protected]", "", { "dependencies": { "playwright-core": "1.58.2" }, "optionalDependencies": { "fsevents": "2.3.2" }, "bin": { "playwright": "cli.js" } }, "sha512-vA30H8Nvkq/cPBnNw4Q8TWz1EJyqgpuinBcHET0YVJVFldr8JDNiU9LaWAE1KqSkRYazuaBhTpB5ZzShOezQ6A=="],
|
||||
|
||||
"playwright-core": ["[email protected]", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-yZkEtftgwS8CsfYo7nm0KE8jsvm6i/PTgVtB8DL726wNf6H2IMsDuxCpJj59KDaxCtSnrWan2AeDqM7JBaultg=="],
|
||||
|
||||
"pngjs": ["[email protected]", "", {}, "sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow=="],
|
||||
|
||||
"postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg=="],
|
||||
|
||||
"prettier": ["[email protected]", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg=="],
|
||||
@@ -1345,6 +1365,8 @@
|
||||
|
||||
"signal-exit": ["[email protected]", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="],
|
||||
|
||||
"sirv": ["[email protected]", "", { "dependencies": { "@polka/url": "^1.0.0-next.24", "mrmime": "^2.0.0", "totalist": "^3.0.0" } }, "sha512-2wcC/oGxHis/BoHkkPwldgiPSYcpZK3JU28WoMVv55yHJgcZ8rlXvuG9iZggz+sU1d4bRgIGASwyWqjxu3FM0g=="],
|
||||
|
||||
"source-map": ["[email protected]", "", {}, "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ=="],
|
||||
|
||||
"source-map-js": ["[email protected]", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
|
||||
@@ -1411,6 +1433,8 @@
|
||||
|
||||
"toml": ["[email protected]", "", {}, "sha512-y/mWCZinnvxjTKYhJ+pYxwD0mRLVvOtdS2Awbgxln6iEnt4rk0yBxeSBHkGJcPucRiG0e55mwWp+g/05rsrd6w=="],
|
||||
|
||||
"totalist": ["[email protected]", "", {}, "sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ=="],
|
||||
|
||||
"tough-cookie": ["[email protected]", "", { "dependencies": { "tldts": "^7.0.5" } }, "sha512-kXuRi1mtaKMrsLUxz3sQYvVl37B0Ns6MzfrtV5DvJceE9bPyspOqk9xxv7XbZWcfLWbFmm997vl83qUWVJA64w=="],
|
||||
|
||||
"tree-kill": ["[email protected]", "", { "bin": { "tree-kill": "cli.js" } }, "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A=="],
|
||||
@@ -1483,6 +1507,8 @@
|
||||
|
||||
"vitest": ["[email protected]", "", { "dependencies": { "@vitest/expect": "4.0.18", "@vitest/mocker": "4.0.18", "@vitest/pretty-format": "4.0.18", "@vitest/runner": "4.0.18", "@vitest/snapshot": "4.0.18", "@vitest/spy": "4.0.18", "@vitest/utils": "4.0.18", "es-module-lexer": "^1.7.0", "expect-type": "^1.2.2", "magic-string": "^0.30.21", "obug": "^2.1.1", "pathe": "^2.0.3", "picomatch": "^4.0.3", "std-env": "^3.10.0", "tinybench": "^2.9.0", "tinyexec": "^1.0.2", "tinyglobby": "^0.2.15", "tinyrainbow": "^3.0.3", "vite": "^6.0.0 || ^7.0.0", "why-is-node-running": "^2.3.0" }, "peerDependencies": { "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", "@vitest/browser-playwright": "4.0.18", "@vitest/browser-preview": "4.0.18", "@vitest/browser-webdriverio": "4.0.18", "@vitest/ui": "4.0.18", "happy-dom": "*", "jsdom": "*" }, "optionalPeers": ["@edge-runtime/vm", "@opentelemetry/api", "@types/node", "@vitest/browser-playwright", "@vitest/browser-preview", "@vitest/browser-webdriverio", "@vitest/ui", "happy-dom", "jsdom"], "bin": { "vitest": "vitest.mjs" } }, "sha512-hOQuK7h0FGKgBAas7v0mSAsnvrIgAvWmRFjmzpJ7SwFHH3g1k2u37JtYwOwmEKhK6ZO3v9ggDBBm0La1LCK4uQ=="],
|
||||
|
||||
"vitest-browser-react": ["[email protected]", "", { "peerDependencies": { "@types/react": "^18.0.0 || ^19.0.0", "@types/react-dom": "^18.0.0 || ^19.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0", "vitest": "^4.0.0" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-YODQX8mHTJCyKNVYTWJrLEYrUtw+QfLl78owgvuE7C5ydgmGBq6v5s4jK2w6wdPhIZsN9PpV1rQbmAevWJjO9g=="],
|
||||
|
||||
"wait-on": ["[email protected]", "", { "dependencies": { "axios": "^1.12.1", "joi": "^18.0.1", "lodash": "^4.17.21", "minimist": "^1.2.8", "rxjs": "^7.8.2" }, "bin": { "wait-on": "bin/wait-on" } }, "sha512-J3WlS0txVHkhLRb2FsmRg3dkMTCV1+M6Xra3Ho7HzZDHpE7DCOnoSoCJsZotrmW3uRMhvIJGSKUKrh/MeF4iag=="],
|
||||
|
||||
"webpack-virtual-modules": ["[email protected]", "", {}, "sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ=="],
|
||||
@@ -1587,6 +1613,8 @@
|
||||
|
||||
"babel-dead-code-elimination/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.0" }, "bin": "./bin/babel-parser.js" }, "sha512-IyDgFV5GeDUVX4YdF/3CPULtVGSXXMLh1xVIgdCgxApktqnQV0r7/8Nqthg+8YLGaAtdyIlo2qIdZrbCv4+7ww=="],
|
||||
|
||||
"chokidar/fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
|
||||
"cliui/wrap-ansi": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="],
|
||||
|
||||
"clone-response/mimic-response": ["[email protected]", "", {}, "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ=="],
|
||||
@@ -1601,8 +1629,14 @@
|
||||
|
||||
"rolldown-plugin-dts/@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^8.0.0-rc.1", "@babel/helper-validator-identifier": "^8.0.0-rc.1" } }, "sha512-ubmJ6TShyaD69VE9DQrlXcdkvJbmwWPB8qYj0H2kaJi29O7vJT9ajSdBd2W8CG34pwL9pYA74fi7RHC1qbLoVQ=="],
|
||||
|
||||
"rollup/fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
|
||||
"serialize-error/type-fest": ["[email protected]", "", {}, "sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg=="],
|
||||
|
||||
"tsx/fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
|
||||
"vite/fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
|
||||
"vitest/vite": ["[email protected]", "", { "dependencies": { "esbuild": "^0.27.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA=="],
|
||||
|
||||
"@babel/generator/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-vi/pfmbrOtQmqgfboaBhaCU50G7mcySVu69VU8z+lYoPPB6WzI9VgV7WQfL908M4oeSH5fDkmoupIqoE0SdApw=="],
|
||||
@@ -1635,6 +1669,8 @@
|
||||
|
||||
"@tailwindcss/node/lightningcss/lightningcss-win32-x64-msvc": ["[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-5g1yc73p+iAkid5phb4oVFMB45417DkRevRbt/El/gKXJk4jid+vPFF/AXbxn05Aky8PapwzZrdJShv5C0avjw=="],
|
||||
|
||||
"@tailwindcss/vite/vite/fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
|
||||
"@types/cacheable-request/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"@types/keyv/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
@@ -1645,6 +1681,10 @@
|
||||
|
||||
"@types/yauzl/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"@vitejs/plugin-react/vite/fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
|
||||
"rolldown-plugin-dts/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-vi/pfmbrOtQmqgfboaBhaCU50G7mcySVu69VU8z+lYoPPB6WzI9VgV7WQfL908M4oeSH5fDkmoupIqoE0SdApw=="],
|
||||
|
||||
"vitest/vite/fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
}
|
||||
}
|
||||
+7
-2
@@ -56,5 +56,10 @@
|
||||
"bun": "^1.3.9",
|
||||
"node": "^24.13.1"
|
||||
},
|
||||
"packageManager": "[email protected]"
|
||||
}
|
||||
"packageManager": "[email protected]",
|
||||
"msw": {
|
||||
"workerDirectory": [
|
||||
"apps/web/public"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/contracts",
|
||||
"version": "0.0.0-alpha.18",
|
||||
"version": "0.0.0-alpha.20",
|
||||
"private": true,
|
||||
"files": [
|
||||
"dist"
|
||||
|
||||
@@ -49,24 +49,6 @@ export type ServerProviderStatus = typeof ServerProviderStatus.Type;
|
||||
export const ServerProviderStatuses = Schema.Array(ServerProviderStatus);
|
||||
export type ServerProviderStatuses = typeof ServerProviderStatuses.Type;
|
||||
|
||||
export const ServerRuntimePlatform = Schema.Literals(["windows", "linux", "macos"]);
|
||||
export type ServerRuntimePlatform = typeof ServerRuntimePlatform.Type;
|
||||
|
||||
export const ServerPathStyle = Schema.Literals(["windows", "posix"]);
|
||||
export type ServerPathStyle = typeof ServerPathStyle.Type;
|
||||
|
||||
export const ServerWindowsInteropMode = Schema.Literals(["windows-native", "wsl-hosted"]);
|
||||
export type ServerWindowsInteropMode = typeof ServerWindowsInteropMode.Type;
|
||||
|
||||
export const ServerRuntimeEnvironment = Schema.Struct({
|
||||
platform: ServerRuntimePlatform,
|
||||
pathStyle: ServerPathStyle,
|
||||
isWsl: Schema.Boolean,
|
||||
windowsInteropMode: Schema.NullOr(ServerWindowsInteropMode),
|
||||
wslDistroName: Schema.NullOr(TrimmedNonEmptyString),
|
||||
});
|
||||
export type ServerRuntimeEnvironment = typeof ServerRuntimeEnvironment.Type;
|
||||
|
||||
export const ServerConfig = Schema.Struct({
|
||||
cwd: TrimmedNonEmptyString,
|
||||
keybindingsConfigPath: TrimmedNonEmptyString,
|
||||
@@ -74,7 +56,6 @@ export const ServerConfig = Schema.Struct({
|
||||
issues: ServerConfigIssues,
|
||||
providers: ServerProviderStatuses,
|
||||
availableEditors: Schema.Array(EditorId),
|
||||
runtimeEnvironment: ServerRuntimeEnvironment,
|
||||
});
|
||||
export type ServerConfig = typeof ServerConfig.Type;
|
||||
|
||||
|
||||
Reference in new issue
Block a user