Compare commits

..
Author SHA1 Message Date
Cursor Agent b3ce952ec9 fix: use Effect.ignore instead of Effect.asVoid in killDirectChild to prevent SIGKILL phase short-circuit
Effect.asVoid only discards the success value but does not suppress errors.
When child.kill fails (e.g., child already exited), the error propagates
through Effect.all, causing the SIGTERM phase to fail and short-circuiting
the SIGKILL escalation phase. This leaves orphaned serve processes alive.

Effect.ignore both discards the value and suppresses errors, making
killDirectChild infallible and allowing the full kill chain to complete.
Also fix the same issue in the Windows path of killOpenCodeProcessGroup.
2026-05-12 13:47:44 +00:00
Julius Marminge b538723e98 Harden OpenCode probe teardown and cleanup
- keep successful provider refreshes when probe scope teardown fails
- terminate stray matching `opencode serve` processes alongside the child
2026-05-12 06:33:08 -07:00
307 changed files with 6432 additions and 10774 deletions

No files matched your search

-8
View File
@@ -46,14 +46,6 @@ jobs:
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Ensure Electron runtime is installed
run: |
if ! node -e "require('./apps/desktop/node_modules/electron')" >/dev/null 2>&1; then
rm -rf apps/desktop/node_modules/electron/dist apps/desktop/node_modules/electron/path.txt
bun apps/desktop/node_modules/electron/install.js
fi
node -e "require('./apps/desktop/node_modules/electron')"
- name: Format
run: bun run fmt:check
-3
View File
@@ -124,9 +124,6 @@ jobs:
group: pr-size-${{ github.event.pull_request.number }}
cancel-in-progress: true
steps:
# This pull_request_target job may fetch untrusted PR commits only as passive
# git data. Do not add dependency installs, build/test scripts, or cache
# actions here; use pull_request plus workflow_run for that pattern instead.
- name: Checkout base repository
uses: actions/checkout@v4
with:
+2 -15
View File
@@ -23,8 +23,8 @@ on:
type: string
permissions:
contents: read
id-token: none
contents: write
id-token: write
jobs:
check_changes:
@@ -420,9 +420,6 @@ jobs:
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' }}
runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
permissions:
contents: read
id-token: write
steps:
- name: Checkout
uses: actions/checkout@v6
@@ -628,9 +625,6 @@ jobs:
router_url="${T3CODE_WEB_ROUTER_URL:-https://app.t3.codes}"
latest_domain="${T3CODE_WEB_LATEST_DOMAIN:-latest.app.t3.codes}"
nightly_domain="${T3CODE_WEB_NIGHTLY_DOMAIN:-nightly.app.t3.codes}"
router_domain="${router_url#http://}"
router_domain="${router_domain#https://}"
router_domain="${router_domain%%/*}"
if [[ "${{ needs.preflight.outputs.release_channel }}" == "stable" ]]; then
channel_domain="$latest_domain"
@@ -661,13 +655,6 @@ jobs:
--token "$VERCEL_TOKEN" \
"${vercel_scope_args[@]}"
if [[ "$channel_name" == "latest" && -n "$router_domain" && "$router_domain" != "$channel_domain" ]]; then
echo "Aliasing $deployment_url to router domain $router_domain."
bunx [email protected] alias set "$deployment_url" "$router_domain" \
--token "$VERCEL_TOKEN" \
"${vercel_scope_args[@]}"
fi
finalize:
name: Finalize release
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' && needs.preflight.outputs.release_channel == 'stable' }}
-1
View File
@@ -23,6 +23,5 @@ __screenshots__/
.tanstack
squashfs-root/
.vercel
.gstack/
dist-electron/
.electron-runtime/
+10 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.24",
"version": "0.0.22",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
@@ -10,24 +10,28 @@
"dev:electron": "node scripts/dev-electron.mjs",
"build": "tsdown",
"start": "node scripts/start-electron.mjs",
"typecheck": "tsgo --noEmit",
"typecheck": "tsc --noEmit",
"test": "vitest run --passWithNoTests",
"smoke-test": "node scripts/smoke-test.mjs"
},
"dependencies": {
"@effect/platform-node": "catalog:",
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"@t3tools/ssh": "workspace:*",
"@t3tools/tailscale": "workspace:*",
"effect": "catalog:",
"electron": "41.5.0",
"electron-updater": "^6.6.2"
},
"devDependencies": {
"@effect/language-service": "catalog:",
"@effect/vitest": "catalog:",
"@t3tools/client-runtime": "workspace:*",
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"@t3tools/ssh": "workspace:*",
"@t3tools/tailscale": "workspace:*",
"@types/node": "catalog:",
"effect-acp": "workspace:*",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
},
"productName": "T3 Code (Alpha)"
+2 -3
View File
@@ -1,8 +1,8 @@
import * as Cause from "effect/Cause";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Random from "effect/Random";
import * as Ref from "effect/Ref";
import * as NetService from "@t3tools/shared/Net";
@@ -26,8 +26,7 @@ const DEFAULT_DESKTOP_BACKEND_PORT = 3773;
const MAX_TCP_PORT = 65_535;
const DESKTOP_BACKEND_PORT_PROBE_HOSTS = ["127.0.0.1", "0.0.0.0", "::"] as const;
const makeDesktopRunId = Crypto.Crypto.pipe(
Effect.flatMap((crypto) => crypto.randomUUIDv4),
const makeDesktopRunId = Random.nextUUIDv4.pipe(
Effect.map((value) => value.replaceAll("-", "").slice(0, 12)),
);
+1 -1
View File
@@ -26,7 +26,7 @@ export interface DesktopAppIdentityShape {
export class DesktopAppIdentity extends Context.Service<
DesktopAppIdentity,
DesktopAppIdentityShape
>()("@t3tools/desktop/app/DesktopAppIdentity") {}
>()("t3/desktop/AppIdentity") {}
const normalizeCommitHash = (value: string): Option.Option<string> => {
const trimmed = value.trim();
+1 -1
View File
@@ -18,7 +18,7 @@ export interface DesktopAssetsShape {
}
export class DesktopAssets extends Context.Service<DesktopAssets, DesktopAssetsShape>()(
"@t3tools/desktop/app/DesktopAssets",
"t3/desktop/Assets",
) {}
const resolveResourcePath = Effect.fn("desktop.assets.resolveResourcePath")(function* (
@@ -32,7 +32,9 @@ const makeEnvironment = (
overrides: Partial<DesktopEnvironment.MakeDesktopEnvironmentInput> = {},
env: Record<string, string | undefined> = {},
) =>
DesktopEnvironment.DesktopEnvironment.pipe(Effect.provide(makeEnvironmentLayer(overrides, env)));
Effect.gen(function* () {
return yield* DesktopEnvironment.DesktopEnvironment;
}).pipe(Effect.provide(makeEnvironmentLayer(overrides, env)));
describe("DesktopEnvironment", () => {
it.effect("derives state paths and development identity inside Effect", () =>
+1 -1
View File
@@ -78,7 +78,7 @@ export interface DesktopEnvironmentShape {
export class DesktopEnvironment extends Context.Service<
DesktopEnvironment,
DesktopEnvironmentShape
>()("@t3tools/desktop/app/DesktopEnvironment") {}
>()("t3/desktop/Environment") {}
const APP_BASE_NAME = "T3 Code";
+2 -5
View File
@@ -24,7 +24,7 @@ export interface DesktopShutdownShape {
}
export class DesktopShutdown extends Context.Service<DesktopShutdown, DesktopShutdownShape>()(
"@t3tools/desktop/app/DesktopLifecycle/DesktopShutdown",
"t3/desktop/Shutdown",
) {}
const makeShutdown = Effect.gen(function* () {
@@ -61,11 +61,8 @@ export interface DesktopLifecycleShape {
readonly register: Effect.Effect<void, never, Scope.Scope | DesktopLifecycleRuntimeServices>;
}
/**
* @effect-expect-leaking DesktopEnvironment | DesktopShutdown | DesktopState | DesktopWindow | ElectronApp | ElectronTheme
*/
export class DesktopLifecycle extends Context.Service<DesktopLifecycle, DesktopLifecycleShape>()(
"@t3tools/desktop/app/DesktopLifecycle",
"t3/desktop/Lifecycle",
) {}
const { logInfo: logLifecycleInfo, logError: logLifecycleError } =
+1 -1
View File
@@ -43,7 +43,7 @@ export interface DesktopBackendOutputLogShape {
export class DesktopBackendOutputLog extends Context.Service<
DesktopBackendOutputLog,
DesktopBackendOutputLogShape
>()("@t3tools/desktop/app/DesktopObservability/DesktopBackendOutputLog") {}
>()("t3/desktop/BackendOutputLog") {}
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
+1 -1
View File
@@ -9,7 +9,7 @@ export interface DesktopStateShape {
}
export class DesktopState extends Context.Service<DesktopState, DesktopStateShape>()(
"@t3tools/desktop/app/DesktopState",
"t3/desktop/State",
) {}
export const layer = Layer.effect(
@@ -1,12 +1,10 @@
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Random from "effect/Random";
import * as Ref from "effect/Ref";
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
@@ -15,16 +13,13 @@ import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
export interface DesktopBackendConfigurationShape {
readonly resolve: Effect.Effect<
DesktopBackendManager.DesktopBackendStartConfig,
PlatformError.PlatformError
>;
readonly resolve: Effect.Effect<DesktopBackendManager.DesktopBackendStartConfig>;
}
export class DesktopBackendConfiguration extends Context.Service<
DesktopBackendConfiguration,
DesktopBackendConfigurationShape
>()("@t3tools/desktop/backend/DesktopBackendConfiguration") {}
>()("t3/desktop/BackendConfiguration") {}
interface BackendObservabilitySettings {
readonly otlpTracesUrl: Option.Option<string>;
@@ -85,6 +80,23 @@ const readPersistedBackendObservabilitySettings: Effect.Effect<
};
});
const getOrCreateBootstrapToken = Effect.fn("desktop.backendConfiguration.bootstrapToken")(
function* (tokenRef: Ref.Ref<Option.Option<string>>) {
const existing = yield* Ref.get(tokenRef);
if (Option.isSome(existing)) {
return existing.value;
}
let token = "";
while (token.length < 48) {
token += (yield* Random.nextUUIDv4).replace(/-/g, "");
}
token = token.slice(0, 48);
yield* Ref.set(tokenRef, Option.some(token));
return token;
},
);
const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolveStartConfig")(
function* (input: {
readonly bootstrapToken: string;
@@ -136,22 +148,11 @@ export const layer = Layer.effect(
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
const crypto = yield* Crypto.Crypto;
const tokenRef = yield* Ref.make(Option.none<string>());
const getOrCreateBootstrapToken = Effect.gen(function* () {
const existing = yield* Ref.get(tokenRef);
if (Option.isSome(existing)) {
return existing.value;
}
const token = Encoding.encodeHex(yield* crypto.randomBytes(24));
yield* Ref.set(tokenRef, Option.some(token));
return token;
});
return DesktopBackendConfiguration.of({
resolve: Effect.gen(function* () {
const bootstrapToken = yield* getOrCreateBootstrapToken;
const bootstrapToken = yield* getOrCreateBootstrapToken(tokenRef);
const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
@@ -116,7 +116,7 @@ export interface DesktopBackendManagerShape {
export class DesktopBackendManager extends Context.Service<
DesktopBackendManager,
DesktopBackendManagerShape
>()("@t3tools/desktop/backend/DesktopBackendManager") {}
>()("t3/desktop/BackendManager") {}
const { logWarning: logBackendManagerWarning, logError: logBackendManagerError } =
DesktopObservability.makeComponentLogger("desktop-backend-manager");
@@ -329,19 +329,9 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
}
yield* Ref.set(desktopState.backendReady, false);
const config = yield* configuration.resolve.pipe(
Effect.tapError((error) =>
logBackendManagerError("failed to generate desktop backend configuration", {
cause: error.message,
}),
),
Effect.option,
);
if (Option.isNone(config)) {
return;
}
const config = yield* configuration.resolve;
const entryExists = yield* fileSystem
.exists(config.value.entryPath)
.exists(config.entryPath)
.pipe(Effect.orElseSucceed(() => false));
yield* cancelRestart;
@@ -349,11 +339,11 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
...latest,
desiredRunning: true,
ready: false,
config: Option.some(config.value),
config: Option.some(config),
}));
if (!entryExists) {
yield* scheduleRestart(`missing server entry at ${config.value.entryPath}`);
yield* scheduleRestart(`missing server entry at ${config.entryPath}`);
return;
}
@@ -435,7 +425,7 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
});
const program = runBackendProcess({
...config.value,
...config,
onStarted: Effect.fn("desktop.backendManager.onStarted")(function* (pid) {
yield* updateActiveRun(runId, (run) => ({
...run,
@@ -443,7 +433,7 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
}));
yield* backendOutputLog.writeSessionBoundary({
phase: "START",
details: `pid=${pid} port=${config.value.bootstrap.port} cwd=${config.value.cwd}`,
details: `pid=${pid} port=${config.bootstrap.port} cwd=${config.cwd}`,
});
}),
onReady: Effect.fn("desktop.backendManager.onReady")(function* () {
@@ -3,7 +3,7 @@ import * as NodeOS from "node:os";
import {
createAdvertisedEndpoint,
type CreateAdvertisedEndpointInput,
} from "@t3tools/shared/advertisedEndpoint";
} from "@t3tools/client-runtime";
import type {
AdvertisedEndpoint,
AdvertisedEndpointProvider,
@@ -275,7 +275,7 @@ export interface DesktopServerExposureShape {
export class DesktopServerExposure extends Context.Service<
DesktopServerExposure,
DesktopServerExposureShape
>()("@t3tools/desktop/backend/DesktopServerExposure") {}
>()("t3/desktop/ServerExposure") {}
export interface DesktopNetworkInterfacesServiceShape {
readonly read: Effect.Effect<DesktopNetworkInterfaces>;
@@ -284,7 +284,7 @@ export interface DesktopNetworkInterfacesServiceShape {
export class DesktopNetworkInterfacesService extends Context.Service<
DesktopNetworkInterfacesService,
DesktopNetworkInterfacesServiceShape
>()("@t3tools/desktop/backend/DesktopServerExposure/DesktopNetworkInterfacesService") {}
>()("t3/desktop/ServerExposure/NetworkInterfaces") {}
interface RuntimeState {
readonly requestedMode: DesktopServerExposureMode;
@@ -1,4 +1,4 @@
import { createAdvertisedEndpoint } from "@t3tools/shared/advertisedEndpoint";
import { createAdvertisedEndpoint } from "@t3tools/client-runtime";
import type { AdvertisedEndpoint, AdvertisedEndpointProvider } from "@t3tools/contracts";
import {
buildTailscaleHttpsBaseUrl,
+1 -1
View File
@@ -39,7 +39,7 @@ export interface ElectronAppShape {
}
export class ElectronApp extends Context.Service<ElectronApp, ElectronAppShape>()(
"@t3tools/desktop/electron/ElectronApp",
"t3/desktop/electron/App",
) {}
const addScopedAppListener = <Args extends ReadonlyArray<unknown>>(
+1 -1
View File
@@ -29,7 +29,7 @@ export interface ElectronDialogShape {
}
export class ElectronDialog extends Context.Service<ElectronDialog, ElectronDialogShape>()(
"@t3tools/desktop/electron/ElectronDialog",
"t3/desktop/electron/Dialog",
) {}
const make = ElectronDialog.of({
+1 -1
View File
@@ -33,7 +33,7 @@ export interface ElectronMenuShape {
}
export class ElectronMenu extends Context.Service<ElectronMenu, ElectronMenuShape>()(
"@t3tools/desktop/electron/ElectronMenu",
"t3/desktop/electron/Menu",
) {}
function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextMenuItem[] {
@@ -52,7 +52,7 @@ export interface ElectronProtocolShape {
}
export class ElectronProtocol extends Context.Service<ElectronProtocol, ElectronProtocolShape>()(
"@t3tools/desktop/electron/ElectronProtocol",
"t3/desktop/electron/Protocol",
) {}
export function normalizeDesktopProtocolPathname(rawPath: string): Option.Option<string> {
@@ -48,7 +48,7 @@ export interface ElectronSafeStorageShape {
export class ElectronSafeStorage extends Context.Service<
ElectronSafeStorage,
ElectronSafeStorageShape
>()("@t3tools/desktop/electron/ElectronSafeStorage") {}
>()("@t3tools/desktop/ElectronSafeStorage") {}
const make = ElectronSafeStorage.of({
isEncryptionAvailable: Effect.try({
+1 -1
View File
@@ -26,7 +26,7 @@ export interface ElectronShellShape {
}
export class ElectronShell extends Context.Service<ElectronShell, ElectronShellShape>()(
"@t3tools/desktop/electron/ElectronShell",
"t3/desktop/electron/Shell",
) {}
const make = ElectronShell.of({
+1 -1
View File
@@ -13,7 +13,7 @@ export interface ElectronThemeShape {
}
export class ElectronTheme extends Context.Service<ElectronTheme, ElectronThemeShape>()(
"@t3tools/desktop/electron/ElectronTheme",
"t3/desktop/electron/Theme",
) {}
const make = ElectronTheme.of({
+1 -1
View File
@@ -67,7 +67,7 @@ export interface ElectronUpdaterShape {
}
export class ElectronUpdater extends Context.Service<ElectronUpdater, ElectronUpdaterShape>()(
"@t3tools/desktop/electron/ElectronUpdater",
"t3/desktop/electron/Updater",
) {}
export const layer = Layer.succeed(ElectronUpdater, {
+1 -1
View File
@@ -33,7 +33,7 @@ export interface ElectronWindowShape {
}
export class ElectronWindow extends Context.Service<ElectronWindow, ElectronWindowShape>()(
"@t3tools/desktop/electron/ElectronWindow",
"t3/desktop/electron/Window",
) {}
const make = Effect.gen(function* () {
+1 -3
View File
@@ -42,9 +42,7 @@ export interface DesktopIpcShape {
) => Effect.Effect<void, never, R | Scope.Scope>;
}
export class DesktopIpc extends Context.Service<DesktopIpc, DesktopIpcShape>()(
"@t3tools/desktop/ipc/DesktopIpc",
) {}
export class DesktopIpc extends Context.Service<DesktopIpc, DesktopIpcShape>()("t3/desktop/Ipc") {}
export const make = (ipcMain: DesktopIpcMain): DesktopIpcShape =>
DesktopIpc.of({
+11 -17
View File
@@ -6,7 +6,6 @@ import {
} from "@t3tools/contracts";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -14,6 +13,7 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Random from "effect/Random";
import * as Schema from "effect/Schema";
import * as SynchronizedRef from "effect/SynchronizedRef";
@@ -89,7 +89,7 @@ export interface DesktopAppSettingsShape {
export class DesktopAppSettings extends Context.Service<
DesktopAppSettings,
DesktopAppSettingsShape
>()("@t3tools/desktop/settings/DesktopAppSettings") {}
>()("t3/desktop/AppSettings") {}
export function resolveDefaultDesktopSettings(appVersion: string): DesktopSettings {
return {
@@ -222,10 +222,10 @@ const writeSettings = Effect.fn("desktop.settings.writeSettings")(function* (inp
readonly settingsPath: string;
readonly settings: DesktopSettings;
readonly defaultSettings: DesktopSettings;
readonly suffix: string;
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
const directory = input.path.dirname(input.settingsPath);
const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
const suffix = (yield* Random.nextUUIDv4).replace(/-/g, "");
const tempPath = `${input.settingsPath}.${process.pid}.${suffix}.tmp`;
const encoded = yield* encodeDesktopSettingsJson(
toDesktopSettingsDocument(input.settings, input.defaultSettings),
);
@@ -240,7 +240,6 @@ export const layer = Layer.effect(
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const crypto = yield* Crypto.Crypto;
const settingsRef = yield* SynchronizedRef.make(environment.defaultDesktopSettings);
const persist = (
@@ -252,18 +251,13 @@ export const layer = Layer.effect(
return Effect.succeed([settingsChange(settings, false), settings] as const);
}
return crypto.randomUUIDv4.pipe(
Effect.map((uuid) => uuid.replace(/-/g, "")),
Effect.flatMap((suffix) =>
writeSettings({
fileSystem,
path,
settingsPath: environment.desktopSettingsPath,
settings: nextSettings,
defaultSettings: environment.defaultDesktopSettings,
suffix,
}),
),
return writeSettings({
fileSystem,
path,
settingsPath: environment.desktopSettingsPath,
settings: nextSettings,
defaultSettings: environment.defaultDesktopSettings,
}).pipe(
Effect.mapError((cause) => new DesktopSettingsWriteError({ cause })),
Effect.as([settingsChange(nextSettings, true), nextSettings] as const),
);
@@ -1,7 +1,6 @@
import { ClientSettingsSchema, type ClientSettings } from "@t3tools/contracts";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -9,6 +8,7 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Random from "effect/Random";
import * as Schema from "effect/Schema";
import * as Ref from "effect/Ref";
@@ -49,7 +49,7 @@ export interface DesktopClientSettingsShape {
export class DesktopClientSettings extends Context.Service<
DesktopClientSettings,
DesktopClientSettingsShape
>()("@t3tools/desktop/settings/DesktopClientSettings") {}
>()("t3/desktop/ClientSettings") {}
const readClientSettings = (
fileSystem: FileSystem.FileSystem,
@@ -74,10 +74,10 @@ const writeClientSettings = Effect.fnUntraced(function* (input: {
readonly path: Path.Path;
readonly settingsPath: string;
readonly settings: ClientSettings;
readonly suffix: string;
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
const directory = input.path.dirname(input.settingsPath);
const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
const suffix = (yield* Random.nextUUIDv4).replace(/-/g, "");
const tempPath = `${input.settingsPath}.${process.pid}.${suffix}.tmp`;
const encoded = yield* encodeClientSettingsJson(input.settings);
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
@@ -90,24 +90,18 @@ export const layer = Layer.effect(
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const crypto = yield* Crypto.Crypto;
return DesktopClientSettings.of({
get: readClientSettings(fileSystem, environment.clientSettingsPath).pipe(
Effect.withSpan("desktop.clientSettings.get"),
),
set: (settings) =>
crypto.randomUUIDv4.pipe(
Effect.map((uuid) => uuid.replace(/-/g, "")),
Effect.flatMap((suffix) =>
writeClientSettings({
fileSystem,
path,
settingsPath: environment.clientSettingsPath,
settings,
suffix,
}),
),
writeClientSettings({
fileSystem,
path,
settingsPath: environment.clientSettingsPath,
settings,
}).pipe(
Effect.mapError((cause) => new DesktopClientSettingsWriteError({ cause })),
Effect.withSpan("desktop.clientSettings.set"),
),
@@ -1,7 +1,6 @@
import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
@@ -10,6 +9,7 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Random from "effect/Random";
import * as Schema from "effect/Schema";
import * as Ref from "effect/Ref";
@@ -121,7 +121,7 @@ export interface DesktopSavedEnvironmentsShape {
export class DesktopSavedEnvironments extends Context.Service<
DesktopSavedEnvironments,
DesktopSavedEnvironmentsShape
>()("@t3tools/desktop/settings/DesktopSavedEnvironments") {}
>()("t3/desktop/SavedEnvironments") {}
function toPersistedSavedEnvironmentRecord(
record: PersistedSavedEnvironmentStorageRecord,
@@ -200,10 +200,10 @@ const writeRegistryDocument = Effect.fn("desktop.savedEnvironments.writeRegistry
readonly path: Path.Path;
readonly registryPath: string;
readonly document: SavedEnvironmentRegistryDocument;
readonly suffix: string;
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
const directory = input.path.dirname(input.registryPath);
const tempPath = `${input.registryPath}.${process.pid}.${input.suffix}.tmp`;
const suffix = (yield* Random.nextUUIDv4).replace(/-/g, "");
const tempPath = `${input.registryPath}.${process.pid}.${suffix}.tmp`;
const encoded = yield* encodeSavedEnvironmentRegistryDocumentJson(input.document);
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
@@ -247,22 +247,14 @@ export const layer = Layer.effect(
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
const crypto = yield* Crypto.Crypto;
const writeDocument = (document: SavedEnvironmentRegistryDocument) =>
crypto.randomUUIDv4.pipe(
Effect.map((uuid) => uuid.replace(/-/g, "")),
Effect.flatMap((suffix) =>
writeRegistryDocument({
fileSystem,
path,
registryPath: environment.savedEnvironmentRegistryPath,
document,
suffix,
}),
),
Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })),
);
writeRegistryDocument({
fileSystem,
path,
registryPath: environment.savedEnvironmentRegistryPath,
document,
}).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
return DesktopSavedEnvironments.of({
getRegistry: readRegistryDocument(fileSystem, environment.savedEnvironmentRegistryPath).pipe(
@@ -26,7 +26,7 @@ export interface DesktopShellEnvironmentShape {
export class DesktopShellEnvironment extends Context.Service<
DesktopShellEnvironment,
DesktopShellEnvironmentShape
>()("@t3tools/desktop/shell/DesktopShellEnvironment") {}
>()("t3/desktop/ShellEnvironment") {}
const LOGIN_SHELL_ENV_NAMES = [
"PATH",
@@ -68,7 +68,7 @@ export interface DesktopSshEnvironmentShape {
export class DesktopSshEnvironment extends Context.Service<
DesktopSshEnvironment,
DesktopSshEnvironmentShape
>()("@t3tools/desktop/ssh/DesktopSshEnvironment") {}
>()("t3/desktop/SshEnvironment") {}
export interface DesktopSshEnvironmentLayerOptions {
readonly resolveCliPackageSpec?: () => string;
@@ -1,5 +1,4 @@
import { assert, describe, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
@@ -87,7 +86,6 @@ function makeElectronWindowLayer(window: ReturnType<typeof makeTestWindow>["wind
function makeLayer(window: ReturnType<typeof makeTestWindow>["window"]) {
return DesktopSshPasswordPrompts.layer({ passwordPromptTimeoutMs: 1_000 }).pipe(
Layer.provide(makeElectronWindowLayer(window)),
Layer.provide(NodeServices.layer),
Layer.provideMerge(TestClock.layer()),
);
}
@@ -2,7 +2,6 @@ import type { DesktopSshPasswordPromptRequest } from "@t3tools/contracts";
import { DesktopSshPasswordPromptResolutionInputSchema } from "@t3tools/contracts";
import type { SshPasswordRequest } from "@t3tools/ssh/auth";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
@@ -10,6 +9,7 @@ import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Random from "effect/Random";
import * as Ref from "effect/Ref";
import * as IpcChannels from "../ipc/channels.ts";
@@ -129,7 +129,7 @@ export interface DesktopSshPasswordPromptsShape {
export class DesktopSshPasswordPrompts extends Context.Service<
DesktopSshPasswordPrompts,
DesktopSshPasswordPromptsShape
>()("@t3tools/desktop/ssh/DesktopSshPasswordPrompts") {}
>()("t3/desktop/SshPasswordPrompts") {}
interface PendingSshPasswordPrompt {
readonly requestId: string;
@@ -163,7 +163,6 @@ const failPending = (
const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (options: LayerOptions = {}) {
const electronWindow = yield* ElectronWindow.ElectronWindow;
const crypto = yield* Crypto.Crypto;
const pendingRef = yield* Ref.make(new Map<string, PendingSshPasswordPrompt>());
const passwordPromptTimeoutMs =
options.passwordPromptTimeoutMs ?? DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS;
@@ -231,11 +230,7 @@ const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (options: La
});
}
const requestId = yield* crypto.randomUUIDv4.pipe(
Effect.mapError(
() => new DesktopSshPromptUnavailableError({ reason: "Secure randomness is unavailable." }),
),
);
const requestId = yield* Random.nextUUIDv4;
const now = yield* DateTime.now;
const expiresAt = DateTime.formatIso(
DateTime.add(now, { milliseconds: passwordPromptTimeoutMs }),
+1 -1
View File
@@ -53,7 +53,7 @@ export interface DesktopSshRemoteApiShape {
export class DesktopSshRemoteApi extends Context.Service<
DesktopSshRemoteApi,
DesktopSshRemoteApiShape
>()("@t3tools/desktop/ssh/DesktopSshRemoteApi") {}
>()("t3/desktop/SshRemoteApi") {}
const decodeExecutionEnvironmentDescriptor = Schema.decodeUnknownEffect(
ExecutionEnvironmentDescriptor,
+1 -1
View File
@@ -100,7 +100,7 @@ export interface DesktopUpdatesShape {
}
export class DesktopUpdates extends Context.Service<DesktopUpdates, DesktopUpdatesShape>()(
"@t3tools/desktop/updates/DesktopUpdates",
"t3/desktop/Updates",
) {}
const {
@@ -21,7 +21,7 @@ export interface DesktopApplicationMenuShape {
export class DesktopApplicationMenu extends Context.Service<
DesktopApplicationMenu,
DesktopApplicationMenuShape
>()("@t3tools/desktop/window/DesktopApplicationMenu") {}
>()("t3/desktop/ApplicationMenu") {}
type DesktopApplicationMenuRuntimeServices =
| DesktopUpdates.DesktopUpdates
+1 -1
View File
@@ -62,7 +62,7 @@ export interface DesktopWindowShape {
}
export class DesktopWindow extends Context.Service<DesktopWindow, DesktopWindowShape>()(
"@t3tools/desktop/window/DesktopWindow",
"t3/desktop/Window",
) {}
const { logInfo: logWindowInfo, logWarning: logWindowWarning } =
+1 -1
View File
@@ -12,7 +12,7 @@ export default defineConfig([
...shared,
entry: ["src/main.ts"],
clean: true,
noExternal: (id) => id.startsWith("@t3tools/"),
noExternal: (id) => id.startsWith("@t3tools/") || id.startsWith("effect-acp"),
},
{
...shared,
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 244 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 358 B

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="257" preserveAspectRatio="xMidYMid" viewBox="0 0 256 257"><path fill="#D97757" d="m50.228 170.321 50.357-28.257.843-2.463-.843-1.361h-2.462l-8.426-.518-28.775-.778-24.952-1.037-24.175-1.296-6.092-1.297L0 125.796l.583-3.759 5.12-3.434 7.324.648 16.202 1.101 24.304 1.685 17.629 1.037 26.118 2.722h4.148l.583-1.685-1.426-1.037-1.101-1.037-25.147-17.045-27.22-18.017-14.258-10.37-7.713-5.25-3.888-4.925-1.685-10.758 7-7.713 9.397.649 2.398.648 9.527 7.323 20.35 15.75L94.817 91.9l3.889 3.24 1.555-1.102.195-.777-1.75-2.917-14.453-26.118-15.425-26.572-6.87-11.018-1.814-6.61c-.648-2.723-1.102-4.991-1.102-7.778l7.972-10.823L71.42 0 82.05 1.426l4.472 3.888 6.61 15.101 10.694 23.786 16.591 32.34 4.861 9.592 2.592 8.879.973 2.722h1.685v-1.556l1.36-18.211 2.528-22.36 2.463-28.776.843-8.1 4.018-9.722 7.971-5.25 6.222 2.981 5.12 7.324-.713 4.73-3.046 19.768-5.962 30.98-3.889 20.739h2.268l2.593-2.593 10.499-13.934 17.628-22.036 7.778-8.749 9.073-9.657 5.833-4.601h11.018l8.1 12.055-3.628 12.443-11.342 14.388-9.398 12.184-13.48 18.147-8.426 14.518.778 1.166 2.01-.194 30.46-6.481 16.462-2.982 19.637-3.37 8.88 4.148.971 4.213-3.5 8.62-20.998 5.184-24.628 4.926-36.682 8.685-.454.324.519.648 16.526 1.555 7.065.389h17.304l32.21 2.398 8.426 5.574 5.055 6.805-.843 5.184-12.962 6.611-17.498-4.148-40.83-9.721-14-3.5h-1.944v1.167l11.666 11.406 21.387 19.314 26.767 24.887 1.36 6.157-3.434 4.86-3.63-.518-23.526-17.693-9.073-7.972-20.545-17.304h-1.36v1.814l4.73 6.935 25.017 37.59 1.296 11.536-1.814 3.76-6.481 2.268-7.13-1.297-14.647-20.544-15.1-23.138-12.185-20.739-1.49.843-7.194 77.448-3.37 3.953-7.778 2.981-6.48-4.925-3.436-7.972 3.435-15.749 4.148-20.544 3.37-16.333 3.046-20.285 1.815-6.74-.13-.454-1.49.194-15.295 20.999-23.267 31.433-18.406 19.702-4.407 1.75-7.648-3.954.713-7.064 4.277-6.286 25.47-32.405 15.36-20.092 9.917-11.6-.065-1.686h-.583L44.07 198.125l-12.055 1.555-5.185-4.86.648-7.972 2.463-2.593 20.35-13.999-.064.065Z"></path></svg>

Before

Width:  |  Height:  |  Size: 2.0 KiB

@@ -1 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?><svg id="cursor_light__Ebene_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 466.73 532.09"><defs></defs><path class="cursor_light__st0" d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z"></path></svg>

Before

Width:  |  Height:  |  Size: 649 B

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="260" preserveAspectRatio="xMidYMid" viewBox="0 0 256 260"><path fill="#fff" d="M239.184 106.203a64.716 64.716 0 0 0-5.576-53.103C219.452 28.459 191 15.784 163.213 21.74A65.586 65.586 0 0 0 52.096 45.22a64.716 64.716 0 0 0-43.23 31.36c-14.31 24.602-11.061 55.634 8.033 76.74a64.665 64.665 0 0 0 5.525 53.102c14.174 24.65 42.644 37.324 70.446 31.36a64.72 64.72 0 0 0 48.754 21.744c28.481.025 53.714-18.361 62.414-45.481a64.767 64.767 0 0 0 43.229-31.36c14.137-24.558 10.875-55.423-8.083-76.483Zm-97.56 136.338a48.397 48.397 0 0 1-31.105-11.255l1.535-.87 51.67-29.825a8.595 8.595 0 0 0 4.247-7.367v-72.85l21.845 12.636c.218.111.37.32.409.563v60.367c-.056 26.818-21.783 48.545-48.601 48.601Zm-104.466-44.61a48.345 48.345 0 0 1-5.781-32.589l1.534.921 51.722 29.826a8.339 8.339 0 0 0 8.441 0l63.181-36.425v25.221a.87.87 0 0 1-.358.665l-52.335 30.184c-23.257 13.398-52.97 5.431-66.404-17.803ZM23.549 85.38a48.499 48.499 0 0 1 25.58-21.333v61.39a8.288 8.288 0 0 0 4.195 7.316l62.874 36.272-21.845 12.636a.819.819 0 0 1-.767 0L41.353 151.53c-23.211-13.454-31.171-43.144-17.804-66.405v.256Zm179.466 41.695-63.08-36.63L161.73 77.86a.819.819 0 0 1 .768 0l52.233 30.184a48.6 48.6 0 0 1-7.316 87.635v-61.391a8.544 8.544 0 0 0-4.4-7.213Zm21.742-32.69-1.535-.922-51.619-30.081a8.39 8.39 0 0 0-8.492 0L99.98 99.808V74.587a.716.716 0 0 1 .307-.665l52.233-30.133a48.652 48.652 0 0 1 72.236 50.391v.205ZM88.061 139.097l-21.845-12.585a.87.87 0 0 1-.41-.614V65.685a48.652 48.652 0 0 1 79.757-37.346l-1.535.87-51.67 29.825a8.595 8.595 0 0 0-4.246 7.367l-.051 72.697Zm11.868-25.58 28.138-16.217 28.188 16.218v32.434l-28.086 16.218-28.188-16.218-.052-32.434Z"></path></svg>

Before

Width:  |  Height:  |  Size: 1.7 KiB

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512"><svg width="512" height="512" viewBox="0 0 512 512" fill="none" xmlns="http://www.w3.org/2000/svg"><rect width="512" height="512" fill="#131010"></rect><path d="M320 224V352H192V224H320Z" fill="#5A5858"></path><path fill-rule="evenodd" clip-rule="evenodd" d="M384 416H128V96H384V416ZM320 160H192V352H320V160Z" fill="white"></path></svg></svg>

Before

Width:  |  Height:  |  Size: 464 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 138 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 652 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 123 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 110 KiB

@@ -1,53 +0,0 @@
---
interface Props {
class?: string;
idPrefix: string;
}
const { class: className, idPrefix } = Astro.props;
---
<svg
class={className}
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 256 295"
aria-hidden="true"
>
<defs>
<linearGradient id={`${idPrefix}0`} x1="48.548%" x2="51.047%" y1="115.276%" y2="41.364%">
<stop offset="0%" stop-color="#FFEED7" />
<stop offset="100%" stop-color="#BDBFC2" />
</linearGradient>
<linearGradient id={`${idPrefix}6`} x1="49.984%" x2="49.984%" y1="89.845%" y2="40.632%">
<stop offset="0%" stop-color="#FFEED7" />
<stop offset="100%" stop-color="#BDBFC2" />
</linearGradient>
<linearGradient id={`${idPrefix}8`} x1="49.841%" x2="50.241%" y1="13.229%" y2="94.673%">
<stop offset="0%" stop-color="#FFF" stop-opacity=".8" />
<stop offset="100%" stop-color="#FFF" stop-opacity="0" />
</linearGradient>
<linearGradient id={`${idPrefix}c`} x1="53.467%" x2="38.949%" y1="48.921%" y2="98.1%">
<stop offset="0%" stop-color="#FFA63F" />
<stop offset="100%" stop-color="#FF0" />
</linearGradient>
<linearGradient id={`${idPrefix}e`} x1="30.581%" x2="65.887%" y1="34.024%" y2="89.175%">
<stop offset="0%" stop-color="#FFA63F" />
<stop offset="100%" stop-color="#FF0" />
</linearGradient>
<linearGradient id={`${idPrefix}i`} x1="49.733%" x2="50.558%" y1="17.609%" y2="99.385%">
<stop offset="0%" stop-color="#FFA63F" />
<stop offset="100%" stop-color="#FF0" />
</linearGradient>
</defs>
<g fill="none">
<path fill="#000" d="M63.213 215.474c-11.387-16.346-13.591-69.606 12.947-102.39C89.292 97.383 92.69 86.455 93.7 71.67c.734-16.805-11.846-66.851 35.537-70.616 48.027-3.857 45.364 43.526 45.088 68.596-.183 21.12 15.52 33.15 26.355 49.68 19.927 30.303 18.274 82.461-3.765 110.745-27.916 35.354-51.791 20.018-67.678 21.304-29.752 1.745-30.762 17.54-66.024-35.905" />
<path fill={`url(#${idPrefix}6)`} d="M81.027 145.684c6.52-14.785 20.386-40.772 20.662-60.883 0-15.978 47.843-19.835 51.7-3.856 3.856 15.978 13.59 39.853 19.834 51.424 6.245 11.478 24.335 48.118 5.051 80.074-17.356 28.284-69.973 50.69-98.073-3.856-9.55-18.917-7.806-42.333.826-62.903" />
<path fill={`url(#${idPrefix}8)`} d="M166.428 151.285c0 16.162-15.519 37.1-42.15 36.916-27.456.183-39.118-20.754-39.118-36.916 0-16.161 18.182-29.293 40.588-29.293 22.498.092 40.68 13.132 40.68 29.293" />
<path fill="#000" stroke="#000" stroke-width=".977" d="M176.805 117.86c13.59 11.02 38.292 49.587 2.204 74.748-11.846 7.806 10.468 32.508 23.049 19.927 43.618-43.894-1.102-94.308-16.53-111.664-13.774-15.151-25.987 3.49-8.723 16.989z" />
<path fill="#000" stroke="#000" stroke-width="1.25" d="M79.925 122.727c-8.907 14.509-30.211 48.669-1.652 66.484 38.384 23.6 27.548 47.108-7.53 25.895-49.404-29.568-5.97-89.257 13.774-112.03 22.59-25.529 4.316 4.683-4.592 19.65z" />
<path fill={`url(#${idPrefix}c)`} stroke="#E68C3F" stroke-width="6.25" d="M51.835 258.542c-20.57-10.928-50.414 2.112-39.578-27.457 2.204-6.704-3.214-16.805.275-23.325 4.133-7.989 13.04-6.244 18.366-11.57 5.234-5.51 8.54-15.06 18.366-13.59 9.734 1.468 16.254 13.406 23.049 28.099 5.05 10.468 22.865 25.253 21.672 37.007-1.47 17.998-21.948 21.396-42.15 10.836z" transform="translate(10)" />
<path fill={`url(#${idPrefix}e)`} stroke="#E68C3F" stroke-width="6.251" d="M194.445 253.49c15.06-18.273 48.578-14.508 25.988-39.577-4.775-5.418-3.306-16.989-9.183-21.947-6.887-6.061-14.509-1.102-21.488-4.224-6.979-3.398-14.325-9.918-22.865-5.327-8.54 4.684-9.459 16.805-10.285 32.783-.735 11.479-11.203 30.671-5.602 41.231 8.081 16.346 29.11 14.142 43.435-2.938z" transform="translate(10)" />
<path fill={`url(#${idPrefix}i)`} stroke="#E68C3F" stroke-width="3.75" d="M97.107 66.344c3.673-3.398 12.58-13.774 29.477-2.939 3.122 2.02 5.693 2.204 11.662 4.775 12.03 4.96 6.336 16.897-6.52 20.937-5.51 1.745-10.468 8.449-20.386 7.806-8.54-.46-10.744-6.06-15.978-9.091-9.275-5.234-10.652-12.305-5.602-16.07 5.051-3.765 6.98-5.143 7.347-5.418z" transform="translate(10)" />
<path fill="#000" d="M133.186 57.712c-.092 5.234 2.48 9.458 5.877 9.458 3.306 0 6.153-4.224 6.245-9.366.091-5.234-2.48-9.459-5.878-9.459-3.397 0-6.152 4.225-6.244 9.367m-21.212.092c.459 4.316-1.194 7.989-3.582 8.356-2.387.276-4.683-2.938-5.142-7.254-.46-4.316 1.194-7.99 3.581-8.357 2.388-.275 4.684 2.939 5.143 7.255" />
</g>
</svg>
+69 -251
View File
@@ -6,7 +6,7 @@ interface Props {
const {
title = "T3 Code",
description = "T3 Code — The open-source control plane for coding agents.",
description = "T3 Code — The best way to code with AI.",
} = Astro.props;
---
@@ -18,7 +18,7 @@ const {
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=DM+Sans:opsz,[email protected],400;9..40,500;9..40,600&family=JetBrains+Mono:wght@400;500&display=swap"
href="https://fonts.googleapis.com/css2?family=DM+Sans:opsz,[email protected],400;9..40,500;9..40,600&display=swap"
rel="stylesheet"
/>
<link rel="icon" href="/favicon.ico" sizes="48x48" />
@@ -30,25 +30,18 @@ const {
<body>
<div class="page">
<nav class="nav">
<div class="nav-inner">
<a href="/" class="nav-brand" aria-label="T3 Code home">
<span class="nav-brand-name">T3 Code</span>
</a>
<div class="nav-right">
<a
class="nav-gh"
href="https://github.com/pingdotgg/t3code"
target="_blank"
rel="noopener noreferrer"
>
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<path d="M12 .5C5.65.5.5 5.65.5 12a11.5 11.5 0 007.86 10.93c.58.1.79-.25.79-.56v-2c-3.2.69-3.88-1.37-3.88-1.37-.52-1.33-1.27-1.69-1.27-1.69-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.18 1.76 1.18 1.02 1.76 2.68 1.25 3.33.96.1-.75.4-1.25.72-1.54-2.55-.29-5.24-1.27-5.24-5.67 0-1.25.45-2.28 1.18-3.08-.12-.29-.51-1.45.11-3.02 0 0 .96-.31 3.15 1.18a10.96 10.96 0 015.74 0c2.19-1.49 3.15-1.18 3.15-1.18.62 1.57.23 2.73.11 3.02.74.8 1.18 1.83 1.18 3.08 0 4.41-2.7 5.38-5.27 5.66.41.36.78 1.06.78 2.13v3.16c0 .31.21.67.8.56A11.5 11.5 0 0023.5 12C23.5 5.65 18.35.5 12 .5z"/>
</svg>
<span>GitHub</span>
</a>
<a class="btn btn-primary" href="/#download">Download</a>
</div>
</div>
<a href="/" class="nav-brand">
<img src="/icon.png" alt="T3" class="nav-icon" />
</a>
<a
href="https://github.com/pingdotgg/t3code"
target="_blank"
rel="noopener noreferrer"
class="nav-github"
>
GitHub
<span class="nav-github-arrow" aria-hidden="true">&#8599;</span>
</a>
</nav>
<main class="main">
@@ -56,54 +49,23 @@ const {
</main>
<footer class="footer">
<div class="footer-inner">
<div class="footer-brand">
<img src="/icon.webp" alt="" />
<span>&copy; {new Date().getFullYear()} T3 Tools Inc · MIT licensed</span>
</div>
<div class="footer-links">
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer">GitHub</a>
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
<a href="/download">Download</a>
</div>
<span class="footer-copy">&copy; {new Date().getFullYear()} T3 Tools Inc</span>
<div class="footer-links">
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer">GitHub</a>
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
</div>
</footer>
</div>
<script>
const nav = document.querySelector(".nav");
const onScroll = () => {
if (!nav) return;
if (window.scrollY > 12) nav.classList.add("is-scrolled");
else nav.classList.remove("is-scrolled");
};
window.addEventListener("scroll", onScroll, { passive: true });
onScroll();
</script>
</body>
</html>
<style is:global>
:root {
--bg: #09090b;
--bg-elev: #0c0c0e;
--bg-card: #111113;
--fg: #fafafa;
--fg-muted: #a1a1aa;
--fg-dim: #71717a;
--fg-faint: #52525b;
--border: rgba(255, 255, 255, 0.08);
--border-strong: rgba(255, 255, 255, 0.14);
--accent-h: 250;
--accent: oklch(0.68 0.17 var(--accent-h));
--accent-dim: oklch(0.68 0.17 var(--accent-h) / 0.15);
--ok: oklch(0.72 0.16 150);
--warn: oklch(0.76 0.15 75);
--font-sans: "DM Sans", -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
--font-mono: "JetBrains Mono", ui-monospace, SFMono-Regular, Menlo, Monaco, monospace;
--radius: 12px;
--radius-sm: 8px;
--radius-lg: 16px;
}
* {
@@ -114,19 +76,16 @@ const {
html {
color-scheme: dark;
scroll-behavior: smooth;
}
body {
background: var(--bg);
color: var(--fg);
font-family: var(--font-sans);
font-feature-settings: "ss01", "ss02";
font-family: "DM Sans", -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
min-height: 100vh;
overflow-x: hidden;
line-height: 1.5;
}
body::after {
@@ -146,103 +105,11 @@ const {
text-decoration: none;
}
button {
font-family: inherit;
cursor: pointer;
border: 0;
background: none;
color: inherit;
}
img,
svg {
img {
display: block;
max-width: 100%;
}
.eyebrow {
font-family: var(--font-mono);
font-size: 11px;
letter-spacing: 0.14em;
text-transform: uppercase;
color: var(--fg-dim);
font-weight: 500;
}
.display {
font-weight: 500;
letter-spacing: -0.035em;
line-height: 1.05;
}
.container {
width: 100%;
max-width: 1240px;
margin: 0 auto;
padding: 0 32px;
}
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
font-weight: 500;
font-size: 14px;
padding: 10px 18px;
border-radius: 8px;
transition: transform 0.18s ease, background 0.18s ease,
border-color 0.18s ease, color 0.18s ease;
white-space: nowrap;
}
.btn-primary {
background: var(--fg);
color: #09090b;
font-weight: 600;
}
.btn-primary:hover {
transform: translateY(-1px);
background: #fff;
}
.btn-primary:active {
transform: translateY(0);
}
.btn-ghost {
color: var(--fg-muted);
border: 1px solid var(--border);
background: transparent;
}
.btn-ghost:hover {
color: var(--fg);
border-color: var(--border-strong);
background: rgba(255, 255, 255, 0.02);
}
.btn-lg {
padding: 14px 22px;
font-size: 15px;
border-radius: 10px;
}
.tile {
position: relative;
border: 1px solid var(--border);
border-radius: var(--radius);
background: linear-gradient(180deg, rgba(255, 255, 255, 0.015), rgba(255, 255, 255, 0));
overflow: hidden;
}
:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
border-radius: 4px;
}
@keyframes fade-in {
from {
opacity: 0;
@@ -253,26 +120,11 @@ const {
transform: translateY(0);
}
}
@keyframes pulse {
50% { opacity: 0.4; }
}
@keyframes spin {
to { transform: rotate(360deg); }
}
@keyframes floatDrift {
0%, 100% { translate: 0 0; }
50% { translate: 0 -10px; }
}
@keyframes blink {
50% { opacity: 0; }
}
</style>
<style>
/* ── Page ── */
.page {
min-height: 100vh;
display: flex;
@@ -280,131 +132,97 @@ const {
overflow-x: hidden;
}
/* ── Navbar ── */
.nav {
position: sticky;
top: 0;
z-index: 50;
backdrop-filter: blur(18px);
-webkit-backdrop-filter: blur(18px);
background: color-mix(in srgb, var(--bg) 75%, transparent);
border-bottom: 1px solid transparent;
transition: border-color 0.3s ease;
}
.nav.is-scrolled {
border-bottom-color: var(--border);
}
.nav-inner {
max-width: 1240px;
margin: 0 auto;
padding: 12px 32px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
padding: 1.5rem 2.5rem;
opacity: 0.5;
transition: opacity 0.4s ease;
}
.nav:hover {
opacity: 1;
}
.nav-brand {
display: inline-flex;
display: flex;
align-items: center;
color: var(--fg);
transition: color 0.2s ease;
}
.nav-brand:hover {
color: #fff;
.nav-icon {
width: 28px;
height: 28px;
border-radius: 6px;
}
.nav-brand-name {
font-size: 16px;
font-weight: 650;
letter-spacing: -0.025em;
line-height: 1;
}
.nav-right {
display: inline-flex;
.nav-github {
display: flex;
align-items: center;
gap: 8px;
}
.nav-gh {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 7px 12px;
border: 1px solid var(--border);
border-radius: 8px;
gap: 0.35rem;
color: var(--fg-muted);
font-family: var(--font-mono);
font-size: 12px;
transition: color 0.2s ease, background 0.2s ease, border-color 0.2s ease;
font-size: 0.875rem;
transition: color 0.3s ease;
}
.nav-gh:hover {
.nav-github:hover {
color: var(--fg);
background: rgba(255, 255, 255, 0.04);
border-color: var(--border-strong);
}
.nav-github-arrow {
display: inline-block;
transition: transform 0.3s ease;
}
.nav-github:hover .nav-github-arrow {
transform: translateX(2px) translateY(-1px);
}
/* ── Main content ── */
.main {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
}
/* ── Footer ── */
.footer {
margin-top: auto;
border-top: 1px solid var(--border);
padding: 40px 0 32px;
}
.footer-inner {
max-width: 1240px;
margin: 0 auto;
padding: 0 32px;
display: flex;
flex-wrap: wrap;
gap: 24px;
align-items: center;
justify-content: space-between;
}
.footer-brand {
display: flex;
align-items: center;
gap: 10px;
font-size: 13px;
padding: 1.5rem 2.5rem;
font-size: 0.8rem;
color: var(--fg-dim);
}
.footer-brand img {
width: 20px;
height: 20px;
border-radius: 4px;
}
.footer-links {
display: flex;
gap: 20px;
gap: 1.25rem;
}
.footer-links a {
font-size: 13px;
color: var(--fg-dim);
transition: color 0.2s ease;
transition: color 0.3s ease;
}
.footer-links a:hover {
color: var(--fg);
}
@media (max-width: 820px) {
.nav-inner,
.footer-inner {
padding-left: 20px;
padding-right: 20px;
/* ── Mobile ── */
@media (max-width: 640px) {
.nav {
padding: 1.25rem;
}
.footer {
padding: 1.25rem;
}
}
</style>
-123
View File
@@ -1,123 +0,0 @@
export type Tweet = {
handle: string;
content: string;
excerpt?: string;
link: string;
};
export const tweets = [
{
handle: "Shay_Benshabtay",
content:
"T3 code is not perfect, but it's damn good. Open and fun , I can make my own fork for my uses and use the great tooling with my own needs.",
link: "https://x.com/Shay_Benshabtay/status/2054668503857156326",
},
{
handle: "teja2495",
content:
"I’ve completely switched to T3 Code for all my workflows. I just switch between different subscriptions and harnesses depending on what I need.",
excerpt: "I’ve completely switched to T3 Code for all my workflows.",
link: "https://x.com/teja2495/status/2052420254991581623",
},
{
handle: "developedbyed",
content: "might say alpha but T3 code is pretty awesome, really fast too",
link: "https://x.com/developedbyed/status/2030627970532921605",
},
{
handle: "tannerlinsley",
content:
"The minute T3 Code supports Claude Code, it could potentially become my daily driver. There's something special there.",
link: "https://x.com/tannerlinsley/status/2031102771529920966",
},
{
handle: "aronprins",
content:
"I already loved T3 Code by @theo and @jullerino, but their Connections implementation is next level epic and for this they should both earn maximum repect 🔥🫡",
excerpt: "I already loved T3 Code, but their Connections implementation is next level epic.",
link: "https://x.com/aronprins/status/2045102518196183109",
},
{
handle: "BennettBuhner",
content:
"T3 Code is literally Codex but better; all your favorite models and harnesses, accessible anywhere! The app is great but the website is even greater, so instead of needing to SSH into a machine, T3 IS my SSH!",
excerpt:
"T3 Code is literally Codex but better; all your favorite models and harnesses, accessible anywhere.",
link: "https://x.com/BennettBuhner/status/2054667115697754387",
},
{
handle: "ex0t1clol",
content: "T3 Code is proof electron apps don't have to suck",
link: "https://x.com/ex0t1clol/status/2054666870008021197",
},
{
handle: "Josikinz",
content:
"T3 code is better because it’s like if the codex Mac app didn’t make my computer run like shit 😋",
link: "https://x.com/Josikinz/status/2030367951694745870",
},
{
handle: "jetpackjoe_",
content: "T3 code is pretty alright I guess",
link: "https://x.com/jetpackjoe_/status/2054666792933404959",
},
{
handle: "mil000",
content: "T3 code saved my relationship!",
link: "https://x.com/mil000/status/2030120041451246071",
},
{
handle: "_winter_wonders",
content: "Heartbreaking: AI-hater has to admit T3 Code is really good.",
link: "https://x.com/_winter_wonders/status/2052350198764970434",
},
{
handle: "kostyniuk00",
content:
"I was not expecting a year ago, that my anti-AI colleagues would thank me a year later, for persuading them to try T3 Code Beta, that really helped them with organizing their workflows. \n\nFantastic product by @jullerino and @theo. Go try it out if you haven’t yet!",
excerpt:
"My anti-AI colleagues thanked me for persuading them to try T3 Code Beta. Fantastic product.",
link: "https://x.com/kostyniuk00/status/2052041388179468521",
},
{
handle: "gnukeith",
content:
"I tried T3 Code it actually fixed issues that Opus couldn’t solve in Claude Code + Theo has replied with “UwU” under my post. Dario has not.",
link: "https://x.com/gnukeith/status/2054670073579630730",
},
{
handle: "peculiarnewbie",
content: "T3 Code is iOS and other harnesses are androids",
link: "https://x.com/peculiarnewbie/status/2054671685027233827",
},
{
handle: "leodev",
content:
"T3 Code is probably the first coding gui that didn't suck performance wise and had a smart team behind it.",
link: "https://x.com/leodev/status/2054679746353537042",
},
{
handle: "pocarles",
content:
"Only using Codex and T3 now.\n\nI thought all AI coding harnesses had roughly the same impact. Using T3 Code taught me how wrong I was. The interface between you and the model changes everything.",
excerpt:
"Using T3 Code taught me how wrong I was. The interface between you and the model changes everything.",
link: "https://x.com/pocarles/status/2054673964274758046",
},
{
handle: "DavidKPiano",
content: "It's like Claude Code if they didn't vibe-code the entire thing",
link: "https://x.com/DavidKPiano/status/2054682983504719930",
},
{
handle: "iamkaffe",
content: "T3Code was the first one to truly care about Linux users.",
link: "https://x.com/iamkaffe/status/2054675539311411280",
},
{
handle: "uwunetes",
content:
"claude code make me go *whine whine whine* and t3 code make me go woof woof awooooo!!!",
link: "https://x.com/uwunetes/status/2054683356022120640",
},
] satisfies Tweet[];
+2 -8
View File
@@ -4,7 +4,6 @@ import { RELEASES_URL } from "../lib/releases";
---
<Layout title="Download — T3 Code" description="Download T3 Code for macOS, Windows, or Linux.">
<div class="download-page">
<h1 class="heading">Download T3 Code</h1>
<p class="subheading">
<span id="version-label">Loading latest release&hellip;</span>
@@ -65,7 +64,6 @@ import { RELEASES_URL } from "../lib/releases";
GitHub releases page<span aria-hidden="true"> &#8599;</span>
</a>
</p>
</div>
</Layout>
<script>
@@ -113,11 +111,7 @@ import { RELEASES_URL } from "../lib/releases";
</script>
<style>
.download-page {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
.main {
padding: 8vh 1.5rem 4rem;
}
@@ -263,7 +257,7 @@ import { RELEASES_URL } from "../lib/releases";
/* ── Mobile ── */
@media (max-width: 640px) {
.download-page {
.main {
padding: 5vh 1.25rem 4rem;
}
File diff suppressed because it is too large. Load diff
-19
View File
@@ -1,19 +0,0 @@
https://x.com/Shay_Benshabtay/status/2054668503857156326
https://x.com/teja2495/status/2052420254991581623
https://x.com/developedbyed/status/2030627970532921605
https://x.com/tannerlinsley/status/2031102771529920966
https://x.com/aronprins/status/2045102518196183109
https://x.com/BennettBuhner/status/2054667115697754387
https://x.com/ex0t1clol/status/2054666870008021197
https://x.com/Josikinz/status/2030367951694745870
https://x.com/jetpackjoe_/status/2054666792933404959
https://x.com/mil000/status/2030120041451246071
https://x.com/_winter_wonders/status/2052350198764970434
https://x.com/kostyniuk00/status/2052041388179468521
https://x.com/gnukeith/status/2054670073579630730
https://x.com/peculiarnewbie/status/2054671685027233827
https://x.com/leodev/status/2054679746353537042
https://x.com/pocarles/status/2054673964274758046
https://x.com/DavidKPiano/status/2054682983504719930
https://x.com/iamkaffe/status/2054675539311411280
https://x.com/uwunetes/status/2054683356022120640
@@ -73,6 +73,7 @@ import {
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
import { WorkspaceEntriesLive } from "../src/workspace/Layers/WorkspaceEntries.ts";
import { WorkspacePathsLive } from "../src/workspace/Layers/WorkspacePaths.ts";
import * as GitVcsDriver from "../src/vcs/GitVcsDriver.ts";
import * as VcsDriverRegistry from "../src/vcs/VcsDriverRegistry.ts";
import { VcsStatusBroadcaster } from "../src/vcs/VcsStatusBroadcaster.ts";
import { GitWorkflowService } from "../src/git/GitWorkflowService.ts";
@@ -310,11 +311,8 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provideMerge(serverSettingsLayer),
);
const gitWorkflowLayer = Layer.mock(GitWorkflowService)({
renameBranch: (input: {
readonly cwd: string;
readonly oldBranch: string;
readonly newBranch: string;
}) => Effect.succeed({ branch: input.newBranch }),
renameBranch: (input: Parameters<GitVcsDriver.GitVcsDriverShape["renameBranch"]>[0]) =>
Effect.succeed({ branch: input.newBranch }),
});
const textGenerationLayer = Layer.succeed(TextGeneration, {
generateBranchName: () => Effect.succeed({ branch: "update" }),
@@ -11,8 +11,8 @@ import {
ProviderDriverKind,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Crypto from "effect/Crypto";
import * as Queue from "effect/Queue";
import * as Random from "effect/Random";
import * as Stream from "effect/Stream";
import {
@@ -226,7 +226,6 @@ function missingSessionEffect(
export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapterHarnessOptions) =>
Effect.gen(function* () {
const provider = options?.provider ?? ProviderDriverKind.make("codex");
const crypto = yield* Crypto.Crypto;
const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
let sessionCount = 0;
const sessions = new Map<ThreadId, SessionState>();
@@ -242,18 +241,6 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
>();
const emit = (event: ProviderRuntimeEvent) => Queue.offer(runtimeEvents, event);
const randomUUIDv4 = (threadId: ThreadId) =>
crypto.randomUUIDv4.pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterValidationError({
provider,
operation: "crypto/randomUUIDv4",
issue: `Failed to generate test runtime identifier for thread '${threadId}'.`,
cause,
}),
),
);
const startSession: ProviderAdapterShape<ProviderAdapterError>["startSession"] = (input) =>
Effect.gen(function* () {
@@ -322,7 +309,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
for (const fixtureEvent of response.events) {
const rawEvent: Record<string, unknown> = {
...(fixtureEvent as Record<string, unknown>),
eventId: yield* randomUUIDv4(input.threadId),
eventId: yield* Random.nextUUIDv4,
provider,
sessionId: RuntimeSessionId.make(String(input.threadId)),
};
@@ -379,7 +366,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
if (deferredTurnCompletedEvents.length === 0) {
yield* emit({
type: "turn.completed",
eventId: EventId.make(yield* randomUUIDv4(input.threadId)),
eventId: EventId.make(yield* Random.nextUUIDv4),
provider,
createdAt: nowIso(),
threadId: state.snapshot.threadId,
+9 -6
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.24",
"version": "0.0.22",
"license": "MIT",
"repository": {
"type": "git",
@@ -19,21 +19,23 @@
"build": "node scripts/cli.ts build",
"build:bundle": "tsdown",
"start": "node dist/bin.mjs",
"typecheck": "tsgo --noEmit",
"test": "vitest run"
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:process-reaper": "vitest run src/server.test.ts src/provider/Layers/ClaudeAdapter.test.ts src/provider/Layers/ProviderSessionDirectory.test.ts src/provider/Layers/ProviderSessionReaper.test.ts src/provider/Layers/CodexAdapter.test.ts"
},
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.3.154",
"@anthropic-ai/claude-agent-sdk": "^0.2.111",
"@effect/platform-bun": "catalog:",
"@effect/platform-node": "catalog:",
"@effect/platform-node-shared": "catalog:",
"@effect/sql-sqlite-bun": "catalog:",
"@opencode-ai/sdk": "^1.3.15",
"@pierre/diffs": "catalog:",
"effect": "catalog:",
"node-pty": "^1.1.0"
"node-pty": "^1.1.0",
"open": "^10.1.0"
},
"devDependencies": {
"@effect/language-service": "catalog:",
"@effect/vitest": "catalog:",
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
@@ -44,6 +46,7 @@
"effect-acp": "workspace:*",
"effect-codex-app-server": "workspace:*",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
},
"engines": {
+3 -1
View File
@@ -1,6 +1,7 @@
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Random from "effect/Random";
export const writeFileStringAtomically = (input: {
readonly filePath: string;
@@ -10,6 +11,7 @@ export const writeFileStringAtomically = (input: {
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempFileId = yield* Random.nextUUIDv4;
const targetDirectory = path.dirname(input.filePath);
yield* fs.makeDirectory(targetDirectory, { recursive: true });
@@ -17,7 +19,7 @@ export const writeFileStringAtomically = (input: {
directory: targetDirectory,
prefix: `${path.basename(input.filePath)}.`,
});
const tempPath = path.join(tempDirectory, "contents.tmp");
const tempPath = path.join(tempDirectory, `${tempFileId}.tmp`);
yield* fs.writeFileString(tempPath, input.contents);
yield* fs.rename(tempPath, input.filePath);
+10 -16
View File
@@ -64,16 +64,11 @@ export const makeAuthControlPlane = Effect.gen(function* () {
const listPairingLinks: AuthControlPlaneShape["listPairingLinks"] = (input) =>
bootstrapCredentials.listActive().pipe(
Effect.map((pairingLinks) => {
const activeLinks: Array<AuthPairingLink> = [];
for (const pairingLink of pairingLinks) {
if (input?.role && pairingLink.role !== input.role) {
continue;
}
if (input?.excludeSubjects?.includes(pairingLink.subject)) {
continue;
}
activeLinks.push(
Effect.map((pairingLinks) =>
pairingLinks
.filter((pairingLink) => (input?.role ? pairingLink.role === input.role : true))
.filter((pairingLink) => !input?.excludeSubjects?.includes(pairingLink.subject))
.map((pairingLink) =>
pairingLink.label
? ({
id: pairingLink.id,
@@ -92,12 +87,11 @@ export const makeAuthControlPlane = Effect.gen(function* () {
createdAt: pairingLink.createdAt,
expiresAt: pairingLink.expiresAt,
} satisfies AuthPairingLink),
);
}
return activeLinks.toSorted(
(left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds,
);
}),
)
.toSorted(
(left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds,
),
),
Effect.mapError(toAuthControlPlaneError("Failed to list pairing links.")),
);
@@ -1,5 +1,4 @@
import type { AuthPairingLink } from "@t3tools/contracts";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
@@ -47,7 +46,6 @@ const generatePairingToken = (): string => {
};
export const makeBootstrapCredentialService = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const config = yield* ServerConfig;
const pairingLinks = yield* AuthPairingLinkRepository;
const seededGrantsRef = yield* Ref.make(new Map<string, StoredBootstrapGrant>());
@@ -143,7 +141,7 @@ export const makeBootstrapCredentialService = Effect.gen(function* () {
const issueOneTimeToken: BootstrapCredentialServiceShape["issueOneTimeToken"] = (input) =>
Effect.gen(function* () {
const id = yield* crypto.randomUUIDv4;
const id = crypto.randomUUID();
const credential = generatePairingToken();
const ttl = input?.ttl ?? DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES;
const now = yield* DateTime.now;
@@ -1,6 +1,5 @@
import { AuthSessionId, type AuthClientMetadata, type AuthClientSession } from "@t3tools/contracts";
import * as Clock from "effect/Clock";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
@@ -91,7 +90,6 @@ function toAuthClientSession(input: Omit<AuthClientSession, "current">): AuthCli
}
export const makeSessionCredentialService = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const serverConfig = yield* ServerConfig;
const secretStore = yield* ServerSecretStore;
const authSessions = yield* AuthSessionRepository;
@@ -205,7 +203,7 @@ export const makeSessionCredentialService = Effect.gen(function* () {
const encodeClaims = Schema.encodeEffect(Schema.fromJsonString(SessionClaims));
const issue: SessionCredentialServiceShape["issue"] = (input) =>
Effect.gen(function* () {
const sessionId = AuthSessionId.make(yield* crypto.randomUUIDv4);
const sessionId = AuthSessionId.make(crypto.randomUUID());
const issuedAt = yield* DateTime.now;
const expiresAt = DateTime.add(issuedAt, {
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),
@@ -69,5 +69,5 @@ export interface AuthControlPlaneShape {
}
export class AuthControlPlane extends Context.Service<AuthControlPlane, AuthControlPlaneShape>()(
"t3/auth/Services/AuthControlPlane",
"t3/AuthControlPlane",
) {}
+1 -1
View File
@@ -1,4 +1,4 @@
// @effect-diagnostics nodeBuiltinImport:off - CLI integration exercises Node HTTP and filesystem boundaries.
// @effect-diagnostics-next-line nodeBuiltinImport:off - NodeHttpServer.layer takes `NodeHttp.createServer` as arg
import * as NodeHttp from "node:http";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
@@ -41,110 +41,11 @@ function makeThreadCheckpointContext(input: {
}
describe("CheckpointDiffQueryLive", () => {
it("uses the narrow full-thread context lookup for all-turns diffs", async () => {
const projectId = ProjectId.make("project-full-thread");
const threadId = ThreadId.make("thread-full-thread");
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 4);
let getThreadCheckpointContextCalls = 0;
let getFullThreadDiffContextCalls = 0;
const diffCheckpointsCalls: Array<{
readonly fromCheckpointRef: CheckpointRef;
readonly toCheckpointRef: CheckpointRef;
readonly cwd: string;
readonly ignoreWhitespace: boolean;
}> = [];
const checkpointStore: CheckpointStoreShape = {
isGitRepository: () => Effect.succeed(true),
captureCheckpoint: () => Effect.void,
hasCheckpointRef: () => Effect.succeed(true),
restoreCheckpoint: () => Effect.succeed(true),
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd, ignoreWhitespace }) =>
Effect.sync(() => {
diffCheckpointsCalls.push({
fromCheckpointRef,
toCheckpointRef,
cwd,
ignoreWhitespace,
});
return "full thread diff patch";
}),
deleteCheckpointRefs: () => Effect.void,
};
const layer = CheckpointDiffQueryLive.pipe(
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery, {
getCommandReadModel: () =>
Effect.die("CheckpointDiffQuery should not request the command read model"),
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getProjectShellById: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () =>
Effect.sync(() => {
getThreadCheckpointContextCalls += 1;
return Option.none();
}),
getFullThreadDiffContext: () =>
Effect.sync(() => {
getFullThreadDiffContextCalls += 1;
return Option.some({
threadId,
projectId,
workspaceRoot: "/tmp/workspace",
worktreePath: "/tmp/worktree",
latestCheckpointTurnCount: 4,
toCheckpointRef,
});
}),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
}),
),
);
const result = await Effect.runPromise(
Effect.gen(function* () {
const query = yield* CheckpointDiffQuery;
return yield* query.getFullThreadDiff({
threadId,
toTurnCount: 4,
ignoreWhitespace: true,
});
}).pipe(Effect.provide(layer)),
);
expect(getThreadCheckpointContextCalls).toBe(0);
expect(getFullThreadDiffContextCalls).toBe(1);
expect(diffCheckpointsCalls).toEqual([
{
cwd: "/tmp/worktree",
fromCheckpointRef: checkpointRefForThreadTurn(threadId, 0),
toCheckpointRef,
ignoreWhitespace: true,
},
]);
expect(result).toEqual({
threadId,
fromTurnCount: 0,
toTurnCount: 4,
diff: "full thread diff patch",
});
});
it("computes diffs using canonical turn-0 checkpoint refs", async () => {
const projectId = ProjectId.make("project-1");
const threadId = ThreadId.make("thread-1");
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
const hasCheckpointRefCalls: Array<CheckpointRef> = [];
const diffCheckpointsCalls: Array<{
readonly fromCheckpointRef: CheckpointRef;
readonly toCheckpointRef: CheckpointRef;
@@ -164,7 +65,11 @@ describe("CheckpointDiffQueryLive", () => {
const checkpointStore: CheckpointStoreShape = {
isGitRepository: () => Effect.succeed(true),
captureCheckpoint: () => Effect.void,
hasCheckpointRef: () => Effect.succeed(true),
hasCheckpointRef: ({ checkpointRef }) =>
Effect.sync(() => {
hasCheckpointRefCalls.push(checkpointRef);
return true;
}),
restoreCheckpoint: () => Effect.succeed(true),
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd, ignoreWhitespace }) =>
Effect.sync(() => {
@@ -197,7 +102,6 @@ describe("CheckpointDiffQueryLive", () => {
getProjectShellById: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
}),
@@ -217,6 +121,7 @@ describe("CheckpointDiffQueryLive", () => {
);
const expectedFromRef = checkpointRefForThreadTurn(threadId, 0);
expect(hasCheckpointRefCalls).toEqual([expectedFromRef, toCheckpointRef]);
expect(diffCheckpointsCalls).toEqual([
{
cwd: "/tmp/workspace",
@@ -279,7 +184,6 @@ describe("CheckpointDiffQueryLive", () => {
getProjectShellById: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
}),
@@ -300,74 +204,6 @@ describe("CheckpointDiffQueryLive", () => {
expect(diffCheckpointsCalls).toEqual([{ ignoreWhitespace: true }]);
});
it("does not preflight checkpoint refs before diffing", async () => {
const projectId = ProjectId.make("project-no-preflight");
const threadId = ThreadId.make("thread-no-preflight");
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
let hasCheckpointRefCallCount = 0;
const threadCheckpointContext = makeThreadCheckpointContext({
projectId,
threadId,
workspaceRoot: "/tmp/workspace",
worktreePath: null,
checkpointTurnCount: 1,
checkpointRef: toCheckpointRef,
});
const checkpointStore: CheckpointStoreShape = {
isGitRepository: () => Effect.succeed(true),
captureCheckpoint: () => Effect.void,
hasCheckpointRef: () =>
Effect.sync(() => {
hasCheckpointRefCallCount += 1;
return true;
}),
restoreCheckpoint: () => Effect.succeed(true),
diffCheckpoints: () => Effect.succeed("diff patch"),
deleteCheckpointRefs: () => Effect.void,
};
const layer = CheckpointDiffQueryLive.pipe(
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery, {
getCommandReadModel: () =>
Effect.die("CheckpointDiffQuery should not request the command read model"),
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getProjectShellById: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
}),
),
);
await Effect.runPromise(
Effect.gen(function* () {
const query = yield* CheckpointDiffQuery;
return yield* query.getTurnDiff({
threadId,
fromTurnCount: 0,
toTurnCount: 1,
ignoreWhitespace: true,
});
}).pipe(Effect.provide(layer)),
);
expect(hasCheckpointRefCallCount).toBe(0);
});
it("fails when the thread is missing from the snapshot", async () => {
const threadId = ThreadId.make("thread-missing");
@@ -398,7 +234,6 @@ describe("CheckpointDiffQueryLive", () => {
getProjectShellById: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
}),
@@ -1,7 +1,6 @@
import {
type CheckpointRef,
OrchestrationGetTurnDiffResult,
type ThreadId,
type OrchestrationGetFullThreadDiffInput,
type OrchestrationGetFullThreadDiffResult,
type OrchestrationGetTurnDiffResult as OrchestrationGetTurnDiffResultType,
} from "@t3tools/contracts";
@@ -21,22 +20,6 @@ import {
const isTurnDiffResult = Schema.is(OrchestrationGetTurnDiffResult);
function buildTurnDiffResult(
input: {
readonly threadId: ThreadId;
readonly fromTurnCount: number;
readonly toTurnCount: number;
},
diff: string,
): OrchestrationGetTurnDiffResultType {
return {
threadId: input.threadId,
fromTurnCount: input.fromTurnCount,
toTurnCount: input.toTurnCount,
diff,
};
}
const make = Effect.gen(function* () {
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const checkpointStore = yield* CheckpointStore;
@@ -45,12 +28,6 @@ const make = Effect.gen(function* () {
function* (input) {
const operation = "CheckpointDiffQuery.getTurnDiff";
const ignoreWhitespace = input.ignoreWhitespace ?? true;
yield* Effect.annotateCurrentSpan({
"checkpoint.thread_id": input.threadId,
"checkpoint.from_turn_count": input.fromTurnCount,
"checkpoint.to_turn_count": input.toTurnCount,
"checkpoint.ignore_whitespace": ignoreWhitespace,
});
if (input.fromTurnCount === input.toTurnCount) {
const emptyDiff: OrchestrationGetTurnDiffResultType = {
@@ -68,9 +45,9 @@ const make = Effect.gen(function* () {
return emptyDiff;
}
const threadContext = yield* projectionSnapshotQuery
.getThreadCheckpointContext(input.threadId)
.pipe(Effect.withSpan("checkpoint.turnDiff.lookupContext"));
const threadContext = yield* projectionSnapshotQuery.getThreadCheckpointContext(
input.threadId,
);
if (Option.isNone(threadContext)) {
return yield* new CheckpointInvariantError({
operation,
@@ -123,17 +100,50 @@ const make = Effect.gen(function* () {
});
}
const diff = yield* checkpointStore
.diffCheckpoints({
cwd: workspaceCwd,
fromCheckpointRef,
toCheckpointRef,
fallbackFromToHead: false,
ignoreWhitespace,
})
.pipe(Effect.withSpan("checkpoint.turnDiff.diffCheckpoints"));
const [fromExists, toExists] = yield* Effect.all(
[
checkpointStore.hasCheckpointRef({
cwd: workspaceCwd,
checkpointRef: fromCheckpointRef,
}),
checkpointStore.hasCheckpointRef({
cwd: workspaceCwd,
checkpointRef: toCheckpointRef,
}),
],
{ concurrency: "unbounded" },
);
const turnDiff = buildTurnDiffResult(input, diff);
if (!fromExists) {
return yield* new CheckpointUnavailableError({
threadId: input.threadId,
turnCount: input.fromTurnCount,
detail: `Filesystem checkpoint is unavailable for turn ${input.fromTurnCount}.`,
});
}
if (!toExists) {
return yield* new CheckpointUnavailableError({
threadId: input.threadId,
turnCount: input.toTurnCount,
detail: `Filesystem checkpoint is unavailable for turn ${input.toTurnCount}.`,
});
}
const diff = yield* checkpointStore.diffCheckpoints({
cwd: workspaceCwd,
fromCheckpointRef,
toCheckpointRef,
fallbackFromToHead: false,
ignoreWhitespace,
});
const turnDiff: OrchestrationGetTurnDiffResultType = {
threadId: input.threadId,
fromTurnCount: input.fromTurnCount,
toTurnCount: input.toTurnCount,
diff,
};
if (!isTurnDiffResult(turnDiff)) {
return yield* new CheckpointInvariantError({
operation,
@@ -145,99 +155,15 @@ const make = Effect.gen(function* () {
},
);
const getFullThreadDiff: CheckpointDiffQueryShape["getFullThreadDiff"] = Effect.fn(
"CheckpointDiffQuery.getFullThreadDiff",
)(function* (input) {
const operation = "CheckpointDiffQuery.getFullThreadDiff";
const ignoreWhitespace = input.ignoreWhitespace ?? true;
yield* Effect.annotateCurrentSpan({
"checkpoint.thread_id": input.threadId,
"checkpoint.from_turn_count": 0,
"checkpoint.to_turn_count": input.toTurnCount,
"checkpoint.ignore_whitespace": ignoreWhitespace,
"checkpoint.diff_kind": "full-thread",
});
if (input.toTurnCount === 0) {
const emptyDiff = buildTurnDiffResult(
{
threadId: input.threadId,
fromTurnCount: 0,
toTurnCount: 0,
},
"",
);
if (!isTurnDiffResult(emptyDiff)) {
return yield* new CheckpointInvariantError({
operation,
detail: "Computed full thread diff result does not satisfy contract schema.",
});
}
return emptyDiff satisfies OrchestrationGetFullThreadDiffResult;
}
const threadContext = yield* projectionSnapshotQuery
.getFullThreadDiffContext(input.threadId, input.toTurnCount)
.pipe(Effect.withSpan("checkpoint.fullThread.lookupContext"));
if (Option.isNone(threadContext)) {
return yield* new CheckpointInvariantError({
operation,
detail: `Thread '${input.threadId}' not found.`,
});
}
if (input.toTurnCount > threadContext.value.latestCheckpointTurnCount) {
return yield* new CheckpointUnavailableError({
threadId: input.threadId,
turnCount: input.toTurnCount,
detail: `Turn diff range exceeds current turn count: requested ${input.toTurnCount}, current ${threadContext.value.latestCheckpointTurnCount}.`,
});
}
const workspaceCwd = threadContext.value.worktreePath ?? threadContext.value.workspaceRoot;
if (!workspaceCwd) {
return yield* new CheckpointInvariantError({
operation,
detail: `Workspace path missing for thread '${input.threadId}' when computing full thread diff.`,
});
}
if (!threadContext.value.toCheckpointRef) {
return yield* new CheckpointUnavailableError({
threadId: input.threadId,
turnCount: input.toTurnCount,
detail: `Checkpoint ref is unavailable for turn ${input.toTurnCount}.`,
});
}
const diff = yield* checkpointStore
.diffCheckpoints({
cwd: workspaceCwd,
fromCheckpointRef: checkpointRefForThreadTurn(input.threadId, 0),
toCheckpointRef: threadContext.value.toCheckpointRef as CheckpointRef,
fallbackFromToHead: false,
ignoreWhitespace,
})
.pipe(Effect.withSpan("checkpoint.fullThread.diffCheckpoints"));
const turnDiff = buildTurnDiffResult(
{
threadId: input.threadId,
fromTurnCount: 0,
toTurnCount: input.toTurnCount,
},
diff,
);
if (!isTurnDiffResult(turnDiff)) {
return yield* new CheckpointInvariantError({
operation,
detail: "Computed full thread diff result does not satisfy contract schema.",
});
}
return turnDiff satisfies OrchestrationGetFullThreadDiffResult;
});
const getFullThreadDiff: CheckpointDiffQueryShape["getFullThreadDiff"] = (
input: OrchestrationGetFullThreadDiffInput,
) =>
getTurnDiff({
threadId: input.threadId,
fromTurnCount: 0,
toTurnCount: input.toTurnCount,
ignoreWhitespace: input.ignoreWhitespace ?? true,
}).pipe(Effect.map((result): OrchestrationGetFullThreadDiffResult => result));
return {
getTurnDiff,
@@ -1,79 +1,304 @@
/**
* CheckpointStoreLive - Filesystem checkpoint store adapter layer.
*
* Resolves the active VCS driver once per checkpoint operation and delegates
* checkpoint-specific behavior to the driver's optional checkpoint capability.
* Implements hidden Git-ref checkpoint capture/restore directly with
* Effect-native child process execution (`effect/unstable/process`).
*
* This layer owns filesystem/Git interactions only; it does not persist
* checkpoint metadata and does not coordinate provider rollback semantics.
*
* @module CheckpointStoreLive
*/
import { randomUUID } from "node:crypto";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
import { VcsUnsupportedOperationError } from "@t3tools/contracts";
import { CheckpointInvariantError } from "../Errors.ts";
import { VcsProcessExitError } from "@t3tools/contracts";
import { VcsDriverRegistry } from "../../vcs/VcsDriverRegistry.ts";
import type { VcsCheckpointOps } from "../../vcs/VcsDriver.ts";
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
import { CheckpointRef } from "@t3tools/contracts";
const CHECKPOINT_DIFF_MAX_OUTPUT_BYTES = 10_000_000;
const makeCheckpointStore = Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const vcsRegistry = yield* VcsDriverRegistry;
const vcs = {
execute: (input: {
readonly operation: string;
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly stdin?: string;
readonly env?: NodeJS.ProcessEnv;
readonly allowNonZeroExit?: boolean;
readonly timeoutMs?: number;
readonly maxOutputBytes?: number;
readonly truncateOutputAtMaxBytes?: boolean;
}) =>
vcsRegistry
.resolve({ cwd: input.cwd, requestedKind: "git" })
.pipe(Effect.flatMap((handle) => handle.driver.execute(input))),
};
const resolveCheckpoints = Effect.fn("CheckpointStore.resolveCheckpoints")(function* (
operation: string,
cwd: string,
) {
const handle = yield* vcsRegistry.resolve({ cwd });
if (!handle.driver.checkpoints) {
return yield* new VcsUnsupportedOperationError({
operation,
kind: handle.kind,
detail: `${handle.kind} driver does not implement checkpoint operations.`,
});
}
return handle.driver.checkpoints satisfies VcsCheckpointOps;
});
const resolveHeadCommit = (cwd: string) =>
vcs
.execute({
operation: "CheckpointStore.resolveHeadCommit",
cwd,
args: ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"],
allowNonZeroExit: true,
})
.pipe(
Effect.map((result) => {
if (result.exitCode !== 0) {
return null;
}
const commit = result.stdout.trim();
return commit.length > 0 ? commit : null;
}),
);
const hasHeadCommit = (cwd: string) =>
vcs
.execute({
operation: "CheckpointStore.hasHeadCommit",
cwd,
args: ["rev-parse", "--verify", "HEAD"],
allowNonZeroExit: true,
})
.pipe(Effect.map((result) => result.exitCode === 0));
const resolveCheckpointCommit = (cwd: string, checkpointRef: CheckpointRef) =>
vcs
.execute({
operation: "CheckpointStore.resolveCheckpointCommit",
cwd,
args: ["rev-parse", "--verify", "--quiet", `${checkpointRef}^{commit}`],
allowNonZeroExit: true,
})
.pipe(
Effect.map((result) => {
if (result.exitCode !== 0) {
return null;
}
const commit = result.stdout.trim();
return commit.length > 0 ? commit : null;
}),
);
const isGitRepository: CheckpointStoreShape["isGitRepository"] = (cwd) =>
vcsRegistry.resolve({ cwd, requestedKind: "git" }).pipe(
Effect.map(() => true),
Effect.catch(() => Effect.succeed(false)),
);
vcs
.execute({
operation: "CheckpointStore.isGitRepository",
cwd,
args: ["rev-parse", "--is-inside-work-tree"],
allowNonZeroExit: true,
})
.pipe(
Effect.map((result) => result.exitCode === 0 && result.stdout.trim() === "true"),
Effect.catch(() => Effect.succeed(false)),
);
const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = Effect.fn(
"captureCheckpoint",
)(function* (input) {
const checkpoints = yield* resolveCheckpoints("CheckpointStore.captureCheckpoint", input.cwd);
return yield* checkpoints.captureCheckpoint(input);
const operation = "CheckpointStore.captureCheckpoint";
yield* Effect.acquireUseRelease(
fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }),
Effect.fn("captureCheckpoint.withTempDirectory")(function* (tempDir) {
const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
const commitEnv: NodeJS.ProcessEnv = {
...process.env,
GIT_INDEX_FILE: tempIndexPath,
GIT_AUTHOR_NAME: "T3 Code",
GIT_AUTHOR_EMAIL: "[email protected]",
GIT_COMMITTER_NAME: "T3 Code",
GIT_COMMITTER_EMAIL: "[email protected]",
};
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["read-tree", "HEAD"],
env: commitEnv,
});
}
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["add", "-A", "--", "."],
env: commitEnv,
});
const writeTreeResult = yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["write-tree"],
env: commitEnv,
});
const treeOid = writeTreeResult.stdout.trim();
if (treeOid.length === 0) {
return yield* new VcsProcessExitError({
operation,
command: "git write-tree",
cwd: input.cwd,
exitCode: 0,
detail: "git write-tree returned an empty tree oid.",
});
}
const message = `t3 checkpoint ref=${input.checkpointRef}`;
const commitTreeResult = yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["commit-tree", treeOid, "-m", message],
env: commitEnv,
});
const commitOid = commitTreeResult.stdout.trim();
if (commitOid.length === 0) {
return yield* new VcsProcessExitError({
operation,
command: "git commit-tree",
cwd: input.cwd,
exitCode: 0,
detail: "git commit-tree returned an empty commit oid.",
});
}
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["update-ref", input.checkpointRef, commitOid],
});
}),
(tempDir) => fs.remove(tempDir, { recursive: true }),
).pipe(
Effect.catchTags({
PlatformError: (error) =>
Effect.fail(
new CheckpointInvariantError({
operation: "CheckpointStore.captureCheckpoint",
detail: "Failed to capture checkpoint.",
cause: error,
}),
),
}),
);
});
const hasCheckpointRef: CheckpointStoreShape["hasCheckpointRef"] = Effect.fn("hasCheckpointRef")(
function* (input) {
const checkpoints = yield* resolveCheckpoints("CheckpointStore.hasCheckpointRef", input.cwd);
return yield* checkpoints.hasCheckpointRef(input);
},
);
const hasCheckpointRef: CheckpointStoreShape["hasCheckpointRef"] = (input) =>
resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
Effect.map((commit) => commit !== null),
);
const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = Effect.fn(
"restoreCheckpoint",
)(function* (input) {
const checkpoints = yield* resolveCheckpoints("CheckpointStore.restoreCheckpoint", input.cwd);
return yield* checkpoints.restoreCheckpoint(input);
const operation = "CheckpointStore.restoreCheckpoint";
let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
if (!commitOid && input.fallbackToHead === true) {
commitOid = yield* resolveHeadCommit(input.cwd);
}
if (!commitOid) {
return false;
}
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
});
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["clean", "-fd", "--", "."],
});
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["reset", "--quiet", "--", "."],
});
}
return true;
});
const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = Effect.fn("diffCheckpoints")(
function* (input) {
const checkpoints = yield* resolveCheckpoints("CheckpointStore.diffCheckpoints", input.cwd);
return yield* checkpoints.diffCheckpoints(input);
const operation = "CheckpointStore.diffCheckpoints";
let fromCommitOid = yield* resolveCheckpointCommit(input.cwd, input.fromCheckpointRef);
const toCommitOid = yield* resolveCheckpointCommit(input.cwd, input.toCheckpointRef);
if (!fromCommitOid && input.fallbackFromToHead === true) {
const headCommit = yield* resolveHeadCommit(input.cwd);
if (headCommit) {
fromCommitOid = headCommit;
}
}
if (!fromCommitOid || !toCommitOid) {
return yield* new VcsProcessExitError({
operation,
command: "git diff",
cwd: input.cwd,
exitCode: 1,
detail: "Checkpoint ref is unavailable for diff operation.",
});
}
const diffArgs = [
"diff",
"--patch",
"--minimal",
"--no-color",
...(input.ignoreWhitespace ? ["--ignore-all-space"] : []),
fromCommitOid,
toCommitOid,
];
const result = yield* vcs.execute({
operation,
cwd: input.cwd,
args: diffArgs,
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
});
return result.stdout;
},
);
const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = Effect.fn(
"deleteCheckpointRefs",
)(function* (input) {
const checkpoints = yield* resolveCheckpoints(
"CheckpointStore.deleteCheckpointRefs",
input.cwd,
const operation = "CheckpointStore.deleteCheckpointRefs";
yield* Effect.forEach(
input.checkpointRefs,
(checkpointRef) =>
vcs.execute({
operation,
cwd: input.cwd,
args: ["update-ref", "-d", checkpointRef],
allowNonZeroExit: true,
}),
{ discard: true },
);
return yield* checkpoints.deleteCheckpointRefs(input);
});
return {
+5 -16
View File
@@ -5,7 +5,6 @@ import {
type ClientOrchestrationCommand,
} from "@t3tools/contracts";
import * as Console from "effect/Console";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
@@ -59,16 +58,6 @@ class ProjectCommandError extends Data.TaggedError("ProjectCommandError")<{
readonly message: string;
}> {}
const projectCommandUuid = Crypto.Crypto.pipe(
Effect.flatMap((crypto) => crypto.randomUUIDv4),
Effect.mapError(
() =>
new ProjectCommandError({
message: "Failed to generate a project command identifier.",
}),
),
);
const ProjectCliRuntimeLive = Layer.mergeAll(
WorkspacePathsLive,
OrchestrationLayerLive.pipe(
@@ -271,7 +260,7 @@ const runProjectMutation = Effect.fn("runProjectMutation")(function* (
}) => Effect.Effect<
string,
Error,
Crypto.Crypto | FileSystem.FileSystem | HttpClient.HttpClient | Path.Path | WorkspacePaths
FileSystem.FileSystem | HttpClient.HttpClient | Path.Path | WorkspacePaths
>,
) {
const logLevel = yield* GlobalFlag.LogLevel;
@@ -354,10 +343,10 @@ const projectAddCommand = Command.make("add", {
}
const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));
const projectId = ProjectId.make(yield* projectCommandUuid);
const projectId = ProjectId.make(crypto.randomUUID());
yield* dispatch({
type: "project.create",
commandId: CommandId.make(yield* projectCommandUuid),
commandId: CommandId.make(crypto.randomUUID()),
projectId,
title,
workspaceRoot,
@@ -395,7 +384,7 @@ const projectRemoveCommand = Command.make("remove", {
});
yield* dispatch({
type: "project.delete",
commandId: CommandId.make(yield* projectCommandUuid),
commandId: CommandId.make(crypto.randomUUID()),
projectId: project.id,
});
return `Removed project ${project.id} (${project.title}).`;
@@ -435,7 +424,7 @@ const projectRenameCommand = Command.make("rename", {
yield* dispatch({
type: "project.meta.update",
commandId: CommandId.make(yield* projectCommandUuid),
commandId: CommandId.make(crypto.randomUUID()),
projectId: project.id,
title: nextTitle,
});
@@ -15,7 +15,7 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
export interface ProcessRow {
interface ProcessRow {
readonly pid: number;
readonly ppid: number;
readonly pgid: number | null;
@@ -186,7 +186,7 @@ function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
}
}
export function buildDescendantEntries(
function buildDescendantEntries(
rows: ReadonlyArray<ProcessRow>,
serverPid: number,
): ReadonlyArray<ServerProcessDiagnosticsEntry> {
@@ -230,7 +230,7 @@ export function buildDescendantEntries(
return entries;
}
export function isDiagnosticsQueryProcess(row: ProcessRow, serverPid: number): boolean {
function isDiagnosticsQueryProcess(row: ProcessRow, serverPid: number): boolean {
if (row.ppid !== serverPid) return false;
const command = row.command.trim();
@@ -370,7 +370,7 @@ function readWindowsProcessRows(): Effect.Effect<
);
}
export const readProcessRows = (platform = process.platform) =>
const readProcessRows = (platform = process.platform) =>
platform === "win32" ? readWindowsProcessRows() : readPosixProcessRows();
export function aggregateProcessDiagnostics(input: {
@@ -1,231 +0,0 @@
import { describe, expect, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import {
aggregateProcessResourceHistory,
collectMonitoredSamples,
} from "./ProcessResourceMonitor.ts";
describe("ProcessResourceMonitor", () => {
it.effect("samples the server root process and descendants", () =>
Effect.sync(() => {
const sampledAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
const samples = collectMonitoredSamples({
serverPid: 100,
sampledAt,
sampledAtMs: DateTime.toEpochMillis(sampledAt),
rows: [
{
pid: 100,
ppid: 1,
pgid: 100,
status: "S",
cpuPercent: 2,
rssBytes: 1_000,
elapsed: "01:00",
command: "t3 server",
},
{
pid: 101,
ppid: 100,
pgid: 100,
status: "S",
cpuPercent: 10,
rssBytes: 2_000,
elapsed: "00:20",
command: "codex app-server",
},
{
pid: 102,
ppid: 101,
pgid: 100,
status: "R",
cpuPercent: 50,
rssBytes: 3_000,
elapsed: "00:05",
command: "rg needle",
},
{
pid: 200,
ppid: 1,
pgid: 200,
status: "R",
cpuPercent: 99,
rssBytes: 9_000,
elapsed: "00:05",
command: "unrelated",
},
],
});
expect(samples.map((sample) => sample.pid)).toEqual([100, 101, 102]);
expect(samples.map((sample) => sample.depth)).toEqual([0, 1, 2]);
expect(samples[0]?.isServerRoot).toBe(true);
expect(samples[1]?.isServerRoot).toBe(false);
}),
);
it.effect("rolls samples up by process and CPU time", () =>
Effect.sync(() => {
const firstAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
const secondAt = DateTime.makeUnsafe("2026-05-05T10:00:05.000Z");
const samples = [
...collectMonitoredSamples({
serverPid: 100,
sampledAt: firstAt,
sampledAtMs: DateTime.toEpochMillis(firstAt),
rows: [
{
pid: 100,
ppid: 1,
pgid: 100,
status: "S",
cpuPercent: 10,
rssBytes: 1_000,
elapsed: "01:00",
command: "t3 server",
},
],
}),
...collectMonitoredSamples({
serverPid: 100,
sampledAt: secondAt,
sampledAtMs: DateTime.toEpochMillis(secondAt),
rows: [
{
pid: 100,
ppid: 1,
pgid: 100,
status: "S",
cpuPercent: 30,
rssBytes: 2_000,
elapsed: "01:05",
command: "t3 server",
},
],
}),
];
const result = aggregateProcessResourceHistory({
samples,
readAt: secondAt,
readAtMs: DateTime.toEpochMillis(secondAt),
windowMs: 60_000,
bucketMs: 10_000,
lastError: null,
});
expect(Option.isNone(result.error)).toBe(true);
expect(result.topProcesses).toHaveLength(1);
expect(result.topProcesses[0]?.avgCpuPercent).toBe(20);
expect(result.topProcesses[0]?.maxCpuPercent).toBe(30);
expect(result.topProcesses[0]?.cpuSecondsApprox).toBe(2);
expect(result.totalCpuSecondsApprox).toBe(2);
expect(result.buckets.some((bucket) => bucket.maxCpuPercent === 30)).toBe(true);
}),
);
it.effect("keeps a process grouped when elapsed time drifts between samples", () =>
Effect.sync(() => {
const firstAt = DateTime.makeUnsafe("2026-05-05T10:00:00.400Z");
const secondAt = DateTime.makeUnsafe("2026-05-05T10:00:05.900Z");
const samples = [
...collectMonitoredSamples({
serverPid: 100,
sampledAt: firstAt,
sampledAtMs: DateTime.toEpochMillis(firstAt),
rows: [
{
pid: 100,
ppid: 1,
pgid: 100,
status: "S",
cpuPercent: 1,
rssBytes: 1_000,
elapsed: "01:00",
command: "t3 server",
},
],
}),
...collectMonitoredSamples({
serverPid: 100,
sampledAt: secondAt,
sampledAtMs: DateTime.toEpochMillis(secondAt),
rows: [
{
pid: 100,
ppid: 1,
pgid: 100,
status: "S",
cpuPercent: 2,
rssBytes: 2_000,
elapsed: "01:06",
command: "t3 server",
},
],
}),
];
const result = aggregateProcessResourceHistory({
samples,
readAt: secondAt,
readAtMs: DateTime.toEpochMillis(secondAt),
windowMs: 60_000,
bucketMs: 10_000,
lastError: null,
});
expect(result.topProcesses).toHaveLength(1);
expect(result.topProcesses[0]?.isServerRoot).toBe(true);
expect(result.topProcesses[0]?.sampleCount).toBe(2);
expect(result.topProcesses[0]?.maxRssBytes).toBe(2_000);
}),
);
it.effect("returns all process summaries in the selected window", () =>
Effect.sync(() => {
const sampledAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
const samples = collectMonitoredSamples({
serverPid: 100,
sampledAt,
sampledAtMs: DateTime.toEpochMillis(sampledAt),
rows: [
{
pid: 100,
ppid: 1,
pgid: 100,
status: "S",
cpuPercent: 1,
rssBytes: 1_000,
elapsed: "01:00",
command: "t3 server",
},
...Array.from({ length: 35 }, (_, index) => ({
pid: 200 + index,
ppid: index === 0 ? 100 : 199 + index,
pgid: 100,
status: "S",
cpuPercent: 35 - index,
rssBytes: 2_000 + index,
elapsed: "00:10",
command: `worker ${index}`,
})),
],
});
const result = aggregateProcessResourceHistory({
samples,
readAt: sampledAt,
readAtMs: DateTime.toEpochMillis(sampledAt),
windowMs: 60_000,
bucketMs: 10_000,
lastError: null,
});
expect(result.topProcesses).toHaveLength(36);
expect(result.topProcesses.some((process) => process.command === "worker 34")).toBe(true);
}),
);
});
@@ -1,299 +0,0 @@
import type {
ServerProcessResourceHistoryBucket,
ServerProcessResourceHistoryInput,
ServerProcessResourceHistoryResult,
ServerProcessResourceHistorySummary,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import { ChildProcessSpawner } from "effect/unstable/process";
import {
buildDescendantEntries,
isDiagnosticsQueryProcess,
type ProcessRow,
readProcessRows,
} from "./ProcessDiagnostics.ts";
const SAMPLE_INTERVAL_MS = 5_000;
const RETENTION_MS = 60 * 60_000;
const MAX_RETAINED_SAMPLES = 20_000;
export interface ProcessResourceSample {
readonly sampledAt: DateTime.Utc;
readonly sampledAtMs: number;
readonly processKey: string;
readonly pid: number;
readonly ppid: number;
readonly command: string;
readonly cpuPercent: number;
readonly rssBytes: number;
readonly depth: number;
readonly isServerRoot: boolean;
}
interface MonitorState {
readonly samples: ReadonlyArray<ProcessResourceSample>;
readonly lastError: string | null;
}
export interface ProcessResourceMonitorShape {
readonly readHistory: (
input: ServerProcessResourceHistoryInput,
) => Effect.Effect<ServerProcessResourceHistoryResult>;
}
export class ProcessResourceMonitor extends Context.Service<
ProcessResourceMonitor,
ProcessResourceMonitorShape
>()("t3/diagnostics/ProcessResourceMonitor") {}
function dateTimeFromMillis(ms: number): DateTime.Utc {
return DateTime.makeUnsafe(ms);
}
function sampleKey(row: Pick<ProcessRow, "pid" | "command">): string {
return `${row.pid}:${row.command}`;
}
function findServerRootRow(rows: ReadonlyArray<ProcessRow>, serverPid: number): ProcessRow | null {
return rows.find((row) => row.pid === serverPid) ?? null;
}
export function collectMonitoredSamples(input: {
readonly rows: ReadonlyArray<ProcessRow>;
readonly serverPid: number;
readonly sampledAt: DateTime.Utc;
readonly sampledAtMs: number;
}): ReadonlyArray<ProcessResourceSample> {
const rows = input.rows.filter((row) => !isDiagnosticsQueryProcess(row, input.serverPid));
const root = findServerRootRow(rows, input.serverPid);
const descendants = buildDescendantEntries(rows, input.serverPid);
const samples: ProcessResourceSample[] = [];
if (root) {
samples.push({
sampledAt: input.sampledAt,
sampledAtMs: input.sampledAtMs,
processKey: sampleKey(root),
pid: root.pid,
ppid: root.ppid,
command: root.command,
cpuPercent: root.cpuPercent,
rssBytes: root.rssBytes,
depth: 0,
isServerRoot: true,
});
}
for (const process of descendants) {
samples.push({
sampledAt: input.sampledAt,
sampledAtMs: input.sampledAtMs,
processKey: sampleKey(process),
pid: process.pid,
ppid: process.ppid,
command: process.command,
cpuPercent: process.cpuPercent,
rssBytes: process.rssBytes,
depth: process.depth + 1,
isServerRoot: false,
});
}
return samples;
}
function trimSamples(
samples: ReadonlyArray<ProcessResourceSample>,
nowMs: number,
): ReadonlyArray<ProcessResourceSample> {
const minSampledAtMs = nowMs - RETENTION_MS;
const retained = samples.filter((sample) => sample.sampledAtMs >= minSampledAtMs);
return retained.length <= MAX_RETAINED_SAMPLES
? retained
: retained.slice(retained.length - MAX_RETAINED_SAMPLES);
}
function summarizeProcesses(
samples: ReadonlyArray<ProcessResourceSample>,
): ReadonlyArray<ServerProcessResourceHistorySummary> {
const groups = new Map<string, ProcessResourceSample[]>();
for (const sample of samples) {
const processSamples = groups.get(sample.processKey) ?? [];
processSamples.push(sample);
groups.set(sample.processKey, processSamples);
}
return [...groups.entries()]
.map(([processKey, processSamples]) => {
const sorted = processSamples.toSorted((left, right) => left.sampledAtMs - right.sampledAtMs);
const first = sorted[0]!;
const latest = sorted[sorted.length - 1]!;
const cpuPercentTotal = sorted.reduce((total, sample) => total + sample.cpuPercent, 0);
const maxCpuPercent = Math.max(...sorted.map((sample) => sample.cpuPercent));
const maxRssBytes = Math.max(...sorted.map((sample) => sample.rssBytes));
const cpuSecondsApprox = sorted.reduce(
(total, sample) => total + (sample.cpuPercent / 100) * (SAMPLE_INTERVAL_MS / 1_000),
0,
);
return {
processKey,
pid: latest.pid,
ppid: latest.ppid,
command: latest.command,
depth: latest.depth,
isServerRoot: latest.isServerRoot,
firstSeenAt: first.sampledAt,
lastSeenAt: latest.sampledAt,
currentCpuPercent: latest.cpuPercent,
avgCpuPercent: cpuPercentTotal / sorted.length,
maxCpuPercent,
cpuSecondsApprox,
currentRssBytes: latest.rssBytes,
maxRssBytes,
sampleCount: sorted.length,
} satisfies ServerProcessResourceHistorySummary;
})
.toSorted((left, right) => right.cpuSecondsApprox - left.cpuSecondsApprox);
}
function buildBuckets(input: {
readonly samples: ReadonlyArray<ProcessResourceSample>;
readonly nowMs: number;
readonly windowMs: number;
readonly bucketMs: number;
}): ReadonlyArray<ServerProcessResourceHistoryBucket> {
const bucketMs = Math.max(1_000, input.bucketMs);
const windowStartMs = input.nowMs - input.windowMs;
const buckets: ServerProcessResourceHistoryBucket[] = [];
for (let startedAtMs = windowStartMs; startedAtMs < input.nowMs; startedAtMs += bucketMs) {
const endedAtMs = Math.min(input.nowMs, startedAtMs + bucketMs);
const bucketSamples = input.samples.filter(
(sample) =>
sample.sampledAtMs >= startedAtMs &&
(endedAtMs === input.nowMs
? sample.sampledAtMs <= endedAtMs
: sample.sampledAtMs < endedAtMs),
);
const samplesByRead = new Map<number, ProcessResourceSample[]>();
for (const sample of bucketSamples) {
const samplesAtTime = samplesByRead.get(sample.sampledAtMs) ?? [];
samplesAtTime.push(sample);
samplesByRead.set(sample.sampledAtMs, samplesAtTime);
}
const readTotals = [...samplesByRead.values()].map((samplesAtTime) => ({
cpuPercent: samplesAtTime.reduce((total, sample) => total + sample.cpuPercent, 0),
rssBytes: samplesAtTime.reduce((total, sample) => total + sample.rssBytes, 0),
processCount: samplesAtTime.length,
}));
const avgCpuPercent =
readTotals.length === 0
? 0
: readTotals.reduce((total, read) => total + read.cpuPercent, 0) / readTotals.length;
buckets.push({
startedAt: dateTimeFromMillis(startedAtMs),
endedAt: dateTimeFromMillis(endedAtMs),
avgCpuPercent,
maxCpuPercent: readTotals.length ? Math.max(...readTotals.map((read) => read.cpuPercent)) : 0,
maxRssBytes: readTotals.length ? Math.max(...readTotals.map((read) => read.rssBytes)) : 0,
maxProcessCount: readTotals.length
? Math.max(...readTotals.map((read) => read.processCount))
: 0,
});
}
return buckets;
}
export function aggregateProcessResourceHistory(input: {
readonly samples: ReadonlyArray<ProcessResourceSample>;
readonly readAt: DateTime.Utc;
readonly readAtMs: number;
readonly windowMs: number;
readonly bucketMs: number;
readonly lastError: string | null;
}): ServerProcessResourceHistoryResult {
const windowMs = Math.max(1_000, input.windowMs);
const bucketMs = Math.max(1_000, input.bucketMs);
const minSampledAtMs = input.readAtMs - windowMs;
const samples = input.samples.filter((sample) => sample.sampledAtMs >= minSampledAtMs);
const topProcesses = summarizeProcesses(samples);
const totalCpuSecondsApprox = samples.reduce(
(total, sample) => total + (sample.cpuPercent / 100) * (SAMPLE_INTERVAL_MS / 1_000),
0,
);
return {
readAt: input.readAt,
windowMs,
bucketMs,
sampleIntervalMs: SAMPLE_INTERVAL_MS,
retainedSampleCount: input.samples.length,
totalCpuSecondsApprox,
buckets: buildBuckets({ samples, nowMs: input.readAtMs, windowMs, bucketMs }),
topProcesses,
error: input.lastError ? Option.some({ message: input.lastError }) : Option.none(),
};
}
export const make = Effect.fn("makeProcessResourceMonitor")(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const state = yield* Ref.make<MonitorState>({ samples: [], lastError: null });
const sampleOnce = Effect.gen(function* () {
const sampledAt = yield* DateTime.now;
const sampledAtMs = DateTime.toEpochMillis(sampledAt);
const rows = yield* readProcessRows().pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
const samples = collectMonitoredSamples({
rows,
serverPid: process.pid,
sampledAt,
sampledAtMs,
});
yield* Ref.update(state, (current) => ({
samples: trimSamples([...current.samples, ...samples], sampledAtMs),
lastError: null,
}));
}).pipe(
Effect.catch((error: unknown) =>
Ref.update(state, (current) => ({
...current,
lastError: error instanceof Error ? error.message : "Failed to sample process resources.",
})),
),
);
yield* Effect.forever(sampleOnce.pipe(Effect.andThen(Effect.sleep(SAMPLE_INTERVAL_MS)))).pipe(
Effect.forkScoped,
);
const readHistory: ProcessResourceMonitorShape["readHistory"] = (input) =>
Effect.gen(function* () {
const readAt = yield* DateTime.now;
const readAtMs = DateTime.toEpochMillis(readAt);
const current = yield* Ref.get(state);
return aggregateProcessResourceHistory({
samples: current.samples,
readAt,
readAtMs,
windowMs: input.windowMs,
bucketMs: input.bucketMs,
lastError: current.lastError,
});
});
return ProcessResourceMonitor.of({ readHistory });
});
export const layer = Layer.effect(ProcessResourceMonitor, make());
@@ -1,12 +1,11 @@
import { EnvironmentId, type ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
import * as Crypto from "effect/Crypto";
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 { ServerConfig } from "../../config.ts";
import { layer as ProcessRunnerLive } from "../../processRunner.ts";
import { ServerEnvironment, type ServerEnvironmentShape } from "../Services/ServerEnvironment.ts";
import packageJson from "../../../package.json" with { type: "json" };
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
@@ -39,7 +38,6 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const serverConfig = yield* ServerConfig;
const crypto = yield* Crypto.Crypto;
const readPersistedEnvironmentId = Effect.gen(function* () {
const exists = yield* fileSystem
@@ -65,7 +63,7 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function
return persisted;
}
const generated = yield* crypto.randomUUIDv4;
const generated = yield* Random.nextUUIDv4;
yield* persistEnvironmentId(generated);
return generated;
});
@@ -95,6 +93,4 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function
} satisfies ServerEnvironmentShape;
});
export const ServerEnvironmentLive = Layer.effect(ServerEnvironment, makeServerEnvironment()).pipe(
Layer.provide(ProcessRunnerLive),
);
export const ServerEnvironmentLive = Layer.effect(ServerEnvironment, makeServerEnvironment());
@@ -1,36 +1,20 @@
import { afterEach, describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import { vi } from "vitest";
import { ProcessRunner, ProcessSpawnError, type ProcessRunnerShape } from "../../processRunner.ts";
vi.mock("../../processRunner.ts", () => ({
runProcess: vi.fn(),
}));
import { runProcess } from "../../processRunner.ts";
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
import { ChildProcessSpawner } from "effect/unstable/process";
const runMock = vi.fn<ProcessRunnerShape["run"]>();
const ProcessRunnerTest = Layer.succeed(
ProcessRunner,
ProcessRunner.of({
run: (input) => runMock(input),
}),
);
const mockedRunProcess = vi.mocked(runProcess);
const NoopFileSystemLayer = FileSystem.layerNoop({});
const TestLayer = Layer.merge(NoopFileSystemLayer, ProcessRunnerTest);
const LinuxMachineInfoLayer = Layer.merge(
ProcessRunnerTest,
FileSystem.layerNoop({
exists: (path) => Effect.succeed(path === "/etc/machine-info"),
readFileString: (path) =>
path === "/etc/machine-info"
? Effect.succeed('PRETTY_HOSTNAME="Build Agent 01"\nICON_NAME="computer-vm"\n')
: Effect.succeed(""),
}),
);
afterEach(() => {
runMock.mockReset();
mockedRunProcess.mockReset();
});
describe("resolveServerEnvironmentLabel", () => {
@@ -40,7 +24,7 @@ describe("resolveServerEnvironmentLabel", () => {
cwdBaseName: "t3code",
platform: "win32",
hostname: "macbook-pro",
}).pipe(Effect.provide(TestLayer));
}).pipe(Effect.provide(NoopFileSystemLayer));
expect(result).toBe("macbook-pro");
}),
@@ -48,30 +32,25 @@ describe("resolveServerEnvironmentLabel", () => {
it.effect("prefers the macOS ComputerName", () =>
Effect.gen(function* () {
runMock.mockReturnValueOnce(
Effect.succeed({
stdout: " Julius's MacBook Pro \n",
stderr: "",
code: ChildProcessSpawner.ExitCode(0),
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
}),
);
mockedRunProcess.mockResolvedValueOnce({
stdout: " Julius's MacBook Pro \n",
stderr: "",
code: 0,
signal: null,
timedOut: false,
});
const result = yield* resolveServerEnvironmentLabel({
cwdBaseName: "t3code",
platform: "darwin",
hostname: "macbook-pro",
}).pipe(Effect.provide(TestLayer));
}).pipe(Effect.provide(NoopFileSystemLayer));
expect(result).toBe("Julius's MacBook Pro");
expect(runMock).toHaveBeenCalledWith(
expect.objectContaining({
command: "scutil",
args: ["--get", "ComputerName"],
timeoutBehavior: "timedOutResult",
}),
expect(mockedRunProcess).toHaveBeenCalledWith(
"scutil",
["--get", "ComputerName"],
expect.objectContaining({ allowNonZeroExit: true }),
);
}),
);
@@ -82,39 +61,44 @@ describe("resolveServerEnvironmentLabel", () => {
cwdBaseName: "t3code",
platform: "linux",
hostname: "buildbox",
}).pipe(Effect.provide(LinuxMachineInfoLayer));
}).pipe(
Effect.provide(
FileSystem.layerNoop({
exists: (path) => Effect.succeed(path === "/etc/machine-info"),
readFileString: (path) =>
path === "/etc/machine-info"
? Effect.succeed('PRETTY_HOSTNAME="Build Agent 01"\nICON_NAME="computer-vm"\n')
: Effect.succeed(""),
}),
),
);
expect(result).toBe("Build Agent 01");
expect(runMock).not.toHaveBeenCalled();
expect(mockedRunProcess).not.toHaveBeenCalled();
}),
);
it.effect("falls back to hostnamectl pretty hostname on Linux", () =>
Effect.gen(function* () {
runMock.mockReturnValueOnce(
Effect.succeed({
stdout: "CI Runner\n",
stderr: "",
code: ChildProcessSpawner.ExitCode(0),
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
}),
);
mockedRunProcess.mockResolvedValueOnce({
stdout: "CI Runner\n",
stderr: "",
code: 0,
signal: null,
timedOut: false,
});
const result = yield* resolveServerEnvironmentLabel({
cwdBaseName: "t3code",
platform: "linux",
hostname: "runner-01",
}).pipe(Effect.provide(TestLayer));
}).pipe(Effect.provide(NoopFileSystemLayer));
expect(result).toBe("CI Runner");
expect(runMock).toHaveBeenCalledWith(
expect.objectContaining({
command: "hostnamectl",
args: ["--pretty"],
timeoutBehavior: "timedOutResult",
}),
expect(mockedRunProcess).toHaveBeenCalledWith(
"hostnamectl",
["--pretty"],
expect.objectContaining({ allowNonZeroExit: true }),
);
}),
);
@@ -125,7 +109,7 @@ describe("resolveServerEnvironmentLabel", () => {
cwdBaseName: "t3code",
platform: "win32",
hostname: "JULIUS-LAPTOP",
}).pipe(Effect.provide(TestLayer));
}).pipe(Effect.provide(NoopFileSystemLayer));
expect(result).toBe("JULIUS-LAPTOP");
}),
@@ -133,21 +117,13 @@ describe("resolveServerEnvironmentLabel", () => {
it.effect("falls back to the hostname when the friendly-label command is missing", () =>
Effect.gen(function* () {
runMock.mockReturnValueOnce(
Effect.fail(
new ProcessSpawnError({
command: "scutil",
args: ["--get", "ComputerName"],
cause: new Error("spawn scutil ENOENT"),
}),
),
);
mockedRunProcess.mockRejectedValueOnce(new Error("spawn scutil ENOENT"));
const result = yield* resolveServerEnvironmentLabel({
cwdBaseName: "t3code",
platform: "darwin",
hostname: "macbook-pro",
}).pipe(Effect.provide(TestLayer));
}).pipe(Effect.provide(NoopFileSystemLayer));
expect(result).toBe("macbook-pro");
}),
@@ -155,22 +131,19 @@ describe("resolveServerEnvironmentLabel", () => {
it.effect("falls back to the cwd basename when the hostname is blank", () =>
Effect.gen(function* () {
runMock.mockReturnValueOnce(
Effect.succeed({
stdout: " ",
stderr: "",
code: ChildProcessSpawner.ExitCode(0),
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
}),
);
mockedRunProcess.mockResolvedValueOnce({
stdout: " ",
stderr: "",
code: 0,
signal: null,
timedOut: false,
});
const result = yield* resolveServerEnvironmentLabel({
cwdBaseName: "t3code",
platform: "linux",
hostname: " ",
}).pipe(Effect.provide(TestLayer));
}).pipe(Effect.provide(NoopFileSystemLayer));
expect(result).toBe("t3code");
}),
@@ -2,9 +2,8 @@ import * as OS from "node:os";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import { ProcessRunner } from "../../processRunner.ts";
import { runProcess } from "../../processRunner.ts";
interface ResolveServerEnvironmentLabelInput {
readonly cwdBaseName: string;
@@ -53,21 +52,19 @@ const runFriendlyLabelCommand = Effect.fn("runFriendlyLabelCommand")(function* (
command: string,
args: readonly string[],
) {
const processRunner = yield* ProcessRunner;
const result = yield* processRunner
.run({
command,
args,
timeoutBehavior: "timedOutResult",
shell: process.platform === "win32",
})
.pipe(Effect.option);
const result = yield* Effect.tryPromise({
try: () =>
runProcess(command, args, {
allowNonZeroExit: true,
}),
catch: () => null,
}).pipe(Effect.orElseSucceed(() => null));
if (Option.isNone(result) || result.value.code !== 0) {
if (!result || result.code !== 0) {
return null;
}
return normalizeLabel(result.value.stdout);
return normalizeLabel(result.stdout);
});
const resolveFriendlyHostLabel = Effect.fn("resolveFriendlyHostLabel")(function* (
+22 -28
View File
@@ -1,7 +1,8 @@
import { randomUUID } from "node:crypto";
import * as Arr from "effect/Array";
import * as Cache from "effect/Cache";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
@@ -531,39 +532,32 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const sourceControlProviders = yield* SourceControlProviderRegistry;
const textGeneration = yield* TextGeneration;
const projectSetupScriptRunner = yield* ProjectSetupScriptRunner;
const crypto = yield* Crypto.Crypto;
const sourceControlProvider = (cwd: string) => sourceControlProviders.resolve({ cwd });
const serverSettingsService = yield* ServerSettingsService;
const randomUUIDv4 = crypto.randomUUIDv4.pipe(
Effect.mapError((cause) =>
gitManagerError("randomUUIDv4", "Failed to generate Git operation identifier.", cause),
),
);
const createProgressEmitter = (
input: { cwd: string; action: GitStackedAction },
options?: GitRunStackedActionOptions,
) =>
(options?.actionId === undefined ? randomUUIDv4 : Effect.succeed(options.actionId)).pipe(
Effect.map((actionId) => {
const reporter = options?.progressReporter;
const emit = (event: GitActionProgressPayload) =>
reporter
? reporter.publish({
actionId,
cwd: input.cwd,
action: input.action,
...event,
} as GitActionProgressEvent)
: Effect.void;
) => {
const actionId = options?.actionId ?? randomUUID();
const reporter = options?.progressReporter;
return {
actionId,
emit,
};
}),
);
const emit = (event: GitActionProgressPayload) =>
reporter
? reporter.publish({
actionId,
cwd: input.cwd,
action: input.action,
...event,
} as GitActionProgressEvent)
: Effect.void;
return {
actionId,
emit,
};
};
const configurePullRequestHeadUpstreamBase = Effect.fn("configurePullRequestHeadUpstream")(
function* (
@@ -1307,7 +1301,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
modelSelection,
});
const bodyFile = path.join(tempDir, `t3code-pr-body-${process.pid}-${yield* randomUUIDv4}.md`);
const bodyFile = path.join(tempDir, `t3code-pr-body-${process.pid}-${randomUUID()}.md`);
yield* fileSystem
.writeFileString(bodyFile, generated.body)
.pipe(
@@ -1597,7 +1591,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fn("runStackedAction")(
function* (input, options) {
const progress = yield* createProgressEmitter(input, options);
const progress = createProgressEmitter(input, options);
const currentPhase = yield* Ref.make<Option.Option<GitActionProgressPhase>>(Option.none());
const runAction = Effect.fn("runStackedAction.runAction")(function* (): Effect.fn.Return<
+4 -8
View File
@@ -1,12 +1,8 @@
export function parseRemoteNamesInGitOrder(stdout: string): ReadonlyArray<string> {
const remoteNames: Array<string> = [];
for (const line of stdout.split("\n")) {
const remoteName = line.trim();
if (remoteName.length > 0) {
remoteNames.push(remoteName);
}
}
return remoteNames;
return stdout
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0);
}
export function parseRemoteNames(stdout: string): ReadonlyArray<string> {
+4 -7
View File
@@ -35,13 +35,10 @@ export function parseBase64DataUrl(
const match = /^data:([^,]+),([a-z0-9+/=\r\n ]+)$/i.exec(dataUrl.trim());
if (!match) return null;
const headerParts: Array<string> = [];
for (const part of (match[1] ?? "").split(";")) {
const trimmed = part.trim();
if (trimmed.length > 0) {
headerParts.push(trimmed);
}
}
const headerParts = (match[1] ?? "")
.split(";")
.map((part) => part.trim())
.filter((part) => part.length > 0);
if (headerParts.length < 2) {
return null;
}
+3 -6
View File
@@ -32,7 +32,6 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Predicate from "effect/Predicate";
import * as PubSub from "effect/PubSub";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import * as SchemaIssue from "effect/SchemaIssue";
import * as SchemaTransformation from "effect/SchemaTransformation";
@@ -539,11 +538,9 @@ const makeKeybindings = Effect.gen(function* () {
return;
}
const matchingDefaults = Array.filterMap(DEFAULT_KEYBINDINGS, (defaultRule) =>
customConfig.some((entry) => isSameKeybindingRule(entry, defaultRule))
? Result.succeed(defaultRule.command)
: Result.failVoid,
);
const matchingDefaults = DEFAULT_KEYBINDINGS.filter((defaultRule) =>
customConfig.some((entry) => isSameKeybindingRule(entry, defaultRule)),
).map((rule) => rule.command);
if (matchingDefaults.length > 0) {
yield* Effect.logWarning("default keybinding rule already defined in user config", {
path: keybindingsConfigPath,
@@ -18,7 +18,6 @@ const DEFAULT_RPC_SPAN_ATTRIBUTES = {
const RPC_METHODS_WITH_TRACING_DISABLED: ReadonlySet<string> = new Set([
WS_METHODS.serverGetTraceDiagnostics,
WS_METHODS.serverGetProcessDiagnostics,
WS_METHODS.serverGetProcessResourceHistory,
WS_METHODS.serverSignalProcess,
]);
@@ -1,53 +1,17 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { assertSuccess } from "@effect/vitest/utils";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as Random from "effect/Random";
import {
isCommandAvailable,
launchBrowser,
launchEditorProcess,
launchDetached,
resolveAvailableEditors,
resolveBrowserLaunch,
resolveEditorLaunch,
} from "./externalLauncher.ts";
function encodeUtf16LeBase64(input: string): string {
const bytes = new Uint8Array(input.length * 2);
for (let index = 0; index < input.length; index += 1) {
const code = input.charCodeAt(index);
bytes[index * 2] = code & 0xff;
bytes[index * 2 + 1] = code >>> 8;
}
return Encoding.encodeBase64(bytes);
}
function makeMockDetachedHandle(onUnref: () => void = () => undefined) {
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
isRunning: Effect.succeed(true),
kill: () => Effect.void,
unref: Effect.sync(() => {
onUnref();
return Effect.void;
}),
stdin: Sink.drain,
stdout: Stream.empty,
stderr: Stream.empty,
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
});
}
} from "./open.ts";
it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
it.effect("returns commands for command-based editors", () =>
@@ -252,70 +216,70 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
});
const lineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "cursor" },
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "cursor" },
"darwin",
{ PATH: "" },
);
assert.deepEqual(lineAndColumn, {
command: "cursor",
args: ["--goto", "/tmp/workspace/src/process/externalLauncher.ts:71:5"],
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
const traeLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "trae" },
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "trae" },
"darwin",
);
assert.deepEqual(traeLineAndColumn, {
command: "trae",
args: ["--goto", "/tmp/workspace/src/process/externalLauncher.ts:71:5"],
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
const kiroLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "kiro" },
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "kiro" },
"darwin",
{ PATH: "" },
);
assert.deepEqual(kiroLineAndColumn, {
command: "kiro",
args: ["ide", "--goto", "/tmp/workspace/src/process/externalLauncher.ts:71:5"],
args: ["ide", "--goto", "/tmp/workspace/src/open.ts:71:5"],
});
const vscodeLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "vscode" },
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
"darwin",
{ PATH: "" },
);
assert.deepEqual(vscodeLineAndColumn, {
command: "code",
args: ["--goto", "/tmp/workspace/src/process/externalLauncher.ts:71:5"],
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
const vscodeInsidersLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "vscode-insiders" },
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode-insiders" },
"darwin",
);
assert.deepEqual(vscodeInsidersLineAndColumn, {
command: "code-insiders",
args: ["--goto", "/tmp/workspace/src/process/externalLauncher.ts:71:5"],
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
const vscodiumLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "vscodium" },
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscodium" },
"darwin",
);
assert.deepEqual(vscodiumLineAndColumn, {
command: "codium",
args: ["--goto", "/tmp/workspace/src/process/externalLauncher.ts:71:5"],
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
const zedLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "zed" },
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "zed" },
"darwin",
{ PATH: "" },
);
assert.deepEqual(zedLineAndColumn, {
command: "zed",
args: ["/tmp/workspace/src/process/externalLauncher.ts:71:5"],
args: ["/tmp/workspace/src/open.ts:71:5"],
});
const zedLineOnly = yield* resolveEditorLaunch(
@@ -338,102 +302,102 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
});
const ideaLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "idea" },
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "idea" },
"darwin",
);
assert.deepEqual(ideaLineAndColumn, {
command: "idea",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
});
const aquaLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "aqua" },
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "aqua" },
"darwin",
);
assert.deepEqual(aquaLineAndColumn, {
command: "aqua",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
});
const clionLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "clion" },
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "clion" },
"darwin",
);
assert.deepEqual(clionLineAndColumn, {
command: "clion",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
});
const datagripLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "datagrip" },
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "datagrip" },
"darwin",
);
assert.deepEqual(datagripLineAndColumn, {
command: "datagrip",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
});
const dataspellLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "dataspell" },
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "dataspell" },
"darwin",
);
assert.deepEqual(dataspellLineAndColumn, {
command: "dataspell",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
});
const golandLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "goland" },
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "goland" },
"darwin",
);
assert.deepEqual(golandLineAndColumn, {
command: "goland",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
});
const phpstormLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "phpstorm" },
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "phpstorm" },
"darwin",
);
assert.deepEqual(phpstormLineAndColumn, {
command: "phpstorm",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
});
const pycharmLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "pycharm" },
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "pycharm" },
"darwin",
);
assert.deepEqual(pycharmLineAndColumn, {
command: "pycharm",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
});
const riderLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "rider" },
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "rider" },
"darwin",
);
assert.deepEqual(riderLineAndColumn, {
command: "rider",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
});
const rubymineLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "rubymine" },
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "rubymine" },
"darwin",
);
assert.deepEqual(rubymineLineAndColumn, {
command: "rubymine",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
});
const rustroverLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "rustrover" },
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "rustrover" },
"darwin",
);
assert.deepEqual(rustroverLineAndColumn, {
command: "rustrover",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
});
const webstormLineOnly = yield* resolveEditorLaunch(
@@ -451,7 +415,7 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-external-launcher-test-" });
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
yield* fs.writeFileString(path.join(dir, "zeditor"), "#!/bin/sh\nexit 0\n");
yield* fs.chmod(path.join(dir, "zeditor"), 0o755);
@@ -513,149 +477,23 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
);
});
it("resolveBrowserLaunch maps default browser launchers by platform", () => {
const target = "https://example.com/some path?name=o'hara";
assert.deepEqual(resolveBrowserLaunch(target, "darwin").command, "open");
assert.deepEqual(resolveBrowserLaunch(target, "darwin").args, [target]);
assert.deepEqual(resolveBrowserLaunch(target, "darwin").options, {
detached: true,
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
});
assert.deepEqual(resolveBrowserLaunch(target, "linux", {}).command, "xdg-open");
assert.deepEqual(resolveBrowserLaunch(target, "linux", {}).args, [target]);
const windows = resolveBrowserLaunch(target, "win32", {
SYSTEMROOT: "C:\\Windows",
});
assert.equal(windows.command, "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe");
assert.deepEqual(windows.args, [
"-NoProfile",
"-NonInteractive",
"-ExecutionPolicy",
"Bypass",
"-EncodedCommand",
encodeUtf16LeBase64(
"$ProgressPreference = 'SilentlyContinue'; Start 'https://example.com/some path?name=o''hara'",
),
]);
assert.deepEqual(windows.options, {
detached: true,
shell: false,
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
});
});
it("resolveBrowserLaunch opens through Windows from WSL when not remote", () => {
const launch = resolveBrowserLaunch("https://example.com", "linux", {
WSL_DISTRO_NAME: "Ubuntu",
});
assert.equal(launch.command, "/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe");
assert.equal(launch.options.detached, true);
});
it("resolveBrowserLaunch keeps xdg-open for WSL over SSH", () => {
const launch = resolveBrowserLaunch("https://example.com", "linux", {
WSL_DISTRO_NAME: "Ubuntu",
SSH_CONNECTION: "client server",
});
assert.equal(launch.command, "xdg-open");
});
it.layer(NodeServices.layer)("launchBrowser", (it) => {
it.effect("spawns through the ChildProcessSpawner service and unrefs the handle", () =>
it.layer(NodeServices.layer)("launchDetached", (it) => {
it.effect("resolves when command can be spawned", () =>
Effect.gen(function* () {
let spawnedCommand: ChildProcess.StandardCommand | undefined;
let didUnref = false;
const spawnerLayer = Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {
spawn: (command) =>
Effect.sync(() => {
assert.equal(ChildProcess.isStandardCommand(command), true);
if (!ChildProcess.isStandardCommand(command)) {
throw new Error("Expected a standard command");
}
spawnedCommand = command;
return makeMockDetachedHandle(() => {
didUnref = true;
});
}),
});
const result = yield* launchBrowser("https://example.com").pipe(
Effect.provide(spawnerLayer),
Effect.result,
);
assertSuccess(result, undefined);
assert.ok(spawnedCommand);
const expectedLaunch = resolveBrowserLaunch("https://example.com");
assert.equal(spawnedCommand.command, expectedLaunch.command);
assert.deepEqual(spawnedCommand.args, expectedLaunch.args);
assert.deepEqual(spawnedCommand.options, expectedLaunch.options);
assert.equal(didUnref, true);
}),
);
});
it.layer(NodeServices.layer)("launchEditorProcess", (it) => {
it.effect("spawns through the ChildProcessSpawner service and unrefs the handle", () =>
Effect.gen(function* () {
let spawnedCommand: ChildProcess.StandardCommand | undefined;
let didUnref = false;
const expectedArgs = ["-e", "process.exit(0)"];
const spawnerLayer = Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {
spawn: (command) =>
Effect.sync(() => {
assert.equal(ChildProcess.isStandardCommand(command), true);
if (!ChildProcess.isStandardCommand(command)) {
throw new Error("Expected a standard command");
}
spawnedCommand = command;
return makeMockDetachedHandle(() => {
didUnref = true;
});
}),
});
const result = yield* launchEditorProcess({
const result = yield* launchDetached({
command: process.execPath,
args: expectedArgs,
}).pipe(Effect.provide(spawnerLayer), Effect.result);
args: ["-e", "process.exit(0)"],
}).pipe(Effect.result);
assertSuccess(result, undefined);
assert.ok(spawnedCommand);
assert.equal(spawnedCommand.command, process.execPath);
assert.deepEqual(
spawnedCommand.args,
process.platform === "win32" ? expectedArgs.map((arg) => `"${arg}"`) : expectedArgs,
);
assert.deepEqual(spawnedCommand.options, {
detached: true,
shell: process.platform === "win32",
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
});
assert.equal(didUnref, true);
}),
);
it.effect("rejects when command does not exist", () =>
Effect.gen(function* () {
const spawnerLayer = Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {});
const result = yield* launchEditorProcess({
command: `t3code-no-such-command-${yield* Crypto.Crypto.pipe(
Effect.flatMap((crypto) => crypto.randomUUIDv4),
)}`,
const result = yield* launchDetached({
command: `t3code-no-such-command-${yield* Random.nextUUIDv4}`,
args: [],
}).pipe(Effect.provide(spawnerLayer), Effect.result);
}).pipe(Effect.result);
assert.equal(result._tag, "Failure");
}),
);
@@ -666,7 +504,7 @@ it.layer(NodeServices.layer)("isCommandAvailable", (it) => {
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-external-launcher-test-" });
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
yield* fs.writeFileString(path.join(dir, "code.CMD"), "@echo off\r\n");
const env = {
PATH: dir,
@@ -688,7 +526,7 @@ it.layer(NodeServices.layer)("isCommandAvailable", (it) => {
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-external-launcher-test-" });
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
yield* fs.writeFileString(path.join(dir, "npm"), "echo nope\r\n");
const env = {
PATH: dir,
@@ -702,7 +540,7 @@ it.layer(NodeServices.layer)("isCommandAvailable", (it) => {
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-external-launcher-test-" });
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
yield* fs.writeFileString(path.join(dir, "my.tool.CMD"), "@echo off\r\n");
const env = {
PATH: dir,
@@ -716,8 +554,8 @@ it.layer(NodeServices.layer)("isCommandAvailable", (it) => {
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const firstDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-external-launcher-test-" });
const secondDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-external-launcher-test-" });
const firstDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
const secondDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
yield* fs.writeFileString(path.join(firstDir, "code.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(secondDir, "code.CMD"), "MZ");
const env = {
Loaded 100 of 307 files, more files were not shown because too many files have changed in this diff. Show more