How OfficeCLI Watch Mode Provides Live Browser Preview with Auto-Refresh
OfficeCLI watch mode delivers a live browser preview with automatic refresh by using a Server-Sent Events (SSE) stream to push DOM mutations from a local development server to two lightweight client-side JavaScript layers that update the page incrementally without reloading.
The iOfficeAI/OfficeCLI tool provides a real-time document preview environment that keeps your browser synchronized with file changes as you edit. Watch mode creates a seamless live editing experience by combining a persistent SSE connection with a dual-layer client architecture that separates document rendering from visual decorations.
The Two-Layer Client Architecture
OfficeCLI implements watch mode through two coordinated JavaScript layers that run in the browser. This separation of concerns ensures that document content updates without disrupting user selections, marks, or interactive overlays.
The Document Rendering Layer (watch-sse-core.js)
The core rendering engine resides in src/officecli/Resources/watch-sse-core.js. This script establishes the SSE connection and handles all DOM mutations.
Upon loading, the script creates a persistent connection to the server:
var es = new EventSource('/events');
The core layer registers listeners for various server-sent actions including update, doc-switched, and navigation commands. When a full update arrives, it replaces the entire document body using _replaceDocumentBody(msg). For incremental changes to Word or Excel documents, it applies targeted patches via wordDiffUpdate or wordPatchUpdate.
After every DOM mutation, the core script invokes window._watchReapplyHook() to signal the overlay layer that decorations must be redrawn. This hook bridges the two layers and ensures visual state persists across content updates.
The Decoration Layer (watch-overlay.js)
The overlay system lives in src/officecli/Resources/watch-overlay.js and manages user selections, marks, and interactive elements.
This layer registers the re-apply hook that the core expects:
window._watchReapplyHook = reapplyDecorations;
The reapplyDecorations function calls applySelectionToDom() and applyMarks() to redraw visual highlights after every content change. The overlay script maintains local state in _selection and _marks arrays, which it updates when receiving selection-update or mark-update messages via the same SSE stream.
User interactions such as clicks, drags, or rubber-band selections trigger POST requests to /api/selection, sending the current selection paths back to the server for synchronization across all connected browsers.
How Server-Sent Events Drive Auto-Refresh
The communication channel runs over a unidirectional SSE stream at the /events endpoint. When you start watch mode with officecli watch path/to/document.docx, the CLI spawns a local server that serves the preview HTML and maintains SSE connections.
The server emits JSON messages describing changes:
// Server-side broadcast (simplified)
function broadcastUpdate(msg) {
const data = `data: ${JSON.stringify(msg)}\n\n`;
clients.forEach(client => client.res.write(data));
}
// Example: File change notification
broadcastUpdate({ action: 'full', version: 42 });
Because the browser maintains a persistent connection, updates arrive instantly without polling overhead. The client-side scripts parse these messages and apply changes locally, eliminating the latency of full page reloads.
DOM Updates Without Page Reloads
Watch mode preserves the live editing experience through intelligent DOM manipulation strategies. When the source file changes, the server analyzes the document type and generates appropriate update instructions.
For full document replacements, the core script swaps the entire body content:
// Inside watch-sse-core.js
if (msg.action === 'full') {
_replaceDocumentBody(msg);
}
For incremental updates, the system applies diff-based patches that modify only changed elements. This approach maintains scroll position, focus states, and user interactions while updating content.
Navigation commands such as scroll or goto execute directly against the DOM, moving the viewport to specific elements without triggering a refresh.
Starting Watch Mode and Usage Examples
Launch the live preview from your terminal:
officecli watch path/to/document.docx
The CLI outputs a local URL such as http://localhost:3000/preview. Opening this URL loads a minimal HTML skeleton that injects both watch scripts:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Document Preview</title>
<script src="/Resources/watch-sse-core.js"></script>
<script src="/Resources/watch-overlay.js"></script>
</head>
<body>
<!-- Server injects document content here -->
</body>
</html>
The overlay script handles user selections and communicates back to the server:
// Sending selection updates to the server
function postSelection(paths) {
fetch('/api/selection', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ paths })
});
}
When selection state changes on the server, the broadcast reaches all connected clients:
// Inside watch-overlay.js
es.addEventListener('update', e => {
const msg = JSON.parse(e.data);
if (msg.action === 'selection-update') {
_selection = msg.paths || [];
applySelectionToDom();
}
});
Summary
- Dual-layer architecture:
watch-sse-core.jshandles document rendering whilewatch-overlay.jsmanages selections and decorations, communicating via thewindow._watchReapplyHook()callback. - Server-Sent Events: Persistent SSE connection to
/eventsenables instant, unidirectional server-to-browser communication without polling. - Incremental updates: The system uses full body replacement or diff-based patching (
wordDiffUpdate,wordPatchUpdate) to refresh content without reloading the page. - State synchronization: Selection and mark states persist across updates through the overlay layer, which reapplies decorations after every DOM mutation.
- Bidirectional interaction: User selections POST to
/api/selection, allowing the server to broadcast state changes to all connected browsers.
Frequently Asked Questions
How does watch mode avoid full page reloads when documents change?
Watch mode avoids reloads by using Server-Sent Events to stream DOM mutation instructions directly to the browser. The watch-sse-core.js script receives these messages and applies them incrementally—either replacing the entire body or patching specific elements—while the overlay layer immediately reapply decorations through the _watchReapplyHook callback, preserving all interactive state.
What happens to my text selection when the document updates?
The overlay layer in watch-sse-core.js maintains selection state in the _selection array and automatically redraws highlights after every content update. When the core script finishes mutating the DOM, it calls window._watchReapplyHook(), which triggers applySelectionToDom() in the overlay layer, ensuring your selection survives incremental patches or full body replacements.
Can multiple browsers view the same live preview simultaneously?
Yes. The watch server maintains SSE connections to all connected clients and broadcasts update messages to every browser viewing the preview. When one user posts a selection change to /api/selection, the server distributes the selection-update event to all connected EventSource instances, keeping multiple views synchronized in real time.
Which file types support the incremental word-patch updates?
The system supports specialized incremental updates for Word documents through the wordPatchUpdate and wordDiffUpdate functions in watch-sse-core.js. These apply targeted DOM changes rather than full replacements, though the architecture supports full-body updates for any document type when incremental patching is not available.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →