Compare commits

..
Author SHA1 Message Date
Cursor Agent a4a2302607 refactor: extract encodeJsonStringForDiagnostics into @t3tools/shared/schemaJson
The identical helper function was duplicated across ClaudeAdapter.ts,
CursorAdapter.ts, and opencodeRuntime.ts. Consolidate into the shared
schemaJson module and import from there.
2026-05-08 18:57:39 +00:00
Julius Marmingeandcodex e9f549048b Fix release smoke workspace fixture
Co-authored-by: codex <[email protected]>
2026-05-08 11:45:46 -07:00
Julius Marmingeandcodex f0dc3c5ac9 Harden schema runtime decoding
Co-authored-by: codex <[email protected]>
2026-05-08 11:42:37 -07:00
Julius Marmingeandcodex 3dd82e21b0 Add t3code oxlint schema compile rule
Co-authored-by: codex <[email protected]>
2026-05-08 11:27:39 -07:00
Julius Marminge 06c2b010c6 Refine oxlint rule harness effect types
- Switch to explicit Effect module imports
- Encode Oxlint config with Schema
- Simplify test assertions and harness signatures
2026-05-08 11:01:45 -07:00
Julius Marmingeandcodex b9fad2305e Add oxlint rule for inline schema compilers
- Introduce a t3code oxlint plugin and wire it into repo linting

- Flag Effect Schema compiler calls inside function bodies

- Add fixture-based tests for valid and invalid cases

Co-authored-by: codex <[email protected]>
2026-05-08 10:51:20 -07:00
126 changed files with 1901 additions and 5420 deletions

No files matched your search

+1 -156
View File
@@ -244,68 +244,6 @@ jobs:
exit $code
}
- name: Prepare Azure Trusted Signing
if: matrix.platform == 'win'
shell: pwsh
env:
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_TRUSTED_SIGNING_ENDPOINT: ${{ secrets.AZURE_TRUSTED_SIGNING_ENDPOINT }}
AZURE_TRUSTED_SIGNING_ACCOUNT_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }}
AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME }}
AZURE_TRUSTED_SIGNING_PUBLISHER_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_PUBLISHER_NAME }}
run: |
$ErrorActionPreference = "Stop"
$requiredSecrets = @(
$env:AZURE_TENANT_ID,
$env:AZURE_CLIENT_ID,
$env:AZURE_CLIENT_SECRET,
$env:AZURE_TRUSTED_SIGNING_ENDPOINT,
$env:AZURE_TRUSTED_SIGNING_ACCOUNT_NAME,
$env:AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME,
$env:AZURE_TRUSTED_SIGNING_PUBLISHER_NAME
)
if ($requiredSecrets | Where-Object { [string]::IsNullOrWhiteSpace($_) }) {
Write-Host "Azure Trusted Signing disabled; skipping TrustedSigning module preparation."
exit 0
}
try {
Install-PackageProvider `
-Name NuGet `
-MinimumVersion 2.8.5.201 `
-Force `
-Scope CurrentUser `
-ErrorAction Stop
} catch {
Write-Warning "Could not bootstrap NuGet package provider. Continuing because the runner may already have a usable provider. $($_.Exception.Message)"
}
Install-Module `
-Name TrustedSigning `
-MinimumVersion 0.5.0 `
-Force `
-AllowClobber `
-Repository PSGallery `
-Scope CurrentUser `
-ErrorAction Stop
Import-Module TrustedSigning -MinimumVersion 0.5.0 -Force
Get-Command Invoke-TrustedSigning -ErrorAction Stop
$moduleRoots = @(
[System.IO.Path]::Combine([Environment]::GetFolderPath("MyDocuments"), "PowerShell", "Modules"),
[System.IO.Path]::Combine([Environment]::GetFolderPath("MyDocuments"), "WindowsPowerShell", "Modules"),
[System.IO.Path]::Combine($env:ProgramFiles, "PowerShell", "Modules"),
[System.IO.Path]::Combine($env:ProgramFiles, "WindowsPowerShell", "Modules")
)
$modulePathEntries = @($moduleRoots + ($env:PSModulePath -split ";")) |
Where-Object { $_ -and (Test-Path $_) } |
Select-Object -Unique
"PSModulePath=$($modulePathEntries -join ';')" >> $env:GITHUB_ENV
- name: Build desktop artifact
shell: bash
env:
@@ -573,98 +511,6 @@ jobs:
fail_on_unmatched_files: true
token: ${{ steps.app_token.outputs.token }}
deploy_web:
name: Deploy hosted web app
needs: [preflight, release]
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' }}
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
env:
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}
T3CODE_WEB_ROUTER_URL: ${{ vars.T3CODE_WEB_ROUTER_URL }}
T3CODE_WEB_LATEST_DOMAIN: ${{ vars.T3CODE_WEB_LATEST_DOMAIN }}
T3CODE_WEB_NIGHTLY_DOMAIN: ${{ vars.T3CODE_WEB_NIGHTLY_DOMAIN }}
VERCEL_TEAM_SLUG: ${{ vars.VERCEL_TEAM_SLUG }}
steps:
- name: Checkout
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: package.json
- name: Install release tooling dependencies
run: bun install --frozen-lockfile --filter=@t3tools/scripts --filter=@t3tools/web
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Refresh release lockfile
run: bun install --lockfile-only --ignore-scripts
- name: Deploy and alias channel
shell: bash
run: |
set -euo pipefail
if [[ -z "${VERCEL_TOKEN:-}" || -z "${VERCEL_ORG_ID:-}" || -z "${VERCEL_PROJECT_ID:-}" ]]; then
echo "Missing one or more required Vercel secrets: VERCEL_TOKEN, VERCEL_ORG_ID, VERCEL_PROJECT_ID." >&2
exit 1
fi
router_url="${T3CODE_WEB_ROUTER_URL:-https://app.t3.codes}"
latest_domain="${T3CODE_WEB_LATEST_DOMAIN:-latest.app.t3.codes}"
nightly_domain="${T3CODE_WEB_NIGHTLY_DOMAIN:-nightly.app.t3.codes}"
router_domain="${router_url#http://}"
router_domain="${router_domain#https://}"
router_domain="${router_domain%%/*}"
if [[ "${{ needs.preflight.outputs.release_channel }}" == "stable" ]]; then
channel_domain="$latest_domain"
channel_name="latest"
else
channel_domain="$nightly_domain"
channel_name="nightly"
fi
vercel_scope="${VERCEL_TEAM_SLUG:-$VERCEL_ORG_ID}"
vercel_scope_args=(--scope "$vercel_scope")
echo "Deploying hosted web app for $channel_name channel."
deployment_url="$(
bunx [email protected] deploy \
--prod \
--skip-domain \
--yes \
--token "$VERCEL_TOKEN" \
"${vercel_scope_args[@]}" \
--build-env "APP_VERSION=${{ needs.preflight.outputs.version }}" \
--build-env "VITE_HOSTED_APP_URL=$router_url" \
--build-env "VITE_HOSTED_APP_CHANNEL=$channel_name"
)"
echo "Aliasing $deployment_url to $channel_domain."
bunx [email protected] alias set "$deployment_url" "$channel_domain" \
--token "$VERCEL_TOKEN" \
"${vercel_scope_args[@]}"
if [[ "$channel_name" == "latest" && -n "$router_domain" && "$router_domain" != "$channel_domain" ]]; then
echo "Aliasing $deployment_url to router domain $router_domain."
bunx [email protected] alias set "$deployment_url" "$router_domain" \
--token "$VERCEL_TOKEN" \
"${vercel_scope_args[@]}"
fi
finalize:
name: Finalize release
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' && needs.preflight.outputs.release_channel == 'stable' }}
@@ -749,9 +595,8 @@ jobs:
always() && !cancelled() &&
needs.preflight.result == 'success' &&
needs.release.result == 'success' &&
needs.deploy_web.result == 'success' &&
(needs.finalize.result == 'success' || needs.finalize.result == 'skipped')
needs: [preflight, release, deploy_web, finalize]
needs: [preflight, release, finalize]
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
-37
View File
@@ -115,43 +115,6 @@ After setup, the renderer connects to a local forwarded HTTP/WebSocket endpoint.
SSH launch is a desktop feature because it needs local process and SSH access. Once the environment is paired and saved, it uses the same environment list and connection model as direct LAN, Tailscale, HTTPS, or future tunnel-backed environments.
#### SSH Launch Troubleshooting
The desktop SSH launcher connects with a non-interactive `sh` session, writes a small launcher script under `~/.t3/ssh-launch/<host-key>/`, starts or reuses a remote T3 server, and forwards the remote loopback port back to your desktop.
The remote host must have a compatible Node.js runtime. T3 Code uses the server package's `engines.node` requirement:
```text
^22.16 || ^23.11 || >=24.10
```
During SSH launch, T3 Code first checks whether `node` is already available on `PATH`. If it is missing, the launcher tries common non-interactive shell locations and version-manager shims/activation hooks:
- `~/.local/bin`, `~/bin`, `/opt/homebrew/bin`, `/usr/local/bin`, `/usr/bin`, `/bin`
- Volta via `~/.volta/bin`
- asdf via `~/.asdf/shims`, `~/.asdf/bin`, or `~/.asdf/asdf.sh`
- mise via `~/.local/share/mise/shims`, `~/.mise/shims`, or `mise activate sh`
- fnm via `fnm env --use-on-cd --shell sh` or `fnm env --shell sh`
- nodenv via `~/.nodenv/bin`, `~/.nodenv/shims`, or `nodenv init -`
- nvm via `$NVM_DIR/nvm.sh`, then `nvm use default`, `nvm use node`, or `nvm use --lts`
- installed nvm versions under `$NVM_DIR/versions/node/*/bin`
If launch fails with `node: command not found`, a port-scan failure, or a message that the remote Node version does not satisfy the required range, SSH into the host and check the same non-interactive shell path T3 Code uses:
```bash
ssh [email protected] 'sh -lc "command -v node && node --version"'
```
If that does not print a compatible Node version, configure your version manager for non-interactive shells or install a compatible Node binary in one of the searched locations. For example, with nvm you may need a default alias:
```bash
nvm alias default 24
```
With mise/asdf/fnm/nodenv, make sure the tool's shim directory is installed and points at a Node version satisfying the range above.
If reconnecting after an app update fails, retry the SSH launch once. The launcher now compares its generated runner script, stops stale launcher-managed remote servers, clears the SSH launch PID/port state, and starts a fresh remote server. You should not normally need to delete `~/.t3/ssh-launch` or kill `t3` processes manually.
## How Pairing Works
The remote device does not need a long-lived secret up front.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.23",
"version": "0.0.22",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
+1 -6
View File
@@ -11,7 +11,6 @@ import * as Electron from "electron";
import * as NetService from "@t3tools/shared/Net";
import { resolveRemoteT3CliPackageSpec } from "@t3tools/ssh/command";
import type { RemoteT3RunnerOptions } from "@t3tools/ssh/tunnel";
import serverPackageJson from "../../server/package.json" with { type: "json" };
import type { DesktopSettings as DesktopSettingsValue } from "./settings/DesktopAppSettings.ts";
import * as DesktopIpc from "./ipc/DesktopIpc.ts";
@@ -66,10 +65,7 @@ const resolveDesktopSshCliRunner = (
): RemoteT3RunnerOptions => {
const devRemoteEntryPath = Option.getOrUndefined(environment.devRemoteT3ServerEntryPath);
if (environment.isDevelopment && devRemoteEntryPath !== undefined) {
return {
nodeScriptPath: devRemoteEntryPath,
nodeEngineRange: serverPackageJson.engines.node,
};
return { nodeScriptPath: devRemoteEntryPath };
}
return {
packageSpec: resolveRemoteT3CliPackageSpec({
@@ -77,7 +73,6 @@ const resolveDesktopSshCliRunner = (
updateChannel: settings.updateChannel,
isDevelopment: environment.isDevelopment,
}),
nodeEngineRange: serverPackageJson.engines.node,
};
};
@@ -73,6 +73,7 @@ import {
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
import { WorkspaceEntriesLive } from "../src/workspace/Layers/WorkspaceEntries.ts";
import { WorkspacePathsLive } from "../src/workspace/Layers/WorkspacePaths.ts";
import * as GitVcsDriver from "../src/vcs/GitVcsDriver.ts";
import * as VcsDriverRegistry from "../src/vcs/VcsDriverRegistry.ts";
import { VcsStatusBroadcaster } from "../src/vcs/VcsStatusBroadcaster.ts";
import { GitWorkflowService } from "../src/git/GitWorkflowService.ts";
@@ -310,11 +311,8 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provideMerge(serverSettingsLayer),
);
const gitWorkflowLayer = Layer.mock(GitWorkflowService)({
renameBranch: (input: {
readonly cwd: string;
readonly oldBranch: string;
readonly newBranch: string;
}) => Effect.succeed({ branch: input.newBranch }),
renameBranch: (input: Parameters<GitVcsDriver.GitVcsDriverShape["renameBranch"]>[0]) =>
Effect.succeed({ branch: input.newBranch }),
});
const textGenerationLayer = Layer.succeed(TextGeneration, {
generateBranchName: () => Effect.succeed({ branch: "update" }),
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.23",
"version": "0.0.22",
"license": "MIT",
"repository": {
"type": "git",
+3 -12
View File
@@ -14,7 +14,6 @@ import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstab
import { AuthError, ServerAuth } from "./Services/ServerAuth.ts";
import { SessionCredentialService } from "./Services/SessionCredentialService.ts";
import { deriveAuthClientMetadata } from "./utils.ts";
import { browserApiCorsHeaders } from "../httpCors.ts";
export const respondToAuthError = (error: AuthError) =>
Effect.gen(function* () {
@@ -28,7 +27,7 @@ export const respondToAuthError = (error: AuthError) =>
{
error: error.message,
},
{ status: error.status ?? 500, headers: browserApiCorsHeaders },
{ status: error.status ?? 500 },
);
});
@@ -39,10 +38,7 @@ export const authSessionRouteLayer = HttpRouter.add(
const request = yield* HttpServerRequest.HttpServerRequest;
const serverAuth = yield* ServerAuth;
const session = yield* serverAuth.getSessionState(request);
return HttpServerResponse.jsonUnsafe(session, {
status: 200,
headers: browserApiCorsHeaders,
});
return HttpServerResponse.jsonUnsafe(session, { status: 200 });
}),
);
@@ -85,10 +81,7 @@ export const authBootstrapRouteLayer = HttpRouter.add(
deriveAuthClientMetadata({ request }),
);
return yield* HttpServerResponse.jsonUnsafe(result.response, {
status: 200,
headers: browserApiCorsHeaders,
}).pipe(
return yield* HttpServerResponse.jsonUnsafe(result.response, { status: 200 }).pipe(
HttpServerResponse.setCookie(sessions.cookieName, result.sessionToken, {
expires: DateTime.toDate(result.response.expiresAt),
httpOnly: true,
@@ -121,7 +114,6 @@ export const authBearerBootstrapRouteLayer = HttpRouter.add(
);
return HttpServerResponse.jsonUnsafe(result satisfies AuthBearerBootstrapResult, {
status: 200,
headers: browserApiCorsHeaders,
});
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
);
@@ -136,7 +128,6 @@ export const authWebSocketTokenRouteLayer = HttpRouter.add(
const result = yield* serverAuth.issueWebSocketToken(session);
return HttpServerResponse.jsonUnsafe(result satisfies AuthWebSocketTokenResult, {
status: 200,
headers: browserApiCorsHeaders,
});
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
);
@@ -41,110 +41,11 @@ function makeThreadCheckpointContext(input: {
}
describe("CheckpointDiffQueryLive", () => {
it("uses the narrow full-thread context lookup for all-turns diffs", async () => {
const projectId = ProjectId.make("project-full-thread");
const threadId = ThreadId.make("thread-full-thread");
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 4);
let getThreadCheckpointContextCalls = 0;
let getFullThreadDiffContextCalls = 0;
const diffCheckpointsCalls: Array<{
readonly fromCheckpointRef: CheckpointRef;
readonly toCheckpointRef: CheckpointRef;
readonly cwd: string;
readonly ignoreWhitespace: boolean;
}> = [];
const checkpointStore: CheckpointStoreShape = {
isGitRepository: () => Effect.succeed(true),
captureCheckpoint: () => Effect.void,
hasCheckpointRef: () => Effect.succeed(true),
restoreCheckpoint: () => Effect.succeed(true),
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd, ignoreWhitespace }) =>
Effect.sync(() => {
diffCheckpointsCalls.push({
fromCheckpointRef,
toCheckpointRef,
cwd,
ignoreWhitespace,
});
return "full thread diff patch";
}),
deleteCheckpointRefs: () => Effect.void,
};
const layer = CheckpointDiffQueryLive.pipe(
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery, {
getCommandReadModel: () =>
Effect.die("CheckpointDiffQuery should not request the command read model"),
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getProjectShellById: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () =>
Effect.sync(() => {
getThreadCheckpointContextCalls += 1;
return Option.none();
}),
getFullThreadDiffContext: () =>
Effect.sync(() => {
getFullThreadDiffContextCalls += 1;
return Option.some({
threadId,
projectId,
workspaceRoot: "/tmp/workspace",
worktreePath: "/tmp/worktree",
latestCheckpointTurnCount: 4,
toCheckpointRef,
});
}),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
}),
),
);
const result = await Effect.runPromise(
Effect.gen(function* () {
const query = yield* CheckpointDiffQuery;
return yield* query.getFullThreadDiff({
threadId,
toTurnCount: 4,
ignoreWhitespace: true,
});
}).pipe(Effect.provide(layer)),
);
expect(getThreadCheckpointContextCalls).toBe(0);
expect(getFullThreadDiffContextCalls).toBe(1);
expect(diffCheckpointsCalls).toEqual([
{
cwd: "/tmp/worktree",
fromCheckpointRef: checkpointRefForThreadTurn(threadId, 0),
toCheckpointRef,
ignoreWhitespace: true,
},
]);
expect(result).toEqual({
threadId,
fromTurnCount: 0,
toTurnCount: 4,
diff: "full thread diff patch",
});
});
it("computes diffs using canonical turn-0 checkpoint refs", async () => {
const projectId = ProjectId.make("project-1");
const threadId = ThreadId.make("thread-1");
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
const hasCheckpointRefCalls: Array<CheckpointRef> = [];
const diffCheckpointsCalls: Array<{
readonly fromCheckpointRef: CheckpointRef;
readonly toCheckpointRef: CheckpointRef;
@@ -164,7 +65,11 @@ describe("CheckpointDiffQueryLive", () => {
const checkpointStore: CheckpointStoreShape = {
isGitRepository: () => Effect.succeed(true),
captureCheckpoint: () => Effect.void,
hasCheckpointRef: () => Effect.succeed(true),
hasCheckpointRef: ({ checkpointRef }) =>
Effect.sync(() => {
hasCheckpointRefCalls.push(checkpointRef);
return true;
}),
restoreCheckpoint: () => Effect.succeed(true),
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd, ignoreWhitespace }) =>
Effect.sync(() => {
@@ -189,15 +94,12 @@ describe("CheckpointDiffQueryLive", () => {
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getProjectShellById: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
}),
@@ -217,6 +119,7 @@ describe("CheckpointDiffQueryLive", () => {
);
const expectedFromRef = checkpointRefForThreadTurn(threadId, 0);
expect(hasCheckpointRefCalls).toEqual([expectedFromRef, toCheckpointRef]);
expect(diffCheckpointsCalls).toEqual([
{
cwd: "/tmp/workspace",
@@ -271,15 +174,12 @@ describe("CheckpointDiffQueryLive", () => {
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getProjectShellById: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
}),
@@ -300,74 +200,6 @@ describe("CheckpointDiffQueryLive", () => {
expect(diffCheckpointsCalls).toEqual([{ ignoreWhitespace: true }]);
});
it("does not preflight checkpoint refs before diffing", async () => {
const projectId = ProjectId.make("project-no-preflight");
const threadId = ThreadId.make("thread-no-preflight");
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
let hasCheckpointRefCallCount = 0;
const threadCheckpointContext = makeThreadCheckpointContext({
projectId,
threadId,
workspaceRoot: "/tmp/workspace",
worktreePath: null,
checkpointTurnCount: 1,
checkpointRef: toCheckpointRef,
});
const checkpointStore: CheckpointStoreShape = {
isGitRepository: () => Effect.succeed(true),
captureCheckpoint: () => Effect.void,
hasCheckpointRef: () =>
Effect.sync(() => {
hasCheckpointRefCallCount += 1;
return true;
}),
restoreCheckpoint: () => Effect.succeed(true),
diffCheckpoints: () => Effect.succeed("diff patch"),
deleteCheckpointRefs: () => Effect.void,
};
const layer = CheckpointDiffQueryLive.pipe(
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery, {
getCommandReadModel: () =>
Effect.die("CheckpointDiffQuery should not request the command read model"),
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getProjectShellById: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
}),
),
);
await Effect.runPromise(
Effect.gen(function* () {
const query = yield* CheckpointDiffQuery;
return yield* query.getTurnDiff({
threadId,
fromTurnCount: 0,
toTurnCount: 1,
ignoreWhitespace: true,
});
}).pipe(Effect.provide(layer)),
);
expect(hasCheckpointRefCallCount).toBe(0);
});
it("fails when the thread is missing from the snapshot", async () => {
const threadId = ThreadId.make("thread-missing");
@@ -390,15 +222,12 @@ describe("CheckpointDiffQueryLive", () => {
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getProjectShellById: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
}),
@@ -1,7 +1,6 @@
import {
type CheckpointRef,
OrchestrationGetTurnDiffResult,
type ThreadId,
type OrchestrationGetFullThreadDiffInput,
type OrchestrationGetFullThreadDiffResult,
type OrchestrationGetTurnDiffResult as OrchestrationGetTurnDiffResultType,
} from "@t3tools/contracts";
@@ -21,22 +20,6 @@ import {
const isTurnDiffResult = Schema.is(OrchestrationGetTurnDiffResult);
function buildTurnDiffResult(
input: {
readonly threadId: ThreadId;
readonly fromTurnCount: number;
readonly toTurnCount: number;
},
diff: string,
): OrchestrationGetTurnDiffResultType {
return {
threadId: input.threadId,
fromTurnCount: input.fromTurnCount,
toTurnCount: input.toTurnCount,
diff,
};
}
const make = Effect.gen(function* () {
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const checkpointStore = yield* CheckpointStore;
@@ -45,12 +28,6 @@ const make = Effect.gen(function* () {
function* (input) {
const operation = "CheckpointDiffQuery.getTurnDiff";
const ignoreWhitespace = input.ignoreWhitespace ?? true;
yield* Effect.annotateCurrentSpan({
"checkpoint.thread_id": input.threadId,
"checkpoint.from_turn_count": input.fromTurnCount,
"checkpoint.to_turn_count": input.toTurnCount,
"checkpoint.ignore_whitespace": ignoreWhitespace,
});
if (input.fromTurnCount === input.toTurnCount) {
const emptyDiff: OrchestrationGetTurnDiffResultType = {
@@ -68,9 +45,9 @@ const make = Effect.gen(function* () {
return emptyDiff;
}
const threadContext = yield* projectionSnapshotQuery
.getThreadCheckpointContext(input.threadId)
.pipe(Effect.withSpan("checkpoint.turnDiff.lookupContext"));
const threadContext = yield* projectionSnapshotQuery.getThreadCheckpointContext(
input.threadId,
);
if (Option.isNone(threadContext)) {
return yield* new CheckpointInvariantError({
operation,
@@ -123,17 +100,50 @@ const make = Effect.gen(function* () {
});
}
const diff = yield* checkpointStore
.diffCheckpoints({
cwd: workspaceCwd,
fromCheckpointRef,
toCheckpointRef,
fallbackFromToHead: false,
ignoreWhitespace,
})
.pipe(Effect.withSpan("checkpoint.turnDiff.diffCheckpoints"));
const [fromExists, toExists] = yield* Effect.all(
[
checkpointStore.hasCheckpointRef({
cwd: workspaceCwd,
checkpointRef: fromCheckpointRef,
}),
checkpointStore.hasCheckpointRef({
cwd: workspaceCwd,
checkpointRef: toCheckpointRef,
}),
],
{ concurrency: "unbounded" },
);
const turnDiff = buildTurnDiffResult(input, diff);
if (!fromExists) {
return yield* new CheckpointUnavailableError({
threadId: input.threadId,
turnCount: input.fromTurnCount,
detail: `Filesystem checkpoint is unavailable for turn ${input.fromTurnCount}.`,
});
}
if (!toExists) {
return yield* new CheckpointUnavailableError({
threadId: input.threadId,
turnCount: input.toTurnCount,
detail: `Filesystem checkpoint is unavailable for turn ${input.toTurnCount}.`,
});
}
const diff = yield* checkpointStore.diffCheckpoints({
cwd: workspaceCwd,
fromCheckpointRef,
toCheckpointRef,
fallbackFromToHead: false,
ignoreWhitespace,
});
const turnDiff: OrchestrationGetTurnDiffResultType = {
threadId: input.threadId,
fromTurnCount: input.fromTurnCount,
toTurnCount: input.toTurnCount,
diff,
};
if (!isTurnDiffResult(turnDiff)) {
return yield* new CheckpointInvariantError({
operation,
@@ -145,99 +155,15 @@ const make = Effect.gen(function* () {
},
);
const getFullThreadDiff: CheckpointDiffQueryShape["getFullThreadDiff"] = Effect.fn(
"CheckpointDiffQuery.getFullThreadDiff",
)(function* (input) {
const operation = "CheckpointDiffQuery.getFullThreadDiff";
const ignoreWhitespace = input.ignoreWhitespace ?? true;
yield* Effect.annotateCurrentSpan({
"checkpoint.thread_id": input.threadId,
"checkpoint.from_turn_count": 0,
"checkpoint.to_turn_count": input.toTurnCount,
"checkpoint.ignore_whitespace": ignoreWhitespace,
"checkpoint.diff_kind": "full-thread",
});
if (input.toTurnCount === 0) {
const emptyDiff = buildTurnDiffResult(
{
threadId: input.threadId,
fromTurnCount: 0,
toTurnCount: 0,
},
"",
);
if (!isTurnDiffResult(emptyDiff)) {
return yield* new CheckpointInvariantError({
operation,
detail: "Computed full thread diff result does not satisfy contract schema.",
});
}
return emptyDiff satisfies OrchestrationGetFullThreadDiffResult;
}
const threadContext = yield* projectionSnapshotQuery
.getFullThreadDiffContext(input.threadId, input.toTurnCount)
.pipe(Effect.withSpan("checkpoint.fullThread.lookupContext"));
if (Option.isNone(threadContext)) {
return yield* new CheckpointInvariantError({
operation,
detail: `Thread '${input.threadId}' not found.`,
});
}
if (input.toTurnCount > threadContext.value.latestCheckpointTurnCount) {
return yield* new CheckpointUnavailableError({
threadId: input.threadId,
turnCount: input.toTurnCount,
detail: `Turn diff range exceeds current turn count: requested ${input.toTurnCount}, current ${threadContext.value.latestCheckpointTurnCount}.`,
});
}
const workspaceCwd = threadContext.value.worktreePath ?? threadContext.value.workspaceRoot;
if (!workspaceCwd) {
return yield* new CheckpointInvariantError({
operation,
detail: `Workspace path missing for thread '${input.threadId}' when computing full thread diff.`,
});
}
if (!threadContext.value.toCheckpointRef) {
return yield* new CheckpointUnavailableError({
threadId: input.threadId,
turnCount: input.toTurnCount,
detail: `Checkpoint ref is unavailable for turn ${input.toTurnCount}.`,
});
}
const diff = yield* checkpointStore
.diffCheckpoints({
cwd: workspaceCwd,
fromCheckpointRef: checkpointRefForThreadTurn(input.threadId, 0),
toCheckpointRef: threadContext.value.toCheckpointRef as CheckpointRef,
fallbackFromToHead: false,
ignoreWhitespace,
})
.pipe(Effect.withSpan("checkpoint.fullThread.diffCheckpoints"));
const turnDiff = buildTurnDiffResult(
{
threadId: input.threadId,
fromTurnCount: 0,
toTurnCount: input.toTurnCount,
},
diff,
);
if (!isTurnDiffResult(turnDiff)) {
return yield* new CheckpointInvariantError({
operation,
detail: "Computed full thread diff result does not satisfy contract schema.",
});
}
return turnDiff satisfies OrchestrationGetFullThreadDiffResult;
});
const getFullThreadDiff: CheckpointDiffQueryShape["getFullThreadDiff"] = (
input: OrchestrationGetFullThreadDiffInput,
) =>
getTurnDiff({
threadId: input.threadId,
fromTurnCount: 0,
toTurnCount: input.toTurnCount,
ignoreWhitespace: input.ignoreWhitespace ?? true,
}).pipe(Effect.map((result): OrchestrationGetFullThreadDiffResult => result));
return {
getTurnDiff,
@@ -1,79 +1,304 @@
/**
* CheckpointStoreLive - Filesystem checkpoint store adapter layer.
*
* Resolves the active VCS driver once per checkpoint operation and delegates
* checkpoint-specific behavior to the driver's optional checkpoint capability.
* Implements hidden Git-ref checkpoint capture/restore directly with
* Effect-native child process execution (`effect/unstable/process`).
*
* This layer owns filesystem/Git interactions only; it does not persist
* checkpoint metadata and does not coordinate provider rollback semantics.
*
* @module CheckpointStoreLive
*/
import { randomUUID } from "node:crypto";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
import { VcsUnsupportedOperationError } from "@t3tools/contracts";
import { CheckpointInvariantError } from "../Errors.ts";
import { VcsProcessExitError } from "@t3tools/contracts";
import { VcsDriverRegistry } from "../../vcs/VcsDriverRegistry.ts";
import type { VcsCheckpointOps } from "../../vcs/VcsDriver.ts";
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
import { CheckpointRef } from "@t3tools/contracts";
const CHECKPOINT_DIFF_MAX_OUTPUT_BYTES = 10_000_000;
const makeCheckpointStore = Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const vcsRegistry = yield* VcsDriverRegistry;
const vcs = {
execute: (input: {
readonly operation: string;
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly stdin?: string;
readonly env?: NodeJS.ProcessEnv;
readonly allowNonZeroExit?: boolean;
readonly timeoutMs?: number;
readonly maxOutputBytes?: number;
readonly truncateOutputAtMaxBytes?: boolean;
}) =>
vcsRegistry
.resolve({ cwd: input.cwd, requestedKind: "git" })
.pipe(Effect.flatMap((handle) => handle.driver.execute(input))),
};
const resolveCheckpoints = Effect.fn("CheckpointStore.resolveCheckpoints")(function* (
operation: string,
cwd: string,
) {
const handle = yield* vcsRegistry.resolve({ cwd });
if (!handle.driver.checkpoints) {
return yield* new VcsUnsupportedOperationError({
operation,
kind: handle.kind,
detail: `${handle.kind} driver does not implement checkpoint operations.`,
});
}
return handle.driver.checkpoints satisfies VcsCheckpointOps;
});
const resolveHeadCommit = (cwd: string) =>
vcs
.execute({
operation: "CheckpointStore.resolveHeadCommit",
cwd,
args: ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"],
allowNonZeroExit: true,
})
.pipe(
Effect.map((result) => {
if (result.exitCode !== 0) {
return null;
}
const commit = result.stdout.trim();
return commit.length > 0 ? commit : null;
}),
);
const hasHeadCommit = (cwd: string) =>
vcs
.execute({
operation: "CheckpointStore.hasHeadCommit",
cwd,
args: ["rev-parse", "--verify", "HEAD"],
allowNonZeroExit: true,
})
.pipe(Effect.map((result) => result.exitCode === 0));
const resolveCheckpointCommit = (cwd: string, checkpointRef: CheckpointRef) =>
vcs
.execute({
operation: "CheckpointStore.resolveCheckpointCommit",
cwd,
args: ["rev-parse", "--verify", "--quiet", `${checkpointRef}^{commit}`],
allowNonZeroExit: true,
})
.pipe(
Effect.map((result) => {
if (result.exitCode !== 0) {
return null;
}
const commit = result.stdout.trim();
return commit.length > 0 ? commit : null;
}),
);
const isGitRepository: CheckpointStoreShape["isGitRepository"] = (cwd) =>
vcsRegistry.resolve({ cwd, requestedKind: "git" }).pipe(
Effect.map(() => true),
Effect.catch(() => Effect.succeed(false)),
);
vcs
.execute({
operation: "CheckpointStore.isGitRepository",
cwd,
args: ["rev-parse", "--is-inside-work-tree"],
allowNonZeroExit: true,
})
.pipe(
Effect.map((result) => result.exitCode === 0 && result.stdout.trim() === "true"),
Effect.catch(() => Effect.succeed(false)),
);
const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = Effect.fn(
"captureCheckpoint",
)(function* (input) {
const checkpoints = yield* resolveCheckpoints("CheckpointStore.captureCheckpoint", input.cwd);
return yield* checkpoints.captureCheckpoint(input);
const operation = "CheckpointStore.captureCheckpoint";
yield* Effect.acquireUseRelease(
fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }),
Effect.fn("captureCheckpoint.withTempDirectory")(function* (tempDir) {
const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
const commitEnv: NodeJS.ProcessEnv = {
...process.env,
GIT_INDEX_FILE: tempIndexPath,
GIT_AUTHOR_NAME: "T3 Code",
GIT_AUTHOR_EMAIL: "[email protected]",
GIT_COMMITTER_NAME: "T3 Code",
GIT_COMMITTER_EMAIL: "[email protected]",
};
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["read-tree", "HEAD"],
env: commitEnv,
});
}
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["add", "-A", "--", "."],
env: commitEnv,
});
const writeTreeResult = yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["write-tree"],
env: commitEnv,
});
const treeOid = writeTreeResult.stdout.trim();
if (treeOid.length === 0) {
return yield* new VcsProcessExitError({
operation,
command: "git write-tree",
cwd: input.cwd,
exitCode: 0,
detail: "git write-tree returned an empty tree oid.",
});
}
const message = `t3 checkpoint ref=${input.checkpointRef}`;
const commitTreeResult = yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["commit-tree", treeOid, "-m", message],
env: commitEnv,
});
const commitOid = commitTreeResult.stdout.trim();
if (commitOid.length === 0) {
return yield* new VcsProcessExitError({
operation,
command: "git commit-tree",
cwd: input.cwd,
exitCode: 0,
detail: "git commit-tree returned an empty commit oid.",
});
}
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["update-ref", input.checkpointRef, commitOid],
});
}),
(tempDir) => fs.remove(tempDir, { recursive: true }),
).pipe(
Effect.catchTags({
PlatformError: (error) =>
Effect.fail(
new CheckpointInvariantError({
operation: "CheckpointStore.captureCheckpoint",
detail: "Failed to capture checkpoint.",
cause: error,
}),
),
}),
);
});
const hasCheckpointRef: CheckpointStoreShape["hasCheckpointRef"] = Effect.fn("hasCheckpointRef")(
function* (input) {
const checkpoints = yield* resolveCheckpoints("CheckpointStore.hasCheckpointRef", input.cwd);
return yield* checkpoints.hasCheckpointRef(input);
},
);
const hasCheckpointRef: CheckpointStoreShape["hasCheckpointRef"] = (input) =>
resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
Effect.map((commit) => commit !== null),
);
const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = Effect.fn(
"restoreCheckpoint",
)(function* (input) {
const checkpoints = yield* resolveCheckpoints("CheckpointStore.restoreCheckpoint", input.cwd);
return yield* checkpoints.restoreCheckpoint(input);
const operation = "CheckpointStore.restoreCheckpoint";
let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
if (!commitOid && input.fallbackToHead === true) {
commitOid = yield* resolveHeadCommit(input.cwd);
}
if (!commitOid) {
return false;
}
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
});
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["clean", "-fd", "--", "."],
});
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["reset", "--quiet", "--", "."],
});
}
return true;
});
const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = Effect.fn("diffCheckpoints")(
function* (input) {
const checkpoints = yield* resolveCheckpoints("CheckpointStore.diffCheckpoints", input.cwd);
return yield* checkpoints.diffCheckpoints(input);
const operation = "CheckpointStore.diffCheckpoints";
let fromCommitOid = yield* resolveCheckpointCommit(input.cwd, input.fromCheckpointRef);
const toCommitOid = yield* resolveCheckpointCommit(input.cwd, input.toCheckpointRef);
if (!fromCommitOid && input.fallbackFromToHead === true) {
const headCommit = yield* resolveHeadCommit(input.cwd);
if (headCommit) {
fromCommitOid = headCommit;
}
}
if (!fromCommitOid || !toCommitOid) {
return yield* new VcsProcessExitError({
operation,
command: "git diff",
cwd: input.cwd,
exitCode: 1,
detail: "Checkpoint ref is unavailable for diff operation.",
});
}
const diffArgs = [
"diff",
"--patch",
"--minimal",
"--no-color",
...(input.ignoreWhitespace ? ["--ignore-all-space"] : []),
fromCommitOid,
toCommitOid,
];
const result = yield* vcs.execute({
operation,
cwd: input.cwd,
args: diffArgs,
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
});
return result.stdout;
},
);
const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = Effect.fn(
"deleteCheckpointRefs",
)(function* (input) {
const checkpoints = yield* resolveCheckpoints(
"CheckpointStore.deleteCheckpointRefs",
input.cwd,
const operation = "CheckpointStore.deleteCheckpointRefs";
yield* Effect.forEach(
input.checkpointRefs,
(checkpointRef) =>
vcs.execute({
operation,
cwd: input.cwd,
args: ["update-ref", "-d", checkpointRef],
allowNonZeroExit: true,
}),
{ discard: true },
);
return yield* checkpoints.deleteCheckpointRefs(input);
});
return {
@@ -6,7 +6,6 @@ import * as Path from "effect/Path";
import * as Random from "effect/Random";
import { ServerConfig } from "../../config.ts";
import { layer as ProcessRunnerLive } from "../../processRunner.ts";
import { ServerEnvironment, type ServerEnvironmentShape } from "../Services/ServerEnvironment.ts";
import packageJson from "../../../package.json" with { type: "json" };
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
@@ -94,6 +93,4 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function
} satisfies ServerEnvironmentShape;
});
export const ServerEnvironmentLive = Layer.effect(ServerEnvironment, makeServerEnvironment()).pipe(
Layer.provide(ProcessRunnerLive),
);
export const ServerEnvironmentLive = Layer.effect(ServerEnvironment, makeServerEnvironment());
@@ -1,36 +1,20 @@
import { afterEach, describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import { vi } from "vitest";
import { ProcessRunner, ProcessSpawnError, type ProcessRunnerShape } from "../../processRunner.ts";
vi.mock("../../processRunner.ts", () => ({
runProcess: vi.fn(),
}));
import { runProcess } from "../../processRunner.ts";
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
import { ChildProcessSpawner } from "effect/unstable/process";
const runMock = vi.fn<ProcessRunnerShape["run"]>();
const ProcessRunnerTest = Layer.succeed(
ProcessRunner,
ProcessRunner.of({
run: (input) => runMock(input),
}),
);
const mockedRunProcess = vi.mocked(runProcess);
const NoopFileSystemLayer = FileSystem.layerNoop({});
const TestLayer = Layer.merge(NoopFileSystemLayer, ProcessRunnerTest);
const LinuxMachineInfoLayer = Layer.merge(
ProcessRunnerTest,
FileSystem.layerNoop({
exists: (path) => Effect.succeed(path === "/etc/machine-info"),
readFileString: (path) =>
path === "/etc/machine-info"
? Effect.succeed('PRETTY_HOSTNAME="Build Agent 01"\nICON_NAME="computer-vm"\n')
: Effect.succeed(""),
}),
);
afterEach(() => {
runMock.mockReset();
mockedRunProcess.mockReset();
});
describe("resolveServerEnvironmentLabel", () => {
@@ -40,7 +24,7 @@ describe("resolveServerEnvironmentLabel", () => {
cwdBaseName: "t3code",
platform: "win32",
hostname: "macbook-pro",
}).pipe(Effect.provide(TestLayer));
}).pipe(Effect.provide(NoopFileSystemLayer));
expect(result).toBe("macbook-pro");
}),
@@ -48,30 +32,25 @@ describe("resolveServerEnvironmentLabel", () => {
it.effect("prefers the macOS ComputerName", () =>
Effect.gen(function* () {
runMock.mockReturnValueOnce(
Effect.succeed({
stdout: " Julius's MacBook Pro \n",
stderr: "",
code: ChildProcessSpawner.ExitCode(0),
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
}),
);
mockedRunProcess.mockResolvedValueOnce({
stdout: " Julius's MacBook Pro \n",
stderr: "",
code: 0,
signal: null,
timedOut: false,
});
const result = yield* resolveServerEnvironmentLabel({
cwdBaseName: "t3code",
platform: "darwin",
hostname: "macbook-pro",
}).pipe(Effect.provide(TestLayer));
}).pipe(Effect.provide(NoopFileSystemLayer));
expect(result).toBe("Julius's MacBook Pro");
expect(runMock).toHaveBeenCalledWith(
expect.objectContaining({
command: "scutil",
args: ["--get", "ComputerName"],
timeoutBehavior: "timedOutResult",
}),
expect(mockedRunProcess).toHaveBeenCalledWith(
"scutil",
["--get", "ComputerName"],
expect.objectContaining({ allowNonZeroExit: true }),
);
}),
);
@@ -82,39 +61,44 @@ describe("resolveServerEnvironmentLabel", () => {
cwdBaseName: "t3code",
platform: "linux",
hostname: "buildbox",
}).pipe(Effect.provide(LinuxMachineInfoLayer));
}).pipe(
Effect.provide(
FileSystem.layerNoop({
exists: (path) => Effect.succeed(path === "/etc/machine-info"),
readFileString: (path) =>
path === "/etc/machine-info"
? Effect.succeed('PRETTY_HOSTNAME="Build Agent 01"\nICON_NAME="computer-vm"\n')
: Effect.succeed(""),
}),
),
);
expect(result).toBe("Build Agent 01");
expect(runMock).not.toHaveBeenCalled();
expect(mockedRunProcess).not.toHaveBeenCalled();
}),
);
it.effect("falls back to hostnamectl pretty hostname on Linux", () =>
Effect.gen(function* () {
runMock.mockReturnValueOnce(
Effect.succeed({
stdout: "CI Runner\n",
stderr: "",
code: ChildProcessSpawner.ExitCode(0),
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
}),
);
mockedRunProcess.mockResolvedValueOnce({
stdout: "CI Runner\n",
stderr: "",
code: 0,
signal: null,
timedOut: false,
});
const result = yield* resolveServerEnvironmentLabel({
cwdBaseName: "t3code",
platform: "linux",
hostname: "runner-01",
}).pipe(Effect.provide(TestLayer));
}).pipe(Effect.provide(NoopFileSystemLayer));
expect(result).toBe("CI Runner");
expect(runMock).toHaveBeenCalledWith(
expect.objectContaining({
command: "hostnamectl",
args: ["--pretty"],
timeoutBehavior: "timedOutResult",
}),
expect(mockedRunProcess).toHaveBeenCalledWith(
"hostnamectl",
["--pretty"],
expect.objectContaining({ allowNonZeroExit: true }),
);
}),
);
@@ -125,7 +109,7 @@ describe("resolveServerEnvironmentLabel", () => {
cwdBaseName: "t3code",
platform: "win32",
hostname: "JULIUS-LAPTOP",
}).pipe(Effect.provide(TestLayer));
}).pipe(Effect.provide(NoopFileSystemLayer));
expect(result).toBe("JULIUS-LAPTOP");
}),
@@ -133,21 +117,13 @@ describe("resolveServerEnvironmentLabel", () => {
it.effect("falls back to the hostname when the friendly-label command is missing", () =>
Effect.gen(function* () {
runMock.mockReturnValueOnce(
Effect.fail(
new ProcessSpawnError({
command: "scutil",
args: ["--get", "ComputerName"],
cause: new Error("spawn scutil ENOENT"),
}),
),
);
mockedRunProcess.mockRejectedValueOnce(new Error("spawn scutil ENOENT"));
const result = yield* resolveServerEnvironmentLabel({
cwdBaseName: "t3code",
platform: "darwin",
hostname: "macbook-pro",
}).pipe(Effect.provide(TestLayer));
}).pipe(Effect.provide(NoopFileSystemLayer));
expect(result).toBe("macbook-pro");
}),
@@ -155,22 +131,19 @@ describe("resolveServerEnvironmentLabel", () => {
it.effect("falls back to the cwd basename when the hostname is blank", () =>
Effect.gen(function* () {
runMock.mockReturnValueOnce(
Effect.succeed({
stdout: " ",
stderr: "",
code: ChildProcessSpawner.ExitCode(0),
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
}),
);
mockedRunProcess.mockResolvedValueOnce({
stdout: " ",
stderr: "",
code: 0,
signal: null,
timedOut: false,
});
const result = yield* resolveServerEnvironmentLabel({
cwdBaseName: "t3code",
platform: "linux",
hostname: " ",
}).pipe(Effect.provide(TestLayer));
}).pipe(Effect.provide(NoopFileSystemLayer));
expect(result).toBe("t3code");
}),
@@ -2,9 +2,8 @@ import * as OS from "node:os";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import { ProcessRunner } from "../../processRunner.ts";
import { runProcess } from "../../processRunner.ts";
interface ResolveServerEnvironmentLabelInput {
readonly cwdBaseName: string;
@@ -53,21 +52,19 @@ const runFriendlyLabelCommand = Effect.fn("runFriendlyLabelCommand")(function* (
command: string,
args: readonly string[],
) {
const processRunner = yield* ProcessRunner;
const result = yield* processRunner
.run({
command,
args,
timeoutBehavior: "timedOutResult",
shell: process.platform === "win32",
})
.pipe(Effect.option);
const result = yield* Effect.tryPromise({
try: () =>
runProcess(command, args, {
allowNonZeroExit: true,
}),
catch: () => null,
}).pipe(Effect.orElseSucceed(() => null));
if (Option.isNone(result) || result.value.code !== 0) {
if (!result || result.code !== 0) {
return null;
}
return normalizeLabel(result.value.stdout);
return normalizeLabel(result.stdout);
});
const resolveFriendlyHostLabel = Effect.fn("resolveFriendlyHostLabel")(function* (
+3 -11
View File
@@ -28,11 +28,6 @@ import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolve
import { ServerAuth } from "./auth/Services/ServerAuth.ts";
import { respondToAuthError } from "./auth/http.ts";
import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";
import {
browserApiCorsAllowedHeaders,
browserApiCorsAllowedMethods,
browserApiCorsHeaders,
} from "./httpCors.ts";
const PROJECT_FAVICON_CACHE_CONTROL = "public, max-age=3600";
const FALLBACK_PROJECT_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;
@@ -40,8 +35,8 @@ const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
export const browserApiCorsLayer = HttpRouter.cors({
allowedMethods: [...browserApiCorsAllowedMethods],
allowedHeaders: [...browserApiCorsAllowedHeaders],
allowedMethods: ["GET", "POST", "OPTIONS"],
allowedHeaders: ["authorization", "b3", "traceparent", "content-type"],
maxAge: 600,
});
@@ -74,10 +69,7 @@ export const serverEnvironmentRouteLayer = HttpRouter.add(
const descriptor = yield* Effect.service(ServerEnvironment).pipe(
Effect.flatMap((serverEnvironment) => serverEnvironment.getDescriptor),
);
return HttpServerResponse.jsonUnsafe(descriptor, {
status: 200,
headers: browserApiCorsHeaders,
});
return HttpServerResponse.jsonUnsafe(descriptor, { status: 200 });
}),
);
-13
View File
@@ -1,13 +0,0 @@
export const browserApiCorsAllowedMethods = ["GET", "POST", "OPTIONS"] as const;
export const browserApiCorsAllowedHeaders = [
"authorization",
"b3",
"traceparent",
"content-type",
] as const;
export const browserApiCorsHeaders = {
"access-control-allow-origin": "*",
"access-control-allow-methods": browserApiCorsAllowedMethods.join(", "),
"access-control-allow-headers": browserApiCorsAllowedHeaders.join(", "),
} as const;
@@ -9,7 +9,6 @@ import {
type OrchestrationEvent,
ProviderInstanceId,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as ManagedRuntime from "effect/ManagedRuntime";
@@ -38,6 +37,7 @@ import {
} from "../Services/ProjectionPipeline.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import { ServerConfig } from "../../config.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
const asMessageId = (value: string): MessageId => MessageId.make(value);
@@ -183,13 +183,6 @@ describe("OrchestrationEngine", () => {
threads: [],
updatedAt: projectionSnapshot.updatedAt,
}),
getArchivedShellSnapshot: () =>
Effect.succeed({
snapshotSequence: projectionSnapshot.snapshotSequence,
projects: [],
threads: [],
updatedAt: projectionSnapshot.updatedAt,
}),
getSnapshotSequence: () =>
Effect.succeed({ snapshotSequence: projectionSnapshot.snapshotSequence }),
getCounts: () => Effect.succeed({ projectCount: 1, threadCount: 1 }),
@@ -197,7 +190,6 @@ describe("OrchestrationEngine", () => {
getProjectShellById: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
}),
@@ -786,7 +778,6 @@ describe("OrchestrationEngine", () => {
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
Layer.provide(RepositoryIdentityResolverLive),
Layer.provide(SqlitePersistenceMemory),
Layer.provide(NodeServices.layer),
),
);
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
@@ -929,7 +920,6 @@ describe("OrchestrationEngine", () => {
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
Layer.provide(RepositoryIdentityResolverLive),
Layer.provide(SqlitePersistenceMemory),
Layer.provide(NodeServices.layer),
),
);
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
@@ -8,7 +8,6 @@ import {
ProviderInstanceId,
} from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as SqlClient from "effect/unstable/sql/SqlClient";
@@ -30,7 +29,6 @@ const projectionSnapshotLayer = it.layer(
OrchestrationProjectionSnapshotQueryLive.pipe(
Layer.provideMerge(RepositoryIdentityResolverLive),
Layer.provideMerge(SqlitePersistenceMemory),
Layer.provideMerge(NodeServices.layer),
),
);
@@ -443,126 +441,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
}),
);
it.effect("keeps archived threads out of the main shell snapshot", () =>
Effect.gen(function* () {
const snapshotQuery = yield* ProjectionSnapshotQuery;
const sql = yield* SqlClient.SqlClient;
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_threads`;
yield* sql`DELETE FROM projection_state`;
yield* sql`
INSERT INTO projection_projects (
project_id,
title,
workspace_root,
default_model_selection_json,
scripts_json,
created_at,
updated_at,
deleted_at
)
VALUES (
'project-archive-test',
'Archive Test',
'/tmp/archive-test',
'{"provider":"codex","model":"gpt-5-codex"}',
'[]',
'2026-04-06T00:00:00.000Z',
'2026-04-06T00:00:01.000Z',
NULL
)
`;
yield* sql`
INSERT INTO projection_threads (
thread_id,
project_id,
title,
model_selection_json,
runtime_mode,
interaction_mode,
branch,
worktree_path,
latest_turn_id,
latest_user_message_at,
pending_approval_count,
pending_user_input_count,
has_actionable_proposed_plan,
created_at,
updated_at,
archived_at,
deleted_at
)
VALUES
(
'thread-active',
'project-archive-test',
'Active Thread',
'{"provider":"codex","model":"gpt-5-codex"}',
'full-access',
'default',
NULL,
NULL,
NULL,
NULL,
0,
0,
0,
'2026-04-06T00:00:02.000Z',
'2026-04-06T00:00:03.000Z',
NULL,
NULL
),
(
'thread-archived',
'project-archive-test',
'Archived Thread',
'{"provider":"codex","model":"gpt-5-codex"}',
'full-access',
'default',
NULL,
NULL,
NULL,
NULL,
0,
0,
0,
'2026-04-06T00:00:04.000Z',
'2026-04-06T00:00:05.000Z',
'2026-04-06T00:00:06.000Z',
NULL
)
`;
yield* sql`
INSERT INTO projection_state (projector, last_applied_sequence, updated_at)
VALUES
(${ORCHESTRATION_PROJECTOR_NAMES.projects}, 4, '2026-04-06T00:00:07.000Z'),
(${ORCHESTRATION_PROJECTOR_NAMES.threads}, 4, '2026-04-06T00:00:07.000Z'),
(${ORCHESTRATION_PROJECTOR_NAMES.threadMessages}, 4, '2026-04-06T00:00:07.000Z'),
(${ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans}, 4, '2026-04-06T00:00:07.000Z'),
(${ORCHESTRATION_PROJECTOR_NAMES.threadActivities}, 4, '2026-04-06T00:00:07.000Z'),
(${ORCHESTRATION_PROJECTOR_NAMES.threadSessions}, 4, '2026-04-06T00:00:07.000Z'),
(${ORCHESTRATION_PROJECTOR_NAMES.checkpoints}, 4, '2026-04-06T00:00:07.000Z')
`;
const shellSnapshot = yield* snapshotQuery.getShellSnapshot();
assert.deepEqual(
shellSnapshot.threads.map((thread) => thread.id),
[ThreadId.make("thread-active")],
);
const archivedShellSnapshot = yield* snapshotQuery.getArchivedShellSnapshot();
assert.deepEqual(
archivedShellSnapshot.threads.map((thread) => thread.id),
[ThreadId.make("thread-archived")],
);
assert.equal(archivedShellSnapshot.threads[0]?.archivedAt, "2026-04-06T00:00:06.000Z");
}),
);
it.effect(
"reads targeted project, thread, and count queries without hydrating the full snapshot",
() =>
@@ -1,6 +1,5 @@
import {
ChatAttachment,
CheckpointRef,
IsoDateTime,
MessageId,
NonNegativeInt,
@@ -50,7 +49,6 @@ import { RepositoryIdentityResolver } from "../../project/Services/RepositoryIde
import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
import {
ProjectionSnapshotQuery,
type ProjectionFullThreadDiffContext,
type ProjectionSnapshotCounts,
type ProjectionThreadCheckpointContext,
type ProjectionSnapshotQueryShape,
@@ -124,18 +122,6 @@ const ProjectionThreadCheckpointContextThreadRowSchema = Schema.Struct({
workspaceRoot: Schema.String,
worktreePath: Schema.NullOr(Schema.String),
});
const FullThreadDiffContextLookupInput = Schema.Struct({
threadId: ThreadId,
checkpointTurnCount: NonNegativeInt,
});
const ProjectionFullThreadDiffContextRowSchema = Schema.Struct({
threadId: ThreadId,
projectId: ProjectId,
workspaceRoot: Schema.String,
worktreePath: Schema.NullOr(Schema.String),
latestCheckpointTurnCount: Schema.NullOr(NonNegativeInt),
toCheckpointRef: Schema.NullOr(CheckpointRef),
});
const REQUIRED_SNAPSHOT_PROJECTORS = [
ORCHESTRATION_PROJECTOR_NAMES.projects,
@@ -341,66 +327,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
const listActiveThreadRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionThreadDbRowSchema,
execute: () =>
sql`
SELECT
thread_id AS "threadId",
project_id AS "projectId",
title,
model_selection_json AS "modelSelection",
runtime_mode AS "runtimeMode",
interaction_mode AS "interactionMode",
branch,
worktree_path AS "worktreePath",
latest_turn_id AS "latestTurnId",
created_at AS "createdAt",
updated_at AS "updatedAt",
archived_at AS "archivedAt",
latest_user_message_at AS "latestUserMessageAt",
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
has_actionable_proposed_plan AS "hasActionableProposedPlan",
deleted_at AS "deletedAt"
FROM projection_threads
WHERE deleted_at IS NULL
AND archived_at IS NULL
ORDER BY project_id ASC, created_at ASC, thread_id ASC
`,
});
const listArchivedThreadRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionThreadDbRowSchema,
execute: () =>
sql`
SELECT
thread_id AS "threadId",
project_id AS "projectId",
title,
model_selection_json AS "modelSelection",
runtime_mode AS "runtimeMode",
interaction_mode AS "interactionMode",
branch,
worktree_path AS "worktreePath",
latest_turn_id AS "latestTurnId",
created_at AS "createdAt",
updated_at AS "updatedAt",
archived_at AS "archivedAt",
latest_user_message_at AS "latestUserMessageAt",
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
has_actionable_proposed_plan AS "hasActionableProposedPlan",
deleted_at AS "deletedAt"
FROM projection_threads
WHERE deleted_at IS NULL
AND archived_at IS NOT NULL
ORDER BY project_id ASC, archived_at DESC, thread_id DESC
`,
});
const listThreadMessageRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionThreadMessageDbRowSchema,
@@ -485,56 +411,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
const listActiveThreadSessionRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionThreadSessionDbRowSchema,
execute: () =>
sql`
SELECT
sessions.thread_id AS "threadId",
sessions.status,
sessions.provider_name AS "providerName",
sessions.provider_instance_id AS "providerInstanceId",
sessions.provider_session_id AS "providerSessionId",
sessions.provider_thread_id AS "providerThreadId",
sessions.runtime_mode AS "runtimeMode",
sessions.active_turn_id AS "activeTurnId",
sessions.last_error AS "lastError",
sessions.updated_at AS "updatedAt"
FROM projection_thread_sessions sessions
INNER JOIN projection_threads threads
ON threads.thread_id = sessions.thread_id
WHERE threads.deleted_at IS NULL
AND threads.archived_at IS NULL
ORDER BY sessions.thread_id ASC
`,
});
const listArchivedThreadSessionRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionThreadSessionDbRowSchema,
execute: () =>
sql`
SELECT
sessions.thread_id AS "threadId",
sessions.status,
sessions.provider_name AS "providerName",
sessions.provider_instance_id AS "providerInstanceId",
sessions.provider_session_id AS "providerSessionId",
sessions.provider_thread_id AS "providerThreadId",
sessions.runtime_mode AS "runtimeMode",
sessions.active_turn_id AS "activeTurnId",
sessions.last_error AS "lastError",
sessions.updated_at AS "updatedAt"
FROM projection_thread_sessions sessions
INNER JOIN projection_threads threads
ON threads.thread_id = sessions.thread_id
WHERE threads.deleted_at IS NULL
AND threads.archived_at IS NOT NULL
ORDER BY sessions.thread_id ASC
`,
});
const listCheckpointRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionCheckpointDbRowSchema,
@@ -599,33 +475,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
ON turns.thread_id = threads.thread_id
AND turns.turn_id = threads.latest_turn_id
WHERE threads.deleted_at IS NULL
AND threads.archived_at IS NULL
AND threads.latest_turn_id IS NOT NULL
ORDER BY turns.thread_id ASC
`,
});
const listArchivedLatestTurnRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionLatestTurnDbRowSchema,
execute: () =>
sql`
SELECT
turns.thread_id AS "threadId",
turns.turn_id AS "turnId",
turns.state,
turns.requested_at AS "requestedAt",
turns.started_at AS "startedAt",
turns.completed_at AS "completedAt",
turns.assistant_message_id AS "assistantMessageId",
turns.source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
turns.source_proposed_plan_id AS "sourceProposedPlanId"
FROM projection_threads threads
JOIN projection_turns turns
ON turns.thread_id = threads.thread_id
AND turns.turn_id = threads.latest_turn_id
WHERE threads.deleted_at IS NULL
AND threads.archived_at IS NOT NULL
AND threads.latest_turn_id IS NOT NULL
ORDER BY turns.thread_id ASC
`,
@@ -708,7 +557,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
FROM projection_threads
WHERE project_id = ${projectId}
AND deleted_at IS NULL
AND archived_at IS NULL
ORDER BY created_at ASC, thread_id ASC
LIMIT 1
`,
@@ -759,7 +607,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
FROM projection_threads
WHERE thread_id = ${threadId}
AND deleted_at IS NULL
AND archived_at IS NULL
LIMIT 1
`,
});
@@ -870,7 +717,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
AND turns.turn_id = threads.latest_turn_id
WHERE threads.thread_id = ${threadId}
AND threads.deleted_at IS NULL
AND threads.archived_at IS NULL
LIMIT 1
`,
});
@@ -896,38 +742,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
const getFullThreadDiffContextRow = SqlSchema.findOneOption({
Request: FullThreadDiffContextLookupInput,
Result: ProjectionFullThreadDiffContextRowSchema,
execute: ({ threadId, checkpointTurnCount }) =>
sql`
SELECT
threads.thread_id AS "threadId",
threads.project_id AS "projectId",
projects.workspace_root AS "workspaceRoot",
threads.worktree_path AS "worktreePath",
(
SELECT MAX(turns.checkpoint_turn_count)
FROM projection_turns AS turns
WHERE turns.thread_id = threads.thread_id
AND turns.checkpoint_turn_count IS NOT NULL
) AS "latestCheckpointTurnCount",
(
SELECT turns.checkpoint_ref
FROM projection_turns AS turns
WHERE turns.thread_id = threads.thread_id
AND turns.checkpoint_turn_count = ${checkpointTurnCount}
LIMIT 1
) AS "toCheckpointRef"
FROM projection_threads AS threads
INNER JOIN projection_projects AS projects
ON projects.project_id = threads.project_id
WHERE threads.thread_id = ${threadId}
AND threads.deleted_at IS NULL
LIMIT 1
`,
});
const getSnapshot: ProjectionSnapshotQueryShape["getSnapshot"] = () =>
sql
.withTransaction(
@@ -1418,7 +1232,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
),
),
listActiveThreadRows(undefined).pipe(
listThreadRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getShellSnapshot:listThreads:query",
@@ -1426,7 +1240,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
),
),
listActiveThreadSessionRows(undefined).pipe(
listThreadSessionRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getShellSnapshot:listThreadSessions:query",
@@ -1536,139 +1350,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
}),
);
const getArchivedShellSnapshot: ProjectionSnapshotQueryShape["getArchivedShellSnapshot"] = () =>
sql
.withTransaction(
Effect.all([
listProjectRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getArchivedShellSnapshot:listProjects:query",
"ProjectionSnapshotQuery.getArchivedShellSnapshot:listProjects:decodeRows",
),
),
),
listArchivedThreadRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getArchivedShellSnapshot:listThreads:query",
"ProjectionSnapshotQuery.getArchivedShellSnapshot:listThreads:decodeRows",
),
),
),
listArchivedThreadSessionRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getArchivedShellSnapshot:listThreadSessions:query",
"ProjectionSnapshotQuery.getArchivedShellSnapshot:listThreadSessions:decodeRows",
),
),
),
listArchivedLatestTurnRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getArchivedShellSnapshot:listLatestTurns:query",
"ProjectionSnapshotQuery.getArchivedShellSnapshot:listLatestTurns:decodeRows",
),
),
),
listProjectionStateRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getArchivedShellSnapshot:listProjectionState:query",
"ProjectionSnapshotQuery.getArchivedShellSnapshot:listProjectionState:decodeRows",
),
),
),
]),
)
.pipe(
Effect.flatMap(([projectRows, threadRows, sessionRows, latestTurnRows, stateRows]) =>
Effect.gen(function* () {
let updatedAt: string | null = null;
for (const row of projectRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
}
for (const row of threadRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
}
for (const row of sessionRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
}
for (const row of latestTurnRows) {
updatedAt = maxIso(updatedAt, row.requestedAt);
if (row.startedAt !== null) {
updatedAt = maxIso(updatedAt, row.startedAt);
}
if (row.completedAt !== null) {
updatedAt = maxIso(updatedAt, row.completedAt);
}
}
for (const row of stateRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
}
const activeProjectIds = new Set(threadRows.map((row) => row.projectId));
const repositoryIdentities = yield* resolveRepositoryIdentitiesForProjects(
projectRows.filter((row) => activeProjectIds.has(row.projectId)),
);
const latestTurnByThread = new Map(
latestTurnRows.map((row) => [row.threadId, mapLatestTurn(row)] as const),
);
const sessionByThread = new Map(
sessionRows.map((row) => [row.threadId, mapSessionRow(row)] as const),
);
const snapshot = {
snapshotSequence: computeSnapshotSequence(stateRows),
projects: projectRows
.filter((row) => row.deletedAt === null && activeProjectIds.has(row.projectId))
.map((row) =>
mapProjectShellRow(row, repositoryIdentities.get(row.projectId) ?? null),
),
threads: threadRows.map(
(row): OrchestrationThreadShell => ({
id: row.threadId,
projectId: row.projectId,
title: row.title,
modelSelection: row.modelSelection,
runtimeMode: row.runtimeMode,
interactionMode: row.interactionMode,
branch: row.branch,
worktreePath: row.worktreePath,
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
archivedAt: row.archivedAt,
session: sessionByThread.get(row.threadId) ?? null,
latestUserMessageAt: row.latestUserMessageAt,
hasPendingApprovals: row.pendingApprovalCount > 0,
hasPendingUserInput: row.pendingUserInputCount > 0,
hasActionableProposedPlan: row.hasActionableProposedPlan > 0,
}),
),
updatedAt: updatedAt ?? "1970-01-01T00:00:00.000Z",
};
return yield* decodeShellSnapshot(snapshot).pipe(
Effect.mapError(
toPersistenceDecodeError(
"ProjectionSnapshotQuery.getArchivedShellSnapshot:decodeShellSnapshot",
),
),
);
}),
),
Effect.mapError((error) => {
if (isPersistenceError(error)) {
return error;
}
return toPersistenceSqlError("ProjectionSnapshotQuery.getArchivedShellSnapshot:query")(
error,
);
}),
);
const getSnapshotSequence: ProjectionSnapshotQueryShape["getSnapshotSequence"] = () =>
listProjectionStateRows(undefined).pipe(
Effect.mapError(
@@ -1805,35 +1486,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
});
});
const getFullThreadDiffContext: NonNullable<
ProjectionSnapshotQueryShape["getFullThreadDiffContext"]
> = (threadId, toTurnCount) =>
Effect.gen(function* () {
const row = yield* getFullThreadDiffContextRow({
threadId,
checkpointTurnCount: toTurnCount,
}).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getFullThreadDiffContext:query",
"ProjectionSnapshotQuery.getFullThreadDiffContext:decodeRow",
),
),
);
if (Option.isNone(row)) {
return Option.none<ProjectionFullThreadDiffContext>();
}
return Option.some({
threadId: row.value.threadId,
projectId: row.value.projectId,
workspaceRoot: row.value.workspaceRoot,
worktreePath: row.value.worktreePath,
latestCheckpointTurnCount: row.value.latestCheckpointTurnCount ?? 0,
toCheckpointRef: row.value.toCheckpointRef,
});
});
const getThreadShellById: ProjectionSnapshotQueryShape["getThreadShellById"] = (threadId) =>
Effect.gen(function* () {
const [threadRow, latestTurnRow, sessionRow] = yield* Effect.all([
@@ -2031,14 +1683,12 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
getCommandReadModel,
getSnapshot,
getShellSnapshot,
getArchivedShellSnapshot,
getSnapshotSequence,
getCounts,
getActiveProjectByWorkspaceRoot,
getProjectShellById,
getFirstActiveThreadIdByProjectId,
getThreadCheckpointContext,
getFullThreadDiffContext,
getThreadShellById,
getThreadDetailById,
} satisfies ProjectionSnapshotQueryShape;
@@ -7,7 +7,6 @@
* @module ProjectionSnapshotQuery
*/
import type {
CheckpointRef,
OrchestrationCheckpointSummary,
OrchestrationProject,
OrchestrationProjectShell,
@@ -41,15 +40,6 @@ export interface ProjectionThreadCheckpointContext {
readonly checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>;
}
export interface ProjectionFullThreadDiffContext {
readonly threadId: ThreadId;
readonly projectId: ProjectId;
readonly workspaceRoot: string;
readonly worktreePath: string | null;
readonly latestCheckpointTurnCount: number;
readonly toCheckpointRef: CheckpointRef | null;
}
/**
* ProjectionSnapshotQueryShape - Service API for read-model snapshots.
*/
@@ -82,17 +72,6 @@ export interface ProjectionSnapshotQueryShape {
ProjectionRepositoryError
>;
/**
* Read archived thread shell summaries for the archive page.
*
* This query is separate from the main shell snapshot so archived threads
* are never bootstrapped into normal navigation state.
*/
readonly getArchivedShellSnapshot: () => Effect.Effect<
OrchestrationShellSnapshot,
ProjectionRepositoryError
>;
/**
* Read the latest projection snapshot sequence without hydrating read-model
* entities.
@@ -135,15 +114,6 @@ export interface ProjectionSnapshotQueryShape {
threadId: ThreadId,
) => Effect.Effect<Option.Option<ProjectionThreadCheckpointContext>, ProjectionRepositoryError>;
/**
* Read only the narrow context needed to compute a full-thread diff from
* checkpoint 0 to a specific turn count.
*/
readonly getFullThreadDiffContext: (
threadId: ThreadId,
toTurnCount: number,
) => Effect.Effect<Option.Option<ProjectionFullThreadDiffContext>, ProjectionRepositoryError>;
/**
* Read a single active thread shell row by id.
*/
@@ -42,7 +42,6 @@ import Migration0026 from "./Migrations/026_CanonicalizeModelSelectionOptions.ts
import Migration0027 from "./Migrations/027_ProviderSessionRuntimeInstanceId.ts";
import Migration0028 from "./Migrations/028_ProjectionThreadSessionInstanceId.ts";
import Migration0029 from "./Migrations/029_ProjectionThreadDetailOrderingIndexes.ts";
import Migration0030 from "./Migrations/030_ProjectionThreadShellArchiveIndexes.ts";
/**
* Migration loader with all migrations defined inline.
@@ -84,7 +83,6 @@ export const migrationEntries = [
[27, "ProviderSessionRuntimeInstanceId", Migration0027],
[28, "ProjectionThreadSessionInstanceId", Migration0028],
[29, "ProjectionThreadDetailOrderingIndexes", Migration0029],
[30, "ProjectionThreadShellArchiveIndexes", Migration0030],
] as const;
export const makeMigrationLoader = (throughId?: number) =>
@@ -1,16 +0,0 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_threads_shell_active
ON projection_threads(deleted_at, archived_at, project_id, created_at, thread_id)
`;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_threads_shell_archived
ON projection_threads(deleted_at, archived_at, project_id, thread_id)
`;
});
+16 -273
View File
@@ -1,282 +1,25 @@
import { describe, expect, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { TestClock } from "effect/testing";
import { ChildProcessSpawner } from "effect/unstable/process";
import { describe, expect, it } from "vitest";
import {
isWindowsCommandNotFound,
ProcessOutputLimitError,
ProcessRunner,
ProcessTimeoutError,
layer as ProcessRunnerLive,
type ProcessRunInput,
} from "./processRunner.ts";
type ChildProcessCommand = {
readonly command: string;
readonly args: ReadonlyArray<string>;
};
// Accesses private properties of ChildProcessCommand for testing purposes
function asChildProcessCommand(command: unknown): ChildProcessCommand {
return command as ChildProcessCommand;
}
function makeHandle(input: {
readonly stdout?: string | Stream.Stream<Uint8Array>;
readonly stderr?: string | Stream.Stream<Uint8Array>;
readonly code?: number;
readonly stdin?: ChildProcessSpawner.ChildProcessHandle["stdin"];
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
}) {
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode: input.exitCode ?? Effect.succeed(ChildProcessSpawner.ExitCode(input.code ?? 0)),
isRunning: Effect.succeed(false),
kill: () => Effect.void,
unref: Effect.succeed(Effect.void),
stdin: input.stdin ?? Sink.drain,
stdout:
typeof input.stdout === "string"
? Stream.encodeText(Stream.make(input.stdout))
: (input.stdout ?? Stream.empty),
stderr:
typeof input.stderr === "string"
? Stream.encodeText(Stream.make(input.stderr))
: (input.stderr ?? Stream.empty),
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
});
}
function makeSpawner(
f: (command: ChildProcessCommand) => Effect.Effect<ChildProcessSpawner.ChildProcessHandle>,
) {
return ChildProcessSpawner.make((command) => f(asChildProcessCommand(command)));
}
const runWith =
(spawner: ChildProcessSpawner.ChildProcessSpawner["Service"]) => (input: ProcessRunInput) =>
Effect.service(ProcessRunner).pipe(
Effect.flatMap((runner) =>
runner.run({
...input,
shell: input.shell ?? false,
}),
),
Effect.provide(
ProcessRunnerLive.pipe(
Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)),
),
),
);
import { isWindowsCommandNotFound, runProcess } from "./processRunner.ts";
describe("runProcess", () => {
it.effect("collects stdout through an injected ChildProcessSpawner", () =>
Effect.gen(function* () {
const spawner = makeSpawner((command) =>
Effect.sync(() => {
expect(command.command).toBe("fake");
expect(command.args).toEqual(["stdout-bytes", "32"]);
return makeHandle({ stdout: "x".repeat(32) });
}),
);
const result = yield* runWith(spawner)({
command: "fake",
args: ["stdout-bytes", "32"],
});
expect(result.code).toBe(0);
expect(result.stdout).toBe("x".repeat(32));
expect(result.timedOut).toBe(false);
}),
);
it.effect("runs through the ProcessRunner service", () => {
const spawner = makeSpawner((command) =>
Effect.sync(() => {
expect(command.command).toBe("fake");
expect(command.args).toEqual(["--service"]);
return makeHandle({ stdout: "service ok" });
}),
);
const layer = ProcessRunnerLive.pipe(
Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)),
);
return Effect.gen(function* () {
const runner = yield* ProcessRunner;
const result = yield* runner.run({
command: "fake",
args: ["--service"],
});
expect(result.stdout).toBe("service ok");
}).pipe(Effect.provide(layer));
it("fails when output exceeds max buffer in default mode", async () => {
await expect(
runProcess("node", ["-e", "process.stdout.write('x'.repeat(2048))"], { maxBufferBytes: 128 }),
).rejects.toThrow("exceeded stdout buffer limit");
});
it.effect("fails when output exceeds max buffer in default mode", () =>
Effect.gen(function* () {
const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stdout: "x".repeat(2048) })));
it("truncates output when outputMode is truncate", async () => {
const result = await runProcess("node", ["-e", "process.stdout.write('x'.repeat(2048))"], {
maxBufferBytes: 128,
outputMode: "truncate",
});
const error = yield* runWith(spawner)({
command: "fake",
args: ["stdout-bytes", "2048"],
maxOutputBytes: 128,
}).pipe(Effect.flip);
expect(error).toBeInstanceOf(ProcessOutputLimitError);
}),
);
it.effect("fails fast on output limit before timeout for long-running output", () =>
Effect.gen(function* () {
const textChunk = "x".repeat(64);
const spawner = makeSpawner(() =>
Effect.succeed(
makeHandle({
stdout: Stream.fromIterable(Array.from({ length: 10 }, () => textChunk)).pipe(
Stream.encodeText,
),
exitCode: Effect.never,
}),
),
);
const error = yield* runWith(spawner)({
command: "fake",
args: ["spam-stdout"],
maxOutputBytes: 128,
timeout: "2 seconds",
}).pipe(Effect.flip);
expect(error).toBeInstanceOf(ProcessOutputLimitError);
}),
);
it.effect("truncates output when outputMode is truncate", () =>
Effect.gen(function* () {
const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stdout: "x".repeat(2048) })));
const result = yield* runWith(spawner)({
command: "fake",
args: ["stdout-bytes", "2048"],
maxOutputBytes: 128,
outputMode: "truncate",
});
expect(result.code).toBe(0);
expect(result.stdout.length).toBeLessThanOrEqual(128);
expect(result.stdoutTruncated).toBe(true);
expect(result.stderrTruncated).toBe(false);
}),
);
it.effect("writes stdin before waiting for exit", () =>
Effect.gen(function* () {
const stdinWritten = yield* Deferred.make<void>();
const decoder = new TextDecoder();
const spawner = makeSpawner(() =>
Effect.succeed(
makeHandle({
stdout: "stdin payload",
stdin: Sink.forEach((chunk: Uint8Array) => {
const text = decoder.decode(chunk, { stream: true });
return text.includes("stdin payload")
? Deferred.succeed(stdinWritten, undefined)
: Effect.void;
}),
exitCode: Deferred.await(stdinWritten).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
}),
),
);
const result = yield* runWith(spawner)({
command: "fake",
args: ["stdin-echo"],
stdin: "stdin payload",
});
expect(result.stdout).toBe("stdin payload");
expect(result.code).toBe(0);
}),
);
it.effect("returns output for non-zero exit codes", () =>
Effect.gen(function* () {
const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stderr: "boom", code: 2 })));
const result = yield* runWith(spawner)({
command: "fake",
args: ["stderr-exit", "boom", "2"],
});
expect(result.code).toBe(2);
expect(result.stderr).toBe("boom");
}),
);
it.effect("fails on timeout", () =>
Effect.gen(function* () {
const spawner = makeSpawner(() =>
Effect.succeed(
makeHandle({
exitCode: Effect.never,
}),
),
);
const errorFiber = yield* runWith(spawner)({
command: "fake",
args: ["sleep"],
timeout: "50 millis",
}).pipe(Effect.flip, Effect.forkScoped);
yield* Effect.yieldNow;
yield* TestClock.adjust(Duration.millis(50));
const error = yield* Fiber.join(errorFiber);
expect(error).toBeInstanceOf(ProcessTimeoutError);
}),
);
it.effect("returns a synthetic timed out result when timeoutBehavior is timedOutResult", () =>
Effect.gen(function* () {
const spawner = makeSpawner(() =>
Effect.succeed(
makeHandle({
exitCode: Effect.never,
}),
),
);
const resultFiber = yield* runWith(spawner)({
command: "fake",
args: ["sleep"],
timeout: "50 millis",
timeoutBehavior: "timedOutResult",
}).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* TestClock.adjust(Duration.millis(50));
const result = yield* Fiber.join(resultFiber);
expect(result).toMatchObject({
stdout: "",
stderr: "",
code: null,
timedOut: true,
stdoutTruncated: false,
stderrTruncated: false,
});
}),
);
expect(result.code).toBe(0);
expect(result.stdout.length).toBeLessThanOrEqual(128);
expect(result.stdoutTruncated).toBe(true);
expect(result.stderrTruncated).toBe(false);
});
});
describe("isWindowsCommandNotFound", () => {
+245 -295
View File
@@ -1,100 +1,42 @@
import * as Data from "effect/Data";
import * as Context from "effect/Context";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
collectUint8StreamText,
type CollectedUint8StreamText,
} from "./stream/collectUint8StreamText.ts";
export interface ProcessRunInput {
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly cwd?: string | undefined;
readonly spawnCwd?: string | undefined;
readonly timeout?: Duration.Input | undefined;
readonly env?: NodeJS.ProcessEnv | undefined;
readonly stdin?: string | undefined;
readonly maxOutputBytes?: number | undefined;
readonly outputMode?: "error" | "truncate" | undefined;
readonly truncatedMarker?: string | undefined;
readonly shell?: boolean | string | undefined;
/**
* On timeout, return a synthetic timedOut result.
* Partial stdout/stderr are not preserved.
*/
readonly timeoutBehavior?: "error" | "timedOutResult" | undefined;
// @effect-diagnostics nodeBuiltinImport:off
import { type ChildProcess as ChildProcessHandle, spawn, spawnSync } from "node:child_process";
import * as NodeTimers from "node:timers";
export interface ProcessRunOptions {
cwd?: string | undefined;
timeoutMs?: number | undefined;
env?: NodeJS.ProcessEnv | undefined;
stdin?: string | undefined;
allowNonZeroExit?: boolean | undefined;
maxBufferBytes?: number | undefined;
outputMode?: "error" | "truncate" | undefined;
}
export interface ProcessRunOutput {
readonly stdout: string;
readonly stderr: string;
readonly code: ChildProcessSpawner.ExitCode | null;
readonly timedOut: boolean;
readonly stdoutTruncated: boolean;
readonly stderrTruncated: boolean;
export interface ProcessRunResult {
stdout: string;
stderr: string;
code: number | null;
signal: NodeJS.Signals | null;
timedOut: boolean;
stdoutTruncated?: boolean | undefined;
stderrTruncated?: boolean | undefined;
}
export class ProcessSpawnError extends Data.TaggedError("ProcessSpawnError")<{
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly cwd?: string | undefined;
readonly cause: unknown;
}> {}
export class ProcessStdinError extends Data.TaggedError("ProcessStdinError")<{
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly cwd?: string | undefined;
readonly cause: unknown;
}> {}
export class ProcessOutputLimitError extends Data.TaggedError("ProcessOutputLimitError")<{
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly cwd?: string | undefined;
readonly stream: "stdout" | "stderr";
readonly maxBytes: number;
}> {}
export class ProcessReadError extends Data.TaggedError("ProcessReadError")<{
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly cwd?: string | undefined;
readonly stream: "stdout" | "stderr" | "exitCode";
readonly cause: unknown;
}> {}
export class ProcessTimeoutError extends Data.TaggedError("ProcessTimeoutError")<{
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly cwd?: string | undefined;
readonly timeoutMs: number;
}> {}
export type ProcessRunError =
| ProcessSpawnError
| ProcessStdinError
| ProcessOutputLimitError
| ProcessReadError
| ProcessTimeoutError;
export interface ProcessRunnerShape {
readonly run: (input: ProcessRunInput) => Effect.Effect<ProcessRunOutput, ProcessRunError>;
function commandLabel(command: string, args: readonly string[]): string {
return [command, ...args].join(" ");
}
export class ProcessRunner extends Context.Service<ProcessRunner, ProcessRunnerShape>()(
"t3/process/ProcessRunner",
) {}
function normalizeSpawnError(command: string, args: readonly string[], error: unknown): Error {
if (!(error instanceof Error)) {
return new Error(`Failed to run ${commandLabel(command, args)}.`);
}
const DEFAULT_TIMEOUT = "60 seconds";
const DEFAULT_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
const maybeCode = (error as NodeJS.ErrnoException).code;
if (maybeCode === "ENOENT") {
return new Error(`Command not found: ${command}`);
}
return new Error(`Failed to run ${commandLabel(command, args)}: ${error.message}`);
}
const WINDOWS_COMMAND_NOT_FOUND_PATTERNS = [
/is not recognized as an internal or external command/i,
@@ -115,222 +57,230 @@ export function isWindowsCommandNotFound(code: number | null, stderr: string): b
return hasWindowsCommandNotFoundMessage(stderr);
}
const collectText = Effect.fn("processRunner.collectText")(function* (input: {
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly cwd?: string | undefined;
readonly streamName: "stdout" | "stderr";
readonly stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
readonly maxOutputBytes: number;
readonly outputMode: "error" | "truncate";
readonly truncatedMarker: string;
}) {
const stream = input.stream.pipe(
Stream.mapError(
(cause) =>
new ProcessReadError({
command: input.command,
args: input.args,
cwd: input.cwd,
stream: input.streamName,
cause,
}),
),
);
if (input.outputMode === "truncate") {
return yield* collectUint8StreamText({
stream,
maxBytes: input.maxOutputBytes,
truncatedMarker: input.truncatedMarker,
});
function normalizeExitError(
command: string,
args: readonly string[],
result: ProcessRunResult,
): Error {
if (isWindowsCommandNotFound(result.code, result.stderr)) {
return new Error(`Command not found: ${command}`);
}
return yield* stream.pipe(
Stream.runFoldEffect<
{
readonly chunks: Uint8Array<ArrayBufferLike>[];
readonly bytes: number;
},
Uint8Array<ArrayBufferLike>,
ProcessOutputLimitError | ProcessReadError,
never
>(
() => ({ chunks: [], bytes: 0 }),
(state, chunk) => {
const remainingBytes = input.maxOutputBytes - state.bytes;
if (remainingBytes <= 0 || chunk.byteLength > remainingBytes) {
return Effect.fail(
new ProcessOutputLimitError({
command: input.command,
args: input.args,
cwd: input.cwd,
stream: input.streamName,
maxBytes: input.maxOutputBytes,
}),
);
}
const reason = result.timedOut
? "timed out"
: `failed (code=${result.code ?? "null"}, signal=${result.signal ?? "null"})`;
const stderr = result.stderr.trim();
const detail = stderr.length > 0 ? ` ${stderr}` : "";
return new Error(`${commandLabel(command, args)} ${reason}.${detail}`);
}
state.chunks.push(chunk);
return Effect.succeed({
chunks: state.chunks,
bytes: state.bytes + chunk.byteLength,
});
},
),
Effect.map(
(state): CollectedUint8StreamText => ({
text: Buffer.concat(state.chunks, state.bytes).toString("utf8"),
bytes: state.bytes,
truncated: false,
}),
),
);
});
function normalizeStdinError(command: string, args: readonly string[], error: unknown): Error {
if (!(error instanceof Error)) {
return new Error(`Failed to write stdin for ${commandLabel(command, args)}.`);
}
return new Error(`Failed to write stdin for ${commandLabel(command, args)}: ${error.message}`);
}
function finalizeRunProcess<R>(
effect: Effect.Effect<ProcessRunOutput, ProcessRunError, R | Scope.Scope>,
input: ProcessRunInput,
): Effect.Effect<ProcessRunOutput, ProcessRunError, Exclude<R, Scope.Scope>> {
const timeout = Duration.fromInputUnsafe(input.timeout ?? DEFAULT_TIMEOUT);
const timeoutBehavior = input.timeoutBehavior ?? "error";
return effect.pipe(
Effect.scoped,
Effect.timeoutOption(timeout),
Effect.flatMap((result) => {
if (Option.isSome(result)) {
return Effect.succeed(result.value);
}
if (timeoutBehavior === "timedOutResult") {
return Effect.succeed({
stdout: "",
stderr: "",
code: null,
timedOut: true,
stdoutTruncated: false,
stderrTruncated: false,
} satisfies ProcessRunOutput);
}
return Effect.fail(
new ProcessTimeoutError({
command: input.command,
args: input.args,
cwd: input.cwd,
timeoutMs: Duration.toMillis(timeout),
}),
);
}),
function normalizeBufferError(
command: string,
args: readonly string[],
stream: "stdout" | "stderr",
maxBufferBytes: number,
): Error {
return new Error(
`${commandLabel(command, args)} exceeded ${stream} buffer limit (${maxBufferBytes} bytes).`,
);
}
const runProcessCore = Effect.fn("processRunner.runProcessCore")(function* (
spawner: ChildProcessSpawner.ChildProcessSpawner["Service"],
input: ProcessRunInput,
): Effect.fn.Return<ProcessRunOutput, ProcessRunError, Scope.Scope> {
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
const outputMode = input.outputMode ?? "error";
const truncatedMarker = input.truncatedMarker ?? "";
const DEFAULT_MAX_BUFFER_BYTES = 8 * 1024 * 1024;
const child = yield* spawner
.spawn(
ChildProcess.make(input.command, [...input.args], {
...((input.spawnCwd ?? input.cwd) ? { cwd: input.spawnCwd ?? input.cwd } : {}),
...(input.env !== undefined
? {
env: input.env,
extendEnv: true,
}
: {}),
...(input.shell !== undefined ? { shell: input.shell } : {}),
}),
)
.pipe(
Effect.mapError(
(cause) =>
new ProcessSpawnError({
command: input.command,
args: input.args,
cwd: input.cwd,
cause,
}),
),
);
const writeStdin =
input.stdin === undefined
? Effect.void
: Stream.run(Stream.encodeText(Stream.make(input.stdin)), child.stdin).pipe(
Effect.mapError(
(cause) =>
new ProcessStdinError({
command: input.command,
args: input.args,
cwd: input.cwd,
cause,
}),
),
);
const [stdout, stderr] = yield* Effect.all(
[
collectText({
command: input.command,
args: input.args,
cwd: input.cwd,
streamName: "stdout",
stream: child.stdout,
maxOutputBytes,
outputMode,
truncatedMarker,
}),
collectText({
command: input.command,
args: input.args,
cwd: input.cwd,
streamName: "stderr",
stream: child.stderr,
maxOutputBytes,
outputMode,
truncatedMarker,
}),
writeStdin,
],
{ concurrency: "unbounded" },
);
const exitCode = yield* child.exitCode.pipe(
Effect.mapError(
(cause) =>
new ProcessReadError({
command: input.command,
args: input.args,
cwd: input.cwd,
stream: "exitCode",
cause,
}),
),
);
/**
* 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 killChild(child: ChildProcessHandle, signal: NodeJS.Signals = "SIGTERM"): 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(signal);
}
function appendChunkWithinLimit(
target: string,
currentBytes: number,
chunk: Buffer,
maxBytes: number,
): {
next: string;
nextBytes: number;
truncated: boolean;
} {
const remaining = maxBytes - currentBytes;
if (remaining <= 0) {
return { next: target, nextBytes: currentBytes, truncated: true };
}
if (chunk.length <= remaining) {
return {
next: `${target}${chunk.toString()}`,
nextBytes: currentBytes + chunk.length,
truncated: false,
};
}
return {
stdout: stdout.text,
stderr: stderr.text,
code: exitCode,
timedOut: false,
stdoutTruncated: stdout.truncated,
stderrTruncated: stderr.truncated,
} satisfies ProcessRunOutput;
});
next: `${target}${chunk.subarray(0, remaining).toString()}`,
nextBytes: currentBytes + remaining,
truncated: true,
};
}
export const make = Effect.fn("makeProcessRunner")(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
export async function runProcess(
command: string,
args: readonly string[],
options: ProcessRunOptions = {},
): Promise<ProcessRunResult> {
const timeoutMs = options.timeoutMs ?? 60_000;
const maxBufferBytes = options.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES;
const outputMode = options.outputMode ?? "error";
const run: ProcessRunnerShape["run"] = (input) =>
finalizeRunProcess(runProcessCore(spawner, input), input);
return new Promise<ProcessRunResult>((resolve, reject) => {
const child = spawn(command, args, {
cwd: options.cwd,
env: options.env,
stdio: "pipe",
shell: process.platform === "win32",
});
return ProcessRunner.of({
run,
let stdout = "";
let stderr = "";
let stdoutBytes = 0;
let stderrBytes = 0;
let stdoutTruncated = false;
let stderrTruncated = false;
let timedOut = false;
let settled = false;
let forceKillTimer: ReturnType<typeof NodeTimers.setTimeout> | null = null;
// @effect-diagnostics-next-line globalTimers:off - Promise/child_process boundary; moving this runner to Effect timers is a separate refactor.
const timeoutTimer = NodeTimers.setTimeout(() => {
timedOut = true;
killChild(child, "SIGTERM");
// @effect-diagnostics-next-line globalTimers:off - Promise/child_process boundary; see timeout timer above.
forceKillTimer = NodeTimers.setTimeout(() => {
killChild(child, "SIGKILL");
}, 1_000);
}, timeoutMs);
const finalize = (callback: () => void): void => {
if (settled) return;
settled = true;
NodeTimers.clearTimeout(timeoutTimer);
if (forceKillTimer) {
NodeTimers.clearTimeout(forceKillTimer);
}
callback();
};
const fail = (error: Error): void => {
killChild(child, "SIGTERM");
finalize(() => {
reject(error);
});
};
const appendOutput = (stream: "stdout" | "stderr", chunk: Buffer | string): Error | null => {
const chunkBuffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
const text = chunkBuffer.toString();
const byteLength = chunkBuffer.length;
if (stream === "stdout") {
if (outputMode === "truncate") {
const appended = appendChunkWithinLimit(stdout, stdoutBytes, chunkBuffer, maxBufferBytes);
stdout = appended.next;
stdoutBytes = appended.nextBytes;
stdoutTruncated = stdoutTruncated || appended.truncated;
return null;
}
stdout += text;
stdoutBytes += byteLength;
if (stdoutBytes > maxBufferBytes) {
return normalizeBufferError(command, args, "stdout", maxBufferBytes);
}
} else {
if (outputMode === "truncate") {
const appended = appendChunkWithinLimit(stderr, stderrBytes, chunkBuffer, maxBufferBytes);
stderr = appended.next;
stderrBytes = appended.nextBytes;
stderrTruncated = stderrTruncated || appended.truncated;
return null;
}
stderr += text;
stderrBytes += byteLength;
if (stderrBytes > maxBufferBytes) {
return normalizeBufferError(command, args, "stderr", maxBufferBytes);
}
}
return null;
};
child.stdout.on("data", (chunk: Buffer | string) => {
const error = appendOutput("stdout", chunk);
if (error) {
fail(error);
}
});
child.stderr.on("data", (chunk: Buffer | string) => {
const error = appendOutput("stderr", chunk);
if (error) {
fail(error);
}
});
child.once("error", (error) => {
finalize(() => {
reject(normalizeSpawnError(command, args, error));
});
});
child.once("close", (code, signal) => {
const result: ProcessRunResult = {
stdout,
stderr,
code,
signal,
timedOut,
stdoutTruncated,
stderrTruncated,
};
finalize(() => {
if (!options.allowNonZeroExit && (timedOut || (code !== null && code !== 0))) {
reject(normalizeExitError(command, args, result));
return;
}
resolve(result);
});
});
child.stdin.once("error", (error) => {
fail(normalizeStdinError(command, args, error));
});
if (options.stdin !== undefined) {
child.stdin.write(options.stdin, (error) => {
if (error) {
fail(normalizeStdinError(command, args, error));
return;
}
child.stdin.end();
});
return;
}
child.stdin.end();
});
});
export const layer = Layer.effect(ProcessRunner, make());
}
@@ -25,7 +25,6 @@ const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) =>
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 1 }),
getCounts: () => Effect.die("unused"),
getActiveProjectByWorkspaceRoot: (workspaceRoot) =>
@@ -36,7 +35,6 @@ const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) =>
Effect.succeed(projectId === project.id ? Option.some(project) : Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
getThreadCheckpointContext: () => Effect.die("unused"),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.die("unused"),
getThreadDetailById: () => Effect.die("unused"),
});
@@ -1,13 +1,15 @@
// @effect-diagnostics nodeBuiltinImport:off
import { realpathSync } from "node:fs";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import { TestClock } from "effect/testing";
import * as TestClock from "effect/testing/TestClock";
import * as ProcessRunner from "../../processRunner.ts";
import { runProcess } from "../../processRunner.ts";
import { RepositoryIdentityResolver } from "../Services/RepositoryIdentityResolver.ts";
import {
makeRepositoryIdentityResolver,
@@ -15,17 +17,11 @@ import {
} from "./RepositoryIdentityResolver.ts";
const normalizePathSeparators = (value: string) => value.replaceAll("\\", "/");
const normalizeResolvedPath = (value: string) => normalizePathSeparators(value);
const normalizeResolvedPath = (value: string) =>
normalizePathSeparators(realpathSync.native(value));
const git = (cwd: string, args: ReadonlyArray<string>) =>
Effect.gen(function* () {
const processRunner = yield* ProcessRunner.ProcessRunner;
return yield* processRunner.run({
command: "git",
args: ["-C", cwd, ...args],
shell: process.platform === "win32",
});
}).pipe(Effect.provide(ProcessRunner.layer));
Effect.promise(() => runProcess("git", ["-C", cwd, ...args]));
const makeRepositoryIdentityResolverTestLayer = (options: {
readonly positiveCacheTtl?: Duration.Input;
@@ -37,7 +33,7 @@ const makeRepositoryIdentityResolverTestLayer = (options: {
cacheCapacity: 16,
...options,
}),
).pipe(Layer.provide(ProcessRunner.layer));
);
it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
it.effect("normalizes equivalent GitHub remotes into a stable repository identity", () =>
@@ -52,13 +48,10 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
const resolver = yield* RepositoryIdentityResolver;
const identity = yield* resolver.resolve(cwd);
const resolvedIdentityRoot =
identity?.rootPath === undefined ? "" : yield* fileSystem.realPath(identity.rootPath);
const resolvedCwd = yield* fileSystem.realPath(cwd);
expect(identity).not.toBeNull();
expect(identity?.canonicalKey).toBe("github.com/t3tools/t3code");
expect(normalizeResolvedPath(resolvedIdentityRoot)).toBe(normalizeResolvedPath(resolvedCwd));
expect(normalizeResolvedPath(identity?.rootPath ?? "")).toBe(normalizeResolvedPath(cwd));
expect(identity?.displayName).toBe("t3tools/t3code");
expect(identity?.provider).toBe("github");
expect(identity?.owner).toBe("t3tools");
@@ -69,11 +62,10 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
it.effect("returns the git top-level root path when resolving from a nested workspace", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const repoRoot = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-repository-identity-nested-root-test-",
});
const nestedWorkspace = path.join(repoRoot, "packages", "web");
const nestedWorkspace = `${repoRoot}/packages/web`;
yield* fileSystem.makeDirectory(nestedWorkspace, { recursive: true });
yield* git(repoRoot, ["init"]);
@@ -81,15 +73,10 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
const resolver = yield* RepositoryIdentityResolver;
const identity = yield* resolver.resolve(nestedWorkspace);
const resolvedIdentityRoot =
identity?.rootPath === undefined ? "" : yield* fileSystem.realPath(identity.rootPath);
const resolvedRepoRoot = yield* fileSystem.realPath(repoRoot);
expect(identity).not.toBeNull();
expect(identity?.canonicalKey).toBe("github.com/t3tools/t3code");
expect(normalizeResolvedPath(resolvedIdentityRoot)).toBe(
normalizeResolvedPath(resolvedRepoRoot),
);
expect(normalizeResolvedPath(identity?.rootPath ?? "")).toBe(normalizeResolvedPath(repoRoot));
}).pipe(Effect.provide(RepositoryIdentityResolverLive)),
);
@@ -9,7 +9,7 @@ import {
normalizeGitRemoteUrl,
} from "@t3tools/shared/git";
import * as ProcessRunner from "../../processRunner.ts";
import { runProcess } from "../../processRunner.ts";
import {
RepositoryIdentityResolver,
type RepositoryIdentityResolverShape,
@@ -83,63 +83,50 @@ interface RepositoryIdentityResolverOptions {
readonly negativeCacheTtl?: Duration.Input;
}
const resolveRepositoryIdentityCacheKey = Effect.fn("resolveRepositoryIdentityCacheKey")(function* (
cwd: string,
) {
const processRunner = yield* ProcessRunner.ProcessRunner;
async function resolveRepositoryIdentityCacheKey(cwd: string): Promise<string> {
let cacheKey = cwd;
const topLevelResult = yield* processRunner
.run({
command: "git",
args: ["-C", cwd, "rev-parse", "--show-toplevel"],
timeoutBehavior: "timedOutResult",
shell: process.platform === "win32",
})
.pipe(Effect.option);
if (topLevelResult._tag === "None" || topLevelResult.value.code !== 0) {
try {
const topLevelResult = await runProcess("git", ["-C", cwd, "rev-parse", "--show-toplevel"], {
allowNonZeroExit: true,
});
if (topLevelResult.code !== 0) {
return cacheKey;
}
const candidate = topLevelResult.stdout.trim();
if (candidate.length > 0) {
cacheKey = candidate;
}
} catch {
return cacheKey;
}
const candidate = topLevelResult.value.stdout.trim();
if (candidate.length > 0) {
cacheKey = candidate;
}
return cacheKey;
});
}
const resolveRepositoryIdentityFromCacheKey = Effect.fn("resolveRepositoryIdentityFromCacheKey")(
function* (
cacheKey: string,
): Effect.fn.Return<RepositoryIdentity | null, never, ProcessRunner.ProcessRunner> {
const processRunner = yield* ProcessRunner.ProcessRunner;
const remoteResult = yield* processRunner
.run({
command: "git",
args: ["-C", cacheKey, "remote", "-v"],
timeoutBehavior: "timedOutResult",
shell: process.platform === "win32",
})
.pipe(Effect.option);
if (remoteResult._tag === "None" || remoteResult.value.code !== 0) {
async function resolveRepositoryIdentityFromCacheKey(
cacheKey: string,
): Promise<RepositoryIdentity | null> {
try {
const remoteResult = await runProcess("git", ["-C", cacheKey, "remote", "-v"], {
allowNonZeroExit: true,
});
if (remoteResult.code !== 0) {
return null;
}
const remote = pickPrimaryRemote(parseRemoteFetchUrls(remoteResult.value.stdout));
const remote = pickPrimaryRemote(parseRemoteFetchUrls(remoteResult.stdout));
return remote ? buildRepositoryIdentity({ ...remote, rootPath: cacheKey }) : null;
},
);
} catch {
return null;
}
}
export const makeRepositoryIdentityResolver = Effect.fn("makeRepositoryIdentityResolver")(
function* (options: RepositoryIdentityResolverOptions = {}) {
const processRunner = yield* ProcessRunner.ProcessRunner;
const repositoryIdentityCache = yield* Cache.makeWith<string, RepositoryIdentity | null>(
(cacheKey) =>
resolveRepositoryIdentityFromCacheKey(cacheKey).pipe(
Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
),
(cacheKey) => Effect.promise(() => resolveRepositoryIdentityFromCacheKey(cacheKey)),
{
capacity: options.cacheCapacity ?? DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY,
timeToLive: Exit.match({
@@ -155,9 +142,7 @@ export const makeRepositoryIdentityResolver = Effect.fn("makeRepositoryIdentityR
const resolve: RepositoryIdentityResolverShape["resolve"] = Effect.fn(
"RepositoryIdentityResolver.resolve",
)(function* (cwd) {
const cacheKey = yield* resolveRepositoryIdentityCacheKey(cwd).pipe(
Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
);
const cacheKey = yield* Effect.promise(() => resolveRepositoryIdentityCacheKey(cwd));
return yield* Cache.get(repositoryIdentityCache, cacheKey);
});
@@ -170,4 +155,4 @@ export const makeRepositoryIdentityResolver = Effect.fn("makeRepositoryIdentityR
export const RepositoryIdentityResolverLive = Layer.effect(
RepositoryIdentityResolver,
makeRepositoryIdentityResolver(),
).pipe(Layer.provide(ProcessRunner.layer));
);
@@ -82,9 +82,9 @@ import {
ProviderAdapterValidationError,
type ProviderAdapterError,
} from "../Errors.ts";
import { encodeJsonStringForDiagnostics } from "@t3tools/shared/schemaJson";
import { type ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.UnknownFromJsonString);
const decodeUnknownJsonStringExit = Schema.decodeUnknownExit(Schema.UnknownFromJsonString);
const PROVIDER = ProviderDriverKind.make("claudeAgent");
@@ -95,11 +95,6 @@ type ClaudeToolResultStreamKind = Extract<
>;
type ClaudeSdkEffort = NonNullable<ClaudeQueryOptions["effort"]>;
function encodeJsonStringForDiagnostics(input: unknown): string | undefined {
const result = encodeUnknownJsonStringExit(input);
return Exit.isSuccess(result) ? result.value : undefined;
}
type PromptQueueItem =
| {
readonly type: "message";
@@ -18,7 +18,6 @@ import {
getProviderOptionCurrentValue,
getProviderOptionDescriptors,
} from "@t3tools/shared/model";
import { compareSemverVersions } from "@t3tools/shared/semver";
import {
query as claudeQuery,
type SlashCommand as ClaudeSlashCommand,
@@ -37,6 +36,7 @@ import {
spawnAndCollect,
type ServerProviderDraft,
} from "../providerSnapshot.ts";
import { compareCliVersions } from "../cliVersion.ts";
import { makeClaudeEnvironment } from "../Drivers/ClaudeHome.ts";
const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({
@@ -180,7 +180,7 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
];
function supportsClaudeOpus47(version: string | null | undefined): boolean {
return version ? compareSemverVersions(version, MINIMUM_CLAUDE_OPUS_4_7_VERSION) >= 0 : false;
return version ? compareCliVersions(version, MINIMUM_CLAUDE_OPUS_4_7_VERSION) >= 0 : false;
}
function getBuiltInClaudeModelsForVersion(
@@ -5,7 +5,6 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Types from "effect/Types";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as CodexClient from "effect-codex-app-server/client";
@@ -23,15 +22,13 @@ import type {
import { ServerSettingsError } from "@t3tools/contracts";
import { createModelCapabilities } from "@t3tools/shared/model";
import {
AUTH_PROBE_TIMEOUT_MS,
buildServerProvider,
type ServerProviderDraft,
} from "../providerSnapshot.ts";
import { buildServerProvider, type ServerProviderDraft } from "../providerSnapshot.ts";
import { expandHomePath } from "../../pathExpansion.ts";
import { scopedSafeTeardown } from "./scopedSafeTeardown.ts";
import packageJson from "../../../package.json" with { type: "json" };
const isCodexAppServerSpawnError = Schema.is(CodexErrors.CodexAppServerSpawnError);
const PROVIDER_PROBE_TIMEOUT_MS = 8_000;
const CODEX_PRESENTATION = {
displayName: "Codex",
showInteractionModeToggle: true,
@@ -248,6 +245,12 @@ export function buildCodexInitializeParams(): CodexSchema.V1InitializeParams {
};
}
// Wrapped with `scopedSafeTeardown("codex-probe")` rather than the usual
// `Effect.scoped` so that a defect from the `Layer.build` finalizer (e.g.
// `ChildProcess.kill` throwing because the `codex app-server` child exited
// early) cannot override a successful probe body. Without this guard the
// defect bubbles past `Effect.result` in `checkCodexProviderStatus`, dies
// `refreshOneSource`, and `providersRef` never receives the snapshot.
const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(function* (input: {
readonly binaryPath: string;
readonly homePath?: string;
@@ -317,7 +320,7 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun
models: appendCustomCodexModels(models, input.customModels ?? []),
skills: parseCodexSkillsListResponse(skillsResponse, input.cwd),
} satisfies CodexAppServerProviderSnapshot;
});
}, scopedSafeTeardown("codex-probe"));
const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider["models"] =>
codexSettings.customModels
@@ -410,7 +413,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
}) => Effect.Effect<
CodexAppServerProviderSnapshot,
CodexErrors.CodexAppServerError,
ChildProcessSpawner.ChildProcessSpawner | Scope.Scope
ChildProcessSpawner.ChildProcessSpawner
> = probeCodexAppServerProvider,
environment: NodeJS.ProcessEnv = process.env,
): Effect.fn.Return<
@@ -444,11 +447,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
cwd: process.cwd(),
customModels: codexSettings.customModels,
environment,
}).pipe(
Effect.scoped,
Effect.timeoutOption(Duration.millis(AUTH_PROBE_TIMEOUT_MS)),
Effect.result,
);
}).pipe(Effect.timeoutOption(Duration.millis(PROVIDER_PROBE_TIMEOUT_MS)), Effect.result);
if (Result.isFailure(probeResult)) {
const error = probeResult.failure;
@@ -53,7 +53,6 @@ const BENIGN_ERROR_LOG_SNIPPETS = [
"state db missing rollout path for thread",
"state db record_discrepancy: find_thread_path_by_id_str_in_subdir, falling_back",
];
const CODEX_APP_SERVER_FORCE_KILL_AFTER = "2 seconds" as const;
const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
"not found",
"missing thread",
@@ -722,7 +721,6 @@ export const makeCodexSessionRuntime = (
ChildProcess.make(options.binaryPath, ["app-server"], {
cwd: options.cwd,
env,
forceKillAfter: CODEX_APP_SERVER_FORCE_KILL_AFTER,
shell: process.platform === "win32",
}),
)
@@ -72,10 +72,10 @@ import {
extractPlanMarkdown,
extractTodosAsPlan,
} from "../acp/CursorAcpExtension.ts";
import { encodeJsonStringForDiagnostics } from "@t3tools/shared/schemaJson";
import { type CursorAdapterShape } from "../Services/CursorAdapter.ts";
import { resolveCursorAcpBaseModelId } from "./CursorProvider.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.UnknownFromJsonString);
const PROVIDER = ProviderDriverKind.make("cursor");
const CURSOR_RESUME_VERSION = 1 as const;
@@ -83,11 +83,6 @@ const ACP_PLAN_MODE_ALIASES = ["plan", "architect"];
const ACP_IMPLEMENT_MODE_ALIASES = ["code", "agent", "default", "chat", "implement"];
const ACP_APPROVAL_MODE_ALIASES = ["ask"];
function encodeJsonStringForDiagnostics(input: unknown): string | undefined {
const result = encodeUnknownJsonStringExit(input);
return Exit.isSuccess(result) ? result.value : undefined;
}
export interface CursorAdapterLiveOptions {
readonly environment?: NodeJS.ProcessEnv;
readonly nativeEventLogPath?: string;
@@ -559,98 +559,17 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
}),
);
it.effect("appends raw assistant text deltas and reconciles part update snapshots", () =>
it.effect("deduplicates overlapping assistant text deltas after part updates", () =>
Effect.sync(() => {
const firstUpdate = mergeOpenCodeAssistantText(undefined, "Hello");
const overlapDelta = appendOpenCodeAssistantTextDelta(firstUpdate.latestText, "lo world");
const secondUpdate = mergeOpenCodeAssistantText(overlapDelta.nextText, "Hellolo world");
const secondUpdate = mergeOpenCodeAssistantText(overlapDelta.nextText, "Hello world!");
assert.deepEqual(
[firstUpdate.deltaToEmit, overlapDelta.deltaToEmit, secondUpdate.deltaToEmit],
["Hello", "lo world", ""],
["Hello", " world", "!"],
);
assert.equal(secondUpdate.latestText, "Hellolo world");
}),
);
it.effect("does not strip coincidental prefix overlap from OpenCode part deltas", () =>
Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
const threadId = asThreadId("thread-opencode-raw-delta");
const part = {
id: "part-raw-delta",
sessionID: "http://127.0.0.1:9999/session",
messageID: "msg-raw-delta",
type: "text",
text: "A B",
time: { start: 1 },
};
runtimeMock.state.subscribedEvents = [
{
type: "message.updated",
properties: {
sessionID: "http://127.0.0.1:9999/session",
info: {
id: "msg-raw-delta",
role: "assistant",
},
},
},
{
type: "message.part.updated",
properties: {
sessionID: "http://127.0.0.1:9999/session",
part,
time: 1,
},
},
{
type: "message.part.delta",
properties: {
sessionID: "http://127.0.0.1:9999/session",
messageID: "msg-raw-delta",
partID: "part-raw-delta",
field: "text",
delta: "Bonus",
},
},
{
type: "message.part.updated",
properties: {
sessionID: "http://127.0.0.1:9999/session",
part: {
...part,
text: "A BBonus",
time: { start: 1, end: 2 },
},
time: 2,
},
},
];
const eventsFiber = yield* adapter.streamEvents.pipe(
Stream.filter((event) => event.threadId === threadId),
Stream.take(5),
Stream.runCollect,
Effect.forkChild,
);
yield* adapter.startSession({
provider: ProviderDriverKind.make("opencode"),
threadId,
runtimeMode: "full-access",
});
const events = Array.from(yield* Fiber.join(eventsFiber).pipe(Effect.timeout("1 second")));
const deltas = events.filter((event) => event.type === "content.delta");
assert.deepEqual(
deltas.map((event) => (event.type === "content.delta" ? event.payload.delta : "")),
["A B", "Bonus"],
);
assert.equal(events.at(-1)?.type, "item.completed");
const completed = events.at(-1);
if (completed?.type === "item.completed") {
assert.equal(completed.payload.detail, "A BBonus");
}
assert.equal(secondUpdate.latestText, "Hello world!");
}),
);
@@ -311,6 +311,16 @@ function commonPrefixLength(left: string, right: string): number {
return index;
}
function suffixPrefixOverlap(text: string, delta: string): number {
const maxLength = Math.min(text.length, delta.length);
for (let length = maxLength; length > 0; length -= 1) {
if (text.endsWith(delta.slice(0, length))) {
return length;
}
}
return 0;
}
function resolveLatestAssistantText(previousText: string | undefined, nextText: string): string {
if (previousText && previousText.length > nextText.length && previousText.startsWith(nextText)) {
return previousText;
@@ -339,9 +349,10 @@ export function appendOpenCodeAssistantTextDelta(
readonly nextText: string;
readonly deltaToEmit: string;
} {
const deltaToEmit = delta.slice(suffixPrefixOverlap(previousText, delta));
return {
nextText: previousText + delta,
deltaToEmit: delta,
nextText: previousText + deltaToEmit,
deltaToEmit,
};
}
@@ -10,7 +10,6 @@ import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import { createModelCapabilities } from "@t3tools/shared/model";
import { compareSemverVersions } from "@t3tools/shared/semver";
import {
buildServerProvider,
nonEmptyTrimmed,
@@ -18,6 +17,7 @@ import {
providerModelsFromSettings,
type ServerProviderDraft,
} from "../providerSnapshot.ts";
import { compareCliVersions } from "../cliVersion.ts";
import {
OpenCodeRuntime,
openCodeRuntimeErrorDetail,
@@ -383,7 +383,7 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
null,
);
}
if (compareSemverVersions(version, MINIMUM_OPENCODE_VERSION) < 0) {
if (compareCliVersions(version, MINIMUM_OPENCODE_VERSION) < 0) {
return buildServerProvider({
presentation: OPENCODE_PRESENTATION,
enabled: openCodeSettings.enabled,
@@ -2,7 +2,6 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, it, assert } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
@@ -28,7 +27,6 @@ import { HttpClient, HttpClientResponse } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import { deepMerge } from "@t3tools/shared/Struct";
import { createModelCapabilities } from "@t3tools/shared/model";
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
import { checkCodexProviderStatus, type CodexAppServerProviderSnapshot } from "./CodexProvider.ts";
import { checkClaudeProviderStatus } from "./ClaudeProvider.ts";
@@ -50,8 +48,6 @@ import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.t
import { ProviderRegistry } from "../Services/ProviderRegistry.ts";
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
const decodeServerSettings = Schema.decodeSync(ServerSettings);
const encodeServerSettings = Schema.encodeSync(ServerSettings);
const encodedDefaultServerSettings = encodeServerSettings(DEFAULT_SERVER_SETTINGS);
const defaultClaudeSettings: ClaudeSettings = Schema.decodeSync(ClaudeSettings)({});
const defaultCodexSettings: CodexSettings = Schema.decodeSync(CodexSettings)({});
@@ -210,31 +206,6 @@ function failingSpawnerLayer(description: string) {
);
}
function hangingScopedSpawnerLayer(killCalls: Ref.Ref<number>) {
return Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.gen(function* () {
const handle = ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode: Effect.never,
isRunning: Effect.succeed(true),
kill: () => Ref.update(killCalls, (current) => current + 1),
unref: Effect.succeed(Effect.void),
stdin: Sink.drain,
stdout: Stream.never,
stderr: Stream.never,
all: Stream.never,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
});
yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
return handle;
}),
),
);
}
const codexModelCapabilities = createModelCapabilities({
optionDescriptors: [
selectDescriptor("reasoningEffort", "Reasoning", [
@@ -285,8 +256,7 @@ function makeMutableServerSettingsService(
updateSettings: (patch) =>
Effect.gen(function* () {
const current = yield* Ref.get(settingsRef);
const next = applyServerSettingsPatch(current, patch);
encodeServerSettings(next);
const next = decodeServerSettings(deepMerge(current, patch));
yield* Ref.set(settingsRef, next);
yield* PubSub.publish(changes, next);
return next;
@@ -447,28 +417,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
);
}),
);
it.effect("closes the app-server probe scope when provider status times out", () =>
Effect.gen(function* () {
const killCalls = yield* Ref.make(0);
const statusFiber = yield* checkCodexProviderStatus(defaultCodexSettings).pipe(
Effect.provide(hangingScopedSpawnerLayer(killCalls)),
Effect.forkChild,
);
yield* Effect.yieldNow;
yield* TestClock.adjust("11 seconds");
yield* Effect.yieldNow;
const status = yield* Fiber.join(statusFiber);
assert.strictEqual(status.status, "error");
assert.strictEqual(
status.message,
"Timed out while checking Codex app-server provider status.",
);
assert.strictEqual(yield* Ref.get(killCalls), 1);
}),
);
});
describe("ProviderRegistryLive", () => {
@@ -982,7 +930,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
const missingBinary = `t3code_codex_missing_`;
const serverSettings = yield* makeMutableServerSettingsService(
decodeServerSettings(
deepMerge(encodedDefaultServerSettings, {
deepMerge(DEFAULT_SERVER_SETTINGS, {
providers: {
// Disable every built-in probe that would otherwise spawn
// on the CI host. `enabled: false` short-circuits each
@@ -1081,7 +1029,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
const secondMissing = `t3code_codex_second_`;
const serverSettings = yield* makeMutableServerSettingsService(
decodeServerSettings(
deepMerge(encodedDefaultServerSettings, {
deepMerge(DEFAULT_SERVER_SETTINGS, {
providers: {
codex: { enabled: true, binaryPath: firstMissing },
claudeAgent: { enabled: false },
@@ -1176,7 +1124,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
Effect.gen(function* () {
const serverSettings = yield* makeMutableServerSettingsService(
decodeServerSettings(
deepMerge(encodedDefaultServerSettings, {
deepMerge(DEFAULT_SERVER_SETTINGS, {
providers: {
codex: { enabled: false },
claudeAgent: { enabled: false },
@@ -1232,7 +1180,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
Effect.gen(function* () {
const serverSettings = yield* makeMutableServerSettingsService(
decodeServerSettings(
deepMerge(encodedDefaultServerSettings, {
deepMerge(DEFAULT_SERVER_SETTINGS, {
providers: {
codex: {
enabled: false,
@@ -194,7 +194,6 @@ describe("ProviderSessionReaper", () => {
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getSnapshotSequence: () =>
Effect.succeed({ snapshotSequence: input.readModel.snapshotSequence }),
getCounts: () => Effect.die("unused"),
@@ -202,7 +201,6 @@ describe("ProviderSessionReaper", () => {
getProjectShellById: () => Effect.die("unused"),
getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
getThreadCheckpointContext: () => Effect.die("unused"),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadShellById: (threadId) =>
Effect.succeed(
input.readModel.threads.find((thread) => thread.id === threadId)
@@ -0,0 +1,96 @@
import { it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import { describe, expect } from "vitest";
import { scopedSafeTeardown } from "./scopedSafeTeardown.ts";
describe("scopedSafeTeardown", () => {
it.effect("returns the body's value when teardown is clean", () =>
Effect.gen(function* () {
const finalizers: string[] = [];
const wrapped = Effect.gen(function* () {
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
finalizers.push("clean");
}),
);
return "body-ok";
}).pipe(scopedSafeTeardown("test"));
const value = yield* wrapped;
expect(value).toBe("body-ok");
expect(finalizers).toEqual(["clean"]);
}),
);
it.effect("preserves body success when a finalizer dies", () =>
// The production failure mode: `Layer.build(...)` registers a finalizer
// that kills a subprocess; if the kill fails, the defect would otherwise
// override a successful probe body.
Effect.gen(function* () {
const finalizers: string[] = [];
const wrapped = Effect.gen(function* () {
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
finalizers.push("ran-before-die");
}),
);
yield* Effect.addFinalizer(() =>
Effect.die(new Error("simulated subprocess kill failure")),
);
return "body-ok";
}).pipe(scopedSafeTeardown("test"));
const value = yield* wrapped;
expect(value).toBe("body-ok");
// The clean finalizer still ran; teardown defect was logged + swallowed.
expect(finalizers).toEqual(["ran-before-die"]);
}),
);
it.effect("preserves typed body failures even when teardown is clean", () =>
Effect.gen(function* () {
class BodyError {
readonly _tag = "BodyError" as const;
}
const wrapped = Effect.gen(function* () {
yield* Effect.addFinalizer(() => Effect.void);
return yield* Effect.fail(new BodyError());
}).pipe(scopedSafeTeardown("test"));
const exit = yield* Effect.exit(wrapped);
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isFailure(exit)) {
// Body's typed failure should surface, not a defect.
const squashed = Cause.squash(exit.cause);
expect(squashed).toBeInstanceOf(BodyError);
}
}),
);
it.effect("prefers the body's typed failure over a teardown defect", () =>
// Even when both the body fails AND teardown defects, the body's typed
// failure is what callers see. This matters because `Effect.result` /
// `.pipe(Effect.exit)` in callers expects a typed Failure, not a Die.
Effect.gen(function* () {
class BodyError {
readonly _tag = "BodyError" as const;
}
const wrapped = Effect.gen(function* () {
yield* Effect.addFinalizer(() =>
Effect.die(new Error("simulated subprocess kill failure")),
);
return yield* Effect.fail(new BodyError());
}).pipe(scopedSafeTeardown("test"));
const exit = yield* Effect.exit(wrapped);
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isFailure(exit)) {
const squashed = Cause.squash(exit.cause);
expect(squashed).toBeInstanceOf(BodyError);
}
}),
);
});
@@ -0,0 +1,63 @@
/**
* scopedSafeTeardown — run a scope-requiring effect so that finalizer
* failures during scope close cannot override the body's Exit.
*
* Motivation
* ----------
* The obvious pattern is `body.pipe(Effect.scoped)`: provide a fresh
* Scope, run the body, close the scope with the body's Exit. If a
* finalizer (e.g. `ChildProcess.kill` from an effect-codex-app-server
* spawn) dies during that close, the combined Exit becomes the
* finalizer's defect — even when the body already succeeded.
*
* Concretely this bit us in the Codex provider probe: a successful
* `initialize` → `account/read` → `skills/list` → `model/list`
* round-trip produced a `CodexAppServerProviderSnapshot`, but the
* `Layer.build(CodexClient.layerCommand(...))` finalizer then failed to
* kill the `codex app-server` subprocess with a `PlatformError`. The
* defect bubbled past `Effect.result` in `checkCodexProviderStatus`,
* died `refreshOneSource`, and `providersRef` never saw the snapshot.
*
* Strategy
* --------
* 1. Make a fresh scope manually.
* 2. Run the body against that scope, capturing its Exit via
* `Effect.exit`.
* 3. Close the scope, catching any cause (typed failure *or* defect)
* with a log.
* 4. Replay the captured Exit so typed body failures still surface and
* successes still return their value.
*
* The helper deliberately logs teardown causes at `Warning` level —
* silently swallowing them is dangerous because they usually indicate a
* real bug in a downstream Layer's finalizer.
*
* @module provider/Layers/scopedSafeTeardown
*/
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Scope from "effect/Scope";
/**
* Run `effect` with a freshly made `Scope.Scope`, guaranteeing that
* teardown failures cannot override the body's Exit.
*
* Shape matches `Effect.scoped`: takes an effect whose env includes
* `Scope.Scope`, returns one whose env excludes it.
*
* @param label Short label for the warning log emitted when teardown
* fails. Use something like `"codex-probe"`.
*/
export const scopedSafeTeardown =
(label: string) =>
<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, Exclude<R, Scope.Scope>> =>
Effect.gen(function* () {
const scope = yield* Scope.make();
const bodyExit = yield* effect.pipe(Effect.provideService(Scope.Scope, scope), Effect.exit);
yield* Scope.close(scope, Exit.void).pipe(
Effect.catchCause((cause) =>
Effect.logWarning(`${label} teardown errored; preserving body result`, cause),
),
);
return yield* bodyExit;
}) as Effect.Effect<A, E, Exclude<R, Scope.Scope>>;
@@ -0,0 +1,17 @@
import { assert, describe, it } from "@effect/vitest";
import { compareCliVersions, normalizeCliVersion } from "./cliVersion.ts";
describe("cliVersion", () => {
it("normalizes versions with a missing patch segment", () => {
assert.strictEqual(normalizeCliVersion("2.1"), "2.1.0");
});
it("compares prerelease versions before stable versions", () => {
assert.isTrue(compareCliVersions("2.1.111-beta.1", "2.1.111") < 0);
});
it("rejects malformed numeric segments", () => {
assert.isTrue(compareCliVersions("1.2.3abc", "1.2.10") > 0);
});
});
+123
View File
@@ -0,0 +1,123 @@
interface ParsedCliSemver {
readonly major: number;
readonly minor: number;
readonly patch: number;
readonly prerelease: ReadonlyArray<string>;
}
const CLI_VERSION_NUMBER_SEGMENT = /^\d+$/;
export function normalizeCliVersion(version: string): string {
const [main, prerelease] = version.trim().split("-", 2);
const segments = (main ?? "")
.split(".")
.map((segment) => segment.trim())
.filter((segment) => segment.length > 0);
if (segments.length === 2) {
segments.push("0");
}
return prerelease ? `${segments.join(".")}-${prerelease}` : segments.join(".");
}
function parseCliSemver(version: string): ParsedCliSemver | null {
const normalized = normalizeCliVersion(version);
const [main = "", prerelease] = normalized.split("-", 2);
const segments = main.split(".");
if (segments.length !== 3) {
return null;
}
const [majorSegment, minorSegment, patchSegment] = segments;
if (majorSegment === undefined || minorSegment === undefined || patchSegment === undefined) {
return null;
}
if (
!CLI_VERSION_NUMBER_SEGMENT.test(majorSegment) ||
!CLI_VERSION_NUMBER_SEGMENT.test(minorSegment) ||
!CLI_VERSION_NUMBER_SEGMENT.test(patchSegment)
) {
return null;
}
const major = Number.parseInt(majorSegment, 10);
const minor = Number.parseInt(minorSegment, 10);
const patch = Number.parseInt(patchSegment, 10);
if (![major, minor, patch].every(Number.isInteger)) {
return null;
}
return {
major,
minor,
patch,
prerelease:
prerelease
?.split(".")
.map((segment) => segment.trim())
.filter((segment) => segment.length > 0) ?? [],
};
}
function comparePrereleaseIdentifier(left: string, right: string): number {
const leftNumeric = /^\d+$/.test(left);
const rightNumeric = /^\d+$/.test(right);
if (leftNumeric && rightNumeric) {
return Number.parseInt(left, 10) - Number.parseInt(right, 10);
}
if (leftNumeric) {
return -1;
}
if (rightNumeric) {
return 1;
}
return left.localeCompare(right);
}
export function compareCliVersions(left: string, right: string): number {
const parsedLeft = parseCliSemver(left);
const parsedRight = parseCliSemver(right);
if (!parsedLeft || !parsedRight) {
return left.localeCompare(right);
}
if (parsedLeft.major !== parsedRight.major) {
return parsedLeft.major - parsedRight.major;
}
if (parsedLeft.minor !== parsedRight.minor) {
return parsedLeft.minor - parsedRight.minor;
}
if (parsedLeft.patch !== parsedRight.patch) {
return parsedLeft.patch - parsedRight.patch;
}
if (parsedLeft.prerelease.length === 0 && parsedRight.prerelease.length === 0) {
return 0;
}
if (parsedLeft.prerelease.length === 0) {
return 1;
}
if (parsedRight.prerelease.length === 0) {
return -1;
}
const length = Math.max(parsedLeft.prerelease.length, parsedRight.prerelease.length);
for (let index = 0; index < length; index += 1) {
const leftIdentifier = parsedLeft.prerelease[index];
const rightIdentifier = parsedRight.prerelease[index];
if (leftIdentifier === undefined) {
return -1;
}
if (rightIdentifier === undefined) {
return 1;
}
const comparison = comparePrereleaseIdentifier(leftIdentifier, rightIdentifier);
if (comparison !== 0) {
return comparison;
}
}
return 0;
}
+1 -7
View File
@@ -24,14 +24,13 @@ import * as P from "effect/Predicate";
import * as Ref from "effect/Ref";
import * as Result from "effect/Result";
import * as Scope from "effect/Scope";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { encodeJsonStringForDiagnostics } from "@t3tools/shared/schemaJson";
import { isWindowsCommandNotFound } from "../processRunner.ts";
import { collectStreamAsString } from "./providerSnapshot.ts";
import * as NetService from "@t3tools/shared/Net";
const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.UnknownFromJsonString);
const OPENCODE_EMPTY_CONFIG_CONTENT = "{}";
const OPENCODE_SERVER_READY_PREFIX = "opencode server listening";
@@ -58,11 +57,6 @@ export class OpenCodeRuntimeError extends Data.TaggedError(OPENCODE_RUNTIME_ERRO
P.isTagged(u, OPENCODE_RUNTIME_ERROR_TAG);
}
function encodeJsonStringForDiagnostics(input: unknown): string | undefined {
const result = encodeUnknownJsonStringExit(input);
return Exit.isSuccess(result) ? result.value : undefined;
}
export function openCodeRuntimeErrorDetail(cause: unknown): string {
if (OpenCodeRuntimeError.is(cause)) return cause.detail;
if (cause instanceof Error && cause.message.trim().length > 0) return cause.message.trim();
@@ -3,7 +3,6 @@ import {
type ServerProvider,
type ServerProviderVersionAdvisory,
} from "@t3tools/contracts";
import { compareSemverVersions } from "@t3tools/shared/semver";
import { resolveCommandPath } from "@t3tools/shared/shell";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
@@ -12,6 +11,8 @@ import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { HttpClient, HttpClientRequest } from "effect/unstable/http";
import { compareCliVersions } from "./cliVersion.ts";
const LATEST_VERSION_CACHE_TTL_MS = 60 * 60 * 1_000;
const LATEST_VERSION_TIMEOUT_MS = 4_000;
const PROVIDER_UPDATE_ACTION_TOAST_MESSAGE = "Install the update now or review provider settings.";
@@ -364,7 +365,7 @@ function deriveVersionAdvisory(input: {
if (!input.latestVersion) {
return { status: "unknown", message: null };
}
if (compareSemverVersions(input.currentVersion, input.latestVersion) < 0) {
if (compareCliVersions(input.currentVersion, input.latestVersion) < 0) {
return {
status: "behind_latest",
message: PROVIDER_UPDATE_ACTION_TOAST_MESSAGE,
+16 -112
View File
@@ -630,13 +630,6 @@ const buildAppUnderTest = (options?: {
threads: [],
updatedAt: "1970-01-01T00:00:00.000Z",
}),
getArchivedShellSnapshot: () =>
Effect.succeed({
snapshotSequence: 0,
projects: [],
threads: [],
updatedAt: "1970-01-01T00:00:00.000Z",
}),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getProjectShellById: () => Effect.succeed(Option.none()),
getThreadShellById: () => Effect.succeed(Option.none()),
@@ -802,12 +795,7 @@ const bootstrapBrowserSession = (
};
});
const bootstrapBearerSession = (
credential = defaultDesktopBootstrapToken,
options?: {
readonly headers?: Record<string, string>;
},
) =>
const bootstrapBearerSession = (credential = defaultDesktopBootstrapToken) =>
Effect.gen(function* () {
const bootstrapUrl = yield* getHttpServerUrl("/api/auth/bootstrap/bearer");
const response = yield* Effect.promise(() =>
@@ -815,7 +803,6 @@ const bootstrapBearerSession = (
method: "POST",
headers: {
"content-type": "application/json",
...options?.headers,
},
body: JSON.stringify({
credential,
@@ -891,22 +878,6 @@ const splitHeaderTokens = (value: string | null) =>
.filter((token) => token.length > 0)
.toSorted();
const assertBrowserApiCorsHeaders = (headers: Headers) => {
assert.equal(headers.get("access-control-allow-origin"), "*");
assert.deepEqual(splitHeaderTokens(headers.get("access-control-allow-methods")), [
"GET",
"OPTIONS",
"POST",
]);
assert.deepEqual(splitHeaderTokens(headers.get("access-control-allow-headers")), [
"authorization",
"b3",
"content-type",
"traceparent",
]);
};
const crossOriginClientOrigin = "http://remote-client.test:3773";
const getWsServerUrl = (
pathname = "",
options?: { authenticated?: boolean; credential?: string },
@@ -1028,28 +999,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("includes CORS headers on public environment descriptor responses", () =>
Effect.gen(function* () {
yield* buildAppUnderTest();
const url = yield* getHttpServerUrl("/.well-known/t3/environment");
const response = yield* Effect.promise(() =>
fetch(url, {
headers: {
origin: crossOriginClientOrigin,
},
}),
);
const body = (yield* Effect.promise(() =>
response.json(),
)) as typeof testEnvironmentDescriptor;
assert.equal(response.status, 200);
assertBrowserApiCorsHeaders(response.headers);
assert.deepEqual(body, testEnvironmentDescriptor);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("reports unauthenticated session state without requiring auth", () =>
Effect.gen(function* () {
yield* buildAppUnderTest();
@@ -1173,62 +1122,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("includes CORS headers on remote auth success responses", () =>
Effect.gen(function* () {
yield* buildAppUnderTest();
const origin = crossOriginClientOrigin;
const { response: bootstrapResponse, body: bootstrapBody } = yield* bootstrapBearerSession(
defaultDesktopBootstrapToken,
{
headers: { origin },
},
);
assert.equal(bootstrapResponse.status, 200);
assertBrowserApiCorsHeaders(bootstrapResponse.headers);
assert.equal(bootstrapBody.authenticated, true);
assert.equal(typeof bootstrapBody.sessionToken, "string");
const sessionUrl = yield* getHttpServerUrl("/api/auth/session");
const sessionResponse = yield* Effect.promise(() =>
fetch(sessionUrl, {
headers: {
authorization: `Bearer ${bootstrapBody.sessionToken ?? ""}`,
origin,
},
}),
);
const sessionBody = (yield* Effect.promise(() => sessionResponse.json())) as {
readonly authenticated: boolean;
readonly sessionMethod?: string;
};
assert.equal(sessionResponse.status, 200);
assertBrowserApiCorsHeaders(sessionResponse.headers);
assert.equal(sessionBody.authenticated, true);
assert.equal(sessionBody.sessionMethod, "bearer-session-token");
const wsTokenUrl = yield* getHttpServerUrl("/api/auth/ws-token");
const wsTokenResponse = yield* Effect.promise(() =>
fetch(wsTokenUrl, {
method: "POST",
headers: {
authorization: `Bearer ${bootstrapBody.sessionToken ?? ""}`,
origin,
},
}),
);
const wsTokenBody = (yield* Effect.promise(() => wsTokenResponse.json())) as {
readonly token: string;
};
assert.equal(wsTokenResponse.status, 200);
assertBrowserApiCorsHeaders(wsTokenResponse.headers);
assert.equal(typeof wsTokenBody.token, "string");
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect(
"responds to remote auth websocket-token preflight requests with authorization CORS headers",
() =>
@@ -1240,7 +1133,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
fetch(wsTokenUrl, {
method: "OPTIONS",
headers: {
origin: crossOriginClientOrigin,
origin: "http://192.168.86.35:3773",
"access-control-request-method": "POST",
"access-control-request-headers": "authorization",
},
@@ -1248,7 +1141,18 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
);
assert.equal(response.status, 204);
assertBrowserApiCorsHeaders(response.headers);
assert.equal(response.headers.get("access-control-allow-origin"), "*");
assert.deepEqual(splitHeaderTokens(response.headers.get("access-control-allow-methods")), [
"GET",
"OPTIONS",
"POST",
]);
assert.deepEqual(splitHeaderTokens(response.headers.get("access-control-allow-headers")), [
"authorization",
"b3",
"content-type",
"traceparent",
]);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
@@ -1261,7 +1165,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
fetch(wsTokenUrl, {
method: "POST",
headers: {
origin: crossOriginClientOrigin,
origin: "http://192.168.86.35:3773",
},
}),
);
@@ -1270,7 +1174,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
};
assert.equal(response.status, 401);
assertBrowserApiCorsHeaders(response.headers);
assert.equal(response.headers.get("access-control-allow-origin"), "*");
assert.equal(body.error, "Authentication required.");
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
@@ -85,7 +85,6 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getSnapshotSequence: () => Effect.die("unused"),
getCounts: () =>
Deferred.await(releaseCounts).pipe(
@@ -98,7 +97,6 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa
getProjectShellById: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
}),
@@ -141,7 +139,6 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getSnapshotSequence: () => Effect.die("unused"),
getCounts: () => Effect.die("unused"),
getActiveProjectByWorkspaceRoot: () =>
@@ -160,7 +157,6 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa
getProjectShellById: () => Effect.die("unused"),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.some(bootstrapThreadId)),
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
getThreadShellById: () => Effect.die("unused"),
getThreadDetailById: () => Effect.die("unused"),
}),
@@ -195,14 +191,12 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getSnapshotSequence: () => Effect.die("unused"),
getCounts: () => Effect.die("unused"),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getProjectShellById: () => Effect.die("unused"),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
getThreadShellById: () => Effect.die("unused"),
getThreadDetailById: () => Effect.die("unused"),
}),
-3
View File
@@ -9,7 +9,6 @@ import {
import { createModelSelection } from "@t3tools/shared/model";
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Duration from "effect/Duration";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
@@ -438,7 +437,6 @@ it.layer(NodeServices.layer)("server settings", (it) => {
serverPassword: "secret-password",
},
},
automaticGitFetchInterval: Duration.seconds(10),
});
assert.equal(next.providers.codex.binaryPath, "/opt/homebrew/bin/codex");
@@ -460,7 +458,6 @@ it.layer(NodeServices.layer)("server settings", (it) => {
serverPassword: "secret-password",
},
},
automaticGitFetchInterval: 10_000,
});
}).pipe(Effect.provide(makeServerSettingsLayer())),
);
+46 -58
View File
@@ -45,33 +45,15 @@ import * as Semaphore from "effect/Semaphore";
import { writeFileStringAtomically } from "./atomicWrite.ts";
import { ServerConfig } from "./config.ts";
import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct";
import { fromJsonStringPretty, fromLenientJson } from "@t3tools/shared/schemaJson";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
import { ServerSecretStore } from "./auth/Services/ServerSecretStore.ts";
const encodeServerSettings = Schema.encodeEffect(ServerSettings);
const encodeServerSettingsJson = Schema.encodeUnknownEffect(fromJsonStringPretty(ServerSettings));
const decodeServerSettings = Schema.decodeUnknownEffect(ServerSettings);
const decodeServerSettings = Schema.decodeEffect(ServerSettings);
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
const normalizeServerSettings = (
settings: ServerSettings,
): Effect.Effect<ServerSettings, ServerSettingsError> =>
encodeServerSettings(settings).pipe(
Effect.flatMap(decodeServerSettings),
Effect.mapError(
(cause) =>
new ServerSettingsError({
settingsPath: "<memory>",
detail: `failed to normalize server settings: ${SchemaIssue.makeFormatterDefault()(cause.issue)}`,
cause,
}),
),
);
function providerEnvironmentSecretName(input: {
readonly instanceId: string;
readonly name: string;
@@ -135,15 +117,9 @@ export class ServerSettingsService extends Context.Service<
Layer.effect(
ServerSettingsService,
Effect.gen(function* () {
const { automaticGitFetchInterval, ...overridesForMerge } = overrides;
const merged = deepMerge(DEFAULT_SERVER_SETTINGS, overridesForMerge);
const initialSettings = yield* normalizeServerSettings({
...merged,
...(automaticGitFetchInterval !== undefined
? { automaticGitFetchInterval: automaticGitFetchInterval as Duration.Duration }
: {}),
});
const currentSettingsRef = yield* Ref.make<ServerSettings>(initialSettings);
const currentSettingsRef = yield* Ref.make<ServerSettings>(
deepMerge(DEFAULT_SERVER_SETTINGS, overrides),
);
return {
start: Effect.void,
@@ -151,8 +127,18 @@ export class ServerSettingsService extends Context.Service<
getSettings: Ref.get(currentSettingsRef),
updateSettings: (patch) =>
Ref.get(currentSettingsRef).pipe(
Effect.map((currentSettings) => applyServerSettingsPatch(currentSettings, patch)),
Effect.flatMap(normalizeServerSettings),
Effect.flatMap((currentSettings) =>
decodeServerSettings(applyServerSettingsPatch(currentSettings, patch)).pipe(
Effect.mapError(
(cause) =>
new ServerSettingsError({
settingsPath: "<memory>",
detail: `failed to normalize server settings: ${SchemaIssue.makeFormatterDefault()(cause.issue)}`,
cause,
}),
),
),
),
Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)),
),
streamChanges: Stream.empty,
@@ -214,10 +200,7 @@ function fallbackTextGenerationProvider(settings: ServerSettings): ServerSetting
}
// Values under these keys are compared as a whole — never stripped field-by-field.
const ATOMIC_SETTINGS_KEYS: ReadonlySet<string> = new Set([
"automaticGitFetchInterval",
"textGenerationModelSelection",
]);
const ATOMIC_SETTINGS_KEYS: ReadonlySet<string> = new Set(["textGenerationModelSelection"]);
function stripDefaultServerSettings(current: unknown, defaults: unknown): unknown | undefined {
if (Array.isArray(current) || Array.isArray(defaults)) {
@@ -447,29 +430,25 @@ const makeServerSettings = Effect.gen(function* () {
};
});
const writeSettingsAtomically = Effect.fnUntraced(
function* (settings: ServerSettings) {
const sparseSettingsJson = yield* encodeServerSettingsJson(
stripDefaultServerSettings(settings, DEFAULT_SERVER_SETTINGS) ?? {},
);
const writeSettingsAtomically = (settings: ServerSettings) => {
const sparseSettings = stripDefaultServerSettings(settings, DEFAULT_SERVER_SETTINGS) ?? {};
return yield* writeFileStringAtomically({
filePath: settingsPath,
contents: `${sparseSettingsJson}\n`,
}).pipe(
Effect.provideService(FileSystem.FileSystem, fs),
Effect.provideService(Path.Path, pathService),
);
},
Effect.mapError(
(cause) =>
new ServerSettingsError({
settingsPath,
detail: "failed to write settings file",
cause,
}),
),
);
return writeFileStringAtomically({
filePath: settingsPath,
contents: `${JSON.stringify(sparseSettings, null, 2)}\n`,
}).pipe(
Effect.provideService(FileSystem.FileSystem, fs),
Effect.provideService(Path.Path, pathService),
Effect.mapError(
(cause) =>
new ServerSettingsError({
settingsPath,
detail: "failed to write settings file",
cause,
}),
),
);
};
const revalidateAndEmit = writeSemaphore.withPermits(1)(
Effect.gen(function* () {
@@ -554,7 +533,16 @@ const makeServerSettings = Effect.gen(function* () {
current,
applyServerSettingsPatch(current, patch),
);
const next = yield* normalizeServerSettings(nextPersisted);
const next = yield* decodeServerSettings(nextPersisted).pipe(
Effect.mapError(
(cause) =>
new ServerSettingsError({
settingsPath: "<memory>",
detail: `failed to normalize server settings: ${SchemaIssue.makeFormatterDefault()(cause.issue)}`,
cause,
}),
),
);
yield* writeSettingsAtomically(next);
yield* Cache.set(settingsCache, cacheKey, next);
yield* emitChange(next);
@@ -100,7 +100,7 @@ export const layer = Layer.effect(
cwd: config.cwd,
timeoutMs: 5_000,
maxOutputBytes: 8_000,
appendTruncationMarker: true,
truncateOutputAtMaxBytes: true,
})
.pipe(
Effect.map(
@@ -139,7 +139,7 @@ function probeCli(input: {
cwd: input.cwd,
timeoutMs: 5_000,
maxOutputBytes: 8_000,
appendTruncationMarker: true,
truncateOutputAtMaxBytes: true,
})
.pipe(
Effect.map(
@@ -216,7 +216,7 @@ export function probeSourceControlProvider(input: {
allowNonZeroExit: true,
timeoutMs: 5_000,
maxOutputBytes: 8_000,
appendTruncationMarker: true,
truncateOutputAtMaxBytes: true,
})
.pipe(
Effect.map(
@@ -8,7 +8,7 @@ export interface CollectedUint8StreamText {
}
interface CollectState {
chunks: Uint8Array[];
readonly text: string;
readonly bytes: number;
readonly truncated: boolean;
}
@@ -18,21 +18,18 @@ export const collectUint8StreamText = <E>(input: {
readonly maxBytes?: number | undefined;
readonly truncatedMarker?: string | null | undefined;
}): Effect.Effect<CollectedUint8StreamText, E> => {
const decoder = new TextDecoder();
const maxBytes = input.maxBytes ?? Number.POSITIVE_INFINITY;
const truncatedMarker = input.truncatedMarker ?? "";
return input.stream.pipe(
Stream.runFold(
(): CollectState => ({
chunks: [],
text: "",
bytes: 0,
truncated: false,
}),
(state, chunk): CollectState => {
/*
* keep draining after truncation so the child process can exit normally.
* its a know issue that on windows killing after the output cap can force an expensive taskkill operation and hurt performance
*/
if (state.truncated) {
return state;
}
@@ -41,30 +38,30 @@ export const collectUint8StreamText = <E>(input: {
if (remainingBytes <= 0) {
return {
...state,
text: `${state.text}${truncatedMarker}`,
truncated: true,
};
}
const nextChunk =
chunk.byteLength > remainingBytes ? chunk.slice(0, remainingBytes) : chunk;
state.chunks.push(nextChunk);
const text = `${state.text}${decoder.decode(nextChunk, { stream: true })}`;
const bytes = state.bytes + nextChunk.byteLength;
const truncated = chunk.byteLength > remainingBytes;
return {
chunks: state.chunks,
text: truncated ? `${text}${truncatedMarker}` : text,
bytes,
truncated,
};
},
),
Effect.map((state): CollectedUint8StreamText => {
const text = Buffer.concat(state.chunks, state.bytes).toString("utf8");
return {
text: state.truncated && truncatedMarker.length > 0 ? `${text}${truncatedMarker}` : text,
Effect.map(
(state): CollectedUint8StreamText => ({
text: state.truncated ? state.text : `${state.text}${decoder.decode()}`,
bytes: state.bytes,
truncated: state.truncated,
};
}),
}),
),
);
};
+60 -149
View File
@@ -6,24 +6,21 @@ import {
type TerminalOpenInput,
type TerminalRestartInput,
} from "@t3tools/contracts";
import * as Data from "effect/Data";
import * as Cause from "effect/Cause";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Ref from "effect/Ref";
import * as Schedule from "effect/Schedule";
import * as Scope from "effect/Scope";
import { TestClock } from "effect/testing";
import * as TestClock from "effect/testing/TestClock";
import { expect } from "vitest";
import * as ProcessRunner from "../../processRunner.ts";
import type { TerminalManagerShape } from "../Services/Manager.ts";
import {
type PtyAdapterShape,
@@ -34,10 +31,6 @@ import {
} from "../Services/PTY.ts";
import { makeTerminalManagerWithOptions } from "./Manager.ts";
class WaitForConditionError extends Data.TaggedError("WaitForConditionError")<{
readonly message: string;
}> {}
class FakePtyProcess implements PtyProcess {
readonly writes: string[] = [];
readonly resizeCalls: Array<{ cols: number; rows: number }> = [];
@@ -134,21 +127,11 @@ class FakePtyAdapter implements PtyAdapterShape {
const waitFor = <E, R>(
predicate: Effect.Effect<boolean, E, R>,
timeout: Duration.Input = 800,
): Effect.Effect<void, WaitForConditionError | E, R> =>
): Effect.Effect<void, E | Cause.TimeoutError, R> =>
predicate.pipe(
Effect.filterOrFail(
(done) => done,
() => new WaitForConditionError({ message: "Condition not met" }),
),
Effect.filter((done) => done),
Effect.retry(Schedule.spaced("15 millis")),
Effect.timeoutOption(timeout),
Effect.flatMap((result) =>
Option.match(result, {
onNone: () =>
Effect.fail(new WaitForConditionError({ message: "Timed out waiting for condition" })),
onSome: () => Effect.void,
}),
),
Effect.timeout(timeout),
);
function openInput(overrides: Partial<TerminalOpenInput> = {}): TerminalOpenInput {
@@ -173,27 +156,33 @@ function restartInput(overrides: Partial<TerminalRestartInput> = {}): TerminalRe
};
}
const historyLogPath = (logsDir: string, threadId = "thread-1") =>
Effect.service(Path.Path).pipe(
Effect.map(({ join }) => join(logsDir, `terminal_${Encoding.encodeBase64Url(threadId)}.log`)),
);
function historyLogName(threadId: string): string {
return `terminal_${Encoding.encodeBase64Url(threadId)}.log`;
}
const multiTerminalHistoryLogPath = (
function multiTerminalHistoryLogName(threadId: string, terminalId: string): string {
const threadPart = `terminal_${Encoding.encodeBase64Url(threadId)}`;
if (terminalId === DEFAULT_TERMINAL_ID) {
return `${threadPart}.log`;
}
return `${threadPart}_${Encoding.encodeBase64Url(terminalId)}.log`;
}
function historyLogPath(logsDir: string, threadId = "thread-1"): string {
return joinPath(logsDir, historyLogName(threadId));
}
function multiTerminalHistoryLogPath(
logsDir: string,
threadId = "thread-1",
terminalId = DEFAULT_TERMINAL_ID,
) =>
Effect.service(Path.Path).pipe(
Effect.map(({ join }) => {
const threadPart = `terminal_${Encoding.encodeBase64Url(threadId)}`;
return join(
logsDir,
terminalId === DEFAULT_TERMINAL_ID
? `${threadPart}.log`
: `${threadPart}_${Encoding.encodeBase64Url(terminalId)}.log`,
);
}),
);
terminalId = "default",
): string {
return joinPath(logsDir, multiTerminalHistoryLogName(threadId, terminalId));
}
function joinPath(...segments: ReadonlyArray<string>): string {
return segments.join("/");
}
interface CreateManagerOptions {
shellResolver?: () => string;
@@ -220,13 +209,13 @@ const createManager = (
): Effect.Effect<
ManagerFixture,
PlatformError.PlatformError,
FileSystem.FileSystem | Path.Path | Scope.Scope | ProcessRunner.ProcessRunner
FileSystem.FileSystem | Path.Path | Scope.Scope
> =>
Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) =>
Effect.gen(function* () {
const { join } = yield* Path.Path;
const pathService = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-terminal-" });
const logsDir = join(baseDir, "userdata", "logs", "terminals");
const logsDir = pathService.join(baseDir, "userdata", "logs", "terminals");
const ptyAdapter = options.ptyAdapter ?? new FakePtyAdapter();
const manager = yield* makeTerminalManagerWithOptions({
@@ -257,7 +246,6 @@ const createManager = (
return {
baseDir,
logsDir,
join,
ptyAdapter,
manager,
getEvents: Ref.get(eventsRef),
@@ -265,12 +253,7 @@ const createManager = (
}),
);
it.layer(
Layer.merge(NodeServices.layer, ProcessRunner.layer.pipe(Layer.provide(NodeServices.layer))),
{ excludeTestServices: true },
)("TerminalManager", (it) => {
const itEffectSkipOnWindows = process.platform === "win32" ? it.effect.skip : it.effect;
it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (it) => {
it.effect("spawns lazily and reuses running terminal per thread", () =>
Effect.gen(function* () {
const { manager, ptyAdapter } = yield* createManager();
@@ -307,13 +290,13 @@ it.layer(
fs.writeFileString(filePath, contents),
);
itEffectSkipOnWindows("preserves non-notFound cwd stat failures", () =>
it.effect("preserves non-notFound cwd stat failures", () =>
Effect.gen(function* () {
const path = yield* Path.Path;
if (process.platform === "win32") return;
const { manager, baseDir } = yield* createManager();
const blockedRoot = path.join(baseDir, "blocked-root");
const blockedCwd = path.join(blockedRoot, "cwd");
const blockedRoot = joinPath(baseDir, "blocked-root");
const blockedCwd = joinPath(blockedRoot, "cwd");
yield* makeDirectory(blockedCwd);
yield* chmod(blockedRoot, 0o000);
@@ -407,27 +390,15 @@ it.layer(
it.effect("clears transcript and emits cleared event", () =>
Effect.gen(function* () {
const { manager, ptyAdapter, logsDir, getEvents } = yield* createManager();
const path = yield* Path.Path;
yield* manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
process.emitData("hello\n");
yield* waitFor(
historyLogPath(logsDir).pipe(
Effect.provideService(Path.Path, path),
Effect.flatMap(pathExists),
),
);
yield* waitFor(pathExists(historyLogPath(logsDir)));
yield* manager.clear({ threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID });
yield* waitFor(
historyLogPath(logsDir).pipe(
Effect.provideService(Path.Path, path),
Effect.flatMap(readFileString),
Effect.map((text) => text === ""),
),
);
yield* waitFor(Effect.map(readFileString(historyLogPath(logsDir)), (text) => text === ""));
const events = yield* getEvents;
expect(events.some((event) => event.type === "cleared")).toBe(true);
@@ -450,34 +421,21 @@ it.layer(
expect(firstProcess).toBeDefined();
if (!firstProcess) return;
firstProcess.emitData("before restart\n");
const path = yield* Path.Path;
yield* waitFor(
historyLogPath(logsDir).pipe(
Effect.provideService(Path.Path, path),
Effect.flatMap(pathExists),
),
);
yield* waitFor(pathExists(historyLogPath(logsDir)));
const snapshot = yield* manager.restart(restartInput());
assert.equal(snapshot.history, "");
assert.equal(snapshot.status, "running");
expect(ptyAdapter.spawnInputs).toHaveLength(2);
yield* waitFor(
historyLogPath(logsDir).pipe(
Effect.provideService(Path.Path, path),
Effect.flatMap(readFileString),
Effect.map((text) => text === ""),
),
);
yield* waitFor(Effect.map(readFileString(historyLogPath(logsDir)), (text) => text === ""));
}),
);
it.effect("propagates explicit worktree metadata through snapshots and lifecycle events", () =>
Effect.gen(function* () {
const { manager, getEvents, baseDir } = yield* createManager();
const path = yield* Path.Path;
const firstWorktreePath = path.join(baseDir, "worktrees", "feature-a");
const secondWorktreePath = path.join(baseDir, "worktrees", "feature-b");
const firstWorktreePath = joinPath(baseDir, "worktrees", "feature-a");
const secondWorktreePath = joinPath(baseDir, "worktrees", "feature-b");
yield* makeDirectory(firstWorktreePath);
yield* makeDirectory(secondWorktreePath);
const startedSnapshot = yield* manager.open(
@@ -513,8 +471,7 @@ it.layer(
it.effect("preserves worktree metadata when reopening an exited session", () =>
Effect.gen(function* () {
const { manager, ptyAdapter, getEvents, baseDir } = yield* createManager();
const path = yield* Path.Path;
const worktreePath = path.join(baseDir, "worktrees", "feature-a");
const worktreePath = joinPath(baseDir, "worktrees", "feature-a");
yield* makeDirectory(worktreePath);
yield* manager.open(
@@ -556,18 +513,12 @@ it.layer(
it.effect("emits exited event and reopens with clean transcript after exit", () =>
Effect.gen(function* () {
const { manager, ptyAdapter, logsDir, getEvents } = yield* createManager();
const path = yield* Path.Path;
yield* manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
process.emitData("old data\n");
yield* waitFor(
historyLogPath(logsDir).pipe(
Effect.provideService(Path.Path, path),
Effect.flatMap(pathExists),
),
);
yield* waitFor(pathExists(historyLogPath(logsDir)));
process.emitExit({ exitCode: 0, signal: 0 });
yield* waitFor(
@@ -577,12 +528,7 @@ it.layer(
assert.equal(reopened.history, "");
expect(ptyAdapter.spawnInputs).toHaveLength(2);
expect(
yield* historyLogPath(logsDir).pipe(
Effect.provideService(Path.Path, path),
Effect.flatMap(readFileString),
),
).toBe("");
expect(yield* readFileString(historyLogPath(logsDir))).toBe("");
}),
);
@@ -769,21 +715,10 @@ it.layer(
expect(process).toBeDefined();
if (!process) return;
process.emitData("bye\n");
const path = yield* Path.Path;
yield* waitFor(
historyLogPath(logsDir).pipe(
Effect.provideService(Path.Path, path),
Effect.flatMap(pathExists),
),
);
yield* waitFor(pathExists(historyLogPath(logsDir)));
yield* manager.close({ threadId: "thread-1", deleteHistory: true });
expect(
yield* historyLogPath(logsDir).pipe(
Effect.provideService(Path.Path, path),
Effect.flatMap(pathExists),
),
).toBe(false);
expect(yield* pathExists(historyLogPath(logsDir))).toBe(false);
}),
);
@@ -800,36 +735,19 @@ it.layer(
defaultProcess.emitData("default\n");
sidecarProcess.emitData("sidecar\n");
const path = yield* Path.Path;
yield* waitFor(
multiTerminalHistoryLogPath(logsDir, "thread-1", "default").pipe(
Effect.provideService(Path.Path, path),
Effect.flatMap(pathExists),
),
);
yield* waitFor(
multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar").pipe(
Effect.provideService(Path.Path, path),
Effect.flatMap(pathExists),
),
);
yield* waitFor(pathExists(multiTerminalHistoryLogPath(logsDir, "thread-1", "default")));
yield* waitFor(pathExists(multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar")));
yield* manager.close({ threadId: "thread-1", deleteHistory: true });
assert.equal(defaultProcess.killed, true);
assert.equal(sidecarProcess.killed, true);
expect(
yield* multiTerminalHistoryLogPath(logsDir, "thread-1", "default").pipe(
Effect.provideService(Path.Path, path),
Effect.flatMap(pathExists),
),
).toBe(false);
expect(
yield* multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar").pipe(
Effect.provideService(Path.Path, path),
Effect.flatMap(pathExists),
),
).toBe(false);
expect(yield* pathExists(multiTerminalHistoryLogPath(logsDir, "thread-1", "default"))).toBe(
false,
);
expect(yield* pathExists(multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar"))).toBe(
false,
);
}),
);
@@ -868,13 +786,7 @@ it.layer(
first.emitData("first-history\n");
second.emitData("second-history\n");
const path = yield* Path.Path;
yield* waitFor(
historyLogPath(logsDir, "thread-1").pipe(
Effect.provideService(Path.Path, path),
Effect.flatMap(pathExists),
),
);
yield* waitFor(pathExists(historyLogPath(logsDir, "thread-1")));
first.emitExit({ exitCode: 0, signal: 0 });
yield* Effect.sleep(Duration.millis(5));
second.emitExit({ exitCode: 0, signal: 0 });
@@ -897,9 +809,8 @@ it.layer(
it.effect("migrates legacy transcript filenames to terminal-scoped history path on open", () =>
Effect.gen(function* () {
const { manager, logsDir } = yield* createManager();
const path = yield* Path.Path;
const legacyPath = path.join(logsDir, "thread-1.log");
const nextPath = yield* historyLogPath(logsDir);
const legacyPath = joinPath(logsDir, "thread-1.log");
const nextPath = historyLogPath(logsDir);
yield* writeFileString(legacyPath, "legacy-line\n");
const snapshot = yield* manager.open(openInput());
+77 -113
View File
@@ -5,13 +5,13 @@ import {
type TerminalSessionStatus,
} from "@t3tools/contracts";
import { makeKeyedCoalescingWorker } from "@t3tools/shared/KeyedCoalescingWorker";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as Equal from "effect/Equal";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as DateTime from "effect/DateTime";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
@@ -26,7 +26,7 @@ import {
terminalRestartsTotal,
terminalSessionsTotal,
} from "../../observability/Metrics.ts";
import * as ProcessRunner from "../../processRunner.ts";
import { runProcess } from "../../processRunner.ts";
import {
TerminalCwdError,
TerminalHistoryError,
@@ -51,7 +51,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 nowIso = Effect.map(DateTime.now, DateTime.formatIso);
class TerminalSubprocessCheckError extends Schema.TaggedErrorClass<TerminalSubprocessCheckError>()(
"TerminalSubprocessCheckError",
@@ -73,9 +72,7 @@ class TerminalProcessSignalError extends Schema.TaggedErrorClass<TerminalProcess
) {}
interface TerminalSubprocessChecker {
(
terminalPid: number,
): Effect.Effect<boolean, TerminalSubprocessCheckError, ProcessRunner.ProcessRunner>;
(terminalPid: number): Effect.Effect<boolean, TerminalSubprocessCheckError>;
}
interface ShellCandidate {
@@ -214,23 +211,17 @@ function normalizeShellCommand(
return firstToken.replace(/^['"]|['"]$/g, "");
}
function basenameForPlatform(command: string, platform: NodeJS.Platform): string {
const normalized =
platform === "win32" ? command.replaceAll("/", "\\") : command.replaceAll("\\", "/");
const parts = normalized
.split(platform === "win32" ? /\\+/ : /\/+/)
.filter((part) => part.length > 0);
return parts.at(-1) ?? normalized;
function basename(command: string, platform: NodeJS.Platform): string {
const normalized = platform === "win32" ? command.replaceAll("/", "\\") : command;
const separator = platform === "win32" ? "\\" : "/";
return normalized.slice(normalized.lastIndexOf(separator) + 1);
}
function joinWindowsPath(...parts: ReadonlyArray<string>): string {
return parts
.map((part, index) => {
if (index === 0) return part.replace(/[\\/]+$/g, "");
return part.replace(/^[\\/]+|[\\/]+$/g, "");
})
.filter((part) => part.length > 0)
.join("\\");
function joinWindowsPath(...segments: ReadonlyArray<string>): string {
return segments
.filter((segment) => segment.length > 0)
.join("\\")
.replace(/\\+/g, "\\");
}
function shellCandidateFromCommand(
@@ -238,7 +229,7 @@ function shellCandidateFromCommand(
platform: NodeJS.Platform = process.platform,
): ShellCandidate | null {
if (!command || command.length === 0) return null;
const shellName = basenameForPlatform(command, platform).toLowerCase();
const shellName = basename(command, platform).toLowerCase();
if (platform === "win32" && (shellName === "pwsh.exe" || shellName === "powershell.exe")) {
return { shell: command, args: ["-NoLogo"] };
}
@@ -366,82 +357,66 @@ function isRetryableShellSpawnError(error: PtySpawnError): boolean {
function checkWindowsSubprocessActivity(
terminalPid: number,
): Effect.Effect<boolean, TerminalSubprocessCheckError, ProcessRunner.ProcessRunner> {
): Effect.Effect<boolean, TerminalSubprocessCheckError> {
const command = [
`$children = Get-CimInstance Win32_Process -Filter "ParentProcessId = ${terminalPid}" -ErrorAction SilentlyContinue`,
"if ($children) { exit 0 }",
"exit 1",
].join("; ");
return Effect.gen(function* () {
const processRunner = yield* ProcessRunner.ProcessRunner;
return yield* processRunner.run({
command: "powershell.exe",
args: ["-NoProfile", "-NonInteractive", "-Command", command],
timeout: "1500 millis",
maxOutputBytes: 32_768,
outputMode: "truncate",
shell: process.platform === "win32",
timeoutBehavior: "timedOutResult",
});
}).pipe(
Effect.map((result) => result.code === 0),
Effect.mapError(
(cause) =>
new TerminalSubprocessCheckError({
message: "Failed to check Windows terminal subprocess activity.",
cause,
terminalPid,
command: "powershell",
}),
),
);
return Effect.tryPromise({
try: () =>
runProcess("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", command], {
timeoutMs: 1_500,
allowNonZeroExit: true,
maxBufferBytes: 32_768,
outputMode: "truncate",
}),
catch: (cause) =>
new TerminalSubprocessCheckError({
message: "Failed to check Windows terminal subprocess activity.",
cause,
terminalPid,
command: "powershell",
}),
}).pipe(Effect.map((result) => result.code === 0));
}
const checkPosixSubprocessActivity = Effect.fn("terminal.checkPosixSubprocessActivity")(function* (
terminalPid: number,
): Effect.fn.Return<boolean, TerminalSubprocessCheckError, ProcessRunner.ProcessRunner> {
const processRunner = yield* ProcessRunner.ProcessRunner;
const runPgrep = processRunner
.run({
command: "pgrep",
args: ["-P", String(terminalPid)],
timeout: "1 second",
maxOutputBytes: 32_768,
outputMode: "truncate",
timeoutBehavior: "timedOutResult",
})
.pipe(
Effect.mapError(
(cause) =>
new TerminalSubprocessCheckError({
message: "Failed to inspect terminal subprocesses with pgrep.",
cause,
terminalPid,
command: "pgrep",
}),
),
);
): Effect.fn.Return<boolean, TerminalSubprocessCheckError> {
const runPgrep = Effect.tryPromise({
try: () =>
runProcess("pgrep", ["-P", String(terminalPid)], {
timeoutMs: 1_000,
allowNonZeroExit: true,
maxBufferBytes: 32_768,
outputMode: "truncate",
}),
catch: (cause) =>
new TerminalSubprocessCheckError({
message: "Failed to inspect terminal subprocesses with pgrep.",
cause,
terminalPid,
command: "pgrep",
}),
});
const runPs = processRunner
.run({
command: "ps",
args: ["-eo", "pid=,ppid="],
timeout: "1 second",
maxOutputBytes: 262_144,
outputMode: "truncate",
timeoutBehavior: "timedOutResult",
})
.pipe(
Effect.mapError(
(cause) =>
new TerminalSubprocessCheckError({
message: "Failed to inspect terminal subprocesses with ps.",
cause,
terminalPid,
command: "ps",
}),
),
);
const runPs = Effect.tryPromise({
try: () =>
runProcess("ps", ["-eo", "pid=,ppid="], {
timeoutMs: 1_000,
allowNonZeroExit: true,
maxBufferBytes: 262_144,
outputMode: "truncate",
}),
catch: (cause) =>
new TerminalSubprocessCheckError({
message: "Failed to inspect terminal subprocesses with ps.",
cause,
terminalPid,
command: "ps",
}),
});
const pgrepResult = yield* Effect.exit(runPgrep);
if (pgrepResult._tag === "Success") {
@@ -472,7 +447,7 @@ const checkPosixSubprocessActivity = Effect.fn("terminal.checkPosixSubprocessAct
const defaultSubprocessChecker = Effect.fn("terminal.defaultSubprocessChecker")(function* (
terminalPid: number,
): Effect.fn.Return<boolean, TerminalSubprocessCheckError, ProcessRunner.ProcessRunner> {
): Effect.fn.Return<boolean, TerminalSubprocessCheckError> {
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
return false;
}
@@ -750,19 +725,14 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
const path = yield* Path.Path;
const context = yield* Effect.context<never>();
const runFork = Effect.runForkWith(context);
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
const logsDir = options.logsDir;
const historyLineLimit = options.historyLineLimit ?? DEFAULT_HISTORY_LINE_LIMIT;
const platform = options.platform ?? process.platform;
const baseEnv = options.env ?? process.env;
const shellResolver = options.shellResolver ?? (() => defaultShellResolver(platform, baseEnv));
const processRunner = yield* ProcessRunner.ProcessRunner;
const subprocessChecker =
options.subprocessChecker ??
((terminalPid) =>
defaultSubprocessChecker(terminalPid).pipe(
Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
));
const subprocessChecker = options.subprocessChecker ?? defaultSubprocessChecker;
const subprocessPollIntervalMs =
options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS;
const processKillGraceMs = options.processKillGraceMs ?? DEFAULT_PROCESS_KILL_GRACE_MS;
@@ -1449,23 +1419,22 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
runFork(drainProcessEvents(session, processPid));
});
const runningAt = yield* nowIso;
const startedAt = yield* nowIso;
yield* modifyManagerState((state) => {
session.process = ptyProcess;
session.pid = processPid;
session.status = "running";
session.updatedAt = runningAt;
session.updatedAt = startedAt;
session.unsubscribeData = unsubscribeData;
session.unsubscribeExit = unsubscribeExit;
return [undefined, state] as const;
});
const createdAt = yield* nowIso;
yield* publishEvent({
type: eventType,
threadId: session.threadId,
terminalId: session.terminalId,
createdAt,
createdAt: startedAt,
snapshot: snapshot(session),
});
}),
@@ -1482,8 +1451,8 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
if (ptyProcess) {
yield* startKillEscalation(ptyProcess, session.threadId, session.terminalId);
}
const erroredAt = yield* nowIso;
const failedAt = yield* nowIso;
yield* modifyManagerState((state) => {
session.status = "error";
session.pid = null;
@@ -1494,19 +1463,18 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
session.pendingProcessEvents = [];
session.pendingProcessEventIndex = 0;
session.processEventDrainRunning = false;
session.updatedAt = erroredAt;
session.updatedAt = failedAt;
return [undefined, state] as const;
});
yield* evictInactiveSessionsIfNeeded();
const message = error.message;
const createdAt = yield* nowIso;
yield* publishEvent({
type: "error",
threadId: session.threadId,
terminalId: session.terminalId,
createdAt,
createdAt: failedAt,
message,
});
yield* Effect.logError("failed to start terminal", {
@@ -1579,7 +1547,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
}
const updatedAt = yield* nowIso;
const createdAt = yield* nowIso;
const event = yield* modifyManagerState((state) => {
const liveSession: Option.Option<TerminalSessionState> = Option.fromNullishOr(
state.sessions.get(toSessionKey(session.threadId, session.terminalId)),
@@ -1601,7 +1568,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
type: "activity" as const,
threadId: liveSession.value.threadId,
terminalId: liveSession.value.terminalId,
createdAt,
createdAt: updatedAt,
hasRunningSubprocess: hasRunningSubprocess.value,
}),
state,
@@ -1830,20 +1797,19 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
Effect.gen(function* () {
const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID;
const session = yield* requireSession(input.threadId, terminalId);
const updatedAt = yield* nowIso;
session.history = "";
session.pendingHistoryControlSequence = "";
session.pendingProcessEvents = [];
session.pendingProcessEventIndex = 0;
session.processEventDrainRunning = false;
session.updatedAt = updatedAt;
const clearedAt = yield* nowIso;
session.updatedAt = clearedAt;
yield* persistHistory(input.threadId, terminalId, session.history);
const createdAt = yield* nowIso;
yield* publishEvent({
type: "cleared",
threadId: input.threadId,
terminalId,
createdAt,
createdAt: clearedAt,
});
}),
);
@@ -1967,6 +1933,4 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
},
);
export const TerminalManagerLive = Layer.effect(TerminalManager, makeTerminalManager()).pipe(
Layer.provide(ProcessRunner.layer),
);
export const TerminalManagerLive = Layer.effect(TerminalManager, makeTerminalManager());
@@ -6,7 +6,6 @@ import { ChildProcessSpawner } from "effect/unstable/process";
import { type CursorSettings, type ModelSelection } from "@t3tools/contracts";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { extractJsonObject } from "@t3tools/shared/schemaJson";
import { TextGenerationError } from "@t3tools/contracts";
import { type ThreadTitleGenerationResult, type TextGenerationShape } from "./TextGeneration.ts";
@@ -17,6 +16,7 @@ import {
buildThreadTitlePrompt,
} from "./TextGenerationPrompts.ts";
import {
extractJsonObject,
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
@@ -13,7 +13,6 @@ import {
} from "@t3tools/contracts";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
import { extractJsonObject } from "@t3tools/shared/schemaJson";
import { ServerConfig } from "../config.ts";
import { resolveAttachmentPath } from "../attachmentStore.ts";
@@ -25,6 +24,7 @@ import {
} from "./TextGenerationPrompts.ts";
import { type TextGenerationShape } from "./TextGeneration.ts";
import {
extractJsonObject,
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
@@ -1,6 +1,6 @@
import { TextGenerationError } from "@t3tools/contracts";
import * as Schema from "effect/Schema";
import { TextGenerationError } from "@t3tools/contracts";
const isTextGenerationError = Schema.is(TextGenerationError);
/** Convert an Effect Schema to a flat JSON Schema object, inlining `$defs` when present. */
@@ -19,6 +19,54 @@ export function limitSection(value: string, maxChars: number): string {
return `${truncated}\n\n[truncated]`;
}
export function extractJsonObject(raw: string): string {
const trimmed = raw.trim();
if (trimmed.length === 0) {
return trimmed;
}
const start = trimmed.indexOf("{");
if (start < 0) {
return trimmed;
}
let depth = 0;
let inString = false;
let escaping = false;
for (let index = start; index < trimmed.length; index += 1) {
const char = trimmed[index];
if (inString) {
if (escaping) {
escaping = false;
} else if (char === "\\") {
escaping = true;
} else if (char === '"') {
inString = false;
}
continue;
}
if (char === '"') {
inString = true;
continue;
}
if (char === "{") {
depth += 1;
continue;
}
if (char === "}") {
depth -= 1;
if (depth === 0) {
return trimmed.slice(start, index + 1);
}
}
}
return trimmed.slice(start);
}
/** Normalise a raw commit subject to imperative-mood, ≤72 chars, no trailing period. */
export function sanitizeCommitSubject(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
+13 -20
View File
@@ -67,7 +67,6 @@ runVcsDriverContractSuite<GitVcsDriver.GitVcsDriver, GitContractError>({
it.effect("GitVcsDriver forwards execute env to the VCS process", () => {
let observedEnv: NodeJS.ProcessEnv | undefined;
let observedAppendTruncationMarker: boolean | undefined;
return Effect.gen(function* () {
const driver = yield* GitVcsDriver.makeVcsDriverShape();
@@ -79,32 +78,26 @@ it.effect("GitVcsDriver forwards execute env to the VCS process", () => {
env: {
GIT_INDEX_FILE: "/tmp/t3-index",
},
appendTruncationMarker: true,
});
assert.deepStrictEqual(observedEnv, {
GIT_INDEX_FILE: "/tmp/t3-index",
});
assert.strictEqual(observedAppendTruncationMarker, true);
}).pipe(
Effect.provide(
Layer.mergeAll(
NodeServices.layer,
Layer.mock(VcsProcess.VcsProcess)({
run: (input) =>
Effect.sync(() => {
observedEnv = input.env;
observedAppendTruncationMarker = input.appendTruncationMarker;
return {
exitCode: ChildProcessSpawner.ExitCode(0),
stdout: "",
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
};
}),
}),
),
Layer.mock(VcsProcess.VcsProcess)({
run: (input) =>
Effect.sync(() => {
observedEnv = input.env;
return {
exitCode: ChildProcessSpawner.ExitCode(0),
stdout: "",
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
};
}),
}),
),
);
});
+22 -288
View File
@@ -1,12 +1,8 @@
import { randomUUID } from "node:crypto";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import { ChildProcessSpawner } from "effect/unstable/process";
import {
@@ -39,7 +35,7 @@ export interface ExecuteGitInput {
readonly allowNonZeroExit?: boolean;
readonly timeoutMs?: number;
readonly maxOutputBytes?: number;
readonly appendTruncationMarker?: boolean;
readonly truncateOutputAtMaxBytes?: boolean;
readonly progress?: ExecuteGitProgress;
}
@@ -222,7 +218,6 @@ export class GitVcsDriver extends Context.Service<GitVcsDriver, GitVcsDriverShap
const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
const CHECKPOINT_DIFF_MAX_OUTPUT_BYTES = 10_000_000;
const WORKSPACE_GIT_HARDENED_CONFIG_ARGS = [
"-c",
"core.fsmonitor=false",
@@ -323,15 +318,14 @@ const gitCommand = (
readonly allowNonZeroExit?: boolean;
readonly timeoutMs?: number;
readonly maxOutputBytes?: number;
readonly appendTruncationMarker?: boolean;
readonly truncateOutputAtMaxBytes?: boolean;
},
) =>
process.run({
operation,
command: "git",
args: ["-C", cwd, ...args],
args,
cwd,
spawnCwd: globalThis.process.cwd(),
...(options?.stdin !== undefined ? { stdin: options.stdin } : {}),
...(options?.env !== undefined ? { env: options.env } : {}),
...(options?.allowNonZeroExit !== undefined
@@ -339,15 +333,13 @@ const gitCommand = (
: {}),
...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
...(options?.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}),
...(options?.appendTruncationMarker !== undefined
? { appendTruncationMarker: options.appendTruncationMarker }
...(options?.truncateOutputAtMaxBytes !== undefined
? { truncateOutputAtMaxBytes: options.truncateOutputAtMaxBytes }
: {}),
});
export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const vcsProcess = yield* VcsProcess.VcsProcess;
const process = yield* VcsProcess.VcsProcess;
const capabilities = {
kind: "git" as const,
supportsWorktrees: true,
@@ -359,7 +351,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
const isInsideWorkTree: VcsDriver.VcsDriverShape["isInsideWorkTree"] = (cwd) =>
gitCommand(
vcsProcess,
process,
"GitVcsDriver.isInsideWorkTree",
cwd,
["rev-parse", "--is-inside-work-tree"],
@@ -371,14 +363,14 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
).pipe(Effect.map((result) => result.exitCode === 0 && result.stdout.trim() === "true"));
const execute: VcsDriver.VcsDriverShape["execute"] = (input) =>
gitCommand(vcsProcess, input.operation, input.cwd, input.args, {
gitCommand(process, input.operation, input.cwd, input.args, {
...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
...(input.env !== undefined ? { env: input.env } : {}),
...(input.allowNonZeroExit !== undefined ? { allowNonZeroExit: input.allowNonZeroExit } : {}),
...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}),
...(input.appendTruncationMarker !== undefined
? { appendTruncationMarker: input.appendTruncationMarker }
...(input.truncateOutputAtMaxBytes !== undefined
? { truncateOutputAtMaxBytes: input.truncateOutputAtMaxBytes }
: {}),
});
@@ -389,12 +381,12 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
return null;
}
const root = yield* gitCommand(vcsProcess, "GitVcsDriver.detectRepository.root", cwd, [
const root = yield* gitCommand(process, "GitVcsDriver.detectRepository.root", cwd, [
"rev-parse",
"--show-toplevel",
]);
const gitCommonDir = yield* gitCommand(
vcsProcess,
process,
"GitVcsDriver.detectRepository.commonDir",
cwd,
["rev-parse", "--git-common-dir"],
@@ -410,7 +402,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
const listWorkspaceFiles: VcsDriver.VcsDriverShape["listWorkspaceFiles"] = (cwd) =>
gitCommand(
vcsProcess,
process,
"GitVcsDriver.listWorkspaceFiles",
cwd,
[
@@ -425,7 +417,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
allowNonZeroExit: true,
timeoutMs: 20_000,
maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
appendTruncationMarker: true,
truncateOutputAtMaxBytes: true,
},
).pipe(
Effect.flatMap((result) =>
@@ -452,17 +444,11 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
const listRemotes: VcsDriver.VcsDriverShape["listRemotes"] = Effect.fn("listRemotes")(
function* (cwd) {
const result = yield* gitCommand(
vcsProcess,
"GitVcsDriver.listRemotes",
cwd,
["remote", "-v"],
{
allowNonZeroExit: true,
timeoutMs: 5_000,
maxOutputBytes: 64 * 1024,
},
);
const result = yield* gitCommand(process, "GitVcsDriver.listRemotes", cwd, ["remote", "-v"], {
allowNonZeroExit: true,
timeoutMs: 5_000,
maxOutputBytes: 64 * 1024,
});
if (result.exitCode !== 0) {
return yield* new VcsProcessExitError({
@@ -508,7 +494,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
for (const chunk of chunks) {
const result = yield* gitCommand(
vcsProcess,
process,
"GitVcsDriver.filterIgnoredPaths",
cwd,
[...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, "check-ignore", "--no-index", "-z", "--stdin"],
@@ -517,7 +503,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
allowNonZeroExit: true,
timeoutMs: 20_000,
maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
appendTruncationMarker: true,
truncateOutputAtMaxBytes: true,
},
);
@@ -544,266 +530,14 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
});
const initRepository: VcsDriver.VcsDriverShape["initRepository"] = (input) =>
gitCommand(vcsProcess, "GitVcsDriver.initRepository", input.cwd, ["init"], {
gitCommand(process, "GitVcsDriver.initRepository", input.cwd, ["init"], {
timeoutMs: 10_000,
maxOutputBytes: 64 * 1024,
}).pipe(Effect.asVoid);
const resolveHeadCommit = (cwd: string) =>
execute({
operation: "GitVcsDriver.checkpoints.resolveHeadCommit",
cwd,
args: ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"],
allowNonZeroExit: true,
}).pipe(
Effect.map((result) => {
if (result.exitCode !== 0) {
return null;
}
const commit = result.stdout.trim();
return commit.length > 0 ? commit : null;
}),
);
const hasHeadCommit = (cwd: string) =>
execute({
operation: "GitVcsDriver.checkpoints.hasHeadCommit",
cwd,
args: ["rev-parse", "--verify", "HEAD"],
allowNonZeroExit: true,
}).pipe(Effect.map((result) => result.exitCode === 0));
const resolveCheckpointCommit = (cwd: string, checkpointRef: string) =>
execute({
operation: "GitVcsDriver.checkpoints.resolveCheckpointCommit",
cwd,
args: ["rev-parse", "--verify", "--quiet", `${checkpointRef}^{commit}`],
allowNonZeroExit: true,
}).pipe(
Effect.map((result) => {
if (result.exitCode !== 0) {
return null;
}
const commit = result.stdout.trim();
return commit.length > 0 ? commit : null;
}),
);
const resolveGitCommonDir = (cwd: string) =>
Effect.gen(function* () {
const result = yield* execute({
operation: "GitVcsDriver.checkpoints.resolveGitCommonDir",
cwd,
args: ["rev-parse", "--git-common-dir"],
});
const gitCommonDir = result.stdout.trim();
return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir);
});
const checkpoints: VcsDriver.VcsCheckpointOps = {
captureCheckpoint: Effect.fn("GitVcsDriver.checkpoints.captureCheckpoint")(function* (input) {
const operation = "GitVcsDriver.checkpoints.captureCheckpoint";
const gitCommonDir = yield* resolveGitCommonDir(input.cwd);
const tempIndexPath = path.join(gitCommonDir, `t3-checkpoint-index-${randomUUID()}`);
const commitEnv: NodeJS.ProcessEnv = {
...process.env,
GIT_INDEX_FILE: tempIndexPath,
GIT_AUTHOR_NAME: "T3 Code",
GIT_AUTHOR_EMAIL: "[email protected]",
GIT_COMMITTER_NAME: "T3 Code",
GIT_COMMITTER_EMAIL: "[email protected]",
};
const cleanupTempIndex = fileSystem
.remove(tempIndexPath, { force: true })
.pipe(Effect.ignore);
yield* Effect.gen(function* () {
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* execute({
operation,
cwd: input.cwd,
args: ["read-tree", "HEAD"],
env: commitEnv,
});
}
yield* execute({
operation,
cwd: input.cwd,
args: ["add", "-A", "--", "."],
env: commitEnv,
});
const writeTreeResult = yield* execute({
operation,
cwd: input.cwd,
args: ["write-tree"],
env: commitEnv,
});
const treeOid = writeTreeResult.stdout.trim();
if (treeOid.length === 0) {
return yield* new VcsProcessExitError({
operation,
command: "git write-tree",
cwd: input.cwd,
exitCode: 0,
detail: "git write-tree returned an empty tree oid.",
});
}
const message = `t3 checkpoint ref=${input.checkpointRef}`;
const commitTreeResult = yield* execute({
operation,
cwd: input.cwd,
args: ["commit-tree", treeOid, "-m", message],
env: commitEnv,
});
const commitOid = commitTreeResult.stdout.trim();
if (commitOid.length === 0) {
return yield* new VcsProcessExitError({
operation,
command: "git commit-tree",
cwd: input.cwd,
exitCode: 0,
detail: "git commit-tree returned an empty commit oid.",
});
}
yield* execute({
operation,
cwd: input.cwd,
args: ["update-ref", input.checkpointRef, commitOid],
});
}).pipe(Effect.ensuring(cleanupTempIndex));
}),
hasCheckpointRef: (input) =>
resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
Effect.map((commit) => commit !== null),
),
restoreCheckpoint: Effect.fn("GitVcsDriver.checkpoints.restoreCheckpoint")(function* (input) {
const operation = "GitVcsDriver.checkpoints.restoreCheckpoint";
let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
if (!commitOid && input.fallbackToHead === true) {
commitOid = yield* resolveHeadCommit(input.cwd);
}
if (!commitOid) {
return false;
}
yield* execute({
operation,
cwd: input.cwd,
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
});
yield* execute({
operation,
cwd: input.cwd,
args: ["clean", "-fd", "--", "."],
});
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* execute({
operation,
cwd: input.cwd,
args: ["reset", "--quiet", "--", "."],
});
}
return true;
}),
diffCheckpoints: Effect.fn("GitVcsDriver.checkpoints.diffCheckpoints")(function* (input) {
const operation = "GitVcsDriver.checkpoints.diffCheckpoints";
yield* Effect.annotateCurrentSpan({
"checkpoint.cwd": input.cwd,
"checkpoint.from_ref": input.fromCheckpointRef,
"checkpoint.to_ref": input.toCheckpointRef,
"checkpoint.ignore_whitespace": input.ignoreWhitespace,
"checkpoint.fallback_from_to_head": input.fallbackFromToHead,
});
let fromRevision: string = input.fromCheckpointRef;
if (input.fallbackFromToHead === true) {
const resolvedFromCommit = yield* resolveCheckpointCommit(
input.cwd,
input.fromCheckpointRef,
);
if (resolvedFromCommit) {
fromRevision = resolvedFromCommit;
} else {
const headCommit = yield* resolveHeadCommit(input.cwd);
if (!headCommit) {
return yield* new VcsProcessExitError({
operation,
command: "git diff",
cwd: input.cwd,
exitCode: 1,
detail: "Checkpoint ref is unavailable for diff operation.",
});
}
fromRevision = headCommit;
}
}
const result = yield* execute({
operation,
cwd: input.cwd,
args: [
"diff",
"--patch",
"--no-color",
"--no-ext-diff",
"--no-textconv",
...(input.ignoreWhitespace ? ["--ignore-all-space"] : []),
`${fromRevision}^{commit}`,
`${input.toCheckpointRef}^{commit}`,
],
allowNonZeroExit: true,
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
});
if (result.exitCode !== 0) {
return yield* new VcsProcessExitError({
operation,
command: "git diff",
cwd: input.cwd,
exitCode: result.exitCode,
detail: result.stderr.trim() || "Checkpoint ref is unavailable for diff operation.",
});
}
return result.stdout;
}),
deleteCheckpointRefs: Effect.fn("GitVcsDriver.checkpoints.deleteCheckpointRefs")(
function* (input) {
yield* Effect.forEach(
input.checkpointRefs,
(checkpointRef) =>
execute({
operation: "GitVcsDriver.checkpoints.deleteCheckpointRefs",
cwd: input.cwd,
args: ["update-ref", "-d", checkpointRef],
allowNonZeroExit: true,
}),
{ discard: true },
);
},
),
};
return VcsDriver.VcsDriver.of({
capabilities,
execute,
checkpoints,
detectRepository,
isInsideWorkTree,
listWorkspaceFiles,
@@ -130,65 +130,6 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
}),
);
it.effect("disables SSH askpass for background upstream status fetches", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const tempDir = yield* makeTmpDir("git-vcs-driver-ssh-env-");
const { initialBranch } = yield* initRepoWithCommit(cwd);
const fileSystem = yield* FileSystem.FileSystem;
const pathService = yield* Path.Path;
const sshLogPath = pathService.join(tempDir, "ssh-env.txt");
const sshWrapperPath = pathService.join(tempDir, "ssh-wrapper.sh");
const previousGitSsh = process.env.GIT_SSH;
const previousAskpassRequire = process.env.SSH_ASKPASS_REQUIRE;
const previousAskpassLog = process.env.T3_TEST_SSH_ASKPASS_LOG;
yield* fileSystem.writeFileString(
sshWrapperPath,
[
"#!/bin/sh",
'printf "%s\\n" "${SSH_ASKPASS_REQUIRE:-}" > "$T3_TEST_SSH_ASKPASS_LOG"',
"exit 1",
"",
].join("\n"),
);
yield* fileSystem.chmod(sshWrapperPath, 0o755);
yield* git(cwd, ["remote", "add", "origin", "ssh://example.invalid/repo.git"]);
yield* git(cwd, ["update-ref", `refs/remotes/origin/${initialBranch}`, "HEAD"]);
yield* git(cwd, ["branch", "--set-upstream-to", `origin/${initialBranch}`]);
yield* Effect.gen(function* () {
process.env.GIT_SSH = sshWrapperPath;
process.env.SSH_ASKPASS_REQUIRE = "force";
process.env.T3_TEST_SSH_ASKPASS_LOG = sshLogPath;
yield* (yield* GitVcsDriver.GitVcsDriver).statusDetails(cwd);
assert.equal((yield* fileSystem.readFileString(sshLogPath)).trim(), "never");
}).pipe(
Effect.ensuring(
Effect.sync(() => {
if (previousGitSsh === undefined) {
delete process.env.GIT_SSH;
} else {
process.env.GIT_SSH = previousGitSsh;
}
if (previousAskpassRequire === undefined) {
delete process.env.SSH_ASKPASS_REQUIRE;
} else {
process.env.SSH_ASKPASS_REQUIRE = previousAskpassRequire;
}
if (previousAskpassLog === undefined) {
delete process.env.T3_TEST_SSH_ASKPASS_LOG;
} else {
process.env.T3_TEST_SSH_ASKPASS_LOG = previousAskpassLog;
}
}),
),
);
}),
);
it.effect("reuses the no-upstream fallback ahead count for default-branch delta", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
+15 -21
View File
@@ -41,9 +41,6 @@ const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
const STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN = Duration.seconds(5);
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
const STATUS_UPSTREAM_REFRESH_ENV = Object.freeze({
SSH_ASKPASS_REQUIRE: "never",
} satisfies NodeJS.ProcessEnv);
const DEFAULT_BASE_BRANCH_CANDIDATES = ["main", "master"] as const;
const GIT_LIST_BRANCHES_DEFAULT_LIMIT = 100;
const NON_REPOSITORY_STATUS_DETAILS = Object.freeze<GitVcsDriver.GitStatusDetails>({
@@ -75,9 +72,8 @@ interface ExecuteGitOptions {
timeoutMs?: number | undefined;
allowNonZeroExit?: boolean | undefined;
fallbackErrorMessage?: string | undefined;
env?: NodeJS.ProcessEnv | undefined;
maxOutputBytes?: number | undefined;
appendTruncationMarker?: boolean | undefined;
truncateOutputAtMaxBytes?: boolean | undefined;
progress?: GitVcsDriver.ExecuteGitProgress | undefined;
}
@@ -535,7 +531,7 @@ const collectOutput = Effect.fnUntraced(function* <E>(
input: Pick<GitVcsDriver.ExecuteGitInput, "operation" | "cwd" | "args">,
stream: Stream.Stream<Uint8Array, E>,
maxOutputBytes: number,
appendTruncationMarker: boolean,
truncateOutputAtMaxBytes: boolean,
onLine: ((line: string) => Effect.Effect<void, never>) | undefined,
): Effect.fn.Return<{ readonly text: string; readonly truncated: boolean }, GitCommandError> {
const decoder = new TextDecoder();
@@ -565,11 +561,11 @@ const collectOutput = Effect.fnUntraced(function* <E>(
});
const processChunk = Effect.fnUntraced(function* (chunk: Uint8Array) {
if (appendTruncationMarker && truncated) {
if (truncateOutputAtMaxBytes && truncated) {
return;
}
const nextBytes = bytes + chunk.byteLength;
if (!appendTruncationMarker && nextBytes > maxOutputBytes) {
if (!truncateOutputAtMaxBytes && nextBytes > maxOutputBytes) {
return yield* new GitCommandError({
operation: input.operation,
command: quoteGitCommand(input.args),
@@ -579,11 +575,11 @@ const collectOutput = Effect.fnUntraced(function* <E>(
}
const chunkToDecode =
appendTruncationMarker && nextBytes > maxOutputBytes
truncateOutputAtMaxBytes && nextBytes > maxOutputBytes
? chunk.subarray(0, Math.max(0, maxOutputBytes - bytes))
: chunk;
bytes += chunkToDecode.byteLength;
truncated = appendTruncationMarker && nextBytes > maxOutputBytes;
truncated = truncateOutputAtMaxBytes && nextBytes > maxOutputBytes;
const decoded = decoder.decode(chunkToDecode, { stream: !truncated });
text += decoded;
@@ -619,7 +615,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
} as const;
const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
const appendTruncationMarker = input.appendTruncationMarker ?? false;
const truncateOutputAtMaxBytes = input.truncateOutputAtMaxBytes ?? false;
const runGitCommand = Effect.fn("runGitCommand")(function* () {
const trace2Monitor = yield* createTrace2Monitor(commandInput, input.progress).pipe(
@@ -646,14 +642,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
commandInput,
child.stdout,
maxOutputBytes,
appendTruncationMarker,
truncateOutputAtMaxBytes,
input.progress?.onStdoutLine,
),
collectOutput(
commandInput,
child.stderr,
maxOutputBytes,
appendTruncationMarker,
truncateOutputAtMaxBytes,
input.progress?.onStderrLine,
),
child.exitCode.pipe(
@@ -742,12 +738,11 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
cwd,
args,
...(options.stdin !== undefined ? { stdin: options.stdin } : {}),
...(options.env !== undefined ? { env: options.env } : {}),
allowNonZeroExit: true,
...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
...(options.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}),
...(options.appendTruncationMarker !== undefined
? { appendTruncationMarker: options.appendTruncationMarker }
...(options.truncateOutputAtMaxBytes !== undefined
? { truncateOutputAtMaxBytes: options.truncateOutputAtMaxBytes }
: {}),
...(options.progress ? { progress: options.progress } : {}),
}).pipe(
@@ -875,7 +870,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
["--git-dir", gitCommonDir, "fetch", "--quiet", "--no-tags", remoteName],
{
allowNonZeroExit: true,
env: STATUS_UPSTREAM_REFRESH_ENV,
timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT),
},
).pipe(Effect.asVoid);
@@ -1379,7 +1373,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
["diff", "--cached", "--patch", "--minimal"],
{
maxOutputBytes: PREPARED_COMMIT_PATCH_MAX_OUTPUT_BYTES,
appendTruncationMarker: true,
truncateOutputAtMaxBytes: true,
},
);
@@ -1598,7 +1592,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
["log", "--oneline", range],
{
maxOutputBytes: RANGE_COMMIT_SUMMARY_MAX_OUTPUT_BYTES,
appendTruncationMarker: true,
truncateOutputAtMaxBytes: true,
},
),
runGitStdoutWithOptions(
@@ -1607,7 +1601,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
["diff", "--stat", range],
{
maxOutputBytes: RANGE_DIFF_SUMMARY_MAX_OUTPUT_BYTES,
appendTruncationMarker: true,
truncateOutputAtMaxBytes: true,
},
),
runGitStdoutWithOptions(
@@ -1616,7 +1610,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
["diff", "--patch", "--minimal", range],
{
maxOutputBytes: RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES,
appendTruncationMarker: true,
truncateOutputAtMaxBytes: true,
},
),
],
-40
View File
@@ -9,53 +9,13 @@ import type {
VcsListWorkspaceFilesResult,
VcsRepositoryIdentity,
} from "@t3tools/contracts";
import { CheckpointRef } from "@t3tools/contracts";
import * as VcsProcess from "./VcsProcess.ts";
export interface VcsCaptureCheckpointInput {
readonly cwd: string;
readonly checkpointRef: CheckpointRef;
}
export interface VcsRestoreCheckpointInput {
readonly cwd: string;
readonly checkpointRef: CheckpointRef;
readonly fallbackToHead?: boolean;
}
export interface VcsDiffCheckpointsInput {
readonly cwd: string;
readonly fromCheckpointRef: CheckpointRef;
readonly toCheckpointRef: CheckpointRef;
readonly fallbackFromToHead?: boolean;
readonly ignoreWhitespace: boolean;
}
export interface VcsDeleteCheckpointRefsInput {
readonly cwd: string;
readonly checkpointRefs: ReadonlyArray<CheckpointRef>;
}
export interface VcsCheckpointOps {
readonly captureCheckpoint: (input: VcsCaptureCheckpointInput) => Effect.Effect<void, VcsError>;
readonly hasCheckpointRef: (
input: Omit<VcsRestoreCheckpointInput, "fallbackToHead">,
) => Effect.Effect<boolean, VcsError>;
readonly restoreCheckpoint: (
input: VcsRestoreCheckpointInput,
) => Effect.Effect<boolean, VcsError>;
readonly diffCheckpoints: (input: VcsDiffCheckpointsInput) => Effect.Effect<string, VcsError>;
readonly deleteCheckpointRefs: (
input: VcsDeleteCheckpointRefsInput,
) => Effect.Effect<void, VcsError>;
}
export interface VcsDriverShape {
readonly capabilities: VcsDriverCapabilities;
readonly execute: (
input: Omit<VcsProcess.VcsProcessInput, "command">,
) => Effect.Effect<VcsProcess.VcsProcessOutput, VcsError>;
readonly checkpoints?: VcsCheckpointOps;
readonly detectRepository: (cwd: string) => Effect.Effect<VcsRepositoryIdentity | null, VcsError>;
readonly isInsideWorkTree: (cwd: string) => Effect.Effect<boolean, VcsError>;
readonly listWorkspaceFiles: (
+2 -10
View File
@@ -1,5 +1,4 @@
import { assert, it, describe } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { ChildProcessSpawner } from "effect/unstable/process";
@@ -16,13 +15,9 @@ const processOutput = (stdout: string): VcsProcess.VcsProcessOutput => ({
stderrTruncated: false,
});
const normalizeGitArgs = (args: ReadonlyArray<string>): ReadonlyArray<string> =>
args[0] === "-C" && args.length >= 2 ? args.slice(2) : args;
describe("VcsDriverRegistry", () => {
it.effect("routes directly by VCS driver kind for non-repository workflows", () => {
const layer = Layer.effect(VcsDriverRegistry.VcsDriverRegistry, VcsDriverRegistry.make()).pipe(
Layer.provide(NodeServices.layer),
Layer.provide(
Layer.mock(VcsProjectConfig.VcsProjectConfig)({
resolveKind: (input) => Effect.succeed(input.requestedKind ?? "auto"),
@@ -46,7 +41,6 @@ describe("VcsDriverRegistry", () => {
it.effect("caches repository detection for repeated resolves in the same cwd and kind", () => {
const calls: VcsProcess.VcsProcessInput[] = [];
const layer = Layer.effect(VcsDriverRegistry.VcsDriverRegistry, VcsDriverRegistry.make()).pipe(
Layer.provide(NodeServices.layer),
Layer.provide(
Layer.mock(VcsProjectConfig.VcsProjectConfig)({
resolveKind: (input) => Effect.succeed(input.requestedKind ?? "auto"),
@@ -57,9 +51,7 @@ describe("VcsDriverRegistry", () => {
run: (input) =>
Effect.sync(() => {
calls.push(input);
const normalizedArgs =
input.args[0] === "-C" && input.args.length >= 2 ? input.args.slice(2) : input.args;
const command = normalizedArgs.join(" ");
const command = input.args.join(" ");
if (command === "rev-parse --is-inside-work-tree") {
return processOutput("true\n");
}
@@ -83,7 +75,7 @@ describe("VcsDriverRegistry", () => {
assert.equal(first.repository.rootPath, "/repo");
assert.equal(second.repository.rootPath, "/repo");
assert.deepStrictEqual(
calls.map((call) => normalizeGitArgs(call.args).join(" ")),
calls.map((call) => call.args.join(" ")),
[
"rev-parse --is-inside-work-tree",
"rev-parse --show-toplevel",
-138
View File
@@ -1,138 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "@effect/vitest";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import { TestClock } from "effect/testing";
import { VcsProcessExitError, VcsProcessTimeoutError } from "@t3tools/contracts";
import * as VcsProcess from "./VcsProcess.ts";
const run = (input: VcsProcess.VcsProcessInput) =>
Effect.gen(function* () {
const process = yield* VcsProcess.VcsProcess;
return yield* process.run(input);
});
const liveLayer = VcsProcess.layer.pipe(Layer.provide(NodeServices.layer));
const provideLive = <A, E, R>(effect: Effect.Effect<A, E, R | VcsProcess.VcsProcess>) =>
effect.pipe(Effect.provide(liveLayer));
describe("VcsProcess.run", () => {
it.effect("collects stdout", () =>
Effect.gen(function* () {
const result = yield* run({
operation: "test.stdout",
command: "node",
args: ["-e", "process.stdout.write('hello')"],
cwd: process.cwd(),
});
expect(result.stdout).toBe("hello");
expect(result.stderr).toBe("");
expect(result.stdoutTruncated).toBe(false);
expect(result.stderrTruncated).toBe(false);
}).pipe(provideLive),
);
it.effect("writes stdin before waiting for exit", () =>
Effect.gen(function* () {
const result = yield* run({
operation: "test.stdin",
command: "node",
args: [
"-e",
[
"process.stdin.setEncoding('utf8');",
"let data='';",
"process.stdin.on('data', chunk => { data += chunk; });",
"process.stdin.on('end', () => { process.stdout.write(data); });",
].join(""),
],
cwd: process.cwd(),
stdin: "stdin payload",
});
expect(result.stdout).toBe("stdin payload");
}).pipe(provideLive),
);
it.effect("fails with VcsProcessExitError for non-zero exits by default", () =>
Effect.gen(function* () {
const error = yield* run({
operation: "test.exit",
command: "node",
args: ["-e", "process.stderr.write('boom'); process.exit(2)"],
cwd: process.cwd(),
}).pipe(Effect.flip);
expect(error).toBeInstanceOf(VcsProcessExitError);
}).pipe(provideLive),
);
it.effect("returns output when non-zero exits are allowed", () =>
Effect.gen(function* () {
const result = yield* run({
operation: "test.allowed-exit",
command: "node",
args: ["-e", "process.stderr.write('boom'); process.exit(2)"],
cwd: process.cwd(),
allowNonZeroExit: true,
});
expect(result.exitCode).toBe(2);
expect(result.stderr).toBe("boom");
}).pipe(provideLive),
);
it.effect("truncates output and appends the marker when requested", () =>
Effect.gen(function* () {
const result = yield* run({
operation: "test.truncate-marker",
command: "node",
args: ["-e", "process.stdout.write('x'.repeat(2048))"],
cwd: process.cwd(),
maxOutputBytes: 128,
appendTruncationMarker: true,
});
expect(result.stdoutTruncated).toBe(true);
expect(result.stdout).toContain("[truncated]");
expect(result.stderrTruncated).toBe(false);
}).pipe(provideLive),
);
it.effect("truncates without the marker when truncation markers are disabled", () =>
Effect.gen(function* () {
const result = yield* run({
operation: "test.truncate-silent",
command: "node",
args: ["-e", "process.stdout.write('x'.repeat(2048))"],
cwd: process.cwd(),
maxOutputBytes: 128,
});
expect(result.stdoutTruncated).toBe(true);
expect(result.stdout).not.toContain("[truncated]");
}).pipe(provideLive),
);
it.effect("fails with VcsProcessTimeoutError on timeout", () =>
Effect.gen(function* () {
const errorFiber = yield* run({
operation: "test.timeout",
command: "node",
args: ["-e", "setTimeout(() => {}, 5000)"],
cwd: process.cwd(),
timeoutMs: 50,
}).pipe(Effect.flip, Effect.forkScoped);
yield* Effect.yieldNow;
yield* TestClock.adjust(Duration.millis(50));
const error = yield* Fiber.join(errorFiber);
expect(error).toBeInstanceOf(VcsProcessTimeoutError);
}).pipe(provideLive),
);
});
+183 -70
View File
@@ -1,7 +1,12 @@
import * as Duration from "effect/Duration";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
VcsOutputDecodeError,
@@ -10,21 +15,19 @@ import {
VcsProcessSpawnError,
VcsProcessTimeoutError,
} from "@t3tools/contracts";
import { ProcessRunner, layer as ProcessRunnerLive } from "../processRunner.ts";
import * as Match from "effect/Match";
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
export interface VcsProcessInput {
readonly operation: string;
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly cwd: string;
readonly spawnCwd?: string;
readonly stdin?: string;
readonly env?: NodeJS.ProcessEnv;
readonly allowNonZeroExit?: boolean;
readonly timeoutMs?: number;
readonly maxOutputBytes?: number;
readonly appendTruncationMarker?: boolean;
readonly truncateOutputAtMaxBytes?: boolean;
}
export interface VcsProcessOutput {
@@ -35,7 +38,25 @@ export interface VcsProcessOutput {
readonly stderrTruncated: boolean;
}
export interface VcsProcessCollectedText {
readonly text: string;
readonly truncated: boolean;
}
export interface VcsProcessHandle {
readonly pid: ChildProcessSpawner.ProcessId;
readonly stdin: Sink.Sink<void, Uint8Array, never, VcsError>;
readonly stdout: Stream.Stream<Uint8Array, VcsError>;
readonly stderr: Stream.Stream<Uint8Array, VcsError>;
readonly exitCode: Effect.Effect<ChildProcessSpawner.ExitCode, VcsError>;
readonly writeStdin: (input: string) => Effect.Effect<void, VcsError>;
}
export interface VcsProcessShape {
readonly withProcess: <A, E, R>(
input: VcsProcessInput,
use: (handle: VcsProcessHandle) => Effect.Effect<A, E, R>,
) => Effect.Effect<A, E | VcsError, R>;
readonly run: (input: VcsProcessInput) => Effect.Effect<VcsProcessOutput, VcsError>;
}
@@ -51,72 +72,164 @@ function commandLabel(command: string, args: ReadonlyArray<string>): string {
return [command, ...args].join(" ");
}
export const make = Effect.fn("makeVcsProcess")(function* () {
const processRunner = yield* ProcessRunner;
const run = Effect.fn("VcsProcess.run")(function* (input: VcsProcessInput) {
const label = commandLabel(input.command, input.args);
const baseError = {
operation: input.operation,
command: label,
cwd: input.cwd,
};
const result = yield* processRunner
.run({
command: input.command,
args: input.args,
cwd: input.cwd,
...(input.spawnCwd !== undefined ? { spawnCwd: input.spawnCwd } : {}),
...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
...(input.env !== undefined ? { env: input.env } : {}),
timeout: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
maxOutputBytes: input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES,
outputMode: "truncate",
truncatedMarker: input.appendTruncationMarker ? OUTPUT_TRUNCATED_MARKER : "",
timeoutBehavior: "error",
})
.pipe(
Effect.mapError(
Match.valueTags({
ProcessSpawnError: (error) =>
VcsProcessSpawnError.fromProcessSpawnError(baseError, error),
ProcessOutputLimitError: (error) =>
VcsOutputDecodeError.fromProcessOutputLimitError(baseError, error),
ProcessTimeoutError: (error) =>
VcsProcessTimeoutError.fromProcessTimeoutError(baseError, error),
ProcessStdinError: (error) =>
VcsOutputDecodeError.fromProcessStdinError(baseError, error),
ProcessReadError: (error) =>
VcsOutputDecodeError.fromProcessReadError(baseError, error),
}),
),
);
if (result.code === null) {
return yield* VcsOutputDecodeError.missingExitCode(baseError);
}
if (!input.allowNonZeroExit && result.code !== 0) {
return yield* new VcsProcessExitError({
operation: input.operation,
command: label,
cwd: input.cwd,
exitCode: result.code,
detail: result.stderr.trim() || `${label} exited with code ${result.code}.`,
});
}
return {
exitCode: result.code,
stdout: result.stdout,
stderr: result.stderr,
stdoutTruncated: result.stdoutTruncated,
stderrTruncated: result.stderrTruncated,
} satisfies VcsProcessOutput;
function outputDecodeError(
input: VcsProcessInput,
detail: string,
cause: unknown,
): VcsOutputDecodeError {
return new VcsOutputDecodeError({
operation: input.operation,
command: commandLabel(input.command, input.args),
cwd: input.cwd,
detail,
cause,
});
}
return VcsProcess.of({ run });
export const collectText = Effect.fn("VcsProcess.collectText")(function* (input: {
readonly operation: string;
readonly command: string;
readonly cwd: string;
readonly stream: Stream.Stream<Uint8Array, VcsError>;
readonly maxOutputBytes?: number;
readonly truncateOutputAtMaxBytes?: boolean;
}) {
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
return yield* collectUint8StreamText({
stream: input.stream,
maxBytes: maxOutputBytes,
truncatedMarker: input.truncateOutputAtMaxBytes ? OUTPUT_TRUNCATED_MARKER : null,
});
});
export const layer = Layer.effect(VcsProcess, make()).pipe(Layer.provide(ProcessRunnerLive));
export const make = Effect.fn("makeVcsProcess")(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const spawn = Effect.fn("VcsProcess.spawn")(function* (input: VcsProcessInput) {
const label = commandLabel(input.command, input.args);
const child = yield* spawner
.spawn(
ChildProcess.make(input.command, [...input.args], {
cwd: input.cwd,
env: {
...process.env,
...input.env,
},
}),
)
.pipe(
Effect.mapError(
(cause) =>
new VcsProcessSpawnError({
operation: input.operation,
command: label,
cwd: input.cwd,
cause,
}),
),
);
yield* Effect.addFinalizer(() => child.kill().pipe(Effect.ignore));
const mapStreamError = (streamName: "stdout" | "stderr") =>
Stream.mapError((cause: PlatformError.PlatformError) =>
outputDecodeError(input, `failed to read process ${streamName}`, cause),
);
const mapEffectError = (detail: string) =>
Effect.mapError((cause: PlatformError.PlatformError) =>
outputDecodeError(input, detail, cause),
);
const writeStdin = (stdin: string) =>
Stream.run(Stream.encodeText(Stream.make(stdin)), child.stdin).pipe(
mapEffectError("failed to write process stdin"),
);
return {
pid: child.pid,
stdin: child.stdin.pipe(
Sink.mapError((cause) => outputDecodeError(input, "failed to write process stdin", cause)),
),
stdout: child.stdout.pipe(mapStreamError("stdout")),
stderr: child.stderr.pipe(mapStreamError("stderr")),
exitCode: child.exitCode.pipe(mapEffectError("failed to read process exit code")),
writeStdin,
} satisfies VcsProcessHandle;
});
const withProcess: VcsProcessShape["withProcess"] = (input, use) =>
Effect.scoped(spawn(input).pipe(Effect.flatMap(use)));
const run = Effect.fn("VcsProcess.run")(function* (input: VcsProcessInput) {
const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
const label = commandLabel(input.command, input.args);
const runProcess = Effect.gen(function* () {
const [stdout, stderr, exitCode] = yield* withProcess(input, (child) =>
Effect.all(
[
collectText({
operation: input.operation,
command: label,
cwd: input.cwd,
stream: child.stdout,
maxOutputBytes,
truncateOutputAtMaxBytes: input.truncateOutputAtMaxBytes ?? false,
}),
collectText({
operation: input.operation,
command: label,
cwd: input.cwd,
stream: child.stderr,
maxOutputBytes,
truncateOutputAtMaxBytes: input.truncateOutputAtMaxBytes ?? false,
}),
child.exitCode,
input.stdin === undefined ? Effect.void : child.writeStdin(input.stdin),
],
{ concurrency: "unbounded" },
),
).pipe(Effect.map(([stdout, stderr, exitCode]) => [stdout, stderr, exitCode] as const));
if (!input.allowNonZeroExit && exitCode !== 0) {
return yield* new VcsProcessExitError({
operation: input.operation,
command: label,
cwd: input.cwd,
exitCode,
detail: stderr.text.trim() || `${label} exited with code ${exitCode}.`,
});
}
return {
exitCode,
stdout: stdout.text,
stderr: stderr.text,
stdoutTruncated: stdout.truncated,
stderrTruncated: stderr.truncated,
} satisfies VcsProcessOutput;
});
return yield* runProcess.pipe(
Effect.scoped,
Effect.timeoutOption(Duration.millis(timeoutMs)),
Effect.flatMap((result) =>
Option.match(result, {
onSome: Effect.succeed,
onNone: () =>
Effect.fail(
new VcsProcessTimeoutError({
operation: input.operation,
command: label,
cwd: input.cwd,
timeoutMs,
}),
),
}),
),
);
});
return VcsProcess.of({ withProcess, run });
});
export const layer = Layer.effect(VcsProcess, make());
@@ -1,7 +1,6 @@
import { assert, it, describe } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
@@ -285,31 +284,6 @@ describe("VcsStatusBroadcaster", () => {
}).pipe(Effect.provide(makeTestLayer(state)));
});
it.effect("does not start automatic remote refreshes when disabled", () => {
const state = {
currentLocalStatus: baseLocalStatus,
currentRemoteStatus: baseRemoteStatus,
localStatusCalls: 0,
remoteStatusCalls: 0,
localInvalidationCalls: 0,
remoteInvalidationCalls: 0,
};
return Effect.gen(function* () {
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
const snapshot = yield* Stream.runHead(
broadcaster.streamStatus(
{ cwd: "/repo" },
{ automaticRemoteRefreshInterval: Effect.succeed(Duration.zero) },
),
);
assert.isTrue(Option.isSome(snapshot));
assert.equal(state.remoteStatusCalls, 0);
assert.equal(state.remoteInvalidationCalls, 0);
}).pipe(Effect.provide(makeTestLayer(state)));
});
it.effect("stops the remote poller after the last stream subscriber disconnects", () => {
const state = {
currentLocalStatus: baseLocalStatus,
+9 -32
View File
@@ -22,7 +22,7 @@ import { mergeGitStatusParts } from "@t3tools/shared/git";
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
const DEFAULT_VCS_STATUS_REFRESH_INTERVAL = Duration.seconds(30);
const VCS_STATUS_REFRESH_INTERVAL = Duration.seconds(30);
interface VcsStatusChange {
readonly cwd: string;
@@ -44,10 +44,6 @@ interface ActiveRemotePoller {
readonly subscriberCount: number;
}
interface StreamStatusOptions {
readonly automaticRemoteRefreshInterval?: Effect.Effect<Duration.Duration, never>;
}
export interface VcsStatusBroadcasterShape {
readonly getStatus: (
input: VcsStatusInput,
@@ -58,7 +54,6 @@ export interface VcsStatusBroadcasterShape {
readonly refreshStatus: (cwd: string) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
readonly streamStatus: (
input: VcsStatusInput,
options?: StreamStatusOptions,
) => Stream.Stream<VcsStatusStreamEvent, GitManagerServiceError>;
}
@@ -237,32 +232,19 @@ export const layer = Layer.effect(
return mergeGitStatusParts(local, remote);
});
const makeRemoteRefreshLoop = (
cwd: string,
automaticRemoteRefreshInterval: Effect.Effect<Duration.Duration, never>,
) => {
const logRefreshFailure = (error: GitManagerServiceError) =>
const makeRemoteRefreshLoop = (cwd: string) => {
const logRefreshFailure = (error: Error) =>
Effect.logWarning("VCS remote status refresh failed", {
cwd,
detail: error.message,
});
const refreshRemoteStatusIfEnabled = automaticRemoteRefreshInterval.pipe(
Effect.flatMap((interval) =>
Duration.isZero(interval) ? Effect.void : refreshRemoteStatus(cwd).pipe(Effect.asVoid),
),
);
const sleepForConfiguredInterval = automaticRemoteRefreshInterval.pipe(
Effect.flatMap((interval) =>
Effect.sleep(Duration.isZero(interval) ? DEFAULT_VCS_STATUS_REFRESH_INTERVAL : interval),
),
);
return refreshRemoteStatusIfEnabled.pipe(
return refreshRemoteStatus(cwd).pipe(
Effect.catch(logRefreshFailure),
Effect.andThen(
Effect.forever(
sleepForConfiguredInterval.pipe(
Effect.andThen(refreshRemoteStatusIfEnabled.pipe(Effect.catch(logRefreshFailure))),
Effect.sleep(VCS_STATUS_REFRESH_INTERVAL).pipe(
Effect.andThen(refreshRemoteStatus(cwd).pipe(Effect.catch(logRefreshFailure))),
),
),
),
@@ -271,7 +253,6 @@ export const layer = Layer.effect(
const retainRemotePoller = Effect.fn("VcsStatusBroadcaster.retainRemotePoller")(function* (
cwd: string,
automaticRemoteRefreshInterval: Effect.Effect<Duration.Duration, never>,
) {
yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
const existing = activePollers.get(cwd);
@@ -284,7 +265,7 @@ export const layer = Layer.effect(
return Effect.succeed([undefined, nextPollers] as const);
}
return makeRemoteRefreshLoop(cwd, automaticRemoteRefreshInterval).pipe(
return makeRemoteRefreshLoop(cwd).pipe(
Effect.forkIn(broadcasterScope),
Effect.map((fiber) => {
const nextPollers = new Map(activePollers);
@@ -326,18 +307,14 @@ export const layer = Layer.effect(
}
});
const streamStatus: VcsStatusBroadcasterShape["streamStatus"] = (input, options) =>
const streamStatus: VcsStatusBroadcasterShape["streamStatus"] = (input) =>
Stream.unwrap(
Effect.gen(function* () {
const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
const subscription = yield* PubSub.subscribe(changesPubSub);
const initialLocal = yield* getOrLoadLocalStatus(cwd);
const initialRemote = (yield* getCachedStatus(cwd))?.remote?.value ?? null;
yield* retainRemotePoller(
cwd,
options?.automaticRemoteRefreshInterval ??
Effect.succeed(DEFAULT_VCS_STATUS_REFRESH_INTERVAL),
);
yield* retainRemotePoller(cwd);
const release = releaseRemotePoller(cwd).pipe(Effect.ignore, Effect.asVoid);
@@ -11,10 +11,6 @@ import * as Option from "effect/Option";
import type { VcsDriverKind } from "@t3tools/contracts";
import * as VcsDriver from "../VcsDriver.ts";
function normalizePathForComparison(value: string): string {
return value.replaceAll("\\", "/");
}
export interface VcsDriverFixture<R, E> {
readonly createRepo: (cwd: string) => Effect.Effect<void, E, R>;
readonly writeFile: (
@@ -71,11 +67,7 @@ export function runVcsDriverContractSuite<R, E>(input: VcsDriverContractSuiteInp
yield* input.fixture.writeFile(cwd, "src/index.ts", "export const value = 1;\n");
const identity = yield* driver.detectRepository(cwd);
assert.equal(identity?.kind, input.kind);
assert.isTrue(
normalizePathForComparison(identity?.rootPath ?? "").endsWith(
normalizePathForComparison(cwd),
),
);
assert.isTrue(identity?.rootPath.endsWith(cwd));
assert.equal(identity?.freshness.source, "live-local");
assert.isTrue(DateTime.isDateTime(identity?.freshness.observedAt));
assert.isTrue(Option.isNone(identity?.freshness.expiresAt ?? Option.none()));
+1 -41
View File
@@ -9,7 +9,6 @@ import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import {
DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL,
type AuthAccessStreamEvent,
AuthSessionId,
CommandId,
@@ -181,14 +180,6 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
const serverEnvironment = yield* ServerEnvironment;
const serverAuth = yield* ServerAuth;
const sourceControlDiscovery = yield* SourceControlDiscoveryLayer.SourceControlDiscovery;
const automaticGitFetchInterval = serverSettings.getSettings.pipe(
Effect.map((settings) => settings.automaticGitFetchInterval),
Effect.catch((cause) =>
Effect.logWarning("Failed to read automatic Git fetch interval setting", {
detail: cause.message,
}).pipe(Effect.as(DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL)),
),
);
const sourceControlRepositories = yield* SourceControlRepositoryService;
const bootstrapCredentials = yield* BootstrapCredentialService;
const sessions = yield* SessionCredentialService;
@@ -317,7 +308,6 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
}),
);
case "thread.deleted":
case "thread.archived":
return Effect.succeed(
Option.some({
kind: "thread-removed" as const,
@@ -325,17 +315,6 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
threadId: event.payload.threadId,
}),
);
case "thread.unarchived":
return projectionSnapshotQuery.getThreadShellById(event.payload.threadId).pipe(
Effect.map((thread) =>
Option.map(thread, (nextThread) => ({
kind: "thread-upserted" as const,
sequence: event.sequence,
thread: nextThread,
})),
),
Effect.catch(() => Effect.succeed(Option.none())),
);
default:
if (event.aggregateKind !== "thread") {
return Effect.succeed(Option.none());
@@ -755,23 +734,6 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
}),
{ "rpc.aggregate": "orchestration" },
),
[ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot]: (_input) =>
observeRpcEffect(
ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot,
projectionSnapshotQuery.getArchivedShellSnapshot().pipe(
Effect.tapError((cause) =>
Effect.logError("orchestration archived shell snapshot load failed", { cause }),
),
Effect.mapError(
(cause) =>
new OrchestrationGetSnapshotError({
message: "Failed to load archived orchestration shell snapshot",
cause,
}),
),
),
{ "rpc.aggregate": "orchestration" },
),
[ORCHESTRATION_WS_METHODS.subscribeThread]: (input) =>
observeRpcStreamEffect(
ORCHESTRATION_WS_METHODS.subscribeThread,
@@ -990,9 +952,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
[WS_METHODS.subscribeVcsStatus]: (input) =>
observeRpcStream(
WS_METHODS.subscribeVcsStatus,
vcsStatusBroadcaster.streamStatus(input, {
automaticRemoteRefreshInterval: automaticGitFetchInterval,
}),
vcsStatusBroadcaster.streamStatus(input),
{
"rpc.aggregate": "vcs",
},
+1 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/web",
"version": "0.0.23",
"version": "0.0.22",
"private": true,
"type": "module",
"scripts": {
@@ -50,7 +50,6 @@
"@types/babel__core": "^7.20.5",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@vercel/config": "^0.3.0",
"@vitejs/plugin-react": "^6.0.0",
"@vitest/browser-playwright": "^4.0.18",
"babel-plugin-react-compiler": "^19.0.0-beta-e552027-20250112",
-20
View File
@@ -34,24 +34,4 @@ describe("branding", () => {
expect(branding.APP_STAGE_LABEL).toBe("Nightly");
expect(branding.APP_DISPLAY_NAME).toBe("T3 Code (Nightly)");
});
it("normalizes hosted app channel metadata", async () => {
vi.stubEnv("VITE_HOSTED_APP_CHANNEL", "nightly");
const branding = await import("./branding");
expect(branding.HOSTED_APP_CHANNEL).toBe("nightly");
expect(branding.HOSTED_APP_CHANNEL_LABEL).toBe("Nightly");
expect(branding.APP_STAGE_LABEL).toBe("Nightly");
expect(branding.APP_DISPLAY_NAME).toBe("T3 Code (Nightly)");
});
it("ignores unknown hosted app channels", async () => {
vi.stubEnv("VITE_HOSTED_APP_CHANNEL", "preview");
const branding = await import("./branding");
expect(branding.HOSTED_APP_CHANNEL).toBeNull();
expect(branding.HOSTED_APP_CHANNEL_LABEL).toBeNull();
});
});
+1 -8
View File
@@ -9,17 +9,10 @@ function readInjectedDesktopAppBranding(): DesktopAppBranding | null {
}
const injectedDesktopAppBranding = readInjectedDesktopAppBranding();
const hostedAppChannel = import.meta.env.VITE_HOSTED_APP_CHANNEL?.trim().toLowerCase();
export const HOSTED_APP_CHANNEL =
hostedAppChannel === "latest" || hostedAppChannel === "nightly" ? hostedAppChannel : null;
export const HOSTED_APP_CHANNEL_LABEL =
HOSTED_APP_CHANNEL === "nightly" ? "Nightly" : HOSTED_APP_CHANNEL === "latest" ? "Latest" : null;
export const APP_BASE_NAME = injectedDesktopAppBranding?.baseName ?? "T3 Code";
export const APP_STAGE_LABEL =
injectedDesktopAppBranding?.stageLabel ??
HOSTED_APP_CHANNEL_LABEL ??
(import.meta.env.DEV ? "Dev" : "Alpha");
injectedDesktopAppBranding?.stageLabel ?? (import.meta.env.DEV ? "Dev" : "Alpha");
export const APP_DISPLAY_NAME =
injectedDesktopAppBranding?.displayName ?? `${APP_BASE_NAME} (${APP_STAGE_LABEL})`;
export const APP_VERSION = import.meta.env.APP_VERSION || "0.0.0";
+2 -8
View File
@@ -18,13 +18,11 @@ import {
WS_METHODS,
OrchestrationSessionStatus,
DEFAULT_SERVER_SETTINGS,
ServerConfig as ServerConfigSchema,
} from "@t3tools/contracts";
import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime";
import { createModelCapabilities, createModelSelection } from "@t3tools/shared/model";
import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { HttpResponse, http, ws } from "msw";
import { setupWorker } from "msw/browser";
import { page } from "vitest/browser";
@@ -108,7 +106,6 @@ const rpcHarness = new BrowserWsRpcHarness();
const wsRequests = rpcHarness.requests;
let customWsRpcResolver: ((body: NormalizedWsRpcRequestBody) => unknown | undefined) | null = null;
const wsLink = ws.link(/ws(s)?:\/\/.*/);
const encodeServerConfig = Schema.encodeSync(ServerConfigSchema);
interface ViewportSpec {
name: string;
@@ -221,9 +218,6 @@ function createMockEnvironmentApi(input: {
getFullThreadDiff: (() => {
throw new Error("Not implemented in browser test.");
}) as EnvironmentApi["orchestration"]["getFullThreadDiff"],
getArchivedShellSnapshot: (() => {
throw new Error("Not implemented in browser test.");
}) as EnvironmentApi["orchestration"]["getArchivedShellSnapshot"],
subscribeShell: (() => () => undefined) as EnvironmentApi["orchestration"]["subscribeShell"],
subscribeThread: (() => () =>
undefined) as EnvironmentApi["orchestration"]["subscribeThread"],
@@ -958,7 +952,7 @@ function resolveWsRpc(body: NormalizedWsRpcRequestBody): unknown {
}
const tag = body._tag;
if (tag === WS_METHODS.serverGetConfig) {
return encodeServerConfig(fixture.serverConfig);
return fixture.serverConfig;
}
if (tag === WS_METHODS.serverDiscoverSourceControl) {
return {
@@ -1665,7 +1659,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
{
version: 1,
type: "snapshot",
config: encodeServerConfig(fixture.serverConfig),
config: fixture.serverConfig,
},
];
}
+5 -5
View File
@@ -119,10 +119,7 @@ import { getProviderModelCapabilities, resolveSelectableProvider } from "../prov
import { useSettings } from "../hooks/useSettings";
import { resolveAppModelSelectionForInstance } from "../modelSelection";
import { isTerminalFocused } from "../lib/terminalFocus";
import {
deriveLogicalProjectKeyFromSettings,
selectProjectGroupingSettings,
} from "../logicalProject";
import { deriveLogicalProjectKeyFromSettings } from "../logicalProject";
import {
reconnectSavedEnvironment,
useSavedEnvironmentRegistryStore,
@@ -945,7 +942,10 @@ export default function ChatView(props: ChatViewProps) {
},
[],
);
const projectGroupingSettings = useSettings(selectProjectGroupingSettings);
const projectGroupingSettings = useSettings((settings) => ({
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
}));
const logicalProjectEnvironments = useMemo(() => {
if (!activeProject) return [];
const logicalKey = deriveLogicalProjectKeyFromSettings(activeProject, projectGroupingSettings);
@@ -1434,6 +1434,7 @@ export default function GitActionsControl({
description: result.toast.description,
timeout: 0,
actionProps: toastActionProps,
actionVariant: "outline",
data: successToastData,
}),
);
@@ -11,15 +11,12 @@ import {
ProviderInstanceId,
type ServerConfig,
type ServerLifecycleWelcomePayload,
ServerConfig as ServerConfigSchema,
ServerSettings,
type ThreadId,
WS_METHODS,
} from "@t3tools/contracts";
import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
import { ws, http, HttpResponse } from "msw";
import { setupWorker } from "msw/browser";
import * as Schema from "effect/Schema";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { render } from "vitest-browser-react";
@@ -53,8 +50,6 @@ interface TestFixture {
let fixture: TestFixture;
const rpcHarness = new BrowserWsRpcHarness();
const encodeServerConfig = Schema.encodeSync(ServerConfigSchema);
const encodeServerSettings = Schema.encodeSync(ServerSettings);
const wsLink = ws.link(/ws(s)?:\/\/.*/);
@@ -259,7 +254,7 @@ function buildFixture(): TestFixture {
function resolveWsRpc(tag: string): unknown {
if (tag === WS_METHODS.serverGetConfig) {
return encodeServerConfig(fixture.serverConfig);
return fixture.serverConfig;
}
if (tag === WS_METHODS.vcsListRefs) {
return {
@@ -399,7 +394,7 @@ async function waitForServerConfigStreamReady(): Promise<void> {
rpcHarness.emitStreamValue(WS_METHODS.subscribeServerConfig, {
version: 1,
type: "settingsUpdated",
payload: { settings: encodeServerSettings(fixture.serverConfig.settings) },
payload: { settings: fixture.serverConfig.settings },
});
try {
@@ -490,7 +485,7 @@ describe("Keybindings update toast", () => {
{
version: 1,
type: "snapshot",
config: encodeServerConfig(fixture.serverConfig),
config: fixture.serverConfig,
},
];
}
+8 -3
View File
@@ -183,7 +183,6 @@ import {
derivePhysicalProjectKey,
deriveProjectGroupingOverrideKey,
getProjectOrderKey,
selectProjectGroupingSettings,
} from "../logicalProject";
import {
useSavedEnvironmentRegistryStore,
@@ -941,7 +940,10 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
const defaultThreadEnvMode = useSettings<ThreadEnvMode>(
(settings) => settings.defaultThreadEnvMode,
);
const projectGroupingSettings = useSettings(selectProjectGroupingSettings);
const projectGroupingSettings = useSettings((settings) => ({
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
}));
const { updateSettings } = useUpdateSettings();
const sidebarThreadPreviewCount = useSettings<SidebarThreadPreviewCount>(
(settings) => settings.sidebarThreadPreviewCount,
@@ -2798,7 +2800,10 @@ export default function Sidebar() {
const sidebarThreadSortOrder = useSettings((s) => s.sidebarThreadSortOrder);
const sidebarProjectSortOrder = useSettings((s) => s.sidebarProjectSortOrder);
const sidebarProjectGroupingMode = useSettings((s) => s.sidebarProjectGroupingMode);
const projectGroupingSettings = useSettings(selectProjectGroupingSettings);
const projectGroupingSettings = useSettings((settings) => ({
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
}));
const sidebarThreadPreviewCount = useSettings((s) => s.sidebarThreadPreviewCount);
const { updateSettings } = useUpdateSettings();
const { handleNewThread } = useNewThreadHandler();
@@ -1,4 +1,4 @@
import { type ReactNode, useEffect, useEffectEvent, useRef } from "react";
import { type ReactNode, useEffect, useEffectEvent, useRef, useState } from "react";
import { type SlowRpcAckRequest, useSlowRpcAckRequests } from "../rpc/requestLatencyState";
import {
@@ -147,12 +147,7 @@ export function shouldRestartStalledReconnect(
export function WebSocketConnectionCoordinator() {
const status = useWsConnectionStatus();
useWebSocketConnectionCoordinatorEffects(status);
return null;
}
function useWebSocketConnectionCoordinatorEffects(status: WsConnectionStatus) {
const [nowMs, setNowMs] = useState(() => Date.now());
const lastForcedReconnectAtRef = useRef(0);
const toastIdRef = useRef<ReturnType<typeof toastManager.add> | null>(null);
const toastResetTimerRef = useRef<number | null>(null);
@@ -206,7 +201,73 @@ function useWebSocketConnectionCoordinatorEffects(status: WsConnectionStatus) {
runReconnect(false);
});
const syncConnectionToast = useEffectEvent((nowMs: number) => {
useEffect(() => {
const handleOnline = () => {
triggerAutoReconnect("online");
};
const handleFocus = () => {
triggerAutoReconnect("focus");
};
syncBrowserOnlineStatus();
window.addEventListener("online", handleOnline);
window.addEventListener("offline", syncBrowserOnlineStatus);
window.addEventListener("focus", handleFocus);
return () => {
window.removeEventListener("online", handleOnline);
window.removeEventListener("offline", syncBrowserOnlineStatus);
window.removeEventListener("focus", handleFocus);
};
}, []);
useEffect(() => {
if (status.reconnectPhase !== "waiting" || status.nextRetryAt === null) {
return;
}
setNowMs(Date.now());
const intervalId = window.setInterval(() => {
setNowMs(Date.now());
}, 1_000);
return () => {
window.clearInterval(intervalId);
};
}, [status.nextRetryAt, status.reconnectPhase]);
useEffect(() => {
if (
status.reconnectPhase !== "waiting" ||
status.nextRetryAt === null ||
!status.online ||
!status.hasConnected
) {
return;
}
const nextRetryAt = status.nextRetryAt;
const timeoutMs = Math.max(0, new Date(nextRetryAt).getTime() - Date.now()) + 1_500;
const timeoutId = window.setTimeout(() => {
const currentStatus = getWsConnectionStatus();
if (!shouldRestartStalledReconnect(currentStatus, nextRetryAt)) {
return;
}
runReconnect(false);
}, timeoutMs);
return () => {
window.clearTimeout(timeoutId);
};
}, [
status.hasConnected,
status.nextRetryAt,
status.online,
status.reconnectAttemptCount,
status.reconnectPhase,
]);
useEffect(() => {
const uiState = getWsConnectionUiState(status);
const previousUiState = previousUiStateRef.current;
const previousDisconnectedAt = previousDisconnectedAtRef.current;
@@ -304,76 +365,7 @@ function useWebSocketConnectionCoordinatorEffects(status: WsConnectionStatus) {
previousUiStateRef.current = uiState;
previousDisconnectedAtRef.current = status.disconnectedAt;
});
useEffect(() => {
const handleOnline = () => {
triggerAutoReconnect("online");
};
const handleFocus = () => {
triggerAutoReconnect("focus");
};
syncBrowserOnlineStatus();
window.addEventListener("online", handleOnline);
window.addEventListener("offline", syncBrowserOnlineStatus);
window.addEventListener("focus", handleFocus);
return () => {
window.removeEventListener("online", handleOnline);
window.removeEventListener("offline", syncBrowserOnlineStatus);
window.removeEventListener("focus", handleFocus);
};
}, []);
useEffect(() => {
if (status.reconnectPhase !== "waiting" || status.nextRetryAt === null) {
return;
}
const intervalId = window.setInterval(() => {
syncConnectionToast(Date.now());
}, 1_000);
return () => {
window.clearInterval(intervalId);
};
}, [status.nextRetryAt, status.reconnectPhase]);
useEffect(() => {
if (
status.reconnectPhase !== "waiting" ||
status.nextRetryAt === null ||
!status.online ||
!status.hasConnected
) {
return;
}
const nextRetryAt = status.nextRetryAt;
const timeoutMs = Math.max(0, new Date(nextRetryAt).getTime() - Date.now()) + 1_500;
const timeoutId = window.setTimeout(() => {
const currentStatus = getWsConnectionStatus();
if (!shouldRestartStalledReconnect(currentStatus, nextRetryAt)) {
return;
}
runReconnect(false);
}, timeoutMs);
return () => {
window.clearTimeout(timeoutId);
};
}, [
status.hasConnected,
status.nextRetryAt,
status.online,
status.reconnectAttemptCount,
status.reconnectPhase,
]);
useEffect(() => {
syncConnectionToast(Date.now());
}, [status]);
}, [nowMs, status]);
useEffect(() => {
return () => {
@@ -382,6 +374,8 @@ function useWebSocketConnectionCoordinatorEffects(status: WsConnectionStatus) {
}
};
}, []);
return null;
}
export function SlowRpcAckToastCoordinator() {
@@ -48,8 +48,6 @@ vi.mock("@legendapp/list/react", async () => {
import { MessagesTimeline } from "./MessagesTimeline";
const MESSAGE_CREATED_AT = "2026-04-13T12:00:00.000Z";
function buildProps() {
return {
isWorking: false,
@@ -75,27 +73,6 @@ function buildProps() {
};
}
function buildLongUserMessageText(tail = "deep hidden detail only after expand") {
return Array.from({ length: 9 }, (_, index) =>
index === 8 ? tail : `Line ${index + 1}: ${"verbose prompt content ".repeat(8).trim()}`,
).join("\n");
}
function buildUserTimelineEntry(text: string) {
return {
id: "entry-1",
kind: "message" as const,
createdAt: MESSAGE_CREATED_AT,
message: {
id: "message-1" as never,
role: "user" as const,
text,
createdAt: MESSAGE_CREATED_AT,
streaming: false,
},
};
}
describe("MessagesTimeline", () => {
afterEach(() => {
scrollToEndSpy.mockReset();
@@ -180,87 +157,4 @@ describe("MessagesTimeline", () => {
await screen.unmount();
}
});
it("starts long user messages collapsed by default", async () => {
const screen = await render(
<MessagesTimeline
{...buildProps()}
timelineEntries={[buildUserTimelineEntry(buildLongUserMessageText())]}
/>,
);
try {
const toggle = page.getByRole("button", { name: "Show full message" });
await expect.element(toggle).toBeVisible();
await expect.element(toggle).toHaveAttribute("aria-expanded", "false");
const messageBody = document.querySelector(
"[data-user-message-body='true']",
) as HTMLDivElement | null;
expect(messageBody?.getAttribute("data-user-message-collapsed")).toBe("true");
expect(messageBody?.className).toContain("max-h-44");
expect(messageBody?.className).toContain("overflow-hidden");
expect(messageBody?.getAttribute("data-user-message-fade")).toBe("true");
expect(messageBody?.style.maskImage).toContain("linear-gradient");
} finally {
await screen.unmount();
}
});
it("expands and re-collapses long user messages from the toggle", async () => {
const screen = await render(
<MessagesTimeline
{...buildProps()}
timelineEntries={[buildUserTimelineEntry(buildLongUserMessageText())]}
/>,
);
try {
const expandButton = page.getByRole("button", { name: "Show full message" });
await expect.element(expandButton).toBeVisible();
expect(document.body.textContent ?? "").toContain("deep hidden detail only after expand");
await expandButton.click();
const collapseButton = page.getByRole("button", { name: "Show less" });
await expect.element(collapseButton).toBeVisible();
await expect.element(collapseButton).toHaveAttribute("aria-expanded", "true");
let messageBody = document.querySelector("[data-user-message-body='true']");
expect(messageBody?.getAttribute("data-user-message-collapsed")).toBe("false");
expect(messageBody?.className).not.toContain("max-h-44");
expect(messageBody?.getAttribute("data-user-message-fade")).toBe("false");
expect((messageBody as HTMLDivElement | null)?.style.maskImage ?? "").toBe("");
await collapseButton.click();
await expect.element(page.getByRole("button", { name: "Show full message" })).toBeVisible();
messageBody = document.querySelector("[data-user-message-body='true']");
expect(messageBody?.getAttribute("data-user-message-collapsed")).toBe("true");
expect(messageBody?.className).toContain("max-h-44");
expect(messageBody?.getAttribute("data-user-message-fade")).toBe("true");
expect((messageBody as HTMLDivElement | null)?.style.maskImage).toContain("linear-gradient");
} finally {
await screen.unmount();
}
});
it("starts the newest long user prompt collapsed", async () => {
const screen = await render(
<MessagesTimeline
{...buildProps()}
timelineEntries={[buildUserTimelineEntry(buildLongUserMessageText("latest long prompt"))]}
/>,
);
try {
await expect.element(page.getByRole("button", { name: "Show full message" })).toBeVisible();
const messageBody = document.querySelector("[data-user-message-body='true']");
expect(messageBody?.getAttribute("data-user-message-collapsed")).toBe("true");
} finally {
await screen.unmount();
}
});
});
@@ -73,7 +73,6 @@ beforeAll(() => {
});
const ACTIVE_THREAD_ENVIRONMENT_ID = EnvironmentId.make("environment-local");
const MESSAGE_CREATED_AT = "2026-03-17T19:12:28.000Z";
function buildProps() {
return {
@@ -100,73 +99,33 @@ function buildProps() {
};
}
function buildLongUserMessageText(tail = "deep hidden detail only after expand") {
return Array.from({ length: 9 }, (_, index) =>
index === 8 ? tail : `Line ${index + 1}: ${"verbose prompt content ".repeat(8).trim()}`,
).join("\n");
}
function buildUserTimelineEntry(text: string) {
return {
id: "entry-1",
kind: "message" as const,
createdAt: MESSAGE_CREATED_AT,
message: {
id: MessageId.make("message-1"),
role: "user" as const,
text,
createdAt: MESSAGE_CREATED_AT,
streaming: false,
},
};
}
describe("MessagesTimeline", () => {
it("renders collapse controls for long user messages", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
timelineEntries={[buildUserTimelineEntry(buildLongUserMessageText())]}
/>,
);
expect(markup).toContain("Show full message");
expect(markup).toContain('data-user-message-collapsed="true"');
expect(markup).toContain('data-user-message-fade="true"');
expect(markup).toContain('data-user-message-footer="true"');
});
it("does not render collapse controls for short user messages", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
timelineEntries={[buildUserTimelineEntry("Short prompt.")]}
/>,
);
expect(markup).not.toContain("Show full message");
expect(markup).toContain('data-user-message-collapsible="false"');
});
it("renders inline terminal labels with the composer chip UI", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
timelineEntries={[
buildUserTimelineEntry(
[
buildLongUserMessageText("yoo what's @terminal-1:1-5 mean"),
"",
"<terminal_context>",
"- Terminal 1 lines 1-5:",
" 1 | julius@mac effect-http-ws-cli % bun i",
" 2 | bun install v1.3.9 (cf6cdbbb)",
"</terminal_context>",
].join("\n"),
),
{
id: "entry-1",
kind: "message",
createdAt: "2026-03-17T19:12:28.000Z",
message: {
id: MessageId.make("message-2"),
role: "user",
text: [
"yoo what's @terminal-1:1-5 mean",
"",
"<terminal_context>",
"- Terminal 1 lines 1-5:",
" 1 | julius@mac effect-http-ws-cli % bun i",
" 2 | bun install v1.3.9 (cf6cdbbb)",
"</terminal_context>",
].join("\n"),
createdAt: "2026-03-17T19:12:28.000Z",
streaming: false,
},
},
]}
/>,
);
@@ -174,23 +133,8 @@ describe("MessagesTimeline", () => {
expect(markup).toContain("Terminal 1 lines 1-5");
expect(markup).toContain("lucide-terminal");
expect(markup).toContain("yoo what&#x27;s ");
expect(markup).toContain("Show full message");
}, 20_000);
it("keeps the copy button for collapsed long user messages", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
timelineEntries={[buildUserTimelineEntry(buildLongUserMessageText())]}
/>,
);
expect(markup).toContain('aria-label="Copy link"');
expect(markup).toContain('data-user-message-collapsed="true"');
expect(markup).toContain('data-user-message-footer="true"');
});
it("renders context compaction entries in the normal work log", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
+18 -100
View File
@@ -365,24 +365,24 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
))}
</div>
)}
<CollapsibleUserMessageBody
text={displayedUserMessage.visibleText}
terminalContexts={terminalContexts}
skills={ctx.skills}
footer={
<>
<div className="flex items-center gap-1.5 opacity-0 transition-opacity duration-200 focus-within:opacity-100 group-hover:opacity-100">
{displayedUserMessage.copyText && (
<MessageCopyButton text={displayedUserMessage.copyText} />
)}
{canRevertAgentWork && <RevertUserMessageButton messageId={row.message.id} />}
</div>
<p className="text-right text-xs text-muted-foreground/50">
{formatTimestamp(row.message.createdAt, ctx.timestampFormat)}
</p>
</>
}
/>
{(displayedUserMessage.visibleText.trim().length > 0 || terminalContexts.length > 0) && (
<UserMessageBody
text={displayedUserMessage.visibleText}
terminalContexts={terminalContexts}
skills={ctx.skills}
/>
)}
<div className="mt-1.5 flex items-center justify-end gap-2">
<div className="flex items-center gap-1.5 opacity-0 transition-opacity duration-200 focus-within:opacity-100 group-hover:opacity-100">
{displayedUserMessage.copyText && (
<MessageCopyButton text={displayedUserMessage.copyText} />
)}
{canRevertAgentWork && <RevertUserMessageButton messageId={row.message.id} />}
</div>
<p className="text-right text-xs text-muted-foreground/50">
{formatTimestamp(row.message.createdAt, ctx.timestampFormat)}
</p>
</div>
</div>
</div>
);
@@ -755,88 +755,6 @@ const UserMessageTerminalContextInlineLabel = memo(
},
);
const MAX_COLLAPSED_USER_MESSAGE_LINES = 8;
const MAX_COLLAPSED_USER_MESSAGE_LENGTH = 600;
const COLLAPSED_USER_MESSAGE_FADE_HEIGHT_REM = 1.75;
const COLLAPSED_USER_MESSAGE_FADE_MASK = `linear-gradient(to bottom, black calc(100% - ${COLLAPSED_USER_MESSAGE_FADE_HEIGHT_REM}rem), transparent)`;
function shouldCollapseUserMessage(text: string): boolean {
if (text.trim().length === 0) {
return false;
}
return (
text.length > MAX_COLLAPSED_USER_MESSAGE_LENGTH ||
text.split("\n").length > MAX_COLLAPSED_USER_MESSAGE_LINES
);
}
const CollapsibleUserMessageBody = memo(function CollapsibleUserMessageBody(props: {
text: string;
terminalContexts: ParsedTerminalContextEntry[];
skills: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
footer?: ReactNode;
}) {
const [expanded, setExpanded] = useState(false);
const hasVisibleBody = props.text.trim().length > 0 || props.terminalContexts.length > 0;
const canCollapse = hasVisibleBody && shouldCollapseUserMessage(props.text);
const isCollapsed = canCollapse && !expanded;
return (
<div>
{hasVisibleBody ? (
<div
className={cn("relative", isCollapsed && "max-h-44 overflow-hidden")}
data-user-message-body="true"
data-user-message-collapsed={isCollapsed ? "true" : "false"}
data-user-message-collapsible={canCollapse ? "true" : "false"}
data-user-message-fade={isCollapsed ? "true" : "false"}
style={
isCollapsed
? {
WebkitMaskImage: COLLAPSED_USER_MESSAGE_FADE_MASK,
maskImage: COLLAPSED_USER_MESSAGE_FADE_MASK,
}
: undefined
}
>
<UserMessageBody
text={props.text}
terminalContexts={props.terminalContexts}
skills={props.skills}
/>
</div>
) : null}
{canCollapse || props.footer ? (
<div
className={cn(
"mt-1.5 flex items-center gap-2",
canCollapse && props.footer ? "justify-between" : "justify-end",
)}
data-user-message-footer="true"
>
{canCollapse ? (
<Button
type="button"
size="xs"
variant="ghost"
aria-expanded={expanded}
data-scroll-anchor-ignore
onClick={() => setExpanded((value) => !value)}
className="-ml-1 h-6 rounded-md px-1.5 text-xs text-muted-foreground/72 hover:bg-muted/55 hover:text-foreground/85"
>
{expanded ? "Show less" : "Show full message"}
</Button>
) : null}
{props.footer ? (
<div className="ml-auto flex items-center gap-2">{props.footer}</div>
) : null}
</div>
) : null}
</div>
);
});
const UserMessageBody = memo(function UserMessageBody(props: {
text: string;
terminalContexts: ParsedTerminalContextEntry[];
@@ -2662,26 +2662,14 @@ export function ConnectionsSettings() {
}
}}
>
<Tooltip>
<TooltipTrigger
render={
<DialogTrigger
render={
<Button
size="xs"
variant="ghost"
className="h-5 gap-1 rounded-sm px-1 text-[11px] font-normal text-muted-foreground/60 hover:text-muted-foreground"
aria-label="Add environment"
>
<PlusIcon className="size-3" />
<span>Add environment</span>
</Button>
}
/>
}
/>
<TooltipPopup side="top">Add environment</TooltipPopup>
</Tooltip>
<DialogTrigger
render={
<Button size="xs" variant="outline">
<PlusIcon className="size-3" />
Add environment
</Button>
}
/>
<DialogPopup className="max-h-[80dvh] sm:max-w-3xl">
<DialogHeader>
<DialogTitle>Add Environment</DialogTitle>
@@ -648,7 +648,7 @@ export function ProviderInstanceCard({
);
const authRowNode = (
<p className="flex min-w-0 flex-wrap items-center gap-x-1 text-xs text-muted-foreground/80">
<p className="flex min-w-0 flex-wrap items-center gap-x-1 text-xs text-muted-foreground">
{hasAuthenticatedEmail ? (
<>
<span>Authenticated as</span>
@@ -1256,47 +1256,10 @@ describe("SourceControlSettingsPanel discovery states", () => {
</AppAtomRegistryProvider>,
);
await expect.element(page.getByRole("switch", { name: "Git availability" })).toBeDisabled();
await expect.element(page.getByRole("heading", { name: "Git" })).toBeInTheDocument();
await expect.element(page.getByText("Nothing detected yet")).not.toBeInTheDocument();
});
it("shows Git fetch interval settings inside the Git details dropdown", async () => {
setSourceControlDiscoveryStub(async () => ({
versionControlSystems: [
{
kind: "git",
label: "Git",
executable: "git",
implemented: true,
status: "available",
version: Option.some("git version 2.50.0"),
installHint: "Install Git.",
detail: Option.none(),
},
],
sourceControlProviders: [],
}));
mounted = await render(
<AppAtomRegistryProvider>
<SourceControlSettingsPanel />
</AppAtomRegistryProvider>,
);
const toggle = page.getByRole("button", { name: "Toggle Git details" });
await expect.element(toggle).toHaveAttribute("aria-expanded", "false");
await toggle.click();
await expect.element(toggle).toHaveAttribute("aria-expanded", "true");
await expect
.element(page.getByLabelText("Automatic Git fetch interval in seconds"))
.toBeVisible();
await expect
.element(page.getByText("Automatic Git fetches run every 30 seconds"))
.not.toBeInTheDocument();
});
it("does not rescan on remount while the discovery atom is fresh", async () => {
let calls = 0;
setSourceControlDiscoveryStub(async () => {
@@ -1324,7 +1287,7 @@ describe("SourceControlSettingsPanel discovery states", () => {
</AppAtomRegistryProvider>,
);
await expect.element(page.getByRole("switch", { name: "Git availability" })).toBeDisabled();
await expect.element(page.getByRole("heading", { name: "Git" })).toBeInTheDocument();
expect(calls).toBe(1);
const teardown = mounted.cleanup ?? mounted.unmount;
@@ -1338,7 +1301,7 @@ describe("SourceControlSettingsPanel discovery states", () => {
</AppAtomRegistryProvider>,
);
await expect.element(page.getByRole("switch", { name: "Git availability" })).toBeDisabled();
await expect.element(page.getByRole("heading", { name: "Git" })).toBeInTheDocument();
expect(calls).toBe(1);
});
});
@@ -14,9 +14,8 @@ import {
import { scopeThreadRef } from "@t3tools/client-runtime";
import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
import { createModelSelection } from "@t3tools/shared/model";
import * as Duration from "effect/Duration";
import * as Equal from "effect/Equal";
import { APP_VERSION, HOSTED_APP_CHANNEL, HOSTED_APP_CHANNEL_LABEL } from "../../branding";
import { APP_VERSION } from "../../branding";
import {
canCheckForUpdate,
getDesktopUpdateButtonTooltip,
@@ -27,7 +26,6 @@ import {
import { ProviderModelPicker } from "../chat/ProviderModelPicker";
import { TraitsPicker } from "../chat/TraitsPicker";
import { isElectron } from "../../env";
import { buildHostedChannelSelectionUrl, type HostedAppChannel } from "../../hostedPairing";
import { useTheme } from "../../hooks/useTheme";
import { useSettings, useUpdateSettings } from "../../hooks/useSettings";
import { useThreadActions } from "../../hooks/useThreadActions";
@@ -45,10 +43,14 @@ import {
} from "../../providerInstances";
import { ensureLocalApi, readLocalApi } from "../../localApi";
import { useShallow } from "zustand/react/shallow";
import { selectProjectsAcrossEnvironments, useStore } from "../../store";
import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState";
import {
selectProjectsAcrossEnvironments,
selectThreadShellsAcrossEnvironments,
useStore,
} from "../../store";
import { formatRelativeTime, formatRelativeTimeLabel } from "../../timestampFormat";
import { Button } from "../ui/button";
import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "../ui/empty";
import { DraftInput } from "../ui/draft-input";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
import { Switch } from "../ui/switch";
@@ -160,7 +162,6 @@ function AboutVersionSection() {
const updateState = updateStateQuery.data ?? null;
const hasDesktopBridge = typeof window !== "undefined" && Boolean(window.desktopBridge);
const selectedUpdateChannel = updateState?.channel ?? "latest";
const selectedHostedAppChannel = hasDesktopBridge ? null : HOSTED_APP_CHANNEL;
const handleUpdateChannelChange = useCallback(
(channel: DesktopUpdateChannel) => {
@@ -313,66 +314,36 @@ function AboutVersionSection() {
</Tooltip>
}
/>
{hasDesktopBridge ? (
<SettingsRow
title="Update track"
description="Stable follows full releases. Nightly follows the nightly desktop channel and can switch back to stable immediately."
control={
<Select
value={selectedUpdateChannel}
onValueChange={(value) => {
handleUpdateChannelChange(value as DesktopUpdateChannel);
}}
<SettingsRow
title="Update track"
description="Stable follows full releases. Nightly follows the nightly desktop channel and can switch back to stable immediately."
control={
<Select
value={selectedUpdateChannel}
onValueChange={(value) => {
handleUpdateChannelChange(value as DesktopUpdateChannel);
}}
>
<SelectTrigger
className="w-full sm:w-40"
aria-label="Update track"
disabled={!hasDesktopBridge || isChangingUpdateChannel}
>
<SelectTrigger
className="w-full sm:w-40"
aria-label="Update track"
disabled={isChangingUpdateChannel}
>
<SelectValue>
{selectedUpdateChannel === "nightly" ? "Nightly" : "Stable"}
</SelectValue>
</SelectTrigger>
<SelectPopup align="end" alignItemWithTrigger={false}>
<SelectItem hideIndicator value="latest">
Stable
</SelectItem>
<SelectItem hideIndicator value="nightly">
Nightly
</SelectItem>
</SelectPopup>
</Select>
}
/>
) : selectedHostedAppChannel ? (
<SettingsRow
title="Update track"
description="Switches the hosted app release channel."
control={
<Select
value={selectedHostedAppChannel}
onValueChange={(value) => {
if (value === selectedHostedAppChannel) return;
window.location.assign(
buildHostedChannelSelectionUrl({ channel: value as HostedAppChannel }),
);
}}
>
<SelectTrigger className="w-full sm:w-40" aria-label="Update track">
<SelectValue>{HOSTED_APP_CHANNEL_LABEL}</SelectValue>
</SelectTrigger>
<SelectPopup align="end" alignItemWithTrigger={false}>
<SelectItem hideIndicator value="latest">
Latest
</SelectItem>
<SelectItem hideIndicator value="nightly">
Nightly
</SelectItem>
</SelectPopup>
</Select>
}
/>
) : null}
<SelectValue>
{selectedUpdateChannel === "nightly" ? "Nightly" : "Stable"}
</SelectValue>
</SelectTrigger>
<SelectPopup align="end" alignItemWithTrigger={false}>
<SelectItem hideIndicator value="latest">
Stable
</SelectItem>
<SelectItem hideIndicator value="nightly">
Nightly
</SelectItem>
</SelectPopup>
</Select>
}
/>
</>
);
}
@@ -408,10 +379,6 @@ export function useSettingsRestore(onRestored?: () => void) {
...(settings.enableAssistantStreaming !== DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming
? ["Assistant output"]
: []),
...(Duration.toMillis(settings.automaticGitFetchInterval) !==
Duration.toMillis(DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval)
? ["Automatic Git fetch interval"]
: []),
...(settings.defaultThreadEnvMode !== DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode
? ["New thread mode"]
: []),
@@ -435,7 +402,6 @@ export function useSettingsRestore(onRestored?: () => void) {
settings.defaultThreadEnvMode,
settings.diffIgnoreWhitespace,
settings.diffWordWrap,
settings.automaticGitFetchInterval,
settings.enableAssistantStreaming,
settings.sidebarThreadPreviewCount,
settings.timestampFormat,
@@ -461,7 +427,6 @@ export function useSettingsRestore(onRestored?: () => void) {
sidebarThreadPreviewCount: DEFAULT_UNIFIED_SETTINGS.sidebarThreadPreviewCount,
autoOpenPlanSidebar: DEFAULT_UNIFIED_SETTINGS.autoOpenPlanSidebar,
enableAssistantStreaming: DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming,
automaticGitFetchInterval: DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval,
defaultThreadEnvMode: DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode,
addProjectBaseDirectory: DEFAULT_UNIFIED_SETTINGS.addProjectBaseDirectory,
confirmThreadArchive: DEFAULT_UNIFIED_SETTINGS.confirmThreadArchive,
@@ -892,7 +857,7 @@ export function GeneralSettingsPanel() {
</SettingsSection>
<SettingsSection title="About">
{isElectron || HOSTED_APP_CHANNEL ? (
{isElectron ? (
<AboutVersionSection />
) : (
<SettingsRow
@@ -1333,50 +1298,14 @@ export function ProviderSettingsPanel() {
export function ArchivedThreadsPanel() {
const projects = useStore(useShallow(selectProjectsAcrossEnvironments));
const threads = useStore(useShallow(selectThreadShellsAcrossEnvironments));
const { unarchiveThread, confirmAndDeleteThread } = useThreadActions();
const environmentIds = useMemo(
() => [...new Set(projects.map((project) => project.environmentId))],
[projects],
);
const {
snapshots: archivedSnapshots,
error: archiveError,
isLoading: isLoadingArchive,
refresh: refreshArchivedThreads,
} = useArchivedThreadSnapshots(environmentIds);
const archivedGroups = useMemo(() => {
const projectsByEnvironmentAndId = new Map(
archivedSnapshots.flatMap(({ environmentId, snapshot }) =>
snapshot.projects.map(
(project) =>
[
`${environmentId}:${project.id}`,
{
id: project.id,
environmentId,
name: project.title,
cwd: project.workspaceRoot,
},
] as const,
),
),
);
const threads = archivedSnapshots.flatMap(({ environmentId, snapshot }) =>
snapshot.threads.map((thread) => ({
...thread,
environmentId,
})),
);
return [...projectsByEnvironmentAndId.values()]
return projects
.map((project) => ({
project,
threads: threads
.filter(
(thread) =>
thread.projectId === project.id && thread.environmentId === project.environmentId,
)
.filter((thread) => thread.projectId === project.id && thread.archivedAt !== null)
.toSorted((left, right) => {
const leftKey = left.archivedAt ?? left.createdAt;
const rightKey = right.archivedAt ?? right.createdAt;
@@ -1384,7 +1313,7 @@ export function ArchivedThreadsPanel() {
}),
}))
.filter((group) => group.threads.length > 0);
}, [archivedSnapshots]);
}, [projects, threads]);
const handleArchivedThreadContextMenu = useCallback(
async (threadRef: ScopedThreadRef, position: { x: number; y: number }) => {
@@ -1401,7 +1330,6 @@ export function ArchivedThreadsPanel() {
if (clicked === "unarchive") {
try {
await unarchiveThread(threadRef);
refreshArchivedThreads();
} catch (error) {
toastManager.add(
stackedThreadToast({
@@ -1416,37 +1344,24 @@ export function ArchivedThreadsPanel() {
if (clicked === "delete") {
await confirmAndDeleteThread(threadRef);
refreshArchivedThreads();
}
},
[confirmAndDeleteThread, refreshArchivedThreads, unarchiveThread],
[confirmAndDeleteThread, unarchiveThread],
);
return (
<SettingsPageContainer>
{archivedGroups.length === 0 ? (
<SettingsSection title="Archived threads">
<SettingsRow
title={
<span className="inline-flex items-center gap-2">
{isLoadingArchive ? (
<LoaderIcon className="size-3.5 animate-spin text-muted-foreground" />
) : (
<ArchiveIcon className="size-3.5 text-muted-foreground" />
)}
{isLoadingArchive
? "Loading archived threads"
: archiveError
? "Could not load archived threads"
: "No archived threads"}
</span>
}
description={
isLoadingArchive
? "Checking connected environments."
: (archiveError ?? "Archived threads will appear here.")
}
/>
<Empty className="min-h-88">
<EmptyMedia variant="icon">
<ArchiveIcon />
</EmptyMedia>
<EmptyHeader>
<EmptyTitle>No archived threads</EmptyTitle>
<EmptyDescription>Archived threads will appear here.</EmptyDescription>
</EmptyHeader>
</Empty>
</SettingsSection>
) : (
archivedGroups.map(({ project, threads: projectThreads }) => (
@@ -1456,8 +1371,9 @@ export function ArchivedThreadsPanel() {
icon={<ProjectFavicon environmentId={project.environmentId} cwd={project.cwd} />}
>
{projectThreads.map((thread) => (
<SettingsRow
<div
key={thread.id}
className="flex items-center justify-between gap-3 border-t border-border px-4 py-3 first:border-t-0 sm:px-5"
onContextMenu={(event) => {
event.preventDefault();
void handleArchivedThreadContextMenu(
@@ -1468,40 +1384,39 @@ export function ArchivedThreadsPanel() {
},
);
}}
title={thread.title}
description={
<>
>
<div className="min-w-0 flex-1">
<h3 className="truncate text-sm font-medium text-foreground">{thread.title}</h3>
<p className="text-xs text-muted-foreground">
Archived {formatRelativeTimeLabel(thread.archivedAt ?? thread.createdAt)}
{" \u00b7 Created "}
{formatRelativeTimeLabel(thread.createdAt)}
</>
}
control={
<Button
type="button"
variant="outline"
size="sm"
className="h-7 shrink-0 cursor-pointer gap-1.5 px-2.5"
onClick={() =>
void unarchiveThread(scopeThreadRef(thread.environmentId, thread.id))
.then(() => refreshArchivedThreads())
.catch((error) => {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to unarchive thread",
description:
error instanceof Error ? error.message : "An error occurred.",
}),
);
})
}
>
<ArchiveX className="size-3.5" />
<span>Unarchive</span>
</Button>
}
/>
</p>
</div>
<Button
type="button"
variant="outline"
size="sm"
className="h-7 shrink-0 cursor-pointer gap-1.5 px-2.5"
onClick={() =>
void unarchiveThread(scopeThreadRef(thread.environmentId, thread.id)).catch(
(error) => {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to unarchive thread",
description:
error instanceof Error ? error.message : "An error occurred.",
}),
);
},
)
}
>
<ArchiveX className="size-3.5" />
<span>Unarchive</span>
</Button>
</div>
))}
</SettingsSection>
))
@@ -1,7 +1,6 @@
import { ChevronDownIcon, GitPullRequestIcon, RefreshCwIcon } from "lucide-react";
import * as Duration from "effect/Duration";
import { GitPullRequestIcon, RefreshCwIcon } from "lucide-react";
import * as Option from "effect/Option";
import { useState, type ReactNode } from "react";
import { type ReactNode } from "react";
import type {
SourceControlProviderKind,
SourceControlDiscoveryResult,
@@ -10,9 +9,7 @@ import type {
VcsDriverKind,
VcsDiscoveryItem,
} from "@t3tools/contracts";
import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
import { useSettings, useUpdateSettings } from "../../hooks/useSettings";
import { cn } from "../../lib/utils";
import {
refreshSourceControlDiscovery,
@@ -20,7 +17,6 @@ import {
} from "../../lib/sourceControlDiscoveryState";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
import { Collapsible, CollapsibleContent } from "../ui/collapsible";
import {
Empty,
EmptyContent,
@@ -30,13 +26,6 @@ import {
EmptyTitle,
} from "../ui/empty";
import { Skeleton } from "../ui/skeleton";
import {
NumberField,
NumberFieldDecrement,
NumberFieldGroup,
NumberFieldIncrement,
NumberFieldInput,
} from "../ui/number-field";
import { Switch } from "../ui/switch";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import {
@@ -49,7 +38,7 @@ import {
type Icon,
} from "../Icons";
import { RedactedSensitiveText } from "./RedactedSensitiveText";
import { SettingResetButton, SettingsPageContainer, SettingsSection } from "./settingsLayout";
import { SettingsPageContainer, SettingsSection } from "./settingsLayout";
const EMPTY_DISCOVERY_RESULT: SourceControlDiscoveryResult = {
versionControlSystems: [],
@@ -69,18 +58,6 @@ const VCS_ICONS: Partial<Record<VcsDriverKind, Icon>> = {
};
const SOURCE_CONTROL_SKELETON_ROWS = ["primary", "secondary"] as const;
const GIT_FETCH_INTERVAL_STEP_SECONDS = 5;
function durationToSeconds(duration: Duration.Duration): number {
return Math.round(Duration.toMillis(duration) / 1_000);
}
function normalizeFetchIntervalSeconds(value: number | null): number {
if (value === null || !Number.isFinite(value)) {
return 0;
}
return Math.max(0, Math.round(value));
}
function optionLabel(value: Option.Option<string>): string | null {
return Option.getOrNull(value);
@@ -169,7 +146,7 @@ function itemSummary({
}
if (item.status !== "available") {
return <span>Not available on this server: {item.installHint}</span>;
return <span>Not available on this server — {item.installHint}</span>;
}
if (auth) {
@@ -212,10 +189,8 @@ function itemSummary({
function DiscoveryItemRow({
item,
children,
}: {
readonly item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem;
readonly children?: ReactNode;
}) {
const version = optionLabel(item.version);
const enabled =
@@ -223,8 +198,6 @@ function DiscoveryItemRow({
const auth = isProviderDiscoveryItem(item) ? item.auth : null;
const authStatus = auth ? authPresentation(auth) : null;
const authAccount = auth ? optionLabel(auth.account) : null;
const [isExpanded, setIsExpanded] = useState(false);
const hasDetails = children !== undefined;
return (
<div
@@ -238,9 +211,9 @@ function DiscoveryItemRow({
<div className="min-w-0 flex-1 space-y-1">
<div className="flex min-w-0 flex-wrap items-center gap-2">
<SourceControlItemMark item={item} />
<span className="truncate text-[13px] font-semibold tracking-[-0.01em] text-foreground">
<h3 className="truncate text-[13px] font-semibold tracking-[-0.01em] text-foreground">
{item.label}
</span>
</h3>
{version ? <code className="text-xs text-muted-foreground">{version}</code> : null}
{isVcsNotReady(item) ? (
<Badge variant="warning" size="sm">
@@ -253,105 +226,17 @@ function DiscoveryItemRow({
</Badge>
) : null}
</div>
<p className="flex min-w-0 flex-wrap items-center gap-x-1 text-xs text-muted-foreground/80">
<p className="flex min-w-0 flex-wrap items-center gap-x-1 text-xs text-muted-foreground">
{itemSummary({ item, auth, authAccount })}
</p>
</div>
<div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
{hasDetails ? (
<Button
size="sm"
variant="ghost"
className="h-7 px-2 text-xs text-muted-foreground hover:text-foreground"
onClick={() => setIsExpanded((open) => !open)}
aria-expanded={isExpanded}
aria-label={`Toggle ${item.label} details`}
>
<ChevronDownIcon
className={cn("size-3.5 transition-transform", isExpanded && "rotate-180")}
/>
</Button>
) : null}
{!isVcsNotReady(item) ? (
<Switch checked={enabled} disabled aria-label={`${item.label} availability`} />
) : null}
</div>
</div>
</div>
{hasDetails ? (
<Collapsible open={isExpanded} onOpenChange={setIsExpanded}>
<CollapsibleContent>
<div className="border-t border-border/60 px-4 py-3 sm:px-5">{children}</div>
</CollapsibleContent>
</Collapsible>
) : null}
</div>
);
}
function GitFetchIntervalSettings() {
const automaticGitFetchInterval = useSettings((settings) => settings.automaticGitFetchInterval);
const { updateSettings } = useUpdateSettings();
const automaticGitFetchIntervalSeconds = durationToSeconds(automaticGitFetchInterval);
const defaultAutomaticGitFetchIntervalSeconds = durationToSeconds(
DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval,
);
const canResetFetchInterval =
automaticGitFetchIntervalSeconds !== defaultAutomaticGitFetchIntervalSeconds;
return (
<div className="grid gap-3">
<div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
<div className="min-w-0 space-y-1">
<div className="flex min-w-0 items-center gap-1">
<span className="text-xs font-medium text-foreground">Fetch interval</span>
<span
className={cn(
"inline-flex size-5 shrink-0 items-center justify-center transition-opacity",
canResetFetchInterval ? "opacity-100" : "pointer-events-none opacity-0",
)}
aria-hidden={!canResetFetchInterval}
>
{canResetFetchInterval ? (
<SettingResetButton
label="fetch interval"
onClick={() =>
updateSettings({
automaticGitFetchInterval: DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval,
})
}
/>
) : null}
</span>
</div>
<p className="max-w-2xl text-xs leading-relaxed text-muted-foreground">
Refresh remote branch status in the background. Set this to 0 seconds if Git credentials
or security keys should only be prompted by explicit Git actions.
</p>
</div>
<div className="flex shrink-0 items-center gap-2">
<NumberField
value={automaticGitFetchIntervalSeconds}
min={0}
step={GIT_FETCH_INTERVAL_STEP_SECONDS}
size="sm"
className="w-32"
onValueChange={(value) =>
updateSettings({
automaticGitFetchInterval: Duration.seconds(normalizeFetchIntervalSeconds(value)),
})
}
>
<NumberFieldGroup>
<NumberFieldDecrement aria-label="Decrease fetch interval" />
<NumberFieldInput aria-label="Automatic Git fetch interval in seconds" />
<NumberFieldIncrement aria-label="Increase fetch interval" />
</NumberFieldGroup>
</NumberField>
<span className="text-xs text-muted-foreground">seconds</span>
</div>
</div>
</div>
);
}
@@ -439,6 +324,7 @@ function EmptySourceControlDiscovery({
export function SourceControlSettingsPanel() {
const discovery = useSourceControlDiscovery();
const result = discovery.data ?? EMPTY_DISCOVERY_RESULT;
const hasDiscoveryItems =
result.versionControlSystems.length > 0 || result.sourceControlProviders.length > 0;
@@ -478,9 +364,7 @@ export function SourceControlSettingsPanel() {
{result.versionControlSystems.length > 0 ? (
<SettingsSection title="Version Control" headerAction={scanButton}>
{result.versionControlSystems.map((item) => (
<DiscoveryItemRow key={`vcs:${item.kind}`} item={item}>
{item.kind === "git" ? <GitFetchIntervalSettings /> : undefined}
</DiscoveryItemRow>
<DiscoveryItemRow key={`vcs:${item.kind}`} item={item} />
))}
</SettingsSection>
) : null}
@@ -52,9 +52,7 @@ export function SettingsRow({
resetAction,
control,
children,
className,
...rowProps
}: Omit<ComponentPropsWithoutRef<"div">, "title"> & {
}: {
title: ReactNode;
description: ReactNode;
status?: ReactNode;
@@ -64,11 +62,9 @@ export function SettingsRow({
}) {
return (
<div
{...rowProps}
className={cn(
"border-t border-border/60 px-4 first:border-t-0 sm:px-5",
children ? "pt-3.5 pb-0" : "py-3.5",
className,
)}
>
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
-1
View File
@@ -47,7 +47,6 @@ export function createEnvironmentApi(rpcClient: WsRpcClient): EnvironmentApi {
dispatchCommand: rpcClient.orchestration.dispatchCommand,
getTurnDiff: rpcClient.orchestration.getTurnDiff,
getFullThreadDiff: rpcClient.orchestration.getFullThreadDiff,
getArchivedShellSnapshot: rpcClient.orchestration.getArchivedShellSnapshot,
subscribeShell: (callback, options) =>
rpcClient.orchestration.subscribeShell(callback, options),
subscribeThread: (input, callback, options) =>
+5 -6
View File
@@ -10,11 +10,7 @@ import {
} from "../composerDraftStore";
import { newDraftId, newThreadId } from "../lib/utils";
import { orderItemsByPreferredIds } from "../components/Sidebar.logic";
import {
deriveLogicalProjectKeyFromSettings,
getProjectOrderKey,
selectProjectGroupingSettings,
} from "../logicalProject";
import { deriveLogicalProjectKeyFromSettings, getProjectOrderKey } from "../logicalProject";
import { selectProjectsAcrossEnvironments, useStore } from "../store";
import { createThreadSelectorByRef } from "../storeSelectors";
import { resolveThreadRouteTarget } from "../threadRoutes";
@@ -23,7 +19,10 @@ import { useSettings } from "./useSettings";
function useNewThreadState() {
const projects = useStore(useShallow((store) => selectProjectsAcrossEnvironments(store)));
const projectGroupingSettings = useSettings(selectProjectGroupingSettings);
const projectGroupingSettings = useSettings((settings) => ({
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
}));
const router = useRouter();
const getCurrentRouteTarget = useCallback(() => {
const currentRouteParams = router.state.matches[router.state.matches.length - 1]?.params ?? {};
+10 -24
View File
@@ -9,7 +9,6 @@ import { useComposerDraftStore } from "../composerDraftStore";
import { useNewThreadHandler } from "./useHandleNewThread";
import { ensureEnvironmentApi, readEnvironmentApi } from "../environmentApi";
import { invalidateGitQueries } from "../lib/gitReactQuery";
import { refreshArchivedThreadsForEnvironment } from "../lib/archivedThreadsState";
import { newCommandId } from "../lib/utils";
import { readLocalApi } from "../localApi";
import {
@@ -69,22 +68,19 @@ export function useThreadActions() {
throw new Error("Cannot archive a running thread.");
}
const currentRouteThreadRef = getCurrentRouteThreadRef();
const shouldNavigateToDraft =
currentRouteThreadRef?.threadId === threadRef.threadId &&
currentRouteThreadRef.environmentId === threadRef.environmentId;
const archiveCommand = api.orchestration.dispatchCommand({
await api.orchestration.dispatchCommand({
type: "thread.archive",
commandId: newCommandId(),
threadId: threadRef.threadId,
});
const currentRouteThreadRef = getCurrentRouteThreadRef();
if (shouldNavigateToDraft) {
if (
currentRouteThreadRef?.threadId === threadRef.threadId &&
currentRouteThreadRef.environmentId === threadRef.environmentId
) {
await handleNewThreadRef.current(scopeProjectRef(thread.environmentId, thread.projectId));
}
await archiveCommand;
refreshArchivedThreadsForEnvironment(threadRef.environmentId);
},
[getCurrentRouteThreadRef, resolveThreadTarget],
);
@@ -97,7 +93,6 @@ export function useThreadActions() {
commandId: newCommandId(),
threadId: target.threadId,
});
refreshArchivedThreadsForEnvironment(target.environmentId);
}, []);
const deleteThread = useCallback(
@@ -105,16 +100,7 @@ export function useThreadActions() {
const api = readEnvironmentApi(target.environmentId);
if (!api) return;
const resolved = resolveThreadTarget(target);
if (!resolved) {
// Thread not in main store (e.g. archived thread) — dispatch delete directly.
await api.orchestration.dispatchCommand({
type: "thread.delete",
commandId: newCommandId(),
threadId: target.threadId,
});
refreshArchivedThreadsForEnvironment(target.environmentId);
return;
}
if (!resolved) return;
const { thread, threadRef } = resolved;
const state = useStore.getState();
const threads = selectThreadsForEnvironment(state, threadRef.environmentId);
@@ -189,7 +175,6 @@ export function useThreadActions() {
commandId: newCommandId(),
threadId: threadRef.threadId,
});
refreshArchivedThreadsForEnvironment(threadRef.environmentId);
clearComposerDraftForThread(threadRef);
clearProjectDraftThreadById(
scopeProjectRef(threadRef.environmentId, thread.projectId),
@@ -267,12 +252,13 @@ export function useThreadActions() {
if (!api) return;
const localApi = readLocalApi();
const resolved = resolveThreadTarget(target);
if (!resolved) return;
const { thread } = resolved;
if (confirmThreadDelete && localApi) {
const title = resolved?.thread.title ?? "this thread";
const confirmed = await localApi.dialogs.confirm(
[
`Delete thread "${title}"?`,
`Delete thread "${thread.title}"?`,
"This permanently clears conversation history for this thread.",
].join("\n"),
);
-28
View File
@@ -1,7 +1,6 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import {
buildHostedChannelSelectionUrl,
buildHostedPairingUrl,
hasHostedPairingRequest,
isHostedStaticApp,
@@ -43,21 +42,6 @@ describe("hostedPairing", () => {
expect(url.hash).toBe("#token=pairing-token");
});
it("builds hosted channel selection URLs through the configured router origin", () => {
vi.stubEnv("VITE_HOSTED_APP_URL", "https://app.t3.codes");
const url = new URL(
buildHostedChannelSelectionUrl({
channel: "nightly",
}),
);
expect(url.origin).toBe("https://app.t3.codes");
expect(url.pathname).toBe("/__t3code/channel");
expect(url.searchParams.get("channel")).toBe("nightly");
expect(url.searchParams.has("next")).toBe(false);
});
it("ignores incomplete hosted pairing requests", () => {
expect(
hasHostedPairingRequest(new URL("https://app.t3.codes/pair?host=backend.example.com")),
@@ -79,16 +63,4 @@ describe("hostedPairing", () => {
vi.stubEnv("VITE_HTTP_URL", "https://backend.example.com");
expect(isHostedStaticApp(new URL("https://preview.t3.codes/"))).toBe(false);
});
it("detects hosted channel aliases as static apps", () => {
vi.stubEnv("VITE_HOSTED_APP_URL", "https://app.t3.codes");
vi.stubEnv("VITE_HOSTED_APP_CHANNEL", "nightly");
vi.stubEnv("VITE_HTTP_URL", "");
vi.stubEnv("VITE_WS_URL", "");
expect(isHostedStaticApp(new URL("https://nightly.app.t3.codes/"))).toBe(true);
vi.stubEnv("VITE_HTTP_URL", "https://backend.example.com");
expect(isHostedStaticApp(new URL("https://nightly.app.t3.codes/"))).toBe(false);
});
});
-19
View File
@@ -8,8 +8,6 @@ export interface HostedPairingRequest {
readonly label: string;
}
export type HostedAppChannel = "latest" | "nightly";
function configuredHostedAppUrl(): string {
return import.meta.env.VITE_HOSTED_APP_URL?.trim() || DEFAULT_HOSTED_APP_URL;
}
@@ -18,11 +16,6 @@ function configuredBackendUrl(): string {
return import.meta.env.VITE_HTTP_URL?.trim() || import.meta.env.VITE_WS_URL?.trim() || "";
}
function configuredHostedAppChannel(): HostedAppChannel | null {
const channel = import.meta.env.VITE_HOSTED_APP_CHANNEL?.trim().toLowerCase();
return channel === "latest" || channel === "nightly" ? channel : null;
}
function originFromUrl(value: string): string | null {
try {
return new URL(value).origin;
@@ -36,10 +29,6 @@ export function isHostedStaticApp(url: URL = new URL(window.location.href)): boo
return false;
}
if (configuredHostedAppChannel()) {
return true;
}
const hostedOrigin = originFromUrl(configuredHostedAppUrl());
return hostedOrigin !== null && url.origin === hostedOrigin;
}
@@ -79,11 +68,3 @@ export function buildHostedPairingUrl(input: {
return setPairingTokenOnUrl(url, input.token).toString();
}
export function buildHostedChannelSelectionUrl(input: {
readonly channel: HostedAppChannel;
}): string {
const url = new URL("/__t3code/channel", configuredHostedAppUrl());
url.searchParams.set("channel", input.channel);
return url.toString();
}
-106
View File
@@ -1,106 +0,0 @@
import { useAtomValue } from "@effect/atom-react";
import { EnvironmentId, type OrchestrationShellSnapshot } from "@t3tools/contracts";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
import { useCallback, useMemo } from "react";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { readEnvironmentApi } from "../environmentApi";
import { appAtomRegistry } from "../rpc/atomRegistry";
const ARCHIVED_THREADS_STALE_TIME_MS = 5_000;
const ARCHIVED_THREADS_IDLE_TTL_MS = 5 * 60_000;
const ARCHIVED_THREADS_ENVIRONMENT_KEY_SEPARATOR = "\u001f";
export type ArchivedSnapshotEntry = {
readonly environmentId: EnvironmentId;
readonly snapshot: OrchestrationShellSnapshot;
};
const knownArchivedThreadEnvironmentKeys = new Set<string>();
function makeArchivedThreadsEnvironmentKey(environmentIds: ReadonlyArray<EnvironmentId>): string {
return environmentIds.toSorted().join(ARCHIVED_THREADS_ENVIRONMENT_KEY_SEPARATOR);
}
function parseArchivedThreadsEnvironmentKey(key: string): ReadonlyArray<EnvironmentId> {
if (key.length === 0) {
return [];
}
return key
.split(ARCHIVED_THREADS_ENVIRONMENT_KEY_SEPARATOR)
.map((environmentId) => EnvironmentId.make(environmentId));
}
const archivedThreadSnapshotsAtom = Atom.family((environmentKey: string) => {
knownArchivedThreadEnvironmentKeys.add(environmentKey);
return Atom.make(
Effect.promise(async (): Promise<ReadonlyArray<ArchivedSnapshotEntry>> => {
const environmentIds = parseArchivedThreadsEnvironmentKey(environmentKey);
const snapshots = await Promise.all(
environmentIds.map(async (environmentId) => {
const api = readEnvironmentApi(environmentId);
if (!api) {
return null;
}
return {
environmentId,
snapshot: await api.orchestration.getArchivedShellSnapshot(),
};
}),
);
return snapshots.filter((snapshot) => snapshot !== null);
}),
).pipe(
Atom.swr({
staleTime: ARCHIVED_THREADS_STALE_TIME_MS,
revalidateOnMount: true,
}),
Atom.setIdleTTL(ARCHIVED_THREADS_IDLE_TTL_MS),
Atom.withLabel(`archived-thread-snapshots:${environmentKey}`),
);
});
function readArchivedThreadsError(
result: AsyncResult.AsyncResult<ReadonlyArray<ArchivedSnapshotEntry>, unknown>,
): string | null {
if (result._tag !== "Failure") {
return null;
}
const error = Cause.squash(result.cause);
return error instanceof Error ? error.message : "Failed to load archived threads.";
}
export function refreshArchivedThreadsForEnvironment(environmentId: EnvironmentId): void {
for (const key of knownArchivedThreadEnvironmentKeys) {
if (parseArchivedThreadsEnvironmentKey(key).includes(environmentId)) {
appAtomRegistry.refresh(archivedThreadSnapshotsAtom(key));
}
}
}
export function useArchivedThreadSnapshots(environmentIds: ReadonlyArray<EnvironmentId>): {
readonly snapshots: ReadonlyArray<ArchivedSnapshotEntry>;
readonly error: string | null;
readonly isLoading: boolean;
readonly refresh: () => void;
} {
const environmentKey = useMemo(
() => makeArchivedThreadsEnvironmentKey(environmentIds),
[environmentIds],
);
const atom = archivedThreadSnapshotsAtom(environmentKey);
const result = useAtomValue(atom);
const snapshots = Option.getOrElse(AsyncResult.value(result), () => []);
const refresh = useCallback(() => {
appAtomRegistry.refresh(atom);
}, [atom]);
return {
snapshots,
error: readArchivedThreadsError(result),
isLoading: result.waiting,
refresh,
};
}
-8
View File
@@ -1,6 +1,5 @@
import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime";
import type { ScopedProjectRef, SidebarProjectGroupingMode } from "@t3tools/contracts";
import type { UnifiedSettings } from "@t3tools/contracts/settings";
import { normalizeProjectPathForComparison } from "./lib/projectPaths";
import type { Project } from "./types";
@@ -11,13 +10,6 @@ export interface ProjectGroupingSettings {
export type ProjectGroupingMode = SidebarProjectGroupingMode;
export function selectProjectGroupingSettings(settings: UnifiedSettings): ProjectGroupingSettings {
return {
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
};
}
function uniqueNonEmptyValues(values: ReadonlyArray<string | null | undefined>): string[] {
const seen = new Set<string>();
const unique: string[] = [];
+4 -2
View File
@@ -33,7 +33,6 @@ import { useSettings } from "../hooks/useSettings";
import {
deriveLogicalProjectKeyFromSettings,
derivePhysicalProjectKeyFromPath,
selectProjectGroupingSettings,
} from "../logicalProject";
import {
getServerConfigUpdatedNotification,
@@ -282,7 +281,10 @@ function EventRouter() {
const setActiveEnvironmentId = useStore((store) => store.setActiveEnvironmentId);
const navigate = useNavigate();
const pathname = useLocation({ select: (loc) => loc.pathname });
const projectGroupingSettings = useSettings(selectProjectGroupingSettings);
const projectGroupingSettings = useSettings((settings) => ({
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
}));
const readPathname = useEffectEvent(() => pathname);
const handledBootstrapThreadIdRef = useRef<string | null>(null);
const seenServerConfigUpdateIdRef = useRef(getServerConfigUpdatedNotification()?.id ?? 0);
-7
View File
@@ -143,9 +143,6 @@ export interface WsRpcClient {
readonly dispatchCommand: RpcUnaryMethod<typeof ORCHESTRATION_WS_METHODS.dispatchCommand>;
readonly getTurnDiff: RpcUnaryMethod<typeof ORCHESTRATION_WS_METHODS.getTurnDiff>;
readonly getFullThreadDiff: RpcUnaryMethod<typeof ORCHESTRATION_WS_METHODS.getFullThreadDiff>;
readonly getArchivedShellSnapshot: RpcUnaryNoArgMethod<
typeof ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot
>;
readonly subscribeShell: RpcStreamMethod<typeof ORCHESTRATION_WS_METHODS.subscribeShell>;
readonly subscribeThread: RpcInputStreamMethod<typeof ORCHESTRATION_WS_METHODS.subscribeThread>;
};
@@ -291,10 +288,6 @@ export function createWsRpcClient(transport: WsTransport): WsRpcClient {
transport.request((client) => client[ORCHESTRATION_WS_METHODS.getTurnDiff](input)),
getFullThreadDiff: (input) =>
transport.request((client) => client[ORCHESTRATION_WS_METHODS.getFullThreadDiff](input)),
getArchivedShellSnapshot: () =>
transport.request((client) =>
client[ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot]({}),
),
subscribeShell: (listener, options) =>
transport.subscribe(
(client) => client[ORCHESTRATION_WS_METHODS.subscribeShell]({}),
+2 -5
View File
@@ -1,5 +1,4 @@
import { DEFAULT_SERVER_SETTINGS, ServerSettings, WS_METHODS } from "@t3tools/contracts";
import * as Schema from "effect/Schema";
import { DEFAULT_SERVER_SETTINGS, WS_METHODS } from "@t3tools/contracts";
import * as Stream from "effect/Stream";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -19,8 +18,6 @@ import {
} from "../rpc/wsConnectionState";
import { WsTransport } from "./wsTransport";
const encodeServerSettings = Schema.encodeSync(ServerSettings);
type WsEventType = "open" | "message" | "close" | "error";
type WsEvent = { code?: number; data?: unknown; reason?: string; type?: string };
type WsListener = (event?: WsEvent) => void;
@@ -1225,7 +1222,7 @@ describe("WsTransport", () => {
requestId: requestMessage.id,
exit: {
_tag: "Success",
value: encodeServerSettings(DEFAULT_SERVER_SETTINGS),
value: DEFAULT_SERVER_SETTINGS,
},
}),
);
-1
View File
@@ -6,7 +6,6 @@ interface ImportMetaEnv {
readonly VITE_HTTP_URL: string;
readonly VITE_WS_URL: string;
readonly VITE_HOSTED_APP_URL: string;
readonly VITE_HOSTED_APP_CHANNEL: string;
readonly APP_VERSION: string;
}
+1 -1
View File
@@ -35,5 +35,5 @@
}
]
},
"include": ["src", "vite.config.ts", "vercel.ts", "test"]
"include": ["src", "vite.config.ts", "test"]
}
+10
View File
@@ -0,0 +1,10 @@
{
"buildCommand": "turbo build --filter @t3tools/web && bun ../../scripts/apply-web-brand-assets.ts production",
"installCommand": "bun add -g turbo && bun install --filter '@t3tools/contracts' --filter '@t3tools/client-runtime' --filter '@t3tools/scripts' --filter '@t3tools/web'",
"rewrites": [
{
"source": "/(.*)",
"destination": "/index.html"
}
]
}
-66
View File
@@ -1,66 +0,0 @@
import { matchers, routes, type Transform, type VercelConfig } from "@vercel/config/v1";
const ROUTER_HOST = "app.t3.codes";
const HOSTED_WEB_CHANNEL_COOKIE = "t3code_web_channel";
const LATEST_ORIGIN = "https://latest.app.t3.codes";
const NIGHTLY_ORIGIN = "https://nightly.app.t3.codes";
const CLEAN_CHANNEL_QUERY_TRANSFORMS = [
{
type: "request.query",
op: "delete",
target: { key: "channel" },
},
] satisfies Transform[];
function channelCookie(channel: "latest" | "nightly"): string {
return [
`${HOSTED_WEB_CHANNEL_COOKIE}=${channel}`,
"Path=/",
"Max-Age=31536000",
"HttpOnly",
"Secure",
"SameSite=Lax",
].join("; ");
}
export const config: VercelConfig = {
buildCommand:
'turbo build --filter @t3tools/web && bun ../../scripts/apply-web-brand-assets.ts --channel "${VITE_HOSTED_APP_CHANNEL:-latest}"',
git: {
deploymentEnabled: false,
},
installCommand:
"bun add -g turbo && bun install --filter '@t3tools/contracts' --filter '@t3tools/client-runtime' --filter '@t3tools/scripts' --filter '@t3tools/web'",
routes: [
{
src: "/__t3code/channel",
has: [matchers.query("channel", "nightly")],
transforms: CLEAN_CHANNEL_QUERY_TRANSFORMS,
headers: {
Location: "/",
"Set-Cookie": channelCookie("nightly"),
},
status: 302,
},
{
src: "/__t3code/channel",
transforms: CLEAN_CHANNEL_QUERY_TRANSFORMS,
headers: {
Location: "/",
"Set-Cookie": channelCookie("latest"),
},
status: 302,
},
{
src: "/(.*)",
has: [matchers.host(ROUTER_HOST), matchers.cookie(HOSTED_WEB_CHANNEL_COOKIE, "nightly")],
dest: `${NIGHTLY_ORIGIN}/$1`,
},
{
src: "/(.*)",
has: [matchers.host(ROUTER_HOST)],
dest: `${LATEST_ORIGIN}/$1`,
},
],
rewrites: [routes.rewrite("/(.*)", "/index.html")],
};
+2 -9
View File
@@ -8,20 +8,14 @@ import pkg from "./package.json" with { type: "json" };
const port = Number(process.env.PORT ?? 5733);
const host = process.env.HOST?.trim() || "localhost";
const configuredWsUrl = process.env.VITE_WS_URL?.trim();
const configuredHostedAppChannel = process.env.VITE_HOSTED_APP_CHANNEL?.trim() || "";
const configuredAppVersion = process.env.APP_VERSION?.trim() || pkg.version;
const configuredHostedAppUrl = (() => {
const explicitHostedAppUrl = process.env.VITE_HOSTED_APP_URL?.trim();
if (explicitHostedAppUrl) {
return explicitHostedAppUrl;
}
if (process.env.VERCEL_ENV === "production" && process.env.VERCEL_PROJECT_PRODUCTION_URL) {
return `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`;
}
if (process.env.VERCEL_URL) {
return `https://${process.env.VERCEL_URL}`;
}
return undefined;
return process.env.VITE_HOSTED_APP_URL?.trim();
})();
const sourcemapEnv = process.env.T3CODE_WEB_SOURCEMAP?.trim().toLowerCase();
@@ -82,8 +76,7 @@ export default defineConfig({
// In dev mode, tell the web app where the WebSocket server lives
"import.meta.env.VITE_WS_URL": JSON.stringify(configuredWsUrl ?? ""),
"import.meta.env.VITE_HOSTED_APP_URL": JSON.stringify(configuredHostedAppUrl ?? ""),
"import.meta.env.VITE_HOSTED_APP_CHANNEL": JSON.stringify(configuredHostedAppChannel),
"import.meta.env.APP_VERSION": JSON.stringify(configuredAppVersion),
"import.meta.env.APP_VERSION": JSON.stringify(pkg.version),
},
resolve: {
tsconfigPaths: true,
-29
View File
@@ -124,7 +124,6 @@
"@types/babel__core": "^7.20.5",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@vercel/config": "^0.3.0",
"@vitejs/plugin-react": "^6.0.0",
"@vitest/browser-playwright": "^4.0.18",
"babel-plugin-react-compiler": "^19.0.0-beta-e552027-20250112",
@@ -928,14 +927,6 @@
"@ungap/structured-clone": ["@ungap/[email protected]", "", {}, "sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g=="],
"@vercel/config": ["@vercel/[email protected]", "", { "dependencies": { "@vercel/routing-utils": "6.2.0", "pretty-cache-header": "^1.0.0", "zod": "^3.22.0" }, "bin": { "config": "dist/cli.js" } }, "sha512-Tf5k5y2F478oTiQcU5R8Ntix1UejE6NdduZnI7aa1XXxjCtifX1XdRS/D2uTjiQAwIL3pLa1LSAN80ABbba+TQ=="],
"@vercel/functions": ["@vercel/[email protected]", "", { "dependencies": { "@vercel/oidc": "3.4.0" }, "peerDependencies": { "@aws-sdk/credential-provider-web-identity": "*" }, "optionalPeers": ["@aws-sdk/credential-provider-web-identity"] }, "sha512-+RokZ+4gkYyOsKBuJ29cQ8iSZG123LLJbZfPry20kkTgrN9U0277La4feP4DnWVo3sGoYa4plCEKY9XKUYoX9g=="],
"@vercel/oidc": ["@vercel/[email protected]", "", {}, "sha512-p0sKfHkfRmMaqqDwNL4tjnX9TgRrLMlEtUjIxfrEns8pOxz1R9ztqOVI+ehqiq93/2/HnfPe/UBZkfAZwnx0UA=="],
"@vercel/routing-utils": ["@vercel/[email protected]", "", { "dependencies": { "path-to-regexp": "6.1.0", "path-to-regexp-updated": "npm:[email protected]" }, "optionalDependencies": { "ajv": "^6.12.3" } }, "sha512-YI2cGYZmJKEyGSEgf5Fw5rVuW7X1bTOQ7/pnLRNTFMH3YB3qqP5erCLCJGv2kIvNo1iQAPINHQRJj6ykEdGoPg=="],
"@vitejs/plugin-react": ["@vitejs/[email protected]", "", { "dependencies": { "@rolldown/pluginutils": "1.0.0-rc.7" }, "peerDependencies": { "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0", "babel-plugin-react-compiler": "^1.0.0", "vite": "^8.0.0" }, "optionalPeers": ["@rolldown/plugin-babel", "babel-plugin-react-compiler"] }, "sha512-l9X/E3cDb+xY3SWzlG1MOGt2usfEHGMNIaegaUGFsLkb3RCn/k8/TOXBcab+OndDI4TBtktT8/9BwwW8Vi9KUQ=="],
"@vitest/browser": ["@vitest/[email protected]", "", { "dependencies": { "@blazediff/core": "1.9.1", "@vitest/mocker": "4.1.0", "@vitest/utils": "4.1.0", "magic-string": "^0.30.21", "pngjs": "^7.0.0", "sirv": "^3.0.2", "tinyrainbow": "^3.0.3", "ws": "^8.19.0" }, "peerDependencies": { "vitest": "4.1.0" } }, "sha512-tG/iOrgbiHQks0ew7CdelUyNEHkv8NLrt+CqdTivIuoSnXvO7scWMn4Kqo78/UGY1NJ6Hv+vp8BvRnED/bjFdQ=="],
@@ -1250,8 +1241,6 @@
"fast-deep-equal": ["[email protected]", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="],
"fast-json-stable-stringify": ["[email protected]", "", {}, "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw=="],
"fast-uri": ["[email protected]", "", {}, "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA=="],
"fd-slicer": ["[email protected]", "", { "dependencies": { "pend": "~1.2.0" } }, "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g=="],
@@ -1696,8 +1685,6 @@
"path-to-regexp": ["[email protected]", "", {}, "sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ=="],
"path-to-regexp-updated": ["[email protected]", "", {}, "sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ=="],
"pathe": ["[email protected]", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="],
"pend": ["[email protected]", "", {}, "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg=="],
@@ -1720,8 +1707,6 @@
"prettier": ["[email protected]", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg=="],
"pretty-cache-header": ["[email protected]", "", { "dependencies": { "timestring": "^6.0.0" } }, "sha512-xtXazslu25CdnGnUkByU1RoOjK55TqwatJkjjJLg5ZAdz2Lngko/mmaUgeET36P2GMlNwh3fdM7FWBO717pNcw=="],
"prismjs": ["[email protected]", "", {}, "sha512-DEvV2ZF2r2/63V+tK8hQvrR2ZGn10srHbXviTlcv7Kpzw8jWiNTqbVgjO3IY8RxrrOUF8VPMQQFysYYYv0YZxw=="],
"progress": ["[email protected]", "", {}, "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA=="],
@@ -1732,8 +1717,6 @@
"pump": ["[email protected]", "", { "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA=="],
"punycode": ["[email protected]", "", {}, "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg=="],
"pure-rand": ["[email protected]", "", {}, "sha512-53B3MB8wetRdD6JZ4W/0gDKaOvKwuXrEmV1auQc0hASWge8rieKV4PCCVNVbJ+i24miiubb4c/B+dg8Ho0ikYw=="],
"qs": ["[email protected]", "", { "dependencies": { "side-channel": "^1.1.0" } }, "sha512-6YHEFRL9mfgcAvql/XhwTvf5jKcOiiupt2FiJxHkiX1z4j7WL8J/jRHYLluORvc1XxB5rV20KoeK00gVJamspg=="],
@@ -1914,8 +1897,6 @@
"tapable": ["[email protected]", "", {}, "sha512-g9ljZiwki/LfxmQADO3dEY1CbpmXT5Hm2fJ+QaGKwSXUylMybePR7/67YW7jOrrvjEgL1Fmz5kzyAjWVWLlucg=="],
"timestring": ["[email protected]", "", {}, "sha512-wMctrWD2HZZLuIlchlkE2dfXJh7J2KDI9Dwl+2abPYg0mswQHfOAyQW3jJg1pY5VfttSINZuKcXoB3FGypVklA=="],
"tiny-inflate": ["[email protected]", "", {}, "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw=="],
"tiny-invariant": ["[email protected]", "", {}, "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg=="],
@@ -2038,8 +2019,6 @@
"update-browserslist-db": ["[email protected]", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w=="],
"uri-js": ["[email protected]", "", { "dependencies": { "punycode": "^2.1.0" } }, "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg=="],
"use-sync-external-store": ["[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w=="],
"uuid": ["[email protected]", "", { "bin": { "uuid": "dist-node/bin/uuid" } }, "sha512-XQegIaBTVUjSHliKqcnFqYypAd4S+WCYt5NIeRs6w/UAry7z8Y9j5ZwRRL4kzq9U3sD6v+85er9FvkEaBpji2w=="],
@@ -2214,12 +2193,6 @@
"@tanstack/router-utils/@babel/generator": ["@babel/[email protected]", "", { "dependencies": { "@babel/parser": "^7.29.0", "@babel/types": "^7.29.0", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "jsesc": "^3.0.2" } }, "sha512-qsaF+9Qcm2Qv8SRIMMscAvG4O3lJ0F1GuMo5HR/Bp02LopNgnZBC/EkbevHFeGs4ls/oPz9v+Bsmzbkbe+0dUw=="],
"@vercel/config/zod": ["[email protected]", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
"@vercel/routing-utils/ajv": ["[email protected]", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw=="],
"@vercel/routing-utils/path-to-regexp": ["[email protected]", "", {}, "sha512-h9DqehX3zZZDCEm+xbfU0ZmwCGFCAAraPJWMXJ4+v32NjZJilVg3k1TcKsRgIb8IQ/izZSaydDc1OhJCZvs2Dw=="],
"@vitest/browser/ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg=="],
"anymatch/picomatch": ["[email protected]", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="],
@@ -2344,8 +2317,6 @@
"@tanstack/router-plugin/chokidar/readdirp": ["[email protected]", "", { "dependencies": { "picomatch": "^2.2.1" } }, "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA=="],
"@vercel/routing-utils/ajv/json-schema-traverse": ["[email protected]", "", {}, "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg=="],
"ast-kit/@babel/parser/@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^8.0.0-rc.2", "@babel/helper-validator-identifier": "^8.0.0-rc.2" } }, "sha512-91gAaWRznDwSX4E2tZ1YjBuIfnQVOFDCQ2r0Toby0gu4XEbyF623kXLMA8d4ZbCu+fINcrudkmEcwSUHgDDkNw=="],
"csso/css-tree/mdn-data": ["[email protected]", "", {}, "sha512-aylIc7Z9y4yzHYAJNuESG3hfhC+0Ibp/MAMiaOZgNv4pmEdFyfZhhhny4MNiAfWdBQ1RQ2mfDWmM1x8SvGyp8g=="],
Loaded 100 of 126 files, more files were not shown because too many files have changed in this diff. Show more