@devries-cameron20 / t3code Mirror · read-only / commits / b9522c845b
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 04:30 UTC

fix(client): a big server config on a slow link no longer drops the connection in a loop (#23758)

Co-authored-by: PR Batch Tester <agent@local.test> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: maria-rcks <maria@kuuro.net>

shivam committed Nov 5, 2026 at 06:54 UTC b9522c845b06cb8c852c28e9fa747c6335e9f6b3
5 files changed +152 -5
apps/server/src/ws.ts
+19 -1
@@ -262,6 +262,10 @@ import * as SessionStore from "./auth/SessionStore.ts";
262 import { failEnvironmentAuthInvalid, failEnvironmentInternal } from "./auth/http.ts";
263 import { isNetworkPath } from "@t3tools/shared/path";
264 import * as RelayClient from "@t3tools/shared/relayClient";
265 +import {
266 + SOCKET_FRAME_PARTS_QUERY_PARAM,
267 + splitLargeSocketFrames,
268 +} from "@t3tools/shared/socketFrameParts";
269 import { isTelemetryIdHash } from "@t3tools/shared/telemetryId";
270 import {
271 sameUsageLimitCommandCoverage,
@@ -3533,11 +3537,25 @@ export const layer = Layer.unwrap(
3537 ),
3538 ),
3539 );
3540 + const framedRpcWebSocketHttpEffect = url.value.searchParams.has(
3541 + SOCKET_FRAME_PARTS_QUERY_PARAM,
3542 + )
3543 + ? rpcWebSocketHttpEffect.pipe(
3544 + Effect.provideService(
3545 + HttpServerRequest.HttpServerRequest,
3546 + // The RPC server upgrades the request itself, so its socket is
3547 + // wrapped through the request it reads.
3548 + Object.create(request, {
3549 + upgrade: { value: Effect.map(request.upgrade, splitLargeSocketFrames) },
3550 + }),
3551 + ),
3552 + )
3553 + : rpcWebSocketHttpEffect;
3554 return yield* Effect.acquireUseRelease(
3555 sessions.markConnected(session.sessionId),
3556 () =>
3557 Effect.raceFirst(
3540 - rpcWebSocketHttpEffect,
3558 + framedRpcWebSocketHttpEffect,
3559 sessions.awaitInvalidation(session.sessionId, session.proofKeyThumbprint).pipe(
3560 Effect.as(HttpServerResponse.empty()),
3561 Effect.catchTags({
packages/client-runtime/src/rpc/session.test.ts
+33 -1
@@ -8,6 +8,7 @@ import {
8 WS_METHODS,
9 UsageLimitSourceId,
10 } from "@t3tools/contracts";
11 +import { splitSocketFrame } from "@t3tools/shared/socketFrameParts";
12 import { describe, expect, it } from "@effect/vitest";
13 import * as Cause from "effect/Cause";
14 import * as Deferred from "effect/Deferred";
@@ -21,6 +22,7 @@ import * as Schema from "effect/Schema";
22 import * as Stream from "effect/Stream";
23 import * as SubscriptionRef from "effect/SubscriptionRef";
24 import * as Socket from "effect/socket/Socket";
25 +import * as TestClock from "effect/testing/TestClock";
26
27 import {
28 AVAILABLE_CONNECTION_STATE,
@@ -275,6 +277,36 @@ const publishConfigEvents = Effect.fn("TestRpcSessionFactory.publishConfigEvents
277 });
278
279 describe("RpcSessionFactory", () => {
280 + it.effect("connects while a large config snapshot downloads at 4000 bytes per second", () =>
281 + Effect.gen(function* () {
282 + const { factory, sockets } = yield* makeFactory();
283 + const session = yield* factory.connect(PREPARED);
284 + const readyFiber = yield* Effect.forkChild(session.ready);
285 + const socket = yield* awaitSocket(sockets);
286 + socket.open();
287 + const request = yield* awaitRequest(socket);
288 + // Multi-byte text, so parts must be sized in UTF-8 bytes and never split a surrogate pair.
289 + const config = { ...SERVER_CONFIG, cwd: "/" + "é€😀x".repeat(32 * 1024) };
290 + const frame = encodeJson({
291 + _tag: "Chunk",
292 + requestId: request.id,
293 + values: [{ version: 1, type: "snapshot", config: encodeServerConfig(config) }],
294 + });
295 + const parts = new URL(socket.url).searchParams.has("frameParts")
296 + ? splitSocketFrame(frame)
297 + : [frame];
298 +
299 + for (const part of parts) {
300 + const bytes = new TextEncoder().encode(part);
301 + yield* TestClock.adjust((bytes.length / 4000) * 1000);
302 + socket.serverMessage(new TextDecoder().decode(bytes));
303 + }
304 + yield* Fiber.join(readyFiber);
305 +
306 + expect(yield* session.initialConfig).toEqual(config);
307 + }),
308 + );
309 +
310 it.effect("owns one scoped websocket attempt and exposes readiness and closure", () =>
311 Effect.gen(function* () {
312 const { factory, sockets } = yield* makeFactory();
@@ -282,7 +314,7 @@ describe("RpcSessionFactory", () => {
314 const readyFiber = yield* Effect.forkChild(session.ready);
315 const socket = yield* awaitSocket(sockets);
316
285 - expect(socket.url).toBe(PREPARED.socketUrl);
317 + expect(socket.url).toBe(`${PREPARED.socketUrl}&frameParts=1`);
318 socket.open();
319 yield* completeInitialConfig(socket);
320 yield* Fiber.join(readyFiber);
packages/client-runtime/src/rpc/session.ts
+15 -3
@@ -4,6 +4,10 @@ import {
4 WsSubscribeServerConfigRpc,
5 WS_METHODS,
6 } from "@t3tools/contracts";
7 +import {
8 + joinSocketFrameParts,
9 + SOCKET_FRAME_PARTS_QUERY_PARAM,
10 +} from "@t3tools/shared/socketFrameParts";
11 import * as Cause from "effect/Cause";
12 import * as Context from "effect/Context";
13 import * as Deferred from "effect/Deferred";
@@ -223,9 +227,17 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* (
227 });
228 return socket;
229 };
226 - const layerSocket = Socket.layerWebSocket(connection.socketUrl, {
227 - openTimeout: SOCKET_OPEN_TIMEOUT,
228 - }).pipe(
230 + const socketUrl = new URL(connection.socketUrl);
231 + socketUrl.searchParams.set(SOCKET_FRAME_PARTS_QUERY_PARAM, "1");
232 + const layerSocket = Layer.effect(
233 + Socket.Socket,
234 + Effect.map(Effect.service(Socket.Socket), joinSocketFrameParts),
235 + ).pipe(
236 + Layer.provide(
237 + Socket.layerWebSocket(socketUrl.toString(), {
238 + openTimeout: SOCKET_OPEN_TIMEOUT,
239 + }),
240 + ),
241 Layer.provide(Layer.succeed(Socket.WebSocketConstructor, countingWebSocketConstructor)),
242 );
243 const layerProtocol = Layer.effect(
packages/shared/package.json
+4
@@ -19,6 +19,10 @@
19 "types": "./src/delimitedPreview.ts",
20 "import": "./src/delimitedPreview.ts"
21 },
22 + "./socketFrameParts": {
23 + "types": "./src/socketFrameParts.ts",
24 + "import": "./src/socketFrameParts.ts"
25 + },
26 "./composerPullRequestMatches": {
27 "types": "./src/composerPullRequestMatches.ts",
28 "import": "./src/composerPullRequestMatches.ts"
packages/shared/src/socketFrameParts.ts new
+81
@@ -0,0 +1,81 @@
1 +import * as Arr from "effect/Array";
2 +import * as Effect from "effect/Effect";
3 +import * as Socket from "effect/socket/Socket";
4 +
5 +// Old clients omit this; old servers ignore it.
6 +export const SOCKET_FRAME_PARTS_QUERY_PARAM = "frameParts";
7 +
8 +// WebSocket messages arrive whole. At 4,000 bytes/s each part takes about
9 +// 12 seconds, leaving margin before the client's 15-second liveness timeout.
10 +const SOCKET_FRAME_PART_BYTES = 48 * 1024;
11 +
12 +// No JSON message starts with a record separator. It marks every part but the last.
13 +const PART_PREFIX = "\u001e";
14 +
15 +// The RPC client only counts frames that decode to messages as liveness, and
16 +// ignores pongs, so each held-back part reads to it as one.
17 +const PART_RECEIVED_FRAME = '{"_tag":"Pong"}';
18 +
19 +/** Splits on the UTF-8 size the frame has on the wire, never inside a surrogate pair. */
20 +export function splitSocketFrame(
21 + frame: string,
22 + partBytes = SOCKET_FRAME_PART_BYTES,
23 +): Arr.NonEmptyReadonlyArray<string> {
24 + // UTF-8 spends at most 3 bytes on a UTF-16 code unit.
25 + if (frame.length * 3 <= partBytes) return [frame];
26 + const parts: Array<string> = [];
27 + let start = 0;
28 + let bytes = PART_PREFIX.length;
29 + for (let index = 0; index < frame.length;) {
30 + const code = frame.charCodeAt(index);
31 + const pair = code >= 0xd800 && code <= 0xdbff && index + 1 < frame.length;
32 + const size = pair ? 4 : code < 0x80 ? 1 : code < 0x800 ? 2 : 3;
33 + if (bytes + size > partBytes) {
34 + parts.push(PART_PREFIX + frame.slice(start, index));
35 + start = index;
36 + bytes = PART_PREFIX.length;
37 + }
38 + bytes += size;
39 + index += pair ? 2 : 1;
40 + }
41 + return Arr.append(parts, frame.slice(start));
42 +}
43 +
44 +/** Server side: sends string frames longer than one part as consecutive parts. */
45 +export function splitLargeSocketFrames(socket: Socket.Socket): Socket.Socket {
46 + const split = (chunk: string | Uint8Array): Arr.NonEmptyReadonlyArray<string | Uint8Array> =>
47 + typeof chunk === "string" ? splitSocketFrame(chunk) : [chunk];
48 + return Socket.make({
49 + reader: socket.reader,
50 + writer: Effect.map(socket.writer, (writer) => ({
51 + write: (chunk) =>
52 + typeof chunk === "string" ? writer.writeAll(splitSocketFrame(chunk)) : writer.write(chunk),
53 + writeAll: (chunks) => writer.writeAll(Arr.flatMap(chunks, split)),
54 + })),
55 + });
56 +}
57 +
58 +/** Client side: joins parts back into whole frames. */
59 +export function joinSocketFrameParts(socket: Socket.Socket): Socket.Socket {
60 + return Socket.make({
61 + reader: Effect.map(socket.reader, (reader) => {
62 + let pending = "";
63 + const join = (frame: string | Uint8Array) => {
64 + if (typeof frame !== "string") return frame;
65 + if (frame.startsWith(PART_PREFIX)) {
66 + pending += frame.slice(PART_PREFIX.length);
67 + return PART_RECEIVED_FRAME;
68 + }
69 + if (pending === "") return frame;
70 + const whole = pending + frame;
71 + pending = "";
72 + return whole;
73 + };
74 + return {
75 + upgrade: reader.upgrade,
76 + pull: Effect.map(reader.pull, Arr.map(join)),
77 + };
78 + }),
79 + writer: socket.writer,
80 + });
81 +}