Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cfd7af1464 | ||
|
|
91263ff1bf | ||
|
|
cff8c10d13 | ||
|
|
3c32bc8fd1 | ||
|
|
6efdf67e15 | ||
|
|
39371c6012 | ||
|
|
99efaa0faa | ||
|
|
6b9feb1bd3 | ||
|
|
e0f3abd1a4 | ||
|
|
34ec8a86fb | ||
|
|
932df4ed17 | ||
|
|
63859aa072 | ||
|
|
7bfacd55d8 | ||
|
|
271d65e047 | ||
|
|
aa8b9f2286 | ||
|
|
073eb389d3 | ||
|
|
825263b6f9 |
No files matched your search
@@ -244,6 +244,68 @@ 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:
|
||||
@@ -511,6 +573,88 @@ 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}"
|
||||
|
||||
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[@]}"
|
||||
|
||||
finalize:
|
||||
name: Finalize release
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' && needs.preflight.outputs.release_channel == 'stable' }}
|
||||
@@ -595,8 +739,9 @@ 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, finalize]
|
||||
needs: [preflight, release, deploy_web, finalize]
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
|
||||
+4
-1
@@ -9,6 +9,7 @@
|
||||
"**/routeTree.gen.ts"
|
||||
],
|
||||
"plugins": ["eslint", "oxc", "react", "unicorn", "typescript"],
|
||||
"jsPlugins": ["./oxlint-plugin-t3code/index.ts"],
|
||||
"categories": {
|
||||
"correctness": "warn",
|
||||
"suspicious": "warn",
|
||||
@@ -17,6 +18,8 @@
|
||||
"rules": {
|
||||
"react-in-jsx-scope": "off",
|
||||
"eslint/no-shadow": "off",
|
||||
"eslint/no-await-in-loop": "off"
|
||||
"eslint/no-await-in-loop": "off",
|
||||
"eslint/no-underscore-dangle": "off",
|
||||
"t3code/no-inline-schema-compile": "warn"
|
||||
}
|
||||
}
|
||||
@@ -115,6 +115,43 @@ 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.
|
||||
|
||||
@@ -16,6 +16,7 @@ const COMMIT_HASH_DISPLAY_LENGTH = 12;
|
||||
const AppPackageMetadata = Schema.Struct({
|
||||
t3codeCommitHash: Schema.optional(Schema.String),
|
||||
});
|
||||
const decodeAppPackageMetadata = Schema.decodeEffect(Schema.fromJsonString(AppPackageMetadata));
|
||||
|
||||
export interface DesktopAppIdentityShape {
|
||||
readonly resolveUserDataPath: Effect.Effect<string>;
|
||||
@@ -47,7 +48,7 @@ const make = Effect.gen(function* () {
|
||||
return yield* Option.match(raw, {
|
||||
onNone: () => Effect.succeed(Option.none<string>()),
|
||||
onSome: (value) =>
|
||||
Schema.decodeEffect(Schema.fromJsonString(AppPackageMetadata))(value).pipe(
|
||||
decodeAppPackageMetadata(value).pipe(
|
||||
Effect.map((parsed) =>
|
||||
Option.fromNullishOr(parsed.t3codeCommitHash).pipe(Option.flatMap(normalizeCommitHash)),
|
||||
),
|
||||
|
||||
@@ -25,6 +25,10 @@ import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopState from "../app/DesktopState.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
|
||||
const decodeDesktopBackendBootstrap = Schema.decodeEffect(
|
||||
Schema.fromJsonString(DesktopBackendBootstrap),
|
||||
);
|
||||
|
||||
const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
executablePath: "/electron",
|
||||
entryPath: "/server/bin.mjs",
|
||||
@@ -94,7 +98,7 @@ const healthyHttpClientLayer = httpClientLayer((request) =>
|
||||
);
|
||||
|
||||
function decodeBootstrap(raw: string) {
|
||||
return Schema.decodeEffect(Schema.fromJsonString(DesktopBackendBootstrap))(raw);
|
||||
return decodeDesktopBackendBootstrap(raw);
|
||||
}
|
||||
|
||||
function makeManagerLayer(input: {
|
||||
|
||||
@@ -11,6 +11,7 @@ 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";
|
||||
@@ -65,7 +66,10 @@ const resolveDesktopSshCliRunner = (
|
||||
): RemoteT3RunnerOptions => {
|
||||
const devRemoteEntryPath = Option.getOrUndefined(environment.devRemoteT3ServerEntryPath);
|
||||
if (environment.isDevelopment && devRemoteEntryPath !== undefined) {
|
||||
return { nodeScriptPath: devRemoteEntryPath };
|
||||
return {
|
||||
nodeScriptPath: devRemoteEntryPath,
|
||||
nodeEngineRange: serverPackageJson.engines.node,
|
||||
};
|
||||
}
|
||||
return {
|
||||
packageSpec: resolveRemoteT3CliPackageSpec({
|
||||
@@ -73,6 +77,7 @@ const resolveDesktopSshCliRunner = (
|
||||
updateChannel: settings.updateChannel,
|
||||
isDevelopment: environment.isDevelopment,
|
||||
}),
|
||||
nodeEngineRange: serverPackageJson.engines.node,
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -20,10 +20,14 @@ const ClientSettingsDocumentSchema = Schema.Struct({
|
||||
|
||||
const ClientSettingsJson = fromLenientJson(ClientSettingsSchema);
|
||||
const LegacyClientSettingsDocumentJson = fromLenientJson(ClientSettingsDocumentSchema);
|
||||
const decodeLegacyClientSettingsDocumentJson = Schema.decodeEffect(
|
||||
LegacyClientSettingsDocumentJson,
|
||||
);
|
||||
const decodeClientSettingsJsonValue = Schema.decodeEffect(ClientSettingsJson);
|
||||
const decodeClientSettingsJson = (raw: string): Effect.Effect<ClientSettings, Schema.SchemaError> =>
|
||||
Schema.decodeEffect(LegacyClientSettingsDocumentJson)(raw).pipe(
|
||||
decodeLegacyClientSettingsDocumentJson(raw).pipe(
|
||||
Effect.map((document) => document.settings),
|
||||
Effect.catch(() => Schema.decodeEffect(ClientSettingsJson)(raw)),
|
||||
Effect.catch(() => decodeClientSettingsJsonValue(raw)),
|
||||
);
|
||||
const encodeClientSettingsJson = Schema.encodeEffect(ClientSettingsJson);
|
||||
|
||||
|
||||
@@ -54,6 +54,9 @@ const UpdateInfo = Schema.Struct({
|
||||
const DownloadProgressInfo = Schema.Struct({
|
||||
percent: Schema.Number,
|
||||
});
|
||||
const decodeAppUpdateYmlConfig = Schema.decodeUnknownEffect(AppUpdateYmlConfig);
|
||||
const decodeUpdateInfo = Schema.decodeUnknownEffect(UpdateInfo);
|
||||
const decodeDownloadProgressInfo = Schema.decodeUnknownEffect(DownloadProgressInfo);
|
||||
|
||||
const currentIsoTimestamp = DateTime.now.pipe(Effect.map(DateTime.formatIso));
|
||||
|
||||
@@ -115,7 +118,7 @@ function parseAppUpdateYml(raw: string): Effect.Effect<Option.Option<AppUpdateYm
|
||||
}
|
||||
}
|
||||
|
||||
return Schema.decodeUnknownEffect(AppUpdateYmlConfig)(entries).pipe(
|
||||
return decodeAppUpdateYmlConfig(entries).pipe(
|
||||
Effect.map((config) => (config.provider ? Option.some(config) : Option.none())),
|
||||
Effect.catch(() => Effect.succeed(Option.none<AppUpdateYmlConfig>())),
|
||||
);
|
||||
@@ -408,7 +411,7 @@ const make = Effect.gen(function* () {
|
||||
const handleUpdateAvailable = Effect.fn("desktop.updates.handleUpdateAvailable")(function* (
|
||||
raw: unknown,
|
||||
) {
|
||||
yield* Schema.decodeUnknownEffect(UpdateInfo)(raw).pipe(
|
||||
yield* decodeUpdateInfo(raw).pipe(
|
||||
Effect.flatMap(
|
||||
Effect.fn("desktop.updates.applyUpdateAvailable")(function* (info) {
|
||||
const state = yield* Ref.get(updateStateRef);
|
||||
@@ -479,7 +482,7 @@ const make = Effect.gen(function* () {
|
||||
const handleDownloadProgress = Effect.fn("desktop.updates.handleDownloadProgress")(function* (
|
||||
raw: unknown,
|
||||
) {
|
||||
yield* Schema.decodeUnknownEffect(DownloadProgressInfo)(raw).pipe(
|
||||
yield* decodeDownloadProgressInfo(raw).pipe(
|
||||
Effect.flatMap(
|
||||
Effect.fn("desktop.updates.applyDownloadProgress")(function* (progress) {
|
||||
const state = yield* Ref.get(updateStateRef);
|
||||
@@ -506,7 +509,7 @@ const make = Effect.gen(function* () {
|
||||
const handleUpdateDownloaded = Effect.fn("desktop.updates.handleUpdateDownloaded")(function* (
|
||||
raw: unknown,
|
||||
) {
|
||||
yield* Schema.decodeUnknownEffect(UpdateInfo)(raw).pipe(
|
||||
yield* decodeUpdateInfo(raw).pipe(
|
||||
Effect.flatMap(
|
||||
Effect.fn("desktop.updates.applyUpdateDownloaded")(function* (info) {
|
||||
const state = yield* Ref.get(updateStateRef);
|
||||
|
||||
@@ -79,6 +79,8 @@ import { VcsStatusBroadcaster } from "../src/vcs/VcsStatusBroadcaster.ts";
|
||||
import { GitWorkflowService } from "../src/git/GitWorkflowService.ts";
|
||||
import * as VcsProcess from "../src/vcs/VcsProcess.ts";
|
||||
|
||||
const decodeCodexSettings = Schema.decodeEffect(CodexSettings);
|
||||
|
||||
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||
return execFileSync("git", args, {
|
||||
cwd,
|
||||
@@ -266,7 +268,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
const realCodexRegistry = Layer.effect(
|
||||
ProviderAdapterRegistry,
|
||||
Effect.gen(function* () {
|
||||
const codexSettings = Schema.decodeSync(CodexSettings)({});
|
||||
const codexSettings = yield* decodeCodexSettings({});
|
||||
const codexAdapter = yield* makeCodexAdapter(codexSettings);
|
||||
return makeAdapterRegistryMock({
|
||||
[ProviderDriverKind.make("codex")]: codexAdapter,
|
||||
|
||||
@@ -14,6 +14,7 @@ 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* () {
|
||||
@@ -27,7 +28,7 @@ export const respondToAuthError = (error: AuthError) =>
|
||||
{
|
||||
error: error.message,
|
||||
},
|
||||
{ status: error.status ?? 500 },
|
||||
{ status: error.status ?? 500, headers: browserApiCorsHeaders },
|
||||
);
|
||||
});
|
||||
|
||||
@@ -38,7 +39,10 @@ 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 });
|
||||
return HttpServerResponse.jsonUnsafe(session, {
|
||||
status: 200,
|
||||
headers: browserApiCorsHeaders,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -81,7 +85,10 @@ export const authBootstrapRouteLayer = HttpRouter.add(
|
||||
deriveAuthClientMetadata({ request }),
|
||||
);
|
||||
|
||||
return yield* HttpServerResponse.jsonUnsafe(result.response, { status: 200 }).pipe(
|
||||
return yield* HttpServerResponse.jsonUnsafe(result.response, {
|
||||
status: 200,
|
||||
headers: browserApiCorsHeaders,
|
||||
}).pipe(
|
||||
HttpServerResponse.setCookie(sessions.cookieName, result.sessionToken, {
|
||||
expires: DateTime.toDate(result.response.expiresAt),
|
||||
httpOnly: true,
|
||||
@@ -114,6 +121,7 @@ export const authBearerBootstrapRouteLayer = HttpRouter.add(
|
||||
);
|
||||
return HttpServerResponse.jsonUnsafe(result satisfies AuthBearerBootstrapResult, {
|
||||
status: 200,
|
||||
headers: browserApiCorsHeaders,
|
||||
});
|
||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
||||
);
|
||||
@@ -128,6 +136,7 @@ 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))),
|
||||
);
|
||||
|
||||
@@ -38,6 +38,7 @@ vi.mock("node:fs", async (importOriginal) => {
|
||||
});
|
||||
|
||||
const TestEnvelopeSchema = Schema.Struct({ mode: Schema.String });
|
||||
const encodeTestEnvelopeSchema = Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema));
|
||||
|
||||
it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
|
||||
it.effect("uses platform-specific fd paths", () =>
|
||||
@@ -55,9 +56,7 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
|
||||
|
||||
yield* fs.writeFileString(
|
||||
filePath,
|
||||
`${yield* Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema))({
|
||||
mode: "desktop",
|
||||
})}\n`,
|
||||
`${yield* encodeTestEnvelopeSchema({ mode: "desktop" })}\n`,
|
||||
);
|
||||
|
||||
const fd = yield* Effect.acquireRelease(
|
||||
@@ -79,9 +78,7 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
|
||||
|
||||
yield* fs.writeFileString(
|
||||
filePath,
|
||||
`${yield* Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema))({
|
||||
mode: "desktop",
|
||||
})}\n`,
|
||||
`${yield* encodeTestEnvelopeSchema({ mode: "desktop" })}\n`,
|
||||
);
|
||||
|
||||
// Open without acquireRelease: the direct-stream fallback uses autoClose: true,
|
||||
|
||||
@@ -94,6 +94,8 @@ 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()),
|
||||
@@ -174,6 +176,8 @@ 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()),
|
||||
@@ -222,6 +226,8 @@ 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()),
|
||||
|
||||
@@ -50,6 +50,7 @@ class ProcessDiagnosticsError extends Schema.TaggedErrorClass<ProcessDiagnostics
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {}
|
||||
const isProcessDiagnosticsError = Schema.is(ProcessDiagnosticsError);
|
||||
|
||||
function toProcessDiagnosticsError(message: string, cause?: unknown): ProcessDiagnosticsError {
|
||||
return new ProcessDiagnosticsError({
|
||||
@@ -316,7 +317,7 @@ const runProcess = Effect.fn("runProcess")(
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) =>
|
||||
Schema.is(ProcessDiagnosticsError)(cause)
|
||||
isProcessDiagnosticsError(cause)
|
||||
? cause
|
||||
: toProcessDiagnosticsError(input.errorMessage, cause),
|
||||
),
|
||||
|
||||
+11
-3
@@ -28,6 +28,11 @@ 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>`;
|
||||
@@ -35,8 +40,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: ["GET", "POST", "OPTIONS"],
|
||||
allowedHeaders: ["authorization", "b3", "traceparent", "content-type"],
|
||||
allowedMethods: [...browserApiCorsAllowedMethods],
|
||||
allowedHeaders: [...browserApiCorsAllowedHeaders],
|
||||
maxAge: 600,
|
||||
});
|
||||
|
||||
@@ -69,7 +74,10 @@ export const serverEnvironmentRouteLayer = HttpRouter.add(
|
||||
const descriptor = yield* Effect.service(ServerEnvironment).pipe(
|
||||
Effect.flatMap((serverEnvironment) => serverEnvironment.getDescriptor),
|
||||
);
|
||||
return HttpServerResponse.jsonUnsafe(descriptor, { status: 200 });
|
||||
return HttpServerResponse.jsonUnsafe(descriptor, {
|
||||
status: 200,
|
||||
headers: browserApiCorsHeaders,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
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;
|
||||
@@ -23,6 +23,12 @@ import {
|
||||
import { KeybindingsConfigError } from "@t3tools/contracts";
|
||||
|
||||
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
|
||||
const encodeKeybindingsConfigJson = Schema.encodeEffect(KeybindingsConfigJson);
|
||||
const decodeKeybindingsConfigJson = Schema.decodeUnknownEffect(KeybindingsConfigJson);
|
||||
const encodeResolvedKeybindingFromConfig = Schema.encodeEffect(ResolvedKeybindingFromConfig);
|
||||
const decodeResolvedKeybindingFromConfigExit = Schema.decodeUnknownExit(
|
||||
ResolvedKeybindingFromConfig,
|
||||
);
|
||||
const makeKeybindingsLayer = () => {
|
||||
return KeybindingsLive.pipe(
|
||||
Layer.provideMerge(
|
||||
@@ -45,7 +51,7 @@ const writeKeybindingsConfig = (configPath: string, rules: readonly KeybindingRu
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const encoded = yield* Schema.encodeEffect(KeybindingsConfigJson)(rules);
|
||||
const encoded = yield* encodeKeybindingsConfigJson(rules);
|
||||
yield* fileSystem.makeDirectory(path.dirname(configPath), { recursive: true });
|
||||
yield* fileSystem.writeFileString(configPath, encoded);
|
||||
});
|
||||
@@ -54,7 +60,7 @@ const readKeybindingsConfig = (configPath: string) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const rawConfig = yield* fileSystem.readFileString(configPath);
|
||||
return yield* Schema.decodeUnknownEffect(KeybindingsConfigJson)(rawConfig);
|
||||
return yield* decodeKeybindingsConfigJson(rawConfig);
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
@@ -111,7 +117,7 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
|
||||
it.effect("encodes resolved plus-key shortcuts", () =>
|
||||
Effect.gen(function* () {
|
||||
const encoded = yield* Schema.encodeEffect(ResolvedKeybindingFromConfig)({
|
||||
const encoded = yield* encodeResolvedKeybindingFromConfig({
|
||||
command: "terminal.toggle",
|
||||
shortcut: {
|
||||
key: "+",
|
||||
@@ -157,7 +163,7 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
|
||||
it.effect("formats invalid resolved keybinding rules with the custom message", () =>
|
||||
Effect.sync(() => {
|
||||
const result = Schema.decodeUnknownExit(ResolvedKeybindingFromConfig)({
|
||||
const result = decodeResolvedKeybindingFromConfigExit({
|
||||
key: "mod+shift+d+o",
|
||||
command: "terminal.new",
|
||||
});
|
||||
|
||||
@@ -170,6 +170,10 @@ function encodeWhenAst(node: KeybindingWhenNode): string {
|
||||
|
||||
const RawKeybindingsEntries = fromLenientJson(Schema.Array(Schema.Unknown));
|
||||
const KeybindingsConfigPrettyJson = fromJsonStringPretty(KeybindingsConfig);
|
||||
const decodeKeybindingRuleExit = Schema.decodeUnknownExit(KeybindingRule);
|
||||
const decodeResolvedKeybindingFromConfigExit = Schema.decodeExit(ResolvedKeybindingFromConfig);
|
||||
const decodeRawKeybindingsEntriesExit = Schema.decodeUnknownExit(RawKeybindingsEntries);
|
||||
const encodeKeybindingsConfigPrettyJson = Schema.encodeEffect(KeybindingsConfigPrettyJson);
|
||||
|
||||
export interface KeybindingsConfigState {
|
||||
readonly keybindings: ResolvedKeybindingsConfig;
|
||||
@@ -344,7 +348,7 @@ const makeKeybindings = Effect.gen(function* () {
|
||||
|
||||
return yield* Effect.forEach(rawConfig, (entry) =>
|
||||
Effect.gen(function* () {
|
||||
const decodedRule = Schema.decodeUnknownExit(KeybindingRule)(entry);
|
||||
const decodedRule = decodeKeybindingRuleExit(entry);
|
||||
if (decodedRule._tag === "Failure") {
|
||||
yield* Effect.logWarning("ignoring invalid keybinding entry", {
|
||||
path: keybindingsConfigPath,
|
||||
@@ -353,7 +357,7 @@ const makeKeybindings = Effect.gen(function* () {
|
||||
});
|
||||
return null;
|
||||
}
|
||||
const resolved = Schema.decodeExit(ResolvedKeybindingFromConfig)(decodedRule.value);
|
||||
const resolved = decodeResolvedKeybindingFromConfigExit(decodedRule.value);
|
||||
if (resolved._tag === "Failure") {
|
||||
yield* Effect.logWarning("ignoring invalid keybinding entry", {
|
||||
path: keybindingsConfigPath,
|
||||
@@ -379,7 +383,7 @@ const makeKeybindings = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
const rawConfig = yield* readRawConfig;
|
||||
const decodedEntries = Schema.decodeUnknownExit(RawKeybindingsEntries)(rawConfig);
|
||||
const decodedEntries = decodeRawKeybindingsEntriesExit(rawConfig);
|
||||
if (decodedEntries._tag === "Failure") {
|
||||
const detail = `expected JSON array (${Cause.pretty(decodedEntries.cause)})`;
|
||||
return {
|
||||
@@ -391,7 +395,7 @@ const makeKeybindings = Effect.gen(function* () {
|
||||
const keybindings: KeybindingRule[] = [];
|
||||
const issues: ServerConfigIssue[] = [];
|
||||
for (const [index, entry] of decodedEntries.value.entries()) {
|
||||
const decodedRule = Schema.decodeUnknownExit(KeybindingRule)(entry);
|
||||
const decodedRule = decodeKeybindingRuleExit(entry);
|
||||
if (decodedRule._tag === "Failure") {
|
||||
const detail = Cause.pretty(decodedRule.cause);
|
||||
issues.push(invalidEntryIssue(index, detail));
|
||||
@@ -404,7 +408,7 @@ const makeKeybindings = Effect.gen(function* () {
|
||||
continue;
|
||||
}
|
||||
|
||||
const resolvedRule = Schema.decodeExit(ResolvedKeybindingFromConfig)(decodedRule.value);
|
||||
const resolvedRule = decodeResolvedKeybindingFromConfigExit(decodedRule.value);
|
||||
if (resolvedRule._tag === "Failure") {
|
||||
const detail = Cause.pretty(resolvedRule.cause);
|
||||
issues.push(invalidEntryIssue(index, detail));
|
||||
@@ -423,7 +427,7 @@ const makeKeybindings = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const writeConfigAtomically = (rules: readonly KeybindingRule[]) => {
|
||||
return Schema.encodeEffect(KeybindingsConfigPrettyJson)(rules).pipe(
|
||||
return encodeKeybindingsConfigPrettyJson(rules).pipe(
|
||||
Effect.map((encoded) => `${encoded}\n`),
|
||||
Effect.flatMap((encoded) =>
|
||||
writeFileStringAtomically({
|
||||
|
||||
@@ -3,8 +3,12 @@ import { assert, it } from "@effect/vitest";
|
||||
import { assertSuccess } from "@effect/vitest/utils";
|
||||
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 * as Random from "effect/Random";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
isCommandAvailable,
|
||||
@@ -13,6 +17,22 @@ import {
|
||||
resolveEditorLaunch,
|
||||
} from "./open.ts";
|
||||
|
||||
function makeOpenProcessHandle(onUnref: Effect.Effect<void> = Effect.void) {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(123),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () => Effect.void,
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.empty,
|
||||
stderr: Stream.empty,
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
unref: Effect.as(onUnref, Effect.void),
|
||||
});
|
||||
}
|
||||
|
||||
it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
it.effect("returns commands for command-based editors", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -478,13 +498,36 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("launchDetached", (it) => {
|
||||
it.effect("resolves when command can be spawned", () =>
|
||||
it.effect("resolves when command can be spawned through ChildProcessSpawner", () =>
|
||||
Effect.gen(function* () {
|
||||
const commands: Array<ChildProcess.Command> = [];
|
||||
let unrefCount = 0;
|
||||
const spawnerLayer = Layer.mock(ChildProcessSpawner.ChildProcessSpawner)({
|
||||
spawn: (command) =>
|
||||
Effect.sync(() => {
|
||||
commands.push(command);
|
||||
return makeOpenProcessHandle(
|
||||
Effect.sync(() => {
|
||||
unrefCount += 1;
|
||||
}),
|
||||
);
|
||||
}),
|
||||
});
|
||||
|
||||
const result = yield* launchDetached({
|
||||
command: process.execPath,
|
||||
args: ["-e", "process.exit(0)"],
|
||||
}).pipe(Effect.result);
|
||||
}).pipe(Effect.provide(spawnerLayer), Effect.result);
|
||||
|
||||
assertSuccess(result, undefined);
|
||||
assert.equal(unrefCount, 1);
|
||||
assert.lengthOf(commands, 1);
|
||||
const command = commands[0] as unknown as {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
};
|
||||
assert.equal(command.command, process.execPath);
|
||||
assert.deepEqual(command.args, ["-e", "process.exit(0)"]);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -493,7 +536,10 @@ it.layer(NodeServices.layer)("launchDetached", (it) => {
|
||||
const result = yield* launchDetached({
|
||||
command: `t3code-no-such-command-${yield* Random.nextUUIDv4}`,
|
||||
args: [],
|
||||
}).pipe(Effect.result);
|
||||
}).pipe(
|
||||
Effect.provide(Layer.mock(ChildProcessSpawner.ChildProcessSpawner)({})),
|
||||
Effect.result,
|
||||
);
|
||||
assert.equal(result._tag, "Failure");
|
||||
}),
|
||||
);
|
||||
|
||||
+31
-32
@@ -1,4 +1,3 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
/**
|
||||
* Open - Browser/editor launch service interface.
|
||||
*
|
||||
@@ -7,13 +6,12 @@
|
||||
*
|
||||
* @module Open
|
||||
*/
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
import { EDITORS, OpenError, type EditorId } from "@t3tools/contracts";
|
||||
import { isCommandAvailable, type CommandAvailabilityOptions } from "@t3tools/shared/shell";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
// ==============================
|
||||
// Definitions
|
||||
@@ -191,38 +189,34 @@ export const launchDetached = (launch: EditorLaunch) =>
|
||||
return yield* new OpenError({ message: `Editor command not found: ${launch.command}` });
|
||||
}
|
||||
|
||||
yield* Effect.callback<void, OpenError>((resume) => {
|
||||
let child;
|
||||
try {
|
||||
const isWin32 = process.platform === "win32";
|
||||
child = spawn(
|
||||
launch.command,
|
||||
isWin32 ? launch.args.map((a) => `"${a}"`) : [...launch.args],
|
||||
{
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
shell: isWin32,
|
||||
},
|
||||
const isWin32 = process.platform === "win32";
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const child = yield* spawner.spawn(
|
||||
ChildProcess.make(
|
||||
launch.command,
|
||||
isWin32 ? launch.args.map((a) => `"${a}"`) : [...launch.args],
|
||||
{
|
||||
detached: true,
|
||||
shell: isWin32,
|
||||
stdin: "ignore",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
},
|
||||
),
|
||||
);
|
||||
} catch (error) {
|
||||
return resume(
|
||||
Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
|
||||
);
|
||||
}
|
||||
|
||||
const handleSpawn = () => {
|
||||
child.unref();
|
||||
resume(Effect.void);
|
||||
};
|
||||
|
||||
child.once("spawn", handleSpawn);
|
||||
child.once("error", (cause) =>
|
||||
resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
|
||||
);
|
||||
});
|
||||
yield* Effect.asVoid(child.unref);
|
||||
}),
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new OpenError({ message: "failed to spawn detached process", cause }),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const open = yield* Effect.tryPromise({
|
||||
try: () => import("open"),
|
||||
catch: (cause) => new OpenError({ message: "failed to load browser opener", cause }),
|
||||
@@ -234,7 +228,12 @@ const make = Effect.gen(function* () {
|
||||
try: () => open.default(target),
|
||||
catch: (cause) => new OpenError({ message: "Browser auto-open failed", cause }),
|
||||
}),
|
||||
openInEditor: (input) => Effect.flatMap(resolveEditorLaunch(input), launchDetached),
|
||||
openInEditor: (input) =>
|
||||
Effect.flatMap(resolveEditorLaunch(input), (launch) =>
|
||||
launchDetached(launch).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
),
|
||||
),
|
||||
} satisfies OpenShape;
|
||||
});
|
||||
|
||||
|
||||
@@ -183,6 +183,13 @@ 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 }),
|
||||
|
||||
@@ -44,6 +44,10 @@ import {
|
||||
OrchestrationEngineService,
|
||||
type OrchestrationEngineShape,
|
||||
} from "../Services/OrchestrationEngine.ts";
|
||||
const isOrchestrationCommandPreviouslyRejectedError = Schema.is(
|
||||
OrchestrationCommandPreviouslyRejectedError,
|
||||
);
|
||||
const isOrchestrationCommandInvariantError = Schema.is(OrchestrationCommandInvariantError);
|
||||
|
||||
interface CommandEnvelope {
|
||||
command: OrchestrationCommand;
|
||||
@@ -245,7 +249,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
const error = Cause.squash(exit.cause) as OrchestrationDispatchError;
|
||||
if (!Schema.is(OrchestrationCommandPreviouslyRejectedError)(error)) {
|
||||
if (!isOrchestrationCommandPreviouslyRejectedError(error)) {
|
||||
yield* reconcileReadModelAfterDispatchFailure.pipe(
|
||||
Effect.catch(() =>
|
||||
Effect.logWarning(
|
||||
@@ -259,7 +263,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
if (Schema.is(OrchestrationCommandInvariantError)(error)) {
|
||||
if (isOrchestrationCommandInvariantError(error)) {
|
||||
yield* commandReceiptRepository
|
||||
.upsert({
|
||||
commandId: envelope.command.commandId,
|
||||
|
||||
@@ -441,6 +441,126 @@ 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",
|
||||
() =>
|
||||
|
||||
@@ -327,6 +327,66 @@ 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,
|
||||
@@ -411,6 +471,56 @@ 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,
|
||||
@@ -475,6 +585,33 @@ 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
|
||||
`,
|
||||
@@ -557,6 +694,7 @@ 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
|
||||
`,
|
||||
@@ -607,6 +745,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
FROM projection_threads
|
||||
WHERE thread_id = ${threadId}
|
||||
AND deleted_at IS NULL
|
||||
AND archived_at IS NULL
|
||||
LIMIT 1
|
||||
`,
|
||||
});
|
||||
@@ -717,6 +856,7 @@ 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
|
||||
`,
|
||||
});
|
||||
@@ -1232,7 +1372,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadRows(undefined).pipe(
|
||||
listActiveThreadRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listThreads:query",
|
||||
@@ -1240,7 +1380,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadSessionRows(undefined).pipe(
|
||||
listActiveThreadSessionRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listThreadSessions:query",
|
||||
@@ -1350,6 +1490,139 @@ 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(
|
||||
@@ -1683,6 +1956,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
getCommandReadModel,
|
||||
getSnapshot,
|
||||
getShellSnapshot,
|
||||
getArchivedShellSnapshot,
|
||||
getSnapshotSequence,
|
||||
getCounts,
|
||||
getActiveProjectByWorkspaceRoot,
|
||||
|
||||
@@ -39,6 +39,8 @@ import {
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
|
||||
import { GitWorkflowService } from "../../git/GitWorkflowService.ts";
|
||||
const isProviderAdapterRequestError = Schema.is(ProviderAdapterRequestError);
|
||||
const isProviderDriverKind = Schema.is(ProviderDriverKind);
|
||||
|
||||
type ProviderIntentEvent = Extract<
|
||||
OrchestrationEvent,
|
||||
@@ -118,7 +120,7 @@ function findProviderAdapterRequestError(
|
||||
cause: Cause.Cause<ProviderServiceError>,
|
||||
): ProviderAdapterRequestError | undefined {
|
||||
const failReason = cause.reasons.find(Cause.isFailReason);
|
||||
return Schema.is(ProviderAdapterRequestError)(failReason?.error) ? failReason.error : undefined;
|
||||
return isProviderAdapterRequestError(failReason?.error) ? failReason.error : undefined;
|
||||
}
|
||||
|
||||
function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
|
||||
@@ -233,7 +235,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
const formatFailureDetail = (cause: Cause.Cause<unknown>): string => {
|
||||
const failReason = cause.reasons.find(Cause.isFailReason);
|
||||
const providerError = Schema.is(ProviderAdapterRequestError)(failReason?.error)
|
||||
const providerError = isProviderAdapterRequestError(failReason?.error)
|
||||
? failReason.error
|
||||
: undefined;
|
||||
if (providerError) {
|
||||
@@ -361,7 +363,7 @@ const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
const desiredDriverKind = desiredInfo.driverKind;
|
||||
if (!Schema.is(ProviderDriverKind)(desiredDriverKind)) {
|
||||
if (!isProviderDriverKind(desiredDriverKind)) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: providerErrorLabel(String(desiredDriverKind)),
|
||||
method: "thread.turn.start",
|
||||
|
||||
@@ -72,6 +72,17 @@ 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.
|
||||
|
||||
@@ -47,15 +47,14 @@ function updateThread(
|
||||
}
|
||||
|
||||
function decodeForEvent<A>(
|
||||
schema: Schema.Schema<A>,
|
||||
schema: Schema.Decoder<A, never>,
|
||||
value: unknown,
|
||||
eventType: OrchestrationEvent["type"],
|
||||
field: string,
|
||||
): Effect.Effect<A, OrchestrationProjectorDecodeError> {
|
||||
return Effect.try({
|
||||
try: () => Schema.decodeUnknownSync(schema as any)(value),
|
||||
catch: (error) => toProjectorDecodeError(`${eventType}:${field}`)(error as Schema.SchemaError),
|
||||
});
|
||||
return Schema.decodeUnknownEffect(schema)(value).pipe(
|
||||
Effect.mapError(toProjectorDecodeError(`${eventType}:${field}`)),
|
||||
);
|
||||
}
|
||||
|
||||
function retainThreadMessagesAfterRevert(
|
||||
|
||||
@@ -30,6 +30,8 @@ export class PersistenceDecodeError extends Schema.TaggedErrorClass<PersistenceD
|
||||
return `Decode error in ${this.operation}: ${this.issue}`;
|
||||
}
|
||||
}
|
||||
const isPersistenceSqlError = Schema.is(PersistenceSqlError);
|
||||
const isPersistenceDecodeError = Schema.is(PersistenceDecodeError);
|
||||
|
||||
export function toPersistenceSqlError(operation: string) {
|
||||
return (cause: unknown): PersistenceSqlError =>
|
||||
@@ -59,7 +61,7 @@ export function toPersistenceDecodeCauseError(operation: string) {
|
||||
}
|
||||
|
||||
export const isPersistenceError = (u: unknown) =>
|
||||
Schema.is(PersistenceSqlError)(u) || Schema.is(PersistenceDecodeError)(u);
|
||||
isPersistenceSqlError(u) || isPersistenceDecodeError(u);
|
||||
|
||||
// ===============================
|
||||
// Provider Session Repository Errors
|
||||
|
||||
@@ -10,6 +10,7 @@ import { PersistenceDecodeError } from "../Errors.ts";
|
||||
import { OrchestrationEventStore } from "../Services/OrchestrationEventStore.ts";
|
||||
import { OrchestrationEventStoreLive } from "./OrchestrationEventStore.ts";
|
||||
import { SqlitePersistenceMemory } from "./Sqlite.ts";
|
||||
const isPersistenceDecodeError = Schema.is(PersistenceDecodeError);
|
||||
|
||||
const layer = it.layer(
|
||||
OrchestrationEventStoreLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
|
||||
@@ -110,7 +111,7 @@ layer("OrchestrationEventStore", (it) => {
|
||||
);
|
||||
assert.equal(replayResult._tag, "Failure");
|
||||
if (replayResult._tag === "Failure") {
|
||||
assert.ok(Schema.is(PersistenceDecodeError)(replayResult.failure));
|
||||
assert.ok(isPersistenceDecodeError(replayResult.failure));
|
||||
assert.ok(
|
||||
replayResult.failure.operation.includes(
|
||||
"OrchestrationEventStore.readFromSequence:decodeRows",
|
||||
|
||||
@@ -42,6 +42,7 @@ 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.
|
||||
@@ -83,6 +84,7 @@ export const migrationEntries = [
|
||||
[27, "ProviderSessionRuntimeInstanceId", Migration0027],
|
||||
[28, "ProjectionThreadSessionInstanceId", Migration0028],
|
||||
[29, "ProjectionThreadDetailOrderingIndexes", Migration0029],
|
||||
[30, "ProjectionThreadShellArchiveIndexes", Migration0030],
|
||||
] as const;
|
||||
|
||||
export const makeMigrationLoader = (throughId?: number) =>
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
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)
|
||||
`;
|
||||
});
|
||||
@@ -25,6 +25,7 @@ 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) =>
|
||||
|
||||
@@ -48,6 +48,7 @@ import {
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
} from "../providerMaintenance.ts";
|
||||
import { makeClaudeCapabilitiesCacheKey, makeClaudeContinuationGroupKey } from "./ClaudeHome.ts";
|
||||
const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("claudeAgent");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
@@ -105,7 +106,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
supportsMultipleInstances: true,
|
||||
},
|
||||
configSchema: ClaudeSettings,
|
||||
defaultConfig: (): ClaudeSettings => Schema.decodeSync(ClaudeSettings)({}),
|
||||
defaultConfig: (): ClaudeSettings => decodeClaudeSettings({}),
|
||||
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
@@ -51,6 +51,7 @@ import {
|
||||
materializeCodexShadowHome,
|
||||
resolveCodexHomeLayout,
|
||||
} from "./CodexHomeLayout.ts";
|
||||
const decodeCodexSettings = Schema.decodeSync(CodexSettings);
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("codex");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
@@ -103,7 +104,7 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
supportsMultipleInstances: true,
|
||||
},
|
||||
configSchema: CodexSettings,
|
||||
defaultConfig: (): CodexSettings => Schema.decodeSync(CodexSettings)({}),
|
||||
defaultConfig: (): CodexSettings => decodeCodexSettings({}),
|
||||
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
materializeCodexShadowHome,
|
||||
resolveCodexHomeLayout,
|
||||
} from "./CodexHomeLayout.ts";
|
||||
const decodeCodexSettingsValue = Schema.decodeSync(CodexSettings);
|
||||
|
||||
const decodeCodexSettings = (input: {
|
||||
readonly enabled?: boolean;
|
||||
@@ -18,7 +19,7 @@ const decodeCodexSettings = (input: {
|
||||
readonly shadowHomePath?: string;
|
||||
readonly customModels?: readonly string[];
|
||||
readonly binaryPath?: string;
|
||||
}): CodexSettings => Schema.decodeSync(CodexSettings)(input);
|
||||
}): CodexSettings => decodeCodexSettingsValue(input);
|
||||
|
||||
const makeTempDir = Effect.fn("CodexHomeLayout.test.makeTempDir")(function* (prefix: string) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -74,6 +74,7 @@ export class CodexShadowHomeError extends Schema.TaggedErrorClass<CodexShadowHom
|
||||
return this.detail;
|
||||
}
|
||||
}
|
||||
const isCodexShadowHomeError = Schema.is(CodexShadowHomeError);
|
||||
|
||||
type LinkState =
|
||||
| {
|
||||
@@ -88,7 +89,7 @@ type LinkState =
|
||||
};
|
||||
|
||||
function toShadowHomeError(cause: unknown): CodexShadowHomeError {
|
||||
return Schema.is(CodexShadowHomeError)(cause)
|
||||
return isCodexShadowHomeError(cause)
|
||||
? cause
|
||||
: new CodexShadowHomeError({
|
||||
detail: "Failed to materialize Codex shadow home.",
|
||||
|
||||
@@ -45,6 +45,7 @@ import {
|
||||
makeStaticProviderMaintenanceResolver,
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
} from "../providerMaintenance.ts";
|
||||
const decodeCursorSettings = Schema.decodeSync(CursorSettings);
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("cursor");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
@@ -89,7 +90,7 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
supportsMultipleInstances: true,
|
||||
},
|
||||
configSchema: CursorSettings,
|
||||
defaultConfig: (): CursorSettings => Schema.decodeSync(CursorSettings)({}),
|
||||
defaultConfig: (): CursorSettings => decodeCursorSettings({}),
|
||||
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
@@ -46,6 +46,7 @@ import {
|
||||
normalizeCommandPath,
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
} from "../providerMaintenance.ts";
|
||||
const decodeOpenCodeSettings = Schema.decodeSync(OpenCodeSettings);
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("opencode");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
@@ -102,7 +103,7 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
supportsMultipleInstances: true,
|
||||
},
|
||||
configSchema: OpenCodeSettings,
|
||||
defaultConfig: (): OpenCodeSettings => Schema.decodeSync(OpenCodeSettings)({}),
|
||||
defaultConfig: (): OpenCodeSettings => decodeOpenCodeSettings({}),
|
||||
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
|
||||
Effect.gen(function* () {
|
||||
const openCodeRuntime = yield* OpenCodeRuntime;
|
||||
|
||||
@@ -38,6 +38,7 @@ import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderAdapterValidationError } from "../Errors.ts";
|
||||
import type { ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
|
||||
import { makeClaudeAdapter, type ClaudeAdapterLiveOptions } from "./ClaudeAdapter.ts";
|
||||
const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
|
||||
|
||||
// Test-local service tag so the rest of the file can keep using `yield* ClaudeAdapter`.
|
||||
class ClaudeAdapter extends Context.Service<ClaudeAdapter, ClaudeAdapterShape>()(
|
||||
@@ -186,7 +187,7 @@ function makeHarness(config?: {
|
||||
layer: Layer.effect(
|
||||
ClaudeAdapter,
|
||||
Effect.gen(function* () {
|
||||
const claudeConfig = Schema.decodeSync(ClaudeSettings)(config?.claudeConfig ?? {});
|
||||
const claudeConfig = decodeClaudeSettings(config?.claudeConfig ?? {});
|
||||
return yield* makeClaudeAdapter(claudeConfig, adapterOptions);
|
||||
}),
|
||||
).pipe(
|
||||
@@ -1344,7 +1345,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
const layer = Layer.effect(
|
||||
ClaudeAdapter,
|
||||
Effect.gen(function* () {
|
||||
const claudeConfig = Schema.decodeSync(ClaudeSettings)({});
|
||||
const claudeConfig = decodeClaudeSettings({});
|
||||
return yield* makeClaudeAdapter(claudeConfig, {
|
||||
createQuery: () => {
|
||||
const query = new FakeClaudeQuery();
|
||||
@@ -1427,7 +1428,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
const layer = Layer.effect(
|
||||
ClaudeAdapter,
|
||||
Effect.gen(function* () {
|
||||
const claudeConfig = Schema.decodeSync(ClaudeSettings)({});
|
||||
const claudeConfig = decodeClaudeSettings({});
|
||||
return yield* makeClaudeAdapter(claudeConfig, {
|
||||
createQuery: (input) => {
|
||||
// Simulate the SDK consuming the prompt iterable
|
||||
|
||||
@@ -84,6 +84,8 @@ import {
|
||||
} from "../Errors.ts";
|
||||
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");
|
||||
type ClaudeTextStreamKind = Extract<RuntimeContentStreamKind, "assistant_text" | "reasoning_text">;
|
||||
@@ -93,6 +95,11 @@ 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";
|
||||
@@ -545,7 +552,7 @@ function summarizeToolRequest(toolName: string, input: Record<string, unknown>):
|
||||
}
|
||||
}
|
||||
|
||||
const serialized = Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(input);
|
||||
const serialized = encodeJsonStringForDiagnostics(input) ?? "[unserializable input]";
|
||||
if (serialized.length <= 400) {
|
||||
return `${toolName}: ${serialized}`;
|
||||
}
|
||||
@@ -810,22 +817,18 @@ function exitPlanCaptureKey(input: {
|
||||
}
|
||||
|
||||
function tryParseJsonRecord(value: string): Record<string, unknown> | undefined {
|
||||
try {
|
||||
const parsed = Schema.decodeUnknownSync(Schema.UnknownFromJsonString)(value);
|
||||
return parsed && typeof parsed === "object" && !Array.isArray(parsed)
|
||||
? (parsed as Record<string, unknown>)
|
||||
: undefined;
|
||||
} catch {
|
||||
const result = decodeUnknownJsonStringExit(value);
|
||||
if (!Exit.isSuccess(result)) {
|
||||
return undefined;
|
||||
}
|
||||
const parsed = result.value;
|
||||
return parsed && typeof parsed === "object" && !Array.isArray(parsed)
|
||||
? (parsed as Record<string, unknown>)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function toolInputFingerprint(input: Record<string, unknown>): string | undefined {
|
||||
try {
|
||||
return Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(input);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
return encodeJsonStringForDiagnostics(input);
|
||||
}
|
||||
|
||||
function toolResultStreamKind(itemType: CanonicalItemType): ClaudeToolResultStreamKind | undefined {
|
||||
@@ -2941,12 +2944,8 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
"claude.query.include_partial_messages": true,
|
||||
"claude.query.additional_directories": input.cwd ? [input.cwd] : [],
|
||||
"claude.query.setting_sources": [...CLAUDE_SETTING_SOURCES],
|
||||
"claude.query.settings_json": Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(
|
||||
settings,
|
||||
),
|
||||
"claude.query.extra_args_json": Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(
|
||||
extraArgs,
|
||||
),
|
||||
"claude.query.settings_json": encodeJsonStringForDiagnostics(settings) ?? "",
|
||||
"claude.query.extra_args_json": encodeJsonStringForDiagnostics(extraArgs) ?? "",
|
||||
"claude.query.path_to_executable": claudeBinaryPath,
|
||||
});
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
getProviderOptionCurrentValue,
|
||||
getProviderOptionDescriptors,
|
||||
} from "@t3tools/shared/model";
|
||||
import { compareSemverVersions } from "@t3tools/shared/semver";
|
||||
import {
|
||||
query as claudeQuery,
|
||||
type SlashCommand as ClaudeSlashCommand,
|
||||
@@ -36,7 +37,6 @@ 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 ? compareCliVersions(version, MINIMUM_CLAUDE_OPUS_4_7_VERSION) >= 0 : false;
|
||||
return version ? compareSemverVersions(version, MINIMUM_CLAUDE_OPUS_4_7_VERSION) >= 0 : false;
|
||||
}
|
||||
|
||||
function getBuiltInClaudeModelsForVersion(
|
||||
|
||||
@@ -46,6 +46,7 @@ import {
|
||||
type CodexThreadSnapshot,
|
||||
} from "./CodexSessionRuntime.ts";
|
||||
import { makeCodexAdapter } from "./CodexAdapter.ts";
|
||||
const decodeCodexSettings = Schema.decodeSync(CodexSettings);
|
||||
|
||||
// Test-local service tag so the rest of the file can keep using `yield* CodexAdapter`.
|
||||
class CodexAdapter extends Context.Service<CodexAdapter, CodexAdapterShape>()(
|
||||
@@ -224,7 +225,7 @@ const validationLayer = it.layer(
|
||||
Layer.effect(
|
||||
CodexAdapter,
|
||||
Effect.gen(function* () {
|
||||
const codexConfig = Schema.decodeSync(CodexSettings)({});
|
||||
const codexConfig = decodeCodexSettings({});
|
||||
return yield* makeCodexAdapter(codexConfig, {
|
||||
makeRuntime: validationRuntimeFactory.factory,
|
||||
});
|
||||
@@ -293,7 +294,7 @@ const sessionErrorLayer = it.layer(
|
||||
Layer.effect(
|
||||
CodexAdapter,
|
||||
Effect.gen(function* () {
|
||||
const codexConfig = Schema.decodeSync(CodexSettings)({});
|
||||
const codexConfig = decodeCodexSettings({});
|
||||
return yield* makeCodexAdapter(codexConfig, {
|
||||
makeRuntime: sessionRuntimeFactory.factory,
|
||||
});
|
||||
@@ -364,7 +365,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
|
||||
const customLayer = Layer.effect(
|
||||
CodexAdapter,
|
||||
Effect.gen(function* () {
|
||||
const codexConfig = Schema.decodeSync(CodexSettings)({});
|
||||
const codexConfig = decodeCodexSettings({});
|
||||
return yield* makeCodexAdapter(codexConfig, {
|
||||
instanceId: customInstanceId,
|
||||
makeRuntime: customRuntimeFactory.factory,
|
||||
@@ -419,7 +420,7 @@ const lifecycleLayer = it.layer(
|
||||
Layer.effect(
|
||||
CodexAdapter,
|
||||
Effect.gen(function* () {
|
||||
const codexConfig = Schema.decodeSync(CodexSettings)({});
|
||||
const codexConfig = decodeCodexSettings({});
|
||||
return yield* makeCodexAdapter(codexConfig, {
|
||||
makeRuntime: lifecycleRuntimeFactory.factory,
|
||||
});
|
||||
@@ -1034,7 +1035,7 @@ const scopedLifecycleLayer = it.layer(
|
||||
Layer.effect(
|
||||
CodexAdapter,
|
||||
Effect.gen(function* () {
|
||||
const codexConfig = Schema.decodeSync(CodexSettings)({});
|
||||
const codexConfig = decodeCodexSettings({});
|
||||
return yield* makeCodexAdapter(codexConfig, {
|
||||
makeRuntime: scopedLifecycleRuntimeFactory.factory,
|
||||
});
|
||||
@@ -1078,7 +1079,7 @@ const scopedFailureLayer = it.layer(
|
||||
Layer.effect(
|
||||
CodexAdapter,
|
||||
Effect.gen(function* () {
|
||||
const codexConfig = Schema.decodeSync(CodexSettings)({});
|
||||
const codexConfig = decodeCodexSettings({});
|
||||
return yield* makeCodexAdapter(codexConfig, {
|
||||
makeRuntime: scopedFailureRuntimeFactory.factory,
|
||||
});
|
||||
@@ -1127,7 +1128,7 @@ it.effect("flushes managed native logs when the adapter layer shuts down", () =>
|
||||
const layer = Layer.effect(
|
||||
CodexAdapter,
|
||||
Effect.gen(function* () {
|
||||
const codexConfig = Schema.decodeSync(CodexSettings)({});
|
||||
const codexConfig = decodeCodexSettings({});
|
||||
return yield* makeCodexAdapter(codexConfig, {
|
||||
makeRuntime: runtimeFactory.factory,
|
||||
nativeEventLogPath: basePath,
|
||||
|
||||
@@ -61,6 +61,12 @@ import {
|
||||
type CodexSessionRuntimeShape,
|
||||
} from "./CodexSessionRuntime.ts";
|
||||
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
const isCodexAppServerProcessExitedError = Schema.is(CodexErrors.CodexAppServerProcessExitedError);
|
||||
const isCodexAppServerTransportError = Schema.is(CodexErrors.CodexAppServerTransportError);
|
||||
const isCodexSessionRuntimeThreadIdMissingError = Schema.is(
|
||||
CodexSessionRuntimeThreadIdMissingError,
|
||||
);
|
||||
const isCodexResumeCursorSchema = Schema.is(CodexResumeCursorSchema);
|
||||
|
||||
const PROVIDER = ProviderDriverKind.make("codex");
|
||||
|
||||
@@ -91,10 +97,7 @@ function mapCodexRuntimeError(
|
||||
method: string,
|
||||
error: CodexSessionRuntimeError,
|
||||
): ProviderAdapterError {
|
||||
if (
|
||||
Schema.is(CodexErrors.CodexAppServerProcessExitedError)(error) ||
|
||||
Schema.is(CodexErrors.CodexAppServerTransportError)(error)
|
||||
) {
|
||||
if (isCodexAppServerProcessExitedError(error) || isCodexAppServerTransportError(error)) {
|
||||
return new ProviderAdapterSessionClosedError({
|
||||
provider: PROVIDER,
|
||||
threadId,
|
||||
@@ -102,7 +105,7 @@ function mapCodexRuntimeError(
|
||||
});
|
||||
}
|
||||
|
||||
if (Schema.is(CodexSessionRuntimeThreadIdMissingError)(error)) {
|
||||
if (isCodexSessionRuntimeThreadIdMissingError(error)) {
|
||||
return new ProviderAdapterSessionNotFoundError({
|
||||
provider: PROVIDER,
|
||||
threadId,
|
||||
@@ -134,7 +137,8 @@ function readPayload<A>(
|
||||
schema: Schema.Schema<A>,
|
||||
payload: ProviderEvent["payload"],
|
||||
): A | undefined {
|
||||
return Schema.is(schema)(payload) ? payload : undefined;
|
||||
const isPayload = Schema.is(schema);
|
||||
return isPayload(payload) ? payload : undefined;
|
||||
}
|
||||
|
||||
function trimText(value: string | undefined | null): string | undefined {
|
||||
@@ -1381,7 +1385,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
binaryPath: codexConfig.binaryPath,
|
||||
...(options?.environment ? { environment: options.environment } : {}),
|
||||
...(codexConfig.homePath ? { homePath: codexConfig.homePath } : {}),
|
||||
...(Schema.is(CodexResumeCursorSchema)(input.resumeCursor)
|
||||
...(isCodexResumeCursorSchema(input.resumeCursor)
|
||||
? { resumeCursor: input.resumeCursor }
|
||||
: {}),
|
||||
runtimeMode: input.runtimeMode,
|
||||
|
||||
@@ -26,6 +26,7 @@ import { buildServerProvider, type ServerProviderDraft } from "../providerSnapsh
|
||||
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 = {
|
||||
@@ -450,7 +451,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
|
||||
|
||||
if (Result.isFailure(probeResult)) {
|
||||
const error = probeResult.failure;
|
||||
const installed = !Schema.is(CodexErrors.CodexAppServerSpawnError)(error);
|
||||
const installed = !isCodexAppServerSpawnError(error);
|
||||
return buildServerProvider({
|
||||
presentation: CODEX_PRESENTATION,
|
||||
enabled: codexSettings.enabled,
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
isRecoverableThreadResumeError,
|
||||
openCodexThread,
|
||||
} from "./CodexSessionRuntime.ts";
|
||||
const isCodexAppServerRequestError = Schema.is(CodexErrors.CodexAppServerRequestError);
|
||||
|
||||
function makeThreadOpenResponse(
|
||||
threadId: string,
|
||||
@@ -269,7 +270,7 @@ describe("openCodexThread", () => {
|
||||
}),
|
||||
),
|
||||
(error: unknown) =>
|
||||
Schema.is(CodexErrors.CodexAppServerRequestError)(error) &&
|
||||
isCodexAppServerRequestError(error) &&
|
||||
error.errorMessage === "timed out waiting for server",
|
||||
);
|
||||
});
|
||||
|
||||
@@ -41,6 +41,7 @@ import {
|
||||
CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
|
||||
CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
|
||||
} from "../CodexDeveloperInstructions.ts";
|
||||
const decodeV2TurnStartResponse = Schema.decodeUnknownEffect(EffectCodexSchema.V2TurnStartResponse);
|
||||
|
||||
const PROVIDER = ProviderDriverKind.make("codex");
|
||||
|
||||
@@ -66,6 +67,8 @@ export const CodexResumeCursorSchema = Schema.Struct({
|
||||
const CodexUserInputAnswerObject = Schema.Struct({
|
||||
answers: Schema.Array(Schema.String),
|
||||
});
|
||||
const isCodexResumeCursorSchema = Schema.is(CodexResumeCursorSchema);
|
||||
const isCodexUserInputAnswerObject = Schema.is(CodexUserInputAnswerObject);
|
||||
|
||||
// TODO: Verify `packages/effect-codex-app-server/scripts/generate.ts` so the generated
|
||||
// `V2TurnStartParams` schema includes `collaborationMode` directly.
|
||||
@@ -74,6 +77,9 @@ const CodexTurnStartParamsWithCollaborationMode = EffectCodexSchema.V2TurnStartP
|
||||
collaborationMode: Schema.optionalKey(EffectCodexSchema.V2TurnStartParams__CollaborationMode),
|
||||
}),
|
||||
);
|
||||
const decodeCodexTurnStartParamsWithCollaborationMode = Schema.decodeUnknownEffect(
|
||||
CodexTurnStartParamsWithCollaborationMode,
|
||||
);
|
||||
|
||||
export type CodexTurnStartParamsWithCollaborationMode =
|
||||
typeof CodexTurnStartParamsWithCollaborationMode.Type;
|
||||
@@ -248,7 +254,7 @@ function normalizeCodexModelSlug(
|
||||
function readResumeCursorThreadId(
|
||||
resumeCursor: ProviderSession["resumeCursor"],
|
||||
): string | undefined {
|
||||
return Schema.is(CodexResumeCursorSchema)(resumeCursor) ? resumeCursor.threadId : undefined;
|
||||
return isCodexResumeCursorSchema(resumeCursor) ? resumeCursor.threadId : undefined;
|
||||
}
|
||||
|
||||
function runtimeModeToThreadConfig(input: RuntimeMode): {
|
||||
@@ -367,7 +373,7 @@ export function buildTurnStartParams(input: {
|
||||
...(input.effort ? { effort: input.effort } : {}),
|
||||
});
|
||||
|
||||
return Schema.decodeUnknownEffect(CodexTurnStartParamsWithCollaborationMode)({
|
||||
return decodeCodexTurnStartParamsWithCollaborationMode({
|
||||
threadId: input.threadId,
|
||||
input: turnInput,
|
||||
approvalPolicy: config.approvalPolicy,
|
||||
@@ -623,7 +629,7 @@ function toCodexUserInputAnswer(
|
||||
const answers = value.filter((entry): entry is string => typeof entry === "string");
|
||||
return Effect.succeed({ answers });
|
||||
}
|
||||
if (Schema.is(CodexUserInputAnswerObject)(value)) {
|
||||
if (isCodexUserInputAnswerObject(value)) {
|
||||
return Effect.succeed({ answers: value.answers });
|
||||
}
|
||||
return Effect.fail(new CodexSessionRuntimeInvalidUserInputAnswersError({ questionId }));
|
||||
@@ -1247,9 +1253,7 @@ export const makeCodexSessionRuntime = (
|
||||
...(input.interactionMode ? { interactionMode: input.interactionMode } : {}),
|
||||
});
|
||||
const rawResponse = yield* client.raw.request("turn/start", params);
|
||||
const response = yield* Schema.decodeUnknownEffect(EffectCodexSchema.V2TurnStartResponse)(
|
||||
rawResponse,
|
||||
).pipe(
|
||||
const response = yield* decodeV2TurnStartResponse(rawResponse).pipe(
|
||||
Effect.mapError((error) =>
|
||||
toProtocolParseError("Invalid turn/start response payload", error),
|
||||
),
|
||||
|
||||
@@ -28,6 +28,7 @@ import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import type { CursorAdapterShape } from "../Services/CursorAdapter.ts";
|
||||
import { makeCursorAdapter } from "./CursorAdapter.ts";
|
||||
const decodeCursorSettings = Schema.decodeSync(CursorSettings);
|
||||
|
||||
// Test-local service tag so the rest of the file can keep using `yield* CursorAdapter`.
|
||||
class CursorAdapter extends Context.Service<CursorAdapter, CursorAdapterShape>()(
|
||||
@@ -132,7 +133,7 @@ const cursorAdapterTestLayer = it.layer(
|
||||
Layer.effect(
|
||||
CursorAdapter,
|
||||
Effect.gen(function* () {
|
||||
const cursorConfig = Schema.decodeSync(CursorSettings)({});
|
||||
const cursorConfig = decodeCursorSettings({});
|
||||
const resolveSettings = yield* makeResolveCursorSettings;
|
||||
return yield* makeCursorAdapter(cursorConfig, { resolveSettings });
|
||||
}),
|
||||
@@ -607,7 +608,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
|
||||
Layer.effect(
|
||||
CursorAdapter,
|
||||
Effect.gen(function* () {
|
||||
const cursorConfig = Schema.decodeSync(CursorSettings)({});
|
||||
const cursorConfig = decodeCursorSettings({});
|
||||
const resolveSettings = yield* makeResolveCursorSettings;
|
||||
return yield* makeCursorAdapter(cursorConfig, { resolveSettings });
|
||||
}),
|
||||
@@ -1239,7 +1240,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
|
||||
const customAdapterLayer = Layer.effect(
|
||||
CursorAdapter,
|
||||
Effect.gen(function* () {
|
||||
const cursorConfig = Schema.decodeSync(CursorSettings)({});
|
||||
const cursorConfig = decodeCursorSettings({});
|
||||
const resolveSettings = yield* makeResolveCursorSettings;
|
||||
return yield* makeCursorAdapter(cursorConfig, {
|
||||
instanceId: customInstanceId,
|
||||
|
||||
@@ -75,6 +75,7 @@ import {
|
||||
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;
|
||||
@@ -82,6 +83,11 @@ 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;
|
||||
@@ -390,7 +396,7 @@ export function makeCursorAdapter(
|
||||
method: string,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const fingerprint = `${ctx.activeTurnId ?? "no-turn"}:${Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(payload)}`;
|
||||
const fingerprint = `${ctx.activeTurnId ?? "no-turn"}:${encodeJsonStringForDiagnostics(payload) ?? "[unserializable payload]"}`;
|
||||
if (ctx.lastPlanFingerprint === fingerprint) {
|
||||
return;
|
||||
}
|
||||
@@ -640,7 +646,8 @@ export function makeCursorAdapter(
|
||||
permissionRequest,
|
||||
detail:
|
||||
permissionRequest.detail ??
|
||||
Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(params).slice(0, 2000),
|
||||
encodeJsonStringForDiagnostics(params)?.slice(0, 2000) ??
|
||||
"[unserializable params]",
|
||||
args: params,
|
||||
source: "acp.jsonrpc",
|
||||
method: "session/request_permission",
|
||||
|
||||
@@ -559,17 +559,98 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("deduplicates overlapping assistant text deltas after part updates", () =>
|
||||
it.effect("appends raw assistant text deltas and reconciles part update snapshots", () =>
|
||||
Effect.sync(() => {
|
||||
const firstUpdate = mergeOpenCodeAssistantText(undefined, "Hello");
|
||||
const overlapDelta = appendOpenCodeAssistantTextDelta(firstUpdate.latestText, "lo world");
|
||||
const secondUpdate = mergeOpenCodeAssistantText(overlapDelta.nextText, "Hello world!");
|
||||
const secondUpdate = mergeOpenCodeAssistantText(overlapDelta.nextText, "Hellolo world");
|
||||
|
||||
assert.deepEqual(
|
||||
[firstUpdate.deltaToEmit, overlapDelta.deltaToEmit, secondUpdate.deltaToEmit],
|
||||
["Hello", " world", "!"],
|
||||
["Hello", "lo world", ""],
|
||||
);
|
||||
assert.equal(secondUpdate.latestText, "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");
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -311,16 +311,6 @@ 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;
|
||||
@@ -349,10 +339,9 @@ export function appendOpenCodeAssistantTextDelta(
|
||||
readonly nextText: string;
|
||||
readonly deltaToEmit: string;
|
||||
} {
|
||||
const deltaToEmit = delta.slice(suffixPrefixOverlap(previousText, delta));
|
||||
return {
|
||||
nextText: previousText + deltaToEmit,
|
||||
deltaToEmit,
|
||||
nextText: previousText + delta,
|
||||
deltaToEmit: delta,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
} from "../opencodeRuntime.ts";
|
||||
import { checkOpenCodeProviderStatus } from "./OpenCodeProvider.ts";
|
||||
import type { OpenCodeInventory } from "../opencodeRuntime.ts";
|
||||
const decodeOpenCodeSettings = Schema.decodeSync(OpenCodeSettings);
|
||||
|
||||
const DEFAULT_VERSION_STDOUT = "opencode 1.14.19\n";
|
||||
|
||||
@@ -106,7 +107,7 @@ const testLayer = Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble).pipe
|
||||
);
|
||||
|
||||
const makeOpenCodeSettings = (overrides?: Partial<OpenCodeSettings>): OpenCodeSettings =>
|
||||
Schema.decodeSync(OpenCodeSettings)({
|
||||
decodeOpenCodeSettings({
|
||||
enabled: true,
|
||||
binaryPath: "opencode",
|
||||
serverUrl: "",
|
||||
|
||||
@@ -10,6 +10,7 @@ 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,
|
||||
@@ -17,7 +18,6 @@ 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 (compareCliVersions(version, MINIMUM_OPENCODE_VERSION) < 0) {
|
||||
if (compareSemverVersions(version, MINIMUM_OPENCODE_VERSION) < 0) {
|
||||
return buildServerProvider({
|
||||
presentation: OPENCODE_PRESENTATION,
|
||||
enabled: openCodeSettings.enabled,
|
||||
|
||||
@@ -27,6 +27,7 @@ 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";
|
||||
@@ -47,6 +48,9 @@ import type { ProviderInstance } from "../ProviderDriver.ts";
|
||||
import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
|
||||
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)({});
|
||||
@@ -255,7 +259,8 @@ function makeMutableServerSettingsService(
|
||||
updateSettings: (patch) =>
|
||||
Effect.gen(function* () {
|
||||
const current = yield* Ref.get(settingsRef);
|
||||
const next = Schema.decodeSync(ServerSettings)(deepMerge(current, patch));
|
||||
const next = applyServerSettingsPatch(current, patch);
|
||||
encodeServerSettings(next);
|
||||
yield* Ref.set(settingsRef, next);
|
||||
yield* PubSub.publish(changes, next);
|
||||
return next;
|
||||
@@ -928,8 +933,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
Effect.gen(function* () {
|
||||
const missingBinary = `t3code_codex_missing_`;
|
||||
const serverSettings = yield* makeMutableServerSettingsService(
|
||||
Schema.decodeSync(ServerSettings)(
|
||||
deepMerge(DEFAULT_SERVER_SETTINGS, {
|
||||
decodeServerSettings(
|
||||
deepMerge(encodedDefaultServerSettings, {
|
||||
providers: {
|
||||
// Disable every built-in probe that would otherwise spawn
|
||||
// on the CI host. `enabled: false` short-circuits each
|
||||
@@ -1027,8 +1032,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
const firstMissing = `t3code_codex_first_`;
|
||||
const secondMissing = `t3code_codex_second_`;
|
||||
const serverSettings = yield* makeMutableServerSettingsService(
|
||||
Schema.decodeSync(ServerSettings)(
|
||||
deepMerge(DEFAULT_SERVER_SETTINGS, {
|
||||
decodeServerSettings(
|
||||
deepMerge(encodedDefaultServerSettings, {
|
||||
providers: {
|
||||
codex: { enabled: true, binaryPath: firstMissing },
|
||||
claudeAgent: { enabled: false },
|
||||
@@ -1122,8 +1127,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
it.effect("includes unavailable instance snapshots in getProviders", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* makeMutableServerSettingsService(
|
||||
Schema.decodeSync(ServerSettings)(
|
||||
deepMerge(DEFAULT_SERVER_SETTINGS, {
|
||||
decodeServerSettings(
|
||||
deepMerge(encodedDefaultServerSettings, {
|
||||
providers: {
|
||||
codex: { enabled: false },
|
||||
claudeAgent: { enabled: false },
|
||||
@@ -1178,8 +1183,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* makeMutableServerSettingsService(
|
||||
Schema.decodeSync(ServerSettings)(
|
||||
deepMerge(DEFAULT_SERVER_SETTINGS, {
|
||||
decodeServerSettings(
|
||||
deepMerge(encodedDefaultServerSettings, {
|
||||
providers: {
|
||||
codex: {
|
||||
enabled: false,
|
||||
|
||||
@@ -56,6 +56,7 @@ import {
|
||||
import { type EventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
import { ProviderEventLoggers } from "./ProviderEventLoggers.ts";
|
||||
import { AnalyticsService } from "../../telemetry/Services/AnalyticsService.ts";
|
||||
const isModelSelection = Schema.is(ModelSelection);
|
||||
|
||||
/**
|
||||
* Hook for tests that want to override the canonical event logger pulled
|
||||
@@ -87,8 +88,9 @@ const decodeInputOrValidationError = <S extends Schema.Top>(input: {
|
||||
readonly operation: string;
|
||||
readonly schema: S;
|
||||
readonly payload: unknown;
|
||||
}) =>
|
||||
Schema.decodeUnknownEffect(input.schema)(input.payload).pipe(
|
||||
}) => {
|
||||
const decodeProviderRequestInput = Schema.decodeUnknownEffect(input.schema);
|
||||
return decodeProviderRequestInput(input.payload).pipe(
|
||||
Effect.mapError(
|
||||
(schemaError) =>
|
||||
new ProviderValidationError({
|
||||
@@ -98,6 +100,7 @@ const decodeInputOrValidationError = <S extends Schema.Top>(input: {
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
function toRuntimeStatus(session: ProviderSession): "starting" | "running" | "stopped" | "error" {
|
||||
switch (session.status) {
|
||||
@@ -142,7 +145,7 @@ function readPersistedModelSelection(
|
||||
return undefined;
|
||||
}
|
||||
const raw = "modelSelection" in runtimePayload ? runtimePayload.modelSelection : undefined;
|
||||
return Schema.is(ModelSelection)(raw) ? raw : undefined;
|
||||
return isModelSelection(raw) ? raw : undefined;
|
||||
}
|
||||
|
||||
function readPersistedCwd(
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
type ProviderRuntimeBindingWithMetadata,
|
||||
type ProviderSessionDirectoryShape,
|
||||
} from "../Services/ProviderSessionDirectory.ts";
|
||||
const decodeProviderDriverKindValue = Schema.decodeUnknownEffect(ProviderDriverKind);
|
||||
|
||||
function toPersistenceError(operation: string) {
|
||||
return (cause: unknown) =>
|
||||
@@ -28,7 +29,7 @@ function decodeProviderDriverKind(
|
||||
providerName: string,
|
||||
operation: string,
|
||||
): Effect.Effect<ProviderDriverKind, ProviderSessionDirectoryPersistenceError> {
|
||||
return Schema.decodeUnknownEffect(ProviderDriverKind)(providerName).pipe(
|
||||
return decodeProviderDriverKindValue(providerName).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderSessionDirectoryPersistenceError({
|
||||
|
||||
@@ -194,6 +194,7 @@ 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"),
|
||||
|
||||
@@ -11,6 +11,8 @@ import {
|
||||
ProviderAdapterSessionClosedError,
|
||||
type ProviderAdapterError,
|
||||
} from "../Errors.ts";
|
||||
const isAcpProcessExitedError = Schema.is(EffectAcpErrors.AcpProcessExitedError);
|
||||
const isAcpRequestError = Schema.is(EffectAcpErrors.AcpRequestError);
|
||||
|
||||
export function mapAcpToAdapterError(
|
||||
provider: ProviderDriverKind,
|
||||
@@ -18,14 +20,14 @@ export function mapAcpToAdapterError(
|
||||
method: string,
|
||||
error: EffectAcpErrors.AcpError,
|
||||
): ProviderAdapterError {
|
||||
if (Schema.is(EffectAcpErrors.AcpProcessExitedError)(error)) {
|
||||
if (isAcpProcessExitedError(error)) {
|
||||
return new ProviderAdapterSessionClosedError({
|
||||
provider,
|
||||
threadId,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
if (Schema.is(EffectAcpErrors.AcpRequestError)(error)) {
|
||||
if (isAcpRequestError(error)) {
|
||||
return new ProviderAdapterRequestError({
|
||||
provider,
|
||||
method,
|
||||
|
||||
@@ -7,7 +7,6 @@ import * as Queue from "effect/Queue";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as EffectAcpClient from "effect-acp/client";
|
||||
@@ -27,6 +26,10 @@ import {
|
||||
type AcpToolCallState,
|
||||
} from "./AcpRuntimeModel.ts";
|
||||
|
||||
function formatConfigOptionValue(value: string | boolean): string {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
export interface AcpSpawnInput {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
@@ -277,7 +280,7 @@ const makeAcpSessionRuntime = (
|
||||
}
|
||||
return yield* new EffectAcpErrors.AcpRequestError({
|
||||
code: -32602,
|
||||
errorMessage: `Invalid value ${Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(value)} for session config option "${configOption.id}": expected boolean`,
|
||||
errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option "${configOption.id}": expected boolean`,
|
||||
data: {
|
||||
configId: configOption.id,
|
||||
expectedType: "boolean",
|
||||
@@ -288,7 +291,7 @@ const makeAcpSessionRuntime = (
|
||||
if (typeof value !== "string") {
|
||||
return yield* new EffectAcpErrors.AcpRequestError({
|
||||
code: -32602,
|
||||
errorMessage: `Invalid value ${Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(value)} for session config option "${configOption.id}": expected string`,
|
||||
errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option "${configOption.id}": expected string`,
|
||||
data: {
|
||||
configId: configOption.id,
|
||||
expectedType: "string",
|
||||
@@ -302,7 +305,7 @@ const makeAcpSessionRuntime = (
|
||||
}
|
||||
return yield* new EffectAcpErrors.AcpRequestError({
|
||||
code: -32602,
|
||||
errorMessage: `Invalid value ${Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(value)} for session config option "${configOption.id}": expected one of ${allowedValues.join(", ")}`,
|
||||
errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option "${configOption.id}": expected one of ${allowedValues.join(", ")}`,
|
||||
data: {
|
||||
configId: configOption.id,
|
||||
allowedValues,
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,123 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -31,6 +31,8 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
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";
|
||||
const DEFAULT_OPENCODE_SERVER_TIMEOUT_MS = 5_000;
|
||||
@@ -56,6 +58,11 @@ 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();
|
||||
@@ -64,10 +71,9 @@ export function openCodeRuntimeErrorDetail(cause: unknown): string {
|
||||
const anyCause = cause as Record<string, unknown>;
|
||||
const status = (anyCause.response as { status?: number } | undefined)?.status;
|
||||
const body = anyCause.error ?? anyCause.data ?? anyCause.body;
|
||||
try {
|
||||
return `status=${status ?? "?"} body=${Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(body ?? cause)}`;
|
||||
} catch {
|
||||
/* fall through */
|
||||
const encodedBody = encodeJsonStringForDiagnostics(body ?? cause);
|
||||
if (encodedBody) {
|
||||
return `status=${status ?? "?"} body=${encodedBody}`;
|
||||
}
|
||||
}
|
||||
return String(cause);
|
||||
@@ -336,7 +342,7 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
|
||||
shell: process.platform === "win32",
|
||||
env: {
|
||||
...(input.environment ?? process.env),
|
||||
OPENCODE_CONFIG_CONTENT: Schema.encodeUnknownSync(Schema.UnknownFromJsonString)({}),
|
||||
OPENCODE_CONFIG_CONTENT: OPENCODE_EMPTY_CONFIG_CONTENT,
|
||||
},
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -3,6 +3,7 @@ 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";
|
||||
@@ -11,8 +12,6 @@ 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.";
|
||||
@@ -365,7 +364,7 @@ function deriveVersionAdvisory(input: {
|
||||
if (!input.latestVersion) {
|
||||
return { status: "unknown", message: null };
|
||||
}
|
||||
if (compareCliVersions(input.currentVersion, input.latestVersion) < 0) {
|
||||
if (compareSemverVersions(input.currentVersion, input.latestVersion) < 0) {
|
||||
return {
|
||||
status: "behind_latest",
|
||||
message: PROVIDER_UPDATE_ACTION_TOAST_MESSAGE,
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
makeProviderMaintenanceCapabilities,
|
||||
type ProviderMaintenanceCapabilities,
|
||||
} from "./providerMaintenance.ts";
|
||||
const isServerProviderUpdateError = Schema.is(ServerProviderUpdateError);
|
||||
|
||||
const CODEX_DRIVER = ProviderDriverKind.make("codex");
|
||||
const CURSOR_DRIVER = ProviderDriverKind.make("cursor");
|
||||
@@ -455,8 +456,8 @@ describe("providerMaintenanceRunner", () => {
|
||||
assert.strictEqual(Exit.isFailure(second), true);
|
||||
if (Exit.isFailure(second)) {
|
||||
const error = Cause.squash(second.cause);
|
||||
assert.strictEqual(Schema.is(ServerProviderUpdateError)(error), true);
|
||||
if (Schema.is(ServerProviderUpdateError)(error)) {
|
||||
assert.strictEqual(isServerProviderUpdateError(error), true);
|
||||
if (isServerProviderUpdateError(error)) {
|
||||
assert.include(error.reason, "already running");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ import { makeProviderMaintenanceCommandCoordinator } from "./providerMaintenance
|
||||
import { enrichProviderSnapshotWithVersionAdvisory } from "./providerMaintenance.ts";
|
||||
import type { ProviderMaintenanceCapabilities } from "./providerMaintenance.ts";
|
||||
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
|
||||
const isServerProviderUpdateError = Schema.is(ServerProviderUpdateError);
|
||||
|
||||
const UPDATE_TIMEOUT_MS = 5 * 60_000;
|
||||
const UPDATE_OUTPUT_MAX_BYTES = 10_000;
|
||||
@@ -397,7 +398,7 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () {
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
Schema.is(ServerProviderUpdateError)(error)
|
||||
isServerProviderUpdateError(error)
|
||||
? new ServerProviderUpdateError({
|
||||
provider,
|
||||
reason: error.reason,
|
||||
|
||||
+112
-16
@@ -630,6 +630,13 @@ 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()),
|
||||
@@ -795,7 +802,12 @@ const bootstrapBrowserSession = (
|
||||
};
|
||||
});
|
||||
|
||||
const bootstrapBearerSession = (credential = defaultDesktopBootstrapToken) =>
|
||||
const bootstrapBearerSession = (
|
||||
credential = defaultDesktopBootstrapToken,
|
||||
options?: {
|
||||
readonly headers?: Record<string, string>;
|
||||
},
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const bootstrapUrl = yield* getHttpServerUrl("/api/auth/bootstrap/bearer");
|
||||
const response = yield* Effect.promise(() =>
|
||||
@@ -803,6 +815,7 @@ const bootstrapBearerSession = (credential = defaultDesktopBootstrapToken) =>
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
...options?.headers,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
credential,
|
||||
@@ -878,6 +891,22 @@ 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 },
|
||||
@@ -999,6 +1028,28 @@ 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();
|
||||
@@ -1122,6 +1173,62 @@ 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",
|
||||
() =>
|
||||
@@ -1133,7 +1240,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
fetch(wsTokenUrl, {
|
||||
method: "OPTIONS",
|
||||
headers: {
|
||||
origin: "http://192.168.86.35:3773",
|
||||
origin: crossOriginClientOrigin,
|
||||
"access-control-request-method": "POST",
|
||||
"access-control-request-headers": "authorization",
|
||||
},
|
||||
@@ -1141,18 +1248,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
);
|
||||
|
||||
assert.equal(response.status, 204);
|
||||
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",
|
||||
]);
|
||||
assertBrowserApiCorsHeaders(response.headers);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
@@ -1165,7 +1261,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
fetch(wsTokenUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
origin: "http://192.168.86.35:3773",
|
||||
origin: crossOriginClientOrigin,
|
||||
},
|
||||
}),
|
||||
);
|
||||
@@ -1174,7 +1270,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
};
|
||||
|
||||
assert.equal(response.status, 401);
|
||||
assert.equal(response.headers.get("access-control-allow-origin"), "*");
|
||||
assertBrowserApiCorsHeaders(response.headers);
|
||||
assert.equal(body.error, "Authentication required.");
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
@@ -85,6 +85,7 @@ 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(
|
||||
@@ -139,6 +140,7 @@ 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: () =>
|
||||
@@ -191,6 +193,7 @@ 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()),
|
||||
|
||||
@@ -9,6 +9,7 @@ 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";
|
||||
@@ -437,6 +438,7 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
serverPassword: "secret-password",
|
||||
},
|
||||
},
|
||||
automaticGitFetchInterval: Duration.seconds(10),
|
||||
});
|
||||
|
||||
assert.equal(next.providers.codex.binaryPath, "/opt/homebrew/bin/codex");
|
||||
@@ -458,6 +460,7 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
serverPassword: "secret-password",
|
||||
},
|
||||
},
|
||||
automaticGitFetchInterval: 10_000,
|
||||
});
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
|
||||
@@ -45,14 +45,33 @@ 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 { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import { fromJsonStringPretty, 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 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;
|
||||
@@ -116,9 +135,15 @@ export class ServerSettingsService extends Context.Service<
|
||||
Layer.effect(
|
||||
ServerSettingsService,
|
||||
Effect.gen(function* () {
|
||||
const currentSettingsRef = yield* Ref.make<ServerSettings>(
|
||||
deepMerge(DEFAULT_SERVER_SETTINGS, overrides),
|
||||
);
|
||||
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);
|
||||
|
||||
return {
|
||||
start: Effect.void,
|
||||
@@ -126,20 +151,8 @@ export class ServerSettingsService extends Context.Service<
|
||||
getSettings: Ref.get(currentSettingsRef),
|
||||
updateSettings: (patch) =>
|
||||
Ref.get(currentSettingsRef).pipe(
|
||||
Effect.flatMap((currentSettings) =>
|
||||
Schema.decodeEffect(ServerSettings)(
|
||||
applyServerSettingsPatch(currentSettings, patch),
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerSettingsError({
|
||||
settingsPath: "<memory>",
|
||||
detail: `failed to normalize server settings: ${SchemaIssue.makeFormatterDefault()(cause.issue)}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.map((currentSettings) => applyServerSettingsPatch(currentSettings, patch)),
|
||||
Effect.flatMap(normalizeServerSettings),
|
||||
Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)),
|
||||
),
|
||||
streamChanges: Stream.empty,
|
||||
@@ -149,6 +162,7 @@ export class ServerSettingsService extends Context.Service<
|
||||
}
|
||||
|
||||
const ServerSettingsJson = fromLenientJson(ServerSettings);
|
||||
const decodeServerSettingsJsonExit = Schema.decodeUnknownExit(ServerSettingsJson);
|
||||
|
||||
type LegacyProviderSettings = ServerSettings["providers"][keyof ServerSettings["providers"]];
|
||||
|
||||
@@ -200,7 +214,10 @@ 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(["textGenerationModelSelection"]);
|
||||
const ATOMIC_SETTINGS_KEYS: ReadonlySet<string> = new Set([
|
||||
"automaticGitFetchInterval",
|
||||
"textGenerationModelSelection",
|
||||
]);
|
||||
|
||||
function stripDefaultServerSettings(current: unknown, defaults: unknown): unknown | undefined {
|
||||
if (Array.isArray(current) || Array.isArray(defaults)) {
|
||||
@@ -280,7 +297,7 @@ const makeServerSettings = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
const raw = yield* readRawConfig;
|
||||
const decoded = Schema.decodeUnknownExit(ServerSettingsJson)(raw);
|
||||
const decoded = decodeServerSettingsJsonExit(raw);
|
||||
if (decoded._tag === "Failure") {
|
||||
yield* Effect.logWarning("failed to parse settings.json, using defaults", {
|
||||
path: settingsPath,
|
||||
@@ -430,25 +447,29 @@ const makeServerSettings = Effect.gen(function* () {
|
||||
};
|
||||
});
|
||||
|
||||
const writeSettingsAtomically = (settings: ServerSettings) => {
|
||||
const sparseSettings = stripDefaultServerSettings(settings, DEFAULT_SERVER_SETTINGS) ?? {};
|
||||
const writeSettingsAtomically = Effect.fnUntraced(
|
||||
function* (settings: ServerSettings) {
|
||||
const sparseSettingsJson = yield* encodeServerSettingsJson(
|
||||
stripDefaultServerSettings(settings, DEFAULT_SERVER_SETTINGS) ?? {},
|
||||
);
|
||||
|
||||
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,
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
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,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const revalidateAndEmit = writeSemaphore.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
@@ -533,16 +554,7 @@ const makeServerSettings = Effect.gen(function* () {
|
||||
current,
|
||||
applyServerSettingsPatch(current, patch),
|
||||
);
|
||||
const next = yield* Schema.decodeEffect(ServerSettings)(nextPersisted).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerSettingsError({
|
||||
settingsPath: "<memory>",
|
||||
detail: `failed to normalize server settings: ${SchemaIssue.makeFormatterDefault()(cause.issue)}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const next = yield* normalizeServerSettings(nextPersisted);
|
||||
yield* writeSettingsAtomically(next);
|
||||
yield* Cache.set(settingsCache, cacheKey, next);
|
||||
yield* emitChange(next);
|
||||
|
||||
@@ -44,6 +44,7 @@ export class BitbucketApiError extends Schema.TaggedErrorClass<BitbucketApiError
|
||||
return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
const isBitbucketApiErrorValue = Schema.is(BitbucketApiError);
|
||||
|
||||
const RawBitbucketRepositorySchema = Schema.Struct({
|
||||
full_name: TrimmedNonEmptyString,
|
||||
@@ -350,7 +351,7 @@ function requestError(operation: string, cause: unknown): BitbucketApiError {
|
||||
}
|
||||
|
||||
function isBitbucketApiError(cause: unknown): cause is BitbucketApiError {
|
||||
return Schema.is(BitbucketApiError)(cause);
|
||||
return isBitbucketApiErrorValue(cause);
|
||||
}
|
||||
|
||||
function responseError(
|
||||
|
||||
@@ -13,6 +13,7 @@ import * as GitHubCli from "./GitHubCli.ts";
|
||||
import * as GitHubPullRequests from "./gitHubPullRequests.ts";
|
||||
import * as SourceControlProvider from "./SourceControlProvider.ts";
|
||||
import * as SourceControlProviderDiscovery from "./SourceControlProviderDiscovery.ts";
|
||||
const isSourceControlProviderError = Schema.is(SourceControlProviderError);
|
||||
|
||||
function providerError(
|
||||
operation: string,
|
||||
@@ -153,7 +154,7 @@ export const make = Effect.fn("makeGitHubSourceControlProvider")(function* () {
|
||||
);
|
||||
}),
|
||||
Effect.mapError((error) =>
|
||||
Schema.is(SourceControlProviderError)(error)
|
||||
isSourceControlProviderError(error)
|
||||
? error
|
||||
: providerError("listChangeRequests", error),
|
||||
),
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
|
||||
const isSourceControlRepositoryError = Schema.is(SourceControlRepositoryError);
|
||||
|
||||
export interface SourceControlRepositoryServiceShape {
|
||||
readonly lookupRepository: (
|
||||
@@ -69,7 +70,7 @@ function repositoryError(input: {
|
||||
|
||||
function mapRepositoryError(operation: string, provider: SourceControlProviderKind) {
|
||||
return Effect.mapError((cause: unknown) =>
|
||||
Schema.is(SourceControlRepositoryError)(cause)
|
||||
isSourceControlRepositoryError(cause)
|
||||
? cause
|
||||
: repositoryError({
|
||||
operation,
|
||||
|
||||
@@ -13,6 +13,7 @@ import { ServerConfig } from "../config.ts";
|
||||
import { type TextGenerationShape } from "./TextGeneration.ts";
|
||||
import { sanitizeThreadTitle } from "./TextGenerationUtils.ts";
|
||||
import { makeClaudeTextGeneration } from "./ClaudeTextGeneration.ts";
|
||||
const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
|
||||
|
||||
const ClaudeTextGenerationTestLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3code-claude-text-generation-test-",
|
||||
@@ -182,7 +183,7 @@ function withFakeClaudeEnv<A, E, R>(
|
||||
}),
|
||||
);
|
||||
|
||||
const config = Schema.decodeSync(ClaudeSettings)(input.claudeConfig ?? {});
|
||||
const config = decodeClaudeSettings(input.claudeConfig ?? {});
|
||||
const textGeneration = yield* makeClaudeTextGeneration(config);
|
||||
return yield* effectFn(textGeneration);
|
||||
}).pipe(Effect.scoped);
|
||||
|
||||
@@ -53,6 +53,9 @@ const ClaudeOutputEnvelope = Schema.Struct({
|
||||
structured_output: Schema.Unknown,
|
||||
});
|
||||
|
||||
const encodeJsonString = Schema.encodeEffect(Schema.UnknownFromJsonString);
|
||||
const decodeClaudeOutputEnvelope = Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope));
|
||||
|
||||
export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(function* (
|
||||
claudeSettings: ClaudeSettings,
|
||||
environment: NodeJS.ProcessEnv = process.env,
|
||||
@@ -75,6 +78,26 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
),
|
||||
);
|
||||
|
||||
const encodeJsonForOperation = (
|
||||
operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle",
|
||||
value: unknown,
|
||||
detail: string,
|
||||
): Effect.Effect<string, TextGenerationError> =>
|
||||
encodeJsonString(value).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
/**
|
||||
* Spawn the Claude CLI with structured JSON output and return the parsed,
|
||||
* schema-validated result.
|
||||
@@ -96,8 +119,10 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
outputSchemaJson: S;
|
||||
modelSelection: ModelSelection;
|
||||
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
|
||||
const jsonSchemaStr = Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(
|
||||
const jsonSchemaStr = yield* encodeJsonForOperation(
|
||||
operation,
|
||||
toJsonSchemaObject(outputSchemaJson),
|
||||
"Failed to encode structured output schema.",
|
||||
);
|
||||
const caps = getClaudeModelCapabilities(modelSelection.model);
|
||||
const descriptors = getProviderOptionDescriptors({
|
||||
@@ -118,6 +143,14 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}),
|
||||
...(fastMode ? { fastMode: true } : {}),
|
||||
};
|
||||
const settingsJson =
|
||||
Object.keys(settings).length > 0
|
||||
? yield* encodeJsonForOperation(
|
||||
operation,
|
||||
settings,
|
||||
"Failed to encode Claude CLI settings.",
|
||||
)
|
||||
: undefined;
|
||||
|
||||
const runClaudeCommand = Effect.fn("runClaudeJson.runClaudeCommand")(function* () {
|
||||
const command = ChildProcess.make(
|
||||
@@ -131,9 +164,7 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
"--model",
|
||||
resolveClaudeApiModelId(modelSelection),
|
||||
...(cliEffort ? ["--effort", cliEffort] : []),
|
||||
...(Object.keys(settings).length > 0
|
||||
? ["--settings", Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(settings)]
|
||||
: []),
|
||||
...(settingsJson ? ["--settings", settingsJson] : []),
|
||||
"--dangerously-skip-permissions",
|
||||
],
|
||||
{
|
||||
@@ -197,9 +228,7 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
),
|
||||
);
|
||||
|
||||
const envelope = yield* Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope))(
|
||||
rawStdout,
|
||||
).pipe(
|
||||
const envelope = yield* decodeClaudeOutputEnvelope(rawStdout).pipe(
|
||||
Effect.catchTag("SchemaError", (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
@@ -211,7 +240,8 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
),
|
||||
);
|
||||
|
||||
return yield* Schema.decodeEffect(outputSchemaJson)(envelope.structured_output).pipe(
|
||||
const decodeOutput = Schema.decodeEffect(outputSchemaJson);
|
||||
return yield* decodeOutput(envelope.structured_output).pipe(
|
||||
Effect.catchTag("SchemaError", (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
|
||||
@@ -14,6 +14,7 @@ import { CodexSettings, ProviderInstanceId, TextGenerationError } from "@t3tools
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import { type TextGenerationShape } from "./TextGeneration.ts";
|
||||
import { makeCodexTextGeneration } from "./CodexTextGeneration.ts";
|
||||
const decodeCodexSettings = Schema.decodeSync(CodexSettings);
|
||||
|
||||
const DEFAULT_TEST_MODEL_SELECTION = createModelSelection(
|
||||
ProviderInstanceId.make("codex"),
|
||||
@@ -172,7 +173,7 @@ function withFakeCodexEnv<A, E, R>(
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
|
||||
const codexPath = yield* makeFakeCodexBinary(tempDir, input);
|
||||
const config = Schema.decodeSync(CodexSettings)({ binaryPath: codexPath });
|
||||
const config = decodeCodexSettings({ binaryPath: codexPath });
|
||||
const textGeneration = yield* makeCodexTextGeneration(config);
|
||||
return yield* effectFn(textGeneration);
|
||||
}).pipe(Effect.scoped);
|
||||
|
||||
@@ -40,6 +40,7 @@ import {
|
||||
|
||||
const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
|
||||
const CODEX_TIMEOUT_MS = 180_000;
|
||||
const encodeJsonString = Schema.encodeEffect(Schema.UnknownFromJsonString);
|
||||
/**
|
||||
* Build a Codex text-generation closure bound to a specific `CodexSettings`
|
||||
* payload. See `makeCodexAdapter` for the overall per-instance rationale.
|
||||
@@ -99,6 +100,25 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
||||
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
|
||||
fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
const encodeJsonForOperation = (
|
||||
operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle",
|
||||
value: unknown,
|
||||
): Effect.Effect<string, TextGenerationError> =>
|
||||
encodeJsonString(value).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Failed to encode structured output schema.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const materializeImageAttachments = Effect.fn("materializeImageAttachments")(function* (
|
||||
_operation:
|
||||
| "generateCommitMessage"
|
||||
@@ -156,11 +176,11 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
||||
cleanupPaths?: ReadonlyArray<string>;
|
||||
modelSelection: ModelSelection;
|
||||
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
|
||||
const schemaPath = yield* writeTempFile(
|
||||
const schemaJson = yield* encodeJsonForOperation(
|
||||
operation,
|
||||
"codex-schema",
|
||||
Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(toJsonSchemaObject(outputSchemaJson)),
|
||||
toJsonSchemaObject(outputSchemaJson),
|
||||
);
|
||||
const schemaPath = yield* writeTempFile(operation, "codex-schema", schemaJson);
|
||||
const outputPath = yield* writeTempFile(operation, "codex-output", "");
|
||||
|
||||
const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () {
|
||||
@@ -259,6 +279,8 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
||||
),
|
||||
);
|
||||
|
||||
const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));
|
||||
|
||||
return yield* fileSystem.readFileString(outputPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
@@ -268,7 +290,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))),
|
||||
Effect.flatMap(decodeOutput),
|
||||
Effect.catchTag("SchemaError", (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
|
||||
@@ -19,6 +19,7 @@ import { CursorSettings, ProviderInstanceId } from "@t3tools/contracts";
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import { type TextGenerationShape } from "./TextGeneration.ts";
|
||||
import { makeCursorTextGeneration } from "./CursorTextGeneration.ts";
|
||||
const decodeCursorSettings = Schema.decodeSync(CursorSettings);
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const mockAgentPath = path.join(__dirname, "../../scripts/acp-mock-agent.ts");
|
||||
@@ -65,7 +66,7 @@ function withFakeAcpAgent<A, E, R>(
|
||||
}),
|
||||
);
|
||||
const agentPath = makeAcpAgentWrapper(tempDir, env);
|
||||
const config = Schema.decodeSync(CursorSettings)({ binaryPath: agentPath });
|
||||
const config = decodeCursorSettings({ binaryPath: agentPath });
|
||||
const textGeneration = yield* makeCursorTextGeneration(config);
|
||||
return yield* effectFn(textGeneration);
|
||||
}).pipe(Effect.scoped);
|
||||
|
||||
@@ -6,6 +6,7 @@ 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";
|
||||
@@ -16,7 +17,6 @@ import {
|
||||
buildThreadTitlePrompt,
|
||||
} from "./TextGenerationPrompts.ts";
|
||||
import {
|
||||
extractJsonObject,
|
||||
sanitizeCommitSubject,
|
||||
sanitizePrTitle,
|
||||
sanitizeThreadTitle,
|
||||
@@ -154,9 +154,8 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
|
||||
});
|
||||
}
|
||||
|
||||
return yield* Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))(
|
||||
extractJsonObject(rawResult),
|
||||
).pipe(
|
||||
const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));
|
||||
return yield* decodeOutput(extractJsonObject(rawResult)).pipe(
|
||||
Effect.catchTag("SchemaError", (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
|
||||
@@ -13,6 +13,7 @@ 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";
|
||||
@@ -24,7 +25,6 @@ import {
|
||||
} from "./TextGenerationPrompts.ts";
|
||||
import { type TextGenerationShape } from "./TextGeneration.ts";
|
||||
import {
|
||||
extractJsonObject,
|
||||
sanitizeCommitSubject,
|
||||
sanitizePrTitle,
|
||||
sanitizeThreadTitle,
|
||||
@@ -352,9 +352,8 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
|
||||
releaseSharedServer,
|
||||
);
|
||||
|
||||
return yield* Schema.decodeEffect(Schema.fromJsonString(input.outputSchemaJson))(
|
||||
extractJsonObject(rawOutput),
|
||||
).pipe(
|
||||
const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(input.outputSchemaJson));
|
||||
return yield* decodeOutput(extractJsonObject(rawOutput)).pipe(
|
||||
Effect.catchTag("SchemaError", (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
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. */
|
||||
export function toJsonSchemaObject(schema: Schema.Top): unknown {
|
||||
@@ -18,54 +19,6 @@ 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() ?? "";
|
||||
@@ -127,7 +80,7 @@ export function normalizeCliError(
|
||||
error: unknown,
|
||||
fallback: string,
|
||||
): TextGenerationError {
|
||||
if (Schema.is(TextGenerationError)(error)) {
|
||||
if (isTextGenerationError(error)) {
|
||||
return error;
|
||||
}
|
||||
|
||||
|
||||
@@ -130,6 +130,65 @@ 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();
|
||||
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
parseRemoteRefWithRemoteNames,
|
||||
} from "../git/remoteRefs.ts";
|
||||
import { ServerConfig } from "../config.ts";
|
||||
const isGitCommandError = Schema.is(GitCommandError);
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
|
||||
@@ -40,6 +41,9 @@ 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>({
|
||||
@@ -71,6 +75,7 @@ interface ExecuteGitOptions {
|
||||
timeoutMs?: number | undefined;
|
||||
allowNonZeroExit?: boolean | undefined;
|
||||
fallbackErrorMessage?: string | undefined;
|
||||
env?: NodeJS.ProcessEnv | undefined;
|
||||
maxOutputBytes?: number | undefined;
|
||||
truncateOutputAtMaxBytes?: boolean | undefined;
|
||||
progress?: GitVcsDriver.ExecuteGitProgress | undefined;
|
||||
@@ -327,7 +332,7 @@ function toGitCommandError(
|
||||
detail: string,
|
||||
) {
|
||||
return (cause: unknown) =>
|
||||
Schema.is(GitCommandError)(cause)
|
||||
isGitCommandError(cause)
|
||||
? cause
|
||||
: new GitCommandError({
|
||||
operation: input.operation,
|
||||
@@ -737,6 +742,7 @@ 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 } : {}),
|
||||
@@ -869,6 +875,7 @@ 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);
|
||||
|
||||
@@ -41,8 +41,7 @@ describe("VcsProjectConfig", () => {
|
||||
yield* fileSystem.makeDirectory(nested, { recursive: true });
|
||||
yield* fileSystem.writeFileString(
|
||||
path.join(configDir, "vcs.json"),
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
JSON.stringify({ vcs: { kind: "jj" } }),
|
||||
'{"vcs":{"kind":"jj"}}',
|
||||
);
|
||||
|
||||
const config = yield* VcsProjectConfig.VcsProjectConfig;
|
||||
@@ -53,6 +52,47 @@ describe("VcsProjectConfig", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(TestLayer)("ignores malformed .t3code/vcs.json files", (it) => {
|
||||
it.effect("returns auto for invalid JSON", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-vcs-config-test-",
|
||||
});
|
||||
const configDir = path.join(root, ".t3code");
|
||||
yield* fileSystem.makeDirectory(configDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(path.join(configDir, "vcs.json"), "{not json");
|
||||
|
||||
const config = yield* VcsProjectConfig.VcsProjectConfig;
|
||||
const kind = yield* config.resolveKind({ cwd: root });
|
||||
|
||||
assert.equal(kind, "auto");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns auto for schema-invalid JSON", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-vcs-config-test-",
|
||||
});
|
||||
const configDir = path.join(root, ".t3code");
|
||||
yield* fileSystem.makeDirectory(configDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(
|
||||
path.join(configDir, "vcs.json"),
|
||||
'{"vcs":{"kind":"svn"}}',
|
||||
);
|
||||
|
||||
const config = yield* VcsProjectConfig.VcsProjectConfig;
|
||||
const kind = yield* config.resolveKind({ cwd: root });
|
||||
|
||||
assert.equal(kind, "auto");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(TestLayer)("falls back to auto when no config exists", (it) => {
|
||||
it.effect("returns auto", () =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -2,6 +2,7 @@ import * as Context from "effect/Context";
|
||||
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 * as Schema from "effect/Schema";
|
||||
|
||||
@@ -15,15 +16,10 @@ const ProjectVcsConfig = Schema.Struct({
|
||||
),
|
||||
vcsKind: Schema.optional(VcsDriverKind),
|
||||
});
|
||||
|
||||
interface ProjectVcsConfigFile {
|
||||
readonly vcs?:
|
||||
| {
|
||||
readonly kind?: VcsDriverKindType | undefined;
|
||||
}
|
||||
| undefined;
|
||||
readonly vcsKind?: VcsDriverKindType | undefined;
|
||||
}
|
||||
type ProjectVcsConfigFile = typeof ProjectVcsConfig.Type;
|
||||
const decodeProjectVcsConfigJson = Schema.decodeUnknownOption(
|
||||
Schema.fromJsonString(ProjectVcsConfig),
|
||||
);
|
||||
|
||||
export interface VcsProjectConfigResolveInput {
|
||||
readonly cwd: string;
|
||||
@@ -44,14 +40,8 @@ function configuredKind(config: ProjectVcsConfigFile): VcsDriverKindType | "auto
|
||||
return config.vcs?.kind ?? config.vcsKind ?? "auto";
|
||||
}
|
||||
|
||||
function parseConfig(raw: string): ProjectVcsConfigFile | null {
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
return Schema.is(ProjectVcsConfig)(parsed) ? parsed : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
const parseConfig = (raw: string): Option.Option<ProjectVcsConfigFile> =>
|
||||
decodeProjectVcsConfigJson(raw);
|
||||
|
||||
export const make = Effect.fn("makeVcsProjectConfig")(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
@@ -62,12 +52,12 @@ export const make = Effect.fn("makeVcsProjectConfig")(function* () {
|
||||
while (true) {
|
||||
const candidate = path.join(current, ".t3code", "vcs.json");
|
||||
if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {
|
||||
return candidate;
|
||||
return Option.some(candidate);
|
||||
}
|
||||
|
||||
const parent = path.dirname(current);
|
||||
if (parent === current) {
|
||||
return null;
|
||||
return Option.none();
|
||||
}
|
||||
current = parent;
|
||||
}
|
||||
@@ -77,26 +67,27 @@ export const make = Effect.fn("makeVcsProjectConfig")(function* () {
|
||||
configPath: string,
|
||||
) {
|
||||
const raw = yield* fileSystem.readFileString(configPath).pipe(
|
||||
Effect.map(Option.some),
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("failed to read VCS project config", {
|
||||
configPath,
|
||||
error,
|
||||
}).pipe(Effect.as(null)),
|
||||
}).pipe(Effect.as(Option.none())),
|
||||
),
|
||||
);
|
||||
if (raw === null) {
|
||||
if (Option.isNone(raw)) {
|
||||
return "auto" as const;
|
||||
}
|
||||
|
||||
const parsed = parseConfig(raw);
|
||||
if (parsed === null) {
|
||||
const parsed = parseConfig(raw.value);
|
||||
if (Option.isNone(parsed)) {
|
||||
yield* Effect.logWarning("invalid VCS project config", {
|
||||
configPath,
|
||||
});
|
||||
return "auto" as const;
|
||||
}
|
||||
|
||||
return configuredKind(parsed);
|
||||
return configuredKind(parsed.value);
|
||||
});
|
||||
|
||||
const resolveKind: VcsProjectConfigShape["resolveKind"] = Effect.fn(
|
||||
@@ -107,11 +98,10 @@ export const make = Effect.fn("makeVcsProjectConfig")(function* () {
|
||||
}
|
||||
|
||||
const configPath = yield* findConfigPath(input.cwd);
|
||||
if (configPath === null) {
|
||||
return "auto";
|
||||
}
|
||||
|
||||
return yield* readConfiguredKind(configPath);
|
||||
return yield* Option.match(configPath, {
|
||||
onNone: () => Effect.succeed("auto" as const),
|
||||
onSome: readConfiguredKind,
|
||||
});
|
||||
});
|
||||
|
||||
return VcsProjectConfig.of({
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
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";
|
||||
@@ -284,6 +285,31 @@ 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,
|
||||
|
||||
@@ -22,7 +22,7 @@ import { mergeGitStatusParts } from "@t3tools/shared/git";
|
||||
|
||||
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
|
||||
|
||||
const VCS_STATUS_REFRESH_INTERVAL = Duration.seconds(30);
|
||||
const DEFAULT_VCS_STATUS_REFRESH_INTERVAL = Duration.seconds(30);
|
||||
|
||||
interface VcsStatusChange {
|
||||
readonly cwd: string;
|
||||
@@ -44,6 +44,10 @@ interface ActiveRemotePoller {
|
||||
readonly subscriberCount: number;
|
||||
}
|
||||
|
||||
interface StreamStatusOptions {
|
||||
readonly automaticRemoteRefreshInterval?: Effect.Effect<Duration.Duration, never>;
|
||||
}
|
||||
|
||||
export interface VcsStatusBroadcasterShape {
|
||||
readonly getStatus: (
|
||||
input: VcsStatusInput,
|
||||
@@ -54,6 +58,7 @@ export interface VcsStatusBroadcasterShape {
|
||||
readonly refreshStatus: (cwd: string) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
|
||||
readonly streamStatus: (
|
||||
input: VcsStatusInput,
|
||||
options?: StreamStatusOptions,
|
||||
) => Stream.Stream<VcsStatusStreamEvent, GitManagerServiceError>;
|
||||
}
|
||||
|
||||
@@ -232,19 +237,32 @@ export const layer = Layer.effect(
|
||||
return mergeGitStatusParts(local, remote);
|
||||
});
|
||||
|
||||
const makeRemoteRefreshLoop = (cwd: string) => {
|
||||
const logRefreshFailure = (error: Error) =>
|
||||
const makeRemoteRefreshLoop = (
|
||||
cwd: string,
|
||||
automaticRemoteRefreshInterval: Effect.Effect<Duration.Duration, never>,
|
||||
) => {
|
||||
const logRefreshFailure = (error: GitManagerServiceError) =>
|
||||
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 refreshRemoteStatus(cwd).pipe(
|
||||
return refreshRemoteStatusIfEnabled.pipe(
|
||||
Effect.catch(logRefreshFailure),
|
||||
Effect.andThen(
|
||||
Effect.forever(
|
||||
Effect.sleep(VCS_STATUS_REFRESH_INTERVAL).pipe(
|
||||
Effect.andThen(refreshRemoteStatus(cwd).pipe(Effect.catch(logRefreshFailure))),
|
||||
sleepForConfiguredInterval.pipe(
|
||||
Effect.andThen(refreshRemoteStatusIfEnabled.pipe(Effect.catch(logRefreshFailure))),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -253,6 +271,7 @@ 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);
|
||||
@@ -265,7 +284,7 @@ export const layer = Layer.effect(
|
||||
return Effect.succeed([undefined, nextPollers] as const);
|
||||
}
|
||||
|
||||
return makeRemoteRefreshLoop(cwd).pipe(
|
||||
return makeRemoteRefreshLoop(cwd, automaticRemoteRefreshInterval).pipe(
|
||||
Effect.forkIn(broadcasterScope),
|
||||
Effect.map((fiber) => {
|
||||
const nextPollers = new Map(activePollers);
|
||||
@@ -307,14 +326,18 @@ export const layer = Layer.effect(
|
||||
}
|
||||
});
|
||||
|
||||
const streamStatus: VcsStatusBroadcasterShape["streamStatus"] = (input) =>
|
||||
const streamStatus: VcsStatusBroadcasterShape["streamStatus"] = (input, options) =>
|
||||
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);
|
||||
yield* retainRemotePoller(
|
||||
cwd,
|
||||
options?.automaticRemoteRefreshInterval ??
|
||||
Effect.succeed(DEFAULT_VCS_STATUS_REFRESH_INTERVAL),
|
||||
);
|
||||
|
||||
const release = releaseRemotePoller(cwd).pipe(Effect.ignore, Effect.asVoid);
|
||||
|
||||
|
||||
+47
-5
@@ -9,6 +9,7 @@ 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,
|
||||
@@ -86,6 +87,8 @@ import {
|
||||
type SessionCredentialChange,
|
||||
} from "./auth/Services/SessionCredentialService.ts";
|
||||
import { respondToAuthError } from "./auth/http.ts";
|
||||
const isOrchestrationDispatchCommandError = Schema.is(OrchestrationDispatchCommandError);
|
||||
const isWorkspacePathOutsideRootError = Schema.is(WorkspacePathOutsideRootError);
|
||||
|
||||
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
|
||||
|
||||
@@ -178,6 +181,14 @@ 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;
|
||||
@@ -216,7 +227,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
});
|
||||
|
||||
const toDispatchCommandError = (cause: unknown, fallbackMessage: string) =>
|
||||
Schema.is(OrchestrationDispatchCommandError)(cause)
|
||||
isOrchestrationDispatchCommandError(cause)
|
||||
? cause
|
||||
: new OrchestrationDispatchCommandError({
|
||||
message: cause instanceof Error ? cause.message : fallbackMessage,
|
||||
@@ -225,7 +236,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
|
||||
const toBootstrapDispatchCommandCauseError = (cause: Cause.Cause<unknown>) => {
|
||||
const error = Cause.squash(cause);
|
||||
return Schema.is(OrchestrationDispatchCommandError)(error)
|
||||
return isOrchestrationDispatchCommandError(error)
|
||||
? error
|
||||
: new OrchestrationDispatchCommandError({
|
||||
message:
|
||||
@@ -306,6 +317,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
}),
|
||||
);
|
||||
case "thread.deleted":
|
||||
case "thread.archived":
|
||||
return Effect.succeed(
|
||||
Option.some({
|
||||
kind: "thread-removed" as const,
|
||||
@@ -313,6 +325,17 @@ 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());
|
||||
@@ -637,7 +660,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
return result;
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
Schema.is(OrchestrationDispatchCommandError)(cause)
|
||||
isOrchestrationDispatchCommandError(cause)
|
||||
? cause
|
||||
: new OrchestrationDispatchCommandError({
|
||||
message: "Failed to dispatch orchestration command",
|
||||
@@ -732,6 +755,23 @@ 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,
|
||||
@@ -918,7 +958,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
WS_METHODS.projectsWriteFile,
|
||||
workspaceFileSystem.writeFile(input).pipe(
|
||||
Effect.mapError((cause) => {
|
||||
const message = Schema.is(WorkspacePathOutsideRootError)(cause)
|
||||
const message = isWorkspacePathOutsideRootError(cause)
|
||||
? "Workspace file path must stay within the project root."
|
||||
: "Failed to write workspace file";
|
||||
return new ProjectWriteFileError({
|
||||
@@ -950,7 +990,9 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
[WS_METHODS.subscribeVcsStatus]: (input) =>
|
||||
observeRpcStream(
|
||||
WS_METHODS.subscribeVcsStatus,
|
||||
vcsStatusBroadcaster.streamStatus(input),
|
||||
vcsStatusBroadcaster.streamStatus(input, {
|
||||
automaticRemoteRefreshInterval: automaticGitFetchInterval,
|
||||
}),
|
||||
{
|
||||
"rpc.aggregate": "vcs",
|
||||
},
|
||||
|
||||
@@ -50,6 +50,7 @@
|
||||
"@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",
|
||||
|
||||
@@ -34,4 +34,22 @@ 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");
|
||||
});
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -9,6 +9,7 @@ function readInjectedDesktopAppBranding(): DesktopAppBranding | null {
|
||||
}
|
||||
|
||||
const injectedDesktopAppBranding = readInjectedDesktopAppBranding();
|
||||
const hostedAppChannel = import.meta.env.VITE_HOSTED_APP_CHANNEL?.trim().toLowerCase();
|
||||
|
||||
export const APP_BASE_NAME = injectedDesktopAppBranding?.baseName ?? "T3 Code";
|
||||
export const APP_STAGE_LABEL =
|
||||
@@ -16,3 +17,7 @@ export const APP_STAGE_LABEL =
|
||||
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";
|
||||
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;
|
||||
@@ -18,11 +18,13 @@ 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";
|
||||
@@ -106,6 +108,7 @@ 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;
|
||||
@@ -218,6 +221,9 @@ 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"],
|
||||
@@ -952,7 +958,7 @@ function resolveWsRpc(body: NormalizedWsRpcRequestBody): unknown {
|
||||
}
|
||||
const tag = body._tag;
|
||||
if (tag === WS_METHODS.serverGetConfig) {
|
||||
return fixture.serverConfig;
|
||||
return encodeServerConfig(fixture.serverConfig);
|
||||
}
|
||||
if (tag === WS_METHODS.serverDiscoverSourceControl) {
|
||||
return {
|
||||
@@ -1659,7 +1665,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
{
|
||||
version: 1,
|
||||
type: "snapshot",
|
||||
config: fixture.serverConfig,
|
||||
config: encodeServerConfig(fixture.serverConfig),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
@@ -11,12 +11,15 @@ 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";
|
||||
|
||||
@@ -50,6 +53,8 @@ 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)?:\/\/.*/);
|
||||
|
||||
@@ -254,7 +259,7 @@ function buildFixture(): TestFixture {
|
||||
|
||||
function resolveWsRpc(tag: string): unknown {
|
||||
if (tag === WS_METHODS.serverGetConfig) {
|
||||
return fixture.serverConfig;
|
||||
return encodeServerConfig(fixture.serverConfig);
|
||||
}
|
||||
if (tag === WS_METHODS.vcsListRefs) {
|
||||
return {
|
||||
@@ -394,7 +399,7 @@ async function waitForServerConfigStreamReady(): Promise<void> {
|
||||
rpcHarness.emitStreamValue(WS_METHODS.subscribeServerConfig, {
|
||||
version: 1,
|
||||
type: "settingsUpdated",
|
||||
payload: { settings: fixture.serverConfig.settings },
|
||||
payload: { settings: encodeServerSettings(fixture.serverConfig.settings) },
|
||||
});
|
||||
|
||||
try {
|
||||
@@ -485,7 +490,7 @@ describe("Keybindings update toast", () => {
|
||||
{
|
||||
version: 1,
|
||||
type: "snapshot",
|
||||
config: fixture.serverConfig,
|
||||
config: encodeServerConfig(fixture.serverConfig),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
@@ -48,6 +48,8 @@ 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,
|
||||
@@ -73,6 +75,27 @@ 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();
|
||||
@@ -157,4 +180,87 @@ 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,6 +73,7 @@ beforeAll(() => {
|
||||
});
|
||||
|
||||
const ACTIVE_THREAD_ENVIRONMENT_ID = EnvironmentId.make("environment-local");
|
||||
const MESSAGE_CREATED_AT = "2026-03-17T19:12:28.000Z";
|
||||
|
||||
function buildProps() {
|
||||
return {
|
||||
@@ -99,33 +100,73 @@ 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={[
|
||||
{
|
||||
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,
|
||||
},
|
||||
},
|
||||
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"),
|
||||
),
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
@@ -133,8 +174,23 @@ describe("MessagesTimeline", () => {
|
||||
expect(markup).toContain("Terminal 1 lines 1-5");
|
||||
expect(markup).toContain("lucide-terminal");
|
||||
expect(markup).toContain("yoo what'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(
|
||||
|
||||
@@ -365,24 +365,24 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{(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>
|
||||
<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>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -755,6 +755,88 @@ 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,14 +2662,26 @@ export function ConnectionsSettings() {
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogTrigger
|
||||
render={
|
||||
<Button size="xs" variant="outline">
|
||||
<PlusIcon className="size-3" />
|
||||
Add environment
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<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>
|
||||
<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">
|
||||
<p className="flex min-w-0 flex-wrap items-center gap-x-1 text-xs text-muted-foreground/80">
|
||||
{hasAuthenticatedEmail ? (
|
||||
<>
|
||||
<span>Authenticated as</span>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo, type ReactNode } from "react";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type {
|
||||
ProviderSettingsFormAnnotation,
|
||||
@@ -63,12 +64,9 @@ function readProviderSettingsFormSchemaAnnotation(
|
||||
function readFieldBooleanDefault(
|
||||
fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
|
||||
): boolean | undefined {
|
||||
try {
|
||||
const decoded = Schema.decodeUnknownSync(fieldSchema as Schema.Decoder<unknown>)(undefined);
|
||||
return typeof decoded === "boolean" ? decoded : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
const decodeDefault = Schema.decodeUnknownOption(fieldSchema as Schema.Decoder<unknown>);
|
||||
const decoded = decodeDefault(undefined);
|
||||
return Option.isSome(decoded) && typeof decoded.value === "boolean" ? decoded.value : undefined;
|
||||
}
|
||||
|
||||
export function deriveProviderSettingsFields(
|
||||
|
||||
@@ -1256,10 +1256,47 @@ describe("SourceControlSettingsPanel discovery states", () => {
|
||||
</AppAtomRegistryProvider>,
|
||||
);
|
||||
|
||||
await expect.element(page.getByRole("heading", { name: "Git" })).toBeInTheDocument();
|
||||
await expect.element(page.getByRole("switch", { name: "Git availability" })).toBeDisabled();
|
||||
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 () => {
|
||||
@@ -1287,7 +1324,7 @@ describe("SourceControlSettingsPanel discovery states", () => {
|
||||
</AppAtomRegistryProvider>,
|
||||
);
|
||||
|
||||
await expect.element(page.getByRole("heading", { name: "Git" })).toBeInTheDocument();
|
||||
await expect.element(page.getByRole("switch", { name: "Git availability" })).toBeDisabled();
|
||||
expect(calls).toBe(1);
|
||||
|
||||
const teardown = mounted.cleanup ?? mounted.unmount;
|
||||
@@ -1301,7 +1338,7 @@ describe("SourceControlSettingsPanel discovery states", () => {
|
||||
</AppAtomRegistryProvider>,
|
||||
);
|
||||
|
||||
await expect.element(page.getByRole("heading", { name: "Git" })).toBeInTheDocument();
|
||||
await expect.element(page.getByRole("switch", { name: "Git availability" })).toBeDisabled();
|
||||
expect(calls).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -14,8 +14,9 @@ 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 } from "../../branding";
|
||||
import { APP_VERSION, HOSTED_APP_CHANNEL, HOSTED_APP_CHANNEL_LABEL } from "../../branding";
|
||||
import {
|
||||
canCheckForUpdate,
|
||||
getDesktopUpdateButtonTooltip,
|
||||
@@ -26,6 +27,7 @@ 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";
|
||||
@@ -43,14 +45,10 @@ import {
|
||||
} from "../../providerInstances";
|
||||
import { ensureLocalApi, readLocalApi } from "../../localApi";
|
||||
import { useShallow } from "zustand/react/shallow";
|
||||
import {
|
||||
selectProjectsAcrossEnvironments,
|
||||
selectThreadShellsAcrossEnvironments,
|
||||
useStore,
|
||||
} from "../../store";
|
||||
import { selectProjectsAcrossEnvironments, useStore } from "../../store";
|
||||
import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState";
|
||||
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";
|
||||
@@ -162,6 +160,7 @@ 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) => {
|
||||
@@ -314,36 +313,66 @@ function AboutVersionSection() {
|
||||
</Tooltip>
|
||||
}
|
||||
/>
|
||||
<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}
|
||||
{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);
|
||||
}}
|
||||
>
|
||||
<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>
|
||||
}
|
||||
/>
|
||||
<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}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -379,6 +408,10 @@ 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"]
|
||||
: []),
|
||||
@@ -402,6 +435,7 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
settings.defaultThreadEnvMode,
|
||||
settings.diffIgnoreWhitespace,
|
||||
settings.diffWordWrap,
|
||||
settings.automaticGitFetchInterval,
|
||||
settings.enableAssistantStreaming,
|
||||
settings.sidebarThreadPreviewCount,
|
||||
settings.timestampFormat,
|
||||
@@ -427,6 +461,7 @@ 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,
|
||||
@@ -1298,14 +1333,50 @@ 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(() => {
|
||||
return projects
|
||||
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()]
|
||||
.map((project) => ({
|
||||
project,
|
||||
threads: threads
|
||||
.filter((thread) => thread.projectId === project.id && thread.archivedAt !== null)
|
||||
.filter(
|
||||
(thread) =>
|
||||
thread.projectId === project.id && thread.environmentId === project.environmentId,
|
||||
)
|
||||
.toSorted((left, right) => {
|
||||
const leftKey = left.archivedAt ?? left.createdAt;
|
||||
const rightKey = right.archivedAt ?? right.createdAt;
|
||||
@@ -1313,7 +1384,7 @@ export function ArchivedThreadsPanel() {
|
||||
}),
|
||||
}))
|
||||
.filter((group) => group.threads.length > 0);
|
||||
}, [projects, threads]);
|
||||
}, [archivedSnapshots]);
|
||||
|
||||
const handleArchivedThreadContextMenu = useCallback(
|
||||
async (threadRef: ScopedThreadRef, position: { x: number; y: number }) => {
|
||||
@@ -1330,6 +1401,7 @@ export function ArchivedThreadsPanel() {
|
||||
if (clicked === "unarchive") {
|
||||
try {
|
||||
await unarchiveThread(threadRef);
|
||||
refreshArchivedThreads();
|
||||
} catch (error) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
@@ -1344,24 +1416,37 @@ export function ArchivedThreadsPanel() {
|
||||
|
||||
if (clicked === "delete") {
|
||||
await confirmAndDeleteThread(threadRef);
|
||||
refreshArchivedThreads();
|
||||
}
|
||||
},
|
||||
[confirmAndDeleteThread, unarchiveThread],
|
||||
[confirmAndDeleteThread, refreshArchivedThreads, unarchiveThread],
|
||||
);
|
||||
|
||||
return (
|
||||
<SettingsPageContainer>
|
||||
{archivedGroups.length === 0 ? (
|
||||
<SettingsSection title="Archived threads">
|
||||
<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>
|
||||
<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.")
|
||||
}
|
||||
/>
|
||||
</SettingsSection>
|
||||
) : (
|
||||
archivedGroups.map(({ project, threads: projectThreads }) => (
|
||||
@@ -1371,9 +1456,8 @@ export function ArchivedThreadsPanel() {
|
||||
icon={<ProjectFavicon environmentId={project.environmentId} cwd={project.cwd} />}
|
||||
>
|
||||
{projectThreads.map((thread) => (
|
||||
<div
|
||||
<SettingsRow
|
||||
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(
|
||||
@@ -1384,39 +1468,40 @@ export function ArchivedThreadsPanel() {
|
||||
},
|
||||
);
|
||||
}}
|
||||
>
|
||||
<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">
|
||||
title={thread.title}
|
||||
description={
|
||||
<>
|
||||
Archived {formatRelativeTimeLabel(thread.archivedAt ?? thread.createdAt)}
|
||||
{" \u00b7 Created "}
|
||||
{formatRelativeTimeLabel(thread.createdAt)}
|
||||
</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>
|
||||
</>
|
||||
}
|
||||
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>
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</SettingsSection>
|
||||
))
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { GitPullRequestIcon, RefreshCwIcon } from "lucide-react";
|
||||
import { ChevronDownIcon, GitPullRequestIcon, RefreshCwIcon } from "lucide-react";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Option from "effect/Option";
|
||||
import { type ReactNode } from "react";
|
||||
import { useState, type ReactNode } from "react";
|
||||
import type {
|
||||
SourceControlProviderKind,
|
||||
SourceControlDiscoveryResult,
|
||||
@@ -9,7 +10,9 @@ 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,
|
||||
@@ -17,6 +20,7 @@ import {
|
||||
} from "../../lib/sourceControlDiscoveryState";
|
||||
import { Badge } from "../ui/badge";
|
||||
import { Button } from "../ui/button";
|
||||
import { Collapsible, CollapsibleContent } from "../ui/collapsible";
|
||||
import {
|
||||
Empty,
|
||||
EmptyContent,
|
||||
@@ -26,6 +30,13 @@ 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 {
|
||||
@@ -38,7 +49,7 @@ import {
|
||||
type Icon,
|
||||
} from "../Icons";
|
||||
import { RedactedSensitiveText } from "./RedactedSensitiveText";
|
||||
import { SettingsPageContainer, SettingsSection } from "./settingsLayout";
|
||||
import { SettingResetButton, SettingsPageContainer, SettingsSection } from "./settingsLayout";
|
||||
|
||||
const EMPTY_DISCOVERY_RESULT: SourceControlDiscoveryResult = {
|
||||
versionControlSystems: [],
|
||||
@@ -58,6 +69,18 @@ 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);
|
||||
@@ -146,7 +169,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) {
|
||||
@@ -189,8 +212,10 @@ function itemSummary({
|
||||
|
||||
function DiscoveryItemRow({
|
||||
item,
|
||||
children,
|
||||
}: {
|
||||
readonly item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem;
|
||||
readonly children?: ReactNode;
|
||||
}) {
|
||||
const version = optionLabel(item.version);
|
||||
const enabled =
|
||||
@@ -198,6 +223,8 @@ 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
|
||||
@@ -211,9 +238,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} />
|
||||
<h3 className="truncate text-[13px] font-semibold tracking-[-0.01em] text-foreground">
|
||||
<span className="truncate text-[13px] font-semibold tracking-[-0.01em] text-foreground">
|
||||
{item.label}
|
||||
</h3>
|
||||
</span>
|
||||
{version ? <code className="text-xs text-muted-foreground">{version}</code> : null}
|
||||
{isVcsNotReady(item) ? (
|
||||
<Badge variant="warning" size="sm">
|
||||
@@ -226,17 +253,105 @@ function DiscoveryItemRow({
|
||||
</Badge>
|
||||
) : null}
|
||||
</div>
|
||||
<p className="flex min-w-0 flex-wrap items-center gap-x-1 text-xs text-muted-foreground">
|
||||
<p className="flex min-w-0 flex-wrap items-center gap-x-1 text-xs text-muted-foreground/80">
|
||||
{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>
|
||||
);
|
||||
}
|
||||
@@ -324,7 +439,6 @@ 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;
|
||||
@@ -364,7 +478,9 @@ export function SourceControlSettingsPanel() {
|
||||
{result.versionControlSystems.length > 0 ? (
|
||||
<SettingsSection title="Version Control" headerAction={scanButton}>
|
||||
{result.versionControlSystems.map((item) => (
|
||||
<DiscoveryItemRow key={`vcs:${item.kind}`} item={item} />
|
||||
<DiscoveryItemRow key={`vcs:${item.kind}`} item={item}>
|
||||
{item.kind === "git" ? <GitFetchIntervalSettings /> : undefined}
|
||||
</DiscoveryItemRow>
|
||||
))}
|
||||
</SettingsSection>
|
||||
) : null}
|
||||
|
||||
@@ -52,7 +52,9 @@ export function SettingsRow({
|
||||
resetAction,
|
||||
control,
|
||||
children,
|
||||
}: {
|
||||
className,
|
||||
...rowProps
|
||||
}: Omit<ComponentPropsWithoutRef<"div">, "title"> & {
|
||||
title: ReactNode;
|
||||
description: ReactNode;
|
||||
status?: ReactNode;
|
||||
@@ -62,9 +64,11 @@ 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">
|
||||
|
||||
Loaded 100 of 161 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user