,
-) =>
- 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 c5d55afe7f94a..6f4a25507f2fe 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 255dae1884bb9..baafbca9817ac 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 5e33ad84bc120..9c117b76e7d36 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 3e59c5bd4735c..ee45ff0cefc67 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 0000000000000..cf315ff223ae5
--- /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/triage.test.ts b/apps/server/src/cli/triage.test.ts
index 05eaf04e1f014..25f7baeb3211e 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 c9173a3d46889..cb0f94b254589 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 cbbf4670d6f67..a71a8f00b81c7 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 3d623430a368a..fd74ed0ffce28 100644
--- a/apps/server/src/cloud/CloudLink.ts
+++ b/apps/server/src/cloud/CloudLink.ts
@@ -2,7 +2,6 @@ import {
type AuthSessionId,
AuthStandardClientScopes,
AuthViewOnlyClientScopes,
- EnvironmentAuthenticatedPrincipal,
type EnvironmentCloudLinkStateResult,
type EnvironmentCloudPreferencesRequest,
type EnvironmentCloudRelayConfigResult,
@@ -42,7 +41,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";
@@ -50,6 +49,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";
@@ -58,12 +58,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";
@@ -76,6 +71,7 @@ import { makeRelayEnvironmentClient } from "../relay/relayEnvironmentClient.ts";
import { loopbackUrlHostForAddress } from "../startupAccess.ts";
import {
type CliDesiredLinkMode,
+ dropRevokedCloudLink,
readCliDesiredCloudLink,
readCliDesiredLinkMode,
setCliDesiredCloudLink,
@@ -116,13 +112,11 @@ import {
import {
hasBoundedCloudProofLifetime,
hasExactScope,
- hasForwardedAuthorityHeaders,
- isAllowedEndpointOrigin,
+ isLoopbackEndpointOrigin,
isSupportedLinkProviderKind,
linkProofScopes,
managedEndpointRuntimeConfigsMatch,
parseManagedEndpointLocalOrigin,
- requestAbsoluteUrl,
} from "./linkChecks.ts";
import { desktopUpdateRestartPending, pendingUpdateHandoffExists } from "./updateHandoff.ts";
@@ -257,6 +251,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.",
@@ -425,21 +420,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,
@@ -474,6 +463,12 @@ export class CloudLink extends Context.Service<
EnvironmentCloudLinkStateResult,
CloudLinkInternalError | ManagedLimits.ManagedPolicyRefusedError
>;
+ readonly updateLiveActivityPreference: (
+ enabled: boolean,
+ ) => Effect.Effect<
+ RelayOkResponse,
+ CloudLinkInternalError | ManagedLimits.ManagedPolicyRefusedError
+ >;
readonly answerHealthRequest: (
request: RelayCloudEnvironmentHealthRequest,
) => Effect.Effect<
@@ -597,21 +592,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.
@@ -634,7 +636,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
@@ -653,18 +655,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")),
);
@@ -777,11 +769,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 (
@@ -796,6 +788,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;
@@ -888,19 +900,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,
@@ -1188,7 +1197,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)) {
@@ -1251,22 +1260,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,
@@ -1475,6 +1489,37 @@ const make = Effect.gen(function* () {
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, internalError("change-sharing-mode")),
);
+ 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
@@ -1715,6 +1760,7 @@ const make = Effect.gen(function* () {
unlink,
updatePreferences: refused,
setSharingMode: refused,
+ updateLiveActivityPreference: refused,
answerHealthRequest: refused,
mintCredential: refused,
reconcileDesiredLinkIfStillDesired: notDesired,
@@ -1732,6 +1778,7 @@ const make = Effect.gen(function* () {
unlink,
updatePreferences,
setSharingMode,
+ updateLiveActivityPreference,
answerHealthRequest,
mintCredential,
reconcileDesiredLinkIfStillDesired,
diff --git a/apps/server/src/cloud/http.test.ts b/apps/server/src/cloud/http.test.ts
index 50f11d8ca25c4..a292097e398d2 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)({
@@ -162,10 +163,10 @@ const linkProofClient = Effect.gen(function* () {
Effect.promise(() =>
handler(new Request(`${NON_LOOPBACK_ORIGIN}${path}`, headers ? { headers } : {})),
);
- 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}` },
}),
),
@@ -176,16 +177,27 @@ const linkProofClient = Effect.gen(function* () {
return { post, get, 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;
@@ -201,104 +213,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 db06c206a826d..be292087296ba 100644
--- a/apps/server/src/cloud/http.ts
+++ b/apps/server/src/cloud/http.ts
@@ -1,6 +1,7 @@
import {
AuthAccessWriteScope,
AuthRelayReadScope,
+ AuthRelayConfigureScope,
AuthRelayWriteScope,
EnvironmentCloudEndpointUnavailableError,
EnvironmentHttpApi,
@@ -12,7 +13,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";
@@ -20,7 +21,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";
@@ -118,24 +118,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", () =>
@@ -159,6 +162,13 @@ export const layer = HttpApiBuilder.group(
),
),
)
+ .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 607e2c08f8a53..6b8f19e60a694 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/device/DeviceHubOperations.ts b/apps/server/src/device/DeviceHubOperations.ts
index def65c957a439..41f68548b5103 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 2d7255e2921cb..00e942f1e6df5 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 1760623071efb..04f5c9082b606 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 2db95349f1021..73da4ec2a6bac 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 92d693a17382b..77acae07dee63 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 2e260451de2d7..723228a64f04a 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 bf3d301f73708..239de06ce546d 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) =>
projects.find((project) => project.project.id === preferredProjectId) ?? projects[0];
- const own = preferFirst(
- onTracker.filter((project) => project.scope.toLowerCase() === link.scope.toLowerCase()),
- );
+ const scope = link.scope.toLowerCase();
+ const own =
+ preferFirst(onTracker.filter((project) => project.scope.toLowerCase() === scope)) ??
+ preferFirst(
+ onTracker.filter((project) => project.scope.toLowerCase() === gitHost?.link.scopeAlias),
+ );
const lender = own ?? preferFirst(onTracker);
if (lender === undefined) {
return yield* new IssueUnavailableError({ reason: "tracker-unsupported" });
diff --git a/apps/server/src/issue/IssueTrackerConnections.ts b/apps/server/src/issue/IssueTrackerConnections.ts
index 9e9a0fae3447b..390cc9701e858 100644
--- a/apps/server/src/issue/IssueTrackerConnections.ts
+++ b/apps/server/src/issue/IssueTrackerConnections.ts
@@ -87,6 +87,7 @@ const make = Effect.gen(function* () {
connected: true,
account: probe.account,
detail: null,
+ ...(probe.workspace === undefined ? {} : { workspace: probe.workspace }),
scopes: probe.scopes,
})),
Effect.catch((error) =>
@@ -156,6 +157,7 @@ const make = Effect.gen(function* () {
connected: true,
account: probe.account,
detail: null,
+ ...(probe.workspace === undefined ? {} : { workspace: probe.workspace }),
scopes: probe.scopes,
};
});
diff --git a/apps/server/src/issue/linkedThreads.test.ts b/apps/server/src/issue/linkedThreads.test.ts
new file mode 100644
index 0000000000000..6b5005398869a
--- /dev/null
+++ b/apps/server/src/issue/linkedThreads.test.ts
@@ -0,0 +1,56 @@
+import { IssueTrackerKind } from "@t3tools/contracts";
+import { expect, it } from "@effect/vitest";
+import * as Effect from "effect/Effect";
+import * as Schema from "effect/Schema";
+import * as SqlClient from "effect/sql/SqlClient";
+
+import * as SqlitePersistence from "../persistence/Sqlite.ts";
+import { listLinkedIssueThreads } from "./linkedThreads.ts";
+
+const encodePayload = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
+
+it.effect("finds every thread linked to exactly one issue, newest activity first", () =>
+ Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ const at = (day: number) => `2026-11-0${day}T00:00:00.000Z`;
+ const issue = { tracker: "linear", host: "linear.app", scope: "eng", key: "ENG-7" };
+ const fixtures = [
+ { id: "older", day: 1, issues: [issue] },
+ { id: "newer", day: 2, issues: [{ ...issue, key: "ENG-8" }, issue] },
+ { id: "settled", day: 3, issues: [issue], payload: { settledOverride: "settled" } },
+ { id: "archived", day: 4, issues: [issue], archived: true },
+ { id: "deleted", day: 5, issues: [issue], deleted: true },
+ { id: "side-chat", day: 5, issues: [issue], payload: { lineage: { sideChat: true } } },
+ { id: "other-key", day: 5, issues: [{ ...issue, key: "ENG-70" }] },
+ { id: "other-scope", day: 5, issues: [{ ...issue, scope: "design" }] },
+ { id: "other-tracker", day: 5, issues: [{ ...issue, tracker: "github" }] },
+ { id: "unlinked", day: 5, issues: [] },
+ ];
+ for (const fixture of fixtures) {
+ const payload = yield* encodePayload({ ...fixture.payload, issues: fixture.issues });
+ yield* sql`
+ INSERT INTO orchestration_v2_projection_threads (
+ thread_id, project_id, title, default_provider, runtime_mode, interaction_mode,
+ created_at, updated_at, archived_at, deleted_at, payload_json
+ ) VALUES (
+ ${fixture.id}, 'project-1', ${fixture.id}, 'codex', 'full-access', 'default',
+ ${at(1)}, ${at(fixture.day)}, ${fixture.archived ? at(fixture.day) : null},
+ ${fixture.deleted ? at(fixture.day) : null}, ${payload}
+ )
+ `;
+ }
+
+ const result = yield* listLinkedIssueThreads({
+ tracker: IssueTrackerKind.make("linear"),
+ host: "Linear.app",
+ scope: "ENG",
+ key: "ENG-7",
+ });
+ expect(result.threads.map((thread) => [thread.id, thread.settled, thread.archivedAt])).toEqual([
+ ["archived", false, at(4)],
+ ["settled", true, null],
+ ["newer", false, null],
+ ["older", false, null],
+ ]);
+ }).pipe(Effect.provide(SqlitePersistence.layerMemory)),
+);
diff --git a/apps/server/src/issue/linkedThreads.ts b/apps/server/src/issue/linkedThreads.ts
new file mode 100644
index 0000000000000..c38b75c6b0944
--- /dev/null
+++ b/apps/server/src/issue/linkedThreads.ts
@@ -0,0 +1,64 @@
+import {
+ IssueLinkedThreadsResult,
+ IssueOperationError,
+ threadIssueKeysEqual,
+ type ThreadIssueKey,
+} from "@t3tools/contracts";
+import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
+import * as Effect from "effect/Effect";
+import * as Schema from "effect/Schema";
+import * as SqlClient from "effect/sql/SqlClient";
+
+const decodeLinkedThreads = Schema.decodeUnknownEffect(IssueLinkedThreadsResult);
+
+/** The threads an issue is linked to; the rows and filters `linkedThreads` uses for pull requests. */
+export const listLinkedIssueThreads = Effect.fn("listLinkedIssueThreads")(
+ function* (key: ThreadIssueKey) {
+ const sql = yield* SqlClient.SqlClient;
+ const rows = yield* sql<{
+ id: string;
+ projectId: string;
+ title: string;
+ archivedAt: string | null;
+ settled: number;
+ tracker: ThreadIssueKey["tracker"];
+ host: string;
+ scope: string;
+ key: string;
+ }>`
+ SELECT t.thread_id AS id, t.project_id AS "projectId", t.title,
+ t.archived_at AS "archivedAt",
+ (json_extract(t.payload_json, '$.settledAt') IS NOT NULL
+ OR json_extract(t.payload_json, '$.settledOverride') IS 'settled') AS settled,
+ json_extract(link.value, '$.tracker') AS tracker,
+ json_extract(link.value, '$.host') AS host,
+ json_extract(link.value, '$.scope') AS scope,
+ json_extract(link.value, '$.key') AS key,
+ t.updated_at AS "updatedAt"
+ FROM orchestration_v2_projection_threads AS t
+ JOIN json_each(t.payload_json, '$.issues') AS link
+ WHERE json_extract(link.value, '$.key') = ${key.key.trim()}
+ AND t.deleted_at IS NULL
+ AND json_extract(t.payload_json, '$.lineage.sideChat') IS NOT 1
+ ORDER BY "updatedAt" DESC, id ASC
+ `.pipe(NodeSqliteClient.readOnly);
+ const threads = rows
+ .filter((row) => threadIssueKeysEqual(row, key))
+ .map(({ id, projectId, title, archivedAt, settled }) => ({
+ id,
+ projectId,
+ title,
+ archivedAt,
+ settled: settled === 1,
+ }));
+ return yield* decodeLinkedThreads({ threads });
+ },
+ Effect.mapError(
+ (cause) =>
+ new IssueOperationError({
+ operation: "linkedThreads",
+ detail: "Could not load linked threads.",
+ cause,
+ }),
+ ),
+);
diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.ts
index 761991fd48769..e5d47410817f2 100644
--- a/apps/server/src/mcp/McpHttpServer.test.ts
+++ b/apps/server/src/mcp/McpHttpServer.test.ts
@@ -12,6 +12,7 @@ import {
OrchestratorMcpEnvironmentTarget,
OrchestratorMcpFailure,
PreviewTabId,
+ ProjectId,
ProviderInstanceId,
ProviderInteractionMode,
RuntimeMode,
@@ -46,6 +47,7 @@ import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
import * as PreviewManager from "../preview/Manager.ts";
import * as DeviceService from "../device/DeviceService.ts";
+import * as GitManager from "../git/GitManager.ts";
import * as PullRequestReviewGuideService from "../pullRequest/PullRequestReviewGuideService.ts";
import * as PullRequestService from "../pullRequest/PullRequestService.ts";
import * as ServerConfig from "../config.ts";
@@ -108,6 +110,7 @@ const layerPullRequestsTest = McpHttpServer.layerPullRequestsToolkit.pipe(
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(PullRequestReviewGuideService.PullRequestReviewGuideService)({}),
Layer.mock(PullRequestService.PullRequestService)({}),
+ Layer.mock(GitManager.GitManager)({}),
Layer.mock(Orchestrator.OrchestratorV2)({}),
Layer.mock(ProjectionStore.ProjectionStoreV2)({}),
NodeServices.layer,
@@ -1201,6 +1204,38 @@ it.effect("answers 2026-07-28 discovery and keeps 2025-06-18 as the initialize f
expect.arrayContaining([expect.objectContaining({ name: "probe" })]),
);
+ // The Go MCP SDK sends this without request metadata, though 2026-07-28 does not define it.
+ const rootsChanged = (
+ client: HttpClient.HttpClient,
+ message: object = {},
+ headers: Record = {},
+ ) =>
+ client.post("/mcp", {
+ headers: {
+ accept: "application/json, text/event-stream",
+ "mcp-method": "notifications/roots/list_changed",
+ "mcp-protocol-version": "2026-07-28",
+ ...headers,
+ },
+ body: HttpBody.text(
+ JSON.stringify({
+ jsonrpc: "2.0",
+ method: "notifications/roots/list_changed",
+ params: {},
+ ...message,
+ }),
+ "application/json",
+ ),
+ });
+ const acknowledged = yield* rootsChanged(httpClient);
+ expect(acknowledged.status).toBe(202);
+ expect(yield* acknowledged.text).toBe("");
+ expect((yield* rootsChanged(yield* HttpClient.HttpClient)).status).toBe(401);
+ expect((yield* rootsChanged(httpClient, { id: 7 })).status).toBe(400);
+ expect((yield* rootsChanged(httpClient, {}, { origin: "https://example.com" })).status).toBe(
+ 403,
+ );
+
const initializeResponse = yield* httpClient.post("/mcp", {
headers: { accept: "application/json, text/event-stream" },
body: HttpBody.text(
@@ -1723,95 +1758,126 @@ it.effect("hides tools for links and refuses another environment while the beta
).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
-it.effect("lists pull request watch tools only to threads that are not delegated children", () =>
- Effect.scoped(
- Effect.gen(function* () {
- const scopeFor = (
- token: string,
- subagent: boolean,
- ): McpInvocationContext.McpThreadInvocationScope => ({
- environmentId,
- requestNamespace: token,
- thread: {
- threadId: ThreadId.make(`thread-${token}`),
- providerSessionId: token,
- providerInstanceId: ProviderInstanceId.make("codex"),
- subagent,
- },
- client: undefined,
- capabilities: new Set(["pull-requests"]),
- issuedAt: 1,
- });
- const scopes = new Map([
- ["parentToken", scopeFor("parentToken", false)],
- ["childToken", scopeFor("childToken", true)],
- ]);
- const serverLayer = McpHttpServer.layerMcpTransport(
- McpHttpServer.layerPullRequestsToolkit,
- ).pipe(
- Layer.provide(ServerSettings.layerTest()),
- Layer.provide(
- Layer.mock(McpSessionRegistry.McpSessionRegistry)({
- resolve: (token) => Effect.succeed(scopes.get(token)),
- }),
- ),
- Layer.provide(
- Layer.mergeAll(
- McpToolAccessTestkit.liveThreadsLayer,
- Layer.mock(ProjectService.ProjectService)({}),
- Layer.mock(PullRequestReviewGuideService.PullRequestReviewGuideService)({}),
- Layer.mock(PullRequestService.PullRequestService)({}),
- Layer.mock(Orchestrator.OrchestratorV2)({}),
- Layer.mock(ProjectionStore.ProjectionStoreV2)({}),
- NodeServices.layer,
- NodeCrypto.layer,
+it.effect(
+ "lists watch tools only to threads that are not delegated children, and forge tools only where the project has a forge",
+ () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const scopeFor = (
+ token: string,
+ subagent: boolean,
+ ): McpInvocationContext.McpThreadInvocationScope => ({
+ environmentId,
+ requestNamespace: token,
+ thread: {
+ threadId: ThreadId.make(`thread-${token}`),
+ providerSessionId: token,
+ providerInstanceId: ProviderInstanceId.make("codex"),
+ subagent,
+ },
+ client: undefined,
+ capabilities: new Set(["pull-requests"]),
+ issuedAt: 1,
+ });
+ const scopes = new Map([
+ ["parentToken", scopeFor("parentToken", false)],
+ ["childToken", scopeFor("childToken", true)],
+ ["noForgeToken", scopeFor("noForgeToken", false)],
+ ]);
+ const serverLayer = McpHttpServer.layerMcpTransport(
+ McpHttpServer.layerPullRequestsToolkit,
+ ).pipe(
+ Layer.provide(ServerSettings.layerTest()),
+ Layer.provide(
+ Layer.mock(McpSessionRegistry.McpSessionRegistry)({
+ resolve: (token) => Effect.succeed(scopes.get(token)),
+ }),
),
- ),
- );
- yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe(
- Layer.build,
- );
- const httpClient = yield* HttpClient.HttpClient;
- const listedTools = (token: string) =>
- Effect.gen(function* () {
- const headers = {
- accept: "application/json, text/event-stream",
- authorization: `Bearer ${token}`,
- };
- const initialize = yield* httpClient.post("/mcp", {
- headers,
- body: HttpBody.text(
- `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
- "application/json",
- ),
- });
- const listed = yield* httpClient.post("/mcp", {
- headers: {
- ...headers,
- "mcp-session-id": initialize.headers["mcp-session-id"]!,
- "mcp-protocol-version": "2025-06-18",
- },
- body: HttpBody.text(
- `{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}`,
- "application/json",
+ Layer.provide(
+ Layer.mergeAll(
+ McpToolAccessTestkit.liveThreadsLayer,
+ Layer.mock(ProjectService.ProjectService)({}),
+ Layer.mock(PullRequestReviewGuideService.PullRequestReviewGuideService)({}),
+ Layer.mock(PullRequestService.PullRequestService)({
+ servesProject: (projectId) => Effect.succeed(projectId !== "project-noForgeToken"),
+ }),
+ Layer.mock(GitManager.GitManager)({}),
+ Layer.mock(Orchestrator.OrchestratorV2)({}),
+ Layer.mock(ProjectionStore.ProjectionStoreV2)({
+ getThreadShell: (threadId) =>
+ Effect.succeed({
+ projectId: ProjectId.make(threadId.replace("thread-", "project-")),
+ } as never),
+ }),
+ NodeServices.layer,
+ NodeCrypto.layer,
),
+ ),
+ );
+ yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe(
+ Layer.build,
+ );
+ const httpClient = yield* HttpClient.HttpClient;
+ const listedTools = (token: string) =>
+ Effect.gen(function* () {
+ const headers = {
+ accept: "application/json, text/event-stream",
+ authorization: `Bearer ${token}`,
+ };
+ const initialize = yield* httpClient.post("/mcp", {
+ headers,
+ body: HttpBody.text(
+ `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
+ "application/json",
+ ),
+ });
+ const listed = yield* httpClient.post("/mcp", {
+ headers: {
+ ...headers,
+ "mcp-session-id": initialize.headers["mcp-session-id"]!,
+ "mcp-protocol-version": "2025-06-18",
+ },
+ body: HttpBody.text(
+ `{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}`,
+ "application/json",
+ ),
+ });
+ const body = (yield* listed.json) as {
+ readonly result: { readonly tools: ReadonlyArray<{ readonly name: string }> };
+ };
+ return body.result.tools.map((tool) => tool.name);
});
- const body = (yield* listed.json) as {
- readonly result: { readonly tools: ReadonlyArray<{ readonly name: string }> };
- };
- return body.result.tools.map((tool) => tool.name);
- });
- const parentTools = yield* listedTools("parentToken");
- const childTools = yield* listedTools("childToken");
- expect(parentTools).toEqual(
- expect.arrayContaining(["link_pull_request", "watch_pull_request", "unwatch_pull_request"]),
- );
- expect(childTools).toContain("link_pull_request");
- expect(childTools).not.toContain("watch_pull_request");
- expect(childTools).not.toContain("unwatch_pull_request");
- }),
- ).pipe(Effect.provide(NodeHttpServer.layerTest)),
+ const parentTools = yield* listedTools("parentToken");
+ const childTools = yield* listedTools("childToken");
+ expect(parentTools).toEqual(
+ expect.arrayContaining([
+ "link_pull_request",
+ "watch_pull_request",
+ "unwatch_pull_request",
+ ]),
+ );
+ expect(childTools).toContain("link_pull_request");
+ expect(childTools).not.toContain("watch_pull_request");
+ expect(childTools).not.toContain("unwatch_pull_request");
+ expect(parentTools).toEqual(
+ expect.arrayContaining([
+ "pull_request_read",
+ "pull_request_review",
+ "pull_request_merge",
+ "ci_logs",
+ "ci_rerun",
+ ]),
+ );
+ const noForgeTools = yield* listedTools("noForgeToken");
+ expect(noForgeTools).toEqual(
+ expect.arrayContaining(["link_pull_request", "watch_pull_request"]),
+ );
+ expect(
+ noForgeTools.filter((name) => name.startsWith("pull_request_") || name.startsWith("ci_")),
+ ).toEqual([]);
+ }),
+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect(
diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts
index 9a85e5e01f3c5..53d232aad842a 100644
--- a/apps/server/src/mcp/McpHttpServer.ts
+++ b/apps/server/src/mcp/McpHttpServer.ts
@@ -1,6 +1,8 @@
+import * as Cache from "effect/Cache";
import * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
+import * as Duration from "effect/Duration";
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -33,6 +35,8 @@ import * as DeviceService from "../device/DeviceService.ts";
import * as HtmlRender from "../htmlRender/HtmlRender.ts";
import * as ThreadCommandExecutor from "../orchestration-v2/ThreadCommandExecutor.ts";
import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
+import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
+import * as PullRequestService from "../pullRequest/PullRequestService.ts";
import * as PullRequestWatchService from "../pullRequest/PullRequestWatchService.ts";
import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
import * as AnalyticsService from "../telemetry/AnalyticsService.ts";
@@ -167,6 +171,38 @@ const normalizeMcpHttpResponse = (
: response;
};
+// The first protocol is the fallback for clients that offer an unknown version.
+const mcpProtocols = [McpProtocol.v2025_06_18, McpProtocol.v2026_07_28] as const;
+
+/**
+ * Effect answers 400 to a notification a sessionless protocol does not define, because it requires
+ * `_meta` before it checks the method. The Go MCP SDK still sends `notifications/roots/list_changed`
+ * there and closes its connection on that 400. Remove once Effect ignores undefined notifications.
+ */
+const isUndefinedNotification = Effect.fnUntraced(function* (
+ request: HttpServerRequest.HttpServerRequest,
+) {
+ const method = request.headers["mcp-method"];
+ const protocol = mcpProtocols.find(
+ (candidate) => candidate.protocolVersion === request.headers["mcp-protocol-version"],
+ );
+ if (
+ request.method !== "POST" ||
+ protocol?.runtime._tag !== "Stateless" ||
+ !method?.startsWith("notifications/") ||
+ protocol.clientRpcs.requests.has(method)
+ ) {
+ return false;
+ }
+ const message = yield* Effect.orElseSucceed(request.json, () => undefined);
+ return (
+ Predicate.isReadonlyObject(message) &&
+ message.jsonrpc === "2.0" &&
+ message.method === method &&
+ !Predicate.hasProperty(message, "id")
+ );
+});
+
// Session tokens are `.`; registry tokens are a bare base64url secret.
const looksLikeProviderToken = (token: string) => token.length > 0 && !token.includes(".");
@@ -245,6 +281,24 @@ const makeMcpAuthMiddleware = Effect.gen(function* () {
Effect.map((settings) => settings.linkedEnvironmentsEnabled),
Effect.orElseSucceed(() => false),
);
+ const pullRequests = yield* Effect.serviceOption(PullRequestService.PullRequestService);
+ const projections = yield* Effect.serviceOption(ProjectionStore.ProjectionStoreV2);
+ // Every request reads it, and a remote added mid-thread shows the tools within a minute.
+ const forgeOfThread = yield* Cache.make({
+ capacity: 1_000,
+ timeToLive: Duration.minutes(1),
+ lookup: (threadId: ThreadId): Effect.Effect =>
+ Option.isNone(pullRequests) || Option.isNone(projections)
+ ? Effect.undefined
+ : projections.value.getThreadShell(threadId).pipe(
+ Effect.flatMap((thread) =>
+ thread === null
+ ? Effect.undefined
+ : pullRequests.value.servesProject(thread.projectId),
+ ),
+ Effect.orElseSucceed(() => undefined),
+ ),
+ });
const authenticateRequest = Effect.fn("McpHttpServer.authenticateRequest")(function* (
request: HttpServerRequest.HttpServerRequest,
) {
@@ -278,7 +332,11 @@ const makeMcpAuthMiddleware = Effect.gen(function* () {
const linkedEnvironments = yield* linksEnabled;
if (limited.client?.linked === true && !linkedEnvironments) return linkedEnvironmentsOff;
const origin = Option.getOrUndefined(Option.map(requestUrl(request), (url) => url.origin));
- return { ...limited, linkedEnvironments, origin };
+ const forge =
+ limited.thread === undefined
+ ? undefined
+ : yield* Cache.get(forgeOfThread, limited.thread.threadId);
+ return { ...limited, linkedEnvironments, origin, ...(forge === undefined ? {} : { forge }) };
});
// Untraced: a span here would wrap the tool call; the HTTP server span already covers it.
return Effect.fnUntraced(function* (httpEffect) {
@@ -287,6 +345,7 @@ const makeMcpAuthMiddleware = Effect.gen(function* () {
if (request.headers.origin !== undefined) return HttpServerResponse.empty({ status: 403 });
const admitted = yield* authenticateRequest(request);
if (HttpServerResponse.isHttpServerResponse(admitted)) return admitted;
+ if (yield* isUndefinedNotification(request)) return HttpServerResponse.empty({ status: 202 });
return yield* httpEffect.pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, admitted),
Effect.map(normalizeMcpHttpResponse),
@@ -1336,8 +1395,7 @@ export const layerMcpTransport = (registrations: Layer.Layer {
return scope?.linkedEnvironments !== false;
};
+/** `McpSchema.EnabledWhen` for tools that act on the thread's forge, hidden where it has none. */
+export const hiddenWithoutForge = (): boolean => {
+ const fiber = Fiber.getCurrent();
+ const scope = fiber && Context.getOrUndefined(fiber.context, McpInvocationContext);
+ return scope?.forge !== false;
+};
+
export type McpCapabilityError = C extends "preview"
? PreviewAutomationUnavailableError
: McpCapabilityUnavailableError;
diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts
index 802f3dfd761e3..0bbb8a65327d0 100644
--- a/apps/server/src/mcp/OrchestratorMcpService.test.ts
+++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts
@@ -6,6 +6,7 @@ import {
ContextTransferId,
EnvironmentId,
GitCommandError,
+ isLiveSubagentShell,
MessageId,
NodeId,
ORCHESTRATOR_MCP_RUNNING_TASK_NEXT,
@@ -4861,6 +4862,18 @@ describe("OrchestratorMcpService thread list", () => {
{ taskId: "sleep-600", kind: "command" as const, awaited: true as const },
],
},
+ {
+ ...shell("thread:c-settled", "project:c", false),
+ settledOverride: "settled" as const,
+ settledAt: DateTime.makeUnsafe("2026-01-02T00:00:00Z"),
+ },
+ {
+ ...shell("thread:c-awaiting-command", "project:c", false),
+ activityRunStatus: null,
+ pendingBackgroundTasks: [
+ { taskId: "sleep-600", kind: "command" as const, awaited: true as const },
+ ],
+ },
];
const shellRequests: Array> = [];
const service = layerOrchestratorService.pipe(
@@ -4875,6 +4888,14 @@ describe("OrchestratorMcpService thread list", () => {
(thread) => input.projectId === undefined || thread.projectId === input.projectId,
),
),
+ listActiveShellIndex: () =>
+ Effect.succeed(
+ shells.map((thread) => ({
+ ...thread,
+ mayBeLive: isLiveSubagentShell(thread),
+ hasRemoteTasks: false,
+ })),
+ ),
getShellSnapshot: (options) => {
const threadIds = options?.threadIds ?? shells.map((thread) => thread.id);
shellRequests.push(threadIds);
@@ -4979,6 +5000,22 @@ describe("OrchestratorMcpService thread list", () => {
}).pipe(Effect.provide(service)),
);
+ it.effect("skips building shells for settled threads when every status filter is live", () =>
+ Effect.gen(function* () {
+ const mcp = yield* OrchestratorMcpService.OrchestratorMcpService;
+ shellRequests.length = 0;
+ const listed = yield* mcp.listThreads(client, {
+ projectId: ProjectId.make("project:c"),
+ statuses: ["preparing", "queued", "starting", "running", "waiting"],
+ });
+ assert.deepStrictEqual(
+ listed.threads.map((thread) => thread.threadId),
+ ["thread:c-awaiting-command"],
+ );
+ assert.notInclude(shellRequests.flat(), ThreadId.make("thread:c-settled"));
+ }).pipe(Effect.provide(service)),
+ );
+
it.effect("builds shells only for the threads on the page", () =>
Effect.gen(function* () {
const mcp = yield* OrchestratorMcpService.OrchestratorMcpService;
diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts
index 95e269c64c97f..8dcd025c82481 100644
--- a/apps/server/src/mcp/OrchestratorMcpService.ts
+++ b/apps/server/src/mcp/OrchestratorMcpService.ts
@@ -934,6 +934,14 @@ function threadStatus(
return backgroundWorkHoldsCompletion(pendingBackgroundTasks ?? []) ? "waiting" : settledStatus;
}
+const LIVE_LISTED_THREAD_STATUSES: ReadonlySet = new Set([
+ "queued",
+ "preparing",
+ "starting",
+ "running",
+ "waiting",
+]);
+
function listedThreadStatus(shell: OrchestrationV2ThreadShell) {
return threadStatus(shell.activityRunStatus, shell.status, shell.pendingBackgroundTasks);
}
@@ -3280,7 +3288,21 @@ const make = Effect.gen(function* () {
? null
: new Set(input.statuses);
const titleContains = input.titleContains?.toLocaleLowerCase();
+ // A live status needs a source the index's mayBeLive covers, so a live-only filter
+ // skips building shells for every thread that cannot match.
+ const mayBeLiveIds =
+ statuses !== null &&
+ [...statuses].every((status) => LIVE_LISTED_THREAD_STATUSES.has(status))
+ ? new Set(
+ (yield* threadManagement
+ .listActiveShellIndex()
+ .pipe(Effect.mapError(listFailure))).flatMap((entry) =>
+ entry.mayBeLive ? [entry.id] : [],
+ ),
+ )
+ : null;
const candidates = projectThreads
+ .filter((thread) => mayBeLiveIds === null || mayBeLiveIds.has(thread.id))
.filter(
(thread) =>
input.settled === undefined || threadSettlement(thread).settled === input.settled,
diff --git a/apps/server/src/mcp/toolkits/project/handlers.test.ts b/apps/server/src/mcp/toolkits/project/handlers.test.ts
index 2bfcd896b3802..8fcccc0246e20 100644
--- a/apps/server/src/mcp/toolkits/project/handlers.test.ts
+++ b/apps/server/src/mcp/toolkits/project/handlers.test.ts
@@ -1052,6 +1052,47 @@ it.effect("an agent cannot delete the built-in scratch project, even with force"
}),
);
+it.effect("reading a project shows the default model saved in Settings", () =>
+ Effect.gen(function* () {
+ const overrideModel = {
+ instanceId: ProviderInstanceId.make("claudeAgent"),
+ model: "claude-sonnet",
+ };
+ const harness = clientLaunchHarness({
+ runtimeModeCeiling: "full-access",
+ overrideModel,
+ launched: [],
+ });
+ const dependencies = Layer.merge(
+ harness.dependencies,
+ Layer.mock(Project.ProjectService)({
+ getById: (projectId) =>
+ Effect.succeedSome({
+ id: projectId,
+ title: "Client target",
+ workspaceRoot: "/projects/client-target",
+ defaultModelSelection: null,
+ scripts: [],
+ createdAt: "2026-01-01T00:00:00.000Z",
+ updatedAt: "2026-01-01T00:00:00.000Z",
+ deletedAt: null,
+ }),
+ }),
+ );
+ const toolkit = yield* ProjectToolkit.pipe(
+ Effect.provide(
+ McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)),
+ ),
+ );
+
+ const read = yield* toolkit
+ .handle("t3_project_read", { projectId: harness.projectId })
+ .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
+
+ expect(read.at(-1)?.result).toMatchObject({ defaultModelSelection: overrideModel });
+ }),
+);
+
it.effect("an update the project refuses tells the agent why", () =>
Effect.gen(function* () {
const harness = clientLaunchHarness({ runtimeModeCeiling: "full-access", launched: [] });
diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts
index 86e3350bbf22b..651a764f3b8d4 100644
--- a/apps/server/src/mcp/toolkits/project/handlers.ts
+++ b/apps/server/src/mcp/toolkits/project/handlers.ts
@@ -5,6 +5,7 @@ import {
OrchestratorMcpFailure,
type OrchestrationV2ThreadLaunchWorkspaceStrategy,
ProjectId,
+ type Project as ProjectRecord,
T3_PROJECT_FILE_NAME,
} from "@t3tools/contracts";
import * as Digest from "effect/crypto/Digest";
@@ -165,6 +166,25 @@ const access = Effect.gen(function* () {
yield* readCaller();
return yield* Project.ProjectService;
});
+
+/** Settings, not the project record, hold the project default model that new threads use. */
+const withSavedDefaultModel = Effect.gen(function* () {
+ const settings = yield* ServerSettings.ServerSettingsService.pipe(
+ Effect.flatMap((service) => service.getSettings),
+ Effect.mapError(unavailable),
+ );
+ return (project: ProjectRecord) => {
+ const resolved = resolveProjectSettings(settings, project.id, project);
+ return {
+ ...project,
+ defaultModelSelection:
+ resolved.sources.defaultModelSelection === "project"
+ ? resolved.settings.defaultModelSelection
+ : null,
+ };
+ };
+});
+
export const layer = McpToolAccess.toLayer(ProjectToolkit, {
t3_thread_launch: McpToolAccess.startsThreads(
(input) => input,
@@ -407,9 +427,10 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
Effect.gen(function* () {
const projects = yield* access;
// Identities are resolved: linked environments find this side's project by repository.
- return yield* projects
+ const page = yield* projects
.listPage({ cursor: input.cursor ?? 0, limit: input.limit ?? 20 })
.pipe(Effect.mapError(unavailable));
+ return { ...page, projects: page.projects.map(yield* withSavedDefaultModel) };
}),
),
t3_project_read: McpToolAccess.reads((input) =>
@@ -421,7 +442,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
code: "invalid_request",
message: "The project was not found.",
});
- return result.value;
+ return (yield* withSavedDefaultModel)(result.value);
}),
),
t3_project_create: McpToolAccess.writesEnvironment(
@@ -475,9 +496,10 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
t3_project_update: McpToolAccess.writesEnvironment((input) =>
Effect.gen(function* () {
const projects = yield* Project.ProjectService;
- return yield* projects
+ const updated = yield* projects
.update({ ...input, commandId: yield* newCommandId() })
.pipe(Effect.mapError(projectFailure));
+ return (yield* withSavedDefaultModel)(updated);
}),
),
t3_project_delete: McpToolAccess.writesEnvironment((input) =>
diff --git a/apps/server/src/mcp/toolkits/project/tools.ts b/apps/server/src/mcp/toolkits/project/tools.ts
index 7de832eea28ad..57ba4467fd9de 100644
--- a/apps/server/src/mcp/toolkits/project/tools.ts
+++ b/apps/server/src/mcp/toolkits/project/tools.ts
@@ -47,6 +47,7 @@ const shared = {
McpInvocationContext.McpInvocationContext,
ThreadManagementService.ThreadManagementService,
ProjectService.ProjectService,
+ ServerSettings.ServerSettingsService,
SecureRandom.SecureRandom,
],
};
diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts
index 3c454cbe6e48c..b036392730fa9 100644
--- a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts
+++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts
@@ -6,6 +6,12 @@ import {
type OrchestrationV2ServerCommand as OrchestrationCommand,
PullRequestOperationError,
type OrchestrationProjectShell,
+ type PullRequestActionInput,
+ type PullRequestDiffResult,
+ type PullRequestSubmitReviewInput,
+ type PullRequestActivity,
+ type PullRequestListInput,
+ type PullRequestDetail,
type PullRequestRef,
type PullRequestReviewGuideResult,
type ThreadPullRequestLink,
@@ -14,12 +20,14 @@ import {
import { describe, expect, it } from "@effect/vitest";
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as Effect from "effect/Effect";
+import * as Base64Url from "effect/encoding/Base64Url";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import type { Tool } from "effect/ai";
+import * as GitManager from "../../../git/GitManager.ts";
import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts";
import {
type PullRequestTestThread,
@@ -28,6 +36,7 @@ import {
import * as ProjectService from "../../../project/ProjectService.ts";
import * as PullRequestWatchService from "../../../pullRequest/PullRequestWatchService.ts";
import * as PullRequestReviewGuideService from "../../../pullRequest/PullRequestReviewGuideService.ts";
+import * as PullRequestService from "../../../pullRequest/PullRequestService.ts";
import * as McpInvocationContext from "../../McpInvocationContext.ts";
import * as McpToolAccess from "../../McpToolAccess.ts";
import * as McpToolAccessTestkit from "../../McpToolAccess.testkit.ts";
@@ -144,6 +153,8 @@ interface HarnessOptions {
PullRequestReviewGuideResult & { started: boolean },
PullRequestOperationError
>;
+ readonly pullRequests?: Partial;
+ readonly git?: Partial;
}
const NO_GUIDE: PullRequestReviewGuideResult = { guide: null, run: null, currentHeadSha: "head-1" };
@@ -196,6 +207,8 @@ const makeHarness = Effect.fn("makePullRequestsToolkitHarness")(function* (
Effect.succeed(id === thread?.id ? v2PullRequestThread(thread) : null),
dispatch,
}),
+ Layer.mock(PullRequestService.PullRequestService)(options.pullRequests ?? {}),
+ Layer.mock(GitManager.GitManager)(options.git ?? {}),
Layer.succeed(SecureRandom.SecureRandom, testCrypto),
McpToolAccessTestkit.liveThreadsLayer,
);
@@ -784,3 +797,513 @@ describe("pull request guide tools", () => {
}),
);
});
+
+describe("source control tools", () => {
+ const branchThread = {
+ ...makeThread([]),
+ worktreePath: "/workspace/worktree",
+ branchPullRequest: {
+ projectId: PROJECT_ID,
+ repository: "t3tools/t3code",
+ number: 42,
+ url: "https://github.com/t3tools/t3code/pull/42",
+ },
+ };
+ const detail = {
+ title: "Add tools",
+ body: "Adds tools.",
+ state: "open",
+ isDraft: false,
+ author: null,
+ headBranch: "tools",
+ baseBranch: "main",
+ headSha: "abc123",
+ mergeability: "mergeable",
+ additions: 1,
+ deletions: 0,
+ changedFiles: 1,
+ labels: [],
+ reviewers: [],
+ checks: [{ name: "CI", status: "success", description: null, url: null }],
+ } as unknown as PullRequestDetail;
+ const reviewThread = (id: string, isResolved: boolean) => ({
+ id,
+ path: "a.ts",
+ line: 1,
+ side: "right" as const,
+ isResolved,
+ isOutdated: false,
+ comments: [],
+ });
+ const activity: PullRequestActivity = {
+ comments: [],
+ commentCount: 0,
+ commentsTruncated: false,
+ reviewThreads: [reviewThread("open-thread", false), reviewThread("done-thread", true)],
+ commits: [],
+ };
+
+ it.effect("reads the thread's branch PR, only the sections asked, without resolved threads", () =>
+ Effect.gen(function* () {
+ const asked: Array = [];
+ const harness = yield* makeHarness({
+ thread: branchThread,
+ pullRequests: {
+ detail: (ref) => Effect.sync(() => asked.push(ref)).pipe(Effect.as(detail)),
+ activity: () => Effect.succeed(activity),
+ },
+ });
+ const result = yield* harness.call("pull_request_read", {
+ sections: ["summary", "conversation"],
+ });
+ expect(asked).toEqual([
+ {
+ projectId: PROJECT_ID,
+ host: "github.com",
+ repository: "t3tools/t3code",
+ number: 42,
+ allowStale: false,
+ },
+ ]);
+ expect(result.summary?.headSha).toBe("abc123");
+ expect(result.checks).toBeUndefined();
+ expect(result.conversation?.reviewThreads.map((thread) => thread.id)).toEqual([
+ "open-thread",
+ ]);
+ expect(result.conversation?.hiddenResolvedThreads).toBe(1);
+ }),
+ );
+
+ it.effect("pages a long conversation and the PR list through the cursors they return", () =>
+ Effect.gen(function* () {
+ const comment = (body: string) =>
+ ({ id: body.slice(0, 8), author: null, body, createdAt: "2026-11-01T00:00:00Z" }) as never;
+ const long = (id: string) => ({
+ ...reviewThread(id, false),
+ comments: [comment("x".repeat(20_000))],
+ });
+ const listed: Array = [];
+ let firstResolved = false;
+ const harness = yield* makeHarness({
+ thread: branchThread,
+ pullRequests: {
+ activity: () =>
+ Effect.sync(() => ({
+ ...activity,
+ reviewThreads: [
+ {
+ ...long("first"),
+ isResolved: firstResolved,
+ nextCommentsCursor: "later",
+ },
+ long("second"),
+ reviewThread("done-thread", true),
+ ],
+ })),
+ threadComments: (input) =>
+ Effect.succeed(
+ input.cursor === "later"
+ ? { comments: [comment("reply")], nextCursor: null }
+ : { comments: [], nextCursor: null },
+ ),
+ list: (input) =>
+ Effect.sync(() => listed.push(input)).pipe(
+ Effect.as({
+ viewers: {},
+ providers: [],
+ entries: [],
+ errors: [],
+ truncated: input.cursors === undefined,
+ nextCursors: input.cursors === undefined ? { "t3tools/t3code": "page-2" } : {},
+ }),
+ ),
+ },
+ });
+ const first = yield* harness.call("pull_request_read", { sections: ["conversation"] });
+ expect(first.conversation?.reviewThreads).toMatchObject([
+ { id: "first", moreComments: false, comments: [{}, { body: "reply" }] },
+ ]);
+ const cursor = first.conversation?.nextCursor;
+ expect(cursor).toEqual(expect.any(String));
+ // The agent resolves what it read; the next page still starts at the next thread.
+ firstResolved = true;
+ const second = yield* harness.call("pull_request_read", { cursor: cursor! });
+ expect(second.summary).toBeUndefined();
+ expect(second.conversation?.reviewThreads.map((thread) => thread.id)).toEqual(["second"]);
+ expect(second.conversation?.nextCursor).toBeNull();
+ // A cursor past the current end finishes instead of repeating an empty page.
+ const stale = Base64Url.encode(
+ JSON.stringify({ threads: 99, comments: 99, includeResolved: false }),
+ );
+ const past = yield* harness.call("pull_request_read", { cursor: stale });
+ expect(past.conversation).toMatchObject({ reviewThreads: [], nextCursor: null });
+
+ const page = yield* harness.call("pull_request_list", {});
+ yield* harness.call("pull_request_list", { cursor: page.nextCursor! });
+ expect(listed.map((input) => input.cursors)).toEqual([
+ undefined,
+ { "t3tools/t3code": "page-2" },
+ ]);
+ const invalid = yield* harness
+ .call("pull_request_read", { cursor: "not-a-cursor" })
+ .pipe(Effect.flip);
+ expect(invalid._tag).toBe("PullRequestCursorInvalidError");
+ }),
+ );
+
+ it.effect("asks for a number when the thread's branch has no PR", () =>
+ Effect.gen(function* () {
+ const harness = yield* makeHarness();
+ const error = yield* harness.call("pull_request_read", {}).pipe(Effect.flip);
+ expect(error._tag).toBe("PullRequestBranchHasNoneError");
+ }),
+ );
+
+ it.effect("reads the PR this thread opened before status sync reports it", () =>
+ Effect.gen(function* () {
+ const asked: Array = [];
+ const opened = (headBranch: string) =>
+ makeHarness({
+ thread: { ...makeThread([makeLink(43, { source: "created" })]), branch: "tools" },
+ pullRequests: {
+ summary: () => Effect.succeed({ state: "open", headBranch } as never),
+ detail: (ref) => Effect.sync(() => asked.push(ref)).pipe(Effect.as(detail)),
+ },
+ });
+ const harness = yield* opened("tools");
+ yield* harness.call("pull_request_read", { sections: ["summary"] });
+ expect(asked).toMatchObject([{ number: 43 }]);
+
+ // Before sync, the host says which branch it came from; another branch's is not this one.
+ const moved = yield* opened("old");
+ const unsynced = yield* moved.call("pull_request_read", {}).pipe(Effect.flip);
+ expect(unsynced._tag).toBe("PullRequestBranchHasNoneError");
+
+ // After a switch to another branch, the PR opened from the old one is not the branch's.
+ const switched = yield* makeHarness({
+ thread: {
+ ...makeThread([makeLink(43, { source: "created", headBranch: "old" })]),
+ branch: "new",
+ },
+ });
+ const error = yield* switched
+ .call("pull_request_update", { title: "New title" })
+ .pipe(Effect.flip);
+ expect(error._tag).toBe("PullRequestBranchHasNoneError");
+ }),
+ );
+
+ it.effect("merges pinned to the head the agent checked", () =>
+ Effect.gen(function* () {
+ const actions: Array = [];
+ const harness = yield* makeHarness({
+ thread: branchThread,
+ pullRequests: {
+ runAction: (input) => Effect.sync(() => void actions.push(input)),
+ summary: () => Effect.succeed({ state: "open" } as never),
+ },
+ });
+ const result = yield* harness.call("pull_request_merge", {
+ expectedHeadSha: "abc123",
+ method: "squash",
+ auto: true,
+ });
+ expect(result).toMatchObject({ number: 42, state: "open" });
+ expect(actions).toMatchObject([
+ {
+ number: 42,
+ action: "enable-auto-merge",
+ expectedHeadSha: "abc123",
+ mergeMethod: "squash",
+ },
+ ]);
+ }),
+ );
+
+ it.effect("a stack merge pins every open layer up to the PR", () =>
+ Effect.gen(function* () {
+ const actions: Array = [];
+ let lowerHead: string | undefined = "bbb";
+ const layer = (number: number, state: "open" | "merged", headSha: string | undefined) => ({
+ number,
+ state,
+ ...(headSha === undefined ? {} : { headSha }),
+ headBranch: `layer-${number}`,
+ });
+ const harness = yield* makeHarness({
+ thread: branchThread,
+ pullRequests: {
+ stack: (_input, options) =>
+ options?.bypassCache !== true
+ ? Effect.die("a merge must not pin heads from the cache")
+ : Effect.succeed({
+ id: "stack-1",
+ number: 7,
+ url: "https://github.com/acme/app/stacks/7",
+ base: "main",
+ layers: [
+ layer(40, "merged", "aaa"),
+ layer(41, "open", lowerHead),
+ layer(42, "open", "stale"),
+ layer(43, "open", "ddd"),
+ ],
+ }),
+ runAction: (input) => Effect.sync(() => void actions.push(input)),
+ summary: () => Effect.succeed({ state: "merged" } as never),
+ },
+ });
+ yield* harness.call("pull_request_merge", { expectedHeadSha: "ccc", stack: true });
+ expect(actions).toMatchObject([
+ {
+ number: 42,
+ action: "merge",
+ stackNumber: 7,
+ expectedStackHeads: [
+ { number: 41, headSha: "bbb" },
+ { number: 42, headSha: "ccc" },
+ ],
+ },
+ ]);
+ lowerHead = undefined;
+ const unpinned = yield* harness
+ .call("pull_request_merge", { expectedHeadSha: "ccc", stack: true })
+ .pipe(Effect.flip);
+ expect(unpinned._tag).toBe("PullRequestForgeError");
+ expect(actions).toHaveLength(1);
+ }),
+ );
+
+ it.effect("re-running checks reopens a watch that saw its checks finish", () =>
+ Effect.gen(function* () {
+ const watch = {
+ startedAt: "2026-08-20T00:00:00.000Z",
+ headSha: "abc123",
+ failedChecks: ["test"],
+ passed: false,
+ passedChecks: [],
+ remarksThrough: "2026-08-20T00:00:00.000Z",
+ remarkIds: [],
+ conflicting: false,
+ wakes: 0,
+ };
+ const rerun = (checksPending: boolean | undefined, reran: boolean) =>
+ Effect.gen(function* () {
+ const harness = yield* makeHarness({
+ thread: {
+ ...branchThread,
+ pullRequests: [
+ makeLink(42, {
+ watch: checksPending === undefined ? watch : { ...watch, checksPending },
+ }),
+ ],
+ },
+ pullRequests: {
+ rerunChecks: () => Effect.succeed([{ name: "test", rerun: reran, detail: null }]),
+ },
+ });
+ yield* harness.call("ci_rerun", {});
+ return yield* Ref.get(harness.commands);
+ });
+ expect(yield* rerun(false, true)).toMatchObject([
+ { type: "thread.pull-request-watch.checks-reopen", threadId: THREAD_ID },
+ ]);
+ // Nothing re-ran, or the watch has no answer to clear.
+ expect(yield* rerun(false, false)).toEqual([]);
+ expect(yield* rerun(undefined, true)).toEqual([]);
+ }),
+ );
+
+ it.effect("opens a PR from the thread's worktree and links it even if dismissed", () =>
+ Effect.gen(function* () {
+ const opened: Array<{ readonly cwd: string; readonly draft: boolean | undefined }> = [];
+ const harness = yield* makeHarness({
+ thread: {
+ ...makeThread([makeLink(43, { source: "stack-dismissed" })]),
+ worktreePath: "/workspace/worktree",
+ },
+ git: {
+ createPullRequest: (input) =>
+ Effect.sync(() => opened.push({ cwd: input.cwd, draft: input.draft })).pipe(
+ Effect.as({
+ status: "created" as const,
+ url: "https://github.com/t3tools/t3code/pull/43",
+ number: 43,
+ baseBranch: "main",
+ headBranch: "tools",
+ title: input.title,
+ }),
+ ),
+ },
+ });
+ const result = yield* harness.call("pull_request_create", {
+ title: "Add tools",
+ body: "Adds tools.",
+ draft: true,
+ });
+ expect(result).toMatchObject({ number: 43, created: true });
+ expect(opened).toEqual([{ cwd: "/workspace/worktree", draft: true }]);
+ expect(yield* Ref.get(harness.commands)).toMatchObject([
+ { type: "thread.pull-request.link", number: 43, source: "created" },
+ ]);
+ }),
+ );
+
+ it.effect("replies to and resolves a review thread, and refuses resolving without one", () =>
+ Effect.gen(function* () {
+ const calls: Array = [];
+ const harness = yield* makeHarness({
+ thread: branchThread,
+ pullRequests: {
+ replyToThread: (input) => Effect.sync(() => calls.push(`reply ${input.threadId}`)),
+ setThreadResolution: (input) =>
+ input.threadId === "locked-thread"
+ ? Effect.fail(
+ new PullRequestOperationError({
+ operation: "setThreadResolution",
+ detail: "Locked.",
+ }),
+ )
+ : Effect.sync(() => void calls.push(`resolve ${input.threadId} ${input.resolved}`)),
+ },
+ });
+ const result = yield* harness.call("pull_request_respond", {
+ reviewThreadId: "open-thread",
+ body: "Fixed.",
+ resolved: true,
+ });
+ expect(result).toMatchObject({ replied: true, resolved: true });
+ expect(calls).toEqual(["reply open-thread", "resolve open-thread true"]);
+ const partial = yield* harness
+ .call("pull_request_respond", {
+ reviewThreadId: "locked-thread",
+ body: "Fixed.",
+ resolved: true,
+ })
+ .pipe(Effect.flip);
+ expect(partial.message).toContain("The reply was posted");
+ const error = yield* harness
+ .call("pull_request_respond", { body: "Done", resolved: true })
+ .pipe(Effect.flip);
+ expect(error._tag).toBe("PullRequestNothingToDoError");
+ }),
+ );
+
+ it.effect("places review comments by the diff page that shows their line", () =>
+ Effect.gen(function* () {
+ const reviews: Array = [];
+ const pages: Record = {
+ first: {
+ patch:
+ "diff --git a/a.ts b/a.ts\n--- a/a.ts\n+++ b/a.ts\n@@ -1,2 +1,2 @@\n-old\n+new\n same\n",
+ truncated: false,
+ nextCursor: "second",
+ },
+ second: {
+ patch:
+ "diff --git a/b.ts b/b.ts\n--- a/b.ts\n+++ b/b.ts\n@@ -9,1 +9,2 @@\n kept\n+added\n",
+ truncated: false,
+ nextCursor: null,
+ },
+ };
+ const harness = yield* makeHarness({
+ thread: branchThread,
+ pullRequests: {
+ diff: (input) => Effect.succeed(pages[input.cursor ?? "first"]!),
+ submitReview: (input) => Effect.sync(() => void reviews.push(input)),
+ },
+ });
+ yield* harness.call("pull_request_review", {
+ verdict: "request-changes",
+ body: "Two things.",
+ comments: [
+ { path: "b.ts", line: 10, startLine: 9, body: "Why?" },
+ { path: "a.ts", line: 1, side: "old", body: "Keep this." },
+ ],
+ });
+ expect(reviews).toMatchObject([
+ {
+ number: 42,
+ verdict: "request-changes",
+ body: "Two things.",
+ comments: [
+ {
+ path: "b.ts",
+ position: { kind: "added", newLine: 10 },
+ startPosition: { kind: "context", oldLine: 9, newLine: 9, side: "right" },
+ },
+ { path: "a.ts", position: { kind: "deleted", oldLine: 1 } },
+ ],
+ },
+ ]);
+
+ // A line the diff never shows fails before anything is posted.
+ const error = yield* harness
+ .call("pull_request_review", {
+ verdict: "comment",
+ comments: [{ path: "a.ts", line: 40, body: "Here?" }],
+ })
+ .pipe(Effect.flip);
+ expect(error.message).toContain("a.ts line 40 (new side) is not in this PR's diff");
+ expect(reviews).toHaveLength(1);
+ }),
+ );
+
+ it.effect("updates labels, requests reviewers by login, and closes the PR", () =>
+ Effect.gen(function* () {
+ const calls: Array = [];
+ const harness = yield* makeHarness({
+ thread: branchThread,
+ pullRequests: {
+ setLabels: (input) =>
+ Effect.sync(() => void calls.push(["labels", input.labels, input.applied])),
+ reviewerCandidates: (input) =>
+ Effect.succeed({
+ candidates: [
+ {
+ id: "MDQ6VXNlcjE=",
+ kind: "user",
+ login: input.query === "Octo" ? "octo" : "x",
+ name: null,
+ avatarUrl: null,
+ isRequested: false,
+ },
+ {
+ id: "core",
+ kind: "team",
+ login: "acme/core",
+ name: null,
+ avatarUrl: null,
+ isRequested: false,
+ },
+ ],
+ } as never),
+ requestReviewers: (input) =>
+ Effect.sync(() => void calls.push(["reviewers", input.reviewers])),
+ runAction: (input) => Effect.sync(() => void calls.push(["action", input.action])),
+ },
+ });
+ yield* harness.call("pull_request_update", {
+ addLabels: ["bug"],
+ removeLabels: ["wip"],
+ requestReviewers: ["Octo", "acme/core"],
+ state: "closed",
+ });
+ expect(calls).toEqual([
+ ["labels", ["bug"], true],
+ ["labels", ["wip"], false],
+ [
+ "reviewers",
+ [
+ { id: "MDQ6VXNlcjE=", kind: "user" },
+ { id: "core", kind: "team" },
+ ],
+ ],
+ ["action", "close"],
+ ]);
+ const unknown = yield* harness
+ .call("pull_request_update", { requestReviewers: ["nobody"] })
+ .pipe(Effect.flip);
+ expect(unknown.message).toContain("No reviewer named nobody");
+ }),
+ );
+});
diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts
index 884dd09a3dea4..65eaf22975c68 100644
--- a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts
+++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts
@@ -1,21 +1,34 @@
import {
CommandId,
+ NonNegativeInt,
+ type PullRequestActivity,
+ PullRequestListCursors,
+ type PullRequestRef,
+ type PullRequestReviewCommentDraft,
+ type PullRequestReviewThread,
type OrchestrationProjectShell,
type PullRequestState,
+ type PullRequestWatchUntil,
type OrchestrationV2ThreadShell,
type ThreadId,
type ThreadPullRequestLink,
+ TrimmedNonEmptyString,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as Effect from "effect/Effect";
+import * as Base64Url from "effect/encoding/Base64Url";
import * as Option from "effect/Option";
+import * as Schema from "effect/Schema";
+import * as GitManager from "../../../git/GitManager.ts";
import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts";
import * as ProjectService from "../../../project/ProjectService.ts";
import * as PullRequestWatchService from "../../../pullRequest/PullRequestWatchService.ts";
import { resolveTarget, type ResolvedTarget } from "../../../pullRequest/pullRequestTarget.ts";
import * as PullRequestReviewGuideService from "../../../pullRequest/PullRequestReviewGuideService.ts";
+import * as PullRequestService from "../../../pullRequest/PullRequestService.ts";
+import { reviewPositionInPatch } from "../../../pullRequest/pullRequestReviewPosition.ts";
import { pullRequestSyncKey } from "../../../pullRequest/pullRequestSyncKey.ts";
import { sourceControlDefinitions } from "../../../sourceControl/sourceControlDefinitions.ts";
import {
@@ -31,6 +44,14 @@ import * as McpToolAccess from "../../McpToolAccess.ts";
import { threadNotFound } from "../../threadAccess.ts";
import {
type ListThreadPullRequestsResult,
+ PullRequestBranchHasNoneError,
+ PullRequestCursorInvalidError,
+ PullRequestForgeError,
+ PullRequestNothingToDoError,
+ type PullRequestReadSection,
+ type ReadPullRequestResult,
+ type ReviewLineComment,
+ type ThreadPullRequestInput,
PullRequestLinkFailedError,
PullRequestUnlinkFailedError,
PullRequestListFailedError,
@@ -43,6 +64,97 @@ import {
CHILD_PULL_REQUEST_REPORT_NEXT,
} from "./tools.ts";
+const ReadCursor = Schema.Union([
+ Schema.Struct({ diff: TrimmedNonEmptyString }),
+ Schema.Struct({
+ threads: NonNegativeInt,
+ comments: NonNegativeInt,
+ includeResolved: Schema.Boolean,
+ }),
+]);
+type ReadCursor = typeof ReadCursor.Type;
+
+const ReadCursorJson = Schema.fromJsonString(ReadCursor);
+const ListCursorsJson = Schema.fromJsonString(PullRequestListCursors);
+const encodeReadCursorJson = Schema.encodeSync(ReadCursorJson);
+const encodeListCursorsJson = Schema.encodeSync(ListCursorsJson);
+const decodeReadCursorJson = Schema.decodeUnknownEffect(ReadCursorJson);
+const decodeListCursorsJson = Schema.decodeUnknownEffect(ListCursorsJson);
+
+const decodeCursorText = (cursor: string) =>
+ Effect.fromResult(Base64Url.decodeString(cursor)).pipe(
+ Effect.mapError(() => new PullRequestCursorInvalidError({})),
+ );
+
+const readCursors = {
+ encode: (value: ReadCursor) => Base64Url.encode(encodeReadCursorJson(value)),
+ decode: (cursor: string) =>
+ decodeCursorText(cursor).pipe(
+ Effect.flatMap(decodeReadCursorJson),
+ Effect.mapError(() => new PullRequestCursorInvalidError({})),
+ ),
+};
+
+const listCursors = {
+ encode: (value: PullRequestListCursors) => Base64Url.encode(encodeListCursorsJson(value)),
+ decode: (cursor: string) =>
+ decodeCursorText(cursor).pipe(
+ Effect.flatMap(decodeListCursorsJson),
+ Effect.mapError(() => new PullRequestCursorInvalidError({})),
+ ),
+};
+
+/** Keeps one conversation page near the size of a capped CI log. */
+const CONVERSATION_PAGE_CHARS = 32_000;
+const THREAD_COMMENT_PAGES = 4;
+/** Diff pages searched for review comment lines; a PR past this is too big to review by line. */
+const REVIEW_DIFF_PAGES = 10;
+
+function conversationPage(
+ activity: PullRequestActivity,
+ start: { readonly threads: number; readonly comments: number },
+ includeResolved: boolean,
+) {
+ // Offsets index the unfiltered lists, whose order resolving a thread does not change.
+ const { reviewThreads, comments } = activity;
+ const pageThreads: Array = [];
+ const pageComments: Array = [];
+ let size = 0;
+ let thread = Math.min(start.threads, reviewThreads.length);
+ let comment = Math.min(start.comments, comments.length);
+ const fits = (item: unknown) => {
+ const next = size + JSON.stringify(item).length;
+ if (next > CONVERSATION_PAGE_CHARS && pageThreads.length + pageComments.length > 0) {
+ return false;
+ }
+ size = next;
+ return true;
+ };
+ // Review threads come first: they hold the feedback an agent acts on.
+ while (thread < reviewThreads.length) {
+ const next = reviewThreads[thread]!;
+ if (includeResolved || !next.isResolved) {
+ if (!fits(next)) break;
+ pageThreads.push(next);
+ }
+ thread += 1;
+ }
+ if (thread === reviewThreads.length) {
+ while (comment < comments.length && fits(comments[comment])) {
+ pageComments.push(comments[comment++]!);
+ }
+ }
+ const done = thread === reviewThreads.length && comment === comments.length;
+ return {
+ threads: pageThreads,
+ comments: pageComments,
+ hiddenResolvedThreads: includeResolved
+ ? 0
+ : reviewThreads.filter((candidate) => candidate.isResolved).length,
+ next: done ? null : { threads: thread, comments: comment, includeResolved },
+ };
+}
+
function entryOf(
link: ThreadPullRequestLink,
chains: ReturnType,
@@ -147,6 +259,8 @@ const make = Effect.gen(function* () {
const engine = yield* Orchestrator.OrchestratorV2;
const reviewGuides = yield* PullRequestReviewGuideService.PullRequestReviewGuideService;
const watches = yield* PullRequestWatchService.PullRequestWatchService;
+ const pullRequests = yield* PullRequestService.PullRequestService;
+ const git = yield* GitManager.GitManager;
const projects = yield* ProjectService.ProjectService;
const random = yield* SecureRandom.SecureRandom;
@@ -161,7 +275,8 @@ const make = Effect.gen(function* () {
Failure:
| typeof PullRequestLinkFailedError
| typeof PullRequestUnlinkFailedError
- | typeof PullRequestListFailedError,
+ | typeof PullRequestListFailedError
+ | typeof PullRequestForgeError,
requested: ThreadId | undefined,
) {
const scope = yield* McpInvocationContext.requireMcpCapability("pull-requests");
@@ -181,7 +296,10 @@ const make = Effect.gen(function* () {
const projectOf = (
thread: OrchestrationV2ThreadShell,
- Failure: typeof PullRequestLinkFailedError | typeof PullRequestUnlinkFailedError,
+ Failure:
+ | typeof PullRequestLinkFailedError
+ | typeof PullRequestUnlinkFailedError
+ | typeof PullRequestForgeError,
) =>
projects.getShell(thread.projectId).pipe(
Effect.map(Option.getOrUndefined),
@@ -199,18 +317,20 @@ const make = Effect.gen(function* () {
// The domain service owns the registration span.
const setWatching = Effect.fnUntraced(function* (
- input: PullRequestTargetInput,
+ input: PullRequestTargetInput & { readonly until?: PullRequestWatchUntil | undefined },
watching: boolean,
) {
const scope = yield* McpInvocationContext.requireMcpCapability("pull-requests");
const threadId = input.threadId ?? scope.thread?.threadId;
if (threadId === undefined) return yield* new PullRequestThreadRequiredError();
- return yield* watches.setWatching({ threadId, target: input, watching }).pipe(
- Effect.catchTags({
- PullRequestWatchThreadNotFoundError: (error) =>
- threadNotFound(engine, scope, error.threadId, error.message),
- }),
- );
+ return yield* watches
+ .setWatching({ threadId, target: input, watching, until: input.until })
+ .pipe(
+ Effect.catchTags({
+ PullRequestWatchThreadNotFoundError: (error) =>
+ threadNotFound(engine, scope, error.threadId, error.message),
+ }),
+ );
});
const locateAll = Effect.fn("PullRequestsToolkit.locateAll")(function* (
@@ -277,6 +397,297 @@ const make = Effect.gen(function* () {
handle: (params: P) => Effect.Effect,
) => McpToolAccess.writesThreads((params: P) => [params.threadId], handle);
+ const forgeFailure = (error: { readonly message: string }) =>
+ new PullRequestForgeError({ detail: error.message, cause: error });
+
+ // Layers below the target are pinned to the heads read here; the host refuses if any moved.
+ const stackMergeScope = Effect.fnUntraced(function* (
+ ref: PullRequestRef,
+ input: { readonly expectedHeadSha: string; readonly auto?: boolean | undefined },
+ ) {
+ if (input.auto === true)
+ return yield* new PullRequestForgeError({ detail: "A stack merge cannot wait with auto." });
+ const stack = yield* pullRequests
+ .stack(ref, { bypassCache: true })
+ .pipe(Effect.mapError(forgeFailure));
+ const end = stack?.layers.findIndex((layer) => layer.number === ref.number) ?? -1;
+ if (stack === null || end === -1)
+ return yield* new PullRequestForgeError({
+ detail: `PR #${ref.number} is not in a stack this host can merge. Merge it without stack.`,
+ });
+ const expectedStackHeads: Array<{ readonly number: number; readonly headSha: string }> = [];
+ for (const layer of stack.layers.slice(0, end + 1)) {
+ if (layer.state === "merged") continue;
+ const headSha = layer.number === ref.number ? input.expectedHeadSha : layer.headSha;
+ if (headSha === undefined)
+ return yield* new PullRequestForgeError({
+ detail: `The host did not report PR #${layer.number}'s head, so the stack cannot be pinned. Try again.`,
+ });
+ expectedStackHeads.push({ number: layer.number, headSha });
+ }
+ return { stackNumber: stack.number, expectedStackHeads };
+ });
+
+ /** A login or org/team, matched to the host's own reviewer id. */
+ const reviewerNamed = (ref: PullRequestRef, name: string) =>
+ pullRequests.reviewerCandidates({ ...ref, query: name }).pipe(
+ Effect.mapError(forgeFailure),
+ Effect.flatMap(({ candidates }) => {
+ const wanted = name.toLowerCase();
+ const match = candidates.find(
+ (candidate) =>
+ candidate.login.toLowerCase() === wanted || candidate.id.toLowerCase() === wanted,
+ );
+ return match === undefined
+ ? Effect.fail(
+ new PullRequestForgeError({
+ detail: `No reviewer named ${name} can be requested on this PR.`,
+ }),
+ )
+ : Effect.succeed({ id: match.id, kind: match.kind });
+ }),
+ );
+
+ /** Line comments placed by the PR's diff, which says whether each line was added, removed, or kept. */
+ const reviewComments = Effect.fn("PullRequestsToolkit.reviewComments")(function* (
+ ref: PullRequestRef,
+ comments: ReadonlyArray,
+ ) {
+ const placed = new Map();
+ const unplaced = () => comments.filter((comment) => !placed.has(comment));
+ let cursor: string | undefined;
+ for (let page = 0; page < REVIEW_DIFF_PAGES && unplaced().length > 0; page += 1) {
+ const diff = yield* pullRequests
+ .diff({ ...ref, ...(cursor === undefined ? {} : { cursor }) })
+ .pipe(Effect.mapError(forgeFailure));
+ for (const comment of unplaced()) {
+ const side = comment.side ?? "new";
+ const position = reviewPositionInPatch(diff.patch, comment.path, comment.line, side);
+ const start =
+ comment.startLine === undefined
+ ? undefined
+ : reviewPositionInPatch(diff.patch, comment.path, comment.startLine, side);
+ if (position === null || start === null) continue;
+ placed.set(comment, {
+ path: comment.path,
+ position,
+ ...(start === undefined ? {} : { startPosition: start }),
+ body: comment.body,
+ });
+ }
+ if (diff.nextCursor === null) break;
+ cursor = diff.nextCursor;
+ }
+ const missing = unplaced()[0];
+ if (missing !== undefined) {
+ return yield* new PullRequestForgeError({
+ detail: `${missing.path} line ${missing.startLine ?? missing.line} (${missing.side ?? "new"} side) is not in this PR's diff. Comment on a changed line or one shown around it.`,
+ });
+ }
+ return comments.map((comment) => placed.get(comment)!);
+ });
+
+ /** The thread's checkout, its project, and the PR the input names (default: the branch's). */
+ const locate = Effect.fn("PullRequestsToolkit.locate")(function* (input: ThreadPullRequestInput) {
+ const thread = yield* requireThread(PullRequestForgeError, undefined);
+ const project = yield* projectOf(thread, PullRequestForgeError);
+ if (project === undefined) {
+ return yield* new PullRequestProjectNotFoundError({ repository: input.repository ?? "" });
+ }
+ // Status sync sets branchPullRequest later, so a PR this thread just opened counts too,
+ // unless it is another branch's.
+ const opened =
+ thread.branchPullRequest === null || thread.branchPullRequest === undefined
+ ? threadPullRequestsOf(thread).findLast(
+ (link) =>
+ link.source === "created" &&
+ (link.snapshot === null || link.snapshot.headBranch === thread.branch),
+ )
+ : undefined;
+ const branchPullRequest = thread.branchPullRequest ?? opened ?? null;
+ const branchRepository =
+ project.repositoryIdentity == null
+ ? undefined
+ : (sourceControlDefinitions.repositorySelector(project.repositoryIdentity) ?? undefined);
+ const named =
+ input.number !== undefined
+ ? { number: input.number, repository: input.repository ?? branchRepository }
+ : branchPullRequest === null
+ ? null
+ : { number: branchPullRequest.number, repository: branchPullRequest.repository };
+ if (named === null) return yield* new PullRequestBranchHasNoneError();
+ const target = yield* resolveTarget(named, project);
+ const ref: PullRequestRef = {
+ projectId: project.id,
+ host: target.host,
+ repository: target.repository,
+ number: target.number,
+ };
+ if (input.number === undefined && opened !== undefined && opened.snapshot === null) {
+ // Not synced yet, so only the host knows which branch it was opened from.
+ const summary = yield* pullRequests.summary(ref).pipe(Effect.mapError(forgeFailure));
+ if (summary.headBranch !== thread.branch) return yield* new PullRequestBranchHasNoneError();
+ }
+ return { thread, project, target, ref };
+ });
+
+ const identityOf = (target: ResolvedTarget) => ({
+ host: target.host,
+ repository: target.repository,
+ number: target.number,
+ url: target.url,
+ });
+
+ /** The thread's comments past its first page, when the host pages them. */
+ const restOfThread = Effect.fn("PullRequestsToolkit.restOfThread")(function* (
+ ref: PullRequestRef,
+ thread: PullRequestReviewThread,
+ ) {
+ const comments: Array = [];
+ let cursor = thread.nextCommentsCursor;
+ for (let page = 0; cursor !== undefined && page < THREAD_COMMENT_PAGES; page += 1) {
+ const read = yield* pullRequests
+ .threadComments({ ...ref, threadId: thread.id, cursor })
+ .pipe(Effect.option);
+ if (Option.isNone(read)) break;
+ comments.push(...read.value.comments);
+ cursor = read.value.nextCursor ?? undefined;
+ }
+ return { comments, moreComments: cursor !== undefined };
+ });
+
+ const readSections = Effect.fn("PullRequestsToolkit.readSections")(function* (
+ ref: PullRequestRef,
+ sections: ReadonlyArray,
+ includeResolved: boolean,
+ cursor: ReadCursor | undefined,
+ ) {
+ const wants = (section: PullRequestReadSection) => sections.includes(section);
+ const diffCursor = cursor !== undefined && "diff" in cursor ? cursor.diff : undefined;
+ const [detail, activity, diff] = yield* Effect.all(
+ [
+ // Agents pin merges to this headSha, so it must not come from a stale snapshot.
+ wants("summary") || wants("checks")
+ ? pullRequests.detail({ ...ref, allowStale: false }).pipe(Effect.asSome)
+ : Effect.succeedNone,
+ wants("conversation") ? pullRequests.activity(ref).pipe(Effect.asSome) : Effect.succeedNone,
+ wants("diff")
+ ? pullRequests
+ .diff({ ...ref, ...(diffCursor === undefined ? {} : { cursor: diffCursor }) })
+ .pipe(Effect.asSome)
+ : Effect.succeedNone,
+ ],
+ { concurrency: "unbounded" },
+ ).pipe(Effect.mapError(forgeFailure));
+ const page = Option.map(activity, (value) =>
+ conversationPage(
+ value,
+ cursor !== undefined && "threads" in cursor ? cursor : { threads: 0, comments: 0 },
+ includeResolved,
+ ),
+ );
+ const threadRests = Option.isSome(page)
+ ? yield* Effect.forEach(page.value.threads, (thread) => restOfThread(ref, thread), {
+ concurrency: 4,
+ })
+ : [];
+ const result: Omit = {
+ ...(Option.isSome(detail) && wants("summary")
+ ? {
+ summary: {
+ title: detail.value.title,
+ body: detail.value.body,
+ state: detail.value.state,
+ isDraft: detail.value.isDraft,
+ author: detail.value.author?.login ?? null,
+ headBranch: detail.value.headBranch,
+ baseBranch: detail.value.baseBranch,
+ headSha: detail.value.headSha ?? null,
+ mergeability: detail.value.mergeability,
+ behindBy: detail.value.behindBy ?? null,
+ autoMergeEnabled: detail.value.autoMergeEnabled ?? null,
+ additions: detail.value.additions,
+ deletions: detail.value.deletions,
+ changedFiles: detail.value.changedFiles,
+ labels: detail.value.labels.map((label) => label.name),
+ reviewers: detail.value.reviewers.map((reviewer) => reviewer.login),
+ },
+ }
+ : {}),
+ ...(Option.isSome(detail) && wants("checks") ? { checks: detail.value.checks } : {}),
+ ...(Option.isSome(activity) && Option.isSome(page)
+ ? {
+ conversation: {
+ comments: page.value.comments.map((comment) => ({
+ id: comment.id,
+ kind: comment.kind,
+ author: comment.author?.login ?? null,
+ body: comment.body,
+ createdAt: comment.createdAt,
+ path: comment.path,
+ reviewState: comment.reviewState,
+ })),
+ reviewThreads: page.value.threads.map((thread, index) => ({
+ id: thread.id,
+ path: thread.path,
+ line: thread.line,
+ isResolved: thread.isResolved,
+ isOutdated: thread.isOutdated,
+ comments: [...thread.comments, ...threadRests[index]!.comments].map((comment) => ({
+ author: comment.author?.login ?? null,
+ body: comment.body,
+ createdAt: comment.createdAt,
+ })),
+ moreComments: threadRests[index]!.moreComments,
+ })),
+ hiddenResolvedThreads: page.value.hiddenResolvedThreads,
+ truncated:
+ activity.value.commentsTruncated || activity.value.reviewThreadsTruncated === true,
+ nextCursor: page.value.next === null ? null : readCursors.encode(page.value.next),
+ },
+ }
+ : {}),
+ ...(Option.isSome(diff)
+ ? {
+ diff: {
+ patch: diff.value.patch,
+ truncated: diff.value.truncated,
+ nextCursor:
+ diff.value.nextCursor === null
+ ? null
+ : readCursors.encode({ diff: diff.value.nextCursor }),
+ },
+ }
+ : {}),
+ };
+ return result;
+ });
+
+ const linkToThread = Effect.fn("PullRequestsToolkit.linkToThread")(function* (
+ thread: OrchestrationV2ThreadShell,
+ target: ResolvedTarget,
+ ) {
+ if (
+ threadPullRequestsOf(thread).some(
+ (link) => link.source !== "stack-dismissed" && threadPullRequestKeysEqual(link, target),
+ )
+ ) {
+ return;
+ }
+ yield* engine
+ .dispatch({
+ type: "thread.pull-request.link",
+ commandId: yield* commandId("mcp-pr-create", thread.id),
+ threadId: thread.id,
+ host: target.host,
+ repository: target.repository,
+ number: target.number,
+ url: target.url,
+ source: "created",
+ })
+ .pipe(Effect.catchCause(dispatchFailure(PullRequestLinkFailedError)));
+ });
+
return {
link_pull_request: writesThread((input) =>
Effect.gen(function* () {
@@ -536,6 +947,274 @@ const make = Effect.gen(function* () {
};
}),
),
+ pull_request_read: McpToolAccess.reads((input) =>
+ Effect.gen(function* () {
+ const cursor =
+ input.cursor === undefined ? undefined : yield* readCursors.decode(input.cursor);
+ const { target, ref } = yield* locate(input);
+ // A cursor continues the one section it came from, with that read's options.
+ const sections: ReadonlyArray