Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

fix(desktop): a crashed or failing chat window comes back instead of staying blank

leepokaic7eca98e284e
diff --git a/apps/desktop/src/main/host-proxy.ts b/apps/desktop/src/main/host-proxy.ts
index e46331b0..740ab18b 100644
--- a/apps/desktop/src/main/host-proxy.ts
+++ b/apps/desktop/src/main/host-proxy.ts
@@ -1,10 +1,11 @@
-import { ipcMain, type WebContents } from 'electron'
+import { app, ipcMain, type WebContents } from 'electron'
import type { CallError } from '../shared/ipc'
import { noteAnalyticsSetting } from './analytics'
// Loopback HTTP + SSE for the renderer. The host has no CORS (it's a loopback API for local
// apps), so requests leave from the main process.
+/** Open streams by `<window>:<id>`: each window's page numbers its streams from 1. */
const streams = new Map<string, AbortController>()
function isLoopback(url: string) {
@@ -43,11 +44,26 @@ async function call(baseURL: string, token: string, method: string, body: unknow
return value
}
+function close(key: string) {
+ const controller = streams.get(key)
+ streams.delete(key)
+ controller?.abort()
+}
+
+/** A crashed page's streams (a page that unloads closes its own, preload/index.ts): left open, they'd feed the reloaded page. */
+function closePage(contents: WebContents) {
+ const prefix = `${contents.id}:`
+ for (const key of streams.keys()) if (key.startsWith(prefix)) close(key)
+}
+
function stream(sender: WebContents, id: string, url: string, token: string) {
+ const key = `${sender.id}:${id}`
const controller = new AbortController()
- streams.set(id, controller)
+ streams.set(key, controller)
+ // A closed stream sends nothing more: the page that reloaded may have given its id to a new stream.
+ const open = () => streams.get(key) === controller
const send = (channel: string, payload: unknown) => {
- if (!sender.isDestroyed()) sender.send(channel, id, payload)
+ if (open() && !sender.isDestroyed()) sender.send(channel, id, payload)
}
void (async () => {
// Idle timeout, not a total one: the host pings every 15 s, so silence this long means it's gone.
@@ -82,12 +98,12 @@ function stream(sender: WebContents, id: string, url: string, token: string) {
send('host:stream:end', null)
} catch (error) {
const e = error as Partial<CallError>
- send('host:stream:end', controller.signal.aborted && streams.has(id)
+ send('host:stream:end', controller.signal.aborted
? { status: 0, message: "Can't reach your computer." }
: { status: e.status ?? 0, message: e.message ?? "Can't reach your computer." })
} finally {
if (idle) clearTimeout(idle)
- streams.delete(id)
+ if (open()) streams.delete(key)
}
})()
}
@@ -100,9 +116,6 @@ export function registerHostProxy() {
),
)
ipcMain.on('host:stream:open', (e, id: string, url: string, token: string) => stream(e.sender, id, url, token))
- ipcMain.on('host:stream:close', (_e, id: string) => {
- const controller = streams.get(id)
- streams.delete(id)
- controller?.abort()
- })
+ ipcMain.on('host:stream:close', (e, id: string) => close(`${e.sender.id}:${id}`))
+ app.on('render-process-gone', (_e, contents) => closePage(contents))
}
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts
index 7be7d2b0..c67bb40b 100644
--- a/apps/desktop/src/main/index.ts
+++ b/apps/desktop/src/main/index.ts
@@ -24,6 +24,7 @@ import { registerSSHConfig } from './ssh-config'
import { QuitLifecycle } from './quit-lifecycle'
import { Island } from './island'
import { registerErrorReports } from './error-reports'
+import { registerRendererRecovery } from './renderer-recovery'
import { reportHostSetupFailure } from './analytics'
import { launchAtLogin, openedAtLogin, setLaunchAtLogin, updateLoginItem } from './login-item'
@@ -42,6 +43,7 @@ if (!app.isPackaged && process.env.CODYNC_REMOTE_DEBUG) app.commandLine.appendSw
const host = new HostController()
registerErrorReports(host)
+registerRendererRecovery()
host.on('setupFailed', reportHostSetupFailure)
const account = new AccountService()
const updates = new Updates(host)
diff --git a/apps/desktop/src/main/renderer-recovery.ts b/apps/desktop/src/main/renderer-recovery.ts
new file mode 100644
index 00000000..b0c929aa
--- /dev/null
+++ b/apps/desktop/src/main/renderer-recovery.ts
@@ -0,0 +1,21 @@
+import { app, type RenderProcessGoneDetails, type WebContents } from 'electron'
+
+/** Why a window's page can die and come back by loading again; `clean-exit` and `killed` mean it was ended on purpose. */
+const RECOVERABLE: ReadonlySet<RenderProcessGoneDetails['reason']> = new Set(['crashed', 'oom', 'abnormal-exit', 'memory-eviction'])
+/** Reloads in a row: a page that crashes again after these stays down instead of looping. */
+const MAX_RELOADS = 2
+/** A page that stayed up this long since its reload counts as recovered: its next crash starts the count again. */
+const RECOVERED_MS = 60_000
+
+/** A window whose page crashed loads it again instead of staying blank (error-reports.ts reports the crash). */
+export function registerRendererRecovery() {
+ const reloads = new WeakMap<WebContents, { at: number; count: number }>()
+ app.on('render-process-gone', (_e, contents, { reason }) => {
+ if (!RECOVERABLE.has(reason) || contents.isDestroyed()) return
+ const last = reloads.get(contents)
+ const count = last && Date.now() - last.at < RECOVERED_MS ? last.count + 1 : 1
+ if (count > MAX_RELOADS) return
+ reloads.set(contents, { at: Date.now(), count })
+ contents.reload()
+ })
+}
diff --git a/apps/desktop/src/main/voice-shortcut.ts b/apps/desktop/src/main/voice-shortcut.ts
index df01d3d6..73316c88 100644
--- a/apps/desktop/src/main/voice-shortcut.ts
+++ b/apps/desktop/src/main/voice-shortcut.ts
@@ -67,6 +67,10 @@ export class VoiceShortcutKeys {
return this.shortcut
})
ipcMain.on('voice:calling', (e, on: boolean) => (this.call = on ? e.sender : null))
+ // A page that crashed mid-call never says the call ended; its reload starts without one.
+ app.on('render-process-gone', (_e, contents) => {
+ if (contents === this.call) this.call = null
+ })
app.on('will-quit', () => this.stop?.())
this.sync()
}
diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.ts
index b1934a60..8bef190b 100644
--- a/apps/desktop/src/preload/index.ts
+++ b/apps/desktop/src/preload/index.ts
@@ -11,6 +11,11 @@ ipcRenderer.on('host:stream:end', (_e, id: string, error: CallError | null) => {
streams.delete(id)
s?.onEnd(error)
})
+// A page that goes (a reload, its window closing) closes its streams: the next page numbers its own from 1 again.
+window.addEventListener('pagehide', () => {
+ for (const id of streams.keys()) ipcRenderer.send('host:stream:close', id)
+ streams.clear()
+})
function listen<T>(channel: string, cb: (value: T) => void) {
const handler = (_e: IpcRendererEvent, value: T) => cb(value)
diff --git a/apps/desktop/src/renderer/main.tsx b/apps/desktop/src/renderer/main.tsx
index 6b6c50b3..b817ef3b 100644
--- a/apps/desktop/src/renderer/main.tsx
+++ b/apps/desktop/src/renderer/main.tsx
@@ -2,6 +2,7 @@ import { createRoot } from 'react-dom/client'
import './styles/theme.css'
import { ChatWindow } from './views/ChatWindow'
import { PairingWindow } from './views/PairingWindow'
+import { RenderBoundary } from './views/RenderBoundary'
import { IslandWindow } from './views/island/IslandWindow'
import { IslandModel } from './views/island/island-model'
import { AppModel } from './store/app-model'
@@ -10,7 +11,7 @@ import { applyTextSize, prefs } from './lib/prefs'
import { account } from './store/account'
import { errorReport } from '@shared/error-report'
-// Error tracking: this window's uncaught errors go to the host (shared/error-report.ts).
+// Error tracking: this window's uncaught errors, and those RenderBoundary caught, go to the host (shared/error-report.ts).
const report = (error: unknown, mechanism: string) => window.codync.app.reportError(errorReport(error, 'desktop-renderer', mechanism))
// An error event without an error (the ResizeObserver loop notice) has nothing to report.
window.addEventListener('error', (e) => { if (e.error != null) report(e.error, 'onerror') })
@@ -21,7 +22,13 @@ document.title = window.codync.appName
document.documentElement.dataset.platform = window.codync.platform
document.documentElement.dataset.window = page
applyTextSize(prefs.textSize.get())
-const root = createRoot(document.getElementById('root')!)
+const root = createRoot(document.getElementById('root')!, {
+ // Setting this replaces React's own logging of the error.
+ onCaughtError: (error) => {
+ console.error(error)
+ report(error, 'react')
+ },
+})
if (page === 'island') {
// The island only draws what the chat window sends it: no host connection of its own.
@@ -33,5 +40,9 @@ if (page === 'island') {
const app = new AppModel(page !== 'pairing')
void app.start()
if (page !== 'pairing') void account.start()
- root.render(<AppContext.Provider value={app}>{page === 'pairing' ? <PairingWindow /> : <ChatWindow />}</AppContext.Provider>)
+ root.render(
+ <RenderBoundary>
+ <AppContext.Provider value={app}>{page === 'pairing' ? <PairingWindow /> : <ChatWindow />}</AppContext.Provider>
+ </RenderBoundary>,
+ )
}
diff --git a/apps/desktop/src/renderer/views/HostStateView.tsx b/apps/desktop/src/renderer/views/HostStateView.tsx
index 2f3f67f9..b8b971d8 100644
--- a/apps/desktop/src/renderer/views/HostStateView.tsx
+++ b/apps/desktop/src/renderer/views/HostStateView.tsx
@@ -51,14 +51,14 @@ function HostBot({ compact, mood }: { compact: boolean; mood: Mood }) {
)
}
-/** A quiet placeholder for an empty screen: icon (an SF Symbol name or artwork), title, a line of help and an optional action. */
-export function EmptyState({ icon, title, message, action, compact = false }: { icon: string | ReactElement; title: string; message: string; action?: [string, () => void]; compact?: boolean }) {
+/** A quiet placeholder for an empty screen: icon (an SF Symbol name or artwork), title, an optional line of help and an optional action. */
+export function EmptyState({ icon, title, message, action, compact = false }: { icon: string | ReactElement; title: string; message?: string; action?: [string, () => void]; compact?: boolean }) {
const tr = useTr()
return (
<div className={`empty-state ${compact ? 'local-recovery' : ''}`}>
{typeof icon === 'string' ? <Icon name={icon} size={compact ? 22 : 36} weight="light" color="var(--tertiary)" /> : icon}
<Text as="div" size={compact ? 'callout' : 'title3'} weight="semibold" tone="text">{tr(title)}</Text>
- <Text as="div" size="callout" tone="secondary" className="empty-state-message">{tr(message)}</Text>
+ {message ? <Text as="div" size="callout" tone="secondary" className="empty-state-message">{tr(message)}</Text> : null}
{action ? (
<Button kind={compact ? 'secondary' : 'primary'} onClick={action[1]} className="empty-state-action">
{action[0]}
diff --git a/apps/desktop/src/renderer/views/RenderBoundary.tsx b/apps/desktop/src/renderer/views/RenderBoundary.tsx
new file mode 100644
index 00000000..116bb5fc
--- /dev/null
+++ b/apps/desktop/src/renderer/views/RenderBoundary.tsx
@@ -0,0 +1,16 @@
+import { Component, type ReactNode } from 'react'
+import { EmptyState } from './HostStateView'
+
+/** A view that throws while rendering would unmount the whole window and leave it blank: this shows an error state with a reload instead. */
+export class RenderBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {
+ state = { failed: false }
+
+ static getDerivedStateFromError() {
+ return { failed: true }
+ }
+
+ render() {
+ if (!this.state.failed) return this.props.children
+ return <EmptyState icon="exclamationmark.triangle.fill" title="Something went wrong" action={['Try again', () => location.reload()]} />
+ }
+}
diff --git a/docs/architecture/desktop-app.md b/docs/architecture/desktop-app.md
index 08f46dd7..edbc21b2 100644
--- a/docs/architecture/desktop-app.md
+++ b/docs/architecture/desktop-app.md
@@ -22,7 +22,7 @@ reaching the end of a history response determines when there are no earlier mess
| Path | |
|---|---|
-| `src/main/` | Main process: host service (`host-controller.ts`), loopback HTTP/SSE proxy (`host-proxy.ts`), menu bar/tray, windows, account sign-in (Clerk Frontend API, `account.ts`), cloud API and device key (`cloud.ts`), updates (`updates.ts`), SSH tunnels (`ssh.ts`), Codync Screen agent (`screen.ts`), on-device speech (`speech.ts`) and its [voice input shortcut](../features/voice-call.md#voice-input-shortcut) (`voice-shortcut.ts`), browser sign-in callbacks (`auth.ts`), the [notch island](../features/notch-island.md) window (`island.ts`), [error tracking](../features/analytics.md#error-tracking) (`error-reports.ts`) |
+| `src/main/` | Main process: host service (`host-controller.ts`), loopback HTTP/SSE proxy (`host-proxy.ts`), menu bar/tray, windows, account sign-in (Clerk Frontend API, `account.ts`), cloud API and device key (`cloud.ts`), updates (`updates.ts`), SSH tunnels (`ssh.ts`), Codync Screen agent (`screen.ts`), on-device speech (`speech.ts`) and its [voice input shortcut](../features/voice-call.md#voice-input-shortcut) (`voice-shortcut.ts`), browser sign-in callbacks (`auth.ts`), the [notch island](../features/notch-island.md) window (`island.ts`), [error tracking](../features/analytics.md#error-tracking) (`error-reports.ts`) and reloading a crashed window (`renderer-recovery.ts`) |
| `src/preload/` | The `window.codync` bridge (types in `src/shared/ipc.ts`) |
| `src/renderer/store/` | `BotStore` (port of kit's; `bot-store.ts` actions over `bot-sync.ts` events stream and `bot-mirror.ts` state), `AppModel` (window state, approvals), `CloudModel` (claims, cloud default), `AccountSession` |
| `src/renderer/components/` | Design system: controls, overlays (sheets, dialogs, menus), SF Symbol icons, character avatars, thinking orbs |
diff --git a/docs/features/analytics.md b/docs/features/analytics.md
index a1d8d7e8..e9abfc9f 100644
--- a/docs/features/analytics.md
+++ b/docs/features/analytics.md
@@ -97,8 +97,11 @@ builds PostHog frames itself (oldest first, the failing one last): generic `cust
analytics task), and `reportError`, loopback only, for the computer's apps. Process `host`.
- **Terminal UI**: its panics, through `reportError` from the panic hook. Process `tui`.
- **Desktop** (`apps/desktop/src/main/error-reports.ts`, `shared/error-report.ts`): uncaught
- errors and rejections in the main process and every window, and windows or helpers that
- crashed (`RendererGone`, `GPUGone`, … with Electron's reason), through `reportError`. Not
+ errors and rejections in the main process and every window, errors a view threw while
+ rendering (mechanism `react`: the chat and pairing windows show *Something went wrong* with
+ *Try again* instead of going blank), and windows or helpers that crashed (`RendererGone`,
+ `GPUGone`, … with Electron's reason), through `reportError`. A window whose page crashed loads
+ it again (`renderer-recovery.ts`), at most twice in a row before it has stayed up a minute. Not
reported: error events that carry no error (the ResizeObserver loop notice), and helpers that
exited normally or were ended from outside (`clean-exit`, `killed`: logout, shutdown, an update),
and a GPU process that couldn't launch (the app goes on with software rendering).