# How to Use OfficeCLI's Watch Mode for Live Document Preview

> Discover OfficeCLI watch mode for live document preview. Instantly see Word, PowerPoint, and Excel file changes in your browser without page reloads.

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

---

**OfficeCLI's watch mode starts a local SSE server that streams rendered HTML fragments to your browser, updating the preview instantly when you edit Word, PowerPoint, or Excel files without reloading the page.**

The `iOfficeAI/OfficeCLI` repository provides a **watch mode** that enables real-time document preview directly in your browser. When you invoke `officecli watch <file>`, the tool launches a lightweight Server-Sent Events (SSE) server that keeps the rendered HTML synchronized with your document edits. This architecture supports Word, PowerPoint, and Excel formats through a unified pipeline that isolates the watch process from the source file to prevent corruption.

## Starting the Watch Server

To begin a live preview session, execute the watch command followed by your document path. The CLI will output a local URL (e.g., `http://localhost:12345`) where you can view the rendered document.

```bash

# Start live preview for a Word document

officecli watch my-document.docx

# The command prints a localhost URL; open it in any browser

# Edit the file in your preferred editor—updates appear automatically

```

To terminate the session, press `Ctrl+C` in the terminal or run `officecli unwatch my-document.docx`. The server performs an orderly shutdown by canceling its internal `_cts` token, disposing the TCP listener, and removing the temporary marker file (`officecli-watch-<hash>.port`).

## Architecture of the Watch System

The watch implementation consists of three distinct layers that work together to deliver incremental updates:

- **Core Server Layer**: [`src/officecli/Core/Watch/WatchServer.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Core/Watch/WatchServer.cs) manages the TCP listener, serves the SSE stream, and handles process lifecycle.
- **Core Script Layer**: [`src/officecli/Resources/watch-sse-core.js`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Resources/watch-sse-core.js) renders the initial document HTML and exposes the `window._watchReapplyHook` callback.
- **Overlay Script Layer**: [`src/officecli/Resources/watch-overlay.js`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Resources/watch-overlay.js) receives change notifications via the EventSource and updates the DOM without reloading.

The **watch notifier** ([`src/officecli/Core/Watch/WatchNotifier.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Core/Watch/WatchNotifier.cs)) acts as a fire-and-forget helper that pushes HTML fragments to the running server through a named pipe, preserving the watch-isolation guarantee.

## How the Live Preview Works

When you start a watch session, the following sequence ensures your browser stays synchronized with file changes:

1. **Server Initialization**: `WatchServer` creates a marker file and loads embedded JavaScript resources using `LoadWatchResource("Resources.watch-sse-core.js")` and `LoadWatchResource("Resources.watch-overlay.js")`.

2. **SSE Stream Establishment**: The server opens a TCP listener restricted to `localhost`/`127.0.0.1` and returns a `Content-Type: text/event-stream` header to establish the persistent connection.

3. **Initial Document Render**: [`watch-sse-core.js`](https://github.com/iOfficeAI/OfficeCLI/blob/main/watch-sse-core.js) builds the HTML preview from the Office document and injects it into the page. It initializes `window._watchEs` as the EventSource and defines `window._watchReapplyHook` for subsequent updates.

4. **Overlay Activation**: [`watch-overlay.js`](https://github.com/iOfficeAI/OfficeCLI/blob/main/watch-overlay.js) replaces the reapply hook with its own `reapplyDecorations` function, enabling it to react to incremental updates while preserving UI state like selection highlights.

5. **Change Notification**: When a handler detects mutations (e.g., [`WordHandler.HtmlPreview.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/WordHandler.HtmlPreview.cs) rendering a paragraph edit), it calls `WatchNotifier.NotifyAsync(htmlFragment)`. The notifier connects to the named pipe with a 100ms timeout and forwards the HTML payload.

6. **Browser Update**: The overlay script receives the SSE event, parses the HTML fragment, and injects it into the DOM via the reapply hook, updating the preview without a full page reload.

7. **Graceful Shutdown**: Upon receiving `SIGTERM` or `Ctrl+C`, the `Shutdown()` method cancels the `_cts` token, stops the watchdog timer, and cleans up the marker file.

## Security and Isolation Guarantees

The watch subsystem implements strict boundaries to protect your documents and system:

- **File Isolation**: The server never opens the original Office file directly. It only receives HTML snapshots from handlers (e.g., [`ExcelHandler.HtmlPreview.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/ExcelHandler.HtmlPreview.cs), [`PowerPointHandler.HtmlPreview.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/PowerPointHandler.HtmlPreview.cs)), ensuring the watch process cannot corrupt the source document.
- **Network Restrictions**: By default, the TCP listener only accepts connections from `localhost`. You can explicitly whitelist additional hosts via the `OFFICECLI_WATCH_ALLOWED_HOSTS` environment variable to prevent DNS rebinding attacks.
- **Resource Embedding**: Both [`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) are embedded resources within the binary, ensuring the watch functionality works without external file dependencies.

## Programmatic Integration

You can trigger live updates from custom handlers by invoking the notifier with rendered HTML:

```csharp
// Inside a document handler after generating HTML
string htmlFragment = RenderWordToHtml(doc);
await WatchNotifier.NotifyAsync(htmlFragment);

```

The browser-side scripts expose hooks for customization:

```javascript
// watch-overlay.js registers the update handler
var es = window._watchEs;
window._watchReapplyHook = reapplyDecorations;

// You can extend reapplyDecorations to add UI indicators
function reapplyDecorations() {
    // Custom logic to highlight changed regions
    console.log('Document updated via SSE');
}

```

## Summary

- **Start watching** with `officecli watch <file>` to launch the SSE server and generate a localhost preview URL.
- **Three-layer architecture** separates server management ([`WatchServer.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/WatchServer.cs)), core rendering ([`watch-sse-core.js`](https://github.com/iOfficeAI/OfficeCLI/blob/main/watch-sse-core.js)), and overlay updates ([`watch-overlay.js`](https://github.com/iOfficeAI/OfficeCLI/blob/main/watch-overlay.js)).
- **Isolation guarantee** ensures the watch process never touches the original Office file, receiving only HTML snapshots via `WatchNotifier.NotifyAsync`.
- **Cross-format support** works uniformly across Word, PowerPoint, and Excel through their respective `HtmlPreview` handlers.
- **Security defaults** restrict connections to localhost unless explicitly configured otherwise via environment variables.

## Frequently Asked Questions

### What file formats support watch mode in OfficeCLI?

OfficeCLI's watch mode supports Word (`.docx`), PowerPoint (`.pptx`), and Excel (`.xlsx`) files. Each format implements a dedicated handler—[`WordHandler.HtmlPreview.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/WordHandler.HtmlPreview.cs), [`PowerPointHandler.HtmlPreview.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/PowerPointHandler.HtmlPreview.cs), and [`ExcelHandler.HtmlPreview.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/ExcelHandler.HtmlPreview.cs)—that converts the document to HTML and feeds it into the same unified watch pipeline.

### How does OfficeCLI watch mode prevent document corruption?

The system enforces **watch isolation** by design. The `WatchServer` never opens or locks the original Office file; it only receives HTML fragments through the named pipe from `WatchNotifier`. This architecture guarantees that bugs or crashes in the watch process cannot write to or corrupt the source document.

### Can I access the live preview from another device on my network?

By default, no. The server binds only to `localhost`/`127.0.0.1` to prevent unauthorized access. However, you can set the `OFFICECLI_WATCH_ALLOWED_HOSTS` environment variable to explicitly whitelist IP addresses or hostnames if you need to share the preview across your local network.

### How do I stop the watch server if the terminal is closed?

If the terminal session ends abruptly, you can run `officecli unwatch <filename>` from a new terminal to signal the orphaned process to shut down. Alternatively, the server includes an idle-autosave watchdog that automatically terminates the process after a period of inactivity, cleaning up the `officecli-watch-<hash>.port` marker file.