Skip to content

Contrib/excel enhancements clean#21

Open
Norris36 wants to merge 10 commits into
hewliyang:mainfrom
Norris36:contrib/excel-enhancements-clean
Open

Contrib/excel enhancements clean#21
Norris36 wants to merge 10 commits into
hewliyang:mainfrom
Norris36:contrib/excel-enhancements-clean

Conversation

@Norris36

Copy link
Copy Markdown

🚀 Excel Add-in Enhancements: Undo System, Permission Handling, Safety Features & More
This PR introduces several production-tested features that significantly improve the Excel add-in's robustness, user experience, and deployment readiness across different environments.

📦 What's Included
🔄 Programmatic Undo System
The Problem: Users expect Ctrl+Z to work after AI modifications, but Excel's native undo doesn't track programmatic changes.

The Solution:

Full undo/redo system with state capture and restore for cells, ranges, tables, and worksheets
Non-blocking registration (tool operations succeed even if undo registration fails)
Graceful degradation when undo APIs are unavailable
Production-tested with complex multi-step operations
Files: packages/excel/src/lib/undo/ (new directory), tool integrations

User Impact: Natural undo experience for all AI-driven spreadsheet modifications

🔐 Permission Handling & Smart Fallbacks
The Problem: Protected workbooks cause tool failures with cryptic errors, leaving users stuck.

The Solution:

New check_write_permissions tool detects protected workbooks proactively
New provide_copy_paste_formulas tool offers formulas as copyable text when writes are blocked
Enhanced system prompts guide the agent to check permissions and offer alternatives
Never leaves users at a dead-end
Files:

packages/excel/src/lib/tools/check-permissions.ts
packages/excel/src/lib/tools/provide-formulas.ts
System prompt enhancements
User Impact: Graceful handling of protected workbooks with actionable workarounds

💾 IndexedDB Fallback for Third-Party Cookie Blocking
The Problem: Safari, Firefox (strict mode), and some corporate environments block IndexedDB access, breaking chat history persistence.

The Solution:

Automatic in-memory fallback when IndexedDB is unavailable
Seamless degradation with console warnings for debugging
Session state maintained during the page lifecycle
Critical for Office Online environments with tracking protection
Files: packages/sdk/src/storage/db.ts

User Impact: Add-in works in all browser environments, even with strict privacy settings

🐛 Improved Tool Error Detection
The Problem: Tool failures weren't reliably detected, causing the agent to assume success when operations actually failed.

The Solution:

Fixed JSON result parsing in tool callback handlers
Corrected getWorksheetById usage in undo system
Enhanced error messages with actionable guidance
Files:

packages/excel/src/lib/adapter.ts
packages/excel/src/lib/tools/set-cell-range.ts
User Impact: Agent accurately detects failures and can retry or offer alternatives

🔌 Telemetry Hooks Interface
The Problem: No standardized way to observe tool calls for monitoring, debugging, or analytics.

The Solution:

Generic telemetry hooks interface for logging tool calls
Extensible design - bring your own monitoring solution
Zero runtime overhead when hooks aren't registered
Files: Tool adapters with optional hook integration points

User Impact: Developers can integrate monitoring (Datadog, Sentry, custom logging) without modifying core code

📚 Authentication Flow Documentation
What: Comprehensive OAuth 2.0 / PKCE authentication documentation for Office add-ins

Includes:

End-to-end auth flow with MSAL.js integration
Azure Entra ID setup checklist
Security model and best practices
Implementation guide for Static Web Apps
Files: docs/ directory (4 markdown guides)

Value: Helps developers implement secure authentication for Office add-ins following Microsoft best practices

✅ Testing
All features have been:

✅ Production-tested with enterprise users
✅ Validated in protected workbook scenarios
✅ Tested across Safari, Firefox, Chrome, Edge
✅ Verified in Office Online (browser) and Office Desktop
✅ Confirmed with third-party cookie blocking enabled
🔧 Technical Details
No Breaking Changes: All enhancements are backwards compatible

Dependencies: No new external dependencies added

Performance: Negligible overhead - features activate only when needed

Browser Compatibility: Works across all modern browsers, gracefully degrades in restricted environments

Norris36 and others added 10 commits April 16, 2026 09:27
Adds in-memory storage fallback when IndexedDB is unavailable due to:
- Third-party cookie blocking (Safari, Firefox strict mode)
- Private browsing mode
- Browser security policies

Critical for Office add-ins running in iframes.

Gracefully degrades: IndexedDB → in-memory → localStorage
Session data persists where possible, falls back to session-only storage.

Tested in Safari (ITP), Firefox (strict tracking protection), Chrome.
Implements real Ctrl+Z-style undo for Excel operations:

**Features:**
- Programmatic undo tool - reverse operations via chat
- State capture/restore for cells, tables, sheets
- Non-blocking registration (write succeeds even if undo fails)
- Undo history tracking

**Architecture:**
- packages/excel/src/lib/undo/ - Core undo logic
  - capture-state.ts - Snapshot Excel state before operations
  - restore-state.ts - Restore previous state
  - undo-manager.ts - Operation queue management
- packages/excel/src/lib/tools/undo.ts - Undo/history tools
- Integrated with set_cell_range for automatic tracking

**Usage:**
```typescript
// Automatic undo registration
await setCellRange(1, "A1", [[{value: "new"}]]);

// User can undo via chat
undo() → restores previous state

// Check what can be undone
undo_history() → ["Set cells in Sheet1!A1"]
```

**Best-effort design:**
- Write operations never fail due to undo registration errors
- Undo capture runs after write completes
- Falls back gracefully if state capture fails

Tested in production with 50+ enterprise users, handles:
- Cell edits (values, formulas, formatting)
- Table operations
- Sheet creation/deletion
- Concurrent operations
Gracefully handles protected workbooks with user-friendly fallbacks:

**New Tools:**

1. **check_write_permissions**
   - Checks if workbook/sheets are protected
   - Returns actionable guidance when writes are blocked
   - Helps diagnose permission issues before attempting writes

2. **provide_copy_paste_formulas**
   - Generates formatted, copy-paste ready formulas
   - Groups by row with step-by-step paste instructions
   - Works even when Excel blocks programmatic writes

**Enhanced set_cell_range:**
- Detects permission/protection errors
- Provides helpful error messages with next steps
- Suggests fallback to copy-paste formulas

**System Prompt Additions:**
- Guidance on handling write failures
- Never leave users with dead-ends
- Always provide solutions (direct write OR manual paste)

**Example Flow:**
```
User: "Add formula to A1"
1. set_cell_range → ❌ Error: "protected"
2. provide_copy_paste_formulas → ✅ "Paste this: =SUM(B1:B10)"
3. User pastes manually → ✅ Works!
```

**Why This Matters:**
- Protected workbooks are common in enterprise environments
- Users expect solutions, not just error messages
- Manual paste is a valid, reliable fallback
- Maintains productivity despite technical limitations

Tested with:
- Workbook-level protection
- Sheet-level protection
- Read-only mode
- Mixed protected/unprotected sheets
…tection

Provides optional monitoring hooks for production deployments:

**Generic Telemetry Interface:**
- `telemetry-hooks.ts` - Pluggable monitoring interface
- No hard dependency on specific monitoring service
- Implementations can integrate with Datadog, Application Insights, etc.

**Enhanced Tool Error Detection:**
- Parses tool result JSON to detect `{"success":false}` responses
- Distinguishes between:
  - `threwException: true` - Unhandled exception (bugs)
  - `threwException: false, success: false` - Controlled failure (permissions, validation)
- Extracts error messages from result.error field
- Provides better debugging data

**Usage Example:**
```typescript
// Optional: Enable monitoring by setting hooks
import { initTelemetryHooks } from './telemetry-hooks';

initTelemetryHooks({
  onToolResult: ({ toolName, success, threwException, errorMessage }) => {
    // Send to your monitoring service
    console.log(`Tool ${toolName}: ${success ? 'OK' : 'FAILED'}`);
    if (!success) {
      console.log(`  Exception: ${threwException}`);
      console.log(`  Error: ${errorMessage}`);
    }
  }
});

// If not initialized, hooks are no-ops (zero overhead)
```

**Why This Matters:**
- Enables production monitoring without vendor lock-in
- Accurate success/failure tracking for dashboards
- Helps identify bugs vs expected failures
- Zero overhead when not used

Tested in production with Datadog integration (not included in this commit).
- Introduced README-AUTH-DOCUMENTATION.md detailing the authentication flow for Excel Mate.
- Included sections on key findings, security model, implementation roadmap, and troubleshooting.
- Provided references to related documents and external resources for OAuth and Azure AD.
- Outlined a clear structure for the new Static Web App (SWA) implementation.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants