Merge upstream/main into josh/desktop-wsl-parallel-backends

Re-integrates the WSL parallel-backends renderer onto upstream's rewritten
connection/RPC architecture (#2978), which deleted the saved-env / environmentApi
/ serverState / wsConnectionState subsystem this branch was built on.

Core (packages/client-runtime/connection):
- Add dynamic platform-managed bearer environments: a PlatformConnectionRegistration
  union (Primary|Bearer) and registry.reconcilePlatform(set), which adds/removes
  platform-managed environments as the host topology changes and stashes the bearer
  credential. This models the dual-mode WSL secondary (separate loopback origin,
  bearer auth, dynamic port so it is rederived rather than persisted). The primary
  and the WSL-only primary keep the same-origin cookie path.

Web platform source (apps/web/src/connection/platform.ts):
- Emit the platform set from the plural getLocalEnvironmentBootstraps() IPC: the
  primary (cookie) plus each WSL backend (bearer via bootstrap-token exchange),
  polling and reconciling on toggle. Replaces the deleted 541-line reconciler.

Renderer re-home:
- Drop the old subsystem (environmentApi, rpc/serverState, rpc/wsConnectionState,
  environments/runtime/*, environments/local/*) and their tests.
- Re-home the Sidebar cold-boot indicator, the ConnectionsSettings WSL picker, and
  the multi-environment provider-update feature onto the new hooks (useEnvironments,
  serverEnvironment.updateProvider, the primaryServer* atoms). Desktop-local
  environments are identified by a BearerConnectionTarget with a "local:"
  connection id.
- Drop the inert swap-suppression surface superseded by parallel backends.

Verified: typecheck (web, desktop, client-runtime), connection / provider /
localApi / authBootstrap tests, and lint all pass.
This commit is contained in:
Josh Gratton committed 2026-06-19 16:25:39 -04:00
commit 08a3f9f94a
707 files changed
+48876 -55909

No files matched your search

+42 -3
View File
@@ -35,6 +35,8 @@ describe("AssetAccess", () => {
yield* fileSystem.writeFileString(htmlPath, '<link rel="stylesheet" href="report.css">');
yield* fileSystem.writeFileString(cssPath, "body { color: red; }");
yield* fileSystem.writeFileString(path.join(root, ".env"), "SECRET=value");
const canonicalHtmlPath = yield* fileSystem.realPath(htmlPath);
const canonicalCssPath = yield* fileSystem.realPath(cssPath);
const result = yield* issueAssetUrl({
resource: {
@@ -50,11 +52,11 @@ describe("AssetAccess", () => {
expect(yield* resolveAsset(token, "report.html")).toEqual({
kind: "file",
path: htmlPath,
path: canonicalHtmlPath,
});
expect(yield* resolveAsset(token, "report.css")).toEqual({
kind: "file",
path: cssPath,
path: canonicalCssPath,
});
expect(yield* resolveAsset(token, "../secret.txt")).toBeNull();
expect(yield* resolveAsset(token, ".env")).toBeNull();
@@ -87,6 +89,42 @@ describe("AssetAccess", () => {
}).pipe(Effect.provide(testLayer)),
);
it.effect("issues exact workspace URLs for image previews", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-asset-image-workspace-",
});
const assetsDirectory = path.join(root, "assets");
const imagePath = path.join(assetsDirectory, "icon.png");
const siblingPath = path.join(assetsDirectory, "other.png");
yield* fileSystem.makeDirectory(assetsDirectory, { recursive: true });
yield* fileSystem.writeFile(imagePath, new Uint8Array([137, 80, 78, 71]));
yield* fileSystem.writeFile(siblingPath, new Uint8Array([137, 80, 78, 71]));
const canonicalImagePath = yield* fileSystem.realPath(imagePath);
const result = yield* issueAssetUrl({
resource: {
_tag: "workspace-file",
threadId: ThreadId.make("thread-1"),
path: imagePath,
},
workspaceRoot: root,
});
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
const separatorIndex = suffix.indexOf("/");
const token = suffix.slice(0, separatorIndex);
expect(yield* resolveAsset(token, "icon.png")).toEqual({
kind: "file",
path: canonicalImagePath,
});
expect(yield* resolveAsset(token, "other.png")).toBeNull();
expect(yield* resolveAsset(token, "../icon.png")).toBeNull();
}).pipe(Effect.provide(testLayer)),
);
it.effect("issues exact attachment capabilities by attachment id", () =>
Effect.gen(function* () {
const config = yield* ServerConfig;
@@ -120,6 +158,7 @@ describe("AssetAccess", () => {
});
const faviconPath = path.join(root, "favicon.svg");
yield* fileSystem.writeFileString(faviconPath, "<svg />");
const canonicalFaviconPath = yield* fileSystem.realPath(faviconPath);
const faviconResult = yield* issueAssetUrl({
resource: { _tag: "project-favicon", cwd: root },
@@ -131,7 +170,7 @@ describe("AssetAccess", () => {
faviconSuffix.slice(0, faviconSeparatorIndex),
faviconSuffix.slice(faviconSeparatorIndex + 1),
),
).toEqual({ kind: "file", path: faviconPath });
).toEqual({ kind: "file", path: canonicalFaviconPath });
yield* fileSystem.remove(faviconPath);
const fallbackResult = yield* issueAssetUrl({
+45 -21
View File
@@ -1,5 +1,11 @@
import type { AssetResource } from "@t3tools/contracts";
import { AssetAccessError } from "@t3tools/contracts";
import {
isWorkspaceImagePreviewPath,
isWorkspacePreviewEntryPath,
WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
} from "@t3tools/shared/filePreview";
import * as Clock from "effect/Clock";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -24,22 +30,14 @@ export const FALLBACK_PROJECT_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/
const SIGNING_SECRET_NAME = "asset-access-signing-key";
const ASSET_TOKEN_TTL_MS = 60 * 60 * 1000;
const PREVIEWABLE_EXTENSIONS = new Set([".htm", ".html", ".pdf"]);
const PREVIEW_ASSET_EXTENSIONS = new Set([
...PREVIEWABLE_EXTENSIONS,
".avif",
...WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
...WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
".css",
".gif",
".ico",
".jpeg",
".jpg",
".js",
".mjs",
".otf",
".png",
".svg",
".ttf",
".webp",
".woff",
".woff2",
]);
@@ -52,6 +50,13 @@ const AssetClaimsSchema = Schema.Union([
baseRelativePath: Schema.String,
expiresAt: Schema.Number,
}),
Schema.Struct({
version: Schema.Literal(1),
kind: Schema.Literal("workspace-file-exact"),
workspaceRoot: Schema.String,
relativePath: Schema.String,
expiresAt: Schema.Number,
}),
Schema.Struct({
version: Schema.Literal(1),
kind: Schema.Literal("attachment"),
@@ -144,8 +149,8 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
const resolved = yield* workspacePaths
.resolveRelativePathWithinRoot({ workspaceRoot, relativePath })
.pipe(Effect.mapError((cause) => failAccess(cause.message, cause)));
if (!PREVIEWABLE_EXTENSIONS.has(path.extname(resolved.relativePath).toLowerCase())) {
return yield* failAccess("Only HTML and PDF files can open in the browser.");
if (!isWorkspacePreviewEntryPath(resolved.relativePath)) {
return yield* failAccess("Only browser documents and images can be previewed.");
}
const canonicalFile = yield* resolveCanonicalWorkspaceFile({
workspaceRoot,
@@ -154,15 +159,24 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
if (!canonicalFile) {
return yield* failAccess("Workspace asset was not found.");
}
claims = {
version: 1,
kind: "workspace-file",
workspaceRoot: yield* fileSystem
.realPath(workspaceRoot)
.pipe(Effect.mapError((cause) => failAccess("Failed to resolve workspace.", cause))),
baseRelativePath: path.dirname(resolved.relativePath),
expiresAt,
};
const canonicalWorkspaceRoot = yield* fileSystem
.realPath(workspaceRoot)
.pipe(Effect.mapError((cause) => failAccess("Failed to resolve workspace.", cause)));
claims = isWorkspaceImagePreviewPath(resolved.relativePath)
? {
version: 1,
kind: "workspace-file-exact",
workspaceRoot: canonicalWorkspaceRoot,
relativePath: resolved.relativePath,
expiresAt,
}
: {
version: 1,
kind: "workspace-file",
workspaceRoot: canonicalWorkspaceRoot,
baseRelativePath: path.dirname(resolved.relativePath),
expiresAt,
};
fileName = path.basename(resolved.relativePath);
break;
}
@@ -268,6 +282,16 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
const decodedPath = decodeRelativePath(relativePath);
if (decodedPath === null) return null;
const path = yield* Path.Path;
if (claims.kind === "workspace-file-exact") {
if (decodedPath !== path.basename(claims.relativePath)) return null;
const exactWorkspaceFile = yield* resolveCanonicalWorkspaceFile({
workspaceRoot: claims.workspaceRoot,
relativePath: claims.relativePath,
});
return exactWorkspaceFile
? ({ kind: "file", path: exactWorkspaceFile } satisfies ResolvedAsset)
: null;
}
const segments = decodedPath.split(/[\\/]/);
if (
decodedPath.length === 0 ||
+4
View File
@@ -25,6 +25,7 @@ import { parseAllowedOAuthScope } from "@t3tools/shared/oauthScope";
import { causeErrorTag } from "@t3tools/shared/observability";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import { identity } from "effect/Function";
import * as Layer from "effect/Layer";
import * as Cookies from "effect/unstable/http/Cookies";
import * as HttpEffect from "effect/unstable/http/HttpEffect";
@@ -33,6 +34,7 @@ import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
import * as EnvironmentAuth from "./EnvironmentAuth.ts";
import * as SessionStore from "./SessionStore.ts";
import { traceAuthenticatedRelayRequest, traceRelayRequest } from "../cloud/traceRelayRequest.ts";
import { deriveAuthClientMetadata } from "./utils.ts";
import { verifyRequestDpopProof } from "./dpop.ts";
@@ -177,6 +179,7 @@ export const environmentAuthenticatedAuthLayer = Layer.effect(
...session,
scopes: new Set(session.scopes),
}),
session.subject === "cloud-connect" ? traceAuthenticatedRelayRequest : identity,
);
}).pipe(Effect.catchTag("EnvironmentAuthInvalidError", appendDpopChallengeOnUnauthorized));
}),
@@ -289,6 +292,7 @@ export const authHttpApiLayer = HttpApiBuilder.group(
proofKeyThumbprint ? { proofKeyThumbprint } : undefined,
);
},
traceRelayRequest,
Effect.catchTags({
ServerAuthInvalidCredentialError: (error) => failEnvironmentAuthInvalid(error.reason),
ServerAuthInvalidRequestError: (error) => failEnvironmentInvalidRequest(error.reason),
@@ -10,7 +10,10 @@ import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as RelayClient from "@t3tools/shared/relayClient";
import { makeCloudManagedEndpointRuntime } from "./ManagedEndpointRuntime.ts";
import {
classifyRelayClientOutput,
makeCloudManagedEndpointRuntime,
} from "./ManagedEndpointRuntime.ts";
const relayClientAvailableLayer = Layer.succeed(
RelayClient.RelayClient,
@@ -57,6 +60,20 @@ function makeHandle(input: {
}
describe("CloudManagedEndpointRuntime", () => {
it("classifies Cloudflare connection and warning output", () => {
expect(
classifyRelayClientOutput(
"2026-06-17T02:00:00Z INF Registered tunnel connection connIndex=0",
),
).toBe("connected");
expect(
classifyRelayClientOutput("2026-06-17T02:00:00Z ERR Failed to serve tunnel connection"),
).toBe("warning");
expect(classifyRelayClientOutput("2026-06-17T02:00:00Z INF Starting metrics server")).toBe(
"debug",
);
});
it.effect("starts, deduplicates, rotates, and stops the Cloudflare connector", () =>
Effect.gen(function* () {
const spawned: Array<ChildProcess.StandardCommand> = [];
@@ -113,8 +130,8 @@ describe("CloudManagedEndpointRuntime", () => {
"token-1",
"token-2",
]);
expect(spawned.map((command) => command.options.stdout)).toEqual(["ignore", "ignore"]);
expect(spawned.map((command) => command.options.stderr)).toEqual(["ignore", "ignore"]);
expect(spawned.map((command) => command.options.stdout)).toEqual(["pipe", "pipe"]);
expect(spawned.map((command) => command.options.stderr)).toEqual(["pipe", "pipe"]);
expect(spawned.map((command) => command.options.detached)).toEqual([false, false]);
expect(spawned.map((command) => command.options.shell)).toEqual([false, false]);
expect(killed).toEqual([100, 101]);
@@ -9,6 +9,7 @@ import * as Ref from "effect/Ref";
import * as Result from "effect/Result";
import * as Semaphore from "effect/Semaphore";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
@@ -68,6 +69,13 @@ interface ActiveConnector {
readonly config: RelayManagedEndpointRuntimeConfig;
}
export function classifyRelayClientOutput(line: string): "connected" | "warning" | "debug" {
if (/\bRegistered tunnel connection\b/iu.test(line)) {
return "connected";
}
return /\b(?:ERR|WRN)\b/u.test(line) ? "warning" : "debug";
}
function runtimeConfigKey(config: RelayManagedEndpointRuntimeConfig): string {
return JSON.stringify({
providerKind: config.providerKind,
@@ -141,6 +149,39 @@ export const makeCloudManagedEndpointRuntime = Effect.gen(function* () {
Effect.catchCause((cause) => Effect.logWarning("Relay client supervisor failed", { cause })),
);
const observeConnectorOutput = (connector: ActiveConnector) =>
connector.child.all.pipe(
Stream.decodeText(),
Stream.splitLines,
Stream.map((line) => line.trim()),
Stream.filter((line) => line.length > 0),
Stream.runForEach((line) => {
const output = line.replaceAll(connector.config.connectorToken, "<redacted>");
const attributes = {
pid: Number(connector.child.pid),
tunnelId: connector.config.tunnelId,
tunnelName: connector.config.tunnelName,
output,
};
switch (classifyRelayClientOutput(line)) {
case "connected":
return Effect.logInfo("Relay client tunnel connection registered", attributes);
case "warning":
return Effect.logWarning("Relay client reported a transport warning", attributes);
case "debug":
return Effect.logDebug("Relay client output", attributes);
}
}),
Effect.catchCause((cause) =>
Effect.logWarning("Relay client output observer failed", {
cause,
pid: Number(connector.child.pid),
tunnelId: connector.config.tunnelId,
tunnelName: connector.config.tunnelName,
}),
),
);
reconcileConfig = Effect.fn("CloudManagedEndpointRuntime.reconcileConfig")(function* (config) {
if (!config || config.providerKind !== "cloudflare_tunnel") {
yield* stopActive;
@@ -190,14 +231,15 @@ export const makeCloudManagedEndpointRuntime = Effect.gen(function* () {
TUNNEL_TOKEN: config.connectorToken,
},
shell: false,
stderr: "ignore",
stdout: "ignore",
stderr: "pipe",
stdout: "pipe",
}),
)
.pipe(
Effect.provideService(Scope.Scope, connectorScope),
Effect.tap(() =>
Effect.logInfo("Relay client started", {
Effect.tap((child) =>
Effect.logInfo("Relay client process started; waiting for tunnel connection", {
pid: Number(child.pid),
tunnelId: config.tunnelId,
tunnelName: config.tunnelName,
}),
@@ -232,6 +274,7 @@ export const makeCloudManagedEndpointRuntime = Effect.gen(function* () {
config,
} satisfies ActiveConnector;
yield* Ref.set(activeRef, connector);
yield* Effect.forkIn(observeConnectorOutput(connector), connectorScope);
yield* Effect.forkIn(superviseConnector(connector), connectorScope);
return {
status: "running",
+37 -8
View File
@@ -11,15 +11,12 @@ import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { ServerEnvironment } from "../environment/Services/ServerEnvironment.ts";
import * as CliTokenManager from "./CliTokenManager.ts";
import {
consumeCloudReplayGuards,
reconcileDesiredCloudLink,
traceRelayBrokerHandler,
} from "./http.ts";
import { consumeCloudReplayGuards, reconcileDesiredCloudLink } from "./http.ts";
import {
CloudManagedEndpointRuntime,
type CloudManagedEndpointRuntimeShape,
} from "./ManagedEndpointRuntime.ts";
import { traceAuthenticatedRelayRequest, traceRelayRequest } from "./traceRelayRequest.ts";
const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
new ServerSecretStore.SecretStoreError({
@@ -75,8 +72,8 @@ describe("consumeCloudReplayGuards", () => {
);
});
describe("traceRelayBrokerHandler", () => {
it.effect("continues the incoming relay trace with the product tracer", () =>
describe("relay request tracing", () => {
it.effect("does not accept an unauthenticated request trace parent", () =>
Effect.gen(function* () {
const spans: Array<Tracer.Span> = [];
const productTracer = Tracer.make({
@@ -94,7 +91,39 @@ describe("traceRelayBrokerHandler", () => {
}),
);
yield* traceRelayBrokerHandler(Effect.void.pipe(Effect.withSpan("relay.mint.handler"))).pipe(
yield* traceRelayRequest(Effect.void.pipe(Effect.withSpan("relay.mint.handler"))).pipe(
Effect.provideService(HttpServerRequest.HttpServerRequest, request),
Effect.provideService(RelayClientTracer, Option.some(productTracer)),
);
expect(spans).toHaveLength(1);
const span = spans[0]!;
expect(span.traceId).not.toBe("0123456789abcdef0123456789abcdef");
expect(Option.isNone(span.parent)).toBe(true);
}),
);
it.effect("continues an authenticated relay trace with the product tracer", () =>
Effect.gen(function* () {
const spans: Array<Tracer.Span> = [];
const productTracer = Tracer.make({
span: (options) => {
const span = new Tracer.NativeSpan(options);
spans.push(span);
return span;
},
});
const request = HttpServerRequest.fromWeb(
new Request("https://environment.example.test/api/t3-cloud/mint-credential", {
headers: {
traceparent: "00-0123456789abcdef0123456789abcdef-0123456789abcdef-01",
},
}),
);
yield* traceAuthenticatedRelayRequest(
Effect.void.pipe(Effect.withSpan("relay.mint.handler")),
).pipe(
Effect.provideService(HttpServerRequest.HttpServerRequest, request),
Effect.provideService(RelayClientTracer, Option.some(productTracer)),
);
+3 -15
View File
@@ -48,7 +48,7 @@ import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as HttpEffect from "effect/unstable/http/HttpEffect";
import { HttpServerRequest, HttpServerResponse, HttpTraceContext } from "effect/unstable/http";
import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
@@ -77,6 +77,7 @@ import { relayUrlConfig } from "./publicConfig.ts";
import * as CliState from "./CliState.ts";
import * as CliTokenManager from "./CliTokenManager.ts";
import { getOrCreateEnvironmentKeyPairFromSecretStore } from "./environmentKeys.ts";
import { traceRelayRequest } from "./traceRelayRequest.ts";
const CLOUD_MINT_NONCE_PREFIX = "cloud-mint-nonce-";
const CLOUD_MINT_JTI_PREFIX = "cloud-mint-jti-";
@@ -111,19 +112,6 @@ const requireRelayUrl = relayUrlConfig.pipe(
),
);
export const traceRelayBrokerHandler = <A, E, R>(
effect: Effect.Effect<A, E, R>,
): Effect.Effect<A, E, R | HttpServerRequest.HttpServerRequest> =>
HttpServerRequest.HttpServerRequest.pipe(
Effect.flatMap((request) =>
Option.match(HttpTraceContext.fromHeaders(request.headers), {
onNone: () => effect,
onSome: (parent) => effect.pipe(Effect.withParentSpan(parent)),
}),
),
withRelayClientTracing,
);
function bytesToString(bytes: Uint8Array): string {
return new TextDecoder().decode(bytes);
}
@@ -953,7 +941,7 @@ export const connectHttpApiLayer = HttpApiBuilder.group(
.handle("health", ({ payload }) => cloudEnvironmentHealthHandler(dependencies, payload))
.handle("mintCredential", ({ payload }) => cloudMintCredentialHandler(dependencies, payload))
.handle("t3MintCredential", ({ payload }) =>
traceRelayBrokerHandler(cloudMintCredentialHandler(dependencies, payload)),
traceRelayRequest(cloudMintCredentialHandler(dependencies, payload)),
);
}),
);
@@ -0,0 +1,21 @@
import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { HttpServerRequest, HttpTraceContext } from "effect/unstable/http";
export const traceRelayRequest = <A, E, R>(
effect: Effect.Effect<A, E, R>,
): Effect.Effect<A, E, R> => effect.pipe(withRelayClientTracing);
export const traceAuthenticatedRelayRequest = <A, E, R>(
effect: Effect.Effect<A, E, R>,
): Effect.Effect<A, E, R | HttpServerRequest.HttpServerRequest> =>
HttpServerRequest.HttpServerRequest.pipe(
Effect.flatMap((request) =>
Option.match(HttpTraceContext.fromHeaders(request.headers), {
onNone: () => effect,
onSome: (parent) => effect.pipe(Effect.withParentSpan(parent)),
}),
),
withRelayClientTracing,
);
+19 -6
View File
@@ -47,7 +47,11 @@ import { ProjectSetupScriptRunner } from "../project/Services/ProjectSetupScript
import { extractBranchNameFromRemoteRef } from "./remoteRefs.ts";
import { ServerSettingsService } from "../serverSettings.ts";
import type { GitManagerServiceError } from "@t3tools/contracts";
import { GitVcsDriver, type GitStatusDetails } from "../vcs/GitVcsDriver.ts";
import {
GitVcsDriver,
type GitRemoteStatusOptions,
type GitStatusDetails,
} from "../vcs/GitVcsDriver.ts";
import { SourceControlProviderRegistry } from "../sourceControl/SourceControlProviderRegistry.ts";
import type { ChangeRequest } from "@t3tools/contracts";
@@ -69,6 +73,7 @@ export interface GitManagerShape {
) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
readonly remoteStatus: (
input: VcsStatusInput,
options?: GitRemoteStatusOptions,
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
@@ -745,9 +750,12 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
normalizeStatusCacheKey(cwd).pipe(
Effect.flatMap((cacheKey) => Cache.invalidate(localStatusResultCache, cacheKey)),
);
const readRemoteStatus = Effect.fn("readRemoteStatus")(function* (cwd: string) {
const readRemoteStatus = Effect.fn("readRemoteStatus")(function* (
cwd: string,
options?: GitRemoteStatusOptions,
) {
const details = yield* gitCore
.statusDetailsRemote(cwd)
.statusDetailsRemote(cwd, options)
.pipe(Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(null)));
if (details === null || !details.isRepo) {
return null;
@@ -778,7 +786,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
pr,
} satisfies VcsStatusRemoteResult;
});
const remoteStatusResultCache = yield* Cache.makeWith(readRemoteStatus, {
const remoteStatusResultCache = yield* Cache.makeWith((cwd: string) => readRemoteStatus(cwd), {
capacity: STATUS_RESULT_CACHE_CAPACITY,
timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),
});
@@ -1355,13 +1363,18 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
return yield* Cache.get(localStatusResultCache, cacheKey);
});
const remoteStatus: GitManagerShape["remoteStatus"] = Effect.fn("remoteStatus")(
function* (input) {
function* (input, options) {
const cacheKey = yield* normalizeStatusCacheKey(input.cwd);
if (options?.refreshUpstream === false) {
return yield* readRemoteStatus(cacheKey, options);
}
return yield* Cache.get(remoteStatusResultCache, cacheKey);
},
);
const status: GitManagerShape["status"] = Effect.fn("status")(function* (input) {
const [local, remote] = yield* Effect.all([localStatus(input), remoteStatus(input)]);
const [local, remote] = yield* Effect.all([localStatus(input), remoteStatus(input)], {
concurrency: "unbounded",
});
return mergeGitStatusParts(local, remote);
});
const invalidateLocalStatus: GitManagerShape["invalidateLocalStatus"] = Effect.fn(
+24 -3
View File
@@ -29,7 +29,7 @@ import {
} from "@t3tools/contracts";
import { GitManager, type GitRunStackedActionOptions } from "./GitManager.ts";
import { GitVcsDriver } from "../vcs/GitVcsDriver.ts";
import { GitVcsDriver, type GitRemoteStatusOptions } from "../vcs/GitVcsDriver.ts";
import { VcsDriverRegistry } from "../vcs/VcsDriverRegistry.ts";
export interface GitWorkflowServiceShape {
@@ -41,6 +41,7 @@ export interface GitWorkflowServiceShape {
) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
readonly remoteStatus: (
input: VcsStatusInput,
options?: GitRemoteStatusOptions,
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
@@ -60,6 +61,18 @@ export interface GitWorkflowServiceShape {
readonly createWorktree: (
input: VcsCreateWorktreeInput,
) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
readonly fetchRemote: (input: {
readonly cwd: string;
readonly remoteName: string;
}) => Effect.Effect<void, GitCommandError>;
readonly resolveRemoteTrackingCommit: (input: {
readonly cwd: string;
readonly refName: string;
readonly fallbackRemoteName: string;
}) => Effect.Effect<
{ readonly commitSha: string; readonly remoteRefName: string },
GitCommandError
>;
readonly removeWorktree: (input: VcsRemoveWorktreeInput) => Effect.Effect<void, GitCommandError>;
readonly createRef: (
input: VcsCreateRefInput,
@@ -259,10 +272,10 @@ export const make = Effect.fn("makeGitWorkflowService")(function* () {
: Effect.succeed(nonRepositoryLocalStatus()),
),
),
remoteStatus: (input) =>
remoteStatus: (input, options) =>
detectGitRepositoryForStatus("GitWorkflowService.remoteStatus", input.cwd).pipe(
Effect.flatMap((isGitRepository) =>
isGitRepository ? gitManager.remoteStatus(input) : Effect.succeed(null),
isGitRepository ? gitManager.remoteStatus(input, options) : Effect.succeed(null),
),
),
invalidateLocalStatus: gitManager.invalidateLocalStatus,
@@ -294,6 +307,14 @@ export const make = Effect.fn("makeGitWorkflowService")(function* () {
ensureGitCommand("GitWorkflowService.createWorktree", input.cwd).pipe(
Effect.andThen(git.createWorktree(input)),
),
fetchRemote: (input) =>
ensureGitCommand("GitWorkflowService.fetchRemote", input.cwd).pipe(
Effect.andThen(git.fetchRemote(input)),
),
resolveRemoteTrackingCommit: (input) =>
ensureGitCommand("GitWorkflowService.resolveRemoteTrackingCommit", input.cwd).pipe(
Effect.andThen(git.resolveRemoteTrackingCommit(input)),
),
removeWorktree: (input) =>
ensureGitCommand("GitWorkflowService.removeWorktree", input.cwd).pipe(
Effect.andThen(git.removeWorktree(input)),
+2 -1
View File
@@ -32,6 +32,7 @@ import {
} from "./assets/AssetAccess.ts";
import { BrowserTraceCollector } from "./observability/Services/BrowserTraceCollector.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import { traceRelayRequest } from "./cloud/traceRelayRequest.ts";
import {
annotateEnvironmentRequest,
failEnvironmentScopeRequired,
@@ -100,7 +101,7 @@ export const serverEnvironmentHttpApiLayer = HttpApiBuilder.group(
Effect.fn("environment.metadata.descriptor")(function* (args) {
yield* annotateEnvironmentRequest(args.endpoint.name);
return yield* serverEnvironment.getDescriptor;
}),
}, traceRelayRequest),
);
}),
);
+55 -1
View File
@@ -1,10 +1,11 @@
import { expect, it } from "@effect/vitest";
import { NodeHttpServer } from "@effect/platform-node";
import { EnvironmentId, PreviewTabId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Stream from "effect/Stream";
import { McpSchema, McpServer } from "effect/unstable/ai";
import { HttpServerResponse } from "effect/unstable/http";
import { HttpBody, HttpClient, HttpRouter, HttpServerResponse } from "effect/unstable/http";
import * as McpHttpServer from "./McpHttpServer.ts";
import * as McpInvocationContext from "./McpInvocationContext.ts";
@@ -48,6 +49,59 @@ it("normalizes empty successful notification responses to accepted", () => {
expect(resultResponse.status).toBe(200);
});
it.effect("terminates HTTP MCP sessions with DELETE", () =>
Effect.scoped(
Effect.gen(function* () {
const serverLayer = McpServer.layerHttp({
name: "MCP termination test",
version: "1.0.0",
path: "/mcp",
});
yield* HttpRouter.serve(serverLayer, {
disableListenLog: true,
disableLogger: true,
}).pipe(Layer.build);
const httpClient = yield* HttpClient.HttpClient;
const initializeResponse = yield* httpClient.post("/mcp", {
headers: { accept: "application/json, text/event-stream" },
body: HttpBody.text(
`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"mcp-test","version":"1.0.0"}}}`,
"application/json",
),
});
const sessionId = initializeResponse.headers["mcp-session-id"];
expect(initializeResponse.status).toBe(200);
expect(sessionId).not.toBeNull();
const missingSessionResponse = yield* httpClient.del("/mcp");
expect(missingSessionResponse.status).toBe(400);
const unknownSessionResponse = yield* httpClient.del("/mcp", {
headers: { "mcp-session-id": "unknown-session" },
});
expect(unknownSessionResponse.status).toBe(404);
const terminateResponse = yield* httpClient.del("/mcp", {
headers: { "mcp-session-id": sessionId! },
});
expect(terminateResponse.status).toBe(204);
const reusedSessionResponse = yield* httpClient.post("/mcp", {
headers: {
accept: "application/json, text/event-stream",
"mcp-session-id": sessionId!,
},
body: HttpBody.text(
`{"jsonrpc":"2.0","id":2,"method":"ping","params":{}}`,
"application/json",
),
});
expect(reusedSessionResponse.status).toBe(404);
}),
).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("registers annotated tools and preserves authenticated request context", () =>
Effect.scoped(
Effect.gen(function* () {
+28 -6
View File
@@ -8,16 +8,18 @@ import { ServerEnvironment } from "../environment/Services/ServerEnvironment.ts"
import * as McpSessionRegistry from "./McpSessionRegistry.ts";
const environmentId = EnvironmentId.make("environment-1");
const fakeHttpServer = HttpServer.HttpServer.of({
address: { _tag: "TcpAddress", hostname: "127.0.0.1", port: 43123 },
serve: (() => Effect.void) as HttpServer.HttpServer["Service"]["serve"],
});
const makeFakeHttpServer = (hostname: string, port = 43123) =>
HttpServer.HttpServer.of({
address: { _tag: "TcpAddress", hostname, port },
serve: (() => Effect.void) as HttpServer.HttpServer["Service"]["serve"],
});
const fakeHttpServer = makeFakeHttpServer("127.0.0.1");
const fakeEnvironment = ServerEnvironment.of({
getEnvironmentId: Effect.succeed(environmentId),
getDescriptor: Effect.die("unused"),
});
const makeRegistry = (now: () => number) =>
const makeRegistry = (now: () => number, httpServer = fakeHttpServer) =>
McpSessionRegistry.__testing
.make({
now,
@@ -25,7 +27,7 @@ const makeRegistry = (now: () => number) =>
maximumLifetimeMs: 1_000,
})
.pipe(
Effect.provideService(HttpServer.HttpServer, fakeHttpServer),
Effect.provideService(HttpServer.HttpServer, httpServer),
Effect.provideService(ServerEnvironment, fakeEnvironment),
Effect.provide(NodeServices.layer),
);
@@ -53,6 +55,26 @@ it.effect("stores only a token hash, resolves the bearer token, and revokes by t
}),
);
it.effect("builds MCP endpoints from the bound server host", () =>
Effect.gen(function* () {
const cases = [
["100.64.0.40", "http://100.64.0.40:43123/mcp"],
["0.0.0.0", "http://127.0.0.1:43123/mcp"],
["localhost", "http://localhost:43123/mcp"],
["127.0.0.1", "http://127.0.0.1:43123/mcp"],
] as const;
for (const [hostname, expectedEndpoint] of cases) {
const registry = yield* makeRegistry(() => 1_000, makeFakeHttpServer(hostname));
const issued = yield* registry.issue({
threadId: ThreadId.make(`thread-${hostname}`),
providerInstanceId: ProviderInstanceId.make("codex"),
});
expect(issued.config.endpoint).toBe(expectedEndpoint);
}
}),
);
it.effect("expires credentials after inactivity", () =>
Effect.gen(function* () {
let timestamp = 1_000;
+12 -1
View File
@@ -60,6 +60,17 @@ const bytesToHex = (bytes: Uint8Array): string =>
const tokenFromBytes = (bytes: Uint8Array): string => Buffer.from(bytes).toString("base64url");
const getHttpMcpEndpointHost = (hostname: string): string => {
const normalized = hostname.toLowerCase();
const endpointHostname =
normalized === "0.0.0.0" || normalized === "::" || normalized === "[::]"
? "127.0.0.1"
: hostname;
return endpointHostname.includes(":") && !endpointHostname.startsWith("[")
? `[${endpointHostname}]`
: endpointHostname;
};
const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
options: McpSessionRegistryOptions = {},
) {
@@ -73,7 +84,7 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
const maximumLifetimeMs = options.maximumLifetimeMs ?? DEFAULT_MAXIMUM_LIFETIME_MS;
const endpoint =
httpServer.address._tag === "TcpAddress"
? `http://127.0.0.1:${httpServer.address.port}/mcp`
? `http://${getHttpMcpEndpointHost(httpServer.address.hostname)}:${httpServer.address.port}/mcp`
: "http://127.0.0.1/mcp";
const hashToken = (token: string) =>
@@ -71,7 +71,7 @@ const deriveServerPathsSync = (baseDir: string, devUrl: URL | undefined) =>
async function waitFor(
predicate: () => boolean | Promise<boolean>,
timeoutMs = 2000,
timeoutMs = 10_000,
): Promise<void> {
const deadline = (await Effect.runPromise(Clock.currentTimeMillis)) + timeoutMs;
const poll = async (): Promise<void> => {
@@ -97,6 +97,27 @@ function makeMemorySecretStore() {
}
describe.sequential("signRelayAgentActivityPublishProof", () => {
it("distinguishes pending link credentials from disabled publication", () => {
expect(
AgentAwarenessRelay.resolveAgentActivityPublishingStartupState({
relayConfigured: false,
publishEnabled: false,
}),
).toBe("waiting-for-link");
expect(
AgentAwarenessRelay.resolveAgentActivityPublishingStartupState({
relayConfigured: true,
publishEnabled: false,
}),
).toBe("disabled");
expect(
AgentAwarenessRelay.resolveAgentActivityPublishingStartupState({
relayConfigured: true,
publishEnabled: true,
}),
).toBe("enabled");
});
it("derives the thread id from the aggregate id for thread events without payload thread ids", () => {
const threadId = "thread-aggregate-1" as ThreadId;
const now = "2026-05-25T00:00:00.000Z";
+53 -19
View File
@@ -100,6 +100,16 @@ export function isAgentActivityPublishingEnabled(value: string | null): boolean
return value === "true";
}
export function resolveAgentActivityPublishingStartupState(input: {
readonly relayConfigured: boolean;
readonly publishEnabled: boolean;
}): "waiting-for-link" | "disabled" | "enabled" {
if (!input.relayConfigured) {
return "waiting-for-link";
}
return input.publishEnabled ? "enabled" : "disabled";
}
const RELAY_AGENT_ACTIVITY_DETAIL_MAX_LENGTH = 160;
const REDACTED_RELAY_AGENT_FAILURE_DETAIL = "The agent run failed.";
@@ -304,7 +314,7 @@ const make = Effect.gen(function* () {
}
const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
if (!relayConfig) {
yield* Effect.logDebug("agent activity publish skipped; T3 Connect config missing", {
yield* Effect.logDebug("agent activity publish skipped; relay link credentials unavailable", {
threadId,
});
return;
@@ -423,7 +433,7 @@ const make = Effect.gen(function* () {
}
const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
if (!relayConfig) {
yield* Effect.logDebug("agent activity snapshot skipped; T3 Connect config missing");
yield* Effect.logDebug("agent activity snapshot skipped; relay link credentials unavailable");
return false;
}
const environmentId = yield* serverEnvironment.getEnvironmentId;
@@ -444,31 +454,55 @@ const make = Effect.gen(function* () {
return true;
});
const publishActiveThreadsOnceWhenConfigured = Effect.gen(function* () {
while (!(yield* Ref.get(activeSnapshotPublishedRef))) {
const published = yield* publishActiveThreadsUnsafe.pipe(Effect.orElseSucceed(() => false));
if (published) {
yield* Ref.set(activeSnapshotPublishedRef, true);
return;
const publishActiveThreadsOnceWhenConfigured = (logEnabledWhenReady: boolean) =>
Effect.gen(function* () {
while (!(yield* Ref.get(activeSnapshotPublishedRef))) {
const published = yield* publishActiveThreadsUnsafe.pipe(Effect.orElseSucceed(() => false));
if (published) {
yield* Ref.set(activeSnapshotPublishedRef, true);
if (logEnabledWhenReady) {
const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
yield* Effect.logInfo("agent activity publishing enabled after link reconciliation", {
relayUrl: relayConfig?.url,
});
}
return;
}
yield* Effect.sleep("5 seconds");
}
yield* Effect.sleep("5 seconds");
}
});
});
const worker = yield* makeDrainableWorker(publishThread);
const start: AgentAwarenessRelayShape["start"] = Effect.fn("AgentAwarenessRelay.start")(
function* () {
const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
if (!relayConfig) {
yield* Effect.logInfo("agent activity publishing standby; T3 Connect config missing");
} else {
yield* Effect.logInfo("agent activity publishing enabled", {
relayUrl: relayConfig.url,
});
const [relayConfig, publishEnabled] = yield* Effect.all([
readRelayConfig.pipe(Effect.orElseSucceed(() => null)),
readPublishAgentActivityEnabled.pipe(Effect.orElseSucceed(() => false)),
]);
const startupState = resolveAgentActivityPublishingStartupState({
relayConfigured: relayConfig !== null,
publishEnabled,
});
switch (startupState) {
case "waiting-for-link":
yield* Effect.logInfo(
"agent activity publishing standby; waiting for T3 Connect link reconciliation",
);
break;
case "disabled":
yield* Effect.logInfo("agent activity publishing disabled by T3 Connect configuration");
break;
case "enabled":
yield* Effect.logInfo("agent activity publishing enabled", {
relayUrl: relayConfig?.url,
});
break;
}
yield* Effect.forkScoped(
Effect.sleep("1 second").pipe(Effect.andThen(publishActiveThreadsOnceWhenConfigured)),
Effect.sleep("1 second").pipe(
Effect.andThen(publishActiveThreadsOnceWhenConfigured(startupState !== "enabled")),
),
);
yield* Effect.forkScoped(
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
+44 -6
View File
@@ -5919,6 +5919,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
() =>
Effect.gen(function* () {
const dispatchedCommands: Array<OrchestrationCommand> = [];
const bootstrapGitOperations: string[] = [];
const refreshStatus = vi.fn((_: string) =>
Effect.succeed({
isRepo: true,
@@ -5937,13 +5938,33 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
pr: null,
}),
);
const fetchRemote = vi.fn(
(_: Parameters<GitVcsDriver.GitVcsDriverShape["fetchRemote"]>[0]) =>
Effect.sync(() => {
bootstrapGitOperations.push("fetch");
}),
);
const fetchedOriginCommit = "0123456789abcdef0123456789abcdef01234567";
const resolveRemoteTrackingCommit = vi.fn(
(_: Parameters<GitVcsDriver.GitVcsDriverShape["resolveRemoteTrackingCommit"]>[0]) =>
Effect.sync(() => {
bootstrapGitOperations.push("resolve-remote-commit");
return {
commitSha: fetchedOriginCommit,
remoteRefName: "origin/main",
};
}),
);
const createWorktree = vi.fn(
(_: Parameters<GitVcsDriver.GitVcsDriverShape["createWorktree"]>[0]) =>
Effect.succeed({
worktree: {
refName: "t3code/bootstrap-refName",
path: "/tmp/bootstrap-worktree",
},
Effect.sync(() => {
bootstrapGitOperations.push("create-worktree");
return {
worktree: {
refName: "t3code/bootstrap-refName",
path: "/tmp/bootstrap-worktree",
},
};
}),
);
const runForThread = vi.fn(
@@ -5960,6 +5981,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
yield* buildAppUnderTest({
layers: {
gitVcsDriver: {
fetchRemote,
resolveRemoteTrackingCommit,
createWorktree,
},
vcsStatusBroadcaster: {
@@ -6011,6 +6034,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
projectCwd: "/tmp/project",
baseBranch: "main",
branch: "t3code/bootstrap-refName",
startFromOrigin: true,
},
runSetupScript: true,
},
@@ -6032,10 +6056,24 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
);
assert.deepEqual(createWorktree.mock.calls[0]?.[0], {
cwd: "/tmp/project",
refName: "main",
refName: fetchedOriginCommit,
newRefName: "t3code/bootstrap-refName",
path: null,
});
assert.deepEqual(fetchRemote.mock.calls[0]?.[0], {
cwd: "/tmp/project",
remoteName: "origin",
});
assert.deepEqual(resolveRemoteTrackingCommit.mock.calls[0]?.[0], {
cwd: "/tmp/project",
refName: "main",
fallbackRemoteName: "origin",
});
assert.deepEqual(bootstrapGitOperations, [
"fetch",
"resolve-remote-commit",
"create-worktree",
]);
assert.deepEqual(runForThread.mock.calls[0]?.[0], {
threadId: ThreadId.make("thread-bootstrap"),
projectId: defaultProjectId,
+2 -2
View File
@@ -126,7 +126,7 @@ const HttpServerLive = Layer.unwrap(
);
return BunHttpServer.layer({
port: config.port,
...(config.host ? { hostname: config.host } : {}),
hostname: config.host ?? "127.0.0.1",
gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,
});
} else {
@@ -135,7 +135,7 @@ const HttpServerLive = Layer.unwrap(
Effect.promise(() => import("node:http")),
]);
return NodeHttpServer.layer(NodeHttp.createServer, {
host: config.host,
host: config.host ?? "127.0.0.1",
port: config.port,
gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,
});
@@ -319,6 +319,31 @@ it.layer(
}),
);
it.effect("keeps attach streams live when a terminal id is closed and reopened", () =>
Effect.gen(function* () {
const { manager, ptyAdapter } = yield* createManager();
const attachEvents = yield* Ref.make<ReadonlyArray<TerminalAttachStreamEvent>>([]);
const unsubscribe = yield* manager.attachStream(openInput(), (event) =>
Ref.update(attachEvents, (events) => [...events, event]),
);
yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
yield* manager.close({
threadId: "thread-1",
terminalId: DEFAULT_TERMINAL_ID,
deleteHistory: true,
});
yield* manager.open(openInput());
const events = yield* Ref.get(attachEvents);
expect(events.map((event) => event.type)).toEqual(["snapshot", "closed", "snapshot"]);
expect(
events.filter((event) => event.type === "snapshot").map((event) => event.snapshot.status),
).toEqual(["running", "running"]);
expect(ptyAdapter.spawnInputs).toHaveLength(2);
}),
);
it.effect("attaches to exited sessions without restarting them", () =>
Effect.gen(function* () {
const { manager, ptyAdapter, getEvents } = yield* createManager();
@@ -478,6 +503,30 @@ it.layer(
}),
);
it.effect("ignores delayed resize requests after a terminal closes", () =>
Effect.gen(function* () {
const { manager, ptyAdapter } = yield* createManager();
yield* manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
yield* manager.close({
threadId: "thread-1",
terminalId: DEFAULT_TERMINAL_ID,
deleteHistory: true,
});
yield* manager.resize({
threadId: "thread-1",
terminalId: DEFAULT_TERMINAL_ID,
cols: 120,
rows: 30,
});
expect(process.resizeCalls).toEqual([]);
}),
);
it.effect("resizes running terminal on open when a different size is requested", () =>
Effect.gen(function* () {
const { manager, ptyAdapter } = yield* createManager();
+16 -12
View File
@@ -5,6 +5,7 @@ import {
type TerminalEvent,
type TerminalMetadataStreamEvent,
type TerminalOpenInput,
type TerminalResizeInput,
type TerminalSessionSnapshot,
type TerminalSessionStatus,
type TerminalSummary,
@@ -2325,22 +2326,25 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
yield* Effect.sync(() => process.write(input.data));
});
const resize: TerminalManagerShape["resize"] = Effect.fn("terminal.resize")(function* (input) {
const terminalId = input.terminalId;
const session = yield* requireSession(input.threadId, terminalId);
const process = session.process;
if (!process || session.status !== "running") {
return yield* new TerminalNotRunningError({
threadId: input.threadId,
terminalId,
});
const resizeLocked = Effect.fn("terminal.resize")(function* (input: TerminalResizeInput) {
const session = yield* getSession(input.threadId, input.terminalId);
// ResizeObserver traffic can already be in flight when the UI closes the session.
if (Option.isNone(session)) {
return;
}
session.cols = input.cols;
session.rows = input.rows;
session.updatedAt = yield* nowIso;
const process = session.value.process;
if (!process || session.value.status !== "running") {
return;
}
session.value.cols = input.cols;
session.value.rows = input.rows;
session.value.updatedAt = yield* nowIso;
yield* Effect.sync(() => process.resize(input.cols, input.rows));
});
const resize: TerminalManagerShape["resize"] = (input) =>
withThreadLock(input.threadId, resizeLocked(input));
const clear: TerminalManagerShape["clear"] = (input) =>
withThreadLock(
input.threadId,
+25
View File
@@ -161,6 +161,22 @@ export interface GitFetchRemoteTrackingBranchInput {
remoteBranch: string;
}
export interface GitFetchRemoteInput {
cwd: string;
remoteName: string;
}
export interface GitResolveRemoteTrackingCommitInput {
cwd: string;
refName: string;
fallbackRemoteName: string;
}
export interface GitResolveRemoteTrackingCommitResult {
commitSha: string;
remoteRefName: string;
}
export interface GitSetBranchUpstreamInput {
cwd: string;
branch: string;
@@ -168,6 +184,10 @@ export interface GitSetBranchUpstreamInput {
remoteBranch: string;
}
export interface GitRemoteStatusOptions {
readonly refreshUpstream?: boolean;
}
export interface GitVcsDriverShape {
readonly execute: (input: ExecuteGitInput) => Effect.Effect<ExecuteGitResult, GitCommandError>;
readonly status: (input: VcsStatusInput) => Effect.Effect<VcsStatusResult, GitCommandError>;
@@ -175,6 +195,7 @@ export interface GitVcsDriverShape {
readonly statusDetailsLocal: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
readonly statusDetailsRemote: (
cwd: string,
options?: GitRemoteStatusOptions,
) => Effect.Effect<GitRemoteStatusDetails, GitCommandError>;
readonly prepareCommitContext: (
cwd: string,
@@ -212,6 +233,10 @@ export interface GitVcsDriverShape {
) => Effect.Effect<void, GitCommandError>;
readonly ensureRemote: (input: GitEnsureRemoteInput) => Effect.Effect<string, GitCommandError>;
readonly resolvePrimaryRemoteName: (cwd: string) => Effect.Effect<string, GitCommandError>;
readonly fetchRemote: (input: GitFetchRemoteInput) => Effect.Effect<void, GitCommandError>;
readonly resolveRemoteTrackingCommit: (
input: GitResolveRemoteTrackingCommitInput,
) => Effect.Effect<GitResolveRemoteTrackingCommitResult, GitCommandError>;
readonly fetchRemoteBranch: (
input: GitFetchRemoteBranchInput,
) => Effect.Effect<void, GitCommandError>;
+126 -20
View File
@@ -183,6 +183,35 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
}),
);
it.effect("can read cached remote divergence without fetching upstream", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const remote = yield* makeTmpDir("git-vcs-driver-remote-");
const updater = yield* makeTmpDir("git-vcs-driver-updater-");
const { initialBranch } = yield* initRepoWithCommit(cwd);
yield* git(remote, ["init", "--bare"]);
yield* git(cwd, ["remote", "add", "origin", remote]);
yield* git(cwd, ["push", "-u", "origin", initialBranch]);
yield* git(updater, ["clone", remote, "."]);
yield* git(updater, ["config", "user.email", "[email protected]"]);
yield* git(updater, ["config", "user.name", "Test"]);
yield* writeTextFile(updater, "remote.txt", "remote\n");
yield* git(updater, ["add", "remote.txt"]);
yield* git(updater, ["commit", "-m", "remote commit"]);
yield* git(updater, ["push", "origin", initialBranch]);
const driver = yield* GitVcsDriver.GitVcsDriver;
const cachedStatus = yield* driver.statusDetailsRemote(cwd, {
refreshUpstream: false,
});
const refreshedStatus = yield* driver.statusDetailsRemote(cwd);
assert.equal(cachedStatus.behindCount, 0);
assert.equal(refreshedStatus.behindCount, 1);
}),
);
it.effect("uses origin HEAD for default-branch detection with a non-origin upstream", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
@@ -216,7 +245,7 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
}),
);
it.effect("disables SSH askpass for background upstream status fetches", () =>
it.effect("makes background upstream status fetches non-interactive", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const tempDir = yield* makeTmpDir("git-vcs-driver-ssh-env-");
@@ -225,15 +254,26 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
const pathService = yield* Path.Path;
const sshLogPath = pathService.join(tempDir, "ssh-env.txt");
const sshWrapperPath = pathService.join(tempDir, "ssh-wrapper.sh");
const previousGitSsh = process.env.GIT_SSH;
const previousAskpassRequire = process.env.SSH_ASKPASS_REQUIRE;
const previousAskpassLog = process.env.T3_TEST_SSH_ASKPASS_LOG;
const envKeys = [
"GCM_INTERACTIVE",
"GIT_ASKPASS",
"GIT_SSH",
"GIT_TERMINAL_PROMPT",
"SSH_ASKPASS",
"SSH_ASKPASS_REQUIRE",
"T3_TEST_SSH_ASKPASS_LOG",
] as const;
const previousEnv = new Map(envKeys.map((key) => [key, process.env[key]]));
yield* fileSystem.writeFileString(
sshWrapperPath,
[
"#!/bin/sh",
'printf "%s\\n" "${SSH_ASKPASS_REQUIRE:-}" > "$T3_TEST_SSH_ASKPASS_LOG"',
'printf "GCM_INTERACTIVE=%s\\n" "${GCM_INTERACTIVE:-}" > "$T3_TEST_SSH_ASKPASS_LOG"',
'printf "GIT_ASKPASS=%s\\n" "${GIT_ASKPASS:-}" >> "$T3_TEST_SSH_ASKPASS_LOG"',
'printf "GIT_TERMINAL_PROMPT=%s\\n" "${GIT_TERMINAL_PROMPT:-}" >> "$T3_TEST_SSH_ASKPASS_LOG"',
'printf "SSH_ASKPASS=%s\\n" "${SSH_ASKPASS:-}" >> "$T3_TEST_SSH_ASKPASS_LOG"',
'printf "SSH_ASKPASS_REQUIRE=%s\\n" "${SSH_ASKPASS_REQUIRE:-}" >> "$T3_TEST_SSH_ASKPASS_LOG"',
"exit 1",
"",
].join("\n"),
@@ -245,29 +285,32 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
yield* Effect.gen(function* () {
process.env.GIT_SSH = sshWrapperPath;
process.env.GCM_INTERACTIVE = "always";
process.env.GIT_ASKPASS = "git-askpass";
process.env.GIT_TERMINAL_PROMPT = "1";
process.env.SSH_ASKPASS = "ssh-askpass";
process.env.SSH_ASKPASS_REQUIRE = "force";
process.env.T3_TEST_SSH_ASKPASS_LOG = sshLogPath;
yield* (yield* GitVcsDriver.GitVcsDriver).statusDetails(cwd);
assert.equal((yield* fileSystem.readFileString(sshLogPath)).trim(), "never");
assert.deepEqual((yield* fileSystem.readFileString(sshLogPath)).trim().split(/\r?\n/), [
"GCM_INTERACTIVE=never",
"GIT_ASKPASS=",
"GIT_TERMINAL_PROMPT=0",
"SSH_ASKPASS=",
"SSH_ASKPASS_REQUIRE=never",
]);
}).pipe(
Effect.ensuring(
Effect.sync(() => {
if (previousGitSsh === undefined) {
delete process.env.GIT_SSH;
} else {
process.env.GIT_SSH = previousGitSsh;
}
if (previousAskpassRequire === undefined) {
delete process.env.SSH_ASKPASS_REQUIRE;
} else {
process.env.SSH_ASKPASS_REQUIRE = previousAskpassRequire;
}
if (previousAskpassLog === undefined) {
delete process.env.T3_TEST_SSH_ASKPASS_LOG;
} else {
process.env.T3_TEST_SSH_ASKPASS_LOG = previousAskpassLog;
for (const key of envKeys) {
const previous = previousEnv.get(key);
if (previous === undefined) {
delete process.env[key];
} else {
process.env[key] = previous;
}
}
}),
),
@@ -399,6 +442,69 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
});
describe("remote operations", () => {
it.effect("creates a worktree from the latest fetched remote commit", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const remote = yield* makeTmpDir("git-remote-");
const peer = yield* makeTmpDir("git-peer-");
const { initialBranch } = yield* initRepoWithCommit(cwd);
yield* git(remote, ["init", "--bare"]);
yield* git(cwd, ["remote", "add", "origin", remote]);
yield* git(cwd, ["push", "-u", "origin", initialBranch]);
yield* git(remote, ["symbolic-ref", "HEAD", `refs/heads/${initialBranch}`]);
const beforeFetch = yield* git(cwd, ["rev-parse", `refs/remotes/origin/${initialBranch}`]);
yield* git(peer, ["clone", remote, "."]);
yield* git(peer, ["config", "user.email", "[email protected]"]);
yield* git(peer, ["config", "user.name", "Test"]);
yield* writeTextFile(peer, "remote-change.txt", "remote\n");
yield* git(peer, ["add", "remote-change.txt"]);
yield* git(peer, ["commit", "-m", "remote change"]);
yield* git(peer, ["push", "origin", initialBranch]);
const remoteHead = yield* git(peer, ["rev-parse", "HEAD"]);
assert.notEqual(beforeFetch, remoteHead);
const driver = yield* GitVcsDriver.GitVcsDriver;
yield* driver.fetchRemote({ cwd, remoteName: "origin" });
const resolvedBase = yield* driver.resolveRemoteTrackingCommit({
cwd,
refName: initialBranch,
fallbackRemoteName: "origin",
});
const explicitlyResolvedBase = yield* driver.resolveRemoteTrackingCommit({
cwd,
refName: `origin/${initialBranch}`,
fallbackRemoteName: "origin",
});
assert.deepEqual(resolvedBase, {
commitSha: remoteHead,
remoteRefName: `origin/${initialBranch}`,
});
assert.deepEqual(explicitlyResolvedBase, resolvedBase);
assert.equal(yield* git(cwd, ["rev-parse", initialBranch]), beforeFetch);
const pathService = yield* Path.Path;
const worktreePath = pathService.join(
yield* makeTmpDir("git-fetched-worktrees-"),
"fetched-origin",
);
yield* driver.createWorktree({
cwd,
path: worktreePath,
refName: resolvedBase.commitSha,
newRefName: "t3code/fetched-origin",
});
assert.equal(yield* git(worktreePath, ["rev-parse", "HEAD"]), remoteHead);
assert.equal(
yield* driver.readConfigValue(worktreePath, "branch.t3code/fetched-origin.remote"),
null,
);
}),
);
it.effect("pushes with upstream setup and skips when already up to date", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
+45 -5
View File
@@ -54,6 +54,10 @@ const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
const STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN = Duration.seconds(5);
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
const STATUS_UPSTREAM_REFRESH_ENV = Object.freeze({
GCM_INTERACTIVE: "never",
GIT_ASKPASS: "",
GIT_TERMINAL_PROMPT: "0",
SSH_ASKPASS: "",
SSH_ASKPASS_REQUIRE: "never",
} satisfies NodeJS.ProcessEnv);
const DEFAULT_BASE_BRANCH_CANDIDATES = ["main", "master"] as const;
@@ -1440,11 +1444,13 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
const statusDetailsRemote: GitVcsDriver.GitVcsDriverShape["statusDetailsRemote"] = Effect.fn(
"statusDetailsRemote",
)(function* (cwd) {
yield* refreshStatusUpstreamIfStale(cwd).pipe(
Effect.catchIf(isMissingGitCwdError, () => Effect.void),
Effect.ignoreCause({ log: true }),
);
)(function* (cwd, options) {
if (options?.refreshUpstream !== false) {
yield* refreshStatusUpstreamIfStale(cwd).pipe(
Effect.catchIf(isMissingGitCwdError, () => Effect.void),
Effect.ignoreCause({ log: true }),
);
}
return yield* readStatusDetailsRemote(cwd);
});
@@ -2182,6 +2188,38 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
);
});
const fetchRemote: GitVcsDriver.GitVcsDriverShape["fetchRemote"] = Effect.fn("fetchRemote")(
function* (input) {
yield* executeGit(
"GitVcsDriver.fetchRemote",
input.cwd,
["fetch", "--quiet", input.remoteName],
{
env: STATUS_UPSTREAM_REFRESH_ENV,
fallbackErrorMessage: `git fetch ${input.remoteName} failed`,
},
);
},
);
const resolveRemoteTrackingCommit: GitVcsDriver.GitVcsDriverShape["resolveRemoteTrackingCommit"] =
Effect.fn("resolveRemoteTrackingCommit")(function* (input) {
const remoteNames = yield* listRemoteNames(input.cwd);
const parsedRemoteRef = parseRemoteRefWithRemoteNames(
input.refName,
remoteNames.toSorted((left, right) => right.length - left.length),
);
const remoteRefName =
parsedRemoteRef?.remoteRef ?? `${input.fallbackRemoteName}/${input.refName}`;
const commitSha = yield* runGitStdout("GitVcsDriver.resolveRemoteTrackingCommit", input.cwd, [
"rev-parse",
"--verify",
`refs/remotes/${remoteRefName}^{commit}`,
]).pipe(Effect.map((stdout) => stdout.trim()));
return { commitSha, remoteRefName };
});
const fetchRemoteBranch: GitVcsDriver.GitVcsDriverShape["fetchRemoteBranch"] = Effect.fn(
"fetchRemoteBranch",
)(function* (input) {
@@ -2407,6 +2445,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
fetchPullRequestBranch,
ensureRemote,
resolvePrimaryRemoteName,
fetchRemote,
resolveRemoteTrackingCommit,
fetchRemoteBranch,
fetchRemoteTrackingBranch,
setBranchUpstream,
@@ -17,6 +17,7 @@ import type {
VcsStatusResult,
VcsStatusStreamEvent,
} from "@t3tools/contracts";
import { GitManagerError } from "@t3tools/contracts";
import * as VcsStatusBroadcaster from "./VcsStatusBroadcaster.ts";
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
@@ -42,6 +43,18 @@ const baseRemoteStatus: VcsStatusRemoteResult = {
pr: null,
};
const remoteStatusWithPr: VcsStatusRemoteResult = {
...baseRemoteStatus,
pr: {
number: 2978,
title: "[codex] Rewrite client connection architecture",
url: "https://github.com/pingdotgg/t3code/pull/2978",
baseRef: "main",
headRef: "codex/connection-state-audit",
state: "open",
},
};
const baseStatus: VcsStatusResult = {
...baseLocalStatus,
...baseRemoteStatus,
@@ -54,6 +67,7 @@ function makeTestLayer(state: {
remoteStatusCalls: number;
localInvalidationCalls: number;
remoteInvalidationCalls: number;
remoteStatusRefreshUpstreamValues?: Array<boolean | undefined>;
}) {
return VcsStatusBroadcaster.layer.pipe(
Layer.provideMerge(NodeServices.layer),
@@ -64,9 +78,10 @@ function makeTestLayer(state: {
state.localStatusCalls += 1;
return state.currentLocalStatus;
}),
remoteStatus: () =>
remoteStatus: (_input, options) =>
Effect.sync(() => {
state.remoteStatusCalls += 1;
state.remoteStatusRefreshUpstreamValues?.push(options?.refreshUpstream);
return state.currentRemoteStatus;
}),
invalidateLocalStatus: () =>
@@ -149,6 +164,71 @@ describe("VcsStatusBroadcaster", () => {
}).pipe(Effect.provide(makeTestLayer(state)));
});
it.effect("keeps the cached snapshot unchanged when a refresh branch fails", () => {
const state = {
currentLocalStatus: baseLocalStatus,
currentRemoteStatus: baseRemoteStatus,
localStatusCalls: 0,
remoteStatusCalls: 0,
localInvalidationCalls: 0,
remoteInvalidationCalls: 0,
failRemoteStatus: false,
};
const testLayer = VcsStatusBroadcaster.layer.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provide(
Layer.mock(GitWorkflowService.GitWorkflowService)({
localStatus: () =>
Effect.sync(() => {
state.localStatusCalls += 1;
return state.currentLocalStatus;
}),
remoteStatus: () =>
Effect.suspend(() => {
state.remoteStatusCalls += 1;
return state.failRemoteStatus
? Effect.fail(
new GitManagerError({
operation: "VcsStatusBroadcaster.test",
detail: "remote status failed",
}),
)
: Effect.succeed(state.currentRemoteStatus);
}),
invalidateLocalStatus: () =>
Effect.sync(() => {
state.localInvalidationCalls += 1;
}),
invalidateRemoteStatus: () =>
Effect.sync(() => {
state.remoteInvalidationCalls += 1;
}),
}),
),
);
return Effect.gen(function* () {
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
yield* broadcaster.getStatus({ cwd: "/repo" });
state.currentLocalStatus = {
...baseLocalStatus,
refName: "feature/partial-refresh",
};
state.currentRemoteStatus = {
...baseRemoteStatus,
aheadCount: 3,
};
state.failRemoteStatus = true;
const refreshExit = yield* broadcaster.refreshStatus("/repo").pipe(Effect.exit);
const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
assert.isTrue(Exit.isFailure(refreshExit));
assert.deepStrictEqual(cached, baseStatus);
}).pipe(Effect.provide(testLayer));
});
it.effect("refreshes only the cached local snapshot when requested", () => {
const state = {
currentLocalStatus: baseLocalStatus,
@@ -286,29 +366,146 @@ describe("VcsStatusBroadcaster", () => {
}).pipe(Effect.provide(makeTestLayer(state)));
});
it.effect("does not start automatic remote refreshes when disabled", () => {
it.effect("loads remote status once when periodic refreshes are disabled", () => {
const state = {
currentLocalStatus: baseLocalStatus,
currentRemoteStatus: baseRemoteStatus,
currentRemoteStatus: remoteStatusWithPr,
localStatusCalls: 0,
remoteStatusCalls: 0,
localInvalidationCalls: 0,
remoteInvalidationCalls: 0,
remoteStatusRefreshUpstreamValues: [] as Array<boolean | undefined>,
};
return Effect.gen(function* () {
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
const snapshot = yield* Stream.runHead(
const scope = yield* Scope.make();
const snapshotDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
const remoteUpdatedDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
yield* Stream.runForEach(
broadcaster.streamStatus(
{ cwd: "/repo" },
{ automaticRemoteRefreshInterval: Effect.succeed(Duration.zero) },
),
);
(event) => {
if (event._tag === "snapshot") {
return Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore);
}
if (event._tag === "remoteUpdated") {
return Deferred.succeed(remoteUpdatedDeferred, event).pipe(Effect.ignore);
}
return Effect.void;
},
).pipe(Effect.forkIn(scope));
assert.isTrue(Option.isSome(snapshot));
assert.equal(state.remoteStatusCalls, 0);
const snapshot = yield* Deferred.await(snapshotDeferred);
const remoteUpdated = yield* Deferred.await(remoteUpdatedDeferred);
assert.deepStrictEqual(snapshot, {
_tag: "snapshot",
local: baseLocalStatus,
remote: null,
} satisfies VcsStatusStreamEvent);
assert.deepStrictEqual(remoteUpdated, {
_tag: "remoteUpdated",
remote: remoteStatusWithPr,
} satisfies VcsStatusStreamEvent);
assert.equal(state.remoteStatusCalls, 1);
assert.equal(state.remoteInvalidationCalls, 0);
}).pipe(Effect.provide(makeTestLayer(state)));
assert.deepStrictEqual(state.remoteStatusRefreshUpstreamValues, [false]);
yield* TestClock.adjust(Duration.minutes(2));
assert.equal(state.remoteStatusCalls, 1);
assert.equal(state.remoteInvalidationCalls, 0);
yield* Scope.close(scope, Exit.void);
}).pipe(Effect.provide(Layer.merge(makeTestLayer(state), TestClock.layer())));
});
it.effect("retries the initial remote load when periodic refreshes are disabled", () => {
const state = {
currentLocalStatus: baseLocalStatus,
localStatusCalls: 0,
remoteStatusCalls: 0,
localInvalidationCalls: 0,
remoteInvalidationCalls: 0,
remoteStatusRefreshUpstreamValues: [] as Array<boolean | undefined>,
};
let firstRemoteAttemptDeferred: Deferred.Deferred<void> | null = null;
const testLayer = VcsStatusBroadcaster.layer.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provide(
Layer.mock(GitWorkflowService.GitWorkflowService)({
localStatus: () =>
Effect.sync(() => {
state.localStatusCalls += 1;
return state.currentLocalStatus;
}),
remoteStatus: (_input, options) =>
Effect.suspend(() => {
state.remoteStatusCalls += 1;
state.remoteStatusRefreshUpstreamValues.push(options?.refreshUpstream);
if (state.remoteStatusCalls === 1) {
return Effect.fail(
new GitManagerError({
operation: "VcsStatusBroadcaster.test",
detail: "initial remote status failed",
}),
).pipe(
Effect.ensuring(
firstRemoteAttemptDeferred
? Deferred.succeed(firstRemoteAttemptDeferred, undefined).pipe(Effect.ignore)
: Effect.void,
),
);
}
return Effect.succeed(remoteStatusWithPr);
}),
invalidateLocalStatus: () =>
Effect.sync(() => {
state.localInvalidationCalls += 1;
}),
invalidateRemoteStatus: () =>
Effect.sync(() => {
state.remoteInvalidationCalls += 1;
}),
}),
),
);
return Effect.gen(function* () {
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
const scope = yield* Scope.make();
firstRemoteAttemptDeferred = yield* Deferred.make<void>();
const remoteUpdatedDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
yield* Stream.runForEach(
broadcaster.streamStatus(
{ cwd: "/repo" },
{ automaticRemoteRefreshInterval: Effect.succeed(Duration.zero) },
),
(event) =>
event._tag === "remoteUpdated"
? Deferred.succeed(remoteUpdatedDeferred, event).pipe(Effect.ignore)
: Effect.void,
).pipe(Effect.forkIn(scope));
yield* Deferred.await(firstRemoteAttemptDeferred);
yield* Effect.yieldNow;
assert.equal(state.remoteStatusCalls, 1);
yield* TestClock.adjust(Duration.seconds(30));
const remoteUpdated = yield* Deferred.await(remoteUpdatedDeferred);
assert.deepStrictEqual(remoteUpdated, {
_tag: "remoteUpdated",
remote: remoteStatusWithPr,
} satisfies VcsStatusStreamEvent);
assert.equal(state.remoteStatusCalls, 2);
assert.equal(state.remoteInvalidationCalls, 0);
assert.deepStrictEqual(state.remoteStatusRefreshUpstreamValues, [false, false]);
yield* Scope.close(scope, Exit.void);
}).pipe(Effect.provide(Layer.merge(testLayer, TestClock.layer())));
});
it.effect("delays automatic refresh when a cached remote snapshot is available", () => {
+84 -34
View File
@@ -179,6 +179,48 @@ export const layer = Layer.effect(
},
);
const updateCachedStatus = Effect.fn("VcsStatusBroadcaster.updateCachedStatus")(function* (
cwd: string,
local: VcsStatusLocalResult,
remote: VcsStatusRemoteResult | null,
options?: { publish?: boolean },
) {
const nextLocal = {
fingerprint: fingerprintStatusPart(local),
value: local,
} satisfies CachedValue<VcsStatusLocalResult>;
const nextRemote = {
fingerprint: fingerprintStatusPart(remote),
value: remote,
} satisfies CachedValue<VcsStatusRemoteResult | null>;
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
const previous = cache.get(cwd) ?? { local: null, remote: null };
const nextCache = new Map(cache);
nextCache.set(cwd, {
local: nextLocal,
remote: nextRemote,
});
return [
previous.local?.fingerprint !== nextLocal.fingerprint ||
previous.remote?.fingerprint !== nextRemote.fingerprint,
nextCache,
] as const;
});
if (options?.publish && shouldPublish) {
yield* PubSub.publish(changesPubSub, {
cwd,
event: {
_tag: "snapshot",
local,
remote,
},
});
}
return mergeGitStatusParts(local, remote);
});
const loadLocalStatus = Effect.fn("VcsStatusBroadcaster.loadLocalStatus")(function* (
cwd: string,
) {
@@ -186,13 +228,6 @@ export const layer = Layer.effect(
return yield* updateCachedLocalStatus(cwd, local);
});
const loadRemoteStatus = Effect.fn("VcsStatusBroadcaster.loadRemoteStatus")(function* (
cwd: string,
) {
const remote = yield* workflow.remoteStatus({ cwd });
return yield* updateCachedRemoteStatus(cwd, remote);
});
const getOrLoadLocalStatus = Effect.fn("VcsStatusBroadcaster.getOrLoadLocalStatus")(function* (
cwd: string,
) {
@@ -203,43 +238,49 @@ export const layer = Layer.effect(
return yield* loadLocalStatus(cwd);
});
const getOrLoadRemoteStatus = Effect.fn("VcsStatusBroadcaster.getOrLoadRemoteStatus")(
function* (cwd: string) {
const cached = yield* getCachedStatus(cwd);
if (cached?.remote) {
return cached.remote.value;
}
return yield* loadRemoteStatus(cwd);
},
);
const withFileSystem = Effect.provideService(FileSystem.FileSystem, fs);
const getStatus: VcsStatusBroadcasterShape["getStatus"] = Effect.fn(
"VcsStatusBroadcaster.getStatus",
)(function* (input) {
const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
const [local, remote] = yield* Effect.all([
getOrLoadLocalStatus(cwd),
getOrLoadRemoteStatus(cwd),
]);
return mergeGitStatusParts(local, remote);
const cached = yield* getCachedStatus(cwd);
if (cached?.local && cached.remote) {
return mergeGitStatusParts(cached.local.value, cached.remote.value);
}
const [local, remote] = yield* Effect.all(
[
cached?.local ? Effect.succeed(cached.local.value) : workflow.localStatus({ cwd }),
cached?.remote ? Effect.succeed(cached.remote.value) : workflow.remoteStatus({ cwd }),
],
{ concurrency: "unbounded" },
);
return yield* updateCachedStatus(cwd, local, remote);
});
const refreshLocalStatusCore = Effect.fn("VcsStatusBroadcaster.refreshLocalStatusCore")(
function* (cwd: string) {
yield* workflow.invalidateLocalStatus(cwd);
const local = yield* workflow.localStatus({ cwd });
return yield* updateCachedLocalStatus(cwd, local, { publish: true });
},
);
const refreshLocalStatus: VcsStatusBroadcasterShape["refreshLocalStatus"] = Effect.fn(
"VcsStatusBroadcaster.refreshLocalStatus",
)(function* (rawCwd) {
const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
yield* workflow.invalidateLocalStatus(cwd);
const local = yield* workflow.localStatus({ cwd });
return yield* updateCachedLocalStatus(cwd, local, { publish: true });
return yield* refreshLocalStatusCore(cwd);
});
const refreshRemoteStatus = Effect.fn("VcsStatusBroadcaster.refreshRemoteStatus")(function* (
cwd: string,
options?: { readonly refreshUpstream?: boolean },
) {
yield* workflow.invalidateRemoteStatus(cwd);
const remote = yield* workflow.remoteStatus({ cwd });
if (options?.refreshUpstream !== false) {
yield* workflow.invalidateRemoteStatus(cwd);
}
const remote = yield* workflow.remoteStatus({ cwd }, options);
return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
});
@@ -247,11 +288,15 @@ export const layer = Layer.effect(
"VcsStatusBroadcaster.refreshStatus",
)(function* (rawCwd) {
const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
const [local, remote] = yield* Effect.all([
refreshLocalStatus(cwd),
refreshRemoteStatus(cwd),
]);
return mergeGitStatusParts(local, remote);
yield* Effect.all(
[workflow.invalidateLocalStatus(cwd), workflow.invalidateRemoteStatus(cwd)],
{ concurrency: "unbounded", discard: true },
);
const [local, remote] = yield* Effect.all(
[workflow.localStatus({ cwd }), workflow.remoteStatus({ cwd })],
{ concurrency: "unbounded" },
);
return yield* updateCachedStatus(cwd, local, remote, { publish: true });
});
const makeRemoteRefreshLoop = (
@@ -261,17 +306,22 @@ export const layer = Layer.effect(
) => {
return Effect.gen(function* () {
const consecutiveFailuresRef = yield* Ref.make(0);
const needsInitialRefreshRef = yield* Ref.make(refreshImmediately);
const refreshRemoteStatusIfEnabled = Effect.gen(function* () {
const configuredInterval = yield* automaticRemoteRefreshInterval;
const activeInterval = Duration.isZero(configuredInterval)
? DEFAULT_VCS_STATUS_REFRESH_INTERVAL
: configuredInterval;
if (Duration.isZero(configuredInterval)) {
const needsInitialRefresh = yield* Ref.get(needsInitialRefreshRef);
if (Duration.isZero(configuredInterval) && !needsInitialRefresh) {
return activeInterval;
}
const exit = yield* refreshRemoteStatus(cwd).pipe(Effect.exit);
const exit = yield* refreshRemoteStatus(cwd, {
refreshUpstream: !Duration.isZero(configuredInterval),
}).pipe(Effect.exit);
if (Exit.isSuccess(exit)) {
yield* Ref.set(needsInitialRefreshRef, false);
yield* Ref.set(consecutiveFailuresRef, 0);
return activeInterval;
}
+14 -1
View File
@@ -694,9 +694,22 @@ const makeWsRpcLayer = (currentSession: AuthenticatedSession) =>
}
if (bootstrap?.prepareWorktree) {
let worktreeBaseRef = bootstrap.prepareWorktree.baseBranch;
if (bootstrap.prepareWorktree.startFromOrigin) {
yield* gitWorkflow.fetchRemote({
cwd: bootstrap.prepareWorktree.projectCwd,
remoteName: "origin",
});
const resolvedRemoteBase = yield* gitWorkflow.resolveRemoteTrackingCommit({
cwd: bootstrap.prepareWorktree.projectCwd,
refName: bootstrap.prepareWorktree.baseBranch,
fallbackRemoteName: "origin",
});
worktreeBaseRef = resolvedRemoteBase.commitSha;
}
const worktree = yield* gitWorkflow.createWorktree({
cwd: bootstrap.prepareWorktree.projectCwd,
refName: bootstrap.prepareWorktree.baseBranch,
refName: worktreeBaseRef,
newRefName: bootstrap.prepareWorktree.branch,
path: null,
});