,
-) =>
- Effect.acquireUseRelease(
- environmentAuth.issueSession({
- scopes: [scope],
- subject: "cloud-cli",
- label: "t3 connect cli",
- }),
- (issued) => run(issued.token),
- (issued) => environmentAuth.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),
- );
-
type LiveCloudActionResult =
| { readonly status: "not-running" }
| { readonly status: "server-gone" }
@@ -329,17 +312,11 @@ const runLiveCloudUnlink = Effect.fn("cloud.cli.run_live_unlink")(function* () {
return { status: "server-gone" } satisfies LiveCloudActionResult;
}
- const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
const result = yield* Effect.exit(
- withCloudCliSessionToken(environmentAuth, AuthRelayWriteScope, (token) =>
- HttpApiClient.make(EnvironmentHttpApi, {
- baseUrl: runtimeState.value.origin,
- }).pipe(
- Effect.flatMap((client) =>
- client.connect.unlink({ headers: { authorization: `Bearer ${token}` } }),
- ),
- Effect.timeout(CLOUD_CLI_LIVE_SERVER_TIMEOUT),
- ),
+ RunningServer.serverClient(runtimeState.value.origin, [AuthRelayWriteScope]).pipe(
+ Effect.flatMap((client) => client.connect.unlink({ headers: {} })),
+ Effect.timeout(CLOUD_CLI_LIVE_SERVER_TIMEOUT),
+ Effect.scoped,
),
);
return Exit.isSuccess(result)
@@ -357,15 +334,12 @@ const checkLiveReachability = Effect.fn("cloud.cli.check_live_reachability")(fun
const config = yield* ServerConfig.ServerConfig;
const runtimeState = yield* readLiveServerRuntimeState(config.serverRuntimeStatePath);
if (Option.isNone(runtimeState)) return null;
- const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
- return yield* withCloudCliSessionToken(environmentAuth, AuthRelayReadScope, (token) =>
- HttpApiClient.make(EnvironmentHttpApi, { baseUrl: runtimeState.value.origin }).pipe(
- Effect.flatMap((client) =>
- client.connect.checkReachability({ headers: { authorization: `Bearer ${token}` } }),
- ),
- Effect.timeout(CLOUD_CLI_REACHABILITY_TIMEOUT),
- ),
- ).pipe(Effect.orElseSucceed(() => null));
+ return yield* RunningServer.serverClient(runtimeState.value.origin, [AuthRelayReadScope]).pipe(
+ Effect.flatMap((client) => client.connect.checkReachability({ headers: {} })),
+ Effect.timeout(CLOUD_CLI_REACHABILITY_TIMEOUT),
+ Effect.scoped,
+ Effect.orElseSucceed(() => null),
+ );
});
function formatAlertBox(text: string): string {
diff --git a/apps/server/src/cli/deferredImports.test.ts b/apps/server/src/cli/deferredImports.test.ts
index c5d55afe7f94..6f4a25507f2f 100644
--- a/apps/server/src/cli/deferredImports.test.ts
+++ b/apps/server/src/cli/deferredImports.test.ts
@@ -80,13 +80,21 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("CLI deferred imp
const runtimeStatePath = NodePath.join(baseDir, "userdata", "server-runtime.json");
yield* persistServerRuntimeState({
path: runtimeStatePath,
- state: yield* makePersistedServerRuntimeState({
- config: { host: "127.0.0.1", devUrl: undefined },
- port: 3_773,
- }),
+ // An owner id skips the legacy liveness probe, so only the free lock decides.
+ state: {
+ ...(yield* makePersistedServerRuntimeState({
+ config: { host: "127.0.0.1", devUrl: undefined },
+ port: 3_773,
+ })),
+ ownerId: "dead-server",
+ },
});
const unreachable: typeof globalThis.fetch = () =>
- Promise.reject(new Error("connection refused"));
+ Promise.reject(
+ new TypeError("fetch failed", {
+ cause: Object.assign(new Error("connect ECONNREFUSED"), { code: "ECONNREFUSED" }),
+ }),
+ );
const exit = yield* runCli(["project", "add", root, "--base-dir", baseDir]).pipe(
Effect.provideService(FetchHttpClient.Fetch, unreachable),
diff --git a/apps/server/src/cli/pair.test.ts b/apps/server/src/cli/pair.test.ts
index 255dae1884bb..baafbca9817a 100644
--- a/apps/server/src/cli/pair.test.ts
+++ b/apps/server/src/cli/pair.test.ts
@@ -14,6 +14,7 @@ import * as Cause from "effect/Cause";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
+import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
@@ -29,6 +30,8 @@ import {
SERVICE_LAUNCHER_PROTOCOL,
} from "../cloud/serviceProtocol.ts";
import * as ServiceLauncherClient from "../cloud/serviceLauncherClient.ts";
+import * as ProcessRunner from "../processRunner.ts";
+import * as ServerOwnership from "../serverOwnership.ts";
import {
makePersistedServerRuntimeState,
persistServerRuntimeState,
@@ -691,6 +694,148 @@ describe("t3 pair", () => {
);
});
+describe("auth session revoke", () => {
+ // Nothing listens on the recorded port; `server` stubs what fetch meets there instead.
+ it.effect.each([
+ {
+ label: "goes through a running server, which closes open connections",
+ recorded: true,
+ lockHeld: false,
+ server: "answers",
+ outcome: "revoked by server",
+ },
+ {
+ label: "writes the database when no server runs",
+ recorded: false,
+ lockHeld: false,
+ server: "none",
+ outcome: "revoked locally",
+ },
+ {
+ label: "writes the database when the recorded server has stopped",
+ recorded: true,
+ lockHeld: false,
+ server: "none",
+ outcome: "revoked locally",
+ },
+ {
+ label: "changes nothing when a running server refuses the connection",
+ recorded: true,
+ lockHeld: true,
+ server: "none",
+ outcome: "RunningServerUnreachableError",
+ },
+ {
+ label: "does not repeat a change locally when the server stops replying mid-request",
+ recorded: true,
+ lockHeld: false,
+ server: "hangs",
+ outcome: "RunningServerNoReplyError",
+ },
+ {
+ label: "does not repeat a change locally when the server answers with an error",
+ recorded: true,
+ lockHeld: false,
+ server: "fails",
+ outcome: "HttpClientError",
+ },
+ ] as const)("$label", ({ recorded, lockHeld, server, outcome }) =>
+ provideCliTestLayers(
+ Effect.gen(function* () {
+ const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-cli-revoke-test-"));
+ const statePath = NodePath.join(baseDir, "userdata", "server-runtime.json");
+ const issued = JSON.parse(
+ yield* captureStdout(
+ runCli(["auth", "session", "issue", "--base-dir", baseDir, "--json"]),
+ ),
+ ) as { readonly sessionId: string };
+ if (recorded) {
+ // A port just released has no listener, so connecting to it is refused.
+ const port = yield* (yield* NetService.NetService).reserveLoopbackPort("127.0.0.1");
+ yield* persistServerRuntimeState({
+ path: statePath,
+ // An owner id skips the legacy liveness probe, so only the lock decides.
+ state: {
+ ...baseState,
+ pid: process.pid,
+ ownerId: "test-owner",
+ port,
+ origin: `http://127.0.0.1:${port}`,
+ },
+ });
+ }
+ if (lockHeld) {
+ yield* ServerOwnership.acquireServerOwnership(statePath).pipe(
+ Effect.provide(ProcessRunner.layer),
+ );
+ }
+
+ const requests: Array<{ readonly path: string; readonly body: unknown }> = [];
+ const requestStarted = Promise.withResolvers();
+ const fetch: typeof globalThis.fetch | undefined =
+ server === "answers" || server === "fails"
+ ? async (input, init) => {
+ requests.push({
+ path: new URL(String(input)).pathname,
+ body: JSON.parse(String(init?.body)),
+ });
+ return server === "answers"
+ ? Response.json({ revoked: true })
+ : new Response(null, { status: 502 });
+ }
+ : server === "hangs"
+ ? (_input, init) => {
+ requestStarted.resolve();
+ return new Promise((_resolve, reject) =>
+ init?.signal?.addEventListener("abort", () => reject(init.signal?.reason)),
+ );
+ }
+ : undefined;
+ const revoke = runCli([
+ "auth",
+ "session",
+ "revoke",
+ "--base-dir",
+ baseDir,
+ issued.sessionId,
+ ]);
+ const running = yield* (
+ fetch === undefined
+ ? revoke
+ : revoke.pipe(Effect.provideService(FetchHttpClient.Fetch, fetch))
+ ).pipe(Effect.exit, Effect.forkChild);
+ if (server === "hangs") {
+ yield* Effect.promise(() => requestStarted.promise);
+ yield* TestClock.adjust("30 seconds");
+ }
+ const exit = yield* Fiber.join(running);
+ const listed = JSON.parse(
+ yield* captureStdout(
+ runCli(["auth", "session", "list", "--base-dir", baseDir, "--json"]),
+ ),
+ ) as ReadonlyArray<{ readonly sessionId: string }>;
+
+ assert.deepEqual(
+ requests,
+ server === "answers" || server === "fails"
+ ? [{ path: "/api/auth/clients/revoke", body: { sessionId: issued.sessionId } }]
+ : [],
+ );
+ if (outcome === "revoked by server" || outcome === "revoked locally") {
+ assert.isTrue(Exit.isSuccess(exit));
+ } else {
+ assert.include(Cause.pretty(Exit.isFailure(exit) ? exit.cause : Cause.empty), outcome);
+ }
+ // The stub server revokes nothing, and the CLI's own session is gone either way.
+ assert.deepEqual(
+ listed.map((session) => session.sessionId),
+ outcome === "revoked locally" ? [] : [issued.sessionId],
+ );
+ }).pipe(Effect.scoped),
+ ),
+ );
+});
+
describe("auth scope options", () => {
it.effect.each([
{ group: "pairing", action: "create" },
diff --git a/apps/server/src/cli/project.test.ts b/apps/server/src/cli/project.test.ts
index 5e33ad84bc12..9c117b76e7d3 100644
--- a/apps/server/src/cli/project.test.ts
+++ b/apps/server/src/cli/project.test.ts
@@ -162,7 +162,7 @@ it.effect.each(["snapshot", "mutation"] as const)(
const isMutation = init?.method === "POST";
if (isMutation) mutations++;
else snapshotRequests++;
- if (slowRequest === "mutation" ? isMutation : !isMutation && snapshotRequests === 2) {
+ if (slowRequest === "mutation" ? isMutation : !isMutation) {
requestReceived.resolve();
await releaseResponse.promise;
}
@@ -191,7 +191,7 @@ it.effect.each(["snapshot", "mutation"] as const)(
releaseResponse.resolve();
yield* Fiber.join(add);
- assert.equal(snapshotRequests, 2);
+ assert.equal(snapshotRequests, 1);
assert.equal(mutations, 1);
assert.deepEqual((yield* readProjects(baseDir)).projects, []);
}).pipe(Effect.provide(NodeServices.layer)),
diff --git a/apps/server/src/cli/project.ts b/apps/server/src/cli/project.ts
index 3e59c5bd4735..ee45ff0cefc6 100644
--- a/apps/server/src/cli/project.ts
+++ b/apps/server/src/cli/project.ts
@@ -1,7 +1,6 @@
import {
AuthStandardClientScopes,
CommandId,
- EnvironmentHttpApi,
EnvironmentHttpCommonError,
type ProjectMutation,
type ProjectSnapshot,
@@ -9,7 +8,6 @@ import {
} from "@t3tools/contracts";
import * as Console from "effect/Console";
import * as SecureRandom from "effect/crypto/SecureRandom";
-import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -19,15 +17,12 @@ import * as References from "effect/References";
import * as Schema from "effect/Schema";
import { Argument, Command, Flag, GlobalFlag } from "effect/cli";
import { FetchHttpClient, HttpClient, HttpClientError } from "effect/http";
-import * as HttpApiClient from "effect/http-api/HttpApiClient";
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as ServerConfig from "../config.ts";
import * as SqlitePersistence from "../persistence/Sqlite.ts";
-import * as ProcessRunner from "../processRunner.ts";
-import * as ServerOwnership from "../serverOwnership.ts";
import type * as RuntimeLayer from "../orchestration-v2/runtimeLayer.ts";
import * as ProjectEnrichmentService from "../project/ProjectEnrichmentService.ts";
import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
@@ -37,12 +32,9 @@ import { projectMutationOperation } from "../project/ProjectMutation.ts";
import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
-import {
- clearPersistedServerRuntimeState,
- readLiveServerRuntimeState,
-} from "../serverRuntimeState.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
import { type CliAuthLocationFlags, projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
+import * as RunningServer from "./runningServer.ts";
type ProjectMutationTarget = {
readonly id: ProjectId;
@@ -50,7 +42,6 @@ type ProjectMutationTarget = {
readonly workspaceRoot: string;
};
-type ProjectCommandExecutionMode = "live" | "offline";
type ProjectCliDispatchCommand = ProjectMutation;
const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
@@ -94,18 +85,6 @@ export class ProjectLiveServerUndeclaredStatusError extends Schema.TaggedError()(
- "ProjectLiveServerRequestError",
- {
- operation: Schema.Literal("callLiveServer"),
- cause: Schema.Defect(),
- },
-) {
- override get message(): string {
- return "Failed to call the running server.";
- }
-}
-
export class ProjectTitleEmptyError extends Schema.TaggedError()(
"ProjectTitleEmptyError",
{
@@ -162,7 +141,6 @@ export const ProjectCommandError = Schema.Union([
ProjectCommandIdGenerationError,
ProjectLiveServerDeclaredResponseError,
ProjectLiveServerUndeclaredStatusError,
- ProjectLiveServerRequestError,
ProjectTitleEmptyError,
ProjectIdentifierEmptyError,
ProjectNotFoundError,
@@ -170,7 +148,8 @@ export const ProjectCommandError = Schema.Union([
]);
export type ProjectCommandError = typeof ProjectCommandError.Type;
-function projectCommandErrorFromLiveServerRequest(cause: unknown): ProjectCommandError {
+/** Names a server's error answer; unanswered requests pass through for `changeState`. */
+function projectCommandErrorFromServerAnswer(cause: E) {
if (isEnvironmentHttpCommonError(cause)) {
return new ProjectLiveServerDeclaredResponseError({
operation: "callLiveServer",
@@ -186,8 +165,7 @@ function projectCommandErrorFromLiveServerRequest(cause: unknown): ProjectComman
cause,
});
}
-
- return new ProjectLiveServerRequestError({ operation: "callLiveServer", cause });
+ return cause;
}
const projectCommandUuid = SecureRandom.SecureRandom.pipe(
@@ -221,26 +199,6 @@ const makeProjectCliRuntimeLayer = (layerProjectService: typeof RuntimeLayer.lay
Layer.provideMerge(SqlitePersistence.layerConfig),
);
-const PROJECT_CLI_LIVE_SERVER_PROBE_TIMEOUT = Duration.seconds(1);
-const PROJECT_CLI_LIVE_SERVER_REQUEST_TIMEOUT = Duration.seconds(10);
-const withProjectCliSessionToken = (
- environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"],
- run: (token: string) => Effect.Effect,
-) =>
- Effect.acquireUseRelease(
- environmentAuth.issueSession({
- scopes: AuthStandardClientScopes,
- label: "t3 project cli",
- }),
- (issued) => run(issued.token),
- (issued) => environmentAuth.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),
- );
-
-const makeLiveServerClient = (origin: string) =>
- HttpApiClient.make(EnvironmentHttpApi, {
- baseUrl: origin,
- });
-
const normalizeWorkspaceRootForProjectCommand = Effect.fn(
"normalizeWorkspaceRootForProjectCommand",
)(function* (workspaceRoot: string) {
@@ -324,72 +282,6 @@ const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (
} satisfies ProjectMutationTarget;
});
-const fetchLiveOrchestrationSnapshot = Effect.fn("project.fetchLiveOrchestrationSnapshot")(
- function* (origin: string, bearerToken: string, _timeout?: Duration.Duration) {
- const client = yield* makeLiveServerClient(origin);
- return yield* client.projects.snapshot({
- headers: { authorization: `Bearer ${bearerToken}` },
- });
- },
- (effect, _origin, _bearerToken, timeout = PROJECT_CLI_LIVE_SERVER_REQUEST_TIMEOUT) =>
- effect.pipe(Effect.timeout(timeout), Effect.mapError(projectCommandErrorFromLiveServerRequest)),
-);
-
-const dispatchLiveOrchestrationCommand = Effect.fn("project.dispatchLiveOrchestrationCommand")(
- function* (origin: string, bearerToken: string, command: ProjectCliDispatchCommand) {
- const client = yield* makeLiveServerClient(origin);
- yield* client.projects.mutate({
- headers: { authorization: `Bearer ${bearerToken}` },
- payload: command,
- } as Parameters[0]);
- },
- (effect, _origin, _bearerToken, _command) =>
- effect.pipe(
- Effect.timeout(PROJECT_CLI_LIVE_SERVER_REQUEST_TIMEOUT),
- Effect.mapError(projectCommandErrorFromLiveServerRequest),
- ),
-);
-
-const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
- const projects = yield* ProjectService.ProjectService;
- return yield* projects.snapshot;
-});
-
-const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecutionMode")(
- function* (
- environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"],
- config: ServerConfig.ServerConfig["Service"],
- ) {
- const runtimeState = yield* readLiveServerRuntimeState(config.serverRuntimeStatePath);
- if (Option.isNone(runtimeState)) {
- return Option.none<{ readonly origin: string }>();
- }
-
- const attempt = withProjectCliSessionToken(environmentAuth, (token) =>
- fetchLiveOrchestrationSnapshot(
- runtimeState.value.origin,
- token,
- PROJECT_CLI_LIVE_SERVER_PROBE_TIMEOUT,
- ).pipe(
- Effect.as({
- origin: runtimeState.value.origin,
- }),
- ),
- );
-
- const attempted = yield* Effect.result(attempt);
- if (attempted._tag === "Success") {
- return Option.some(attempted.success);
- }
-
- yield* Effect.logDebug("Failed to connect to the persisted project CLI server.", {
- origin: runtimeState.value.origin,
- cause: attempted.failure,
- });
- return Option.none<{ readonly origin: string }>();
- },
-);
-
const runProjectMutation = Effect.fn("runProjectMutation")(function* (
flags: CliAuthLocationFlags,
run: (input: {
@@ -397,7 +289,6 @@ const runProjectMutation = Effect.fn("runProjectMutation")(function* (
readonly dispatch: (
command: ProjectCliDispatchCommand,
) => Effect.Effect;
- readonly mode: ProjectCommandExecutionMode;
}) => Effect.Effect<
string,
Error,
@@ -413,54 +304,44 @@ const runProjectMutation = Effect.fn("runProjectMutation")(function* (
const minimumLogLevel = config.logLevel;
return yield* Effect.gen(function* () {
- const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
- const liveMode = yield* tryResolveLiveProjectExecutionMode(environmentAuth, config);
-
- if (Option.isSome(liveMode)) {
- return yield* withProjectCliSessionToken(environmentAuth, (token) =>
- Effect.gen(function* () {
- const snapshot = yield* fetchLiveOrchestrationSnapshot(liveMode.value.origin, token);
- const output = yield* run({
- snapshot,
- dispatch: (command) =>
- dispatchLiveOrchestrationCommand(liveMode.value.origin, token, command),
- mode: "live",
- });
- yield* Console.log(output);
- }),
- );
- }
-
- // Before ownership and clearing, so a failed import leaves server state alone.
- const { layerProjectService } = yield* Effect.promise(
- () => import("../orchestration-v2/runtimeLayer.ts"),
- );
- const layerOfflineRuntime = makeProjectCliRuntimeLayer(layerProjectService).pipe(
- Layer.provide(ServerConfig.layer(config)),
- Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
- );
-
- // An unreachable server may still be running; never write behind it.
- yield* ServerOwnership.acquireServerOwnership(config.serverRuntimeStatePath).pipe(
- Effect.provide(ProcessRunner.layer),
- );
- yield* clearPersistedServerRuntimeState(config.serverRuntimeStatePath);
- return yield* Effect.gen(function* () {
- const snapshot = yield* getOfflineSnapshot();
- const projects = yield* ProjectService.ProjectService;
- const output = yield* run({
- snapshot,
- dispatch: (command) => projectMutationOperation(projects, command).pipe(Effect.asVoid),
- mode: "offline",
- });
- yield* Console.log(output);
- }).pipe(Effect.provide(layerOfflineRuntime));
+ const output = yield* RunningServer.changeState({
+ scopes: AuthStandardClientScopes,
+ viaServer: Effect.fn("project.viaServer")(function* (client) {
+ return yield* run({
+ snapshot: yield* client.projects.snapshot({ headers: {} }),
+ dispatch: (command) =>
+ client.projects.mutate({ headers: {}, payload: command } as Parameters<
+ typeof client.projects.mutate
+ >[0]),
+ });
+ }, Effect.mapError(projectCommandErrorFromServerAnswer)),
+ locally: Effect.promise(() => import("../orchestration-v2/runtimeLayer.ts")).pipe(
+ Effect.flatMap(({ layerProjectService }) =>
+ Effect.gen(function* () {
+ const projects = yield* ProjectService.ProjectService;
+ return yield* run({
+ snapshot: yield* projects.snapshot,
+ dispatch: (command) =>
+ projectMutationOperation(projects, command).pipe(Effect.asVoid),
+ });
+ }).pipe(
+ Effect.provide(
+ makeProjectCliRuntimeLayer(layerProjectService).pipe(
+ Layer.provide(ServerConfig.layer(config)),
+ Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
+ ),
+ ),
+ ),
+ ),
+ ),
+ });
+ yield* Console.log(output);
}).pipe(
Effect.scoped,
Effect.provide(
Layer.mergeAll(EnvironmentAuth.layerRuntime, WorkspacePaths.layer).pipe(
Layer.provideMerge(FetchHttpClient.layer),
- Layer.provide(ServerConfig.layer(config)),
+ Layer.provideMerge(ServerConfig.layer(config)),
Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
),
),
diff --git a/apps/server/src/cli/runningServer.ts b/apps/server/src/cli/runningServer.ts
new file mode 100644
index 000000000000..cf315ff223ae
--- /dev/null
+++ b/apps/server/src/cli/runningServer.ts
@@ -0,0 +1,129 @@
+import { type AuthEnvironmentScope, EnvironmentHttpApi } from "@t3tools/contracts";
+import * as Cause from "effect/Cause";
+import * as Duration from "effect/Duration";
+import * as Effect from "effect/Effect";
+import * as Option from "effect/Option";
+import * as Predicate from "effect/Predicate";
+import * as Schema from "effect/Schema";
+import * as FetchHttpClient from "effect/http/FetchHttpClient";
+import * as HttpClient from "effect/http/HttpClient";
+import * as HttpClientError from "effect/http/HttpClientError";
+import * as HttpClientRequest from "effect/http/HttpClientRequest";
+import * as HttpApiClient from "effect/http-api/HttpApiClient";
+
+import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
+import * as ServerConfig from "../config.ts";
+import * as ProcessRunner from "../processRunner.ts";
+import * as ServerOwnership from "../serverOwnership.ts";
+import {
+ clearPersistedServerRuntimeState,
+ readLiveServerRuntimeState,
+} from "../serverRuntimeState.ts";
+
+export class RunningServerUnreachableError extends Schema.TaggedError()(
+ "RunningServerUnreachableError",
+ { origin: Schema.String, cause: Schema.Defect() },
+) {
+ override get message(): string {
+ return `The T3 Code server at ${this.origin} is running but refused the connection, so nothing was changed. Retry, or restart the server and retry.`;
+ }
+}
+
+export class RunningServerNoReplyError extends Schema.TaggedError()(
+ "RunningServerNoReplyError",
+ { origin: Schema.String, cause: Schema.Defect() },
+) {
+ override get message(): string {
+ return `The T3 Code server at ${this.origin} did not reply, so the change may or may not have been made. Check the current state before you retry.`;
+ }
+}
+
+export type ServerClient = HttpApiClient.ForApi;
+
+// The scope revokes the session; the TTL bounds it if that never runs.
+const SESSION_TTL = Duration.minutes(2);
+const REQUEST_TIMEOUT = Duration.seconds(30);
+
+/** A client of the server at `origin`, signed in as a short-lived session for the scope. */
+export const serverClient = Effect.fn("RunningServer.serverClient")(function* (
+ origin: string,
+ scopes: ReadonlyArray,
+) {
+ const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
+ const session = yield* Effect.acquireRelease(
+ environmentAuth.issueSession({ scopes, subject: "cli", label: "t3 cli", ttl: SESSION_TTL }),
+ ({ sessionId }) => environmentAuth.revokeSession(sessionId).pipe(Effect.ignore({ log: true })),
+ );
+ return yield* HttpApiClient.make(EnvironmentHttpApi, {
+ baseUrl: origin,
+ transformClient: HttpClient.mapRequest(HttpClientRequest.bearerToken(session.token)),
+ }).pipe(Effect.provide(FetchHttpClient.layer));
+});
+
+// The request never reached a server, so it changed nothing there.
+const NOT_CONNECTED_CODES = new Set([
+ "ECONNREFUSED",
+ "ENOTFOUND",
+ "EHOSTUNREACH",
+ "ENETUNREACH",
+ "EADDRNOTAVAIL",
+ "UND_ERR_CONNECT_TIMEOUT",
+]);
+const systemErrorCode = (error: unknown) =>
+ [error, Predicate.hasProperty(error, "cause") ? error.cause : undefined]
+ .map((candidate) => (Predicate.hasProperty(candidate, "code") ? candidate.code : undefined))
+ .find(Predicate.isString);
+const neverConnected = (cause: unknown) => {
+ if (!HttpClientError.isHttpClientError(cause) || cause.reason._tag !== "TransportError") {
+ return false;
+ }
+ const code = systemErrorCode(cause.reason.cause);
+ return code !== undefined && NOT_CONNECTED_CODES.has(code);
+};
+const isUnanswered = (cause: unknown) =>
+ Cause.isTimeoutError(cause) ||
+ (HttpClientError.isHttpClientError(cause) && cause.response === undefined);
+
+/**
+ * Makes a change through the running server, so the server applies it and its clients see it.
+ * With no server, makes it locally while holding the ownership lock, so none starts midway.
+ */
+export const changeState = Effect.fn("RunningServer.changeState")(function* ({
+ scopes,
+ viaServer,
+ locally,
+}: {
+ readonly scopes: ReadonlyArray;
+ readonly viaServer: (client: ServerClient) => Effect.Effect;
+ readonly locally: Effect.Effect;
+}) {
+ const { serverRuntimeStatePath } = yield* ServerConfig.ServerConfig;
+ const changeLocally = (
+ ifServerRuns: (error: ServerOwnership.ServerAlreadyRunningError) => Effect.Effect,
+ ) =>
+ ServerOwnership.acquireServerOwnership(serverRuntimeStatePath).pipe(
+ Effect.provide(ProcessRunner.layer),
+ Effect.catchTags({ ServerAlreadyRunningError: ifServerRuns }),
+ Effect.andThen(locally),
+ // The lock proves the recorded server is gone; drop its record once the change lands.
+ Effect.tap(() => clearPersistedServerRuntimeState(serverRuntimeStatePath)),
+ Effect.scoped,
+ );
+
+ const running = yield* readLiveServerRuntimeState(serverRuntimeStatePath);
+ if (Option.isNone(running)) return yield* changeLocally(Effect.fail);
+ const { origin } = running.value;
+ return yield* serverClient(origin, scopes).pipe(
+ Effect.flatMap(viaServer),
+ Effect.timeout(REQUEST_TIMEOUT),
+ Effect.scoped,
+ // A refused connection reached no server, so the lock decides whether one still runs.
+ Effect.catchIf(neverConnected, (cause) =>
+ changeLocally(() => Effect.fail(new RunningServerUnreachableError({ origin, cause }))),
+ ),
+ // Once connected, the server may have made the change; writing it again could repeat it.
+ Effect.catchIf(isUnanswered, (cause) =>
+ Effect.fail(new RunningServerNoReplyError({ origin, cause })),
+ ),
+ );
+});
diff --git a/apps/server/src/cli/theme.test.ts b/apps/server/src/cli/theme.test.ts
index 15affe279574..b81cf6926c57 100644
--- a/apps/server/src/cli/theme.test.ts
+++ b/apps/server/src/cli/theme.test.ts
@@ -12,11 +12,14 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as TestConsole from "effect/testing/TestConsole";
import { Command } from "effect/cli";
+import { vi } from "vite-plus/test";
import { cli } from "../binCli.ts";
import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
import * as HostProcess from "@t3tools/shared/HostProcess";
+vi.mock("node:fs", { spy: true });
+
// Windows chmod cannot force these directory or file permission failures.
const windowsHost = HostProcess.Platform.defaultValue() === "win32";
@@ -133,6 +136,75 @@ describe("t3 theme", () => {
}),
);
+ it.effect("refuses to publish over a directory with the theme's file name", () =>
+ Effect.gen(function* () {
+ const baseDir = makeBaseDir();
+ const taken = NodePath.join(baseDir, "userdata", "themes", "nightfall.json");
+ NodeFS.mkdirSync(taken, { recursive: true });
+ NodeFS.writeFileSync(NodePath.join(taken, "notes.txt"), "notes");
+ const themeFile = NodePath.join(baseDir, "nightfall.json");
+ NodeFS.writeFileSync(themeFile, NIGHTFALL_THEME_JSON);
+
+ const failure = yield* runCli(["theme", "set", themeFile, "--base-dir", baseDir]).pipe(
+ Effect.flip,
+ );
+
+ assert.include(String(failure), "is a directory");
+ assert.equal(NodeFS.readFileSync(NodePath.join(taken, "notes.txt"), "utf8"), "notes");
+ assert.deepEqual(NodeFS.readdirSync(NodePath.dirname(taken)), ["nightfall.json"]);
+ assert.equal(NodeFS.existsSync(settingsPathFor(baseDir)), false);
+ }),
+ );
+
+ it.effect("refuses to publish over a directory created just before backup", () =>
+ Effect.gen(function* () {
+ const baseDir = makeBaseDir();
+ const themeFile = NodePath.join(baseDir, "nightfall.json");
+ NodeFS.writeFileSync(themeFile, NIGHTFALL_THEME_JSON);
+ const themesDir = NodePath.join(baseDir, "userdata", "themes");
+ const destination = NodePath.join(themesDir, "nightfall.json");
+ const notes = NodePath.join(destination, "notes.txt");
+ const { renameSync } = yield* Effect.promise(() => vi.importActual("node:fs"));
+ using _insertDirectory = vi.spyOn(NodeFS, "renameSync").mockImplementationOnce((from, to) => {
+ NodeFS.mkdirSync(destination);
+ NodeFS.writeFileSync(notes, "notes");
+ renameSync(from, to);
+ });
+
+ const failure = yield* runCli(["theme", "set", themeFile, "--base-dir", baseDir]).pipe(
+ Effect.flip,
+ );
+
+ assert.include(String(failure), "is a directory");
+ assert.equal(NodeFS.readFileSync(notes, "utf8"), "notes");
+ assert.deepEqual(NodeFS.readdirSync(themesDir), ["nightfall.json"]);
+ assert.equal(NodeFS.existsSync(settingsPathFor(baseDir)), false);
+ }),
+ );
+
+ it.effect("publishes a theme despite a rollback file left by an earlier process", () =>
+ Effect.gen(function* () {
+ const baseDir = makeBaseDir();
+ const themeFile = NodePath.join(baseDir, "nightfall.json");
+ NodeFS.writeFileSync(themeFile, NIGHTFALL_THEME_JSON);
+ const themesDir = NodePath.join(baseDir, "userdata", "themes");
+ const destination = NodePath.join(themesDir, "nightfall.json");
+ const staleBackup = `${destination}.rollback-${process.pid}`;
+ NodeFS.mkdirSync(themesDir, { recursive: true });
+ NodeFS.writeFileSync(staleBackup, "previous theme");
+
+ yield* runCli(["theme", "set", themeFile, "--base-dir", baseDir]);
+
+ assert.equal(readSettings(baseDir).defaultTheme, "nightfall");
+ assert.equal(NodeFS.readFileSync(destination, "utf8"), NIGHTFALL_THEME_JSON);
+ assert.equal(NodeFS.readFileSync(staleBackup, "utf8"), "previous theme");
+ assert.deepEqual(NodeFS.readdirSync(themesDir).sort(), [
+ "nightfall.json",
+ NodePath.basename(staleBackup),
+ ]);
+ }),
+ );
+
it.effect("rejects a file that is not a theme and sets nothing", () =>
Effect.gen(function* () {
const baseDir = makeBaseDir();
diff --git a/apps/server/src/cli/theme.ts b/apps/server/src/cli/theme.ts
index 2f692c0a7550..26048240d524 100644
--- a/apps/server/src/cli/theme.ts
+++ b/apps/server/src/cli/theme.ts
@@ -1,6 +1,7 @@
// @effect-diagnostics nodeBuiltinImport:off - publish commits and rollbacks
// move exact directory entries with rename, which the FileSystem service does
// not expose atomically.
+import * as NodeCrypto from "node:crypto";
import * as NodeFS from "node:fs";
import {
@@ -120,6 +121,17 @@ export class ThemePublishError extends Schema.TaggedError()(
}
}
+export class ThemeDestinationDirectoryError extends Schema.TaggedError()(
+ "ThemeDestinationDirectoryError",
+ { themeId: Schema.String, destinationPath: Schema.String },
+) {
+ override get message(): string {
+ return `${this.destinationPath} is a directory, so the theme cannot be published as "${this.themeId}". Move it, or pass another id with --id.`;
+ }
+}
+
+const isThemeDestinationDirectoryError = Schema.is(ThemeDestinationDirectoryError);
+
const INVALID_THEME_ID_REASON =
"is not a valid theme id (lowercase letters, digits, and hyphens; not an appearance keyword)";
@@ -306,8 +318,6 @@ const publishThemeFile = Effect.fn(function* (input: {
}
const destinationPath = path.join(input.themesDir, `${themeId}.json`);
- // Non-JSON suffixes hide these from the watcher; PIDs isolate concurrent publishers.
- const backupPath = `${destinationPath}.rollback-${process.pid}`;
const stagingPath = `${destinationPath}.staging-${process.pid}`;
yield* fs
.makeDirectory(input.themesDir, { recursive: true })
@@ -316,6 +326,14 @@ const publishThemeFile = Effect.fn(function* (input: {
const publishFailure = (cause: unknown) =>
new ThemePublishError({ themesDir: input.themesDir, cause });
+ const destinationIsDirectory = yield* Effect.try({
+ try: () => NodeFS.lstatSync(destinationPath, { throwIfNoEntry: false })?.isDirectory() ?? false,
+ catch: publishFailure,
+ });
+ if (destinationIsDirectory) {
+ return yield* new ThemeDestinationDirectoryError({ themeId, destinationPath });
+ }
+
// O_EXCL prevents following a symlink at the predictable staging path.
// Preserve bytes exactly: even an added newline could exceed the watcher's size limit.
const stagedIno = yield* Effect.try({
@@ -338,19 +356,42 @@ const publishThemeFile = Effect.fn(function* (input: {
catch: publishFailure,
});
- // Atomic rename avoids a check/replace race and preserves the exact entry for rollback.
- const hadPrevious = yield* Effect.try({
+ const backupPath = yield* Effect.try({
try: () => {
+ // A fresh path leaves any backup from a crashed publish intact.
+ const rollbackPath = `${destinationPath}.rollback-${NodeCrypto.randomUUID()}`;
+ // A rename onto a regular file rejects a directory even if it appeared after lstat.
+ const fd = NodeFS.openSync(rollbackPath, "wx", 0o600);
+ let saved = false;
try {
- NodeFS.renameSync(destinationPath, backupPath);
- return true;
+ NodeFS.closeSync(fd);
+ NodeFS.renameSync(destinationPath, rollbackPath);
+ saved = true;
+ return rollbackPath;
} catch (error) {
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
+ if (NodeFS.lstatSync(destinationPath, { throwIfNoEntry: false })?.isDirectory()) {
+ throw new ThemeDestinationDirectoryError({ themeId, destinationPath });
+ }
throw error;
+ } finally {
+ if (!saved) {
+ try {
+ NodeFS.unlinkSync(rollbackPath);
+ } catch {}
+ }
}
},
- catch: publishFailure,
- });
+ catch: (cause) => (isThemeDestinationDirectoryError(cause) ? cause : publishFailure(cause)),
+ }).pipe(
+ Effect.onError(() =>
+ Effect.sync(() => {
+ try {
+ NodeFS.unlinkSync(stagingPath);
+ } catch {}
+ }),
+ ),
+ );
const revert = Effect.sync(() => {
try {
@@ -365,7 +406,7 @@ const publishThemeFile = Effect.fn(function* (input: {
return null;
}
})();
- if (hadPrevious) {
+ if (backupPath !== null) {
if (destinationIno === null || destinationIno === stagedIno) {
NodeFS.renameSync(backupPath, destinationPath);
} else {
@@ -378,7 +419,7 @@ const publishThemeFile = Effect.fn(function* (input: {
});
const cleanup = Effect.sync(() => {
try {
- if (hadPrevious) NodeFS.unlinkSync(backupPath);
+ if (backupPath !== null) NodeFS.unlinkSync(backupPath);
} catch {}
});
diff --git a/apps/server/src/cli/triage.test.ts b/apps/server/src/cli/triage.test.ts
index 05eaf04e1f01..25f7baeb3211 100644
--- a/apps/server/src/cli/triage.test.ts
+++ b/apps/server/src/cli/triage.test.ts
@@ -1,22 +1,139 @@
-// @effect-diagnostics nodeBuiltinImport:off - CLI integration spawns a fake agent from PATH.
+// @effect-diagnostics nodeBuiltinImport:off -- Exercise the CLI with isolated executable fixtures.
+import * as NodeChildProcess from "node:child_process";
import * as NodeFS from "node:fs";
+import * as NodeFSP from "node:fs/promises";
+import * as NodeOS from "node:os";
import * as NodePath from "node:path";
+import * as NodeURL from "node:url";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
+import { assert, it } from "@effect/vitest";
import { TRIAGE_PROMPT_FILE_NAME } from "@t3tools/contracts";
+import * as HostProcess from "@t3tools/shared/HostProcess";
import * as NetService from "@t3tools/shared/Net";
-import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
-import * as TestConsole from "effect/testing/TestConsole";
import { Command } from "effect/cli";
-import { vi } from "vite-plus/test";
+import * as TestConsole from "effect/testing/TestConsole";
+import { expect, vi } from "vite-plus/test";
import { cli } from "../binCli.ts";
import { buildTriageLaunchPrompt } from "../triage/triagePrompt.ts";
+const cliPath = NodeURL.fileURLToPath(new URL("../bin.ts", import.meta.url));
+
+async function fixture(commands: ReadonlyArray) {
+ const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-triage-"));
+ const bin = NodePath.join(root, "bin");
+ const record = NodePath.join(root, "launch.json");
+ await NodeFSP.mkdir(bin);
+ const script = NodePath.join(root, "agent.cjs");
+ await NodeFSP.writeFile(
+ script,
+ `require("node:fs").writeFileSync(process.env.TRIAGE_TEST_RECORD, JSON.stringify({ command: process.argv[2], args: process.argv.slice(3), cwd: process.cwd() }));`,
+ );
+ for (const command of commands) {
+ const windows = HostProcess.Platform.defaultValue() === "win32";
+ const executable = NodePath.join(bin, windows ? `${command}.cmd` : command);
+ const quote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;
+ await NodeFSP.writeFile(
+ executable,
+ windows
+ ? `@"${process.execPath}" "${script}" ${command} %*\r\n`
+ : `#!/bin/sh\nexec ${quote(process.execPath)} ${quote(script)} ${quote(command)} "$@"\n`,
+ { mode: 0o755 },
+ );
+ }
+ return {
+ root,
+ record,
+ run: (args: ReadonlyArray) =>
+ new Promise<{ code: number | null; stdout: string; stderr: string }>((resolve, reject) => {
+ const child = NodeChildProcess.spawn(
+ process.execPath,
+ [cliPath, "triage", "--base-dir", NodePath.join(root, "home with spaces"), ...args],
+ {
+ env: {
+ ...process.env,
+ PATH: bin,
+ TRIAGE_TEST_RECORD: record,
+ },
+ stdio: ["ignore", "pipe", "pipe"],
+ },
+ );
+ let stdout = "";
+ let stderr = "";
+ child.stdout.on("data", (data) => (stdout += String(data)));
+ child.stderr.on("data", (data) => (stderr += String(data)));
+ child.once("error", reject);
+ child.once("close", (code) => resolve({ code, stdout, stderr }));
+ }),
+ async [Symbol.asyncDispose]() {
+ await NodeFSP.rm(root, { recursive: true, force: true });
+ },
+ };
+}
+
+it.live.each([
+ { commands: ["agy", "codex"], agent: "antigravity", command: "agy", model: "test-model" },
+ { commands: ["agy"], agent: undefined, command: "agy", model: undefined },
+ { commands: ["agy", "codex"], agent: "codex", command: "codex", model: "test-model" },
+ { commands: ["agy", "codex", "claude"], agent: "claude", command: "claude", model: undefined },
+])(
+ "launches $command with the triage prompt (agent=$agent, model=$model)",
+ ({ commands, agent, command, model }) =>
+ Effect.promise(async () => {
+ await using setup = await fixture(commands);
+ const result = await setup.run([
+ ...(agent === undefined ? [] : ["--agent", agent]),
+ ...(model === undefined ? [] : ["--model", model]),
+ ]);
+ expect(result.code, result.stdout + result.stderr).toBe(0);
+ const launch = JSON.parse(await NodeFSP.readFile(setup.record, "utf8")) as {
+ command: string;
+ args: string[];
+ cwd: string;
+ };
+ expect(launch.command).toBe(command);
+ expect(launch.args.slice(0, -1)).toEqual([
+ ...(model === undefined ? [] : ["--model", model]),
+ ...(command === "agy" ? ["--prompt-interactive"] : []),
+ ]);
+ expect(launch.args.at(-1)).toContain(NodePath.join(launch.cwd, "triage-playbook.md"));
+ expect(
+ await NodeFSP.readFile(NodePath.join(launch.cwd, "triage-playbook.md"), "utf8"),
+ ).toContain("context.md");
+ }),
+);
+
+it.live(
+ "requires an explicit choice when Codex and Antigravity are installed without a terminal",
+ () =>
+ Effect.promise(async () => {
+ await using setup = await fixture(["agy", "codex"]);
+ const result = await setup.run([]);
+ expect(result.code).toBe(1);
+ expect(result.stdout + result.stderr).toContain("--agent antigravity");
+ expect(result.stdout + result.stderr).toContain("--agent codex");
+ expect(result.stdout + result.stderr).not.toContain("Starting");
+ await expect(NodeFSP.stat(setup.record)).rejects.toMatchObject({ code: "ENOENT" });
+ }),
+);
+
+it.live("reports the missing agy executable when Antigravity is explicitly requested", () =>
+ Effect.promise(async () => {
+ await using setup = await fixture(["codex"]);
+ const result = await setup.run(["--agent", "antigravity"]);
+ expect(result.code).toBe(1);
+ expect(result.stdout + result.stderr).toContain(
+ "`agy` is not installed or was not found on PATH.",
+ );
+ await expect(NodeFSP.stat(setup.record)).rejects.toMatchObject({ code: "ENOENT" });
+ }),
+);
+
const FAILING_AGENT_POSIX = `#!/bin/sh
echo "Error: There is not enough space on the disk. (os error 112)" >&2
exit 1
diff --git a/apps/server/src/cli/triage.ts b/apps/server/src/cli/triage.ts
index c9173a3d4688..cb0f94b25458 100644
--- a/apps/server/src/cli/triage.ts
+++ b/apps/server/src/cli/triage.ts
@@ -22,11 +22,12 @@ import { interactiveStdin } from "./consoleStdin.ts";
import { resolveCliCommand } from "./invocation.ts";
interface TriageAgent {
- readonly id: "claude" | "codex";
+ readonly id: "claude" | "codex" | "antigravity";
readonly command: string;
readonly label: string;
readonly stateDirEnv: string;
readonly defaultStateDir: string;
+ readonly promptArgs?: ReadonlyArray;
}
const TRIAGE_AGENTS: ReadonlyArray = [
@@ -44,6 +45,14 @@ const TRIAGE_AGENTS: ReadonlyArray = [
stateDirEnv: "CODEX_HOME",
defaultStateDir: ".codex",
},
+ {
+ id: "antigravity",
+ command: "agy",
+ label: "Antigravity",
+ stateDirEnv: "GEMINI_HOME",
+ defaultStateDir: ".gemini",
+ promptArgs: ["--prompt-interactive"],
+ },
];
const resolveAgentStateDir = (agent: TriageAgent) =>
@@ -63,7 +72,7 @@ export class TriageAgentChoiceRequiredError extends Schema.TaggedError
Effect.gen(function* () {
@@ -179,7 +188,9 @@ export const triageCommand = Command.make("triage", {
if (requested !== undefined) {
selected = installed.find((agent) => agent.id === requested);
if (selected === undefined) {
- return yield* new TriageAgentUnavailableError({ agent: requested });
+ return yield* new TriageAgentUnavailableError({
+ agent: TRIAGE_AGENTS.find((agent) => agent.id === requested)?.command ?? requested,
+ });
}
} else if (installed.length === 1) {
selected = installed[0];
@@ -197,7 +208,7 @@ export const triageCommand = Command.make("triage", {
if (selected === undefined) {
yield* Console.log(
[
- "No supported agent CLI (claude, codex) was found on this machine.",
+ "No supported agent CLI (claude, codex, agy) was found on this machine.",
"",
...describeTriageFiles(session),
"",
@@ -211,6 +222,7 @@ export const triageCommand = Command.make("triage", {
const launchPrompt = buildTriageLaunchPrompt(promptFilePath);
const spawnSpec = yield* resolveSpawnCommand(selected.command, [
...(model === undefined ? [] : ["--model", model]),
+ ...(selected.promptArgs ?? []),
launchPrompt,
]);
yield* Console.log(`Starting ${selected.label}. It will ask what went wrong.\n`);
diff --git a/apps/server/src/cloud/CloudLink.lifecycle.test.ts b/apps/server/src/cloud/CloudLink.lifecycle.test.ts
index cbbf4670d6f6..a71a8f00b81c 100644
--- a/apps/server/src/cloud/CloudLink.lifecycle.test.ts
+++ b/apps/server/src/cloud/CloudLink.lifecycle.test.ts
@@ -1,6 +1,7 @@
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "@effect/vitest";
+import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -10,22 +11,11 @@ import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
-import {
- HttpClient,
- HttpClientResponse,
- HttpServer,
- HttpServerRequest,
- type HttpClientRequest,
-} from "effect/http";
+import { HttpClient, HttpClientResponse, HttpServer, type HttpClientRequest } from "effect/http";
import { RELAY_LINK_PROOF_TYP, signRelayJwt, verifyRelayJwt } from "@t3tools/shared/relayJwt";
import * as NetAddress from "effect/net/NetAddress";
-import {
- AuthSessionId,
- type AuthEnvironmentScope,
- EnvironmentAuthenticatedPrincipal,
- EnvironmentId,
-} from "@t3tools/contracts";
+import { EnvironmentId } from "@t3tools/contracts";
import * as EnvironmentKeys from "./environmentKeys.ts";
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
@@ -268,11 +258,14 @@ describe("releaseManagedTunnelOnShutdown", () => {
),
),
- Effect.provide(
+ Effect.provide([
ServerConfigModule.layerTest("/", { prefix: "t3-http-release-test-" }).pipe(
Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
),
- ),
+ ConfigProvider.layer(
+ ConfigProvider.fromEnv({ env: { T3CODE_RELAY_URL: "https://relay.example.test" } }),
+ ),
+ ]),
Effect.scoped,
);
@@ -308,30 +301,16 @@ describe("releaseManagedTunnelOnShutdown", () => {
});
yield* TestClock.setTime((relayNow + skewSeconds) * 1_000);
const link = yield* CloudLink.CloudLink;
- const proof = yield* link
- .linkProof(
- {
- challenge,
- relayIssuer,
- endpoint: {
- httpBaseUrl: "http://127.0.0.1:3773",
- wsBaseUrl: "ws://127.0.0.1:3773",
- providerKind: "manual",
- },
- origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
- },
- HttpServerRequest.fromWeb(
- new Request("http://127.0.0.1:3773/api/t3-connect/link-proof"),
- ),
- )
- .pipe(
- Effect.provideService(EnvironmentAuthenticatedPrincipal, {
- sessionId: AuthSessionId.make("test-session"),
- subject: "test",
- method: "bearer-access-token",
- scopes: new Set(),
- }),
- );
+ const proof = yield* link.linkProof({
+ challenge,
+ relayIssuer,
+ endpoint: {
+ httpBaseUrl: "http://127.0.0.1:3773",
+ wsBaseUrl: "ws://127.0.0.1:3773",
+ providerKind: "manual",
+ },
+ origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
+ });
const environmentKeys =
yield* EnvironmentKeys.getOrCreateEnvironmentKeyPairFromSecretStore(store);
yield* TestClock.setTime(relayNow * 1_000);
@@ -400,6 +379,20 @@ describe("releaseManagedTunnelOnShutdown", () => {
}).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
});
+ it.effect("releases a tunnel only through the configured relay", () => {
+ const { store, values } = makeMemorySecretStore(managedLinkSecrets);
+ values.set(RELAY_URL_SECRET, new TextEncoder().encode("https://old-relay.example.test"));
+ const applyConfigCalls: Array = [];
+ const requests: Array = [];
+
+ return Effect.gen(function* () {
+ const link = yield* CloudLink.CloudLink;
+ expect(yield* link.releaseManagedTunnelOnShutdown()).toBe(false);
+ expect(applyConfigCalls).toEqual([]);
+ expect(requests).toEqual([]);
+ }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
+ });
+
it.effect("leaves the tunnel of a web/mobile-installed link untouched", () => {
const { store, values } = makeMemorySecretStore([
[CLOUD_ENDPOINT_RUNTIME_CONFIG, "runtime-config"],
@@ -715,28 +708,117 @@ describe("releaseManagedTunnelOnShutdown", () => {
);
});
- it.effect("clears the revoked mark when the environment is linked again", () => {
- const { store } = makeMemorySecretStore([
+ it.effect.each([
+ {
+ name: "replaces a revoked link to another account",
+ revoked: true,
+ startup: false,
+ cloudUserId: "user-456",
+ },
+ {
+ name: "replaces a revoked link to the same account",
+ revoked: true,
+ startup: false,
+ cloudUserId: "user-123",
+ },
+ {
+ name: "replaces a revoked link after a partial drop removed its user id",
+ revoked: true,
+ startup: false,
+ cloudUserId: "user-456",
+ partialDrop: true,
+ },
+ {
+ name: "rejects switching an active link to another account",
+ revoked: false,
+ startup: false,
+ cloudUserId: "user-456",
+ },
+ {
+ name: "keeps a revoked link when startup links another account",
+ revoked: true,
+ startup: true,
+ cloudUserId: "user-456",
+ },
+ ])("$name", ({ revoked, startup, cloudUserId, partialDrop }) => {
+ const { store, values } = makeMemorySecretStore([
[RELAY_URL_SECRET, "https://relay.example.test"],
- [CLOUD_LINKED_USER_ID, "user-123"],
- [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "revoked-credential"],
- [CLOUD_LINK_REVOKED, "true"],
+ ...(partialDrop ? [] : [[CLOUD_LINKED_USER_ID, "user-123"] as const]),
+ [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "old-credential"],
+ ...(revoked ? [[CLOUD_LINK_REVOKED, "true"] as const] : []),
+ [CLOUD_CLI_DESIRED_LINK_SECRET, startup ? "publish_only" : "managed"],
]);
const cloudMintPublicKey =
"-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAqZ2u2LjMoAyG2QTHXmITJ9w6RzZtVUAv394XCcPV0zE=\n-----END PUBLIC KEY-----";
return Effect.gen(function* () {
const link = yield* CloudLink.CloudLink;
- expect((yield* link.linkState()).linkRevoked).toBe(true);
- yield* link.applyRelayConfig({
- relayUrl: "https://relay.example.test",
- cloudUserId: "user-123",
- environmentCredential: "fresh-credential",
- cloudMintPublicKey,
- endpointRuntime: null,
+ expect((yield* link.linkState()).linkRevoked).toBe(revoked && !partialDrop);
+ const relink = Effect.gen(function* () {
+ if (startup) {
+ yield* link.reconcileDesiredLinkIfStillDesired("http://127.0.0.1:3773");
+ } else {
+ yield* link.applyRelayConfig({
+ relayUrl: "https://relay.example.test",
+ cloudUserId,
+ environmentCredential: "fresh-credential",
+ cloudMintPublicKey,
+ endpointRuntime: null,
+ });
+ }
});
- expect(yield* link.linkState()).toMatchObject({ linked: true, linkRevoked: false });
- }).pipe(provideReleaseHarness({ store, applyConfigCalls: [], requests: [] }));
+ const result = yield* relink.pipe(
+ Effect.provide(
+ ConfigProvider.layer(
+ ConfigProvider.fromEnv({ env: { T3CODE_RELAY_URL: "https://relay.example.test" } }),
+ ),
+ ),
+ Effect.flip,
+ Effect.option,
+ );
+ if (revoked && !startup) {
+ expect(result).toEqual(Option.none());
+ expect(yield* link.linkState()).toMatchObject({
+ linked: true,
+ linkRevoked: false,
+ cloudUserId,
+ });
+ expect(new TextDecoder().decode(values.get(RELAY_ENVIRONMENT_CREDENTIAL_SECRET))).toBe(
+ "fresh-credential",
+ );
+ expect(values.has(CLOUD_CLI_DESIRED_LINK_SECRET)).toBe(cloudUserId === "user-123");
+ } else {
+ expect(Option.getOrThrow(result)).toBeInstanceOf(CloudLink.CloudLinkAccountMismatchError);
+ expect(yield* link.linkState()).toMatchObject({
+ cloudUserId: "user-123",
+ linkRevoked: revoked,
+ });
+ expect(values.has(CLOUD_CLI_DESIRED_LINK_SECRET)).toBe(true);
+ }
+ }).pipe(
+ provideReleaseHarness({
+ store,
+ applyConfigCalls: [],
+ requests: [],
+ respond: () =>
+ Response.json({
+ challenge: "challenge-1",
+ expiresAt: "2099-01-01T00:00:00.000Z",
+ ok: true,
+ cloudUserId: "user-456",
+ environmentId: "env_123",
+ endpoint: {
+ httpBaseUrl: "http://127.0.0.1:3773",
+ wsBaseUrl: "ws://127.0.0.1:3773",
+ providerKind: "manual",
+ },
+ endpointRuntime: null,
+ relayIssuer: "https://relay.example.test",
+ environmentCredential: "fresh-credential",
+ cloudMintPublicKey,
+ }),
+ }),
+ );
});
it.effect(
diff --git a/apps/server/src/cloud/CloudLink.ts b/apps/server/src/cloud/CloudLink.ts
index 0e31ca736aae..8f9dc8c60f34 100644
--- a/apps/server/src/cloud/CloudLink.ts
+++ b/apps/server/src/cloud/CloudLink.ts
@@ -1,5 +1,4 @@
import {
- EnvironmentAuthenticatedPrincipal,
type EnvironmentCloudLinkStateResult,
type EnvironmentCloudPreferencesRequest,
type EnvironmentCloudRelayConfigResult,
@@ -38,7 +37,7 @@ import {
RELAY_MINT_RESPONSE_TYP,
verifyRelayJwt,
} from "@t3tools/shared/relayJwt";
-import { isSecureRelayUrl } from "@t3tools/shared/relayUrl";
+import { isSecureRelayUrl, normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";
import * as Context from "effect/Context";
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as Signature from "effect/crypto/Signature";
@@ -46,6 +45,7 @@ import * as Jwk from "effect/jose/Jwk";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
+import * as FetchHttpClient from "effect/http/FetchHttpClient";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
@@ -54,12 +54,7 @@ import type * as PlatformError from "effect/PlatformError";
import * as Schedule from "effect/Schedule";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
-import {
- HttpClient,
- HttpClientRequest,
- HttpClientResponse,
- type HttpServerRequest,
-} from "effect/http";
+import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
import type * as HttpClientError from "effect/http/HttpClientError";
import * as HttpServer from "effect/http/HttpServer";
@@ -72,6 +67,7 @@ import { makeRelayEnvironmentClient } from "../relay/relayEnvironmentClient.ts";
import { loopbackUrlHostForAddress } from "../startupAccess.ts";
import {
type CliDesiredLinkMode,
+ dropRevokedCloudLink,
readCliDesiredCloudLink,
readCliDesiredLinkMode,
setCliDesiredCloudLink,
@@ -110,13 +106,11 @@ import {
import {
hasBoundedCloudProofLifetime,
hasExactScope,
- hasForwardedAuthorityHeaders,
- isAllowedEndpointOrigin,
+ isLoopbackEndpointOrigin,
isSupportedLinkProviderKind,
linkProofScopes,
managedEndpointRuntimeConfigsMatch,
parseManagedEndpointLocalOrigin,
- requestAbsoluteUrl,
} from "./linkChecks.ts";
import { desktopUpdateRestartPending, pendingUpdateHandoffExists } from "./updateHandoff.ts";
@@ -251,6 +245,7 @@ const INTERNAL_OPERATION_MESSAGES = {
"persist-recovered-tunnel": "Could not persist the recovered managed tunnel configuration.",
"read-relay-config": "Could not read environment relay configuration.",
"remove-relay-config": "Could not remove environment relay configuration.",
+ "update-live-activity-preference": "Could not update T3 Connect Live Activity preferences.",
"update-webhook-settings": "Could not update T3 Connect webhook settings.",
"read-preferences": "Could not read environment cloud preferences.",
"persist-preferences": "Could not persist environment cloud preferences.",
@@ -414,21 +409,15 @@ type ManagedTunnelRegistration =
export class CloudLink extends Context.Service<
CloudLink,
{
- /**
- * Signs the proof the relay asks for to link this environment. The request
- * must reach this server directly. Desktop bootstrap sessions may use the
- * WSL IP; all other sessions must use the loopback origin they name.
- */
+ /** Signs the proof the relay asks for to link this environment, for this server's own origin. */
readonly linkProof: (
request: RelayLinkProofRequest,
- httpRequest: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<
RelayEnvironmentLinkProof,
| CloudLinkOriginInvalidError
| CloudLinkInternalError
| EnvironmentAuth.ServerAuthInternalError
- | ManagedLimits.ManagedPolicyRefusedError,
- EnvironmentAuthenticatedPrincipal
+ | ManagedLimits.ManagedPolicyRefusedError
>;
readonly applyRelayConfig: (
payload: RelayEnvironmentConfigRequest,
@@ -455,6 +444,12 @@ export class CloudLink extends Context.Service<
EnvironmentCloudLinkStateResult,
CloudLinkNotLinkedError | CloudLinkInternalError | ManagedLimits.ManagedPolicyRefusedError
>;
+ readonly updateLiveActivityPreference: (
+ enabled: boolean,
+ ) => Effect.Effect<
+ RelayOkResponse,
+ CloudLinkInternalError | ManagedLimits.ManagedPolicyRefusedError
+ >;
readonly answerHealthRequest: (
request: RelayCloudEnvironmentHealthRequest,
) => Effect.Effect<
@@ -578,21 +573,28 @@ const make = Effect.gen(function* () {
),
);
+ // The tunnel must reach this server, so the signed origin is its own loopback address, never the caller's.
+ const serverLoopbackOrigin = Effect.gen(function* () {
+ const address = httpServer.address;
+ if (typeof address === "string" || !("port" in address)) {
+ return yield* new CloudLinkInternalError({ operation: "resolve-server-origin" });
+ }
+ const { origin } = parseManagedEndpointLocalOrigin(
+ `http://${loopbackUrlHostForAddress(address)}:${address.port}`,
+ );
+ if (!isLoopbackEndpointOrigin(origin)) {
+ return yield* new CloudLinkOriginInvalidError({ origin: "local" });
+ }
+ return origin;
+ });
+
const makeCloudLinkProof = Effect.fn("environment.cloud.makeLinkProof")(function* (
request: RelayLinkProofRequest,
- requestUrl: string,
- allowNonLoopbackRequestHost = false,
) {
- if (
- !isSupportedLinkProviderKind(request) ||
- !isAllowedEndpointOrigin({
- origin: request.origin,
- requestUrl,
- allowNonLoopbackRequestHost,
- })
- ) {
+ if (!isSupportedLinkProviderKind(request)) {
return yield* new CloudLinkOriginInvalidError({ origin: "endpoint" });
}
+ const origin = yield* serverLoopbackOrigin;
const now = yield* DateTime.now;
const nowSeconds = Math.floor(now.epochMilliseconds / 1_000);
// Borrow only the relay clock; the relay still verifies and consumes the challenge.
@@ -615,7 +617,7 @@ const make = Effect.gen(function* () {
environmentId: descriptor.environmentId,
environmentPublicKey: normalizePemForSignedPayload(signingKey.publicKey),
endpoint: request.endpoint,
- origin: request.origin,
+ origin,
scopes: linkProofScopes(request),
} satisfies RelayEnvironmentLinkProofPayload;
return yield* signingKey
@@ -634,18 +636,8 @@ const make = Effect.gen(function* () {
});
const linkProof = Effect.fn("environment.cloud.linkProof")(
- function* (request: RelayLinkProofRequest, httpRequest: HttpServerRequest.HttpServerRequest) {
- const requestUrl = requestAbsoluteUrl(httpRequest);
- if (requestUrl === null || hasForwardedAuthorityHeaders(httpRequest)) {
- return yield* new CloudLinkOriginInvalidError({ origin: "endpoint" });
- }
- const principal = yield* EnvironmentAuthenticatedPrincipal;
- // WSL desktop requests use the distro IP; only the server-issued bootstrap subject qualifies.
- return yield* makeCloudLinkProof(
- request,
- requestUrl,
- principal.subject === "desktop-bootstrap",
- );
+ function* (request: RelayLinkProofRequest) {
+ return yield* makeCloudLinkProof(request);
},
Effect.catchIf(ServerSecretStore.isSecretStoreError, internalError("generate-link-proof")),
);
@@ -758,11 +750,11 @@ const make = Effect.gen(function* () {
options?: {
readonly lockHeld?: boolean;
readonly confirmedOrigin?: RelayManagedEndpointOrigin;
+ readonly replaceRevokedLink?: boolean;
},
) {
const apply = Effect.gen(function* () {
yield* validateRelayConfigPayload(payload);
- yield* validateLinkedCloudUser(payload.cloudUserId);
yield* validateCloudMintPublicKey(payload.cloudMintPublicKey);
// Reject unsupported runtimes before they can stop a healthy tunnel.
if (
@@ -777,6 +769,26 @@ const make = Effect.gen(function* () {
},
});
}
+ // Only an explicit link replaces a revoked one: a clock-skew 401 can mark a live link revoked.
+ if (options?.replaceRevokedLink === true) {
+ const [revoked, previousUserId] = yield* Effect.all([
+ secrets.get(CLOUD_LINK_REVOKED),
+ secrets.get(CLOUD_LINKED_USER_ID),
+ ]);
+ // The CLI token may belong to the old account. Release it before the drop so a failed
+ // write leaves the revoked mark for a retry; a partial drop can leave no user id.
+ if (
+ Option.isSome(revoked) &&
+ Option.match(previousUserId, {
+ onNone: () => true,
+ onSome: (userId) => bytesToString(userId) !== payload.cloudUserId,
+ })
+ ) {
+ yield* setCliDesiredCloudLink(false).pipe(withSecrets);
+ }
+ yield* dropRevokedCloudLink.pipe(withSecrets);
+ }
+ yield* validateLinkedCloudUser(payload.cloudUserId);
const endpointRuntimeJson = payload.endpointRuntime
? yield* encodeEndpointRuntimeConfigJson(payload.endpointRuntime)
: null;
@@ -869,19 +881,16 @@ const make = Effect.gen(function* () {
},
schema: RelayEnvironmentLinkChallengeResponse,
});
- const proof = yield* makeCloudLinkProof(
- {
- challenge: challenge.challenge,
- relayIssuer: relayUrl,
- endpoint: {
- httpBaseUrl: parsedOrigin.httpBaseUrl,
- wsBaseUrl: parsedOrigin.wsBaseUrl,
- providerKind: managedTunnelsEnabled ? "cloudflare_tunnel" : "manual",
- },
- origin: parsedOrigin.origin,
+ const proof = yield* makeCloudLinkProof({
+ challenge: challenge.challenge,
+ relayIssuer: relayUrl,
+ endpoint: {
+ httpBaseUrl: parsedOrigin.httpBaseUrl,
+ wsBaseUrl: parsedOrigin.wsBaseUrl,
+ providerKind: managedTunnelsEnabled ? "cloudflare_tunnel" : "manual",
},
- parsedOrigin.httpBaseUrl,
- );
+ origin: parsedOrigin.origin,
+ });
const link = yield* relayClientRequest({
url: `${relayUrl}/v1/client/environment-links`,
token: token.accessToken,
@@ -1169,7 +1178,7 @@ const make = Effect.gen(function* () {
const applyRelayConfig = Effect.fn("environment.cloud.relayConfig")(
function* (payload: RelayEnvironmentConfigRequest) {
- const result = yield* applyCloudRelayConfig(payload);
+ const result = yield* applyCloudRelayConfig(payload, { replaceRevokedLink: true });
if (payload.endpointRuntime?.providerKind === "cloudflare_tunnel") {
const address = httpServer.address;
if (typeof address === "string" || !("port" in address)) {
@@ -1232,22 +1241,27 @@ const make = Effect.gen(function* () {
yield* Effect.logInfo("Keeping the managed tunnel across the update restart");
return false;
}
- const token = yield* cliTokenManager.getExisting;
- if (Option.isNone(token)) {
+ const relayUrl = yield* requireRelayUrl.pipe(Effect.option);
+ const installedRelayUrl = yield* secrets.get(RELAY_URL_SECRET);
+ if (
+ Option.isNone(relayUrl) ||
+ Option.isNone(installedRelayUrl) ||
+ normalizeSecureRelayUrl(bytesToString(installedRelayUrl.value)) !== relayUrl.value
+ ) {
return false;
}
- // Use the persisted relay URL; T3CODE_RELAY_URL may have changed since linking.
- const relayUrl = yield* secrets.get(RELAY_URL_SECRET);
- if (Option.isNone(relayUrl)) {
+ const token = yield* cliTokenManager.getExisting;
+ if (Option.isNone(token)) {
return false;
}
const environmentId = yield* environment.getEnvironmentId;
yield* endpointRuntime.applyConfig(null);
const response = yield* HttpClientRequest.delete(
- `${bytesToString(relayUrl.value)}/v1/client/environment-links/${encodeURIComponent(environmentId)}/tunnel`,
+ `${relayUrl.value}/v1/client/environment-links/${encodeURIComponent(environmentId)}/tunnel`,
).pipe(
HttpClientRequest.bearerToken(token.value.accessToken),
httpClient.execute,
+ Effect.provideService(FetchHttpClient.RequestInit, { redirect: "error" }),
Effect.flatMap(filterRelayResponse),
Effect.flatMap(HttpClientResponse.schemaBodyJson(RelayOkResponse)),
withRelayClientTracing,
@@ -1425,6 +1439,37 @@ const make = Effect.gen(function* () {
Effect.catchIf(ServerSecretStore.isSecretStoreError, internalError("read-preferences")),
);
+ const updateLiveActivityPreference = Effect.fn("environment.cloud.updateLiveActivityPreference")(
+ function* (liveActivitiesEnabled: boolean) {
+ return yield* endpointRuntime.withLinkStateLock(
+ Effect.gen(function* () {
+ const connection = yield* readRelayConnection.pipe(withSecrets);
+ const cloudUserId = yield* secrets.get(CLOUD_LINKED_USER_ID);
+ const revoked = yield* secrets.get(CLOUD_LINK_REVOKED);
+ if (connection === null || Option.isNone(cloudUserId) || Option.isSome(revoked)) {
+ return { ok: false };
+ }
+ const environmentId = yield* environment.getEnvironmentId;
+ const client = yield* makeRelayEnvironmentClient(connection);
+ return yield* client.server
+ .updateLiveActivityPreference({
+ params: { environmentId },
+ payload: { cloudUserId: bytesToString(cloudUserId.value), liveActivitiesEnabled },
+ })
+ .pipe(
+ Effect.provideService(FetchHttpClient.RequestInit, { redirect: "error" }),
+ Effect.timeout("10 seconds"),
+ Effect.catch(internalError("update-live-activity-preference")),
+ );
+ }),
+ );
+ },
+ Effect.catchIf(
+ ServerSecretStore.isSecretStoreError,
+ internalError("update-live-activity-preference"),
+ ),
+ );
+
const answerHealthRequest = Effect.fn("environment.cloud.health")(
function* (request: RelayCloudEnvironmentHealthRequest) {
const cloudMintPublicKey = yield* secrets
@@ -1654,6 +1699,7 @@ const make = Effect.gen(function* () {
linkState,
unlink,
updatePreferences: refused,
+ updateLiveActivityPreference: refused,
answerHealthRequest: refused,
mintCredential: refused,
reconcileDesiredLinkIfStillDesired: notDesired,
@@ -1670,6 +1716,7 @@ const make = Effect.gen(function* () {
linkState,
unlink,
updatePreferences,
+ updateLiveActivityPreference,
answerHealthRequest,
mintCredential,
reconcileDesiredLinkIfStillDesired,
diff --git a/apps/server/src/cloud/http.test.ts b/apps/server/src/cloud/http.test.ts
index 35d9b346ee83..5115a27e6301 100644
--- a/apps/server/src/cloud/http.test.ts
+++ b/apps/server/src/cloud/http.test.ts
@@ -43,7 +43,6 @@ import * as ServerSettings from "../serverSettings.ts";
const DESKTOP_BOOTSTRAP_TOKEN = "test-desktop-bootstrap-token";
const NON_LOOPBACK_ORIGIN = "http://172.24.162.233:3773";
-const LOOPBACK_ORIGIN = "http://127.0.0.1:3773";
const proofRequest: RelayLinkProofRequest = {
challenge: "test-challenge",
relayIssuer: "https://relay.example.test",
@@ -99,7 +98,9 @@ const layerLinkProofRoutes = HttpApiBuilder.layer(LinkProofTestApi).pipe(
capabilities: { repositoryIdentity: false },
}),
}),
- Layer.mock(ManagedEndpointRuntime.CloudManagedEndpointRuntime)({}),
+ Layer.mock(ManagedEndpointRuntime.CloudManagedEndpointRuntime)({
+ withLinkStateLock: (effect) => effect,
+ }),
Layer.mock(CliTokenManager.CloudCliTokenManager)({}),
Layer.mock(AgentAwarenessRelay.AgentAwarenessRelay)({}),
Layer.mock(HttpServer.HttpServer)({
@@ -158,10 +159,10 @@ const linkProofClient = Effect.gen(function* () {
const payload = (yield* responseJson(response)) as { access_token: string };
return payload.access_token;
});
- const linkableHere = (token: string, origin = NON_LOOPBACK_ORIGIN) =>
+ const linkableHere = (token: string) =>
Effect.promise(() =>
handler(
- new Request(`${origin}/api/connect/link-state`, {
+ new Request(`${NON_LOOPBACK_ORIGIN}/api/connect/link-state`, {
headers: { authorization: `Bearer ${token}` },
}),
),
@@ -172,16 +173,27 @@ const linkProofClient = Effect.gen(function* () {
return { post, exchange, linkableHere };
});
-describe("link proof over a non-loopback desktop transport", () => {
+describe("link proof over a non-loopback transport", () => {
it.effect(
- "signs a loopback tunnel origin after desktop bootstrap token exchange over a non-loopback host",
+ "signs this server's loopback origin for a remote client allowed to configure the relay",
() =>
Effect.gen(function* () {
const { post, exchange } = yield* linkProofClient;
- const token = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN);
- const response = yield* post("/api/connect/link-proof", proofRequest, {
- authorization: `Bearer ${token}`,
- });
+ const admin = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN);
+ const paired = yield* post(
+ "/api/auth/pairing-token",
+ { scopes: ["relay:read", "relay:configure"] },
+ { authorization: `Bearer ${admin}` },
+ );
+ expect(paired.status).toBe(200);
+ const { credential } = (yield* responseJson(paired)) as { credential: string };
+ const token = yield* exchange(credential);
+ // The caller's origin and forwarding headers must not steer the tunnel elsewhere.
+ const response = yield* post(
+ "/api/connect/link-proof",
+ { ...proofRequest, origin: { localHttpHost: "172.24.162.233", localHttpPort: 5432 } },
+ { authorization: `Bearer ${token}`, "x-forwarded-host": "evil.example.test" },
+ );
expect(response.status).toBe(200);
expect(response.headers.get("cache-control")).toBe("no-store");
const proof = (yield* responseJson(response)) as string;
@@ -197,104 +209,89 @@ describe("link proof over a non-loopback desktop transport", () => {
audience: proofRequest.relayIssuer,
});
expect(verified).toMatchObject({
- origin: proofRequest.origin,
+ origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
endpoint: proofRequest.endpoint,
challenge: proofRequest.challenge,
});
}).pipe(Effect.provide(NodeCrypto.layerSignature)),
);
- it.effect(
- "does not pass desktop trust to a paired client or accept client-supplied provenance",
- () =>
- Effect.gen(function* () {
- const { post, exchange, linkableHere } = yield* linkProofClient;
- const desktop = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN);
- const paired = yield* post(
- "/api/auth/pairing-token",
- {
- scopes: ["relay:read", "relay:write"],
- label: "desktop-bootstrap",
- subject: "desktop-bootstrap",
- },
- { authorization: `Bearer ${desktop}` },
- );
- expect(paired.status).toBe(200);
- const { credential } = (yield* responseJson(paired)) as { credential: string };
- const token = yield* exchange(credential);
- const headers = { authorization: `Bearer ${token}`, "x-desktop-bootstrap": "true" };
- const payload = {
- ...proofRequest,
- allowNonLoopbackRequestHost: true,
- subject: "desktop-bootstrap",
- };
- const rejected = yield* post("/api/connect/link-proof", payload, headers);
- expect(rejected.status).toBe(400);
- expect(yield* responseJson(rejected)).toMatchObject({
- message: "Invalid managed endpoint origin.",
- });
- const loopback = yield* post(
- "/api/connect/link-proof",
- proofRequest,
- headers,
- LOOPBACK_ORIGIN,
+ it.effect("offers Turn on to any session allowed to configure the relay", () =>
+ Effect.gen(function* () {
+ const { post, exchange, linkableHere } = yield* linkProofClient;
+ const desktop = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN);
+ const pair = (scopes: ReadonlyArray) =>
+ post("/api/auth/pairing-token", { scopes }, { authorization: `Bearer ${desktop}` }).pipe(
+ Effect.flatMap(responseJson),
+ Effect.flatMap((paired) => exchange((paired as { credential: string }).credential)),
);
- expect(loopback.status).toBe(200);
- // Clients offer Turn on only to the desktop's own session; SSH forwards look like loopback.
- expect(yield* linkableHere(desktop)).toBe(true);
- expect(yield* linkableHere(token)).toBe(false);
- expect(yield* linkableHere(token, LOOPBACK_ORIGIN)).toBe(false);
- }),
+ expect(yield* linkableHere(desktop)).toBe(true);
+ const remote = yield* pair(["relay:read", "relay:write", "relay:configure"]);
+ expect(yield* linkableHere(remote)).toBe(true);
+ expect(yield* linkableHere(yield* pair(["relay:read", "relay:write"]))).toBe(false);
+ expect(yield* linkableHere(yield* pair(["relay:read", "relay:configure"]))).toBe(false);
+ }),
);
- it.effect.each([
- {
- name: "non-loopback tunnel origin",
- origin: { localHttpHost: "172.24.162.233", localHttpPort: 3773 },
- headers: {},
- },
- {
- name: "mismatched port",
- origin: { localHttpHost: "127.0.0.1", localHttpPort: 3774 },
- headers: {},
- },
- {
- name: "forwarded host",
- origin: proofRequest.origin,
- headers: { "x-forwarded-host": "127.0.0.1:3773" },
- },
- {
- name: "forwarded protocol",
- origin: proofRequest.origin,
- headers: { "x-forwarded-proto": "http" },
- },
- ])("rejects $name even for desktop bootstrap", ({ origin, headers }) =>
+ it.effect("requires relay configuration permission even for desktop bootstrap", () =>
Effect.gen(function* () {
const { post, exchange } = yield* linkProofClient;
- const token = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN);
- const response = yield* post(
- "/api/connect/link-proof",
- { ...proofRequest, origin },
- { ...headers, authorization: `Bearer ${token}` },
- );
- expect(response.status).toBe(400);
+ const token = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN, "relay:write");
+ const response = yield* post("/api/connect/link-proof", proofRequest, {
+ authorization: `Bearer ${token}`,
+ });
+ expect(response.status).toBe(403);
expect(yield* responseJson(response)).toMatchObject({
- message: "Invalid managed endpoint origin.",
+ code: "insufficient_scope",
+ requiredScope: "relay:write",
+ requiredPermission: "relay:configure",
});
}),
);
- it.effect("requires relay-write scope even for desktop bootstrap", () =>
+ it.effect("allows relay writers to set preferences without creating a link", () =>
Effect.gen(function* () {
const { post, exchange } = yield* linkProofClient;
- const token = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN, "relay:read");
- const response = yield* post("/api/connect/link-proof", proofRequest, {
- authorization: `Bearer ${token}`,
- });
+ const path = "/api/connect/live-activity-preference";
+ const payload = { liveActivitiesEnabled: true };
+ const readToken = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN, "relay:read");
+ const denied = yield* post(path, payload, { authorization: `Bearer ${readToken}` });
+ expect(denied.status).toBe(403);
+
+ const writeToken = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN, "relay:write");
+ const unlinked = yield* post(path, payload, { authorization: `Bearer ${writeToken}` });
+ expect(unlinked.status).toBe(200);
+ expect(yield* responseJson(unlinked)).toEqual({ ok: false });
+ }),
+ );
+
+ it.effect("requires explicit permission to configure the relay", () =>
+ Effect.gen(function* () {
+ const { post, exchange } = yield* linkProofClient;
+ const admin = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN);
+ const paired = yield* post(
+ "/api/auth/pairing-token",
+ {},
+ { authorization: `Bearer ${admin}` },
+ );
+ expect(paired.status).toBe(200);
+ const { credential } = (yield* responseJson(paired)) as { credential: string };
+ const token = yield* exchange(credential);
+ const response = yield* post(
+ "/api/connect/relay-config",
+ {
+ relayUrl: "https://relay.example.test",
+ cloudUserId: "test-link-owner",
+ environmentCredential: "test-environment-credential",
+ cloudMintPublicKey: "test-public-key",
+ endpointRuntime: null,
+ },
+ { authorization: `Bearer ${token}` },
+ );
expect(response.status).toBe(403);
expect(yield* responseJson(response)).toMatchObject({
code: "insufficient_scope",
- requiredScope: "relay:write",
+ requiredPermission: "relay:configure",
});
}),
);
diff --git a/apps/server/src/cloud/http.ts b/apps/server/src/cloud/http.ts
index c95fcf051bd6..84491a274398 100644
--- a/apps/server/src/cloud/http.ts
+++ b/apps/server/src/cloud/http.ts
@@ -1,5 +1,6 @@
import {
AuthRelayReadScope,
+ AuthRelayConfigureScope,
AuthRelayWriteScope,
EnvironmentCloudEndpointUnavailableError,
EnvironmentHttpApi,
@@ -11,7 +12,7 @@ import {
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as HttpEffect from "effect/http/HttpEffect";
-import { HttpServerRequest, HttpServerResponse } from "effect/http";
+import { HttpServerResponse } from "effect/http";
import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
import { requireEnvironmentScope } from "../auth/http.ts";
@@ -19,7 +20,6 @@ import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
import * as ManagedLimits from "../policy/managedLimits.ts";
import * as CloudLink from "./CloudLink.ts";
import * as ConnectReachability from "./ConnectReachability.ts";
-import { canLinkHere } from "./linkChecks.ts";
import type { RelayRequestError } from "./relayResponse.ts";
import { traceRelayRequest } from "./traceRelayRequest.ts";
@@ -117,24 +117,27 @@ export const layer = HttpApiBuilder.group(
return handlers
.handle("linkProof", ({ payload }) =>
Effect.gen(function* () {
- yield* requireEnvironmentScope(AuthRelayWriteScope);
- const request = yield* HttpServerRequest.HttpServerRequest;
- const proof = yield* toHttpError(cloudLink.linkProof(payload, request));
+ yield* requireEnvironmentScope(AuthRelayConfigureScope);
+ const proof = yield* toHttpError(cloudLink.linkProof(payload));
yield* appendCloudCredentialResponseHeaders;
return proof;
}),
)
.handle("relayConfig", ({ payload }) =>
- requireEnvironmentScope(AuthRelayWriteScope).pipe(
- Effect.andThen(toHttpErrorOrUnavailable(cloudLink.applyRelayConfig(payload))),
- ),
+ Effect.gen(function* () {
+ yield* requireEnvironmentScope(AuthRelayConfigureScope);
+ return yield* toHttpErrorOrUnavailable(cloudLink.applyRelayConfig(payload));
+ }),
)
.handle("linkState", () =>
Effect.gen(function* () {
const principal = yield* requireEnvironmentScope(AuthRelayReadScope);
const state = yield* toHttpError(cloudLink.linkState());
- const request = yield* HttpServerRequest.HttpServerRequest;
- return { ...state, linkableHere: canLinkHere(request, principal.subject) };
+ // Linking also writes relay preferences, so configure alone cannot finish it.
+ const linkableHere =
+ principal.scopes.has(AuthRelayConfigureScope) &&
+ principal.scopes.has(AuthRelayWriteScope);
+ return { ...state, linkableHere };
}),
)
.handle("checkReachability", () =>
@@ -150,6 +153,13 @@ export const layer = HttpApiBuilder.group(
Effect.andThen(toHttpError(cloudLink.updatePreferences(payload))),
),
)
+ .handle("liveActivityPreference", ({ payload }) =>
+ requireEnvironmentScope(AuthRelayWriteScope).pipe(
+ Effect.andThen(
+ toHttpError(cloudLink.updateLiveActivityPreference(payload.liveActivitiesEnabled)),
+ ),
+ ),
+ )
.handle("health", ({ payload }) =>
toHttpError(cloudLink.answerHealthRequest(payload)).pipe(
Effect.tap(() => appendCloudCredentialResponseHeaders),
diff --git a/apps/server/src/cloud/linkChecks.ts b/apps/server/src/cloud/linkChecks.ts
index 607e2c08f8a5..6b8f19e60a69 100644
--- a/apps/server/src/cloud/linkChecks.ts
+++ b/apps/server/src/cloud/linkChecks.ts
@@ -4,7 +4,6 @@ import type {
RelayManagedEndpointOrigin,
RelayManagedEndpointRuntimeConfig,
} from "@t3tools/contracts/relay";
-import type { HttpServerRequest } from "effect/http";
const CLOUD_PROOF_MAX_LIFETIME_SECONDS = 5 * 60;
const CLOUD_PROOF_CLOCK_SKEW_SECONDS = 60;
@@ -21,33 +20,6 @@ function isLoopbackHostname(hostname: string): boolean {
return LOOPBACK_HOSTNAMES.has(normalizeHostname(hostname));
}
-function firstForwardedHeaderValue(value: string | undefined): string | undefined {
- const first = value?.split(",")[0]?.trim();
- return first && first.length > 0 ? first : undefined;
-}
-
-export function requestAbsoluteUrl(request: HttpServerRequest.HttpServerRequest): string | null {
- try {
- return new URL(request.originalUrl).href;
- } catch {
- const host = firstForwardedHeaderValue(request.headers.host) ?? "127.0.0.1";
- try {
- return new URL(request.originalUrl, `http://${host}`).href;
- } catch {
- return null;
- }
- }
-}
-
-export function hasForwardedAuthorityHeaders(
- request: HttpServerRequest.HttpServerRequest,
-): boolean {
- return (
- firstForwardedHeaderValue(request.headers["x-forwarded-host"]) !== undefined ||
- firstForwardedHeaderValue(request.headers["x-forwarded-proto"]) !== undefined
- );
-}
-
function endpointRequestPort(url: URL): number {
return Number(url.port || (url.protocol === "https:" ? 443 : 80));
}
@@ -79,37 +51,8 @@ export function parseManagedEndpointLocalOrigin(localOrigin: string) {
};
}
-/**
- * Whether clients should offer to turn on T3 Connect over this session: only the desktop app's
- * own bootstrap session, from any address (WSL answers on a distro IP), never through a proxy.
- * A loopback address alone does not count, since SSH port forwards look like loopback too.
- */
-export function canLinkHere(
- request: HttpServerRequest.HttpServerRequest,
- subject: string,
-): boolean {
- return (
- subject === "desktop-bootstrap" &&
- requestAbsoluteUrl(request) !== null &&
- !hasForwardedAuthorityHeaders(request)
- );
-}
-
-export function isAllowedEndpointOrigin(input: {
- readonly origin: RelayManagedEndpointOrigin;
- readonly requestUrl: string;
- readonly allowNonLoopbackRequestHost?: boolean;
-}): boolean {
- if (!isLoopbackHostname(input.origin.localHttpHost)) {
- return false;
- }
-
- const url = new URL(input.requestUrl);
- if (!input.allowNonLoopbackRequestHost && !isLoopbackHostname(url.hostname)) {
- return false;
- }
-
- return input.origin.localHttpPort === endpointRequestPort(url);
+export function isLoopbackEndpointOrigin(origin: RelayManagedEndpointOrigin): boolean {
+ return isLoopbackHostname(origin.localHttpHost);
}
export function isSupportedLinkProviderKind(request: RelayLinkProofRequest): boolean {
diff --git a/apps/server/src/cloud/pinnedRuntime.test.ts b/apps/server/src/cloud/pinnedRuntime.test.ts
index 0c016a504c9b..7e4d69482eeb 100644
--- a/apps/server/src/cloud/pinnedRuntime.test.ts
+++ b/apps/server/src/cloud/pinnedRuntime.test.ts
@@ -236,14 +236,38 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => {
}),
);
- it.effect("retries a release archive whose body fails after the host answered", () =>
+ it.effect.each([
+ { name: "body fails after the host answered", first: "body fails", honorsRange: true },
+ {
+ name: "body stalls and its resume ends early",
+ first: "body stalls",
+ honorsRange: true,
+ shortResume: true,
+ },
+ { name: "body stalls on a host that ignores Range", first: "body stalls", honorsRange: false },
+ { name: "response headers stall", first: "headers stall", honorsRange: true },
+ {
+ name: "whole body arrives and then stalls",
+ first: "body stalls",
+ honorsRange: true,
+ wholeArchive: true,
+ },
+ ] as const)("resumes a release archive download when its $name", (row) =>
Effect.gen(function* () {
+ const { first, honorsRange } = row;
+ const shortResume = "shortResume" in row;
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-retry-body-" });
const checksums = yield* validChecksums;
- let archiveRequests = 0;
+ const ranges: Array = [];
+ const checksumRanges: Array = [];
+ const progress: PinnedRuntimeProgress[] = [];
+ const checksumsRequested = yield* Deferred.make();
const archiveRequested = yield* Deferred.make();
+ const shortResumeRequested = yield* Deferred.make();
+ const total = archiveBytes.length;
+ const heldBytes = "wholeArchive" in row ? archiveBytes : archiveBytes.slice(0, 4);
const install = yield* ensurePinnedRuntimeInstalled({
baseDir,
version,
@@ -252,21 +276,72 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => {
platform: "linux",
arch: "x64",
httpClient: HttpClient.make((request) => {
- const isChecksums = request.url.endsWith("/SHA256SUMS");
+ if (request.url.endsWith("/SHA256SUMS")) {
+ checksumRanges.push(request.headers["range"]);
+ const response = HttpClientResponse.fromWeb(request, new Response(checksums));
+ if (checksumRanges.length > 1) return Effect.succeed(response);
+ Deferred.doneUnsafe(checksumsRequested, Effect.void);
+ // The checksums fail once after a prefix, which their retry must not resume from.
+ const failingBody = Stream.concat(
+ Stream.make(new TextEncoder().encode(checksums).slice(0, 8)),
+ Stream.fail(
+ new HttpClientError.HttpClientError({
+ reason: new HttpClientError.DecodeError({ request, response }),
+ }),
+ ),
+ );
+ return Effect.sleep("1 second").pipe(
+ Effect.as(
+ Object.create(response, { stream: { value: failingBody } }),
+ ),
+ );
+ }
+ const range = request.headers["range"];
+ ranges.push(range);
+ if (ranges.length > 1) {
+ const start = honorsRange ? Number(/^bytes=(\d+)-$/.exec(range ?? "")?.[1] ?? 0) : 0;
+ // A short resume stops one byte early; the next retry asks for that byte.
+ const end = shortResume && ranges.length === 2 ? total - 1 : total;
+ const response = HttpClientResponse.fromWeb(
+ request,
+ start >= total
+ ? new Response("", {
+ status: 416,
+ headers: { "content-range": `bytes */${total}` },
+ })
+ : start > 0
+ ? new Response(archiveBytes.slice(start, end), {
+ status: 206,
+ headers: { "content-range": `bytes ${start}-${end - 1}/${total}` },
+ })
+ : new Response(archiveBytes, { headers: { "content-length": `${total}` } }),
+ );
+ if (end === total) return Effect.succeed(response);
+ Deferred.doneUnsafe(shortResumeRequested, Effect.void);
+ // An Effect stream keeps the body, and so the retry wait after it, on the test clock.
+ const body = Stream.make(archiveBytes.slice(start, end));
+ return Effect.sleep("1 second").pipe(
+ Effect.as(
+ Object.create(response, { stream: { value: body } }),
+ ),
+ );
+ }
+ Deferred.doneUnsafe(archiveRequested, Effect.void);
+ if (first === "headers stall") return Effect.never;
const response = HttpClientResponse.fromWeb(
request,
- new Response(isChecksums ? checksums : archiveBytes),
+ new Response(archiveBytes, { headers: { "content-length": `${total}` } }),
);
- if (isChecksums || ++archiveRequests > 1) return Effect.succeed(response);
const failingBody = Stream.concat(
- Stream.make(archiveBytes.slice(0, 4)),
- Stream.fail(
- new HttpClientError.HttpClientError({
- reason: new HttpClientError.DecodeError({ request, response }),
- }),
- ),
+ Stream.make(heldBytes),
+ first === "body stalls"
+ ? Stream.never
+ : Stream.fail(
+ new HttpClientError.HttpClientError({
+ reason: new HttpClientError.DecodeError({ request, response }),
+ }),
+ ),
);
- Deferred.doneUnsafe(archiveRequested, Effect.void);
// TestClock follows the work a woken sleep starts, so one adjust reaches the retry wait.
return Effect.sleep("1 second").pipe(
Effect.as(
@@ -276,12 +351,34 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => {
}),
runner: extractingRunner(fs, path),
validate: () => Effect.void,
+ onProgress: (event) => progress.push(event),
}).pipe(Effect.forkScoped);
- yield* Deferred.await(archiveRequested);
+ yield* Deferred.await(checksumsRequested);
yield* TestClock.adjust(Duration.seconds(3));
+ yield* Deferred.await(archiveRequested);
+ // The one-minute stall bound, then the first two-second retry backoff.
+ yield* TestClock.adjust(Duration.seconds(first === "body fails" ? 3 : 63));
+ if (shortResume) {
+ yield* Deferred.await(shortResumeRequested);
+ // Its one-second delay, then the second, four-second backoff.
+ yield* TestClock.adjust(Duration.seconds(5));
+ }
const paths = yield* Fiber.join(install);
+ assert.deepEqual(checksumRanges, [undefined, undefined]);
+ assert.deepEqual(ranges, [
+ undefined,
+ first === "headers stall" ? undefined : `bytes=${heldBytes.length}-`,
+ ...(shortResume ? [`bytes=${total - 1}-`] : []),
+ ]);
assert.equal(yield* fs.readFileString(paths.sentinelPath), `${version}\n`);
- assert.equal(archiveRequests, 2);
+ assert.deepEqual(
+ progress.findLast((event) => event.stage === "download"),
+ {
+ stage: "download",
+ received: total,
+ total,
+ },
+ );
}),
);
diff --git a/apps/server/src/cloud/pinnedRuntime.ts b/apps/server/src/cloud/pinnedRuntime.ts
index 09c8145a4a61..08180f80a67a 100644
--- a/apps/server/src/cloud/pinnedRuntime.ts
+++ b/apps/server/src/cloud/pinnedRuntime.ts
@@ -126,54 +126,120 @@ const DOWNLOAD_RETRY = { times: 3, schedule: Schedule.exponential("2 seconds") }
const isTransientDownloadFailure = (
error: HttpClientError.HttpClientError | Cause.TimeoutError,
): boolean => {
- // No answer or a stall means the host cannot reach the release source; retrying only delays that.
- if (error._tag === "TimeoutError") return false;
+ // A slow link stalls past the bound and then recovers; the retry resumes from the bytes held.
+ if (error._tag === "TimeoutError") return true;
// Body bytes are read raw, so a DecodeError is a body that failed after the host answered.
if (error.reason._tag === "DecodeError") return true;
const status = error.response?.status;
return status !== undefined && (status >= 500 || status === 429 || status === 408);
};
+const CONTENT_RANGE = /^bytes (\d+)-\d+\/(\d+|\*)$/;
+
+const concatChunks = (chunks: ReadonlyArray, length: number): Uint8Array => {
+ const bytes = new Uint8Array(length);
+ let offset = 0;
+ for (const chunk of chunks) {
+ bytes.set(chunk, offset);
+ offset += chunk.byteLength;
+ }
+ return bytes;
+};
+
const fetchReleaseAsset = Effect.fn("cloud.pinned_runtime.fetch_release_asset")(function* (
httpClient: HttpClient.HttpClient,
url: string,
step: string,
+ // Only a digest-checked asset resumes; anything else restarts at byte 0 on each retry.
+ resume: boolean,
onProgress?: (progress: PinnedRuntimeProgress) => void,
) {
+ // Bytes from earlier attempts outlive the retry so a stalled download resumes with Range.
+ let chunks: Array = [];
+ let received = 0;
// Bound stalls while holding the install lock, but allow transfers that keep
// receiving bytes to finish regardless of their total duration.
- return yield* httpClient.execute(HttpClientRequest.get(url)).pipe(
- Effect.flatMap(HttpClientResponse.filterStatusOk),
+ return yield* Effect.suspend(() => {
+ if (!resume) {
+ chunks = [];
+ received = 0;
+ }
+ return httpClient.execute(
+ received > 0
+ ? HttpClientRequest.get(url).pipe(
+ HttpClientRequest.setHeader("range", `bytes=${received}-`),
+ )
+ : HttpClientRequest.get(url),
+ );
+ }).pipe(
+ // A resume answered 416 has nothing after the held bytes to send; the archive
+ // checksum decides whether they are the whole file.
+ Effect.filterOrElse(
+ (response) => received > 0 && response.status === 416,
+ HttpClientResponse.filterStatusOk,
+ ),
Effect.timeout(PINNED_RUNTIME_DOWNLOAD_STALL_TIMEOUT),
Effect.flatMap(
Effect.fn(function* (response) {
- const length = Number(response.headers["content-length"]);
+ if (response.status === 416) return concatChunks(chunks, received);
+ const contentRange =
+ response.status === 206
+ ? CONTENT_RANGE.exec(response.headers["content-range"] ?? "")
+ : null;
+ if (response.status === 206 && Number(contentRange?.[1]) !== received) {
+ chunks = [];
+ received = 0;
+ return yield* new HttpClientError.HttpClientError({
+ reason: new HttpClientError.DecodeError({
+ request: response.request,
+ response,
+ description: "partial content does not resume the bytes already received",
+ }),
+ });
+ }
+ if (contentRange === null) {
+ chunks = [];
+ received = 0;
+ }
+ const length = Number(
+ contentRange === null ? response.headers["content-length"] : contentRange[2],
+ );
const total = Number.isFinite(length) && length > 0 ? length : undefined;
- let received = 0;
onProgress?.({ stage: "download", received, total });
- const chunks = yield* response.stream.pipe(
+ const attemptStart = received;
+ yield* response.stream.pipe(
Stream.timeoutOrElse({
duration: PINNED_RUNTIME_DOWNLOAD_STALL_TIMEOUT,
orElse: () => Stream.fail(new Cause.TimeoutError()),
}),
- Stream.tap((chunk) =>
+ Stream.runForEach((chunk) =>
Effect.sync(() => {
+ chunks.push(chunk);
received += chunk.byteLength;
onProgress?.({ stage: "download", received, total });
}),
),
- Stream.runCollect,
);
+ // A server may end a 206 before the declared total; a retry asks for the rest.
+ if (
+ resume &&
+ contentRange !== null &&
+ total !== undefined &&
+ received > attemptStart &&
+ received < total
+ ) {
+ return yield* new HttpClientError.HttpClientError({
+ reason: new HttpClientError.DecodeError({
+ request: response.request,
+ response,
+ description: "partial content ended before the declared total",
+ }),
+ });
+ }
if (total === undefined && received > 0) {
onProgress?.({ stage: "download", received, total: received });
}
- const bytes = new Uint8Array(received);
- let offset = 0;
- for (const chunk of chunks) {
- bytes.set(chunk, offset);
- offset += chunk.byteLength;
- }
- return bytes;
+ return concatChunks(chunks, received);
}),
),
Effect.retry({ ...DOWNLOAD_RETRY, while: isTransientDownloadFailure }),
@@ -212,6 +278,7 @@ const installFromArchive = Effect.fn("cloud.pinned_runtime.install_archive")(fun
httpClient,
cliReleaseAssetUrl(input.version, fileName, input.releaseBaseUrl),
"downloading the t3 release archive",
+ true,
input.onProgress,
);
input.onProgress?.({ stage: "verify" });
@@ -271,6 +338,7 @@ const publishedArchive = Effect.fn("cloud.pinned_runtime.published_archive")(fun
input.httpClient,
cliReleaseAssetUrl(input.version, CLI_RELEASE_CHECKSUMS_FILE, input.releaseBaseUrl),
"downloading the t3 release checksums",
+ false,
),
),
);
diff --git a/apps/server/src/device/DeviceHubOperations.ts b/apps/server/src/device/DeviceHubOperations.ts
index def65c957a43..41f68548b510 100644
--- a/apps/server/src/device/DeviceHubOperations.ts
+++ b/apps/server/src/device/DeviceHubOperations.ts
@@ -20,6 +20,9 @@ const LIST_TIMEOUT_SECONDS = 40;
const SIMULATOR_LIST_FAILED =
/^\[apple-utils\] (?:Failed to (?:run `xcrun simctl list devices|parse JSON output:|list devices:)|`xcrun simctl list devices --json` did not respond within )/;
// The hub passes numeric display IDs that Xcode 26 rejects; iOS 27 needs them for multiple displays.
+// expo-device-hub 0.22.1 returns no Android devices when avdmanager fails, before it runs adb.
+const AVDMANAGER_LIST_FAILED = "[android-utils] Failed to run `avdmanager list avd`";
+const GETPROP_LINE = /^\[([^\]]+)\]: \[(.*)\]$/;
const runsOnXcode26Runtime = (version: string) => Number(/^iOS (\d+)/.exec(version)?.[1]) <= 26;
const DEFAULT_DISPLAY_SCREENSHOT = `f=$(mktemp -t t3-screenshot) || exit 1
trap 'rm -f "$f"' 0
@@ -121,6 +124,51 @@ export const makeDeviceHubOperations = (options: {
Effect.flatMap((request) => hubJson(request, HubActionResult, "attach stream", BOOT_TIMEOUT)),
);
+ // Mirrors the hub's own adb discovery for when it skips it.
+ const listAdbDevices = Effect.gen(function* () {
+ const listed = yield* run("adb", ["devices", "-l"]);
+ if (listed.code !== 0) return undefined;
+ const serials = listed.stdout
+ .split(/\r?\n/)
+ .map((line) => line.trim().split(/\s+/))
+ .flatMap(([serial, state]) => (serial && state === "device" ? [serial] : []));
+ return yield* Effect.forEach(serials, (serial) =>
+ Effect.gen(function* () {
+ const getprop = yield* run("adb", ["-s", serial, "shell", "getprop"]);
+ const props = new Map(
+ getprop.stdout.split(/\r?\n/).flatMap((line) => {
+ const match = GETPROP_LINE.exec(line.trim());
+ return match ? [[match[1]!, match[2]!] as const] : [];
+ }),
+ );
+ const emulator = props.get("ro.kernel.qemu") === "1" || props.get("ro.boot.qemu") === "1";
+ const avdName = emulator
+ ? (yield* run("adb", ["-s", serial, "emu", "avd", "name"])).stdout
+ .split(/\r?\n/)
+ .map((line) => line.trim())
+ .find((line) => line && line !== "OK" && !line.startsWith("KO"))
+ : undefined;
+ const model = props.get("ro.product.model");
+ const manufacturer = props.get("ro.product.manufacturer");
+ const release = props.get("ro.build.version.release");
+ return {
+ id: serial,
+ name: emulator
+ ? (avdName ?? serial)
+ : model
+ ? [manufacturer, model].filter(Boolean).join(" ")
+ : serial,
+ platform: "android",
+ version: release
+ ? `Android ${/^\d+$/.test(release) ? `${release}.0` : release}`
+ : "Android",
+ booted: true,
+ physical: !emulator,
+ } satisfies HostDevice;
+ }),
+ );
+ });
+
const list: DeviceOperations["list"] = Effect.gen(function* () {
const listed = yield* fetchJson(
HttpClientRequest.get(`${origin}/api/devices`),
@@ -161,6 +209,15 @@ export const makeDeviceHubOperations = (options: {
}) ?? [];
let androidDiscoveryIncomplete = false;
if (androidAvailable) {
+ if (hubList.errors?.some((error) => error.message.startsWith(AVDMANAGER_LIST_FAILED))) {
+ const adbDevices = yield* listAdbDevices;
+ if (adbDevices === undefined) {
+ androidDiscoveryIncomplete = true;
+ details.push("Could not list Android devices (adb devices -l).");
+ } else {
+ devices.push(...adbDevices);
+ }
+ }
const avds = yield* run("emulator", ["-list-avds"]);
// Discovered devices stay listed; the AVDs that could not be listed are a warning.
if (avds.code !== 0) {
diff --git a/apps/server/src/device/DeviceService.test.ts b/apps/server/src/device/DeviceService.test.ts
index 2d7255e2921c..00e942f1e6df 100644
--- a/apps/server/src/device/DeviceService.test.ts
+++ b/apps/server/src/device/DeviceService.test.ts
@@ -103,6 +103,63 @@ it.effect.each([400, 500])(
}),
);
+it.effect("lists adb-attached physical devices when the hub cannot run avdmanager", () =>
+ Effect.gen(function* () {
+ // expo-device-hub returns no Android devices at all once `avdmanager list avd` fails.
+ const operations = makeDeviceHubOperations({
+ hostId: LOCAL_DEVICE_HOST_ID,
+ origin: "http://device.test",
+ http: HttpClient.make((request) =>
+ Effect.succeed(
+ HttpClientResponse.fromWeb(
+ request,
+ Response.json({
+ simulators: [],
+ emulators: [],
+ errors: [
+ {
+ id: "avd",
+ message: "[android-utils] Failed to run `avdmanager list avd`:",
+ error:
+ "Error: Command failed: avdmanager list avd\nThe operation couldn’t be completed. Unable to locate a Java Runtime.",
+ },
+ ],
+ }),
+ ),
+ ),
+ ),
+ run: (command, args) =>
+ Effect.succeed(
+ command === "adb" && args.includes("devices")
+ ? {
+ code: 0,
+ stdout:
+ "List of devices attached\nR52T10ABCDE device usb:1-1 product:gts9wifi model:SM_X710 device:gts9wifi transport_id:1\n\n",
+ stderr: "",
+ }
+ : command === "adb" && args.includes("getprop")
+ ? {
+ code: 0,
+ stdout:
+ "[ro.product.manufacturer]: [samsung]\n[ro.product.model]: [SM-X710]\n[ro.build.version.release]: [15]\n",
+ stderr: "",
+ }
+ : { code: 0, stdout: "", stderr: "" },
+ ),
+ platformAvailable: (platform) => Effect.succeed(platform === "android"),
+ });
+ const listed = yield* operations.list;
+ expect(listed.devices).toContainEqual(
+ expect.objectContaining({
+ id: "R52T10ABCDE",
+ platform: "android",
+ booted: true,
+ physical: true,
+ }),
+ );
+ }),
+);
+
const fixture = Effect.fn("fixture")(function* (
onBoot: Effect.Effect = Effect.void,
bootError?: string | { error?: string; errors?: Array<{ message: string; error?: string }> },
diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts
index 1760623071ef..04f5c9082b60 100644
--- a/apps/server/src/environment/ServerEnvironment.ts
+++ b/apps/server/src/environment/ServerEnvironment.ts
@@ -223,12 +223,14 @@ export const make = Effect.gen(function* () {
repositoryIdentity: true,
connectionProbe: true,
attachmentUploads: true,
+ accessTokenRenewal: true,
questionAttachments: true,
fileAttachments: { maxUploadBytes: PROVIDER_SEND_TURN_MAX_FILE_BYTES },
pullRequests: true,
pullRequestChecks: true,
issues: true,
linkedThreadRefreshes: true,
+ issueLinkedThreads: true,
sideChats: true,
vcsBranchStatus: true,
inlineMessageContext: true,
diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts
index 2db95349f102..73da4ec2a6ba 100644
--- a/apps/server/src/git/GitManager.test.ts
+++ b/apps/server/src/git/GitManager.test.ts
@@ -1,6 +1,6 @@
import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";
-import { SourceControlProviderKind } from "@t3tools/contracts";
+import { type PullRequestActionInput, SourceControlProviderKind } from "@t3tools/contracts";
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";
@@ -64,6 +64,7 @@ import * as SourceControlProviderRegistry from "../sourceControl/SourceControlPr
import * as ServerConfig from "../config.ts";
import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
+import * as PullRequestService from "../pullRequest/PullRequestService.ts";
import * as SqlitePersistence from "../persistence/Sqlite.ts";
import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
@@ -628,6 +629,7 @@ function preparePullRequestThread(
function makeManager(input?: {
providerScenario?: FakeProviderScenario;
+ pullRequests?: Partial;
sourceControlProvider?: SourceControlProvider["Service"];
textGeneration?: Partial;
serverSettings?: Parameters[0];
@@ -736,6 +738,7 @@ function makeManager(input?: {
const layerManager = Layer.mergeAll(
Layer.succeed(TextGeneration.TextGeneration, textGeneration),
+ Layer.mock(PullRequestService.PullRequestService)(input?.pullRequests ?? {}),
Layer.mock(ProviderRegistry.ProviderRegistry)({
getProviders: Effect.succeed([]),
}),
@@ -4418,6 +4421,88 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
}),
);
+ it.effect("createPullRequest refuses a branch with commits it has not pushed", () =>
+ Effect.gen(function* () {
+ const repoDir = yield* makeTempDir("t3code-git-manager-");
+ yield* initRepo(repoDir);
+ const remoteDir = yield* createBareRemote();
+ yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
+ yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
+ yield* runGit(repoDir, ["checkout", "-b", "feature/unpushed"]);
+ yield* runGit(repoDir, ["push", "-u", "origin", "feature/unpushed"]);
+ NodeFS.writeFileSync(NodePath.join(repoDir, "late.txt"), "late\n");
+ yield* runGit(repoDir, ["add", "late.txt"]);
+ yield* runGit(repoDir, ["commit", "-m", "Late commit"]);
+ const { manager, providerCalls } = yield* makeManager({
+ providerScenario: { prListSequence: [[], []] },
+ });
+
+ const error = yield* Effect.flip(
+ manager.createPullRequest({
+ cwd: repoDir,
+ projectId: ProjectId.make("project-1"),
+ title: "Feature",
+ body: "Body",
+ }),
+ );
+
+ expect(error.message).toContain("1 unpushed commit");
+ expect(created(providerCalls)).toEqual([]);
+
+ // An open PR is returned as it is; returning it publishes nothing.
+ const open = {
+ number: 7,
+ title: "Feature",
+ url: "https://github.com/pingdotgg/codething-mvp/pull/7",
+ baseRefName: "main",
+ headRefName: "feature/unpushed",
+ };
+ const existing = yield* makeManager({ providerScenario: { prListSequence: [[open]] } });
+ const found = yield* existing.manager.createPullRequest({
+ cwd: repoDir,
+ projectId: ProjectId.make("project-1"),
+ title: "Feature",
+ body: "Body",
+ });
+ expect(found).toMatchObject({ status: "opened_existing", number: 7 });
+
+ // A retry after a failed draft finds the open PR and still drafts it.
+ const actions: Array = [];
+ const retried = yield* makeManager({
+ providerScenario: { prListSequence: [[open]] },
+ pullRequests: {
+ summary: () => Effect.succeed({ isDraft: false } as never),
+ runAction: (action) => Effect.sync(() => void actions.push(action)),
+ },
+ });
+ yield* retried.manager.createPullRequest({
+ cwd: repoDir,
+ projectId: ProjectId.make("project-1"),
+ title: "Feature",
+ body: "Body",
+ draft: true,
+ });
+ expect(actions).toMatchObject([
+ { repository: "pingdotgg/codething-mvp", number: 7, action: "draft" },
+ ]);
+
+ // A draft of a PR the host does not list yet fails, so a retry drafts it.
+ yield* runGit(repoDir, ["push"]);
+ const unlisted = yield* makeManager({ providerScenario: { prListSequence: [[], []] } });
+ const notListed = yield* Effect.flip(
+ unlisted.manager.createPullRequest({
+ cwd: repoDir,
+ projectId: ProjectId.make("project-1"),
+ title: "Feature",
+ body: "Body",
+ draft: true,
+ }),
+ );
+ expect(notListed.message).toContain("does not list it yet");
+ expect(created(unlisted.providerCalls)).toHaveLength(1);
+ }),
+ );
+
it.effect("generates PR content from the created worktree's selected remote base", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts
index 92d693a17382..77acae07dee6 100644
--- a/apps/server/src/git/GitManager.ts
+++ b/apps/server/src/git/GitManager.ts
@@ -81,6 +81,8 @@ import {
import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
+import * as PullRequestService from "../pullRequest/PullRequestService.ts";
+import { createdPullRequestKey } from "./linkCreatedPullRequest.ts";
import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
import { extractBranchNameFromRemoteRef } from "./remoteRefs.ts";
import { detachStackFrame } from "./detachStackFrame.ts";
@@ -125,6 +127,16 @@ interface SourceControlTextGenerationSettings {
readonly style: SourceControlWritingStyleSettings;
}
+export interface GitCreatePullRequestResult {
+ readonly status: "created" | "opened_existing";
+ /** Absent when the host accepted the PR but did not list it back yet. */
+ readonly url?: string;
+ readonly number?: number;
+ readonly baseBranch: string;
+ readonly headBranch: string;
+ readonly title: string;
+}
+
export class GitManager extends Context.Service<
GitManager,
{
@@ -175,6 +187,15 @@ export class GitManager extends Context.Service<
input: GitRunStackedActionInput,
options?: GitRunStackedActionOptions,
) => Effect.Effect;
+ /** Opens a PR for the checkout's pushed branch, or returns the one already open. */
+ readonly createPullRequest: (input: {
+ readonly cwd: string;
+ readonly projectId: ProjectId;
+ readonly title: string;
+ readonly body: string;
+ readonly baseBranch?: string | undefined;
+ readonly draft?: boolean | undefined;
+ }) => Effect.Effect;
readonly subscribePullRequestStateChanges: Effect.Effect<
Stream.Stream,
never,
@@ -747,6 +768,7 @@ export const make = Effect.gen(function* () {
);
});
const serverSettingsService = yield* ServerSettings.ServerSettingsService;
+ const pullRequests = yield* PullRequestService.PullRequestService;
const threads = yield* ProjectionStore.ProjectionStoreV2;
const projects = yield* ProjectStore.ProjectStoreV2;
const projectSettingsFor = Effect.fnUntraced(function* (input: {
@@ -2437,13 +2459,18 @@ export const make = Effect.gen(function* () {
});
});
- const runPrStep = Effect.fn("runPrStep")(function* (
- settings: SourceControlTextGenerationSettings,
+ const openPrFromBranch = Effect.fn("openPrFromBranch")(function* (
cwd: string,
fallbackBranch: string | null,
- threadId: ThreadId | undefined,
emit: GitActionProgressEmitter,
- pushRemoteRef?: { readonly remoteName: string; readonly upstreamRef: string },
+ pushRemoteRef: { readonly remoteName: string; readonly upstreamRef: string } | undefined,
+ requestedBase: string | undefined,
+ content: (input: {
+ readonly provider: SourceControlProvider.SourceControlProvider["Service"];
+ readonly baseBranch: string;
+ readonly baseRef: string;
+ readonly headBranch: string;
+ }) => Effect.Effect<{ readonly title: string; readonly body: string }, E>,
) {
const provider = yield* sourceControlProvider(cwd);
const terms = sourceControlDefinitions.get(provider.kind).changeRequest;
@@ -2483,42 +2510,22 @@ export const make = Effect.gen(function* () {
};
}
- const { baseBranch, baseRef } = yield* resolvePrBase(
- cwd,
- branch,
- details.upstreamRef,
- headContext,
- );
- yield* emit({
- kind: "phase_started",
- phase: "pr",
- label: `Generating ${terms.shortLabel} content...`,
- });
- const baseRangeRef = yield* resolveBaseRangeRef(cwd, baseRef);
- const rangeContext = yield* gitCore.readRangeContext(cwd, baseRangeRef);
- const policy = yield* resolveStylePolicy(cwd, settings);
- const changeRequestTemplate =
- settings.style.followChangeRequestTemplates && provider.readChangeRequestTemplate
- ? Option.getOrUndefined(
- yield* provider.readChangeRequestTemplate({ cwd, treeish: baseRangeRef }),
- )
- : undefined;
- const threadContext = yield* readThreadContext(threadId);
-
- const generated = yield* textGeneration.generatePrContent({
- cwd,
+ // A PR opened from the remote branch would leave out commits not pushed yet.
+ if (details.aheadCount > 0) {
+ return yield* new GitManagerError({
+ operation: "runPrStep",
+ cwd,
+ detail: `The branch has ${details.aheadCount} unpushed commit${details.aheadCount === 1 ? "" : "s"}. Push before opening the PR.`,
+ });
+ }
+ const resolved = yield* resolvePrBase(cwd, branch, details.upstreamRef, headContext);
+ const baseBranch = requestedBase ?? resolved.baseBranch;
+ const generated = yield* content({
+ provider,
baseBranch,
+ baseRef: requestedBase ?? resolved.baseRef,
headBranch: headContext.headBranch,
- commitSummary: limitContext(rangeContext.commitSummary, 20_000),
- diffSummary: limitContext(rangeContext.diffSummary, 20_000),
- diffPatch: limitContext(rangeContext.diffPatch, 60_000),
- ...(changeRequestTemplate ? { changeRequestTemplate } : {}),
- ...(threadContext ? { threadContext } : {}),
- ...(policy ? { policy } : {}),
- modelSelection: settings.modelSelection,
- projectId: settings.projectId,
});
-
const bodyFile = path.join(
tempDir,
`t3code-pr-body-${process.pid}-${yield* randomUUIDv4(cwd)}.md`,
@@ -2587,6 +2594,112 @@ export const make = Effect.gen(function* () {
};
});
+ const runPrStep = (
+ settings: SourceControlTextGenerationSettings,
+ cwd: string,
+ fallbackBranch: string | null,
+ threadId: ThreadId | undefined,
+ emit: GitActionProgressEmitter,
+ pushRemoteRef?: { readonly remoteName: string; readonly upstreamRef: string },
+ ) =>
+ openPrFromBranch(
+ cwd,
+ fallbackBranch,
+ emit,
+ pushRemoteRef,
+ undefined,
+ ({ provider, baseBranch, baseRef, headBranch }) =>
+ Effect.gen(function* () {
+ const terms = sourceControlDefinitions.get(provider.kind).changeRequest;
+ yield* emit({
+ kind: "phase_started",
+ phase: "pr",
+ label: `Generating ${terms.shortLabel} content...`,
+ });
+ const baseRangeRef = yield* resolveBaseRangeRef(cwd, baseRef);
+ const rangeContext = yield* gitCore.readRangeContext(cwd, baseRangeRef);
+ const policy = yield* resolveStylePolicy(cwd, settings);
+ const changeRequestTemplate =
+ settings.style.followChangeRequestTemplates && provider.readChangeRequestTemplate
+ ? Option.getOrUndefined(
+ yield* provider.readChangeRequestTemplate({ cwd, treeish: baseRangeRef }),
+ )
+ : undefined;
+ const threadContext = yield* readThreadContext(threadId);
+
+ return yield* textGeneration.generatePrContent({
+ cwd,
+ baseBranch,
+ headBranch,
+ commitSummary: limitContext(rangeContext.commitSummary, 20_000),
+ diffSummary: limitContext(rangeContext.diffSummary, 20_000),
+ diffPatch: limitContext(rangeContext.diffPatch, 60_000),
+ ...(changeRequestTemplate ? { changeRequestTemplate } : {}),
+ ...(threadContext ? { threadContext } : {}),
+ ...(policy ? { policy } : {}),
+ modelSelection: settings.modelSelection,
+ projectId: settings.projectId,
+ });
+ }),
+ );
+
+ const createPullRequest: GitManager["Service"]["createPullRequest"] = Effect.fn(
+ "GitManager.createPullRequest",
+ )(function* (input) {
+ const result = yield* openPrFromBranch(
+ input.cwd,
+ null,
+ () => Effect.void,
+ undefined,
+ input.baseBranch,
+ () => Effect.succeed({ title: input.title, body: input.body }),
+ );
+ // The thread's branch PR comes from status, which may hold the lookup from before.
+ if (result.status === "created") yield* invalidateStatus(input.cwd);
+ if (input.draft === true && !(yield* draftOpened(input, result))) {
+ // A retry finds the open PR and drafts it then.
+ return yield* new GitManagerError({
+ operation: "createPullRequest",
+ cwd: input.cwd,
+ detail: "Opened the pull request, but the host does not list it yet to make it a draft.",
+ });
+ }
+ return result;
+ });
+
+ /** A retry after a failed draft finds the PR it opened, so an open one is checked too. */
+ const draftOpened = Effect.fn("GitManager.draftOpened")(
+ function* (
+ input: { readonly cwd: string; readonly projectId: ProjectId },
+ result: GitCreatePullRequestResult,
+ ) {
+ const project = yield* projects.getShell(input.projectId).pipe(
+ Effect.map(Option.getOrUndefined),
+ Effect.orElseSucceed(() => undefined),
+ );
+ const key = createdPullRequestKey({ pr: result }, project);
+ if (key === null) return false;
+ const ref = { projectId: input.projectId, ...key };
+ const isDraft =
+ result.status === "opened_existing" &&
+ (yield* pullRequests.summary({ ...ref, allowStale: false })).isDraft;
+ if (!isDraft) yield* pullRequests.runAction({ ...ref, action: "draft" });
+ return true;
+ },
+ (effect, input) =>
+ effect.pipe(
+ Effect.mapError(
+ (cause) =>
+ new GitManagerError({
+ operation: "createPullRequest",
+ cwd: input.cwd,
+ detail: `Opened the pull request, but could not make it a draft: ${cause.message}`,
+ cause,
+ }),
+ ),
+ ),
+ );
+
const localStatus: GitManager["Service"]["localStatus"] = Effect.fn("localStatus")(
function* (input, options) {
const cacheKey = yield* normalizeStatusCacheKey(input.cwd);
@@ -3726,6 +3839,7 @@ export const make = Effect.gen(function* () {
resolvePullRequest,
preparePullRequestThread,
runStackedAction,
+ createPullRequest,
subscribePullRequestStateChanges: PubSub.subscribe(pullRequestStateChanges).pipe(
Effect.map((subscription) => Stream.fromSubscription(subscription)),
),
diff --git a/apps/server/src/issue/IssueService.test.ts b/apps/server/src/issue/IssueService.test.ts
index 2e260451de2d..723228a64f04 100644
--- a/apps/server/src/issue/IssueService.test.ts
+++ b/apps/server/src/issue/IssueService.test.ts
@@ -293,6 +293,39 @@ describe("IssueService", () => {
}),
);
+ it.effect("resolves both legacy Azure work item URLs through the bound project", () =>
+ Effect.gen(function* () {
+ const tracker = IssueTrackerKind.make("azure-devops");
+ const host = "acme.visualstudio.com";
+ const service = yield* makeService({
+ projects: [
+ project({ id: "api", repository: "Api/_git/api", provider: tracker, host }),
+ project({
+ id: "web",
+ repository: "DefaultCollection/Web/_git/web",
+ provider: tracker,
+ host,
+ }),
+ ],
+ trackers: [fakeTracker({ kind: tracker })],
+ });
+ for (const path of ["Web", "DefaultCollection/Web"]) {
+ const ref = yield* service.resolveUrl(
+ `https://${host}/${path}/_workitems/edit/9`,
+ "api" as ProjectId,
+ );
+ expect(ref).toEqual({
+ projectId: "web",
+ tracker,
+ host,
+ scope: "DefaultCollection/Web",
+ key: "9",
+ writable: true,
+ });
+ }
+ }),
+ );
+
it.effect("sends writes as interactive requests and reads as background ones", () =>
Effect.gen(function* () {
const interactive: Array = [];
@@ -515,15 +548,20 @@ describe("IssueService with a standalone tracker", () => {
const projects = [project({ id: "web", repository: "acme/web" }), project({ id: "notes" })];
const trackers = [fakeTracker(record(GITHUB)), fakeStandaloneTracker(record(LINEAR))];
const bound = yield* makeService({
- projects,
+ projects: [...projects, project({ id: "api", repository: "acme/api" })],
trackers,
bindings: { ["web" as ProjectId]: { tracker: LINEAR, scope: "ENG" } },
});
const result = yield* bound.list({ state: "open" });
- expect(listed.sort()).toEqual(["github github.com acme/web", "linear linear.app ENG"]);
+ expect(listed.sort()).toEqual([
+ "github github.com acme/api",
+ "github github.com acme/web",
+ "linear linear.app ENG",
+ ]);
expect(result.entries.map((entry) => [entry.tracker, entry.scope, entry.key]).sort()).toEqual(
[
+ ["github", "acme/api", "1"],
["github", "acme/web", "1"],
["linear", "ENG", "ENG-1"],
],
@@ -538,6 +576,14 @@ describe("IssueService with a standalone tracker", () => {
host: "linear.app",
scope: "ENG",
});
+ // Narrowed to one project, both of its trackers are still read.
+ listed.length = 0;
+ const selected = yield* bound.list({ state: "open", projectId: "web" as ProjectId });
+ expect(listed.sort()).toEqual(["github github.com acme/web", "linear linear.app ENG"]);
+ expect(selected.entries.map((entry) => [entry.projectId, entry.scope]).sort()).toEqual([
+ ["web", "ENG"],
+ ["web", "acme/web"],
+ ]);
// A reference picks the project's tracker by kind; both are the project's own, so writable.
const linearRef = {
projectId: "web" as ProjectId,
diff --git a/apps/server/src/issue/IssueService.ts b/apps/server/src/issue/IssueService.ts
index bf3d301f7370..239de06ce546 100644
--- a/apps/server/src/issue/IssueService.ts
+++ b/apps/server/src/issue/IssueService.ts
@@ -408,6 +408,7 @@ const make = Effect.gen(function* () {
assignee: input.assignee,
sort: input.sort ?? "updated",
cursor,
+ refresh: input.refresh,
}),
),
Effect.result,
@@ -704,9 +705,12 @@ const make = Effect.gen(function* () {
const onTracker = onAuthority.length > 0 ? onAuthority : onHost;
const preferFirst = (projects: ReadonlyArray