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(web-app): merge late Cowork threads into the store instead of replacing it

Akarshan Biswas411d91ead608
diff --git a/web-app/src/lib/__tests__/refreshThreads.test.ts b/web-app/src/lib/__tests__/refreshThreads.test.ts
index 25fb368c7..539b2269c 100644
--- a/web-app/src/lib/__tests__/refreshThreads.test.ts
+++ b/web-app/src/lib/__tests__/refreshThreads.test.ts
@@ -2,42 +2,96 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
const h = vi.hoisted(() => ({
fetchThreads: vi.fn(),
- setThreads: vi.fn(),
- existing: {} as Record<string, unknown>,
}))
vi.mock('@/hooks/useServiceHub', () => ({
- getServiceHub: () => ({ threads: () => ({ fetchThreads: h.fetchThreads }) }),
+ getServiceHub: () => ({
+ threads: () => ({ fetchThreads: h.fetchThreads, deleteThread: vi.fn() }),
+ path: () => ({ sep: () => '/' }),
+ }),
}))
-vi.mock('@/hooks/useThreads', () => ({
- useThreads: {
- getState: () => ({ setThreads: h.setThreads, threads: h.existing }),
- },
+vi.mock('@/hooks/useAgentMode', () => ({
+ useAgentMode: { getState: () => ({ removeThread: vi.fn() }) },
+}))
+vi.mock('@/stores/chat-session-store', () => ({
+ useChatSessions: { getState: () => ({ removeSession: vi.fn() }) },
+}))
+vi.mock('@/hooks/useAppState', () => ({
+ useAppState: { getState: () => ({ clearThreadState: vi.fn() }) },
+}))
+vi.mock('@/lib/agentTools', () => ({ cleanupThreadWorkspace: vi.fn() }))
+vi.mock('@/lib/extensions/host', () => ({
+ getExtensionHost: () => ({ services: { get: () => undefined } }),
}))
import { refreshThreadsFromBackend } from '../refreshThreads'
+import { useThreads } from '@/hooks/useThreads'
+
+const t = (id: string, extra: Partial<Thread> = {}) =>
+ ({ id, title: `T ${id}`, updated: 1, ...extra }) as unknown as Thread
describe('refreshThreadsFromBackend', () => {
beforeEach(() => {
h.fetchThreads.mockReset()
- h.setThreads.mockReset()
- h.existing = {}
+ useThreads.setState({ threads: {}, searchIndex: null })
})
- it('replaces the store with the freshly listed threads', async () => {
- h.fetchThreads.mockResolvedValue([{ id: 'a' }, { id: 'b' }])
+ it('adds the freshly listed threads that the store lacks', async () => {
+ h.fetchThreads.mockResolvedValue([t('a'), t('b')])
await refreshThreadsFromBackend()
- expect(h.setThreads).toHaveBeenCalledWith([{ id: 'a' }, { id: 'b' }])
+ expect(Object.keys(useThreads.getState().threads).sort()).toEqual(['a', 'b'])
+ })
+
+ it('never replaces a thread the store already has: renames and favourites stay', async () => {
+ useThreads.setState({
+ threads: { a: t('a', { title: 'Renamed', isFavorite: true }) },
+ })
+ h.fetchThreads.mockResolvedValue([t('a'), t('late')])
+ await refreshThreadsFromBackend()
+ const { threads } = useThreads.getState()
+ expect(threads.a.title).toBe('Renamed')
+ expect(threads.a.isFavorite).toBe(true)
+ expect(threads.late).toBeDefined()
+ })
+
+ it('keeps a thread created while the fetch was in flight', async () => {
+ useThreads.setState({ threads: { a: t('a') } })
+ let release!: (v: Thread[]) => void
+ h.fetchThreads.mockReturnValue(new Promise((r) => (release = r)))
+ const pending = refreshThreadsFromBackend()
+ // The user starts a new chat; the backend list was read before it existed.
+ useThreads.setState((s) => ({ threads: { ...s.threads, fresh: t('fresh') } }))
+ release([t('a'), t('late')])
+ await pending
+ expect(Object.keys(useThreads.getState().threads).sort()).toEqual([
+ 'a',
+ 'fresh',
+ 'late',
+ ])
+ })
+
+ it('does not bring back a thread deleted while the fetch was in flight', async () => {
+ useThreads.setState({ threads: { a: t('a'), gone: t('gone') } })
+ let release!: (v: Thread[]) => void
+ h.fetchThreads.mockReturnValue(new Promise((r) => (release = r)))
+ const pending = refreshThreadsFromBackend()
+ useThreads.getState().deleteThread('gone')
+ // One created and deleted inside the window is not resurrected either.
+ useThreads.setState((s) => ({ threads: { ...s.threads, brief: t('brief') } }))
+ useThreads.getState().deleteThread('brief')
+ release([t('a'), t('gone'), t('brief'), t('late')])
+ await pending
+ expect(Object.keys(useThreads.getState().threads).sort()).toEqual(['a', 'late'])
})
- it('never wipes a populated list with an empty result', async () => {
- h.existing = { a: {} }
+ it('an empty result changes nothing', async () => {
+ useThreads.setState({ threads: { a: t('a') } })
h.fetchThreads.mockResolvedValue([])
await refreshThreadsFromBackend()
- expect(h.setThreads).not.toHaveBeenCalled()
+ expect(Object.keys(useThreads.getState().threads)).toEqual(['a'])
})
- it('lets a fetch failure propagate to its caller', async () => {
+ it('lets a fetch failure propagate to its caller and stops watching the store', async () => {
h.fetchThreads.mockRejectedValue(new Error('not ready'))
await expect(refreshThreadsFromBackend()).rejects.toThrow('not ready')
})
diff --git a/web-app/src/lib/refreshThreads.ts b/web-app/src/lib/refreshThreads.ts
index ace82f9ca..f2070a190 100644
--- a/web-app/src/lib/refreshThreads.ts
+++ b/web-app/src/lib/refreshThreads.ts
@@ -2,18 +2,31 @@ import { getServiceHub } from '@/hooks/useServiceHub'
import { useThreads } from '@/hooks/useThreads'
/**
- * Re-list threads from the backend into the thread store. Used when something
+ * Add the threads the backend has and the store lacks. Used when something
* created threads after the first list (the Cowork migration finishing in the
- * background). Like DataProvider's load, an empty result never replaces a
- * populated list. A failure propagates; the caller decides it is non-fatal.
+ * background). A failure propagates; the caller decides it is non-fatal.
+ *
+ * It MERGES, never replaces: the app is already interactive when this runs, so
+ * the store is newer than the fetched list. Threads already in the store keep
+ * their state (renames, favourites, order); a thread created while the fetch
+ * was in flight stays; a thread the store held at any point during the fetch
+ * and no longer holds was deleted meanwhile and is not brought back.
*/
export async function refreshThreadsFromBackend(): Promise<void> {
- const threads = await getServiceHub().threads().fetchThreads()
- if (
- threads.length === 0 &&
- Object.keys(useThreads.getState().threads).length > 0
- ) {
- return
+ // Every id the store held from the start of the fetch on.
+ const seen = new Set(Object.keys(useThreads.getState().threads))
+ const unsubscribe = useThreads.subscribe((state) => {
+ for (const id of Object.keys(state.threads)) seen.add(id)
+ })
+ let fetched: Thread[]
+ try {
+ fetched = await getServiceHub().threads().fetchThreads()
+ } finally {
+ unsubscribe()
}
- useThreads.getState().setThreads(threads)
+ // No await from here: the store cannot change between this read and the write.
+ const current = useThreads.getState().threads
+ const late = fetched.filter((t) => !(t.id in current) && !seen.has(t.id))
+ if (late.length === 0) return
+ useThreads.getState().setThreads([...Object.values(current), ...late])
}