# How OfficeCLI's Watch Command Live Preview Feature Automatically Refreshes the Browser on Document Edits

> Discover how OfficeCLI's watch command live preview automatically refreshes your browser on document edits. Learn how SSE and WatchServer deliver instant HTML updates.

- Repository: [OfficeAI/OfficeCLI](https://github.com/iofficeai/OfficeCLI)
- Tags: how-to-guide
- Published: 2026-07-17

---

**The live preview feature uses a Server-Sent Events (SSE) relay running in a background `WatchServer` process that pushes HTML updates to the browser through a named pipe whenever document edits occur.**

The `officecli watch` command provides a live preview feature that automatically refreshes your browser as you edit documents. This capability is implemented in the iOfficeAI/OfficeCLI repository through a lightweight SSE relay architecture that bridges CLI commands with browser updates. Understanding this mechanism reveals how the tool achieves real-time synchronization without requiring a full page reload.

## How the Watch Server Initializes the Live Preview

When you execute `officecli watch <file>`, the CLI spawns a dedicated `WatchServer` process that acts as the central hub for the live preview feature. In [`src/officecli/Core/Watch/WatchServer.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Core/Watch/WatchServer.cs), the constructor (lines 31-41) initializes a `TcpListener` on a local port and writes a temporary marker file to `$TMPDIR` (named `officecli-watch-<hash>.port`). This marker allows subsequent CLI commands to discover the running server without spawning duplicates.

The server embeds two JavaScript resources directly into the preview page: [`watch-sse-core.js`](https://github.com/iOfficeAI/OfficeCLI/blob/main/watch-sse-core.js) and [`watch-overlay.js`](https://github.com/iOfficeAI/OfficeCLI/blob/main/watch-overlay.js). As implemented in [`WatchServer.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/WatchServer.cs) (lines 90-99), the server injects these scripts as `<script>` tags when serving the initial HTML. The core script handles the SSE connection and DOM updates, while the overlay script adds UI helpers for selection, marks, and scrolling.

## The SSE Communication Pipeline

The browser auto-refresh mechanism relies on a unidirectional SSE stream that pushes updates from the server to the client.

### Server-Side Event Broadcasting

When the watch server receives a change notification, it processes the message through `HandleWatchMessage` in [`WatchServer.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/WatchServer.cs) (lines 313-379). This method parses the incoming JSON payload, updates the cached HTML snapshot, and broadcasts the change via `SendSseEvent`. The server maintains a list of connected `HttpResponse` objects representing active browser sessions, ensuring every client receives the update simultaneously.

### Client-Side Event Handling

The injected [`watch-sse-core.js`](https://github.com/iOfficeAI/OfficeCLI/blob/main/watch-sse-core.js) opens an `EventSource` connection to `http://localhost:<port>/events`. When the server broadcasts an event, the client-side script parses the JSON payload and applies the appropriate DOM transformation. For full refreshes (`action="full"`), it replaces the entire `<body>` content. For incremental updates, it patches only affected slides or scrolls to specific anchors as defined in [`watch-sse-core.js`](https://github.com/iOfficeAI/OfficeCLI/blob/main/watch-sse-core.js) (lines 150-210).

## Triggering Automatic Refreshes from CLI Commands

The live preview feature activates automatically when any mutating CLI command completes. After operations like `officecli format` or `officecli add-slide`, the `ResidentServer` or `CommandBuilder` invokes `WatchNotifier.NotifyIfWatching(filePath, new WatchMessage ...)`.

In [`src/officecli/Core/Watch/WatchNotifier.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Core/Watch/WatchNotifier.cs), this method opens a named pipe created by the watch server (identified via the marker file) and writes the `WatchMessage` object. The message includes the action type (`full`, `replace`, `add`, `remove`, or `scroll`), the rendered HTML payload, and optional scroll targets. This non-blocking write returns immediately, allowing the CLI to continue while the server processes the update asynchronously.

## Incremental Updates vs. Full Refreshes

The watch server optimizes performance by computing diff patches for supported document types. For Word and Excel files, `WatchServer` attempts to generate incremental updates through `ComputeWordPatches` and `ComputeExcelPatches` methods. These compute minimal DOM changes rather than transmitting complete HTML documents, reducing network overhead and rendering time.

When incremental patching fails or for unsupported formats, the server falls back to full refreshes. The `WatchMessage` with `Action="full"` triggers a complete body replacement in the browser, ensuring consistency even when complex structural changes occur.

## Starting and Stopping the Watch Server

To initiate a live preview session:

```bash
officecli watch mydoc.docx

```

This command outputs the local preview URL:

```

Watch: http://localhost:53721
Watching: /abs/path/to/mydoc.docx
Press Ctrl+C to stop.

```

The server continues running until explicitly terminated. When you press `Ctrl+C` or execute `officecli unwatch <file>`, the `StopAsync` method in [`WatchServer.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/WatchServer.cs) (lines 422-445) removes the marker file, closes the TCP listener, terminates all SSE connections, and exits gracefully.

## Summary

- **Isolation architecture**: The watch server never modifies the original document file; it only receives pre-rendered HTML through a named pipe.
- **SSE-based updates**: The browser maintains a persistent `EventSource` connection to receive JSON payloads describing document changes.
- **Automatic triggering**: CLI commands automatically notify the watch server via `WatchNotifier.NotifyIfWatching` after mutating operations.
- **Incremental optimization**: Word and Excel documents use computed diff patches when possible, falling back to full HTML replacements for complex changes.
- **Process discovery**: A temporary marker file enables CLI commands to locate and communicate with the watch server without additional configuration.

## Frequently Asked Questions

### How does the browser establish the initial connection to the watch server?

The watch server injects [`watch-sse-core.js`](https://github.com/iOfficeAI/OfficeCLI/blob/main/watch-sse-core.js) into the preview page when first serving the HTML. This script immediately opens an `EventSource` connection to `/events` on the local port, establishing a persistent SSE stream that listens for updates from the server.

### What happens if I edit the document using external tools?

The live preview feature only triggers when using OfficeCLI commands that call `WatchNotifier.NotifyIfWatching`. External edits to the document file do not automatically trigger browser refreshes unless you subsequently run an OfficeCLI command that processes the file and generates the notification.

### Does the watch server modify the original document file?

No. According to the isolation architecture in [`WatchServer.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/WatchServer.cs), the server never touches the on-disk document directly. It only receives pre-rendered HTML snapshots via the named pipe, ensuring the live preview feature operates safely without risking document corruption.

### Can multiple browsers connect to the same watch session simultaneously?

Yes. The `WatchServer` maintains a collection of active SSE connections in `SendSseEvent` and broadcasts updates to all connected clients. Each browser instance running the preview URL receives identical synchronization messages, allowing multiple viewers to track document edits in real time.