Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(web-app): reconcile local API server status with the backend on boot (#9629)
Akarshan Biswasd24eba1741a4
diff --git a/web-app/src/hooks/__tests__/usePrompt.test.ts b/web-app/src/hooks/__tests__/usePrompt.test.tsindex ccdb8ec67..c0a8b5bf8 100644--- a/web-app/src/hooks/__tests__/usePrompt.test.ts+++ b/web-app/src/hooks/__tests__/usePrompt.test.ts@@ -91,3 +91,22 @@ describe('usePrompt', () => {})})})++describe('usePrompt draft persistence', () => {+ it('writes only the prompt to sessionStorage so a reload can restore it', () => {+ usePrompt.setState({ prompt: '', promptHistory: [], historyIndex: -1, draftPrompt: '' })+ act(() => usePrompt.getState().setPrompt('unsent draft'))++ const stored = JSON.parse(sessionStorage.getItem('chat-prompt-draft') ?? '{}')+ expect(stored.state).toEqual({ prompt: 'unsent draft' })+ })++ it('rehydrates the draft from sessionStorage', async () => {+ sessionStorage.setItem(+ 'chat-prompt-draft',+ JSON.stringify({ state: { prompt: 'restored' }, version: 0 })+ )+ await usePrompt.persist.rehydrate()+ expect(usePrompt.getState().prompt).toBe('restored')+ })+})diff --git a/web-app/src/hooks/usePrompt.ts b/web-app/src/hooks/usePrompt.tsindex 1c97ef20f..b8cb8320d 100644--- a/web-app/src/hooks/usePrompt.ts+++ b/web-app/src/hooks/usePrompt.ts@@ -1,4 +1,5 @@import { create } from 'zustand'+import { persist, createJSONStorage } from 'zustand/middleware'const MAX_HISTORY_SIZE = 100@@ -16,66 +17,77 @@ type PromptStoreState = {resetHistoryNavigation: () => void}-export const usePrompt = create<PromptStoreState>((set, get) => ({- prompt: '',- setPrompt: (value) => {- set({ prompt: value })- // Reset history navigation when user types manually- if (get().historyIndex !== -1) {- set({ historyIndex: -1 })- }- },- resetPrompt: () => set({ prompt: '' }),-- // History state- promptHistory: [],- historyIndex: -1,- draftPrompt: '',+// The unsent draft lives in sessionStorage so it survives a webview reload+// (e.g. WebKitGTK recovering a hidden window) but not a fresh app launch.+export const usePrompt = create<PromptStoreState>()(+ persist(+ (set, get) => ({+ prompt: '',+ setPrompt: (value) => {+ set({ prompt: value })+ // Reset history navigation when user types manually+ if (get().historyIndex !== -1) {+ set({ historyIndex: -1 })+ }+ },+ resetPrompt: () => set({ prompt: '' }),- addToHistory: (value) => {- const trimmed = value.trim()- if (!trimmed) return- const { promptHistory } = get()- // Avoid consecutive duplicates- if (promptHistory.length > 0 && promptHistory[0] === trimmed) return- set({- promptHistory: [trimmed, ...promptHistory].slice(0, MAX_HISTORY_SIZE),+ // History state+ promptHistory: [],historyIndex: -1,- })- },-- navigateHistory: (direction) => {- const { promptHistory, historyIndex, prompt, draftPrompt } = get()- if (promptHistory.length === 0) return+ draftPrompt: '',- if (direction === 'up') {- const nextIndex = historyIndex + 1- if (nextIndex >= promptHistory.length) return- // Save current input as draft when first entering history- const newDraft = historyIndex === -1 ? prompt : draftPrompt- set({- historyIndex: nextIndex,- draftPrompt: newDraft,- prompt: promptHistory[nextIndex],- })- } else {- // direction === 'down'- if (historyIndex <= -1) return- const nextIndex = historyIndex - 1- if (nextIndex === -1) {- // Restore draft+ addToHistory: (value) => {+ const trimmed = value.trim()+ if (!trimmed) return+ const { promptHistory } = get()+ // Avoid consecutive duplicates+ if (promptHistory.length > 0 && promptHistory[0] === trimmed) returnset({+ promptHistory: [trimmed, ...promptHistory].slice(0, MAX_HISTORY_SIZE),historyIndex: -1,- prompt: draftPrompt,- })- } else {- set({- historyIndex: nextIndex,- prompt: promptHistory[nextIndex],})- }- }- },+ },++ navigateHistory: (direction) => {+ const { promptHistory, historyIndex, prompt, draftPrompt } = get()+ if (promptHistory.length === 0) return- resetHistoryNavigation: () => set({ historyIndex: -1, draftPrompt: '' }),-}))+ if (direction === 'up') {+ const nextIndex = historyIndex + 1+ if (nextIndex >= promptHistory.length) return+ // Save current input as draft when first entering history+ const newDraft = historyIndex === -1 ? prompt : draftPrompt+ set({+ historyIndex: nextIndex,+ draftPrompt: newDraft,+ prompt: promptHistory[nextIndex],+ })+ } else {+ // direction === 'down'+ if (historyIndex <= -1) return+ const nextIndex = historyIndex - 1+ if (nextIndex === -1) {+ // Restore draft+ set({+ historyIndex: -1,+ prompt: draftPrompt,+ })+ } else {+ set({+ historyIndex: nextIndex,+ prompt: promptHistory[nextIndex],+ })+ }+ }+ },++ resetHistoryNavigation: () => set({ historyIndex: -1, draftPrompt: '' }),+ }),+ {+ name: 'chat-prompt-draft',+ storage: createJSONStorage(() => sessionStorage),+ partialize: (state) => ({ prompt: state.prompt }),+ }+ )+)diff --git a/web-app/src/providers/DataProvider.tsx b/web-app/src/providers/DataProvider.tsxindex 05b26a685..75a7bf529 100644--- a/web-app/src/providers/DataProvider.tsx+++ b/web-app/src/providers/DataProvider.tsx@@ -401,79 +401,84 @@ export function DataProvider() {)}, [serviceHub, runInBackground])- // Auto-start Local API Server on app startup if enabled+ // Reconcile the UI with the backend server on every webview boot (the Rust+ // server outlives the webview, e.g. across a hide-to-tray reload), then+ // auto-start it only if enabled and not already running.useEffect(() => {- if (enableOnStartup) {- // Check if server is already running- serviceHub- .app()- .getServerStatus()- .then(async (isRunning) => {- if (isRunning) {- console.log('Local API Server is already running')- setServerStatus('running')- return- }+ // Only a start this effect began may be rolled back to 'stopped': a failed+ // status query must not clobber a start the user began elsewhere.+ let startedPending = false+ serviceHub+ .app()+ .getServerStatus()+ .then(async (isRunning) => {+ if (isRunning) {+ console.log('Local API Server is already running')+ setServerStatus('running')+ return+ }- setServerStatus('pending')+ if (!enableOnStartup) return- // Start model(s): prefer user-configured default, fall back to last session's models- const modelsToStart = (() => {- if (defaultModelLocalApiServer) {- return [defaultModelLocalApiServer]- }- return lastServerModels- })()-- if (modelsToStart.length > 0) {- await Promise.allSettled(- modelsToStart.map(async ({ model, provider: providerName }) => {- const provider = getProviderByName(providerName)- if (!provider) return- try {- await serviceHub.models().startModel(provider, model, true)- console.log(`Auto-started server model: ${model}`)- } catch (err) {- console.warn(`Failed to auto-start server model ${model}:`, err)- }- })- )- }+ setServerStatus('pending')+ startedPending = true- return window.core?.api- ?.startServer({- host: serverHost,- port: serverPort,- prefix: apiPrefix,- apiKey,- trustedHosts,- isCorsEnabled: corsEnabled,- isVerboseEnabled: verboseLogs,- proxyTimeout: proxyTimeout,- })- .then(async (actualPort: number) => {- // Store the actual port that was assigned (important for mobile with port 0)- if (actualPort && actualPort !== serverPort) {- setServerPort(actualPort)- }- setServerStatus('running')- // Persist whichever models are actually running so next startup can restore them- const activeModels = await serviceHub.models().getActiveModels().catch(() => [] as string[])- if (activeModels.length > 0) {- const allProviders = useModelProvider.getState().providers- const serverModels = activeModels.flatMap((id) => {- const p = allProviders.find((p) => p?.models?.some((m: { id: string }) => m.id === id))- return p ? [{ model: id, provider: p.provider }] : []- })- if (serverModels.length > 0) setLastServerModels(serverModels)+ // Start model(s): prefer user-configured default, fall back to last session's models+ const modelsToStart = (() => {+ if (defaultModelLocalApiServer) {+ return [defaultModelLocalApiServer]+ }+ return lastServerModels+ })()++ if (modelsToStart.length > 0) {+ await Promise.allSettled(+ modelsToStart.map(async ({ model, provider: providerName }) => {+ const provider = getProviderByName(providerName)+ if (!provider) return+ try {+ await serviceHub.models().startModel(provider, model, true)+ console.log(`Auto-started server model: ${model}`)+ } catch (err) {+ console.warn(`Failed to auto-start server model ${model}:`, err)}})- })- .catch((error: unknown) => {- console.error('Failed to start Local API Server on startup:', error)- setServerStatus('stopped')- })- }+ )+ }++ return window.core?.api+ ?.startServer({+ host: serverHost,+ port: serverPort,+ prefix: apiPrefix,+ apiKey,+ trustedHosts,+ isCorsEnabled: corsEnabled,+ isVerboseEnabled: verboseLogs,+ proxyTimeout: proxyTimeout,+ })+ .then(async (actualPort: number) => {+ // Store the actual port that was assigned (important for mobile with port 0)+ if (actualPort && actualPort !== serverPort) {+ setServerPort(actualPort)+ }+ setServerStatus('running')+ // Persist whichever models are actually running so next startup can restore them+ const activeModels = await serviceHub.models().getActiveModels().catch(() => [] as string[])+ if (activeModels.length > 0) {+ const allProviders = useModelProvider.getState().providers+ const serverModels = activeModels.flatMap((id) => {+ const p = allProviders.find((p) => p?.models?.some((m: { id: string }) => m.id === id))+ return p ? [{ model: id, provider: p.provider }] : []+ })+ if (serverModels.length > 0) setLastServerModels(serverModels)+ }+ })+ })+ .catch((error: unknown) => {+ console.error('Failed to sync or start Local API Server on startup:', error)+ if (startedPending) setServerStatus('stopped')+ })// eslint-disable-next-line react-hooks/exhaustive-deps}, [serviceHub])diff --git a/web-app/src/providers/__tests__/DataProvider.test.tsx b/web-app/src/providers/__tests__/DataProvider.test.tsxindex 72948a46b..58bd80913 100644--- a/web-app/src/providers/__tests__/DataProvider.test.tsx+++ b/web-app/src/providers/__tests__/DataProvider.test.tsx@@ -473,10 +473,19 @@ describe('DataProvider', () => {it('does not start server on mount when enableOnStartup is false', async () => {render(<DataProvider />)- await act(async () => {- await Promise.resolve()+ await waitFor(() => {+ expect(hubState.getServerStatus).toHaveBeenCalled()+ })+ expect(h.setServerStatus).not.toHaveBeenCalledWith('pending')+ expect(hubState.startServer).not.toHaveBeenCalled()+ })++ it('reflects an already-running server on boot even when enableOnStartup is false', async () => {+ hubState.getServerStatus.mockResolvedValue(true)+ render(<DataProvider />)+ await waitFor(() => {+ expect(h.setServerStatus).toHaveBeenCalledWith('running')})- expect(hubState.getServerStatus).not.toHaveBeenCalled()expect(hubState.startServer).not.toHaveBeenCalled()})@@ -516,10 +525,11 @@ describe('DataProvider', () => {})})- it('sets server status to stopped on startup failure', async () => {+ it('sets server status to stopped when the startup start fails', async () => {const err = vi.spyOn(console, 'error').mockImplementation(() => {})h.localApi.enableOnStartup = true- hubState.getServerStatus.mockRejectedValue(new Error('fail'))+ hubState.getServerStatus.mockResolvedValue(false)+ hubState.startServer.mockRejectedValue(new Error('fail'))render(<DataProvider />)await waitFor(() => {expect(h.setServerStatus).toHaveBeenCalledWith('stopped')@@ -527,6 +537,17 @@ describe('DataProvider', () => {err.mockRestore()})+ it('leaves the status alone when only the status query fails', async () => {+ const err = vi.spyOn(console, 'error').mockImplementation(() => {})+ hubState.getServerStatus.mockRejectedValue(new Error('fail'))+ render(<DataProvider />)+ await waitFor(() => {+ expect(err).toHaveBeenCalled()+ })+ expect(h.setServerStatus).not.toHaveBeenCalled()+ err.mockRestore()+ })+it('navigates to hub model route when handling a valid deep link', async () => {const deeplinkUrl = 'jan://host/action/owner/repo'hubState.deeplinkGetCurrent.mockResolvedValue([deeplinkUrl])diff --git a/web-app/src/routes/settings/__tests__/local-api-server.test.tsx b/web-app/src/routes/settings/__tests__/local-api-server.test.tsxindex 90536b8e3..e545368fe 100644--- a/web-app/src/routes/settings/__tests__/local-api-server.test.tsx+++ b/web-app/src/routes/settings/__tests__/local-api-server.test.tsx@@ -7,10 +7,11 @@ import { toast } from 'sonner'const ensureModelForServer = vi.hoisted(() => vi.fn())const startServer = vi.hoisted(() => vi.fn())+const getServerStatus = vi.hoisted(() => vi.fn())// One stable object: the page re-runs an effect whenever the hub identity changes.const hub = vi.hoisted(() => ({models: () => ({ getActiveModels: () => Promise.resolve([]) }),- app: () => ({ getServerStatus: () => Promise.resolve(false) }),+ app: () => ({ getServerStatus }),window: () => ({ openLocalApiServerLogsWindow: () => Promise.resolve() }),}))@@ -51,9 +52,25 @@ describe('Local API server page: starting on a public address', () => {ensureModelForServer.mockResolvedValue({ status: 'loaded' })startServer.mockResolvedValue(1337);(window as unknown as { core: unknown }).core = { api: { startServer } }+ getServerStatus.mockResolvedValue(false)useAppState.setState({ serverStatus: 'stopped' })})+ it('corrects a stale running status when the backend server is stopped', async () => {+ useAppState.setState({ serverStatus: 'running' })+ render(<Page />)++ await waitFor(() => expect(useAppState.getState().serverStatus).toBe('stopped'))+ })++ it('leaves a pending status alone when the backend is not running yet', async () => {+ useAppState.setState({ serverStatus: 'pending' })+ render(<Page />)++ await waitFor(() => expect(getServerStatus).toHaveBeenCalled())+ expect(useAppState.getState().serverStatus).toBe('pending')+ })+it.each(['', ' '])('asks for an API key instead of loading a model when the host is 0.0.0.0 and the key is %j',(apiKey) => {diff --git a/web-app/src/routes/settings/local-api-server.tsx b/web-app/src/routes/settings/local-api-server.tsxindex 960006475..c269d2337 100644--- a/web-app/src/routes/settings/local-api-server.tsx+++ b/web-app/src/routes/settings/local-api-server.tsx@@ -98,6 +98,9 @@ function LocalAPIServerContent() {console.log('Server status check:', running)if (running) {setServerStatus('running')+ } else if (useAppState.getState().serverStatus === 'running') {+ // Never touch 'pending': a start/stop of ours is still in flight.+ setServerStatus('stopped')}} catch (error) {console.error('Failed to check server status:', error)