diff --git a/website/src/components/commandPalette/providers/recentsProvider.ts b/website/src/components/commandPalette/providers/recentsProvider.ts index 7e6debf10d27..0a04963f2450 100644 --- a/website/src/components/commandPalette/providers/recentsProvider.ts +++ b/website/src/components/commandPalette/providers/recentsProvider.ts @@ -405,6 +405,7 @@ export function useRecentsProvider(): ResourceProvider { // the resume has entered the session, nothing on failure (#15732). focusComposerForResumedSession( dispatch(resumeFromHistory({ key: s.key, title: s.title || s.key })).unwrap(), + store, ) navigate('/chat') }, diff --git a/website/src/components/commandPalette/providers/sessionsProvider.ts b/website/src/components/commandPalette/providers/sessionsProvider.ts index 29d76a91c688..e2996a5ca298 100644 --- a/website/src/components/commandPalette/providers/sessionsProvider.ts +++ b/website/src/components/commandPalette/providers/sessionsProvider.ts @@ -5,7 +5,7 @@ import { useNavigate } from 'react-router-dom' import { useQuery, useQueryClient } from '@tanstack/react-query' import { api } from '../../../api/client' -import { useAppDispatch, useAppSelector } from '../../../store' +import { useAppDispatch, useAppSelector, useAppStore } from '../../../store' import { resumeFromHistory } from '../../../store/chatSlice' import { useSelectInstance } from '../../../hooks/useSelectInstance' import { focusComposerForResumedSession } from '../../../pages/chat/composerFocus' @@ -293,6 +293,9 @@ export function useSessionsProvider(opts?: { active?: boolean }): ResourceProvider { const dispatch = useAppDispatch() + // Read on the focus frame after a resume: only a resume that took the view + // moves the caret. + const store = useAppStore() const navigate = useNavigate() const queryClient = useQueryClient() const openInSplit = opts?.openInSplit @@ -369,7 +372,7 @@ export function useSessionsProvider(opts?: { // already active, and declines while this surface's input still holds // focus. Unwrapped, so a failed resume focuses nothing; the slice records // the failure either way (see resumeFromHistory.rejected). - focusComposerForResumedSession(dispatch(resumeFromHistory(ref)).unwrap()) + focusComposerForResumedSession(dispatch(resumeFromHistory(ref)).unwrap(), store) // The palette can be opened from ANY page (artifacts, settings, …); // resumeFromHistory only activates the slot in the store, so land // the user on the chat surface where that slot renders. @@ -377,6 +380,6 @@ export function useSessionsProvider(opts?: { }, openInSplit, }), - [dispatch, navigate, queryClient, openInSplit, selectInstance], + [dispatch, store, navigate, queryClient, openInSplit, selectInstance], ) } diff --git a/website/src/hooks/useSessionActions.cov80.test.tsx b/website/src/hooks/useSessionActions.cov80.test.tsx index 6c4d86509278..c9713ad39802 100644 --- a/website/src/hooks/useSessionActions.cov80.test.tsx +++ b/website/src/hooks/useSessionActions.cov80.test.tsx @@ -85,7 +85,8 @@ describe('duplicate', () => { const { result } = harness() act(() => result.current.duplicate(KEY)) await waitFor(() => expect(apiMock.forkChatSlot).toHaveBeenCalledWith(KEY)) - await waitFor(() => expect(switchSlot).toHaveBeenCalledWith('zzq-forked')) + // The switch names the fork's request number, so a later click still wins (`forkMayOpen`). + await waitFor(() => expect(switchSlot).toHaveBeenCalledWith({ key: 'zzq-forked', requestSeq: expect.any(Number) })) }) it('switches nowhere when the fork is refused', async () => { diff --git a/website/src/hooks/useSessionActions.ts b/website/src/hooks/useSessionActions.ts index 939cc8384af5..726c9556a286 100644 --- a/website/src/hooks/useSessionActions.ts +++ b/website/src/hooks/useSessionActions.ts @@ -259,7 +259,7 @@ export function useSessionActions(mode?: string, opts?: { // The user opened another session while the fork ran: the fork stays // listed, and the view and its chrome (Split View) stay as they are. if (!forkMayOpen(store.getState(), started.origin)) return - dispatch(switchSlot(data.key)) + dispatch(switchSlot({ key: data.key, requestSeq: started.origin.seq })) // The child inherits the source's folder, which can be collapsed (the // source row sits in the pinned group or a board lane, or another tab // collapsed the folder meanwhile): open that path so the active row shows. diff --git a/website/src/pages/chat-sidebar/create.ts b/website/src/pages/chat-sidebar/create.ts index 97d8e765ff71..ac0c385ee0e0 100644 --- a/website/src/pages/chat-sidebar/create.ts +++ b/website/src/pages/chat-sidebar/create.ts @@ -64,7 +64,10 @@ function plainCreateKey(folderId: string, columnId?: string, memoryMode?: string */ async function createSlotWithOrigin(dispatch: AppDispatch, args: Parameters[0]): Promise<{ slot: Slot; origin: ForkOrigin }> { const action = await dispatch(createSlot(args)) - if (createSlot.fulfilled.match(action)) return { slot: action.payload, origin: { activeSlot: action.meta.originActiveSlot ?? null, moves: action.meta.originActiveSlotMoves, autoMoves: action.meta.originActiveSlotAutoMoves } } + if (createSlot.fulfilled.match(action)) { + const m = action.meta + return { slot: action.payload, origin: { activeSlot: m.originActiveSlot ?? null, moves: m.originActiveSlotMoves, autoMoves: m.originActiveSlotAutoMoves, requestMoves: m.originActiveSlotRequestMoves, seq: m.originRequestSeq, burst: m.originRequestBurst } } + } unwrapResult(action) throw new Error('createSlot settled without fulfilling or rejecting') } @@ -77,7 +80,7 @@ export function useFolderChatCreate({ folders, mode, dispatch, dropSlotMutation, mode: string | undefined dispatch: AppDispatch dropSlotMutation: BoardColumnMutations['dropSlotMutation'] - onOpenSlotInNewTab: ((key: string, opts?: { background?: boolean | undefined; } | undefined) => void) | undefined + onOpenSlotInNewTab: ((key: string, opts?: { background?: boolean | undefined; requestSeq?: number } | undefined) => void) | undefined // A plain create ACTIVATES the new session, so the host must leave Split View // and show it — the same callback a row click fires (ChatSidebar's // `onSelectSlot`). Without it the grid keeps drawing the old split over a @@ -174,7 +177,7 @@ export function useFolderChatCreate({ folders, mode, dispatch, dropSlotMutation, if (inNewTab && onOpenSlotInNewTab && slot?.key) { // Adds a tab beside the active one; `foreground` also switches to it, // same as the header New button's gestures (see createChatMutation). - onOpenSlotInNewTab(slot.key, { background: inNewTab === 'background' }) + onOpenSlotInNewTab(slot.key, { background: inNewTab === 'background', ...(inNewTab === 'foreground' ? { requestSeq: origin.seq } : {}) }) // A foreground tab switches the view onto the new session, so leave // Split View too — the same guarded callback the header New fires // after its own foreground switch (createChatMutation). The plain @@ -278,7 +281,7 @@ export function useSessionCreate({ setNewChatError, dispatch, mode, onOpenSlotIn setNewChatError: Dispatch> dispatch: AppDispatch mode: string | undefined - onOpenSlotInNewTab: ((key: string, opts?: { background?: boolean | undefined; } | undefined) => void) | undefined + onOpenSlotInNewTab: ((key: string, opts?: { background?: boolean | undefined; requestSeq?: number } | undefined) => void) | undefined // Leave Split View on a plain create so the new, now-active session shows // instead of the old split (#21935). Same callback a row click fires; the // background-tab gesture does not fire it (the split is kept on purpose). @@ -344,7 +347,7 @@ export function useSessionCreate({ setNewChatError, dispatch, mode, onOpenSlotIn onSuccess: ({ slot, origin }, { inNewTab: requested }) => { const inNewTab = settledTabMode(store, requested, origin) if (inNewTab && onOpenSlotInNewTab) { - onOpenSlotInNewTab(slot.key, { background: inNewTab === 'background' }) + onOpenSlotInNewTab(slot.key, { background: inNewTab === 'background', ...(inNewTab === 'foreground' ? { requestSeq: origin.seq } : {}) }) // Background: the user stays on their transcript, so its composer keeps // whatever focus it had — no `focusComposer`, same as the row gesture. if (inNewTab === 'background') return diff --git a/website/src/pages/chat-sidebar/scope.ts b/website/src/pages/chat-sidebar/scope.ts index 03b6ed510056..d588567f4c82 100644 --- a/website/src/pages/chat-sidebar/scope.ts +++ b/website/src/pages/chat-sidebar/scope.ts @@ -98,7 +98,7 @@ export interface ChatSidebarProps { * window), and an omitted callback leaves the gestures unbound rather than * falling back to a plain switch — a middle-click that quietly navigated * would be indistinguishable from a misfire. */ - onOpenSlotInNewTab?: (key: string, opts?: { background?: boolean }) => void + onOpenSlotInNewTab?: (key: string, opts?: { background?: boolean; requestSeq?: number }) => void /** Reveal a session's pull request / issue in the side panel instead of * leaving for the provider's website. * diff --git a/website/src/pages/chat/composerFocus.ts b/website/src/pages/chat/composerFocus.ts index 4e66ee295eeb..060aac206fe4 100644 --- a/website/src/pages/chat/composerFocus.ts +++ b/website/src/pages/chat/composerFocus.ts @@ -472,18 +472,25 @@ function queryComposerForSlot(key: string | undefined): HTMLElement | null { * `focusComposerAfter` gives: the slice records it, and there is no new * composer to focus. * - * No still-active read here: `resumeFromHistory` moves the active slot only in - * its fulfilled reducer, at the moment this promise settles, so there is no - * provisional window for a keystroke to land in, and the slot the reducer - * entered IS the one the gesture named. + * A displayable answer is still not proof the view moved: the reducer also + * declines to open a resume that answers after the user opened another session + * or clicked a newer row. So the store is read on the focus frame, and the + * caret moves only when `key` is the active slot then. On the single-chat + * surface the one composer belongs to the session the user moved to. * * `key` is the thunk's own payload field -- the slot the gateway resumed, which * is the one the reducer entered -- and names the pane to focus in split view * (#15937). */ -export function focusComposerForResumedSession(resumed: Promise<{ ok: boolean; surface?: string; key: string }>): void { +export function focusComposerForResumedSession( + resumed: Promise<{ ok: boolean; surface?: string; key: string }>, + store: { getState(): { chat: { activeSlot: string | null } } }, +): void { void resumed - .then(result => { if (result.ok && isChatPageSurface(result.surface)) requestAnimationFrame(() => focusComposerNow(result.key)) }) + .then(result => { + if (!result.ok || !isChatPageSurface(result.surface)) return + requestAnimationFrame(() => { if (store.getState().chat.activeSlot === result.key) focusComposerNow(result.key) }) + }) .catch(() => {}) } diff --git a/website/src/pages/chat/memoryModeSwitch.ts b/website/src/pages/chat/memoryModeSwitch.ts index 56e557d7cbc1..6ff825e574f8 100644 --- a/website/src/pages/chat/memoryModeSwitch.ts +++ b/website/src/pages/chat/memoryModeSwitch.ts @@ -79,8 +79,11 @@ export async function runMemorySwitch( // draft, which for a fresh slot is empty, and the old slot (where the // draft lives) is deleted afterwards. let created: { key?: string } | undefined + // The pending action numbers this create (`requestSeq`) synchronously, so + // the origin read right after it carries the create's own number. + const creating = c.dispatch(createSlot({ ...opts, activate: false })) const origin = captureForkOrigin(c.store.getState()) - try { created = await c.dispatch(createSlot({ ...opts, activate: false })).unwrap() } catch (error) { + try { created = await creating.unwrap() } catch (error) { c.showActionError(errMessage(error) || unknownError()) return false } @@ -133,7 +136,7 @@ export async function runMemorySwitch( else if (left) revisited = true }) try { - await c.dispatch(switchSlot(next)).unwrap() + await c.dispatch(switchSlot({ key: next, requestSeq: origin.seq })).unwrap() } catch (error) { // The rejected switch moves the view back to the old slot, and the // slot-change effect clears any error not marked to survive a switch -- diff --git a/website/src/pages/chat/page/SessionsSidebarChrome.tsx b/website/src/pages/chat/page/SessionsSidebarChrome.tsx index 6e56388bdefd..a7ecec5d904b 100644 --- a/website/src/pages/chat/page/SessionsSidebarChrome.tsx +++ b/website/src/pages/chat/page/SessionsSidebarChrome.tsx @@ -58,7 +58,7 @@ interface SessionsSidebarChromeProps { canStageSessionRef: boolean chatPaneEl: HTMLDivElement | null stageSessionRef: (ref: SessionRef) => void - openSlotInNewTab: (key: string, opts?: { background?: boolean; }) => void + openSlotInNewTab: (key: string, opts?: { background?: boolean; requestSeq?: number }) => void ownsSessionTabs: boolean activePoppedOut: boolean focusActivePopout: (id: string) => void diff --git a/website/src/pages/chat/page/sessionsDrawer.ts b/website/src/pages/chat/page/sessionsDrawer.ts index 1283ca0b9e82..c34e0ec033d8 100644 --- a/website/src/pages/chat/page/sessionsDrawer.ts +++ b/website/src/pages/chat/page/sessionsDrawer.ts @@ -347,12 +347,15 @@ export function useSessionsDrawer({ // null and the slot-state reset that follows leaves it undefined. const reduxStore = useStore() const prevActiveSlotRef = useRef(activeSlot ?? null) - const userMovesRef = useRef(reduxStore.getState().chat.activeSlotMoves ?? 0) + // A create, fork or resume the user clicked opens in `activeSlotRequestMoves`, + // and that is their pick too. + const userPicks = (s: RootState) => (s.chat.activeSlotMoves ?? 0) + (s.chat.activeSlotRequestMoves ?? 0) + const userMovesRef = useRef(userPicks(reduxStore.getState())) useEffect(() => { const left = prevActiveSlotRef.current const now = activeSlot ?? null const state = reduxStore.getState() - const userMoves = state.chat.activeSlotMoves ?? 0 + const userMoves = userPicks(state) const userMoved = userMoves !== userMovesRef.current prevActiveSlotRef.current = now userMovesRef.current = userMoves diff --git a/website/src/pages/chat/useChatPageSessionController.ts b/website/src/pages/chat/useChatPageSessionController.ts index 5277f381c338..e60bb2f21d7f 100644 --- a/website/src/pages/chat/useChatPageSessionController.ts +++ b/website/src/pages/chat/useChatPageSessionController.ts @@ -7,7 +7,7 @@ import { api } from '../../api/client' import type { ChatLaunchOptions } from '../../app-sdk' import { i18nT } from '../../i18n/t' import { useSessionTabs } from '../../hooks/useSessionTabs' -import { useAppSelector, type AppDispatch } from '../../store' +import { useAppSelector, useAppStore, type AppDispatch } from '../../store' import { createSlot, deleteSlot, @@ -28,6 +28,7 @@ import { shouldReplaceSessionUrl, popMaySwitchSession } from '../../utils/sessio import { sessionShortNameFrom, shortNameMatches, type ShortNameMatch } from '../../utils/sessionKeys' import { toSlug } from '../../utils/shareUrl' import { focusComposer } from './composerFocus' +import { PENDING_OPEN_LEASE_MS, resumeStillOpening } from '../../store/chatSlice' /** Read a URL-derived key from the close-hold record without traversing its prototype. */ export function closeHoldForUrl(closing: Record, key: string | null): T | undefined { @@ -40,11 +41,7 @@ export function closeHoldForUrl(closing: Record, key: string | nul // the banner false — but it no longer proves the user is waiting for that link, // so it may only retire the notice, never move them. const SID_RECOVERY_WINDOW_MS = 30_000 -/** How long the chat page, having lost its chat, waits for this window's own - * pending create or fork to open one before it auto-picks as usual. Every - * measured create and fork answered within 3.5 s; a request still open after - * this is treated as hung for the page's purposes and keeps running. */ -export const PENDING_OPEN_LEASE_MS = 10_000 +export { PENDING_OPEN_LEASE_MS } /** The key of the history entry the browser stands on, which can be ahead of * the rendered `location.key` while a router transition is uncommitted. The @@ -180,6 +177,9 @@ export function useChatPageSessionController({ * the composer all hang off it), and a second caller inside a layout hook * would be a second place that decides what "activate" means. */ const ownsSessionTabs = !embedded + // Read at settle time by the resume callbacks: whether the resume took the + // view is the store's answer, not the thunk's. + const store = useAppStore() // Read at click time, not captured: the callbacks below are memoized and the // gateway can drop between renders. const connectedRef = useRef(connected) @@ -194,7 +194,9 @@ export function useChatPageSessionController({ * needs the same lock — and the strip is marked aria-disabled so the click * visibly refuses instead of silently doing nothing. */ - const openSlotInNewTab = useCallback((key: string, opts?: { background?: boolean }) => { + // `requestSeq`: the foreground tab opens a create that just answered, with + // the create's origin number, so a request clicked after it still opens. + const openSlotInNewTab = useCallback((key: string, opts?: { background?: boolean; requestSeq?: number }) => { sessionTabs.openInNewTab(key) // A BACKGROUND open (middle-click, modifier-click) queues the session and // leaves the user where they are — the browser/editor meaning of the @@ -204,7 +206,7 @@ export function useChatPageSessionController({ if (!connectedRef.current) return // Foreground open-in-tab is a user gesture on a session reference: the // announced class. - if (key !== activeSlotRef.current) dispatch(switchSlot({ key, announceOnMissing: true })) + if (key !== activeSlotRef.current) dispatch(switchSlot({ key, announceOnMissing: true, ...(opts?.requestSeq !== undefined ? { requestSeq: opts.requestSeq } : {}) })) // Depends on the ONE member it calls, not on `sessionTabs` — that hook // returns a fresh object literal every render, so the whole object as a dep // makes this callback (and thus ChatSidebar's `onOpenSlotInNewTab`, and thus @@ -930,19 +932,37 @@ export function useChatPageSessionController({ return } void dispatch(resumeFromHistory({ key: target.stem, title: target.title })).then(result => { + // The user left ChatPage while the resume ran: its captured route + // is stale, and a navigate here would pull them back to chat. + if (unmountedRef.current) return // A refused, renamed or off-surface resume never reaches `?sid=` // (the reducer leaves activeSlot alone off-surface); release URL sync. + // Nor does one the reducer declined to open because the user moved + // while it ran, so the live active slot decides, as it does in + // handleResumeSession. const resumed = resumeFromHistory.fulfilled.match(result) && result.payload.ok && result.payload.key === target.key && isChatPageSurface(result.payload.surface) + && store.getState().chat.activeSlot === target.key if (resumed) return popInFlightRef.current = false + // The URL was rewritten to name the target, and URL sync skipped + // every switch while it was held. Name the session on screen + // instead, in place: a push would leave a Back entry for a session + // that never showed. URL sync then normalizes the slug. + const viewing = store.getState().chat.activeSlot + if (viewing && viewing !== target.key) { + const back = new URLSearchParams(searchParamsRef.current) + back.set('sid', viewing) + back.delete('slot') + navigate({ pathname: locationPathname, search: `?${back}`, hash: locationHash }, { replace: true }) + } // "Opened " would name a session that never opened; the // unresumable notice explains why. Leave a later link's notice alone. setSidMatches(cur => (cur === mine ? null : cur)) }) }) // Read once per link: the refs carry the live roster and URL into the answer. - }, [connected, slotsLoaded, embedded, embedMode, dispatch, navigate, locationPathname, locationHash, filteredSlotsRef, queryClient]) + }, [connected, slotsLoaded, embedded, embedMode, dispatch, navigate, locationPathname, locationHash, filteredSlotsRef, queryClient, store]) useEffect(() => { if (embedded && !embedMode) return @@ -1146,12 +1166,15 @@ export function useChatPageSessionController({ // The hub's record of this pane's last chat (#16009), used for the first // pick only. A soft hint, unlike ?sid=: a chat that is gone falls through. const slotHintRef = useRef(embedded ? null : searchParams.get(PANE_SLOT_HINT_PARAM)) - // A create or fork started here that will open its own chat when it lands. - const openPending = useAppSelector(s => s.chat.foregroundCreateId != null || (s.chat.pendingForkOpens ?? 0) > 0) + // A create, fork or resume started here that will open its own chat when it lands. + // A resume past the lease is hung: its entry stays until another resume + // starts, and it must not hold the page empty for another lease. + const openPending = useAppSelector(s => s.chat.foregroundCreateId != null || (s.chat.pendingForkOpens ?? 0) > 0 || resumeStillOpening(s.chat, Date.now())) // The wait is a lease, not a promise: create and fork POSTs carry no // deadline, so a request the connection never settles would otherwise keep // the page empty for good. The lease starts when the page loses its chat - // with a request pending and lapses after PENDING_OPEN_LEASE_MS; the pick + // with a request pending and lapses after PENDING_OPEN_LEASE_MS, the bound + // that also ends a pending resume's repeat guard; the pick // below then runs as if nothing were pending. It never touches the pending // count or foregroundCreateId, so a late settlement still lowers exactly // its own share, and a late success still opens its chat (the pick was an @@ -1225,7 +1248,8 @@ export function useChatPageSessionController({ const handleResumeSession = useCallback(async (key: string, title: string) => { try { - const result = await dispatch(resumeFromHistory({ key, title })).unwrap() + const resuming = dispatch(resumeFromHistory({ key, title })) + const result = await resuming.unwrap() // The cleanup below is the SECOND half of a swap: it retires the tab the // resumed session is replacing. A resume that answered with a surface // this page cannot display never performs the first half — the reducer @@ -1236,12 +1260,21 @@ export function useChatPageSessionController({ // apart: the wire request succeeds either way, which is why the thunk // returns `surface` at all. if (!result.ok || !isChatPageSurface(result.surface)) return + // Nor when the resume did not take the view: the user opened another + // session (or clicked a newer row) while it was pending, so the tab it + // would retire is not being replaced. + if (store.getState().chat.activeSlot !== result.key) return + // Nor when it took the view from another session than the tab captured + // here: a repeated click from a session the user opened since, or a + // create that opened first, is what the resume replaced. + const opened = store.getState().chat.lastResumeActivation + if (opened?.requestId !== resuming.requestId || opened.replaced !== activeSlot) return if (activeSlot && activeSlot !== key) { delete drafts.current[activeSlot]; delete fileDrafts.current[activeSlot]; delete pasteDrafts.current[activeSlot]; prevSlot.current = null; saveDrafts() dispatch(deleteSlot(activeSlot)).unwrap().catch(() => {}) } } catch { /* resume failed — keep current slot */ } - }, [activeSlot, dispatch, drafts, fileDrafts, pasteDrafts, prevSlot, saveDrafts]) + }, [activeSlot, dispatch, drafts, fileDrafts, pasteDrafts, prevSlot, saveDrafts, store]) return { closeSessionTab, diff --git a/website/src/pages/useChatPageSlotSwitches.ts b/website/src/pages/useChatPageSlotSwitches.ts index 13e0d7b51854..eed97dec53bc 100644 --- a/website/src/pages/useChatPageSlotSwitches.ts +++ b/website/src/pages/useChatPageSlotSwitches.ts @@ -35,9 +35,6 @@ export function useForkSession({ const forkDirectionChoice = forkCfg?.tail_fork_enabled === true const handleFork = useCallback(async (visibleIndex: number, messageId?: string, explicitDirection?: 'head') => { if (!activeSlot) return - // Read before the config fetch and the fork request: the user can open - // another session while either runs, and the fork then must not take the view. - const origin = captureForkOrigin(store.getState()) let direction: 'head' | 'tail' = 'head' // hoisted so the catch advises the same way let control: string | undefined // Pending until the child is active or the fork failed (the `finally`), so @@ -47,6 +44,10 @@ export function useForkSession({ let released = false const release = () => { if (!released) { released = true; dispatch(forkOpenSettled()) } } dispatch(forkOpenStarted()) + // Read after the start, which numbers this fork (`requestSeq`), and before + // the config fetch and the fork request: the user can open another + // session while either runs, and the fork then must not take the view. + const origin = captureForkOrigin(store.getState()) try { // Fork WITHOUT a prompt: an unsent composer draft must never be // auto-submitted into the freshly forked session. The @@ -68,7 +69,7 @@ export function useForkSession({ const result = await dispatch(forkSlot({ slot: activeSlot, atIndex: visibleIndex, messageId, direction })).unwrap() if (result.ok) { if (forkMayOpen(store.getState(), origin)) { - const switching = dispatch(switchSlot(result.key)) + const switching = dispatch(switchSlot({ key: result.key, requestSeq: origin.seq })) // The child inherits this session's folder, which can be collapsed when // the session was opened from the command bar, a tab or a link: open // that path so the child's row shows. switchSlot.pending has already diff --git a/website/src/store/chat/lifecycle.ts b/website/src/store/chat/lifecycle.ts index 1c102bb5df06..5d857a0b1847 100644 --- a/website/src/store/chat/lifecycle.ts +++ b/website/src/store/chat/lifecycle.ts @@ -43,7 +43,7 @@ const configuredDefaultMemoryMode = () => export const createSlot = createAsyncThunk< ChatSlot, { agent?: string; agent_kind?: 'member' | 'template'; appAgentOwner?: string; model?: string; mode?: string; memory_mode?: string; folder_id?: string | null; title?: string; color_index?: number | null; color_hex?: string | null; project?: string | null; activate?: boolean; sessionFolder?: boolean; defaultFolder?: boolean; prefill?: string; automatic?: boolean } | string | undefined, - { fulfilledMeta: { originActiveSlot: string | null; originActiveSlotMoves: number; originActiveSlotAutoMoves: number; activate: boolean; prefillStaged?: boolean; automatic?: boolean } } + { fulfilledMeta: Required<OriginMeta> & { activate: boolean; prefillStaged?: boolean; automatic?: boolean } } >( 'chat/createSlot', async (opts, { getState, fulfillWithValue }) => { @@ -183,13 +183,29 @@ export const createSlot = createAsyncThunk< // caller can fall back to another channel. const prefill = typeof opts === 'string' ? undefined : opts?.prefill const prefillStaged = !!prefill && writePrefill(slot.key, prefill) - return fulfillWithValue(slot, { originActiveSlot: origin.activeSlot, originActiveSlotMoves: origin.moves, originActiveSlotAutoMoves: origin.autoMoves, activate, prefillStaged, automatic }) + return fulfillWithValue(slot, { ...originMeta(origin), activate, prefillStaged, automatic }) }, ) -export const resumeFromHistory = createAsyncThunk( +/** How long a create, fork or resume started in this window counts as on its + * way. Every measured create and fork answered within 3.5 s; a request still + * open after this is treated as hung and keeps running. The chat page, having + * lost its chat, waits this long for such a request to open one before it + * auto-picks as usual, and a resume stops blocking a repeat of its row after + * it. */ +export const PENDING_OPEN_LEASE_MS = 10_000 + +export const resumeFromHistory = createAsyncThunk< + { ok: boolean; key: string; surface: string; nextBefore: number; messages: ReturnType<typeof filterMessages>; hasMore: boolean; total: number }, + { key: string; title: string }, + { pendingMeta: { startedAt: number }; fulfilledMeta: Required<OriginMeta> } +>( 'chat/resumeFromHistory', - async ({ key, title }: { key: string; title: string }, { dispatch }) => { + async ({ key, title }, { dispatch, getState, fulfillWithValue }) => { + // Where the user stands when the resume starts, as `createSlot` captures + // it. A resume rebuilds the slot from its transcript and can take seconds; + // the fulfilled reducer asks `forkMayOpen` before it opens the session. + const origin = captureForkOrigin(getState() as RootState) const d = await api.resumeChatSlot(key, title) if (d.ok) { dispatch(addSlotOptimistic({ key: d.key, title: title || d.key, messages: 0, running: false, memory_mode: d.memory_mode, mode: d.mode, surface: d.surface ?? d.mode, pending_approval: false, waiting_for_input: false, last_activity_ts: undefined })) @@ -203,10 +219,42 @@ export const resumeFromHistory = createAsyncThunk( // shows default/orchestrator, see isChatPageSurface) can tell a // silently-unusable resume apart from a genuinely failed one (#3624) -- // the request succeeds either way, so `ok` alone cannot distinguish them. - return { ok: d.ok, key: d.key, surface: d.surface ?? d.mode, nextBefore: cursor ?? 0, messages: filterMessages(d.messages || []), hasMore: cursor !== null && (d.has_more || false), total: d.total || 0 } + return fulfillWithValue( + { ok: d.ok, key: d.key, surface: d.surface ?? d.mode, nextBefore: cursor ?? 0, messages: filterMessages(d.messages || []), hasMore: cursor !== null && (d.has_more || false), total: d.total || 0 }, + originMeta(origin), + ) + }, + { + // A repeat of a resume already on its way (a double click or a double + // Enter on a slow row) is dropped here, for every entry point at once, + // whatever other rows were resumed in between. Only for the lease: the + // POST has no deadline, and a request that never answers must not leave + // its row dead for good. The drop is dispatched as a rejection so the + // reducer can hand the latest-click token back to the resume it repeats. + condition: ({ key }, { getState }) => { + const newest = newestResumeOf((getState() as RootState).chat, key) + return !newest || Date.now() - newest.startedAt >= PENDING_OPEN_LEASE_MS + }, + dispatchConditionRejection: true, + getPendingMeta: () => ({ startedAt: Date.now() }), }, ) +/** Whether a resume started in this window is still within its lease at + * `now`. An entry past the lease is a hung request, not one on its way. */ +export function resumeStillOpening(chat: Pick<ChatState, 'pendingResumes'>, now: number): boolean { + return Object.values(chat.pendingResumes ?? {}).some(p => now - p.startedAt < PENDING_OPEN_LEASE_MS) +} + +/** The newest resume of `key` still on its way, if any. */ +function newestResumeOf(chat: Pick<ChatState, 'pendingResumes'>, key: string): { requestId: string; startedAt: number } | null { + let newest: { requestId: string; startedAt: number } | null = null + for (const [requestId, p] of Object.entries(chat.pendingResumes ?? {})) { + if (p.key === key && (!newest || p.startedAt >= newest.startedAt)) newest = { requestId, startedAt: p.startedAt } + } + return newest +} + /** The action that lists a successful fork in the sidebar. Every fork path * dispatches this before activating the fork: the chat page clears an active * session its slot list lacks. `openCreatedSlot` uses it the same way for a @@ -218,10 +266,50 @@ export function listForkedSlot(d: Pick<ChatSlot, 'key'> & Partial<Pick<ChatSlot, } /** Where the user stood when a fork or create started; see `forkMayOpen`. */ -export interface ForkOrigin { activeSlot: string | null; moves: number; autoMoves: number } +export interface ForkOrigin { activeSlot: string | null; moves: number; autoMoves: number; requestMoves: number; seq: number; burst: number } export function captureForkOrigin(state: Pick<RootState, 'chat'>): ForkOrigin { - return { activeSlot: state.chat.activeSlot, moves: state.chat.activeSlotMoves ?? 0, autoMoves: state.chat.activeSlotAutoMoves ?? 0 } + const c = state.chat + return { activeSlot: c.activeSlot, moves: c.activeSlotMoves ?? 0, autoMoves: c.activeSlotAutoMoves ?? 0, requestMoves: c.activeSlotRequestMoves ?? 0, seq: c.requestSeq ?? 0, burst: c.requestBurst ?? 0 } +} + +/** The origin a create or resume thunk sent in its meta. An action without + * the request fields (a fixture, an older caller) reads as one that started + * now, after every other request. */ +export function originFromMeta(state: ChatState, meta: OriginMeta): ForkOrigin { + return { + activeSlot: meta.originActiveSlot ?? null, + moves: meta.originActiveSlotMoves ?? 0, + autoMoves: meta.originActiveSlotAutoMoves ?? 0, + requestMoves: meta.originActiveSlotRequestMoves ?? state.activeSlotRequestMoves ?? 0, + seq: meta.originRequestSeq ?? state.requestSeq ?? 0, + burst: meta.originRequestBurst ?? state.requestBurst ?? 0, + } +} + +export interface OriginMeta { + originActiveSlot?: string | null + originActiveSlotMoves?: number + originActiveSlotAutoMoves?: number + originActiveSlotRequestMoves?: number + originRequestSeq?: number + originRequestBurst?: number +} + +function originMeta(origin: ForkOrigin): Required<OriginMeta> { + return { + originActiveSlot: origin.activeSlot, + originActiveSlotMoves: origin.moves, + originActiveSlotAutoMoves: origin.autoMoves, + originActiveSlotRequestMoves: origin.requestMoves, + originRequestSeq: origin.seq, + originRequestBurst: origin.burst, + } +} + +/** Records that a request with `origin` opened its session. */ +function noteRequestActivation(state: ChatState, origin: ForkOrigin): void { + state.activatedRequestSeq = Math.max(state.activatedRequestSeq ?? 0, origin.seq) } /** Whether a fork or create that just resolved may open its new session. @@ -232,12 +320,19 @@ export function captureForkOrigin(state: Pick<RootState, 'chat'>): ForkOrigin { * and came back, since coming back is a choice too; an equal `activeSlot` * alone cannot tell that apart from never moving. A move the chat page made * on its own, after it lost the origin from its list, is not a choice, and - * the new session still opens. The new session is listed in the sidebar - * either way; only the switch, and what the caller does on opening it, is - * skipped. */ + * the new session still opens. Nor is a move made by another create, fork or + * resume opening its session: that request was clicked before this one, so + * this one still opens, while a request clicked after this one that has + * already opened its session keeps the view. The new session is listed in + * the sidebar either way; only the switch, and what the caller does on + * opening it, is skipped. */ export function forkMayOpen(state: Pick<RootState, 'chat'>, origin: ForkOrigin): boolean { - if ((state.chat.activeSlotMoves ?? 0) !== origin.moves) return false - return state.chat.activeSlot === origin.activeSlot || (state.chat.activeSlotAutoMoves ?? 0) !== origin.autoMoves + const c = state.chat + if ((c.activeSlotMoves ?? 0) !== origin.moves) return false + if ((c.activatedRequestSeq ?? 0) > origin.seq) return false + return c.activeSlot === origin.activeSlot + || (c.activeSlotAutoMoves ?? 0) !== origin.autoMoves + || (c.activeSlotRequestMoves ?? 0) !== origin.requestMoves } export const forkSlot = createAsyncThunk( @@ -367,6 +462,7 @@ export function addLifecycleCases(builder: ActionReducerMapBuilder<ChatState>): }) .addCase(createSlot.pending, (state, action) => { state.creatingSlot = true + state.requestSeq = (state.requestSeq ?? 0) + 1 const arg = action.meta.arg if (typeof arg === 'string' || arg?.activate !== false) { state.foregroundCreateId = action.meta.requestId @@ -391,24 +487,39 @@ export function addLifecycleCases(builder: ActionReducerMapBuilder<ChatState>): // are. `send()`'s forceNew path and welcome-screen New Chat both leave // the user on the origin with no move, so they still activate normally. // - // Conscious edge: a rapid double New Chat from the same slot makes both - // creates capture the same origin; the first fulfilled activates its - // slot (moving activeSlot), so the second sees activeSlot !== origin and - // stays put. "First create wins" rather than the prior "last wins". Both - // slots exist in the sidebar and both land the user on an empty chat, so - // the outcomes are equivalent, accepted over re-stealing focus. + // Conscious edge: a rapid double New Chat is one request made twice, so + // the first create to open keeps the view, and the text typed while + // both ran stays where it was carried (create-carry in composerDrafts). + // This create's pending action cleared `lastCreatedActivation`, so a + // value naming another create means that one opened since this started. + // Both slots exist in the sidebar. A resume or fork clicked after a + // create still opens over it (`forkMayOpen`). // Caller asked for a background create (see `activate` above): the slot // is registered but focus stays put until the caller switches to it. if (action.meta.activate === false) return - const origin = { activeSlot: action.meta.originActiveSlot ?? null, moves: action.meta.originActiveSlotMoves ?? 0, autoMoves: action.meta.originActiveSlotAutoMoves ?? 0 } + const origin = originFromMeta(state, action.meta) + // Only for creates in one burst (no resume or fork clicked since the + // first, however many creates came between), and only while the first + // is still the newest request to have opened. A resume or fork clicked + // between them, or opened after the first, makes this create the later + // click, and it opens as any later click does. + const opened = state.lastCreatedActivation + if (opened && opened.requestId !== action.meta.requestId && opened.seq === (state.activatedRequestSeq ?? 0) + && opened.burst !== undefined && opened.burst === origin.burst) return if (!forkMayOpen({ chat: state }, origin)) return if (state.activeSlot) { state.slotActivity[state.activeSlot] = { toolLog: state.toolLog, subagents: state.subagents, activityTab: state.activityTab, activityOpen: state.activityOpen } state.slotHistory = pushHistory(state.slotHistory, state.activeSlot) parkActiveTranscript(state) } - enterActiveSlot(state, action.payload.key, action.meta.automatic === true) - state.lastCreatedActivation = { slot: action.payload.key, requestId: action.meta.requestId } + // An automatic create (#23412) is the page's own move, so it counts + // as one and orders no request; any other create is a request opening. + if (action.meta.automatic === true) enterActiveSlot(state, action.payload.key, true) + else { + enterActiveSlot(state, action.payload.key, 'request') + noteRequestActivation(state, origin) + } + state.lastCreatedActivation = { slot: action.payload.key, requestId: action.meta.requestId, seq: origin.seq, burst: origin.burst } // A default-folder create learns its folder only from this response, so // no caller can open a collapsed default folder (or a collapsed // ancestor) before the create, the way a folder "+" create does. The @@ -459,9 +570,24 @@ export function addLifecycleCases(builder: ActionReducerMapBuilder<ChatState>): // A new attempt supersedes whatever the previous one narrated, and its // requestId becomes the only answer allowed to write the notice below. state.lastResumeRequestId = action.meta.requestId + // Entries past the lease are hung requests that may never settle; drop + // them so the map stays bounded. A late answer still lands, it only has + // no entry left to remove. + const startedAt = action.meta.startedAt + const pendingResumes: NonNullable<ChatState['pendingResumes']> = {} + for (const [id, p] of Object.entries(state.pendingResumes ?? {})) { + if (startedAt - p.startedAt < PENDING_OPEN_LEASE_MS) pendingResumes[id] = p + } + state.requestSeq = (state.requestSeq ?? 0) + 1 + state.requestBurst = (state.requestBurst ?? 0) + 1 + pendingResumes[action.meta.requestId] = { key: action.meta.arg.key, startedAt, origin: captureForkOrigin({ chat: state }) } + state.pendingResumes = pendingResumes state.unresumableResume = null }) .addCase(resumeFromHistory.fulfilled, (state, action) => { + const latest = action.meta.requestId === state.lastResumeRequestId + const entry = state.pendingResumes?.[action.meta.requestId] + if (entry) delete state.pendingResumes![action.meta.requestId] // A resume that resolved to a surface ChatPage cannot display must not // mutate this slice at all: consuming the history row while the notice // says "can't be opened" reads as data loss, and switching activeSlot @@ -510,6 +636,18 @@ export function addLifecycleCases(builder: ActionReducerMapBuilder<ChatState>): // nothing here and must not move the offset. state.historyOffset = Math.max(0, state.historyOffset - 1) } + // The session is an open tab now either way; only taking the view is + // conditional. A later resume is the user's newer pick, so an earlier + // one answering after it must not open (latest click wins, the same + // token that orders the notice). And a session the user opened while + // this resume was pending, or a return to the origin, is a choice the + // late answer must not undo: the rule creates and forks follow. + // The entry's origin moves with a repeated click; the thunk's own + // capture covers an answer whose entry was pruned as hung. + const origin = entry?.origin ?? originFromMeta(state, action.meta) + if (!latest || !forkMayOpen({ chat: state }, origin)) return + noteRequestActivation(state, origin) + state.lastResumeActivation = { requestId: action.meta.requestId, replaced: state.activeSlot } state.slotHistory = state.slotHistory.filter(k => k !== action.payload.key) if (state.activeSlot) { state.slotActivity[state.activeSlot] = { toolLog: state.toolLog, subagents: state.subagents, activityTab: state.activityTab, activityOpen: state.activityOpen } @@ -533,7 +671,7 @@ export function addLifecycleCases(builder: ActionReducerMapBuilder<ChatState>): const resumedRun = state.slotRun[safeKey(action.payload.key)] state.lastChunkSeq = resumedRun?.lastChunkSeq state.lastChunkGen = resumedRun?.lastChunkGen - enterActiveSlot(state, action.payload.key) + enterActiveSlot(state, action.payload.key, 'request') state.messages = mergePreservedPastes(state.messages, action.payload.messages) state.slotState = 'idle' state.pendingTurnSlot = null @@ -547,6 +685,26 @@ export function addLifecycleCases(builder: ActionReducerMapBuilder<ChatState>): // silent swallow -- ChatPage's `catch {}`, the palette providers' // `void dispatch`, the notification panel's console log -- so the click // looked exactly as dead as the bug this field exists to fix. + if (action.meta.condition) { + // A repeat dropped by `condition`: nothing was sent and nothing + // failed. The click is still the user's newest pick, so the resume it + // repeats becomes the latest again and opens when it answers, judged + // from where the user stands now, even when another row was resumed + // in between. + const repeated = newestResumeOf(state, action.meta.arg.key) + if (repeated) { + state.lastResumeRequestId = repeated.requestId + // The repeat is a click of its own, after every request started so far. + state.requestSeq = (state.requestSeq ?? 0) + 1 + state.requestBurst = (state.requestBurst ?? 0) + 1 + state.pendingResumes![repeated.requestId].origin = captureForkOrigin({ chat: state }) + // A notice an in-between resume raised names a row the user has + // moved past, as a fresh click would clear it. + state.unresumableResume = null + } + return + } + if (state.pendingResumes) delete state.pendingResumes[action.meta.requestId] if (action.meta.requestId !== state.lastResumeRequestId) return state.unresumableResume = { key: action.meta.arg.key, diff --git a/website/src/store/chat/runState.ts b/website/src/store/chat/runState.ts index 76f4f478e5a2..c90cc64830b8 100644 --- a/website/src/store/chat/runState.ts +++ b/website/src/store/chat/runState.ts @@ -230,7 +230,7 @@ export const settleEndedActiveTurn = ( * `switchSlot.pending` saved in `slotSwitchOrigin`. A delete can leave the * evicted chat's key, which matches nothing while `activeSlot` is null, and * the next entry here replaces it. */ -export function enterActiveSlot(state: ChatState, target: string | null, automatic = false): void { +export function enterActiveSlot(state: ChatState, target: string | null, automatic: boolean | 'request' = false): void { const outgoing = state.activeSlot if (outgoing !== null && outgoing !== target && !isUnsafeKey(outgoing)) { const runs = (state.slotRun ??= {}) @@ -241,7 +241,9 @@ export function enterActiveSlot(state: ChatState, target: string | null, automat || (state.runEpoch?.[safeKey(outgoing)] ?? 0) !== (state.activeRunEpochAtEntry ?? 0) if (observed) setRunState(runs[safeKey(outgoing)] ??= { state: 'idle' }, mirrorState) } - if (outgoing !== target && automatic) state.activeSlotAutoMoves = (state.activeSlotAutoMoves ?? 0) + 1 + // `'request'`: a create, fork or resume opening its session as it answers. + if (outgoing !== target && automatic === 'request') state.activeSlotRequestMoves = (state.activeSlotRequestMoves ?? 0) + 1 + else if (outgoing !== target && automatic) state.activeSlotAutoMoves = (state.activeSlotAutoMoves ?? 0) + 1 else if (outgoing !== target) state.activeSlotMoves = (state.activeSlotMoves ?? 0) + 1 // A chat entered while a phone or an embedded chat holds Keep side panel // open off opens its panel when the hold lifts, because without the hold it @@ -270,7 +272,11 @@ export const runStateReducers = { * caller pairs it with exactly one `forkOpenSettled`, after its own * switch to the child, so the count stays raised from the click until * the child is active. */ - forkOpenStarted(state: ChatState) { state.pendingForkOpens = (state.pendingForkOpens ?? 0) + 1 }, + forkOpenStarted(state: ChatState) { + state.pendingForkOpens = (state.pendingForkOpens ?? 0) + 1 + state.requestSeq = (state.requestSeq ?? 0) + 1 + state.requestBurst = (state.requestBurst ?? 0) + 1 + }, forkOpenSettled(state: ChatState) { state.pendingForkOpens = Math.max(0, (state.pendingForkOpens ?? 0) - 1) }, clearSlotState(state: ChatState) { state.messages = []; state.toolLog = []; state.subagents = {}; state.activityTab = 'changes'; state.slotRunning = false; state.slotStopping = false; state.slotState = 'idle'; setPagingCursor(state, false, 0); state.loadingOlder = false; state.lastChunkSeq = undefined; state.lastChunkGen = undefined; state._wsChunkedDuringFetch = false; state.slotStatusDetail = {}; state.voicePlaying = false; state.voiceAudio = null; if (state.activeSlot) delete state.pendingQuestions?.[state.activeSlot] diff --git a/website/src/store/chat/slotSwitch.ts b/website/src/store/chat/slotSwitch.ts index ba8ac6b090df..6725b4d3bfc9 100644 --- a/website/src/store/chat/slotSwitch.ts +++ b/website/src/store/chat/slotSwitch.ts @@ -59,8 +59,12 @@ import { walkWindowBackTo } from './windowWalk' * recovery. * - `automatic`: the chat page's own auto-select after it lost the active * chat. The move counts in `activeSlotAutoMoves`, so a pending fork still - * opens its child (see `forkMayOpen`). */ -export type SwitchSlotArg = string | { key: string; keepTargetOnMissing?: boolean; announceOnMissing?: boolean; automatic?: boolean } + * opens its child (see `forkMayOpen`). + * - `requestSeq`: a fork opening its child, with the fork's origin `seq`. + * The move counts in `activeSlotRequestMoves`, so a request clicked after + * the fork still opens, and one clicked before it does not take the view + * back (see `forkMayOpen`). */ +export type SwitchSlotArg = string | { key: string; keepTargetOnMissing?: boolean; announceOnMissing?: boolean; automatic?: boolean; requestSeq?: number } /** The slot key of a `switchSlot` argument, in either spelling. Non-object * values pass through untouched: a hand-rolled test dispatch can omit @@ -470,7 +474,10 @@ export function addSlotSwitchCases(builder: ActionReducerMapBuilder<ChatState>): // the target -- so the hand-back inside reads the mirror while it still // describes the outgoing slot. WS events for the new slot are accepted // from here on. - enterActiveSlot(state, target, typeof action.meta.arg === 'object' && action.meta.arg !== null && action.meta.arg.automatic === true) + const switchArg = typeof action.meta.arg === 'object' && action.meta.arg !== null ? action.meta.arg : null + const openedBy = typeof switchArg?.requestSeq === 'number' ? switchArg.requestSeq : null + enterActiveSlot(state, target, switchArg?.automatic === true ? true : openedBy !== null ? 'request' : false) + if (openedBy !== null) state.activatedRequestSeq = Math.max(state.activatedRequestSeq ?? 0, openedBy) if (target !== outgoingSlot) { state.lastChunkSeq = runs[safeKey(target)]?.lastChunkSeq state.lastChunkGen = runs[safeKey(target)]?.lastChunkGen diff --git a/website/src/store/chat/state.ts b/website/src/store/chat/state.ts index cad39c4a7424..43e2cff8a1f4 100644 --- a/website/src/store/chat/state.ts +++ b/website/src/store/chat/state.ts @@ -210,6 +210,26 @@ export interface ChatState { * `automatic` auto-select). Kept apart from `activeSlotMoves`, which then * counts only moves the user asked for. */ activeSlotAutoMoves?: number + /** Moves made by a create, fork or resume opening its session when it + * answered. Also kept apart from `activeSlotMoves`: such a move is a + * request the user made earlier, so it does not undo a later click. */ + activeSlotRequestMoves?: number + /** Counts the creates, forks and resumes started in this window, so each + * request's origin (`captureForkOrigin`) records how many started before + * it. */ + requestSeq?: number + /** Bumped when a resume or fork starts. Creates started with the same + * value are one burst of New clicks with no other request between them, + * and the first of them to open keeps the view. */ + requestBurst?: number + /** The `requestSeq` origin of the newest request that has opened its + * session. A request whose origin is older does not take the view back + * from it (`forkMayOpen`): the click made later wins. */ + activatedRequestSeq?: number + /** The resume that opened its session last, and the session that was + * active when it did, so the swap in `handleResumeSession` retires only + * the tab that resume replaced. */ + lastResumeActivation?: { requestId: string; replaced: string | null } | null /** Forks started in this window that will open their child when they * succeed and `forkMayOpen` allows it. Creates are tracked by * `foregroundCreateId`. While either is pending, the chat page does not @@ -358,6 +378,16 @@ export interface ChatState { * sequence ref, which could only order ITS OWN clicks -- a palette resume * racing a sidebar resume was unordered before. */ lastResumeRequestId: string | null + /** Every resume still on its way, by requestId: the history key it asked + * for and when it started. A second resume of a key with an entry younger + * than PENDING_OPEN_LEASE_MS is dropped (a double click on a slow resume), + * whichever resumes ran in between; an older entry is treated as hung and + * no longer blocks the row. The chat page counts a non-empty map like a + * pending create or fork. Ordering stays with `lastResumeRequestId`. + * `origin` is where the user stood at the last click that asked for this + * resume, re-taken when a repeat is dropped; the fulfilled reducer asks + * `forkMayOpen` against it. */ + pendingResumes?: Record<string, { key: string; startedAt: number; origin: { activeSlot: string | null; moves: number; autoMoves: number; requestMoves: number; seq: number; burst: number } }> /** A history delete the gateway REFUSED (409 with a `code`), sibling of * `unresumableResume` above and rendered at the same site. The row is still * in `history` -- nothing was deleted -- so without this the click looked @@ -393,7 +423,7 @@ export interface ChatState { * cleared when the next foreground create starts. ChatPage carries text * typed during a create only on this activation, and only when the * requestId matches its snapshot (see ChatPage's create-carry note). */ - lastCreatedActivation: { slot: string; requestId: string } | null + lastCreatedActivation: { slot: string; requestId: string; seq?: number; burst?: number } | null slotContextPct: Record<string, number> // Real token counts behind the context ring (from the adapter usage_update), // keyed by slot. Used for the ring tooltip so "44%" shows its absolute @@ -695,6 +725,11 @@ export const initialState: ChatState = { activeSlot: null, activeSlotMoves: 0, activeSlotAutoMoves: 0, + activeSlotRequestMoves: 0, + requestSeq: 0, + requestBurst: 0, + activatedRequestSeq: 0, + lastResumeActivation: null, messages: [], slotRunning: false, slotStopping: false, @@ -721,6 +756,7 @@ export const initialState: ChatState = { historyOffset: 0, unresumableResume: null, lastResumeRequestId: null, + pendingResumes: {}, undeletableHistory: null, pendingInput: null, mainComposerAppend: null, diff --git a/website/src/store/chatSlice.abortOlderOnSwitch.test.ts b/website/src/store/chatSlice.abortOlderOnSwitch.test.ts index ffee46317447..5d27788f68b6 100644 --- a/website/src/store/chatSlice.abortOlderOnSwitch.test.ts +++ b/website/src/store/chatSlice.abortOlderOnSwitch.test.ts @@ -55,7 +55,6 @@ vi.mock('../api/client', () => ({ import chatReducer, { setActiveSlot, - resumeFromHistory, loadOlderMessages, switchSlot, refreshSlot, @@ -63,6 +62,7 @@ import chatReducer, { isSupersededPagingRejection, } from './chatSlice' import { api } from '../api/client' +import { landResume } from '../test/resumeLanded' function makeStore() { return configureStore({ @@ -74,13 +74,7 @@ function makeStore() { /** Arms the cursor the way resume does: last PAGE of TOTAL, has_more true. */ function resumed(store: ReturnType<typeof makeStore>, key = 'A') { store.dispatch(setActiveSlot(key)) - store.dispatch( - resumeFromHistory.fulfilled( - { ok: true, key, nextBefore: TOTAL - PAGE, messages: HISTORY.slice(TOTAL - PAGE), hasMore: true, total: TOTAL }, - 'req-resume', - { key, title: key }, - ), - ) + landResume(store, { ok: true, key, nextBefore: TOTAL - PAGE, messages: HISTORY.slice(TOTAL - PAGE), hasMore: true, total: TOTAL }, 'req-resume', { key, title: key }) } /** Lets queued microtasks (thunk settle + reducer) run. */ @@ -447,13 +441,7 @@ describe('a background refresh must not re-validate a cursor a pending switch in // outliving one. The shape here is the real case the retry exists for: a tab // holding history from before the conversation moved on. store.dispatch(setActiveSlot('A')) - store.dispatch( - resumeFromHistory.fulfilled( - { ok: true, key: 'A', nextBefore: 0, messages: HISTORY.slice(0, PAGE), hasMore: false, total: TOTAL }, - 'req-resume', - { key: 'A', title: 'A' }, - ), - ) + landResume(store, { ok: true, key: 'A', nextBefore: 0, messages: HISTORY.slice(0, PAGE), hasMore: false, total: TOTAL }, 'req-resume', { key: 'A', title: 'A' }) store.dispatch(switchSlot('A')) await flush() diff --git a/website/src/store/chatSlice.olderHistoryCursor.test.ts b/website/src/store/chatSlice.olderHistoryCursor.test.ts index 579d9263a26c..9b4273fba786 100644 --- a/website/src/store/chatSlice.olderHistoryCursor.test.ts +++ b/website/src/store/chatSlice.olderHistoryCursor.test.ts @@ -50,6 +50,7 @@ import chatReducer, { switchSlot, } from './chatSlice' import { api } from '../api/client' +import { landResume } from '../test/resumeLanded' // Pin the NARROW walk page size (100): loadOlderMessages sizes its page by // viewport (narrow 100 / desktop 300), and these fixtures hold only 300 rows @@ -74,13 +75,7 @@ function makeStore() { function resumed(store: ReturnType<typeof makeStore>) { store.dispatch(setActiveSlot('active')) const recent = HISTORY.slice(TOTAL - PAGE) - store.dispatch( - resumeFromHistory.fulfilled( - { ok: true, key: 'active', nextBefore: TOTAL - PAGE, messages: recent, hasMore: true, total: TOTAL }, - 'req-resume', - { key: 'active', title: 'active' }, - ), - ) + landResume(store, { ok: true, key: 'active', nextBefore: TOTAL - PAGE, messages: recent, hasMore: true, total: TOTAL }, 'req-resume', { key: 'active', title: 'active' }) } const detail = () => api.chatSlotDetail as unknown as { mock: { calls: unknown[][] } } @@ -244,13 +239,7 @@ describe('slotOlderError is scoped to the slot that failed', () => { it('clears the flag when resumeFromHistory re-bases history for another slot', () => { const store = afterFailedOlderFetch() - store.dispatch( - resumeFromHistory.fulfilled( - { ok: true, key: 'other', nextBefore: TOTAL - PAGE, messages: HISTORY.slice(TOTAL - PAGE), hasMore: true, total: TOTAL }, - 'req-resume-other', - { key: 'other', title: 'other' }, - ), - ) + landResume(store, { ok: true, key: 'other', nextBefore: TOTAL - PAGE, messages: HISTORY.slice(TOTAL - PAGE), hasMore: true, total: TOTAL }, 'req-resume-other', { key: 'other', title: 'other' }) expect(store.getState().chat.slotHasMore).toBe(true) expect(store.getState().chat.slotOlderError).toBe(false) diff --git a/website/src/store/chatSlice.ownership.test.ts b/website/src/store/chatSlice.ownership.test.ts index 9ad06a0262bc..97d8699e4eb4 100644 --- a/website/src/store/chatSlice.ownership.test.ts +++ b/website/src/store/chatSlice.ownership.test.ts @@ -181,7 +181,7 @@ const REEXPORTS: Array<[string, Record<string, unknown>, string[]]> = [ ['slotRefresh', slotRefresh, ['refreshSlot', 'warmSlotCache']], ['runState', runState, ['wireTurnIdentity']], ['windowWalk', windowWalk, ['WINDOW_WALK_MAX_PAGES']], - ['lifecycle', lifecycle, ['captureForkOrigin', 'clearHistorySessions', 'createSlot', 'deleteHistorySession', 'fetchHistory', 'forkMayOpen', 'forkSlot', 'listForkedSlot', 'resumeFromHistory']], + ['lifecycle', lifecycle, ['PENDING_OPEN_LEASE_MS', 'captureForkOrigin', 'clearHistorySessions', 'createSlot', 'deleteHistorySession', 'fetchHistory', 'forkMayOpen', 'forkSlot', 'listForkedSlot', 'resumeFromHistory', 'resumeStillOpening']], ['openCreatedSlot', openCreatedSlot, ['openCreatedSlot']], ] diff --git a/website/src/store/chatSlice.publicSurface.test.ts b/website/src/store/chatSlice.publicSurface.test.ts index b68e6dada5b0..8fd5f07c3eb6 100644 --- a/website/src/store/chatSlice.publicSurface.test.ts +++ b/website/src/store/chatSlice.publicSurface.test.ts @@ -79,7 +79,7 @@ const FUNCTIONS = [ 'abortActiveOlderFetch', 'batchedTextAboveFloor', 'capturePendingAskId', 'clampToolOutput', 'countMatchedFetchLimit', 'floorForGen', 'hasUnidentifiedDurableRow', 'hydrateQueuedBubbles', 'isActiveSubagent', 'isAnsweredQuestionEnding', 'isAwaitingSpawnApproval', 'isSpawnApprovalGone', 'isSpawnApprovalRetired', 'captureForkOrigin', 'forkMayOpen', 'isSupersededPagingRejection', 'isTerminalWorkflowStatus', 'listForkedSlot', 'mcpAppKey', 'missedChunkMarker', 'normalizeQueueEntries', - 'openCreatedSlot', 'pendingQuestionFor', 'queueEditBroadcastAt', 'queueEntryAttachments', 'queueEntryQuote', 'raiseChunkSeq', + 'openCreatedSlot', 'pendingQuestionFor', 'queueEditBroadcastAt', 'queueEntryAttachments', 'queueEntryQuote', 'raiseChunkSeq', 'resumeStillOpening', 'selectActiveSlotProject', 'selectAutomationForSlot', 'selectComposerBusy', 'selectContinuable', 'selectProjectChipLocked', 'selectSendAccepted', 'selectSendConfirmed', 'selectSidebarApprovalCounts', 'selectSidebarAutomationRunningKeys', 'selectSidebarStartedSubagentCounts', 'selectSidebarSubagentCounts', 'selectSidebarWorkflowActive', 'selectSidebarWorkflowActiveKeys', @@ -96,6 +96,7 @@ const CONSTANTS: Record<string, unknown> = { OLDER_PAGE_LIMIT: 100, OLDER_WALK_PAGE_LIMIT: 100, PANE_HYDRATE_LIMIT: 50, + PENDING_OPEN_LEASE_MS: 10_000, QUIET_END_SERVER: 'kirocrew-core', QUIET_END_TOOL: 'nothing_to_do', REFRESH_LIMIT_CEILING: 500, @@ -108,12 +109,12 @@ const CONSTANTS: Record<string, unknown> = { /** The initial state in its declared key order. `lastChunkSeq` and * `lastChunkGen` are present as `undefined`, which JSON would hide. */ const INITIAL_STATE = { - activeSlot: null, activeSlotMoves: 0, activeSlotAutoMoves: 0, messages: [], slotRunning: false, slotStopping: false, slotState: 'idle', + activeSlot: null, activeSlotMoves: 0, activeSlotAutoMoves: 0, activeSlotRequestMoves: 0, requestSeq: 0, requestBurst: 0, activatedRequestSeq: 0, lastResumeActivation: null, messages: [], slotRunning: false, slotStopping: false, slotState: 'idle', slotStatusDetail: {}, slotHasMore: false, slotOldestIndex: 0, slotCursorKey: null, slotSwitchRequestId: null, slotSwitchTarget: null, slotSwitchLatestRequestId: null, slotSwitchOrigin: null, switchSlotGone: null, loadingOlder: false, slotOlderError: false, lastChunkSeq: undefined, lastChunkGen: undefined, _wsChunkedDuringFetch: false, liveFrameSeq: 0, refreshAppliedSeq: {}, _redeliveredFramesDropped: 0, history: [], historyHasMore: false, - historyOffset: 0, unresumableResume: null, lastResumeRequestId: null, undeletableHistory: null, + historyOffset: 0, unresumableResume: null, lastResumeRequestId: null, pendingResumes: {}, undeletableHistory: null, pendingInput: null, mainComposerAppend: null, agentSwitchNotice: null, creatingSlot: false, foregroundCreateId: null, pendingForkOpens: 0, lastCreatedActivation: null, slotContextPct: {}, slotContextTokens: {}, voicePlaying: false, voicePreparing: false, voiceAudio: null, subagents: {}, subagentQueued: {}, subagentQueuedReason: {}, automations: {}, diff --git a/website/src/store/chatSlice.ts b/website/src/store/chatSlice.ts index d986adeed7cd..435853970f01 100644 --- a/website/src/store/chatSlice.ts +++ b/website/src/store/chatSlice.ts @@ -1216,7 +1216,7 @@ export { clearSwitchSlotGone, switchSlot, switchSlotNoticeCopy, type SwitchSlotA export { refreshSlot, warmSlotCache } from './chat/slotRefresh' export { wireTurnIdentity } from './chat/runState' export { WINDOW_WALK_MAX_PAGES } from './chat/windowWalk' -export { captureForkOrigin, clearHistorySessions, createSlot, deleteHistorySession, fetchHistory, forkMayOpen, forkSlot, listForkedSlot, resumeFromHistory, type ForkOrigin } from './chat/lifecycle' +export { PENDING_OPEN_LEASE_MS, captureForkOrigin, clearHistorySessions, createSlot, deleteHistorySession, fetchHistory, forkMayOpen, forkSlot, listForkedSlot, resumeFromHistory, resumeStillOpening, type ForkOrigin } from './chat/lifecycle' export { openCreatedSlot } from './chat/openCreatedSlot' export default withRefreshRevision(chatSlice.reducer) diff --git a/website/src/test/ChatPage.memoryChip.test.tsx b/website/src/test/ChatPage.memoryChip.test.tsx index dc9699dafe08..b1910ad9b122 100644 --- a/website/src/test/ChatPage.memoryChip.test.tsx +++ b/website/src/test/ChatPage.memoryChip.test.tsx @@ -104,7 +104,10 @@ const settledSwitches: string[] = [] /** Replacement slots whose `createSlot` has fulfilled. */ const createdSlots: string[] = [] const recordSettledSwitch: Middleware = () => next => action => { - if (switchSlot.fulfilled.match(action) || switchSlot.rejected.match(action)) settledSwitches.push(action.meta.arg) + if (switchSlot.fulfilled.match(action) || switchSlot.rejected.match(action)) { + const arg = action.meta.arg + settledSwitches.push(typeof arg === 'string' ? arg : arg.key) + } if (createSlot.fulfilled.match(action) && action.payload?.key) createdSlots.push(action.payload.key) return next(action) } diff --git a/website/src/test/ChatPage.resumeSurfaceGate.test.tsx b/website/src/test/ChatPage.resumeSurfaceGate.test.tsx index cee2a999ffc2..11fe28b2b62d 100644 --- a/website/src/test/ChatPage.resumeSurfaceGate.test.tsx +++ b/website/src/test/ChatPage.resumeSurfaceGate.test.tsx @@ -34,7 +34,7 @@ vi.mock('../api/client', () => ({ }, })) -import chatReducer, { resumeFromHistory, deleteSlot } from '../store/chatSlice' +import chatReducer, { captureForkOrigin, createSlot, resumeFromHistory, deleteSlot, setActiveSlot } from '../store/chatSlice' import dashboardReducer from '../store/dashboardSlice' import { isChatPageSurface } from '../utils/channelOrigin' import { api } from '../api/client' @@ -61,8 +61,12 @@ function makeHandleResumeSession( ) { return async (key: string, title: string) => { try { - const result = await store.dispatch(resumeFromHistory({ key, title }) as never).unwrap() + const resuming = store.dispatch(resumeFromHistory({ key, title }) as never) as unknown as { requestId: string; unwrap: () => Promise<{ ok: boolean; key: string; surface: string }> } + const result = await resuming.unwrap() if (!result.ok || !isChatPageSurface(result.surface)) return + if (store.getState().chat.activeSlot !== result.key) return + const opened = store.getState().chat.lastResumeActivation + if (opened?.requestId !== resuming.requestId || opened.replaced !== activeSlot) return if (activeSlot && activeSlot !== key) { delete drafts[activeSlot] await store.dispatch(deleteSlot(activeSlot) as never).unwrap().catch(() => {}) @@ -71,6 +75,12 @@ function makeHandleResumeSession( } } +/** The origin meta `createSlot` sends for a create started on the store now. */ +function captureForkOriginMeta(store: ReturnType<typeof makeStore>) { + const o = captureForkOrigin(store.getState() as never) + return { originActiveSlot: o.activeSlot, originActiveSlotMoves: o.moves, originActiveSlotAutoMoves: o.autoMoves, originActiveSlotRequestMoves: o.requestMoves, originRequestSeq: o.seq } +} + beforeEach(() => { resumeChatSlotMock.mockReset() deleteChatSlotMock.mockClear() @@ -95,6 +105,7 @@ describe('ChatPage handleResumeSession surface gate (#5925)', () => { it('still completes the swap when the resume lands on a surface the chat page shows', async () => { resumeChatSlotMock.mockResolvedValue({ ok: true, key: 'chat-9', mode: '', messages: [] }) const store = makeStore() + store.dispatch(setActiveSlot('chat-1')) const drafts: Record<string, string> = { 'chat-1': 'half-typed question' } await makeHandleResumeSession(store, 'chat-1', drafts)('chat-9', 'Older chat') @@ -104,6 +115,76 @@ describe('ChatPage handleResumeSession surface gate (#5925)', () => { expect(store.getState().chat.activeSlot).toBe('chat-9') }) + // The resume answered after the user opened another session, so it did not + // take the view (`forkMayOpen`). The tab it would have replaced stays. + it('does not delete the origin tab when the user moved while the resume ran', async () => { + let land!: (v: unknown) => void + resumeChatSlotMock.mockReturnValue(new Promise(r => { land = r })) + const store = makeStore() + store.dispatch(setActiveSlot('chat-1')) + const drafts: Record<string, string> = { 'chat-1': 'half-typed question' } + + const done = makeHandleResumeSession(store, 'chat-1', drafts)('chat-9', 'Older chat') + await vi.waitFor(() => expect(resumeChatSlotMock).toHaveBeenCalled()) + store.dispatch(setActiveSlot('chat-2')) + land({ ok: true, key: 'chat-9', mode: '', messages: [] }) + await done + + expect(deleteChatSlotMock).not.toHaveBeenCalled() + expect(drafts['chat-1']).toBe('half-typed question') + expect(store.getState().chat.activeSlot).toBe('chat-2') + }) + + // The user left chat-1 for chat-2 and clicked the same row again within the + // lease. The repeat sends nothing and moves the pending resume's origin to + // chat-2, so the answer opens chat-9 from there. That swap replaced chat-2, + // not the tab the first click captured, so chat-1 and its draft stay. + it('does not delete the first tab when a repeated click opened the resume from another session', async () => { + let land!: (v: unknown) => void + resumeChatSlotMock.mockReturnValue(new Promise(r => { land = r })) + const store = makeStore() + store.dispatch(setActiveSlot('chat-1')) + const drafts: Record<string, string> = { 'chat-1': 'half-typed question' } + + const first = makeHandleResumeSession(store, 'chat-1', drafts)('chat-9', 'Older chat') + await vi.waitFor(() => expect(resumeChatSlotMock).toHaveBeenCalled()) + store.dispatch(setActiveSlot('chat-2')) + await store.dispatch(resumeFromHistory({ key: 'chat-9', title: 'Older chat' }) as never) + expect(resumeChatSlotMock).toHaveBeenCalledTimes(1) + land({ ok: true, key: 'chat-9', mode: '', messages: [] }) + await first + + expect(store.getState().chat.activeSlot).toBe('chat-9') + expect(deleteChatSlotMock).not.toHaveBeenCalled() + expect(drafts['chat-1']).toBe('half-typed question') + }) + + // New was clicked first and opened before the resume answered, so the + // resume replaced the new chat, not chat-1. chat-1 keeps its draft. + it('does not delete the first tab when a create opened before the resume answered', async () => { + let land!: (v: unknown) => void + resumeChatSlotMock.mockReturnValue(new Promise(r => { land = r })) + const store = makeStore() + store.dispatch(setActiveSlot('chat-1')) + const drafts: Record<string, string> = { 'chat-1': 'half-typed question' } + + // New first: its origin is taken as it starts, before the resume click. + store.dispatch(createSlot.pending('create-1', undefined)) + const createOrigin = captureForkOriginMeta(store) + const done = makeHandleResumeSession(store, 'chat-1', drafts)('chat-9', 'Older chat') + await vi.waitFor(() => expect(resumeChatSlotMock).toHaveBeenCalled()) + store.dispatch(createSlot.fulfilled({ key: 'chat-new', title: 'New', messages: 0, running: false } as never, 'create-1', undefined, { + ...createOrigin, activate: true, + })) + expect(store.getState().chat.activeSlot).toBe('chat-new') + land({ ok: true, key: 'chat-9', mode: '', messages: [] }) + await done + + expect(store.getState().chat.activeSlot).toBe('chat-9') + expect(deleteChatSlotMock).not.toHaveBeenCalled() + expect(drafts['chat-1']).toBe('half-typed question') + }) + it('leaves the current slot alone when the resume failed outright', async () => { resumeChatSlotMock.mockResolvedValue({ ok: false, key: 'gone', messages: [] }) const store = makeStore() diff --git a/website/src/test/ChatPage.sid.test.tsx b/website/src/test/ChatPage.sid.test.tsx index 4b8ef2bdf5f4..b16372cdb849 100644 --- a/website/src/test/ChatPage.sid.test.tsx +++ b/website/src/test/ChatPage.sid.test.tsx @@ -659,6 +659,54 @@ describe('ChatPage ?sid= URL parameter', () => { await waitFor(() => expect(currentUrl).toContain('sid=chat-2-200')) }) + // The resume answers ok on a chat surface, but the reducer leaves the view + // where the user moved while it ran. Nothing is on `?sid=` then, so URL + // sync must not stay held for it, and "Opened" must not name it. + it('keeps URL sync alive when the user opened another session while the resume ran', async () => { + vi.mocked(api.sessionsNamed).mockResolvedValueOnce({ + sessions: [{ key: 'dashboard_chat-7-50', title: 'Old' }, { key: 'dashboard_chat-7-300', title: 'Newer open' }], + }) + let answer: (v: unknown) => void = () => {} + vi.mocked(api.resumeChatSlot).mockReturnValueOnce(new Promise(r => { answer = r }) as never) + const { store } = renderChatPage({ route: '/chat?sid=chat-7', slots: [...slots, slot('chat-7-300', 'Newer open')] }) + await waitFor(() => expect(api.resumeChatSlot).toHaveBeenCalledWith('dashboard_chat-7-50', 'Old')) + await waitFor(() => expect(currentUrl).toContain('sid=chat-7-50')) + await waitFor(() => expect(notice()).toBeTruthy()) + + await act(async () => { store.dispatch(switchSlot('chat-2-200')) }) + await act(async () => { answer({ ok: true, key: 'chat-7-50', mode: '', messages: [] }) }) + + expect(store.getState().chat.activeSlot).toBe('chat-2-200') + await waitFor(() => expect(currentUrl).toContain('sid=chat-2-200')) + await waitFor(() => expect(notice()).toBeNull()) + await act(async () => { store.dispatch(switchSlot('chat-1-100')) }) + await waitFor(() => expect(currentUrl).toContain('sid=chat-1-100')) + // The entry was amended in place, so Back reaches the session the user + // was on, not the one that never showed. + await act(async () => { navBack() }) + await waitFor(() => expect(currentUrl).toContain('sid=chat-2-200')) + await waitFor(() => expect(store.getState().chat.activeSlot).toBe('chat-2-200')) + }) + + // The user moved off the link's session and then off ChatPage while the + // resume ran. Its answer must not route them back to chat. + it('leaves the page the user went to when the resume answers after ChatPage unmounts', async () => { + vi.mocked(api.sessionsNamed).mockResolvedValueOnce({ sessions: [{ key: 'dashboard_chat-7-50', title: 'Old' }] }) + let answer: (v: unknown) => void = () => {} + vi.mocked(api.resumeChatSlot).mockReturnValueOnce(new Promise(r => { answer = r }) as never) + const { store } = renderChatPage({ route: '/chat?sid=chat-7', slots }) + await waitFor(() => expect(api.resumeChatSlot).toHaveBeenCalledWith('dashboard_chat-7-50', 'Old')) + await waitFor(() => expect(currentUrl).toContain('sid=chat-7-50')) + + await act(async () => { store.dispatch(switchSlot('chat-2-200')) }) + await act(async () => { navTo('/developer') }) + await waitFor(() => expect(currentUrl).toBe('/developer')) + await act(async () => { answer({ ok: true, key: 'chat-7-50', mode: '', messages: [] }) }) + + expect(currentUrl).toBe('/developer') + expect(screen.getByText('developer')).toBeTruthy() + }) + it('opens the oldest of several matches and lists the others', async () => { const many = [...slots, slot('chat-7-300', 'Newer open'), slot('chat-7-100', 'Older open')] vi.mocked(api.sessionsNamed).mockResolvedValueOnce({ diff --git a/website/src/test/ChatPage.waitsForPendingOpen.test.tsx b/website/src/test/ChatPage.waitsForPendingOpen.test.tsx index 4cf10a8a71df..138d9d60637e 100644 --- a/website/src/test/ChatPage.waitsForPendingOpen.test.tsx +++ b/website/src/test/ChatPage.waitsForPendingOpen.test.tsx @@ -14,7 +14,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { Provider } from 'react-redux' import { MemoryRouter, Routes, Route } from 'react-router-dom' import { createTestStore } from './helpers' -import { createSlot, forkOpenSettled, forkOpenStarted } from '../store/chatSlice' +import { createSlot, forkOpenSettled, forkOpenStarted, resumeFromHistory } from '../store/chatSlice' import { sseSlots } from '../store/dashboardSlice' import { ThemeProvider } from '../hooks/useTheme' import type { RootState } from '../store' @@ -273,6 +273,36 @@ describe('the active chat leaves the list while a new chat is on its way', () => expect(store.getState().chat.activeSlot).toBe('chat-2-200') }) + // Only the pending action lands: the POST never answers, so the entry stays. + const hangResume = (store: ReturnType<typeof renderChatPage>) => act(async () => { + store.dispatch(resumeFromHistory.pending('resume-hung', { key: 'chat-hung', title: 'Hung' }, { startedAt: Date.now() })) + }) + + it('a resume within its lease holds the pick', async () => { + const store = renderChatPage() + await waitFor(() => expect(store.getState().chat.activeSlot).toBe(ORIGIN)) + pinClock() + await hangResume(store) + await advance(PENDING_OPEN_LEASE_MS - 1) + await act(async () => { store.dispatch(sseSlots(withoutOrigin)) }) + await act(async () => {}) + expect(store.getState().chat.activeSlot).toBeNull() + }) + + it('a resume past its lease does not hold a later pick', async () => { + const store = renderChatPage() + await waitFor(() => expect(store.getState().chat.activeSlot).toBe(ORIGIN)) + pinClock() + await hangResume(store) + await advance(PENDING_OPEN_LEASE_MS) + // The hung entry is still there: nothing pruned it. + expect(Object.keys(store.getState().chat.pendingResumes ?? {})).toEqual(['resume-hung']) + + await act(async () => { store.dispatch(sseSlots(withoutOrigin)) }) + await act(async () => {}) + expect(store.getState().chat.activeSlot).toBe(OLDEST) + }) + it('with nothing pending, the first listed chat opens at once (unchanged)', async () => { const store = renderChatPage() await waitFor(() => expect(store.getState().chat.activeSlot).toBe(ORIGIN)) diff --git a/website/src/test/ChatSidebar.boardFolderCreateInTab.test.tsx b/website/src/test/ChatSidebar.boardFolderCreateInTab.test.tsx index 45bd880bb1e9..992625dba278 100644 --- a/website/src/test/ChatSidebar.boardFolderCreateInTab.test.tsx +++ b/website/src/test/ChatSidebar.boardFolderCreateInTab.test.tsx @@ -184,7 +184,7 @@ describe('ChatSidebar - board-view folder create open-as-tab gestures', () => { const { container, store } = renderSidebar(onOpen) fireEvent.click(colPlus(container), { ctrlKey: true, shiftKey: true }) await created() - await waitFor(() => expect(onOpen).toHaveBeenCalledWith(NEW_KEY, { background: false })) + await waitFor(() => expect(onOpen).toHaveBeenCalledWith(NEW_KEY, { background: false, requestSeq: expect.any(Number) })) // The create itself did not activate; the tab opener switches after the tab exists. expect(store.getState().chat.activeSlot).toBe(ORIGIN) await waitFor(() => expect(mocks.dropSlotToColumn).toHaveBeenCalledWith(NEW_KEY, COL_A)) @@ -195,7 +195,7 @@ describe('ChatSidebar - board-view folder create open-as-tab gestures', () => { const { container, store } = renderSidebar(onOpen) fireEvent.click(colEmptyRow(container), { ctrlKey: true, shiftKey: true }) await created() - await waitFor(() => expect(onOpen).toHaveBeenCalledWith(NEW_KEY, { background: false })) + await waitFor(() => expect(onOpen).toHaveBeenCalledWith(NEW_KEY, { background: false, requestSeq: expect.any(Number) })) expect(store.getState().chat.activeSlot).toBe(ORIGIN) }) diff --git a/website/src/test/ChatSidebar.folderCreateInTab.test.tsx b/website/src/test/ChatSidebar.folderCreateInTab.test.tsx index 9a6a90c71d64..7c86fe803f6e 100644 --- a/website/src/test/ChatSidebar.folderCreateInTab.test.tsx +++ b/website/src/test/ChatSidebar.folderCreateInTab.test.tsx @@ -187,7 +187,7 @@ describe('ChatSidebar - list-view folder create open-as-tab gestures', () => { const store = renderSidebar(onOpen) fireEvent.click(plusButton(), { ctrlKey: true, shiftKey: true }) await created() - await waitFor(() => expect(onOpen).toHaveBeenCalledWith(NEW_KEY, { background: false })) + await waitFor(() => expect(onOpen).toHaveBeenCalledWith(NEW_KEY, { background: false, requestSeq: expect.any(Number) })) // The create did not activate: the switch is the tab opener's job, after // the tab exists, so the tab the user was on is kept rather than replaced. expect(store.getState().chat.activeSlot).toBe(ORIGIN) @@ -206,7 +206,7 @@ describe('ChatSidebar - list-view folder create open-as-tab gestures', () => { store.dispatch({ type: 'chat/setActiveSlot', payload: 'elsewhere' }) resolveCreate({ key: NEW_KEY, folder_id: FOLDER_ID }) await waitFor(() => expect(onOpen).toHaveBeenCalledWith(NEW_KEY, { background: true })) - expect(onOpen).not.toHaveBeenCalledWith(NEW_KEY, { background: false }) + expect(onOpen).not.toHaveBeenCalledWith(NEW_KEY, { background: false, requestSeq: expect.any(Number) }) }) it('on mac, Cmd+Shift-click on the folder "+" opens a foreground tab', async () => { @@ -215,7 +215,7 @@ describe('ChatSidebar - list-view folder create open-as-tab gestures', () => { const store = renderSidebar(onOpen) fireEvent.click(plusButton(), { metaKey: true, shiftKey: true }) await created() - await waitFor(() => expect(onOpen).toHaveBeenCalledWith(NEW_KEY, { background: false })) + await waitFor(() => expect(onOpen).toHaveBeenCalledWith(NEW_KEY, { background: false, requestSeq: expect.any(Number) })) expect(store.getState().chat.activeSlot).toBe(ORIGIN) }) @@ -224,7 +224,7 @@ describe('ChatSidebar - list-view folder create open-as-tab gestures', () => { const store = renderSidebar(onOpen) fireEvent.click(emptyRow(), { ctrlKey: true, shiftKey: true }) await created() - await waitFor(() => expect(onOpen).toHaveBeenCalledWith(NEW_KEY, { background: false })) + await waitFor(() => expect(onOpen).toHaveBeenCalledWith(NEW_KEY, { background: false, requestSeq: expect.any(Number) })) expect(store.getState().chat.activeSlot).toBe(ORIGIN) }) diff --git a/website/src/test/ChatSidebar.newChatInTab.test.tsx b/website/src/test/ChatSidebar.newChatInTab.test.tsx index 6cae9c752105..d90367b59050 100644 --- a/website/src/test/ChatSidebar.newChatInTab.test.tsx +++ b/website/src/test/ChatSidebar.newChatInTab.test.tsx @@ -151,7 +151,7 @@ describe('ChatSidebar – New button open-as-tab gestures', () => { const store = renderSidebar(onOpen) fireEvent.click(newButton(), { ctrlKey: true, shiftKey: true }) await created() - await waitFor(() => expect(onOpen).toHaveBeenCalledWith(NEW_KEY, { background: false })) + await waitFor(() => expect(onOpen).toHaveBeenCalledWith(NEW_KEY, { background: false, requestSeq: expect.any(Number) })) // The create did not activate: the switch is the tab opener's job, after // the tab exists, so the tab the user was on is kept rather than replaced. expect(store.getState().chat.activeSlot).toBe(ORIGIN) @@ -170,7 +170,7 @@ describe('ChatSidebar – New button open-as-tab gestures', () => { store.dispatch({ type: 'chat/setActiveSlot', payload: 'elsewhere' }) resolveCreate({ key: NEW_KEY }) await waitFor(() => expect(onOpen).toHaveBeenCalledWith(NEW_KEY, { background: true })) - expect(onOpen).not.toHaveBeenCalledWith(NEW_KEY, { background: false }) + expect(onOpen).not.toHaveBeenCalledWith(NEW_KEY, { background: false, requestSeq: expect.any(Number) }) }) it('Ctrl+Shift-click whose create resolves after the user went away and came back opens a BACKGROUND tab', async () => { @@ -186,7 +186,7 @@ describe('ChatSidebar – New button open-as-tab gestures', () => { store.dispatch({ type: 'chat/setActiveSlot', payload: ORIGIN }) resolveCreate({ key: NEW_KEY }) await waitFor(() => expect(onOpen).toHaveBeenCalledWith(NEW_KEY, { background: true })) - expect(onOpen).not.toHaveBeenCalledWith(NEW_KEY, { background: false }) + expect(onOpen).not.toHaveBeenCalledWith(NEW_KEY, { background: false, requestSeq: expect.any(Number) }) expect(store.getState().chat.activeSlot).toBe(ORIGIN) }) @@ -196,7 +196,7 @@ describe('ChatSidebar – New button open-as-tab gestures', () => { const store = renderSidebar(onOpen) fireEvent.click(newButton(), { metaKey: true, shiftKey: true }) await created() - await waitFor(() => expect(onOpen).toHaveBeenCalledWith(NEW_KEY, { background: false })) + await waitFor(() => expect(onOpen).toHaveBeenCalledWith(NEW_KEY, { background: false, requestSeq: expect.any(Number) })) expect(store.getState().chat.activeSlot).toBe(ORIGIN) }) diff --git a/website/src/test/ChatSidebar.newChatLeavesSplit.test.tsx b/website/src/test/ChatSidebar.newChatLeavesSplit.test.tsx index b213cefc975f..e2a692cc446c 100644 --- a/website/src/test/ChatSidebar.newChatLeavesSplit.test.tsx +++ b/website/src/test/ChatSidebar.newChatLeavesSplit.test.tsx @@ -211,7 +211,7 @@ describe('ChatSidebar – a plain create leaves Split View (#21935)', () => { store = renderSidebar({ onSelectSlot, onOpenSlotInNewTab: onOpen, folders: [FOLDER] }) fireEvent.click(await screen.findByTestId('folder-new-chat-f1'), { ctrlKey: true, shiftKey: true }) await created() - await waitFor(() => expect(onOpen).toHaveBeenCalledWith(NEW_KEY, { background: false })) + await waitFor(() => expect(onOpen).toHaveBeenCalledWith(NEW_KEY, { background: false, requestSeq: expect.any(Number) })) await waitFor(() => expect(onSelectSlot).toHaveBeenCalledWith(NEW_KEY)) expect(store.getState().chat.activeSlot).toBe(NEW_KEY) }) diff --git a/website/src/test/ChatSidebar.offline.test.tsx b/website/src/test/ChatSidebar.offline.test.tsx index 8129e4427ccd..49218f9750ed 100644 --- a/website/src/test/ChatSidebar.offline.test.tsx +++ b/website/src/test/ChatSidebar.offline.test.tsx @@ -31,7 +31,9 @@ const { switchSlotMock, resumeFromHistoryMock } = vi.hoisted(() => ({ // needs its own `unwrap` to match that shape now that chat-sidebar/HistoryPane.tsx's resume // handler chains off it (#3624). Never-resolving is fine — these tests only // assert the dispatch call happened, not what resume does after it resolves. - resumeFromHistoryMock: vi.fn(() => ({ type: 'chat/resumeFromHistory/pending', meta: {}, unwrap: () => new Promise(() => {}) })), + // The pending reducer reads `meta.arg.key` and `meta.startedAt`, as on a + // real pending action. + resumeFromHistoryMock: vi.fn((arg?: unknown) => ({ type: 'chat/resumeFromHistory/pending', meta: { arg, requestId: 'r-offline', startedAt: 0 }, unwrap: () => new Promise(() => {}) })), })) vi.mock('../store/chatSlice', async (importOriginal) => { diff --git a/website/src/test/ChatSliceCoverageSecondPass.test.tsx b/website/src/test/ChatSliceCoverageSecondPass.test.tsx index c9b9933b72f0..999d5df7e859 100644 --- a/website/src/test/ChatSliceCoverageSecondPass.test.tsx +++ b/website/src/test/ChatSliceCoverageSecondPass.test.tsx @@ -71,6 +71,7 @@ import { SPAWN_LAUNCH_MARKER } from '../pages/chat/types' import { ASK_ANSWERED_HEADER, ASK_QUESTION_SERVER, MAX_TOOL_RESULT_CHARS } from '../utils/askQuestionTool' import type { ChatMessage, ChatSlot } from '../types' import type { RootState } from '../store' +import { reduceResume } from './resumeLanded' import { __resetErrorJournalForTests, recordError } from '../utils/errorReport' const apiMock = vi.hoisted(() => ({ @@ -1749,14 +1750,14 @@ describe('chatSlice thunks', () => { let s = chatReducer(initial, setActiveSlot('A')) // Arm the cursor the way a resume does: one resident message out of ten, so // nine remain above it. Each page then carries the next cursor itself. - s = chatReducer(s, lifecycle('chat/resumeFromHistory/fulfilled', 'A', { + s = reduceResume(chatReducer, s, { ok: true, key: 'A', nextBefore: 9, messages: [msg({ role: 'user', content: 'newest', ts: '9' })], hasMore: true, total: 10, - })) + }, 'req-1', { key: 'A', title: 'A' }) expect(s.slotOldestIndex).toBe(9) s = chatReducer(s, lifecycle('chat/loadOlder/pending', 'A', undefined)) expect(s.loadingOlder).toBe(true) diff --git a/website/src/test/chatSlice.sidePanelAlwaysOpen.test.ts b/website/src/test/chatSlice.sidePanelAlwaysOpen.test.ts index 3e064fe37da4..14e1c5a3c040 100644 --- a/website/src/test/chatSlice.sidePanelAlwaysOpen.test.ts +++ b/website/src/test/chatSlice.sidePanelAlwaysOpen.test.ts @@ -9,8 +9,9 @@ */ import { describe, it, expect, beforeEach } from 'vitest' import type { UnknownAction } from '@reduxjs/toolkit' -import reducer, { captureForkOrigin, setActiveSlot, setSidePanelAlwaysOpen, toggleActivity, openActivityToTab, resumeFromHistory, switchSlot } from '../store/chatSlice' +import reducer, { captureForkOrigin, setActiveSlot, setSidePanelAlwaysOpen, toggleActivity, openActivityToTab, switchSlot } from '../store/chatSlice' import './mockApiClient' +import { reduceResume } from './resumeLanded' const initial = () => reducer(undefined, { type: '@@INIT' }) /** The user's setting turning on or off, on a chat page that allows it (the @@ -38,10 +39,9 @@ const created = (key: string, from: ReturnType<typeof initial>) => { payload: { key }, } } -const resumed = (key: string) => resumeFromHistory.fulfilled( - { ok: true, key, nextBefore: 0, messages: [], hasMore: false, total: 0 }, - `resume-${key}`, - { key, title: key }, +/** A resume of `key` that started on state `from` and took the view. */ +const resumed = (from: ReturnType<typeof initial>, key: string) => reduceResume( + reducer, from, { ok: true, key, nextBefore: 0, messages: [], hasMore: false, total: 0 }, `resume-${key}`, { key, title: key }, ) beforeEach(() => { localStorage.clear() }) @@ -62,7 +62,7 @@ describe('Keep side panel open', () => { expect(s.activeSlot).toBe('NEW') expect(s.activityOpen).toBe(true) s = reducer(s, toggleActivity()) - s = reducer(s, resumed('OLD')) + s = resumed(s, 'OLD') expect(s.activityOpen).toBe(true) }) diff --git a/website/src/test/chatSlice.slots.test.ts b/website/src/test/chatSlice.slots.test.ts index 60a8f3815c1a..7863bef9749f 100644 --- a/website/src/test/chatSlice.slots.test.ts +++ b/website/src/test/chatSlice.slots.test.ts @@ -6,6 +6,7 @@ */ import { describe, it, expect } from 'vitest' import type { ChatMessage, SubagentActivity, ToolActivity } from '../types' +import { reduceResume } from './resumeLanded' import reducer, { setActiveSlot, appendMessage, @@ -195,22 +196,14 @@ describe('slotHistory — session navigation stack', () => { it('resumeFromHistory.fulfilled with a chat-page surface still consumes the row and switches', () => { let state = { ...initial, activeSlot: 'A', history: [{ key: 'H', title: 'old', messages: 1 }] } - state = reducer(state, { - type: 'chat/resumeFromHistory/fulfilled', - meta: { arg: { key: 'H', title: 'old' }, requestId: 'r1', requestStatus: 'fulfilled' as const }, - payload: { ok: true, key: 'H', surface: 'orchestrator', messages: [], hasMore: false, total: 0 }, - }) + state = reduceResume(reducer, state, { ok: true, key: 'H', surface: 'orchestrator', messages: [], hasMore: false, total: 0 }, 'r1', { key: 'H', title: 'old' }) expect(state.history).toEqual([]) expect(state.activeSlot).toBe('H') }) it('resumeFromHistory.fulfilled pushes activeSlot onto history', () => { let state = { ...initial, activeSlot: 'A' } - state = reducer(state, { - type: 'chat/resumeFromHistory/fulfilled', - meta: { arg: { key: 'H', title: 'old' }, requestId: 'r1', requestStatus: 'fulfilled' as const }, - payload: { ok: true, key: 'H', messages: [], hasMore: false, total: 0 }, - }) + state = reduceResume(reducer, state, { ok: true, key: 'H', messages: [], hasMore: false, total: 0 }, 'r1', { key: 'H', title: 'old' }) expect(state.activeSlot).toBe('H') expect(state.slotHistory).toEqual(['A']) }) @@ -257,11 +250,7 @@ describe('slotHistory — session navigation stack', () => { it('resumeFromHistory removes resumed key from history (invariant: activeSlot ∉ slotHistory)', () => { let state = { ...initial, activeSlot: 'A', slotHistory: ['H', 'B'] } - state = reducer(state, { - type: 'chat/resumeFromHistory/fulfilled', - meta: { arg: { key: 'H', title: 'old' }, requestId: 'r1', requestStatus: 'fulfilled' as const }, - payload: { ok: true, key: 'H', messages: [], hasMore: false, total: 0 }, - }) + state = reduceResume(reducer, state, { ok: true, key: 'H', messages: [], hasMore: false, total: 0 }, 'r1', { key: 'H', title: 'old' }) expect(state.activeSlot).toBe('H') expect(state.slotHistory).not.toContain('H') expect(state.slotHistory).toContain('A') @@ -517,7 +506,7 @@ describe('create activation tracking — which create activated which slot', () expect(state.foregroundCreateId).toBe('r1') state = reducer(state, fulfilled('r1', 'A', 'new-slot')) expect(state.activeSlot).toBe('new-slot') - expect(state.lastCreatedActivation).toEqual({ slot: 'new-slot', requestId: 'r1' }) + expect(state.lastCreatedActivation).toEqual({ slot: 'new-slot', requestId: 'r1', seq: expect.any(Number), burst: expect.any(Number) }) expect(state.foregroundCreateId).toBeNull() }) @@ -541,7 +530,7 @@ describe('create activation tracking — which create activated which slot', () state = reducer(state, fulfilled('bg', 'A', 'bg-slot', false)) expect(state.foregroundCreateId).toBe('fg') state = reducer(state, fulfilled('fg', 'A', 'fg-slot')) - expect(state.lastCreatedActivation).toEqual({ slot: 'fg-slot', requestId: 'fg' }) + expect(state.lastCreatedActivation).toEqual({ slot: 'fg-slot', requestId: 'fg', seq: expect.any(Number), burst: expect.any(Number) }) }) it('a second foreground create takes over the pending id, and the first one activating carries its own id', () => { @@ -549,7 +538,7 @@ describe('create activation tracking — which create activated which slot', () state = reducer(state, pending('r2')) expect(state.foregroundCreateId).toBe('r2') state = reducer(state, fulfilled('r1', 'A', 'slot-1')) - expect(state.lastCreatedActivation).toEqual({ slot: 'slot-1', requestId: 'r1' }) + expect(state.lastCreatedActivation).toEqual({ slot: 'slot-1', requestId: 'r1', seq: expect.any(Number), burst: expect.any(Number) }) expect(state.foregroundCreateId).toBe('r2') }) diff --git a/website/src/test/composerFocus.test.ts b/website/src/test/composerFocus.test.ts index 407908cf9d26..655b4413489f 100644 --- a/website/src/test/composerFocus.test.ts +++ b/website/src/test/composerFocus.test.ts @@ -416,10 +416,14 @@ describe('focusComposerForOpenedSession — a quick-search surface opened a sess describe('focusComposerForResumedSession — only once the resume entered the session', () => { const RESUMED = 'zzq-resumed' const entered = { ok: true, surface: '', key: RESUMED } + // The store as the fulfilled reducer leaves it when the resume took the view. + let viewing: string | null = RESUMED + const store = { getState: () => ({ chat: { activeSlot: viewing } }) } + beforeEach(() => { viewing = RESUMED }) it('does NOT focus while the resume is in flight, then focuses once it has entered', async () => { let resolve!: (r: { ok: boolean; surface?: string; key: string }) => void - focusComposerForResumedSession(new Promise(r => { resolve = r })) + focusComposerForResumedSession(new Promise(r => { resolve = r }), store) await flushFrame() expect(document.activeElement).not.toBe(composer) resolve(entered) @@ -428,13 +432,23 @@ describe('focusComposerForResumedSession — only once the resume entered the se }) it('focuses nothing for an `ok: false` answer — the reducer left the active slot where it was', async () => { - focusComposerForResumedSession(Promise.resolve({ ok: false, surface: '', key: RESUMED })) + focusComposerForResumedSession(Promise.resolve({ ok: false, surface: '', key: RESUMED }), store) await flushFrame() expect(document.activeElement).not.toBe(composer) }) it('focuses nothing for a surface the chat page cannot display (#3624)', async () => { - focusComposerForResumedSession(Promise.resolve({ ok: true, surface: 'slack', key: RESUMED })) + focusComposerForResumedSession(Promise.resolve({ ok: true, surface: 'slack', key: RESUMED }), store) + await flushFrame() + expect(document.activeElement).not.toBe(composer) + }) + + it('focuses nothing when the resume answered but did not take the view (the user moved meanwhile)', async () => { + // The fulfilled reducer declined to open it: the composer on the page + // belongs to the session the user moved to. + viewing = 'zzq-moved-to' + focusComposerForResumedSession(Promise.resolve(entered), store) + await flushFrame() await flushFrame() expect(document.activeElement).not.toBe(composer) }) @@ -442,7 +456,7 @@ describe('focusComposerForResumedSession — only once the resume entered the se it('focuses nothing when the resume rejects, and does not leak the rejection', async () => { const unhandled = vi.fn() process.on('unhandledRejection', unhandled) - focusComposerForResumedSession(Promise.reject(new Error('404'))) + focusComposerForResumedSession(Promise.reject(new Error('404')), store) await flushFrame() await flushFrame() process.off('unhandledRejection', unhandled) @@ -478,7 +492,7 @@ describe('focusComposerForResumedSession — only once the resume entered the se }) it('focuses the composer of the pane bound to the resumed key, never the grid-focused pane\'s', async () => { - focusComposerForResumedSession(Promise.resolve(entered)) + focusComposerForResumedSession(Promise.resolve(entered), store) await flushFrame() await flushFrame() expect(document.activeElement).toBe(resumedPane.ta) @@ -487,7 +501,7 @@ describe('focusComposerForResumedSession — only once the resume entered the se it('focuses nothing when panes are mounted and none is bound to the resumed key', async () => { resumedPane.pane.setAttribute('data-pane-slot', 'zzq-some-other-slot') - focusComposerForResumedSession(Promise.resolve(entered)) + focusComposerForResumedSession(Promise.resolve(entered), store) await flushFrame() await flushFrame() expect(document.activeElement).not.toBe(focusedPane.ta) diff --git a/website/src/test/forkRespectsSwitchAway.test.tsx b/website/src/test/forkRespectsSwitchAway.test.tsx index 1538ff6307c6..1aba30d17d2b 100644 --- a/website/src/test/forkRespectsSwitchAway.test.tsx +++ b/website/src/test/forkRespectsSwitchAway.test.tsx @@ -17,7 +17,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import type { ReactNode } from 'react' import type { ChatSlot } from '../types' -const mocks = vi.hoisted(() => ({ forkChatSlot: vi.fn(), dashboardConfig: vi.fn() })) +const mocks = vi.hoisted(() => ({ forkChatSlot: vi.fn(), dashboardConfig: vi.fn(), resumeChatSlot: vi.fn() })) vi.mock('../api/client', async () => { const { ApiError } = await import('../api/apiError') return { @@ -31,7 +31,7 @@ vi.mock('../api/client', async () => { import { store } from '../store' import { sseSlots } from '../store/dashboardSlice' -import { dropActiveSlot, setActiveSlot, switchSlot } from '../store/chatSlice' +import { dropActiveSlot, resumeFromHistory, setActiveSlot, switchSlot } from '../store/chatSlice' import { useSessionActions } from '../hooks/useSessionActions' import { useForkSession } from '../pages/useChatPageSlotSwitches' @@ -172,6 +172,27 @@ describe('transcript Fork from here', () => { return { result, showActionError } } + // A resume clicked before the fork answers after the fork opened its + // child: the fork is the later click, so the child keeps the view. + it('keeps the child when a resume clicked before the fork answers after it', async () => { + const land = deferredFork() + let landResume!: (v: unknown) => void + mocks.resumeChatSlot.mockReturnValue(new Promise(r => { landResume = r })) + const { result } = renderFork() + + let resumed!: Promise<unknown> + act(() => { resumed = store.dispatch(resumeFromHistory({ key: 'chat-fork-old', title: 'Old' })) }) + await waitFor(() => expect(mocks.resumeChatSlot).toHaveBeenCalled()) + let forked!: Promise<void> + act(() => { forked = result.current.handleFork(1) }) + await waitFor(() => expect(mocks.forkChatSlot).toHaveBeenCalled()) + await act(async () => { land(); await forked }) + await waitFor(() => expect(activeSlot()).toBe(CHILD)) + await act(async () => { landResume({ ok: true, key: 'chat-fork-old', mode: '', messages: [] }); await resumed }) + + expect(activeSlot()).toBe(CHILD) + }) + it('leaves the user on the session they opened while the fork ran', async () => { const land = deferredFork() const { result, showActionError } = renderFork() diff --git a/website/src/test/latestClickAcrossKinds.test.ts b/website/src/test/latestClickAcrossKinds.test.ts new file mode 100644 index 000000000000..86f1e8604dac --- /dev/null +++ b/website/src/test/latestClickAcrossKinds.test.ts @@ -0,0 +1,240 @@ +/** + * The session clicked last opens, whichever kinds of request the clicks made. + * A create, fork or resume that opened its session switched the view, but + * that switch was a request the user made before this one, not a move away + * from it, so a request clicked after it still opens when it answers. A + * request clicked earlier never undoes one clicked later. + * + * The real `createSlot` and `resumeFromHistory` thunks run against deferred + * api answers. + */ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest' +import type { ChatSlot } from '../types' + +const mocks = vi.hoisted(() => ({ resumeChatSlot: vi.fn(), createChatSlot: vi.fn() })) +vi.mock('../api/client', async () => { + const { ApiError } = await import('../api/apiError') + return { + SEARCH_MIN_CHARS: 2, + ApiError, + api: new Proxy(mocks as Record<string, unknown>, { + get: (t, p: string) => (p in t ? t[p] : vi.fn().mockResolvedValue([])), + }), + } +}) + +import { store } from '../store' +import { sseSlots } from '../store/dashboardSlice' +import { captureForkOrigin, createSlot, forkMayOpen, forkOpenSettled, forkOpenStarted, listForkedSlot, resumeFromHistory, setActiveSlot, switchSlot } from '../store/chatSlice' + +const ORIGIN = 'chat-kinds-origin' +const OTHER = 'chat-kinds-other' +const R1 = 'chat-kinds-r1' +const NEW = 'chat-kinds-new' +const CHILD = 'chat-kinds-child' + +let landCreate: (v: unknown) => void = () => {} +let landResume: (v: unknown) => void = () => {} +const activeSlot = () => store.getState().chat.activeSlot +const created = { key: NEW, title: 'New Session', messages: 0, running: false } +const resumed = { ok: true, key: R1, mode: 'orchestrator', messages: [] } + +beforeEach(() => { + mocks.createChatSlot.mockImplementation(() => new Promise(r => { landCreate = r })) + mocks.resumeChatSlot.mockImplementation(() => new Promise(r => { landResume = r })) + const slot = (key: string): ChatSlot => ({ key, title: key, messages: 2, running: false, folder_id: '' }) + store.dispatch(sseSlots([slot(ORIGIN), slot(OTHER)])) + store.dispatch(setActiveSlot(ORIGIN)) + store.dispatch({ type: 'chat/fetchHistory/fulfilled', payload: { sessions: [{ key: R1, title: R1 }], hasMore: false, offset: 0, append: false } }) +}) +afterEach(() => { + vi.clearAllMocks() + store.dispatch(setActiveSlot(null)) + store.dispatch(sseSlots([])) +}) + +// Each returns its request wrapped: an async function returning the thunk's +// promise itself would wait for the request to settle. +async function startCreate() { + const c = store.dispatch(createSlot({ memory_mode: 'persistent' })) + await vi.waitFor(() => expect(mocks.createChatSlot).toHaveBeenCalled()) + return { done: c } +} +async function startResume() { + const r = store.dispatch(resumeFromHistory({ key: R1, title: R1 })) + await vi.waitFor(() => expect(mocks.resumeChatSlot).toHaveBeenCalled()) + return { done: r } +} + +describe('latest click across create and resume', () => { + it('opens the resume clicked after New when the create answers first', async () => { + const c = await startCreate() + const r = await startResume() + landCreate(created) + await c.done + expect(activeSlot()).toBe(NEW) + landResume(resumed) + await r.done + expect(activeSlot()).toBe(R1) + }) + + it('keeps the resume clicked after New when the create answers last', async () => { + const c = await startCreate() + const r = await startResume() + landResume(resumed) + await r.done + expect(activeSlot()).toBe(R1) + landCreate(created) + await c.done + expect(activeSlot()).toBe(R1) + }) + + it('opens New clicked after a resume when the resume answers first', async () => { + const r = await startResume() + const c = await startCreate() + landResume(resumed) + await r.done + expect(activeSlot()).toBe(R1) + landCreate(created) + await c.done + expect(activeSlot()).toBe(NEW) + }) + + it('still leaves the user where they moved while both were pending', async () => { + const c = await startCreate() + const r = await startResume() + store.dispatch(setActiveSlot(OTHER)) + landCreate(created) + await c.done + landResume(resumed) + await r.done + expect(activeSlot()).toBe(OTHER) + }) +}) + +describe('two creates in a row', () => { + // One request made twice: the first to open keeps the view, so text typed + // while both ran stays in the chat it was carried into. + it('keeps the first create that opened', async () => { + const lands: Array<(v: unknown) => void> = [] + mocks.createChatSlot.mockImplementation(() => new Promise(r => { lands.push(r) })) + const c1 = store.dispatch(createSlot({ memory_mode: 'persistent' })) + const c2 = store.dispatch(createSlot({ memory_mode: 'persistent' })) + await vi.waitFor(() => expect(lands).toHaveLength(2)) + lands[0]({ key: 'chat-kinds-new-1', title: 'New', messages: 0, running: false }) + await c1 + lands[1]({ key: 'chat-kinds-new-2', title: 'New', messages: 0, running: false }) + await c2 + expect(activeSlot()).toBe('chat-kinds-new-1') + }) +}) + +describe('a create, a resume, then another create', () => { + // The resume opened between the two creates, so the second create is the + // later click over it and opens. + it('opens the second create when the resume opened after the first', async () => { + const lands: Array<(v: unknown) => void> = [] + mocks.createChatSlot.mockImplementation(() => new Promise(r => { lands.push(r) })) + const c1 = store.dispatch(createSlot({ memory_mode: 'persistent' })) + await vi.waitFor(() => expect(lands).toHaveLength(1)) + const r = await startResume() + const c2 = store.dispatch(createSlot({ memory_mode: 'persistent' })) + await vi.waitFor(() => expect(lands).toHaveLength(2)) + lands[0]({ key: 'chat-kinds-new-1', title: 'New', messages: 0, running: false }) + await c1 + landResume(resumed) + await r.done + expect(activeSlot()).toBe(R1) + lands[1]({ key: 'chat-kinds-new-2', title: 'New', messages: 0, running: false }) + await c2 + expect(activeSlot()).toBe('chat-kinds-new-2') + }) +}) + +describe('three creates in a row', () => { + // One burst of New presses: the first to open keeps the view, however many + // creates came after it, so the text typed into it stays on screen. + it('keeps the first create that opened', async () => { + const lands: Array<(v: unknown) => void> = [] + mocks.createChatSlot.mockImplementation(() => new Promise(r => { lands.push(r) })) + const cs = [1, 2, 3].map(() => store.dispatch(createSlot({ memory_mode: 'persistent' }))) + await vi.waitFor(() => expect(lands).toHaveLength(3)) + for (const [i, land] of lands.entries()) { + land({ key: `chat-kinds-new-${i + 1}`, title: 'New', messages: 0, running: false }) + await cs[i] + } + expect(activeSlot()).toBe('chat-kinds-new-1') + }) +}) + +describe('a create, a resume, then another create, answering create, create, resume', () => { + // The resume was clicked between the creates, so the second create is not + // a repeat of the first: it is the last click and keeps the view. + it('ends on the second create', async () => { + const lands: Array<(v: unknown) => void> = [] + mocks.createChatSlot.mockImplementation(() => new Promise(r => { lands.push(r) })) + const c1 = store.dispatch(createSlot({ memory_mode: 'persistent' })) + await vi.waitFor(() => expect(lands).toHaveLength(1)) + const r = await startResume() + const c2 = store.dispatch(createSlot({ memory_mode: 'persistent' })) + await vi.waitFor(() => expect(lands).toHaveLength(2)) + lands[0]({ key: 'chat-kinds-new-1', title: 'New', messages: 0, running: false }) + await c1 + lands[1]({ key: 'chat-kinds-new-2', title: 'New', messages: 0, running: false }) + await c2 + expect(activeSlot()).toBe('chat-kinds-new-2') + landResume(resumed) + await r.done + expect(activeSlot()).toBe('chat-kinds-new-2') + }) +}) + +describe('a create that opens through a foreground tab', () => { + // Cmd/Ctrl+Shift-click New: the create runs with `activate: false`, and its + // success opens the tab with `switchSlot`, naming the create's number. + it('still lets a resume clicked after it open', async () => { + const c = store.dispatch(createSlot({ memory_mode: 'persistent', activate: false })) + await vi.waitFor(() => expect(mocks.createChatSlot).toHaveBeenCalled()) + const r = await startResume() + landCreate(created) + const action = await c + if (!createSlot.fulfilled.match(action)) throw new Error('create did not fulfil') + await store.dispatch(switchSlot({ key: NEW, announceOnMissing: true, requestSeq: action.meta.originRequestSeq })) + expect(activeSlot()).toBe(NEW) + landResume(resumed) + await r.done + expect(activeSlot()).toBe(R1) + }) +}) + +describe('latest click across fork and create', () => { + // The sidebar Fork's own path: capture, list the child, then switch with + // the origin's request number. + async function landFork(origin: ReturnType<typeof captureForkOrigin>) { + store.dispatch(listForkedSlot({ key: CHILD, title: CHILD })) + if (forkMayOpen(store.getState(), origin)) await store.dispatch(switchSlot({ key: CHILD, requestSeq: origin.seq })) + store.dispatch(forkOpenSettled()) + } + + it('opens New clicked after a sidebar Fork when the fork answers first', async () => { + store.dispatch(forkOpenStarted()) + const fork = captureForkOrigin(store.getState()) + const c = await startCreate() + await landFork(fork) + expect(activeSlot()).toBe(CHILD) + landCreate(created) + await c.done + expect(activeSlot()).toBe(NEW) + }) + + it('keeps New clicked after a sidebar Fork when the fork answers last', async () => { + store.dispatch(forkOpenStarted()) + const fork = captureForkOrigin(store.getState()) + const c = await startCreate() + landCreate(created) + await c.done + expect(activeSlot()).toBe(NEW) + await landFork(fork) + expect(activeSlot()).toBe(NEW) + }) +}) diff --git a/website/src/test/olderHistoryTrigger.test.tsx b/website/src/test/olderHistoryTrigger.test.tsx index 616141300b62..49ede24675fd 100644 --- a/website/src/test/olderHistoryTrigger.test.tsx +++ b/website/src/test/olderHistoryTrigger.test.tsx @@ -18,10 +18,11 @@ import { fileURLToPath } from 'node:url' import { dirname, resolve } from 'node:path' import { useVirtualChat } from '../hooks/virtualizer/useVirtualChat' import { createTestStore } from './helpers' +import { landResume } from './resumeLanded' // The walk's page size is asserted through its CONSTANT, never a spelled-out // number: what these tests own is "the walk asks for a walk-sized page", and a // literal turns a deliberate retune of that size into two unrelated red tests. -import { loadOlderMessages, resumeFromHistory, OLDER_WALK_PAGE_LIMIT } from '../store/chatSlice' +import { loadOlderMessages, OLDER_WALK_PAGE_LIMIT } from '../store/chatSlice' import { shouldPaginateOlder } from '../pages/chat/pagination' import { shouldAutoFillOlder } from '../pages/ChatPage' import { api } from '../api/client' @@ -229,11 +230,7 @@ describe('older-history trigger — fetch through the gate', () => { /** Seed a resumed session through the real reducer path that reads `has_more`. */ function resumedStore(hasMore: boolean) { const store = createTestStore() - store.dispatch(resumeFromHistory.fulfilled( - { ok: true, key: 'slot-1', messages: [], hasMore, nextBefore: OLDEST, rawCount: RESUME_RAW, total: TOTAL }, - 'req-1', - { key: 'slot-1', title: 'slot-1' }, - )) + landResume(store, { ok: true, key: 'slot-1', messages: [], hasMore, nextBefore: OLDEST, rawCount: RESUME_RAW, total: TOTAL }, 'req-1', { key: 'slot-1', title: 'slot-1' }) return store } diff --git a/website/src/test/resumeLanded.ts b/website/src/test/resumeLanded.ts new file mode 100644 index 000000000000..0f165d698d4b --- /dev/null +++ b/website/src/test/resumeLanded.ts @@ -0,0 +1,42 @@ +/** + * Lands a `resumeFromHistory` the way the real thunk does, for fixtures that + * seed a resumed session without a network round trip: the `pending` action + * first, then `fulfilled` carrying the origin the thunk records when it + * starts. The fulfilled reducer opens the session only for the latest resume + * and only when the user has not moved since (`forkMayOpen`), so a bare + * fulfilled action with no pending and no origin no longer stands for a resume + * that took the view. + */ +import type { UnknownAction } from '@reduxjs/toolkit' +import { captureForkOrigin, resumeFromHistory, type ChatState } from '../store/chatSlice' + +type Arg = { key: string; title: string } + +/** The pending and fulfilled actions for a resume started from `chat`. */ +export function resumeLandedActions(chat: ChatState, payload: unknown, requestId: string, arg: Arg): [UnknownAction, UnknownAction] { + const origin = captureForkOrigin({ chat }) + return [ + // The fulfilled action follows at once, so the entry's age never matters. + resumeFromHistory.pending(requestId, arg, { startedAt: 0 }), + resumeFromHistory.fulfilled(payload as never, requestId, arg, { + originActiveSlot: origin.activeSlot, + originActiveSlotMoves: origin.moves, + originActiveSlotAutoMoves: origin.autoMoves, + }), + ] +} + +/** Dispatches a landed resume into a store. */ +export function landResume( + store: { dispatch: (a: UnknownAction) => unknown; getState: () => { chat: ChatState } }, + payload: unknown, + requestId: string, + arg: Arg, +): void { + for (const a of resumeLandedActions(store.getState().chat, payload, requestId, arg)) store.dispatch(a) +} + +/** Applies a landed resume to a bare slice state. */ +export function reduceResume<S extends ChatState>(reducer: (s: S, a: UnknownAction) => S, state: S, payload: unknown, requestId: string, arg: Arg): S { + return resumeLandedActions(state, payload, requestId, arg).reduce(reducer, state) +} diff --git a/website/src/test/resumeRespectsSwitchAway.test.ts b/website/src/test/resumeRespectsSwitchAway.test.ts new file mode 100644 index 000000000000..8e2893ef6f86 --- /dev/null +++ b/website/src/test/resumeRespectsSwitchAway.test.ts @@ -0,0 +1,255 @@ +/** + * A resume from Older sessions (or any other resume entry point) that answers + * after the user moved must leave the user where they are, the rule creates + * and forks follow (`forkMayOpen`): another session opened meanwhile, or a + * return to the origin, is a choice the late answer must not undo. The resumed + * session is still listed as an open tab and leaves Older sessions. + * + * Two resumes in a row: the later click wins, so an earlier resume answering + * after the later one does not take the view back. A repeat of a resume on its + * way sends nothing, also with another row resumed in between, until the + * pending-open lease ends. While a resume is pending the chat page knows one + * is on its way (`pendingResumes`), as it knows of a pending create or fork. + * + * The real `resumeFromHistory` thunk runs against a deferred + * `api.resumeChatSlot`, one per history key. + */ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest' +import type { ChatSlot } from '../types' + +const mocks = vi.hoisted(() => ({ resumeChatSlot: vi.fn() })) +vi.mock('../api/client', async () => { + const { ApiError } = await import('../api/apiError') + return { + SEARCH_MIN_CHARS: 2, + ApiError, + api: new Proxy(mocks as Record<string, unknown>, { + get: (t, p: string) => (p in t ? t[p] : vi.fn().mockResolvedValue([])), + }), + } +}) + +import { store } from '../store' +import { sseSlots } from '../store/dashboardSlice' +import { dropActiveSlot, PENDING_OPEN_LEASE_MS, resumeFromHistory, setActiveSlot, switchSlot } from '../store/chatSlice' + +const ORIGIN = 'chat-resume-origin' +const OTHER = 'chat-resume-other' +const R1 = 'chat-resume-r1' +const R2 = 'chat-resume-r2' + +// The deferred answers per history key, oldest first; `land(key)` resolves the +// oldest one still open. +const pending = new Map<string, Array<(v: unknown) => void>>() +function land(key: string) { + const resolve = pending.get(key)?.shift() + if (!resolve) throw new Error(`no resume pending for ${key}`) + resolve({ ok: true, key, mode: 'orchestrator', messages: [] }) +} +const posts = (key: string) => mocks.resumeChatSlot.mock.calls.filter(c => c[0] === key).length +const pendingKeys = () => Object.values(store.getState().chat.pendingResumes ?? {}).map(p => p.key).sort() + +const activeSlot = () => store.getState().chat.activeSlot +const listed = (key: string) => store.getState().dashboard.slots.some(s => s.key === key) +const inHistory = (key: string) => store.getState().chat.history.some(s => s.key === key) +const resume = (key: string) => store.dispatch(resumeFromHistory({ key, title: key })) + +beforeEach(() => { + mocks.resumeChatSlot.mockImplementation((key: string) => new Promise(r => { pending.set(key, [...(pending.get(key) ?? []), r]) })) + const slot = (key: string): ChatSlot => ({ key, title: key, messages: 2, running: false, folder_id: '' }) + store.dispatch(sseSlots([slot(ORIGIN), slot(OTHER)])) + store.dispatch(setActiveSlot(ORIGIN)) + store.dispatch({ type: 'chat/fetchHistory/fulfilled', payload: { sessions: [R1, R2].map(key => ({ key, title: key })), hasMore: false, offset: 0, append: false } }) +}) +afterEach(async () => { + vi.useRealTimers() + // Settle every resume a test left open, so no entry leaks into the next. + for (const [key, list] of pending) while (list.length) land(key) + await vi.waitFor(() => expect(pendingKeys()).toEqual([])) + vi.clearAllMocks() + pending.clear() + store.dispatch(setActiveSlot(null)) + store.dispatch(sseSlots([])) +}) + +describe('resumeFromHistory resolving after the user moved', () => { + it('leaves the user on the session they opened while the resume ran', async () => { + const resumed = resume(R1) + await vi.waitFor(() => expect(mocks.resumeChatSlot).toHaveBeenCalled()) + store.dispatch(setActiveSlot(OTHER)) + land(R1) + await resumed + + expect(activeSlot()).toBe(OTHER) + expect(listed(R1)).toBe(true) + expect(inHistory(R1)).toBe(false) + }) + + it('leaves the user on the origin when they went away and came back while the resume ran', async () => { + const resumed = resume(R1) + await vi.waitFor(() => expect(mocks.resumeChatSlot).toHaveBeenCalled()) + store.dispatch(setActiveSlot(OTHER)) + store.dispatch(setActiveSlot(ORIGIN)) + land(R1) + await resumed + + expect(activeSlot()).toBe(ORIGIN) + expect(listed(R1)).toBe(true) + }) + + it('opens the later of two resumes when the earlier one answers last', async () => { + const first = resume(R1) + const second = resume(R2) + await vi.waitFor(() => expect(mocks.resumeChatSlot).toHaveBeenCalledTimes(2)) + land(R2) + await second + expect(activeSlot()).toBe(R2) + land(R1) + await first + + expect(activeSlot()).toBe(R2) + expect(listed(R1)).toBe(true) + expect(inHistory(R1)).toBe(false) + }) + + it('sends one resume for a repeated click on the row on its way', async () => { + const resumed = resume(R1) + void resume(R1) + await vi.waitFor(() => expect(mocks.resumeChatSlot).toHaveBeenCalled()) + expect(mocks.resumeChatSlot).toHaveBeenCalledTimes(1) + expect(pendingKeys()).toEqual([R1]) + land(R1) + await resumed + + expect(activeSlot()).toBe(R1) + expect(pendingKeys()).toEqual([]) + }) + + it('clears the pending resume when it fails', async () => { + mocks.resumeChatSlot.mockRejectedValueOnce(new Error('boom')) + await resume(R1) + + expect(pendingKeys()).toEqual([]) + expect(activeSlot()).toBe(ORIGIN) + }) + + // The chat page lost the origin and moved the view itself: no user choice, + // so the resumed session still opens. + it('opens the session when the page itself dropped the origin and auto-selected another session', async () => { + const resumed = resume(R1) + await vi.waitFor(() => expect(mocks.resumeChatSlot).toHaveBeenCalled()) + store.dispatch(dropActiveSlot()) + void store.dispatch(switchSlot({ key: OTHER, automatic: true })) + land(R1) + await resumed + + expect(activeSlot()).toBe(R1) + }) + + it('opens the session when the user stayed on the origin', async () => { + const resumed = resume(R1) + await vi.waitFor(() => expect(mocks.resumeChatSlot).toHaveBeenCalled()) + store.dispatch(setActiveSlot(ORIGIN)) + land(R1) + await resumed + + expect(activeSlot()).toBe(R1) + expect(inHistory(R1)).toBe(false) + }) + + // A resume of another row in between must not reopen the guard: each + // pending resume holds its own entry. + it('sends one resume for H1, H2, H1 while the first H1 is still on its way, and opens H1', async () => { + const first = resume(R1) + const second = resume(R2) + await vi.waitFor(() => expect(mocks.resumeChatSlot).toHaveBeenCalledTimes(2)) + land(R2) + await second + expect(activeSlot()).toBe(R2) + expect(pendingKeys()).toEqual([R1]) + + const repeat = await resume(R1) + expect(resumeFromHistory.rejected.match(repeat) && repeat.meta.condition).toBe(true) + expect(posts(R1)).toBe(1) + expect(store.getState().chat.unresumableResume).toBeNull() + + // The repeat was the user's newest click, so the H1 already on its way + // opens when it answers, from R2 where they now stand. + land(R1) + await first + expect(activeSlot()).toBe(R1) + expect(pendingKeys()).toEqual([]) + }) + + it('does not open H1 when the user moved after the repeated H1 click', async () => { + const first = resume(R1) + await vi.waitFor(() => expect(mocks.resumeChatSlot).toHaveBeenCalledTimes(1)) + await resume(R1) + store.dispatch(setActiveSlot(OTHER)) + land(R1) + await first + + expect(activeSlot()).toBe(OTHER) + expect(listed(R1)).toBe(true) + }) +}) + +describe('the repeat guard is bounded by the pending-open lease', () => { + // The resume POST carries no deadline. Only Date is faked, and set by hand, + // so the guard's age is exact. No `vi.waitFor` here: with fake timers on it + // advances the clock on every poll. + const T0 = new Date('2026-10-22T12:00:00Z').getTime() + const at = (ms: number) => vi.setSystemTime(T0 + ms) + const settle = () => new Promise(r => setTimeout(r, 0)) + beforeEach(() => { + vi.useFakeTimers({ toFake: ['Date'] }) + at(0) + }) + + it('drops a repeat until the lease ends, then sends a fresh resume for a hung one', async () => { + const hung = resume(R1) + await settle() + expect(posts(R1)).toBe(1) + + at(PENDING_OPEN_LEASE_MS - 1) + await resume(R1) + expect(posts(R1)).toBe(1) + + at(PENDING_OPEN_LEASE_MS) + const fresh = resume(R1) + await settle() + expect(posts(R1)).toBe(2) + // The hung entry is dropped when the fresh one starts; only the fresh one + // is on its way. + expect(pendingKeys()).toEqual([R1]) + + // The fresh one is the latest: the hung one answering first lists the + // session without opening it, and the fresh one opens it. + land(R1) + await hung + expect(activeSlot()).toBe(ORIGIN) + expect(listed(R1)).toBe(true) + land(R1) + await fresh + expect(activeSlot()).toBe(R1) + expect(pendingKeys()).toEqual([]) + }) + + it('a late answer from a hung resume does not open once a newer resume ran', async () => { + const hung = resume(R1) + await settle() + at(PENDING_OPEN_LEASE_MS) + const later = resume(R2) + await settle() + expect(posts(R2)).toBe(1) + land(R2) + await later + expect(activeSlot()).toBe(R2) + + land(R1) + await hung + expect(activeSlot()).toBe(R2) + expect(listed(R1)).toBe(true) + expect(pendingKeys()).toEqual([]) + }) +})