Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix(chat): keep a tool-using turn running when the user opens another thread (#9311) (#9313)

James Dame7cbcf6d232f
diff --git a/web-app/src/components/ai-elements/tool.tsx b/web-app/src/components/ai-elements/tool.tsx
index c784e1a39..a52698b9f 100644
--- a/web-app/src/components/ai-elements/tool.tsx
+++ b/web-app/src/components/ai-elements/tool.tsx
@@ -30,7 +30,10 @@ import {
} from '@/lib/toolInputSummary'
import { summarizeToolOutput } from '@/lib/toolOutputSummary'
import { useToolApprovalRequests } from '@/hooks/useToolApprovalRequests'
-import { useToolCallRuntime } from '@/hooks/useToolCallRuntime'
+import {
+ queuePositionOf,
+ useToolCallRuntime,
+} from '@/hooks/useToolCallRuntime'
import { ToolElapsed } from './tool-runtime'
import { useTranslation } from '@/i18n/react-i18next-compat'
import { Button } from '@/components/ui/button'
@@ -173,7 +176,7 @@ export const ToolHeader = memo(
const summary = useMemo(() => summarizeToolInput(input), [input])
// Position in the pending queue, or -1 once the executor has reached it.
const queuePosition = useToolCallRuntime((s) =>
- toolCallId ? s.queue.indexOf(toolCallId) : -1
+ toolCallId ? queuePositionOf(s, toolCallId) : -1
)
const startedAt = useToolCallRuntime((s) =>
toolCallId ? s.timings[toolCallId]?.startedAt : undefined
diff --git a/web-app/src/containers/message/ChainOfThoughtGroup.tsx b/web-app/src/containers/message/ChainOfThoughtGroup.tsx
index ecb664e11..93bfc43bc 100644
--- a/web-app/src/containers/message/ChainOfThoughtGroup.tsx
+++ b/web-app/src/containers/message/ChainOfThoughtGroup.tsx
@@ -13,7 +13,7 @@ import {
import { Button } from '@/components/ui/button'
import { useToolApprovalRequests } from '@/hooks/useToolApprovalRequests'
import {
- findRunningToolCallId,
+ isToolCallRunning,
useToolCallRuntime,
} from '@/hooks/useToolCallRuntime'
import { useTranslation } from '@/i18n/react-i18next-compat'
@@ -56,7 +56,16 @@ export const ChainOfThoughtGroup = memo(
}: ChainOfThoughtGroupProps) => {
const { t } = useTranslation()
const pendingApprovals = useToolApprovalRequests((s) => s.pending)
- const runningToolCallId = useToolCallRuntime((s) => findRunningToolCallId(s.timings))
+ // This trace's own running call: another thread's loop may be running one
+ // in the background at the same time.
+ const runningToolCallId = useToolCallRuntime(
+ (s) =>
+ entries.find(
+ (e) =>
+ e.part.toolCallId !== undefined &&
+ isToolCallRunning(s.timings[e.part.toolCallId])
+ )?.part.toolCallId
+ )
// Seed the header from a persisted duration on reload; persist the live
// measurement so it survives the next one. Keyed by the (stable) message id.
const storedDuration = useCoTDuration((s) => s.durations[messageId])
diff --git a/web-app/src/hooks/__tests__/use-chat.test.ts b/web-app/src/hooks/__tests__/use-chat.test.ts
new file mode 100644
index 000000000..79e769297
--- /dev/null
+++ b/web-app/src/hooks/__tests__/use-chat.test.ts
@@ -0,0 +1,86 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { renderHook } from '@testing-library/react'
+
+// The thread route is reused across thread switches, so useChat outlives a
+// session. A turn left running in the background (#9311) keeps using its
+// session's transport, which must therefore never be handed to, or rewritten
+// by, the thread opened next.
+
+vi.mock('@/lib/custom-chat-transport', () => ({
+ CustomChatTransport: class {
+ systemMessage?: string
+ threadId?: string
+ constructor(systemMessage?: string, threadId?: string) {
+ this.systemMessage = systemMessage
+ this.threadId = threadId
+ }
+ updateSystemMessage(systemMessage?: string) {
+ this.systemMessage = systemMessage
+ }
+ setOnTokenUsage() {}
+ refreshTools() {}
+ },
+}))
+vi.mock('@ai-sdk/react', () => ({
+ Chat: class {
+ status = 'ready'
+ transport: unknown
+ constructor(init: { transport: unknown }) {
+ this.transport = init.transport
+ }
+ stop() {}
+ },
+ useChat: () => ({ status: 'ready', messages: [] }),
+}))
+vi.mock('@/hooks/useAppState', () => ({
+ useAppState: (selector: (s: unknown) => unknown) =>
+ selector({ mcpToolNames: new Set(), ragToolNames: new Set() }),
+}))
+
+import { useChat } from '../use-chat'
+import { useChatSessions } from '@/stores/chat-session-store'
+
+type FakeTransport = { systemMessage?: string; threadId?: string }
+
+const transportOf = (sessionId: string) =>
+ useChatSessions.getState().sessions[sessionId]?.transport as unknown as
+ | FakeTransport
+ | undefined
+
+describe('useChat transport per session', () => {
+ beforeEach(() => {
+ useChatSessions.getState().clearSessions()
+ })
+
+ it('gives a newly opened thread its own transport', () => {
+ const { rerender } = renderHook(
+ (props: { sessionId: string; systemMessage: string }) => useChat(props),
+ { initialProps: { sessionId: 'a', systemMessage: 'A rules' } }
+ )
+ rerender({ sessionId: 'b', systemMessage: 'B rules' })
+
+ expect(transportOf('b')).not.toBe(transportOf('a'))
+ expect(transportOf('b')).toMatchObject({
+ threadId: 'b',
+ systemMessage: 'B rules',
+ })
+ // A's turn may still be running: its instructions must be A's.
+ expect(transportOf('a')).toMatchObject({
+ threadId: 'a',
+ systemMessage: 'A rules',
+ })
+ })
+
+ it('goes back to the session transport a thread already has', () => {
+ const { rerender } = renderHook(
+ (props: { sessionId: string; systemMessage: string }) => useChat(props),
+ { initialProps: { sessionId: 'a', systemMessage: 'A rules' } }
+ )
+ const a = transportOf('a')
+ rerender({ sessionId: 'b', systemMessage: 'B rules' })
+ rerender({ sessionId: 'a', systemMessage: 'A rules' })
+
+ expect(transportOf('a')).toBe(a)
+ expect(transportOf('b')?.systemMessage).toBe('B rules')
+ })
+})
diff --git a/web-app/src/hooks/__tests__/useThreads.coverage.test.ts b/web-app/src/hooks/__tests__/useThreads.coverage.test.ts
index 75582c028..f44c482f0 100644
--- a/web-app/src/hooks/__tests__/useThreads.coverage.test.ts
+++ b/web-app/src/hooks/__tests__/useThreads.coverage.test.ts
@@ -1,6 +1,7 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { act, renderHook } from '@testing-library/react'
import { useThreads } from '../useThreads'
+import { useChatSessions } from '@/stores/chat-session-store'
vi.mock('@/services/threads', () => ({
createThread: vi.fn(),
@@ -310,6 +311,36 @@ describe('useThreads - coverage', () => {
expect(result.current.threads['t3']).toBeDefined()
})
+ // Removing the chat session is what ends a turn still running in the
+ // background (#9311), so deleting a thread in bulk must remove it too.
+ it('removes the chat session of each thread deleted in bulk', () => {
+ const { result } = renderHook(() => useThreads())
+ const session = (id: string) =>
+ useChatSessions
+ .getState()
+ .ensureSession(
+ id,
+ {} as never,
+ () => ({ status: 'ready', stop: vi.fn() }) as never
+ )
+
+ act(() => {
+ result.current.setThreads([
+ { id: 't1', title: 'Fav', isFavorite: true } as any,
+ { id: 't2', title: 'Normal' } as any,
+ ])
+ session('t1')
+ session('t2')
+ })
+
+ act(() => {
+ result.current.deleteAllThreads()
+ })
+
+ expect(useChatSessions.getState().sessions['t2']).toBeUndefined()
+ expect(useChatSessions.getState().sessions['t1']).toBeDefined()
+ })
+
it('should clear all threads', () => {
const { result } = renderHook(() => useThreads())
diff --git a/web-app/src/hooks/__tests__/useToolCallRuntime.test.ts b/web-app/src/hooks/__tests__/useToolCallRuntime.test.ts
index ffafe6f2d..f680ef8a1 100644
--- a/web-app/src/hooks/__tests__/useToolCallRuntime.test.ts
+++ b/web-app/src/hooks/__tests__/useToolCallRuntime.test.ts
@@ -1,6 +1,7 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import {
findRunningToolCallId,
+ queuePositionOf,
useToolCallRuntime,
withToolTiming,
} from '../useToolCallRuntime'
@@ -159,6 +160,100 @@ describe('useToolCallRuntime', () => {
expect(store().diffs).toEqual({ a: 'first again', b: 'second' })
})
+ // A turn keeps running when the user opens another thread (#9311), so tool
+ // loops of several threads share the store at once. Each must see and settle
+ // only its own calls.
+ describe('loops of different threads', () => {
+ it('queues each thread behind its own calls only', () => {
+ store().enqueue(['a1', 'a2'], 'thread-a')
+ store().enqueue(['b1', 'b2'], 'thread-b')
+ expect(queuePositionOf(store(), 'a2')).toBe(1)
+ expect(queuePositionOf(store(), 'b1')).toBe(0)
+ expect(queuePositionOf(store(), 'b2')).toBe(1)
+ })
+
+ it("does not take another thread's queue or running call when a turn starts", () => {
+ store().enqueue(['a1', 'a2'], 'thread-a')
+ store().markRunning('a1')
+ store().enqueue(['b1'], 'thread-b')
+ expect(store().timings['a1'].endedAt).toBeUndefined()
+ expect(store().queue).toEqual(['a2', 'b1'])
+ })
+
+ it("leaves another thread's queue alone when a loop ends", () => {
+ store().enqueue(['a1', 'a2'], 'thread-a')
+ store().enqueue(['b1', 'b2'], 'thread-b')
+ store().settleRemaining('thread-a')
+ expect(store().queue).toEqual(['b1', 'b2'])
+ expect(store().timings['a2'].endedAt).toBeDefined()
+ expect(store().timings['b1'].endedAt).toBeUndefined()
+ })
+
+ it("attaches progress to the running call of the update's server", () => {
+ store().enqueue(['a1'], 'thread-a')
+ store().enqueue(['b1'], 'thread-b')
+ store().markRunning('a1', 'github')
+ store().markRunning('b1', 'fetch')
+ store().reportProgress({ server: 'fetch', progress: 1 })
+ expect(store().progress['b1']).toMatchObject({ server: 'fetch' })
+ expect(store().progress['a1']).toBeUndefined()
+ })
+
+ // Nothing in the update says which of them it belongs to.
+ it('drops progress it cannot attribute to one call', () => {
+ store().enqueue(['a1'], 'thread-a')
+ store().enqueue(['b1'], 'thread-b')
+ store().markRunning('a1', 'github')
+ store().markRunning('b1', 'github')
+ store().reportProgress({ server: 'github', progress: 1 })
+ expect(store().progress).toEqual({})
+ })
+
+ it('does not attach progress to the only running call when its server differs', () => {
+ store().enqueue(['a1'], 'thread-a')
+ store().markRunning('a1', 'github')
+ store().reportProgress({ server: 'fetch', progress: 1 })
+ expect(store().progress).toEqual({})
+ })
+
+ // Cowork records no server, so its call is matched by being the only one.
+ it('attaches progress to the only running call when its server is unknown', () => {
+ store().enqueue(['c1'])
+ store().markRunning('c1')
+ store().reportProgress({ server: 'fetch', progress: 1 })
+ expect(store().progress['c1']).toMatchObject({ server: 'fetch' })
+ })
+
+ it('releases calls enqueued without an owner when asked for none', () => {
+ store().enqueue(['c1'])
+ store().markRunning('c1')
+ store().markSettled('c1')
+ store().enqueue(['a1'], 'thread-a')
+ store().markRunning('a1')
+ store().markSettled('a1')
+ store().releaseSettled()
+ expect(store().timings['c1']).toBeUndefined()
+ expect(store().timings['a1']).toBeDefined()
+ })
+
+ it("releases a left thread's settled calls, keeping what its loop still runs", () => {
+ store().enqueue(['a1', 'a2', 'a3'], 'thread-a')
+ store().enqueue(['b1'], 'thread-b')
+ store().markRunning('a1')
+ store().recordDiff('a1', 'diff')
+ store().markSettled('a1')
+ store().markRunning('a2')
+ store().markRunning('b1')
+ store().markSettled('b1')
+ store().releaseSettled('thread-a')
+ expect(store().timings['a1']).toBeUndefined()
+ expect(store().diffs['a1']).toBeUndefined()
+ expect(store().timings['a2'].startedAt).toBeDefined()
+ expect(queuePositionOf(store(), 'a3')).toBe(0)
+ expect(store().timings['b1']).toBeDefined()
+ })
+ })
+
/// Cowork dispatches serially and has no queue to report, but its cards still
/// need a duration -- without a timing entry the header shows a bare spinner.
it('times a single call from dispatch to settle', async () => {
diff --git a/web-app/src/hooks/use-chat.ts b/web-app/src/hooks/use-chat.ts
index 7edaed320..29895a16d 100644
--- a/web-app/src/hooks/use-chat.ts
+++ b/web-app/src/hooks/use-chat.ts
@@ -31,6 +31,10 @@ export function useChat(
options?: CustomChatOptions
) {
const transportRef = useRef<CustomChatTransport | undefined>(undefined) // Using a ref here so we can update the model used in the transport without having to reload the page or recreate the transport
+ // The session transportRef belongs to. The hook outlives a session switch (the
+ // thread route is reused), and a turn left running in the background keeps
+ // using its own transport, so a session must never inherit another's.
+ const transportSessionRef = useRef<string | undefined>(undefined)
const {
sessionId,
sessionTitle,
@@ -51,28 +55,27 @@ export function useChat(
: undefined
// Create transport immediately with modelId and provider
- if (!transportRef.current) {
- transportRef.current =
- existingSessionTransport ?? new CustomChatTransport(systemMessage, sessionId)
+ if (existingSessionTransport) {
+ transportRef.current = existingSessionTransport
} else if (
- existingSessionTransport &&
- transportRef.current !== existingSessionTransport
+ !transportRef.current ||
+ transportSessionRef.current !== sessionId
) {
- transportRef.current = existingSessionTransport
+ transportRef.current = new CustomChatTransport(systemMessage, sessionId)
}
+ transportSessionRef.current = sessionId
+ const transport = transportRef.current
+ // Keyed by transport too, so a session switch hands the instructions and
+ // callback to the new session's transport.
useEffect(() => {
- if (transportRef.current) {
- transportRef.current.updateSystemMessage(systemMessage)
- }
- }, [systemMessage])
+ transport.updateSystemMessage(systemMessage)
+ }, [transport, systemMessage])
// Update the token usage callback when it changes
useEffect(() => {
- if (transportRef.current) {
- transportRef.current.setOnTokenUsage(onTokenUsage)
- }
- }, [onTokenUsage])
+ transport.setOnTokenUsage(onTokenUsage)
+ }, [transport, onTokenUsage])
// Memoize to prevent calling ensureSession (which has side effects) on every render
const chat = useMemo(() => {
@@ -123,22 +126,21 @@ export function useChat(
[]
)
- // Expose method to update RAG tools availability
+ // Expose method to update RAG tools availability. A new identity per
+ // transport, so a caller's effect re-runs for a newly opened session's.
const updateRagToolsAvailability = useCallback(
async (
hasDocuments: boolean,
modelSupportsTools: boolean,
ragFeatureAvailable: boolean
) => {
- if (transportRef.current) {
- await transportRef.current.updateRagToolsAvailability(
- hasDocuments,
- modelSupportsTools,
- ragFeatureAvailable
- )
- }
+ await transport.updateRagToolsAvailability(
+ hasDocuments,
+ modelSupportsTools,
+ ragFeatureAvailable
+ )
},
- []
+ [transport]
)
return {
diff --git a/web-app/src/hooks/useThreads.ts b/web-app/src/hooks/useThreads.ts
index bd9baa13e..f73fc3c47 100644
--- a/web-app/src/hooks/useThreads.ts
+++ b/web-app/src/hooks/useThreads.ts
@@ -231,8 +231,13 @@ export const useThreads = create<ThreadState>()((set, get) => ({
!state.threads[threadId].metadata?.project
)
- // Delete threads and clean up their out-of-store artifacts
+ // Delete threads and clean up their out-of-store artifacts. As in
+ // deleteThread: removing the chat session is what ends a turn the thread
+ // still has running in the background.
threadsToDeleteIds.forEach((threadId) => {
+ useAgentMode.getState().removeThread(threadId)
+ useChatSessions.getState().removeSession(threadId)
+ useAppState.getState().clearThreadState(threadId)
cleanupThreadArtifacts(threadId)
getServiceHub().threads().deleteThread(threadId)
})
diff --git a/web-app/src/hooks/useToolCallRuntime.ts b/web-app/src/hooks/useToolCallRuntime.ts
index b8d6af3af..14ba0178c 100644
--- a/web-app/src/hooks/useToolCallRuntime.ts
+++ b/web-app/src/hooks/useToolCallRuntime.ts
@@ -4,6 +4,14 @@ export type ToolCallTiming = {
/** Unset until the executor reaches this call. */
startedAt?: number
endedAt?: number
+ /**
+ * The tool loop that enqueued the call (chat: its thread). Loops of different
+ * threads run at once, since a turn keeps going when the user opens another
+ * thread, so queue position and settlement are per owner.
+ */
+ owner?: string
+ /** The MCP server serving the call, so a progress update can find it. */
+ server?: string
}
/** A `notifications/progress` update from an MCP server. */
@@ -21,7 +29,7 @@ export type ToolCallRuntimeSnapshot = {
/**
* Calls the executor has not reached yet, in execution order. Position is
* read from here rather than stored per call, so entries move up as the ones
- * ahead of them start.
+ * ahead of them start. Holds every owner's calls; see queuePositionOf.
*/
queue: string[]
timings: Record<string, ToolCallTiming>
@@ -38,25 +46,46 @@ export type ToolCallRuntimeSnapshot = {
type ToolCallRuntimeState = ToolCallRuntimeSnapshot & {
/**
- * Starts a turn. Earlier timings are kept: their cards are still on screen
- * and would otherwise lose the duration they had been showing.
+ * Starts a turn of `owner`'s loop, replacing what that loop still had queued.
+ * Earlier timings are kept: their cards are still on screen and would
+ * otherwise lose the duration they had been showing.
*/
- enqueue: (toolCallIds: string[]) => void
- markRunning: (toolCallId: string) => void
+ enqueue: (toolCallIds: string[], owner?: string) => void
+ markRunning: (toolCallId: string, server?: string) => void
markSettled: (toolCallId: string) => void
/**
* Records an MCP progress update against the running call. The notification
* carries no tool call id, so the running call is the only thing it can
- * belong to -- well defined because tools execute one at a time.
+ * belong to: a loop runs its tools one at a time, and when loops of several
+ * threads each have one running, the update's server picks between them. A
+ * call whose server is known and differs never takes it, and an update that
+ * still matches more than one call is dropped, not guessed. (Cowork does not
+ * record servers; its calls take an update whenever they are the only one.)
*/
reportProgress: (update: ToolProgressUpdate) => void
/** Records a display-only diff against the call that produced it. */
recordDiff: (toolCallId: string, diff: string) => void
- /** Ends a turn: nothing still queued will run, so stop showing it as waiting. */
- settleRemaining: () => void
+ /**
+ * Ends `owner`'s turn: nothing it still has queued will run, so stop showing
+ * it as waiting. Another loop's queue is left alone.
+ */
+ settleRemaining: (owner?: string) => void
+ /**
+ * Drops the state of `owner`'s settled calls, for when the cards showing them
+ * unmount. Its queued and running calls are kept: the loop may still be going
+ * in the background, and what it settles from now on is there on return.
+ */
+ releaseSettled: (owner?: string) => void
reset: () => void
}
+/** The owner of calls enqueued without one. */
+const NO_OWNER = ''
+
+export function isToolCallRunning(timing: ToolCallTiming | undefined): boolean {
+ return timing?.startedAt !== undefined && timing.endedAt === undefined
+}
+
/**
* The call currently executing, if any. Returns a primitive, so it is safe to
* use directly as a store selector.
@@ -65,13 +94,25 @@ export function findRunningToolCallId(
timings: Record<string, ToolCallTiming>
): string | undefined {
for (const [id, timing] of Object.entries(timings)) {
- if (timing.startedAt !== undefined && timing.endedAt === undefined) {
- return id
- }
+ if (isToolCallRunning(timing)) return id
}
return undefined
}
+/**
+ * A waiting call's place in its own loop's line (0 = next), or -1 once the
+ * executor has reached it. Another thread's queued calls are not ahead of it.
+ */
+export function queuePositionOf(
+ snapshot: Pick<ToolCallRuntimeSnapshot, 'queue' | 'timings'>,
+ toolCallId: string
+): number {
+ const owner = snapshot.timings[toolCallId]?.owner ?? NO_OWNER
+ return snapshot.queue
+ .filter((id) => (snapshot.timings[id]?.owner ?? NO_OWNER) === owner)
+ .indexOf(toolCallId)
+}
+
/**
* Timing and queue position for in-flight tool calls -- the two things the SDK
* message part cannot express, since a queued call and a running one are both
@@ -84,34 +125,40 @@ export const useToolCallRuntime = create<ToolCallRuntimeState>()((set) => ({
progress: {},
diffs: {},
- enqueue: (toolCallIds) =>
+ enqueue: (toolCallIds, owner = NO_OWNER) =>
set((s) => {
const timings = { ...s.timings }
- // A turn cannot start while a call from the previous one is still
- // running, so anything left running was stranded by a severed turn (HMR
- // in dev, a reload, a crashed executor). Left alone it keeps ticking and
- // steals the running slot from every later call.
- const stranded = findRunningToolCallId(timings)
- if (stranded) {
- timings[stranded] = { ...timings[stranded], endedAt: Date.now() }
+ const owns = (id: string) => (timings[id]?.owner ?? NO_OWNER) === owner
+ // A turn cannot start while a call from the same loop's previous one is
+ // still running, so anything of this owner left running was stranded by a
+ // severed turn (HMR in dev, a reload, a crashed executor). Left alone it
+ // keeps ticking and steals the running slot from every later call.
+ for (const [id, timing] of Object.entries(timings)) {
+ if (owns(id) && isToolCallRunning(timing)) {
+ timings[id] = { ...timing, endedAt: Date.now() }
+ }
}
return {
- queue: [...toolCallIds],
+ queue: [...s.queue.filter((id) => !owns(id)), ...toolCallIds],
timings: {
...timings,
- ...Object.fromEntries(toolCallIds.map((id) => [id, {}])),
+ ...Object.fromEntries(toolCallIds.map((id) => [id, { owner }])),
},
}
}),
- markRunning: (toolCallId) =>
+ markRunning: (toolCallId, server) =>
set((s) =>
s.timings[toolCallId]
? {
queue: s.queue.filter((id) => id !== toolCallId),
timings: {
...s.timings,
- [toolCallId]: { ...s.timings[toolCallId], startedAt: Date.now() },
+ [toolCallId]: {
+ ...s.timings[toolCallId],
+ startedAt: Date.now(),
+ ...(server ? { server } : {}),
+ },
},
}
: s
@@ -134,22 +181,58 @@ export const useToolCallRuntime = create<ToolCallRuntimeState>()((set) => ({
reportProgress: (update) =>
set((s) => {
- const running = findRunningToolCallId(s.timings)
- return running ? { progress: { ...s.progress, [running]: update } } : s
+ let running = Object.keys(s.timings).filter((id) => {
+ const timing = s.timings[id]
+ return (
+ isToolCallRunning(timing) &&
+ (timing.server === undefined || timing.server === update.server)
+ )
+ })
+ if (running.length > 1) {
+ running = running.filter((id) => s.timings[id].server === update.server)
+ }
+ return running.length === 1
+ ? { progress: { ...s.progress, [running[0]]: update } }
+ : s
}),
recordDiff: (toolCallId, diff) =>
set((s) => ({ diffs: { ...s.diffs, [toolCallId]: diff } })),
- settleRemaining: () =>
+ settleRemaining: (owner = NO_OWNER) =>
set((s) => {
- if (s.queue.length === 0) return s
+ const settled = s.queue.filter(
+ (id) => (s.timings[id]?.owner ?? NO_OWNER) === owner
+ )
+ if (settled.length === 0) return s
const now = Date.now()
const timings = { ...s.timings }
- for (const id of s.queue) {
+ for (const id of settled) {
timings[id] = { ...timings[id], endedAt: now }
}
- return { queue: [], timings }
+ return { queue: s.queue.filter((id) => !settled.includes(id)), timings }
+ }),
+
+ releaseSettled: (owner = NO_OWNER) =>
+ set((s) => {
+ const released = new Set(
+ Object.keys(s.timings).filter(
+ (id) =>
+ (s.timings[id].owner ?? NO_OWNER) === owner &&
+ !s.queue.includes(id) &&
+ !isToolCallRunning(s.timings[id])
+ )
+ )
+ if (released.size === 0) return s
+ const keep = <T>(record: Record<string, T>) =>
+ Object.fromEntries(
+ Object.entries(record).filter(([id]) => !released.has(id))
+ )
+ return {
+ timings: keep(s.timings),
+ progress: keep(s.progress),
+ diffs: keep(s.diffs),
+ }
}),
reset: () => set({ queue: [], timings: {}, progress: {}, diffs: {} }),
diff --git a/web-app/src/lib/__tests__/custom-chat-transport-turn-model.test.ts b/web-app/src/lib/__tests__/custom-chat-transport-turn-model.test.ts
new file mode 100644
index 000000000..009e758c8
--- /dev/null
+++ b/web-app/src/lib/__tests__/custom-chat-transport-turn-model.test.ts
@@ -0,0 +1,216 @@
+import { describe, expect, it, vi, beforeEach } from 'vitest'
+import type { UIMessage } from '@ai-sdk/react'
+import type * as ProviderCaps from '@/lib/providerCaps'
+
+// #9311: a tool-using turn keeps running when the user opens another thread,
+// and opening it moves the global model selection to that thread's model. The
+// turn's automatic follow-up must still go to the model and provider the turn
+// started on, never to the open thread's (possibly remote) one.
+
+const h = vi.hoisted(() => ({
+ serviceHub: null as unknown,
+ selection: {
+ selectedProvider: 'llamacpp',
+ selectedModel: { id: 'local-model', capabilities: [] as string[] },
+ },
+ createModelMock: vi.fn(async (modelId: string) => ({ modelId })),
+}))
+
+h.serviceHub = {
+ mcp: () => ({ getTools: vi.fn(async () => []) }),
+ rag: () => ({ getTools: async () => [] }),
+}
+
+const providers: Record<string, { provider: string; models: unknown[] }> = {
+ llamacpp: { provider: 'llamacpp', models: [] },
+ openai: { provider: 'openai', models: [] },
+}
+
+vi.mock('@/hooks/useServiceHub', () => ({
+ useServiceStore: { getState: () => ({ serviceHub: h.serviceHub }) },
+}))
+vi.mock('@/hooks/useToolAvailable', () => ({
+ useToolAvailable: {
+ getState: () => ({
+ getDisabledTools: () => [],
+ getDefaultDisabledTools: () => [],
+ }),
+ },
+}))
+vi.mock('@/hooks/useModelProvider', () => ({
+ useModelProvider: {
+ getState: () => ({
+ ...h.selection,
+ getProviderByName: (name: string) => providers[name],
+ }),
+ },
+}))
+vi.mock('@/hooks/useAssistant', () => ({
+ useAssistant: { getState: () => ({ currentAssistant: null }) },
+}))
+vi.mock('@/hooks/useThreads', () => ({
+ useThreads: { getState: () => ({ threads: {} }) },
+}))
+vi.mock('@/hooks/useAttachments', () => ({
+ useAttachments: { getState: () => ({ enabled: false }) },
+}))
+vi.mock('@/hooks/useMCPServers', () => ({
+ useMCPServers: { getState: () => ({ settings: {} }) },
+}))
+vi.mock('@/hooks/useAppState', () => ({
+ useAppState: {
+ getState: () => new Proxy({}, { get: () => () => undefined }),
+ },
+}))
+vi.mock('@janhq/tauri-plugin-llamacpp-api', () => ({
+ getLoadedModels: vi.fn(async () => ['local-model']),
+ unloadLlamaModel: vi.fn(),
+}))
+vi.mock('@/lib/extension', () => ({
+ ExtensionManager: { getInstance: () => ({ get: () => null }) },
+}))
+vi.mock('@/lib/mcp-orchestrator', () => ({
+ mcpOrchestrator: { getRelevantTools: vi.fn() },
+}))
+vi.mock('@/lib/mcp-router-model-filter', () => ({
+ isRouterModelSelectable: () => false,
+}))
+vi.mock('@/lib/reasoningProviderOptions', () => ({
+ buildReasoningProviderOptions: () => undefined,
+}))
+vi.mock('@/lib/providerCaps', async (importOriginal) => ({
+ ...(await importOriginal<typeof ProviderCaps>()),
+ isPredefinedRemoteProvider: () => false,
+ getProviderApiType: () => 'openai',
+}))
+vi.mock('../model-factory', () => ({
+ ModelFactory: { createModel: h.createModelMock },
+}))
+vi.mock('ai', async () => {
+ const actual = await vi.importActual<typeof import('ai')>('ai')
+ return {
+ ...actual,
+ streamText: () => ({
+ toUIMessageStream: () => new ReadableStream({ start: (c) => c.close() }),
+ }),
+ }
+})
+
+import { CustomChatTransport } from '../custom-chat-transport'
+
+const user = (id: string, text: string): UIMessage =>
+ ({ id, role: 'user', parts: [{ type: 'text', text }] }) as UIMessage
+
+// The assistant turn whose tool call has its result: what the SDK resubmits
+// automatically as the turn's follow-up.
+const toolTurn = (id: string): UIMessage =>
+ ({
+ id,
+ role: 'assistant',
+ parts: [
+ { type: 'step-start' },
+ {
+ type: 'tool-fetch',
+ toolCallId: `${id}-call`,
+ state: 'output-available',
+ input: {},
+ output: 'result',
+ },
+ ],
+ }) as UIMessage
+
+const send = (
+ transport: CustomChatTransport,
+ messages: UIMessage[],
+ trigger: 'submit-message' | 'regenerate-message' = 'submit-message'
+) =>
+ transport.sendMessages({
+ chatId: 'thread-a',
+ messages,
+ abortSignal: undefined,
+ trigger,
+ messageId: undefined,
+ })
+
+const openOtherThreadOnRemoteModel = () => {
+ h.selection = {
+ selectedProvider: 'openai',
+ selectedModel: { id: 'remote-model', capabilities: [] },
+ }
+}
+
+describe('CustomChatTransport: a turn keeps its model', () => {
+ beforeEach(() => {
+ h.createModelMock.mockClear()
+ h.selection = {
+ selectedProvider: 'llamacpp',
+ selectedModel: { id: 'local-model', capabilities: [] },
+ }
+ })
+
+ it('sends the follow-up to the model the turn started on', async () => {
+ const transport = new CustomChatTransport(undefined, 'thread-a')
+ await send(transport, [user('u1', 'look it up')])
+
+ openOtherThreadOnRemoteModel()
+ await send(transport, [user('u1', 'look it up'), toolTurn('a1')])
+
+ expect(h.createModelMock).toHaveBeenLastCalledWith(
+ 'local-model',
+ providers.llamacpp,
+ expect.anything()
+ )
+ expect(transport.getTurnModelSelection()).toMatchObject({
+ selectedProvider: 'llamacpp',
+ selectedModel: { id: 'local-model' },
+ })
+ })
+
+ it('starts a new turn on the current selection', async () => {
+ const transport = new CustomChatTransport(undefined, 'thread-a')
+ await send(transport, [user('u1', 'look it up')])
+
+ openOtherThreadOnRemoteModel()
+ await send(transport, [user('u1', 'look it up'), toolTurn('a1'), user('u2', 'next')])
+
+ expect(h.createModelMock).toHaveBeenLastCalledWith(
+ 'remote-model',
+ providers.openai,
+ expect.anything()
+ )
+ })
+
+ // Regenerating the reply that followed a tool step sends the same history as
+ // the automatic follow-up did, but the user asked for a new reply: it runs on
+ // the model selected now.
+ it('regenerates a follow-up reply on the current selection', async () => {
+ const transport = new CustomChatTransport(undefined, 'thread-a')
+ await send(transport, [user('u1', 'look it up')])
+
+ openOtherThreadOnRemoteModel()
+ await send(
+ transport,
+ [user('u1', 'look it up'), toolTurn('a1')],
+ 'regenerate-message'
+ )
+
+ expect(h.createModelMock).toHaveBeenLastCalledWith(
+ 'remote-model',
+ providers.openai,
+ expect.anything()
+ )
+ })
+
+ // Nothing to continue: a transport that never ran a turn has no model to keep.
+ it('uses the current selection when no turn has run yet', async () => {
+ const transport = new CustomChatTransport(undefined, 'thread-a')
+ openOtherThreadOnRemoteModel()
+ await send(transport, [user('u1', 'look it up'), toolTurn('a1')])
+
+ expect(h.createModelMock).toHaveBeenLastCalledWith(
+ 'remote-model',
+ providers.openai,
+ expect.anything()
+ )
+ })
+})
diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.ts
index 823a740f9..cbdd2800c 100644
--- a/web-app/src/lib/custom-chat-transport.ts
+++ b/web-app/src/lib/custom-chat-transport.ts
@@ -10,6 +10,7 @@ import {
type LanguageModelUsage,
jsonSchema,
InvalidToolInputError,
+ lastAssistantMessageIsCompleteWithToolCalls,
} from 'ai'
import { repairToolArgs } from './toolCallRepair'
import {
@@ -93,6 +94,11 @@ export type OnFinishCallback = (params: {
message: UIMessage
isAbort?: boolean
}) => void
+/** The provider and model a request runs on. */
+export type ModelSelection = {
+ selectedProvider: string
+ selectedModel: Model | null
+}
/** Partial assistant output replayed as a prefill to resume a stopped turn. */
export type ContinuationContent = { text?: string; reasoning?: string }
export type ServiceHub = {
@@ -879,6 +885,13 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
* clear loading/stream state that the newer request has already set.
*/
private streamGeneration = 0
+ /**
+ * The model the current turn started on. A tool loop's follow-up requests
+ * reuse it rather than the global selection, which follows the open thread:
+ * a turn that carries on after the user opens another thread must not be
+ * sent to that thread's model or provider (#9311).
+ */
+ private turnModelSelection: ModelSelection | null = null
constructor(systemMessage?: string, threadId?: string) {
this.systemMessage = systemMessage
@@ -887,10 +900,36 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
// Tools will be loaded when updateRagToolsAvailability is called with model capabilities
}
- protected getModelSelection(): { selectedProvider: string; selectedModel: Model | null } {
+ protected getModelSelection(): ModelSelection {
return useModelProvider.getState()
}
+ /** The model of this transport's current (or last) turn, if one has run. */
+ getTurnModelSelection(): ModelSelection | null {
+ return this.turnModelSelection
+ }
+
+ /**
+ * The model a request runs on. The SDK's automatic follow-up, sent once the
+ * turn's tool calls all have outcomes, continues that turn on its model.
+ * Anything else starts a turn on the current selection, including a
+ * regenerate, whose history can end on the same completed tool calls.
+ */
+ private resolveTurnModelSelection(
+ messages: UIMessage[],
+ trigger: 'submit-message' | 'regenerate-message'
+ ): ModelSelection {
+ const continuesTurn =
+ this.turnModelSelection !== null &&
+ trigger === 'submit-message' &&
+ lastAssistantMessageIsCompleteWithToolCalls({ messages })
+ if (!continuesTurn) {
+ const { selectedProvider, selectedModel } = this.getModelSelection()
+ this.turnModelSelection = { selectedProvider, selectedModel }
+ }
+ return this.turnModelSelection!
+ }
+
setLastUserMessage(message: string): void {
this.lastUserMessage = message
}
@@ -1013,7 +1052,14 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
}
}
- async refreshTools(abortSignal?: AbortSignal) {
+ /**
+ * @param modelSelection The model the tools are built for: the request's own
+ * when called from sendMessages, else the current selection.
+ */
+ async refreshTools(
+ abortSignal?: AbortSignal,
+ modelSelection: ModelSelection = this.getModelSelection()
+ ) {
// Resolve the memory digest before the prompt is built: the builder is
// sync, so it reads the snapshot this await guarantees. Error-safe and
// cached inside agentTools, so this is one IPC round-trip per store change.
@@ -1032,7 +1078,7 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
return disabledToolKeys.includes(toolKey)
}
- const selectedModel = this.getModelSelection().selectedModel
+ const selectedModel = modelSelection.selectedModel
const modelSupportsTools = selectedModel?.capabilities?.includes('tools') ?? this.modelSupportsTools
// Only load tools if model supports them
@@ -1340,7 +1386,11 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
// Capture the effective provider name early so the Anthropic serial
// tool-use repair later uses the same value that was used to create the
// model, even if the user switches provider mid-request.
- const { selectedModel, selectedProvider: providerId } = this.getModelSelection()
+ const turnModelSelection = this.resolveTurnModelSelection(
+ options.messages,
+ options.trigger
+ )
+ const { selectedModel, selectedProvider: providerId } = turnModelSelection
const modelId = selectedModel?.id
const effectiveProviderName = providerId
const provider = useModelProvider.getState().getProviderByName(providerId)
@@ -1438,7 +1488,7 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
throw engineFailure('model-errors:createModelFailed', error)
}
- await this.refreshTools(options.abortSignal)
+ await this.refreshTools(options.abortSignal, turnModelSelection)
// Split assistant turns that place text after tool calls into separate
// messages. Required by the Claude API (tool_use / tool_result pairing) and
diff --git a/web-app/src/lib/thread-title-summarizer.ts b/web-app/src/lib/thread-title-summarizer.ts
index 66a7f104e..b6742de9a 100644
--- a/web-app/src/lib/thread-title-summarizer.ts
+++ b/web-app/src/lib/thread-title-summarizer.ts
@@ -1,6 +1,7 @@
import { generateText } from 'ai'
import { ModelFactory } from './model-factory'
import { useModelProvider } from '@/hooks/useModelProvider'
+import type { ModelSelection } from './custom-chat-transport'
import { BACKGROUND_THREAD_ID, CHAT_SLOT_ID } from '@/constants/models'
const MAX_TITLE_WORDS = 10
@@ -56,16 +57,20 @@ export function cleanTitle(raw: string): string | null {
/**
* Generate a summarized thread title from the user's first message.
- * Uses the currently selected model via a non-streaming generateText call.
+ * Uses the given model (the thread's own, which a turn finishing in the
+ * background no longer shares with the open thread), else the currently
+ * selected one, via a non-streaming generateText call.
* Returns null on failure or if the signal is aborted.
*/
export async function generateThreadTitle(
transcript: string,
- abortSignal: AbortSignal
+ abortSignal: AbortSignal,
+ modelSelection?: ModelSelection
): Promise<string | null> {
try {
- const { selectedModel, selectedProvider, getProviderByName } =
- useModelProvider.getState()
+ const { getProviderByName } = useModelProvider.getState()
+ const { selectedModel, selectedProvider } =
+ modelSelection ?? useModelProvider.getState()
if (!selectedModel || !selectedProvider) {
console.warn('[ThreadTitle] No model/provider selected')
return null
diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsx
index 72d6231f6..cd8a264cd 100644
--- a/web-app/src/routes/threads/$threadId.tsx
+++ b/web-app/src/routes/threads/$threadId.tsx
@@ -122,16 +122,17 @@ const CHAT_STATUS = {
const TITLE_REFRESH_EVERY_N_ASSISTANT_MESSAGES = 4
// What an explicit Stop aborts to end a thread's running tool call, by thread.
-// Aborted only by Stop: leaving a thread ends its tool loop (see the cleanup in
-// ThreadDetail) but must not cancel a call that is running, whose result still
-// lands in the retained session. Keyed by thread because the route component is
-// reused across thread switches, so a Stop in one thread can never reach
-// another's call, and the Stop button still works after coming back.
+// Aborted by Stop, and by deleting the thread, where the call's result has
+// nowhere to go; leaving the thread does not. Keyed by thread because the route
+// component is reused across thread switches, so a Stop in one thread can never
+// reach another's call, and the Stop button still works after coming back.
const toolStopControllers = new Map<string, AbortController>()
-// What ends a thread's tool loop: aborted when the thread is left or stopped, it
-// stops the loop between calls and the auto follow-up of the turn. Keyed by
-// thread for the same reason as the Stop controllers; a ref on the component
+// What ends a thread's tool loop: aborted when the thread is stopped or deleted,
+// it stops the loop between calls and the auto follow-up of the turn. Leaving
+// the thread does not abort it: the turn keeps running in the retained chat
+// session, as a reply without tools does, and is there when the user returns.
+// Keyed by thread for the same reason as the Stop controllers; a ref on the component
// would be shared by every thread's loop and let one thread's Stop, or one
// thread's loop finishing, end another's.
const toolLoopControllers = new Map<string, AbortController>()
@@ -144,6 +145,63 @@ const toolLoopTurns = new WeakMap<AbortController, string>()
// runtime, drop the approvals or clear the busy flag the newer loop now owns.
const toolLoopGeneration = new Map<string, number>()
+// What a handler that starts a generation leaves for the onFinish that ends it,
+// by thread. A turn can finish in the background while another thread is open
+// (#9311), and the route component is reused across thread switches, so with a
+// component ref that onFinish would consume what was set up for the open thread:
+// link its reply under the other thread's message, or delete a message of the
+// other thread as the "stale partial" of a Continue.
+//
+// The message the next assistant reply hangs off (versioning).
+const pendingAssistantParents = new Map<string, string>()
+// The stopped assistant message a Continue replaces in place.
+const continueReplaceIds = new Map<string, string>()
+// The partial output of a reply that stopped at the context limit, for the
+// "Increase Context Size" button to resume from.
+const pendingContinuations = new Map<
+ string,
+ { message: UIMessage; text: string }
+>()
+// The n_ctx the thread's local model launched with, read by isContextLimitStop.
+const launchedCtxLens = new Map<string, number | undefined>()
+// The thread's in-flight title summarization. Only that thread's own activity
+// cancels it.
+const titleAborts = new Map<string, AbortController>()
+
+const takeFrom = <V,>(map: Map<string, V>, threadId: string) => {
+ const value = map.get(threadId)
+ map.delete(threadId)
+ return value
+}
+const setOrClear = (
+ map: Map<string, string>,
+ threadId: string,
+ value: string | null
+) => {
+ if (value == null) map.delete(threadId)
+ else map.set(threadId, value)
+}
+const abortTitle = (threadId: string) => {
+ takeFrom(titleAborts, threadId)?.abort()
+}
+// A deleted thread's hand-offs go with its chat session. Every thread that sets
+// one has a session: the route creates it while rendering the thread.
+useChatSessions.subscribe((state) => {
+ for (const threadId of titleAborts.keys()) {
+ if (!state.sessions[threadId]) abortTitle(threadId)
+ }
+ for (const map of [
+ pendingAssistantParents,
+ continueReplaceIds,
+ pendingContinuations,
+ launchedCtxLens,
+ ]) {
+ for (const threadId of map.keys()) {
+ if (!state.sessions[threadId]) map.delete(threadId)
+ }
+ }
+})
+
// Approval promises started in onToolCall (so the popup appears immediately) and
// awaited by the onFinish execution loop, keyed by thread and then toolCallId.
// Executing stays in onFinish so the tool result lands on a completed assistant
@@ -165,7 +223,7 @@ const forgetApprovals = (threadId: string) => {
}
// Recorded for a call that never ran because its chat was closed (the thread was
-// left) rather than because the user refused or stopped it.
+// deleted) rather than because the user refused or stopped it.
const CHAT_CLOSED_TOOL_ERROR =
'Tool call cancelled: the chat was closed before it ran.'
@@ -179,8 +237,8 @@ const SHELL_DISABLED_TOOL_ERROR =
// Rewrites a turn that is already stored with what its live copy holds now. A
// turn is stored before its tools run, so a call's outcome (result, error,
// stopped) only reaches storage when a later reply rewrites the turn; when no
-// reply follows (Stop, or the thread was left) it has to be written here, or the
-// call reloads as "Running" after a restart.
+// reply follows (Stop) it has to be written here, or the call reloads as
+// "Running" after a restart.
function rewriteStoredTurn(
threadId: string,
message: UIMessage,
@@ -208,6 +266,17 @@ function serverForTool(toolName: string): string | undefined {
?.server
}
+// The model a thread's turn runs on. A turn can finish in the background while
+// another thread is open, and the global selection follows the open thread.
+function turnModelOf(threadId: string) {
+ return (
+ useChatSessions
+ .getState()
+ .sessions[threadId]?.transport.getTurnModelSelection() ??
+ useModelProvider.getState()
+ )
+}
+
// How a call to a chat agent tool name is served. The switch is enforced where
// the command would run, not only where the tool is offered: a call can still
// arrive from replayed history or from a turn in flight when it flips. Such a
@@ -305,7 +374,10 @@ function ThreadDetail() {
const getSessionData = useChatSessions((state) => state.getSessionData)
const sessionData = getSessionData(threadId)
- const titleAbortRef = useRef<AbortController | null>(null)
+ // The thread on screen. onFinish is a closure of the render that created its
+ // chat, so this is how a turn finishing in the background tells it is not.
+ const openThreadIdRef = useRef(threadId)
+ openThreadIdRef.current = threadId
// Check if we should follow up with tool calls (respects abort signal)
const followUpMessage = useCallback(
@@ -341,9 +413,22 @@ function ThreadDetail() {
}, [thread])
// Holds the partial assistant message while the model reloads after a
- // context-limit hit, so the user sees it instead of a blank gap.
- const [pendingContinueMessage, setPendingContinueMessage] =
- useState<UIMessage | null>(null)
+ // context-limit hit, so the user sees it instead of a blank gap. Tagged with
+ // its thread: the turn it resumes can finish while another thread is open, so
+ // it is shown only in its own thread and cleared by that turn.
+ const [pendingContinue, setPendingContinue] = useState<{
+ threadId: string
+ message: UIMessage
+ } | null>(null)
+ const pendingContinueMessage =
+ pendingContinue && pendingContinue.threadId === threadId
+ ? pendingContinue.message
+ : null
+ const clearPendingContinue = useCallback(
+ (ofThread: string) =>
+ setPendingContinue((prev) => (prev?.threadId === ofThread ? null : prev)),
+ []
+ )
const [contextLimitError, setContextLimitError] = useState<Error | null>(null)
// Per-thread so the shimmer survives navigating away and back while the
// embedding run is still in flight.
@@ -383,30 +468,12 @@ function ThreadDetail() {
const backendError = isLlamacppActive ? backendErrorRaw : undefined
const handleContextSizeIncreaseRef = useRef<(() => void) | null>(null)
- const setContinueFromContentRef = useRef<((content: string) => void) | null>(
- null
- )
const setChatMessagesRef = useRef<
((updater: (prev: UIMessage[]) => UIMessage[]) => void) | null
>(null)
- // Holds the partial assistant output captured when the model stops with
- // `finishReason === 'length'`. Consumed by `handleContextSizeIncrease` so
- // the manual "Increase Context Size" button resumes from where the stream
- // stopped rather than regenerating from scratch.
- const pendingContinuationRef = useRef<{
- message: UIMessage
- text: string
- } | null>(null)
- // Set before a generation when the resulting assistant message should be
- // linked to a specific parent (versioning). Consumed once in onFinish.
- const pendingAssistantParentId = useRef<string | null>(null)
- // n_ctx the local model launched with. onFinish is synchronous, so it is
- // fetched once streaming starts (the model is loaded by then).
- const launchedCtxLenRef = useRef<number | undefined>(undefined)
- // Holds the id of a stopped assistant message being resumed. Continuing must
- // extend the turn in place, not fork a new version, so onFinish deletes this
- // stale partial once the continued reply is persisted.
- const continueReplaceIdRef = useRef<string | null>(null)
+ // The per-turn hand-offs to onFinish (pending parent, Continue target,
+ // context-limit partial, launched n_ctx) are module maps keyed by thread; see
+ // pendingAssistantParents.
// Use the AI SDK chat hook
const {
@@ -447,14 +514,13 @@ function ThreadDetail() {
const finishReason = msgMeta?.finishReason as string | undefined
// Consume once per generation so a skipped persist (error/empty) can't
// leak the replace target into a later, unrelated turn.
- const continueReplaceId = continueReplaceIdRef.current
- continueReplaceIdRef.current = null
+ const continueReplaceId = takeFrom(continueReplaceIds, threadId) ?? null
// Context limit hit: send partial content as prefill so the model continues
// from where it stopped. The stream wrapper injects it as the first text-delta
// of the new message, so the user sees the partial text immediately.
if (!isAbort && finishReason === 'length') {
- const providerState = useModelProvider.getState()
+ const providerState = turnModelOf(threadId)
const isContextLimit = isContextLimitStop({
provider: providerState.selectedProvider,
usage: msgMeta?.usage as
@@ -463,7 +529,7 @@ function ThreadDetail() {
ctxLen:
providerState.selectedModel?.settings?.ctx_len?.controller_props
?.value,
- launchedCtxLen: launchedCtxLenRef.current,
+ launchedCtxLen: launchedCtxLens.get(threadId),
})
if (isContextLimit) {
@@ -475,17 +541,21 @@ function ThreadDetail() {
.map((p) => (p as { type: 'text'; text: string }).text)
.join('')
if (partialText) {
- pendingContinuationRef.current = { message, text: partialText }
+ pendingContinuations.set(threadId, { message, text: partialText })
}
+ // Stamped on the thread's own messages, so a thread that finished in
+ // the background shows the banner when the user returns to it.
stampContextErrorOnThread(threadId)
- setContextLimitError(new Error(OUT_OF_CONTEXT_SIZE))
+ if (openThreadIdRef.current === threadId) {
+ setContextLimitError(new Error(OUT_OF_CONTEXT_SIZE))
+ }
return
}
// Non-context-limit length truncation: fall through and persist the
// partial marked as stopped so the "Continue" button can resume it.
}
- if (!isAbort && message.parts.length) setPendingContinueMessage(null)
+ if (!isAbort && message.parts.length) clearPendingContinue(threadId)
// Nothing would be persisted for an empty reply, so without this the
// turn silently vanishes and the user cannot tell it failed. The error
@@ -494,8 +564,8 @@ function ThreadDetail() {
// the error into its metadata.error, which hydration restores on reload.
if (isEmptyReply({ message, isAbort, isError, finishReason })) {
const userTurnId =
- pendingAssistantParentId.current ?? resolveAssistantParent(undefined)
- pendingAssistantParentId.current = null
+ takeFrom(pendingAssistantParents, threadId) ??
+ resolveAssistantParent(undefined)
if (userTurnId) {
useMessageErrors
.getState()
@@ -547,9 +617,8 @@ function ThreadDetail() {
useMessages.getState().getMessages(threadId),
message.id,
continueReplaceId,
- pendingAssistantParentId.current
+ takeFrom(pendingAssistantParents, threadId) ?? null
)
- pendingAssistantParentId.current = null
let parentForAssistant = continuation.parentId
@@ -674,22 +743,44 @@ function ThreadDetail() {
// Tools run one at a time below, so the rest are genuinely queued.
useToolCallRuntime
.getState()
- .enqueue(sessionData.tools.map((tc) => tc.toolCallId))
+ .enqueue(
+ sessionData.tools.map((tc) => tc.toolCallId),
+ threadId
+ )
}
- // The outcomes handed to the chat, so a loop that ends after the thread was
- // left can wait for them to land before it persists the turn.
- const outputs: Promise<unknown>[] = []
+ // Deleting the thread removes its chat session, and that ends the loop:
+ // nothing may run, prompt, or call the model again for a thread that is
+ // gone. Released approvals resolve as denied, so the loop is not left
+ // waiting on a prompt nobody can see, and a call still running is ended
+ // as by Stop, since its result has nowhere to go. Leaving the thread ends
+ // nothing.
+ let released = false
+ const unwatchSession = hasTools
+ ? useChatSessions.subscribe((state) => {
+ if (released || state.sessions[threadId]) return
+ released = true
+ callController.abort()
+ stopController.abort()
+ forgetApprovals(threadId)
+ useToolApprovalRequests.getState().clearPendingForThread(threadId)
+ })
+ : undefined
+ // An explicit Stop, which settles the turn's calls itself (see
+ // handleStop). Deleting the thread also aborts the Stop signal, to end the
+ // running call, but the loop still records the calls it cuts short.
+ const stoppedByUser = () => stopSignal.aborted && !released
+
const record = (output: Parameters<typeof addToolOutput>[0]) => {
- outputs.push(Promise.resolve(addToolOutput(output)))
+ void addToolOutput(output)
}
;(async () => {
for (const toolCall of sessionData.tools) {
- // Stop settles the turn's calls itself (see handleStop).
- if (stopSignal.aborted) break
- // The thread was left before this call's turn came: it will not run,
- // and without an outcome its card would read "Running" on return.
+ if (stoppedByUser()) break
+ // The thread was deleted before this call's turn came: it will not run.
+ // Recorded as the chat closing, like a cut-short approval below, so
+ // every call of the turn ends with an outcome.
if (signal.aborted) {
record({
state: 'output-error',
@@ -726,18 +817,18 @@ function ThreadDetail() {
serverForTool(toolName)
))
approvalsOf(threadId).delete(toolCall.toolCallId)
- // Only an explicit Stop skips the result. Leaving the thread also
- // resolves a pending approval as denied; that denial must still be
- // recorded, or the call stays "Running" with nothing running.
- if (stopSignal.aborted) break
+ // Only an explicit Stop skips the result. Deleting the thread also
+ // resolves a pending approval as denied, recorded below as the chat
+ // closing rather than as the user's refusal.
+ if (stoppedByUser()) break
if (!approved) {
record({
state: 'output-error',
tool: toolCall.toolName,
toolCallId: toolCall.toolCallId,
- // Leaving the thread resolves a pending approval as denied; that
- // was not the user's decision and the model reads this later.
+ // Deleting the thread resolves a pending approval as denied; that
+ // was not the user's decision.
errorText: signal.aborted
? CHAT_CLOSED_TOOL_ERROR
: 'Tool execution denied by user',
@@ -747,13 +838,15 @@ function ThreadDetail() {
// Timed from here, not from approval, so a long approval wait is
// not reported as the tool being slow.
- useToolCallRuntime.getState().markRunning(toolCall.toolCallId)
+ useToolCallRuntime
+ .getState()
+ .markRunning(toolCall.toolCallId, serverForTool(toolName))
// A tool result is injected into conversation history verbatim, so a
// page-sized one can exhaust the context on its own. This is the
// budget the window this model actually has affords; it is narrowed
// against the user's configured ceiling where the result is built.
- const ctxLen = useModelProvider.getState().selectedModel?.settings
+ const ctxLen = turnModelOf(threadId).selectedModel?.settings
?.ctx_len?.controller_props?.value
const maxOutputChars = deriveToolOutputCap(
typeof ctxLen === 'number' ? ctxLen : undefined
@@ -850,19 +943,9 @@ function ThreadDetail() {
}
}
- // The thread was left: no follow-up reply will run to rewrite the stored
- // turn, so write what the live copy holds (results and errors included).
- // This turn by its id, not the last message: the user may have come back
- // and started another turn before this one's calls returned.
- if (signal.aborted && !stopSignal.aborted) {
- await Promise.allSettled(outputs)
- const turn = useChatSessions
- .getState()
- .sessions[threadId]?.chat.messages.find((m) => m.id === message.id)
- if (turn?.role === 'assistant') rewriteStoredTurn(threadId, turn, false)
- }
+ unwatchSession?.()
if (!hasTools || toolLoopGeneration.get(threadId) !== generation) return
- useToolCallRuntime.getState().settleRemaining()
+ useToolCallRuntime.getState().settleRemaining(threadId)
forgetApprovals(threadId)
sessionData.tools = []
// Only this loop's own: a later loop of the thread may have replaced it.
@@ -877,8 +960,9 @@ function ThreadDetail() {
if (error.name !== 'AbortError') {
console.error('Tool call error:', error)
}
+ unwatchSession?.()
if (!hasTools || toolLoopGeneration.get(threadId) !== generation) return
- useToolCallRuntime.getState().settleRemaining()
+ useToolCallRuntime.getState().settleRemaining(threadId)
forgetApprovals(threadId)
sessionData.tools = []
if (toolLoopControllers.get(threadId) === callController) {
@@ -924,8 +1008,9 @@ function ThreadDetail() {
.join('\n\n') ||
useThreads.getState().threads[threadId]?.title
if (inputText) {
- const provider = useModelProvider.getState().selectedProvider
- const modelId = useModelProvider.getState().selectedModel?.id
+ const turnModel = turnModelOf(threadId)
+ const provider = turnModel.selectedProvider
+ const modelId = turnModel.selectedModel?.id
;(async () => {
if (provider === 'llamacpp' && modelId) {
let idle = false
@@ -941,16 +1026,22 @@ function ThreadDetail() {
}
if (!idle) return
}
- titleAbortRef.current?.abort()
+ // Deleted while waiting for the engine: nothing to name, and the
+ // deletion has already cancelled what it could.
+ if (!useChatSessions.getState().sessions[threadId]) return
+ titleAborts.get(threadId)?.abort()
const controller = new AbortController()
- titleAbortRef.current = controller
+ titleAborts.set(threadId, controller)
const title = await generateThreadTitle(
inputText,
- controller.signal
+ controller.signal,
+ turnModel
)
+ if (titleAborts.get(threadId) === controller) {
+ titleAborts.delete(threadId)
+ }
if (!title || controller.signal.aborted) return
useThreads.getState().updateThread(threadId, { title })
- titleAbortRef.current = null
})()
}
}
@@ -1007,9 +1098,8 @@ function ThreadDetail() {
// drops the approval prompts, and settles whatever tool call never got to
// finish so its card stops saying "Running" (and stays settled on reload).
const handleStop = useCallback(() => {
- // The Stop controller outlives the thread-switch cleanup, which deletes the
- // loop controller, so it is what says which turn is still running a call.
- // One already aborted was stopped earlier; its loop is only winding down.
+ // The Stop controller is what says which turn is still running a call. One
+ // already aborted was stopped earlier; its loop is only winding down.
const stopping = toolStopControllers.get(threadId)
const running = stopping?.signal.aborted ? undefined : stopping
// The turn whose call this aborts; with none running (the reply is still
@@ -1117,15 +1207,19 @@ function ThreadDetail() {
useEffect(() => {
if (status !== 'streaming') return
- launchedCtxLenRef.current = undefined
- const modelId = selectedModel?.id
- const ext = getLocalPropsExtension(selectedProvider)
+ launchedCtxLens.delete(threadId)
+ // The model the streaming turn runs on, which a follow-up keeps even if
+ // the selection has changed since the turn started.
+ const { selectedModel: turnModel, selectedProvider: turnProvider } =
+ turnModelOf(threadId)
+ const modelId = turnModel?.id
+ const ext = getLocalPropsExtension(turnProvider)
if (!modelId || !ext?.getModelProps) return
let cancelled = false
ext
.getModelProps(modelId)
.then((props) => {
- if (!cancelled) launchedCtxLenRef.current = readCtxLen(props?.nCtx)
+ if (!cancelled) launchedCtxLens.set(threadId, readCtxLen(props?.nCtx))
})
.catch(() => {
// Router unreachable: isContextLimitStop falls back to its default.
@@ -1133,7 +1227,7 @@ function ThreadDetail() {
return () => {
cancelled = true
}
- }, [status, selectedProvider, selectedModel?.id])
+ }, [status, threadId])
useEffect(() => {
if (status === 'streaming') {
@@ -1143,8 +1237,6 @@ function ThreadDetail() {
useEffect(() => {
setCurrentThreadId(threadId)
- titleAbortRef.current?.abort()
- titleAbortRef.current = null
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [threadId])
@@ -1241,28 +1333,29 @@ function ThreadDetail() {
}, [threadId, serviceHub])
useEffect(() => {
+ // A title being summarized is left to finish: it belongs to its thread,
+ // not to the screen, and only writes that thread's title.
return () => {
- titleAbortRef.current?.abort()
setCurrentThreadId(undefined)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
- // The route component is reused across thread switches (no remount), so tear
- // down the in-flight tool loop and release approvals waiting on the thread we
- // are leaving. Cleanup captures the previous threadId; without this the
- // unresolved approval promise keeps that thread marked busy forever.
+ // The route component is reused across thread switches (no remount). Leaving
+ // a thread must not end its turn: its tool loop, any approval it waits on and
+ // the follow-up reply live in module state and the retained chat session, so
+ // they carry on in the background and the approval prompt is still there on
+ // return (#9311). Only Stop or deleting the thread ends the loop.
useEffect(() => {
return () => {
- toolLoopControllers.get(threadId)?.abort()
- toolLoopControllers.delete(threadId)
- forgetApprovals(threadId)
- useToolApprovalRequests.getState().clearPendingForThread(threadId)
- // Drop per-thread timing/progress/diff state from the shared runtime
- // store. The cards for the thread we leave are unmounting, so a thread a
- // later visit cannot show another thread's diff. (code.tsx re-hydrates
+ // Drop the left thread's settled timing/progress/diff state from the
+ // shared runtime store: its cards are unmounting. Calls its loop still
+ // has queued or running are kept for its return. (code.tsx re-hydrates
// its own diffs on mount, so it is unaffected by clearing here.)
- useToolCallRuntime.getState().reset()
+ useToolCallRuntime.getState().releaseSettled(threadId)
+ // Cowork's calls have no owner and nothing else releases them; this is
+ // where the whole store used to be reset, so they go at the same point.
+ useToolCallRuntime.getState().releaseSettled()
}
}, [threadId])
@@ -1296,8 +1389,7 @@ function ThreadDetail() {
draft: string = text
) => {
// Cancel any in-flight title summarization so it doesn't compete with this request
- titleAbortRef.current?.abort()
- titleAbortRef.current = null
+ abortTitle(threadId)
// Get all attachments from the store (media transferred from the
// new-thread key, plus documents).
@@ -1502,7 +1594,7 @@ function ThreadDetail() {
...baseUserMessage,
metadata: { ...(baseUserMessage.metadata ?? {}), parentId },
}
- pendingAssistantParentId.current = messageId
+ pendingAssistantParents.set(threadId, messageId)
}
addMessage(userMessage)
@@ -1714,8 +1806,7 @@ function ThreadDetail() {
const idx = siblings.findIndex((m) => m.id === messageId)
const next = siblings[idx + dir]
if (!next) return
- titleAbortRef.current?.abort()
- titleAbortRef.current = null
+ abortTitle(threadId)
clearBannerErrors()
setActiveBranch(next)
syncActivePath()
@@ -1764,11 +1855,14 @@ function ThreadDetail() {
}
if (contextLimitError) setContextLimitError(null)
if (hadBannerError) stripBannerMetadata()
- titleAbortRef.current?.abort()
- titleAbortRef.current = null
+ abortTitle(threadId)
ensureBranched()
- pendingAssistantParentId.current = resolveAssistantParent(messageId)
+ setOrClear(
+ pendingAssistantParents,
+ threadId,
+ resolveAssistantParent(messageId)
+ )
endRunningTools()
regenerate(messageId ? { messageId } : undefined)
@@ -1780,6 +1874,7 @@ function ThreadDetail() {
contextLimitError,
ensureBranched,
resolveAssistantParent,
+ threadId,
]
)
@@ -1800,10 +1895,10 @@ function ThreadDetail() {
const reasoning = collect('reasoning')
if (!text && !reasoning) return
setContinueFromContent({ text, reasoning })
- continueReplaceIdRef.current = messageId
+ continueReplaceIds.set(threadId, messageId)
handleRegenerate(messageId)
},
- [chatMessages, setContinueFromContent, handleRegenerate]
+ [chatMessages, setContinueFromContent, handleRegenerate, threadId]
)
// Editing forks a new sibling version (the original + its subtree are kept).
@@ -1815,8 +1910,7 @@ function ThreadDetail() {
if (!target) return
useMessageErrors.getState().clearError(messageId)
- titleAbortRef.current?.abort()
- titleAbortRef.current = null
+ abortTitle(threadId)
const newId = generateId()
const sibling = makeSibling(target, {
@@ -1828,7 +1922,7 @@ function ThreadDetail() {
setActiveBranch(sibling)
if (target.role === 'user') {
- pendingAssistantParentId.current = newId
+ pendingAssistantParents.set(threadId, newId)
syncActivePath()
endRunningTools()
regenerate({ messageId: newId })
@@ -1843,6 +1937,7 @@ function ThreadDetail() {
syncActivePath,
regenerate,
endRunningTools,
+ threadId,
]
)
@@ -1944,11 +2039,14 @@ function ThreadDetail() {
// Consume any pending partial captured at the `finishReason === 'length'`
// event so the regenerate resumes from where the stream stopped, and the
// "Growing the Mind…" shimmer renders while the model reloads.
- const pending = pendingContinuationRef.current
- pendingContinuationRef.current = null
+ // The prefill goes on this thread's own transport: the user may have
+ // opened another thread while the model reloaded.
+ const pending = takeFrom(pendingContinuations, threadId)
if (pending) {
- setContinueFromContentRef.current?.(pending.text)
- setPendingContinueMessage(pending.message)
+ useChatSessions
+ .getState()
+ .sessions[threadId]?.transport.setContinueFromContent(pending.text)
+ setPendingContinue({ threadId, message: pending.message })
}
setTimeout(() => {
@@ -1965,7 +2063,6 @@ function ThreadDetail() {
// Keep refs in sync so onFinish always calls the latest versions
handleContextSizeIncreaseRef.current = handleContextSizeIncrease
- setContinueFromContentRef.current = setContinueFromContent
setChatMessagesRef.current = setChatMessages
useEffect(() => {
@@ -1982,14 +2079,12 @@ function ThreadDetail() {
}, [oomError, backendError, contextLimitError, status, stop])
useEffect(() => {
- if (status === 'streaming' && pendingContinuationRef.current) {
+ if (status === 'streaming') {
// The new turn is now flowing; drop the saved partial so it can't be
// consumed by a later, unrelated "Increase Context Size" click.
- pendingContinuationRef.current = null
- }
- if (status === 'error' && pendingContinueMessage) {
- setPendingContinueMessage(null)
+ pendingContinuations.delete(threadId)
}
+ if (status === 'error') clearPendingContinue(threadId)
}, [status]) // eslint-disable-line react-hooks/exhaustive-deps
// Message queue: auto-send the next queued message when the stream finishes.
diff --git a/web-app/src/routes/threads/__tests__/$threadId.test.tsx b/web-app/src/routes/threads/__tests__/$threadId.test.tsx
index 2143cba46..5c2045282 100644
--- a/web-app/src/routes/threads/__tests__/$threadId.test.tsx
+++ b/web-app/src/routes/threads/__tests__/$threadId.test.tsx
@@ -1,5 +1,5 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
-import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { render, screen, act, waitFor } from '@testing-library/react'
import '@testing-library/jest-dom'
import React from 'react'
@@ -94,6 +94,19 @@ const h = vi.hoisted(() => {
}
const useChatSessionsMock: any = (selector: any) => selector(chatSessionsState)
useChatSessionsMock.getState = () => chatSessionsState
+ // Listeners the route registers to learn a thread's session was removed (the
+ // thread was deleted); removeChatSession below notifies them.
+ const chatSessionListeners = new Set<(state: any) => void>()
+ useChatSessionsMock.subscribe = (listener: (state: any) => void) => {
+ chatSessionListeners.add(listener)
+ return () => chatSessionListeners.delete(listener)
+ }
+ const removeChatSession = (threadId: string) => {
+ const rest = { ...chatSessionsState.sessions }
+ delete rest[threadId]
+ chatSessionsState.sessions = rest
+ for (const listener of [...chatSessionListeners]) listener(chatSessionsState)
+ }
const attachmentsState: any = {
getAttachments: vi.fn(() => []),
@@ -158,6 +171,7 @@ const h = vi.hoisted(() => {
useModelProviderMock,
chatSessionsState,
useChatSessionsMock,
+ removeChatSession,
attachmentsState,
useChatAttachmentsMock,
useAttachmentsState,
@@ -498,6 +512,10 @@ const renderComponent = () => {
describe('ThreadDetail route', () => {
beforeEach(() => {
+ // Leaving a thread no longer ends its tool loop, so a loop an earlier test
+ // left waiting would keep its approvals. Deleting the threads ends them.
+ h.removeChatSession('thread-1')
+ h.removeChatSession('thread-2')
vi.clearAllMocks()
h.chatState.messages = []
h.chatState.status = 'ready'
@@ -568,10 +586,12 @@ describe('ThreadDetail route', () => {
expect(h.threadsState.setCurrentThreadId).toHaveBeenLastCalledWith(undefined)
})
- it('clears this thread pending tool approvals on unmount', () => {
+ // Leaving is not Stop: an approval the thread waits on stays up, and is still
+ // there to answer on return (#9311).
+ it('keeps this thread pending tool approvals on unmount', () => {
const { unmount } = renderComponent()
unmount()
- expect(h.toolApprovalState.clearPendingForThread).toHaveBeenCalledWith('thread-1')
+ expect(h.toolApprovalState.clearPendingForThread).not.toHaveBeenCalled()
})
it('renders messages passed through useChat', () => {
@@ -992,6 +1012,167 @@ describe('ThreadDetail route', () => {
})
})
+ // #9311: a turn keeps running after the user opens another thread, and its
+ // onFinish is a closure of the render that created its chat. What the open
+ // thread set up for its own next reply, and its banners, must not be taken
+ // or shown by the background thread's turn.
+ describe('a turn finishing behind another thread', () => {
+ const Component = () => Route.component as React.ComponentType
+ const text = (value: string) => [
+ { type: 'text', text: { value, annotations: [] } },
+ ]
+ const threadB = [
+ { id: 'b-u1', role: 'user', created_at: 1, content: text('q'), metadata: { parentId: null } },
+ { id: 'b-a1', role: 'assistant', created_at: 2, content: text('r'), metadata: { parentId: 'b-u1' } },
+ ]
+ const openThreadB = (rerender: (ui: React.ReactElement) => void) => {
+ const C = Component()
+ h.routeParams.threadId = 'thread-2'
+ h.threadsState.threads['thread-2'] = {
+ id: 'thread-2',
+ title: 'Other',
+ metadata: {},
+ assistants: [],
+ model: { id: 'gpt-x', provider: 'openai' },
+ }
+ const threadA = h.messagesState.getMessages()
+ h.messagesState.getMessages = vi.fn((id?: string) =>
+ id === 'thread-2' ? threadB : threadA
+ )
+ h.chatState.messages = [
+ { id: 'b-u1', role: 'user', parts: [{ type: 'text', text: 'q' }] },
+ { id: 'b-a1', role: 'assistant', parts: [{ type: 'text', text: 'r' }] },
+ ]
+ rerender(<C />)
+ }
+ const persisted = (id: string) =>
+ h.messagesState.addMessage.mock.calls
+ .map((c: any[]) => c[0])
+ .find((m: any) => m.id === id)
+
+ afterEach(() => {
+ h.routeParams.threadId = 'thread-1'
+ delete h.threadsState.threads['thread-2']
+ })
+
+ it("leaves the open thread's pending reply parent for its own reply", () => {
+ const { rerender } = renderComponent()
+ const onFinishA = (h as any).capturedOnFinish
+ openThreadB(rerender)
+ // The open thread starts a new version of its reply.
+ act(() => {
+ screen.getByTestId('regen-b-a1').click()
+ })
+
+ act(() => {
+ onFinishA({
+ message: { id: 'a-bg', role: 'assistant', parts: [{ type: 'text', text: 'A' }], metadata: {} },
+ isAbort: false,
+ })
+ })
+ expect(persisted('a-bg').thread_id).toBe('thread-1')
+ expect(persisted('a-bg').metadata.parentId).not.toBe('b-u1')
+
+ act(() => {
+ ;(h as any).capturedOnFinish({
+ message: { id: 'b-a2', role: 'assistant', parts: [{ type: 'text', text: 'B' }], metadata: {} },
+ isAbort: false,
+ })
+ })
+ expect(persisted('b-a2').metadata.parentId).toBe('b-u1')
+ })
+
+ // The partial shown while the model reloads after "Increase Context Size"
+ // belongs to its thread: never shown in another, and cleared by its own
+ // turn finishing even while another thread is open.
+ it("keeps the reload placeholder to its own thread", async () => {
+ h.modelProviderState.selectedProvider = 'llamacpp'
+ const C = Route.component as React.ComponentType
+ const { rerender } = renderComponent()
+ const onFinishA = (h as any).capturedOnFinish
+ act(() => {
+ onFinishA({
+ message: {
+ id: 'a-len',
+ role: 'assistant',
+ parts: [{ type: 'text', text: 'partial answer' }],
+ metadata: {
+ finishReason: 'length',
+ usage: { inputTokens: 30000, outputTokens: 4000 },
+ },
+ },
+ isAbort: false,
+ isError: false,
+ })
+ })
+ const realModels = hub.models as () => Record<string, unknown>
+ hub.models = () => ({
+ ...realModels(),
+ updateModelSettings: vi.fn().mockResolvedValue(undefined),
+ })
+ // The click regenerates after a delay; it must not fire in a later test.
+ vi.useFakeTimers()
+ try {
+ await act(async () => {
+ screen.getByText('Increase Context Size').click()
+ })
+ } finally {
+ vi.clearAllTimers()
+ vi.useRealTimers()
+ hub.models = realModels
+ }
+ // In front, its own thread shows the partial while the model reloads.
+ h.chatState.status = 'submitted'
+ rerender(<C />)
+ expect(screen.getByTestId('message-a-len')).toBeInTheDocument()
+
+ openThreadB(rerender)
+ expect(screen.queryByTestId('message-a-len')).toBeNull()
+
+ // A's resumed reply finishes behind B.
+ act(() => {
+ onFinishA({
+ message: { id: 'a-len', role: 'assistant', parts: [{ type: 'text', text: 'partial answer, done' }], metadata: {} },
+ isAbort: false,
+ })
+ })
+ h.routeParams.threadId = 'thread-1'
+ h.chatState.messages = []
+ rerender(<C />)
+ expect(screen.queryByTestId('message-a-len')).toBeNull()
+ })
+
+ it("does not show its context-limit banner on the open thread", () => {
+ h.modelProviderState.selectedProvider = 'llamacpp'
+ const { rerender } = renderComponent()
+ const onFinishA = (h as any).capturedOnFinish
+ openThreadB(rerender)
+
+ act(() => {
+ onFinishA({
+ message: {
+ id: 'a-len',
+ role: 'assistant',
+ parts: [{ type: 'text', text: 'partial answer' }],
+ metadata: {
+ finishReason: 'length',
+ usage: { inputTokens: 30000, outputTokens: 4000 },
+ },
+ },
+ isAbort: false,
+ isError: false,
+ })
+ })
+
+ expect(screen.queryByText('Increase Context Size')).toBeNull()
+ // Stamped on its own thread instead, which shows it on return.
+ const stamped = h.messagesState.updateMessage.mock.calls
+ .map((c: any[]) => c[0])
+ .find((m: any) => m.metadata?.contextError)
+ expect(stamped?.id).toBe('u1')
+ })
+ })
+
describe('empty replies (#9228)', () => {
beforeEach(() => {
useMessageErrors.getState().clearAll()
@@ -1280,11 +1461,11 @@ describe('ThreadDetail route', () => {
renderComponent()
await act(async () => {
- await (h as any).capturedOnToolCall(toolCall('tc1'))
+ await (h as any).capturedOnToolCall(toolCall('tc-server'))
})
expect(h.toolApprovalState.requestApproval).toHaveBeenCalledWith(
- 'tc1',
+ 'tc-server',
'fetch',
'thread-1',
'fetch-server'
@@ -1631,6 +1812,61 @@ describe('ThreadDetail route', () => {
expect(cancel).not.toHaveBeenCalled()
})
+ // Deleting the thread is the one other way a running call ends: its result
+ // would have nowhere to go.
+ it('deleting the thread cancels its running MCP call', async () => {
+ h.appStateState.mcpToolNames = new Set(['fetch'])
+ const cancel = vi.fn().mockResolvedValue(undefined)
+ hub.mcp = () =>
+ ({
+ callToolWithCancellation: () => ({
+ promise: new Promise(() => {}),
+ cancel,
+ token: 't',
+ }),
+ }) as never
+
+ renderComponent()
+ await arrive('tcA')
+ await act(async () => {
+ await finishWithToolCalls()
+ })
+ expect(cancel).not.toHaveBeenCalled()
+ await act(async () => {
+ h.removeChatSession('thread-1')
+ })
+
+ expect(cancel).toHaveBeenCalledTimes(1)
+ })
+
+ // The left thread's finished cards unmount, so their runtime state goes;
+ // a call its loop is still running stays for its return, and another
+ // thread's state is not touched.
+ it("leaving a thread releases only its own settled runtime state", async () => {
+ const runtime = useToolCallRuntime.getState()
+ runtime.enqueue(['a-done', 'a-running'], 'thread-1')
+ runtime.markRunning('a-done')
+ runtime.markSettled('a-done')
+ runtime.markRunning('a-running')
+ runtime.enqueue(['b-done'], 'thread-3')
+ runtime.markRunning('b-done')
+ runtime.markSettled('b-done')
+ const Component = Route.component as React.ComponentType
+
+ try {
+ const { rerender } = renderComponent()
+ h.routeParams.threadId = 'thread-2'
+ rerender(<Component />)
+ } finally {
+ h.routeParams.threadId = 'thread-1'
+ }
+
+ const { timings } = useToolCallRuntime.getState()
+ expect(timings['a-done']).toBeUndefined()
+ expect(timings['a-running']?.startedAt).toBeDefined()
+ expect(timings['b-done']).toBeDefined()
+ })
+
// A turn of a thread that was left can finish in the background, after
// another thread is shown. A Stop there is that thread's, and must not end
// the background thread's loop: its queued calls still run.
@@ -1843,6 +2079,7 @@ describe('ThreadDetail route', () => {
])
h.chatSessionsState.sessions = {
'thread-1': {
+ transport: { getTurnModelSelection: () => null },
chat: {
messages: [
{
@@ -1911,6 +2148,7 @@ describe('ThreadDetail route', () => {
])
h.chatSessionsState.sessions = {
'thread-1': {
+ transport: { getTurnModelSelection: () => null },
chat: {
messages: [
{
@@ -1980,6 +2218,7 @@ describe('ThreadDetail route', () => {
// Live: the result has just landed, and a second call is unfinished.
h.chatSessionsState.sessions = {
'thread-1': {
+ transport: { getTurnModelSelection: () => null },
chat: {
messages: [
{ id: 'u1', role: 'user', parts: [{ type: 'text', text: 'go' }] },
@@ -2033,9 +2272,9 @@ describe('ThreadDetail route', () => {
}
})
- // Leaving the thread resolves a pending approval as denied. It must be
+ // Deleting the thread resolves a pending approval as denied. It must be
// recorded, or the call stays "Running" with nothing running, but not as a
- // refusal by the user: the model reads this on the next turn.
+ // refusal by the user.
it('records a cut-short approval as the chat closing, not a user denial', async () => {
h.appStateState.mcpToolNames = new Set(['fetch'])
let decide: (approved: boolean) => void = () => {}
@@ -2044,12 +2283,17 @@ describe('ThreadDetail route', () => {
)
h.mockAddToolOutput.mockClear()
- const { unmount } = renderComponent()
+ renderComponent()
await arrive('tcA')
await act(async () => {
await finishWithToolCalls()
})
- unmount()
+ await act(async () => {
+ h.removeChatSession('thread-1')
+ })
+ expect(h.toolApprovalState.clearPendingForThread).toHaveBeenCalledWith(
+ 'thread-1'
+ )
await act(async () => {
decide(false)
})
@@ -2063,67 +2307,100 @@ describe('ThreadDetail route', () => {
)
})
- // No reply follows once the thread is left, and a reply is what rewrites a
- // stored turn. Without a rewrite here the call reloads as "Running".
- it('stores the outcome of a call cut short by leaving the thread', async () => {
+ // #9311: leaving a thread while its tool call runs must not end the turn.
+ // The call's result lands and the reply continues: the follow-up check,
+ // which the SDK runs as the result lands, still says to send.
+ it('leaving the thread lets the turn continue after its tool call', async () => {
+ h.appStateState.mcpToolNames = new Set(['fetch'])
+ let finish: (r: unknown) => void = () => {}
+ hub.mcp = () =>
+ ({
+ callToolWithCancellation: () => ({
+ promise: new Promise((resolve) => (finish = resolve)),
+ cancel: vi.fn().mockResolvedValue(undefined),
+ token: 't',
+ }),
+ }) as never
+ const Component = Route.component as React.ComponentType
+
+ try {
+ const { rerender } = renderComponent()
+ const followUpA = (h as any).capturedSendAutomaticallyWhen
+ const followUps: boolean[] = []
+ h.mockAddToolOutput.mockImplementation(() => {
+ followUps.push(followUpA({ messages: [] }))
+ })
+ await arrive('tcA')
+ await act(async () => {
+ await finishWithToolCalls()
+ })
+
+ h.routeParams.threadId = 'thread-2'
+ rerender(<Component />)
+ await act(async () => {
+ finish({ error: '', content: [{ type: 'text', text: 'ok' }] })
+ })
+
+ expect(h.mockAddToolOutput).toHaveBeenCalledWith(
+ expect.objectContaining({ toolCallId: 'tcA', output: expect.anything() })
+ )
+ expect(followUps).toEqual([true])
+ } finally {
+ h.routeParams.threadId = 'thread-1'
+ h.mockAddToolOutput.mockReset()
+ }
+ })
+
+ // An approval the left thread waits on stays pending, so the user can
+ // answer it on return; the call then runs and the reply continues.
+ it('leaving the thread keeps its pending approval answerable', async () => {
h.appStateState.mcpToolNames = new Set(['fetch'])
let decide: (approved: boolean) => void = () => {}
h.toolApprovalState.requestApproval = vi.fn(
() => new Promise<boolean>((resolve) => (decide = resolve))
)
- h.messagesState.getMessages = vi.fn(() => [
- { id: 'a-tc', role: 'assistant', content: [], metadata: {} },
- ])
- h.chatSessionsState.sessions = {
- 'thread-1': {
- chat: {
- messages: [
- {
- id: 'a-tc',
- role: 'assistant',
- parts: [
- {
- type: 'tool-fetch',
- toolCallId: 'tcA',
- input: {},
- state: 'output-error',
- errorText: 'Tool call cancelled: the chat was closed before it ran.',
- },
- ],
- },
- // The user came back and started another turn meanwhile.
- {
- id: 'a-new',
- role: 'assistant',
- parts: [{ type: 'text', text: 'a newer turn' }],
- },
- ],
+ const started: string[] = []
+ hub.mcp = () =>
+ ({
+ callToolWithCancellation: (call: any) => {
+ started.push(call.toolName)
+ return {
+ promise: Promise.resolve({ error: '', content: [] }),
+ cancel: vi.fn().mockResolvedValue(undefined),
+ token: 't',
+ }
},
- },
- }
- h.messagesState.updateMessage.mockClear()
+ }) as never
+ h.mockAddToolOutput.mockClear()
+ const Component = Route.component as React.ComponentType
try {
- const { unmount } = renderComponent()
+ const { rerender } = renderComponent()
await arrive('tcA')
await act(async () => {
await finishWithToolCalls()
})
- unmount()
+
+ h.routeParams.threadId = 'thread-2'
+ rerender(<Component />)
+ expect(h.toolApprovalState.clearPendingForThread).not.toHaveBeenCalled()
+
+ h.routeParams.threadId = 'thread-1'
+ rerender(<Component />)
await act(async () => {
- decide(false)
+ decide(true)
})
+
+ expect(started).toEqual(['fetch'])
+ expect(h.mockAddToolOutput).toHaveBeenCalledWith(
+ expect.objectContaining({ toolCallId: 'tcA' })
+ )
+ expect(h.mockAddToolOutput).not.toHaveBeenCalledWith(
+ expect.objectContaining({ state: 'output-error' })
+ )
} finally {
- h.chatSessionsState.sessions = {}
+ h.routeParams.threadId = 'thread-1'
}
-
- const stored = h.messagesState.updateMessage.mock.calls
- .map((c: any[]) => c[0])
- .find((m: any) => m.id === 'a-tc')
- expect(stored.metadata.toolErrors).toEqual({
- tcA: expect.stringContaining('chat was closed'),
- })
- expect(stored.metadata.stopped).toBeUndefined()
})
// The approval promises are shared by every thread's loop. A thread whose
@@ -2177,12 +2454,14 @@ describe('ThreadDetail route', () => {
)
h.mockAddToolOutput.mockClear()
- const { unmount } = renderComponent()
+ renderComponent()
await arrive('tcA', 'tcB')
await act(async () => {
await finishWithToolCalls()
})
- unmount()
+ await act(async () => {
+ h.removeChatSession('thread-1')
+ })
await act(async () => {
decide.tcA(false)
})