Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 46 additions & 12 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2496,10 +2496,20 @@ let _albumSseDebounce: ReturnType<typeof setTimeout> | null = null;
let _currentAlbumPath: string | null = null;
let _currentAlbumRecursive = false;

// Set when the stream drops. The server does not replay events, so anything
// that changed during the outage is only picked up by resyncing on reconnect.
let sseNeedsResync = false;

function connectSSE() {
const evtSource = new EventSource('/api/watch');
evtSource.onmessage = (event) => {
if (event.data === 'connected') return;
if (event.data === 'connected') {
if (sseNeedsResync) {
sseNeedsResync = false;
resyncAfterReconnect();
}
return;
}
try {
const data = JSON.parse(event.data) as { event: string; path: string };
if (data.event === 'change' && data.path === currentFilePath) reloadCurrentFile();
Expand All @@ -2519,22 +2529,46 @@ function connectSSE() {
};
evtSource.onerror = () => {
evtSource.close();
showReconnectBanner();
sseNeedsResync = true;
setReconnectBanner('Connection lost — reconnecting...');
setTimeout(connectSSE, 3000);
};
}

let reconnectBanner: HTMLDivElement | null = null;
/** Re-fetch every live view, as if each had received a change event. */
function resyncAfterReconnect() {
fileTree?.refresh();
// A comparison keeps the file it replaced as current; reloading that would
// navigate away from the comparison.
if (currentFilePath && !compareActive) void reloadCurrentFile();
if (splitActive && splitFilePath) void loadIntoSplit(splitFilePath);
void reloadCurrentAlbum();
if (reconnectBanner) {
setReconnectBanner('Reconnected');
reconnectBannerTimer = setTimeout(() => setReconnectBanner(null), 2000);
}
}

function showReconnectBanner() {
if (reconnectBanner?.isConnected) return;
const banner = document.createElement('div');
reconnectBanner = banner;
banner.id = 'reconnect-banner';
banner.className = 'reconnect-banner';
banner.innerHTML = 'Connection lost — reconnecting...';
document.body.appendChild(banner);
setTimeout(() => banner.remove(), 4000);
let reconnectBanner: HTMLDivElement | null = null;
let reconnectBannerTimer: ReturnType<typeof setTimeout> | null = null;

/** Show the banner with `text` (kept up until replaced), or remove it with null. */
function setReconnectBanner(text: string | null) {
if (reconnectBannerTimer) clearTimeout(reconnectBannerTimer);
reconnectBannerTimer = null;
if (text === null) {
reconnectBanner?.remove();
reconnectBanner = null;
return;
}
if (!reconnectBanner?.isConnected) {
reconnectBanner = document.createElement('div');
reconnectBanner.id = 'reconnect-banner';
reconnectBanner.className = 'reconnect-banner';
reconnectBanner.setAttribute('role', 'status');
document.body.appendChild(reconnectBanner);
}
reconnectBanner.textContent = text;
}

let serverRootPath: string | null = null;
Expand Down
63 changes: 63 additions & 0 deletions tests/regression.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,69 @@ test.describe('Regression: bug-fix suite', () => {
await expect(page.locator('#viewer h1')).toContainText('Live Reload v2', { timeout: 15000 });
});

test('live reload: a change made while the stream was down is applied on reconnect', async ({ page }) => {
const file = join(DIR, 'live-reload-resync.md');
writeFileSync(file, '# Resync v1\n');

// First connection: a stream that ends right after the handshake, as when
// the server restarts or the laptop sleeps. Then refuse reconnects until
// the file has changed, and finally let the real stream through.
let phase: 'first' | 'down' | 'up' = 'first';
await page.route('**/api/watch', async (route) => {
if (phase === 'first') {
phase = 'down';
await route.fulfill({ status: 200, contentType: 'text/event-stream', body: 'data: connected\n\n' });
} else if (phase === 'down') {
await route.abort();
} else {
await route.continue();
}
});
await page.goto('/#file=live-reload-resync.md');
await expect(page.locator('#viewer h1')).toContainText('Resync v1');
const banner = page.locator('body > .reconnect-banner');
await expect(banner).toBeVisible();

// The change event is broadcast while this page has no stream, so it is lost.
writeFileSync(file, '# Resync v2\n');
// The banner stays up for the whole outage instead of timing out.
await page.waitForTimeout(5000);
await expect(banner).toBeVisible();
await expect(page.locator('#viewer h1')).toContainText('Resync v1');

phase = 'up';
await expect(page.locator('#viewer h1')).toContainText('Resync v2', { timeout: 15000 });
await expect(banner).toHaveCount(0, { timeout: 10000 });
});

test('live reload: reconnecting keeps an open image comparison', async ({ page }) => {
// The comparison leaves the previously opened file as the current one, so
// a reconnect resync must not navigate back to it.
let phase: 'first' | 'down' | 'up' = 'first';
await page.route('**/api/watch', async (route) => {
if (phase === 'first') {
phase = 'down';
await route.fulfill({ status: 200, contentType: 'text/event-stream', body: 'data: connected\n\n' });
} else if (phase === 'down') {
await route.abort();
} else {
await route.continue();
}
});
await page.goto('/#file=README.md');
await expect(page.locator('#viewer h1')).toContainText('Hello DocView');
await page.evaluate(() => { location.hash = '#compare=images%2Fa.png&compare=images%2Fb.jpg'; });
await expect(page.locator('#compare-view-pane')).toBeVisible();
const banner = page.locator('body > .reconnect-banner');
await expect(banner).toBeVisible();

phase = 'up';
await expect(banner).toHaveText('Reconnected', { timeout: 10000 });
await expect(banner).toHaveCount(0, { timeout: 10000 });
await expect(page.locator('#compare-view-pane')).toBeVisible();
await expect(page.locator('.compare-pane-item')).toHaveCount(2);
});

// NOTE: an `add → file tree refresh` variant was intentionally omitted: the
// add/unlink broadcast refreshes the tree in EVERY connected page, which
// destabilizes parallel tests interacting with the tree (context menu spec).
Expand Down
1 change: 1 addition & 0 deletions tests/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -408,6 +408,7 @@ flowchart TD
// (file-local reload) instead of `add` (global tree refresh in every page),
// keeping cross-test interference minimal.
write('live-reload.md', '# Live Reload v1\n');
write('live-reload-resync.md', '# Resync v1\n');

// Filename containing an HTML injection payload — the breadcrumb must
// escape path segments instead of injecting an <img> element.
Expand Down
Loading