onenote-performance-tuning
Optimize OneNote Graph API performance for large notebooks, image handling, and batch operations. Use when dealing with slow API responses, large notebooks, image uploads, or HTTP 507 errors. Trigger with "onenote performance", "onenote slow", "onenote large notebook", "onenote image upload".
What this skill does
# OneNote — Performance Tuning & Optimization
## Overview
OneNote performance degrades predictably at scale: notebooks with 100+ sections take 3-5 seconds per API call when using `$expand`, pages with embedded images over 4MB fail silently, and sections hitting the page limit return `507 Insufficient Storage`. Image uploads are capped at 25MB per multipart part, and requesting full page content for hundreds of pages without `$select` can exhaust your rate budget in seconds.
This skill provides tested patterns for every performance bottleneck: selective `$expand` and `$select` for minimal payloads, image compression before upload, batch requests via `$batch`, pagination with `$top` to avoid loading thousands of pages, and caching strategies that invalidate on change detection.
Key pain points addressed:
- Full `$expand=sections($expand=pages)` on large notebooks can take 10+ seconds and return multi-MB responses
- Image uploads silently fail when a single multipart part exceeds 25MB — no error, just missing image
- `507 Insufficient Storage` when a section hits its page limit (approximately 5,000 pages)
- Page content retrieval (`GET /pages/{id}/content`) is 5-10x slower than metadata-only requests
## Prerequisites
- Azure app registration with delegated permissions: `Notes.ReadWrite`
- App-only auth deprecated March 31, 2025 — use delegated auth only
- Python: `pip install msgraph-sdk azure-identity Pillow` (Pillow for image compression)
- Node/TypeScript: `npm install @microsoft/microsoft-graph-client @azure/identity @azure/msal-node sharp` (sharp for image compression)
## Instructions
### Step 1 — Use $select to Minimize Payload Size
Every Graph API call should specify `$select` to return only the fields you need. The default response includes navigation properties, OData metadata, and verbose timestamps that inflate payloads:
```typescript
// BAD — returns ~2KB per page with all metadata
const pages = await client.api("/me/onenote/pages").get();
// GOOD — returns ~200 bytes per page with only needed fields
const pages = await client.api("/me/onenote/pages")
.select("id,title,lastModifiedDateTime")
.get();
// For notebooks, avoid expanding everything
// BAD — can take 10+ seconds on large notebooks
const notebooks = await client.api("/me/onenote/notebooks")
.expand("sections($expand=pages)")
.get();
// GOOD — get structure first, then drill into sections on demand
const notebooks = await client.api("/me/onenote/notebooks")
.select("id,displayName,lastModifiedDateTime,sectionsUrl")
.get();
```
Payload size comparison for a notebook with 50 sections and 500 pages:
| Query | Response Size | Response Time |
|-------|--------------|---------------|
| Full `$expand` | ~800KB | 5-10s |
| `$select` on notebook only | ~2KB | 200ms |
| `$select` + `$top(10)` sections | ~1KB | 150ms |
### Step 2 — Paginate Large Sections
Sections can accumulate thousands of pages. Always use `$top` to limit initial loads:
```typescript
async function* iteratePages(client: any, sectionId: string, pageSize: number = 50) {
let url: string | null =
`/me/onenote/sections/${sectionId}/pages?$select=id,title,lastModifiedDateTime&$orderby=lastModifiedDateTime desc&$top=${pageSize}`;
while (url) {
const response = await client.api(url).get();
const pages = response.value ?? [];
for (const page of pages) {
yield page;
}
// Stop if we got fewer than requested
if (pages.length < pageSize) break;
url = response["@odata.nextLink"] ?? null;
}
}
// Usage — process pages lazily
for await (const page of iteratePages(client, sectionId)) {
console.log(`Processing: ${page.title}`);
if (shouldStop(page)) break; // Can bail early
}
```
### Step 3 — Image Upload with Size Validation
OneNote accepts images via multipart form data. Each part is limited to 25MB. Images larger than 4MB in the rendered page can cause performance issues in the client. Always validate and compress before upload:
```typescript
import sharp from "sharp";
interface ImageUploadResult {
success: boolean;
originalSize: number;
compressedSize: number;
error?: string;
}
async function prepareImageForUpload(
imageBuffer: Buffer,
maxSizeBytes: number = 4 * 1024 * 1024, // 4MB target for good page performance
hardLimit: number = 25 * 1024 * 1024 // 25MB absolute limit per multipart part
): Promise<{ buffer: Buffer; result: ImageUploadResult }> {
const originalSize = imageBuffer.length;
if (originalSize > hardLimit) {
return {
buffer: imageBuffer,
result: { success: false, originalSize, compressedSize: originalSize,
error: `Image exceeds 25MB hard limit (${(originalSize / 1024 / 1024).toFixed(1)}MB)` },
};
}
if (originalSize <= maxSizeBytes) {
return {
buffer: imageBuffer,
result: { success: true, originalSize, compressedSize: originalSize },
};
}
// Progressively compress: reduce quality, then resize
let compressed = imageBuffer;
const qualities = [80, 60, 40];
for (const quality of qualities) {
compressed = await sharp(imageBuffer)
.jpeg({ quality, progressive: true })
.toBuffer();
if (compressed.length <= maxSizeBytes) break;
}
// If still too large, resize
if (compressed.length > maxSizeBytes) {
const metadata = await sharp(imageBuffer).metadata();
const scale = Math.sqrt(maxSizeBytes / compressed.length);
compressed = await sharp(imageBuffer)
.resize(Math.round((metadata.width ?? 1920) * scale))
.jpeg({ quality: 60 })
.toBuffer();
}
return {
buffer: compressed,
result: { success: true, originalSize, compressedSize: compressed.length },
};
}
```
**Supported image formats:** TIFF, PNG, GIF, JPEG, BMP. OneNote does not support WebP or AVIF — convert before uploading.
### Step 4 — Multipart Page Creation with Images
```typescript
async function createPageWithImage(
client: any,
sectionId: string,
title: string,
htmlBody: string,
imageName: string,
imageBuffer: Buffer
): Promise<any> {
// Validate and compress image
const { buffer, result } = await prepareImageForUpload(imageBuffer);
if (!result.success) throw new Error(result.error);
const boundary = `OneNoteBoundary${Date.now()}`;
const body = [
`--${boundary}`,
'Content-Disposition: form-data; name="Presentation"',
"Content-Type: text/html",
"",
`<!DOCTYPE html><html><head><title>${title}</title></head>`,
`<body>${htmlBody}<img src="name:${imageName}" alt="${imageName}" /></body></html>`,
`--${boundary}`,
`Content-Disposition: form-data; name="${imageName}"`,
"Content-Type: image/jpeg",
"",
buffer.toString("binary"),
`--${boundary}--`,
].join("\r\n");
return client.api(`/me/onenote/sections/${sectionId}/pages`)
.header("Content-Type", `multipart/form-data; boundary=${boundary}`)
.post(body);
}
```
### Step 5 — Batch Requests for Bulk Operations
The `$batch` endpoint processes up to 20 operations per request. This is the single most effective optimization for bulk workloads — it reduces HTTP overhead and counts as one request against rate limits:
```typescript
async function batchGetPageMetadata(
client: any,
pageIds: string[]
): Promise<Map<string, any>> {
const results = new Map<string, any>();
const BATCH_SIZE = 20;
for (let i = 0; i < pageIds.length; i += BATCH_SIZE) {
const chunk = pageIds.slice(i, i + BATCH_SIZE);
const batchBody = {
requests: chunk.map((id, idx) => ({
id: String(idx),
method: "GET",
url: `/me/onenote/pages/${id}?$select=id,title,lastModifiedDateTime`,
})),
};
const response = await client.api("/$batch").post(batchBody);
for (const item of response.responses) {
if (item.status === 200) {
results.set(item.body.id, item.body);
} else if (item.status === 404) {
// Page was deleted — skip
console.warn(`Page ${chunk[parseInt(item.Related in Image & Video
watch
IncludedWatch a video (URL or local path). Downloads with yt-dlp, extracts auto-scaled frames with ffmpeg, pulls the transcript from captions (or Whisper API fallback), and hands the result to Claude so it can answer questions about what's in the video.
physical-ai-defect-image-generation
IncludedUse when the user wants to orchestrate defect image generation, run associated setup, or handle outputs on OSMO. The Day 0 path handles cold-start with USD-to-ROI, image-edit augmentation, and AnomalyGen to create initial PCBA datasets. The Day 1 path performs inference and labeling on real images. This skill helps with first-time asset setup, creation of finetuning checkpoints, and configuring deployment. Trigger keywords: defect image generation, dig workflow, dig pipeline, defect image detection workflow, aoi pipeline, aoi anomalygen, usd2roi anomalygen, day 0 pcba, day 1 pcba, day 1 real-photo alignment, day 1 manual roi, metal surface anomaly, glass defect, anomalygen finetune, setup_pcb, setup_metal, setup_glass, setup_pretrained, dig setup, dig datasets, dig pretrained checkpoint, dig image-edit endpoint.
accelint-react-best-practices
IncludedReact performance optimization and best practices. ALWAYS use this skill when working with any React code - writing components, hooks, JSX; refactoring; optimizing re-renders, memoization, state management; reviewing for performance; fixing hydration mismatches; debugging infinite re-renders, stale closures, input focus loss, animations restarting; preventing remounting; implementing transitions, lazy initialization, effect dependencies. Even simple React tasks benefit from these patterns. Covers React 19+ (useEffectEvent, Activity, ref props). Triggers - useEffect, useState, useMemo, useCallback, memo, inline components, nested components, components inside components, re-render, performance, hydration, SSR, Next.js, useDeferredValue, combined hooks.
elevenlabs-agents
IncludedBuild conversational AI voice agents with ElevenLabs Platform using React, JavaScript, React Native, or Swift SDKs. Configure agents, tools (client/server/MCP), RAG knowledge bases, multi-voice, and Scribe real-time STT. Use when: building voice chat interfaces, implementing AI phone agents with Twilio, configuring agent workflows or tools, adding RAG knowledge bases, testing with CLI "agents as code", or troubleshooting deprecated @11labs packages, Android audio cutoff, CSP violations, dynamic variables, or WebRTC config. Keywords: ElevenLabs Agents, ElevenLabs voice agents, AI voice agents, conversational AI, @elevenlabs/react, @elevenlabs/client, @elevenlabs/react-native, @elevenlabs/elevenlabs-js, @elevenlabs/agents-cli, elevenlabs SDK, voice AI, TTS, text-to-speech, ASR, speech recognition, turn-taking model, WebRTC voice, WebSocket voice, ElevenLabs conversation, agent system prompt, agent tools, agent knowledge base, RAG voice agents, multi-voice agents, pronunciation dictionary, voice speed control, elevenlabs scribe, @11labs deprecated, Android audio cutoff, CSP violation elevenlabs, dynamic variables elevenlabs, case-sensitive tool names, webhook authentication
humanizer
IncludedHumanize AI-generated text by detecting and removing patterns typical of LLM output. Rewrites text to sound natural, specific, and human. Uses 28 pattern detectors, 560+ AI vocabulary terms across 3 tiers, and statistical analysis (burstiness, type-token ratio, readability) for comprehensive detection. Use when asked to humanize text, de-AI writing, make content sound more natural/human, review writing for AI patterns, score text for AI detection, or improve AI-generated drafts. Covers content, language, style, communication, and filler categories.
generating-mermaid-diagrams
IncludedSalesforce architecture diagrams using Mermaid with ASCII fallback. Use this skill when generating text-based diagrams for Salesforce architecture, OAuth flows, ERDs, integration sequences, or Agentforce structure. TRIGGER when: user says "diagram", "visualize", "ERD", or asks for sequence diagrams, flowcharts, class diagrams, or architecture visualizations in Mermaid. DO NOT TRIGGER when: user wants PNG/SVG image output (use generating-visual-diagrams), or asks about non-Salesforce systems.