Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(web-app): open Cowork on /cowork/$sessionId and keep chat off Cowork threads
Akarshan Biswas043175c06065
diff --git a/web-app/src/__tests__/main.test.tsx b/web-app/src/__tests__/main.test.tsxindex 258c096f0..d5e04fc85 100644--- a/web-app/src/__tests__/main.test.tsx+++ b/web-app/src/__tests__/main.test.tsx@@ -28,6 +28,9 @@ vi.mock('@tauri-apps/api/core', () => ({vi.mock('../routeTree.gen', () => ({routeTree: 'mocked-route-tree',}))+vi.mock('../providers/StartupProvider', () => ({+ StartupProvider: ({ children }: { children: unknown }) => children,+}))vi.mock('../index.css', () => ({}))vi.mock('../i18n', () => ({}))diff --git a/web-app/src/components/left-sidebar/NavCowork.tsx b/web-app/src/components/left-sidebar/NavCowork.tsxindex aa4468684..4fdf3eb65 100644--- a/web-app/src/components/left-sidebar/NavCowork.tsx+++ b/web-app/src/components/left-sidebar/NavCowork.tsx@@ -49,7 +49,6 @@ import {type AnimatedLucidePreset,} from '@/components/animated-icon/animated-lucide'import {- startNewSession,useCoworkSessions,type CoworkSession,} from '@/hooks/useCoworkSessions'@@ -181,20 +180,20 @@ export function NavCowork() {title: string} | null>(null)- const goCowork = useCallback(() => navigate({ to: route.cowork }), [navigate])const newSessionIconRef = useRef<MessageCircleIconHandle>(null)const settingsIconRef = useRef<SettingsIconHandle>(null)+ // A new conversation starts on the home composer; /cowork/$sessionId only+ // opens sessions that already exist.const newSession = () => {- startNewSession(Object.keys(useCoworkRun.getState().runId))- goCowork()+ navigate({ to: route.home })}const selectSession = useCallback((id: string) => {useCoworkSessions.getState().selectSession(id)pruneEmpty()- goCowork()+ navigate({ to: route.coworkSession, params: { sessionId: id } })},- [goCowork]+ [navigate])const items: CoworkNavItem[] = [diff --git a/web-app/src/components/left-sidebar/NavTabs.tsx b/web-app/src/components/left-sidebar/NavTabs.tsxindex faafd626c..a8a57444d 100644--- a/web-app/src/components/left-sidebar/NavTabs.tsx+++ b/web-app/src/components/left-sidebar/NavTabs.tsx@@ -2,7 +2,6 @@ import { useRef } from 'react'import { Link } from '@tanstack/react-router'import { Handshake, HomeIcon, type LucideIcon } from 'lucide-react'import { route, isCoworkRoute } from '@/constants/routes'-import { isCoworkEnabled } from '@/lib/version'import { cn } from '@/lib/utils'import { useTranslation } from '@/i18n/react-i18next-compat'import { useThreads } from '@/hooks/useThreads'@@ -68,10 +67,6 @@ export function NavTabs({ surfacePath }: { surfacePath: string }) {(s) => !threadId || Boolean(s.threads[threadId]))- // Home is the only surface outside the channels that ship Cowork, so there is- // no switcher to render - a lone Home pill is not a choice.- if (!isCoworkEnabled()) return null-const tabs: TabItem[] = [{label: t('common:home'),diff --git a/web-app/src/components/left-sidebar/__tests__/coworkGate.test.tsx b/web-app/src/components/left-sidebar/__tests__/coworkGate.test.tsxdeleted file mode 100644index af5fd5a81..000000000--- a/web-app/src/components/left-sidebar/__tests__/coworkGate.test.tsx+++ /dev/null@@ -1,81 +0,0 @@-import '@testing-library/jest-dom/vitest'-import type { ReactNode } from 'react'-import { beforeEach, expect, it, vi } from 'vitest'-import { render, screen } from '@testing-library/react'--const channel = vi.hoisted(() => ({ cowork: false }))-const navigation = vi.hoisted(() => ({ pathname: '/' }))--vi.mock('@/lib/version', async (importOriginal) => ({- ...(await importOriginal<typeof import('@/lib/version')>()),- isCoworkEnabled: () => channel.cowork,-}))-vi.mock('@tanstack/react-router', () => ({- useLocation: () => ({ pathname: navigation.pathname }),- Link: ({ to, children, ...props }: { to: string; children: ReactNode }) => (- <a {...props} href={to}>- {children}- </a>- ),-}))-vi.mock('@/i18n/react-i18next-compat', () => ({- useTranslation: () => ({ t: (key: string) => key }),-}))-vi.mock('@/hooks/useLeftPanel', () => ({- useLeftPanel: () => ({ open: true }),-}))-vi.mock('@/hooks/useThreads', () => ({- useThreads: (- selector: (state: { threads: Record<string, unknown> }) => unknown- ) => selector({ threads: {} }),-}))-vi.mock('@/stores/titlebar-layout-store', () => ({- useTitlebarLayout: () => 0,-}))-vi.mock('@/containers/DownloadManegement', () => ({- DownloadManagement: () => null,-}))-vi.mock('../NavCowork', () => ({ NavCowork: () => <div>Cowork sessions</div> }))-vi.mock('../NavMain', () => ({ NavMain: () => <div>Chat navigation</div> }))-vi.mock('../NavChats', () => ({ NavChats: () => <div>Chat threads</div> }))-vi.mock('../NavProjects', () => ({ NavProjects: () => null }))-vi.mock('@/components/ui/sidebar', () => {- const Box = ({ children }: { children: ReactNode }) => <div>{children}</div>- return {- Sidebar: Box,- SidebarContent: Box,- SidebarHeader: Box,- SidebarTrigger: () => null,- SidebarRail: () => null,- }-})--import { LeftSidebar } from '..'--beforeEach(() => {- channel.cowork = false- navigation.pathname = '/'-})--it('keeps a Cowork URL on the chat surface on builds that do not ship Cowork', () => {- navigation.pathname = '/cowork'- render(<LeftSidebar />)-- expect(screen.getByText('Chat navigation')).toBeInTheDocument()- expect(screen.getByText('Chat threads')).toBeInTheDocument()- expect(screen.queryByText('Cowork sessions')).not.toBeInTheDocument()- expect(screen.queryByRole('link', { name: 'common:cowork' })).not.toBeInTheDocument()- // The switcher has a single surface left, so it is not rendered at all.- expect(screen.queryByRole('link', { name: 'common:home' })).not.toBeInTheDocument()-})--it('shows the Cowork surface and the tab switcher where Cowork ships', () => {- channel.cowork = true- navigation.pathname = '/cowork'- render(<LeftSidebar />)-- expect(screen.getByText('Cowork sessions')).toBeInTheDocument()- expect(screen.getByRole('link', { name: 'common:cowork' })).toBeInTheDocument()- expect(screen.getByRole('link', { name: 'common:home' })).toBeInTheDocument()- expect(screen.queryByText('Chat threads')).not.toBeInTheDocument()-})diff --git a/web-app/src/components/left-sidebar/index.tsx b/web-app/src/components/left-sidebar/index.tsxindex bf07af4d7..3b0018793 100644--- a/web-app/src/components/left-sidebar/index.tsx+++ b/web-app/src/components/left-sidebar/index.tsx@@ -19,7 +19,6 @@ import { cn } from '@/lib/utils'import { useTitlebarLayout } from '@/stores/titlebar-layout-store'import { useLocation } from '@tanstack/react-router'import { isCoworkRoute, route } from '@/constants/routes'-import { isCoworkEnabled } from '@/lib/version'export function LeftSidebar() {const { open: isLeftPanelOpen } = useLeftPanel()@@ -29,7 +28,7 @@ export function LeftSidebar() {const [lastSurfacePath, setLastSurfacePath] = useState(pathname)if (!inSettings && lastSurfacePath !== pathname) setLastSurfacePath(pathname)const surfacePath = inSettings ? lastSurfacePath : pathname- const isCowork = isCoworkRoute(surfacePath) && isCoworkEnabled()+ const isCowork = isCoworkRoute(surfacePath)// Right-align the header and hide "Jan" when native controls own the top-left// (macOS, or a Linux DE placing buttons left).const leftButtons = useTitlebarLayout((s) => s.layout.left.length)diff --git a/web-app/src/constants/routes.ts b/web-app/src/constants/routes.tsindex a99e9a231..e74ece386 100644--- a/web-app/src/constants/routes.ts+++ b/web-app/src/constants/routes.ts@@ -2,6 +2,7 @@ export const route = {// home as new chat or threadhome: '/',cowork: '/cowork',+ coworkSession: '/cowork/$sessionId',artifacts: '/artifacts',appLogs: '/logs',project: '/project',@@ -40,4 +41,6 @@ export const route = {* instead of falling back to Home. A new Cowork route only has to be added here.*/export const isCoworkRoute = (pathname: string): boolean =>- pathname === route.cowork || pathname === route.artifacts+ pathname === route.cowork ||+ pathname.startsWith(`${route.cowork}/`) ||+ pathname === route.artifactsdiff --git a/web-app/src/routes/cowork.tsx b/web-app/src/containers/CoworkPage.tsxsimilarity index 99%rename from web-app/src/routes/cowork.tsxrename to web-app/src/containers/CoworkPage.tsxindex c2d8bd8e6..0acd5380b 100644--- a/web-app/src/routes/cowork.tsx+++ b/web-app/src/containers/CoworkPage.tsx@@ -1,10 +1,9 @@/* eslint-disable @typescript-eslint/no-explicit-any */-import { createFileRoute, useNavigate } from '@tanstack/react-router'+import { useNavigate } from '@tanstack/react-router'import ChatInput from '@/containers/ChatInput'import HeaderPage from '@/containers/HeaderPage'import { useTranslation } from '@/i18n/react-i18next-compat'import { route } from '@/constants/routes'-import { ensureCoworkEnabled } from '@/lib/coworkAccess'import { useServiceHub } from '@/hooks/useServiceHub'import {Fragment,@@ -157,11 +156,6 @@ import {skillCommandPrefix,} from '@/lib/skillCommands'-export const Route = createFileRoute(route.cowork as any)({- beforeLoad: () => ensureCoworkEnabled(),- component: CoworkPage,-})-// Slash-menu rows share keyboard behavior but expose their category visually.type MenuItemKind = 'skill' | 'command' | 'model'@@ -199,7 +193,11 @@ function sessionMonitorLane(sid: string): MonitorLane {}))}-function CoworkPage() {+/**+ * The Cowork conversation view. It reads the current session from the store;+ * `/cowork/$sessionId` keeps that selection in lockstep with the URL.+ */+export function CoworkPage() {const { t } = useTranslation()const navigate = useNavigate()const serviceHub = useServiceHub()@@ -1697,9 +1695,9 @@ function CoworkPage() {<CoworkBudgetNoticekind="tokens"onCompact={() => void handleCompact()}- onNewSession={() =>- useCoworkSessions.getState().createSession()- }+ // A new conversation starts on the home composer; creating a+ // session here would leave the URL on the old one.+ onNewSession={() => void navigate({ to: route.home })}/>)}</ConversationContent>diff --git a/web-app/src/containers/SettingsMenu.tsx b/web-app/src/containers/SettingsMenu.tsxindex fb8fa1cf3..9adad6210 100644--- a/web-app/src/containers/SettingsMenu.tsx+++ b/web-app/src/containers/SettingsMenu.tsx@@ -22,7 +22,6 @@ import {} from '@tabler/icons-react'import { useMatches, useNavigate } from '@tanstack/react-router'import { cn } from '@/lib/utils'-import { isCoworkEnabled } from '@/lib/version'import { useModelProvider } from '@/hooks/useModelProvider'import { getProviderTitle, isLocalProvider } from '@/lib/utils'@@ -201,15 +200,11 @@ const SettingsMenu = () => {route: route.settings.web_search,icon: IconWorldSearch,},- ...(isCoworkEnabled()- ? [- {- title: 'common:cowork',- route: route.settings.cowork,- icon: IconFolderCode,- },- ]- : []),+ {+ title: 'common:cowork',+ route: route.settings.cowork,+ icon: IconFolderCode,+ },{title: 'common:keyboardShortcuts',route: route.settings.shortcuts,diff --git a/web-app/src/containers/__tests__/SettingsMenu.test.tsx b/web-app/src/containers/__tests__/SettingsMenu.test.tsxindex 182ba54bc..184d327f7 100644--- a/web-app/src/containers/__tests__/SettingsMenu.test.tsx+++ b/web-app/src/containers/__tests__/SettingsMenu.test.tsx@@ -5,14 +5,7 @@ import SettingsMenu from '../SettingsMenu'import { useNavigate, useMatches } from '@tanstack/react-router'import { useModelProvider } from '@/hooks/useModelProvider'-vi.mock('@/lib/version', async (importOriginal) => ({- ...(await importOriginal<typeof import('@/lib/version')>()),- isCoworkEnabled: () => channel.cowork,-}))-// Mock global platform constants - simulate desktop (Tauri) environment-const channel = vi.hoisted(() => ({ cowork: true }))-Object.defineProperty(global, 'IS_IOS', { value: false, writable: true })Object.defineProperty(global, 'IS_ANDROID', { value: false, writable: true })Object.defineProperty(global, 'IS_WEB_APP', { value: false, writable: true })@@ -90,7 +83,6 @@ describe('SettingsMenu', () => {beforeEach(() => {vi.clearAllMocks()- channel.cowork = truevi.mocked(useNavigate).mockReturnValue(mockNavigate)vi.mocked(useMatches).mockReturnValue(mockMatches)@@ -119,18 +111,11 @@ describe('SettingsMenu', () => {expect(screen.getByText('common:privacy')).toBeInTheDocument()})- it('lists the Cowork settings entry where Cowork ships', () => {+ it('lists the Cowork settings entry on every channel', () => {render(<SettingsMenu />)expect(screen.getByText('common:cowork')).toBeInTheDocument()})- it('omits the Cowork settings entry on builds that do not ship Cowork', () => {- channel.cowork = false- render(<SettingsMenu />)- expect(screen.queryByText('common:cowork')).not.toBeInTheDocument()- expect(screen.getByText('common:general')).toBeInTheDocument()- })-it('links to the Extensions settings page', () => {render(<SettingsMenu />)expect(screen.getByText('common:extensions').closest('a')).toHaveAttribute(diff --git a/web-app/src/lib/__tests__/coworkAccess.test.tsx b/web-app/src/lib/__tests__/coworkAccess.test.tsxdeleted file mode 100644index f1af9247d..000000000--- a/web-app/src/lib/__tests__/coworkAccess.test.tsx+++ /dev/null@@ -1,65 +0,0 @@-import { describe, it, expect, vi, beforeEach } from 'vitest'-import {- createMemoryHistory,- createRootRoute,- createRoute,- createRouter,-} from '@tanstack/react-router'--const channel = vi.hoisted(() => ({ cowork: false }))--vi.mock('@/lib/version', async (importOriginal) => ({- ...(await importOriginal<typeof import('@/lib/version')>()),- isCoworkEnabled: () => channel.cowork,-}))--import { ensureCoworkEnabled } from '../coworkAccess'-import { route } from '@/constants/routes'--/**- * The real router over the guarded routes, so a redirect is observable as the- * path the app settles on rather than as an object thrown by the guard.- */-async function routerAt(pathname: string) {- const rootRoute = createRootRoute()- const page = (path: string, beforeLoad?: () => void) =>- createRoute({- getParentRoute: () => rootRoute,- path,- beforeLoad,- component: () => null,- })- const router = createRouter({- routeTree: rootRoute.addChildren([- page(route.home),- page(route.cowork, () => ensureCoworkEnabled()),- page(route.settings.general),- page(route.settings.cowork, () =>- ensureCoworkEnabled(route.settings.general)- ),- ]),- history: createMemoryHistory({ initialEntries: [pathname] }),- })- await router.load()- return router.state.location.pathname-}--beforeEach(() => {- channel.cowork = false-})--describe('ensureCoworkEnabled', () => {- it('lands a bookmarked Cowork URL on Home', async () => {- expect(await routerAt(route.cowork)).toBe(route.home)- })-- it('lands the Cowork settings URL on General settings', async () => {- expect(await routerAt(route.settings.cowork)).toBe(route.settings.general)- })-- it('keeps Cowork URLs routable where Cowork ships', async () => {- channel.cowork = true- expect(await routerAt(route.cowork)).toBe(route.cowork)- expect(await routerAt(route.settings.cowork)).toBe(route.settings.cowork)- })-})diff --git a/web-app/src/lib/__tests__/coworkHandoff.test.ts b/web-app/src/lib/__tests__/coworkHandoff.test.tsnew file mode 100644index 000000000..aa25dda19--- /dev/null+++ b/web-app/src/lib/__tests__/coworkHandoff.test.ts@@ -0,0 +1,59 @@+import { describe, it, expect, beforeEach } from 'vitest'+import {+ claimCoworkHandoff,+ clearCoworkHandoff,+ discardStaleCoworkHandoffs,+ peekCoworkHandoff,+ releaseCoworkHandoff,+ writeCoworkHandoff,+ COWORK_HANDOFF_PREFIX,+} from '../coworkHandoff'++describe('coworkHandoff', () => {+ beforeEach(() => {+ sessionStorage.clear()+ for (const id of ['a', 'b', 'gone']) clearCoworkHandoff(id)+ })++ it('stores text in sessionStorage and returns it without removing it', () => {+ writeCoworkHandoff('a', { text: 'hello', draft: 'hello' })+ expect(peekCoworkHandoff('a')?.text).toBe('hello')+ expect(peekCoworkHandoff('a')?.text).toBe('hello')+ })++ it('never serializes attachments into sessionStorage, but returns them by session id', () => {+ const files = [{ type: 'file' as const, mediaType: 'image/png', url: 'data:image/png;base64,AAAA' }]+ writeCoworkHandoff('a', { text: 'x', files })+ expect(sessionStorage.getItem(`${COWORK_HANDOFF_PREFIX}a`)).not.toContain('base64')+ expect(peekCoworkHandoff('a')?.files).toEqual(files)+ })++ it('is claimable exactly once (StrictMode double effect), and again after a release', () => {+ expect(claimCoworkHandoff('a')).toBe(true)+ expect(claimCoworkHandoff('a')).toBe(false)+ releaseCoworkHandoff('a')+ expect(claimCoworkHandoff('a')).toBe(true)+ })++ it('clear removes the text, the attachments and the claim', () => {+ writeCoworkHandoff('a', { text: 'x', files: [{ type: 'file', mediaType: 'a/b', url: 'u' }] })+ claimCoworkHandoff('a')+ clearCoworkHandoff('a')+ expect(peekCoworkHandoff('a')).toBeNull()+ expect(claimCoworkHandoff('a')).toBe(true)+ })++ it('drops a corrupt entry instead of throwing', () => {+ sessionStorage.setItem(`${COWORK_HANDOFF_PREFIX}a`, '{nope')+ expect(peekCoworkHandoff('a')).toBeNull()+ expect(sessionStorage.getItem(`${COWORK_HANDOFF_PREFIX}a`)).toBeNull()+ })++ it('discards handoffs whose session no longer exists, keeps live ones', () => {+ writeCoworkHandoff('a', { text: 'live' })+ writeCoworkHandoff('gone', { text: 'stale' })+ discardStaleCoworkHandoffs(new Set(['a']))+ expect(peekCoworkHandoff('a')).not.toBeNull()+ expect(peekCoworkHandoff('gone')).toBeNull()+ })+})diff --git a/web-app/src/lib/__tests__/threadMode.test.ts b/web-app/src/lib/__tests__/threadMode.test.tsnew file mode 100644index 000000000..8228a61d7--- /dev/null+++ b/web-app/src/lib/__tests__/threadMode.test.ts@@ -0,0 +1,17 @@+import { describe, it, expect } from 'vitest'+import { getThreadMode, isCoworkThread } from '../threadMode'++describe('threadMode', () => {+ it('treats absent mode and absent metadata as chat', () => {+ expect(getThreadMode({})).toBe('chat')+ expect(getThreadMode({ metadata: {} })).toBe('chat')+ expect(getThreadMode({ metadata: null })).toBe('chat')+ expect(getThreadMode(undefined)).toBe('chat')+ })++ it('reads cowork and ignores unknown values', () => {+ expect(getThreadMode({ metadata: { mode: 'cowork' } })).toBe('cowork')+ expect(isCoworkThread({ metadata: { mode: 'cowork' } })).toBe(true)+ expect(getThreadMode({ metadata: { mode: 'weird' } })).toBe('chat')+ })+})diff --git a/web-app/src/lib/__tests__/threadRouteClassification.test.ts b/web-app/src/lib/__tests__/threadRouteClassification.test.tsnew file mode 100644index 000000000..807038eef--- /dev/null+++ b/web-app/src/lib/__tests__/threadRouteClassification.test.ts@@ -0,0 +1,184 @@+/**+ * Unit tests for the bounded startup retry used by /threads/$threadId+ * beforeLoad: a fetchThreads that throws while the+ * Conversational extension is still registering must not strand the deep+ * link, and an exhausted window must surface as the typed recoverable error+ * (never an implicit "ordinary chat" classification). An EMPTY fetched list+ * before store hydration does not prove the startup inventory has committed,+ * so [] retries and then fails closed until successful hydration.+ */+import { describe, it, expect, vi } from 'vitest'+import {+ resolveThreadForRoute,+ ThreadClassificationUnavailableError,+ THREAD_LOOKUP_ATTEMPTS,+ threadLookupDelayMs,+} from '../threadRouteClassification'++type T = { id: string; metadata?: Record<string, unknown> }++const noSleep = vi.fn(() => Promise.resolve())++const base = (over: Partial<Parameters<typeof resolveThreadForRoute<T>>[0]>) => ({+ threadId: 't1',+ readThread: () => undefined as T | undefined,+ fetchThreads: () => Promise.resolve([] as T[]),+ sleep: noSleep,+ ...over,+})++describe('resolveThreadForRoute', () => {+ it('returns the store-resident record without fetching', async () => {+ const fetchThreads = vi.fn()+ const resident = { id: 't1' }+ const result = await resolveThreadForRoute<T>(+ base({ readThread: () => resident, fetchThreads })+ )+ expect(result).toBe(resident)+ expect(fetchThreads).not.toHaveBeenCalled()+ })++ it('startup failure then success: retries and classifies the cowork thread', async () => {+ const cowork = { id: 't1', metadata: { mode: 'cowork' } }+ const fetchThreads = vi+ .fn<() => Promise<T[]>>()+ .mockRejectedValueOnce(new Error('Conversational extension not available yet'))+ .mockRejectedValueOnce(new Error('Conversational extension not available yet'))+ .mockResolvedValueOnce([cowork])+ const result = await resolveThreadForRoute<T>(base({ fetchThreads }))+ expect(result).toBe(cowork)+ expect(fetchThreads).toHaveBeenCalledTimes(3)+ })++ it('resolves undefined for an id a HEALTHY backend does not know (NON-empty list)', async () => {+ const fetchThreads = vi.fn<() => Promise<T[]>>().mockResolvedValue([{ id: 'other' }])+ const result = await resolveThreadForRoute<T>(base({ fetchThreads }))+ expect(result).toBeUndefined()+ expect(fetchThreads).toHaveBeenCalledTimes(1)+ })++ it('empty list then success: [] is not authoritative, the retry classifies the cowork thread', async () => {+ // An empty fallback before store hydration does not prove the startup+ // inventory has committed. Wait for the record or authoritative hydration+ // rather than mounting writable Chat over an undecidable conversation.+ const cowork = { id: 't1', metadata: { mode: 'cowork' } }+ const fetchThreads = vi+ .fn<() => Promise<T[]>>()+ .mockResolvedValueOnce([])+ .mockResolvedValueOnce([])+ .mockResolvedValueOnce([cowork])+ const result = await resolveThreadForRoute<T>(base({ fetchThreads }))+ expect(result).toBe(cowork)+ expect(fetchThreads).toHaveBeenCalledTimes(3)+ })++ it('an all-empty window fails closed with the typed error, never a healthy unknown', async () => {+ const fetchThreads = vi.fn<() => Promise<T[]>>().mockResolvedValue([])+ const err = await resolveThreadForRoute<T>(base({ fetchThreads })).then(+ () => null,+ (e) => e+ )+ expect(err).toBeInstanceOf(ThreadClassificationUnavailableError)+ expect((err as ThreadClassificationUnavailableError).threadId).toBe('t1')+ expect(+ String((err as ThreadClassificationUnavailableError).causeError)+ ).toMatch(/empty list/)+ expect(fetchThreads).toHaveBeenCalledTimes(THREAD_LOOKUP_ATTEMPTS)+ })++ it('isHydrated=true: a store miss is authoritative and never fetches', async () => {+ const fetchThreads = vi.fn()+ const result = await resolveThreadForRoute<T>(+ base({ fetchThreads, isHydrated: () => true })+ )+ expect(result).toBeUndefined()+ expect(fetchThreads).not.toHaveBeenCalled()+ })++ it('isHydrated=true still lets a resident record win', async () => {+ const resident = { id: 't1', metadata: { mode: 'cowork' } }+ const result = await resolveThreadForRoute<T>(+ base({ readThread: () => resident, isHydrated: () => true })+ )+ expect(result).toBe(resident)+ })++ it('hydration succeeding during an empty fetch ends in an authoritative miss, not an error', async () => {+ let hydrated = false+ const fetchThreads = vi.fn<() => Promise<T[]>>(async () => {+ hydrated = true+ return []+ })+ const result = await resolveThreadForRoute<T>(+ base({ fetchThreads, isHydrated: () => hydrated })+ )+ expect(result).toBeUndefined()+ expect(fetchThreads).toHaveBeenCalledTimes(1)+ })++ it('exhausted window throws the typed recoverable error, never a silent chat classification', async () => {+ const boom = new Error('Conversational extension not available yet')+ const fetchThreads = vi.fn<() => Promise<T[]>>().mockRejectedValue(boom)+ const err = await resolveThreadForRoute<T>(base({ fetchThreads })).then(+ () => null,+ (e) => e+ )+ expect(err).toBeInstanceOf(ThreadClassificationUnavailableError)+ expect((err as ThreadClassificationUnavailableError).threadId).toBe('t1')+ expect((err as ThreadClassificationUnavailableError).causeError).toBe(boom)+ expect(fetchThreads).toHaveBeenCalledTimes(THREAD_LOOKUP_ATTEMPTS)+ })++ it('a store hydration landing during a backoff wins before the next fetch', async () => {+ let store: T | undefined+ const fetchThreads = vi+ .fn<() => Promise<T[]>>()+ .mockRejectedValue(new Error('not ready'))+ const sleep = vi.fn(() => {+ store = { id: 't1', metadata: { mode: 'cowork' } }+ return Promise.resolve()+ })+ const result = await resolveThreadForRoute<T>(+ base({ readThread: () => store, fetchThreads, sleep })+ )+ expect(result).toEqual({ id: 't1', metadata: { mode: 'cowork' } })+ expect(fetchThreads).toHaveBeenCalledTimes(1)+ })++ it('mid-await store-wins: a record committed DURING a successful fetch beats the stale snapshot', async () => {+ let store: T | undefined+ const committed = { id: 't1', metadata: { mode: 'cowork' } }+ const fetchThreads = vi.fn<() => Promise<T[]>>(async () => {+ store = committed // lands while the fetch is in flight+ return [] // stale pre-commit backend snapshot+ })+ const result = await resolveThreadForRoute<T>(+ base({ readThread: () => store, fetchThreads })+ )+ expect(result).toBe(committed)+ })++ it('a hydration landing during the FINAL failed attempt still resolves instead of throwing', async () => {+ let store: T | undefined+ const fetchThreads = vi.fn<() => Promise<T[]>>(async () => {+ if (fetchThreads.mock.calls.length === THREAD_LOOKUP_ATTEMPTS) {+ store = { id: 't1' }+ }+ throw new Error('not ready')+ })+ const result = await resolveThreadForRoute<T>(+ base({ readThread: () => store, fetchThreads })+ )+ expect(result).toEqual({ id: 't1' })+ expect(fetchThreads).toHaveBeenCalledTimes(THREAD_LOOKUP_ATTEMPTS)+ })++ it('backoff stays bounded (startup window, not an unbounded spin)', () => {+ expect(threadLookupDelayMs(0)).toBe(150)+ expect(threadLookupDelayMs(THREAD_LOOKUP_ATTEMPTS - 1)).toBeLessThanOrEqual(1000)+ const total = Array.from({ length: THREAD_LOOKUP_ATTEMPTS - 1 }, (_, i) =>+ threadLookupDelayMs(i)+ ).reduce((a, b) => a + b, 0)+ expect(total).toBeLessThan(3000)+ })+})diff --git a/web-app/src/lib/__tests__/threadRouteGuard.test.ts b/web-app/src/lib/__tests__/threadRouteGuard.test.tsnew file mode 100644index 000000000..d23c01a95--- /dev/null+++ b/web-app/src/lib/__tests__/threadRouteGuard.test.ts@@ -0,0 +1,98 @@+import { describe, it, expect } from 'vitest'+import { shouldRedirectThreadToCowork } from '../threadRouteGuard'++type SessionArg = Parameters<typeof shouldRedirectThreadToCowork>[1][number]++const session = (+ id: string,+ unavailable?: SessionArg['unavailable']+): SessionArg => (unavailable ? { id, unavailable } : { id })++const chatThread = { metadata: {} }+const coworkThread = { metadata: { mode: 'cowork' } }++describe('shouldRedirectThreadToCowork', () => {+ // Baseline: the pre-existing redirect behavior is preserved.+ it('redirects a normal cowork session id to the Cowork view', () => {+ expect(+ shouldRedirectThreadToCowork('a', [session('a')], coworkThread)+ ).toBe(true)+ })++ it('keeps an ordinary chat thread on the chat route', () => {+ expect(+ shouldRedirectThreadToCowork('a', [session('b')], chatThread)+ ).toBe(false)+ expect(shouldRedirectThreadToCowork('a', [], chatThread)).toBe(false)+ expect(shouldRedirectThreadToCowork('a', [], undefined)).toBe(false)+ })++ // R2: an id-collision placeholder marks a legacy session whose id is owned+ // by a real chat thread. The chat keeps its route.+ it('does not let an id-collision placeholder hijack the real chat route', () => {+ expect(+ shouldRedirectThreadToCowork(+ 'a',+ [session('a', 'id-collision')],+ chatThread+ )+ ).toBe(false)+ })++ it('still redirects when the thread record itself is cowork-mode even if a collision placeholder exists', () => {+ // Defensive: loadCoworkSessions only mints id-collision against chat ids,+ // but if the record says cowork the chat view must never mount.+ expect(+ shouldRedirectThreadToCowork(+ 'a',+ [session('a', 'id-collision')],+ coworkThread+ )+ ).toBe(true)+ })++ // Preserved: the other unavailable placeholders render (read-only) in the+ // Cowork view, so they keep claiming the route.+ it.each(['missing-sidecar', 'unreadable-sidecar'] as const)(+ 'redirects a %s placeholder to the Cowork view',+ (reason) => {+ expect(+ shouldRedirectThreadToCowork('a', [session('a', reason)], coworkThread)+ ).toBe(true)+ }+ )++ // R3: failed hydration leaves the session store empty while the thread list+ // still carries the committed cowork record. The chat view must not mount.+ it('redirects a cowork-mode thread even when the session store is empty (failed hydration)', () => {+ expect(shouldRedirectThreadToCowork('a', [], coworkThread)).toBe(true)+ })++ it('redirects a cowork-mode thread missing from a non-empty session store', () => {+ expect(+ shouldRedirectThreadToCowork('a', [session('b')], coworkThread)+ ).toBe(true)+ })++ // Absent metadata.mode means chat (threadMode contract): an unhydrated id+ // with no cowork marker anywhere stays on the chat route.+ it('does not redirect when neither store knows the id', () => {+ expect(shouldRedirectThreadToCowork('a', [], null)).toBe(false)+ expect(+ shouldRedirectThreadToCowork('a', [], { metadata: { mode: 'chat' } })+ ).toBe(false)+ expect(shouldRedirectThreadToCowork('a', [], { metadata: null })).toBe(+ false+ )+ })++ it('matches only the exact thread id', () => {+ expect(+ shouldRedirectThreadToCowork(+ 'a',+ [session('a-2'), session('b', 'id-collision')],+ chatThread+ )+ ).toBe(false)+ })+})diff --git a/web-app/src/lib/__tests__/version.test.ts b/web-app/src/lib/__tests__/version.test.tsindex 4b3aa4d88..c38780c20 100644--- a/web-app/src/lib/__tests__/version.test.ts+++ b/web-app/src/lib/__tests__/version.test.ts@@ -39,26 +39,4 @@ describe('version', () => {const mod = await import('../version')expect(mod.isProd).toBe(false)})-- it('isCoworkEnabled is true on nightly and on the dev server', async () => {- ;(globalThis as any).VERSION = '1.0.0-nightly'- vi.doMock('../utils', () => ({ isDev: vi.fn(() => false) }))- expect((await import('../version')).isCoworkEnabled()).toBe(true)-- vi.resetModules()- ;(globalThis as any).VERSION = '1.0.0'- vi.doMock('../utils', () => ({ isDev: vi.fn(() => true) }))- expect((await import('../version')).isCoworkEnabled()).toBe(true)- })-- it('isCoworkEnabled is false on beta and on stable releases', async () => {- ;(globalThis as any).VERSION = '1.0.0-beta'- vi.doMock('../utils', () => ({ isDev: vi.fn(() => false) }))- expect((await import('../version')).isCoworkEnabled()).toBe(false)-- vi.resetModules()- ;(globalThis as any).VERSION = '1.0.0'- vi.doMock('../utils', () => ({ isDev: vi.fn(() => false) }))- expect((await import('../version')).isCoworkEnabled()).toBe(false)- })})diff --git a/web-app/src/lib/coworkAccess.ts b/web-app/src/lib/coworkAccess.tsdeleted file mode 100644index 83c496e10..000000000--- a/web-app/src/lib/coworkAccess.ts+++ /dev/null@@ -1,12 +0,0 @@-import { redirect } from '@tanstack/react-router'-import { route } from '@/constants/routes'-import { isCoworkEnabled } from '@/lib/version'--/**- * `beforeLoad` guard for every Cowork URL. On a build that does not ship- * Cowork, a bookmarked `/cowork`, `/artifacts` or `/settings/cowork` link lands- * on `fallback` instead of mounting a surface that has no entry point left.- */-export function ensureCoworkEnabled(fallback: string = route.home) {- if (!isCoworkEnabled()) throw redirect({ to: fallback })-}diff --git a/web-app/src/lib/coworkHandoff.ts b/web-app/src/lib/coworkHandoff.tsnew file mode 100644index 000000000..4253be92d--- /dev/null+++ b/web-app/src/lib/coworkHandoff.ts@@ -0,0 +1,93 @@+import type { Attachment } from '@/types/attachment'++/**+ * First-prompt handoff from the home composer to a new Cowork session.+ *+ * The text goes through sessionStorage (small, survives a reload, the same+ * pattern Chat uses). Media and document attachments can be large, so they are+ * NOT serialized: they travel by session id through an in-memory map, which a+ * reload drops. Chat avoids sessionStorage for media for the same quota reason.+ *+ * Consumption is two-step so a first submit that is refused (no tool-capable+ * model) is not lost: `peek` reads without removing, and the caller `clear`s+ * only once the run was accepted. `claim` guards against the double effect that+ * StrictMode runs in development.+ */++export const COWORK_HANDOFF_PREFIX = 'cowork-initial-message:'++export type CoworkHandoff = {+ text: string+ draft?: string+ files?: Array<{ type: 'file'; mediaType: string; url: string }>+ documents?: Attachment[]+}++type Stored = { text: string; draft?: string }++const attachments = new Map<+ string,+ Pick<CoworkHandoff, 'files' | 'documents'>+>()+const claimed = new Set<string>()++const keyFor = (sessionId: string) => `${COWORK_HANDOFF_PREFIX}${sessionId}`++export function writeCoworkHandoff(sessionId: string, handoff: CoworkHandoff) {+ const stored: Stored = { text: handoff.text, draft: handoff.draft }+ sessionStorage.setItem(keyFor(sessionId), JSON.stringify(stored))+ if (handoff.files?.length || handoff.documents?.length) {+ attachments.set(sessionId, {+ files: handoff.files,+ documents: handoff.documents,+ })+ }+}++export function peekCoworkHandoff(sessionId: string): CoworkHandoff | null {+ const raw = sessionStorage.getItem(keyFor(sessionId))+ if (!raw) return null+ try {+ const stored = JSON.parse(raw) as Stored+ if (typeof stored.text !== 'string') return null+ return { ...stored, ...(attachments.get(sessionId) ?? {}) }+ } catch {+ sessionStorage.removeItem(keyFor(sessionId))+ return null+ }+}++/**+ * True exactly once per session id until `clearCoworkHandoff` or a release.+ */+export function claimCoworkHandoff(sessionId: string): boolean {+ if (claimed.has(sessionId)) return false+ claimed.add(sessionId)+ return true+}++/**+ * Let a refused submit be tried again (e.g. after the user picks a model).+ */+export function releaseCoworkHandoff(sessionId: string) {+ claimed.delete(sessionId)+}++export function clearCoworkHandoff(sessionId: string) {+ sessionStorage.removeItem(keyFor(sessionId))+ attachments.delete(sessionId)+ claimed.delete(sessionId)+}++/**+ * A handoff for a session that no longer exists (reload before the first+ * commit, session pruned) must not linger: drop it.+ */+export function discardStaleCoworkHandoffs(liveSessionIds: Set<string>) {+ for (let i = sessionStorage.length - 1; i >= 0; i--) {+ const key = sessionStorage.key(i)+ if (!key?.startsWith(COWORK_HANDOFF_PREFIX)) continue+ const id = key.slice(COWORK_HANDOFF_PREFIX.length)+ if (!liveSessionIds.has(id)) clearCoworkHandoff(id)+ }+}diff --git a/web-app/src/lib/threadRouteClassification.ts b/web-app/src/lib/threadRouteClassification.tsnew file mode 100644index 000000000..78b8035a4--- /dev/null+++ b/web-app/src/lib/threadRouteClassification.ts@@ -0,0 +1,143 @@+/**+ * Route-local thread classification for `/threads/$threadId` deep links that+ * arrive before the threads store has hydrated.+ *+ * Startup and classification guarantees:+ *+ * - StartupProvider initializes services and extensions BEFORE RouterProvider+ * loads the initial route. Root-route providers cannot do this: beforeLoad+ * runs before the root component mounts. The bounded lookup retry is only+ * for late/recovering extensions (including the setup watchdog), not a+ * substitute for initializing services before route loading.+ *+ * - When every attempt fails the classification is UNKNOWN, and a writable+ * chat must never mount over an undecidable thread (it would fork a cowork+ * transcript into `messages.jsonl`). The failure surfaces as a typed+ * {@link ThreadClassificationUnavailableError} that the route renders as a+ * recoverable Retry screen instead of a dead end.+ *+ * - The store is re-read before every attempt AND after every successful+ * fetch: a hydration (or a cowork commit) landing DURING an await is newer+ * than the fetched backend snapshot, and deciding on the stale snapshot+ * could classify a just-committed cowork thread as an ordinary chat.+ * Nothing fetched is ever written back into the store.+ *+ * - Before successful store hydration, an empty fallback listing is treated+ * conservatively as unknown: it cannot establish that the store's complete+ * startup inventory has committed. Retry within the bounded window, then+ * show the recoverable error. Once DataProvider commits a validated listing+ * (including a genuinely empty array), its success-only flag makes a store+ * miss authoritative and avoids the fallback entirely.+ *+ * Hydration signal: `useThreads.threadsHydrated` is a SUCCESS-ONLY flag set+ * by DataProvider's success branch after the service validated an actual+ * array response (the service now throws on a non-array, so `[]` is a real+ * zero-thread listing). It is deliberately NOT `isLoadingThreads`, which+ * DataProvider also clears when its retries exhaust. When hydrated, a+ * store miss is authoritative (`undefined`) and the backend lookup is+ * skipped; the store is still re-read first and after every await, so a+ * newer store record (cowork commit / migration race) always wins and its+ * persisted metadata drives classification. When NOT hydrated (fresh+ * startup) an empty fallback list stays UNKNOWN and fails closed.+ */++export class ThreadClassificationUnavailableError extends Error {+ readonly threadId: string+ /** The last fetch rejection; named to avoid depending on ES2022 `cause`. */+ readonly causeError: unknown++ constructor(threadId: string, causeError: unknown) {+ super(+ `Could not confirm whether conversation "${threadId}" is a chat or a ` ++ 'Cowork session. Please retry; if this persists, restart the app.'+ )+ this.name = 'ThreadClassificationUnavailableError'+ this.threadId = threadId+ this.causeError = causeError+ }+}++/** Bounded startup window: 6 attempts, backoff 150/300/450/600/750ms. */+export const THREAD_LOOKUP_ATTEMPTS = 6++export const threadLookupDelayMs = (attempt: number): number =>+ Math.min(1000, 150 * (attempt + 1))++const defaultSleep = (ms: number) =>+ new Promise<void>((resolve) => setTimeout(resolve, ms))++export interface ResolveThreadForRouteOptions<T extends { id: string }> {+ threadId: string+ /** Live store read; consulted before every attempt and after every fetch. */+ readThread: () => T | undefined+ /** Backend lookup; may reject while the extension is still registering. */+ fetchThreads: () => Promise<T[]>+ /** Success-only hydration flag; true makes a store miss authoritative. */+ isHydrated?: () => boolean+ attempts?: number+ delayMs?: (attempt: number) => number+ sleep?: (ms: number) => Promise<void>+}++/**+ * Resolves the thread record a route decision needs, retrying backend+ * startup failures over a bounded window. Resolves `undefined` for an id+ * unknown to both the store and a HEALTHY backend - which requires a+ * NON-empty fallback list or successful store hydration+ * (existing unknown-id behavior); throws+ * {@link ThreadClassificationUnavailableError} when the backend never+ * answered (every attempt rejected OR returned an empty list), so the+ * caller can refuse to mount a writable chat.+ */+export async function resolveThreadForRoute<T extends { id: string }>(+ options: ResolveThreadForRouteOptions<T>+): Promise<T | undefined> {+ const {+ threadId,+ readThread,+ fetchThreads,+ isHydrated = () => false,+ attempts = THREAD_LOOKUP_ATTEMPTS,+ delayMs = threadLookupDelayMs,+ sleep = defaultSleep,+ } = options++ let lastError: unknown+ for (let attempt = 0; attempt < attempts; attempt++) {+ // A hydration may have landed while we backed off.+ const resident = readThread()+ if (resident) return resident+ // Success-only hydration already applied the full listing: a miss is real.+ if (isHydrated()) return undefined+ try {+ const fetched = await fetchThreads()+ // Mid-await store-wins: a record committed during the fetch is newer+ // than the backend snapshot the fetch was issued against.+ const midAwait = readThread()+ if (midAwait) return midAwait+ if (fetched.length > 0) {+ // Only a non-empty list is authoritative: the id either is in it+ // or is a genuine miss (existing unknown-id behavior).+ return fetched.find((t) => t.id === threadId)+ }+ // Hydration may have succeeded while we awaited (store re-read above+ // found no record), so a miss is authoritative now.+ if (isHydrated()) return undefined+ // Before store hydration, an empty fallback does not establish a+ // committed startup inventory. Keep the route fail-closed until a+ // record or successful hydration makes classification authoritative.+ lastError = new Error(+ 'Thread list fetch returned an empty list; cannot distinguish ' ++ '"backend not ready" from "no threads exist".'+ )+ } catch (error) {+ lastError = error+ }+ if (attempt < attempts - 1) await sleep(delayMs(attempt))+ }+ // The store can also hydrate during the FINAL failed attempt.+ const resident = readThread()+ if (resident) return resident+ if (isHydrated()) return undefined+ throw new ThreadClassificationUnavailableError(threadId, lastError)+}diff --git a/web-app/src/lib/threadRouteGuard.ts b/web-app/src/lib/threadRouteGuard.tsnew file mode 100644index 000000000..8bfcdbf30--- /dev/null+++ b/web-app/src/lib/threadRouteGuard.ts@@ -0,0 +1,34 @@+import type { CoworkSession } from '@/hooks/useCoworkSessions'+import { isCoworkThread } from '@/lib/threadMode'++/**+ * Decides whether `/threads/$threadId` must hand the conversation to the+ * Cowork view instead of mounting the writable chat view.+ *+ * Two invariants:+ *+ * - An `id-collision` placeholder marks a legacy Cowork session whose id is+ * owned by a REAL chat thread. The chat keeps its route; the placeholder+ * stays reachable at `/cowork/$sessionId` only. Every other session -+ * including the other unavailable placeholders, which the Cowork view+ * renders read-only - claims the route as before.+ *+ * - A thread committed with `metadata.mode === 'cowork'` never mounts the+ * chat view, even when the session store holds no matching session (failed+ * `startCoworkSync` hydration renders routes over an empty store). Mounting+ * chat there forks the transcript into `messages.jsonl`, invisible to the+ * Cowork view. Redirecting instead is safe: with an empty store the Cowork+ * route falls back home without creating or writing anything.+ *+ * Pure on its inputs so the decision is testable without the route tree; the+ * route's `beforeLoad` feeds it the live stores.+ */+export function shouldRedirectThreadToCowork(+ threadId: string,+ sessions: ReadonlyArray<Pick<CoworkSession, 'id' | 'unavailable'>>,+ thread: { metadata?: Record<string, unknown> | null } | null | undefined+): boolean {+ const session = sessions.find((s) => s.id === threadId)+ if (session && session.unavailable !== 'id-collision') return true+ return isCoworkThread(thread)+}diff --git a/web-app/src/lib/version.ts b/web-app/src/lib/version.tsindex 6b051561f..fbbe217b3 100644--- a/web-app/src/lib/version.ts+++ b/web-app/src/lib/version.ts@@ -3,15 +3,3 @@ import { isDev } from './utils'export const isNightly = VERSION.includes('-')export const isBeta = VERSION.includes('beta')export const isProd = !isNightly && !isBeta && !isDev()--/**- * Builds that are allowed to show the Cowork surface (sidebar tab, routes and- * settings). Cowork is a preview feature: it ships in nightly builds and in the- * local dev server, and stays out of beta and stable releases until it is- * announced. Read it at render time - `isDev()` looks at `window.location`, so- * tests can stub the channel per case.- *- * Beta releases carry a hyphen too (`0.7.4-beta`), so `isBeta` has to be- * excluded explicitly - same rule the updater uses to label nightly builds.- */-export const isCoworkEnabled = () => (isNightly && !isBeta) || isDev()diff --git a/web-app/src/locales/de-DE/common.json b/web-app/src/locales/de-DE/common.jsonindex a2a0e49d9..52e7502d2 100644--- a/web-app/src/locales/de-DE/common.json+++ b/web-app/src/locales/de-DE/common.json@@ -414,5 +414,10 @@"missingThreadDescription": "Der gespeicherte Thread fehlt, daher werden Änderungen nicht mehr gespeichert. Sie können ihn weiterhin lesen, exportieren oder löschen.","writeRefusedTitle": "Eine Cowork-Unterhaltung kann nicht gespeichert werden","writeRefusedDescription": "Jan kann diese Unterhaltung nicht unter ihrer aktuellen ID speichern, daher werden Änderungen nicht gespeichert. Sie können sie weiterhin lesen, exportieren oder löschen."+ },+ "threadRoute": {+ "notReadyTitle": "Diese Unterhaltung ist noch nicht bereit",+ "notReadyDescription": "Jan konnte nicht bestätigen, ob diese Unterhaltung ein Chat oder eine Cowork-Aufgabe ist. Versuche es erneut; falls das Problem bestehen bleibt, starte die App neu.",+ "retry": "Erneut versuchen"}}diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.jsonindex 54ec85178..b853fe69b 100644--- a/web-app/src/locales/en/common.json+++ b/web-app/src/locales/en/common.json@@ -797,5 +797,10 @@"missingThreadDescription": "Its stored thread is missing, so changes are no longer saved. You can still read, export or delete it.","writeRefusedTitle": "A Cowork conversation cannot be saved","writeRefusedDescription": "Jan cannot store this conversation under its current id, so changes are not saved. You can still read, export or delete it."+ },+ "threadRoute": {+ "notReadyTitle": "This conversation isn't ready yet",+ "notReadyDescription": "Jan could not confirm whether this conversation is a chat or a Cowork task. Retry; if this persists, restart the app.",+ "retry": "Retry"}}diff --git a/web-app/src/locales/fr/common.json b/web-app/src/locales/fr/common.jsonindex 925578cd0..ae3b75f31 100644--- a/web-app/src/locales/fr/common.json+++ b/web-app/src/locales/fr/common.json@@ -417,5 +417,10 @@"missingThreadDescription": "Son fil enregistré est introuvable, les modifications ne sont donc plus enregistrées. Vous pouvez toujours le lire, l'exporter ou le supprimer.","writeRefusedTitle": "Une conversation Cowork ne peut pas être enregistrée","writeRefusedDescription": "Jan ne peut pas enregistrer cette conversation sous son identifiant actuel, les modifications ne sont donc pas enregistrées. Vous pouvez toujours la lire, l'exporter ou la supprimer."+ },+ "threadRoute": {+ "notReadyTitle": "Cette conversation n'est pas encore prête",+ "notReadyDescription": "Jan n'a pas pu confirmer si cette conversation est un chat ou une tâche Cowork. Réessayez ; si le problème persiste, redémarrez l'application.",+ "retry": "Réessayer"}}diff --git a/web-app/src/locales/ja/common.json b/web-app/src/locales/ja/common.jsonindex bc6e0f069..ac3c58099 100644--- a/web-app/src/locales/ja/common.json+++ b/web-app/src/locales/ja/common.json@@ -531,5 +531,10 @@"missingThreadDescription": "保存されているスレッドが見つからないため、変更は保存されなくなりました。読み取り、エクスポート、削除は引き続き可能です。","writeRefusedTitle": "Cowork会話を保存できません","writeRefusedDescription": "Janはこの会話を現在のIDで保存できないため、変更は保存されません。読み取り、エクスポート、削除は引き続き可能です。"+ },+ "threadRoute": {+ "notReadyTitle": "この会話はまだ準備できていません",+ "notReadyDescription": "この会話がチャットかCoworkタスクかをJanが確認できませんでした。再試行してください。解決しない場合はアプリを再起動してください。",+ "retry": "再試行"}}diff --git a/web-app/src/locales/zh-CN/common.json b/web-app/src/locales/zh-CN/common.jsonindex 6873d54e9..e5faa9946 100644--- a/web-app/src/locales/zh-CN/common.json+++ b/web-app/src/locales/zh-CN/common.json@@ -593,5 +593,10 @@"missingThreadDescription": "其存储的会话线程已丢失,因此不再保存更改。您仍可阅读、导出或删除它。","writeRefusedTitle": "无法保存 Cowork 对话","writeRefusedDescription": "Jan 无法以当前 ID 存储此对话,因此不会保存更改。您仍可阅读、导出或删除它。"+ },+ "threadRoute": {+ "notReadyTitle": "此对话尚未就绪",+ "notReadyDescription": "Jan 无法确认此对话是聊天还是 Cowork 任务。请重试;如果问题仍然存在,请重启应用。",+ "retry": "重试"}}diff --git a/web-app/src/main.tsx b/web-app/src/main.tsxindex ad0bbdf0e..8cbf4c6b4 100644--- a/web-app/src/main.tsx+++ b/web-app/src/main.tsx@@ -88,6 +88,7 @@ const boot = async () => {await consumePendingWebdataReset()// Dynamic imports keep store hydration AFTER the localStorage prune above.+ const { StartupProvider } = await import('./providers/StartupProvider')const { routeTree } = await import('./routeTree.gen')await import('./i18n')@@ -98,7 +99,9 @@ const boot = async () => {const root = ReactDOM.createRoot(rootElement)root.render(<StrictMode>- <RouterProvider router={router} />+ <StartupProvider>+ <RouterProvider router={router} />+ </StartupProvider></StrictMode>)}diff --git a/web-app/src/providers/StartupProvider.tsx b/web-app/src/providers/StartupProvider.tsxnew file mode 100644index 000000000..3868f3756--- /dev/null+++ b/web-app/src/providers/StartupProvider.tsx@@ -0,0 +1,20 @@+import type { PropsWithChildren } from 'react'+import { ServiceHubProvider } from './ServiceHubProvider'+import { ExtensionProvider } from './ExtensionProvider'+import { TranslationProvider } from '@/i18n/TranslationContext'++/**+ * Startup must live OUTSIDE RouterProvider: initial beforeLoad runs before the+ * root route mounts. Keeping these gates in RootLayout prevents a direct thread+ * link from ever initializing the services its classification needs. Settings+ * and Cowork migration still hydrate before extensions, then route loading.+ */+export function StartupProvider({ children }: PropsWithChildren) {+ return (+ <ServiceHubProvider>+ <TranslationProvider>+ <ExtensionProvider>{children}</ExtensionProvider>+ </TranslationProvider>+ </ServiceHubProvider>+ )+}diff --git a/web-app/src/providers/__tests__/startupRouting.test.tsx b/web-app/src/providers/__tests__/startupRouting.test.tsxnew file mode 100644index 000000000..1d0a62ba8--- /dev/null+++ b/web-app/src/providers/__tests__/startupRouting.test.tsx@@ -0,0 +1,74 @@+import { useEffect, useState, type PropsWithChildren } from 'react'+import { render, screen } from '@testing-library/react'+import {+ createMemoryHistory,+ createRootRoute,+ createRoute,+ createRouter,+ Outlet,+ RouterProvider,+} from '@tanstack/react-router'+import { describe, expect, it, vi } from 'vitest'+import { resolveThreadForRoute } from '@/lib/threadRouteClassification'++const startup = vi.hoisted(() => ({ services: false, extensions: false }))+vi.mock('../ServiceHubProvider', () => ({+ ServiceHubProvider: ({ children }: PropsWithChildren) => {+ const [ready, setReady] = useState(false)+ useEffect(() => {+ startup.services = true+ setReady(true)+ }, [])+ return ready ? children : null+ },+}))+vi.mock('../ExtensionProvider', () => ({+ ExtensionProvider: ({ children }: PropsWithChildren) => {+ const [ready, setReady] = useState(false)+ useEffect(() => {+ startup.extensions = true+ setReady(true)+ }, [])+ return ready ? children : null+ },+}))+vi.mock('@/i18n/TranslationContext', () => ({+ TranslationProvider: ({ children }: PropsWithChildren) => children,+}))+import { StartupProvider } from '../StartupProvider'++describe('initial direct conversation routing', () => {+ it('initializes services and extensions before the initial beforeLoad, without a home navigation', async () => {+ startup.services = false+ startup.extensions = false+ const root = createRootRoute({ component: Outlet })+ const thread = createRoute({+ getParentRoute: () => root,+ path: '/threads/$threadId',+ beforeLoad: async ({ params }) => {+ await resolveThreadForRoute({+ threadId: params.threadId,+ readThread: () => undefined,+ fetchThreads: async () => {+ if (!startup.services) throw new Error('ServiceHub not initialized')+ if (!startup.extensions) throw new Error('Conversational extension not available yet')+ return [{ id: params.threadId }]+ },+ sleep: () => Promise.resolve(),+ })+ },+ component: () => <div>Writable conversation</div>,+ errorComponent: () => <div>Classification unavailable</div>,+ })+ const router = createRouter({+ routeTree: root.addChildren([thread]),+ history: createMemoryHistory({ initialEntries: ['/threads/existing'] }),+ })+ render(+ <StartupProvider>+ <RouterProvider router={router} />+ </StartupProvider>+ )+ expect(await screen.findByText('Writable conversation')).toBeInTheDocument()+ })+})diff --git a/web-app/src/routeTree.gen.ts b/web-app/src/routeTree.gen.tsindex c48f4f74f..a6d02c3ab 100644--- a/web-app/src/routeTree.gen.ts+++ b/web-app/src/routeTree.gen.ts@@ -11,10 +11,10 @@import { Route as rootRouteImport } from './routes/__root'import { Route as SystemMonitorRouteImport } from './routes/system-monitor'import { Route as LogsRouteImport } from './routes/logs'-import { Route as CoworkRouteImport } from './routes/cowork'import { Route as ArtifactsRouteImport } from './routes/artifacts'import { Route as IndexRouteImport } from './routes/index'import { Route as HubIndexRouteImport } from './routes/hub/index'+import { Route as CoworkIndexRouteImport } from './routes/cowork/index'import { Route as ThreadsThreadIdRouteImport } from './routes/threads/$threadId'import { Route as SettingsWebSearchRouteImport } from './routes/settings/web-search'import { Route as SettingsShortcutsRouteImport } from './routes/settings/shortcuts'@@ -32,6 +32,7 @@ import { Route as SettingsAssistantRouteImport } from './routes/settings/assistaimport { Route as ProjectProjectIdRouteImport } from './routes/project/$projectId'import { Route as LocalApiServerLogsRouteImport } from './routes/local-api-server/logs'import { Route as HubModelIdRouteImport } from './routes/hub/$modelId'+import { Route as CoworkSessionIdRouteImport } from './routes/cowork/$sessionId'import { Route as SettingsProvidersIndexRouteImport } from './routes/settings/providers/index'import { Route as SettingsExtensionsIndexRouteImport } from './routes/settings/extensions/index'import { Route as SettingsProvidersProviderNameRouteImport } from './routes/settings/providers/$providerName'@@ -47,11 +48,6 @@ const LogsRoute = LogsRouteImport.update({path: '/logs',getParentRoute: () => rootRouteImport,} as any)-const CoworkRoute = CoworkRouteImport.update({- id: '/cowork',- path: '/cowork',- getParentRoute: () => rootRouteImport,-} as any)const ArtifactsRoute = ArtifactsRouteImport.update({id: '/artifacts',path: '/artifacts',@@ -67,6 +63,11 @@ const HubIndexRoute = HubIndexRouteImport.update({path: '/hub/',getParentRoute: () => rootRouteImport,} as any)+const CoworkIndexRoute = CoworkIndexRouteImport.update({+ id: '/cowork/',+ path: '/cowork/',+ getParentRoute: () => rootRouteImport,+} as any)const ThreadsThreadIdRoute = ThreadsThreadIdRouteImport.update({id: '/threads/$threadId',path: '/threads/$threadId',@@ -152,6 +153,11 @@ const HubModelIdRoute = HubModelIdRouteImport.update({path: '/hub/$modelId',getParentRoute: () => rootRouteImport,} as any)+const CoworkSessionIdRoute = CoworkSessionIdRouteImport.update({+ id: '/cowork/$sessionId',+ path: '/cowork/$sessionId',+ getParentRoute: () => rootRouteImport,+} as any)const SettingsProvidersIndexRoute = SettingsProvidersIndexRouteImport.update({id: '/settings/providers/',path: '/settings/providers/',@@ -178,9 +184,9 @@ const SettingsExtensionsExtensionIdRoute =export interface FileRoutesByFullPath {'/': typeof IndexRoute'/artifacts': typeof ArtifactsRoute- '/cowork': typeof CoworkRoute'/logs': typeof LogsRoute'/system-monitor': typeof SystemMonitorRoute+ '/cowork/$sessionId': typeof CoworkSessionIdRoute'/hub/$modelId': typeof HubModelIdRoute'/local-api-server/logs': typeof LocalApiServerLogsRoute'/project/$projectId': typeof ProjectProjectIdRoute@@ -198,6 +204,7 @@ export interface FileRoutesByFullPath {'/settings/shortcuts': typeof SettingsShortcutsRoute'/settings/web-search': typeof SettingsWebSearchRoute'/threads/$threadId': typeof ThreadsThreadIdRoute+ '/cowork/': typeof CoworkIndexRoute'/hub/': typeof HubIndexRoute'/settings/extensions/$extensionId': typeof SettingsExtensionsExtensionIdRoute'/settings/providers/$providerName': typeof SettingsProvidersProviderNameRoute@@ -207,9 +214,9 @@ export interface FileRoutesByFullPath {export interface FileRoutesByTo {'/': typeof IndexRoute'/artifacts': typeof ArtifactsRoute- '/cowork': typeof CoworkRoute'/logs': typeof LogsRoute'/system-monitor': typeof SystemMonitorRoute+ '/cowork/$sessionId': typeof CoworkSessionIdRoute'/hub/$modelId': typeof HubModelIdRoute'/local-api-server/logs': typeof LocalApiServerLogsRoute'/project/$projectId': typeof ProjectProjectIdRoute@@ -227,6 +234,7 @@ export interface FileRoutesByTo {'/settings/shortcuts': typeof SettingsShortcutsRoute'/settings/web-search': typeof SettingsWebSearchRoute'/threads/$threadId': typeof ThreadsThreadIdRoute+ '/cowork': typeof CoworkIndexRoute'/hub': typeof HubIndexRoute'/settings/extensions/$extensionId': typeof SettingsExtensionsExtensionIdRoute'/settings/providers/$providerName': typeof SettingsProvidersProviderNameRoute@@ -237,9 +245,9 @@ export interface FileRoutesById {__root__: typeof rootRouteImport'/': typeof IndexRoute'/artifacts': typeof ArtifactsRoute- '/cowork': typeof CoworkRoute'/logs': typeof LogsRoute'/system-monitor': typeof SystemMonitorRoute+ '/cowork/$sessionId': typeof CoworkSessionIdRoute'/hub/$modelId': typeof HubModelIdRoute'/local-api-server/logs': typeof LocalApiServerLogsRoute'/project/$projectId': typeof ProjectProjectIdRoute@@ -257,6 +265,7 @@ export interface FileRoutesById {'/settings/shortcuts': typeof SettingsShortcutsRoute'/settings/web-search': typeof SettingsWebSearchRoute'/threads/$threadId': typeof ThreadsThreadIdRoute+ '/cowork/': typeof CoworkIndexRoute'/hub/': typeof HubIndexRoute'/settings/extensions/$extensionId': typeof SettingsExtensionsExtensionIdRoute'/settings/providers/$providerName': typeof SettingsProvidersProviderNameRoute@@ -268,9 +277,9 @@ export interface FileRouteTypes {fullPaths:| '/'| '/artifacts'- | '/cowork'| '/logs'| '/system-monitor'+ | '/cowork/$sessionId'| '/hub/$modelId'| '/local-api-server/logs'| '/project/$projectId'@@ -288,6 +297,7 @@ export interface FileRouteTypes {| '/settings/shortcuts'| '/settings/web-search'| '/threads/$threadId'+ | '/cowork/'| '/hub/'| '/settings/extensions/$extensionId'| '/settings/providers/$providerName'@@ -297,9 +307,9 @@ export interface FileRouteTypes {to:| '/'| '/artifacts'- | '/cowork'| '/logs'| '/system-monitor'+ | '/cowork/$sessionId'| '/hub/$modelId'| '/local-api-server/logs'| '/project/$projectId'@@ -317,6 +327,7 @@ export interface FileRouteTypes {| '/settings/shortcuts'| '/settings/web-search'| '/threads/$threadId'+ | '/cowork'| '/hub'| '/settings/extensions/$extensionId'| '/settings/providers/$providerName'@@ -326,9 +337,9 @@ export interface FileRouteTypes {| '__root__'| '/'| '/artifacts'- | '/cowork'| '/logs'| '/system-monitor'+ | '/cowork/$sessionId'| '/hub/$modelId'| '/local-api-server/logs'| '/project/$projectId'@@ -346,6 +357,7 @@ export interface FileRouteTypes {| '/settings/shortcuts'| '/settings/web-search'| '/threads/$threadId'+ | '/cowork/'| '/hub/'| '/settings/extensions/$extensionId'| '/settings/providers/$providerName'@@ -356,9 +368,9 @@ export interface FileRouteTypes {export interface RootRouteChildren {IndexRoute: typeof IndexRouteArtifactsRoute: typeof ArtifactsRoute- CoworkRoute: typeof CoworkRouteLogsRoute: typeof LogsRouteSystemMonitorRoute: typeof SystemMonitorRoute+ CoworkSessionIdRoute: typeof CoworkSessionIdRouteHubModelIdRoute: typeof HubModelIdRouteLocalApiServerLogsRoute: typeof LocalApiServerLogsRouteProjectProjectIdRoute: typeof ProjectProjectIdRoute@@ -376,6 +388,7 @@ export interface RootRouteChildren {SettingsShortcutsRoute: typeof SettingsShortcutsRouteSettingsWebSearchRoute: typeof SettingsWebSearchRouteThreadsThreadIdRoute: typeof ThreadsThreadIdRoute+ CoworkIndexRoute: typeof CoworkIndexRouteHubIndexRoute: typeof HubIndexRouteSettingsExtensionsExtensionIdRoute: typeof SettingsExtensionsExtensionIdRouteSettingsProvidersProviderNameRoute: typeof SettingsProvidersProviderNameRoute@@ -399,13 +412,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof LogsRouteImportparentRoute: typeof rootRouteImport}- '/cowork': {- id: '/cowork'- path: '/cowork'- fullPath: '/cowork'- preLoaderRoute: typeof CoworkRouteImport- parentRoute: typeof rootRouteImport- }'/artifacts': {id: '/artifacts'path: '/artifacts'@@ -427,6 +433,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof HubIndexRouteImportparentRoute: typeof rootRouteImport}+ '/cowork/': {+ id: '/cowork/'+ path: '/cowork'+ fullPath: '/cowork/'+ preLoaderRoute: typeof CoworkIndexRouteImport+ parentRoute: typeof rootRouteImport+ }'/threads/$threadId': {id: '/threads/$threadId'path: '/threads/$threadId'@@ -546,6 +559,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof HubModelIdRouteImportparentRoute: typeof rootRouteImport}+ '/cowork/$sessionId': {+ id: '/cowork/$sessionId'+ path: '/cowork/$sessionId'+ fullPath: '/cowork/$sessionId'+ preLoaderRoute: typeof CoworkSessionIdRouteImport+ parentRoute: typeof rootRouteImport+ }'/settings/providers/': {id: '/settings/providers/'path: '/settings/providers'@@ -580,9 +600,9 @@ declare module '@tanstack/react-router' {const rootRouteChildren: RootRouteChildren = {IndexRoute: IndexRoute,ArtifactsRoute: ArtifactsRoute,- CoworkRoute: CoworkRoute,LogsRoute: LogsRoute,SystemMonitorRoute: SystemMonitorRoute,+ CoworkSessionIdRoute: CoworkSessionIdRoute,HubModelIdRoute: HubModelIdRoute,LocalApiServerLogsRoute: LocalApiServerLogsRoute,ProjectProjectIdRoute: ProjectProjectIdRoute,@@ -600,6 +620,7 @@ const rootRouteChildren: RootRouteChildren = {SettingsShortcutsRoute: SettingsShortcutsRoute,SettingsWebSearchRoute: SettingsWebSearchRoute,ThreadsThreadIdRoute: ThreadsThreadIdRoute,+ CoworkIndexRoute: CoworkIndexRoute,HubIndexRoute: HubIndexRoute,SettingsExtensionsExtensionIdRoute: SettingsExtensionsExtensionIdRoute,SettingsProvidersProviderNameRoute: SettingsProvidersProviderNameRoute,diff --git a/web-app/src/routes/__root.tsx b/web-app/src/routes/__root.tsxindex 8e65b3a9d..663924fd4 100644--- a/web-app/src/routes/__root.tsx+++ b/web-app/src/routes/__root.tsx@@ -8,20 +8,17 @@ import { InterfaceProvider } from '@/providers/InterfaceProvider'import { KeyboardShortcutsProvider } from '@/providers/KeyboardShortcuts'import { DataProvider } from '@/providers/DataProvider'import { route } from '@/constants/routes'-import { ExtensionProvider } from '@/providers/ExtensionProvider'import { ToasterProvider } from '@/providers/ToasterProvider'import { useAnalytic } from '@/hooks/useAnalytic'import { useIsOnboarding } from '@/hooks/useIsOnboarding'import { PromptAnalytic } from '@/containers/analytics/PromptAnalytic'import { AnalyticProvider } from '@/providers/AnalyticProvider'import { useLeftPanel } from '@/hooks/useLeftPanel'-import { TranslationProvider } from '@/i18n/TranslationContext'import OutOfContextPromiseModal from '@/containers/dialogs/OutOfContextDialog'import AttachmentIngestionDialog from '@/containers/dialogs/AttachmentIngestionDialog'import GlobalError from '@/containers/GlobalError'import { GlobalEventHandler } from '@/providers/GlobalEventHandler'import { DownloadEventListener } from '@/providers/DownloadEventListener'-import { ServiceHubProvider } from '@/providers/ServiceHubProvider'import { SidebarInset, SidebarProvider } from '@/components/ui/sidebar'import { LeftSidebar } from '@/components/left-sidebar'import { WindowControls } from '@/components/WindowControls'@@ -113,27 +110,24 @@ function RootLayout() {const IS_LOGS_ROUTE = getInitialLayoutType()return (+ // ServiceHub, translations and extensions are mounted by StartupProvider+ // above RouterProvider: the initial route's beforeLoad runs before this+ // component mounts and needs them already initialized.<Fragment>- <ServiceHubProvider>- <ThemeProvider />- <InterfaceProvider />- <ToasterProvider />- <TranslationProvider>- <ExtensionProvider>- <DataProvider />- <GlobalEventHandler />- <DownloadEventListener />- {IS_LOGS_ROUTE ? <LogsLayout /> : <AppLayout />}- </ExtensionProvider>- {/* <TanStackRouterDevtools position="bottom-right" /> */}- <AttachmentIngestionDialog />- <ErrorDialog />- <LlamacppBusyOnExitDialog />- <LlamacppOomListener />- <MissingDependenciesDialog />- <OutOfContextPromiseModal />- </TranslationProvider>- </ServiceHubProvider>+ <ThemeProvider />+ <InterfaceProvider />+ <ToasterProvider />+ <DataProvider />+ <GlobalEventHandler />+ <DownloadEventListener />+ {IS_LOGS_ROUTE ? <LogsLayout /> : <AppLayout />}+ {/* <TanStackRouterDevtools position="bottom-right" /> */}+ <AttachmentIngestionDialog />+ <ErrorDialog />+ <LlamacppBusyOnExitDialog />+ <LlamacppOomListener />+ <MissingDependenciesDialog />+ <OutOfContextPromiseModal /></Fragment>)}diff --git a/web-app/src/routes/__tests__/__root.test.tsx b/web-app/src/routes/__tests__/__root.test.tsxindex 02698e017..e653c6eba 100644--- a/web-app/src/routes/__tests__/__root.test.tsx+++ b/web-app/src/routes/__tests__/__root.test.tsx@@ -155,9 +155,11 @@ describe('__root route', () => {it('renders AppLayout by default (non-logs route)', () => {renderComponent()- expect(screen.getByTestId('service-hub')).toBeInTheDocument()+ // ServiceHub/translation/extensions now mount above RouterProvider, before+ // initial route classification, not inside this route.+ expect(screen.queryByTestId('service-hub')).not.toBeInTheDocument()expect(screen.getByTestId('theme-provider')).toBeInTheDocument()- expect(screen.getByTestId('extension-provider')).toBeInTheDocument()+ expect(screen.queryByTestId('extension-provider')).not.toBeInTheDocument()expect(screen.getByTestId('data-provider')).toBeInTheDocument()expect(screen.getByTestId('left-sidebar')).toBeInTheDocument()expect(screen.getByTestId('outlet')).toBeInTheDocument()diff --git a/web-app/src/routes/__tests__/artifacts.test.tsx b/web-app/src/routes/__tests__/artifacts.test.tsxnew file mode 100644index 000000000..381a45ae4--- /dev/null+++ b/web-app/src/routes/__tests__/artifacts.test.tsx@@ -0,0 +1,95 @@+import '@testing-library/jest-dom/vitest'+import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++const h = vi.hoisted(() => ({+ navigate: vi.fn(),+ select: vi.fn(),+ preview: vi.fn(),+ sessions: [] as unknown[],+}))++vi.mock('@tanstack/react-router', () => ({+ createFileRoute: () => (options: unknown) => ({ options }),+ useNavigate: () => h.navigate,+}))+vi.mock('@/i18n/react-i18next-compat', () => ({+ useTranslation: () => ({+ t: (k: string, o?: { count?: number }) =>+ o?.count !== undefined ? `${k}:${o.count}` : k,+ }),+}))+vi.mock('@/containers/HeaderPage', () => ({ default: () => null }))+vi.mock('@/containers/CoworkArtifactCard', () => ({+ CoworkArtifactCard: ({+ artifact,+ onPreview,+ }: {+ artifact: { title: string }+ onPreview: () => void+ }) => <button onClick={onPreview}>{artifact.title}</button>,+}))+vi.mock('@/hooks/useCoworkSessions', () => ({+ useCoworkSessions: Object.assign(+ (sel: (s: { sessions: unknown[] }) => unknown) =>+ sel({ sessions: h.sessions }),+ { getState: () => ({ selectSession: h.select }) }+ ),+}))+vi.mock('@/hooks/useCoworkRun', () => ({+ useCoworkRun: { getState: () => ({ requestPreview: h.preview }) },+}))+vi.mock('@/hooks/useServiceHub', () => ({+ getServiceHub: () => ({ app: () => ({ getJanDataFolder: async () => '/data' }) }),+}))+vi.mock('@janhq/tauri-plugin-agent-tools-api', () => ({+ threadWorkspacePath: async (_d: string, id: string) => `/data/threads/${id}`,+}))++import { Route } from '../artifacts'++const Page = (Route as unknown as { options: { component: () => JSX.Element } })+ .options.component++beforeEach(() => {+ h.navigate.mockClear()+ h.select.mockClear()+ h.preview.mockClear()+ h.sessions = [+ {+ id: 's1',+ title: 'Old session',+ updated: 5,+ folder: null,+ turns: [+ {+ role: 'tool',+ name: 'write',+ args: { path: 'old.html' },+ result: 'Created old.html (2 bytes)',+ },+ ],+ },+ ]+})+afterEach(cleanup)++describe('Artifacts page', () => {+ it('is not gated to builds that ship the Cowork surface', () => {+ expect(+ (Route as unknown as { options: { beforeLoad?: unknown } }).options+ .beforeLoad+ ).toBeUndefined()+ })++ it('opens the artifact in its conversation URL, not the bare /cowork', async () => {+ render(<Page />)+ fireEvent.click(await screen.findByText('old'))+ expect(h.select).toHaveBeenCalledWith('s1')+ expect(h.preview).toHaveBeenCalledWith('s1', expect.stringContaining('old.html'))+ expect(h.navigate).toHaveBeenCalledWith({+ to: '/cowork/$sessionId',+ params: { sessionId: 's1' },+ })+ })+})diff --git a/web-app/src/routes/__tests__/coworkRoutes.test.tsx b/web-app/src/routes/__tests__/coworkRoutes.test.tsxnew file mode 100644index 000000000..d73323a0e--- /dev/null+++ b/web-app/src/routes/__tests__/coworkRoutes.test.tsx@@ -0,0 +1,116 @@+import { describe, it, expect, beforeEach, vi } from 'vitest'++const mockParams: { sessionId?: string } = {}+vi.mock('@tanstack/react-router', () => ({+ createFileRoute: () => (options: unknown) => options,+ redirect: (r: unknown) => Object.assign(new Error('redirect'), { redirect: r }),+ useParams: () => mockParams,+ useNavigate: () => vi.fn(),+}))+vi.mock('@/containers/CoworkPage', () => ({ CoworkPage: () => null }))++import { act, render } from '@testing-library/react'+import { useCoworkSessions } from '@/hooks/useCoworkSessions'++type Opts = { beforeLoad: (a: { params?: Record<string, string> }) => void }+const run = (o: Opts, params?: Record<string, string>) => {+ try {+ o.beforeLoad({ params })+ return null+ } catch (e) {+ return (e as { redirect: { to: string; params?: unknown } }).redirect+ }+}++const seed = (ids: string[], currentId: string | null) =>+ useCoworkSessions.setState({+ sessions: ids.map((id) => ({+ id,+ title: id,+ folder: null,+ turns: [{ role: 'user', content: 'x' }],+ messages: [],+ updated: 1,+ })),+ currentId,+ })++describe('/cowork', () => {+ beforeEach(() => {+ seed([], null)+ })++ it('forwards to the current session', async () => {+ const { Route } = (await import('../cowork/index')) as unknown as { Route: Opts }+ seed(['a', 'b'], 'b')+ expect(run(Route)).toMatchObject({+ to: '/cowork/$sessionId',+ params: { sessionId: 'b' },+ })+ })++ it('goes home when there is no current session, without creating one', async () => {+ const { Route } = (await import('../cowork/index')) as unknown as { Route: Opts }+ expect(run(Route)).toMatchObject({ to: '/' })+ expect(useCoworkSessions.getState().sessions).toHaveLength(0)+ })+})++describe('/cowork/$sessionId', () => {+ beforeEach(() => {+ seed([], null)+ })++ it('opens a known session', async () => {+ const { Route } = (await import('../cowork/$sessionId')) as unknown as { Route: Opts }+ seed(['a'], null)+ expect(run(Route, { sessionId: 'a' })).toBeNull()+ })++ it('sends an untouched session to unified home', async () => {+ const { Route } = (await import('../cowork/$sessionId')) as unknown as { Route: Opts }+ useCoworkSessions.setState({+ sessions: [{ id: 'blank', title: 'blank', folder: null, turns: [], messages: [], updated: 1 }],+ currentId: null,+ })+ expect(run(Route, { sessionId: 'blank' })).toMatchObject({ to: '/' })+ expect(useCoworkSessions.getState().sessions).toHaveLength(1)+ })++ it('keeps a cleared session reachable instead of redirecting it home', async () => {+ const { Route } = (await import('../cowork/$sessionId')) as unknown as { Route: Opts }+ useCoworkSessions.setState({+ sessions: [{ id: 'cl', title: 'Kept', folder: null, turns: [], messages: [], updated: 1, cleared: true }],+ currentId: null,+ })+ expect(run(Route, { sessionId: 'cl' })).toBeNull()+ })++ it('redirects an unknown id home', async () => {+ const { Route } = (await import('../cowork/$sessionId')) as unknown as { Route: Opts }+ seed(['a'], null)+ expect(run(Route, { sessionId: 'nope' })).toMatchObject({ to: '/' })+ })++ it('selects the opened session in beforeLoad, after the existence check', async () => {+ const { Route } = (await import('../cowork/$sessionId')) as unknown as { Route: Opts }+ seed(['a', 'b'], 'b')+ expect(run(Route, { sessionId: 'nope' })).toMatchObject({ to: '/' })+ expect(useCoworkSessions.getState().currentId).toBe('b')+ expect(run(Route, { sessionId: 'a' })).toBeNull()+ expect(useCoworkSessions.getState().currentId).toBe('a')+ })++ it('does not re-select a session that was deleted while its route is still mounted', async () => {+ const { Route } = (await import('../cowork/$sessionId')) as unknown as {+ Route: Opts & { component: () => null }+ }+ seed(['a', 'b'], 'a')+ mockParams.sessionId = 'a'+ const Component = Route.component as unknown as () => null+ render(<Component />)+ act(() => useCoworkSessions.getState().deleteSession('a'))+ expect(useCoworkSessions.getState().sessions.map((s) => s.id)).toEqual(['b'])+ expect(useCoworkSessions.getState().currentId).toBe('b')+ })+})diff --git a/web-app/src/routes/__tests__/coworkSkills.test.tsx b/web-app/src/routes/__tests__/coworkSkills.test.tsxindex 3faa91490..0e0c866b9 100644--- a/web-app/src/routes/__tests__/coworkSkills.test.tsx+++ b/web-app/src/routes/__tests__/coworkSkills.test.tsx@@ -231,7 +231,7 @@ vi.mock('@/containers/CoworkParkedNotice', () => ({CoworkParkedNotice: () => null,}))-import { Route } from '../cowork'+import { CoworkPage } from '@/containers/CoworkPage'import { useSkills } from '@/hooks/useSkills'import { usePrompt } from '@/hooks/usePrompt'import { startNewSession, useCoworkSessions } from '@/hooks/useCoworkSessions'@@ -246,8 +246,6 @@ import {import { sessionToSidecar } from '@/lib/migrateCoworkSessions'import { localStorageKey } from '@/constants/localStorage'// The router mock returns the supplied component options directly.-const routeOptions = Route as unknown as { component: () => ReactNode }-const CoworkPage = routeOptions.componentfunction Manager() {const { write } = useSkills(null)return (diff --git a/web-app/src/routes/artifacts.tsx b/web-app/src/routes/artifacts.tsxindex 822912036..f44cfa991 100644--- a/web-app/src/routes/artifacts.tsx+++ b/web-app/src/routes/artifacts.tsx@@ -13,7 +13,6 @@ import {DropdownMenuTrigger,} from '@/components/ui/dropdown-menu'import { route } from '@/constants/routes'-import { ensureCoworkEnabled } from '@/lib/coworkAccess'import { useTranslation } from '@/i18n/react-i18next-compat'import { useCoworkSessions } from '@/hooks/useCoworkSessions'import { useCoworkRun } from '@/hooks/useCoworkRun'@@ -26,7 +25,6 @@ import {} from '@/lib/coworkArtifacts'export const Route = createFileRoute(route.artifacts as any)({- beforeLoad: () => ensureCoworkEnabled(),component: ArtifactsPage,})@@ -129,7 +127,10 @@ function ArtifactsPage() {const open = (row: Row) => {useCoworkSessions.getState().selectSession(row.sessionId)useCoworkRun.getState().requestPreview(row.sessionId, row.path)- navigate({ to: route.cowork })+ navigate({+ to: route.coworkSession,+ params: { sessionId: row.sessionId },+ })}return (diff --git a/web-app/src/routes/cowork/$sessionId.tsx b/web-app/src/routes/cowork/$sessionId.tsxnew file mode 100644index 000000000..53c435c18--- /dev/null+++ b/web-app/src/routes/cowork/$sessionId.tsx@@ -0,0 +1,40 @@+import { createFileRoute, redirect, useParams } from '@tanstack/react-router'+import { useEffect } from 'react'+import { useCoworkRun } from '@/hooks/useCoworkRun'+import { peekCoworkHandoff } from '@/lib/coworkHandoff'+import { route } from '@/constants/routes'+import { useCoworkSessions } from '@/hooks/useCoworkSessions'+import { CoworkPage } from '@/containers/CoworkPage'++export const Route = createFileRoute('/cowork/$sessionId')({+ beforeLoad: ({ params }) => {+ const { sessionId } = params as { sessionId: string }+ // Sessions are hydrated before routes render, so an id that is not in the+ // store is unknown, not "not loaded yet".+ const session = useCoworkSessions.getState().sessions.find((s) => s.id === sessionId)+ if (!session) throw redirect({ to: route.home, replace: true })+ // An untouched session is not a different start surface. Keep the unified+ // composer unless its first prompt is being handed off or a run is active.+ if (!session.unavailable && !session.cleared && !session.turns.length && !session.messages.length &&+ !useCoworkRun.getState().runId[sessionId] && !peekCoworkHandoff(sessionId)) {+ throw redirect({ to: route.home, replace: true })+ }+ // Select here, not while rendering: a render-phase store write warns on+ // every switch and re-selects a session deleted under the mounted route.+ useCoworkSessions.getState().selectSession(sessionId)+ },+ component: CoworkSessionRoute,+})++function CoworkSessionRoute() {+ const { sessionId } = useParams({ strict: false }) as { sessionId: string }+ // The URL is the source of truth: the page and every helper it calls read the+ // current session from the store, so keep the two in lockstep.+ // beforeLoad selects on navigation; this resyncs when only the param changes.+ useEffect(() => {+ if (useCoworkSessions.getState().sessions.some((s) => s.id === sessionId)) {+ useCoworkSessions.getState().selectSession(sessionId)+ }+ }, [sessionId])+ return <CoworkPage />+}diff --git a/web-app/src/routes/cowork/index.tsx b/web-app/src/routes/cowork/index.tsxnew file mode 100644index 000000000..8c4a9b9e0--- /dev/null+++ b/web-app/src/routes/cowork/index.tsx@@ -0,0 +1,24 @@+import { createFileRoute, redirect } from '@tanstack/react-router'+import { route } from '@/constants/routes'+import { useCoworkSessions } from '@/hooks/useCoworkSessions'++/**+ * `/cowork` has no conversation of its own any more: it forwards to the+ * current session's URL so every existing link (sidebar, artifacts, commands)+ * keeps working. Sessions are hydrated before any route renders, so reading the+ * store here sees them; it only reuses the current session when there is one,+ * and otherwise goes to the start page rather than creating one in a loader.+ */+export const Route = createFileRoute('/cowork/')({+ beforeLoad: () => {+ const { currentId, sessions } = useCoworkSessions.getState()+ if (currentId && sessions.some((s) => s.id === currentId)) {+ throw redirect({+ to: route.coworkSession,+ params: { sessionId: currentId },+ replace: true,+ })+ }+ throw redirect({ to: route.home, replace: true })+ },+})diff --git a/web-app/src/routes/settings/cowork.tsx b/web-app/src/routes/settings/cowork.tsxindex c0bbc817a..fd1c1275d 100644--- a/web-app/src/routes/settings/cowork.tsx+++ b/web-app/src/routes/settings/cowork.tsx@@ -1,7 +1,6 @@import { createFileRoute } from '@tanstack/react-router'import { useCallback, useEffect, useState } from 'react'import { route } from '@/constants/routes'-import { ensureCoworkEnabled } from '@/lib/coworkAccess'import HeaderPage from '@/containers/HeaderPage'import SettingsMenu from '@/containers/SettingsMenu'import { Card, CardItem } from '@/containers/Card'@@ -45,7 +44,6 @@ import {// eslint-disable-next-line @typescript-eslint/no-explicit-anyexport const Route = createFileRoute(route.settings.cowork as any)({- beforeLoad: () => ensureCoworkEnabled(route.settings.general),component: CoworkSettingsContent,})diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsxindex 0c363449f..dd7816cf7 100644--- a/web-app/src/routes/threads/$threadId.tsx+++ b/web-app/src/routes/threads/$threadId.tsx@@ -1,6 +1,12 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import type { CSSProperties } from 'react'-import { createFileRoute, useParams, useSearch } from '@tanstack/react-router'+import {+ createFileRoute,+ redirect,+ useParams,+ useRouter,+ useSearch,+} from '@tanstack/react-router'import { cn } from '@/lib/utils'import HeaderPage from '@/containers/HeaderPage'@@ -12,10 +18,17 @@ import { MessageItem } from '@/containers/MessageItem'import { useMessages } from '@/hooks/useMessages'import { useMessageErrors } from '@/stores/message-errors'import { buildLoadDiagnosticsReport } from '@/lib/loadDiagnosticsReport'-import { useServiceHub } from '@/hooks/useServiceHub'+import { getServiceHub, useServiceHub } from '@/hooks/useServiceHub'+import { useCoworkSessions } from '@/hooks/useCoworkSessions'+import GlobalError from '@/containers/GlobalError'+import { shouldRedirectThreadToCowork } from '@/lib/threadRouteGuard'+import {+ ThreadClassificationUnavailableError,+ resolveThreadForRoute,+} from '@/lib/threadRouteClassification'import { useTools } from '@/hooks/useTools'import { useAppState } from '@/hooks/useAppState'-import { SESSION_STORAGE_PREFIX } from '@/constants/chat'+import { SESSION_STORAGE_PREFIX, TEMPORARY_CHAT_ID } from '@/constants/chat'import { useChat } from '@/hooks/use-chat'import { useModelProvider } from '@/hooks/useModelProvider'import { engineSlotsIdle } from '@janhq/tauri-plugin-llamacpp-api'@@ -431,9 +444,80 @@ type SearchParams = {threadModel?: ThreadModel}+/**+ * Route-local error screen. A classification failure (the conversation backend+ * never answered within the startup retry window) is recoverable: Retry re-runs+ * `beforeLoad` via router.invalidate(), so the deep link is not stranded on the+ * root GlobalError, which only offers a full reload. Any other error keeps the+ * root boundary's presentation.+ */+function ThreadRouteError({ error }: { error: Error }) {+ const router = useRouter()+ const { t } = useTranslation()+ if (error instanceof ThreadClassificationUnavailableError) {+ return (+ <div className="flex h-full w-full items-center justify-center p-5">+ <div className="max-w-md text-center">+ <IconAlertCircle className="mx-auto size-8 text-destructive" />+ <h2 className="mt-3 text-base font-semibold text-main-view-fg">+ {t('common:threadRoute.notReadyTitle')}+ </h2>+ <p className="mt-2 text-sm text-muted-foreground">+ {t('common:threadRoute.notReadyDescription')}+ </p>+ <Button+ variant="outline"+ size="sm"+ className="mt-4"+ onClick={() => void router.invalidate()}+ >+ <IconRefresh className="size-4 mr-2" />+ {t('common:threadRoute.retry')}+ </Button>+ </div>+ </div>+ )+ }+ return <GlobalError error={error} />+}+// as route.threadsDetailexport const Route = createFileRoute('/threads/$threadId')({+ // A Cowork conversation runs on the Cowork runner and its transcript has a+ // sidecar authority: mounting the writable chat view over it would fork the+ // transcript into messages.jsonl. Decide before the chat view mounts.+ beforeLoad: async ({ params }) => {+ const { threadId } = params as { threadId: string }+ let thread: Thread | undefined = useThreads.getState().threads[threadId]+ // A deep link can load before the threads store hydrates, so a Cowork+ // thread would look like a chat. Look it up from the backend (bounded+ // retries, store re-read around every await; nothing fetched is written+ // back). An undecidable thread throws a typed error, rendered as Retry,+ // instead of mounting a writable chat. The temporary chat is never stored.+ if (!thread && threadId !== TEMPORARY_CHAT_ID) {+ thread = await resolveThreadForRoute<Thread>({+ threadId,+ readThread: () => useThreads.getState().threads[threadId],+ fetchThreads: () => getServiceHub().threads().fetchThreads(),+ isHydrated: () => useThreads.getState().threadsHydrated,+ })+ }+ if (+ shouldRedirectThreadToCowork(+ threadId,+ useCoworkSessions.getState().sessions,+ thread+ )+ ) {+ throw redirect({+ to: '/cowork/$sessionId',+ params: { sessionId: threadId },+ replace: true,+ })+ }+ },component: ThreadDetail,+ errorComponent: ThreadRouteError,validateSearch: (search: Record<string, unknown>): SearchParams => {return {threadModel: search.threadModel as ThreadModel | undefined,diff --git a/web-app/src/routes/threads/__tests__/$threadId.beforeLoad.test.tsx b/web-app/src/routes/threads/__tests__/$threadId.beforeLoad.test.tsxnew file mode 100644index 000000000..7aca122b9--- /dev/null+++ b/web-app/src/routes/threads/__tests__/$threadId.beforeLoad.test.tsx@@ -0,0 +1,403 @@+/**+ * Consumption regressions for the /threads/$threadId beforeLoad guard+ * (integrated persistence review R2/R3). These exercise the REAL Route+ * options with the REAL zustand stores — only the component tree around the+ * route is mocked — so they fail if the route stops consuming+ * shouldRedirectThreadToCowork.+ */+import { describe, it, expect, beforeEach, vi } from 'vitest'++vi.mock('@tanstack/react-router', () => ({+ createFileRoute: () => (options: unknown) => options,+ redirect: (r: unknown) => Object.assign(new Error('redirect'), { redirect: r }),+ useParams: () => ({}),+ useRouter: () => ({ invalidate: vi.fn() }),+ useSearch: () => ({}),+ Link: () => null,+}))++// The route module imports the full chat component tree; stub the heavy+// containers/hooks so importing the Route stays cheap. None of these are+// exercised: only `beforeLoad` runs.+vi.mock('@/containers/HeaderPage', () => ({ default: () => null }))+vi.mock('@/containers/ChatInput', () => ({ default: () => null }))+vi.mock('@/containers/MessageItem', () => ({ MessageItem: () => null }))+vi.mock('@/containers/ConversationHeaderTitle', () => ({+ ConversationHeaderTitle: () => null,+}))+vi.mock('@/hooks/use-chat', () => ({ useChat: vi.fn() }))+vi.mock('@/hooks/useChatShell', () => ({ useChatShell: vi.fn() }))+vi.mock('@janhq/tauri-plugin-llamacpp-api', () => ({ engineSlotsIdle: vi.fn() }))+vi.mock('@/lib/agentTools', () => ({+ CHAT_AGENT_TOOL_NAMES: [],+ executeAgentTool: vi.fn(),+}))+vi.mock('@/lib/webSearchTool', () => ({+ webToolRoute: vi.fn(),+ executeWebTool: vi.fn(),+}))++// beforeLoad falls back to a direct backend lookup when the threads store has+// no record (R3 hydration race). Default to a HEALTHY backend: a NON-empty+// list not containing the looked-up id. An empty list is no longer an+// authoritative answer before the startup inventory has committed, so it+// retries and fails closed; individual tests override per-case.+const healthyUnrelatedList = [+ { id: '__unrelated__', title: 'other', metadata: {} },+]+const fetchThreadsMock = vi.fn<() => Promise<unknown[]>>(() =>+ Promise.resolve(healthyUnrelatedList)+)+vi.mock('@/hooks/useServiceHub', () => ({+ getServiceHub: () => ({ threads: () => ({ fetchThreads: fetchThreadsMock }) }),+ useServiceHub: vi.fn(),+}))++import { Route } from '../$threadId'+import { useCoworkSessions, type CoworkSession } from '@/hooks/useCoworkSessions'+import { useThreads } from '@/hooks/useThreads'+import {+ THREAD_LOOKUP_ATTEMPTS,+ ThreadClassificationUnavailableError,+} from '@/lib/threadRouteClassification'+import type { Thread } from '@janhq/core'++type RouteOpts = {+ beforeLoad: (a: { params: { threadId: string } }) => void | Promise<void>+}++const runBeforeLoad = async (threadId: string) => {+ try {+ await (Route as unknown as RouteOpts).beforeLoad({ params: { threadId } })+ return null+ } catch (e) {+ return (e as { redirect: { to: string; params?: unknown; replace?: boolean } }).redirect+ }+}++const session = (+ id: string,+ unavailable?: CoworkSession['unavailable']+): CoworkSession =>+ ({+ id,+ title: id,+ folder: null,+ turns: [],+ messages: [],+ updated: 1,+ ...(unavailable ? { unavailable } : {}),+ }) as CoworkSession++const seedSessions = (sessions: CoworkSession[]) =>+ useCoworkSessions.setState({ sessions, currentId: null })++const seedThread = (id: string, metadata: Record<string, unknown> | undefined) =>+ useThreads.setState({+ threads: {+ [id]: {+ id,+ title: id,+ metadata,+ assistants: [],+ } as unknown as Thread,+ },+ })++describe('/threads/$threadId beforeLoad guard (R2/R3 consumption)', () => {+ beforeEach(() => {+ seedSessions([])+ useThreads.setState({ threads: {}, threadsHydrated: false })+ fetchThreadsMock.mockClear()+ fetchThreadsMock.mockImplementation(() =>+ Promise.resolve(healthyUnrelatedList)+ )+ })++ it('R2: an id-collision placeholder does NOT steal the route from the real chat', async () => {+ seedThread('shared-id', {})+ seedSessions([session('shared-id', 'id-collision')])+ expect(await runBeforeLoad('shared-id')).toBeNull()+ })++ it('a normal cowork session still redirects to /cowork/$sessionId', async () => {+ seedSessions([session('cw-1')])+ expect(await runBeforeLoad('cw-1')).toMatchObject({+ to: '/cowork/$sessionId',+ params: { sessionId: 'cw-1' },+ replace: true,+ })+ })++ it('unavailable placeholders other than id-collision keep redirecting (read-only Cowork view)', async () => {+ seedSessions([+ session('cw-missing', 'missing-sidecar'),+ session('cw-unreadable', 'unreadable-sidecar'),+ ])+ expect(await runBeforeLoad('cw-missing')).toMatchObject({+ to: '/cowork/$sessionId',+ params: { sessionId: 'cw-missing' },+ })+ expect(await runBeforeLoad('cw-unreadable')).toMatchObject({+ to: '/cowork/$sessionId',+ params: { sessionId: 'cw-unreadable' },+ })+ })++ it('R3: a cowork-mode thread redirects even with an EMPTY session store (no chat fork)', async () => {+ seedThread('cw-orphan', { mode: 'cowork' })+ expect(useCoworkSessions.getState().sessions).toHaveLength(0)+ expect(await runBeforeLoad('cw-orphan')).toMatchObject({+ to: '/cowork/$sessionId',+ params: { sessionId: 'cw-orphan' },+ replace: true,+ })+ })++ it('an ordinary chat thread with no session never redirects', async () => {+ seedThread('chat-1', {})+ expect(await runBeforeLoad('chat-1')).toBeNull()+ // unknown id entirely+ expect(await runBeforeLoad('unknown-id')).toBeNull()+ })++ it('R3 hydration race: BOTH stores empty, persisted cowork thread fetched from backend redirects', async () => {+ fetchThreadsMock.mockImplementation(() =>+ Promise.resolve([+ { id: 'cw-hydrating', title: 'cw', metadata: { mode: 'cowork' } },+ ])+ )+ expect(useCoworkSessions.getState().sessions).toHaveLength(0)+ expect(useThreads.getState().threads['cw-hydrating']).toBeUndefined()+ expect(await runBeforeLoad('cw-hydrating')).toMatchObject({+ to: '/cowork/$sessionId',+ params: { sessionId: 'cw-hydrating' },+ replace: true,+ })+ expect(fetchThreadsMock).toHaveBeenCalledTimes(1)+ // The fetched list is NOT written back: a stale fetch must never+ // overwrite a newer store hydration.+ expect(useThreads.getState().threads['cw-hydrating']).toBeUndefined()+ })++ it('R3 hydration race: a fetched ordinary chat thread mounts chat normally (no redirect)', async () => {+ fetchThreadsMock.mockImplementation(() =>+ Promise.resolve([{ id: 'chat-hydrating', title: 'chat', metadata: {} }])+ )+ expect(await runBeforeLoad('chat-hydrating')).toBeNull()+ expect(fetchThreadsMock).toHaveBeenCalledTimes(1)+ expect(useThreads.getState().threads['chat-hydrating']).toBeUndefined()+ })++ it('R3 stale-fetch race: a store record landing DURING the fetch wins over the stale backend snapshot', async () => {+ // The cowork commit (or a hydration) finishes while the deferred backend+ // lookup is in flight: the fetch was issued before the write completed, so+ // the backend snapshot resolves EMPTY. The post-await decision must re-read+ // the store — code that only consults `fetched.find(...)` classifies the+ // just-committed cowork thread as an ordinary chat and mounts a writable+ // chat view over it.+ fetchThreadsMock.mockImplementation(async () => {+ // Simulate the mid-await store write, then resolve the stale (pre-write)+ // backend snapshot.+ seedThread('cw-racing', { mode: 'cowork' })+ return []+ })+ expect(useThreads.getState().threads['cw-racing']).toBeUndefined()+ expect(await runBeforeLoad('cw-racing')).toMatchObject({+ to: '/cowork/$sessionId',+ params: { sessionId: 'cw-racing' },+ replace: true,+ })+ expect(fetchThreadsMock).toHaveBeenCalledTimes(1)+ // beforeLoad itself still never writes the fetched list back globally —+ // only the externally-landed record is present.+ expect(Object.keys(useThreads.getState().threads)).toEqual(['cw-racing'])+ })++ it('startup failure then recovery: the retry classifies the cowork thread and redirects', async () => {+ // Normal startup: the Conversational extension registers a beat after the+ // first route render, so the first fetch rejects and a later one succeeds.+ fetchThreadsMock+ .mockImplementationOnce(() =>+ Promise.reject(new Error('Conversational extension not available yet'))+ )+ .mockImplementationOnce(() =>+ Promise.resolve([+ { id: 'cw-startup', title: 'cw', metadata: { mode: 'cowork' } },+ ])+ )+ vi.useFakeTimers()+ try {+ const pending = runBeforeLoad('cw-startup')+ await vi.runAllTimersAsync()+ expect(await pending).toMatchObject({+ to: '/cowork/$sessionId',+ params: { sessionId: 'cw-startup' },+ replace: true,+ })+ } finally {+ vi.useRealTimers()+ }+ expect(fetchThreadsMock).toHaveBeenCalledTimes(2)+ })++ it('an exhausted retry window surfaces the typed recoverable error so no writable chat mounts', async () => {+ fetchThreadsMock.mockImplementation(() =>+ Promise.reject(new Error('Conversational extension not available yet'))+ )+ vi.useFakeTimers()+ try {+ const pending = (Route as unknown as RouteOpts)+ .beforeLoad({ params: { threadId: 'cw-undecidable' } }) as Promise<void>+ const settled = pending.then(+ () => null,+ (e) => e+ )+ await vi.runAllTimersAsync()+ const err = await settled+ expect(err).toBeInstanceOf(ThreadClassificationUnavailableError)+ } finally {+ vi.useRealTimers()+ }+ expect(fetchThreadsMock).toHaveBeenCalledTimes(THREAD_LOOKUP_ATTEMPTS)+ })++ it('a hydration landing mid-retry-window wins without waiting out the backend', async () => {+ // A resident record or success-only threadsHydrated skips the lookup;+ // isLoadingThreads alone is not an authoritative hydration signal.+ fetchThreadsMock.mockImplementation(() => {+ // Hydration lands after the first failed attempt.+ if (fetchThreadsMock.mock.calls.length === 1) {+ setTimeout(() => seedThread('cw-late', { mode: 'cowork' }), 0)+ }+ return Promise.reject(new Error('not ready'))+ })+ vi.useFakeTimers()+ try {+ const pending = runBeforeLoad('cw-late')+ await vi.runAllTimersAsync()+ expect(await pending).toMatchObject({+ to: '/cowork/$sessionId',+ params: { sessionId: 'cw-late' },+ replace: true,+ })+ } finally {+ vi.useRealTimers()+ }+ // Resolved from the store, well before the window exhausted.+ expect(fetchThreadsMock.mock.calls.length).toBeLessThan(+ THREAD_LOOKUP_ATTEMPTS+ )+ })++ it('an id unknown to a HEALTHY (non-empty) backend keeps the existing unknown-thread behavior', async () => {+ // fetchThreads resolves the non-empty default list without the id: not+ // found anywhere → no redirect, same as the pre-existing unknown-id path.+ expect(await runBeforeLoad('nowhere-id')).toBeNull()+ expect(fetchThreadsMock).toHaveBeenCalledTimes(1)+ })++ it('empty list then success: [] is treated as not-ready, the retry still redirects the cowork thread', async () => {+ // Before successful store hydration, an empty fallback cannot prove the+ // startup inventory has committed. Retry rather than mounting writable+ // Chat over an undecidable conversation.+ fetchThreadsMock+ .mockImplementationOnce(() => Promise.resolve([]))+ .mockImplementationOnce(() =>+ Promise.resolve([+ { id: 'cw-empty-first', title: 'cw', metadata: { mode: 'cowork' } },+ ])+ )+ vi.useFakeTimers()+ try {+ const pending = runBeforeLoad('cw-empty-first')+ await vi.runAllTimersAsync()+ expect(await pending).toMatchObject({+ to: '/cowork/$sessionId',+ params: { sessionId: 'cw-empty-first' },+ replace: true,+ })+ } finally {+ vi.useRealTimers()+ }+ expect(fetchThreadsMock).toHaveBeenCalledTimes(2)+ })++ it('an all-empty window fails closed with the typed error — no writable chat, no silent unknown', async () => {+ fetchThreadsMock.mockImplementation(() => Promise.resolve([]))+ vi.useFakeTimers()+ try {+ const pending = (Route as unknown as RouteOpts)+ .beforeLoad({ params: { threadId: 'cw-hidden' } }) as Promise<void>+ const settled = pending.then(+ () => null,+ (e) => e+ )+ await vi.runAllTimersAsync()+ const err = await settled+ expect(err).toBeInstanceOf(ThreadClassificationUnavailableError)+ } finally {+ vi.useRealTimers()+ }+ expect(fetchThreadsMock).toHaveBeenCalledTimes(THREAD_LOOKUP_ATTEMPTS)+ })++ it('success-hydrated store + genuinely empty list: a miss is authoritative, no fetch, no error', async () => {+ useThreads.setState({ threads: {}, threadsHydrated: true })+ expect(await runBeforeLoad('fresh-install-id')).toBeNull()+ expect(fetchThreadsMock).not.toHaveBeenCalled()+ })++ it('isLoadingThreads=false alone (DataProvider failure exhaustion) is NOT hydrated: still fails closed', async () => {+ useThreads.setState({ threads: {}, isLoadingThreads: false, threadsHydrated: false })+ fetchThreadsMock.mockImplementation(() => Promise.resolve([]))+ vi.useFakeTimers()+ try {+ const pending = Promise.resolve(+ (Route as unknown as RouteOpts).beforeLoad({+ params: { threadId: 'cw-hidden-2' },+ })+ ).then(+ () => null,+ (e) => e+ )+ await vi.runAllTimersAsync()+ expect(await pending).toBeInstanceOf(ThreadClassificationUnavailableError)+ } finally {+ vi.useRealTimers()+ useThreads.setState({ isLoadingThreads: true })+ }+ expect(fetchThreadsMock).toHaveBeenCalledTimes(THREAD_LOOKUP_ATTEMPTS)+ })++ it('hydrated flag never overrides a store-resident cowork record (persisted metadata wins)', async () => {+ seedThread('cw-hyd', { mode: 'cowork' })+ useThreads.setState({ threadsHydrated: true })+ expect(await runBeforeLoad('cw-hyd')).toMatchObject({+ to: '/cowork/$sessionId',+ })+ expect(fetchThreadsMock).not.toHaveBeenCalled()+ })++ it('a record committed during the fetch wins even when hydration lands in the same window', async () => {+ fetchThreadsMock.mockImplementation(() => {+ seedThread('cw-mid', { mode: 'cowork' })+ useThreads.setState({ threadsHydrated: true })+ return Promise.resolve([])+ })+ expect(await runBeforeLoad('cw-mid')).toMatchObject({+ to: '/cowork/$sessionId',+ })+ })++ it('the temporary chat id never triggers a backend fetch', async () => {+ expect(await runBeforeLoad('temporary-chat')).toBeNull()+ expect(fetchThreadsMock).not.toHaveBeenCalled()+ })++ it('a store-resident thread never triggers a backend fetch', async () => {+ seedThread('chat-1', {})+ expect(await runBeforeLoad('chat-1')).toBeNull()+ expect(fetchThreadsMock).not.toHaveBeenCalled()+ })+})