π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(chat): prevent send continuation from yanking user back to the sent topic (#19768)
Arvin Xu7b7d89e2db94
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.tsindex 8a68056cb27..0eb33d8f92f 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts@@ -5746,10 +5746,13 @@ describe('ConversationLifecycle actions', () => {});// switchTopic should be called with the new topicId and clearNewKey option- expect(switchTopicSpy).toHaveBeenCalledWith(newTopicId, {- clearNewKey: true,- skipRefreshMessage: true,- });+ expect(switchTopicSpy).toHaveBeenCalledWith(+ newTopicId,+ expect.objectContaining({+ clearNewKey: true,+ skipRefreshMessage: true,+ }),+ );// After new topic creation, the _new key should be clearedconst messagesInNewKey = useChatStore.getState().messagesMap[newKey];diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.tsindex 301e00b397e..8258ab34a57 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts@@ -337,6 +337,18 @@ export class ConversationLifecycleActionImpl {let detachCallerAbort = () => {};let hasNotifiedMessageAccepted = false;let sendOperationId: string | undefined = undefined;+ // Where the user was when they hit send. This send's continuations adopt the+ // topic it creates only while the conversation is still here β the awaited+ // preflight (access check, snapshots, topic resolution) is long enough for+ // the user to open another topic, and following them with a switchTopic+ // would yank both the message list and the URL back (see the+ // `onlyIfActiveTopicIn` guards below). The agent and group are pinned too:+ // two blank views share `activeTopicId === null`, so the topic guard alone+ // cannot tell "still on the origin blank view" from "moved to another+ // agent's/group's blank view".+ const sendOriginActiveTopicId = this.#get().activeTopicId || null;+ const sendOriginActiveAgentId = this.#get().activeAgentId ?? null;+ const sendOriginActiveGroupId = this.#get().activeGroupId ?? null;const detachUnacceptedCallerAbort = () => {if (!hasNotifiedMessageAccepted) detachCallerAbort();};@@ -1094,7 +1106,18 @@ export class ConversationLifecycleActionImpl {messageMapKey({ ...operationContext, topicId: null }),currentContextKey,);- await this.#get().switchTopic(mintedTopicId, { skipRefreshMessage: true });+ // Adopt the minted bucket only while the user is still on the view this+ // send started from. If they navigated away while the awaits above+ // (access check, snapshots) were in flight, don't yank them onto the new+ // topic's bucket. The agent/group pins cover the blank-view case: a+ // null topic origin and another conversation's null topic view are+ // indistinguishable without them.+ await this.#get().switchTopic(mintedTopicId, {+ onlyIfActiveAgentId: sendOriginActiveAgentId,+ onlyIfActiveGroupId: sendOriginActiveGroupId,+ onlyIfActiveTopicIn: [sendOriginActiveTopicId],+ skipRefreshMessage: true,+ });}// The topic list store is paginated β a deep-linked older topic can be the@@ -1507,6 +1530,17 @@ export class ConversationLifecycleActionImpl {} else {await this.#get().switchTopic(heteroData.topicId, {clearNewKey: true,+ // The cleanup targets the blank bucket this send came from β the+ // user may be viewing a different conversation by now.+ clearNewKeyContext: {+ agentId: operationContext.agentId,+ groupId: operationContext.groupId,+ },+ // Guard against yanking the user back if they navigated to another+ // topic while the persistence round-trip was in flight. Accept both+ // the minted id and the persisted one: `resolveOptimisticTopic`+ // above re-keys `activeTopicId` from the former to the latter.+ onlyIfActiveTopicIn: [operationContext.topicId ?? null, heteroData.topicId],skipRefreshMessage: true,});}@@ -2040,6 +2074,19 @@ export class ConversationLifecycleActionImpl {// clearNewKey: true ensures the _new key data is cleared after topic creationawait this.#get().switchTopic(data.topicId, {clearNewKey: true,+ // The cleanup targets the blank bucket this send came from β the+ // user may be viewing a different conversation by now.+ clearNewKeyContext: {+ agentId: operationContext.agentId,+ groupId: operationContext.groupId,+ },+ // The send pivoted to the minted topic bucket at send time. If the+ // user navigated to another topic while the persistence round-trip+ // was in flight, leave them where they are β the new topic's unread+ // badge surfaces the completed reply instead of yanking the view back.+ // Both ids are accepted: `resolveOptimisticTopic` above re-keys+ // `activeTopicId` from the minted id to the persisted one.+ onlyIfActiveTopicIn: [operationContext.topicId ?? null, data.topicId],skipRefreshMessage: true,});}diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex e556d77eb14..82cab2e0b17 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -1033,6 +1033,17 @@ export class GatewayActionImpl {if (!messageContext.isolatedTopic) {await this.#get().switchTopic(result.topicId, {clearNewKey: true,+ // The cleanup targets the blank bucket this send came from β the+ // user may be viewing a different conversation by now.+ clearNewKeyContext: {+ agentId: messageContext.agentId,+ groupId: messageContext.groupId,+ },+ // Guard against yanking the user back if they navigated to another+ // topic while execAgentTask's persistence round-trip was in flight.+ // Both ids are accepted: the optimistic-topic re-key above moves+ // `activeTopicId` from the minted id to the persisted one.+ onlyIfActiveTopicIn: [messageContext.topicId ?? null, result.topicId],skipRefreshMessage: true,});}diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.tsindex fccfd4a3835..1a7d411cf93 100644--- a/src/store/chat/slices/topic/action.test.ts+++ b/src/store/chat/slices/topic/action.test.ts@@ -1758,6 +1758,231 @@ describe('topic action', () => {expect(revalidateSpy).toHaveBeenCalledTimes(1);expect(useChatStore.getState().activeTopicId).toBe('topic-b');});++ describe('onlyIfActiveTopicIn guard', () => {+ it('skips the switch when the user has navigated to another topic', async () => {+ // Regression: a send's continuation calls switchTopic(newTopicId) after+ // the persistence round-trip. If the user switched topics while that+ // await was in flight, the unconditional switch yanked the UI (and the+ // URL) back to the sent topic. The guard must drop the switch instead.+ const { result } = renderHook(() => useChatStore());+ const revalidateSpy = vi+ .spyOn(result.current, 'revalidateMessages')+ .mockResolvedValue(undefined);++ await act(async () => {+ useChatStore.setState({ activeTopicId: 'topic-user-moved-to' });+ });++ await act(async () => {+ await result.current.switchTopic('topic-from-send', {+ clearNewKey: true,+ onlyIfActiveTopicIn: ['topic-from-send'],+ skipRefreshMessage: true,+ });+ });++ // The user's own topic stays active; the stale send continuation is a no-op.+ expect(useChatStore.getState().activeTopicId).toBe('topic-user-moved-to');+ expect(revalidateSpy).not.toHaveBeenCalled();+ });++ it('skips the switch when the user moved to the blank new-conversation view', async () => {+ // Unset is the store's own "no topic" representation, so this also+ // covers the guard's normalization of an unset field to `null`.+ const { result } = renderHook(() => useChatStore());+ vi.spyOn(result.current, 'revalidateMessages').mockResolvedValue(undefined);+ await act(async () => {+ useChatStore.setState({ activeTopicId: undefined });+ });++ await act(async () => {+ await result.current.switchTopic('topic-from-send', {+ clearNewKey: true,+ onlyIfActiveTopicIn: ['topic-from-send'],+ skipRefreshMessage: true,+ });+ });++ expect(useChatStore.getState().activeTopicId).toBeUndefined();+ });++ it('applies the switch when the user is still on the expected topic', async () => {+ const { result } = renderHook(() => useChatStore());+ const revalidateSpy = vi+ .spyOn(result.current, 'revalidateMessages')+ .mockResolvedValue(undefined);++ await act(async () => {+ useChatStore.setState({ activeTopicId: 'topic-from-send' });+ });++ await act(async () => {+ await result.current.switchTopic('topic-from-send', {+ clearNewKey: true,+ onlyIfActiveTopicIn: ['topic-from-send'],+ skipRefreshMessage: true,+ });+ });++ expect(useChatStore.getState().activeTopicId).toBe('topic-from-send');+ // clearNewKey still runs its side effects on an applied switch.+ expect(useChatStore.getState().activeThreadId).toBeUndefined();+ // skipRefreshMessage still suppresses the revalidation on an applied switch.+ expect(revalidateSpy).not.toHaveBeenCalled();+ });++ it('applies the switch when the user sits on any accepted bucket', async () => {+ // A send's topic can live under two ids: the client-minted one before+ // the server confirms it, and the persisted one after the re-key. The+ // guard must accept the conversation while it is on either, otherwise+ // the send's own continuation would be dropped on the normal path.+ const { result } = renderHook(() => useChatStore());+ vi.spyOn(result.current, 'revalidateMessages').mockResolvedValue(undefined);++ await act(async () => {+ useChatStore.setState({ activeTopicId: 'topic-persisted' });+ });++ await act(async () => {+ await result.current.switchTopic('topic-persisted', {+ clearNewKey: true,+ onlyIfActiveTopicIn: ['topic-minted', 'topic-persisted'],+ skipRefreshMessage: true,+ });+ });++ expect(useChatStore.getState().activeTopicId).toBe('topic-persisted');+ });++ it('does not consume the switch epoch when the guard skips', async () => {+ const { result } = renderHook(() => useChatStore());+ const revalidateSpy = vi+ .spyOn(result.current, 'revalidateMessages')+ .mockResolvedValue(undefined);++ await act(async () => {+ useChatStore.setState({ activeTopicId: 'other-topic' });+ });++ // A guarded (skipped) call must not invalidate a concurrent normal+ // switch's pending revalidation: the skipped call returns before the+ // epoch bump, so the epoch only moves for real switches.+ await act(async () => {+ const guarded = result.current.switchTopic('topic-from-send', {+ onlyIfActiveTopicIn: ['topic-from-send'],+ skipRefreshMessage: true,+ });+ const real = result.current.switchTopic('real-topic');+ await Promise.all([guarded, real]);+ });++ expect(useChatStore.getState().activeTopicId).toBe('real-topic');+ expect(revalidateSpy).toHaveBeenCalledTimes(1);+ });++ it('skips the switch when the active agent changed between two blank views', async () => {+ // Regression (Codex P1): the topic guard alone cannot tell two blank+ // views apart β both have `activeTopicId` unset. A send from agent A's+ // blank view whose preflight outlasts the user's navigation to agent+ // B's blank view must NOT adopt A's minted topic in B's UI.+ const { result } = renderHook(() => useChatStore());+ const revalidateSpy = vi+ .spyOn(result.current, 'revalidateMessages')+ .mockResolvedValue(undefined);++ await act(async () => {+ useChatStore.setState({ activeAgentId: 'agent-b', activeTopicId: undefined });+ });++ await act(async () => {+ await result.current.switchTopic('topic-minted-by-send', {+ onlyIfActiveAgentId: 'agent-a',+ onlyIfActiveTopicIn: [null],+ skipRefreshMessage: true,+ });+ });++ expect(useChatStore.getState().activeTopicId).toBeUndefined();+ expect(revalidateSpy).not.toHaveBeenCalled();+ });++ it('applies the switch when the agent and topic both still match', async () => {+ const { result } = renderHook(() => useChatStore());+ vi.spyOn(result.current, 'revalidateMessages').mockResolvedValue(undefined);++ await act(async () => {+ useChatStore.setState({ activeAgentId: 'agent-a', activeTopicId: undefined });+ });++ await act(async () => {+ await result.current.switchTopic('topic-minted-by-send', {+ onlyIfActiveAgentId: 'agent-a',+ onlyIfActiveTopicIn: [null],+ skipRefreshMessage: true,+ });+ });++ expect(useChatStore.getState().activeTopicId).toBe('topic-minted-by-send');+ });++ it('skips the switch when the active group changed between two blank views', async () => {+ const { result } = renderHook(() => useChatStore());+ vi.spyOn(result.current, 'revalidateMessages').mockResolvedValue(undefined);++ await act(async () => {+ useChatStore.setState({ activeGroupId: 'group-b', activeTopicId: undefined });+ });++ await act(async () => {+ await result.current.switchTopic('topic-minted-by-send', {+ onlyIfActiveGroupId: null,+ onlyIfActiveTopicIn: [null],+ skipRefreshMessage: true,+ });+ });++ expect(useChatStore.getState().activeTopicId).toBeUndefined();+ });++ it('still clears the origin _new bucket when the guard drops the switch', async () => {+ // Regression (Codex P1): a dropped switch used to suppress the+ // clearNewKey cleanup too, leaving the send's origin blank bucket+ // stale β and cleaning by the current view would wipe the WRONG+ // conversation's bucket. The cleanup must target the origin.+ const { result } = renderHook(() => useChatStore());+ const replaceSpy = vi.spyOn(result.current, 'replaceMessages');+ const clearPortalSpy = vi.spyOn(result.current, 'clearPortalStack');++ await act(async () => {+ useChatStore.setState({+ activeAgentId: 'agent-b',+ activeGroupId: undefined,+ activeTopicId: 'topic-user-moved-to',+ });+ });++ await act(async () => {+ await result.current.switchTopic('topic-from-send', {+ clearNewKey: true,+ clearNewKeyContext: { agentId: 'agent-a', groupId: null },+ onlyIfActiveTopicIn: ['topic-from-send'],+ skipRefreshMessage: true,+ });+ });++ // Navigation droppedβ¦+ expect(useChatStore.getState().activeTopicId).toBe('topic-user-moved-to');+ // β¦but the origin conversation's _new bucket was still cleared.+ expect(clearPortalSpy).toHaveBeenCalled();+ expect(replaceSpy).toHaveBeenCalledWith(+ [],+ expect.objectContaining({+ context: expect.objectContaining({ agentId: 'agent-a', topicId: null }),+ }),+ );+ });+ });});describe('removeSessionTopics', () => {it('should remove all topics from the current session and refresh the topic list', async () => {diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.tsindex 76b6e2d02f4..d946db77e0d 100644--- a/src/store/chat/slices/topic/action.ts+++ b/src/store/chat/slices/topic/action.ts@@ -110,6 +110,41 @@ export interface SwitchTopicOptions {* @default false*/clearNewKey?: boolean;+ /**+ * The conversation whose `_new` bucket the cleanup should target. Send+ * flows pass the conversation the send started from: when the navigation+ * guard drops the switch, the user may be viewing a different agent/group,+ * and cleaning up by current view would wipe that view's blank bucket+ * instead of the send's own. Omit to clean by the current view (legacy).+ */+ clearNewKeyContext?: {+ agentId: string;+ groupId?: string | null;+ scope?: MessageMapScope;+ };+ /**+ * Only apply the switch while the active agent still matches. Send flows+ * pin the agent they started from: the topic guard cannot tell two blank+ * views apart (both have `activeTopicId === null`), so without this a send+ * from agent A's blank view would adopt its minted topic while the user is+ * on agent B's blank view. Omit the option to skip the check.+ */+ onlyIfActiveAgentId?: string | null;+ /**+ * Only apply the switch while the active group still matches β the+ * group-scope counterpart of `onlyIfActiveAgentId`.+ */+ onlyIfActiveGroupId?: string | null;+ /**+ * Only apply the switch while the user is still on one of these conversation+ * buckets. Send flows pass every bucket their conversation can currently live+ * under β the client-minted topic id before the server confirms it, the+ * persisted id after the re-key β so a continuation whose await the user+ * navigated away from skips the switch instead of yanking the UI (and the+ * URL) back to the sent topic. Include `null` to allow the blank+ * new-conversation view. Omit the option to always apply the switch.+ */+ onlyIfActiveTopicIn?: ReadonlyArray<string | null>;/*** Explicit scope for clearing new key data* If not provided, will be inferred from store state (activeGroupId)@@ -1634,7 +1669,6 @@ export class ChatTopicActionImpl {switchTopic = async (id?: string | null, options?: SwitchTopicOptions): Promise<void> => {const opts = options ?? {};- const epoch = ++this.#switchTopicEpoch;const { activeAgentId, activeGroupId } = this.#get();@@ -1643,20 +1677,31 @@ export class ChatTopicActionImpl {// 2. When clearNewKey option is explicitly true// This prevents stale data from previous conversations showing up// Note: Use == null to match both null and undefined+ //+ // Housekeeping runs BEFORE the navigation guard below: a send whose+ // continuation is dropped because the user navigated away is still done+ // with the blank conversation it came from β the cleanup targets that+ // origin bucket (opts.clearNewKeyContext), never the view the user moved+ // to. In the normal (unguarded) case origin and current view are the same+ // conversation, so this is identical to cleaning up after the guard.const shouldClearNewKey = !id || opts.clearNewKey;if (shouldClearNewKey) {this.#get().clearPortalStack();}- if (shouldClearNewKey && activeAgentId) {- // Determine scope: use explicit scope from options, or infer from activeGroupId- const scope = opts.scope ?? (activeGroupId ? 'group' : 'main');+ const cleanupAgentId = opts.clearNewKeyContext?.agentId ?? activeAgentId;+ const cleanupGroupId = opts.clearNewKeyContext?.groupId ?? activeGroupId;++ if (shouldClearNewKey && cleanupAgentId) {+ // Determine scope: use explicit scope, or infer from the cleanup group+ const scope =+ opts.clearNewKeyContext?.scope ?? opts.scope ?? (cleanupGroupId ? 'group' : 'main');this.#get().replaceMessages([], {context: {- agentId: activeAgentId,- groupId: activeGroupId,+ agentId: cleanupAgentId,+ groupId: cleanupGroupId,scope,topicId: null,},@@ -1664,6 +1709,37 @@ export class ChatTopicActionImpl {});}+ // Send-flow continuation guard: if the caller requires the user to still+ // be on a specific conversation and they've navigated elsewhere while the+ // send's awaits were in flight, drop the switch instead of yanking the UI+ // (and the URL, via ChatHydration's route sync) back to the sent topic.+ // The topic id alone cannot tell two blank views apart β a null origin and+ // a null destination look identical β so send flows also pin the agent and+ // group they started from. The epoch token below cannot catch any of this+ // β the user's switch happened in between, but this call is still the+ // newest one. Runs before the epoch bump: a skipped switch must not+ // invalidate a concurrent switch's pending revalidation.+ if (opts.onlyIfActiveTopicIn) {+ // `activeTopicId` uses `null` for "no topic" but is typed `string` and can+ // hold `undefined`/`''` from callers that never went through switchTopic,+ // so normalize before comparing β an unset field must still match an+ // explicit `null` expectation (the blank new-conversation view).+ const activeTopicId = this.#get().activeTopicId || null;+ if (!opts.onlyIfActiveTopicIn.includes(activeTopicId)) return;+ }+ if (+ opts.onlyIfActiveAgentId !== undefined &&+ (activeAgentId ?? null) !== opts.onlyIfActiveAgentId+ )+ return;+ if (+ opts.onlyIfActiveGroupId !== undefined &&+ (activeGroupId ?? null) !== opts.onlyIfActiveGroupId+ )+ return;++ const epoch = ++this.#switchTopicEpoch;+this.#set({ activeTopicId: id || (null as any), activeThreadId: undefined },false,