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, 14:30 UTC
perf: reduce remote reconnect and command delays (#25754)
Co-authored-by: Julius Marminge <julius0216@outlook.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Bilal Bakr committed
Oct 28, 2026 at 07:43 UTC
9910c0e87469a44a18ce5c381533fc0a06c81ef1
7 files changed
+286
-70
apps/server/src/ws.test.ts
+68
@@ -303,6 +303,74 @@ it.live.each(["thread", "shell"] as const)(
303
}).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)),
304
);
305
306
+it.effect("coalesces streaming replay before synchronization and the live tail", () =>
307
+ Effect.gen(function* () {
308
+ const store = yield* OrchestrationEventStore.OrchestrationEventStore;
309
+ const sql = yield* SqlClient.SqlClient;
310
+ const threadId = ThreadId.make("thread:streaming-replay");
311
+ const now = "2026-10-27T00:00:00.000Z";
312
+ const insert = (version: number, text: string, streaming: boolean) => sql<{
313
+ sequence: number;
314
+ }>`
315
+ INSERT INTO orchestration_events (
316
+ event_id, aggregate_kind, stream_id, stream_version, event_type,
317
+ occurred_at, actor_kind, payload_json, metadata_json, application_event_version
318
+ ) VALUES (
319
+ ${`streaming-replay:${version}`}, 'thread', ${threadId}, ${version}, 'message.updated',
320
+ ${now}, 'server', ${JSON.stringify({
321
+ createdBy: "agent",
322
+ creationSource: "web",
323
+ id: "message:streaming-replay",
324
+ threadId,
325
+ runId: null,
326
+ nodeId: null,
327
+ role: "assistant",
328
+ text,
329
+ attachments: [],
330
+ streaming,
331
+ createdAt: now,
332
+ updatedAt: now,
333
+ })}, '{}', 2
334
+ ) RETURNING sequence
335
+ `;
336
+ yield* insert(0, "H", true);
337
+ yield* insert(1, "He", true);
338
+ const [latest] = yield* insert(2, "Hello", true);
339
+ const [completed] = yield* insert(3, "Hello!", false);
340
+ const items = yield* subscribeOrchestrationV2Thread({
341
+ threadId,
342
+ afterSequence: 0,
343
+ requestCompletionMarker: true,
344
+ }).pipe(
345
+ Effect.flatMap(Stream.runCollect),
346
+ Effect.provideService(ThreadManagement.ThreadManagementService, {
347
+ ensureLegacyTranscript: () => Effect.void,
348
+ streamStoredEventsFrom: () =>
349
+ Stream.unwrap(
350
+ insert(4, "Next", false).pipe(
351
+ Effect.map(() =>
352
+ store.readAgentEvents({ threadId, afterSequence: completed!.sequence }),
353
+ ),
354
+ ),
355
+ ),
356
+ } as unknown as ThreadManagement.ThreadManagementService["Service"]),
357
+ );
358
+ assert.deepEqual(
359
+ items.map((item) =>
360
+ item.kind === "event"
361
+ ? [item.sequence, item.event.type === "message.updated" ? item.event.payload.text : null]
362
+ : [item.kind],
363
+ ),
364
+ [
365
+ [latest!.sequence, "Hello"],
366
+ [completed!.sequence, "Hello!"],
367
+ ["synchronized"],
368
+ [completed!.sequence + 1, "Next"],
369
+ ],
370
+ );
371
+ }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)),
372
+);
373
+
374
it.effect("shell snapshots omit idle children and older settled threads only on request", () =>
375
Effect.gen(function* () {
376
const shell = (
apps/server/src/ws.ts
+7
-2
@@ -142,7 +142,10 @@ import {
142
type ShellApplicationEvent,
143
} from "./orchestration-v2/ShellStream.ts";
144
import { ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION } from "./orchestration-v2/ProjectionStore.ts";
145
-import { coalesceThreadLiveStream } from "./orchestration-v2/ThreadLiveEventCoalescer.ts";
145
+import {
146
+ coalesceLiveUpdatedEvents,
147
+ coalesceThreadLiveStream,
148
+} from "./orchestration-v2/ThreadLiveEventCoalescer.ts";
149
import {
150
buildBoundedThreadStreamSnapshot,
151
decideThreadResume,
@@ -947,7 +950,9 @@ export const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subs
950
// Retained creation events may describe deleted threads; replace replay only if a snapshot exists.
951
if (shell !== null) return yield* snapshotThenLive();
952
}
950
- const replay = yield* loadReplayThrough(input.afterSequence, highWater);
953
+ const replay = coalesceLiveUpdatedEvents(
954
+ yield* loadReplayThrough(input.afterSequence, highWater),
955
+ );
956
const plan = decideThreadResume({
957
afterSequence: input.afterSequence,
958
highWater,
packages/client-runtime/src/authorization/layer.test.ts
+124
-4
@@ -1,4 +1,8 @@
1
-import { AuthStandardClientScopes, EnvironmentId } from "@t3tools/contracts";
1
+import {
2
+ AuthStandardClientScopes,
3
+ EnvironmentId,
4
+ ORCHESTRATION_PROTOCOL_VERSION,
5
+} from "@t3tools/contracts";
6
import { type RelayEnvironmentConnectResponse } from "@t3tools/contracts/relay";
7
import { describe, expect, it } from "@effect/vitest";
8
import * as Deferred from "effect/Deferred";
@@ -15,6 +19,11 @@ import * as RpcHttp from "../rpc/http.ts";
19
import * as ClientCapabilities from "../platform/capabilities.ts";
20
import * as RemoteEnvironmentAuthorization from "./service.ts";
21
import * as TokenStore from "./tokenStore.ts";
22
+import { BearerConnectionCredential, BearerConnectionProfile } from "../connection/catalog.ts";
23
+import * as ConnectionCredentialStore from "../connection/credentialStore.ts";
24
+import { BearerConnectionTarget } from "../connection/model.ts";
25
+import * as ConnectionProfileStore from "../connection/profileStore.ts";
26
+import * as ConnectionResolver from "../connection/resolver.ts";
27
28
const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
29
const ENDPOINT = {
@@ -186,7 +195,7 @@ const makeHarness = Effect.fn("TestRemoteAuthorization.makeHarness")(function* (
195
resetTokenCache: Effect.void,
196
});
197
const layer = RemoteEnvironmentAuthorization.layer.pipe(
189
- Layer.provide(
198
+ Layer.provideMerge(
199
Layer.mergeAll(
200
RpcHttp.layerRemoteHttpClient(fetch.fetchFn),
201
Layer.succeed(ManagedRelay.ManagedRelayDpopSigner, signer),
@@ -225,13 +234,124 @@ const makeHarness = Effect.fn("TestRemoteAuthorization.makeHarness")(function* (
234
};
235
});
236
237
+const prepareDirectBearer = Effect.fn("TestRemoteAuthorization.prepareDirectBearer")(function* (
238
+ harness: Effect.Success<ReturnType<typeof makeHarness>>,
239
+ times: number,
240
+) {
241
+ const target = new BearerConnectionTarget({
242
+ environmentId: ENVIRONMENT_ID,
243
+ label: DESCRIPTOR.label,
244
+ connectionId: "direct-1",
245
+ });
246
+ const entry = {
247
+ target,
248
+ profile: Option.some(
249
+ new BearerConnectionProfile({
250
+ connectionId: target.connectionId,
251
+ environmentId: ENVIRONMENT_ID,
252
+ label: target.label,
253
+ httpBaseUrl: ENDPOINT.httpBaseUrl,
254
+ wsBaseUrl: ENDPOINT.wsBaseUrl,
255
+ }),
256
+ ),
257
+ enabled: true,
258
+ };
259
+ const unused = () => Effect.die("unused");
260
+ const layer = ConnectionResolver.layer.pipe(
261
+ Layer.provide(
262
+ Layer.mergeAll(
263
+ harness.layer,
264
+ Layer.succeed(ConnectionProfileStore.ConnectionProfileStore, {
265
+ get: unused,
266
+ put: unused,
267
+ remove: unused,
268
+ }),
269
+ Layer.succeed(ConnectionCredentialStore.ConnectionCredentialStore, {
270
+ get: () => Effect.succeedSome(new BearerConnectionCredential({ token: "bearer-token" })),
271
+ put: unused,
272
+ remove: unused,
273
+ }),
274
+ Layer.succeed(ClientCapabilities.PrimaryEnvironmentAuth, {
275
+ bearerToken: Effect.succeedNone,
276
+ }),
277
+ Layer.succeed(ClientCapabilities.SshEnvironmentGateway, {
278
+ provision: unused,
279
+ prepare: unused,
280
+ disconnect: unused,
281
+ }),
282
+ ),
283
+ ),
284
+ );
285
+ const resolver = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(layer));
286
+ return yield* Effect.forEach(Array.from({ length: times }), () =>
287
+ resolver.prepare(entry).pipe(Effect.result),
288
+ );
289
+});
290
+
291
describe("RemoteEnvironmentAuthorization", () => {
229
- it.effect("reuses a validated bearer descriptor while issuing fresh websocket tickets", () =>
292
+ it.effect("prepares a cold direct bearer connection with one descriptor request", () =>
293
+ Effect.gen(function* () {
294
+ const harness = yield* makeHarness({
295
+ responses: [
296
+ Response.json({
297
+ ...DESCRIPTOR,
298
+ orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION,
299
+ }),
300
+ websocketTicket("cold-ticket"),
301
+ ],
302
+ });
303
+
304
+ const [prepared] = yield* prepareDirectBearer(harness, 1);
305
+
306
+ expect(prepared).toMatchObject({
307
+ _tag: "Success",
308
+ success: { socketUrl: expect.stringContaining("wsTicket=cold-ticket") },
309
+ });
310
+ expect(harness.fetch.calls.map(([url]) => new URL(String(url)).pathname)).toEqual([
311
+ "/.well-known/t3/environment",
312
+ "/api/auth/websocket-ticket/rpc",
313
+ ]);
314
+ }),
315
+ );
316
+
317
+ it.effect("blocks a warm direct bearer prepare when the environment changes identity", () =>
318
+ Effect.gen(function* () {
319
+ const harness = yield* makeHarness({
320
+ responses: [
321
+ Response.json({
322
+ ...DESCRIPTOR,
323
+ orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION,
324
+ }),
325
+ websocketTicket("first-ticket"),
326
+ Response.json({
327
+ ...DESCRIPTOR,
328
+ environmentId: "another-environment",
329
+ orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION,
330
+ }),
331
+ ],
332
+ });
333
+
334
+ const [first, second] = yield* prepareDirectBearer(harness, 2);
335
+
336
+ expect(first?._tag).toBe("Success");
337
+ expect(second).toMatchObject({
338
+ _tag: "Failure",
339
+ failure: { _tag: "ConnectionBlockedError", reason: "configuration" },
340
+ });
341
+ expect(
342
+ harness.fetch.calls.filter(([url]) =>
343
+ String(url).endsWith("/api/auth/websocket-ticket/rpc"),
344
+ ),
345
+ ).toHaveLength(1);
346
+ }),
347
+ );
348
+ it.effect("validates a fresh bearer descriptor while issuing fresh websocket tickets", () =>
349
Effect.gen(function* () {
350
const harness = yield* makeHarness({
351
responses: [
352
Response.json(DESCRIPTOR),
353
websocketTicket("first-ticket"),
354
+ Response.json(DESCRIPTOR),
355
websocketTicket("second-ticket"),
356
],
357
});
@@ -253,7 +373,7 @@ describe("RemoteEnvironmentAuthorization", () => {
373
expect(second.socketUrl).toContain("wsTicket=second-ticket");
374
expect(
375
harness.fetch.calls.filter(([url]) => String(url).endsWith("/.well-known/t3/environment")),
256
- ).toHaveLength(1);
376
+ ).toHaveLength(2);
377
expect(
378
harness.fetch.calls.filter(([url]) =>
379
String(url).endsWith("/api/auth/websocket-ticket/rpc"),
packages/client-runtime/src/authorization/service.ts
+14
-40
@@ -33,7 +33,6 @@ import * as Effect from "effect/Effect";
33
import * as Fiber from "effect/Fiber";
34
import * as Layer from "effect/Layer";
35
import * as Option from "effect/Option";
36
-import * as Ref from "effect/Ref";
36
import * as Result from "effect/Result";
37
import * as Scope from "effect/Scope";
38
import * as Semaphore from "effect/Semaphore";
@@ -50,6 +49,7 @@ export interface AuthorizedRemoteEnvironment {
49
readonly httpBaseUrl: string;
50
readonly socketUrl: string;
51
readonly httpAuthorization: PreparedHttpAuthorization;
52
+ readonly descriptor?: ExecutionEnvironmentDescriptor;
53
}
54
55
export interface AuthorizedRemoteHttpEnvironment {
@@ -86,7 +86,6 @@ export class RemoteEnvironmentAuthorization extends Context.Service<
86
>()("@t3tools/client-runtime/authorization/service/RemoteEnvironmentAuthorization") {}
87
88
const CACHED_ENDPOINT_SOCKET_TIMEOUT_MS = 3_000;
89
-const BEARER_DESCRIPTOR_CACHE_TTL_MS = 10_000;
89
const DPOP_AUTHORIZATION_TIMEOUT_MS = 30_000;
90
91
function mapDpopSocketError(error: RemoteEnvironmentAuthError | ConnectionAttemptError) {
@@ -127,16 +126,6 @@ export const make = Effect.gen(function* () {
126
readonly token: Effect.Effect<TokenStore.RemoteDpopAccessToken, ConnectionAttemptError>;
127
}
128
>();
130
- const bearerDescriptors = yield* Ref.make<
131
- ReadonlyMap<
132
- EnvironmentId,
133
- {
134
- readonly httpBaseUrl: string;
135
- readonly descriptor: ExecutionEnvironmentDescriptor;
136
- readonly validatedAtEpochMs: number;
137
- }
138
- >
139
- >(new Map());
129
130
/**
131
* A saved LAN address can belong to another machine on a different network.
@@ -147,33 +136,15 @@ export const make = Effect.gen(function* () {
136
readonly httpBaseUrl: string;
137
readonly connectionMethod: ClientConnectionMethod;
138
}) {
150
- const now = yield* Clock.currentTimeMillis;
151
- const cachedDescriptor = (yield* Ref.get(bearerDescriptors)).get(input.expectedEnvironmentId);
152
- const canReuseDescriptor =
153
- cachedDescriptor?.httpBaseUrl === input.httpBaseUrl &&
154
- cachedDescriptor.validatedAtEpochMs + BEARER_DESCRIPTOR_CACHE_TTL_MS > now;
155
- const descriptor = canReuseDescriptor
156
- ? cachedDescriptor.descriptor
157
- : yield* fetchDescriptor(input.httpBaseUrl, input.connectionMethod).pipe(
158
- Effect.provideService(HttpClient.HttpClient, httpClient),
159
- );
139
+ const descriptor = yield* fetchDescriptor(input.httpBaseUrl, input.connectionMethod).pipe(
140
+ Effect.provideService(HttpClient.HttpClient, httpClient),
141
+ );
142
if (descriptor.environmentId !== input.expectedEnvironmentId) {
143
return yield* environmentMismatchError({
144
expected: input.expectedEnvironmentId,
145
actual: descriptor.environmentId,
146
});
147
}
166
- if (!canReuseDescriptor) {
167
- yield* Ref.update(bearerDescriptors, (current) => {
168
- const next = new Map(current);
169
- next.set(input.expectedEnvironmentId, {
170
- httpBaseUrl: input.httpBaseUrl,
171
- descriptor,
172
- validatedAtEpochMs: now,
173
- });
174
- return next;
175
- });
176
- }
148
return descriptor;
149
},
150
);
@@ -204,6 +175,7 @@ export const make = Effect.gen(function* () {
175
label: descriptor.label,
176
httpBaseUrl: input.httpBaseUrl,
177
socketUrl,
178
+ descriptor,
179
httpAuthorization: {
180
_tag: "Bearer" as const,
181
token: input.bearerToken,
@@ -492,16 +464,18 @@ export const make = Effect.gen(function* () {
464
input: Parameters<RemoteEnvironmentAuthorization["Service"]["authorizeDpop"]>[0],
465
) {
466
const endpoint = input.directEndpoint;
495
- if (endpoint !== undefined) {
496
- yield* verifyDirectEndpoint({
497
- expectedEnvironmentId: input.expectedEnvironmentId,
498
- httpBaseUrl: endpoint.httpBaseUrl,
499
- connectionMethod: "direct",
500
- });
501
- }
467
+ const descriptor =
468
+ endpoint === undefined
469
+ ? undefined
470
+ : yield* verifyDirectEndpoint({
471
+ expectedEnvironmentId: input.expectedEnvironmentId,
472
+ httpBaseUrl: endpoint.httpBaseUrl,
473
+ connectionMethod: "direct",
474
+ });
475
const authorized = (token: TokenStore.RemoteDpopAccessToken, socketUrl: string) => ({
476
...httpAuthorization(token, endpoint?.httpBaseUrl),
477
socketUrl,
478
+ ...(descriptor === undefined ? {} : { descriptor }),
479
});
480
let selected = yield* getDpopToken(input);
481
if (selected.fromCache) {
packages/client-runtime/src/connection/resolver.ts
+15
-22
@@ -171,11 +171,7 @@ const makeBearerBroker = Effect.fn("clientRuntime.connection.broker.makeBearer")
171
connectionMethod: "direct",
172
});
173
return {
174
- environmentId: authorized.environmentId,
175
- label: authorized.label,
176
- httpBaseUrl: authorized.httpBaseUrl,
177
- socketUrl: authorized.socketUrl,
178
- httpAuthorization: authorized.httpAuthorization,
174
+ ...authorized,
175
target,
176
} satisfies PreparedConnection;
177
});
@@ -190,11 +186,7 @@ const makeRelayBroker = Effect.fn("clientRuntime.connection.broker.makeRelay")(f
186
expectedEnvironmentId: target.environmentId,
187
});
188
return {
193
- environmentId: authorized.environmentId,
194
- label: authorized.label,
195
- httpBaseUrl: authorized.httpBaseUrl,
196
- socketUrl: authorized.socketUrl,
197
- httpAuthorization: authorized.httpAuthorization,
189
+ ...authorized,
190
target,
191
} satisfies PreparedConnection;
192
},
@@ -265,11 +257,7 @@ const makeSshBroker = Effect.fn("clientRuntime.connection.broker.makeSsh")(funct
257
connectionMethod: "ssh",
258
});
259
return {
268
- environmentId: authorized.environmentId,
269
- label: authorized.label,
270
- httpBaseUrl: authorized.httpBaseUrl,
271
- socketUrl: authorized.socketUrl,
272
- httpAuthorization: authorized.httpAuthorization,
260
+ ...authorized,
261
target,
262
} satisfies PreparedConnection;
263
});
@@ -291,7 +279,9 @@ export const make = Effect.gen(function* () {
279
"connection.environment.id": target.environmentId,
280
"connection.target.kind": target._tag,
281
});
294
- const prepared = yield* (() => {
282
+ const authorized: PreparedConnection & {
283
+ readonly descriptor?: ExecutionEnvironmentDescriptor;
284
+ } = yield* (() => {
285
switch (target._tag) {
286
case "PrimaryConnectionTarget":
287
return primary(target);
@@ -303,12 +293,15 @@ export const make = Effect.gen(function* () {
293
return ssh({ ...entry, target });
294
}
295
})();
306
- const descriptor = yield* fetchRemoteEnvironmentDescriptor({
307
- httpBaseUrl: prepared.httpBaseUrl,
308
- }).pipe(
309
- Effect.mapError(mapRemoteEnvironmentError),
310
- Effect.provideService(HttpClient.HttpClient, httpClient),
311
- );
296
+ const { descriptor: authorizedDescriptor, ...prepared } = authorized;
297
+ const descriptor =
298
+ authorizedDescriptor ??
299
+ (yield* fetchRemoteEnvironmentDescriptor({
300
+ httpBaseUrl: prepared.httpBaseUrl,
301
+ }).pipe(
302
+ Effect.mapError(mapRemoteEnvironmentError),
303
+ Effect.provideService(HttpClient.HttpClient, httpClient),
304
+ ));
305
if (descriptor.environmentId !== target.environmentId) {
306
return yield* environmentMismatchError({
307
expected: target.environmentId,
packages/client-runtime/src/state/threadCommands.test.ts
+56
-1
@@ -3,6 +3,7 @@ import {
3
CommandId,
4
RuntimeRequestId,
5
EnvironmentId,
6
+ MessageId,
7
RunId,
8
ORCHESTRATION_V2_WS_METHODS,
9
ProjectId,
@@ -86,6 +87,7 @@ const SNAPSHOT: OrchestrationV2ShellSnapshot = {
87
};
88
89
const makeHarness = Effect.fn("TestThreadCommands.makeHarness")(function* (options?: {
90
+ readonly loadEarlier?: () => Effect.Effect<ThreadHistoryController.ThreadHistoryLoadEarlierResult>;
91
readonly reconcilePendingWork?: (threadId: ThreadId) => Effect.Effect<void>;
92
}) {
93
const requests = yield* Queue.unbounded<{
@@ -126,7 +128,7 @@ const makeHarness = Effect.fn("TestThreadCommands.makeHarness")(function* (optio
128
ThreadHistoryController.ThreadHistoryController.of({
129
register: () => Effect.die("unused"),
130
unregister: () => Effect.void,
129
- loadEarlier: () => Effect.die("unused"),
131
+ loadEarlier: () => options?.loadEarlier?.() ?? Effect.die("unused"),
132
reconcilePendingWork: (_environmentId, threadId) =>
133
options?.reconcilePendingWork?.(threadId) ?? Queue.offer(reconciled, threadId),
134
}),
@@ -142,6 +144,59 @@ const makeHarness = Effect.fn("TestThreadCommands.makeHarness")(function* (optio
144
return { registry, commands, snapshotAtom, visibleAtom, requests, reconciled };
145
});
146
147
+describe("history loading", () => {
148
+ it.effect("sends a message on the thread while earlier history is loading", () =>
149
+ Effect.gen(function* () {
150
+ const historyStarted = yield* Deferred.make<void>();
151
+ const historyReply =
152
+ yield* Deferred.make<ThreadHistoryController.ThreadHistoryLoadEarlierResult>();
153
+ const h = yield* makeHarness({
154
+ loadEarlier: () =>
155
+ Deferred.succeed(historyStarted, undefined).pipe(
156
+ Effect.andThen(Deferred.await(historyReply)),
157
+ ),
158
+ });
159
+ yield* Effect.addFinalizer(() => Deferred.succeed(historyReply, { _tag: "loaded" }));
160
+ const history = h.commands.loadEarlierHistory.run(h.registry, {
161
+ environmentId: ENVIRONMENT_ID,
162
+ input: { threadId: THREAD_ID },
163
+ });
164
+ yield* Deferred.await(historyStarted);
165
+ const send = h.commands.startTurn.run(h.registry, {
166
+ environmentId: ENVIRONMENT_ID,
167
+ input: {
168
+ threadId: THREAD_ID,
169
+ message: {
170
+ messageId: MessageId.make("message"),
171
+ role: "user",
172
+ text: "Send while history loads",
173
+ attachments: [],
174
+ },
175
+ runtimeMode: "full-access",
176
+ interactionMode: "default",
177
+ dispatchMode: "start",
178
+ },
179
+ });
180
+ // Dispatched after Send on another thread, so it arrives first only if Send is queued.
181
+ const controlThreadId = ThreadId.make("control-thread");
182
+ const control = h.commands.interruptTurn.run(h.registry, {
183
+ environmentId: ENVIRONMENT_ID,
184
+ input: { threadId: controlThreadId, runId: RunId.make("control-run") },
185
+ });
186
+ const first = yield* Queue.take(h.requests);
187
+ yield* Deferred.succeed(first.reply, { sequence: 1 });
188
+ yield* Deferred.succeed(historyReply, { _tag: "loaded" });
189
+ const second = yield* Queue.take(h.requests);
190
+ yield* Deferred.succeed(second.reply, { sequence: 2 });
191
+ const results = yield* Effect.promise(() => Promise.all([history, send, control]));
192
+
193
+ expect(first.command).toMatchObject({ type: "message.dispatch", threadId: THREAD_ID });
194
+ expect(second.command).toMatchObject({ type: "run.interrupt", threadId: controlThreadId });
195
+ expect(results.map((value) => value._tag)).toEqual(["Success", "Success", "Success"]);
196
+ }),
197
+ );
198
+});
199
+
200
describe("interrupt turn", () => {
201
// A stale cached item has nothing left to interrupt, so the server can reject Stop.
202
it.effect("reconciles pending work when the server rejects the interrupt", () =>
packages/client-runtime/src/state/threadCommands.ts
+2
-1
@@ -351,7 +351,8 @@ export function createThreadEnvironmentAtoms<R, E>(
351
scheduler,
352
concurrency: {
353
mode: "serial",
354
- key: ({ environmentId, input }) => JSON.stringify([environmentId, input.threadId]),
354
+ key: ({ environmentId, input }) =>
355
+ `history:${JSON.stringify([environmentId, input.threadId])}`,
356
},
357
}),
358
uploadFeedback: createEnvironmentRpcCommand(runtime, {