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

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.


# 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:

The watch notifier (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 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 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 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, 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 and 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:

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

The browser-side scripts expose hooks for customization:

// 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), core rendering (watch-sse-core.js), and overlay updates (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, PowerPointHandler.HtmlPreview.cs, and 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.

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 →