Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(web-app): bound startup's wait for the Cowork migration
Akarshan Biswas45af26c9fc01
diff --git a/web-app/src/lib/__tests__/refreshThreads.test.ts b/web-app/src/lib/__tests__/refreshThreads.test.tsnew file mode 100644index 000000000..25fb368c7--- /dev/null+++ b/web-app/src/lib/__tests__/refreshThreads.test.ts@@ -0,0 +1,44 @@+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 }) }),+}))+vi.mock('@/hooks/useThreads', () => ({+ useThreads: {+ getState: () => ({ setThreads: h.setThreads, threads: h.existing }),+ },+}))++import { refreshThreadsFromBackend } from '../refreshThreads'++describe('refreshThreadsFromBackend', () => {+ beforeEach(() => {+ h.fetchThreads.mockReset()+ h.setThreads.mockReset()+ h.existing = {}+ })++ it('replaces the store with the freshly listed threads', async () => {+ h.fetchThreads.mockResolvedValue([{ id: 'a' }, { id: 'b' }])+ await refreshThreadsFromBackend()+ expect(h.setThreads).toHaveBeenCalledWith([{ id: 'a' }, { id: 'b' }])+ })++ it('never wipes a populated list with an empty result', async () => {+ h.existing = { a: {} }+ h.fetchThreads.mockResolvedValue([])+ await refreshThreadsFromBackend()+ expect(h.setThreads).not.toHaveBeenCalled()+ })++ it('lets a fetch failure propagate to its caller', 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.tsnew file mode 100644index 000000000..ace82f9ca--- /dev/null+++ b/web-app/src/lib/refreshThreads.ts@@ -0,0 +1,19 @@+import { getServiceHub } from '@/hooks/useServiceHub'+import { useThreads } from '@/hooks/useThreads'++/**+ * Re-list threads from the backend into the thread store. 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.+ */+export async function refreshThreadsFromBackend(): Promise<void> {+ const threads = await getServiceHub().threads().fetchThreads()+ if (+ threads.length === 0 &&+ Object.keys(useThreads.getState().threads).length > 0+ ) {+ return+ }+ useThreads.getState().setThreads(threads)+}diff --git a/web-app/src/providers/ServiceHubProvider.tsx b/web-app/src/providers/ServiceHubProvider.tsxindex 3a927adea..60abb11a9 100644--- a/web-app/src/providers/ServiceHubProvider.tsx+++ b/web-app/src/providers/ServiceHubProvider.tsx@@ -4,6 +4,29 @@ import { initializeServiceHubStore } from '@/hooks/useServiceHub'import { hydrateBackendStores } from '@/lib/hydrateStores'import { migrateLocalStorageToBackend } from '@/lib/migrateLocalStorageSettings'import { migrateCoworkSessionsOnStartup } from '@/lib/migrateCoworkSessions'+import { refreshThreadsFromBackend } from '@/lib/refreshThreads'++/**+ * How long startup waits for the Cowork migration. Past it the app renders and+ * the migration keeps running; the thread list is refreshed when it finishes.+ */+export const COWORK_MIGRATION_BUDGET_MS = 3000++/** Resolves with the work's outcome, or with `'timeout'` after `ms`. */+async function withinBudget<T>(+ work: Promise<T>,+ ms: number+): Promise<T | 'timeout'> {+ let timer: ReturnType<typeof setTimeout> | undefined+ const timeout = new Promise<'timeout'>((resolve) => {+ timer = setTimeout(() => resolve('timeout'), ms)+ })+ try {+ return await Promise.race([work, timeout])+ } finally {+ clearTimeout(timer)+ }+}interface ServiceHubProviderProps {children: React.ReactNode@@ -23,9 +46,27 @@ export function ServiceHubProvider({ children }: ServiceHubProviderProps) {// Settings stores use async backend storage; hydrate before rendering// children so no component reads pre-hydration defaults.await hydrateBackendStores()- // One-time copy of Cowork sessions into threads. It must finish before- // children render because they list threads on mount. It never throws.- await migrateCoworkSessionsOnStartup()+ // One-time copy of Cowork sessions into threads. Children list threads+ // on mount, so it is awaited, but only for a bounded time: a huge+ // history must not keep the app from rendering. When it overruns, the+ // rest finishes in the background and the thread list is refreshed+ // then. Neither path throws.+ const migration = migrateCoworkSessionsOnStartup()+ const outcome = await withinBudget(+ migration.catch(() => null),+ COWORK_MIGRATION_BUDGET_MS+ )+ if (outcome === 'timeout') {+ void migration+ .then((late) => {+ if (late && late.migrated.length > 0) {+ return refreshThreadsFromBackend()+ }+ })+ .catch((error) => {+ console.warn('[cowork-migration] late refresh failed:', error)+ })+ }setIsReady(true)}).catch((error) => {diff --git a/web-app/src/providers/__tests__/ServiceHubProvider.test.tsx b/web-app/src/providers/__tests__/ServiceHubProvider.test.tsxindex 166274cfe..71583f521 100644--- a/web-app/src/providers/__tests__/ServiceHubProvider.test.tsx+++ b/web-app/src/providers/__tests__/ServiceHubProvider.test.tsx@@ -1,5 +1,5 @@-import { render, screen, waitFor } from '@testing-library/react'-import { describe, it, expect, vi, beforeEach } from 'vitest'+import { render, screen, waitFor, act } from '@testing-library/react'+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'const h = vi.hoisted(() => ({order: [] as string[],@@ -7,6 +7,7 @@ const h = vi.hoisted(() => ({migrateLocalStorageToBackend: vi.fn(),hydrateBackendStores: vi.fn(),migrateCoworkSessionsOnStartup: vi.fn(),+ refreshThreadsFromBackend: vi.fn(),}))vi.mock('@/services', () => ({@@ -25,7 +26,14 @@ vi.mock('@/lib/migrateCoworkSessions', () => ({migrateCoworkSessionsOnStartup: h.migrateCoworkSessionsOnStartup,}))-import { ServiceHubProvider } from '../ServiceHubProvider'+vi.mock('@/lib/refreshThreads', () => ({+ refreshThreadsFromBackend: h.refreshThreadsFromBackend,+}))++import {+ ServiceHubProvider,+ COWORK_MIGRATION_BUDGET_MS,+} from '../ServiceHubProvider'describe('ServiceHubProvider', () => {beforeEach(() => {@@ -37,6 +45,7 @@ describe('ServiceHubProvider', () => {h.hydrateBackendStores.mockReset().mockImplementation(async () => {h.order.push('hydrate')})+ h.refreshThreadsFromBackend.mockReset().mockResolvedValue(undefined)h.migrateCoworkSessionsOnStartup.mockReset().mockImplementation(async () => {h.order.push('cowork-migration')return null@@ -64,4 +73,97 @@ describe('ServiceHubProvider', () => {)await waitFor(() => expect(screen.getByTestId('child')).toBeTruthy())})++ describe('a slow Cowork migration', () => {+ afterEach(() => {+ vi.useRealTimers()+ })++ const result = (migrated: string[]) => ({+ status: 'complete' as const,+ migrated,+ skipped: [],+ abandoned: [],+ failed: [],+ })++ const deferred = () => {+ let resolve: (r: ReturnType<typeof result>) => void = () => {}+ let reject: (e: Error) => void = () => {}+ const promise = new Promise<ReturnType<typeof result>>((res, rej) => {+ resolve = res+ reject = rej+ })+ return { promise, resolve, reject }+ }++ const mountSlow = () => {+ vi.useFakeTimers({ shouldAdvanceTime: true })+ const d = deferred()+ h.migrateCoworkSessionsOnStartup.mockReturnValue(d.promise)+ render(+ <ServiceHubProvider>+ <div data-testid="child" />+ </ServiceHubProvider>+ )+ return d+ }++ it('does not hold the app past its budget, then refreshes the thread list when it finishes', async () => {+ const d = mountSlow()+ expect(screen.queryByTestId('child')).toBeNull()+ await act(async () => {+ await vi.advanceTimersByTimeAsync(COWORK_MIGRATION_BUDGET_MS + 50)+ })+ expect(screen.getByTestId('child')).toBeTruthy()+ expect(h.refreshThreadsFromBackend).not.toHaveBeenCalled()++ await act(async () => {+ d.resolve(result(['s1']))+ })+ await waitFor(() =>+ expect(h.refreshThreadsFromBackend).toHaveBeenCalledTimes(1)+ )+ })++ it('does not refresh when the late migration copied nothing', async () => {+ const d = mountSlow()+ await vi.advanceTimersByTimeAsync(COWORK_MIGRATION_BUDGET_MS + 50)+ await act(async () => {+ d.resolve(result([]))+ })+ expect(h.refreshThreadsFromBackend).not.toHaveBeenCalled()+ })++ it('a late rejection stays non-throwing', async () => {+ const d = mountSlow()+ await vi.advanceTimersByTimeAsync(COWORK_MIGRATION_BUDGET_MS + 50)+ await act(async () => {+ d.reject(new Error('late boom'))+ })+ expect(screen.getByTestId('child')).toBeTruthy()+ expect(h.refreshThreadsFromBackend).not.toHaveBeenCalled()+ })++ it('a failing refresh stays non-throwing', async () => {+ h.refreshThreadsFromBackend.mockRejectedValue(new Error('refresh boom'))+ const d = mountSlow()+ await vi.advanceTimersByTimeAsync(COWORK_MIGRATION_BUDGET_MS + 50)+ await act(async () => {+ d.resolve(result(['s1']))+ })+ expect(screen.getByTestId('child')).toBeTruthy()+ })++ it('a migration that finishes inside the budget needs no refresh', async () => {+ h.migrateCoworkSessionsOnStartup.mockResolvedValue(result(['s1']))+ render(+ <ServiceHubProvider>+ <div data-testid="child" />+ </ServiceHubProvider>+ )+ await waitFor(() => expect(screen.getByTestId('child')).toBeTruthy())+ expect(h.refreshThreadsFromBackend).not.toHaveBeenCalled()+ })+ })})