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

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.


# Start watching a Word document on the default port

officecli watch MyReport.docx

Specify a custom port using the --port flag:


# 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/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) – Parses arguments, generates initial HTML, and manages the WatchServer lifecycle
  2. Watch Server (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/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 – Establishes the SSE connection, listens for "html" events, and applies DOM diffs using a minimal patch algorithm
  • 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/src/officecli/Core/Watch/WatchNotifier.cs).

Add a visual mark to the current selection:

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

List all current marks:

officecli watch MyReport.docx marks

Navigate to a specific element by its data-path:

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:

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:

// 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), SSE relay server (WatchServer.cs), and client-side JavaScript (watch-sse-core.js and 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, 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 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.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →