xiaohongshu
xiaohongshu
electron
Implement Electron desktop app patterns for PhotoVault bulk uploader. Use when working with main/renderer process communication, chunked uploads, preload scripts, protocol handlers, or auto-updater. Includes security patterns and memory management for large file uploads.
Full skill instructions
When this skill activates, you MUST follow the expert workflow before writing any code:
Spawn Domain Expert using the Task tool with this prompt:
Read the expert prompt at: C:\Users\natha\Stone-Fence-Brain\VENTURES\PhotoVault\claude\experts\electron-expert.md
Then research the codebase and write an implementation plan to: docs/claude/plans/electron-[task-name]-plan.md
Task: [describe the user's request]
Spawn QA Critic after expert returns, using Task tool:
Read the QA critic prompt at: C:\Users\natha\Stone-Fence-Brain\VENTURES\PhotoVault\claude\experts\qa-critic-expert.md
Review the plan at: docs/claude/plans/electron-[task-name]-plan.md
Write critique to: docs/claude/plans/electron-[task-name]-critique.md
Present BOTH plan and critique to user - wait for approval before implementing
DO NOT read files and start coding. DO NOT rationalize that "this is simple." Follow the workflow.
The main process runs Node.js. The renderer process runs web content. Never give the renderer direct Node access.
// main.ts - Main process
ipcMain.handle('read-file', async (_, path) => {
return fs.readFile(path)
})
// preload.ts - Bridge
contextBridge.exposeInMainWorld('api', {
readFile: (path) => ipcRenderer.invoke('read-file', path)
})
// renderer.js - Web content
const content = await window.api.readFile('/path/to/file')
It's a massive security hole. Use contextBridge instead.
// ✅ CORRECT
new BrowserWindow({
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: path.join(__dirname, 'preload.js'),
},
})
Never load entire files into memory. Stream them chunk by chunk.
// ❌ BAD: 4GB file = 4GB RAM usage
const buffer = await fs.readFile(largePath)
// ✅ GOOD: Stream in chunks
const stream = fs.createReadStream(largePath, { highWaterMark: 6 * 1024 * 1024 })
for await (const chunk of stream) {
await uploadChunk(chunk)
}
Enabling nodeIntegration
// WRONG: Any website loaded can access filesystem
new BrowserWindow({
webPreferences: {
nodeIntegration: true, // NEVER DO THIS
},
})
Exposing sensitive functions to renderer
// WRONG: Renderer can delete anything
contextBridge.exposeInMainWorld('api', {
deleteFile: (path) => fs.unlink(path),
})
// RIGHT: Validate and restrict
contextBridge.exposeInMainWorld('api', {
deleteUploadedFile: (fileId) => {
const safePath = validateAndResolvePath(fileId)
return fs.unlink(safePath)
},
})
Sending large data through IPC
// WRONG: IPC has limits, blocks main process
mainWindow.webContents.send('file-data', fileBuffer) // 500MB buffer!
// RIGHT: Send reference, stream separately
mainWindow.webContents.send('file-ready', { path: largeFile, size })
Not cleaning up resources
// WRONG: File handles leak
const stream = fs.createReadStream(path)
stream.pipe(uploadStream)
// RIGHT: Proper cleanup
const stream = fs.createReadStream(path)
try {
await pipeline(stream, uploadStream)
} finally {
stream.destroy()
}
// src/preload.ts
import { contextBridge, ipcRenderer } from 'electron'
contextBridge.exposeInMainWorld('photovault', {
selectFiles: () => ipcRenderer.invoke('select-files'),
selectFolder: () => ipcRenderer.invoke('select-folder'),
startUpload: (galleryId: string, files: string[]) =>
ipcRenderer.invoke('start-upload', galleryId, files),
cancelUpload: () => ipcRenderer.invoke('cancel-upload'),
authenticate: () => ipcRenderer.invoke('authenticate'),
getAuthState: () => ipcRenderer.invoke('get-auth-state'),
logout: () => ipcRenderer.invoke('logout'),
onUploadProgress: (callback: (progress: UploadProgress) => void) => {
const listener = (_: any, progress: UploadProgress) => callback(progress)
ipcRenderer.on('upload-progress', listener)
return () => ipcRenderer.removeListener('upload-progress', listener)
},
})
// src/upload-manager.ts
import { createReadStream, statSync } from 'fs'
import { EventEmitter } from 'events'
const CHUNK_SIZE = 6 * 1024 * 1024 // 6MB chunks
const MAX_RETRIES = 3
export class UploadManager extends EventEmitter {
private cancelled = false
async uploadFile(filePath: string, galleryId: string, hubUrl: string, token: string) {
const stats = statSync(filePath)
const totalChunks = Math.ceil(stats.size / CHUNK_SIZE)
const stream = createReadStream(filePath, { highWaterMark: CHUNK_SIZE })
let chunkIndex = 0
for await (const chunk of stream) {
if (this.cancelled) {
stream.destroy()
throw new Error('Upload cancelled')
}
await this.uploadChunkWithRetry(chunk, chunkIndex, totalChunks, galleryId, hubUrl, token)
chunkIndex++
this.emit('progress', {
file: filePath,
progress: Math.round((chunkIndex / totalChunks) * 100),
})
}
}
cancel() { this.cancelled = true }
}
// In main.ts
function handleDeepLink(url: URL) {
// photovault://auth?token=X&userId=Y
if (url.pathname === '//auth' || url.pathname === '/auth') {
const token = url.searchParams.get('token')
const userId = url.searchParams.get('userId')
if (token && userId) {
authState = { token, userId, authenticated: true }
mainWindow?.webContents.send('auth-complete', authState)
mainWindow?.show()
}
}
}
// Register protocol
app.setAsDefaultProtocolClient('photovault')
| Endpoint | Purpose |
|---|---|
/api/v1/upload/prepare | Create gallery, get upload path |
/api/v1/upload/chunk | Upload individual chunk |
/api/v1/upload/process-chunked | Trigger processing after upload |
/auth/desktop-callback | OAuth callback |
{hubUrl}/auth/desktop-callback?desktop=truephotovault://auth?token=X&userId=Ynpm run dev # Development
npm run build # Build for current platform
npm run build:all # Build for all platforms
xiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience