The best way to control Claude Code, Codex and more from any computer or phone
fix(mobile): delivered messages no longer reappear at the bottom of long threads (#26739)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 28, 2026 at 18:09 UTC
8ff9ae1f87e2b7c62cfacffd08921ff40bb089b1
17 files changed
+176
-60
apps/mobile/src/features/threads/pending-thread-feed.test.ts
+6
-3
@@ -114,14 +114,17 @@ describe("pending timeline messages", () => {
114
expect(appendPendingThreadMessages([], [delivered], [queued])).toEqual([]);
115
});
116
117
- it("stops showing an acknowledged message once the projection holds it, even when the feed hides it", () => {
117
+ it("stops showing an acknowledged message once the thread catches up, even when the feed hides it", () => {
118
// A rolled-back or cancelled queued run keeps its message in projection.messages
119
// while its user_message item leaves the visible feed.
120
const echoed = pending("rolled-back");
121
- const waiting = pending("waiting");
122
- const shown = selectPendingAcknowledgedMessages([echoed, waiting], {
121
+ // A bounded projection pages an applied message out; it must not come back as pending.
122
+ const pagedOut = { ...pending("paged-out"), sequence: 40 };
123
+ const waiting = { ...pending("waiting"), sequence: 50 };
124
+ const shown = selectPendingAcknowledgedMessages([echoed, pagedOut, waiting], {
125
threadKey: "env:thread",
126
queuedMessages: [],
127
+ sequence: 45,
128
projectedMessages: [{ id: echoed.messageId }],
129
});
130
expect(shown).toEqual([waiting]);
apps/mobile/src/features/threads/pending-thread-feed.ts
+13
-5
@@ -5,7 +5,11 @@ import {
5
} from "@t3tools/contracts";
6
import type { ThreadFeedEntry } from "../../lib/threadActivity";
7
import { scopedThreadKey } from "../../lib/scopedEntities";
8
-import type { QueuedThreadMessage } from "../../state/thread-outbox-model";
8
+import { threadHasCaughtUpTo } from "@t3tools/client-runtime/state/threads";
9
+import type {
10
+ AcknowledgedThreadMessage,
11
+ QueuedThreadMessage,
12
+} from "../../state/thread-outbox-model";
13
14
/**
15
* A guest's message waiting for the owner's Send or Dismiss. It is a feed row, not the list
@@ -24,21 +28,25 @@ export type PendingThreadFeedEntry = ThreadFeedEntry & {
28
readonly acknowledged?: boolean;
29
};
30
27
-// An acknowledged row stops being pending once the projection holds its message,
31
+// An acknowledged row stops being pending once the thread catches up to it,
32
// even when the feed hides that message (a rolled-back or cancelled run).
33
export function selectPendingAcknowledgedMessages(
30
- acknowledged: ReadonlyArray<QueuedThreadMessage>,
34
+ acknowledged: ReadonlyArray<AcknowledgedThreadMessage>,
35
thread: {
36
readonly threadKey: string | null;
37
readonly queuedMessages: ReadonlyArray<QueuedThreadMessage>;
38
+ readonly sequence: number;
39
readonly projectedMessages: ReadonlyArray<{ readonly id: string }> | undefined;
40
},
36
-): ReadonlyArray<QueuedThreadMessage> {
41
+): ReadonlyArray<AcknowledgedThreadMessage> {
42
return acknowledged.filter(
43
(message) =>
44
scopedThreadKey(message.environmentId, message.threadId) === thread.threadKey &&
45
!thread.queuedMessages.some((queued) => queued.messageId === message.messageId) &&
41
- !thread.projectedMessages?.some((projected) => projected.id === message.messageId),
46
+ !threadHasCaughtUpTo(message, {
47
+ sequence: thread.sequence,
48
+ messages: thread.projectedMessages,
49
+ }),
50
);
51
}
52
apps/mobile/src/state/acknowledged-thread-messages.ts
+20
-12
@@ -1,31 +1,39 @@
1
import * as Option from "effect/Option";
2
import { Atom } from "effect/reactivity";
3
import { appAtomRegistry } from "./atom-registry";
4
-import type { QueuedThreadMessage } from "./thread-outbox-model";
4
+import { threadHasCaughtUpTo } from "@t3tools/client-runtime/state/threads";
5
+import type { AcknowledgedThreadMessage, QueuedThreadMessage } from "./thread-outbox-model";
6
import { environmentThreadDetails } from "./threads";
7
7
-// Keep acknowledged rows until their subscribed projection arrives; command receipts can precede messages.
8
-// Render hides rows the projection has echoed, so dropping them here only frees memory.
9
-export const acknowledgedThreadMessagesAtom = Atom.make<ReadonlyArray<QueuedThreadMessage>>(
8
+// Keep acknowledged rows until the thread catches up; command receipts can precede messages.
9
+export const acknowledgedThreadMessagesAtom = Atom.make<ReadonlyArray<AcknowledgedThreadMessage>>(
10
[],
11
).pipe(Atom.keepAlive);
12
13
// Peeks at a thread only when something already has it in the registry: reading
14
// it through the registry would open a snapshot load and a live stream of its own.
15
-function isEchoedInMountedThread(message: QueuedThreadMessage): boolean {
16
- const threadAtom = environmentThreadDetails.threadAtom({
15
+function isEchoedInMountedThread(message: AcknowledgedThreadMessage): boolean {
16
+ const stateAtom = environmentThreadDetails.stateAtom({
17
environmentId: message.environmentId,
18
threadId: message.threadId,
19
});
20
- const node = appAtomRegistry.getNodes().get(threadAtom);
20
+ const node = appAtomRegistry.getNodes().get(stateAtom);
21
if (node === undefined) return false;
22
- const loaded: Option.Option<Atom.Type<typeof threadAtom>> = node.valueOption();
23
- const thread = Option.getOrNull(loaded);
24
- return thread?.projection.messages.some((entry) => entry.id === message.messageId) ?? false;
22
+ const loaded: Option.Option<Atom.Type<typeof stateAtom>> = node.valueOption();
23
+ return Option.match(loaded, {
24
+ onNone: () => false,
25
+ onSome: (thread) =>
26
+ threadHasCaughtUpTo(message, {
27
+ sequence: thread.sequence,
28
+ messages: Option.getOrUndefined(thread.data)?.messages,
29
+ }),
30
+ });
31
}
32
33
function writeAcknowledgedThreadMessages(
28
- update: (current: ReadonlyArray<QueuedThreadMessage>) => ReadonlyArray<QueuedThreadMessage>,
34
+ update: (
35
+ current: ReadonlyArray<AcknowledgedThreadMessage>,
36
+ ) => ReadonlyArray<AcknowledgedThreadMessage>,
37
) {
38
const current = appAtomRegistry.get(acknowledgedThreadMessagesAtom);
39
const next = update(current).filter((entry) => !isEchoedInMountedThread(entry));
@@ -35,7 +43,7 @@ function writeAcknowledgedThreadMessages(
43
appAtomRegistry.set(acknowledgedThreadMessagesAtom, next);
44
}
45
38
-export function retainAcknowledgedThreadMessage(message: QueuedThreadMessage) {
46
+export function retainAcknowledgedThreadMessage(message: AcknowledgedThreadMessage) {
47
writeAcknowledgedThreadMessages((current) =>
48
current.some((entry) => entry.messageId === message.messageId)
49
? current
apps/mobile/src/state/thread-outbox-model.ts
+5
@@ -287,3 +287,8 @@ export function resolveThreadOutboxFailureAction(input: {
287
}
288
return "restore";
289
}
290
+
291
+export type AcknowledgedThreadMessage = QueuedThreadMessage & {
292
+ /** The server sequence that committed the message; older servers do not report it. */
293
+ readonly sequence?: number;
294
+};
apps/mobile/src/state/thread-task-permissions.test.ts
+1
@@ -113,6 +113,7 @@ vi.mock("./threads", async () => {
113
environmentThreadDetails: {
114
queueWorkflowAtom: () => Atom.make(null),
115
checkpointSummariesAtom: () => Atom.make([]),
116
+ sequenceAtom: () => Atom.make(0),
117
pendingRequestsAtom: () => Atom.make(state.pendingRequests),
118
},
119
threadEnvironment: {
apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts
+5
-3
@@ -100,7 +100,7 @@ vi.mock("./threads", async () => {
100
familyAtom: () => Atom.make(AsyncResult.success({})),
101
refresh: vi.fn(),
102
},
103
- environmentThreadDetails: { threadAtom: () => Atom.make(null) },
103
+ environmentThreadDetails: { stateAtom: () => Atom.make(null) },
104
};
105
});
106
vi.mock("./git", () => ({ gitEnvironment: { preparePullRequestThread: state.checkout } }));
@@ -224,6 +224,7 @@ beforeEach(() => {
224
]) {
225
command.mockReset().mockResolvedValue(AsyncResult.success(undefined));
226
}
227
+ state.start.mockResolvedValue(AsyncResult.success({}));
228
state.prepare.mockReset().mockImplementation(async ({ attachments }) => ({
229
status: "ready",
230
attachments: [],
@@ -427,7 +428,8 @@ describe("queued task operation access", () => {
428
);
429
await state.manager.enqueue(queued);
430
const started = Promise.withResolvers<void>();
430
- const delivery = Promise.withResolvers<AsyncResult.AsyncResult<void, Error>>();
431
+ const delivery =
432
+ Promise.withResolvers<AsyncResult.AsyncResult<{ readonly sequence?: number }, Error>>();
433
state.start.mockImplementationOnce(() => {
434
started.resolve();
435
return delivery.promise;
@@ -437,7 +439,7 @@ describe("queued task operation access", () => {
439
setOperateGrant("secondary", false);
440
delivery.resolve(
441
accepted
440
- ? AsyncResult.success(undefined)
442
+ ? AsyncResult.success({})
443
: AsyncResult.failure(Cause.fail(new Error("This connection cannot control this task."))),
444
);
445
await drained;
apps/mobile/src/state/threadOutboxDelivery.test.ts
+47
-25
@@ -13,9 +13,12 @@ import type { PreparedTurnAttachments } from "../lib/attachmentUpload";
13
14
const harness = vi.hoisted(() => ({
15
canOperate: true,
16
- threadProjection: null as unknown as import("effect/reactivity").Atom.Writable<{
17
- readonly projection: { readonly messages: ReadonlyArray<{ readonly id: string }> };
18
- } | null>,
16
+ threadState: null as unknown as import("effect/reactivity").Atom.Writable<{
17
+ readonly data: import("effect/Option").Option<{
18
+ readonly messages: ReadonlyArray<{ readonly id: string }>;
19
+ }>;
20
+ readonly sequence: number;
21
+ }>,
22
manager: null as unknown as ReturnType<
23
typeof import("./thread-outbox-manager").createThreadOutboxManager
24
>,
@@ -92,12 +95,14 @@ vi.mock("./git", () => ({ gitEnvironment: {} }));
95
96
vi.mock("./threads", async () => {
97
const { Atom } = await import("effect/reactivity");
95
- harness.threadProjection = Atom.make<{
96
- readonly projection: { readonly messages: ReadonlyArray<{ readonly id: string }> };
97
- } | null>(null).pipe(Atom.keepAlive);
98
+ const Option = await import("effect/Option");
99
+ harness.threadState = Atom.make({
100
+ data: Option.none<{ readonly messages: ReadonlyArray<{ readonly id: string }> }>(),
101
+ sequence: 0,
102
+ }).pipe(Atom.keepAlive);
103
return {
104
threadEnvironment: {},
100
- environmentThreadDetails: { threadAtom: () => harness.threadProjection },
105
+ environmentThreadDetails: { stateAtom: () => harness.threadState },
106
};
107
});
108
@@ -138,6 +143,7 @@ vi.mock("./thread-outbox", async () => {
143
};
144
});
145
146
+import * as Option from "effect/Option";
147
import { appAtomRegistry } from "./atom-registry";
148
import { pendingThreadCreationOutcomesAtom } from "./pending-thread-creation";
149
import { clearThreadComposerError, threadComposerErrorsAtom } from "./thread-composer-error";
@@ -204,7 +210,7 @@ function remainingMessages(): ReadonlyArray<QueuedThreadMessage> {
210
211
beforeEach(() => {
212
appAtomRegistry.set(acknowledgedThreadMessagesAtom, []);
207
- appAtomRegistry.set(harness.threadProjection, null);
213
+ appAtomRegistry.set(harness.threadState, { data: Option.none(), sequence: 0 });
214
harness.canOperate = true;
215
harness.draftFile.setDocument({ schemaVersion: 1, drafts: {} });
216
});
@@ -330,26 +336,32 @@ describe("thread outbox attachment preparation", () => {
336
});
337
338
describe("thread outbox drain delivery cleanup", () => {
333
- it("drops echoed acknowledged rows at the next delivery without subscribing to the thread", async () => {
339
+ it("drops caught-up acknowledged rows at the next delivery without subscribing to the thread", async () => {
340
const first = queuedMessage({ messageId: "awaiting-echo", text: "Delivered" });
341
const second = queuedMessage({ messageId: "next-delivery", text: "Also delivered" });
342
await harness.manager.enqueue(first);
343
await harness.manager.enqueue(second);
344
345
await expect(
340
- completeQueuedMessageDelivery(first, harness.manager.revisionOf(first.messageId)),
346
+ completeQueuedMessageDelivery(first, harness.manager.revisionOf(first.messageId), 7),
347
).resolves.toBe("removed");
342
- expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toEqual([first]);
343
-
344
- appAtomRegistry.set(harness.threadProjection, {
345
- projection: { messages: [{ id: "unrelated" }, { id: first.messageId }] },
348
+ expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toEqual([
349
+ { ...first, sequence: 7 },
350
+ ]);
351
+
352
+ // The thread applied the message, but its bounded window does not hold it.
353
+ appAtomRegistry.set(harness.threadState, {
354
+ data: Option.some({ messages: [{ id: "unrelated" }] }),
355
+ sequence: 7,
356
});
347
- expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toEqual([first]);
357
+ expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toHaveLength(1);
358
359
await expect(
350
- completeQueuedMessageDelivery(second, harness.manager.revisionOf(second.messageId)),
360
+ completeQueuedMessageDelivery(second, harness.manager.revisionOf(second.messageId), 9),
361
).resolves.toBe("removed");
352
- expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toEqual([second]);
362
+ expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toEqual([
363
+ { ...second, sequence: 9 },
364
+ ]);
365
});
366
367
it("removes an acknowledged outbox item even when the sign-out archive write fails", async () => {
@@ -359,7 +371,11 @@ describe("thread outbox drain delivery cleanup", () => {
371
harness.draftFile.setWriteError(new Error("Draft storage unavailable"));
372
373
await expect(
362
- completeQueuedMessageDelivery(message, harness.manager.revisionOf(message.messageId)),
374
+ completeQueuedMessageDelivery(
375
+ message,
376
+ harness.manager.revisionOf(message.messageId),
377
+ undefined,
378
+ ),
379
).resolves.toBe("removed");
380
expect(remainingMessages()).toEqual([]);
381
@@ -390,9 +406,9 @@ describe("thread outbox drain delivery cleanup", () => {
406
).toEqual([message]);
407
408
if (cleared) await harness.manager.clearEnvironment(message.environmentId);
393
- await expect(completeQueuedMessageDelivery(message, deliveryRevision)).resolves.toBe(
394
- cleared ? "edited" : "removed",
395
- );
409
+ await expect(
410
+ completeQueuedMessageDelivery(message, deliveryRevision, undefined),
411
+ ).resolves.toBe(cleared ? "edited" : "removed");
412
413
appAtomRegistry.set(composerDrafts.composerCloudDraftsAtom, {
414
accountId: null,
@@ -412,7 +428,9 @@ describe("thread outbox drain delivery cleanup", () => {
428
await harness.manager.update(edited);
429
await composerDrafts.archiveCloudComposerDrafts("account-a", new Set([message.environmentId]));
430
await harness.manager.clearEnvironment(message.environmentId);
415
- await expect(completeQueuedMessageDelivery(message, deliveryRevision)).resolves.toBe("edited");
431
+ await expect(completeQueuedMessageDelivery(message, deliveryRevision, undefined)).resolves.toBe(
432
+ "edited",
433
+ );
434
await composerDrafts.restoreCloudComposerDrafts("account-a");
435
expect(remainingMessages()).toEqual([edited]);
436
});
@@ -447,7 +465,9 @@ describe("thread outbox drain delivery cleanup", () => {
465
const edited = { ...message, text: "edited while the turn delivered" };
466
await harness.manager.update(edited);
467
450
- await expect(completeQueuedMessageDelivery(message, deliveryRevision)).resolves.toBe("edited");
468
+ await expect(completeQueuedMessageDelivery(message, deliveryRevision, undefined)).resolves.toBe(
469
+ "edited",
470
+ );
471
472
expect(remainingMessages()).toEqual([edited]);
473
expect(harness.removePersistedFile).not.toHaveBeenCalled();
@@ -458,7 +478,9 @@ describe("thread outbox drain delivery cleanup", () => {
478
await harness.manager.enqueue(message);
479
const deliveryRevision = harness.manager.revisionOf(message.messageId);
480
461
- await expect(completeQueuedMessageDelivery(message, deliveryRevision)).resolves.toBe("removed");
481
+ await expect(completeQueuedMessageDelivery(message, deliveryRevision, undefined)).resolves.toBe(
482
+ "removed",
483
+ );
484
485
expect(remainingMessages()).toEqual([]);
486
expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toEqual([message]);
@@ -479,7 +501,7 @@ describe("thread outbox drain delivery cleanup", () => {
501
await harness.manager.enqueue(message);
502
const deliveryRevision = harness.manager.revisionOf(message.messageId);
503
482
- const cleanup = completeQueuedMessageDelivery(message, deliveryRevision);
504
+ const cleanup = completeQueuedMessageDelivery(message, deliveryRevision, undefined);
505
await removeStarted.promise;
506
appAtomRegistry.set(editingQueuedMessageIdsAtom, { [message.messageId]: true });
507
removeBarrier.resolve();
apps/mobile/src/state/threadOutboxDelivery.ts
+20
-3
@@ -250,6 +250,7 @@ function isQueuedMessagePayloadCurrent(
250
export async function completeQueuedMessageDelivery(
251
queuedMessage: QueuedThreadMessage,
252
deliveryRevision: number,
253
+ sequence: number | undefined,
254
): Promise<"removed" | "edited" | "failed"> {
255
clearThreadComposerError(
256
scopedThreadKey(queuedMessage.environmentId, queuedMessage.threadId),
@@ -266,7 +267,9 @@ export async function completeQueuedMessageDelivery(
267
if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) {
268
return "edited";
269
}
269
- retainAcknowledgedThreadMessage(queuedMessage);
270
+ retainAcknowledgedThreadMessage(
271
+ sequence === undefined ? queuedMessage : { ...queuedMessage, sequence },
272
+ );
273
const removed = await removeThreadOutboxMessage(
274
queuedMessage,
275
deliveryRevision,
@@ -616,6 +619,12 @@ const settledCreationOutcomeKeysAtom = Atom.make((get): ReadonlyArray<string> =>
619
);
620
}).pipe(Atom.withLabel("mobile:thread-outbox:settled-creation-outcomes"));
621
622
+function deliveredSequence(
623
+ result: AtomCommandResult<{ readonly sequence?: number }, unknown>,
624
+): number | undefined {
625
+ return AsyncResult.isSuccess(result) ? result.value.sequence : undefined;
626
+}
627
+
628
const runDeliveryCommand = <W, A, E>(
629
command: AtomCommand<W, A, E>,
630
input: W,
@@ -896,7 +905,11 @@ export function createThreadOutboxDelivery(): {
905
}
906
acknowledgedExistingThreadMessageIds.add(persistedMessage.messageId);
907
const delivered =
899
- (await completeQueuedMessageDelivery(persistedMessage, deliveryRevision)) === "removed";
908
+ (await completeQueuedMessageDelivery(
909
+ persistedMessage,
910
+ deliveryRevision,
911
+ deliveredSequence(deliveryResult),
912
+ )) === "removed";
913
if (delivered) {
914
acknowledgedExistingThreadMessageIds.delete(persistedMessage.messageId);
915
}
@@ -1052,7 +1065,11 @@ export function createThreadOutboxDelivery(): {
1065
return restoreQueuedMessage(persistedMessage, failure.message);
1066
}
1067
recordPendingThreadCreationOutcome({ kind: "delivered", message: persistedMessage });
1055
- const outcome = await completeQueuedMessageDelivery(persistedMessage, deliveryRevision);
1068
+ const outcome = await completeQueuedMessageDelivery(
1069
+ persistedMessage,
1070
+ deliveryRevision,
1071
+ deliveredSequence(deliveryResult),
1072
+ );
1073
if (outcome === "edited") {
1074
if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) {
1075
return true;
apps/mobile/src/state/use-thread-composer-state.ts
+7
@@ -110,6 +110,7 @@ const EMPTY_QUEUE_WORKFLOW_ATOM = Atom.make<null>(null).pipe(
110
Atom.withLabel("mobile-thread-queue-workflow:empty"),
111
);
112
const EMPTY_CHECKPOINT_SUMMARIES_ATOM = Atom.make<ReadonlyArray<ThreadCheckpointSummary>>([]);
113
+const EMPTY_THREAD_SEQUENCE_ATOM = Atom.make(0);
114
115
export function appendReviewCommentToDraft(input: {
116
readonly environmentId: EnvironmentId;
@@ -227,6 +228,11 @@ export function useThreadComposerState() {
228
const selectedThreadMessages = selectedThreadProjection?.projection.messages;
229
const selectedThreadAttempts = selectedThreadProjection?.projection.attempts;
230
const selectedThreadNodes = selectedThreadProjection?.projection.nodes;
231
+ const selectedThreadSequence = useAtomValue(
232
+ selectedThreadDetailRef === null
233
+ ? EMPTY_THREAD_SEQUENCE_ATOM
234
+ : environmentThreadDetails.sequenceAtom(selectedThreadDetailRef),
235
+ );
236
const checkpointSummaries = useAtomValue(
237
selectedThreadDetailRef === null
238
? EMPTY_CHECKPOINT_SUMMARIES_ATOM
@@ -254,6 +260,7 @@ export function useThreadComposerState() {
260
const pendingAcknowledgments = selectPendingAcknowledgedMessages(acknowledgedMessages, {
261
threadKey: selectedThreadKey,
262
queuedMessages: selectedThreadQueuedMessages,
263
+ sequence: selectedThreadSequence,
264
projectedMessages: selectedThreadMessages,
265
});
266
if (pendingAcknowledgments.length === 0) return feed;
apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
+3
@@ -1380,6 +1380,9 @@ it.effect("replays a server-allocated launch", () =>
1380
assert.equal(first.threadId, retry.threadId);
1381
assert.isFalse(first.resumed);
1382
assert.isTrue(retry.resumed);
1383
+ // Clients drop their pending copy once the thread reaches the message's commit.
1384
+ assert.isNumber(first.sequence);
1385
+ assert.equal(retry.sequence, first.sequence);
1386
assert.equal(harness.runSetup.mock.calls.length, 1);
1387
assert.equal(retry.projection.messages.length, 1);
1388
assert.equal(retry.projection.runs.length, 1);
apps/server/src/orchestration-v2/ThreadLaunchService.ts
+4
@@ -123,6 +123,7 @@ export interface ThreadLaunchResult {
123
readonly projection: OrchestrationV2ThreadProjection;
124
/** The launch's last write (the initial message, else the thread claim) was accepted before this call. */
125
readonly resumed: boolean;
126
+ readonly sequence?: number;
127
}
128
129
export class ThreadLaunchError extends Schema.TaggedError<ThreadLaunchError>()(
@@ -941,6 +942,7 @@ const make = Effect.gen(function* () {
942
return yield* mapError(input, "resolve-project", threadId)("Project identity changed.");
943
}
944
let runId: RunId | null = null;
945
+ let messageSequence: number | undefined;
946
let messageWasAlreadyAccepted = false;
947
if (input.initialMessage !== undefined) {
948
const messageCommandId = CommandId.make(`${input.commandId}:initial-message`);
@@ -987,6 +989,7 @@ const make = Effect.gen(function* () {
989
);
990
// A concurrent retry can read no receipt and still replay the dispatch.
991
messageWasAlreadyAccepted ||= dispatched.replayed === true;
992
+ messageSequence = dispatched.sequence;
993
const runCreated = dispatched.storedEvents.find(
994
(stored) => stored.event.type === "run.created",
995
);
@@ -1053,6 +1056,7 @@ const make = Effect.gen(function* () {
1056
input.initialMessage === undefined
1057
? Option.isSome(launchReceipt) || claimed.replayed === true
1058
: messageWasAlreadyAccepted,
1059
+ ...(messageSequence === undefined ? {} : { sequence: messageSequence }),
1060
};
1061
});
1062
},
packages/client-runtime/src/operations/commands.performance.test.ts
+1
-1
@@ -223,7 +223,7 @@ describe("routine command transport budget", () => {
223
if (command.type !== "message.dispatch") {
224
throw new Error(`Expected message.dispatch, received ${command.type}`);
225
}
226
- if (!("sequence" in receipt)) {
226
+ if ("projection" in receipt) {
227
throw new Error("Expected a dispatch receipt");
228
}
229
const { deliveryIntent: _deliveryIntent, ...formerCommand } = command;
packages/client-runtime/src/state/threadDetail.ts
+7
@@ -409,6 +409,12 @@ export function createEnvironmentThreadDetailAtoms<E>(
409
Atom.withLabel(`environment-thread-status:${key}`),
410
),
411
);
412
+ const sequenceAtomFamily = Atom.family((key: string) =>
413
+ Atom.make((get) => get(threadStateValueAtomFamily(key)).sequence).pipe(
414
+ Atom.setIdleTTL(0),
415
+ Atom.withLabel(`environment-thread-sequence:${key}`),
416
+ ),
417
+ );
418
const errorAtomFamily = Atom.family((key: string) =>
419
Atom.make((get) => Option.getOrNull(get(threadStateValueAtomFamily(key)).error)).pipe(
420
Atom.setIdleTTL(0),
@@ -439,6 +445,7 @@ export function createEnvironmentThreadDetailAtoms<E>(
445
quietVisibleTurnItemsAtom: (ref: ScopedThreadRef) =>
446
quietVisibleTurnItemsAtomFamily(threadKey(ref)),
447
statusAtom: (ref: ScopedThreadRef) => statusAtomFamily(threadKey(ref)),
448
+ sequenceAtom: (ref: ScopedThreadRef) => sequenceAtomFamily(threadKey(ref)),
449
errorAtom: (ref: ScopedThreadRef) => errorAtomFamily(threadKey(ref)),
450
historyAtom: (ref: ScopedThreadRef) => historyAtomFamily(threadKey(ref)),
451
};
packages/client-runtime/src/state/threadState.ts
+19
@@ -14,6 +14,8 @@ export interface EnvironmentThreadState {
14
* disconnect path.
15
*/
16
readonly history: ThreadHistoryMeta;
17
+ /** The last server sequence `data` reflects, so readers can tell a write has landed without searching paged-out history. */
18
+ readonly sequence: number;
19
}
20
21
export const EMPTY_ENVIRONMENT_THREAD_STATE: EnvironmentThreadState = {
@@ -21,4 +23,21 @@ export const EMPTY_ENVIRONMENT_THREAD_STATE: EnvironmentThreadState = {
23
status: "empty",
24
error: Option.none(),
25
history: EMPTY_THREAD_HISTORY_META,
26
+ sequence: 0,
27
};
28
+
29
+/**
30
+ * A thread holds a write once it has applied the write's commit sequence. A bounded
31
+ * projection can page the message out later, so finding it is only a fallback for
32
+ * servers that do not report the sequence.
33
+ */
34
+export function threadHasCaughtUpTo(
35
+ write: { readonly messageId: string; readonly sequence?: number | undefined },
36
+ thread: {
37
+ readonly sequence: number;
38
+ readonly messages: ReadonlyArray<{ readonly id: string }> | undefined;
39
+ },
40
+): boolean {
41
+ if (write.sequence !== undefined && thread.sequence >= write.sequence) return true;
42
+ return thread.messages?.some((entry) => entry.id === write.messageId) ?? false;
43
+}
packages/client-runtime/src/state/threads-sync.test.ts
+4
-1
@@ -678,7 +678,7 @@ describe("EnvironmentThreads", () => {
678
const harness = yield* makeHarness({ cached: BASE_PROJECTION });
679
680
yield* Queue.offer(harness.inputs, titleUpdated("Live title", CACHED_SNAPSHOT_SEQUENCE + 1));
681
- yield* awaitThreadState(
681
+ const live = yield* awaitThreadState(
682
harness.observed,
683
(value) =>
684
value.status === "live" &&
@@ -686,6 +686,8 @@ describe("EnvironmentThreads", () => {
686
value.data.value.thread.title === "Live title",
687
);
688
689
+ // Readers compare this to a command's commit sequence; it moves with the data it describes.
690
+ expect(live.sequence).toBe(CACHED_SNAPSHOT_SEQUENCE + 1);
691
expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(CACHED_SNAPSHOT_SEQUENCE);
692
expect(yield* Ref.get(harness.loaderCalls)).toBe(0);
693
}),
@@ -1288,6 +1290,7 @@ describe("EnvironmentThreads", () => {
1290
status: "cached",
1291
error: Option.none(),
1292
history: { ...EMPTY_THREAD_HISTORY_META, historyCursor: null, expanded: true },
1293
+ sequence: CACHED_SNAPSHOT_SEQUENCE,
1294
},
1295
sequence: CACHED_SNAPSHOT_SEQUENCE,
1296
persisted: true,
packages/client-runtime/src/state/threads.ts
+12
-7
@@ -224,6 +224,11 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
224
)
225
: Option.none<OrchestrationV2ThreadDetailSnapshot>();
226
const cachedThread = Option.map(cached, (snapshot) => snapshot.projection);
227
+ // Seed the resume cursor from the cached snapshot so a warm cache can catch up
228
+ // via `afterSequence` instead of re-downloading the full thread body.
229
+ const initialSequence =
230
+ retained?.sequence ??
231
+ Option.match(cached, { onNone: () => 0, onSome: (snapshot) => snapshot.snapshotSequence });
232
const initialState: EnvironmentThreadState = retained
233
? cachedThreadState(retained.state)
234
: {
@@ -234,15 +239,11 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
239
onNone: () => EMPTY_THREAD_HISTORY_META,
240
onSome: historyMetaFromCachedSnapshot,
241
}),
242
+ sequence: initialSequence,
243
};
244
const state = yield* SubscriptionRef.make(initialState);
245
const canLoadHistory = Option.isSome(httpClient) && Option.isSome(historyController);
246
const acceptsBoundedSocketSnapshots = yield* Ref.make(canLoadHistory);
241
- // Seed the resume cursor from the cached snapshot so a warm cache can catch up
242
- // via `afterSequence` instead of re-downloading the full thread body.
243
- const initialSequence =
244
- retained?.sequence ??
245
- Option.match(cached, { onNone: () => 0, onSome: (snapshot) => snapshot.snapshotSequence });
247
const lastSequence = yield* SubscriptionRef.make(initialSequence);
248
let committed: ThreadResumeSnapshot = {
249
state: initialState,
@@ -400,6 +401,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
401
},
402
) {
403
const waiting = yield* Ref.get(awaitingCompletion);
404
+ const sequence = yield* SubscriptionRef.get(lastSequence);
405
// Atomic with concurrent history meta updates: never get-then-set the whole
406
// state when only the projection changes. Bounded installs pass history so
407
// projection + cursor persist together in one enqueue.
@@ -420,6 +422,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
422
: ("live" as const),
423
error: previous.error,
424
history,
425
+ sequence,
426
};
427
});
428
// Active projections can update many times per second and retain large tool
@@ -451,6 +454,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
454
status: "deleted",
455
error: Option.none(),
456
history: EMPTY_THREAD_HISTORY_META,
457
+ sequence: yield* SubscriptionRef.get(lastSequence),
458
});
459
yield* remember;
460
if (resumeCache !== undefined && resumeCache.owner !== owner) return;
@@ -571,7 +575,8 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
575
if (applied._tag !== "noop") result = applied;
576
if (applied._tag === "delete") break;
577
}
574
- return [result, current];
578
+ // A batch that changed nothing keeps its state object, so readers do not re-render.
579
+ return [result, result._tag === "noop" ? current : { ...current, sequence }];
580
},
581
);
582
@@ -796,7 +801,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
801
),
802
);
803
if (result._tag !== "loaded") return result;
799
- if (complete) yield* remember;
804
+ if (complete) yield* applyLock.withPermits(1)(remember);
805
nextCursor = keepPaging ? page.nextCursor : null;
806
}
807
if (nextCursor === null) return { _tag: "loaded" } as const;
packages/contracts/src/orchestrationV2.ts
+2
@@ -3573,6 +3573,8 @@ export const OrchestrationV2ThreadLaunchResult = Schema.Struct({
3573
threadId: ThreadId,
3574
projection: OrchestrationV2ThreadProjection,
3575
resumed: Schema.Boolean,
3576
+ /** The initial message's commit sequence. Older servers omit it. */
3577
+ sequence: Schema.optionalKey(NonNegativeInt),
3578
});
3579
export type OrchestrationV2ThreadLaunchResult = typeof OrchestrationV2ThreadLaunchResult.Type;
3580