perf(client): reduce remote request and message sync overhead (#11029)

This commit is contained in:
Bilal Bakr authored and GitHub committed 2026-09-11 13:20:54 -07:00
1 parent 7bd7f99e6c
commit 6e8931d756
12 files changed
+296 -47

No files matched your search

@@ -11,7 +11,7 @@ import * as Effect from "effect/Effect";
import { environmentEndpointUrl } from "../environment/endpoint.ts";
import {
executeEnvironmentHttpRequest,
makeEnvironmentHttpApiClient,
makeEnvironmentHttpApiGroupClient,
type RemoteEnvironmentRequestError,
} from "../rpc/http.ts";
@@ -93,11 +93,11 @@ export const exchangeRemoteDpopAccessToken = Effect.fn(
readonly dpopProof: string;
readonly timeoutMs?: number;
}) {
const client = yield* makeEnvironmentHttpApiClient(input.httpBaseUrl);
const client = yield* makeEnvironmentHttpApiGroupClient(input.httpBaseUrl, "auth");
const response = yield* executeEnvironmentHttpRequest(
environmentEndpointUrl(input.httpBaseUrl, "/oauth/token"),
input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
client.auth.token({
client.token({
headers: { dpop: input.dpopProof },
payload: {
grant_type: AuthTokenExchangeGrantType,
@@ -121,11 +121,11 @@ export const bootstrapRemoteBearerSession = Effect.fn(
readonly clientMetadata?: AuthClientPresentationMetadata;
readonly timeoutMs?: number;
}) {
const client = yield* makeEnvironmentHttpApiClient(input.httpBaseUrl);
const client = yield* makeEnvironmentHttpApiGroupClient(input.httpBaseUrl, "auth");
return yield* executeEnvironmentHttpRequest(
environmentEndpointUrl(input.httpBaseUrl, "/oauth/token"),
input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
client.auth.token({
client.token({
headers: {},
payload: {
grant_type: AuthTokenExchangeGrantType,
@@ -146,11 +146,11 @@ export const fetchRemoteSessionState = Effect.fn(
readonly bearerToken: string;
readonly timeoutMs?: number;
}) {
const client = yield* makeEnvironmentHttpApiClient(input.httpBaseUrl);
const client = yield* makeEnvironmentHttpApiGroupClient(input.httpBaseUrl, "auth");
return yield* executeEnvironmentHttpRequest(
environmentEndpointUrl(input.httpBaseUrl, "/api/auth/session"),
input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
client.auth.session({
client.session({
headers: {
authorization: `Bearer ${input.bearerToken}`,
},
@@ -166,11 +166,11 @@ export const fetchRemoteDpopSessionState = Effect.fn(
readonly dpopProof: string;
readonly timeoutMs?: number;
}) {
const client = yield* makeEnvironmentHttpApiClient(input.httpBaseUrl);
const client = yield* makeEnvironmentHttpApiGroupClient(input.httpBaseUrl, "auth");
return yield* executeEnvironmentHttpRequest(
environmentEndpointUrl(input.httpBaseUrl, "/api/auth/session"),
input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
client.auth.session({
client.session({
headers: {
authorization: `DPoP ${input.accessToken}`,
dpop: input.dpopProof,
@@ -186,11 +186,11 @@ export const issueRemoteWebSocketTicket = Effect.fn(
readonly bearerToken: string;
readonly timeoutMs?: number;
}) {
const client = yield* makeEnvironmentHttpApiClient(input.httpBaseUrl);
const client = yield* makeEnvironmentHttpApiGroupClient(input.httpBaseUrl, "auth");
return yield* executeEnvironmentHttpRequest(
environmentEndpointUrl(input.httpBaseUrl, "/api/auth/websocket-ticket"),
input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
client.auth.webSocketTicket({
client.webSocketTicket({
headers: {
authorization: `Bearer ${input.bearerToken}`,
},
@@ -206,11 +206,11 @@ export const issueRemoteDpopWebSocketTicket = Effect.fn(
readonly dpopProof: string;
readonly timeoutMs?: number;
}) {
const client = yield* makeEnvironmentHttpApiClient(input.httpBaseUrl);
const client = yield* makeEnvironmentHttpApiGroupClient(input.httpBaseUrl, "auth");
return yield* executeEnvironmentHttpRequest(
environmentEndpointUrl(input.httpBaseUrl, "/api/auth/websocket-ticket"),
input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
client.auth.webSocketTicket({
client.webSocketTicket({
headers: {
authorization: `DPoP ${input.accessToken}`,
dpop: input.dpopProof,
@@ -1,17 +1,17 @@
import * as Effect from "effect/Effect";
import { environmentEndpointUrl } from "./endpoint.ts";
import { executeEnvironmentHttpRequest, makeEnvironmentHttpApiClient } from "../rpc/http.ts";
import { executeEnvironmentHttpRequest, makeEnvironmentHttpApiGroupClient } from "../rpc/http.ts";
const DEFAULT_REMOTE_REQUEST_TIMEOUT_MS = 10_000;
export const fetchRemoteEnvironmentDescriptor = Effect.fn(
"clientRuntime.environment.fetchRemoteEnvironmentDescriptor",
)(function* (input: { readonly httpBaseUrl: string; readonly timeoutMs?: number }) {
const client = yield* makeEnvironmentHttpApiClient(input.httpBaseUrl);
const client = yield* makeEnvironmentHttpApiGroupClient(input.httpBaseUrl, "metadata");
return yield* executeEnvironmentHttpRequest(
environmentEndpointUrl(input.httpBaseUrl, "/.well-known/t3/environment"),
input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
client.metadata.descriptor(),
client.descriptor(),
);
});
@@ -0,0 +1,165 @@
import {
EnvironmentId,
EventId,
MessageId,
ProjectId,
ProviderInstanceId,
ThreadId,
type OrchestrationEvent,
type OrchestrationThread,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
import { bench, describe } from "vite-plus/test";
import { issueRemoteWebSocketTicket } from "./authorization/remote.ts";
import { PrimaryConnectionTarget } from "./connection/model.ts";
import { fetchRemoteEnvironmentDescriptor } from "./environment/descriptor.ts";
import type { RemoteEnvironmentRequestError } from "./rpc/http.ts";
import { fetchEnvironmentThreadSnapshot } from "./state/threadSnapshotHttp.ts";
import { applyThreadDetailEvent } from "./state/threadReducer.ts";
const timestamp = "2026-09-01T00:00:00.000Z";
const thread: OrchestrationThread = {
id: ThreadId.make("thread-1"),
projectId: ProjectId.make("project-1"),
title: "Remote thread",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: timestamp,
updatedAt: timestamp,
archivedAt: null,
settledOverride: null,
settledAt: null,
deletedAt: null,
pullRequests: [],
messages: Array.from({ length: 100 }, (_, index) => ({
id: MessageId.make(`message-${index}`),
role: "assistant",
text: "Message text. ".repeat(40),
turnId: null,
streaming: false,
createdAt: timestamp,
updatedAt: timestamp,
})),
proposedPlans: [],
activities: [],
checkpoints: [],
session: null,
};
const target = new PrimaryConnectionTarget({
environmentId: EnvironmentId.make("remote-1"),
label: "Remote",
httpBaseUrl: "https://remote.example.test",
wsBaseUrl: "wss://remote.example.test/ws",
});
const responses = {
"/.well-known/t3/environment": {
environmentId: target.environmentId,
label: target.label,
platform: { os: "linux", arch: "x64" },
serverVersion: "0.0.0-test",
capabilities: { repositoryIdentity: true },
},
"/api/auth/websocket-ticket": { ticket: "test-ticket", expiresAt: timestamp },
"/api/orchestration/threads/thread-1": { snapshotSequence: 1, thread },
};
const httpClient = HttpClient.make((request) =>
Effect.sync(() => {
const path = new URL(request.url).pathname as keyof typeof responses;
return HttpClientResponse.fromWeb(request, Response.json(responses[path]));
}),
);
const requests: Record<
string,
Effect.Effect<unknown, RemoteEnvironmentRequestError, HttpClient.HttpClient>
> = {
"read remote connection descriptor": fetchRemoteEnvironmentDescriptor({
httpBaseUrl: target.httpBaseUrl,
}),
"issue remote WebSocket ticket": issueRemoteWebSocketTicket({
httpBaseUrl: target.httpBaseUrl,
bearerToken: "test-token",
}),
"load remote snapshot with 100 messages": fetchEnvironmentThreadSnapshot({
prepared: {
environmentId: target.environmentId,
label: target.label,
httpBaseUrl: target.httpBaseUrl,
socketUrl: target.wsBaseUrl,
httpAuthorization: null,
target,
},
threadId: thread.id,
signer: Option.none(),
}),
};
describe("remote HTTP processing with an in-memory transport", () => {
for (const [name, request] of Object.entries(requests)) {
bench(
name,
async () => {
await Effect.runPromise(
request.pipe(Effect.provideService(HttpClient.HttpClient, httpClient)),
);
},
{ warmupTime: 1_000, time: 1_500 },
);
}
});
const delta: OrchestrationEvent = {
eventId: EventId.make("delta"),
sequence: 2,
aggregateKind: "thread",
aggregateId: thread.id,
occurredAt: timestamp,
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
type: "thread.message-sent",
payload: {
threadId: thread.id,
messageId: MessageId.make("message-99"),
role: "assistant",
text: " next",
turnId: null,
streaming: true,
createdAt: timestamp,
updatedAt: timestamp,
},
};
describe("remote message replay", () => {
for (const count of [100, 1_000]) {
const loaded = {
...thread,
messages: Array.from({ length: count }, (_, index) => ({
...thread.messages[0]!,
id: MessageId.make(`message-${index}`),
})),
};
const event = {
...delta,
payload: { ...delta.payload, messageId: loaded.messages.at(-1)!.id },
};
bench(
`apply 200 text deltas to ${count} loaded messages`,
() => {
let current: OrchestrationThread = loaded;
for (let index = 0; index < 200; index += 1) {
const result = applyThreadDetailEvent(current, event);
if (result.kind === "updated") current = result.thread;
}
},
{ warmupTime: 1_000, time: 1_500 },
);
}
});
+14
View File
@@ -99,6 +99,20 @@ export const makeEnvironmentHttpApiClient = (httpBaseUrl: string) =>
baseUrl: remoteApiBaseUrl(httpBaseUrl),
});
export const makeEnvironmentHttpApiGroupClient = <
Group extends keyof typeof EnvironmentHttpApi.groups,
>(
httpBaseUrl: string,
group: Group,
) =>
Effect.flatMap(HttpClient.HttpClient, (httpClient) =>
HttpApiClient.group(EnvironmentHttpApi, {
httpClient,
group,
baseUrl: remoteApiBaseUrl(httpBaseUrl),
}),
);
/** Contract-derived request URLs for authentication proofs, tracing, and structured errors. */
export const makeEnvironmentHttpApiUrlBuilder = (httpBaseUrl: string) =>
HttpApiClient.urlBuilder(EnvironmentHttpApi, {
@@ -215,6 +215,17 @@ const LOADERS: ReadonlyArray<{
];
describe("authenticated environment HTTP requests", () => {
it.effect.each(LOADERS)("rejects an invalid $name response", (loader) =>
Effect.gen(function* () {
const harness = makeHarness(() => Response.json({}));
const result = yield* loader
.load(harness.input)
.pipe(Effect.provide(harness.httpLayer), Effect.asVoid, Effect.flip);
expect(result._tag).toBe("RemoteEnvironmentAuthInvalidJsonError");
expect(harness.calls).toHaveLength(1);
}),
);
it.effect.each(LOADERS)("uses current relay authorization and endpoint for $name", (loader) =>
Effect.gen(function* () {
const harness = makeHarness(() => Response.json(loader.response));
@@ -1,14 +1,14 @@
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Result from "effect/Result";
import { FetchHttpClient, type HttpClient, type HttpMethod } from "effect/unstable/http";
import { FetchHttpClient, type HttpMethod } from "effect/unstable/http";
import type { RemoteEnvironmentAuthorization } from "../authorization/service.ts";
import type { PreparedConnection, PreparedHttpAuthorization } from "../connection/model.ts";
import type { ManagedRelayDpopSigner } from "../relay/managedRelay.ts";
import {
executeEnvironmentHttpRequest,
makeEnvironmentHttpApiClient,
makeEnvironmentHttpApiGroupClient,
RemoteEnvironmentAuthFetchError,
RemoteEnvironmentAuthTimeoutError,
type RemoteEnvironmentRequestError,
@@ -86,20 +86,30 @@ const buildEnvironmentAuthHeaders = (
*/
export const executeAuthenticatedEnvironmentHttpRequest = Effect.fn(
"clientRuntime.state.executeAuthenticatedEnvironmentHttpRequest",
)(function* <A, E, R>(input: {
)(function* <
Group extends Parameters<typeof makeEnvironmentHttpApiGroupClient>[1],
A,
E,
R,
>(input: {
readonly prepared: PreparedConnection;
readonly signer: Option.Option<ManagedRelayDpopSigner["Service"]>;
readonly remoteAuthorization?: Option.Option<RemoteEnvironmentAuthorization["Service"]>;
readonly method: HttpMethod.HttpMethod;
readonly url: (httpBaseUrl: string) => string;
readonly timeoutMs: number;
readonly group: Group;
readonly request: (input: {
readonly client: Effect.Success<ReturnType<typeof makeEnvironmentHttpApiClient>>;
readonly client: Effect.Success<ReturnType<typeof makeEnvironmentHttpApiGroupClient<Group>>>;
readonly headers: EnvironmentHttpAuthHeaders;
}) => Effect.Effect<A, E, R>;
/** Some endpoints report rejected credentials in a successful response. */
readonly isUnauthorizedResponse?: (response: NoInfer<A>) => boolean;
}): Effect.fn.Return<A, RemoteEnvironmentRequestError, HttpClient.HttpClient | R> {
}): Effect.fn.Return<
A,
RemoteEnvironmentRequestError,
Effect.Services<ReturnType<typeof makeEnvironmentHttpApiGroupClient<Group>>> | R
> {
let httpBaseUrl = input.prepared.httpBaseUrl;
return yield* Effect.gen(function* () {
let rejectedAccessToken: string | undefined;
@@ -132,7 +142,7 @@ export const executeAuthenticatedEnvironmentHttpRequest = Effect.fn(
}
const requestUrl = input.url(httpBaseUrl);
const client = yield* makeEnvironmentHttpApiClient(httpBaseUrl);
const client = yield* makeEnvironmentHttpApiGroupClient(httpBaseUrl, input.group);
const headers = yield* buildEnvironmentAuthHeaders(
authorization,
input.method,
@@ -50,10 +50,11 @@ export const fetchEnvironmentPullRequestDiff = Effect.fn(
}) {
return yield* executeAuthenticatedEnvironmentHttpRequest({
...input,
group: "pullRequests",
method: "POST",
url: (httpBaseUrl) => makeEnvironmentHttpApiUrlBuilder(httpBaseUrl).pullRequests.diff(),
timeoutMs: input.timeoutMs ?? DEFAULT_PULL_REQUEST_DIFF_TIMEOUT_MS,
request: ({ client, headers }) => client.pullRequests.diff({ payload: input.diff, headers }),
request: ({ client, headers }) => client.diff({ payload: input.diff, headers }),
}).pipe(
Effect.mapError((error) =>
error._tag === "EnvironmentAuthInvalidError" && error.reason === "invalid_credential"
+2 -1
View File
@@ -49,10 +49,11 @@ export const fetchEnvironmentSessionState = Effect.fn(
}) {
return yield* executeAuthenticatedEnvironmentHttpRequest({
...input,
group: "auth",
method: "GET",
url: (httpBaseUrl) => environmentEndpointUrl(httpBaseUrl, "/api/auth/session"),
timeoutMs: input.timeoutMs ?? DEFAULT_SESSION_STATE_TIMEOUT_MS,
request: ({ client, headers }) => client.auth.session({ headers }),
request: ({ client, headers }) => client.session({ headers }),
// This endpoint returns 200 with authenticated:false for expired credentials.
isUnauthorizedResponse: (response) => !response.authenticated,
});
@@ -32,10 +32,11 @@ export const fetchEnvironmentShellSnapshot = Effect.fn(
}) {
return yield* executeAuthenticatedEnvironmentHttpRequest({
...input,
group: "orchestration",
method: "GET",
url: (httpBaseUrl) => environmentEndpointUrl(httpBaseUrl, "/api/orchestration/shell"),
timeoutMs: input.timeoutMs ?? DEFAULT_SHELL_SNAPSHOT_TIMEOUT_MS,
request: ({ client, headers }) => client.orchestration.shellSnapshot({ headers }),
request: ({ client, headers }) => client.shellSnapshot({ headers }),
});
});
@@ -526,6 +526,54 @@ describe("applyThreadDetailEvent", () => {
});
describe("thread.message-sent", () => {
it.each([
["first", ["first+", "middle", "last"]],
["middle", ["first", "middle+", "last"]],
["last", ["first", "middle", "last+"]],
["new", ["first", "middle", "last", "+"]],
] as const)("applies a delta to %s without changing other messages", (id, texts) => {
const messages = Object.freeze(
["first", "middle", "last"].map((name) =>
Object.freeze({
id: MessageId.make(name),
role: "assistant" as const,
text: name,
turnId: null,
streaming: false,
createdAt: baseThread.createdAt,
updatedAt: baseThread.updatedAt,
}),
),
);
const result = applyThreadDetailEvent(
{ ...baseThread, messages },
{
...baseEventFields,
sequence: 6,
occurredAt: baseThread.updatedAt,
aggregateKind: "thread",
aggregateId: baseThread.id,
type: "thread.message-sent",
payload: {
threadId: baseThread.id,
messageId: MessageId.make(id),
role: "assistant",
text: "+",
turnId: null,
streaming: true,
createdAt: baseThread.createdAt,
updatedAt: baseThread.updatedAt,
},
},
);
expect(result.kind).toBe("updated");
if (result.kind !== "updated") return;
expect(result.thread.messages.map((message) => message.text)).toEqual(texts);
for (const [index, message] of messages.entries()) {
if (message.id !== id) expect(result.thread.messages[index]).toBe(message);
}
});
it("appends a new message", () => {
const result = applyThreadDetailEvent(baseThread, {
...baseEventFields,
@@ -386,27 +386,24 @@ export function applyThreadDetailEvent(
updatedAt: event.payload.updatedAt,
};
const existingMessage = thread.messages.find((entry) => entry.id === message.id);
const messages = existingMessage
? Arr.map(thread.messages, (entry) =>
entry.id !== message.id
? entry
: {
...entry,
text: message.streaming
? `${entry.text}${message.text}`
: message.text.length > 0
? message.text
: entry.text,
streaming: message.streaming,
...(message.turnId !== undefined ? { turnId: message.turnId } : {}),
...(message.streaming ? {} : { updatedAt: message.updatedAt }),
...(message.attachments !== undefined
? { attachments: message.attachments }
: {}),
},
)
: Arr.append(thread.messages, message);
let found = false;
const messages = thread.messages.map((entry) => {
if (entry.id !== message.id) return entry;
found = true;
return {
...entry,
text: message.streaming
? `${entry.text}${message.text}`
: message.text.length > 0
? message.text
: entry.text,
streaming: message.streaming,
...(message.turnId !== undefined ? { turnId: message.turnId } : {}),
...(message.streaming ? {} : { updatedAt: message.updatedAt }),
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
};
});
if (!found) messages.push(message);
// Update latestTurn for assistant messages bound to a turn. A completed
// assistant message only settles the turn once the session is no longer
// running it — providers may emit several assistant messages per turn
@@ -45,12 +45,13 @@ export const fetchEnvironmentThreadSnapshot = Effect.fn(
}) {
return yield* executeAuthenticatedEnvironmentHttpRequest({
...input,
group: "orchestration",
method: "GET",
url: (httpBaseUrl) =>
environmentEndpointUrl(httpBaseUrl, `/api/orchestration/threads/${input.threadId}`),
timeoutMs: input.timeoutMs ?? DEFAULT_THREAD_SNAPSHOT_TIMEOUT_MS,
request: ({ client, headers }) =>
client.orchestration.threadSnapshot({
client.threadSnapshot({
params: { threadId: input.threadId },
payload: {
...(input.window !== undefined ? { turnLimit: input.window.turnLimit } : {}),