From 5bfadbf3fa8f8ab7e693ba963cdf1e5b7e2be309 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 24 Oct 2026 22:39:23 +0000 Subject: [PATCH 1/6] test(client-runtime): takeover tests for #19570, failed resume reloads the snapshot Takeover tests for pingdotgg/t3code#19570. When a resumed thread replay dies, the thread must reload the full snapshot instead of staying on Syncing messages, and must show an error if that snapshot also dies. Both tests fail on main; the implementation follows separately. Co-Authored-By: Claude Opus 5.5 --- .../src/state/threads-sync.test.ts | 62 ++++++++++++++++++- 1 file changed, 60 insertions(+), 2 deletions(-) diff --git a/packages/client-runtime/src/state/threads-sync.test.ts b/packages/client-runtime/src/state/threads-sync.test.ts index a772eaaf76c2..b5189d6bea5b 100644 --- a/packages/client-runtime/src/state/threads-sync.test.ts +++ b/packages/client-runtime/src/state/threads-sync.test.ts @@ -69,7 +69,15 @@ const BASE_PROJECTION: OrchestrationV2ThreadProjection = { thread: { ...v2Projection.thread, title: "Cached thread" }, }; -type TestThreadInput = OrchestrationV2ThreadStreamItem | Error; +/** Ends the stream with a defect, like a chunk the client cannot decode. */ +class TestStreamDefect { + readonly message: string; + constructor(message: string) { + this.message = message; + } +} + +type TestThreadInput = OrchestrationV2ThreadStreamItem | Error | TestStreamDefect; function testSession( client: WsRpcProtocolClient, @@ -123,6 +131,7 @@ const makeHarness = Effect.fn("TestEnvironmentThreads.makeHarness")(function* (o const latest = yield* Ref.make(EMPTY_ENVIRONMENT_THREAD_STATE); const retryCount = yield* Ref.make(0); const subscriptionCount = yield* Ref.make(0); + const subscriptions = yield* Queue.unbounded(); const loaderCalls = yield* Ref.make(0); const lastSubscribeAfterSequence = yield* Ref.make(undefined); const lastRequestCompletionMarker = yield* Ref.make(false); @@ -137,7 +146,11 @@ const makeHarness = Effect.fn("TestEnvironmentThreads.makeHarness")(function* (o const streamFrom = (queue: Queue.Queue) => Stream.fromQueue(queue).pipe( Stream.mapEffect((input) => - input instanceof Error ? Effect.fail(input) : Effect.succeed(input), + input instanceof Error + ? Effect.fail(input) + : input instanceof TestStreamDefect + ? Effect.die(new Error(input.message)) + : Effect.succeed(input), ), ); const client = { @@ -155,6 +168,7 @@ const makeHarness = Effect.fn("TestEnvironmentThreads.makeHarness")(function* (o ), Effect.andThen(Ref.set(lastAcceptBoundedSnapshot, input.acceptBoundedSnapshot)), Effect.andThen(Ref.set(lastAcceptCompactTurnItems, input.acceptCompactTurnItems)), + Effect.andThen(Queue.offer(subscriptions, input.afterSequence)), Effect.as(streamFrom(inputs)), ), ), @@ -269,6 +283,7 @@ const makeHarness = Effect.fn("TestEnvironmentThreads.makeHarness")(function* (o latest, retryCount, subscriptionCount, + subscriptions, loaderCalls, lastSubscribeAfterSequence, lastRequestCompletionMarker, @@ -1703,6 +1718,49 @@ describe("EnvironmentThreads", () => { }), ); + it.effect("reloads the snapshot without an error when a resumed replay hits a defect", () => + Effect.gen(function* () { + const harness = yield* makeHarness({ cached: BASE_PROJECTION, completionMarker: true }); + expect(yield* Queue.take(harness.subscriptions)).toBe(CACHED_SNAPSHOT_SEQUENCE); + + yield* Queue.offer(harness.inputs, new TestStreamDefect("Replayed event did not decode")); + expect(yield* Queue.take(harness.subscriptions)).toBeUndefined(); + yield* Queue.offerAll(harness.inputs, [ + snapshot( + { ...BASE_PROJECTION, thread: { ...BASE_PROJECTION.thread, title: "Reloaded thread" } }, + CACHED_SNAPSHOT_SEQUENCE + 5, + ), + synchronized(), + ]); + const live = yield* awaitThreadState(harness.observed, (value) => { + expect(Option.isNone(value.error)).toBe(true); + return value.status === "live"; + }); + expect(Option.getOrThrow(live.data).thread.title).toBe("Reloaded thread"); + + // The reload moved the cursor past the event that broke the resume. + yield* harness.replaceSession; + expect(yield* Queue.take(harness.subscriptions)).toBe(CACHED_SNAPSHOT_SEQUENCE + 5); + }), + ); + + it.effect("shows an error when the snapshot reload after a failed resume hits a defect", () => + Effect.gen(function* () { + const harness = yield* makeHarness({ cached: BASE_PROJECTION, completionMarker: true }); + expect(yield* Queue.take(harness.subscriptions)).toBe(CACHED_SNAPSHOT_SEQUENCE); + yield* Queue.offer(harness.inputs, new TestStreamDefect("Replayed event did not decode")); + expect(yield* Queue.take(harness.subscriptions)).toBeUndefined(); + + yield* Queue.offer(harness.inputs, new TestStreamDefect("Snapshot did not decode")); + const failed = yield* awaitThreadState(harness.observed, (value) => + Option.isSome(value.error), + ); + expect(Option.getOrThrow(failed.error)).toBe("Could not synchronize the thread."); + expect(failed.data).toEqual(Option.some(BASE_PROJECTION)); + expect(yield* Queue.size(harness.subscriptions)).toBe(0); + }), + ); + it.effect("keeps replayed updates synchronizing until the completion marker arrives", () => Effect.gen(function* () { const harness = yield* makeHarness({ cached: BASE_PROJECTION, completionMarker: true }); From baeec8bd987d740e1bb92e6f482416fd7d49d69f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 24 Oct 2026 22:43:32 +0000 Subject: [PATCH 2/6] fix(client-runtime): a failed thread resume reloads the full snapshot When the replay after a saved cursor died, the thread stayed on "Syncing messages" and every later attempt, including a relaunch, asked for the same broken replay. A resume that dies now retries as a full snapshot, which moves the cursor past the bad event. The snapshot request holds until a snapshot applies, so an expected failure or a new session during the reload does not return to the broken cursor. A defect on that snapshot reports the error and stays terminal, so recovery cannot loop. Expected, transport, and interrupt handling are unchanged. Refs pingdotgg/t3code#19563. Based on the original work by @shivamhwp. Co-Authored-By: Claude Opus 5.5 --- .../src/state/threads-sync.test.ts | 23 +++++++++++ packages/client-runtime/src/state/threads.ts | 38 +++++++++++++++++-- 2 files changed, 58 insertions(+), 3 deletions(-) diff --git a/packages/client-runtime/src/state/threads-sync.test.ts b/packages/client-runtime/src/state/threads-sync.test.ts index b5189d6bea5b..ad36b3292605 100644 --- a/packages/client-runtime/src/state/threads-sync.test.ts +++ b/packages/client-runtime/src/state/threads-sync.test.ts @@ -1744,6 +1744,29 @@ describe("EnvironmentThreads", () => { }), ); + it.effect("keeps reloading the snapshot when the reload after a failed resume fails", () => + Effect.gen(function* () { + const harness = yield* makeHarness({ cached: BASE_PROJECTION, completionMarker: true }); + expect(yield* Queue.take(harness.subscriptions)).toBe(CACHED_SNAPSHOT_SEQUENCE); + yield* Queue.offer(harness.inputs, new TestStreamDefect("Replayed event did not decode")); + expect(yield* Queue.take(harness.subscriptions)).toBeUndefined(); + + // The expected-failure retry must not go back to the cursor that died. + yield* Queue.offer(harness.inputs, new Error("Snapshot timed out")); + yield* awaitThreadState(harness.observed, (value) => Option.isSome(value.error)); + yield* TestClock.adjust("250 millis"); + expect(yield* Queue.take(harness.subscriptions)).toBeUndefined(); + + yield* Queue.offerAll(harness.inputs, [ + snapshot(BASE_PROJECTION, CACHED_SNAPSHOT_SEQUENCE + 5), + synchronized(), + ]); + yield* awaitThreadState(harness.observed, (value) => value.status === "live"); + yield* harness.replaceSession; + expect(yield* Queue.take(harness.subscriptions)).toBe(CACHED_SNAPSHOT_SEQUENCE + 5); + }), + ); + it.effect("shows an error when the snapshot reload after a failed resume hits a defect", () => Effect.gen(function* () { const harness = yield* makeHarness({ cached: BASE_PROJECTION, completionMarker: true }); diff --git a/packages/client-runtime/src/state/threads.ts b/packages/client-runtime/src/state/threads.ts index 31985507aac1..c98085a47e91 100644 --- a/packages/client-runtime/src/state/threads.ts +++ b/packages/client-runtime/src/state/threads.ts @@ -251,6 +251,15 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make }; if (resumeCache?.owner === owner) resumeCache.snapshot = committed; const awaitingCompletion = yield* Ref.make(false); + // A resume replays the events after the held cursor. When that replay dies + // (an event this client cannot decode), the same cursor dies the same way on + // every attempt, including after a relaunch from the saved cache. Retry it + // with the full snapshot, which moves the cursor past it. forceSnapshot holds + // until a snapshot applies, so an expected-failure retry or a replacement + // session during the reload does not go back to the broken cursor. + const resuming = yield* Ref.make(false); + const resumeDied = yield* Ref.make(false); + const forceSnapshot = yield* Ref.make(false); const applyLock = yield* Semaphore.make(1); // Save only completed data/cursor updates. A canceled scope must not cache // a cursor whose event has not reached the data yet. @@ -597,6 +606,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make } if (item.kind === "snapshot") { + yield* Ref.set(forceSnapshot, false); yield* SubscriptionRef.set(lastSequence, item.snapshotSequence); const hasProgressiveHistory = item.historyCursor !== undefined || @@ -946,7 +956,8 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make } const sequence = yield* SubscriptionRef.get(lastSequence); - const canResume = Option.isSome(current.data); + const canResume = Option.isSome(current.data) && !(yield* Ref.get(forceSnapshot)); + yield* Ref.set(resuming, canResume); const acceptBoundedSnapshot = yield* Ref.get(acceptsBoundedSocketSnapshots); if (!supportsCompletionMarker && canResume) { yield* SubscriptionRef.update(state, (value) => ({ @@ -966,12 +977,33 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make }; }), { - onDefect: () => setStreamError("Could not synchronize the thread."), + // Classified here rather than after the stream fails: switchMap can + // buffer the failure past a replacement session's makeInput. + onDefect: Effect.fn("EnvironmentThreadState.onSubscriptionDefect")(function* (cause) { + if (Cause.hasDies(cause) && (yield* Ref.get(resuming))) { + yield* Ref.set(resumeDied, true); + } else { + yield* setStreamError("Could not synchronize the thread."); + } + }), onExpectedFailure: (cause) => setStreamError(formatThreadError(cause)), retryExpectedFailureAfter: "250 millis", resubscribe: foregroundResubscriptions, }, - ).pipe(Stream.runForEachArray(applyItems)), + ).pipe( + Stream.runForEachArray(applyItems), + Effect.as(false), + // A defect on the snapshot attempt reports its error and stays terminal, + // so recovery cannot loop. + Effect.catchCause((cause) => + Ref.getAndSet(resumeDied, false).pipe( + Effect.flatMap((died) => + died ? Ref.set(forceSnapshot, true).pipe(Effect.as(true)) : Effect.failCause(cause), + ), + ), + ), + Effect.repeat({ while: (retry) => retry }), + ), ); return state; From 37717c61422400fd1196338211a80f49f6ac649e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 24 Oct 2026 22:55:46 +0000 Subject: [PATCH 3/6] fix(client): a thread that cannot sync shows the error and retries on reconnect A thread whose subscription hit a defect kept its cached messages but showed "Syncing messages" forever, and the subscription ended, so reconnecting could not recover it. Web and mobile now show "Could not sync messages" over the cached conversation. The subscription waits for a new session or a foreground wakeup and tries once more; a resume that already failed retries from the snapshot. Tapping the mobile status reconnects. Refs pingdotgg/t3code#19563. Co-Authored-By: Claude Opus 5.5 --- .../features/threads/ThreadDetailScreen.tsx | 34 +++++++-------- .../features/threads/ThreadRouteScreen.tsx | 3 ++ .../threads/floating-working-status.test.ts | 19 +++++++++ .../threads/floating-working-status.ts | 40 ++++++++++++++++++ apps/web/src/components/ChatView.tsx | 8 +++- .../chat/ComposerActivityStatus.tsx | 6 ++- apps/web/src/state/entities.ts | 9 ++++ apps/web/src/threadSync.test.ts | 24 +++++++++++ apps/web/src/threadSync.ts | 13 +++++- .../src/state/threads-sync.test.ts | 42 ++++++++++++------- packages/client-runtime/src/state/threads.ts | 30 +++++++++---- 11 files changed, 182 insertions(+), 46 deletions(-) create mode 100644 apps/mobile/src/features/threads/floating-working-status.test.ts create mode 100644 apps/web/src/threadSync.test.ts diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index 83fd54f2ac04..16aa3cdf6486 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -172,7 +172,12 @@ import { FLOATING_WORKING_CONTROL_COVERAGE, FloatingWorkingControl, } from "./floating-working-control"; -import { connectionFloatingStatus, type FloatingWorkingStatus } from "./floating-working-status"; +import { + connectionFloatingStatus, + resolveThreadSyncPhase, + threadSyncFloatingStatus, + type FloatingWorkingStatus, +} from "./floating-working-status"; import { derivePendingUserInputMaxHeight, ESTIMATED_KEYBOARD_HEIGHT, @@ -245,6 +250,7 @@ export interface ThreadDetailScreenProps { readonly respondingUserInputId: RuntimeRequestId | null; readonly connectionStateLabel: EnvironmentConnectionPhase; readonly threadSyncStatus?: EnvironmentThreadStatus; + readonly threadSyncError?: string | null; readonly historyControls?: ThreadFeedHistoryControls; readonly activeThreadBusy: boolean; readonly canStopThread: boolean; @@ -635,20 +641,14 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai ); const composerKeyboardOffset = composerBottomInset; const contentPresentationKind = props.contentPresentation.kind; - const realThreadSyncLabel = (() => { - switch (props.threadSyncStatus) { - case "empty": - case "cached": - case "synchronizing": - if (contentPresentationKind === "ready") { - return "Syncing messages..."; - } - return contentPresentationKind === "loading" ? "Loading messages..." : null; - default: - return null; - } - })(); - const threadSyncLabel = useDelayedStatus(selectedThreadKey, realThreadSyncLabel); + const threadSyncPhase = useDelayedStatus( + selectedThreadKey, + resolveThreadSyncPhase({ + status: props.threadSyncStatus, + hasError: (props.threadSyncError ?? null) !== null, + contentKind: contentPresentationKind, + }), + ); const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, { reportFailure: false, }); @@ -765,8 +765,8 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai if (props.creationState?.kind === "failed") { return null; } - if (threadSyncLabel !== null) { - return { kind: "syncing", label: threadSyncLabel }; + if (threadSyncPhase !== null) { + return threadSyncFloatingStatus(threadSyncPhase, props.onReconnectEnvironment); } const childInput = childThreadInputs[0]; if (childInput && contentPresentationKind === "ready") { diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx index 256a8b13b73d..2bfd8a115b75 100644 --- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx @@ -974,6 +974,9 @@ function ThreadRouteContent( respondingUserInputId={requests.respondingUserInputId} connectionStateLabel={routeConnectionState} threadSyncStatus={selectedThreadDetailState.status} + threadSyncError={ + creationState === null ? Option.getOrNull(selectedThreadDetailState.error) : null + } historyControls={historyControls} activeThreadBusy={composer.activeThreadBusy} canStopThread={awaitingBootstrapTurn || composer.interruptibleRunId !== null} diff --git a/apps/mobile/src/features/threads/floating-working-status.test.ts b/apps/mobile/src/features/threads/floating-working-status.test.ts new file mode 100644 index 000000000000..2e397fc72c44 --- /dev/null +++ b/apps/mobile/src/features/threads/floating-working-status.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { resolveThreadSyncPhase, threadSyncFloatingStatus } from "./floating-working-status"; + +describe("thread sync status", () => { + it("shows a failure instead of syncing over cached messages", () => { + expect(resolveThreadSyncPhase({ status: "cached", hasError: true, contentKind: "ready" })).toBe( + "failed", + ); + expect(threadSyncFloatingStatus("failed", () => {})).toMatchObject({ + kind: "connection", + tone: "unavailable", + label: "Could not sync messages", + }); + expect( + resolveThreadSyncPhase({ status: "cached", hasError: false, contentKind: "ready" }), + ).toBe("syncing"); + }); +}); diff --git a/apps/mobile/src/features/threads/floating-working-status.ts b/apps/mobile/src/features/threads/floating-working-status.ts index 264d110f75f7..a73104a98110 100644 --- a/apps/mobile/src/features/threads/floating-working-status.ts +++ b/apps/mobile/src/features/threads/floating-working-status.ts @@ -1,4 +1,7 @@ import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection"; +import type { EnvironmentThreadStatus } from "@t3tools/client-runtime/state/threads"; + +import type { ThreadContentPresentation } from "./threadContentPresentation"; export interface FloatingStatusAction { readonly label: string; @@ -82,3 +85,40 @@ export function connectionFloatingStatus(input: { return null; } } + +export type ThreadSyncPhase = "loading" | "syncing" | "failed"; + +export function resolveThreadSyncPhase(input: { + readonly status: EnvironmentThreadStatus | undefined; + readonly hasError: boolean; + readonly contentKind: ThreadContentPresentation["kind"]; +}): ThreadSyncPhase | null { + switch (input.status) { + case "empty": + case "cached": + case "synchronizing": + if (input.contentKind === "ready") return input.hasError ? "failed" : "syncing"; + return input.contentKind === "loading" ? "loading" : null; + default: + return null; + } +} + +export function threadSyncFloatingStatus( + phase: ThreadSyncPhase, + onRetry: () => void, +): FloatingWorkingStatus { + switch (phase) { + case "loading": + return { kind: "syncing", label: "Loading messages..." }; + case "syncing": + return { kind: "syncing", label: "Syncing messages..." }; + case "failed": + return { + kind: "connection", + tone: "unavailable", + label: "Could not sync messages", + onPress: onRetry, + }; + } +} diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 6252b087abe4..a685a9f0aa61 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -239,6 +239,7 @@ import { useThreadUpdatedAt, useThreadLastVisitedAt, useQuietThreadVisibleTurnItems, + useThreadError, useThreadStatus, useThreadHistory, useQuietThreadShell, @@ -494,12 +495,15 @@ export default function ChatView(props: ChatViewProps) { ? deriveReportedModelSelection(serverProjection) : null; const threadStatus = useThreadStatus(routeThreadDetailRef); + const threadSyncError = useThreadError(routeThreadDetailRef); const threadSyncPhase = resolveThreadSyncPhase({ detailExists: serverProjection !== null, shellExists: serverThread !== null, status: threadStatus, + hasError: threadSyncError !== null, }); const threadDetailLoading = threadSyncPhase === "loading"; + const threadSyncing = threadSyncPhase === "loading" || threadSyncPhase === "syncing"; const activeProviderThread = serverProjection?.providerThreads.find( (thread) => thread.id === serverProjection.thread.activeProviderThreadId, ); @@ -1505,7 +1509,7 @@ export default function ChatView(props: ChatViewProps) { ); const timelineEmpty = timelineEntries.length === 0 && !hasStreamedTimelineRows; const displayedTimeline = resolveThreadSwitchTimeline({ - loading: timelineEmpty && threadSyncPhase !== null, + loading: timelineEmpty && threadSyncing, activeThreadKey, nextEntries: timelineEntries, rememberedForActive: peekRememberedThreadTimeline(activeThreadKey), @@ -3257,7 +3261,7 @@ export default function ChatView(props: ChatViewProps) { entriesInput={timelineEntriesInput} draftEntries={isServerThread ? null : draftTimelineEntries} activeThreadKey={activeThreadKey} - syncing={threadSyncPhase !== null} + syncing={threadSyncing} detailLoading={threadDetailLoading} readyMarkdownCwd={gitCwd} readyWorkspaceRoot={activeWorkspaceRoot ?? null} diff --git a/apps/web/src/components/chat/ComposerActivityStatus.tsx b/apps/web/src/components/chat/ComposerActivityStatus.tsx index 7a8b83ae7366..6ae4431098f0 100644 --- a/apps/web/src/components/chat/ComposerActivityStatus.tsx +++ b/apps/web/src/components/chat/ComposerActivityStatus.tsx @@ -1,3 +1,5 @@ +import { CircleAlertIcon } from "lucide-react"; + import { Spinner } from "~/components/ui/spinner"; import { threadSyncLabel, type ThreadSyncPhase } from "../../threadSync"; @@ -7,13 +9,13 @@ export function ComposerActivityRow({ phase }: { readonly phase: ThreadSyncPhase return ( - + {phase === "failed" ? : } {threadSyncLabel(phase)} diff --git a/apps/web/src/state/entities.ts b/apps/web/src/state/entities.ts index e88422aa54e1..b8a36d2862f0 100644 --- a/apps/web/src/state/entities.ts +++ b/apps/web/src/state/entities.ts @@ -68,6 +68,9 @@ const EMPTY_CHECKPOINT_SUMMARIES_ATOM = Atom.make(null).pipe( Atom.withLabel("web-thread-last-visited:empty"), ); +const EMPTY_THREAD_ERROR_ATOM = Atom.make(null).pipe( + Atom.withLabel("web-thread-error:empty"), +); const EMPTY_UPDATED_AT_ATOM = Atom.make(null).pipe( Atom.withLabel("web-thread-updated-at:empty"), ); @@ -194,6 +197,12 @@ export function useThreadStatus(ref: ScopedThreadRef | null): EnvironmentThreadS ); } +export function useThreadError(ref: ScopedThreadRef | null): string | null { + return useAtomValue( + ref === null ? EMPTY_THREAD_ERROR_ATOM : environmentThreadDetails.errorAtom(ref), + ); +} + export function useThreadHistory(ref: ScopedThreadRef | null): ThreadHistoryMeta { return useAtomValue( ref === null ? EMPTY_THREAD_HISTORY_ATOM : environmentThreadDetails.historyAtom(ref), diff --git a/apps/web/src/threadSync.test.ts b/apps/web/src/threadSync.test.ts new file mode 100644 index 000000000000..d16c2a67790c --- /dev/null +++ b/apps/web/src/threadSync.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { resolveThreadSyncPhase } from "./threadSync"; + +describe("resolveThreadSyncPhase", () => { + it("reports a failed sync instead of syncing over cached messages", () => { + expect( + resolveThreadSyncPhase({ + detailExists: true, + shellExists: true, + status: "cached", + hasError: true, + }), + ).toBe("failed"); + expect( + resolveThreadSyncPhase({ + detailExists: true, + shellExists: true, + status: "synchronizing", + hasError: false, + }), + ).toBe("syncing"); + }); +}); diff --git a/apps/web/src/threadSync.ts b/apps/web/src/threadSync.ts index a8b5446add2c..1dc70f331fcf 100644 --- a/apps/web/src/threadSync.ts +++ b/apps/web/src/threadSync.ts @@ -1,11 +1,12 @@ import type { EnvironmentThreadStatus } from "@t3tools/client-runtime/state/threads"; -export type ThreadSyncPhase = "loading" | "syncing"; +export type ThreadSyncPhase = "loading" | "syncing" | "failed"; export function resolveThreadSyncPhase(input: { readonly detailExists: boolean; readonly shellExists: boolean; readonly status: EnvironmentThreadStatus; + readonly hasError: boolean; }): ThreadSyncPhase | null { if (!input.shellExists) { return null; @@ -15,6 +16,7 @@ export function resolveThreadSyncPhase(input: { case "empty": case "cached": case "synchronizing": + if (input.hasError) return "failed"; return input.detailExists ? "syncing" : "loading"; case "deleted": case "live": @@ -23,5 +25,12 @@ export function resolveThreadSyncPhase(input: { } export function threadSyncLabel(phase: ThreadSyncPhase): string { - return phase === "loading" ? "Loading messages..." : "Syncing messages..."; + switch (phase) { + case "loading": + return "Loading messages..."; + case "syncing": + return "Syncing messages..."; + case "failed": + return "Could not sync messages"; + } } diff --git a/packages/client-runtime/src/state/threads-sync.test.ts b/packages/client-runtime/src/state/threads-sync.test.ts index ad36b3292605..8b4922551644 100644 --- a/packages/client-runtime/src/state/threads-sync.test.ts +++ b/packages/client-runtime/src/state/threads-sync.test.ts @@ -1767,21 +1767,33 @@ describe("EnvironmentThreads", () => { }), ); - it.effect("shows an error when the snapshot reload after a failed resume hits a defect", () => - Effect.gen(function* () { - const harness = yield* makeHarness({ cached: BASE_PROJECTION, completionMarker: true }); - expect(yield* Queue.take(harness.subscriptions)).toBe(CACHED_SNAPSHOT_SEQUENCE); - yield* Queue.offer(harness.inputs, new TestStreamDefect("Replayed event did not decode")); - expect(yield* Queue.take(harness.subscriptions)).toBeUndefined(); - - yield* Queue.offer(harness.inputs, new TestStreamDefect("Snapshot did not decode")); - const failed = yield* awaitThreadState(harness.observed, (value) => - Option.isSome(value.error), - ); - expect(Option.getOrThrow(failed.error)).toBe("Could not synchronize the thread."); - expect(failed.data).toEqual(Option.some(BASE_PROJECTION)); - expect(yield* Queue.size(harness.subscriptions)).toBe(0); - }), + it.effect( + "shows an error when the snapshot reload after a failed resume hits a defect, then retries on a new session", + () => + Effect.gen(function* () { + const harness = yield* makeHarness({ cached: BASE_PROJECTION, completionMarker: true }); + expect(yield* Queue.take(harness.subscriptions)).toBe(CACHED_SNAPSHOT_SEQUENCE); + yield* Queue.offer(harness.inputs, new TestStreamDefect("Replayed event did not decode")); + expect(yield* Queue.take(harness.subscriptions)).toBeUndefined(); + + yield* Queue.offer(harness.inputs, new TestStreamDefect("Snapshot did not decode")); + const failed = yield* awaitThreadState(harness.observed, (value) => + Option.isSome(value.error), + ); + expect(Option.getOrThrow(failed.error)).toBe("Could not synchronize the thread."); + expect(failed.data).toEqual(Option.some(BASE_PROJECTION)); + expect(yield* Queue.size(harness.subscriptions)).toBe(0); + + // A new session retries once, still from the snapshot. + yield* harness.replaceSession; + expect(yield* Queue.take(harness.subscriptions)).toBeUndefined(); + yield* Queue.offerAll(harness.inputs, [ + snapshot(BASE_PROJECTION, CACHED_SNAPSHOT_SEQUENCE + 5), + synchronized(), + ]); + const live = yield* awaitThreadState(harness.observed, (value) => value.status === "live"); + expect(Option.isNone(live.error)).toBe(true); + }), ); it.effect("keeps replayed updates synchronizing until the completion marker arrives", () => diff --git a/packages/client-runtime/src/state/threads.ts b/packages/client-runtime/src/state/threads.ts index c98085a47e91..a299dbb6a7c0 100644 --- a/packages/client-runtime/src/state/threads.ts +++ b/packages/client-runtime/src/state/threads.ts @@ -33,6 +33,7 @@ import * as Persistence from "../platform/persistence.ts"; import { runCachePersistence } from "./cachePersistence.ts"; import * as ManagedRelay from "../relay/managedRelay.ts"; import { request, subscribeDynamic } from "../rpc/client.ts"; +import type { RpcSession } from "../rpc/session.ts"; import { parseThreadKey, threadKey } from "./entities.ts"; import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts"; import { THREAD_SNAPSHOT_IDLE_TTL_MS } from "./threadRetention.ts"; @@ -260,6 +261,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make const resuming = yield* Ref.make(false); const resumeDied = yield* Ref.make(false); const forceSnapshot = yield* Ref.make(false); + const attemptSession = yield* Ref.make(undefined); const applyLock = yield* Semaphore.make(1); // Save only completed data/cursor updates. A canceled scope must not cache // a cursor whose event has not reached the data yet. @@ -895,6 +897,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make Effect.map((config) => config.threadResumeCompletionMarker === true), Effect.orElseSucceed(() => false), ); + yield* Ref.set(attemptSession, session); yield* Ref.set(awaitingCompletion, supportsCompletionMarker); yield* markSynchronizing; yield* Ref.set(resumingLive, false); @@ -993,14 +996,25 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make ).pipe( Stream.runForEachArray(applyItems), Effect.as(false), - // A defect on the snapshot attempt reports its error and stays terminal, - // so recovery cannot loop. - Effect.catchCause((cause) => - Ref.getAndSet(resumeDied, false).pipe( - Effect.flatMap((died) => - died ? Ref.set(forceSnapshot, true).pipe(Effect.as(true)) : Effect.failCause(cause), - ), - ), + Effect.catchCause( + Effect.fn("EnvironmentThreadState.recoverSubscription")(function* (cause) { + if (Cause.hasInterruptsOnly(cause)) return yield* Effect.failCause(cause); + if (yield* Ref.getAndSet(resumeDied, false)) { + yield* Ref.set(forceSnapshot, true); + return true; + } + // Any other defect keeps its error on screen and waits for a new + // session or a foreground wakeup, so recovery cannot loop. A session + // that changed before this wait counts as the next one. + const failedSession = yield* Ref.get(attemptSession); + yield* Stream.merge( + SubscriptionRef.changes(supervisor.session).pipe( + Stream.filter((session) => Option.getOrUndefined(session) !== failedSession), + ), + foregroundResubscriptions, + ).pipe(Stream.runHead); + return true; + }), ), Effect.repeat({ while: (retry) => retry }), ), From e810a33cf8114e5c4e76eeffe8ea299ef8466b71 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 24 Oct 2026 23:02:04 +0000 Subject: [PATCH 4/6] fix(client): sync failures stop dead-end retry taps and stale defects no longer park a healthy session The mobile "Could not sync messages" pill called reconnect, which on a connected environment only health-checks the socket and never resubscribes, so the tap did nothing. It is no longer tappable; a new session or returning to the foreground still retries. A defect while applying stream items never reached onDefect, so the thread sat on "synchronizing" with no error. Recovery now sets the error itself. It also keys the wait on the session whose subscription defected, so a buffered defect from a replaced session retries at once instead of parking the healthy one. Co-Authored-By: Claude Opus 5.5 --- .../features/threads/ThreadDetailScreen.tsx | 2 +- .../threads/floating-working-control.tsx | 7 +++--- .../threads/floating-working-status.test.ts | 3 ++- .../threads/floating-working-status.ts | 11 ++++----- .../src/state/threads-sync.test.ts | 24 +++++++++++++++++++ packages/client-runtime/src/state/threads.ts | 10 ++++++-- 6 files changed, 44 insertions(+), 13 deletions(-) diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index 16aa3cdf6486..6a4ba6396b00 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -766,7 +766,7 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai return null; } if (threadSyncPhase !== null) { - return threadSyncFloatingStatus(threadSyncPhase, props.onReconnectEnvironment); + return threadSyncFloatingStatus(threadSyncPhase); } const childInput = childThreadInputs[0]; if (childInput && contentPresentationKind === "ready") { diff --git a/apps/mobile/src/features/threads/floating-working-control.tsx b/apps/mobile/src/features/threads/floating-working-control.tsx index a012e6253f4f..b7ea620b7190 100644 --- a/apps/mobile/src/features/threads/floating-working-control.tsx +++ b/apps/mobile/src/features/threads/floating-working-control.tsx @@ -162,7 +162,7 @@ export function FloatingWorkingControl(props: { hasQueue || (props.devicePreview !== null && props.browserPreview !== null); const statusInteractive = - props.status?.kind === "connection" || + (props.status?.kind === "connection" && props.status.onPress !== undefined) || props.status?.kind === "child-input" || props.status?.kind === "background"; const capsuleInteractive = @@ -410,10 +410,11 @@ function FloatingStatusLabel(props: { {props.status.tone === "reconnecting" ? ( diff --git a/apps/mobile/src/features/threads/floating-working-status.test.ts b/apps/mobile/src/features/threads/floating-working-status.test.ts index 2e397fc72c44..c693bce0b1d3 100644 --- a/apps/mobile/src/features/threads/floating-working-status.test.ts +++ b/apps/mobile/src/features/threads/floating-working-status.test.ts @@ -7,11 +7,12 @@ describe("thread sync status", () => { expect(resolveThreadSyncPhase({ status: "cached", hasError: true, contentKind: "ready" })).toBe( "failed", ); - expect(threadSyncFloatingStatus("failed", () => {})).toMatchObject({ + expect(threadSyncFloatingStatus("failed")).toMatchObject({ kind: "connection", tone: "unavailable", label: "Could not sync messages", }); + expect(threadSyncFloatingStatus("failed")).not.toHaveProperty("onPress"); expect( resolveThreadSyncPhase({ status: "cached", hasError: false, contentKind: "ready" }), ).toBe("syncing"); diff --git a/apps/mobile/src/features/threads/floating-working-status.ts b/apps/mobile/src/features/threads/floating-working-status.ts index a73104a98110..de8f80a5b7d0 100644 --- a/apps/mobile/src/features/threads/floating-working-status.ts +++ b/apps/mobile/src/features/threads/floating-working-status.ts @@ -40,7 +40,7 @@ export type FloatingWorkingStatus = readonly kind: "connection"; readonly tone: "reconnecting" | "unavailable"; readonly label: string; - readonly onPress: () => void; + readonly onPress?: () => void; }; export function connectionFloatingStatus(input: { @@ -104,10 +104,7 @@ export function resolveThreadSyncPhase(input: { } } -export function threadSyncFloatingStatus( - phase: ThreadSyncPhase, - onRetry: () => void, -): FloatingWorkingStatus { +export function threadSyncFloatingStatus(phase: ThreadSyncPhase): FloatingWorkingStatus { switch (phase) { case "loading": return { kind: "syncing", label: "Loading messages..." }; @@ -117,8 +114,10 @@ export function threadSyncFloatingStatus( return { kind: "connection", tone: "unavailable", + // Not tappable: reconnecting a connected environment only health-checks + // the socket and does not resubscribe. A new session or returning to + // the foreground retries the sync. label: "Could not sync messages", - onPress: onRetry, }; } } diff --git a/packages/client-runtime/src/state/threads-sync.test.ts b/packages/client-runtime/src/state/threads-sync.test.ts index 8b4922551644..e5123a132071 100644 --- a/packages/client-runtime/src/state/threads-sync.test.ts +++ b/packages/client-runtime/src/state/threads-sync.test.ts @@ -1796,6 +1796,30 @@ describe("EnvironmentThreads", () => { }), ); + it.effect("shows an error when applying a streamed item hits a defect", () => + Effect.gen(function* () { + const harness = yield* makeHarness({ cached: BASE_PROJECTION, completionMarker: true }); + expect(yield* Queue.take(harness.subscriptions)).toBe(CACHED_SNAPSHOT_SEQUENCE); + yield* Queue.offerAll(harness.inputs, [ + snapshot(BASE_PROJECTION, CACHED_SNAPSHOT_SEQUENCE), + synchronized(), + ]); + yield* awaitThreadState(harness.observed, (value) => value.status === "live"); + + yield* Queue.offer(harness.inputs, { + kind: "event", + event: null, + } as unknown as OrchestrationV2ThreadStreamItem); + const failed = yield* awaitThreadState(harness.observed, (value) => + Option.isSome(value.error), + ); + expect(Option.getOrThrow(failed.error)).toBe("Could not synchronize the thread."); + + yield* harness.replaceSession; + expect(yield* Queue.take(harness.subscriptions)).toBe(CACHED_SNAPSHOT_SEQUENCE); + }), + ); + it.effect("keeps replayed updates synchronizing until the completion marker arrives", () => Effect.gen(function* () { const harness = yield* makeHarness({ cached: BASE_PROJECTION, completionMarker: true }); diff --git a/packages/client-runtime/src/state/threads.ts b/packages/client-runtime/src/state/threads.ts index a299dbb6a7c0..86907e7dce6e 100644 --- a/packages/client-runtime/src/state/threads.ts +++ b/packages/client-runtime/src/state/threads.ts @@ -262,6 +262,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make const resumeDied = yield* Ref.make(false); const forceSnapshot = yield* Ref.make(false); const attemptSession = yield* Ref.make(undefined); + const defectSession = yield* Ref.make(undefined); const applyLock = yield* Semaphore.make(1); // Save only completed data/cursor updates. A canceled scope must not cache // a cursor whose event has not reached the data yet. @@ -986,6 +987,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make if (Cause.hasDies(cause) && (yield* Ref.get(resuming))) { yield* Ref.set(resumeDied, true); } else { + yield* Ref.set(defectSession, yield* Ref.get(attemptSession)); yield* setStreamError("Could not synchronize the thread."); } }), @@ -1005,8 +1007,12 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make } // Any other defect keeps its error on screen and waits for a new // session or a foreground wakeup, so recovery cannot loop. A session - // that changed before this wait counts as the next one. - const failedSession = yield* Ref.get(attemptSession); + // that changed before this wait counts as the next one, so a buffered + // defect from a replaced session retries at once. A defect applying + // items never reaches onDefect, so the error is set here too. + const failedSession = + (yield* Ref.getAndSet(defectSession, undefined)) ?? (yield* Ref.get(attemptSession)); + yield* setStreamError("Could not synchronize the thread."); yield* Stream.merge( SubscriptionRef.changes(supervisor.session).pipe( Stream.filter((session) => Option.getOrUndefined(session) !== failedSession), From 98f04e9a74bddff40469f0b37117305337357d60 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 14 Nov 2026 07:50:03 +0000 Subject: [PATCH 5/6] fix(web): a failed sync keeps the remembered timeline painted A failed sync only changes the status line; the timeline keeps the same remembered paint it shows while syncing, instead of dropping to empty. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/ChatView.tsx | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 434858ce930b..fca3995167b7 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -543,7 +543,6 @@ export default function ChatView(props: ChatViewProps) { const threadDetailLoading = threadSyncPhase === "loading"; // Held back briefly, so a quick sync does not flash a status line at the end of the timeline. const delayedThreadSyncPhase = useDelayedStatus(routeThreadKey, threadSyncPhase); - const threadSyncing = threadSyncPhase === "loading" || threadSyncPhase === "syncing"; const activeProviderThread = serverProjection?.providerThreads.find( (thread) => thread.id === serverProjection.thread.activeProviderThreadId, ); @@ -3429,7 +3428,7 @@ export default function ChatView(props: ChatViewProps) { entriesInput={timelineEntriesInput} draftEntries={isServerThread ? null : draftTimelineEntries} activeThreadKey={activeThreadKey} - syncing={threadSyncing} + syncing={threadSyncPhase !== null} detailLoading={threadDetailLoading} citationRequest={citationRequest} citationHistory={citationHistory} From 98df6fa93452a90270079297c32d09eacfe50615 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 14 Nov 2026 08:07:57 +0000 Subject: [PATCH 6/6] fix(web): a failed first load keeps the loading state Before any messages load, a sync error stays in the loading phase, as on main, so the timeline does not show the empty-thread placeholder and send stays locked. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/threadSync.test.ts | 8 ++++++++ apps/web/src/threadSync.ts | 4 ++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/apps/web/src/threadSync.test.ts b/apps/web/src/threadSync.test.ts index d16c2a67790c..f76d1bda71fc 100644 --- a/apps/web/src/threadSync.test.ts +++ b/apps/web/src/threadSync.test.ts @@ -12,6 +12,14 @@ describe("resolveThreadSyncPhase", () => { hasError: true, }), ).toBe("failed"); + expect( + resolveThreadSyncPhase({ + detailExists: false, + shellExists: true, + status: "synchronizing", + hasError: true, + }), + ).toBe("loading"); expect( resolveThreadSyncPhase({ detailExists: true, diff --git a/apps/web/src/threadSync.ts b/apps/web/src/threadSync.ts index 1dc70f331fcf..61dad7a577a1 100644 --- a/apps/web/src/threadSync.ts +++ b/apps/web/src/threadSync.ts @@ -16,8 +16,8 @@ export function resolveThreadSyncPhase(input: { case "empty": case "cached": case "synchronizing": - if (input.hasError) return "failed"; - return input.detailExists ? "syncing" : "loading"; + if (!input.detailExists) return "loading"; + return input.hasError ? "failed" : "syncing"; case "deleted": case "live": return null;