Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 55 additions & 4 deletions apps/web/src/components/ChatView.logic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,13 @@ import {
} from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";

import type { Thread } from "../types";
import type { Thread, ThreadShell } from "../types";
import {
MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
branchMismatchKey,
buildExpiredTerminalContextToastCopy,
buildLoadingThreadFromShell,
buildThreadTurnInterruptInput,
createLocalDispatchSnapshot,
deriveComposerSendState,
Expand Down Expand Up @@ -85,6 +86,51 @@ const readySession = {
updatedAt: "2026-03-29T00:00:10.000Z",
};

describe("buildLoadingThreadFromShell", () => {
it("preserves shell metadata and supplies empty detail collections", () => {
const shell = {
environmentId,
id: threadId,
projectId,
title: "Loading thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
},
runtimeMode: "full-access",
interactionMode: "default",
branch: "main",
worktreePath: null,
latestTurn: null,
createdAt: now,
updatedAt: now,
archivedAt: null,
settledOverride: null,
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
session: null,
latestUserMessageAt: now,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
} satisfies ThreadShell;

expect(buildLoadingThreadFromShell(shell)).toMatchObject({
environmentId,
id: threadId,
projectId,
title: "Loading thread",
branch: "main",
deletedAt: null,
messages: [],
proposedPlans: [],
activities: [],
checkpoints: [],
});
});
});

describe("resolveThreadMetadataUpdateForNextTurn", () => {
const modelSelection = {
instanceId: ProviderInstanceId.make("codex"),
Expand Down Expand Up @@ -426,19 +472,24 @@ describe("reconcileRetainedMountedThreadIds", () => {
});

describe("shouldWriteThreadErrorToCurrentServerThread", () => {
it("requires the environment, route thread, and target thread to match", () => {
it("writes errors for a shell-derived active server thread", () => {
const routeThreadRef = { environmentId, threadId };

expect(
shouldWriteThreadErrorToCurrentServerThread({
serverThread: { environmentId, id: threadId },
activeServerThread: { environmentId, id: threadId },
routeThreadRef,
targetThreadId: threadId,
}),
).toBe(true);
});

it("requires an active server thread matching the environment, route, and target", () => {
const routeThreadRef = { environmentId, threadId };

expect(
shouldWriteThreadErrorToCurrentServerThread({
serverThread: null,
activeServerThread: null,
routeThreadRef,
targetThreadId: threadId,
}),
Expand Down
21 changes: 16 additions & 5 deletions apps/web/src/components/ChatView.logic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
type ThreadId,
type TurnId,
} from "@t3tools/contracts";
import { type ChatMessage, type SessionPhase, type Thread } from "../types";
import { type ChatMessage, type SessionPhase, type Thread, type ThreadShell } from "../types";
import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
import * as Schema from "effect/Schema";
import { appAtomRegistry } from "../rpc/atomRegistry";
Expand Down Expand Up @@ -95,8 +95,19 @@ export function buildLocalDraftThread(
};
}

export function buildLoadingThreadFromShell(shell: ThreadShell): Thread {
return {
...shell,
messages: [],
proposedPlans: [],
activities: [],
checkpoints: [],
deletedAt: null,
};
}

export function shouldWriteThreadErrorToCurrentServerThread(input: {
serverThread:
activeServerThread:
| {
environmentId: EnvironmentId;
id: ThreadId;
Expand All @@ -107,10 +118,10 @@ export function shouldWriteThreadErrorToCurrentServerThread(input: {
targetThreadId: ThreadId;
}): boolean {
return Boolean(
input.serverThread &&
input.activeServerThread &&
input.targetThreadId === input.routeThreadRef.threadId &&
input.serverThread.environmentId === input.routeThreadRef.environmentId &&
input.serverThread.id === input.targetThreadId,
input.activeServerThread.environmentId === input.routeThreadRef.environmentId &&
input.activeServerThread.id === input.targetThreadId,
);
}

Expand Down
47 changes: 35 additions & 12 deletions apps/web/src/components/ChatView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,7 @@ import {
import { ThreadErrorBanner } from "./chat/ThreadErrorBanner";
import { resolveThreadPr } from "./ThreadStatusIndicators";
import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack";
import { ThreadSyncStatusPill } from "./chat/ThreadSyncStatusPill";
import {
DRAFT_HERO_TRANSITION_ANIMATION_ID,
DRAFT_HERO_TRANSITION_DURATION_MS,
Expand All @@ -251,6 +252,7 @@ import {
branchMismatchKey,
buildExpiredTerminalContextToastCopy,
buildLocalDraftThread,
buildLoadingThreadFromShell,
buildThreadTurnInterruptInput,
collectUserMessageBlobPreviewUrls,
createLocalDispatchSnapshot,
Expand All @@ -272,9 +274,11 @@ import {
resolveSendEnvMode,
revokeBlobPreviewUrl,
revokeUserMessagePreviewUrls,
shouldWriteThreadErrorToCurrentServerThread,
startNewThreadForProject,
waitForStartedServerThread,
} from "./ChatView.logic";
import type { ThreadSyncPhase } from "../threadSync";
import { useLocalStorage } from "~/hooks/useLocalStorage";
import { useComposerHandleContext } from "../composerHandleContext";
import { sanitizeThreadErrorMessage } from "~/rpc/transportError";
Expand Down Expand Up @@ -465,6 +469,7 @@ type ChatViewProps =
onDiffPanelOpen?: () => void;
reserveTitleBarControlInset?: boolean;
forceExpandedMobileComposer?: boolean;
threadSyncPhase?: ThreadSyncPhase | null;
routeKind: "server";
draftId?: never;
}
Expand All @@ -474,6 +479,7 @@ type ChatViewProps =
onDiffPanelOpen?: () => void;
reserveTitleBarControlInset?: boolean;
forceExpandedMobileComposer?: boolean;
threadSyncPhase?: never;
routeKind: "draft";
draftId: DraftId;
};
Expand Down Expand Up @@ -1132,6 +1138,8 @@ function ChatViewContent(props: ChatViewProps) {
forceExpandedMobileComposer = false,
} = props;
const draftId = routeKind === "draft" ? props.draftId : null;
const threadSyncPhase = routeKind === "server" ? (props.threadSyncPhase ?? null) : null;
const threadDetailLoading = threadSyncPhase === "loading";
const handleNewThread = useNewThreadHandler();
const routeThreadRef = useMemo(
() => scopeThreadRef(environmentId, threadId),
Expand Down Expand Up @@ -1188,7 +1196,16 @@ function ChatViewContent(props: ChatViewProps) {
? store.getDraftSession(draftId)
: null,
);
const routeServerThreadShell = useThreadShell(routeKind === "server" ? routeThreadRef : null);
const serverThread = useThread(routeThreadRef, { waitForShell: draftThread !== null });
const loadingServerThread = useMemo(
() =>
threadDetailLoading && routeServerThreadShell
? buildLoadingThreadFromShell(routeServerThreadShell)
: null,
[routeServerThreadShell, threadDetailLoading],
);
const activeServerThread = serverThread ?? loadingServerThread;
const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);
const activeThreadLastVisitedAt = useUiStateStore(
(store) => store.threadLastVisitedAtById[routeThreadKey],
Expand Down Expand Up @@ -1368,7 +1385,7 @@ function ChatViewContent(props: ChatViewProps) {
? scopeProjectRef(draftThread.environmentId, draftThread.projectId)
: null;
const fallbackDraftProject = useProject(fallbackDraftProjectRef);
const localDraftError = serverThread
const localDraftError = activeServerThread
? null
: ((draftId ? localDraftErrorsByDraftId[draftId]?.message : null) ?? null);
const localServerError = localServerErrorsByThreadKey[routeThreadKey]?.message ?? null;
Expand All @@ -1377,7 +1394,7 @@ function ChatViewContent(props: ChatViewProps) {
// a failed send would silently disappear on promotion. When both keys hold
// an entry, the most recent write wins.
useEffect(() => {
if (!serverThread || !draftId) {
if (!activeServerThread || !draftId) {
return;
}
const pendingDraftEntry = localDraftErrorsByDraftId[draftId];
Expand Down Expand Up @@ -1406,7 +1423,7 @@ function ChatViewContent(props: ChatViewProps) {
[routeThreadKey]: pendingDraftEntry,
};
});
}, [draftId, localDraftErrorsByDraftId, routeThreadKey, serverThread]);
}, [activeServerThread, draftId, localDraftErrorsByDraftId, routeThreadKey]);
const localDraftThread = useMemo(
() =>
draftThread
Expand All @@ -1421,10 +1438,10 @@ function ChatViewContent(props: ChatViewProps) {
// Promotion is data-driven: the draft route keeps rendering while the
// server thread (same pre-allocated ref) starts, so live state must not
// depend on which route is mounted.
const isServerThread = serverThread !== null;
const activeThread = isServerThread ? serverThread : localDraftThread;
const isServerThread = activeServerThread !== null;
const activeThread = activeServerThread ?? localDraftThread;
const threadError = isServerThread
? (localServerError ?? serverThread?.session?.lastError ?? null)
? (localServerError ?? activeServerThread?.session?.lastError ?? null)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Loading errors use draft store

Medium Severity

While thread detail is loading, activeServerThread/isServerThread can be satisfied by loadingServerThread, but setThreadError still only writes server errors when serverThread is non-null. Failures during that window go to the draft error map, while threadError reads localServerErrorsByThreadKey, so error banners may not appear on the server thread route.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 7dd91b5. Configure here.

: localDraftError;
const runtimeMode = composerRuntimeMode ?? activeThread?.runtimeMode ?? DEFAULT_RUNTIME_MODE;
const interactionMode =
Expand Down Expand Up @@ -2490,10 +2507,11 @@ function ChatViewContent(props: ChatViewProps) {
const nextError = sanitizeThreadErrorMessage(error);
const nextEntry: LocalThreadErrorEntry = { message: nextError, at: Date.now() };
if (
serverThread &&
targetThreadId === routeThreadRef.threadId &&
serverThread.environmentId === routeThreadRef.environmentId &&
serverThread.id === targetThreadId
shouldWriteThreadErrorToCurrentServerThread({
activeServerThread,
routeThreadRef,
targetThreadId,
})
) {
setLocalServerErrorsByThreadKey((existing) => {
if ((existing[routeThreadKey]?.message ?? null) === nextError) {
Expand All @@ -2517,7 +2535,7 @@ function ChatViewContent(props: ChatViewProps) {
};
});
},
[draftId, routeThreadKey, routeThreadRef, serverThread],
[activeServerThread, draftId, routeThreadKey, routeThreadRef],
);

const focusComposer = useCallback(() => {
Expand Down Expand Up @@ -4471,6 +4489,7 @@ function ChatViewContent(props: ChatViewProps) {
!activeThread ||
isSendBusy ||
isConnecting ||
threadDetailLoading ||
activeEnvironmentUnavailable ||
sendInFlightRef.current
)
Expand Down Expand Up @@ -5737,7 +5756,7 @@ function ChatViewContent(props: ChatViewProps) {
contentInsetEndAdjustment={composerOverlayHeight}
onIsAtEndChange={onIsAtEndChange}
onManualNavigation={cancelTimelineLiveFollowForUserNavigation}
hideEmptyPlaceholder={isDraftHeroState}
hideEmptyPlaceholder={isDraftHeroState || threadDetailLoading}
topFadeEnabled={!hasTimelineTopBanner}
/>

Expand Down Expand Up @@ -5798,6 +5817,9 @@ function ChatViewContent(props: ChatViewProps) {
) : (
<ComposerBannerStack className="relative z-0" items={composerBannerItems} />
)}
{threadSyncPhase && !activeEnvironmentUnavailable ? (
<ThreadSyncStatusPill phase={threadSyncPhase} />
) : null}
<div
className="relative"
style={
Expand Down Expand Up @@ -5831,6 +5853,7 @@ function ChatViewContent(props: ChatViewProps) {
phase={phase}
isConnecting={isConnecting}
isSendBusy={isSendBusy}
sendDisabledReason={threadDetailLoading ? "Messages loading" : null}
isPreparingWorktree={isPreparingWorktree}
environmentUnavailable={activeEnvironmentUnavailableState}
activePendingApproval={activePendingApproval}
Expand Down
Loading
Loading