From 5d1f1723bdbb1d62549a596137030e4973291073 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Fri, 14 Aug 2026 21:05:10 -0700 Subject: [PATCH] fix: preserve thread view boundaries across clients --- .../features/threads/ThreadRouteScreen.tsx | 52 +++++++++++-------- apps/server/src/orchestration/decider.ts | 19 ++++++- .../orchestration/decider.viewState.test.ts | 8 ++- apps/web/src/components/ChatView.tsx | 11 +++- apps/web/src/components/LegacySidebar.tsx | 26 ++++++---- apps/web/src/components/Sidebar.tsx | 13 ++++- .../src/components/ThreadStatusIndicators.tsx | 11 +++- apps/web/src/hooks/useThreadViewState.ts | 32 ++++++++---- apps/web/src/uiStateStore.test.ts | 18 +++++++ apps/web/src/uiStateStore.ts | 33 ++++++++++++ .../src/operations/commands.test.ts | 2 + packages/contracts/src/orchestration.test.ts | 1 + packages/contracts/src/orchestration.ts | 1 + 13 files changed, 174 insertions(+), 53 deletions(-) diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx index 91629f6ff2..e9b3786d84 100644 --- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx @@ -285,29 +285,35 @@ function ThreadRouteContent( routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState); const routeConnectionError = routeEnvironmentRuntime?.connectionError ?? null; const viewThread = useAtomCommand(threadEnvironment.view, { reportFailure: false }); - useEffect(() => { - const completedAt = selectedThread?.latestTurn?.completedAt; - if ( - selectedThread === null || - completedAt == null || - serverConfig?.environment.capabilities.threadViewState !== true - ) { - return; - } - const viewedAtMs = Date.parse(selectedThread.viewedAt ?? ""); - const completedAtMs = Date.parse(completedAt); - if ( - Number.isFinite(viewedAtMs) && - Number.isFinite(completedAtMs) && - viewedAtMs >= completedAtMs - ) { - return; - } - void viewThread({ - environmentId: selectedThread.environmentId, - input: { threadId: selectedThread.id }, - }); - }, [selectedThread, serverConfig?.environment.capabilities.threadViewState, viewThread]); + const selectedThreadEnvironmentId = selectedThread?.environmentId ?? null; + const selectedThreadId = selectedThread?.id ?? null; + const selectedThreadCompletedAt = selectedThread?.latestTurn?.completedAt ?? null; + const supportsThreadViewState = serverConfig?.environment.capabilities.threadViewState === true; + useFocusEffect( + useCallback(() => { + if ( + selectedThreadEnvironmentId === null || + selectedThreadId === null || + selectedThreadCompletedAt === null || + !supportsThreadViewState + ) { + return; + } + void viewThread({ + environmentId: selectedThreadEnvironmentId, + input: { + threadId: selectedThreadId, + viewedThrough: selectedThreadCompletedAt, + }, + }); + }, [ + selectedThreadCompletedAt, + selectedThreadEnvironmentId, + selectedThreadId, + supportsThreadViewState, + viewThread, + ]), + ); const selectedThreadWithDraftSettings = useMemo( () => selectedThread diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index 0d7d0b1971..243bea958d 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -563,12 +563,27 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" } case "thread.view": { - yield* requireThread({ + const thread = yield* requireThread({ readModel, command, threadId: command.threadId, }); const occurredAt = yield* nowIso; + const cappedViewedAt = DateTime.make(command.viewedThrough).pipe( + Option.filter( + (viewedThrough) => DateTime.Order(viewedThrough, DateTime.makeUnsafe(occurredAt)) <= 0, + ), + Option.as(command.viewedThrough), + Option.getOrElse(() => occurredAt), + ); + const viewedAt = DateTime.make(thread.viewedAt ?? thread.createdAt).pipe( + Option.filter( + (previousViewedAt) => + DateTime.Order(previousViewedAt, DateTime.makeUnsafe(cappedViewedAt)) >= 0, + ), + Option.as(thread.viewedAt ?? thread.createdAt), + Option.getOrElse(() => cappedViewedAt), + ); return { ...(yield* withEventBase({ aggregateKind: "thread", @@ -579,7 +594,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" type: "thread.viewed", payload: { threadId: command.threadId, - viewedAt: occurredAt, + viewedAt, }, }; } diff --git a/apps/server/src/orchestration/decider.viewState.test.ts b/apps/server/src/orchestration/decider.viewState.test.ts index d589aabbb6..cf0f2625b1 100644 --- a/apps/server/src/orchestration/decider.viewState.test.ts +++ b/apps/server/src/orchestration/decider.viewState.test.ts @@ -9,10 +9,12 @@ import { import * as NodeServices from "@effect/platform-node/NodeServices"; import { expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; +import * as TestClock from "effect/testing/TestClock"; import { decideOrchestrationCommand } from "./decider.ts"; const COMPLETED_AT = "2026-01-01T00:01:00.000Z"; +const VIEWED_THROUGH = "2026-01-01T00:00:45.000Z"; function makeReadModel(): OrchestrationReadModel { return { @@ -55,13 +57,15 @@ function makeReadModel(): OrchestrationReadModel { } it.layer(NodeServices.layer)("thread view-state decider", (it) => { - it.effect("stamps a view with server time", () => + it.effect("stamps a view at the acknowledged boundary", () => Effect.gen(function* () { + yield* TestClock.setTime(Date.parse("2026-01-02T00:00:00.000Z")); const event = yield* decideOrchestrationCommand({ command: { type: "thread.view", commandId: CommandId.make("cmd-view"), threadId: ThreadId.make("thread-1"), + viewedThrough: VIEWED_THROUGH, }, readModel: makeReadModel(), }); @@ -69,7 +73,7 @@ it.layer(NodeServices.layer)("thread view-state decider", (it) => { expect(viewed?.type).toBe("thread.viewed"); if (viewed?.type === "thread.viewed") { - expect(viewed.payload.viewedAt).toBe(viewed.occurredAt); + expect(viewed.payload.viewedAt).toBe(VIEWED_THROUGH); } }), ); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index caca433884..10093eadbe 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -101,7 +101,7 @@ import { togglePendingUserInputOptionSelection, type PendingUserInputDraftAnswer, } from "../pendingUserInput"; -import { useUiStateStore } from "../uiStateStore"; +import { resolveThreadViewedAt, useUiStateStore } from "../uiStateStore"; import { useThreadViewState } from "../hooks/useThreadViewState"; import { buildPlanImplementationThreadTitle, @@ -4153,7 +4153,14 @@ function ChatViewContent(props: ChatViewProps) { const activeThreadLocalLastVisitedAt = useUiStateStore((store) => activeThreadKey === null ? undefined : store.threadLastVisitedAtById[activeThreadKey], ); - const activeThreadLastVisitedAt = activeThreadShell?.viewedAt ?? activeThreadLocalLastVisitedAt; + const activeThreadPendingViewState = useUiStateStore((store) => + activeThreadKey === null ? undefined : store.threadViewStatePendingById[activeThreadKey], + ); + const activeThreadLastVisitedAt = resolveThreadViewedAt({ + serverViewedAt: activeThreadShell?.viewedAt, + localViewedAt: activeThreadLocalLastVisitedAt, + pending: activeThreadPendingViewState, + }); const activeThreadWokeVisible = useMemo(() => { if (activeThreadWokeAt === null) return false; if (changeRequestAutoSettles(activeThreadPr?.state, autoSettleOnMerge)) return false; diff --git a/apps/web/src/components/LegacySidebar.tsx b/apps/web/src/components/LegacySidebar.tsx index f148567b4b..bffafbefa7 100644 --- a/apps/web/src/components/LegacySidebar.tsx +++ b/apps/web/src/components/LegacySidebar.tsx @@ -92,6 +92,7 @@ import { previewEnvironment } from "../state/preview"; import { legacyProjectCwdPreferenceKey, resolveProjectExpanded, + resolveThreadViewedAt, useUiStateStore, } from "../uiStateStore"; import { @@ -375,7 +376,12 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr const threadRef = scopeThreadRef(thread.environmentId, thread.id); const threadKey = scopedThreadKey(threadRef); const localLastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]); - const lastVisitedAt = thread.viewedAt ?? localLastVisitedAt; + const pendingViewState = useUiStateStore((state) => state.threadViewStatePendingById[threadKey]); + const lastVisitedAt = resolveThreadViewedAt({ + serverViewedAt: thread.viewedAt, + localViewedAt: localLastVisitedAt, + pending: pendingViewState, + }); const isSelected = useThreadSelectionStore((state) => state.selectedThreadKeys.has(threadKey)); const runningTerminalIds = useThreadRunningTerminalIds({ environmentId: thread.environmentId, @@ -1211,14 +1217,16 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec ); const threadLastVisitedAts = useUiStateStore( useShallow((state) => - projectThreads.map( - (thread) => - thread.viewedAt ?? - state.threadLastVisitedAtById[ - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) - ] ?? - null, - ), + projectThreads.map((thread) => { + const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); + return ( + resolveThreadViewedAt({ + serverViewedAt: thread.viewedAt, + localViewedAt: state.threadLastVisitedAtById[threadKey], + pending: state.threadViewStatePendingById[threadKey], + }) ?? null + ); + }), ), ); const [renamingThreadKey, setRenamingThreadKey] = useState(null); diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 7b922d43eb..1a1fce54dd 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -94,7 +94,11 @@ import { buildSidebarProjectSnapshots, type SidebarProjectSnapshot, } from "../sidebarProjectGrouping"; -import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore"; +import { + legacyProjectCwdPreferenceKey, + resolveThreadViewedAt, + useUiStateStore, +} from "../uiStateStore"; import { useThreadSelectionStore } from "../threadSelectionStore"; import { useThreadActions } from "../hooks/useThreadActions"; import { useThreadViewState } from "../hooks/useThreadViewState"; @@ -743,7 +747,12 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: { const threadKey = scopedThreadKey(threadRef); const isRegeneratingTitle = thread.titleRegeneration != null; const localLastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]); - const lastVisitedAt = thread.viewedAt ?? localLastVisitedAt; + const pendingViewState = useUiStateStore((state) => state.threadViewStatePendingById[threadKey]); + const lastVisitedAt = resolveThreadViewedAt({ + serverViewedAt: thread.viewedAt, + localViewedAt: localLastVisitedAt, + pending: pendingViewState, + }); const isSelected = useThreadSelectionStore((state) => state.selectedThreadKeys.has(threadKey)); const openPrLink = useOpenPrLink(); const runningTerminalIds = useThreadRunningTerminalIds({ diff --git a/apps/web/src/components/ThreadStatusIndicators.tsx b/apps/web/src/components/ThreadStatusIndicators.tsx index 5811c727f6..ea005c1587 100644 --- a/apps/web/src/components/ThreadStatusIndicators.tsx +++ b/apps/web/src/components/ThreadStatusIndicators.tsx @@ -11,7 +11,7 @@ import { useProject } from "../state/entities"; import { useEnvironmentQuery } from "../state/query"; import { useThreadRunningTerminalIds } from "../state/terminalSessions"; import { vcsEnvironment } from "../state/vcs"; -import { useUiStateStore } from "../uiStateStore"; +import { resolveThreadViewedAt, useUiStateStore } from "../uiStateStore"; import { resolveChangeRequestPresentation } from "../sourceControlPresentation"; import { resolveThreadStatusPill, type ThreadStatusPill } from "./Sidebar.logic"; import type { SidebarThreadSummary } from "../types"; @@ -234,7 +234,14 @@ export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummar const localLastVisitedAt = useUiStateStore( (state) => state.threadLastVisitedAtById[scopedThreadKey(threadRef)], ); - const lastVisitedAt = thread.viewedAt ?? localLastVisitedAt; + const pendingViewState = useUiStateStore( + (state) => state.threadViewStatePendingById[scopedThreadKey(threadRef)], + ); + const lastVisitedAt = resolveThreadViewedAt({ + serverViewedAt: thread.viewedAt, + localViewedAt: localLastVisitedAt, + pending: pendingViewState, + }); const threadProject = useProject( useMemo( () => scopeProjectRef(thread.environmentId, thread.projectId), diff --git a/apps/web/src/hooks/useThreadViewState.ts b/apps/web/src/hooks/useThreadViewState.ts index ec424cc376..cdf7b1bd25 100644 --- a/apps/web/src/hooks/useThreadViewState.ts +++ b/apps/web/src/hooks/useThreadViewState.ts @@ -18,40 +18,50 @@ function timestampCovers(timestamp: string | undefined, target: string): boolean export function useThreadViewState() { const markLocalViewed = useUiStateStore((state) => state.markThreadVisited); const markLocalUnread = useUiStateStore((state) => state.markThreadUnread); + const setPending = useUiStateStore((state) => state.setThreadViewStatePending); + const clearPending = useUiStateStore((state) => state.clearThreadViewStatePending); const viewThread = useAtomCommand(threadEnvironment.view, { reportFailure: false }); - const markUnreadOnServer = useAtomCommand(threadEnvironment.markUnread, { - reportFailure: false, - }); + const markUnreadOnServer = useAtomCommand(threadEnvironment.markUnread, "thread mark unread"); const markViewed = useCallback( (threadRef: ScopedThreadRef, viewedThrough: string) => { - markLocalViewed(scopedThreadKey(threadRef), viewedThrough); - if (!readEnvironmentSupportsViewState(threadRef.environmentId)) return; + const threadKey = scopedThreadKey(threadRef); + if (!readEnvironmentSupportsViewState(threadRef.environmentId)) { + markLocalViewed(threadKey, viewedThrough); + return; + } const thread = readThreadShell(threadRef); if (timestampCovers(thread?.viewedAt, viewedThrough)) return; + const pending = { kind: "viewed", targetAt: viewedThrough } as const; + setPending(threadKey, pending); + markLocalViewed(threadKey, viewedThrough); void viewThread({ environmentId: threadRef.environmentId, - input: { threadId: threadRef.threadId }, - }); + input: { threadId: threadRef.threadId, viewedThrough }, + }).then(() => clearPending(threadKey, pending)); }, - [markLocalViewed, viewThread], + [clearPending, markLocalViewed, setPending, viewThread], ); const markUnread = useCallback( (threadRef: ScopedThreadRef, latestTurnCompletedAt: string | null | undefined) => { - markLocalUnread(scopedThreadKey(threadRef), latestTurnCompletedAt); + const threadKey = scopedThreadKey(threadRef); if ( latestTurnCompletedAt == null || !readEnvironmentSupportsViewState(threadRef.environmentId) ) { + markLocalUnread(threadKey, latestTurnCompletedAt); return; } + const pending = { kind: "unread", targetAt: latestTurnCompletedAt } as const; + setPending(threadKey, pending); + markLocalUnread(threadKey, latestTurnCompletedAt); void markUnreadOnServer({ environmentId: threadRef.environmentId, input: { threadId: threadRef.threadId }, - }); + }).then(() => clearPending(threadKey, pending)); }, - [markLocalUnread, markUnreadOnServer], + [clearPending, markLocalUnread, markUnreadOnServer, setPending], ); return useMemo(() => ({ markViewed, markUnread }), [markUnread, markViewed]); diff --git a/apps/web/src/uiStateStore.test.ts b/apps/web/src/uiStateStore.test.ts index 3045028735..04ae138f49 100644 --- a/apps/web/src/uiStateStore.test.ts +++ b/apps/web/src/uiStateStore.test.ts @@ -10,6 +10,7 @@ import { type PersistedUiState, persistState, reorderProjects, + resolveThreadViewedAt, resolveProjectExpanded, setDefaultAdvertisedEndpointKey, setProjectExpanded, @@ -53,6 +54,23 @@ describe("uiStateStore pure functions", () => { expect(markThreadUnread(next, threadId, null)).toBe(next); }); + it("uses local view state only while its server command is pending", () => { + const input = { + serverViewedAt: "2026-02-25T12:30:00.000Z", + localViewedAt: "2026-02-25T12:35:00.000Z", + }; + + expect(resolveThreadViewedAt({ ...input, pending: undefined })).toBe( + "2026-02-25T12:30:00.000Z", + ); + expect( + resolveThreadViewedAt({ + ...input, + pending: { kind: "viewed", targetAt: "2026-02-25T12:35:00.000Z" }, + }), + ).toBe("2026-02-25T12:35:00.000Z"); + }); + it("resolves project expansion from logical, physical, and legacy preference keys", () => { const physicalKey = "environment:/repo/project"; const legacyKey = legacyProjectCwdPreferenceKey("/repo/project"); diff --git a/apps/web/src/uiStateStore.ts b/apps/web/src/uiStateStore.ts index 5d744d540a..73ee090681 100644 --- a/apps/web/src/uiStateStore.ts +++ b/apps/web/src/uiStateStore.ts @@ -45,6 +45,11 @@ export interface UiEndpointState { export interface UiState extends UiProjectState, UiThreadState, UiEndpointState {} +export interface PendingThreadViewState { + kind: "viewed" | "unread"; + targetAt: string; +} + const initialState: UiState = { projectExpandedById: {}, projectOrder: [], @@ -270,6 +275,16 @@ export function markThreadUnread( }; } +export function resolveThreadViewedAt(input: { + serverViewedAt: string | undefined; + localViewedAt: string | undefined; + pending: PendingThreadViewState | undefined; +}): string | undefined { + return input.pending === undefined + ? (input.serverViewedAt ?? input.localViewedAt) + : (input.localViewedAt ?? input.serverViewedAt); +} + export function setThreadChangedFilesExpanded( state: UiState, threadId: string, @@ -382,8 +397,11 @@ export function reorderProjects( } interface UiStateStore extends UiState { + threadViewStatePendingById: Record; markThreadVisited: (threadId: string, visitedAt: string) => void; markThreadUnread: (threadId: string, latestTurnCompletedAt: string | null | undefined) => void; + setThreadViewStatePending: (threadId: string, pending: PendingThreadViewState) => void; + clearThreadViewStatePending: (threadId: string, pending: PendingThreadViewState) => void; setThreadChangedFilesExpanded: (threadId: string, turnId: string, expanded: boolean) => void; setDefaultAdvertisedEndpointKey: (key: string | null) => void; setProjectExpanded: (projectIds: string | readonly string[], expanded: boolean) => void; @@ -396,10 +414,25 @@ interface UiStateStore extends UiState { export const useUiStateStore = create((set) => ({ ...readPersistedState(), + threadViewStatePendingById: {}, markThreadVisited: (threadId, visitedAt) => set((state) => markThreadVisited(state, threadId, visitedAt)), markThreadUnread: (threadId, latestTurnCompletedAt) => set((state) => markThreadUnread(state, threadId, latestTurnCompletedAt)), + setThreadViewStatePending: (threadId, pending) => + set((state) => ({ + threadViewStatePendingById: { + ...state.threadViewStatePendingById, + [threadId]: pending, + }, + })), + clearThreadViewStatePending: (threadId, pending) => + set((state) => { + if (state.threadViewStatePendingById[threadId] !== pending) return state; + const threadViewStatePendingById = { ...state.threadViewStatePendingById }; + delete threadViewStatePendingById[threadId]; + return { threadViewStatePendingById }; + }), setThreadChangedFilesExpanded: (threadId, turnId, expanded) => set((state) => setThreadChangedFilesExpanded(state, threadId, turnId, expanded)), setDefaultAdvertisedEndpointKey: (key) => diff --git a/packages/client-runtime/src/operations/commands.test.ts b/packages/client-runtime/src/operations/commands.test.ts index f0aded7d67..70b5a0b626 100644 --- a/packages/client-runtime/src/operations/commands.test.ts +++ b/packages/client-runtime/src/operations/commands.test.ts @@ -182,6 +182,7 @@ describe("environment commands", () => { yield* viewThread({ commandId: CommandId.make("view-command"), threadId: ThreadId.make("thread-1"), + viewedThrough: "2026-01-01T00:00:00.000Z", }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor)); yield* markThreadUnread({ commandId: CommandId.make("mark-unread-command"), @@ -193,6 +194,7 @@ describe("environment commands", () => { type: "thread.view", commandId: "view-command", threadId: "thread-1", + viewedThrough: "2026-01-01T00:00:00.000Z", }, { type: "thread.mark-unread", diff --git a/packages/contracts/src/orchestration.test.ts b/packages/contracts/src/orchestration.test.ts index 76a3650546..5bb5a8b164 100644 --- a/packages/contracts/src/orchestration.test.ts +++ b/packages/contracts/src/orchestration.test.ts @@ -391,6 +391,7 @@ it.effect("decodes thread view-state commands", () => type: "thread.view", commandId: "cmd-view-1", threadId: "thread-1", + viewedThrough: "2026-01-01T00:00:00.000Z", }); const markUnread = yield* decodeOrchestrationCommand({ type: "thread.mark-unread", diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index fc93f447fb..89b4e0af41 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -707,6 +707,7 @@ const ThreadViewCommand = Schema.Struct({ type: Schema.Literal("thread.view"), commandId: CommandId, threadId: ThreadId, + viewedThrough: IsoDateTime, }); const ThreadMarkUnreadCommand = Schema.Struct({