# How to Use OfficeCLI `watch` Command for Live HTML Preview with Auto-Refresh

> Master the OfficeCLI watch command for instant HTML previews. Auto-refresh renders Word, Excel, and PowerPoint docs live in your browser as you edit via CLI.

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

---

**The `officecli watch` command launches a local Server-Sent Events (SSE) server that renders Word, Excel, and PowerPoint documents as live HTML in your browser, automatically refreshing the view whenever the document is modified through CLI operations.**

The **OfficeCLI** tool from the `iOfficeAI/OfficeCLI` repository provides a sophisticated live preview system for Office documents. By using the **`watch` command**, developers can open a persistent browser session that reflects document changes in real-time without manually reloading the page. This article explains the complete architecture and usage patterns based on the actual source code implementation.

## Starting a Live Preview Session

To begin watching a document, specify the path to any `.docx`, `.xlsx`, or `.pptx` file:

```bash
officecli watch MyReport.docx

```

By default, the server binds to **port 26315**. To use a custom port, include the `--port` argument:

```bash
officecli watch MyPresentation.pptx --port 3000

```

The command blocks until terminated, maintaining the SSE connection to your browser while listening for document changes.

## Architecture of the Live Preview System

The implementation spans three tightly-coupled layers that ensure the document file itself is never locked by the preview server.

### CLI Orchestration Layer

Located in [[`CommandBuilder.Watch.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/CommandBuilder.Watch.cs)](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.Watch.cs#L12-L34), this layer handles argument parsing and initial HTML generation. It first attempts to retrieve rendered HTML from a resident background process via `ResidentClient.TrySend`. If no resident process is available, it falls back to opening the document directly through `DocumentHandlerFactory.Open` and rendering via the registry.

The orchestrator then instantiates `WatchServer` with the file path, chosen port, and initial HTML content, wrapping the entire lifecycle in `SafeRun` to guarantee clean shutdown on SIGINT or SIGTERM.

### SSE Relay Server

The [[`WatchServer.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/WatchServer.cs)](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Core/Watch/WatchServer.cs#L16-L30) implementation acts as a pure Server-Sent Events relay. Crucially, **the server never opens or locks the document file**; it receives pre-rendered HTML strings through a named pipe IPC mechanism (`WatchNotifier`) and pushes updates to connected browsers.

Key responsibilities include:

- **State Management**: Maintains in-memory **selection** (`_currentSelection`) and **marks** (`_currentMarks`) protected by `_selectionLock` and `_marksLock` respectively.
- **Script Injection**: Lazily loads embedded JavaScript resources ([`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)) via `LoadWatchResource` and injects them into the page header.
- **Idle Shutdown**: Automatically terminates after 5 minutes of inactivity, configurable via the `OFFICECLI_WATCH_IDLE_SECONDS` environment variable (implemented in `ResolveIdleTimeout`, lines 106-119).
- **Robust Shutdown**: All termination paths converge on a single `_shutdownTask` guarded by `_shutdownLock`, ensuring the `TcpListener` stops cleanly.

### Browser Client Overlay

Two embedded JavaScript files handle the browser-side logic:

- **[`watch-sse-core.js`](https://github.com/iOfficeAI/OfficeCLI/blob/main/watch-sse-core.js)**: Establishes the SSE connection, listens for `"html"` events, and applies DOM updates using a minimal diff-patch algorithm. It exposes `window._watchEs` (the `EventSource` instance) and triggers `window._watchReapplyHook` after each mutation.
- **[`watch-overlay.js`](https://github.com/iOfficeAI/OfficeCLI/blob/main/watch-overlay.js)**: Registers the reapply hook to implement selection handling, mark rendering, rubber-band drawing, and CSS injection. It communicates back to the server via the named pipe for actions like **mark**, **goto**, and **unmark**.

## Managing a Running Watch Session

While the watch server is active, you can manipulate the preview state through subcommands without restarting the session.

**Adding a Mark**

Annotate specific elements by path:

```bash
officecli watch MyReport.docx mark --color yellow --path /body/p[3]

```

**Listing Marks**

View all current annotations:

```bash
officecli watch MyReport.docx marks

```

**Navigating to Elements**

Scroll the browser view to a specific element:

```bash
officecli watch MyReport.docx goto --path /body/p[5]

```

**Stopping the Server**

Terminate the watch session and release the port:

```bash
officecli unwatch MyReport.docx

```

## Configuration and Lifecycle Management

The watch server includes safeguards for resource management. The **idle timeout** defaults to 300 seconds (5 minutes) but can be adjusted:

```bash
export OFFICECLI_WATCH_IDLE_SECONDS=600
officecli watch MyReport.docx

```

All state (selections and marks) resides strictly in memory and is lost when the server terminates. The shutdown sequence in [`WatchServer.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/WatchServer.cs) ensures that even under forced termination, the underlying TCP socket and named pipe resources are released properly.

## Programmatic Integration

Third-party tools can push updates to a running watch server using the [`WatchNotifier`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Core/Watch/WatchNotifier.cs) static methods. This enables custom workflows where document transformations trigger preview refreshes:

```csharp
// Push a custom HTML snapshot to the watch server
bool success = WatchNotifier.SendRefresh(
    filePath: @"C:\Docs\MyReport.docx",
    html: "<html>...</html>",
    version: 42);

```

The `WatchNotifier` provides non-blocking methods for sending updates, querying the current selection (`GetSelection`), and modifying marks (`AddMark`, `RemoveMark`). Failures are silently ignored, allowing the CLI to continue operating even if no watch process is listening.

## Summary

- The `officecli watch` command provides **live HTML preview** for Word, Excel, and PowerPoint documents through a local SSE server.
- The system uses a **three-layer architecture**: CLI orchestration ([`CommandBuilder.Watch.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/CommandBuilder.Watch.cs)), SSE relay ([`WatchServer.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/WatchServer.cs)), and browser overlay ([`watch-sse-core.js`](https://github.com/iOfficeAI/OfficeCLI/blob/main/watch-sse-core.js), [`watch-overlay.js`](https://github.com/iOfficeAI/OfficeCLI/blob/main/watch-overlay.js)).
- The server operates on **port 26315** by default, supports custom ports via `--port`, and shuts down automatically after an idle period (configurable via `OFFICECLI_WATCH_IDLE_SECONDS`).
- Document state (selections and marks) is maintained **in-memory** only and synchronized via named pipe IPC.
- Subcommands (`mark`, `marks`, `goto`, `unwatch`) allow runtime interaction without restarting the preview session.

## Frequently Asked Questions

### Does the watch server lock the document file?

No. According to the implementation in [`WatchServer.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/WatchServer.cs), the server never opens the document file directly. It receives pre-rendered HTML via named pipe IPC from the CLI process, allowing you to continue editing the file through other `officecli` commands or external applications while the preview remains active.

### What happens if I close the browser tab?

The watch server continues running until the idle timeout expires (default 5 minutes) or you explicitly invoke `officecli unwatch`. You can reconnect by simply refreshing the browser or navigating back to `http://localhost:26315` (or your custom port).

### Can I run multiple watch sessions for different files simultaneously?

Yes, provided each instance uses a distinct port. Specify unique ports using the `--port` argument when launching each `officecli watch` command. The `WatchNotifier` routes updates to the correct server instance based on the file path.

### How does the browser update without reloading?

The client-side [`watch-sse-core.js`](https://github.com/iOfficeAI/OfficeCLI/blob/main/watch-sse-core.js) establishes a Server-Sent Events connection to the `WatchServer`. When the CLI renders new HTML (via the resident process or direct handling), it pushes the content through the named pipe to the server, which broadcasts it as an SSE event. The JavaScript then applies a DOM diff-patch to update only the changed elements, preserving scroll position and UI state.