# How to Use the OfficeCLI Watch Command for Live HTML Preview with Auto-Refresh

> Learn to use the OfficeCLI watch command for live HTML preview. Auto-refresh your browser as you modify documents via the CLI with this powerful SSE server.

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

---

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

The **iOfficeAI/OfficeCLI** repository provides a sophisticated three-layer architecture that enables real-time preview of Word, Excel, and PowerPoint files without manual page reloads. This functionality allows developers and technical writers to see immediate visual feedback when programmatically editing documents via command-line operations.

## Starting a Live Preview Session

To begin watching a document, pass the file path to the `watch` command. By default, the server starts on port **26315** and opens the rendered HTML in your default browser.

```bash

# Start watching a Word document on the default port

officecli watch MyReport.docx

```

Specify a custom port using the `--port` flag:

```bash

# Use port 3000 for the preview server

officecli watch Presentation.pptx --port 3000

```

The initial rendering logic 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) attempts to use a resident process first (`ResidentClient.TrySend` with `mode=html` and `Json=true`). If no resident process is available, it falls back to directly opening the file via `DocumentHandlerFactory.Open` and rendering through the registry using `RenderViaRegistry`.

## Three-Layer Architecture Overview

The watch system operates through three tightly-coupled components that separate concerns between document processing, server communication, and browser rendering:

1. **CLI Orchestration** ([`CommandBuilder.Watch.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/CommandBuilder.Watch.cs)) – Parses arguments, generates initial HTML, and manages the `WatchServer` lifecycle
2. **Watch Server** ([`WatchServer.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/WatchServer.cs)) – A pure SSE relay that never opens document files, receiving HTML via named pipes
3. **Client Overlay** (embedded JavaScript) – Handles DOM updates, selection tracking, and user interactions in the browser

## The Watch Server SSE Relay

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 functions as a **pure Server-Sent Events relay** that maintains a live connection to your browser without ever accessing the document file directly. Instead, it receives pre-rendered HTML strings through a named pipe IPC mechanism (`WatchNotifier`).

Key server capabilities include:

- **In-Memory State Management** – Tracks `_currentSelection` and `_currentMarks` in memory with dedicated lock objects (`_selectionLock`, `_marksLock`) for thread-safe access
- **Idle Timeout Protection** – Automatically shuts down after 5 minutes of inactivity (configurable via the `OFFICECLI_WATCH_IDLE_SECONDS` environment variable), implemented in `ResolveIdleTimeout` (lines 106-119)
- **Graceful Shutdown** – All termination paths converge on a single `_shutdownTask` guarded by `_shutdownLock`, ensuring the `TcpListener` stops cleanly regardless of whether shutdown is triggered by the `unwatch` command, idle timeout, or OS signals

The server injects two embedded JavaScript resources into the HTML header:
- **[`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 diffs using a minimal patch algorithm
- **[`watch-overlay.js`](https://github.com/iOfficeAI/OfficeCLI/blob/main/watch-overlay.js)** – Implements selection handling, mark rendering, rubber-band drawing, and CSS injection, communicating back to the server via the named pipe

## Managing Selections and Marks

While a watch session is active, you can interact with the document state through subcommands that communicate with the running server via [[`WatchNotifier.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/WatchNotifier.cs)](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Core/Watch/WatchNotifier.cs).

Add a visual mark to the current selection:

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

```

List all current marks:

```bash
officecli watch MyReport.docx marks

```

Navigate to a specific element by its data-path:

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

```

These operations use static methods on `WatchNotifier` that are non-blocking; failures (such as no active watch process) are silently ignored to prevent CLI crashes.

## Stopping the Watch Server

Terminate an active watch session using the `unwatch` command:

```bash
officecli unwatch MyReport.docx

```

Alternatively, the server exits automatically after the configured idle timeout expires.

## Programmatic Integration

You can push custom HTML updates to a running watch server from your own C# code using the same named pipe infrastructure:

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

```

This allows external tools or automated workflows to update the live preview when modifying documents outside of the standard CLI commands.

## Configuration Options

The watch command respects the following configuration mechanisms:

- **`--port`** – Override the default port 26315 when starting the server
- **`OFFICECLI_WATCH_IDLE_SECONDS`** – Environment variable controlling the automatic shutdown timeout (default: 300 seconds)

## Summary

- The `officecli watch` command provides **live HTML preview** for `.docx`, `.xlsx`, and `.pptx` files using a **Server-Sent Events architecture**
- The system separates concerns into **CLI orchestration** ([`CommandBuilder.Watch.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/CommandBuilder.Watch.cs)), **SSE relay server** ([`WatchServer.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/WatchServer.cs)), and **client-side JavaScript** ([`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))
- Document state (selections and marks) is maintained **in-memory** on the server, enabling fast queries and modifications without file I/O
- Use **`officecli unwatch`** or wait for the **idle timeout** (configurable via `OFFICECLI_WATCH_IDLE_SECONDS`) to stop the server
- Integrate programmatically using `WatchNotifier.SendRefresh` to push HTML updates via the named pipe IPC

## Frequently Asked Questions

### What file types does the OfficeCLI watch command support?

The watch command supports Word documents (`.docx`), Excel spreadsheets (`.xlsx`), and PowerPoint presentations (`.pptx`). According to the source code in [`CommandBuilder.Watch.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/CommandBuilder.Watch.cs), the system uses `DocumentHandlerFactory.Open` to automatically select the appropriate handler for each file type, rendering them into HTML for browser preview.

### How does the auto-refresh mechanism work without reloading the page?

The browser maintains a persistent **Server-Sent Events (SSE)** connection to the local watch server. When the document changes, the CLI sends new HTML through a named pipe to the `WatchServer`, which pushes it to the browser via SSE. The client-side [`watch-sse-core.js`](https://github.com/iOfficeAI/OfficeCLI/blob/main/watch-sse-core.js) applies DOM diff-patches to update only changed elements, preserving scroll position and selection state.

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

Yes, you can run multiple instances by specifying different ports for each document using the `--port` flag. Each `WatchServer` instance operates independently with its own TCP listener and named pipe communication channel, though each specific file can only have one active watch session at a time.

### Why does my watch server stop after a few minutes of inactivity?

The server implements an **idle timeout** that terminates the process after 5 minutes (300 seconds) of no activity to prevent resource leaks. You can customize this duration by setting the `OFFICECLI_WATCH_IDLE_SECONDS` environment variable before starting the watch command, or simply restart the watch session when needed.