Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: keep project chat runs alive across view switches (#9129)

Nilayd668c28bbf12
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index 9d397f7113e..106652fffd8 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -174,6 +174,8 @@ import {
registerQueuedChatRunSettings,
releasePreStreamRunReservation,
reservePreStreamRun,
+ claimThreadCreation,
+ useChatProjectScope,
shouldAbortPendingQueueForModelBoundary,
shouldAbortPendingQueueForSettingsChange,
snapshotQueuedChatRunSettings,
@@ -3073,6 +3075,9 @@ const Composer: FC<{
({ threadListItem }) => threadListItem.remoteId,
);
const referenceThreadId = threadId ?? activeThreadId ?? null;
+ // Read at Send time, so a send that materializes after a project switch is still filed
+ // where it was made.
+ const projectScope = useChatProjectScope();
const promptQueueThreadIds = compactIds([
threadListItemId,
threadListItemRemoteId,
@@ -3534,6 +3539,17 @@ const Composer: FC<{
}
shouldCorrectPersistedModel ??= !state.remoteId;
const initializingFreshThread = !state.remoteId;
+ // Stamp it with what the queue was STARTED under. This path initializes without
+ // going through the composer, and by dispatch time the adapter may be showing a
+ // different project, so the chat was filed wherever the user is now.
+ if (initializingFreshThread) {
+ claimThreadCreation([state.id, state.remoteId], {
+ projectId: projectIdAtQueueStart,
+ incognito: incognitoAtQueueStart,
+ modelId: runSettingsAtQueueStart.params.checkpoint ?? "",
+ createdAt: Date.now(),
+ });
+ }
// A fresh chat receives its remote id during initialization. Await it
// before append so the adapter can match the queued settings using
// unstable_threadId on its first invocation.
@@ -4054,6 +4070,16 @@ const Composer: FC<{
preStreamRunReservationRef.current = reservationToken;
try {
const sentText = aui.composer().getState().text;
+ // Stamp the send BEFORE send() starts awaiting every incomplete attachment: a document
+ // send reaches initialize() seconds later, by which time navigation may have moved the
+ // project and cleared the temporary flag. See utils/chat-thread-creation-claim.ts.
+ const chatStateAtSend = useChatRuntimeStore.getState();
+ claimThreadCreation(preStreamThreadIds, {
+ projectId: projectScope,
+ incognito: chatStateAtSend.incognito,
+ modelId: chatStateAtSend.params.checkpoint ?? "",
+ createdAt: Date.now(),
+ });
aui.composer().send();
// Empty texts are dropped, so an attachment-only send still clears.
armJustSent(sentText, ...alsoGuard);
@@ -4067,7 +4093,7 @@ const Composer: FC<{
error instanceof Error ? error.message : "Please retry the send.",
});
}
- }, [aui, armJustSent, preStreamThreadIds, referenceThreadId]);
+ }, [aui, armJustSent, preStreamThreadIds, projectScope, referenceThreadId]);
// Gate for both form submit and the Send button. Returns true when it handled
// the event (blocked or queued) so callers stop.
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 132b590ec19..2ecdde01639 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -60,6 +60,7 @@ import {
releasePreStreamRunForThreadIds,
releasePreStreamRunReservation,
} from "../utils/pre-stream-run-reservation";
+import { readThreadCreationClaim } from "../utils/chat-thread-creation-claim";
import {
consumeQueuedChatRunSettings,
snapshotQueuedChatRunSettings,
@@ -3879,8 +3880,18 @@ export function createOpenAIStreamAdapter(
// Before the first await: hydration and a model load both run ahead of the
// first resolveProjectId, and a send survives navigation. Only consulted
// while the thread's own row is still missing.
- const composerProjectIdAtSend =
- useChatRuntimeStore.getState().activeProjectId ?? null;
+ //
+ // ...which for a fresh send is exactly the window this has to be right in, and the store
+ // is no longer a safe reading of it: send() awaits document extraction, and initialize()
+ // does not await its row write, so the user may be in another project by now and the run
+ // would take its instructions, RAG sources and sandbox from one the message was never
+ // sent to. A stamp OF null still wins -- a send from outside any project.
+ const creationClaim = unstable_threadId
+ ? readThreadCreationClaim(unstable_threadId)
+ : undefined;
+ const composerProjectIdAtSend = creationClaim
+ ? creationClaim.projectId
+ : (useChatRuntimeStore.getState().activeProjectId ?? null);
await useChatRuntimeStore.getState().hydratePersistedSettings();
// After the hydrate, not before: the backend reads some settings out of
// SQLite at call time rather than taking them from the request -- Search
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsx
index 020b762e201..b2fd924294f 100644
--- a/studio/frontend/src/features/chat/chat-page.tsx
+++ b/studio/frontend/src/features/chat/chat-page.tsx
@@ -209,6 +209,7 @@ import { useExternalProvidersStore } from "./stores/external-providers-store";
import { buildChatTourSteps } from "./tour";
import type { ChatView, MessageRecord } from "./types";
import { clearNewChatDraft } from "./utils/composer-draft";
+import { isChatThreadDeleted } from "./utils/chat-thread-tombstones";
import {
getStoredChatThread,
isExpectedBackgroundChatStorageError,
@@ -302,15 +303,11 @@ const ARTIFACT_SURFACE_POP_DELAY_MS = 150;
const SingleContent = memo(function SingleContent({
threadId,
- newThreadNonce,
- projectId,
artifact,
artifactSurface,
onCloseArtifact,
}: {
threadId?: string;
- newThreadNonce?: string;
- projectId?: string | null;
artifact?: ChatArtifact | null;
artifactSurface: ChatArtifactSurface;
onCloseArtifact: () => void;
@@ -420,13 +417,7 @@ const SingleContent = memo(function SingleContent({
);
return (
- <ChatRuntimeProvider
- modelType="base"
- initialThreadId={threadId}
- newThreadNonce={newThreadNonce}
- projectId={projectId}
- listThreads={false}
- >
+ <>
<ResizablePanelGroup
orientation="horizontal"
data-artifact-layout-animating={
@@ -514,7 +505,7 @@ const SingleContent = memo(function SingleContent({
}}
/>
) : null}
- </ChatRuntimeProvider>
+ </>
);
});
@@ -741,12 +732,23 @@ const LoraCompareContent = memo(function LoraCompareContent({
const markInitialHistoryReady = useCompareReloadReadiness(pairId);
const active = useChatActive();
- const compareRunning = useChatRuntimeStore(
+ // Global on purpose: a first compare run starts before either thread exists, so there is
+ // no pair id to scope BY -- it files its handles under "__default" until initialize()
+ // persists the row. And the gate has to exist at all because these ids feed ComparePane's
+ // `initialThreadId`, so learning them mid-run points ThreadAutoSwitch at a thread that is
+ // still generating.
+ const anyRunning = useChatRuntimeStore(
(s) => Object.keys(s.runningByThreadId).length > 0,
);
+ // ...but only RE-lists wait. The shared provider (#8908) keeps a base chat's run alive
+ // across the switch into compare, so `anyRunning` is true on arrival for a reason that has
+ // nothing to do with this pair, and gating the FIRST list on it left an existing compare on
+ // blank runtimes with no later edge to recover on. That list has nothing to clobber.
+ const listedPairRef = useRef<string | null>(null);
useEffect(() => {
- if (compareRunning) return;
+ if (anyRunning && listedPairRef.current === pairId) return;
+ listedPairRef.current = pairId;
let isActive = true;
setThreadsSettled(false);
listStoredChatThreads({ pairId })
@@ -766,7 +768,7 @@ const LoraCompareContent = memo(function LoraCompareContent({
return () => {
isActive = false;
};
- }, [pairId, compareRunning]);
+ }, [pairId, anyRunning]);
useEffect(() => {
if (!threadsSettled) return;
@@ -942,9 +944,12 @@ const GeneralCompareContent = memo(function GeneralCompareContent({
const globalGgufVariant = useChatRuntimeStore((s) => s.activeGgufVariant);
const globalIsDiffusion = useChatRuntimeStore((s) => s.loadedIsDiffusion);
const active = useChatActive();
- const compareRunning = useChatRuntimeStore(
+ // Global, with only RE-lists waiting on it; see the note on the Lora variant above for
+ // why a first compare run cannot be scoped by pair, and why the first list must not wait.
+ const anyRunning = useChatRuntimeStore(
(s) => Object.keys(s.runningByThreadId).length > 0,
);
+ const listedPairRef = useRef<string | null>(null);
const [model1, setModel1] = useState<CompareModelSelection>({
id: globalCheckpoint || "",
isLora: false,
@@ -970,7 +975,8 @@ const GeneralCompareContent = memo(function GeneralCompareContent({
);
useEffect(() => {
- if (compareRunning) return;
+ if (anyRunning && listedPairRef.current === pairId) return;
+ listedPairRef.current = pairId;
let isActive = true;
setThreadsSettled(false);
listStoredChatThreads({ pairId })
@@ -998,7 +1004,7 @@ const GeneralCompareContent = memo(function GeneralCompareContent({
return () => {
isActive = false;
};
- }, [pairId, compareRunning]);
+ }, [pairId, anyRunning]);
useEffect(() => {
if (!threadsSettled) return;
@@ -1203,19 +1209,32 @@ function ProjectLanding({
projectId,
projectName,
items,
+ newThreadNonce,
+ rotateNewThreadNonce,
dataLoaded,
+ runtimeReady,
}: {
projectId: string;
projectName: string;
items: SidebarItem[];
+ newThreadNonce: string;
+ rotateNewThreadNonce: () => void;
dataLoaded: boolean;
+ // #9251 holds the reload shell until the landing can be drawn. Its provider is hoisted
+ // above the view switch now (#8908), so the owner of that one reports readiness down.
+ runtimeReady: boolean;
}): ReactElement {
const navigate = useNavigate();
// Gates body-portaled surfaces so they can't linger or act while the landing
// is off-route (e.g. behind another tab).
const active = useChatActive();
+ const wasActiveRef = useRef(active);
const activeThreadId = useChatRuntimeStore((s) => s.activeThreadId);
- const initialActiveThreadRef = useRef<string | null>(null);
+ // Captured in render, not an effect: the shared provider's ThreadNewChatSwitch is an
+ // earlier sibling, so its mount effect blanks activeThreadId before an effect here runs.
+ const [initialActiveThreadId] = useState(
+ () => useChatRuntimeStore.getState().activeThreadId,
+ );
// Land on Sources when the project was just created with dropped files.
const [projectTab, setProjectTab] = useState<"chats" | "sources">(() =>
hasProjectSourcesPending(projectId) ? "sources" : "chats",
@@ -1227,15 +1246,10 @@ function ProjectLanding({
const [pendingNewThreadId, setPendingNewThreadId] = useState<string | null>(
null,
);
- const [newThreadNonce, setNewThreadNonce] = useState(() =>
- createThreadNonce(),
- );
const [previews, setPreviews] = useState<
Record<string, { snippet: string; date: string }>
>({});
- const [runtimeReady, setRuntimeReady] = useState(false);
const reloadReadySent = useRef(false);
- const markRuntimeReady = useCallback(() => setRuntimeReady(true), []);
// Inline rename, mirroring the sidebar recent-row UX: edit the title in place,
// commit on Enter/blur, cancel on Escape. Reuses the projectId-agnostic
// renameChatItem so behavior matches the sidebar.
@@ -1303,15 +1317,13 @@ function ProjectLanding({
}
useEffect(() => {
- initialActiveThreadRef.current =
- useChatRuntimeStore.getState().activeThreadId;
useChatRuntimeStore.getState().setActiveThreadId(null);
useChatRuntimeStore.getState().setContextUsage(null);
setPendingNewThreadId(null);
- setNewThreadNonce(createThreadNonce());
+ rotateNewThreadNonce();
setRenamingId(null);
setPendingRename(null);
- }, [projectId]);
+ }, [projectId, rotateNewThreadNonce]);
useEffect(() => {
if (!pendingRename) return;
@@ -1471,16 +1483,35 @@ function ProjectLanding({
}, [newThreadNonce]);
useEffect(() => {
+ const resumed = active && !wasActiveRef.current;
+ wasActiveRef.current = active;
+ if (!active) {
+ return;
+ }
if (!activeThreadId) {
+ if (resumed && pendingNewThreadId) {
+ // ...unless it was deleted while another view held the screen. Nothing else clears this
+ // id: it is component state, so the sidebar's global delete cannot reach it, and compare
+ // does not hold the chat as the active id either. Restoring a tombstoned thread would put
+ // a conversation storage no longer has back on screen with a composer pointed at it. Fall
+ // through to the rotate below, which is what a landing owning no chat looks like.
+ if (!isChatThreadDeleted(pendingNewThreadId)) {
+ useChatRuntimeStore.getState().setActiveThreadId(pendingNewThreadId);
+ return;
+ }
+ }
// Leaving a created chat for a new one: rotate the nonce so the runtime
// switches to a fresh thread instead of appending to the old chat.
if (pendingNewThreadId) {
- setNewThreadNonce(createThreadNonce());
+ rotateNewThreadNonce();
setPendingNewThreadId(null);
}
return;
}
- if (activeThreadId === initialActiveThreadRef.current) {
+ if (
+ activeThreadId === initialActiveThreadId ||
+ activeThreadId === pendingNewThreadId
+ ) {
return;
}
// Hand the composer's attach choice to the chat it just created: setting
@@ -1496,7 +1527,14 @@ function ProjectLanding({
captured?.nonce === newThreadNonce ? captured.claim : NO_SUCH_CLAIM,
);
setPendingNewThreadId(activeThreadId);
- }, [activeThreadId, pendingNewThreadId, newThreadNonce]);
+ }, [
+ active,
+ activeThreadId,
+ initialActiveThreadId,
+ pendingNewThreadId,
+ newThreadNonce,
+ rotateNewThreadNonce,
+ ]);
useEffect(() => {
let cancelled = false;
@@ -1558,13 +1596,7 @@ function ProjectLanding({
}, [dataLoaded, items, previews, runtimeReady]);
return (
- <ChatRuntimeProvider
- key={projectId}
- projectId={projectId}
- newThreadNonce={newThreadNonce}
- listThreads={false}
- onInitialHistoryReady={markRuntimeReady}
- >
+ <>
{pendingNewThreadId ? (
<div className="flex min-h-0 min-w-0 flex-1 basis-0 flex-col overflow-hidden">
<Thread hideWelcome={true} targetThreadId={pendingNewThreadId} />
@@ -2013,7 +2045,7 @@ function ProjectLanding({
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
- </ChatRuntimeProvider>
+ </>
);
}
@@ -2217,14 +2249,12 @@ export function ChatPage({
const persistedActiveThreadId = isAssistantLocalThreadId(activeThreadId)
? null
: activeThreadId;
- // A chat opened as ?new=<nonce> has no thread in the URL, and it keeps none after
- // the first send, so the model notice never saw the row that send created: switching
- // model in a chat you just started offered nothing until you navigated away and
- // reopened it. The store does learn the id -- runtime-provider publishes it once the
- // visible thread is the one being persisted -- but it still holds the PREVIOUS chat's
- // id for the first render, until ThreadNewChatSwitch blanks it in an effect. Handing
- // that over would put the previous chat's notice on this one. So latch on having seen
- // it blanked for this nonce; before the first send there is nothing to offer anyway.
+ // A ?new=<nonce> chat has no thread in the URL before or after its first send, so the
+ // model notice never saw the row that send created. The store does learn the id, but
+ // for the first render it still holds the PREVIOUS chat's, until ThreadNewChatSwitch
+ // blanks it in an effect -- using it then would show the previous chat's notice here.
+ // So latch on having seen it blanked for this nonce; before the first send there is
+ // nothing to offer anyway.
const newChatBlankedRef = useRef<string | null>(null);
if (
search.new &&
@@ -2606,6 +2636,13 @@ export function ChatPage({
currentProjectId,
]);
+ const [projectNewThreadNonce, setProjectNewThreadNonce] = useState(() =>
+ createThreadNonce(),
+ );
+ const rotateProjectNewThreadNonce = useCallback(() => {
+ setProjectNewThreadNonce(createThreadNonce());
+ }, []);
+
// Temporary chat only applies to a fresh single-view chat. Exit incognito
// when we land on anything else (compare, a project, or an existing thread
// via sidebar/deep link/back), so the toggle isn't stranded and the UI
@@ -2634,6 +2671,36 @@ export function ChatPage({
? "single:implicit"
: artifactViewKey;
+ // Compare replaces the shared provider on screen, so the base view is kept mounted
+ // behind it (hidden + inert): unmounting runs useLocalRuntime's detach(), the backend
+ // cancels on the disconnect, and a project chat's run would die on opening a compare
+ // chat. Frozen to the last non-compare view so the provider's props don't churn.
+ const keptBaseViewRef = useRef<{
+ view: Exclude<ChatView, { mode: "compare" }>;
+ attachmentTargetKey: string;
+ } | null>(null);
+ if (view.mode !== "compare") {
+ keptBaseViewRef.current = { view, attachmentTargetKey: artifactViewKey };
+ }
+ const baseView = keptBaseViewRef.current?.view ?? null;
+ const baseAttachmentTargetKey =
+ keptBaseViewRef.current?.attachmentTargetKey ?? artifactViewKey;
+ const baseBackgrounded = view.mode === "compare";
+
+ // #9251's reload signal, taken here because the provider is hoisted. Stored as the
+ // project it belongs to, not a boolean: the hoisted provider is not remounted when the
+ // project changes, so a flag would stay true and release the next landing's shell early.
+ const projectLandingId =
+ baseView?.mode === "project" ? baseView.projectId : null;
+ const [projectRuntimeReadyFor, setProjectRuntimeReadyFor] = useState<
+ string | null
+ >(null);
+ const markProjectRuntimeReady = useCallback(() => {
+ setProjectRuntimeReadyFor(projectLandingId);
+ }, [projectLandingId]);
+ const projectRuntimeReady =
+ projectLandingId !== null && projectRuntimeReadyFor === projectLandingId;
+
useEffect(() => {
clearAutoOpenedArtifacts();
closeArtifactSurface();
@@ -2888,9 +2955,8 @@ export function ChatPage({
[artifactViewKey],
);
const nativeModelDropState = useNativeModelDrop({
- // Compare used to disable this outright, so a drop there vanished with no
- // overlay and no message (#9036). Keep listening and refuse out loud. The
- // refusal covers models too: nothing may load behind a compare view.
+ // Compare used to disable this outright, so a drop there vanished with no overlay
+ // and no message (#9036). Keep listening and refuse out loud, models included.
enabled: active,
dropsUnsupportedReason:
view.mode === "single"
@@ -3410,9 +3476,8 @@ export function ChatPage({
return [...fromLoras, ...localModels];
}, [lorasFromStore, localModels]);
- // Everything the picker can offer right now, so the chat's own model is only
- // proposed when selecting it would actually work. A model since deleted, or a
- // connection since removed, drops out and the notice stays quiet.
+ // Everything the picker can offer right now, so the chat's own model is only proposed
+ // when selecting it would work: a deleted model or removed connection drops out.
const selectableModelIds = useMemo(
() =>
new Set<string>([
@@ -3423,10 +3488,10 @@ export function ChatPage({
[models, loraModels, externalModels],
);
- // Still handleCheckpointChange, the picker's own handler, but reached the way
- // the picker reaches it: with the row's metadata, not the bare id. A local or
- // fine-tuned row is in neither `/api/models/list` nor the external ids, so
- // without it the switch loads on different arguments than the menu would.
+ // The picker's own handler, reached the way the picker reaches it: with the row's
+ // metadata, not the bare id. A local or fine-tuned row is in neither
+ // `/api/models/list` nor the external ids, so without it the switch loads on
+ // different arguments than the menu would.
const handleSwitchBackToChatModel = useCallback(
(modelId: string) => {
handleCheckpointChange(
@@ -3599,12 +3664,10 @@ export function ChatPage({
render their own copy and the shared-composer menu would have none. It
also portals to body, so gate it on `active` like the tour above. */}
{active && <BypassPermissionsConfirmDialog />}
- {/* `--studio-chat-notice-height` is 0 until ChatModelNotice is actually on
- screen, and the thread viewport adds it to the top padding it already
- reserves for the header. Without it the notice is an opaque bar over
- space nothing reserved, and the top of the first message reads
- underneath it. Declared here, on the nearest ancestor of BOTH the
- notice and the viewport, so the two cannot disagree about its height. */}
+ {/* `--studio-chat-notice-height` is 0 until ChatModelNotice is on screen; the
+ thread viewport adds it to the top padding it reserves for the header, so
+ without it the first message reads under an opaque bar. Declared on the
+ nearest ancestor of BOTH so the two cannot disagree about its height. */}
<div className="relative flex min-h-0 min-w-0 flex-1 basis-0 flex-col overflow-hidden has-[[data-chat-model-notice]]:[--studio-chat-notice-height:2.25rem]">
<NativeModelDropOverlay state={nativeModelDropState} />
{/* Fade under the top bar so messages dissolve as they scroll
@@ -3867,33 +3930,69 @@ export function ChatPage({
/>
)}
- {view.mode === "project" ? (
- <ProjectLanding
- key={view.projectId}
- projectId={view.projectId}
- projectName={currentProject?.name ?? "Project"}
- items={currentProjectItems}
- dataLoaded={currentProjectItemsLoaded && !projectsLoading}
- />
- ) : view.mode === "single" ? (
- // Keyed by project only (not thread / new-chat nonce) so switching threads or
- // starting a New Chat reuses the same provider and switches in place. This keeps
- // an in-flight generation streaming in the background (assistant-ui keeps every
- // alive thread's runtime mounted) instead of remounting the provider and cutting
- // it off; returning to that thread reattaches the live run rather than reloading
- // a half-saved one.
- <NativeAttachmentTargetContext.Provider value={artifactViewKey}>
- <SingleContent
- key={view.projectId ?? "single"}
- threadId={view.threadId}
- newThreadNonce={view.newThreadNonce}
- projectId={view.projectId}
- artifact={selectedArtifact}
- artifactSurface={artifactSurface}
- onCloseArtifact={closeArtifactSurface}
- />
- </NativeAttachmentTargetContext.Provider>
- ) : (
+ {/* One provider shared by the project and single views, never keyed on thread /
+ nonce / project, so switching between them reattaches the live run instead of
+ remounting the runtime and aborting generation (#8908). Any key here brings
+ the bug back. Compare renders as a sibling, not in its place, so it hides
+ this rather than unmounting it -- ComparePane builds its own providers and
+ useRemoteThreadListRuntime throws when they nest. */}
+ {baseView ? (
+ <div
+ className={
+ baseBackgrounded
+ ? "hidden"
+ : "flex min-h-0 min-w-0 flex-1 basis-0 flex-col overflow-hidden"
+ }
+ inert={baseBackgrounded || undefined}
+ >
+ <ChatActiveContext.Provider value={active && !baseBackgrounded}>
+ <ChatRuntimeProvider
+ modelType="base"
+ projectId={baseView.projectId}
+ initialThreadId={
+ baseView.mode === "single" ? baseView.threadId : undefined
+ }
+ newThreadNonce={
+ baseView.mode === "project"
+ ? projectNewThreadNonce
+ : baseView.newThreadNonce
+ }
+ listThreads={false}
+ backgrounded={baseBackgrounded}
+ onInitialHistoryReady={
+ baseView.mode === "project"
+ ? markProjectRuntimeReady
+ : undefined
+ }
+ >
+ {baseView.mode === "project" ? (
+ <ProjectLanding
+ key={baseView.projectId}
+ projectId={baseView.projectId}
+ projectName={currentProject?.name ?? "Project"}
+ items={currentProjectItems}
+ newThreadNonce={projectNewThreadNonce}
+ rotateNewThreadNonce={rotateProjectNewThreadNonce}
+ dataLoaded={currentProjectItemsLoaded && !projectsLoading}
+ runtimeReady={projectRuntimeReady}
+ />
+ ) : (
+ <NativeAttachmentTargetContext.Provider
+ value={baseAttachmentTargetKey}
+ >
+ <SingleContent
+ threadId={baseView.threadId}
+ artifact={selectedArtifact}
+ artifactSurface={artifactSurface}
+ onCloseArtifact={closeArtifactSurface}
+ />
+ </NativeAttachmentTargetContext.Provider>
+ )}
+ </ChatRuntimeProvider>
+ </ChatActiveContext.Provider>
+ </div>
+ ) : null}
+ {view.mode === "compare" ? (
<CompareContent
key={view.pairId}
pairId={view.pairId}
@@ -3907,7 +4006,7 @@ export function ChatPage({
deleteDisabled={modelOperationInProgress}
onExitCompare={exitCompare}
/>
- )}
+ ) : null}
{active && showArtifactOverlay && selectedArtifact ? (
<ArtifactSurface
diff --git a/studio/frontend/src/features/chat/chat-project-scope.ts b/studio/frontend/src/features/chat/chat-project-scope.ts
new file mode 100644
index 00000000000..56ad9919344
--- /dev/null
+++ b/studio/frontend/src/features/chat/chat-project-scope.ts
@@ -0,0 +1,16 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { createContext, useContext } from "react";
+
+/**
+ * The project the runtime provider on this subtree is showing, for the composer to stamp
+ * sends with (see `chat-thread-project-claim.ts`). Context rather than the store's
+ * `activeProjectId`: this is the same value the adapter files threads under, and one source
+ * for both is what makes the claim and the fallback agree.
+ */
+export const ChatProjectScopeContext = createContext<string | null>(null);
+
+export function useChatProjectScope(): string | null {
+ return useContext(ChatProjectScopeContext);
+}
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index d36f5551820..bd75f8126bd 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -120,6 +120,8 @@ export {
releasePreStreamRunReservation,
reservePreStreamRun,
} from "./utils/pre-stream-run-reservation";
+export { claimThreadCreation } from "./utils/chat-thread-creation-claim";
+export { useChatProjectScope } from "./chat-project-scope";
// Audio swaps the same llama-server Chat decodes on, so it needs the same confirmation.
export {
confirmStopRunningChatsIfNeeded,
diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsx
index 52e4c60fcba..0ae9ee511f6 100644
--- a/studio/frontend/src/features/chat/runtime-provider.tsx
+++ b/studio/frontend/src/features/chat/runtime-provider.tsx
@@ -76,6 +76,8 @@ import {
useResearchRunStore,
} from "./stores/research-run-store";
import { ToolPaneScopeContext, toolPaneScope } from "./tool-output-scope";
+import { ChatProjectScopeContext } from "./chat-project-scope";
+import { readThreadCreationClaim } from "./utils/chat-thread-creation-claim";
import type { MessageRecord, ModelType, ThreadRecord } from "./types";
import {
chatContentPartAttachmentIdFromSignature,
@@ -282,11 +284,10 @@ class VisionImageAdapter implements AttachmentAdapter {
class PDFAttachmentAdapter implements AttachmentAdapter {
accept = "application/pdf";
- // Refused here, not at send: the composer empties itself before it awaits
- // send(), so a ceiling that only fires there discards the typed message too.
- // The throw itself is invisible, as with audio: nothing subscribes to
- // attachmentAddError and the picker never awaits addAttachment, so the toast
- // is the only thing that tells the user why no file appeared.
+ // Refused here, not at send: the composer empties itself before it awaits send(), so a
+ // ceiling that only fires there discards the typed message too. The throw is invisible
+ // (nothing subscribes to attachmentAddError, the picker never awaits addAttachment), so
+ // the toast is the only thing telling the user why no file appeared.
add({ file }: { file: File }): Promise<PendingAttachment> {
const sizeError = getDocumentAttachmentSizeError(file, "PDF");
if (sizeError) {
@@ -401,9 +402,9 @@ class DocxAttachmentAdapter implements AttachmentAdapter {
accept =
"application/vnd.openxmlformats-officedocument.wordprocessingml.document";
- // The archive's own parts are checked here too, not just the upload ceiling:
- // a small .docx can still declare a part that only mammoth's inflate would
- // grow past the cap, and refusing that at send() would empty the composer.
+ // The archive's own parts are checked too, not just the upload ceiling: a small .docx
+ // can declare a part that only mammoth's inflate grows past the cap, and refusing that
+ // at send() would empty the composer.
async add({ file }: { file: File }): Promise<PendingAttachment> {
const error = await getDocxAttachmentError(file);
if (error) {
@@ -816,16 +817,24 @@ function createStudioDbAdapter(
// assistant-ui withholds the first message until this resolves, so the row write is tracked, not awaited.
// Captured here, not inside the creator: a retry belongs to the send that initialized it,
// not to a later incognito or checkpoint selection.
+ // What the SEND was made under, not what is on screen now. Materialization is no longer
+ // the same tick as the send, and all four move in between: the adapter is rebuilt with
+ // the new project, and ChatPage's view effect clears `incognito`. A claim of null/false
+ // wins over the store for the same reason.
+ const claim = readThreadCreationClaim(threadId);
const runtimeStateAtInit = useChatRuntimeStore.getState();
- const incognitoAtInit = runtimeStateAtInit.incognito;
- const modelIdAtInit = runtimeStateAtInit.params.checkpoint ?? "";
- const createdAtInit = Date.now();
+ const incognitoAtInit = claim ? claim.incognito : runtimeStateAtInit.incognito;
+ const modelIdAtInit = claim
+ ? claim.modelId
+ : (runtimeStateAtInit.params.checkpoint ?? "");
+ const createdAtInit = claim ? claim.createdAt : Date.now();
+ const projectIdAtInit = claim ? claim.projectId : projectId;
trackStoredChatThreadRecord(threadId, () =>
ensureThreadRecord({
threadId,
modelType,
pairId,
- projectId,
+ projectId: projectIdAtInit,
incognito: incognitoAtInit,
modelId: modelIdAtInit,
createdAt: createdAtInit,
@@ -1139,6 +1148,10 @@ function useStudioRuntimeAdapters(
pairId?: string,
reloadReadyThreadId?: string,
onInitialHistoryReady?: () => void,
+ // A ref, so handing it down never changes the memoized runtime hook's identity: a new
+ // hook identity would rebuild the runtime, which is the one thing this PR must not do.
+ backgroundedRef?: { current: boolean },
+ newThreadSwitchStateRef?: { current: NewThreadSwitchState },
): StudioRuntimeAdapters {
const aui = useAui();
@@ -1483,7 +1496,28 @@ function useStudioRuntimeAdapters(
}
// published before the reads below: a temporary chat has no row to confirm, and a read
// that fails must not leave the runtime pointing at the previously open chat
- if (modelType === "base" && !pairId) {
+ //
+ // ...but not while this pane is only mounted to keep its run attached: a hidden pane
+ // naming itself active reaches Compare's exportThreadIds, so Export pulls the unrelated
+ // base chat. Through a ref, read at publish time, since the write may have been queued
+ // while the pane was still on screen.
+ //
+ // Nor mid-switch. switchToNewThread() is async, so mainThreadId is still the OUTGOING
+ // thread for the whole gap and the guard below reads that as "this pane is on screen"; a
+ // write landing there republishes the chat the user just left into the project they
+ // navigated to. attempt !== landedAttempt is that gap.
+ const switchState = newThreadSwitchStateRef?.current;
+ const switchInFlight = Boolean(
+ switchState &&
+ switchState.activeNonce !== null &&
+ switchState.landedAttempt !== switchState.attempt,
+ );
+ if (
+ modelType === "base" &&
+ !pairId &&
+ !backgroundedRef?.current &&
+ !switchInFlight
+ ) {
const store = useChatRuntimeStore.getState();
const visibleThreadId = aui.threads().getState().mainThreadId;
if (
@@ -1553,7 +1587,9 @@ function useStudioRuntimeAdapters(
}),
[
aui,
+ backgroundedRef,
modelType,
+ newThreadSwitchStateRef,
onInitialHistoryReady,
pairId,
reloadReadyThreadId,
@@ -1609,12 +1645,16 @@ function useRuntimeHook(
pairId?: string,
reloadReadyThreadId?: string,
onInitialHistoryReady?: () => void,
+ backgroundedRef?: { current: boolean },
+ newThreadSwitchStateRef?: { current: NewThreadSwitchState },
): ReturnType<typeof useLocalRuntime> {
const adapters = useStudioRuntimeAdapters(
modelType,
pairId,
reloadReadyThreadId,
onInitialHistoryReady,
+ backgroundedRef,
+ newThreadSwitchStateRef,
);
const persistedChatAdapter = useMemo(
() =>
@@ -1631,6 +1671,8 @@ function createRuntimeHook(
pairId?: string,
reloadReadyThreadId?: string,
onInitialHistoryReady?: () => void,
+ backgroundedRef?: { current: boolean },
+ newThreadSwitchStateRef?: { current: NewThreadSwitchState },
) {
return function useConfiguredRuntimeHook(): ReturnType<
typeof useLocalRuntime
@@ -1640,17 +1682,54 @@ function createRuntimeHook(
pairId,
reloadReadyThreadId,
onInitialHistoryReady,
+ backgroundedRef,
+ newThreadSwitchStateRef,
);
};
}
+// Only bounds the pathological case: a switch that never settles never spends its claim.
+const MAX_PENDING_SAVED_THREAD_SWITCHES = 16;
+
+type PendingSavedThreadSwitch = { id: string; settled: boolean };
+
+type NewThreadSwitchState = {
+ activeNonce: string | null;
+ hasSwitched: boolean;
+ // Bumped by every switch this provider starts. The nonce alone does not identify an
+ // attempt: leaving for a saved chat and coming back releases it, so two switches for
+ // the SAME nonce can be in flight and the older must not speak for the newer.
+ attempt: number;
+ // One entry per switch STARTED, so a nonce view recognises any of these ids landing after
+ // the route moved on. By id rather than id SHAPE, which cannot tell a stale arrival from a
+ // fresh switch's thread. Duplicates matter: two switches for one thread can overlap.
+ // `settled` retires a claim with its own switch, so one that finished off-screen cannot be
+ // spent by a later, legitimate open.
+ pendingSavedThreadIds: PendingSavedThreadSwitch[];
+ // The thread a nonce view is on, with the nonce it belongs to. Once the user has sent,
+ // assistant-ui's newThreadId is gone and switchToNewThread() mints a SECOND blank thread
+ // instead of restoring theirs. A ?new= URL survives materialization, so Back returns to the
+ // same nonce; the pair is what tells a returning nonce from a new one.
+ nonceThread: { nonce: string; threadId: string } | null;
+ // The newest attempt whose own switch has LANDED. Ownership is only recorded from a thread
+ // this nonce's switch actually opened: entering a nonce from a saved chat leaves that chat
+ // as `mainThreadId` until switchToNewThread() resolves and its claim is already retired, so
+ // "unclaimed and current" is not proof of ownership -- recording it there reopened the chat
+ // the user had LEFT.
+ landedAttempt: number;
+};
+
function ThreadAutoSwitch({
threadId,
syncActiveThreadId = true,
+ paused,
+ newThreadSwitchStateRef,
onSwitchFailed,
}: {
threadId: string;
syncActiveThreadId?: boolean;
+ paused: boolean;
+ newThreadSwitchStateRef: { current: NewThreadSwitchState };
onSwitchFailed?: () => void;
}): ReactElement | null {
const aui = useAui();
@@ -1658,47 +1737,111 @@ function ThreadAutoSwitch({
const mainThreadId = useAuiState(({ threads }) => threads.mainThreadId);
useEffect(() => {
- if (!isLoading && mainThreadId !== threadId) {
+ // Paused as well as loading: requestTemporaryPromptQueueStop() names every temporary queue
+ // on the page, not this provider's, so a backgrounded pane would stop a queue the on-screen
+ // view owns. `paused` is a dependency, so both are paid on resume.
+ if (isLoading || paused) {
+ return;
+ }
+ newThreadSwitchStateRef.current.activeNonce = null;
+ if (mainThreadId !== threadId) {
+ // Bumped, not read: this resolves asynchronously into a shared provider, so a newer
+ // switch of EITHER kind must supersede it. Sharing one token across two saved
+ // switches let a late rejection detach the chat already on screen.
+ const attemptAtStart = (newThreadSwitchStateRef.current.attempt += 1);
+ // One entry per switch started, duplicates included: A, B, A starts two A switches
+ // and both can land, so each arrival must spend exactly one entry.
+ const claims = newThreadSwitchStateRef.current.pendingSavedThreadIds;
+ const claim: PendingSavedThreadSwitch = { id: threadId, settled: false };
+ claims.push(claim);
+ // Oldest first: the longest-outstanding switch is least likely to still take a view.
+ if (claims.length > MAX_PENDING_SAVED_THREAD_SWITCHES) {
+ claims.splice(0, claims.length - MAX_PENDING_SAVED_THREAD_SWITCHES);
+ }
// Saved chats keep running in the background, but a temporary chat is
// unreachable after this switch and must not retain an active queue.
requestTemporaryPromptQueueStop();
const switchResult = aui.threads().switchToThread(threadId) as unknown;
if (
switchResult &&
- typeof (switchResult as Promise<void>).catch === "function"
+ typeof (switchResult as Promise<void>).then === "function"
) {
- void (switchResult as Promise<void>).catch(() => {
- if (syncActiveThreadId) {
- useChatRuntimeStore.getState().setActiveThreadId(null);
- }
- onSwitchFailed?.();
- });
+ // Both arms retire the claim, because both end the switch. A rejected switch never
+ // assigns a main thread, so its claim could otherwise sit armed for ever.
+ void (switchResult as Promise<void>).then(
+ () => {
+ claim.settled = true;
+ },
+ () => {
+ claim.settled = true;
+ // Ahead of the staleness guard, deliberately (#9251): this releases the
+ // retained reload shell, and a superseded attempt still ended.
+ onSwitchFailed?.();
+ // Only if this switch is still the current one. Unguarded, a rejection landing
+ // after the user moved to a project landing cleared the active id that view had
+ // just set, detaching a chat this failure has nothing to do with.
+ if (newThreadSwitchStateRef.current.attempt !== attemptAtStart) return;
+ if (syncActiveThreadId) {
+ useChatRuntimeStore.getState().setActiveThreadId(null);
+ }
+ },
+ );
+ } else {
+ // A synchronous switch is already over by the time this line runs.
+ claim.settled = true;
}
}
}, [
aui,
isLoading,
mainThreadId,
+ newThreadSwitchStateRef,
onSwitchFailed,
+ paused,
syncActiveThreadId,
threadId,
]);
useEffect(() => {
- if (!syncActiveThreadId || isLoading || mainThreadId !== threadId) {
+ if (isLoading || mainThreadId !== threadId) {
+ return;
+ }
+ // The switch landed while this view is still mounted, so it was not stale and the
+ // nonce view has nothing to correct. Released here rather than in the promise: this
+ // effect only runs while the saved chat is on screen, which is exactly the condition.
+ // Every SETTLED claim, not just this thread's: the view is stable here, so a finished
+ // switch has had its chance to be corrected. In-flight ones can still land wrong.
+ const state = newThreadSwitchStateRef.current;
+ state.pendingSavedThreadIds = state.pendingSavedThreadIds.filter(
+ (claim) => !claim.settled,
+ );
+ if (!syncActiveThreadId) {
return;
}
useChatRuntimeStore.getState().setActiveThreadId(threadId);
- }, [isLoading, mainThreadId, syncActiveThreadId, threadId]);
+ }, [
+ isLoading,
+ mainThreadId,
+ newThreadSwitchStateRef,
+ syncActiveThreadId,
+ threadId,
+ ]);
return null;
}
function ThreadNewChatSwitch({
nonce,
-}: { nonce: string }): ReactElement | null {
+ paused,
+ newThreadSwitchStateRef,
+}: {
+ nonce: string;
+ paused: boolean;
+ newThreadSwitchStateRef: { current: NewThreadSwitchState };
+}): ReactElement | null {
const aui = useAui();
const isLoading = useAuiState(({ threads }) => threads.isLoading);
+ const mainThreadId = useAuiState(({ threads }) => threads.mainThreadId);
const checkpoint = useChatRuntimeStore((s) => s.params.checkpoint);
const ggufContextLength = useChatRuntimeStore((s) => s.ggufContextLength);
const modelLoading = useChatRuntimeStore((s) => s.modelLoading);
@@ -1708,18 +1851,200 @@ function ThreadNewChatSwitch({
);
// The outgoing thread is not read here: New Chat leaves it running.
useEffect(() => {
- if (isLoading) {
+ if (isLoading || paused) {
+ return;
+ }
+ const switchState = newThreadSwitchStateRef.current;
+ if (switchState.activeNonce === nonce) {
return;
}
+ // Only this nonce's own thread, and only once sent to: a blank placeholder is still
+ // replaced, as a new nonce and an untouched landing both expect.
+ const recorded =
+ switchState.nonceThread?.nonce === nonce
+ ? switchState.nonceThread.threadId
+ : null;
+ const runtimeThreads = aui.threads().__internal_getAssistantRuntime?.();
+ // Guarded, unlike the reads elsewhere that pass an id the runtime just handed back: this
+ // one is REMEMBERED, in a ref that outlives every view switch. getItemById() THROWS
+ // "Entry not available in the store" for a dropped id rather than returning undefined, so
+ // the optional chain would not catch it and the effect would take the app down. Studio
+ // deletes through tombstones today; the point is not to depend on that.
+ let recordedRemoteId: string | undefined;
+ if (recorded) {
+ try {
+ recordedRemoteId = runtimeThreads?.threads
+ .getItemById(recorded)
+ .getState()?.remoteId;
+ } catch {
+ // The thread this nonce remembers is gone; treat it as a nonce that owns nothing.
+ recordedRemoteId = undefined;
+ }
+ }
+ // A tombstoned chat is not one to return to, for the same reason and by the same
+ // mechanism as the resume restore above: deletion leaves the runtime item and its
+ // remoteId intact, so "the store still knows it" is not "it still exists". Falling
+ // through clears nonceThread below, which is what a nonce owning nothing looks like.
+ const returningToOwnChat = Boolean(
+ recorded && recordedRemoteId && !isChatThreadDeleted(recordedRemoteId),
+ );
+ if (!returningToOwnChat) {
+ // A new nonce owns nothing yet; the old record must not survive into it.
+ switchState.nonceThread = null;
+ }
+ const shouldClearAttachments = switchState.hasSwitched;
+ const clearAfterSwitch =
+ shouldClearAttachments && switchState.activeNonce === null;
+ const attempt = switchState.attempt + 1;
+ switchState.attempt = attempt;
+ switchState.activeNonce = nonce;
+ switchState.hasSwitched = true;
+ const clearAttachments = () => {
+ try {
+ // Chained, not just called: clearAttachments() removes each staged file through
+ // the attachment adapter, so a rejecting remove() would go unhandled.
+ void Promise.resolve(aui.composer().clearAttachments()).catch(
+ () => undefined,
+ );
+ } catch {
+ // No thread mounted yet, so there is no composer to carry anything over.
+ }
+ };
+ if (shouldClearAttachments && !clearAfterSwitch) {
+ clearAttachments();
+ }
// Saved chats keep running in the background. A temporary chat is never
// persisted, so abandoning it must also discard its otherwise unreachable
// queue. Queue provenance remains reliable even if incognito was cleared first.
requestTemporaryPromptQueueStop();
+ // A reopen is as cancellable as a saved switch: a project landing remounts with the
+ // OLD nonce and rotates it in an effect, so the reopen is already in flight when the
+ // rotation starts its own. Claimed so a reopen that resolves last is undone below.
+ let reopenClaim: PendingSavedThreadSwitch | null = null;
+ if (returningToOwnChat && recorded) {
+ reopenClaim = { id: recorded, settled: false };
+ switchState.pendingSavedThreadIds.push(reopenClaim);
+ if (
+ switchState.pendingSavedThreadIds.length >
+ MAX_PENDING_SAVED_THREAD_SWITCHES
+ ) {
+ switchState.pendingSavedThreadIds.splice(
+ 0,
+ switchState.pendingSavedThreadIds.length -
+ MAX_PENDING_SAVED_THREAD_SWITCHES,
+ );
+ }
+ }
+ // Dropped when this nonce is still on screen: the reopen did its job and an armed
+ // claim would have the correction undo it. Left armed only if the nonce moved on.
+ const settleReopenClaim = () => {
+ if (!reopenClaim) return;
+ reopenClaim.settled = true;
+ const switchStateNow = newThreadSwitchStateRef.current;
+ if (switchStateNow.activeNonce !== nonce) return;
+ const at = switchStateNow.pendingSavedThreadIds.indexOf(reopenClaim);
+ if (at !== -1) switchStateNow.pendingSavedThreadIds.splice(at, 1);
+ };
// Switch to a fresh local thread without persisting it yet; persistence
// still happens on first message append.
- void aui.threads().switchToNewThread();
+ void Promise.resolve(
+ returningToOwnChat && recorded
+ ? aui.threads().switchToThread(recorded)
+ : aui.threads().switchToNewThread(),
+ ).then(
+ () => {
+ settleReopenClaim();
+ // This attempt's own switch has landed, so the main thread from here on is one it
+ // opened. Only for the CURRENT attempt: a superseded switch landing late says
+ // nothing about the thread a newer one is on.
+ {
+ const switchStateNow = newThreadSwitchStateRef.current;
+ if (switchStateNow.attempt === attempt) {
+ switchStateNow.landedAttempt = attempt;
+ }
+ }
+ if (!clearAfterSwitch) return;
+ const switchStateNow = newThreadSwitchStateRef.current;
+ // By attempt as well as nonce, matching the rejection arm. A saved-thread detour
+ // releases the nonce, so returning starts a newer attempt; without the attempt check
+ // this older completion still matches on nonce and wipes an attachment the newer one
+ // staged. The nonce check stays: the detour nulls it without bumping the attempt.
+ if (switchStateNow.attempt !== attempt) return;
+ if (switchStateNow.activeNonce !== nonce) return;
+ clearAttachments();
+ },
+ () => {
+ settleReopenClaim();
+ // The fresh thread never opened, so the view is still on the outgoing one.
+ // Release the nonce, or the guard at the top of this effect reads it as already
+ // served and the same New Chat can never be retried in place. Both arms are
+ // handled, so a rejection is never unhandled.
+ const switchStateNow = newThreadSwitchStateRef.current;
+ // By attempt, not by nonce alone: a later switch for the same nonce owns the
+ // thread it opened, and releasing it would switch away from a chat in use.
+ if (
+ switchStateNow.attempt === attempt &&
+ switchStateNow.activeNonce === nonce
+ ) {
+ switchStateNow.activeNonce = null;
+ }
+ },
+ );
useChatRuntimeStore.getState().setActiveThreadId(null);
- }, [aui, isLoading, nonce]);
+ }, [aui, isLoading, newThreadSwitchStateRef, nonce, paused]);
+
+ // Reassert this view's thread when a switch started before it lands anyway.
+ //
+ // Leaving a landing for a saved chat and coming back before switchToThread resolves used
+ // to end with assistant-ui assigning that saved thread as the main one: the promise does
+ // not know the route moved, and the shared provider has no remount to absorb it, so the
+ // next message went to the wrong conversation. Recognised by the exact id that switch
+ // asked for, which ThreadAutoSwitch records; the claim clears when honoured, so this fires
+ // once per stale arrival.
+ useEffect(() => {
+ if (isLoading || paused) {
+ return;
+ }
+ const switchState = newThreadSwitchStateRef.current;
+ if (switchState.activeNonce !== nonce) {
+ return;
+ }
+ // Already on the thread this nonce owns, so there is nothing to correct -- and the claim
+ // here is the sibling effect's OWN reopen. switchToThread() early-returns when its target
+ // is already current (assistant-ui#2577), so the reopen resolves on a microtask and its
+ // claim is still outstanding in the same commit. Reading that as a stale arrival replaced
+ // the conversation with a blank chat, via Back from a materialized ?new= chat's own row.
+ if (
+ mainThreadId &&
+ switchState.nonceThread?.nonce === nonce &&
+ switchState.nonceThread.threadId === mainThreadId
+ ) {
+ return;
+ }
+ const claimed = mainThreadId
+ ? switchState.pendingSavedThreadIds.findIndex((claim) => claim.id === mainThreadId)
+ : -1;
+ if (claimed === -1) {
+ // Not a stale arrival, so this is the thread this view owns. Recorded here, not at
+ // the switch: the id changes on materialization and a reattach needs the persisted one.
+ // Only once this nonce's own switch has landed, though -- until then `mainThreadId` is
+ // still the chat the user came FROM.
+ if (mainThreadId && switchState.landedAttempt === switchState.attempt) {
+ switchState.nonceThread = { nonce, threadId: mainThreadId };
+ }
+ return;
+ }
+ switchState.pendingSavedThreadIds.splice(claimed, 1);
+ const reattachTo =
+ switchState.nonceThread?.nonce === nonce
+ ? switchState.nonceThread.threadId
+ : null;
+ void Promise.resolve(
+ reattachTo && reattachTo !== mainThreadId
+ ? aui.threads().switchToThread(reattachTo)
+ : aui.threads().switchToNewThread(),
+ ).catch(() => undefined);
+ }, [aui, isLoading, mainThreadId, newThreadSwitchStateRef, nonce, paused]);
// The effect above blanks the bar, and this view reaches no other recount trigger: no persisted
// thread for the history loader, and ActiveThreadSync is off while a nonce is present. Keyed on
@@ -1727,6 +2052,7 @@ function ThreadNewChatSwitch({
useEffect(() => {
if (
isLoading ||
+ paused ||
modelLoading ||
runActive ||
!checkpoint ||
@@ -1747,6 +2073,7 @@ function ThreadNewChatSwitch({
isLoading,
modelLoading,
nonce,
+ paused,
runActive,
]);
@@ -1771,6 +2098,54 @@ function ActiveThreadSync({
return null;
}
+function NonceThreadResumeRestore({
+ enabled,
+}: { enabled: boolean }): ReactElement | null {
+ const aui = useAui();
+ const mainThreadId = useAuiState(({ threads }) => threads.mainThreadId);
+ const wasEnabledRef = useRef(enabled);
+
+ useEffect(() => {
+ const resumed = enabled && !wasEnabledRef.current;
+ wasEnabledRef.current = enabled;
+ if (!resumed) {
+ return;
+ }
+ // Only ever fills a hole. A restore that overwrote a live id would fight whoever set it.
+ if (useChatRuntimeStore.getState().activeThreadId != null) {
+ return;
+ }
+ // Published raw, as ActiveThreadSync does on the paths this stands in for. A `__LOCALID_`
+ // id is NOT a reason to skip: initialize() writes the row under whatever id assistant-ui
+ // minted and hands it back, so skipping would make this a no-op for the ordinary case.
+ // Consumers needing a persisted id filter for themselves.
+ if (!mainThreadId) {
+ return;
+ }
+ // ...but an UNTOUCHED landing must stay untouched: a compare round trip leaves a blank
+ // placeholder here, and publishing it makes ProjectLanding swap the overview for an
+ // empty Thread. On remoteId, not id shape (see above): a materialized chat keeps its
+ // `__LOCALID_` id and has a remoteId; a placeholder has none.
+ const runtime = aui.threads().__internal_getAssistantRuntime?.();
+ const { remoteId } =
+ runtime?.threads.getItemById(mainThreadId).getState() ?? {};
+ if (!remoteId) {
+ return;
+ }
+ // ...and neither must a chat the user deleted while they were away. Studio deletes by
+ // tombstoning storage rather than calling runtime.threads.delete(), so the runtime item
+ // and its remoteId both survive and every check above still passes. On remoteId, which
+ // is the id storage and the sidebar delete agree on. Restoring here would undo
+ // ProjectLanding's own tombstone check: this publishes the id that check refused to.
+ if (isChatThreadDeleted(remoteId)) {
+ return;
+ }
+ useChatRuntimeStore.getState().setActiveThreadId(mainThreadId);
+ }, [aui, enabled, mainThreadId]);
+
+ return null;
+}
+
// A thread read that fails leaves the chat unpaired, so it is worth a couple of goes.
const THREAD_READ_RETRY_MS = 1_500;
const THREAD_READ_RETRIES = 2;
@@ -2115,13 +2490,21 @@ function CancelRegistrar(): ReactElement | null {
function ThreadBackendAutosave({
modelType,
pairId,
+ backgrounded,
+ newThreadSwitchStateRef,
}: {
modelType: ModelType;
pairId?: string;
+ backgrounded: boolean;
+ newThreadSwitchStateRef: { current: NewThreadSwitchState };
}): ReactElement | null {
const aui = useAui();
const saveChainRef = useRef(Promise.resolve());
const pendingFirstSavesRef = useRef(new Map<string, Promise<void>>());
+ // A ref, not a saveThread dependency: the save may be queued while visible and resolve
+ // after Compare hides the pane, so this must read at PUBLISH time, not schedule time.
+ const backgroundedRef = useRef(backgrounded);
+ backgroundedRef.current = backgrounded;
const reportAutosaveError = useCallback((error: unknown): void => {
if (!isExpectedBackgroundChatStorageError(error)) {
@@ -2154,7 +2537,20 @@ function ThreadBackendAutosave({
return;
}
- if (modelType === "base" && !pairId) {
+ // The save still runs while backgrounded; only the PUBLICATION is suppressed, or a hidden
+ // pane reaches Compare's exportThreadIds and Export pulls the unrelated base chat. Same
+ // stand-down mid-switch, for the same reason as the history adapter's publication:
+ // mainThreadId is still the OUTGOING thread until switchToNewThread() resolves.
+ const switchState = newThreadSwitchStateRef.current;
+ const switchInFlight =
+ switchState.activeNonce !== null &&
+ switchState.landedAttempt !== switchState.attempt;
+ if (
+ modelType === "base" &&
+ !pairId &&
+ !backgroundedRef.current &&
+ !switchInFlight
+ ) {
const store = useChatRuntimeStore.getState();
const activeThreadId = runtime.threads.getState().mainThreadId;
if (activeThreadId === threadId && store.activeThreadId !== remoteId) {
@@ -2162,7 +2558,7 @@ function ThreadBackendAutosave({
}
}
},
- [aui, modelType, pairId],
+ [aui, modelType, newThreadSwitchStateRef, pairId],
);
const queueSave = useCallback(
@@ -2231,6 +2627,7 @@ export function ChatRuntimeProvider({
newThreadNonce,
syncActiveThreadId = true,
listThreads = true,
+ backgrounded = false,
onInitialHistoryReady,
}: {
children: ReactNode;
@@ -2241,8 +2638,29 @@ export function ChatRuntimeProvider({
newThreadNonce?: string;
syncActiveThreadId?: boolean;
listThreads?: boolean;
+ // Mounted only to keep an in-flight run attached while another view is on screen. The
+ // runtime stays alive; everything driving the shared single-chat state (active thread,
+ // context bar, thread-scoped settings) stands down so it can't fight the visible view.
+ backgrounded?: boolean;
onInitialHistoryReady?: () => void;
}): ReactElement {
+ // Read by the history adapter's own active-thread publication, which is the sibling of
+ // ThreadBackendAutosave's and needs the same stand-down. Kept in a ref so the memo below
+ // never sees it change: rebuilding the runtime hook would rebuild the runtime, and the
+ // whole point of the shared provider is that it does not.
+ const backgroundedRef = useRef(backgrounded);
+ backgroundedRef.current = backgrounded;
+ // Declared before the memo below because the memo reads it. Same ref the switch
+ // components mutate, so the adapter can tell "this pane is on screen" from "this pane is
+ // the thread we are switching AWAY from and mainThreadId has not caught up yet".
+ const newThreadSwitchStateRef = useRef<NewThreadSwitchState>({
+ activeNonce: null,
+ hasSwitched: false,
+ attempt: 0,
+ pendingSavedThreadIds: [],
+ nonceThread: null,
+ landedAttempt: 0,
+ });
const runtimeHook = useMemo(
() =>
createRuntimeHook(
@@ -2250,6 +2668,8 @@ export function ChatRuntimeProvider({
pairId,
initialThreadId,
onInitialHistoryReady,
+ backgroundedRef,
+ newThreadSwitchStateRef,
),
[initialThreadId, modelType, onInitialHistoryReady, pairId],
);
@@ -2266,40 +2686,81 @@ export function ChatRuntimeProvider({
}, [modelType, onInitialHistoryReady, pairId]);
const aui = useAui({});
+ useEffect(() => {
+ if (!initialThreadId && !newThreadNonce) {
+ newThreadSwitchStateRef.current.hasSwitched = true;
+ }
+ }, [initialThreadId, newThreadNonce]);
return (
<AssistantRuntimeProvider runtime={runtime} aui={aui}>
{/* Pane identity for the tool-output store maps: the adapter prefixes its
keys with this scope so concurrent panes with colliding tool ids
("call_0") can't bleed live output into each other's cards. */}
+ <ChatProjectScopeContext.Provider value={projectId ?? null}>
<ToolPaneScopeContext.Provider value={toolPaneScope(modelType, pairId)}>
<ActiveThreadSync
enabled={
modelType === "base" &&
!pairId &&
!newThreadNonce &&
- !initialThreadId
+ !initialThreadId &&
+ !backgrounded
}
/>
- <ThreadScopedSettingsSync enabled={modelType === "base" && !pairId} />
- <ActiveBranchRegistrar enabled={modelType === "base" && !pairId} />
- <ThreadContextUsageRecount enabled={modelType === "base" && !pairId} />
- <ThreadBackendAutosave modelType={modelType} pairId={pairId} />
+ {/* Compare clears activeThreadId on the way in, and this view is hidden rather
+ than unmounted, so nothing puts it back: the nonce is unchanged so
+ ThreadNewChatSwitch returns, and ActiveThreadSync is off while a nonce is
+ present. ThreadScopedSettingsSync is NOT nonce-gated, so the chat came back
+ detached -- on installation defaults, its edits moving those instead of its
+ own snapshot, with no title, context usage or model notice. ProjectLanding
+ restores on resume for the same reason; this is the single-chat half. */}
+ <NonceThreadResumeRestore
+ enabled={
+ modelType === "base" &&
+ !pairId &&
+ !!newThreadNonce &&
+ !initialThreadId &&
+ !backgrounded
+ }
+ />
+ <ThreadScopedSettingsSync
+ enabled={modelType === "base" && !pairId && !backgrounded}
+ />
+ <ActiveBranchRegistrar
+ enabled={modelType === "base" && !pairId && !backgrounded}
+ />
+ <ThreadContextUsageRecount
+ enabled={modelType === "base" && !pairId && !backgrounded}
+ />
+ <ThreadBackendAutosave
+ modelType={modelType}
+ pairId={pairId}
+ backgrounded={backgrounded}
+ newThreadSwitchStateRef={newThreadSwitchStateRef}
+ />
<CancelRegistrar />
{initialThreadId && (
<ThreadAutoSwitch
threadId={initialThreadId}
- syncActiveThreadId={syncActiveThreadId}
+ syncActiveThreadId={syncActiveThreadId && !backgrounded}
+ paused={backgrounded}
+ newThreadSwitchStateRef={newThreadSwitchStateRef}
onSwitchFailed={signalFailedInitialSwitchReady}
/>
)}
{!initialThreadId && newThreadNonce && (
- <ThreadNewChatSwitch nonce={newThreadNonce} />
+ <ThreadNewChatSwitch
+ nonce={newThreadNonce}
+ paused={backgrounded}
+ newThreadSwitchStateRef={newThreadSwitchStateRef}
+ />
)}
{/* The view stays mounted (only CSS-hidden) while off-route so the run
stays attached and the stream alive; unmounting aborts generation. */}
{children}
</ToolPaneScopeContext.Provider>
+ </ChatProjectScopeContext.Provider>
</AssistantRuntimeProvider>
);
}
diff --git a/studio/frontend/src/features/chat/utils/chat-thread-creation-claim.ts b/studio/frontend/src/features/chat/utils/chat-thread-creation-claim.ts
new file mode 100644
index 00000000000..44e68a9dfe2
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/chat-thread-creation-claim.ts
@@ -0,0 +1,87 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * The creation inputs a first send was made under, captured when the user pressed Send.
+ *
+ * `initialize()` snapshots project, temporary status, model and creation time when the
+ * thread MATERIALIZES, which used to be the same tick as the send. Two things separated
+ * them: `BaseComposerRuntimeCore.send()` awaits every incomplete attachment before
+ * `handleSend` and Studio's PDF/DOCX/text adapters extract there, and the shared provider
+ * (#8908) now survives a view switch. Navigating meanwhile moves all four -- the adapter is
+ * rebuilt with the new project, and ChatPage's view effect clears `incognito` -- so a
+ * document sent from a Temporary Chat, or from one project into another, was created under
+ * wherever the user ended up. `ensureThreadRecord` already takes these as snapshot
+ * parameters; this is what lets the caller supply them from the send.
+ *
+ * Per SEND, not per thread creation: `switchToNewThread()` reuses an untouched blank thread,
+ * so one local id can be the current new thread in two views in a row.
+ */
+export type ThreadCreationClaim = {
+ projectId: string | null;
+ incognito: boolean;
+ modelId: string;
+ createdAt: number;
+};
+
+const claimsByThreadId = new Map<string, ThreadCreationClaim & { claimedAt: number }>();
+
+/**
+ * Bounded rather than consumed on read: `initialize()` and the run adapter both read a claim
+ * with no ordering guarantee between them, so releasing on the first starves the second.
+ * Expiry is safe -- a persisted row makes `ensureThreadRecord` early-return, a fresh thread
+ * always gets a fresh local id, and every send overwrites the ids it stamps.
+ */
+const CLAIM_TTL_MS = 10 * 60 * 1000;
+const MAX_CLAIMS = 64;
+
+function gc(now: number): void {
+ for (const [threadId, claim] of claimsByThreadId) {
+ if (now - claim.claimedAt > CLAIM_TTL_MS) {
+ claimsByThreadId.delete(threadId);
+ }
+ }
+ while (claimsByThreadId.size > MAX_CLAIMS) {
+ const oldest = claimsByThreadId.keys().next();
+ if (oldest.done) break;
+ claimsByThreadId.delete(oldest.value);
+ }
+}
+
+/** The composer, before `send()` starts awaiting; the queue, before it initializes. */
+export function claimThreadCreation(
+ threadIds: Iterable<string | null | undefined>,
+ claim: ThreadCreationClaim,
+): void {
+ const now = Date.now();
+ for (const threadId of threadIds) {
+ if (!threadId) continue;
+ claimsByThreadId.set(threadId, { ...claim, claimedAt: now });
+ }
+ gc(now);
+}
+
+/**
+ * The whole claim, so a value OF null or false (no project, not temporary) stays
+ * distinguishable from no claim: the first wins over the store, the second defers to it.
+ */
+export function readThreadCreationClaim(
+ threadId: string,
+): ThreadCreationClaim | undefined {
+ const claim = claimsByThreadId.get(threadId);
+ if (!claim) return undefined;
+ if (Date.now() - claim.claimedAt > CLAIM_TTL_MS) {
+ claimsByThreadId.delete(threadId);
+ return undefined;
+ }
+ return {
+ projectId: claim.projectId,
+ incognito: claim.incognito,
+ modelId: claim.modelId,
+ createdAt: claim.createdAt,
+ };
+}
+
+export function __resetThreadCreationClaimsForTests(): void {
+ claimsByThreadId.clear();
+}
diff --git a/studio/frontend/tests/project-attachment-target-adoption.test.ts b/studio/frontend/tests/project-attachment-target-adoption.test.ts
index 3b77e4fad18..b0c1e3f4f70 100644
--- a/studio/frontend/tests/project-attachment-target-adoption.test.ts
+++ b/studio/frontend/tests/project-attachment-target-adoption.test.ts
@@ -142,8 +142,10 @@ test("the run keeps the project it started in", () => {
assert.match(
source,
// Whichever await comes first: the property is that the read is the run's
- // last synchronous statement, not which call follows it.
- /const composerProjectIdAtSend =\s*useChatRuntimeStore\.getState\(\)\.activeProjectId \?\? null;\s*(?:\/\/[^\n]*\n\s*)*await /,
+ // last synchronous statement, not which call follows it. The send-time stamp
+ // takes precedence over the store (#9129: a document send lands after the
+ // user may have navigated), but both reads stay on this side of the await.
+ /const composerProjectIdAtSend = creationClaim\s*\? creationClaim\.projectId\s*: \(useChatRuntimeStore\.getState\(\)\.activeProjectId \?\? null\);\s*(?:\/\/[^\n]*\n\s*)*await /,
"captured before the first await",
);
assert.match(
diff --git a/studio/frontend/tests/project-chat-run-keepalive.test.ts b/studio/frontend/tests/project-chat-run-keepalive.test.ts
new file mode 100644
index 00000000000..ba313130167
--- /dev/null
+++ b/studio/frontend/tests/project-chat-run-keepalive.test.ts
@@ -0,0 +1,436 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// #8908: a chat started inside a project ran under ProjectLanding's own
+// ChatRuntimeProvider, so leaving the project view mid-response unmounted the runtime,
+// useLocalRuntime's cleanup called detach(), and the backend cancelled on the disconnect.
+// The fix is structural and invisible until somebody navigates mid-run, so the shape is
+// pinned here: one provider above the project/single switch, no key, compare a sibling
+// rather than a replacement.
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+const page = readFileSync(
+ new URL("../src/features/chat/chat-page.tsx", import.meta.url),
+ "utf8",
+);
+const provider = readFileSync(
+ new URL("../src/features/chat/runtime-provider.tsx", import.meta.url),
+ "utf8",
+);
+
+/** The source of one component, from its declaration to the next one. */
+function componentSource(source: string, declaration: string): string {
+ const start = source.indexOf(declaration);
+ assert.notEqual(start, -1, `${declaration} not found`);
+ // Both closers: a plain declaration ends at a column-0 "}", a memo() wrapper at "});".
+ // Anything nested is indented, so neither matches early.
+ const ends = ["\n}\n", "\n});\n"]
+ .map((closer) => source.indexOf(closer, start))
+ .filter((index) => index !== -1);
+ assert.notEqual(ends.length, 0, `end of ${declaration} not found`);
+ return source.slice(start, Math.min(...ends));
+}
+
+test("one runtime provider sits above the project/single switch", () => {
+ const mounts = page.match(/<ChatRuntimeProvider/g) ?? [];
+ assert.equal(
+ mounts.length,
+ 2,
+ "one shared provider plus ComparePane's own; a third means a view built its own again",
+ );
+
+ // ComparePane keeps its own: two panes need two runtimes, and
+ // useRemoteThreadListRuntime throws when providers nest.
+ const comparePane = componentSource(page, "function ComparePane({");
+ assert.equal(
+ (comparePane.match(/<ChatRuntimeProvider/g) ?? []).length,
+ 1,
+ "ComparePane owns exactly one",
+ );
+
+ // The two views the bug was about must not build one, or switching between them
+ // remounts the runtime and cuts the run off again.
+ for (const declaration of [
+ "const SingleContent = memo(function SingleContent({",
+ "function ProjectLanding({",
+ ]) {
+ assert.equal(
+ componentSource(page, declaration).includes("<ChatRuntimeProvider"),
+ false,
+ `${declaration} must render under the shared provider, not build one`,
+ );
+ }
+});
+
+test("the shared provider is never keyed", () => {
+ // A key is indistinguishable from remounting: by project (the state before the fix),
+ // by thread, or by nonce all restore #8908.
+ const openingTags = page.match(/<ChatRuntimeProvider[\s\S]*?\n\s*>/g) ?? [];
+ assert.equal(openingTags.length, 2);
+ for (const tag of openingTags) {
+ assert.equal(tag.includes("key="), false, `keyed provider: ${tag}`);
+ }
+
+ // The project's new-chat nonce is owned by ChatPage, not ProjectLanding: the latter
+ // lives under the provider, so a nonce held there would be invisible to it.
+ assert.match(
+ page,
+ /const \[projectNewThreadNonce, setProjectNewThreadNonce\] = useState\(/,
+ );
+});
+
+test("compare hides the shared provider instead of unmounting it", () => {
+ // Rendering CompareContent in the provider's place unmounts it: the same detach()/cancel
+ // path as #8908, reachable now that a run survives the navigation before a compare open.
+ assert.match(page, /const baseBackgrounded = view\.mode === "compare";/);
+ assert.match(page, /inert=\{baseBackgrounded \|\| undefined\}/);
+ assert.match(page, /\{view\.mode === "compare" \? \(\s*<CompareContent/);
+ assert.equal(
+ /\) : \(\s*<CompareContent/.test(page),
+ false,
+ "compare must be a sibling of the provider, not its alternative",
+ );
+
+ // Hidden, it must not drive the shared single-chat state the compare view is using.
+ assert.match(page, /backgrounded=\{baseBackgrounded\}/);
+ for (const gated of [
+ /<ActiveThreadSync\s+enabled=\{[\s\S]*?!backgrounded\s*\}/,
+ /<ThreadScopedSettingsSync\s+enabled=\{[^}]*!backgrounded\s*\}/,
+ /<ActiveBranchRegistrar\s+enabled=\{[^}]*!backgrounded\s*\}/,
+ /<ThreadContextUsageRecount\s+enabled=\{[^}]*!backgrounded\s*\}/,
+ /<ThreadNewChatSwitch[\s\S]*?nonce=\{newThreadNonce\}[\s\S]*?paused=\{backgrounded\}[\s\S]*?\/>/,
+ // The saved-thread switch stands down too: its first effect calls
+ // requestTemporaryPromptQueueStop(), which names every temporary queue on the page
+ // rather than this provider's, so a hidden pane reaching it would stop a queue the
+ // compare view owns. syncActiveThreadId is a dependency, so the effect re-runs on
+ // every compare open and close.
+ /<ThreadAutoSwitch[\s\S]*?paused=\{backgrounded\}[\s\S]*?\/>/,
+ ]) {
+ assert.match(provider, gated);
+ }
+
+ const savedThreadSwitch = componentSource(
+ provider,
+ "function ThreadAutoSwitch({",
+ );
+ assert.match(savedThreadSwitch, /if \(isLoading \|\| paused\) \{/);
+});
+
+test("a switch that never opens releases its nonce", () => {
+ // switchToNewThread() marks the nonce served before it resolves, so a rejection would
+ // leave the guard reading it as handled and the same New Chat could never be retried in
+ // place. Both arms are handled, so the rejection is never unhandled either.
+ const switchSource = componentSource(
+ provider,
+ "function ThreadNewChatSwitch({",
+ );
+ // Either arm of the returning-nonce choice: a nonce coming back to a chat it already
+ // owns reopens that thread instead of minting, and both go through the same handled
+ // .then(ok, err) pair. What this pins is that neither is left unhandled.
+ assert.match(
+ switchSource,
+ /void Promise\.resolve\([\s\S]*?aui\.threads\(\)\.switchToNewThread\(\),?\s*\)\.then\(/,
+ );
+ assert.match(
+ switchSource,
+ /returningToOwnChat && recorded\s*\?\s*aui\.threads\(\)\.switchToThread\(recorded\)/,
+ );
+ // Keyed by attempt as well as nonce: leaving for a saved chat releases the nonce, so
+ // two switches for one nonce can overlap and the older must not release the newer's
+ // thread.
+ assert.match(
+ switchSource,
+ /if \(\s*switchStateNow\.attempt === attempt &&\s*switchStateNow\.activeNonce === nonce\s*\) \{\s*switchStateNow\.activeNonce = null;\s*\}/,
+ );
+ assert.match(switchSource, /const attempt = switchState\.attempt \+ 1;/);
+ // clearAttachments() removes each staged file through the attachment adapter, so the
+ // promise needs handling and not just the synchronous call.
+ assert.match(
+ switchSource,
+ /void Promise\.resolve\(aui\.composer\(\)\.clearAttachments\(\)\)\.catch\(\s*\(\) => undefined,\s*\);/,
+ );
+});
+
+test("compare preserves a materialized project chat", () => {
+ const landing = componentSource(page, "function ProjectLanding({");
+ assert.match(landing, /const wasActiveRef = useRef\(active\);/);
+ assert.match(
+ landing,
+ /const resumed = active && !wasActiveRef\.current;\s*wasActiveRef\.current = active;\s*if \(!active\) \{\s*return;\s*\}/,
+ );
+ assert.match(
+ landing,
+ /if \(resumed && pendingNewThreadId\) \{[\s\S]*?useChatRuntimeStore\.getState\(\)\.setActiveThreadId\(pendingNewThreadId\);\s*return;/,
+ );
+});
+
+test("a staged attachment does not follow the user into the next view", () => {
+ // switchToNewThread() reuses the uninitialized new thread rather than minting one, and
+ // the composer belongs to that thread. With the provider shared it is the same composer
+ // across a project switch, so an unsent attachment would land in the next project's chat.
+ assert.match(
+ provider,
+ /const switchState = newThreadSwitchStateRef\.current;\s*if \(switchState\.activeNonce === nonce\) \{\s*return;\s*\}/,
+ );
+ assert.match(
+ provider,
+ /const clearAfterSwitch =[\s\S]{0,160}?switchState\.activeNonce === null;/,
+ );
+ const switchSource = componentSource(
+ provider,
+ "function ThreadNewChatSwitch({",
+ );
+ assert.equal(
+ switchSource.includes("useRef<NewThreadSwitchState>"),
+ false,
+ "the nonce guard must outlive ThreadNewChatSwitch mounts",
+ );
+ const runtimeProvider = componentSource(
+ provider,
+ "export function ChatRuntimeProvider({",
+ );
+ assert.match(
+ runtimeProvider,
+ /const newThreadSwitchStateRef = useRef<NewThreadSwitchState>\(\{\s*activeNonce: null,\s*hasSwitched: false,\s*attempt: 0,\s*pendingSavedThreadIds: \[\],\s*nonceThread: null,\s*landedAttempt: 0,\s*\}\);/,
+ );
+ assert.match(
+ runtimeProvider,
+ /if \(!initialThreadId && !newThreadNonce\) \{\s*newThreadSwitchStateRef\.current\.hasSwitched = true;\s*\}/,
+ );
+ assert.match(
+ runtimeProvider,
+ /<ThreadNewChatSwitch[\s\S]*?newThreadSwitchStateRef=\{newThreadSwitchStateRef\}[\s\S]*?\/>/,
+ );
+ const savedThreadSwitch = componentSource(
+ provider,
+ "function ThreadAutoSwitch({",
+ );
+ assert.match(
+ savedThreadSwitch,
+ /newThreadSwitchStateRef\.current\.activeNonce = null;/,
+ );
+ assert.match(
+ runtimeProvider,
+ /<ThreadAutoSwitch[\s\S]*?newThreadSwitchStateRef=\{newThreadSwitchStateRef\}[\s\S]*?\/>/,
+ );
+});
+
+test("the outgoing thread id is captured before the provider blanks it", () => {
+ // ThreadNewChatSwitch is an earlier sibling, so on an already-mounted provider its
+ // effect reaches setActiveThreadId(null) before ProjectLanding's effects run. Read in
+ // an effect, the guard below would compare against null forever and Back into a project
+ // would swap the landing for the chat the user just left.
+ assert.match(
+ page,
+ /const \[initialActiveThreadId\] = useState\(\s*\(\) => useChatRuntimeStore\.getState\(\)\.activeThreadId,\s*\);/,
+ );
+ assert.match(
+ page,
+ /if \(\s*activeThreadId === initialActiveThreadId \|\|\s*activeThreadId === pendingNewThreadId\s*\) \{/,
+ );
+ assert.equal(
+ page.includes("initialActiveThreadRef"),
+ false,
+ "no effect-assigned ref left behind",
+ );
+});
+
+test("a nonce only owns a thread its own switch opened", () => {
+ const switchSource = componentSource(provider, "function ThreadNewChatSwitch(");
+ // The record is the thing the reopen runs on. Taking it from whatever thread happens to
+ // be current recorded the chat the user came FROM, because that chat's own claim was
+ // retired while it was on screen and an unclaimed current thread looks like an arrival.
+ assert.match(
+ switchSource,
+ /if \(mainThreadId && switchState\.landedAttempt === switchState\.attempt\) \{\s*switchState\.nonceThread = \{ nonce, threadId: mainThreadId \};/,
+ );
+ // ...and the only thing that sets landedAttempt is that attempt's own switch resolving.
+ assert.match(
+ switchSource,
+ /if \(switchStateNow\.attempt === attempt\) \{\s*switchStateNow\.landedAttempt = attempt;/,
+ );
+});
+
+test("the remembered thread is looked up defensively", () => {
+ const switchSource = componentSource(provider, "function ThreadNewChatSwitch(");
+ // getItemById throws for an id the store has dropped rather than returning undefined, so
+ // the optional chain is not the guard it looks like, and an effect that throws with no
+ // error boundary above it takes the app down. The id here is remembered across every view
+ // switch, which is exactly the kind that can go stale.
+ assert.match(
+ switchSource,
+ /try \{\s*recordedRemoteId = runtimeThreads\?\.threads\s*\.getItemById\(recorded\)\s*\.getState\(\)\?\.remoteId;\s*\} catch \{/,
+ );
+});
+
+test("every active-thread publication stands down while backgrounded", () => {
+ // ThreadBackendAutosave's publication is gated, and so is the history adapter's sibling
+ // inside append() -- which is the one a background run reaches when its assistant message
+ // is persisted during compare. Ungated, a hidden pane names itself active and compare's
+ // exportThreadIds ([model1, model2, activeThreadId]) picks up the unrelated base chat.
+ const publications = provider.match(/setActiveThreadId\(/g) ?? [];
+ assert.ok(publications.length >= 6, "expected the publications to still be here");
+ assert.match(
+ provider,
+ /!backgroundedRef\?\.current &&\s*!switchInFlight\s*\) \{[\s\S]*?store\.setActiveThreadId\(remoteId\);/,
+ );
+ assert.match(
+ provider,
+ /!backgroundedRef\.current &&\s*!switchInFlight\s*\) \{[\s\S]*?store\.setActiveThreadId\(remoteId\);/,
+ );
+ // The refs reach the adapter without joining the memo's dependencies: a new runtime-hook
+ // identity would rebuild the runtime, and not rebuilding it is the whole point.
+ assert.match(
+ provider,
+ /createRuntimeHook\(\s*modelType,\s*pairId,\s*initialThreadId,\s*onInitialHistoryReady,\s*backgroundedRef,\s*newThreadSwitchStateRef,\s*\),\s*\[initialThreadId, modelType, onInitialHistoryReady, pairId\],/,
+ );
+});
+
+test("a publication landing mid-switch does not reclaim the view", () => {
+ // switchToNewThread() is async, so mainThreadId is still the OUTGOING thread until it
+ // resolves, and both publications read it as proof that "this pane is on screen". A write
+ // landing in that gap republishes the chat the user just left, and the project view (opened
+ // with no active thread) renders it inside the new project. attempt !== landedAttempt is
+ // that window.
+ const guards =
+ provider.match(
+ /const switchInFlight[\s\S]{0,240}?switchState\.landedAttempt !== switchState\.attempt/g,
+ ) ?? [];
+ assert.equal(guards.length, 2, "both publications need the same stand-down");
+ for (const guard of guards) {
+ assert.match(guard, /activeNonce !== null/);
+ }
+ // Both read the SAME ref the switch components mutate, so the two never disagree.
+ assert.match(
+ provider,
+ /<ThreadBackendAutosave[\s\S]*?newThreadSwitchStateRef=\{newThreadSwitchStateRef\}[\s\S]*?\/>/,
+ );
+});
+
+test("the landing does not restore a chat that was deleted while it was away", () => {
+ // Retaining the chat across the detour is what this PR added; at the merge base the landing
+ // unmounted and there was nothing to restore. Nothing else clears the retained id: it is
+ // component state, the sidebar deletes globally without reaching it, and compare does not
+ // hold the chat as the store's active id. So a chat deleted during compare came back on
+ // screen with a composer pointed at it.
+ const restore = page.slice(
+ page.indexOf("const resumed = active && !wasActiveRef.current;"),
+ );
+ const guard = restore.slice(0, restore.indexOf("// Leaving a created chat"));
+ assert.match(guard, /if \(!isChatThreadDeleted\(pendingNewThreadId\)\) \{/);
+ assert.ok(
+ guard.indexOf("isChatThreadDeleted(pendingNewThreadId)") <
+ guard.indexOf("setActiveThreadId(pendingNewThreadId)"),
+ "the check has to come before the restore it guards",
+ );
+ // Falling through rather than returning: the rotate below is what leaves the landing
+ // with a fresh thread to send into instead of a dangling retained id.
+ assert.doesNotMatch(guard, /isChatThreadDeleted\(pendingNewThreadId\)\) \{\s*return;/);
+ assert.match(page, /import \{ isChatThreadDeleted \} from "\.\/utils\/chat-thread-tombstones";/);
+});
+
+test("no restore path puts a deleted chat back on screen", () => {
+ // Three places put a retained id back: ProjectLanding's resume effect (pinned above),
+ // NonceThreadResumeRestore, and the remembered-nonce reopen. All three ask the RUNTIME
+ // whether it still knows the thread, and Studio deletes by tombstoning storage rather than
+ // calling runtime.threads.delete(), so all three still answer yes after a delete. Guarding
+ // one fixes nothing.
+ const restore = componentSource(provider, "function NonceThreadResumeRestore({");
+ assert.match(restore, /if \(isChatThreadDeleted\(remoteId\)\) \{\s*return;\s*\}/);
+ assert.ok(
+ restore.indexOf("isChatThreadDeleted(remoteId)") <
+ restore.indexOf("setActiveThreadId(mainThreadId)"),
+ "the check has to come before the publication it guards",
+ );
+ assert.match(
+ provider,
+ /const returningToOwnChat = Boolean\(\s*recorded && recordedRemoteId && !isChatThreadDeleted\(recordedRemoteId\),\s*\);/,
+ );
+});
+
+test("a delayed first send keeps the creation inputs it was sent under", () => {
+ // The adapter is rebuilt every render and handed to the core via __internal_setOptions, so
+ // initialize() reads the provider's LATEST projectId. send() awaits every incomplete
+ // attachment before handleSend and Studio's PDF/DOCX/text adapters extract there, so with
+ // the provider surviving a project switch a document send materializes in whichever project
+ // is on screen by then.
+ const thread = readFileSync(
+ new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),
+ "utf8",
+ );
+ assert.match(
+ thread,
+ /claimThreadCreation\([\s\S]*?\);\s*aui\.composer\(\)\.send\(\);/,
+ "the stamp has to be taken before send() starts awaiting, not after",
+ );
+ // The prompt queue initializes its own fresh thread and never passes the composer, so it
+ // has to stamp too, from what it captured when the queue started.
+ assert.match(
+ thread,
+ /if \(initializingFreshThread\) \{\s*claimThreadCreation\(\[state\.id, state\.remoteId\], \{\s*projectId: projectIdAtQueueStart,\s*incognito: incognitoAtQueueStart,/,
+ );
+ // Per SEND, not per thread creation: switchToNewThread() reuses an untouched blank
+ // thread, so the same local id can be the current new thread in two views in a row.
+ assert.doesNotMatch(provider, /claimThreadCreation\(/);
+ // Every field, not just the project. ChatPage's view effect clears `incognito` on the way
+ // into a project, so a document sent from a Temporary Chat was persisted as a normal one.
+ assert.match(provider, /const claim = readThreadCreationClaim\(threadId\);/);
+ for (const field of [
+ /const incognitoAtInit = claim \? claim\.incognito : runtimeStateAtInit\.incognito;/,
+ /const modelIdAtInit = claim\s*\? claim\.modelId/,
+ /const createdAtInit = claim \? claim\.createdAt : Date\.now\(\);/,
+ /const projectIdAtInit = claim \? claim\.projectId : projectId;/,
+ ]) {
+ assert.match(provider, field);
+ }
+ // A claim OF null/false must win over what the store holds now; `claim?.x ?? store` would
+ // read it as no claim at all.
+ assert.doesNotMatch(provider, /claim\?\.(projectId|incognito|modelId|createdAt) \?\?/);
+
+ // The RUN resolves its project separately from the record write, and takes the run's
+ // instructions, RAG sources and sandbox from it. It reads the same stamp.
+ const adapter = readFileSync(
+ new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),
+ "utf8",
+ );
+ assert.match(
+ adapter,
+ /const creationClaim = unstable_threadId\s*\? readThreadCreationClaim\(unstable_threadId\)\s*: undefined;\s*const composerProjectIdAtSend = creationClaim\s*\? creationClaim\.projectId/,
+ );
+ // ...and the claim has to outlive initialize(), because there is no ordering guarantee
+ // between the two readers. Consuming it on the first read starves the second.
+ assert.doesNotMatch(provider, /releaseThreadCreationClaim/);
+ const claimModule = readFileSync(
+ new URL("../src/features/chat/utils/chat-thread-creation-claim.ts", import.meta.url),
+ "utf8",
+ );
+ assert.doesNotMatch(claimModule, /export function releaseThreadCreationClaim/);
+});
+
+test("compare lists its threads once before it waits on any run", () => {
+ // Two constraints one boolean cannot carry. The wait has to be GLOBAL, because a first
+ // compare run starts before either thread exists and files its handles under "__default";
+ // and it has to exist at all, because these ids feed ComparePane's `initialThreadId`, so
+ // learning them mid-run points ThreadAutoSwitch at a generating thread. But the shared
+ // provider keeps a base chat's run alive across the switch into compare, so a global wait
+ // on the FIRST list left an existing compare on blank runtimes with no later edge to
+ // recover on. That list has nothing to clobber, so only re-lists wait.
+ const waits =
+ page.match(
+ /const anyRunning = useChatRuntimeStore\(\s*\(s\) => Object\.keys\(s\.runningByThreadId\)\.length > 0,\s*\);/g,
+ ) ?? [];
+ assert.equal(waits.length, 2, "both compare variants share the global wait");
+ const gates =
+ page.match(
+ /if \(anyRunning && listedPairRef\.current === pairId\) return;\s*listedPairRef\.current = pairId;/g,
+ ) ?? [];
+ assert.equal(gates.length, 2, "both variants must exempt their first list");
+ assert.equal(
+ (page.match(/\}, \[pairId, anyRunning\]\);/g) ?? []).length,
+ 2,
+ "the settle edge is what re-lists; without it a fresh pair never learns its ids",
+ );
+});
diff --git a/studio/frontend/tests/reload-snapshot.test.ts b/studio/frontend/tests/reload-snapshot.test.ts
index 3ef2d9969ce..6dce333f8e2 100644
--- a/studio/frontend/tests/reload-snapshot.test.ts
+++ b/studio/frontend/tests/reload-snapshot.test.ts
@@ -826,9 +826,22 @@ test("mirrors Temporary Chat privacy and lets history completion retire chat she
runtimeProviderSource,
/!reloadReadyThreadId \|\| loadedThreadId === reloadReadyThreadId/,
);
+ // The rejection arm is a .then(onFulfilled, onRejected) pair since #8908, which needs
+ // both outcomes: that PR retires the switch's claim on either. What this guards is
+ // unchanged -- a failed switchToThread still releases the retained shell -- and the
+ // call must stay AHEAD of that PR's staleness guard, since a superseded attempt is
+ // still an attempt that ended and the shell would otherwise wait for ever.
assert.match(
runtimeProviderSource,
- /switchToThread\(threadId\)[\s\S]*?\.catch\(\(\) => \{[\s\S]*?onSwitchFailed\?\.\(\)/,
+ /switchToThread\(threadId\)[\s\S]*?\.then\([\s\S]*?onSwitchFailed\?\.\(\)/,
+ );
+ const rejectionArm = runtimeProviderSource.slice(
+ runtimeProviderSource.indexOf("onSwitchFailed?.()"),
+ );
+ assert.ok(
+ rejectionArm.indexOf("onSwitchFailed?.()") <
+ rejectionArm.indexOf("attempt !== attemptAtStart"),
+ "onSwitchFailed must fire before the staleness guard can return early",
);
assert.match(
runtimeProviderSource,
diff --git a/tests/studio/test_multi_chat_prompt_queue_contract.py b/tests/studio/test_multi_chat_prompt_queue_contract.py
index 2484004aff2..e56f2fbb134 100644
--- a/tests/studio/test_multi_chat_prompt_queue_contract.py
+++ b/tests/studio/test_multi_chat_prompt_queue_contract.py
@@ -864,3 +864,110 @@ def test_sidebar_exposes_queue_activity_for_each_thread():
assert "{showWorkSpinner && (" in APP_SIDEBAR
assert "hasUnreadActivity" in APP_SIDEBAR
assert "clearChatNotifications(item)" in APP_SIDEBAR
+
+
+def test_a_backgrounded_pane_autosaves_without_naming_itself_active():
+ """The shared provider (#9129) keeps a hidden pane's run alive, so its autosave still fires
+ after Compare has hidden it. The SAVE must keep happening; only the active-thread PUBLICATION
+ is suppressed, or the hidden base pane writes its own remote id into the store and Compare's
+ ``exportThreadIds = [model1, model2, activeThreadId]`` downloads the unrelated base
+ conversation alongside the two compare threads.
+ """
+ autosave = _between(
+ RUNTIME_PROVIDER,
+ "function ThreadBackendAutosave(",
+ "\nexport function useChatActive(",
+ )
+
+ # The pane knows it is hidden.
+ assert (
+ "backgrounded: boolean;" in autosave
+ ), "ThreadBackendAutosave has to be told, like every other sync component here"
+ assert (
+ "backgrounded={backgrounded}" in RUNTIME_PROVIDER
+ ), "and the provider has to pass it, or the prop is inert"
+
+ # Read at publish time, not captured when the save was queued: the save that publishes
+ # may have been scheduled while the pane was on screen and resolve long after Compare
+ # hid it.
+ assert "const backgroundedRef = useRef(backgrounded);" in autosave
+ assert "backgroundedRef.current = backgrounded;" in autosave
+
+ # The publication is what is gated -- and ONLY the publication.
+ assert (
+ "!backgroundedRef.current &&" in autosave
+ ), "the active-thread publication must be gated on the pane being visible"
+ publish_at = autosave.index("store.setActiveThreadId(remoteId)")
+ guard_at = autosave.index("!backgroundedRef.current")
+
+ # ...and on no switch away from this thread being in flight. switchToNewThread() is
+ # async, so mainThreadId still reads as this pane for the whole gap, and a save landing
+ # in it republishes the chat the user just left into the view they navigated to.
+ assert "!switchInFlight" in autosave, (
+ "the publication must also stand down while this provider's own New Chat switch is "
+ "still resolving"
+ )
+ assert (
+ "switchState.landedAttempt !== switchState.attempt" in autosave
+ ), "the in-flight window is attempt != landedAttempt, not merely activeNonce being set"
+ assert guard_at < publish_at, "the guard has to come before the write it guards"
+
+ # The save itself is untouched: gating it would defeat the PR, which exists so a run
+ # that outlives its view still lands on disk.
+ for call in (
+ "await ensureStoredChatThread(remoteId)",
+ "await syncExportedRepositoryToBackend(remoteId, exported)",
+ ):
+ assert call in autosave, f"{call} must still run while backgrounded"
+ assert autosave.index(call) < guard_at, f"{call} must not sit behind the visibility guard"
+
+
+def test_the_history_adapters_publish_stands_down_with_the_autosaves():
+ """``ThreadBackendAutosave`` is not the only place a pane names itself the active thread.
+
+ The history adapter's ``append()`` publishes the same id for every persisted message,
+ including the assistant message of the background run #9129 exists to keep alive.
+ ``enterCompare`` blanks the active id, so the ``!== remoteId`` test passes and a hidden pane
+ republishes itself into the same ``exportThreadIds`` the autosave guard was added for. Both
+ must stand down together, or gating one is decorative.
+ """
+ append = _between(
+ RUNTIME_PROVIDER,
+ " append({ parentId, message }: ExportedMessageRepositoryItem) {",
+ "\n // Always register the adapter so the mic stays clickable",
+ )
+
+ assert (
+ "store.setActiveThreadId(remoteId);" in append
+ ), "this test is about the history adapter's publication; if it moved, follow it"
+ assert (
+ "!backgroundedRef?.current &&" in append
+ ), "the history adapter's publication needs the same visibility gate as the autosave's"
+ assert "!switchInFlight" in append, (
+ "...and the same stand-down while a New Chat switch this provider started is still "
+ "resolving; see the autosave test for why mainThreadId cannot be trusted in that gap"
+ )
+
+ # Read at publish time, through a ref, for the same reason the autosave does: the write
+ # is queued when the message arrives and resolves after Compare may have hidden the pane.
+ assert "const backgroundedRef = useRef(backgrounded);" in RUNTIME_PROVIDER
+ assert "backgroundedRef.current = backgrounded;" in RUNTIME_PROVIDER
+
+ # ...and the ref has to actually reach it. A ref rather than the boolean, so handing it
+ # down cannot change the memoized runtime hook's identity and rebuild the runtime.
+ hook_build = _between(
+ RUNTIME_PROVIDER,
+ " const runtimeHook = useMemo(",
+ " const runtime = useRemoteThreadListRuntime({",
+ )
+ assert "backgroundedRef," in hook_build, "createRuntimeHook has to be handed the ref"
+ assert "[initialThreadId, modelType, onInitialHistoryReady, pairId]," in hook_build, (
+ "and the ref must NOT join the dependency array: a new hook identity rebuilds the "
+ "runtime, which is the one thing the shared provider must never do"
+ )
+
+ # The write itself is untouched. Only the publication is gated.
+ assert "await awaitStoredChatThreadWrites(remoteId);" in append
+ assert append.index("await awaitStoredChatThreadWrites(remoteId);") < append.index(
+ "!backgroundedRef?.current"
+ ), "persisting a background run's message must not sit behind the visibility guard"
diff --git a/tests/studio/test_new_chat_context_recount.py b/tests/studio/test_new_chat_context_recount.py
index aab8d2862e2..628938c94f3 100644
--- a/tests/studio/test_new_chat_context_recount.py
+++ b/tests/studio/test_new_chat_context_recount.py
@@ -48,9 +48,12 @@ BOUND_NAMES = {
"enabled",
"ggufContextLength",
"isLoading",
+ "mainThreadId",
"runActive",
"modelLoading",
+ "newThreadSwitchStateRef",
"nonce",
+ "paused",
}
@@ -144,6 +147,7 @@ export const world: any = {
countedMessages: [] as any[][],
countedModel: undefined as string | undefined,
switchedToNewThread: 0,
+ clearedAttachments: 0,
promptQueueStops: 0,
// Set to { value: x } to stand in for a non-conforming 200 on the count path. Wrapped
// so that { value: undefined } means "the reply omits input_tokens" rather than "no
@@ -357,6 +361,14 @@ const auiFixture: any = {
world.switchedToNewThread += 1;
},
}),
+ // The switch clears a staged attachment before moving on, so the composer has to
+ // exist here: a missing one throws inside the effect and the recount below it
+ // never runs, which reads as a pricing bug rather than a missing stub.
+ composer: () => ({
+ clearAttachments: async () => {
+ world.clearedAttachments += 1;
+ },
+ }),
};
// ---- PRELUDE ENDS: verbatim studio source follows ----
@@ -407,11 +419,33 @@ __RECOUNT_EFFECTS__
}
const renderedDeps: any[] = [];
+const newThreadSwitchStateRef: any = {
+ // attempt mirrors the real ref: the effect reads `attempt + 1`, so omitting it makes
+ // every attempt NaN and NaN !== NaN skips the deferred clear the switch armed.
+ current: { activeNonce: null, hasSwitched: false, attempt: 0, pendingSavedThreadIds: [] },
+};
+
+export function leaveNewChatForSavedThread(): void {
+ newThreadSwitchStateRef.current.activeNonce = null;
+ renderedDeps.length = 0;
+}
+
+export function markImplicitNewChatUsed(): void {
+ newThreadSwitchStateRef.current.hasSwitched = true;
+}
export function renderNewChatSwitch(props: any): void {
const aui = auiFixture;
const isLoading = props.isLoading;
const nonce = props.nonce;
+ // Compare keeps the shared provider mounted but stood down; the recount tests are
+ // all about the view the user is looking at, so it defaults to on screen.
+ const paused = props.paused ?? false;
+ // The stale-switch correction reads it. Defaulting to a runtime-made id keeps that
+ // effect inert here: these tests are about the recount, and a local id is what a
+ // `?new=` view actually holds.
+ const mainThreadId = props.mainThreadId ?? "__LOCALID_recount";
+
// The component reads these through useChatRuntimeStore selectors, so a
// re-render sees whatever the store holds right now.
const checkpoint = state.params.checkpoint;
@@ -421,7 +455,10 @@ export function renderNewChatSwitch(props: any): void {
const scope: any = {
aui,
isLoading,
+ mainThreadId,
+ newThreadSwitchStateRef,
nonce,
+ paused,
checkpoint,
ggufContextLength,
modelLoading,
@@ -546,15 +583,11 @@ LOADED_MODEL = """
def test_the_harness_stubs_every_name_refresh_context_usage_imports() -> None:
"""A new import in the real module must not silently zero the recount.
- `_refresh_module_body()` replays that file with its import block stripped, so
- an imported name that this harness does not define becomes a ReferenceError
- the moment the replayed code reaches it. The failure does not look like a
- missing stub: the effect bails, `counts` stays 0, and the assertion reads
- "the empty New Chat view must be priced exactly once" -- a pricing bug that
- is not there.
-
- That is not hypothetical. #9056 added `findLatestUserVideoBase64` to decline
- pricing a prompt carrying video, and took 41 tests in this file red.
+ `_refresh_module_body()` replays that file with its import block stripped, so an
+ imported name this harness does not define becomes a ReferenceError the moment the
+ replayed code reaches it. The failure does not look like a missing stub: the effect
+ bails, `counts` stays 0, and it reads as a pricing bug that is not there. Not
+ hypothetical: #9056 added `findLatestUserVideoBase64` and took 41 tests here red.
"""
text = read(REFRESH)
# The single braced import list this module takes from ../api/chat-adapter.
@@ -676,6 +709,151 @@ def test_a_new_chat_prices_its_empty_prompt_against_a_resident_gguf(
assert out["promptQueueStops"] == 1, "hydration must not re-stop the prompt queue"
+def test_a_backgrounded_new_chat_view_neither_opens_a_thread_nor_prices_one():
+ """#8908: compare keeps this provider mounted so a project run stays attached.
+
+ Mounted is not on screen. While it is paused the switch must leave the shared
+ single-chat state to the view the user is actually looking at -- no new thread,
+ no blanked active thread, no count -- and must do all of it once the pause lifts,
+ not skip it as already done.
+ """
+ out = _run(
+ textwrap.dedent(
+ f"""
+ // @ts-nocheck
+ import {{ renderNewChatSwitch, seed, snapshot, world }} from "./harness.ts";
+ {LOADED_MODEL}
+ seed({{ activeThreadId: "thread-on-screen" }});
+
+ renderNewChatSwitch({{ isLoading: false, nonce: "n1", paused: true }});
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ const paused = {{
+ switched: world.switchedToNewThread,
+ counts: world.countedMessages.length,
+ activeThreadId: snapshot().activeThreadId,
+ contextUsage: snapshot().contextUsage,
+ }};
+
+ // Compare closes: the view is back on screen and owes both.
+ renderNewChatSwitch({{ isLoading: false, nonce: "n1", paused: false }});
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ console.log(JSON.stringify({{
+ paused,
+ switched: world.switchedToNewThread,
+ counts: world.countedMessages.length,
+ activeThreadId: snapshot().activeThreadId,
+ contextUsage: snapshot().contextUsage,
+ }}));
+ """
+ )
+ )
+ assert out["paused"]["switched"] == 0, "a paused switch must not open a thread"
+ assert out["paused"]["counts"] == 0, "a paused switch must not price a prompt"
+ assert (
+ out["paused"]["activeThreadId"] == "thread-on-screen"
+ ), "a paused switch must not blank the active thread the visible view is using"
+ assert out["paused"]["contextUsage"] is None
+ assert out["switched"] == 1, "releasing the pause must open the new thread"
+ assert out["activeThreadId"] is None
+ assert out["counts"] == 1, "releasing the pause must price the empty prompt once"
+ assert out["contextUsage"] is not None
+
+
+def test_a_staged_attachment_is_cleared_only_when_the_switch_moves_on():
+ """switchToNewThread() reuses the uninitialized new thread, so its composer is the
+ same one the last New Chat used. With one provider shared across the project and
+ single views, an unsent attachment would otherwise follow the user into the next
+ view and be filed with the chat created there. The first switch has nothing to
+ carry, so it must not clear a composer the user is still filling."""
+ out = _run(
+ textwrap.dedent(
+ f"""
+ // @ts-nocheck
+ import {{ renderNewChatSwitch, seed, world }} from "./harness.ts";
+ {LOADED_MODEL}
+ renderNewChatSwitch({{ isLoading: false, nonce: "n1" }});
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ const first = {{
+ switched: world.switchedToNewThread,
+ cleared: world.clearedAttachments,
+ }};
+
+ // A re-render that changes nothing must not clear anything either.
+ renderNewChatSwitch({{ isLoading: false, nonce: "n1" }});
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ const again = {{
+ switched: world.switchedToNewThread,
+ cleared: world.clearedAttachments,
+ }};
+
+ // New Chat, or the next project's landing: a different nonce.
+ renderNewChatSwitch({{ isLoading: false, nonce: "n2" }});
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ console.log(JSON.stringify({{
+ first,
+ again,
+ switched: world.switchedToNewThread,
+ cleared: world.clearedAttachments,
+ }}));
+ """
+ )
+ )
+ assert out["first"] == {
+ "switched": 1,
+ "cleared": 0,
+ }, "the first switch has no outgoing composer to clear"
+ assert out["again"] == {
+ "switched": 1,
+ "cleared": 0,
+ }, "a re-render at the same nonce must not switch or clear again"
+ assert out["switched"] == 2
+ assert out["cleared"] == 1, "moving to another nonce must not carry the attachment"
+
+
+def test_the_first_nonce_switch_clears_an_implicit_new_chat_attachment():
+ out = _run(
+ textwrap.dedent(
+ f"""
+ // @ts-nocheck
+ import {{ markImplicitNewChatUsed, renderNewChatSwitch, seed, world }} from "./harness.ts";
+ {LOADED_MODEL}
+ markImplicitNewChatUsed();
+ renderNewChatSwitch({{ isLoading: false, nonce: "n1" }});
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ console.log(JSON.stringify({{
+ switched: world.switchedToNewThread,
+ cleared: world.clearedAttachments,
+ }}));
+ """
+ )
+ )
+ assert out["switched"] == 1
+ assert out["cleared"] == 1, "a staged implicit-chat attachment must not follow the nonce"
+
+
+def test_back_to_the_same_new_chat_nonce_switches_after_a_saved_thread():
+ out = _run(
+ textwrap.dedent(
+ f"""
+ // @ts-nocheck
+ import {{ leaveNewChatForSavedThread, renderNewChatSwitch, seed, world }} from "./harness.ts";
+ {LOADED_MODEL}
+ renderNewChatSwitch({{ isLoading: false, nonce: "n1" }});
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ leaveNewChatForSavedThread();
+ renderNewChatSwitch({{ isLoading: false, nonce: "n1" }});
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ console.log(JSON.stringify({{
+ switched: world.switchedToNewThread,
+ cleared: world.clearedAttachments,
+ }}));
+ """
+ )
+ )
+ assert out["switched"] == 2, "Back to the same nonce must restore the new thread"
+ assert out["cleared"] == 1, "the reused new-thread composer must lose its attachment"
+
+
@pytest.mark.parametrize(
"reply",
["undefined", "null", '"1670"', "NaN", "Infinity", "{}"],
diff --git a/tests/studio/test_nonce_chat_resume_restore.py b/tests/studio/test_nonce_chat_resume_restore.py
new file mode 100644
index 00000000000..bb508e177db
--- /dev/null
+++ b/tests/studio/test_nonce_chat_resume_restore.py
@@ -0,0 +1,281 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Returning from Compare to a ``/chat?new=<uuid>`` chat must re-attach its thread id.
+
+The provider is HIDDEN rather than unmounted when Compare opens (the point of #9129), but
+``enterCompare`` clears ``activeThreadId`` and nothing put it back for this view:
+``ThreadNewChatSwitch`` returns immediately since the nonce never changed, ``ActiveThreadSync``
+is disabled whenever a nonce is present, and only ``ProjectLanding`` restored on resume.
+
+``ThreadScopedSettingsSync`` is NOT nonce-gated, so the chat came back live but detached, on
+installation defaults, with an edit moving THOSE rather than its own snapshot. Title, context
+usage and the model notice are keyed on the same id.
+
+``NonceThreadResumeRestore``'s effect is sliced verbatim and replayed through the same
+React-effect emulator the sibling suites use, so wiring drift breaks this.
+"""
+
+from __future__ import annotations
+
+import re
+import textwrap
+
+from _node_harness import (
+ WORKDIR,
+ read,
+ require_node,
+ run_harness,
+ slice_between,
+ source_path,
+)
+
+PROVIDER = source_path("studio/frontend/src/features/chat/runtime-provider.tsx")
+TEMP = WORKDIR / "temp" / "nonce_chat_resume_restore"
+SOURCES = (PROVIDER,)
+
+
+def _restore_effect() -> str:
+ """The component's single ``useEffect`` body, verbatim."""
+ component = slice_between(
+ read(PROVIDER),
+ "function NonceThreadResumeRestore(",
+ "\n// A thread read that fails leaves the chat unpaired",
+ )
+ match = re.search(r"useEffect\(\(\) => \{\n(.*?)\n \}, \[([^\]]*)\]\);", component, re.S)
+ assert match, "NonceThreadResumeRestore effect not found"
+ deps = [name.strip() for name in match.group(2).split(",") if name.strip()]
+ assert deps == ["aui", "enabled", "mainThreadId"], f"emulator does not bind {deps}"
+ return match.group(1)
+
+
+def _harness_source() -> str:
+ return f"""
+export const state = {{ activeThreadId: null }};
+export const sets = [];
+const useChatRuntimeStore = {{
+ getState: () => ({{
+ ...state,
+ setActiveThreadId: (id) => {{
+ state.activeThreadId = id;
+ sets.push(id);
+ }},
+ }}),
+}};
+// The real predicate: assistant-ui mints local ids for a thread with no row behind it yet.
+const isAssistantLocalThreadId = (id) =>
+ typeof id === "string" && id.startsWith("__LOCALID_");
+
+// Which threads have been persisted. A thread NOT listed here is a placeholder the
+// runtime minted and nothing was ever written for -- what an untouched project landing
+// holds after a compare round trip. Keyed by thread id, exactly as getItemById is.
+export const remoteIds = {{}};
+const aui = {{
+ threads: () => ({{
+ __internal_getAssistantRuntime: () => ({{
+ threads: {{
+ getItemById: (id) => ({{
+ getState: () => ({{ remoteId: remoteIds[id] }}),
+ }}),
+ }},
+ }}),
+ }}),
+}};
+
+// One mounted component: a ref that survives renders, and an effect re-run only when a
+// dependency actually changed.
+export function mount(initialEnabled) {{
+ const wasEnabledRef = {{ current: initialEnabled }};
+ let last = null;
+ return function render(enabled, mainThreadId) {{
+ const deps = [aui, enabled, mainThreadId];
+ if (last !== null && last[1] === deps[1] && last[2] === deps[2]) return;
+ last = deps;
+ (() => {{
+{_restore_effect()}
+ }})();
+ }};
+}}
+
+export function report(extra) {{
+ console.log(JSON.stringify({{
+ activeThreadId: state.activeThreadId,
+ sets,
+ ...extra,
+ }}));
+}}
+"""
+
+
+def _run(body: str) -> dict:
+ require_node(SOURCES)
+ script = textwrap.dedent(
+ f"""
+ // @ts-nocheck
+ import {{ mount, report, state, sets, remoteIds }} from "./harness.ts";
+ {textwrap.dedent(body)}
+ """
+ )
+ return run_harness(TEMP, _harness_source(), script, sources = SOURCES)
+
+
+def test_returning_from_compare_reattaches_the_materialized_thread() -> None:
+ """The bug, end to end: hide the view, clear the id as Compare does, show it again."""
+ out = _run(
+ """
+ remoteIds["thread-42"] = "remote-42"; // materialized: a row exists for it
+ const render = mount(true);
+ render(true, "thread-42"); // the chat, materialized and attached
+ state.activeThreadId = "thread-42";
+ render(false, "thread-42"); // Compare opens: hidden, and it clears the id
+ state.activeThreadId = null;
+ sets.length = 0;
+ render(true, "thread-42"); // back again
+ report({});
+ """
+ )
+ assert (
+ out["activeThreadId"] == "thread-42"
+ ), "a chat that comes back visible must be attached to the thread it is showing"
+ assert out["sets"] == ["thread-42"], "exactly one restore, on the resume"
+
+
+def test_a_resume_never_overwrites_an_id_somebody_else_already_set() -> None:
+ """The restore only fills a hole. Racing whoever owns the id would be worse than the gap."""
+ out = _run(
+ """
+ const render = mount(true);
+ render(false, "thread-42");
+ state.activeThreadId = "thread-99";
+ sets.length = 0;
+ render(true, "thread-42");
+ report({});
+ """
+ )
+ assert out["sets"] == []
+ assert out["activeThreadId"] == "thread-99"
+
+
+def test_a_fresh_new_chat_is_not_attached_on_its_first_render() -> None:
+ """Mounting is not resuming. An empty New Chat has no thread yet, and publishing one
+ would price and pair a chat the user has not started."""
+ out = _run(
+ """
+ const render = mount(true);
+ render(true, "thread-42");
+ report({});
+ """
+ )
+ assert out["sets"] == []
+ assert out["activeThreadId"] is None
+
+
+def test_a_materialized_chat_keeping_its_runtime_id_is_still_restored() -> None:
+ """The ordinary case, and the one an id-prefix guard would have skipped.
+
+ ``createStudioDbAdapter.initialize()`` writes the row under whatever id assistant-ui
+ minted and returns it, so a ``?new=`` chat that has been sent to keeps its
+ ``__LOCALID_`` id, and refusing that refuses almost every chat this component exists
+ for. Published raw, as ActiveThreadSync does elsewhere; consumers that need a
+ persisted id filter for themselves."""
+ out = _run(
+ """
+ // initialize() wrote the row under the minted id and handed it back, so this
+ // thread IS persisted despite its shape. That is the whole point of the test.
+ remoteIds["__LOCALID_7"] = "__LOCALID_7";
+ const render = mount(true);
+ render(false, "__LOCALID_7");
+ state.activeThreadId = null;
+ sets.length = 0;
+ render(true, "__LOCALID_7");
+ report({});
+ """
+ )
+ assert out["sets"] == ["__LOCALID_7"]
+ assert out["activeThreadId"] == "__LOCALID_7"
+
+
+def test_a_view_with_no_thread_at_all_publishes_nothing() -> None:
+ """Nothing to attach to. `null` is already the state, and writing it again would
+ clear the contextUsage the store keys off it."""
+ out = _run(
+ """
+ const render = mount(true);
+ render(false, null);
+ sets.length = 0;
+ render(true, null);
+ report({});
+ """
+ )
+ assert out["sets"] == []
+ assert out["activeThreadId"] is None
+
+
+def test_staying_hidden_never_restores() -> None:
+ """A backgrounded provider must not write the active thread the visible view owns."""
+ out = _run(
+ """
+ const render = mount(true);
+ render(false, "thread-42");
+ state.activeThreadId = null;
+ sets.length = 0;
+ render(false, "thread-7");
+ report({});
+ """
+ )
+ assert out["sets"] == []
+
+
+def test_the_provider_gates_the_restore_on_a_nonce_view_that_is_visible() -> None:
+ """Structural. The emulator replays the effect but not the props the JSX hands it, so
+ the enable expression is only pinned here. ``newThreadNonce`` and ``initialThreadId``
+ because a saved thread already has ActiveThreadSync, ``pairId``/``base`` because a
+ compare pane has no single chat to attach, ``backgrounded`` because a hidden view must
+ not claim the visible one's id."""
+ jsx = slice_between(
+ read(PROVIDER),
+ "<NonceThreadResumeRestore",
+ "<ThreadScopedSettingsSync",
+ )
+ for clause in (
+ 'modelType === "base"',
+ "!pairId",
+ "!!newThreadNonce",
+ "!initialThreadId",
+ "!backgrounded",
+ ):
+ assert clause in jsx, f"NonceThreadResumeRestore must be gated on {clause}"
+
+
+def test_the_harness_binds_every_name_the_effect_reaches() -> None:
+ """The effect is replayed verbatim, so a name this harness does not define becomes a
+ ReferenceError -- which reads as "the restore never fired", a bug that is not there."""
+ body = _restore_effect()
+ for name in re.findall(r"\b([A-Za-z_$][\w$]*)\s*\(", body):
+ if name in {"if", "return", "for", "while", "switch", "catch"}:
+ continue
+ assert name in _harness_source(), f"the effect calls {name}(), which the harness omits"
+
+
+def test_an_untouched_landing_is_not_read_into_a_chat_on_resume() -> None:
+ """A project landing that was never typed in still holds a blank placeholder thread
+ after a compare round trip, because the runtime mints one eagerly. Publishing it makes
+ ProjectLanding set pendingNewThreadId and swap the project overview for an empty
+ Thread, so the user comes back to a chat they never started.
+
+ Note what is NOT the discriminator: the placeholder here has the same `__LOCALID_`
+ shape as the materialized chat two tests up. Only the absence of a row tells them
+ apart.
+ """
+ out = _run(
+ """
+ const render = mount(true);
+ render(false, "__LOCALID_9"); // hidden by Compare, nothing ever written for it
+ state.activeThreadId = null;
+ sets.length = 0;
+ render(true, "__LOCALID_9"); // back to the landing
+ report({});
+ """
+ )
+ assert out["sets"] == [], "an unpersisted placeholder must not be published"
+ assert out["activeThreadId"] is None, "so the landing stays a landing"
diff --git a/tests/studio/test_project_chat_view_switch.py b/tests/studio/test_project_chat_view_switch.py
new file mode 100644
index 00000000000..fcb02721f64
--- /dev/null
+++ b/tests/studio/test_project_chat_view_switch.py
@@ -0,0 +1,2662 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""One ChatRuntimeProvider spans the project and single views, so switching between them is
+a prop change rather than a remount (#8908).
+
+That keeps a project chat's run attached, and it also breaks the guards the old shape got for
+free: a remounted provider had a fresh ref and composer every time, so a shared one has to
+decide for itself whether a nonce is new (``activeNonce``), whether the composer still holds
+someone else's staged attachment (``hasSwitched``), and whether it is on screen (``paused``).
+``ThreadAutoSwitch`` takes ``paused`` too, since the stop it requests names every temporary
+queue on the page rather than its own provider's.
+
+The five effects that decide those -- ``ThreadAutoSwitch``'s two, ``ThreadNewChatSwitch``'s two
+and the implicit-new-chat marker -- are sliced VERBATIM out of ``runtime-provider.tsx`` and
+replayed through a React-effect emulator (per-effect dependency arrays, re-run only on change,
+memo cleared on unmount). ``requestTemporaryPromptQueueStop`` is sliced verbatim too, because
+whose queue it stops is one of the questions here.
+
+Stubbed: the JSX wiring the props onto the two children (pinned by
+``test_the_provider_wires_the_pause_and_the_shared_ref``), assistant-ui's thread runtime, and
+``refreshContextUsage`` (a counter; the recount itself is pinned by
+``test_new_chat_context_recount.py``). ``ActiveThreadSync`` is not modelled: it is off whenever
+either child is rendered.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+import textwrap
+
+import pytest
+
+from _node_harness import (
+ WORKDIR,
+ read,
+ require_node,
+ run_harness,
+ slice_between,
+ source_path,
+)
+
+PROVIDER = source_path("studio/frontend/src/features/chat/runtime-provider.tsx")
+STORE = source_path("studio/frontend/src/features/chat/stores/chat-runtime-store.ts")
+QUEUE = source_path("studio/frontend/src/features/chat/utils/prompt-queue-boundary.ts")
+
+TEMP = WORKDIR / "temp" / "project_chat_view_switch"
+
+SOURCES = (PROVIDER, STORE, QUEUE)
+
+# Every name the emulator can supply to a sliced dependency array.
+BOUND_NAMES = {
+ "aui",
+ "checkpoint",
+ "ggufContextLength",
+ "initialThreadId",
+ "isLoading",
+ "mainThreadId",
+ "modelLoading",
+ "newThreadNonce",
+ "newThreadSwitchStateRef",
+ "nonce",
+ "onSwitchFailed",
+ "paused",
+ "runActive",
+ "syncActiveThreadId",
+ "threadId",
+}
+
+EFFECT_PATTERN = r"useEffect\(\(\) => \{\n(.*?)\n \}, \[([^\]]*)\]\);"
+
+
+def _effects(text: str, label: str) -> list[tuple[list[str], str]]:
+ """Every ``useEffect`` in a slice as (dependency names, verbatim body)."""
+ matches = re.findall(EFFECT_PATTERN, text, re.S)
+ assert matches, f"{label}: no effects found; the slice markers have moved"
+ effects = [
+ ([name.strip() for name in deps.split(",") if name.strip()], body) for body, deps in matches
+ ]
+ for deps, _body in effects:
+ unknown = set(deps) - BOUND_NAMES
+ assert not unknown, f"{label}: emulator does not bind {sorted(unknown)}"
+ return effects
+
+
+def _auto_switch_source() -> str:
+ return slice_between(
+ read(PROVIDER), "function ThreadAutoSwitch(", "\nfunction ThreadNewChatSwitch("
+ )
+
+
+def _new_chat_source() -> str:
+ return slice_between(
+ read(PROVIDER), "function ThreadNewChatSwitch(", "\nfunction ActiveThreadSync("
+ )
+
+
+def _provider_switch_state_source() -> str:
+ """The provider's shared switch-state ref and the effect that marks it, verbatim."""
+ return slice_between(
+ read(PROVIDER),
+ " const newThreadSwitchStateRef = useRef<NewThreadSwitchState>({",
+ "\n return (",
+ )
+
+
+def _provider_ref_initial_value() -> str:
+ """The object literal the provider's ``useRef`` is created with, verbatim."""
+ match = re.search(
+ r"useRef<NewThreadSwitchState>\((\{.*?\})\);", _provider_switch_state_source(), re.S
+ )
+ assert match, "the shared switch-state ref is no longer created with an object literal"
+ return match.group(1)
+
+
+def _pending_switch_cap() -> str:
+ """The bound on outstanding saved-thread claims, verbatim, so the emulator enforces the
+ number the source actually uses rather than a copy that can drift."""
+ match = re.search(r"^const MAX_PENDING_SAVED_THREAD_SWITCHES = \d+;$", read(PROVIDER), re.M)
+ assert match, "the pending-switch cap is no longer a module-level const"
+ return match.group(0)
+
+
+def _provider_jsx() -> str:
+ """The provider subtree that wires the two children, for the wiring guard."""
+ return slice_between(
+ read(PROVIDER),
+ " <ToolPaneScopeContext.Provider",
+ " {/* The view stays mounted",
+ )
+
+
+def _set_active_thread_id_reducer() -> str:
+ """The one store reducer both components write through, verbatim."""
+ return slice_between(
+ read(STORE),
+ "setActiveThreadId: (activeThreadId) =>",
+ "applyThreadScopedSettings:",
+ ).strip()
+
+
+def _prompt_queue_boundary_body() -> str:
+ """Everything in prompt-queue-boundary.ts after its import block, verbatim."""
+ text = read(QUEUE)
+ marker = 'from "./prompt-queue-model-boundary";'
+ return text[text.index(marker) + len(marker) :]
+
+
+HARNESS_PRELUDE = """
+// @ts-nocheck
+// Fixtures the sliced source reads through. Everything below the PRELUDE marker is
+// copied verbatim out of the studio sources.
+export const world: any = {
+ // What assistant-ui reports as the main thread. The runtime is not modelled; both
+ // switch calls move this the way the real ones do, which is all either effect reads.
+ mainThreadId: null as string | null,
+ switchedToNewThread: 0,
+ switchedToThread: [] as string[],
+ clearedAttachments: 0,
+ refreshes: 0,
+ // Every event the verbatim requestTemporaryPromptQueueStop dispatched, and who fired it.
+ stopEvents: [] as any[],
+ // Materialized prompt queues, keyed by thread, as the queue UI store holds them.
+ promptQueues: {} as Record<string, any>,
+ // Window listeners still registered: a per-switch leak would show up here.
+ eventListeners: 0,
+ // Set to a promise to hold switchToNewThread() open across a nonce change.
+ newThreadGate: null as Promise<void> | null,
+ // Holds switchToThread open, so a saved-chat switch can still be in flight when the
+ // route moves on. That ordering is the whole point of the stale-arrival correction.
+ switchToThreadGate: null as Promise<void> | null,
+ newThreadRejects: false,
+ switchToThreadRejects: false,
+ composerThrows: false,
+ clearAttachmentsRejects: false,
+ // switchToNewThread() calls still awaiting the gate. Must return to 0.
+ pendingNewThreadSwitches: 0,
+ // #9251's shell-release signal, counted so a superseded failure can be shown to still
+ // fire it.
+ switchFailedSignals: 0,
+ // Threads a row exists for. A recorded nonce thread is only worth returning to once the
+ // user has actually sent to it; a blank placeholder is not, and minting a fresh one is
+ // the older behaviour that must survive.
+ remoteIds: {} as Record<string, string>,
+ // Threads the runtime store no longer holds an entry for, so getItemById throws.
+ missingThreadIds: {} as Record<string, boolean>,
+ // Which component's effects are replaying right now, so a module-level call can be
+ // attributed to a caller. Set by the emulator, never read by the sliced source.
+ component: "none",
+};
+
+const state: any = {
+ activeThreadId: null,
+ activeThreadEpoch: 0,
+ contextUsage: null,
+ contextUsageByThreadId: {},
+ params: { checkpoint: "", systemPrompt: "", systemVariables: "" },
+ ggufContextLength: null,
+ modelLoading: false,
+ runningByThreadId: {},
+};
+
+function set(updater: any): void {
+ const patch = typeof updater === "function" ? updater(state) : updater;
+ Object.assign(state, patch);
+}
+
+const actions: any = {
+ __SET_ACTIVE_THREAD_ID__
+};
+
+export const useChatRuntimeStore: any = {
+ getState: () => ({ ...state, ...actions }),
+};
+
+export function seed(patch: any): void {
+ Object.assign(state, patch);
+}
+
+export function snapshot(): any {
+ return {
+ activeThreadId: state.activeThreadId,
+ activeThreadEpoch: state.activeThreadEpoch,
+ contextUsage: state.contextUsage,
+ };
+}
+
+// A thread assistant-ui already holds as main: the chat whose run was left going in the
+// background, so coming back to it is a no-op switch rather than a fresh one.
+export function seedMainThread(threadId: string | null): void {
+ world.mainThreadId = threadId;
+}
+
+// node has no DOM. Only what the sliced boundary module touches is provided, and the
+// dispatch is recorded rather than delivered so a test can read the detail it built.
+class CustomEvent {
+ type: string;
+ detail: any;
+ constructor(type: string, init?: any) {
+ this.type = type;
+ this.detail = init?.detail;
+ }
+}
+const window: any = {
+ addEventListener: (): void => {
+ world.eventListeners += 1;
+ },
+ removeEventListener: (): void => {
+ world.eventListeners -= 1;
+ },
+ dispatchEvent: (event: any): boolean => {
+ world.stopEvents.push({
+ type: event.type,
+ detail: event.detail,
+ firedBy: world.component,
+ });
+ return true;
+ },
+};
+
+// The two names prompt-queue-boundary.ts imports. The queue UI store is read by the
+// verbatim requestTemporaryPromptQueueStop to pick the temporary threads to stop, so it
+// holds real entries; the model boundary belongs to requestLocalPromptQueueStop, which
+// nothing here calls.
+const usePromptQueueUI: any = { getState: () => ({ byThreadId: world.promptQueues }) };
+const localPromptQueueModelBoundary: any = { advance: (): void => {} };
+
+// The recount is pinned by test_new_chat_context_recount.py. Here it only has to show
+// whether the pause gate on the second effect lets it fire.
+async function refreshContextUsage(): Promise<void> {
+ world.refreshes += 1;
+}
+
+const auiFixture: any = {
+ threads: () => ({
+ __internal_getAssistantRuntime: () => ({
+ threads: {
+ // Throws for an unknown id rather than returning undefined, as assistant-ui does:
+ // getThreadListItemState returns SKIP_UPDATE and ShallowMemoizeSubject's constructor
+ // turns that into "Entry not available in the store". A fixture that returned
+ // undefined would quietly excuse a caller that cannot survive the real one.
+ getItemById: (id: string) => {
+ if (world.missingThreadIds[id]) {
+ throw new Error("Entry not available in the store");
+ }
+ return { getState: () => ({ remoteId: world.remoteIds[id] }) };
+ },
+ },
+ }),
+ // Both outcomes go through the gate, so a failure can be held open as long as a
+ // success can: a rejection that lands after the user has moved on is the ordering
+ // the two-arm handler has to survive, and a synchronous throw could not produce it.
+ switchToNewThread: (): Promise<void> => {
+ world.switchedToNewThread += 1;
+ const openedThreadId = `local-${world.switchedToNewThread}`;
+ const rejects = world.newThreadRejects;
+ world.pendingNewThreadSwitches += 1;
+ return Promise.resolve(world.newThreadGate ?? undefined).then(() => {
+ world.pendingNewThreadSwitches -= 1;
+ if (rejects) {
+ throw new Error("switchToNewThread failed");
+ }
+ world.mainThreadId = openedThreadId;
+ });
+ },
+ switchToThread: (threadId: string): Promise<void> => {
+ world.switchedToThread.push(threadId);
+ const rejects = world.switchToThreadRejects;
+ const gate = world.switchToThreadGate;
+ if (!gate) {
+ if (rejects) {
+ return Promise.reject(new Error("switchToThread failed"));
+ }
+ world.mainThreadId = threadId;
+ return Promise.resolve();
+ }
+ // Assistant-ui assigns mainThreadId when the switch settles, with no idea whether
+ // the route still wants it.
+ return gate.then(() => {
+ if (rejects) {
+ throw new Error("switchToThread failed");
+ }
+ world.mainThreadId = threadId;
+ });
+ },
+ }),
+ // A composer only exists once a thread is mounted; the switch reaches for it before
+ // that on the very first mount, which is what its try/catch is for.
+ composer: () => {
+ if (world.composerThrows) {
+ throw new Error("no composer mounted");
+ }
+ return {
+ // Not a bare counter: clearAttachments() removes each staged file through the
+ // attachment adapter, so a remove() that fails rejects the promise it returns.
+ clearAttachments: async (): Promise<void> => {
+ world.clearedAttachments += 1;
+ if (world.clearAttachmentsRejects) {
+ throw new Error("attachment remove() failed");
+ }
+ },
+ };
+ },
+};
+
+// ---- PRELUDE ENDS: verbatim studio source follows ----
+"""
+
+
+HARNESS_RENDER = """
+
+// Replays sliced effects with React's dependency rule: an effect re-runs only when one of
+// its own dependencies changed since the last render, and a component that unmounts loses
+// its memo, so remounting re-runs everything.
+function replayEffects(effects: any[], scope: any, memo: any[]): void {
+ effects.forEach((effect: any, index: number) => {
+ const next = effect.deps.map((name: string) => scope[name]);
+ const previous = memo[index];
+ if (
+ previous != null &&
+ previous.length === next.length &&
+ previous.every((value: any, i: number) => Object.is(value, next[i]))
+ ) {
+ return;
+ }
+ memo[index] = next;
+ effect.run();
+ });
+}
+
+__PENDING_SWITCH_CAP__
+
+const newThreadSwitchStateRef: any = { current: __REF_INITIAL_VALUE__ };
+
+// The four fields the exact-state assertions below were written to lock. `nonceThread` and
+// `landedAttempt` are deliberately NOT among them: both are bookkeeping for the reattach
+// correction, their values are whatever thread and attempt a given test happens to be on,
+// and folding them into twenty unrelated pins would add churn rather than coverage. Each
+// has its own accessor, and its own tests.
+export function switchState(): any {
+ const {
+ nonceThread: _ignored,
+ landedAttempt: _alsoIgnored,
+ ...pinned
+ } = newThreadSwitchStateRef.current;
+ return pinned;
+}
+
+export function nonceThreadId(): any {
+ return newThreadSwitchStateRef.current.nonceThread?.threadId ?? null;
+}
+
+// Whether the nonce's own switch has landed, which is what makes the current main thread
+// its own rather than the one the user came from.
+export function nonceOwnershipIsSettled(): boolean {
+ const { landedAttempt, attempt } = newThreadSwitchStateRef.current;
+ return landedAttempt === attempt;
+}
+
+const providerMemo: any[] = [];
+const autoSwitchMemo: any[] = [];
+const newChatMemo: any[] = [];
+let autoSwitchMounted = false;
+let newChatMounted = false;
+
+// One aui for the session, as a provider that is never remounted holds.
+const aui = auiFixture;
+
+// Each component's effect list is rebuilt per render so the sliced bodies close over that
+// render's props, the way the real closures do. The memo arrays outlive the call.
+// #9251: releases the retained reload shell. The provider hands this to the base pane's
+// ThreadAutoSwitch, and a failed switch has to fire it whether or not a newer switch has
+// superseded this one -- the shell is waiting either way.
+//
+// Module scope, because it is a dependency of the switch effect and the real one is a
+// useCallback. A fresh closure per render would re-run that effect every time and start a
+// switch per render, which is the emulator lying rather than the component misbehaving.
+const onSwitchFailed = () => {
+ world.switchFailedSignals += 1;
+};
+
+function renderThreadAutoSwitch(props: any): void {
+ const threadId: string = props.initialThreadId;
+ const syncActiveThreadId = (props.syncActiveThreadId ?? true) && !props.backgrounded;
+ const paused = Boolean(props.backgrounded);
+ const isLoading = props.isLoading ?? false;
+ // Subscribed through useAuiState, so a render sees whatever assistant-ui holds now.
+ const mainThreadId = world.mainThreadId;
+ const scope: any = {
+ aui,
+ isLoading,
+ mainThreadId,
+ newThreadSwitchStateRef,
+ onSwitchFailed,
+ paused,
+ syncActiveThreadId,
+ threadId,
+ };
+ const effects: any[] = [
+__AUTO_SWITCH_EFFECTS__
+ ];
+ replayEffects(effects, scope, autoSwitchMemo);
+}
+
+function renderThreadNewChatSwitch(props: any): void {
+ const nonce: string = props.newThreadNonce;
+ const paused = Boolean(props.backgrounded);
+ const isLoading = props.isLoading ?? false;
+ // Read through useChatRuntimeStore selectors, so a re-render sees the store as it stands.
+ const checkpoint = state.params.checkpoint;
+ const ggufContextLength = state.ggufContextLength;
+ const modelLoading = state.modelLoading;
+ const runActive = Object.values(state.runningByThreadId ?? {}).some(Boolean);
+ // The stale-switch correction subscribes to it, exactly as ThreadAutoSwitch does.
+ const mainThreadId = world.mainThreadId;
+ const scope: any = {
+ aui,
+ isLoading,
+ mainThreadId,
+ newThreadSwitchStateRef,
+ nonce,
+ paused,
+ checkpoint,
+ ggufContextLength,
+ modelLoading,
+ runActive,
+ };
+ const effects: any[] = [
+__NEW_CHAT_EFFECTS__
+ ];
+ replayEffects(effects, scope, newChatMemo);
+}
+
+function renderProviderBody(props: any): void {
+ const initialThreadId = props.initialThreadId ?? undefined;
+ const newThreadNonce = props.newThreadNonce ?? undefined;
+ const scope: any = { initialThreadId, newThreadNonce };
+ const effects: any[] = [
+__PROVIDER_EFFECTS__
+ ];
+ replayEffects(effects, scope, providerMemo);
+}
+
+/**
+ * One render of ChatRuntimeProvider with the props ChatPage hands it.
+ *
+ * The two child conditions and the derived props are restated from the provider's JSX
+ * rather than sliced (JSX is not replayable here); they are pinned verbatim by
+ * test_the_provider_wires_the_pause_and_the_shared_ref, so a change to either side of
+ * that wiring fails rather than quietly diverging.
+ *
+ * Children's effects run before the parent's, as React commits them.
+ */
+export function renderProvider(props: any = {}): void {
+ const autoSwitchRendered = Boolean(props.initialThreadId);
+ const newChatRendered = !props.initialThreadId && Boolean(props.newThreadNonce);
+ if (!autoSwitchRendered && autoSwitchMounted) {
+ autoSwitchMounted = false;
+ autoSwitchMemo.length = 0;
+ }
+ if (!newChatRendered && newChatMounted) {
+ newChatMounted = false;
+ newChatMemo.length = 0;
+ }
+
+ if (autoSwitchRendered) {
+ autoSwitchMounted = true;
+ world.component = "ThreadAutoSwitch";
+ renderThreadAutoSwitch(props);
+ }
+ if (newChatRendered) {
+ newChatMounted = true;
+ world.component = "ThreadNewChatSwitch";
+ renderThreadNewChatSwitch(props);
+ }
+ world.component = "ChatRuntimeProvider";
+ renderProviderBody(props);
+ world.component = "none";
+}
+
+/**
+ * A render, then the re-render the app does once the switch settles: both switch calls
+ * move assistant-ui's mainThreadId, which is a subscribed value.
+ */
+export async function renderSettled(props: any = {}): Promise<void> {
+ renderProvider(props);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ renderProvider(props);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+}
+"""
+
+
+def _rendered_effects(effects: list[tuple[list[str], str]]) -> str:
+ blocks = []
+ for deps, body in effects:
+ blocks.append(
+ " {\n"
+ f" deps: {json.dumps(deps)},\n"
+ " run: () => {\n"
+ f"{body}\n"
+ " },\n"
+ " },"
+ )
+ return "\n".join(blocks)
+
+
+def _harness_source() -> str:
+ prelude = HARNESS_PRELUDE.replace("__SET_ACTIVE_THREAD_ID__", _set_active_thread_id_reducer())
+ render = (
+ HARNESS_RENDER.replace("__PENDING_SWITCH_CAP__", _pending_switch_cap())
+ .replace("__REF_INITIAL_VALUE__", _provider_ref_initial_value())
+ .replace(
+ "__PROVIDER_EFFECTS__",
+ _rendered_effects(_effects(_provider_switch_state_source(), "ChatRuntimeProvider")),
+ )
+ .replace(
+ "__AUTO_SWITCH_EFFECTS__",
+ _rendered_effects(_effects(_auto_switch_source(), "ThreadAutoSwitch")),
+ )
+ .replace(
+ "__NEW_CHAT_EFFECTS__",
+ _rendered_effects(_effects(_new_chat_source(), "ThreadNewChatSwitch")),
+ )
+ )
+ return prelude + _prompt_queue_boundary_body() + render
+
+
+# A rejected switchToNewThread() is only caught on the deferred path, so node would abort
+# the whole process on the immediate one. Recorded here instead, and asserted on.
+SCRIPT_HEADER = """
+const unhandled: string[] = [];
+process.on("unhandledRejection", (reason: any) => {
+ unhandled.push(String(reason));
+});
+const tick = () => new Promise((resolve) => setTimeout(resolve, 0));
+"""
+
+
+def _run(imports: str, body: str) -> dict:
+ require_node(SOURCES)
+ script = textwrap.dedent(
+ f"""
+ // @ts-nocheck
+ import {{ {imports} }} from "./harness.ts";
+ {SCRIPT_HEADER}
+ {textwrap.dedent(body)}
+ """
+ )
+ return run_harness(TEMP, _harness_source(), script, sources = SOURCES)
+
+
+# A resident GGUF, so the second effect has something it could price. Only the tests about
+# the pause gate need it; everywhere else the bar has nothing to count and stands down.
+LOADED_MODEL = """
+ seed({ params: { checkpoint: "unsloth/gguf-model" }, ggufContextLength: 8192 });
+"""
+
+
+# ---------------------------------------------------------------------------
+# Structural guards for what the emulator restates rather than replays.
+# ---------------------------------------------------------------------------
+
+
+def test_the_provider_wires_the_pause_and_the_shared_ref():
+ """Structural. ``renderProvider`` restates the provider's JSX, so the JSX has to say what
+ it restates: one ref handed to both children, ``paused`` driven by ``backgrounded``, and
+ ``syncActiveThreadId`` stood down while backgrounded. Without this guard the behavioural
+ tests below would keep passing against wiring that no longer exists."""
+ jsx = _provider_jsx()
+ assert "{initialThreadId && (" in jsx, "ThreadAutoSwitch must render only for a saved thread"
+ assert "{!initialThreadId && newThreadNonce && (" in jsx, (
+ "ThreadNewChatSwitch must render only for a new-chat nonce, and never alongside "
+ "ThreadAutoSwitch: both write the same shared switch state"
+ )
+ # Three, not two: ThreadBackendAutosave reads the same ref so its active-thread
+ # publication can tell "this pane is on screen" from "a switch away from it has not
+ # landed yet". Both switch children still share it, which is what the count protects.
+ assert jsx.count("newThreadSwitchStateRef={newThreadSwitchStateRef}") == 3, (
+ "both switch children must share ONE ref, or leaving a new chat for a saved one "
+ "cannot tell the next new chat that the composer is no longer fresh -- and the "
+ "autosave must read that same ref rather than a copy of its own"
+ )
+ for child in ("ThreadAutoSwitch", "ThreadNewChatSwitch", "ThreadBackendAutosave"):
+ opening = jsx.index(f"<{child}")
+ element = jsx[opening : jsx.index("/>", opening)]
+ assert (
+ "newThreadSwitchStateRef={newThreadSwitchStateRef}" in element
+ ), f"{child} must be handed the shared switch state ref"
+ assert jsx.count("paused={backgrounded}") == 2, (
+ "BOTH children must be paused while backgrounded. ThreadAutoSwitch's first effect "
+ "reaches requestTemporaryPromptQueueStop, which names every temporary queue on the "
+ "page rather than this provider's, so an unpaused one stops a queue the view on "
+ "screen owns"
+ )
+ assert (
+ "syncActiveThreadId={syncActiveThreadId && !backgrounded}" in jsx
+ ), "a backgrounded provider must not write the active thread the visible view owns"
+
+
+def test_the_harness_stubs_every_name_the_queue_boundary_imports():
+ """Structural. ``_prompt_queue_boundary_body()`` replays that module with its imports
+ stripped, so an import this harness does not define becomes a ReferenceError the moment
+ a stop is requested -- and that reads as "the switch never fired" rather than as a
+ missing stub."""
+ text = read(QUEUE)
+ imported = re.findall(r"import \{ ([^}]+) \} from", text)
+ names = [name.strip() for block in imported for name in block.split(",") if name.strip()]
+ assert names, "parsed an empty import list; this guard would check nothing"
+ with open(__file__, encoding = "utf-8") as handle:
+ harness = handle.read()
+ missing = [name for name in names if f"const {name}" not in harness]
+ assert not missing, f"prompt-queue-boundary.ts imports {missing}, which this harness omits"
+
+
+# ---------------------------------------------------------------------------
+# (a) Nonce transitions.
+# ---------------------------------------------------------------------------
+
+
+def test_a_first_new_chat_switches_once_and_clears_nothing():
+ """The provider is shared now, so the first nonce it ever sees still has to open a fresh
+ thread -- and must not clear a composer the user may already have staged a file into,
+ since nothing has been carried over yet."""
+ out = _run(
+ "renderSettled, snapshot, switchState, world",
+ """
+ await renderSettled({ newThreadNonce: "n1" });
+ console.log(JSON.stringify({
+ switched: world.switchedToNewThread,
+ cleared: world.clearedAttachments,
+ stops: world.stopEvents.length,
+ activeThreadId: snapshot().activeThreadId,
+ switchState: switchState(),
+ unhandled: unhandled.length,
+ }));
+ """,
+ )
+ assert out["switched"] == 1
+ assert out["cleared"] == 0, "the first switch has no outgoing composer to clear"
+ assert out["stops"] == 1
+ assert out["activeThreadId"] is None
+ assert out["switchState"] == {
+ "activeNonce": "n1",
+ "hasSwitched": True,
+ "attempt": 1,
+ "pendingSavedThreadIds": [],
+ }
+ assert out["unhandled"] == 0
+
+
+def test_re_rendering_at_the_same_nonce_never_switches_again():
+ """A shared provider re-renders constantly (a store write anywhere above it is enough).
+ Only the nonce marks a new chat, so an unchanged one must be inert -- re-switching would
+ throw away the thread the user is typing into."""
+ out = _run(
+ "renderSettled, world",
+ """
+ await renderSettled({ newThreadNonce: "n1" });
+ await renderSettled({ newThreadNonce: "n1" });
+ await renderSettled({ newThreadNonce: "n1" });
+ console.log(JSON.stringify({
+ switched: world.switchedToNewThread,
+ cleared: world.clearedAttachments,
+ stops: world.stopEvents.length,
+ }));
+ """,
+ )
+ assert out["switched"] == 1, "an unchanged nonce must not open a second thread"
+ assert out["cleared"] == 0
+ assert out["stops"] == 1, "nor re-stop the temporary prompt queue"
+
+
+def test_a_nonce_rotation_while_visible_switches_and_clears_at_once():
+ """New Chat clicked while the view is on screen. ``activeNonce`` is not null, so the
+ clear does not wait for the switch: the composer being reused is the one on screen, and
+ it is emptied before the new thread arrives rather than after."""
+ out = _run(
+ "renderProvider, renderSettled, world",
+ """
+ await renderSettled({ newThreadNonce: "n1" });
+ let release: any;
+ world.newThreadGate = new Promise((resolve) => { release = resolve; });
+ renderProvider({ newThreadNonce: "n2" });
+ const midSwitch = {
+ switched: world.switchedToNewThread,
+ cleared: world.clearedAttachments,
+ pending: world.pendingNewThreadSwitches,
+ };
+ release();
+ await tick();
+ console.log(JSON.stringify({
+ midSwitch,
+ switched: world.switchedToNewThread,
+ cleared: world.clearedAttachments,
+ stops: world.stopEvents.length,
+ pending: world.pendingNewThreadSwitches,
+ }));
+ """,
+ )
+ assert out["midSwitch"] == {
+ "switched": 2,
+ "cleared": 1,
+ "pending": 1,
+ }, "with a live composer the clear is immediate, not deferred behind the switch"
+ assert out["switched"] == 2
+ assert out["cleared"] == 1, "one rotation must clear once, not once per render"
+ assert out["stops"] == 2
+ assert out["pending"] == 0
+
+
+def test_a_nonce_that_rotates_while_paused_is_honoured_when_the_view_returns():
+ """Compare keeps this provider mounted so a project run stays attached; the project
+ landing behind it can rotate its nonce meanwhile (a new project, a created chat left
+ behind). The switch owes that rotation once the pause lifts, and owes it exactly once."""
+ out = _run(
+ "renderSettled, seed, world",
+ f"""
+ {LOADED_MODEL}
+ await renderSettled({{ newThreadNonce: "n1" }});
+ // Compare opens.
+ await renderSettled({{ newThreadNonce: "n1", backgrounded: true }});
+ // The landing rotates its nonce while off screen.
+ await renderSettled({{ newThreadNonce: "n2", backgrounded: true }});
+ const paused = {{
+ switched: world.switchedToNewThread,
+ cleared: world.clearedAttachments,
+ stops: world.stopEvents.length,
+ refreshes: world.refreshes,
+ }};
+ // Compare closes.
+ await renderSettled({{ newThreadNonce: "n2" }});
+ console.log(JSON.stringify({{
+ paused,
+ switched: world.switchedToNewThread,
+ cleared: world.clearedAttachments,
+ stops: world.stopEvents.length,
+ }}));
+ """,
+ )
+ assert out["paused"]["switched"] == 1, "a paused view must not open a thread"
+ assert out["paused"]["cleared"] == 0
+ assert out["paused"]["stops"] == 1
+ assert out["switched"] == 2, "the rotation the pause swallowed must be honoured on return"
+ assert out["cleared"] == 1, "and the composer must not carry the staged file into it"
+ assert out["stops"] == 2
+
+
+def test_resuming_at_the_same_nonce_does_not_switch_again():
+ """Entering and leaving compare with nothing else happening. The ref survives the pause,
+ so the returning view recognises its own nonce and leaves the thread it already opened
+ alone -- which is the point of keeping the provider mounted in the first place."""
+ out = _run(
+ "renderSettled, snapshot, switchState, world",
+ """
+ await renderSettled({ newThreadNonce: "n1" });
+ await renderSettled({ newThreadNonce: "n1", backgrounded: true });
+ await renderSettled({ newThreadNonce: "n1" });
+ console.log(JSON.stringify({
+ switched: world.switchedToNewThread,
+ cleared: world.clearedAttachments,
+ stops: world.stopEvents.length,
+ switchState: switchState(),
+ activeThreadId: snapshot().activeThreadId,
+ }));
+ """,
+ )
+ assert out["switched"] == 1, "a round trip through compare must not open a second thread"
+ assert out["cleared"] == 0, "nor empty the composer the user left something staged in"
+ assert out["stops"] == 1, "nor re-stop the temporary prompt queue"
+ assert out["switchState"] == {
+ "activeNonce": "n1",
+ "hasSwitched": True,
+ "attempt": 1,
+ "pendingSavedThreadIds": [],
+ }
+ assert out["activeThreadId"] is None
+
+
+def test_a_paused_new_chat_does_not_touch_the_visible_views_thread():
+ """Mounted is not on screen. While it is paused the switch leaves the shared single-chat
+ state to the view the user is actually looking at."""
+ out = _run(
+ "renderSettled, seed, snapshot, world",
+ f"""
+ {LOADED_MODEL}
+ seed({{ activeThreadId: "thread-on-screen" }});
+ await renderSettled({{ newThreadNonce: "n1", backgrounded: true }});
+ console.log(JSON.stringify({{
+ switched: world.switchedToNewThread,
+ stops: world.stopEvents.length,
+ activeThreadId: snapshot().activeThreadId,
+ }}));
+ """,
+ )
+ assert out["switched"] == 0
+ assert out["stops"] == 0
+ assert (
+ out["activeThreadId"] == "thread-on-screen"
+ ), "a paused switch must not blank the active thread the visible view is using"
+
+
+def test_a_paused_new_chat_does_not_price_the_shared_context_bar():
+ """The pause gate is on the recount effect too. Nothing else would hold it back here --
+ a resident model, no active thread and a blank bar are exactly its firing conditions --
+ so without it a view hidden behind compare would put its own empty prompt on the bar the
+ visible one owns. Deferred, not skipped: the count is owed once the pause lifts."""
+ out = _run(
+ "renderSettled, seed, world",
+ f"""
+ {LOADED_MODEL}
+ seed({{ activeThreadId: null, contextUsage: null }});
+ await renderSettled({{ newThreadNonce: "n1", backgrounded: true }});
+ const paused = {{ refreshes: world.refreshes, switched: world.switchedToNewThread }};
+ await renderSettled({{ newThreadNonce: "n1" }});
+ console.log(JSON.stringify({{
+ paused,
+ refreshes: world.refreshes,
+ switched: world.switchedToNewThread,
+ }}));
+ """,
+ )
+ assert (
+ out["paused"]["refreshes"] == 0
+ ), "a paused view must not price a prompt onto the bar the visible view owns"
+ assert out["paused"]["switched"] == 0
+ assert out["refreshes"] == 1, "releasing the pause must price the empty prompt once"
+ assert out["switched"] == 1
+
+
+# ---------------------------------------------------------------------------
+# (b) Staged attachments, immediate and deferred.
+# ---------------------------------------------------------------------------
+
+
+def test_an_implicit_new_chat_defers_the_clear_until_the_new_thread_arrives():
+ """``/chat`` with no thread and no nonce is a new chat too, so the provider marks the
+ composer used. When a nonce then appears there is no ``activeNonce`` to switch away
+ from, so the clear is deferred: the composer that has to be emptied is the one the new
+ thread brings, and clearing before the switch would empty the outgoing one instead."""
+ out = _run(
+ "renderProvider, renderSettled, switchState, world",
+ """
+ await renderSettled({});
+ const implicit = { switched: world.switchedToNewThread, state: switchState() };
+
+ let release: any;
+ world.newThreadGate = new Promise((resolve) => { release = resolve; });
+ renderProvider({ newThreadNonce: "n1" });
+ await tick();
+ const midSwitch = {
+ switched: world.switchedToNewThread,
+ cleared: world.clearedAttachments,
+ stops: world.stopEvents.length,
+ };
+ release();
+ await tick();
+ console.log(JSON.stringify({
+ implicit,
+ midSwitch,
+ switched: world.switchedToNewThread,
+ cleared: world.clearedAttachments,
+ unhandled: unhandled.length,
+ }));
+ """,
+ )
+ assert out["implicit"]["switched"] == 0, "an implicit new chat opens no thread of its own"
+ assert out["implicit"]["state"] == {
+ "activeNonce": None,
+ "hasSwitched": True,
+ "attempt": 0,
+ "pendingSavedThreadIds": [],
+ }
+ assert out["midSwitch"]["switched"] == 1
+ assert out["midSwitch"]["cleared"] == 0, "the deferred clear must wait for the switch"
+ assert out["midSwitch"]["stops"] == 1
+ assert out["cleared"] == 1, "and must run once the new thread's composer is the live one"
+ assert out["unhandled"] == 0
+
+
+def test_a_composer_that_is_not_mounted_yet_does_not_break_the_switch():
+ """The clear reaches for a composer that may not exist. Its try/catch has to hold on
+ both paths, or the switch below it never runs and the view is stranded on the old
+ thread with a blank bar."""
+ out = _run(
+ "renderSettled, world",
+ """
+ world.composerThrows = true;
+ await renderSettled({});
+ await renderSettled({ newThreadNonce: "n1" });
+ const deferred = { switched: world.switchedToNewThread, cleared: world.clearedAttachments };
+ await renderSettled({ newThreadNonce: "n2" });
+ console.log(JSON.stringify({
+ deferred,
+ switched: world.switchedToNewThread,
+ cleared: world.clearedAttachments,
+ unhandled: unhandled.length,
+ }));
+ """,
+ )
+ assert out["deferred"] == {"switched": 1, "cleared": 0}
+ assert out["switched"] == 2, "a missing composer must not stop the immediate path switching"
+ assert out["cleared"] == 0
+ assert out["unhandled"] == 0
+
+
+ ("setup", "path", "attempts"),
+ [
+ # activeNonce is non-null when the second nonce arrives, so the clear is the
+ # synchronous one, outside any promise chain of its own.
+ pytest.param(
+ 'await renderSettled({ newThreadNonce: "n0" });', "immediate", 2, id = "immediate"
+ ),
+ # activeNonce is null, so the clear is the one the switch's success arm calls.
+ pytest.param("await renderSettled({});", "deferred", 1, id = "deferred"),
+ ],
+)
+def test_an_attachment_remove_that_fails_is_not_an_unhandled_rejection(setup, path, attempts):
+ """``clearAttachments()`` is not a bare call: it removes each staged file through the
+ attachment adapter, so a remove() that fails rejects the promise it returns. The
+ surrounding try/catch cannot see that -- it only guards the synchronous reach for the
+ composer -- so the call has to be chained. The switch itself must still complete either
+ way: an attachment that would not delete is not a reason to strand the view."""
+ nonce = "n1"
+ out = _run(
+ "renderSettled, snapshot, switchState, world",
+ f"""
+ {setup}
+ world.clearAttachmentsRejects = true;
+ await renderSettled({{ newThreadNonce: "{nonce}" }});
+ console.log(JSON.stringify({{
+ switched: world.switchedToNewThread,
+ cleared: world.clearedAttachments,
+ stops: world.stopEvents.length,
+ state: switchState(),
+ activeThreadId: snapshot().activeThreadId,
+ unhandled: unhandled.length,
+ reasons: unhandled,
+ }}));
+ """,
+ )
+ assert out["cleared"] == 1, f"the {path} path still attempts the clear"
+ assert out["unhandled"] == 0, (
+ f"a rejecting attachment remove() on the {path} path became an unhandled "
+ f"rejection: {out['reasons']}"
+ )
+ assert out["state"] == {
+ "activeNonce": nonce,
+ "hasSwitched": True,
+ "attempt": attempts,
+ "pendingSavedThreadIds": [],
+ }
+ assert out["activeThreadId"] is None, "and the switch below it still ran"
+
+
+# ---------------------------------------------------------------------------
+# (c) ThreadAutoSwitch resets the shared nonce.
+# ---------------------------------------------------------------------------
+
+
+def test_opening_a_saved_thread_releases_the_nonce_so_the_same_one_switches_again():
+ """The sidebar hands the same landing nonce back after a saved chat. Without the reset
+ the returning view would recognise its own nonce, decline to switch, and leave the user
+ looking at the saved thread's messages under a New Chat header."""
+ out = _run(
+ "renderSettled, switchState, world",
+ """
+ await renderSettled({ newThreadNonce: "n1" });
+ await renderSettled({ initialThreadId: "thread-a" });
+ const opened = { state: switchState(), switchedTo: world.switchedToThread.slice() };
+ await renderSettled({ newThreadNonce: "n1" });
+ console.log(JSON.stringify({
+ opened,
+ switched: world.switchedToNewThread,
+ cleared: world.clearedAttachments,
+ state: switchState(),
+ }));
+ """,
+ )
+ assert out["opened"]["state"] == {
+ "activeNonce": None,
+ "hasSwitched": True,
+ "attempt": 2,
+ "pendingSavedThreadIds": [],
+ }
+ assert out["opened"]["switchedTo"] == ["thread-a"]
+ assert out["switched"] == 2, "back to the same nonce must restore the new thread"
+ assert out["state"] == {
+ "activeNonce": "n1",
+ "hasSwitched": True,
+ "attempt": 3,
+ "pendingSavedThreadIds": [],
+ }
+
+
+def test_new_chat_then_a_saved_thread_then_new_chat_clears_the_staged_attachment():
+ """The full round trip, which is what a shared provider made possible and what makes
+ the composer stale: the new thread it switches back to is the same uninitialized one,
+ still holding whatever was staged before the detour."""
+ out = _run(
+ "renderProvider, renderSettled, world",
+ """
+ await renderSettled({ newThreadNonce: "n1" });
+ await renderSettled({ initialThreadId: "thread-a" });
+
+ let release: any;
+ world.newThreadGate = new Promise((resolve) => { release = resolve; });
+ renderProvider({ newThreadNonce: "n1" });
+ await tick();
+ const midSwitch = { cleared: world.clearedAttachments };
+ release();
+ await tick();
+ console.log(JSON.stringify({
+ midSwitch,
+ switched: world.switchedToNewThread,
+ cleared: world.clearedAttachments,
+ switchedTo: world.switchedToThread,
+ }));
+ """,
+ )
+ assert (
+ out["midSwitch"]["cleared"] == 0
+ ), "after a saved thread the clear is the deferred one: activeNonce was reset to null"
+ assert out["cleared"] == 1, "the reused new-thread composer must lose its attachment"
+ assert out["switched"] == 2
+
+
+def test_a_saved_thread_that_is_already_the_main_one_still_releases_the_nonce():
+ """Coming back to the chat whose run was left going: assistant-ui already holds it as
+ main, so the switch branch is skipped entirely. The nonce reset has to sit ABOVE that
+ branch or this route back leaves the stale nonce marked active and the next New Chat
+ silently does nothing."""
+ out = _run(
+ "renderSettled, seedMainThread, switchState, world",
+ """
+ await renderSettled({ newThreadNonce: "n1" });
+ // The saved chat is the one assistant-ui already has open.
+ seedMainThread("thread-a");
+ const stopsBefore = world.stopEvents.length;
+ await renderSettled({ initialThreadId: "thread-a" });
+ const opened = {
+ state: switchState(),
+ switchedTo: world.switchedToThread.slice(),
+ stops: world.stopEvents.length - stopsBefore,
+ };
+ await renderSettled({ newThreadNonce: "n1" });
+ console.log(JSON.stringify({
+ opened,
+ switched: world.switchedToNewThread,
+ cleared: world.clearedAttachments,
+ }));
+ """,
+ )
+ assert out["opened"]["switchedTo"] == [], "a thread already open must not be re-opened"
+ assert out["opened"]["stops"] == 0, "nor stop a queue on a switch that did not happen"
+ assert out["opened"]["state"] == {
+ "activeNonce": None,
+ "hasSwitched": True,
+ "attempt": 1,
+ "pendingSavedThreadIds": [],
+ }, "the nonce reset must not sit behind the mainThreadId guard"
+ assert out["switched"] == 2, "the returning New Chat must still open a fresh thread"
+ assert out["cleared"] == 1
+
+
+# ---------------------------------------------------------------------------
+# (d) Rapid switching, faster than switchToNewThread resolves.
+# ---------------------------------------------------------------------------
+
+
+def test_a_deferred_clear_for_a_nonce_that_moved_on_is_dropped():
+ """The deferred clear lands after an await, by which time the user may be two views
+ further on. Clearing then would empty a composer they have since staged a file into,
+ so the guard re-reads the shared ref and drops the callback."""
+ out = _run(
+ "renderProvider, renderSettled, switchState, world",
+ """
+ await renderSettled({});
+ let release: any;
+ world.newThreadGate = new Promise((resolve) => { release = resolve; });
+
+ // Deferred clear armed for n1, still awaiting its switch.
+ renderProvider({ newThreadNonce: "n1" });
+ await tick();
+ // The user moves on before it resolves.
+ renderProvider({ newThreadNonce: "n2" });
+ await tick();
+ const beforeRelease = {
+ switched: world.switchedToNewThread,
+ cleared: world.clearedAttachments,
+ };
+
+ release();
+ await tick();
+ await tick();
+ console.log(JSON.stringify({
+ beforeRelease,
+ switched: world.switchedToNewThread,
+ cleared: world.clearedAttachments,
+ state: switchState(),
+ pending: world.pendingNewThreadSwitches,
+ unhandled: unhandled.length,
+ }));
+ """,
+ )
+ assert out["beforeRelease"] == {
+ "switched": 2,
+ "cleared": 1,
+ }, "n2 takes the immediate path and clears before its own switch"
+ assert (
+ out["cleared"] == 1
+ ), "the stale deferred clear must not fire: n1's composer is two views behind"
+ assert out["switched"] == 2
+ assert out["state"] == {
+ "activeNonce": "n2",
+ "hasSwitched": True,
+ "attempt": 2,
+ "pendingSavedThreadIds": [],
+ }
+ assert out["pending"] == 0, "no switch callback may be left waiting"
+ assert out["unhandled"] == 0
+
+
+def test_three_nonces_faster_than_the_switch_resolves_clear_once_each_at_most():
+ """Clicking New Chat repeatedly. Each nonce owes one thread; only the first is deferred,
+ and only the last deferral could still be the live one."""
+ out = _run(
+ "renderProvider, renderSettled, switchState, world",
+ """
+ await renderSettled({});
+ let release: any;
+ world.newThreadGate = new Promise((resolve) => { release = resolve; });
+ renderProvider({ newThreadNonce: "n1" });
+ renderProvider({ newThreadNonce: "n2" });
+ renderProvider({ newThreadNonce: "n3" });
+ await tick();
+ const beforeRelease = {
+ switched: world.switchedToNewThread,
+ cleared: world.clearedAttachments,
+ };
+ release();
+ await tick();
+ await tick();
+ console.log(JSON.stringify({
+ beforeRelease,
+ switched: world.switchedToNewThread,
+ cleared: world.clearedAttachments,
+ stops: world.stopEvents.length,
+ state: switchState(),
+ pending: world.pendingNewThreadSwitches,
+ }));
+ """,
+ )
+ assert out["switched"] == 3, "every nonce owes exactly one thread"
+ assert out["stops"] == 3
+ assert (
+ out["cleared"] == 2
+ ), "n2 and n3 clear immediately; n1's deferred clear is dropped as stale"
+ assert out["beforeRelease"]["cleared"] == 2, "neither immediate clear waited for a switch"
+ assert out["state"] == {
+ "activeNonce": "n3",
+ "hasSwitched": True,
+ "attempt": 3,
+ "pendingSavedThreadIds": [],
+ }
+ assert out["pending"] == 0
+
+
+# ---------------------------------------------------------------------------
+# (e) A switchToNewThread() that rejects.
+# ---------------------------------------------------------------------------
+
+
+def test_a_rejected_switch_releases_the_nonce_so_the_same_one_can_be_retried():
+ """The state is mutated before the switch is attempted, so a rejection would otherwise
+ leave the guard believing a nonce that never opened a thread is the live one -- and the
+ nonce is the only thing that marks a New Chat, so the same New Chat could never be
+ served again. The rejection arm puts ``activeNonce`` back.
+
+ Retried at the next commit that re-runs the effect, not at the next render: React
+ re-runs an effect only when one of its dependencies changed, which is as true of this
+ effect as of any other. ``paused`` flipping on a compare round trip is one such commit,
+ and it is the one exercised here."""
+ out = _run(
+ "renderProvider, renderSettled, snapshot, switchState, world",
+ """
+ await renderSettled({ newThreadNonce: "n1" });
+ world.newThreadRejects = true;
+ renderProvider({ newThreadNonce: "n2" });
+ await tick();
+ await tick();
+ const afterReject = {
+ switched: world.switchedToNewThread,
+ cleared: world.clearedAttachments,
+ stops: world.stopEvents.length,
+ state: switchState(),
+ activeThreadId: snapshot().activeThreadId,
+ mainThreadId: world.mainThreadId,
+ unhandled: unhandled.length,
+ };
+
+ // Compare opens and closes: paused is a dependency, so the effect runs again.
+ world.newThreadRejects = false;
+ await renderSettled({ newThreadNonce: "n2", backgrounded: true });
+ await renderSettled({ newThreadNonce: "n2" });
+ console.log(JSON.stringify({
+ afterReject,
+ switched: world.switchedToNewThread,
+ state: switchState(),
+ mainThreadId: world.mainThreadId,
+ unhandled: unhandled.length,
+ }));
+ """,
+ )
+ state = out["afterReject"]
+ assert state["switched"] == 2, "the switch was attempted"
+ assert state["state"] == {
+ "activeNonce": None,
+ "hasSwitched": True,
+ "attempt": 2,
+ "pendingSavedThreadIds": [],
+ }, "a nonce whose switch failed must not stay recorded as the live one"
+ assert state["activeThreadId"] is None
+ assert state["mainThreadId"] == "local-1", "the user is still on the previous thread"
+ assert state["cleared"] == 1, "the outgoing composer was already emptied"
+ assert state["unhandled"] == 0, (
+ "both arms of the handler are attached on every path, so a failed switch is never "
+ "an unhandled rejection"
+ )
+ assert out["switched"] == 3, (
+ "the released nonce lets the same New Chat be served in place; without the release "
+ "the view stays on the old thread for good"
+ )
+ assert out["state"] == {
+ "activeNonce": "n2",
+ "hasSwitched": True,
+ "attempt": 3,
+ "pendingSavedThreadIds": [],
+ }
+ assert out["mainThreadId"] == "local-3", "and the retry is the thread the user ends on"
+ assert out["unhandled"] == 0
+
+
+def test_a_rejected_switch_on_the_deferred_path_keeps_the_draft_and_releases_the_nonce():
+ """The deferred clear exists to empty the composer the new thread brings. A switch that
+ failed brought none, so the user is still looking at the outgoing composer and its
+ staged file has to survive -- while the nonce is still released, or the retry that would
+ finally move them off it can never run."""
+ out = _run(
+ "renderSettled, switchState, world",
+ """
+ await renderSettled({});
+ world.newThreadRejects = true;
+ await renderSettled({ newThreadNonce: "n1" });
+ const afterReject = {
+ switched: world.switchedToNewThread,
+ cleared: world.clearedAttachments,
+ state: switchState(),
+ unhandled: unhandled.length,
+ };
+
+ // The retry, once the runtime is healthy again.
+ world.newThreadRejects = false;
+ await renderSettled({ newThreadNonce: "n1", backgrounded: true });
+ await renderSettled({ newThreadNonce: "n1" });
+ console.log(JSON.stringify({
+ afterReject,
+ switched: world.switchedToNewThread,
+ cleared: world.clearedAttachments,
+ state: switchState(),
+ unhandled: unhandled.length,
+ }));
+ """,
+ )
+ assert out["afterReject"]["switched"] == 1
+ assert out["afterReject"]["unhandled"] == 0, "the rejection arm handles it"
+ assert out["afterReject"]["cleared"] == 0, (
+ "a failed switch must not clear: the composer still on screen is the outgoing one, "
+ "and the user's staged file is still theirs"
+ )
+ assert out["afterReject"]["state"] == {
+ "activeNonce": None,
+ "hasSwitched": True,
+ "attempt": 1,
+ "pendingSavedThreadIds": [],
+ }, "the nonce is released on the deferred path too"
+ assert out["switched"] == 2, "the same nonce is retried once the effect re-runs"
+ assert out["cleared"] == 1, "and the retry that does open a thread clears as it should"
+ assert out["state"] == {
+ "activeNonce": "n1",
+ "hasSwitched": True,
+ "attempt": 2,
+ "pendingSavedThreadIds": [],
+ }
+ assert out["unhandled"] == 0
+
+
+def test_a_late_rejection_cannot_disturb_a_nonce_that_has_since_moved_on():
+ """The rejection arm writes to shared state after an await, so it has the same staleness
+ problem the deferred clear has and the same guard: it only releases the nonce it was
+ started for. A failure for n1 arriving after the user reached n2 must leave n2 alone,
+ or the next commit would throw away the thread they are already typing in."""
+ out = _run(
+ "renderProvider, renderSettled, switchState, world",
+ """
+ await renderSettled({});
+ let release: any;
+ world.newThreadGate = new Promise((resolve) => { release = resolve; });
+ world.newThreadRejects = true;
+ renderProvider({ newThreadNonce: "n1" });
+ await tick();
+
+ // The user moves on before n1's failure lands.
+ world.newThreadRejects = false;
+ world.newThreadGate = null;
+ renderProvider({ newThreadNonce: "n2" });
+ await tick();
+ const beforeFailure = { state: switchState(), switched: world.switchedToNewThread };
+
+ release();
+ await tick();
+ await tick();
+ console.log(JSON.stringify({
+ beforeFailure,
+ state: switchState(),
+ switched: world.switchedToNewThread,
+ pending: world.pendingNewThreadSwitches,
+ unhandled: unhandled.length,
+ }));
+ """,
+ )
+ assert out["beforeFailure"]["state"] == {
+ "activeNonce": "n2",
+ "hasSwitched": True,
+ "attempt": 2,
+ "pendingSavedThreadIds": [],
+ }
+ assert out["beforeFailure"]["switched"] == 2
+ assert out["state"] == {
+ "activeNonce": "n2",
+ "hasSwitched": True,
+ "attempt": 2,
+ "pendingSavedThreadIds": [],
+ }, "n1's late failure must not release the nonce n2 opened a thread for"
+ assert out["switched"] == 2, "and must not trigger a switch of its own"
+ assert out["pending"] == 0
+ assert out["unhandled"] == 0
+
+
+def test_a_late_failure_cannot_release_a_nonce_a_newer_attempt_owns():
+ """Two switches for the SAME nonce can be in flight, so the nonce cannot identify an
+ attempt. New Chat starts a switch, a saved chat opens while it runs (releasing the nonce
+ without ending the switch), then the same New Chat starts a second switch that succeeds.
+ When the first fails, a rejection arm keyed on the nonce alone reads its own nonce back and
+ releases it, switching away from the thread the second attempt opened.
+
+ The complement is asserted on the same shared state: a lone failure with nothing overlapping
+ must still release, or a New Chat that failed once could never be served again."""
+ out = _run(
+ "renderProvider, renderSettled, switchState, world",
+ """
+ await renderSettled({});
+
+ // Attempt 1 for n1, held open and destined to fail.
+ let release: any;
+ world.newThreadGate = new Promise((resolve) => { release = resolve; });
+ world.newThreadRejects = true;
+ renderProvider({ newThreadNonce: "n1" });
+ await tick();
+
+ // A saved chat is opened while it is still going: ThreadAutoSwitch releases the
+ // nonce, which is what lets a second switch for the same nonce start at all.
+ world.newThreadGate = null;
+ world.newThreadRejects = false;
+ // renderSettled, not a single render: the app re-renders when the saved switch
+ // moves mainThreadId, and that re-render is what lets ThreadAutoSwitch see its own
+ // thread arrive. Rendering once leaves the switch looking permanently in flight.
+ await renderSettled({ initialThreadId: "thread-a" });
+
+ // Back to the same New Chat: a third attempt for n1, and this one succeeds.
+ renderProvider({ newThreadNonce: "n1" });
+ await tick();
+ const beforeFailure = {
+ state: switchState(),
+ switched: world.switchedToNewThread,
+ mainThreadId: world.mainThreadId,
+ };
+
+ // Only now does the first attempt fail.
+ release();
+ await tick();
+ await tick();
+ const afterFailure = {
+ state: switchState(),
+ mainThreadId: world.mainThreadId,
+ switched: world.switchedToNewThread,
+ };
+
+ // The next commit that re-runs the effect: a compare round trip.
+ await renderSettled({ newThreadNonce: "n1", backgrounded: true });
+ await renderSettled({ newThreadNonce: "n1" });
+ const afterNextCommit = {
+ state: switchState(),
+ switched: world.switchedToNewThread,
+ mainThreadId: world.mainThreadId,
+ };
+
+ // Complement: a lone failure, nothing overlapping, must release.
+ world.newThreadRejects = true;
+ await renderSettled({ newThreadNonce: "n2" });
+ console.log(JSON.stringify({
+ beforeFailure,
+ afterFailure,
+ afterNextCommit,
+ loneFailure: { state: switchState(), switched: world.switchedToNewThread },
+ pending: world.pendingNewThreadSwitches,
+ unhandled: unhandled.length,
+ }));
+ """,
+ )
+ assert (
+ out["beforeFailure"]
+ == {
+ "state": {
+ "activeNonce": "n1",
+ "hasSwitched": True,
+ "attempt": 3,
+ "pendingSavedThreadIds": [],
+ },
+ "switched": 2,
+ "mainThreadId": "local-2",
+ }
+ ), "two new-chat attempts for one nonce, the second of which opened the thread on screen, plus the saved detour between them"
+ assert out["afterFailure"]["state"] == {
+ "activeNonce": "n1",
+ "hasSwitched": True,
+ "attempt": 3,
+ "pendingSavedThreadIds": [],
+ }, "the first attempt's failure must not release a nonce a later one owns"
+ assert (
+ out["afterFailure"]["mainThreadId"] == "local-2"
+ ), "and must not disturb the thread attempt 2 opened"
+ assert out["afterFailure"]["switched"] == 2
+ assert out["afterNextCommit"] == {
+ "state": {
+ "activeNonce": "n1",
+ "hasSwitched": True,
+ "attempt": 3,
+ "pendingSavedThreadIds": [],
+ },
+ "switched": 2,
+ "mainThreadId": "local-2",
+ }, "a released nonce would have made the next commit switch away from local-2"
+ assert out["loneFailure"] == {
+ "state": {
+ "activeNonce": None,
+ "hasSwitched": True,
+ "attempt": 4,
+ "pendingSavedThreadIds": [],
+ },
+ "switched": 3,
+ }, "with nothing overlapping, a failed attempt must still release its nonce"
+ assert out["pending"] == 0
+ assert out["unhandled"] == 0
+
+
+def test_a_late_deferred_clear_cannot_wipe_an_attachment_a_newer_attempt_staged():
+ """The success arm has the same two-in-flight problem. The deferred clear is armed only
+ once the nonce was released, so: a switch, a detour releasing the nonce, a New Chat held open
+ with the clear armed, then a second detour and return starting a newer attempt for the same
+ nonce. When the older switch resolves, a success arm keyed on the nonce alone clears the
+ composer the newer attempt is using, taking an attachment staged in it.
+
+ The complement is asserted on the same shared state: a detour nulls the nonce and must still
+ cancel a pending clear, so the nonce check cannot simply become the attempt check."""
+ out = _run(
+ "renderProvider, renderSettled, switchState, world",
+ """
+ // A first switch, so hasSwitched is set.
+ await renderSettled({ newThreadNonce: "n0" });
+ // Detour releases the nonce, which is what arms the DEFERRED clear next time.
+ await renderSettled({ initialThreadId: "thread-a" });
+
+ // Attempt 2 for n1, held open, deferred clear armed.
+ let release;
+ world.newThreadGate = new Promise((resolve) => { release = resolve; });
+ renderProvider({ newThreadNonce: "n1" });
+ await tick();
+ const armed = { state: switchState(), cleared: world.clearedAttachments };
+
+ // Second detour, then back to the same New Chat: attempt 3 opens its thread.
+ world.newThreadGate = null;
+ renderProvider({ initialThreadId: "thread-a" });
+ await tick();
+ renderProvider({ newThreadNonce: "n1" });
+ await tick();
+ const beforeLate = {
+ state: switchState(),
+ cleared: world.clearedAttachments,
+ switched: world.switchedToNewThread,
+ };
+
+ // Only now does the older switch resolve, with the user settled in attempt 3's thread.
+ release();
+ await tick();
+ await tick();
+ const afterLate = { state: switchState(), cleared: world.clearedAttachments };
+ console.log(JSON.stringify({
+ armed, beforeLate, afterLate, unhandled: unhandled.length,
+ }));
+ """,
+ )
+ assert out["armed"]["state"] == {
+ "activeNonce": "n1",
+ "hasSwitched": True,
+ "attempt": 3,
+ "pendingSavedThreadIds": [],
+ }, "the detour must leave the nonce released so this switch arms the deferred clear"
+ assert (
+ out["beforeLate"]["state"]["attempt"] == 4
+ ), "the return after the second detour must start a newer attempt for the same nonce"
+ assert (
+ out["afterLate"]["cleared"] == out["beforeLate"]["cleared"]
+ ), "the older switch's deferred clear must not wipe the composer the newer attempt opened"
+ assert out["afterLate"]["state"]["activeNonce"] == "n1"
+ assert out["unhandled"] == 0
+
+
+def test_every_switch_the_effect_starts_bumps_the_attempt_exactly_once():
+ """``attempt`` is what tells two in-flight switches apart, so it has to advance once
+ per switch actually started and never on a render that returned at a guard. Driven
+ across the whole mix: a first mount, a repeat render, a rotation, a pause, a resume, a
+ saved-thread detour and a return.
+
+ Saved-thread switches count too. They used not to, which left two of them sharing one
+ token, so a first saved chat rejecting after a second had settled read as current and
+ detached the chat on screen."""
+ out = _run(
+ "renderSettled, switchState, world",
+ """
+ await renderSettled({ newThreadNonce: "n1" });
+ await renderSettled({ newThreadNonce: "n1" });
+ await renderSettled({ newThreadNonce: "n2" });
+ await renderSettled({ newThreadNonce: "n2", backgrounded: true });
+ await renderSettled({ newThreadNonce: "n3", backgrounded: true });
+ await renderSettled({ newThreadNonce: "n3" });
+ await renderSettled({ initialThreadId: "thread-a" });
+ await renderSettled({ newThreadNonce: "n3" });
+ console.log(JSON.stringify({
+ state: switchState(),
+ switched: world.switchedToNewThread,
+ switchedToSaved: world.switchedToThread.length,
+ }));
+ """,
+ )
+ assert out["switched"] == 4, "n1, n2, n3 and the return to n3 after the saved chat"
+ assert out["switchedToSaved"] == 1, "the saved-thread detour"
+ assert out["state"]["attempt"] == out["switched"] + out["switchedToSaved"], (
+ "attempt must count switches started, of either kind, and not renders: a bump on a "
+ "render that returned at a guard would let a stale rejection think it is current, "
+ "and a switch that does not bump would let one think it is current too"
+ )
+ assert out["state"] == {
+ "activeNonce": "n3",
+ "hasSwitched": True,
+ "attempt": 5,
+ "pendingSavedThreadIds": [],
+ }
+
+
+def test_a_rejected_saved_thread_switch_blanks_the_bar_only_while_visible():
+ """ThreadAutoSwitch's own failure path, for contrast: it catches, and the catch is
+ already gated on syncActiveThreadId, so a backgrounded provider cannot blank the active
+ thread the visible view owns even when its switch fails."""
+ out = _run(
+ "renderSettled, seed, snapshot, world",
+ """
+ world.switchToThreadRejects = true;
+ seed({ activeThreadId: "thread-on-screen" });
+ await renderSettled({ initialThreadId: "thread-a", backgrounded: true });
+ const backgroundedRun = {
+ switchedTo: world.switchedToThread.slice(),
+ activeThreadId: snapshot().activeThreadId,
+ };
+ await renderSettled({ initialThreadId: "thread-a" });
+ console.log(JSON.stringify({
+ backgroundedRun,
+ activeThreadId: snapshot().activeThreadId,
+ unhandled: unhandled.length,
+ }));
+ """,
+ )
+ assert (
+ out["backgroundedRun"]["switchedTo"] == []
+ ), "a backgrounded provider does not attempt the switch at all"
+ assert (
+ out["backgroundedRun"]["activeThreadId"] == "thread-on-screen"
+ ), "so it cannot blank the visible view's thread, and its catch is gated as well"
+ assert out["activeThreadId"] is None, "the same failure while visible does blank it"
+ assert out["unhandled"] == 0, "ThreadAutoSwitch catches its own rejection"
+
+
+# ---------------------------------------------------------------------------
+# (f) requestTemporaryPromptQueueStop: how often, and whose queue.
+# ---------------------------------------------------------------------------
+
+
+def test_a_full_compare_round_trip_stops_the_temporary_queue_once():
+ """The stop discards an incognito queue that is about to become unreachable. Pausing and
+ resuming abandons nothing, so the only stop in the whole cycle is the one the New Chat
+ itself owed."""
+ out = _run(
+ "renderSettled, world",
+ """
+ await renderSettled({ newThreadNonce: "n1" });
+ await renderSettled({ newThreadNonce: "n1", backgrounded: true });
+ await renderSettled({ newThreadNonce: "n1", backgrounded: true });
+ await renderSettled({ newThreadNonce: "n1" });
+ await renderSettled({ newThreadNonce: "n1" });
+ console.log(JSON.stringify({
+ stops: world.stopEvents.length,
+ firedBy: world.stopEvents.map((event: any) => event.firedBy),
+ }));
+ """,
+ )
+ assert out["stops"] == 1, "a pause and resume must not re-stop the queue"
+ assert out["firedBy"] == ["ThreadNewChatSwitch"]
+
+
+def test_a_backgrounded_saved_thread_switch_stops_nothing_and_pays_on_resume():
+ """requestTemporaryPromptQueueStop names every materialized temporary queue on the page,
+ not this provider's, so an off-screen caller stops a queue the visible view owns. The
+ pause gate on the first effect is what keeps a backgrounded provider away from it -- and
+ it is a dependency, so the stop and the switch are deferred to the resume, not skipped."""
+ out = _run(
+ "renderSettled, seedMainThread, snapshot, switchState, world",
+ """
+ // An incognito queue materialized by the pane the user is looking at.
+ world.promptQueues = {
+ "temp-chat": { temporary: true },
+ "saved-chat": { temporary: false },
+ };
+ seedMainThread("some-other-thread");
+ await renderSettled({ initialThreadId: "thread-a", backgrounded: true });
+ const backgroundedRun = {
+ stops: world.stopEvents.length,
+ switchedTo: world.switchedToThread.slice(),
+ activeThreadId: snapshot().activeThreadId,
+ };
+
+ // Compare closes: this view is on screen and owes both.
+ await renderSettled({ initialThreadId: "thread-a" });
+ console.log(JSON.stringify({
+ backgroundedRun,
+ stops: world.stopEvents.length,
+ events: world.stopEvents,
+ switchedTo: world.switchedToThread,
+ activeThreadId: snapshot().activeThreadId,
+ state: switchState(),
+ }));
+ """,
+ )
+ assert (
+ out["backgroundedRun"]["stops"] == 0
+ ), "a backgrounded ThreadAutoSwitch must not reach a stop that names the visible view's queue"
+ assert out["backgroundedRun"]["switchedTo"] == [], "nor switch a thread off screen"
+ assert (
+ out["backgroundedRun"]["activeThreadId"] is None
+ ), "and the second effect stays gated through syncActiveThreadId"
+ assert out["stops"] == 1, "the resume pays the stop the pause deferred, exactly once"
+ event = out["events"][0]
+ assert event["firedBy"] == "ThreadAutoSwitch"
+ assert event["detail"]["temporaryOnly"] is True
+ assert event["detail"]["threadIds"] == ["temp-chat"]
+ assert out["switchedTo"] == ["thread-a"], "and the switch the pause deferred"
+ assert out["activeThreadId"] == "thread-a"
+ assert out["state"] == {
+ "activeNonce": None,
+ "hasSwitched": False,
+ "attempt": 1,
+ "pendingSavedThreadIds": [],
+ }, "the nonce reset is deferred with the rest of the effect, and so is the bump"
+
+
+def test_a_failed_saved_thread_switch_retries_only_while_the_view_is_on_screen():
+ """The route that reaches the gate above without a synthetic mount. A switch that fails
+ leaves mainThreadId pointing elsewhere, so the guard the effect would otherwise return
+ at stays open, and ``syncActiveThreadId`` flips on every compare open and close -- a
+ dependency, so each toggle re-runs the effect. Only the on-screen half of that toggle
+ may act: the compare half would be stopping a queue in the pane the user is using."""
+ out = _run(
+ "renderSettled, seedMainThread, world",
+ """
+ world.switchToThreadRejects = true;
+ world.promptQueues = { "compare-temp": { temporary: true } };
+ // The chat the user was reading before clicking the one that is now gone.
+ seedMainThread("thread-b");
+ await renderSettled({ initialThreadId: "thread-a" });
+ const visible = {
+ stops: world.stopEvents.length,
+ switchedTo: world.switchedToThread.length,
+ };
+ // Compare opens, then closes.
+ await renderSettled({ initialThreadId: "thread-a", backgrounded: true });
+ const inCompare = {
+ stops: world.stopEvents.length,
+ switchedTo: world.switchedToThread.length,
+ };
+ await renderSettled({ initialThreadId: "thread-a" });
+ console.log(JSON.stringify({
+ visible,
+ inCompare,
+ stops: world.stopEvents.length,
+ firedBy: world.stopEvents.map((event: any) => event.firedBy),
+ switchedTo: world.switchedToThread.length,
+ unhandled: unhandled.length,
+ }));
+ """,
+ )
+ assert out["visible"] == {"stops": 1, "switchedTo": 1}, "the first attempt is legitimate"
+ assert out["inCompare"] == {"stops": 1, "switchedTo": 1}, (
+ "opening compare re-runs the effect, and the pause gate is what stops it from "
+ "killing the compare pane's own incognito queue"
+ )
+ assert out["stops"] == 2, "closing compare retries, on screen, where the retry belongs"
+ assert out["firedBy"] == ["ThreadAutoSwitch", "ThreadAutoSwitch"]
+ assert out["switchedTo"] == 2
+ assert out["unhandled"] == 0
+
+
+# ---------------------------------------------------------------------------
+# (g) Bounded work across many view switches.
+# ---------------------------------------------------------------------------
+
+
+def test_a_hundred_and_twenty_view_switches_stay_bounded():
+ """The provider now outlives every view switch, so anything it accumulates accumulates
+ for the session: a per-switch listener, a callback left waiting on a switch that already
+ resolved, a second stop per pass. Each switch is allowed a fixed, small amount of work
+ and nothing else."""
+ out = _run(
+ "renderSettled, switchState, world",
+ """
+ const switches = 120;
+ for (let i = 0; i < switches; i += 1) {
+ await renderSettled(
+ i % 2 === 0 ? { newThreadNonce: "n1" } : { initialThreadId: "thread-a" },
+ );
+ }
+ console.log(JSON.stringify({
+ switches,
+ switchedToNewThread: world.switchedToNewThread,
+ switchedToThread: world.switchedToThread.length,
+ cleared: world.clearedAttachments,
+ stops: world.stopEvents.length,
+ listeners: world.eventListeners,
+ pending: world.pendingNewThreadSwitches,
+ state: switchState(),
+ unhandled: unhandled.length,
+ }));
+ """,
+ )
+ passes = out["switches"] // 2
+ assert out["switchedToNewThread"] == passes, "one new thread per project pass, no more"
+ assert out["switchedToThread"] == passes, "one saved-thread switch per single pass"
+ assert (
+ out["cleared"] == passes - 1
+ ), "one clear per return to the landing, and none on the first arrival"
+ assert out["stops"] == 2 * passes, "one stop per switch, not a growing number per switch"
+ assert out["listeners"] == 0, "no listener may survive a view switch"
+ assert out["pending"] == 0, "no switch callback may be left waiting"
+ assert out["state"] == {
+ "activeNonce": None,
+ "hasSwitched": True,
+ "attempt": 2 * passes,
+ "pendingSavedThreadIds": [],
+ }, "one bump per switch started, of either kind, and none per render"
+ assert out["unhandled"] == 0
+
+
[email protected]("switches", [20, 120])
+def test_the_work_per_view_switch_does_not_grow_with_the_session(switches):
+ """The same run at two lengths. Totals that stay linear in the number of switches are
+ what rules out per-switch accumulation; a single length cannot tell O(1) from O(n)."""
+ out = _run(
+ "renderSettled, world",
+ f"""
+ for (let i = 0; i < {switches}; i += 1) {{
+ await renderSettled(
+ i % 2 === 0 ? {{ newThreadNonce: "n1" }} : {{ initialThreadId: "thread-a" }},
+ );
+ }}
+ console.log(JSON.stringify({{
+ stops: world.stopEvents.length,
+ cleared: world.clearedAttachments,
+ switched: world.switchedToNewThread,
+ }}));
+ """,
+ )
+ passes = switches // 2
+ assert out["stops"] == 2 * passes
+ assert out["cleared"] == passes - 1
+ assert out["switched"] == passes
+
+
+def test_a_saved_switch_that_lands_after_the_route_moved_does_not_take_the_view():
+ """The provider is shared now, so a stale switchToThread has nothing to remount into.
+
+ Project landing, then a saved chat, then back before its switch settles. assistant-ui
+ assigns mainThreadId when the promise resolves and cannot know the route moved, so the
+ project landing's composer ended up pointed at the saved chat and the next message went
+ to the wrong conversation. The nonce view recognises that exact id -- the one
+ ThreadAutoSwitch recorded as pending -- and reasserts a fresh thread.
+ """
+ out = _run(
+ "renderProvider, renderSettled, switchState, world",
+ """
+ await renderSettled({ newThreadNonce: "n1" });
+ const openedByLanding = world.mainThreadId;
+
+ // Open a saved chat, but hold its switch open.
+ let release: any;
+ world.switchToThreadGate = new Promise((resolve) => { release = resolve; });
+ renderProvider({ initialThreadId: "thread-a" });
+ await tick();
+
+ // Back to the project landing before it settles.
+ world.switchToThreadGate = null;
+ renderProvider({ newThreadNonce: "n1" });
+ await tick();
+ const beforeArrival = world.mainThreadId;
+
+ // Only now does the saved switch land.
+ release();
+ await tick();
+ await tick();
+ // The commit React runs because mainThreadId moved.
+ renderProvider({ newThreadNonce: "n1" });
+ await tick();
+ await tick();
+
+ console.log(JSON.stringify({
+ openedByLanding,
+ beforeArrival,
+ mainThreadId: world.mainThreadId,
+ switchedTo: world.switchedToThread,
+ savedSwitches: world.switchedToThread.filter((id) => id.startsWith("thread-")),
+ state: switchState(),
+ unhandled: unhandled.length,
+ }));
+ """,
+ )
+ # switchedToThread also carries the correction's reattach, so name the saved ones.
+ assert out["savedSwitches"] == ["thread-a"], "the saved switch really was started"
+ assert out["mainThreadId"] != "thread-a", (
+ "a switch that landed after the user returned must not leave the visible project "
+ "landing pointed at the saved chat, or the next message goes to the wrong thread"
+ )
+ assert out["state"]["activeNonce"] == "n1", "and the landing still owns the nonce"
+ assert out["state"]["pendingSavedThreadIds"] == [], "the claim is spent, not left armed"
+ assert out["unhandled"] == 0
+
+
+def test_a_saved_switch_that_lands_in_time_is_left_alone():
+ """The complement, and the one a blunter guard gets wrong: the user really is on the
+ saved chat when it settles, so nothing may switch away from it."""
+ out = _run(
+ "renderProvider, renderSettled, switchState, world",
+ """
+ await renderSettled({ newThreadNonce: "n1" });
+ await renderSettled({ initialThreadId: "thread-a" });
+ console.log(JSON.stringify({
+ mainThreadId: world.mainThreadId,
+ switchedToNew: world.switchedToNewThread,
+ state: switchState(),
+ unhandled: unhandled.length,
+ }));
+ """,
+ )
+ assert out["mainThreadId"] == "thread-a", "the saved chat is the one on screen"
+ assert out["switchedToNew"] == 1, "only the landing's own switch, no correction"
+ assert out["state"]["pendingSavedThreadIds"] == [], "the claim is released on arrival"
+ assert out["unhandled"] == 0
+
+
+def test_a_saved_switch_that_fails_late_does_not_detach_the_view_that_replaced_it():
+ """The rejection arm writes shared state after an await, so it needs the same staleness
+ guard the other arms have. Unguarded, a saved switch failing after the user returned to
+ the project landing cleared the active id that landing had just set, detaching a chat
+ the failure has nothing to do with."""
+ out = _run(
+ "renderProvider, renderSettled, seed, snapshot, world",
+ """
+ await renderSettled({ newThreadNonce: "n1" });
+
+ let release: any;
+ world.switchToThreadGate = new Promise((resolve) => { release = resolve; });
+ world.switchToThreadRejects = true;
+ renderProvider({ initialThreadId: "thread-a" });
+ await tick();
+
+ // Back to the landing, which takes ownership of the active id.
+ world.switchToThreadGate = null;
+ world.switchToThreadRejects = false;
+ renderProvider({ newThreadNonce: "n1" });
+ await tick();
+ seed({ activeThreadId: "owned-by-the-landing" });
+
+ release();
+ await tick();
+ await tick();
+
+ console.log(JSON.stringify({
+ activeThreadId: snapshot().activeThreadId,
+ unhandled: unhandled.length,
+ }));
+ """,
+ )
+ assert (
+ out["activeThreadId"] == "owned-by-the-landing"
+ ), "a superseded failure must not clear an active id a newer view owns"
+ assert out["unhandled"] == 0
+
+
+def test_two_saved_switches_in_flight_are_both_corrected():
+ """One scalar claim cannot speak for two outstanding switches.
+
+ Open A, open B before A settles, then return to the project landing. If B lands first
+ the correction spends the claim, and A landing afterwards finds nothing recorded: the
+ nonce view leaves assistant-ui pointed at A and the next project-composer message is
+ appended to a chat the user is not looking at. Every switch this view starts has to be
+ tracked, not just the most recent one.
+ """
+ out = _run(
+ "renderProvider, renderSettled, switchState, world",
+ """
+ await renderSettled({ newThreadNonce: "n1" });
+
+ // A opens first and is held.
+ let releaseA: any;
+ world.switchToThreadGate = new Promise((resolve) => { releaseA = resolve; });
+ renderProvider({ initialThreadId: "thread-a" });
+ await tick();
+
+ // B opens before A settles, on its own gate.
+ let releaseB: any;
+ world.switchToThreadGate = new Promise((resolve) => { releaseB = resolve; });
+ renderProvider({ initialThreadId: "thread-b" });
+ await tick();
+
+ // Back to the project landing while both are still out.
+ world.switchToThreadGate = null;
+ renderProvider({ newThreadNonce: "n1" });
+ await tick();
+
+ // B lands first and is corrected.
+ releaseB();
+ await tick();
+ await tick();
+ renderProvider({ newThreadNonce: "n1" });
+ await tick();
+ await tick();
+ const afterB = world.mainThreadId;
+
+ // Then A lands, with the claim already spent on B.
+ releaseA();
+ await tick();
+ await tick();
+ renderProvider({ newThreadNonce: "n1" });
+ await tick();
+ await tick();
+
+ console.log(JSON.stringify({
+ afterB,
+ mainThreadId: world.mainThreadId,
+ savedSwitches: world.switchedToThread.filter((id) => id.startsWith("thread-")),
+ state: switchState(),
+ unhandled: unhandled.length,
+ }));
+ """,
+ )
+ assert out["savedSwitches"] == ["thread-a", "thread-b"], "both saved switches really started"
+ assert out["afterB"] != "thread-b", "the first arrival is corrected, as before"
+ assert out["mainThreadId"] != "thread-a", (
+ "the second stale arrival must be corrected too, or the visible project landing is "
+ "left pointed at a saved chat and the next message goes to it"
+ )
+ assert out["state"]["activeNonce"] == "n1", "and the landing still owns the nonce"
+ assert out["unhandled"] == 0
+
+
+def test_outstanding_claims_stay_bounded():
+ """A claim is only spent when its id arrives, so a switch that never settles never
+ spends one. Nothing here is a real session -- it takes that many saved-chat clicks with
+ not one switch resolving -- but the list must not grow for the life of the tab."""
+ out = _run(
+ "renderProvider, renderSettled, switchState, world",
+ """
+ await renderSettled({ newThreadNonce: "n1" });
+ world.switchToThreadGate = new Promise(() => {});
+ for (let i = 0; i < 40; i += 1) {
+ renderProvider({ initialThreadId: `thread-${i}` });
+ await tick();
+ }
+ console.log(JSON.stringify({
+ claims: switchState().pendingSavedThreadIds,
+ started: world.switchedToThread.length,
+ unhandled: unhandled.length,
+ }));
+ """,
+ )
+ assert out["started"] == 40, "every switch really was started"
+ assert len(out["claims"]) == 16, "the claim list is capped"
+ assert out["claims"][-1] == {
+ "id": "thread-39",
+ "settled": False,
+ }, "and it keeps the newest, dropping the oldest"
+ assert all(
+ claim["settled"] is False for claim in out["claims"]
+ ), "none of these switches ever settled, which is why nothing retired them"
+ assert out["unhandled"] == 0
+
+
+def test_the_same_saved_thread_opened_twice_is_corrected_twice():
+ """Deduplicating the claim by id loses one of two outstanding switches for that id.
+
+ A, then B, then A again before any settles: both A switches are really started, so both
+ can land. The first stale A arrival spends the single claim and the second is accepted
+ beneath the project composer, which is the same wrong-conversation bug one layer down.
+ A claim belongs to a switch, not to a thread id.
+ """
+ out = _run(
+ "renderProvider, renderSettled, switchState, world",
+ """
+ await renderSettled({ newThreadNonce: "n1" });
+
+ let releaseA1: any, releaseB: any, releaseA2: any;
+ world.switchToThreadGate = new Promise((resolve) => { releaseA1 = resolve; });
+ renderProvider({ initialThreadId: "thread-a" });
+ await tick();
+ world.switchToThreadGate = new Promise((resolve) => { releaseB = resolve; });
+ renderProvider({ initialThreadId: "thread-b" });
+ await tick();
+ world.switchToThreadGate = new Promise((resolve) => { releaseA2 = resolve; });
+ renderProvider({ initialThreadId: "thread-a" });
+ await tick();
+
+ // Back to the project landing with all three out.
+ world.switchToThreadGate = null;
+ renderProvider({ newThreadNonce: "n1" });
+ await tick();
+
+ for (const release of [releaseA1, releaseB, releaseA2]) {
+ release();
+ await tick();
+ await tick();
+ renderProvider({ newThreadNonce: "n1" });
+ await tick();
+ await tick();
+ }
+
+ console.log(JSON.stringify({
+ mainThreadId: world.mainThreadId,
+ savedSwitches: world.switchedToThread.filter((id) => id.startsWith("thread-")),
+ state: switchState(),
+ unhandled: unhandled.length,
+ }));
+ """,
+ )
+ assert out["savedSwitches"] == ["thread-a", "thread-b", "thread-a"], "all three really started"
+ assert out["mainThreadId"] != "thread-a", (
+ "the second arrival for the same id must be corrected too, or the visible landing is "
+ "left pointed at the saved chat"
+ )
+ assert out["state"]["activeNonce"] == "n1"
+ assert out["unhandled"] == 0
+
+
+def test_a_saved_switch_failing_late_does_not_detach_the_saved_chat_that_replaced_it():
+ """Only new-chat switches advanced the attempt, so two saved switches shared one token.
+
+ A is still loading when the user opens B. B settles and owns the view. A then rejects,
+ finds the attempt unchanged, passes the staleness guard and clears the active thread id
+ -- detaching the visible B chat from its thread-scoped settings and context state.
+ """
+ out = _run(
+ "renderProvider, renderSettled, snapshot, world",
+ """
+ await renderSettled({ newThreadNonce: "n1" });
+
+ let releaseA: any;
+ world.switchToThreadGate = new Promise((resolve) => { releaseA = resolve; });
+ world.switchToThreadRejects = true;
+ renderProvider({ initialThreadId: "thread-a" });
+ await tick();
+
+ // B opens while A is still out, and succeeds.
+ let releaseB: any;
+ world.switchToThreadGate = new Promise((resolve) => { releaseB = resolve; });
+ world.switchToThreadRejects = false;
+ renderProvider({ initialThreadId: "thread-b" });
+ await tick();
+ releaseB();
+ await tick();
+ await tick();
+ renderProvider({ initialThreadId: "thread-b" });
+ await tick();
+ const beforeFailure = snapshot().activeThreadId;
+
+ // Only now does A fail.
+ releaseA();
+ await tick();
+ await tick();
+
+ console.log(JSON.stringify({
+ beforeFailure,
+ activeThreadId: snapshot().activeThreadId,
+ unhandled: unhandled.length,
+ }));
+ """,
+ )
+ assert out["beforeFailure"] == "thread-b", "B really owned the active id before A failed"
+ assert (
+ out["activeThreadId"] == "thread-b"
+ ), "a superseded saved switch failing must not detach the saved chat now on screen"
+ assert out["unhandled"] == 0
+
+
+def test_a_claim_whose_switch_settled_off_view_does_not_outlive_it():
+ """A claim has to be retired by its own switch settling, not by a view happening to
+ notice that thread.
+
+ A is delayed, B becomes visible, A settles anyway: the B view reasserts B and spends a
+ B claim, and A's claim stays armed with nothing left to correct. Opening A normally
+ later spends the stale claim instead of the new one, so returning to a project composer
+ reads the legitimate A as a stale arrival and starts a SECOND switchToNewThread
+ alongside the landing's own -- which can switch away from a thread the user has already
+ sent a message on.
+ """
+ out = _run(
+ "renderProvider, renderSettled, switchState, world",
+ """
+ await renderSettled({ newThreadNonce: "n1" });
+
+ // A is opened and held.
+ let releaseA: any;
+ world.switchToThreadGate = new Promise((resolve) => { releaseA = resolve; });
+ renderProvider({ initialThreadId: "thread-a" });
+ await tick();
+
+ // B is opened and lands, so B is what the user is looking at.
+ world.switchToThreadGate = null;
+ await renderSettled({ initialThreadId: "thread-b" });
+
+ // A settles anyway, off view. The B view reasserts B.
+ releaseA();
+ await tick();
+ await tick();
+ await renderSettled({ initialThreadId: "thread-b" });
+ const armedAfterB = switchState().pendingSavedThreadIds.length;
+
+ // Later the user opens A normally, and it lands while on screen.
+ await renderSettled({ initialThreadId: "thread-a" });
+
+ // Then goes to the project composer on a fresh nonce.
+ const before = world.switchedToNewThread;
+ await renderSettled({ newThreadNonce: "n2" });
+ await tick();
+ await tick();
+
+ console.log(JSON.stringify({
+ armedAfterB,
+ claims: switchState().pendingSavedThreadIds,
+ newThreadSwitches: world.switchedToNewThread - before,
+ unhandled: unhandled.length,
+ }));
+ """,
+ )
+ assert (
+ out["armedAfterB"] == 0
+ ), "a switch that settled while another saved chat was visible leaves nothing armed"
+ assert out["newThreadSwitches"] == 1, (
+ "the landing's own switch and no correction: a legitimate saved chat that the user "
+ "opened and left is not a stale arrival"
+ )
+ assert out["claims"] == []
+ assert out["unhandled"] == 0
+
+
+0
+
+
+def test_a_stale_arrival_reattaches_the_chat_the_user_started():
+ """Correcting a stale arrival with switchToNewThread() is only right while the nonce's
+ thread is still blank.
+
+ Once the user has sent a message that thread is materialized and assistant-ui's
+ newThreadId has been cleared, so asking for "a new thread" mints a SECOND blank one:
+ the composer walks off the conversation they just started, it looks lost, and the next
+ message lands in the blank thread. The correction has to reattach the thread this view
+ actually owns.
+ """
+ out = _run(
+ "renderProvider, renderSettled, nonceThreadId, world",
+ """
+ await renderSettled({ newThreadNonce: "n1" });
+ const ownThread = world.mainThreadId;
+
+ // Open a saved chat and hold it.
+ let release: any;
+ world.switchToThreadGate = new Promise((resolve) => { release = resolve; });
+ renderProvider({ initialThreadId: "thread-a" });
+ await tick();
+
+ // Back to the landing, which reattaches its own thread...
+ world.switchToThreadGate = null;
+ renderProvider({ newThreadNonce: "n1" });
+ await tick();
+ // ...and the user sends a message, materializing it.
+ world.mainThreadId = "remote-1";
+ renderProvider({ newThreadNonce: "n1" });
+ await tick();
+ await tick();
+
+ const switchesBefore = world.switchedToNewThread;
+
+ // Only now does the saved switch land.
+ release();
+ await tick();
+ await tick();
+ renderProvider({ newThreadNonce: "n1" });
+ await tick();
+ await tick();
+
+ console.log(JSON.stringify({
+ ownThread,
+ mainThreadId: world.mainThreadId,
+ newThreadSwitches: world.switchedToNewThread - switchesBefore,
+ savedSwitches: world.switchedToThread.filter((id) => id.startsWith("thread-")),
+ reattachedTo: world.switchedToThread[world.switchedToThread.length - 1],
+ owned: nonceThreadId(),
+ unhandled: unhandled.length,
+ }));
+ """,
+ )
+ assert out["mainThreadId"] == "remote-1", (
+ "the correction must put the user back on the conversation they started, not on a "
+ "fresh blank thread"
+ )
+ assert out["newThreadSwitches"] == 0, "and it must not mint another thread to do it"
+ assert out["reattachedTo"] == "remote-1", "it reattaches by id"
+ assert out["savedSwitches"] == ["thread-a"], "only the one saved switch was started"
+ assert out["owned"] == "remote-1", (
+ "and the record follows the thread through materialization, which is why the "
+ "reattach can name the persisted id rather than the local one it opened"
+ )
+ assert out["unhandled"] == 0
+
+
+def test_a_superseded_failure_still_releases_the_reload_shell():
+ """#9251 holds a retained shell over a reload until the initial switch reports in, and
+ releases it from ThreadAutoSwitch's rejection arm. This PR added a staleness guard to
+ that arm, so the signal has to sit AHEAD of it: a switch that lost the race is still a
+ switch that ended, and returning early would leave the shell showing its snapshot for
+ ever.
+
+ Cross-PR, and the reason it is asserted here: nothing in #9251's own tests exercises a
+ superseded switch, because before this PR there was no guard to be superseded by.
+ """
+ out = _run(
+ "renderProvider, renderSettled, snapshot, world",
+ """
+ await renderSettled({ newThreadNonce: "n1" });
+
+ // A saved switch that will fail, held open.
+ let release: any;
+ world.switchToThreadGate = new Promise((resolve) => { release = resolve; });
+ world.switchToThreadRejects = true;
+ renderProvider({ initialThreadId: "thread-a" });
+ await tick();
+
+ // The route moves on, so a newer switch owns the runtime and supersedes it.
+ world.switchToThreadGate = null;
+ world.switchToThreadRejects = false;
+ renderProvider({ newThreadNonce: "n1" });
+ await tick();
+ const signalsBefore = world.switchFailedSignals;
+
+ release();
+ await tick();
+ await tick();
+
+ console.log(JSON.stringify({
+ signalsBefore,
+ signals: world.switchFailedSignals,
+ unhandled: unhandled.length,
+ }));
+ """,
+ )
+ assert out["signalsBefore"] == 0, "nothing had failed yet"
+ assert out["signals"] == 1, (
+ "a superseded failure must still release the reload shell, or a reload that races "
+ "a view change hangs on the retained snapshot"
+ )
+ assert out["unhandled"] == 0
+
+
+def test_returning_to_a_nonce_reopens_the_chat_started_under_it():
+ """A ?new= URL does not change when its chat materializes, so Back from a saved chat
+ lands on the same nonce -- and a saved-chat detour released it, so the switch effect
+ runs again and used to mint a fresh blank thread. The conversation the user started is
+ then hidden and their next message opens yet another chat.
+
+ Only for a nonce whose thread was actually sent to. A blank placeholder is still
+ replaced, which is the behaviour the detour test above pins.
+ """
+ out = _run(
+ "renderProvider, renderSettled, world",
+ """
+ await renderSettled({ newThreadNonce: "n1" });
+ const opened = world.mainThreadId;
+
+ // The user sends a message: the thread materializes and gets a row.
+ world.remoteIds[opened] = "remote-1";
+
+ // Off to a saved chat, which releases the nonce...
+ await renderSettled({ initialThreadId: "thread-a" });
+ // ...and Back to the very same nonce.
+ const before = world.switchedToNewThread;
+ await renderSettled({ newThreadNonce: "n1" });
+
+ console.log(JSON.stringify({
+ opened,
+ mainThreadId: world.mainThreadId,
+ mintedOnReturn: world.switchedToNewThread - before,
+ unhandled: unhandled.length,
+ }));
+ """,
+ )
+ assert out["mainThreadId"] == out["opened"], (
+ "coming back to the nonce must reopen the conversation started under it, not a "
+ "blank thread the user has to find their way out of"
+ )
+ assert out["mintedOnReturn"] == 0, "and it must not mint another thread to do it"
+ assert out["unhandled"] == 0
+
+
+def test_a_reopen_that_lands_after_the_nonce_rotated_does_not_take_the_view():
+ """The returning-nonce reopen has to be as cancellable as a saved-thread switch.
+
+ A project landing remounts when the user comes back from a saved chat, and its mount
+ effect rotates the nonce -- but the first render still carries the OLD one, so the
+ reopen starts before the rotation. Two switches are then in flight, and if the reopen
+ resolves last the overview's composer is left on the old conversation and the next
+ prompt appends there.
+ """
+ out = _run(
+ "renderProvider, renderSettled, world",
+ """
+ await renderSettled({ newThreadNonce: "n1" });
+ const started = world.mainThreadId;
+ world.remoteIds[started] = "remote-1";
+
+ // Detour to a saved chat, releasing the nonce.
+ await renderSettled({ initialThreadId: "thread-a" });
+
+ // Back on the stale nonce: the reopen starts, held open.
+ let release: any;
+ world.switchToThreadGate = new Promise((resolve) => { release = resolve; });
+ renderProvider({ newThreadNonce: "n1" });
+ await tick();
+
+ // The landing's mount effect rotates the nonce, starting a fresh switch.
+ world.switchToThreadGate = null;
+ renderProvider({ newThreadNonce: "n2" });
+ await tick();
+ await tick();
+
+ // Only now does the reopen land.
+ release();
+ await tick();
+ await tick();
+ renderProvider({ newThreadNonce: "n2" });
+ await tick();
+ await tick();
+
+ console.log(JSON.stringify({
+ started,
+ mainThreadId: world.mainThreadId,
+ unhandled: unhandled.length,
+ }));
+ """,
+ )
+ assert out["mainThreadId"] != out["started"], (
+ "a reopen that lost the race to a rotated nonce must not leave the overview on the "
+ "old conversation"
+ )
+ assert out["unhandled"] == 0
+
+
+def test_a_nonce_does_not_adopt_the_chat_the_user_came_from():
+ """Ownership is only recorded from a thread the nonce's OWN switch opened.
+
+ Entering New Chat from a saved chat leaves that saved chat as ``mainThreadId`` until
+ switchToNewThread() resolves, and its claim was already retired while it was on screen,
+ so it is unclaimed too. Treating "unclaimed and current" as ownership recorded the chat
+ the user had just LEFT: a detour before the fresh switch settled kept that record, and
+ coming back to the same ?new= URL reopened it, so the next prompt appended to the wrong
+ conversation.
+ """
+ out = _run(
+ "renderProvider, renderSettled, nonceThreadId, nonceOwnershipIsSettled, world",
+ """
+ // A saved chat that has been sent to, so it has a row worth reopening.
+ world.remoteIds["thread-a"] = "remote-a";
+ await renderSettled({ initialThreadId: "thread-a" });
+
+ // New Chat, with its switch held open: the view is still on thread-a.
+ let releaseNew: any;
+ world.newThreadGate = new Promise((resolve) => { releaseNew = resolve; });
+ renderProvider({ newThreadNonce: "n1" });
+ await tick();
+ const ownedWhilePending = nonceThreadId();
+ const settledWhilePending = nonceOwnershipIsSettled();
+
+ // The user leaves for another saved chat before the fresh switch lands.
+ world.newThreadGate = null;
+ releaseNew();
+ await renderSettled({ initialThreadId: "thread-b" });
+
+ // Back to the same ?new= URL.
+ await renderSettled({ newThreadNonce: "n1" });
+
+ console.log(JSON.stringify({
+ ownedWhilePending,
+ settledWhilePending,
+ mainThreadId: world.mainThreadId,
+ unhandled: unhandled.length,
+ }));
+ """,
+ )
+ assert (
+ out["settledWhilePending"] is False
+ ), "the nonce's own switch has not landed yet, so nothing it sees is its own"
+ assert (
+ out["ownedWhilePending"] is None
+ ), "the outgoing saved chat must not be recorded as the nonce's own thread"
+ assert out["mainThreadId"] != "thread-a", (
+ "returning to the nonce must not reopen the chat the user left, or their next "
+ "message appends to it"
+ )
+ assert out["unhandled"] == 0
+
+
+def test_a_nonce_still_owns_the_thread_its_own_switch_opened():
+ """The other half: once the nonce's switch HAS landed, the thread it opened is its own,
+ including after materialization renames it. Without this the reopen never arms and
+ ``test_returning_to_a_nonce_reopens_the_chat_started_under_it`` is the regression."""
+ out = _run(
+ "renderSettled, nonceThreadId, nonceOwnershipIsSettled, world",
+ """
+ world.remoteIds["thread-a"] = "remote-a";
+ await renderSettled({ initialThreadId: "thread-a" });
+
+ // New Chat, allowed to land this time.
+ await renderSettled({ newThreadNonce: "n1" });
+ const opened = world.mainThreadId;
+ const ownedAfterLanding = nonceThreadId();
+ const settledAfterLanding = nonceOwnershipIsSettled();
+
+ // The user sends: the thread materializes and gets a row.
+ world.remoteIds[opened] = "remote-1";
+ await renderSettled({ newThreadNonce: "n1" });
+
+ // Detour and back: the reopen must find it.
+ await renderSettled({ initialThreadId: "thread-b" });
+ const mintedBefore = world.switchedToNewThread;
+ await renderSettled({ newThreadNonce: "n1" });
+
+ console.log(JSON.stringify({
+ opened,
+ ownedAfterLanding,
+ settledAfterLanding,
+ mainThreadId: world.mainThreadId,
+ mintedOnReturn: world.switchedToNewThread - mintedBefore,
+ unhandled: unhandled.length,
+ }));
+ """,
+ )
+ assert out["settledAfterLanding"] is True
+ assert (
+ out["ownedAfterLanding"] == out["opened"]
+ ), "the thread this nonce's own switch opened is the one it owns"
+ assert out["mainThreadId"] == out["opened"], "and coming back must reopen it"
+ assert out["mintedOnReturn"] == 0, "without minting another blank thread to do it"
+ assert out["unhandled"] == 0
+
+
+def test_a_superseded_landing_does_not_hand_ownership_to_a_newer_attempt():
+ """A switch that lands after a newer one started must not mark the newer attempt as
+ settled: the newer switch is still in flight, and its view is still on whatever the
+ older one left behind."""
+ out = _run(
+ "renderProvider, renderSettled, nonceOwnershipIsSettled, world",
+ """
+ world.remoteIds["thread-a"] = "remote-a";
+ await renderSettled({ initialThreadId: "thread-a" });
+
+ // First New Chat, held on its own gate.
+ let releaseFirst: any;
+ world.newThreadGate = new Promise((resolve) => { releaseFirst = resolve; });
+ renderProvider({ newThreadNonce: "n1" });
+ await tick();
+
+ // A second nonce supersedes it, held on a gate of its own so it stays in flight.
+ world.newThreadGate = new Promise(() => {});
+ renderProvider({ newThreadNonce: "n2" });
+ await tick();
+
+ // Only now does the FIRST switch land.
+ releaseFirst();
+ await tick();
+ await tick();
+
+ console.log(JSON.stringify({
+ settled: nonceOwnershipIsSettled(),
+ unhandled: unhandled.length,
+ }));
+ """,
+ )
+ assert (
+ out["settled"] is False
+ ), "an older switch landing says nothing about the attempt that replaced it"
+ assert out["unhandled"] == 0
+
+
+def test_a_remembered_thread_the_store_has_dropped_does_not_take_the_app_down():
+ """``nonceThread`` is a REMEMBERED id, in a ref that outlives every view switch now, and
+ the reopen looks it up with ``getItemById``. That call does not return undefined for an
+ unknown id -- assistant-ui throws "Entry not available in the store" out of
+ ``ShallowMemoizeSubject``'s constructor -- so the optional chain around it catches
+ nothing, and an effect that throws with no error boundary above it blanks the app.
+
+ Studio deletes chats through storage and tombstones rather than ``runtime.threads.delete()``,
+ so nothing evicts an entry today. The reopen must not be the thing that depends on that.
+ """
+ out = _run(
+ "renderSettled, world",
+ """
+ // Open a nonce chat and send to it, so it is remembered as the nonce's own.
+ await renderSettled({ newThreadNonce: "n1" });
+ const opened = world.mainThreadId;
+ world.remoteIds[opened] = "remote-1";
+ await renderSettled({ newThreadNonce: "n1" });
+
+ // Away and back, but the runtime has since dropped the entry.
+ await renderSettled({ initialThreadId: "thread-a" });
+ world.missingThreadIds[opened] = true;
+
+ let threw: any = null;
+ try {
+ await renderSettled({ newThreadNonce: "n1" });
+ } catch (error: any) {
+ threw = String(error?.message ?? error);
+ }
+
+ console.log(JSON.stringify({
+ threw,
+ mainThreadId: world.mainThreadId,
+ unhandled: unhandled.length,
+ }));
+ """,
+ )
+ assert out["threw"] is None, f"the reopen threw out of the effect: {out['threw']}"
+ assert (
+ out["mainThreadId"] != "thread-a"
+ ), "and it still has to leave the saved chat it came from"
+ assert out["unhandled"] == 0
+
+
+def test_back_from_a_nonce_chats_own_row_keeps_that_chat():
+ """The reopen's claim is this view's OWN, and must not read as a stale arrival.
+
+ A materialized ?new= chat can be opened through its own sidebar row, and the ?new= URL
+ never changed, so Back returns to the nonce with that chat already current. The switch
+ effect still pushes a reopen claim for it, and ``switchToThread()`` early-returns when
+ its target is already the main thread, so the claim is still outstanding when the
+ correction effect runs in the same commit. Treating it as somebody else's late arrival
+ fell through to ``switchToNewThread()`` and replaced the conversation the user had just
+ come back to with a blank chat.
+ """
+ out = _run(
+ "renderSettled, world",
+ """
+ await renderSettled({ newThreadNonce: "n1" });
+ const started = world.mainThreadId;
+ world.remoteIds[started] = "remote-1";
+ await renderSettled({ newThreadNonce: "n1" });
+
+ // Opened through its own row, which is how a materialized new chat is reachable.
+ await renderSettled({ initialThreadId: started });
+
+ const mintedBefore = world.switchedToNewThread;
+ await renderSettled({ newThreadNonce: "n1" });
+
+ console.log(JSON.stringify({
+ started,
+ mainThreadId: world.mainThreadId,
+ mintedOnReturn: world.switchedToNewThread - mintedBefore,
+ unhandled: unhandled.length,
+ }));
+ """,
+ )
+ assert (
+ out["mainThreadId"] == out["started"]
+ ), "Back must leave the user in the conversation they came back to, not a blank chat"
+ assert (
+ out["mintedOnReturn"] == 0
+ ), "the remembered chat was already current, so nothing needed opening at all"
+ assert out["unhandled"] == 0