mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
fix: preserve prompt text on network error and allow offline typing (#276)
* fix: preserve prompt text on network error and allow offline typing * fix: preserve prompt on network error, swallow 524 to avoid duplicate sends * feat: add service worker precaching with app shell and runtime cache strategies * fix: copy frontend/plugins into Docker build context * fix: improve service worker update checks with visibility and focus handlers * fix: add connect timeout to event stream to recover from failed connections * fix: remove optimistic message insert, keep prompt in input until server confirms
This commit is contained in:
1 parent
a7d0c13f9a
commit
3e617c2df8
18 files changed
+569
-57
No files matched your search
@@ -17,6 +17,7 @@ import { VersionNotifier } from './components/VersionNotifier'
|
||||
import { PwaUpdatePrompt } from '@/components/PwaUpdatePrompt'
|
||||
import { MobileTabBar } from '@/components/navigation/MobileTabBar'
|
||||
import { MobileSheetHost } from '@/components/navigation/MobileSheetHost'
|
||||
import { RouteErrorBoundary } from '@/components/ui/route-error-boundary'
|
||||
import { DesktopSidebar } from '@/components/navigation/DesktopSidebar'
|
||||
import { useTheme } from './hooks/useTheme'
|
||||
import { useRightEdgeSwipe, useSwipeBack } from './hooks/useMobile'
|
||||
@@ -185,6 +186,7 @@ function AppShell() {
|
||||
const router = createBrowserRouter([
|
||||
{
|
||||
element: <AppShell />,
|
||||
errorElement: <RouteErrorBoundary />,
|
||||
children: [
|
||||
{
|
||||
path: '/login',
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import { useRouteError, isRouteErrorResponse } from 'react-router-dom'
|
||||
import { AlertTriangle, RefreshCw, LogIn, WifiOff } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { parseNetworkError, parseOpenCodeError } from '@/lib/opencode-errors'
|
||||
import type { OpenCodeError } from '@/lib/opencode-errors'
|
||||
|
||||
function isOpenCodeError(error: unknown): error is OpenCodeError {
|
||||
return typeof error === 'object' && error !== null && 'name' in error && 'data' in error
|
||||
}
|
||||
|
||||
function getErrorDetails(error: unknown) {
|
||||
if (isRouteErrorResponse(error)) {
|
||||
if (error.status === 401 || error.status === 403) {
|
||||
return {
|
||||
title: 'Authentication Required',
|
||||
message: 'Please log in to access this page.',
|
||||
isRetryable: false,
|
||||
statusCode: error.status,
|
||||
}
|
||||
}
|
||||
if (error.status === 404) {
|
||||
return {
|
||||
title: 'Page Not Found',
|
||||
message: 'The page you are looking for does not exist.',
|
||||
isRetryable: false,
|
||||
statusCode: error.status,
|
||||
}
|
||||
}
|
||||
return {
|
||||
title: error.statusText || 'Error',
|
||||
message: error.data?.message || error.status.toString(),
|
||||
isRetryable: true,
|
||||
statusCode: error.status,
|
||||
}
|
||||
}
|
||||
|
||||
if (isOpenCodeError(error)) {
|
||||
const parsed = parseOpenCodeError(error)
|
||||
if (parsed) return parsed
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
const networkParsed = parseNetworkError(error)
|
||||
if (networkParsed.title === 'Connection Failed') {
|
||||
return {
|
||||
...networkParsed,
|
||||
title: "You're offline",
|
||||
message: '',
|
||||
isRetryable: false,
|
||||
variant: 'offline' as const,
|
||||
}
|
||||
}
|
||||
return networkParsed
|
||||
}
|
||||
|
||||
return {
|
||||
title: 'Unexpected Error',
|
||||
message: 'An unexpected error occurred. Please try refreshing the page.',
|
||||
isRetryable: true,
|
||||
}
|
||||
}
|
||||
|
||||
export function RouteErrorBoundary() {
|
||||
const error = useRouteError()
|
||||
const details = getErrorDetails(error)
|
||||
const { title, message, isRetryable, statusCode } = details
|
||||
|
||||
const isAuthError = statusCode === 401 || statusCode === 403
|
||||
|
||||
if ('variant' in details && details.variant === 'offline') {
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col items-center justify-center gap-6 bg-background text-foreground">
|
||||
<img src="/icons/icon-192x192.png" alt="" className="h-36 w-36" />
|
||||
<div className="flex items-center gap-3 text-2xl font-semibold text-foreground">
|
||||
<WifiOff className="h-6 w-6" />
|
||||
<span>{title}</span>
|
||||
</div>
|
||||
<Button variant="outline" onClick={() => window.location.reload()} className="gap-2">
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
Reload
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center min-h-screen gap-6 p-6 text-center bg-background">
|
||||
<AlertTriangle className="w-12 h-12 text-destructive" />
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-xl font-semibold text-foreground">{title}</h1>
|
||||
<p className="text-sm text-muted-foreground max-w-sm">{message}</p>
|
||||
</div>
|
||||
<div className="flex gap-3">
|
||||
{isAuthError && (
|
||||
<Button variant="default" onClick={() => (window.location.href = '/login')}>
|
||||
<LogIn className="w-4 h-4 mr-2" />
|
||||
Log in
|
||||
</Button>
|
||||
)}
|
||||
{isRetryable && (
|
||||
<Button variant="outline" onClick={() => window.location.reload()} className="gap-2">
|
||||
<RefreshCw className="w-4 h-4" />
|
||||
Try again
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import type {
|
||||
MessageWithParts,
|
||||
} from "../api/types";
|
||||
import type { paths, components } from "../api/opencode-types";
|
||||
import { parseNetworkError } from "../lib/opencode-errors";
|
||||
import { parseNetworkError, isGatewayTimeout } from "../lib/opencode-errors";
|
||||
import { showToast } from "../lib/toast";
|
||||
import { useSendErrorStore } from "../stores/sendErrorStore";
|
||||
import { useSessionStatus } from "../stores/sessionStatusStore";
|
||||
@@ -401,27 +401,9 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
|
||||
}) => {
|
||||
if (!client) throw new Error("No client available");
|
||||
|
||||
const optimisticUserID = `optimistic_user_${Date.now()}_${Math.random()}`;
|
||||
|
||||
const contentParts = parts || [{ type: "text" as const, content: prompt || "", name: "" }];
|
||||
const userMessageParts = createOptimisticUserMessageParts(
|
||||
sessionID,
|
||||
contentParts,
|
||||
optimisticUserID,
|
||||
);
|
||||
const userMessageInfo = createOptimisticUserMessageInfo(sessionID, optimisticUserID, model, agent, variant);
|
||||
|
||||
const queryKey = messagesQueryKey(opcodeUrl, sessionID, directory);
|
||||
await queryClient.cancelQueries({ queryKey });
|
||||
|
||||
const optimisticMessageWithParts: MessageWithParts = {
|
||||
info: userMessageInfo,
|
||||
parts: userMessageParts,
|
||||
}
|
||||
queryClient.setQueryData<MessageWithParts[]>(
|
||||
queryKey,
|
||||
(old) => [...(old || []), optimisticMessageWithParts],
|
||||
);
|
||||
useSessionStatus.getState().setOptimisticActive(sessionID);
|
||||
|
||||
const requestData: SendPromptRequest = {
|
||||
@@ -490,15 +472,15 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
|
||||
throw error;
|
||||
}
|
||||
|
||||
return { optimisticUserID, queued: true };
|
||||
return { queued: true };
|
||||
}
|
||||
|
||||
const response = await client.sendPrompt(sessionID, requestData);
|
||||
|
||||
return { optimisticUserID, response, queued: false };
|
||||
return { response, queued: false };
|
||||
},
|
||||
onError: (error, variables) => {
|
||||
const { sessionID, queued } = variables;
|
||||
const { sessionID, queued, prompt, parts } = variables;
|
||||
const queryKey = messagesQueryKey(opcodeUrl, sessionID, directory);
|
||||
|
||||
if (queued) {
|
||||
@@ -509,22 +491,21 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
|
||||
queryKey,
|
||||
(old) => old?.filter((msgWithParts) => !msgWithParts.info.id.startsWith("optimistic_")),
|
||||
);
|
||||
|
||||
const isNetworkError = error instanceof TypeError ||
|
||||
(error instanceof FetchError && (error.code === 'TIMEOUT' || error.statusCode === 524));
|
||||
|
||||
if (isNetworkError) {
|
||||
if (isGatewayTimeout(error)) {
|
||||
return;
|
||||
}
|
||||
|
||||
useSessionStatus.getState().clearStatus(sessionID);
|
||||
|
||||
const parsed = parseNetworkError(error);
|
||||
const failedPrompt = getPromptText(prompt, parts);
|
||||
useSendErrorStore.getState().setError({
|
||||
sessionID,
|
||||
title: parsed.title,
|
||||
message: parsed.message,
|
||||
detail: error instanceof FetchError ? error.detail : undefined,
|
||||
failedPrompt: failedPrompt || undefined,
|
||||
});
|
||||
},
|
||||
onSuccess: async (data, variables) => {
|
||||
|
||||
@@ -4,6 +4,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { createElement } from 'react'
|
||||
import { useSendPrompt } from './useOpenCode'
|
||||
import { FetchError } from '../api/fetchWrapper'
|
||||
import { messagesQueryKey } from '../lib/queryInvalidation'
|
||||
|
||||
const mockSendPrompt = vi.fn()
|
||||
const mockSendPromptAsync = vi.fn()
|
||||
@@ -40,6 +41,7 @@ vi.mock('../lib/opencode-errors', () => ({
|
||||
message: err.message,
|
||||
isRetryable: false,
|
||||
})),
|
||||
isGatewayTimeout: vi.fn((err) => err?.statusCode === 524),
|
||||
}))
|
||||
|
||||
const mockClearError = vi.fn()
|
||||
@@ -264,4 +266,68 @@ describe('useSendPrompt', () => {
|
||||
|
||||
expect(mockClearError).toHaveBeenCalledWith('session-2')
|
||||
})
|
||||
|
||||
it('rolls back optimistic prompt and stores failed prompt on network failure', async () => {
|
||||
const queryKey = messagesQueryKey('http://localhost:5551', 'session-lost', '/test')
|
||||
queryClient.setQueryData(queryKey, [])
|
||||
mockSendPrompt.mockRejectedValueOnce(new TypeError('Failed to fetch'))
|
||||
|
||||
const { result } = renderHookWithProviders()
|
||||
|
||||
await expect(
|
||||
result.current.mutateAsync({
|
||||
sessionID: 'session-lost',
|
||||
prompt: 'keep this prompt',
|
||||
})
|
||||
).rejects.toThrow('Failed to fetch')
|
||||
|
||||
expect(mockClearStatus).toHaveBeenCalledWith('session-lost')
|
||||
expect(mockSetError).toHaveBeenCalledWith(expect.objectContaining({
|
||||
sessionID: 'session-lost',
|
||||
failedPrompt: 'keep this prompt',
|
||||
}))
|
||||
expect(queryClient.getQueryData(queryKey)).toEqual([])
|
||||
})
|
||||
|
||||
it('stores failed prompt when queued async request fails before reaching OpenCode', async () => {
|
||||
mockSendPromptAsync.mockRejectedValueOnce(new TypeError('Failed to fetch'))
|
||||
|
||||
const { result } = renderHookWithProviders()
|
||||
|
||||
await expect(
|
||||
result.current.mutateAsync({
|
||||
sessionID: 'session-queued-lost',
|
||||
prompt: 'queued while disconnected',
|
||||
queued: true,
|
||||
})
|
||||
).rejects.toThrow('Failed to fetch')
|
||||
|
||||
expect(mockClearQueuedPrompt).toHaveBeenCalledWith('session-queued-lost')
|
||||
expect(mockClearStatus).toHaveBeenCalledWith('session-queued-lost')
|
||||
expect(mockSetError).toHaveBeenCalledWith(expect.objectContaining({
|
||||
sessionID: 'session-queued-lost',
|
||||
failedPrompt: 'queued while disconnected',
|
||||
}))
|
||||
})
|
||||
|
||||
it('rolls back optimistic message but keeps status and surfaces no error on gateway timeout', async () => {
|
||||
const queryKey = messagesQueryKey('http://localhost:5551', 'session-524', '/test')
|
||||
queryClient.setQueryData(queryKey, [
|
||||
{ info: { id: 'optimistic_user_1' }, parts: [] },
|
||||
])
|
||||
mockSendPrompt.mockRejectedValueOnce(new FetchError('Gateway timeout', 524))
|
||||
|
||||
const { result } = renderHookWithProviders()
|
||||
|
||||
await expect(
|
||||
result.current.mutateAsync({
|
||||
sessionID: 'session-524',
|
||||
prompt: 'long running prompt',
|
||||
})
|
||||
).rejects.toThrow('Gateway timeout')
|
||||
|
||||
expect(queryClient.getQueryData(queryKey)).toEqual([])
|
||||
expect(mockClearStatus).not.toHaveBeenCalled()
|
||||
expect(mockSetError).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,114 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { FetchError } from '@opencode-manager/shared'
|
||||
import { parseNetworkError, isGatewayTimeout } from './opencode-errors'
|
||||
|
||||
describe('parseNetworkError', () => {
|
||||
it('classifies TypeError("Failed to fetch") as Connection Failed', () => {
|
||||
const result = parseNetworkError(new TypeError('Failed to fetch'))
|
||||
expect(result).toEqual({
|
||||
title: 'Connection Failed',
|
||||
message: 'Could not connect to the server. Please check your connection.',
|
||||
isRetryable: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('classifies Error("fetch failed") as Connection Failed', () => {
|
||||
const result = parseNetworkError(new Error('fetch failed'))
|
||||
expect(result).toEqual({
|
||||
title: 'Connection Failed',
|
||||
message: 'Could not connect to the server. Please check your connection.',
|
||||
isRetryable: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('classifies Error("Network Error") as Connection Failed', () => {
|
||||
const result = parseNetworkError(new Error('Network Error'))
|
||||
expect(result).toEqual({
|
||||
title: 'Connection Failed',
|
||||
message: 'Could not connect to the server. Please check your connection.',
|
||||
isRetryable: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('classifies Error("ECONNREFUSED") as Connection Failed', () => {
|
||||
const result = parseNetworkError(new Error('ECONNREFUSED'))
|
||||
expect(result).toEqual({
|
||||
title: 'Connection Failed',
|
||||
message: 'Could not connect to the server. Please check your connection.',
|
||||
isRetryable: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('classifies Error("ECONNRESET") as Connection Failed', () => {
|
||||
const result = parseNetworkError(new Error('ECONNRESET'))
|
||||
expect(result).toEqual({
|
||||
title: 'Connection Failed',
|
||||
message: 'Could not connect to the server. Please check your connection.',
|
||||
isRetryable: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('classifies Error("networkerror") as Connection Failed', () => {
|
||||
const result = parseNetworkError(new Error('networkerror'))
|
||||
expect(result).toEqual({
|
||||
title: 'Connection Failed',
|
||||
message: 'Could not connect to the server. Please check your connection.',
|
||||
isRetryable: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('classifies Error("502 Bad Gateway") as Server Unavailable', () => {
|
||||
const result = parseNetworkError(new Error('502 Bad Gateway'))
|
||||
expect(result).toEqual({
|
||||
title: 'Server Unavailable',
|
||||
message: 'The OpenCode server is not responding. It may need to be restarted.',
|
||||
isRetryable: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('classifies timeout errors as Request Timeout', () => {
|
||||
const result = parseNetworkError(new Error('Request timeout'))
|
||||
expect(result).toEqual({
|
||||
title: 'Request Timeout',
|
||||
message: 'The request took too long to complete. Please try again.',
|
||||
isRetryable: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('classifies FetchError with statusCode 502 as Server Unavailable', () => {
|
||||
const result = parseNetworkError(new FetchError('Proxy request failed', 502))
|
||||
expect(result).toEqual({
|
||||
title: 'Server Unavailable',
|
||||
message: 'The OpenCode server is not responding. It may need to be restarted.',
|
||||
isRetryable: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('classifies FetchError with statusCode 524 as Request Timeout', () => {
|
||||
const result = parseNetworkError(new FetchError('An error occurred', 524))
|
||||
expect(result).toEqual({
|
||||
title: 'Request Timeout',
|
||||
message: 'The request took too long to complete. Please try again.',
|
||||
isRetryable: true,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('isGatewayTimeout', () => {
|
||||
it('returns true for a FetchError with statusCode 524', () => {
|
||||
expect(isGatewayTimeout(new FetchError('Gateway timeout', 524))).toBe(true)
|
||||
})
|
||||
|
||||
it('returns false for a FetchError with statusCode 502', () => {
|
||||
expect(isGatewayTimeout(new FetchError('Bad gateway', 502))).toBe(false)
|
||||
})
|
||||
|
||||
it('returns false for a TypeError', () => {
|
||||
expect(isGatewayTimeout(new TypeError('Failed to fetch'))).toBe(false)
|
||||
})
|
||||
|
||||
it('returns false for non-error values', () => {
|
||||
expect(isGatewayTimeout(undefined)).toBe(false)
|
||||
expect(isGatewayTimeout(524)).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -1,3 +1,4 @@
|
||||
import { FetchError } from '@opencode-manager/shared'
|
||||
import type { components } from '@/api/opencode-types'
|
||||
|
||||
export type OpenCodeError =
|
||||
@@ -61,9 +62,33 @@ export function parseOpenCodeError(error: OpenCodeError | undefined | null): Par
|
||||
}
|
||||
}
|
||||
|
||||
export function isGatewayTimeout(error: unknown): boolean {
|
||||
return error instanceof FetchError && error.statusCode === 524
|
||||
}
|
||||
|
||||
export function parseNetworkError(error: unknown): ParsedError {
|
||||
if (error instanceof Error) {
|
||||
if (error.message.includes('timeout') || error.message.includes('ETIMEDOUT')) {
|
||||
if (error instanceof FetchError) {
|
||||
if (error.statusCode === 502) {
|
||||
return {
|
||||
title: 'Server Unavailable',
|
||||
message: 'The OpenCode server is not responding. It may need to be restarted.',
|
||||
isRetryable: true,
|
||||
}
|
||||
}
|
||||
|
||||
if (error.statusCode === 524) {
|
||||
return {
|
||||
title: 'Request Timeout',
|
||||
message: 'The request took too long to complete. Please try again.',
|
||||
isRetryable: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const message = error.message.toLowerCase()
|
||||
|
||||
if (message.includes('timeout') || message.includes('etimedout')) {
|
||||
return {
|
||||
title: 'Request Timeout',
|
||||
message: 'The request took too long to complete. Please try again.',
|
||||
@@ -71,7 +96,14 @@ export function parseNetworkError(error: unknown): ParsedError {
|
||||
}
|
||||
}
|
||||
|
||||
if (error.message.includes('Network Error') || error.message.includes('ECONNREFUSED')) {
|
||||
if (
|
||||
message.includes('failed to fetch') ||
|
||||
message.includes('network error') ||
|
||||
message.includes('networkerror') ||
|
||||
message.includes('fetch failed') ||
|
||||
message.includes('econnrefused') ||
|
||||
message.includes('econnreset')
|
||||
) {
|
||||
return {
|
||||
title: 'Connection Failed',
|
||||
message: 'Could not connect to the server. Please check your connection.',
|
||||
@@ -79,7 +111,7 @@ export function parseNetworkError(error: unknown): ParsedError {
|
||||
}
|
||||
}
|
||||
|
||||
if (error.message.includes('502') || error.message.includes('Bad Gateway')) {
|
||||
if (message.includes('502') || message.includes('bad gateway')) {
|
||||
return {
|
||||
title: 'Server Unavailable',
|
||||
message: 'The OpenCode server is not responding. It may need to be restarted.',
|
||||
|
||||
@@ -44,6 +44,20 @@ describe('OpenCodeEventStream', () => {
|
||||
expect(healthStates.at(-1)).toMatchObject({ isConnected: true, isHealthy: true, isStalled: false })
|
||||
})
|
||||
|
||||
it('recovers when a connection never opens', async () => {
|
||||
const transport = new TestEventStreamTransport()
|
||||
const stream = new OpenCodeEventStream({ transport })
|
||||
|
||||
stream.subscribeGlobalMonitor({ directories: [], onEvent: vi.fn() })
|
||||
expect(transport.openedUrls).toHaveLength(1)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(10_000)
|
||||
expect(transport.closeCount).toBeGreaterThan(0)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1_000)
|
||||
expect(transport.openedUrls.length).toBeGreaterThan(1)
|
||||
})
|
||||
|
||||
it('reconnects when the watchdog detects a stall', async () => {
|
||||
const transport = new TestEventStreamTransport()
|
||||
const stream = new OpenCodeEventStream({ transport })
|
||||
|
||||
@@ -21,7 +21,7 @@ interface OpenCodeEventStreamOptions {
|
||||
transport?: EventStreamTransport
|
||||
}
|
||||
|
||||
const { RECONNECT_DELAY_MS, MAX_RECONNECT_DELAY_MS, STALL_THRESHOLD_MS, WATCHDOG_TICK_MS } = DEFAULTS.SSE
|
||||
const { RECONNECT_DELAY_MS, MAX_RECONNECT_DELAY_MS, CONNECT_TIMEOUT_MS, STALL_THRESHOLD_MS, WATCHDOG_TICK_MS } = DEFAULTS.SSE
|
||||
|
||||
export class OpenCodeEventStream {
|
||||
private connection: { close(): void } | null = null
|
||||
@@ -30,6 +30,7 @@ export class OpenCodeEventStream {
|
||||
private directoryRefCounts = new Map<string, number>()
|
||||
private pendingDirectories = new Set<string>()
|
||||
private reconnectTimeout: ReturnType<typeof setTimeout> | null = null
|
||||
private connectTimeout: ReturnType<typeof setTimeout> | null = null
|
||||
private reconnectDelay: number = RECONNECT_DELAY_MS
|
||||
private connected = false
|
||||
private subscriberIdCounter = 0
|
||||
@@ -194,9 +195,26 @@ export class OpenCodeEventStream {
|
||||
onConnected: (data) => this.handleConnected(data),
|
||||
onHeartbeat: () => this.markActivity(),
|
||||
})
|
||||
this.startConnectTimeout()
|
||||
}
|
||||
|
||||
private startConnectTimeout(): void {
|
||||
this.clearConnectTimeout()
|
||||
this.connectTimeout = setTimeout(() => {
|
||||
this.connectTimeout = null
|
||||
this.handleError()
|
||||
}, CONNECT_TIMEOUT_MS)
|
||||
}
|
||||
|
||||
private clearConnectTimeout(): void {
|
||||
if (this.connectTimeout) {
|
||||
clearTimeout(this.connectTimeout)
|
||||
this.connectTimeout = null
|
||||
}
|
||||
}
|
||||
|
||||
private handleOpen(): void {
|
||||
this.clearConnectTimeout()
|
||||
this.connected = true
|
||||
this.reconnectDelay = RECONNECT_DELAY_MS
|
||||
this.startWatchdog()
|
||||
@@ -205,6 +223,7 @@ export class OpenCodeEventStream {
|
||||
}
|
||||
|
||||
private handleError(): void {
|
||||
this.clearConnectTimeout()
|
||||
this.connected = false
|
||||
this.clientId = null
|
||||
this.upstreamConnectedCount = null
|
||||
@@ -250,6 +269,7 @@ export class OpenCodeEventStream {
|
||||
this.clientId = null
|
||||
}
|
||||
|
||||
this.clearConnectTimeout()
|
||||
this.connected = true
|
||||
this.startWatchdog()
|
||||
this.markActivity()
|
||||
@@ -263,6 +283,7 @@ export class OpenCodeEventStream {
|
||||
this.reconnectTimeout = null
|
||||
}
|
||||
|
||||
this.clearConnectTimeout()
|
||||
this.stopWatchdog()
|
||||
this.connection?.close()
|
||||
this.connection = null
|
||||
@@ -289,6 +310,7 @@ export class OpenCodeEventStream {
|
||||
this.reconnectTimeout = null
|
||||
}
|
||||
|
||||
this.clearConnectTimeout()
|
||||
this.stopWatchdog()
|
||||
this.connection?.close()
|
||||
this.connection = null
|
||||
|
||||
@@ -4,19 +4,23 @@ type UpdateCallback = () => void;
|
||||
|
||||
let updateCallback: UpdateCallback | null = null;
|
||||
let updatePending = false;
|
||||
let updateNotified = false;
|
||||
|
||||
function notifyUpdate() {
|
||||
if (updateNotified) return;
|
||||
if (!updateCallback) {
|
||||
updatePending = true;
|
||||
return;
|
||||
}
|
||||
updateNotified = true;
|
||||
updatePending = false;
|
||||
updateCallback();
|
||||
}
|
||||
|
||||
export function onServiceWorkerUpdate(callback: UpdateCallback): void {
|
||||
updateCallback = callback;
|
||||
if (updatePending) {
|
||||
if (updatePending && !updateNotified) {
|
||||
updateNotified = true;
|
||||
updatePending = false;
|
||||
callback();
|
||||
}
|
||||
@@ -26,37 +30,47 @@ export function offServiceWorkerUpdate(): void {
|
||||
updateCallback = null;
|
||||
}
|
||||
|
||||
const UPDATE_CHECK_INTERVAL_MS = 60 * 1000;
|
||||
|
||||
export function registerServiceWorker(): void {
|
||||
if (!("serviceWorker" in navigator)) return;
|
||||
|
||||
const hadController = !!navigator.serviceWorker.controller;
|
||||
|
||||
navigator.serviceWorker.addEventListener("message", (event) => {
|
||||
if (event.data?.type === "SW_UPDATED") {
|
||||
notifyUpdate();
|
||||
}
|
||||
});
|
||||
|
||||
navigator.serviceWorker.ready.then((registration) => {
|
||||
if (registration.waiting) {
|
||||
notifyUpdate();
|
||||
}
|
||||
});
|
||||
|
||||
navigator.serviceWorker
|
||||
.register("/sw.js", { scope: "/" })
|
||||
.then((registration) => {
|
||||
if (registration.waiting && hadController) {
|
||||
notifyUpdate();
|
||||
}
|
||||
|
||||
registration.addEventListener("updatefound", () => {
|
||||
const installing = registration.installing;
|
||||
if (!installing) return;
|
||||
installing.addEventListener("statechange", () => {
|
||||
if (installing.state === "installed" && navigator.serviceWorker.controller) {
|
||||
if (installing.state === "installed" && hadController) {
|
||||
notifyUpdate();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
setInterval(() => {
|
||||
const checkForUpdate = () => {
|
||||
registration.update().catch(() => {});
|
||||
}, 60 * 60 * 1000);
|
||||
};
|
||||
|
||||
const onVisibilityChange = () => {
|
||||
if (document.visibilityState === "visible") checkForUpdate();
|
||||
};
|
||||
|
||||
document.addEventListener("visibilitychange", onVisibilityChange);
|
||||
window.addEventListener("focus", checkForUpdate);
|
||||
setInterval(checkForUpdate, UPDATE_CHECK_INTERVAL_MS);
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
@@ -554,7 +554,6 @@ export function SessionDetail() {
|
||||
opcodeUrl={opcodeUrl}
|
||||
directory={repoDirectory}
|
||||
sessionID={sessionId}
|
||||
disabled={!isConnected}
|
||||
showScrollButton={showScrollButton && !hasPromptContent}
|
||||
isSessionActive={isSessionActive}
|
||||
isStreamingResponse={isStreamingResponse}
|
||||
|
||||
@@ -342,4 +342,16 @@ describe('SessionDetail scroll floating button', () => {
|
||||
fireEvent.click(screen.getByLabelText('Scroll to bottom'))
|
||||
expect(mockScrollToBottom).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('does NOT disable PromptInput when SSE is disconnected', async () => {
|
||||
mocks.useSSE.mockReturnValue({ isConnected: false, isReconnecting: true })
|
||||
renderWith({ mobile: true, showScrollButton: false })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.PromptInput).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
const props = mocks.PromptInput.mock.calls.at(-1)?.[0] as { disabled?: boolean }
|
||||
expect(props.disabled).not.toBe(true)
|
||||
})
|
||||
})
|
||||
+82
-15
@@ -1,18 +1,44 @@
|
||||
/// <reference lib="webworker" />
|
||||
|
||||
declare const self: ServiceWorkerGlobalScope & typeof globalThis;
|
||||
const worker = self as unknown as ServiceWorkerGlobalScope & typeof globalThis;
|
||||
|
||||
self.addEventListener("install", () => {
|
||||
self.skipWaiting();
|
||||
interface SwBuildGlobals {
|
||||
__SW_BUILD_HASH__?: string;
|
||||
__SW_PRECACHE__?: string[];
|
||||
}
|
||||
|
||||
const buildGlobals = worker as unknown as SwBuildGlobals;
|
||||
|
||||
const BUILD_HASH = buildGlobals.__SW_BUILD_HASH__ ?? "dev";
|
||||
const PRECACHE_URLS = buildGlobals.__SW_PRECACHE__ ?? [];
|
||||
|
||||
const APP_SHELL_CACHE = `app-shell-${BUILD_HASH}`;
|
||||
const RUNTIME_CACHE = `runtime-${BUILD_HASH}`;
|
||||
const APP_SHELL_URL = "/index.html";
|
||||
const MANAGED_CACHE_PREFIXES = ["app-shell-", "runtime-", "offline-assets-"];
|
||||
|
||||
worker.addEventListener("install", (event) => {
|
||||
event.waitUntil(caches.open(APP_SHELL_CACHE).then((cache) => cache.addAll(PRECACHE_URLS)));
|
||||
worker.skipWaiting();
|
||||
});
|
||||
|
||||
self.addEventListener("activate", (event) => {
|
||||
worker.addEventListener("activate", (event) => {
|
||||
event.waitUntil(
|
||||
caches.keys().then((names) =>
|
||||
Promise.all(names.map((name) => caches.delete(name)))
|
||||
).then(() => self.clients.claim())
|
||||
.then(() => self.clients.matchAll({ type: "window" }))
|
||||
.then((clients) => {
|
||||
caches.keys().then(async (names) => {
|
||||
const stale = names.filter(
|
||||
(name) =>
|
||||
MANAGED_CACHE_PREFIXES.some((prefix) => name.startsWith(prefix)) &&
|
||||
name !== APP_SHELL_CACHE &&
|
||||
name !== RUNTIME_CACHE
|
||||
);
|
||||
const isUpdate = stale.length > 0;
|
||||
|
||||
await Promise.all(stale.map((name) => caches.delete(name)));
|
||||
await worker.clients.claim();
|
||||
|
||||
if (!isUpdate) return;
|
||||
|
||||
const clients = await worker.clients.matchAll({ type: "window" });
|
||||
for (const client of clients) {
|
||||
client.postMessage({ type: "SW_UPDATED" });
|
||||
}
|
||||
@@ -20,6 +46,47 @@ self.addEventListener("activate", (event) => {
|
||||
);
|
||||
});
|
||||
|
||||
async function networkFirstShell(request: Request): Promise<Response> {
|
||||
const cache = await caches.open(APP_SHELL_CACHE);
|
||||
try {
|
||||
const response = await fetch(request);
|
||||
if (response.ok) cache.put(APP_SHELL_URL, response.clone());
|
||||
return response;
|
||||
} catch (error) {
|
||||
const cached = await cache.match(APP_SHELL_URL);
|
||||
if (cached) return cached;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function cacheFirstAsset(request: Request): Promise<Response> {
|
||||
const cached = await caches.match(request);
|
||||
if (cached) return cached;
|
||||
|
||||
const response = await fetch(request);
|
||||
if (response.ok && response.status === 200) {
|
||||
const cache = await caches.open(RUNTIME_CACHE);
|
||||
cache.put(request, response.clone());
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
worker.addEventListener("fetch", (event) => {
|
||||
const { request } = event;
|
||||
if (request.method !== "GET") return;
|
||||
|
||||
const url = new URL(request.url);
|
||||
if (url.origin !== worker.location.origin) return;
|
||||
if (url.pathname.startsWith("/api/") || url.pathname === "/sw.js") return;
|
||||
|
||||
if (request.mode === "navigate") {
|
||||
event.respondWith(networkFirstShell(request));
|
||||
return;
|
||||
}
|
||||
|
||||
event.respondWith(cacheFirstAsset(request));
|
||||
});
|
||||
|
||||
interface PushNotificationData {
|
||||
title: string;
|
||||
body: string;
|
||||
@@ -37,7 +104,7 @@ interface PushNotificationData {
|
||||
};
|
||||
}
|
||||
|
||||
self.addEventListener("push", (event) => {
|
||||
worker.addEventListener("push", (event) => {
|
||||
if (!event.data) return;
|
||||
|
||||
let payload: PushNotificationData;
|
||||
@@ -60,27 +127,27 @@ self.addEventListener("push", (event) => {
|
||||
requireInteraction: isHighPriority(payload.data?.eventType, payload.data?.priority),
|
||||
};
|
||||
|
||||
event.waitUntil(self.registration.showNotification(payload.title, options));
|
||||
event.waitUntil(worker.registration.showNotification(payload.title, options));
|
||||
});
|
||||
|
||||
self.addEventListener("notificationclick", (event) => {
|
||||
worker.addEventListener("notificationclick", (event) => {
|
||||
event.notification.close();
|
||||
|
||||
const url = (event.notification.data?.url as string) ?? "/";
|
||||
|
||||
event.waitUntil(
|
||||
self.clients
|
||||
worker.clients
|
||||
.matchAll({ type: "window", includeUncontrolled: true })
|
||||
.then((clientList) => {
|
||||
for (const client of clientList) {
|
||||
if (new URL(client.url).origin === self.location.origin) {
|
||||
if (new URL(client.url).origin === worker.location.origin) {
|
||||
const channel = new BroadcastChannel("notification-click");
|
||||
channel.postMessage({ url });
|
||||
channel.close();
|
||||
return (client as WindowClient).focus();
|
||||
}
|
||||
}
|
||||
return self.clients.openWindow(url);
|
||||
return worker.clients.openWindow(url);
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user