# How the OfficeCLI Watch Command Provides Live HTML Preview with Auto-Refresh

> Discover how the OfficeCLI watch command offers live HTML preview with auto-refresh. Learn about its SSE server, IPC, and efficient document change broadcasting.

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

---

**The OfficeCLI `watch` command launches a lightweight Server-Sent Events (SSE) server that broadcasts document changes to connected browsers via named-pipe IPC, enabling real-time HTML preview without file-lock contention.**

The **OfficeCLI watch command** transforms static Office documents into live, auto-refreshing HTML previews directly from your terminal. Implemented in the [iOfficeAI/OfficeCLI](https://github.com/iOfficeAI/OfficeCLI) repository, this feature eliminates the need to manually reload browsers when editing Word, Excel, or PowerPoint files. By combining a pure SSE relay with an inter-process communication (IPC) layer, the tool delivers instantaneous visual feedback while avoiding file-lock conflicts.

## Starting the SSE Preview Server

### Initial HTML Snapshot Generation

When you execute `officecli watch <file>`, the system first attempts to retrieve an HTML view through the resident daemon using `ResidentClient.TrySend`. If the daemon is unavailable, it falls back to opening the document directly via the appropriate handler—`PowerPointHandler`, `ExcelHandler`, or `WordHandler`—and calls `RenderViaRegistry` to generate the initial snapshot.

### Embedded JavaScript Injection

The `WatchServer` class in [`src/officecli/Core/Watch/WatchServer.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Core/Watch/WatchServer.cs) (lines 81-91) loads two embedded 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). These scripts handle the client-side SSE plumbing and UI decorations, respectively. The server injects them into the HTML page served to browsers at `http://localhost:26315` (default port).

## Real-Time Update Pipeline via Named Pipes

### The WatchNotifier IPC Channel

Every modifying command—such as `set`, `add`, or `remove`—invokes `WatchNotifier` to broadcast changes. Located in [`src/officecli/Core/Watch/WatchNotifier.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Core/Watch/WatchNotifier.cs) (lines 15-25), this helper opens a named pipe (`officecli-watch-<hash>`) and transmits a JSON message describing the mutation. Messages support two modes:

- **FullHtml**: A complete document snapshot replacement
- **Incremental patches**: `replace`, `add`, or `remove` operations targeting specific slides or blocks

### Server-Side Message Processing

`WatchServer` runs `RunPipeListenerAsync` to accept connections. Upon receiving a message via `HandleSinglePipeClientAsync`, the `HandleWatchMessage` method (lines 118-143) processes the payload:

- If `FullHtml` is present, it replaces `_currentHtml` entirely
- For partial updates, it mutates the cache using `PatchSlideInHtml`, `AppendSlideToHtml`, or `RemoveSlideFromHtml`

After updating the snapshot, the server increments a version counter and emits an SSE event via `SendSseEvent`, transmitting the action type, slide number, HTML fragment, and optional scroll selector.

## Client-Side DOM Synchronization

### SSE Event Handling and Patching

The injected [`watch-sse-core.js`](https://github.com/iOfficeAI/OfficeCLI/blob/main/watch-sse-core.js) establishes an `EventSource` connection to the server. When it receives events, it applies modifications to the DOM based on the action type:

- **full**: Replaces the entire `<body>` element
- **slide-level**: Patches specific slide elements for PowerPoint presentations
- **Word documents**: Computes block-level diffs using `ComputeWordPatches`

### Auxiliary UI Features

The [`watch-overlay.js`](https://github.com/iOfficeAI/OfficeCLI/blob/main/watch-overlay.js) resource provides visual enhancements including selection marks, rubber-band selection, and scroll coordination. When the server sends a `scroll` selector, the client automatically navigates to the target element.

## Process Lifecycle and Resource Management

### Idle Shutdown Protection

To prevent resource leaks, `WatchServer` implements an idle watchdog configurable via `OFFICECLI_WATCH_IDLE_SECONDS` (default 300 seconds). If no browser remains connected for the specified duration, `StopAsync` triggers a clean shutdown, closing TCP sockets and deleting the on-disk marker file.

### Graceful Termination

The server captures SIGTERM, SIGHUP, SIGQUIT, and Ctrl+C signals. Upon termination, it cancels the pipe listener, terminates SSE connections, and releases all file handles without corrupting the underlying Office document.

## Practical Usage Examples

```bash

# Start a watch on a Word document (default port 26315)

officecli watch mydoc.docx

# In another terminal, modify the document; the preview refreshes automatically

officecli set mydoc.docx --text "Hello, world!"

# Add a visual mark that appears in the live preview

officecli watch mark mydoc.docx "/body/p[1]" --color "#ff0000" --note "Important paragraph"

```

When the first command executes, it outputs `Watch: http://localhost:26315`. Opening this URL displays the rendered document, which updates instantly as subsequent commands mutate the file.

## Summary

- The **OfficeCLI watch command** creates a self-contained SSE server that never locks the Office document directly, instead operating on an in-memory HTML snapshot.
- Updates flow through a named-pipe IPC mechanism (`officecli-watch-<hash>`) using `WatchNotifier`, supporting both full snapshots and incremental patches.
- The server in [`WatchServer.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/WatchServer.cs) manages snapshot state, applies DOM-level patches, and broadcasts changes via `SendSseEvent`.
- Client-side JavaScript ([`watch-sse-core.js`](https://github.com/iOfficeAI/OfficeCLI/blob/main/watch-sse-core.js)) handles real-time DOM updates, scrolling, and mark visualization without page reloads.
- Built-in idle detection (`OFFICECLI_WATCH_IDLE_SECONDS`) and signal handling ensure the process terminates cleanly when inactive.

## Frequently Asked Questions

### Does the watch command lock the Office file while running?

No. The `WatchServer` process never opens the Office document directly after the initial render. It works exclusively with an in-memory HTML snapshot, while other commands communicate via named pipes. This architecture prevents file-lock contention, allowing simultaneous editing by other tools.

### What port does the OfficeCLI watch server use?

By default, the server binds to port **26315**. You can access the live preview by navigating to `http://localhost:26315` in any modern web browser. The port prints to stdout when the command initializes.

### How does the browser know when to refresh the preview?

The server pushes updates using **Server-Sent Events (SSE)**. The embedded [`watch-sse-core.js`](https://github.com/iOfficeAI/OfficeCLI/blob/main/watch-sse-core.js) script opens a persistent `EventSource` connection to the server. When document mutations occur, `WatchNotifier` sends JSON messages through the named pipe, triggering `SendSseEvent` to broadcast the change to all connected browsers.

### Can I use the watch command with PowerPoint and Excel, or only Word?

The watch command supports **Word, PowerPoint, and Excel** files. Each document type uses its respective handler (`PowerPointHandler`, `ExcelHandler`, or `WordHandler`) for the initial HTML generation. The real-time update mechanism works across all three formats, with format-specific patching logic (e.g., slide-level updates for PowerPoint).