Skip to content

Commit 19ebb09

Browse files
author
Zoo (VP)
committed
fix(webview): detect dead webview renderer via heartbeat and auto-reload
1 parent 08d05eb commit 19ebb09

6 files changed

Lines changed: 193 additions & 0 deletions

File tree

‎packages/types/src/vscode-extension-host.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -472,6 +472,7 @@ export interface WebviewMessage {
472472
| "getListApiConfiguration"
473473
| "customInstructions"
474474
| "webviewDidLaunch"
475+
| "webviewHeartbeat"
475476
| "newTask"
476477
| "askResponse"
477478
| "terminalOperation"
@@ -696,6 +697,7 @@ export interface WebviewMessage {
696697
ids?: string[]
697698
terminalOperation?: "continue" | "abort"
698699
messageTs?: number
700+
timestamp?: number // For webviewHeartbeat
699701
restoreCheckpoint?: boolean
700702
historyPreviewCollapsed?: boolean
701703
filters?: { type?: string; search?: string; tags?: string[] }

‎src/core/webview/ClineProvider.ts‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,10 @@ export class ClineProvider
223223
private taskEventListeners: WeakMap<Task, Array<() => void>> = new WeakMap()
224224
private currentWorkspacePath: string | undefined
225225
private _disposed = false
226+
private lastWebviewHeartbeatAt = 0
227+
private webviewWatchdogInterval: ReturnType<typeof setInterval> | null = null
228+
private static readonly WEBVIEW_WATCHDOG_TICK_MS = 60_000
229+
private static readonly WEBVIEW_HEARTBEAT_STALE_MS = 90_000
226230
private readonly _postStateToWebviewThrottled = debounce(
227231
async () => {
228232
try {
@@ -842,6 +846,10 @@ export class ClineProvider
842846

843847
this._disposed = true
844848
this._postStateToWebviewThrottled.cancel()
849+
if (this.webviewWatchdogInterval) {
850+
clearInterval(this.webviewWatchdogInterval)
851+
this.webviewWatchdogInterval = null
852+
}
845853
this.log("Disposing ClineProvider...")
846854

847855
// Reject any tasks still waiting for a scheduler permit so they don't
@@ -1082,6 +1090,9 @@ export class ClineProvider
10821090
// and executes code based on the message that is received.
10831091
this.setWebviewMessageListener(webviewView.webview)
10841092

1093+
// Detect a dead webview renderer process (gray screen) via heartbeat timeout.
1094+
this.startWebviewWatchdog()
1095+
10851096
// Initialize code index status subscription for the current workspace.
10861097
this.updateCodeIndexStatusSubscription()
10871098

@@ -1100,6 +1111,9 @@ export class ClineProvider
11001111
// for this visibility listener panel.
11011112
const viewStateDisposable = webviewView.onDidChangeViewState(() => {
11021113
if (this.view?.visible) {
1114+
// Hidden webviews throttle timers, so grant a fresh grace
1115+
// window instead of counting throttled heartbeats as a crash.
1116+
this.updateWebviewHeartbeat()
11031117
void this.postMessageToWebview({ type: "action", action: "didBecomeVisible" })
11041118
} else {
11051119
this.logWebviewHiddenDiagnostics()
@@ -1111,6 +1125,9 @@ export class ClineProvider
11111125
// sidebar
11121126
const visibilityDisposable = webviewView.onDidChangeVisibility(() => {
11131127
if (this.view?.visible) {
1128+
// Hidden webviews throttle timers, so grant a fresh grace
1129+
// window instead of counting throttled heartbeats as a crash.
1130+
this.updateWebviewHeartbeat()
11141131
void this.postMessageToWebview({ type: "action", action: "didBecomeVisible" })
11151132
} else {
11161133
this.logWebviewHiddenDiagnostics()
@@ -3381,6 +3398,39 @@ export class ClineProvider
33813398
)
33823399
}
33833400

3401+
/** Records that the webview renderer is alive; called on every webviewHeartbeat message. */
3402+
public updateWebviewHeartbeat(): void {
3403+
this.lastWebviewHeartbeatAt = Date.now()
3404+
}
3405+
3406+
/**
3407+
* Starts (or restarts) the watchdog that detects a dead webview renderer
3408+
* process. Hidden webviews throttle timers, so becoming visible resets the
3409+
* grace window instead of counting throttled heartbeats as a crash.
3410+
*/
3411+
private startWebviewWatchdog(): void {
3412+
this.updateWebviewHeartbeat()
3413+
if (this.webviewWatchdogInterval) {
3414+
clearInterval(this.webviewWatchdogInterval)
3415+
}
3416+
this.webviewWatchdogInterval = setInterval(() => {
3417+
if (this.view?.visible !== true) {
3418+
return
3419+
}
3420+
if (Date.now() - this.lastWebviewHeartbeatAt <= ClineProvider.WEBVIEW_HEARTBEAT_STALE_MS) {
3421+
return
3422+
}
3423+
this.log("[Zoo Code] Webview heartbeat stale while visible; reloading webview (dead renderer?)")
3424+
void Promise.resolve(vscode.commands.executeCommand("workbench.action.webview.reloadWebviewAction")).catch(
3425+
(error) => {
3426+
this.log(
3427+
`[Zoo Code] Failed to reload webview: ${error instanceof Error ? error.message : String(error)}`,
3428+
)
3429+
},
3430+
)
3431+
}, ClineProvider.WEBVIEW_WATCHDOG_TICK_MS)
3432+
}
3433+
33843434
public getRecentTasks(): string[] {
33853435
if (this.recentTasksCache) {
33863436
return this.recentTasksCache

‎src/core/webview/__tests__/ClineProvider.spec.ts‎

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -663,6 +663,96 @@ describe("ClineProvider", () => {
663663
})
664664
})
665665

666+
describe("webview heartbeat watchdog", () => {
667+
let visibilityCallback: () => void
668+
669+
beforeEach(() => {
670+
// Fake timers must be active before resolveWebviewView so the
671+
// watchdog interval is registered on the fake clock.
672+
vi.useFakeTimers()
673+
mockWebviewView.onDidChangeVisibility = vi.fn().mockImplementation((cb: () => void) => {
674+
visibilityCallback = cb
675+
return { dispose: vi.fn() }
676+
})
677+
})
678+
679+
afterEach(async () => {
680+
await provider.dispose()
681+
vi.useRealTimers()
682+
})
683+
684+
test("does not reload the webview while heartbeats are fresh", async () => {
685+
await provider.resolveWebviewView(mockWebviewView)
686+
vi.mocked(vscode.commands.executeCommand).mockClear()
687+
688+
await vi.advanceTimersByTimeAsync(110_000)
689+
await webviewMessageHandler(provider, { type: "webviewHeartbeat", timestamp: Date.now() })
690+
await vi.advanceTimersByTimeAsync(60_000)
691+
692+
expect(vscode.commands.executeCommand).not.toHaveBeenCalled()
693+
})
694+
695+
test("reloads the webview when the heartbeat is stale and the view is visible", async () => {
696+
await provider.resolveWebviewView(mockWebviewView)
697+
vi.mocked(vscode.commands.executeCommand).mockClear()
698+
699+
await vi.advanceTimersByTimeAsync(120_000)
700+
701+
expect(vscode.commands.executeCommand).toHaveBeenCalledTimes(1)
702+
expect(vscode.commands.executeCommand).toHaveBeenCalledWith("workbench.action.webview.reloadWebviewAction")
703+
})
704+
705+
test("does not reload while the view is hidden even when the heartbeat is stale", async () => {
706+
await provider.resolveWebviewView(mockWebviewView)
707+
Object.defineProperty(mockWebviewView, "visible", { value: false, configurable: true })
708+
vi.mocked(vscode.commands.executeCommand).mockClear()
709+
710+
await vi.advanceTimersByTimeAsync(180_000)
711+
712+
expect(vscode.commands.executeCommand).not.toHaveBeenCalled()
713+
})
714+
715+
test("resets the grace window when the view becomes visible", async () => {
716+
await provider.resolveWebviewView(mockWebviewView)
717+
Object.defineProperty(mockWebviewView, "visible", { value: false, configurable: true })
718+
vi.mocked(vscode.commands.executeCommand).mockClear()
719+
720+
await vi.advanceTimersByTimeAsync(120_000)
721+
expect(vscode.commands.executeCommand).not.toHaveBeenCalled()
722+
723+
Object.defineProperty(mockWebviewView, "visible", { value: true, configurable: true })
724+
visibilityCallback()
725+
726+
await vi.advanceTimersByTimeAsync(60_000)
727+
expect(vscode.commands.executeCommand).not.toHaveBeenCalled()
728+
729+
// Watchdog ticks every 60s; 120s after the flip the heartbeat is stale again.
730+
await vi.advanceTimersByTimeAsync(60_000)
731+
expect(vscode.commands.executeCommand).toHaveBeenCalledTimes(1)
732+
expect(vscode.commands.executeCommand).toHaveBeenCalledWith("workbench.action.webview.reloadWebviewAction")
733+
})
734+
735+
test("stops watching after the provider is disposed", async () => {
736+
await provider.resolveWebviewView(mockWebviewView)
737+
vi.mocked(vscode.commands.executeCommand).mockClear()
738+
739+
await provider.dispose()
740+
await vi.advanceTimersByTimeAsync(180_000)
741+
742+
expect(vscode.commands.executeCommand).not.toHaveBeenCalled()
743+
})
744+
745+
test("does not stack watchdog intervals when resolveWebviewView runs again", async () => {
746+
await provider.resolveWebviewView(mockWebviewView)
747+
await provider.resolveWebviewView(mockWebviewView)
748+
vi.mocked(vscode.commands.executeCommand).mockClear()
749+
750+
await vi.advanceTimersByTimeAsync(120_000)
751+
752+
expect(vscode.commands.executeCommand).toHaveBeenCalledTimes(1)
753+
})
754+
})
755+
666756
test("resolveWebviewView sets up webview correctly in development mode even if local server is not running", async () => {
667757
provider = new ClineProvider(
668758
{ ...mockContext, extensionMode: vscode.ExtensionMode.Development },

‎src/core/webview/webviewMessageHandler.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -688,6 +688,10 @@ export const webviewMessageHandler = async (
688688

689689
provider.isViewLaunched = true
690690
break
691+
case "webviewHeartbeat":
692+
// Timestamp-only update for the dead-renderer watchdog; no other side effects.
693+
provider.updateWebviewHeartbeat()
694+
break
691695
case "newTask":
692696
// Initializing new instance of Cline will make sure that any
693697
// agentically running promises in old instance don't affect our new

‎webview-ui/src/App.tsx‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,15 @@ const App = () => {
206206
// Tell the extension that we are ready to receive messages.
207207
useEffect(() => vscode.postMessage({ type: "webviewDidLaunch" }), [])
208208

209+
// Heartbeat so the extension watchdog can detect a crashed webview renderer
210+
// process (gray screen) and reload the view.
211+
useEffect(() => {
212+
const postHeartbeat = () => vscode.postMessage({ type: "webviewHeartbeat", timestamp: Date.now() })
213+
postHeartbeat()
214+
const interval = setInterval(postHeartbeat, 30_000)
215+
return () => clearInterval(interval)
216+
}, [])
217+
209218
// Initialize source map support for better error reporting
210219
useEffect(() => {
211220
// Initialize source maps for better error reporting in production

‎webview-ui/src/__tests__/App.spec.tsx‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import React from "react"
44
import { render, screen, act, cleanup } from "@/utils/test-utils"
55

66
import AppWithProviders from "../App"
7+
import { vscode } from "@src/utils/vscode"
78

89
vi.mock("@src/utils/vscode", () => ({
910
vscode: {
@@ -476,4 +477,41 @@ describe("App", () => {
476477
expect(chatView.getAttribute("data-hidden")).toBe("false")
477478
expect(screen.queryByTestId("marketplace-view")).not.toBeInTheDocument()
478479
})
480+
481+
describe("webview heartbeat", () => {
482+
afterEach(() => {
483+
vi.useRealTimers()
484+
})
485+
486+
it("posts an immediate heartbeat on mount and then every 30 seconds", () => {
487+
vi.useFakeTimers()
488+
render(<AppWithProviders />)
489+
490+
const postMessageMock = vi.mocked(vscode.postMessage)
491+
expect(postMessageMock).toHaveBeenCalledWith(
492+
expect.objectContaining({ type: "webviewHeartbeat", timestamp: expect.any(Number) }),
493+
)
494+
const callsAfterMount = postMessageMock.mock.calls.length
495+
496+
vi.advanceTimersByTime(30_000)
497+
expect(postMessageMock.mock.calls.length).toBe(callsAfterMount + 1)
498+
499+
vi.advanceTimersByTime(30_000)
500+
expect(postMessageMock.mock.calls.length).toBe(callsAfterMount + 2)
501+
expect(postMessageMock).toHaveBeenLastCalledWith(expect.objectContaining({ type: "webviewHeartbeat" }))
502+
})
503+
504+
it("stops posting heartbeats after unmount", () => {
505+
vi.useFakeTimers()
506+
const { unmount } = render(<AppWithProviders />)
507+
508+
const postMessageMock = vi.mocked(vscode.postMessage)
509+
const callsAfterMount = postMessageMock.mock.calls.length
510+
511+
unmount()
512+
vi.advanceTimersByTime(90_000)
513+
514+
expect(postMessageMock.mock.calls.length).toBe(callsAfterMount)
515+
})
516+
})
479517
})

0 commit comments

Comments
 (0)