TypeScript
fix(mobile): delivered messages no longer reappear at the bottom of long threads (#26739)
Julius Marminge8ff9ae1f87e2
diff --git a/apps/mobile/src/features/threads/pending-thread-feed.test.ts b/apps/mobile/src/features/threads/pending-thread-feed.test.tsindex 314dc1aa477..3d9463c79bd 100644--- a/apps/mobile/src/features/threads/pending-thread-feed.test.ts+++ b/apps/mobile/src/features/threads/pending-thread-feed.test.ts@@ -114,14 +114,17 @@ describe("pending timeline messages", () => {expect(appendPendingThreadMessages([], [delivered], [queued])).toEqual([]);});- it("stops showing an acknowledged message once the projection holds it, even when the feed hides it", () => {+ it("stops showing an acknowledged message once the thread catches up, even when the feed hides it", () => {// A rolled-back or cancelled queued run keeps its message in projection.messages// while its user_message item leaves the visible feed.const echoed = pending("rolled-back");- const waiting = pending("waiting");- const shown = selectPendingAcknowledgedMessages([echoed, waiting], {+ // A bounded projection pages an applied message out; it must not come back as pending.+ const pagedOut = { ...pending("paged-out"), sequence: 40 };+ const waiting = { ...pending("waiting"), sequence: 50 };+ const shown = selectPendingAcknowledgedMessages([echoed, pagedOut, waiting], {threadKey: "env:thread",queuedMessages: [],+ sequence: 45,projectedMessages: [{ id: echoed.messageId }],});expect(shown).toEqual([waiting]);diff --git a/apps/mobile/src/features/threads/pending-thread-feed.ts b/apps/mobile/src/features/threads/pending-thread-feed.tsindex 9eaf42dcee8..d38cc026fdd 100644--- a/apps/mobile/src/features/threads/pending-thread-feed.ts+++ b/apps/mobile/src/features/threads/pending-thread-feed.ts@@ -5,7 +5,11 @@ import {} from "@t3tools/contracts";import type { ThreadFeedEntry } from "../../lib/threadActivity";import { scopedThreadKey } from "../../lib/scopedEntities";-import type { QueuedThreadMessage } from "../../state/thread-outbox-model";+import { threadHasCaughtUpTo } from "@t3tools/client-runtime/state/threads";+import type {+ AcknowledgedThreadMessage,+ QueuedThreadMessage,+} from "../../state/thread-outbox-model";/*** 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 & {readonly acknowledged?: boolean;};-// An acknowledged row stops being pending once the projection holds its message,+// An acknowledged row stops being pending once the thread catches up to it,// even when the feed hides that message (a rolled-back or cancelled run).export function selectPendingAcknowledgedMessages(- acknowledged: ReadonlyArray<QueuedThreadMessage>,+ acknowledged: ReadonlyArray<AcknowledgedThreadMessage>,thread: {readonly threadKey: string | null;readonly queuedMessages: ReadonlyArray<QueuedThreadMessage>;+ readonly sequence: number;readonly projectedMessages: ReadonlyArray<{ readonly id: string }> | undefined;},-): ReadonlyArray<QueuedThreadMessage> {+): ReadonlyArray<AcknowledgedThreadMessage> {return acknowledged.filter((message) =>scopedThreadKey(message.environmentId, message.threadId) === thread.threadKey &&!thread.queuedMessages.some((queued) => queued.messageId === message.messageId) &&- !thread.projectedMessages?.some((projected) => projected.id === message.messageId),+ !threadHasCaughtUpTo(message, {+ sequence: thread.sequence,+ messages: thread.projectedMessages,+ }),);}diff --git a/apps/mobile/src/state/acknowledged-thread-messages.ts b/apps/mobile/src/state/acknowledged-thread-messages.tsindex ab9f26dd7d4..d7935d1debc 100644--- a/apps/mobile/src/state/acknowledged-thread-messages.ts+++ b/apps/mobile/src/state/acknowledged-thread-messages.ts@@ -1,31 +1,39 @@import * as Option from "effect/Option";import { Atom } from "effect/reactivity";import { appAtomRegistry } from "./atom-registry";-import type { QueuedThreadMessage } from "./thread-outbox-model";+import { threadHasCaughtUpTo } from "@t3tools/client-runtime/state/threads";+import type { AcknowledgedThreadMessage, QueuedThreadMessage } from "./thread-outbox-model";import { environmentThreadDetails } from "./threads";-// Keep acknowledged rows until their subscribed projection arrives; command receipts can precede messages.-// Render hides rows the projection has echoed, so dropping them here only frees memory.-export const acknowledgedThreadMessagesAtom = Atom.make<ReadonlyArray<QueuedThreadMessage>>(+// Keep acknowledged rows until the thread catches up; command receipts can precede messages.+export const acknowledgedThreadMessagesAtom = Atom.make<ReadonlyArray<AcknowledgedThreadMessage>>([],).pipe(Atom.keepAlive);// Peeks at a thread only when something already has it in the registry: reading// it through the registry would open a snapshot load and a live stream of its own.-function isEchoedInMountedThread(message: QueuedThreadMessage): boolean {- const threadAtom = environmentThreadDetails.threadAtom({+function isEchoedInMountedThread(message: AcknowledgedThreadMessage): boolean {+ const stateAtom = environmentThreadDetails.stateAtom({environmentId: message.environmentId,threadId: message.threadId,});- const node = appAtomRegistry.getNodes().get(threadAtom);+ const node = appAtomRegistry.getNodes().get(stateAtom);if (node === undefined) return false;- const loaded: Option.Option<Atom.Type<typeof threadAtom>> = node.valueOption();- const thread = Option.getOrNull(loaded);- return thread?.projection.messages.some((entry) => entry.id === message.messageId) ?? false;+ const loaded: Option.Option<Atom.Type<typeof stateAtom>> = node.valueOption();+ return Option.match(loaded, {+ onNone: () => false,+ onSome: (thread) =>+ threadHasCaughtUpTo(message, {+ sequence: thread.sequence,+ messages: Option.getOrUndefined(thread.data)?.messages,+ }),+ });}function writeAcknowledgedThreadMessages(- update: (current: ReadonlyArray<QueuedThreadMessage>) => ReadonlyArray<QueuedThreadMessage>,+ update: (+ current: ReadonlyArray<AcknowledgedThreadMessage>,+ ) => ReadonlyArray<AcknowledgedThreadMessage>,) {const current = appAtomRegistry.get(acknowledgedThreadMessagesAtom);const next = update(current).filter((entry) => !isEchoedInMountedThread(entry));@@ -35,7 +43,7 @@ function writeAcknowledgedThreadMessages(appAtomRegistry.set(acknowledgedThreadMessagesAtom, next);}-export function retainAcknowledgedThreadMessage(message: QueuedThreadMessage) {+export function retainAcknowledgedThreadMessage(message: AcknowledgedThreadMessage) {writeAcknowledgedThreadMessages((current) =>current.some((entry) => entry.messageId === message.messageId)? currentdiff --git a/apps/mobile/src/state/thread-outbox-model.ts b/apps/mobile/src/state/thread-outbox-model.tsindex 16f2de8f099..6c5da0db209 100644--- a/apps/mobile/src/state/thread-outbox-model.ts+++ b/apps/mobile/src/state/thread-outbox-model.ts@@ -287,3 +287,8 @@ export function resolveThreadOutboxFailureAction(input: {}return "restore";}++export type AcknowledgedThreadMessage = QueuedThreadMessage & {+ /** The server sequence that committed the message; older servers do not report it. */+ readonly sequence?: number;+};diff --git a/apps/mobile/src/state/thread-task-permissions.test.ts b/apps/mobile/src/state/thread-task-permissions.test.tsindex acfdd803d42..0b529e99478 100644--- a/apps/mobile/src/state/thread-task-permissions.test.ts+++ b/apps/mobile/src/state/thread-task-permissions.test.ts@@ -113,6 +113,7 @@ vi.mock("./threads", async () => {environmentThreadDetails: {queueWorkflowAtom: () => Atom.make(null),checkpointSummariesAtom: () => Atom.make([]),+ sequenceAtom: () => Atom.make(0),pendingRequestsAtom: () => Atom.make(state.pendingRequests),},threadEnvironment: {diff --git a/apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts b/apps/mobile/src/state/threadOutboxDelivery.permissions.test.tsindex edc80c50070..0ea64764e5d 100644--- a/apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts+++ b/apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts@@ -100,7 +100,7 @@ vi.mock("./threads", async () => {familyAtom: () => Atom.make(AsyncResult.success({})),refresh: vi.fn(),},- environmentThreadDetails: { threadAtom: () => Atom.make(null) },+ environmentThreadDetails: { stateAtom: () => Atom.make(null) },};});vi.mock("./git", () => ({ gitEnvironment: { preparePullRequestThread: state.checkout } }));@@ -224,6 +224,7 @@ beforeEach(() => {]) {command.mockReset().mockResolvedValue(AsyncResult.success(undefined));}+ state.start.mockResolvedValue(AsyncResult.success({}));state.prepare.mockReset().mockImplementation(async ({ attachments }) => ({status: "ready",attachments: [],@@ -427,7 +428,8 @@ describe("queued task operation access", () => {);await state.manager.enqueue(queued);const started = Promise.withResolvers<void>();- const delivery = Promise.withResolvers<AsyncResult.AsyncResult<void, Error>>();+ const delivery =+ Promise.withResolvers<AsyncResult.AsyncResult<{ readonly sequence?: number }, Error>>();state.start.mockImplementationOnce(() => {started.resolve();return delivery.promise;@@ -437,7 +439,7 @@ describe("queued task operation access", () => {setOperateGrant("secondary", false);delivery.resolve(accepted- ? AsyncResult.success(undefined)+ ? AsyncResult.success({}): AsyncResult.failure(Cause.fail(new Error("This connection cannot control this task."))),);await drained;diff --git a/apps/mobile/src/state/threadOutboxDelivery.test.ts b/apps/mobile/src/state/threadOutboxDelivery.test.tsindex 901ffaa9e82..d77ffe1942b 100644--- a/apps/mobile/src/state/threadOutboxDelivery.test.ts+++ b/apps/mobile/src/state/threadOutboxDelivery.test.ts@@ -13,9 +13,12 @@ import type { PreparedTurnAttachments } from "../lib/attachmentUpload";const harness = vi.hoisted(() => ({canOperate: true,- threadProjection: null as unknown as import("effect/reactivity").Atom.Writable<{- readonly projection: { readonly messages: ReadonlyArray<{ readonly id: string }> };- } | null>,+ threadState: null as unknown as import("effect/reactivity").Atom.Writable<{+ readonly data: import("effect/Option").Option<{+ readonly messages: ReadonlyArray<{ readonly id: string }>;+ }>;+ readonly sequence: number;+ }>,manager: null as unknown as ReturnType<typeof import("./thread-outbox-manager").createThreadOutboxManager>,@@ -92,12 +95,14 @@ vi.mock("./git", () => ({ gitEnvironment: {} }));vi.mock("./threads", async () => {const { Atom } = await import("effect/reactivity");- harness.threadProjection = Atom.make<{- readonly projection: { readonly messages: ReadonlyArray<{ readonly id: string }> };- } | null>(null).pipe(Atom.keepAlive);+ const Option = await import("effect/Option");+ harness.threadState = Atom.make({+ data: Option.none<{ readonly messages: ReadonlyArray<{ readonly id: string }> }>(),+ sequence: 0,+ }).pipe(Atom.keepAlive);return {threadEnvironment: {},- environmentThreadDetails: { threadAtom: () => harness.threadProjection },+ environmentThreadDetails: { stateAtom: () => harness.threadState },};});@@ -138,6 +143,7 @@ vi.mock("./thread-outbox", async () => {};});+import * as Option from "effect/Option";import { appAtomRegistry } from "./atom-registry";import { pendingThreadCreationOutcomesAtom } from "./pending-thread-creation";import { clearThreadComposerError, threadComposerErrorsAtom } from "./thread-composer-error";@@ -204,7 +210,7 @@ function remainingMessages(): ReadonlyArray<QueuedThreadMessage> {beforeEach(() => {appAtomRegistry.set(acknowledgedThreadMessagesAtom, []);- appAtomRegistry.set(harness.threadProjection, null);+ appAtomRegistry.set(harness.threadState, { data: Option.none(), sequence: 0 });harness.canOperate = true;harness.draftFile.setDocument({ schemaVersion: 1, drafts: {} });});@@ -330,26 +336,32 @@ describe("thread outbox attachment preparation", () => {});describe("thread outbox drain delivery cleanup", () => {- it("drops echoed acknowledged rows at the next delivery without subscribing to the thread", async () => {+ it("drops caught-up acknowledged rows at the next delivery without subscribing to the thread", async () => {const first = queuedMessage({ messageId: "awaiting-echo", text: "Delivered" });const second = queuedMessage({ messageId: "next-delivery", text: "Also delivered" });await harness.manager.enqueue(first);await harness.manager.enqueue(second);await expect(- completeQueuedMessageDelivery(first, harness.manager.revisionOf(first.messageId)),+ completeQueuedMessageDelivery(first, harness.manager.revisionOf(first.messageId), 7),).resolves.toBe("removed");- expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toEqual([first]);-- appAtomRegistry.set(harness.threadProjection, {- projection: { messages: [{ id: "unrelated" }, { id: first.messageId }] },+ expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toEqual([+ { ...first, sequence: 7 },+ ]);++ // The thread applied the message, but its bounded window does not hold it.+ appAtomRegistry.set(harness.threadState, {+ data: Option.some({ messages: [{ id: "unrelated" }] }),+ sequence: 7,});- expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toEqual([first]);+ expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toHaveLength(1);await expect(- completeQueuedMessageDelivery(second, harness.manager.revisionOf(second.messageId)),+ completeQueuedMessageDelivery(second, harness.manager.revisionOf(second.messageId), 9),).resolves.toBe("removed");- expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toEqual([second]);+ expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toEqual([+ { ...second, sequence: 9 },+ ]);});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", () => {harness.draftFile.setWriteError(new Error("Draft storage unavailable"));await expect(- completeQueuedMessageDelivery(message, harness.manager.revisionOf(message.messageId)),+ completeQueuedMessageDelivery(+ message,+ harness.manager.revisionOf(message.messageId),+ undefined,+ ),).resolves.toBe("removed");expect(remainingMessages()).toEqual([]);@@ -390,9 +406,9 @@ describe("thread outbox drain delivery cleanup", () => {).toEqual([message]);if (cleared) await harness.manager.clearEnvironment(message.environmentId);- await expect(completeQueuedMessageDelivery(message, deliveryRevision)).resolves.toBe(- cleared ? "edited" : "removed",- );+ await expect(+ completeQueuedMessageDelivery(message, deliveryRevision, undefined),+ ).resolves.toBe(cleared ? "edited" : "removed");appAtomRegistry.set(composerDrafts.composerCloudDraftsAtom, {accountId: null,@@ -412,7 +428,9 @@ describe("thread outbox drain delivery cleanup", () => {await harness.manager.update(edited);await composerDrafts.archiveCloudComposerDrafts("account-a", new Set([message.environmentId]));await harness.manager.clearEnvironment(message.environmentId);- await expect(completeQueuedMessageDelivery(message, deliveryRevision)).resolves.toBe("edited");+ await expect(completeQueuedMessageDelivery(message, deliveryRevision, undefined)).resolves.toBe(+ "edited",+ );await composerDrafts.restoreCloudComposerDrafts("account-a");expect(remainingMessages()).toEqual([edited]);});@@ -447,7 +465,9 @@ describe("thread outbox drain delivery cleanup", () => {const edited = { ...message, text: "edited while the turn delivered" };await harness.manager.update(edited);- await expect(completeQueuedMessageDelivery(message, deliveryRevision)).resolves.toBe("edited");+ await expect(completeQueuedMessageDelivery(message, deliveryRevision, undefined)).resolves.toBe(+ "edited",+ );expect(remainingMessages()).toEqual([edited]);expect(harness.removePersistedFile).not.toHaveBeenCalled();@@ -458,7 +478,9 @@ describe("thread outbox drain delivery cleanup", () => {await harness.manager.enqueue(message);const deliveryRevision = harness.manager.revisionOf(message.messageId);- await expect(completeQueuedMessageDelivery(message, deliveryRevision)).resolves.toBe("removed");+ await expect(completeQueuedMessageDelivery(message, deliveryRevision, undefined)).resolves.toBe(+ "removed",+ );expect(remainingMessages()).toEqual([]);expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toEqual([message]);@@ -479,7 +501,7 @@ describe("thread outbox drain delivery cleanup", () => {await harness.manager.enqueue(message);const deliveryRevision = harness.manager.revisionOf(message.messageId);- const cleanup = completeQueuedMessageDelivery(message, deliveryRevision);+ const cleanup = completeQueuedMessageDelivery(message, deliveryRevision, undefined);await removeStarted.promise;appAtomRegistry.set(editingQueuedMessageIdsAtom, { [message.messageId]: true });removeBarrier.resolve();diff --git a/apps/mobile/src/state/threadOutboxDelivery.ts b/apps/mobile/src/state/threadOutboxDelivery.tsindex 5ba633de634..4a20db3b9e9 100644--- a/apps/mobile/src/state/threadOutboxDelivery.ts+++ b/apps/mobile/src/state/threadOutboxDelivery.ts@@ -250,6 +250,7 @@ function isQueuedMessagePayloadCurrent(export async function completeQueuedMessageDelivery(queuedMessage: QueuedThreadMessage,deliveryRevision: number,+ sequence: number | undefined,): Promise<"removed" | "edited" | "failed"> {clearThreadComposerError(scopedThreadKey(queuedMessage.environmentId, queuedMessage.threadId),@@ -266,7 +267,9 @@ export async function completeQueuedMessageDelivery(if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) {return "edited";}- retainAcknowledgedThreadMessage(queuedMessage);+ retainAcknowledgedThreadMessage(+ sequence === undefined ? queuedMessage : { ...queuedMessage, sequence },+ );const removed = await removeThreadOutboxMessage(queuedMessage,deliveryRevision,@@ -616,6 +619,12 @@ const settledCreationOutcomeKeysAtom = Atom.make((get): ReadonlyArray<string> =>);}).pipe(Atom.withLabel("mobile:thread-outbox:settled-creation-outcomes"));+function deliveredSequence(+ result: AtomCommandResult<{ readonly sequence?: number }, unknown>,+): number | undefined {+ return AsyncResult.isSuccess(result) ? result.value.sequence : undefined;+}+const runDeliveryCommand = <W, A, E>(command: AtomCommand<W, A, E>,input: W,@@ -896,7 +905,11 @@ export function createThreadOutboxDelivery(): {}acknowledgedExistingThreadMessageIds.add(persistedMessage.messageId);const delivered =- (await completeQueuedMessageDelivery(persistedMessage, deliveryRevision)) === "removed";+ (await completeQueuedMessageDelivery(+ persistedMessage,+ deliveryRevision,+ deliveredSequence(deliveryResult),+ )) === "removed";if (delivered) {acknowledgedExistingThreadMessageIds.delete(persistedMessage.messageId);}@@ -1052,7 +1065,11 @@ export function createThreadOutboxDelivery(): {return restoreQueuedMessage(persistedMessage, failure.message);}recordPendingThreadCreationOutcome({ kind: "delivered", message: persistedMessage });- const outcome = await completeQueuedMessageDelivery(persistedMessage, deliveryRevision);+ const outcome = await completeQueuedMessageDelivery(+ persistedMessage,+ deliveryRevision,+ deliveredSequence(deliveryResult),+ );if (outcome === "edited") {if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) {return true;diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.tsindex 45f06e198f4..4c14fb56254 100644--- a/apps/mobile/src/state/use-thread-composer-state.ts+++ b/apps/mobile/src/state/use-thread-composer-state.ts@@ -110,6 +110,7 @@ const EMPTY_QUEUE_WORKFLOW_ATOM = Atom.make<null>(null).pipe(Atom.withLabel("mobile-thread-queue-workflow:empty"),);const EMPTY_CHECKPOINT_SUMMARIES_ATOM = Atom.make<ReadonlyArray<ThreadCheckpointSummary>>([]);+const EMPTY_THREAD_SEQUENCE_ATOM = Atom.make(0);export function appendReviewCommentToDraft(input: {readonly environmentId: EnvironmentId;@@ -227,6 +228,11 @@ export function useThreadComposerState() {const selectedThreadMessages = selectedThreadProjection?.projection.messages;const selectedThreadAttempts = selectedThreadProjection?.projection.attempts;const selectedThreadNodes = selectedThreadProjection?.projection.nodes;+ const selectedThreadSequence = useAtomValue(+ selectedThreadDetailRef === null+ ? EMPTY_THREAD_SEQUENCE_ATOM+ : environmentThreadDetails.sequenceAtom(selectedThreadDetailRef),+ );const checkpointSummaries = useAtomValue(selectedThreadDetailRef === null? EMPTY_CHECKPOINT_SUMMARIES_ATOM@@ -254,6 +260,7 @@ export function useThreadComposerState() {const pendingAcknowledgments = selectPendingAcknowledgedMessages(acknowledgedMessages, {threadKey: selectedThreadKey,queuedMessages: selectedThreadQueuedMessages,+ sequence: selectedThreadSequence,projectedMessages: selectedThreadMessages,});if (pendingAcknowledgments.length === 0) return feed;diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.tsindex 88fc87d3bc0..ea1669f4b7d 100644--- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts+++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts@@ -1380,6 +1380,9 @@ it.effect("replays a server-allocated launch", () =>assert.equal(first.threadId, retry.threadId);assert.isFalse(first.resumed);assert.isTrue(retry.resumed);+ // Clients drop their pending copy once the thread reaches the message's commit.+ assert.isNumber(first.sequence);+ assert.equal(retry.sequence, first.sequence);assert.equal(harness.runSetup.mock.calls.length, 1);assert.equal(retry.projection.messages.length, 1);assert.equal(retry.projection.runs.length, 1);diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.tsindex 289df535c12..7a45a54a312 100644--- a/apps/server/src/orchestration-v2/ThreadLaunchService.ts+++ b/apps/server/src/orchestration-v2/ThreadLaunchService.ts@@ -123,6 +123,7 @@ export interface ThreadLaunchResult {readonly projection: OrchestrationV2ThreadProjection;/** The launch's last write (the initial message, else the thread claim) was accepted before this call. */readonly resumed: boolean;+ readonly sequence?: number;}export class ThreadLaunchError extends Schema.TaggedError<ThreadLaunchError>()(@@ -941,6 +942,7 @@ const make = Effect.gen(function* () {return yield* mapError(input, "resolve-project", threadId)("Project identity changed.");}let runId: RunId | null = null;+ let messageSequence: number | undefined;let messageWasAlreadyAccepted = false;if (input.initialMessage !== undefined) {const messageCommandId = CommandId.make(`${input.commandId}:initial-message`);@@ -987,6 +989,7 @@ const make = Effect.gen(function* () {);// A concurrent retry can read no receipt and still replay the dispatch.messageWasAlreadyAccepted ||= dispatched.replayed === true;+ messageSequence = dispatched.sequence;const runCreated = dispatched.storedEvents.find((stored) => stored.event.type === "run.created",);@@ -1053,6 +1056,7 @@ const make = Effect.gen(function* () {input.initialMessage === undefined? Option.isSome(launchReceipt) || claimed.replayed === true: messageWasAlreadyAccepted,+ ...(messageSequence === undefined ? {} : { sequence: messageSequence }),};});},diff --git a/packages/client-runtime/src/operations/commands.performance.test.ts b/packages/client-runtime/src/operations/commands.performance.test.tsindex 2378407c2df..d4be3f1a9f4 100644--- a/packages/client-runtime/src/operations/commands.performance.test.ts+++ b/packages/client-runtime/src/operations/commands.performance.test.ts@@ -223,7 +223,7 @@ describe("routine command transport budget", () => {if (command.type !== "message.dispatch") {throw new Error(`Expected message.dispatch, received ${command.type}`);}- if (!("sequence" in receipt)) {+ if ("projection" in receipt) {throw new Error("Expected a dispatch receipt");}const { deliveryIntent: _deliveryIntent, ...formerCommand } = command;diff --git a/packages/client-runtime/src/state/threadDetail.ts b/packages/client-runtime/src/state/threadDetail.tsindex 0c938003787..e1f30998cae 100644--- a/packages/client-runtime/src/state/threadDetail.ts+++ b/packages/client-runtime/src/state/threadDetail.ts@@ -409,6 +409,12 @@ export function createEnvironmentThreadDetailAtoms<E>(Atom.withLabel(`environment-thread-status:${key}`),),);+ const sequenceAtomFamily = Atom.family((key: string) =>+ Atom.make((get) => get(threadStateValueAtomFamily(key)).sequence).pipe(+ Atom.setIdleTTL(0),+ Atom.withLabel(`environment-thread-sequence:${key}`),+ ),+ );const errorAtomFamily = Atom.family((key: string) =>Atom.make((get) => Option.getOrNull(get(threadStateValueAtomFamily(key)).error)).pipe(Atom.setIdleTTL(0),@@ -439,6 +445,7 @@ export function createEnvironmentThreadDetailAtoms<E>(quietVisibleTurnItemsAtom: (ref: ScopedThreadRef) =>quietVisibleTurnItemsAtomFamily(threadKey(ref)),statusAtom: (ref: ScopedThreadRef) => statusAtomFamily(threadKey(ref)),+ sequenceAtom: (ref: ScopedThreadRef) => sequenceAtomFamily(threadKey(ref)),errorAtom: (ref: ScopedThreadRef) => errorAtomFamily(threadKey(ref)),historyAtom: (ref: ScopedThreadRef) => historyAtomFamily(threadKey(ref)),};diff --git a/packages/client-runtime/src/state/threadState.ts b/packages/client-runtime/src/state/threadState.tsindex 67b227089ab..3b53b68b2f4 100644--- a/packages/client-runtime/src/state/threadState.ts+++ b/packages/client-runtime/src/state/threadState.ts@@ -14,6 +14,8 @@ export interface EnvironmentThreadState {* disconnect path.*/readonly history: ThreadHistoryMeta;+ /** The last server sequence `data` reflects, so readers can tell a write has landed without searching paged-out history. */+ readonly sequence: number;}export const EMPTY_ENVIRONMENT_THREAD_STATE: EnvironmentThreadState = {@@ -21,4 +23,21 @@ export const EMPTY_ENVIRONMENT_THREAD_STATE: EnvironmentThreadState = {status: "empty",error: Option.none(),history: EMPTY_THREAD_HISTORY_META,+ sequence: 0,};++/**+ * A thread holds a write once it has applied the write's commit sequence. A bounded+ * projection can page the message out later, so finding it is only a fallback for+ * servers that do not report the sequence.+ */+export function threadHasCaughtUpTo(+ write: { readonly messageId: string; readonly sequence?: number | undefined },+ thread: {+ readonly sequence: number;+ readonly messages: ReadonlyArray<{ readonly id: string }> | undefined;+ },+): boolean {+ if (write.sequence !== undefined && thread.sequence >= write.sequence) return true;+ return thread.messages?.some((entry) => entry.id === write.messageId) ?? false;+}diff --git a/packages/client-runtime/src/state/threads-sync.test.ts b/packages/client-runtime/src/state/threads-sync.test.tsindex c8c212db41c..eaf1751a1c2 100644--- a/packages/client-runtime/src/state/threads-sync.test.ts+++ b/packages/client-runtime/src/state/threads-sync.test.ts@@ -678,7 +678,7 @@ describe("EnvironmentThreads", () => {const harness = yield* makeHarness({ cached: BASE_PROJECTION });yield* Queue.offer(harness.inputs, titleUpdated("Live title", CACHED_SNAPSHOT_SEQUENCE + 1));- yield* awaitThreadState(+ const live = yield* awaitThreadState(harness.observed,(value) =>value.status === "live" &&@@ -686,6 +686,8 @@ describe("EnvironmentThreads", () => {value.data.value.thread.title === "Live title",);+ // Readers compare this to a command's commit sequence; it moves with the data it describes.+ expect(live.sequence).toBe(CACHED_SNAPSHOT_SEQUENCE + 1);expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(CACHED_SNAPSHOT_SEQUENCE);expect(yield* Ref.get(harness.loaderCalls)).toBe(0);}),@@ -1288,6 +1290,7 @@ describe("EnvironmentThreads", () => {status: "cached",error: Option.none(),history: { ...EMPTY_THREAD_HISTORY_META, historyCursor: null, expanded: true },+ sequence: CACHED_SNAPSHOT_SEQUENCE,},sequence: CACHED_SNAPSHOT_SEQUENCE,persisted: true,diff --git a/packages/client-runtime/src/state/threads.ts b/packages/client-runtime/src/state/threads.tsindex 3cb4192f0ab..c7b22d9dcdf 100644--- a/packages/client-runtime/src/state/threads.ts+++ b/packages/client-runtime/src/state/threads.ts@@ -224,6 +224,11 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make): Option.none<OrchestrationV2ThreadDetailSnapshot>();const cachedThread = Option.map(cached, (snapshot) => snapshot.projection);+ // Seed the resume cursor from the cached snapshot so a warm cache can catch up+ // via `afterSequence` instead of re-downloading the full thread body.+ const initialSequence =+ retained?.sequence ??+ Option.match(cached, { onNone: () => 0, onSome: (snapshot) => snapshot.snapshotSequence });const initialState: EnvironmentThreadState = retained? cachedThreadState(retained.state): {@@ -234,15 +239,11 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.makeonNone: () => EMPTY_THREAD_HISTORY_META,onSome: historyMetaFromCachedSnapshot,}),+ sequence: initialSequence,};const state = yield* SubscriptionRef.make(initialState);const canLoadHistory = Option.isSome(httpClient) && Option.isSome(historyController);const acceptsBoundedSocketSnapshots = yield* Ref.make(canLoadHistory);- // Seed the resume cursor from the cached snapshot so a warm cache can catch up- // via `afterSequence` instead of re-downloading the full thread body.- const initialSequence =- retained?.sequence ??- Option.match(cached, { onNone: () => 0, onSome: (snapshot) => snapshot.snapshotSequence });const lastSequence = yield* SubscriptionRef.make(initialSequence);let committed: ThreadResumeSnapshot = {state: initialState,@@ -400,6 +401,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make},) {const waiting = yield* Ref.get(awaitingCompletion);+ const sequence = yield* SubscriptionRef.get(lastSequence);// Atomic with concurrent history meta updates: never get-then-set the whole// state when only the projection changes. Bounded installs pass history so// projection + cursor persist together in one enqueue.@@ -420,6 +422,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make: ("live" as const),error: previous.error,history,+ sequence,};});// Active projections can update many times per second and retain large tool@@ -451,6 +454,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.makestatus: "deleted",error: Option.none(),history: EMPTY_THREAD_HISTORY_META,+ sequence: yield* SubscriptionRef.get(lastSequence),});yield* remember;if (resumeCache !== undefined && resumeCache.owner !== owner) return;@@ -571,7 +575,8 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.makeif (applied._tag !== "noop") result = applied;if (applied._tag === "delete") break;}- return [result, current];+ // A batch that changed nothing keeps its state object, so readers do not re-render.+ return [result, result._tag === "noop" ? current : { ...current, sequence }];},);@@ -796,7 +801,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make),);if (result._tag !== "loaded") return result;- if (complete) yield* remember;+ if (complete) yield* applyLock.withPermits(1)(remember);nextCursor = keepPaging ? page.nextCursor : null;}if (nextCursor === null) return { _tag: "loaded" } as const;diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.tsindex a1dd871205b..498f81a0e84 100644--- a/packages/contracts/src/orchestrationV2.ts+++ b/packages/contracts/src/orchestrationV2.ts@@ -3573,6 +3573,8 @@ export const OrchestrationV2ThreadLaunchResult = Schema.Struct({threadId: ThreadId,projection: OrchestrationV2ThreadProjection,resumed: Schema.Boolean,+ /** The initial message's commit sequence. Older servers omit it. */+ sequence: Schema.optionalKey(NonNegativeInt),});export type OrchestrationV2ThreadLaunchResult = typeof OrchestrationV2ThreadLaunchResult.Type;