diff --git a/package.json b/package.json index b3a0411..6c890b0 100644 --- a/package.json +++ b/package.json @@ -101,6 +101,7 @@ "build": "esbuild src/vscode/extension.ts --bundle --platform=node --format=cjs --external:vscode --outfile=dist/extension.js && esbuild src/core/xhtml.ts --bundle --platform=node --format=cjs --outfile=dist/xhtml.js && esbuild src/core/epub.ts --bundle --platform=node --format=cjs --external:vscode --outfile=dist/epub.js && esbuild src/core/state-manager.ts --bundle --platform=node --format=cjs --outfile=dist/state-manager.js && esbuild src/core/archive.ts --bundle --platform=node --format=cjs --outfile=dist/archive.js && npm run build:sidecar && npm run build:mcp", "build:sidecar": "esbuild src/antigravity/sidecar-server.ts --bundle --platform=node --format=cjs --outfile=dist/sidecar-server.cjs", "build:mcp": "esbuild src/antigravity/mcp-server.ts --bundle --platform=node --format=cjs --outfile=dist/mcp-server.cjs", + "install:plugin": "node scripts/install-plugin.js", "check": "tsc --noEmit", "check:core": "tsc -p tsconfig.core.json --noEmit", "test": "npm run build && node --test test/*.test.mjs", diff --git a/plugin/README.md b/plugin/README.md new file mode 100644 index 0000000..6b00e83 --- /dev/null +++ b/plugin/README.md @@ -0,0 +1,27 @@ +# XHTML & EPUB Reader — Antigravity 2.0 Plugin + +Interactive reader previewer for EPUB and XHTML publications with native Antigravity 2.0 Auxiliary Pane sidecar and autonomous MCP agent tools. + +## Features +- **Auxiliary Pane Sidecar UI (`sidecar://xhtml-reader-plugin/xhtml-previewer/`)**: + - Standalone reader shell served over lightweight local HTTP server. + - Responsive layout tailored for narrow auxiliary pane (~320px - 480px). + - Light, Dark, and Sepia themes, multi-column paginated & continuous scroll modes, typography controls, and Moon+ Reader style continuous overscroll transitions. + - Heuristic & semantic cross-file footnote preview popovers. + - Live Server-Sent Events (SSE) synchronization. +- **Model Context Protocol (MCP) Tools**: + - `xhtml_open_preview`: Autonomous document loading into the Sidecar previewer. + - `xhtml_get_toc`: Autonomous Table of Contents and spine inspection. + - `xhtml_get_metadata`: Publication metadata extraction (title, creator, language, spine count). + +## Quick Start +1. Ensure bundles are built: + ```bash + npm run build + ``` +2. Install the plugin into local Antigravity config: + ```bash + node scripts/install-plugin.js + ``` +3. Open Antigravity 2.0 and ask the agent: + > *"Show me a preview of sample-book/OEBPS/ch_1.xhtml"* diff --git a/plugin/assets/logo.png b/plugin/assets/logo.png new file mode 100644 index 0000000..7b838ee Binary files /dev/null and b/plugin/assets/logo.png differ diff --git a/plugin/mcp_config.json b/plugin/mcp_config.json new file mode 100644 index 0000000..9120f23 --- /dev/null +++ b/plugin/mcp_config.json @@ -0,0 +1,11 @@ +{ + "mcpServers": { + "xhtml_reader_mcp": { + "command": "node", + "type": "stdio", + "args": [ + "dist/mcp-server.cjs" + ] + } + } +} diff --git a/plugin/plugin.json b/plugin/plugin.json new file mode 100644 index 0000000..7cdd0ff --- /dev/null +++ b/plugin/plugin.json @@ -0,0 +1,18 @@ +{ + "name": "xhtml-reader-plugin", + "displayName": "XHTML & EPUB Reader", + "version": "0.1.0", + "description": "Interactive reader and previewer for XHTML and EPUB publications with auxiliary pane sidecar and MCP agent tools.", + "author": "selvagant", + "homepage": "https://github.com/intxdv/XHTML-Reader-Previewer", + "repository": { + "type": "git", + "url": "https://github.com/intxdv/XHTML-Reader-Previewer.git" + }, + "logo": "assets/logo.png", + "suggestedPrompts": [ + "Open sample-book/OEBPS/ch_1.xhtml in the reader previewer", + "Inspect the Table of Contents of sample-book/OEBPS/ch_1.xhtml", + "Show publication metadata for sample-book/OEBPS/ch_1.xhtml" + ] +} diff --git a/plugin/rules/AGENTS.md b/plugin/rules/AGENTS.md new file mode 100644 index 0000000..91056ad --- /dev/null +++ b/plugin/rules/AGENTS.md @@ -0,0 +1,16 @@ +# XHTML & EPUB Reader Presentation Rules + +When working with digital publications, books, or eBook markup: + +1. **Prioritize the Interactive Sidecar Viewer:** + Whenever the user asks to view, preview, read, or inspect an `.epub`, `.xhtml`, or `.html` file, prefer loading it into the reader previewer over dumping raw HTML or plain text into the chat. + +2. **Always Surface the Sidecar Pill Link:** + Whenever you load or update a document using `xhtml_open_preview` (or when discussing an active publication), you **MUST** include the reader sidecar pill link on its own line or within the summary so the user can open or focus the viewer in the Auxiliary Pane with one click: + ```markdown + [Buka XHTML Reader](sidecar://xhtml-reader-plugin/xhtml-previewer/) + ``` + *(Or in English: `[Open Reader Preview](sidecar://xhtml-reader-plugin/xhtml-previewer/)`)* + +3. **Autonomous Information Retrieval:** + When the user asks questions about chapter structure, table of contents, or book metadata, call `xhtml_get_toc` or `xhtml_get_metadata` directly rather than manually executing shell scripts or extracting archives. diff --git a/plugin/sidecars/xhtml-previewer/sidecar.json b/plugin/sidecars/xhtml-previewer/sidecar.json new file mode 100644 index 0000000..ad65277 --- /dev/null +++ b/plugin/sidecars/xhtml-previewer/sidecar.json @@ -0,0 +1,20 @@ +{ + "command": "node", + "args": [ + "../../dist/sidecar-server.cjs" + ], + "display_name": "XHTML & EPUB Reader", + "description": "Interactive reader and previewer for XHTML and EPUB publications in the auxiliary pane.", + "has_web_ui": true, + "restart_policy": "always", + "ui_config": { + "display_name": "XHTML Reader", + "views": [ + { + "title": "XHTML Reader", + "path": "/", + "entrypoint": "SIDECAR_UI_ENTRYPOINT_AUX_PANE" + } + ] + } +} diff --git a/plugin/skills/xhtml-reader/SKILL.md b/plugin/skills/xhtml-reader/SKILL.md new file mode 100644 index 0000000..cf2f1f4 --- /dev/null +++ b/plugin/skills/xhtml-reader/SKILL.md @@ -0,0 +1,60 @@ +--- +name: xhtml-reader +description: Live interactive preview and inspection of XHTML and EPUB publications inside Antigravity 2.0. Use when the user asks to preview, read, or inspect an EPUB book, XHTML chapter, or digital publication. Provides autonomous tools to open the reader preview in the Auxiliary Pane, inspect publication metadata, and retrieve the Table of Contents (TOC). +--- + +# XHTML & EPUB Reader Skill + +This skill allows the agent to interact with and preview `.epub` archives, extracted EPUB directories, and standalone `.xhtml`/`.html` publications using the integrated **XHTML Reader Previewer Sidecar** and **MCP Tools**. + +## When to Use + +Activate this skill when: +- The user asks to preview, view, or read an `.epub`, `.xhtml`, or `.html` file. +- The user is editing or reviewing EPUB publication markup, CSS styles, or chapter layouts. +- The user wants to inspect a book's Table of Contents (TOC) or spine reading order without manually unzipping. +- The user asks for publication metadata (title, author, language, total chapters, manifest items). + +## Autonomous MCP Tools + +The plugin exposes 3 tools via the `xhtml_reader_mcp` server: + +### 1. `xhtml_open_preview` +Opens a publication file inside the Antigravity Reader Sidecar and prepares the interactive reader shell in the Auxiliary Pane. + +**Arguments:** +- `filePath` *(string, required)*: Absolute path or workspace-relative path to the `.epub` file, extracted EPUB directory, or `.xhtml` file. +- `spineIndex` *(number, optional)*: 0-based index of the spine chapter to open directly. +- `targetId` *(string, optional)*: Element or anchor ID to scroll into view upon loading. + +**Always emit the Sidecar Pill Link:** +Whenever you call `xhtml_open_preview`, you MUST present the interactive sidecar pill link to the user in the response: +```markdown +[Buka XHTML Reader](sidecar://xhtml-reader-plugin/xhtml-previewer/) +``` +*(Or in English: `[Open Reader Preview](sidecar://xhtml-reader-plugin/xhtml-previewer/)`)* + +### 2. `xhtml_get_toc` +Extracts and parses the Table of Contents (`toc.xhtml` / `toc.ncx`) and spine reading sequence of an EPUB publication without opening the GUI. + +**Arguments:** +- `filePath` *(string, required)*: Path to the publication. + +**Use Case:** Quick chapter lookups, book structure analysis, or finding a specific chapter file path. + +### 3. `xhtml_get_metadata` +Extracts publication metadata from the package document (`content.opf`). + +**Arguments:** +- `filePath` *(string, required)*: Path to the publication. + +**Returns:** Title, creator/author, language, identifier, publisher, date, spine chapter count, and total manifest resources. + +## Best Practices & Guidelines + +1. **Prefer Interactive Preview Over Raw Dumps:** + When the user asks about an eBook or chapter, load it with `xhtml_open_preview` and share the `sidecar://` pill so the user can comfortably read it in the Auxiliary Pane alongside their code. +2. **Path Resolution:** + Always provide a valid workspace-relative or absolute path. If the user mentions a file name casually (e.g. "preview ch1"), verify its existence first before calling `xhtml_open_preview`. +3. **Graceful Fallback:** + If the Sidecar server is not yet active, the tool will return a helpful message with instructions to start `node dist/sidecar-server.cjs`. Inform the user or launch the sidecar accordingly. diff --git a/scripts/install-plugin.js b/scripts/install-plugin.js new file mode 100644 index 0000000..0ff2fac --- /dev/null +++ b/scripts/install-plugin.js @@ -0,0 +1,92 @@ +#!/usr/bin/env node +const fs = require('node:fs'); +const fsp = require('node:fs/promises'); +const path = require('node:path'); +const os = require('node:os'); + +async function installPlugin() { + const rootDir = path.resolve(__dirname, '..'); + const pluginSourceDir = path.join(rootDir, 'plugin'); + const distDir = path.join(rootDir, 'dist'); + + console.log('[XHTML Plugin Installer] Checking prerequisites...'); + + // 1. Verify build artifacts + const sidecarBundle = path.join(distDir, 'sidecar-server.cjs'); + const mcpBundle = path.join(distDir, 'mcp-server.cjs'); + + if (!fs.existsSync(sidecarBundle) || !fs.existsSync(mcpBundle)) { + console.error('❌ Build artifacts missing. Please run "npm run build" first.'); + process.exit(1); + } + + // 2. Resolve Antigravity Plugins directory + const homeDir = os.homedir(); + const configBase = process.env.ANTIGRAVITY_CONFIG_DIR || path.join(homeDir, '.gemini', 'config'); + const pluginsDir = path.join(configBase, 'plugins'); + const targetDir = path.join(pluginsDir, 'xhtml-reader-plugin'); + + console.log(`[XHTML Plugin Installer] Target directory: ${targetDir}`); + + // 3. Ensure target directories exist + await fsp.mkdir(targetDir, { recursive: true }); + + // 4. Recursive copy helper + async function copyDir(src, dest) { + await fsp.mkdir(dest, { recursive: true }); + const entries = await fsp.readdir(src, { withFileTypes: true }); + for (const entry of entries) { + const srcPath = path.join(src, entry.name); + const destPath = path.join(dest, entry.name); + if (entry.isDirectory()) { + await copyDir(srcPath, destPath); + } else { + await fsp.copyFile(srcPath, destPath); + } + } + } + + // 5. Copy plugin manifest and components + const itemsToCopy = [ + 'plugin.json', + 'mcp_config.json', + 'assets', + 'sidecars', + 'skills', + 'rules', + 'README.md' + ]; + + for (const item of itemsToCopy) { + const srcPath = path.join(pluginSourceDir, item); + const destPath = path.join(targetDir, item); + if (!fs.existsSync(srcPath)) continue; + + const stat = await fsp.stat(srcPath); + if (stat.isDirectory()) { + await copyDir(srcPath, destPath); + } else { + await fsp.copyFile(srcPath, destPath); + } + } + + // 6. Copy dist artifacts into plugin directory + const targetDistDir = path.join(targetDir, 'dist'); + await copyDir(distDir, targetDistDir); + + console.log('✅ Antigravity 2.0 Plugin successfully deployed!'); + console.log('--------------------------------------------------'); + console.log(`Plugin ID: xhtml-reader-plugin`); + console.log(`Location: ${targetDir}`); + console.log(`MCP Server: dist/mcp-server.cjs (3 tools)`); + console.log(`Sidecar: dist/sidecar-server.cjs (Auxiliary Pane)`); + console.log(`Skill: skills/xhtml-reader/SKILL.md`); + console.log(`Rule: rules/AGENTS.md`); + console.log('--------------------------------------------------'); + console.log('Open Antigravity 2.0 -> Settings / Customizations to inspect the plugin.'); +} + +installPlugin().catch((err) => { + console.error('❌ Installation failed:', err); + process.exit(1); +}); diff --git a/src/antigravity/sidecar-server.ts b/src/antigravity/sidecar-server.ts index b638464..cb0eae5 100644 --- a/src/antigravity/sidecar-server.ts +++ b/src/antigravity/sidecar-server.ts @@ -3,6 +3,7 @@ import * as fs from 'node:fs'; import * as fsp from 'node:fs/promises'; import * as path from 'node:path'; import * as os from 'node:os'; +import { fileURLToPath } from 'node:url'; import { sanitizeXhtml, extractElementById } from '../core/xhtml'; import { readerShell, ReaderNavInfo, ReaderSpineNavInfo, ReaderTocItem } from '../core/reader-shell'; import { @@ -29,6 +30,7 @@ export interface SidecarServerOptions { host?: string; storageDir?: string; cacheDir?: string; + workspaceDirs?: string[]; } export interface LoadedBookState { @@ -70,9 +72,12 @@ export class SidecarServer { private server: http.Server | undefined; private sseClients = new Set(); private cacheManager: EpubCacheManager; + private cacheDir: string; + private workspaceDirs: string[] = []; private stateManager: StateManager; private navigationHistory = new NavigationHistory(); - private loadedBook: LoadedBookState | undefined; + private loadedBooks = new Map(); + private lastActiveWorkspace?: string; private lastFootnoteResponse: { requestId: string; html?: string; error?: string } | undefined; public readonly port: number; @@ -83,7 +88,12 @@ export class SidecarServer { this.port = options.port ?? (envPort ? parseInt(envPort, 10) : 5890); this.host = options.host ?? '127.0.0.1'; + if (options.workspaceDirs && options.workspaceDirs.length > 0) { + this.workspaceDirs = [...options.workspaceDirs]; + } + const cacheBase = options.cacheDir ?? path.join(os.tmpdir(), 'xhtml-reader-sidecar'); + this.cacheDir = cacheBase; this.cacheManager = new EpubCacheManager(cacheBase); const storagePath = options.storageDir @@ -97,8 +107,16 @@ export class SidecarServer { } } - public getLoadedBook(): LoadedBookState | undefined { - return this.loadedBook; + public getLoadedBook(workspace?: string): LoadedBookState | undefined { + if (workspace) { + const key = this.normalizeWorkspaceKey(workspace); + return this.loadedBooks.get(key); + } + if (this.lastActiveWorkspace) { + const book = this.loadedBooks.get(this.lastActiveWorkspace); + if (book) return book; + } + return this.loadedBooks.values().next().value; } public async start(): Promise { @@ -161,8 +179,29 @@ export class SidecarServer { } } - public async openBook(filePath: string, spineIndex = 0, targetId?: string): Promise { - const absolutePath = path.resolve(filePath); + public async openBook( + filePath: string, + spineIndex = 0, + targetId?: string, + workspaceHint?: string + ): Promise { + let absolutePath = path.resolve(filePath); + if (!fs.existsSync(absolutePath)) { + const targetRoot = this.resolveTargetWorkspace(workspaceHint); + const candidate = path.resolve(targetRoot, filePath); + if (fs.existsSync(candidate)) { + absolutePath = candidate; + } else { + const roots = this.resolveWorkspaceDirs(); + for (const r of roots) { + const c = path.resolve(r, filePath); + if (fs.existsSync(c)) { + absolutePath = c; + break; + } + } + } + } await fsp.access(absolutePath, fs.constants.R_OK); const ext = path.extname(absolutePath).toLowerCase(); @@ -188,6 +227,10 @@ export class SidecarServer { } } + let epubPackage: EpubPackage | undefined; + let safeSpineIndex = 0; + let currentChapterPath = absolutePath; + if (containerRootPath) { const containerUri = createResourceUri(path.join(containerRootPath, 'META-INF', 'container.xml')); const containerXml = await fsp.readFile(containerUri.fsPath!, 'utf-8'); @@ -201,14 +244,14 @@ export class SidecarServer { const opfUri = createResourceUri(opfPath); const containerRootUri = createResourceUri(containerRootPath); const opfXml = await fsp.readFile(opfPath, 'utf-8'); - const epubPackage = parseOpfXml(opfXml, opfUri, containerRootUri); + epubPackage = parseOpfXml(opfXml, opfUri, containerRootUri); epubPackage.toc = await loadEpubToc(epubPackage, async (uri) => { return fsp.readFile(uri.fsPath || uri.path, 'utf-8'); }); // Find spine index if opening a specific chapter file - let safeSpineIndex = Math.max(0, Math.min(spineIndex, epubPackage.spine.length - 1)); + safeSpineIndex = Math.max(0, Math.min(spineIndex, epubPackage.spine.length - 1)); if (!stat.isDirectory() && ext !== '.epub') { const foundIdx = epubPackage.spine.findIndex( (item) => path.resolve(item.uri.fsPath || item.uri.path) === absolutePath @@ -219,43 +262,37 @@ export class SidecarServer { } const initialChapter = epubPackage.spine[safeSpineIndex]; - const currentChapterPath = initialChapter ? (initialChapter.uri.fsPath || initialChapter.uri.path) : ''; - - this.loadedBook = { - filePath: absolutePath, - fileName, - isEpub: true, - title: epubPackage.title, - cacheDir: ext === '.epub' ? containerRootPath : undefined, - bookRootDir: containerRootPath, - epubPackage, - currentSpineIndex: safeSpineIndex, - currentChapterPath, - currentFragment: targetId - }; - } else { - // Standalone XHTML / HTML file - const bookRootDir = path.dirname(absolutePath); - this.loadedBook = { - filePath: absolutePath, - fileName, - isEpub: false, - title: fileName, - bookRootDir, - currentSpineIndex: 0, - currentChapterPath: absolutePath, - currentFragment: targetId - }; + currentChapterPath = initialChapter ? (initialChapter.uri.fsPath || initialChapter.uri.path) : ''; } + const targetWs = this.resolveTargetWorkspace(workspaceHint || absolutePath); + const wsKey = this.normalizeWorkspaceKey(targetWs); + + const loadedBook: LoadedBookState = { + filePath: absolutePath, + fileName, + isEpub: Boolean(containerRootPath), + title: containerRootPath && epubPackage ? epubPackage.title : fileName, + cacheDir: ext === '.epub' ? containerRootPath : undefined, + bookRootDir: containerRootPath || path.dirname(absolutePath), + epubPackage, + currentSpineIndex: safeSpineIndex, + currentChapterPath, + currentFragment: targetId + }; + + this.loadedBooks.set(wsKey, loadedBook); + this.lastActiveWorkspace = wsKey; + this.broadcastEvent('bookLoaded', { - title: this.loadedBook.title, - fileName: this.loadedBook.fileName, - currentSpineIndex: this.loadedBook.currentSpineIndex, - isEpub: this.loadedBook.isEpub + workspace: targetWs, + title: loadedBook.title, + fileName: loadedBook.fileName, + currentSpineIndex: loadedBook.currentSpineIndex, + isEpub: loadedBook.isEpub }); - return this.loadedBook; + return loadedBook; } private async rewriteAssets(markup: string, chapterDir: string, bookRootDir: string): Promise { @@ -312,24 +349,35 @@ export class SidecarServer { return; } + // 1b. Brand Logo Asset + if (pathname === '/logo.png' && req.method === 'GET') { + await this.serveLogo(res); + return; + } + // 2. Status API if (pathname === '/api/status' && req.method === 'GET') { + const wsParam = parsedUrl.searchParams.get('workspace') || undefined; + const book = this.getLoadedBook(wsParam); + const wsPath = this.resolveTargetWorkspace(wsParam); + res.writeHead(200, { 'Content-Type': 'application/json' }); res.end( JSON.stringify({ status: 'ok', - loaded: Boolean(this.loadedBook), + loaded: Boolean(book), + workspace: wsPath, port: this.port, - book: this.loadedBook + book: book ? { - filePath: this.loadedBook.filePath, - title: this.loadedBook.title, - fileName: this.loadedBook.fileName, - isEpub: this.loadedBook.isEpub, - currentSpineIndex: this.loadedBook.currentSpineIndex, - totalChapters: this.loadedBook.epubPackage?.spine.length ?? 1, - currentChapterPath: this.loadedBook.currentChapterPath, - currentFragment: this.loadedBook.currentFragment + filePath: book.filePath, + title: book.title, + fileName: book.fileName, + isEpub: book.isEpub, + currentSpineIndex: book.currentSpineIndex, + totalChapters: book.epubPackage?.spine.length ?? 1, + currentChapterPath: book.currentChapterPath, + currentFragment: book.currentFragment } : null }) @@ -343,6 +391,40 @@ export class SidecarServer { return; } + // 3b. Upload and Open File API + if (pathname === '/api/upload' && req.method === 'POST') { + await this.handleUploadApi(req, res); + return; + } + + // 3c. Workspace Files API + if (pathname === '/api/workspace-files' && req.method === 'GET') { + const wsParam = parsedUrl.searchParams.get('workspace'); + const wsPath = this.resolveTargetWorkspace(wsParam || undefined); + const files = await this.scanWorkspaceDir(wsPath); + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ workspace: wsPath, files })); + return; + } + + // 3d. Set Workspace API + if (pathname === '/api/set-workspace' && req.method === 'POST') { + try { + const body = await this.readRequestBody(req); + const parsed = JSON.parse(body || '{}'); + const uris = parsed.workspaceUris || parsed.workspacePaths || []; + const firstUri = uris[0]; + const wsPath = this.resolveTargetWorkspace(firstUri); + const files = await this.scanWorkspaceDir(wsPath); + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ success: true, workspace: wsPath, files })); + } catch (err: any) { + res.writeHead(500, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ success: false, error: err.message })); + } + return; + } + // 4. Server-Sent Events (SSE) Stream if (pathname === '/api/events' && req.method === 'GET') { this.handleSseStream(req, res); @@ -364,7 +446,7 @@ export class SidecarServer { return; } const assetRelPath = rawUrl.replace(/^\/assets\/?/, '').split('?')[0]; - await this.serveAsset(assetRelPath, res); + await this.serveAsset(assetRelPath, res, req); return; } @@ -398,11 +480,13 @@ export class SidecarServer { return; } - const book = await this.openBook(parsed.filePath, parsed.spineIndex, parsed.targetId); + const book = await this.openBook(parsed.filePath, parsed.spineIndex, parsed.targetId, parsed.workspace); + const targetWs = this.resolveTargetWorkspace(parsed.workspace || parsed.filePath); res.writeHead(200, { 'Content-Type': 'application/json' }); res.end( JSON.stringify({ success: true, + workspace: targetWs, title: book.title, isEpub: book.isEpub, totalChapters: book.epubPackage?.spine.length ?? 1 @@ -420,49 +504,57 @@ export class SidecarServer { const body = await this.readRequestBody(req); const msg = JSON.parse(body || '{}'); - if (!this.loadedBook) { + const wsParam = msg.workspace || undefined; + const loadedBook = this.getLoadedBook(wsParam); + + if (!loadedBook) { res.writeHead(400, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'No book loaded' })); return; } + const wsPath = this.resolveTargetWorkspace(wsParam || loadedBook.filePath); + const wsKey = this.normalizeWorkspaceKey(wsPath); + let chapterChanged = false; if (msg.type === 'prevChapter') { - if (this.loadedBook.isEpub && this.loadedBook.epubPackage && this.loadedBook.currentSpineIndex > 0) { - this.loadedBook.currentSpineIndex -= 1; - const chapter = this.loadedBook.epubPackage.spine[this.loadedBook.currentSpineIndex]; - this.loadedBook.currentChapterPath = chapter.uri.fsPath || chapter.uri.path; - this.loadedBook.currentFragment = undefined; - this.loadedBook.startAtBottom = Boolean(msg.startAtBottom); - this.loadedBook.resetToTop = !msg.startAtBottom; + if (loadedBook.isEpub && loadedBook.epubPackage && loadedBook.currentSpineIndex > 0) { + loadedBook.currentSpineIndex -= 1; + const chapter = loadedBook.epubPackage.spine[loadedBook.currentSpineIndex]; + loadedBook.currentChapterPath = chapter.uri.fsPath || chapter.uri.path; + loadedBook.currentFragment = undefined; + loadedBook.startAtBottom = Boolean(msg.startAtBottom); + loadedBook.resetToTop = !msg.startAtBottom; chapterChanged = true; this.broadcastEvent('chapterChanged', { - spineIndex: this.loadedBook.currentSpineIndex, - chapterPath: this.loadedBook.currentChapterPath + workspace: wsPath, + spineIndex: loadedBook.currentSpineIndex, + chapterPath: loadedBook.currentChapterPath }); } } else if (msg.type === 'nextChapter') { if ( - this.loadedBook.isEpub && - this.loadedBook.epubPackage && - this.loadedBook.currentSpineIndex < this.loadedBook.epubPackage.spine.length - 1 + loadedBook.isEpub && + loadedBook.epubPackage && + loadedBook.currentSpineIndex < loadedBook.epubPackage.spine.length - 1 ) { - this.loadedBook.currentSpineIndex += 1; - const chapter = this.loadedBook.epubPackage.spine[this.loadedBook.currentSpineIndex]; - this.loadedBook.currentChapterPath = chapter.uri.fsPath || chapter.uri.path; - this.loadedBook.currentFragment = undefined; - this.loadedBook.resetToTop = true; - this.loadedBook.startAtBottom = false; + loadedBook.currentSpineIndex += 1; + const chapter = loadedBook.epubPackage.spine[loadedBook.currentSpineIndex]; + loadedBook.currentChapterPath = chapter.uri.fsPath || chapter.uri.path; + loadedBook.currentFragment = undefined; + loadedBook.resetToTop = true; + loadedBook.startAtBottom = false; chapterChanged = true; this.broadcastEvent('chapterChanged', { - spineIndex: this.loadedBook.currentSpineIndex, - chapterPath: this.loadedBook.currentChapterPath + workspace: wsPath, + spineIndex: loadedBook.currentSpineIndex, + chapterPath: loadedBook.currentChapterPath }); } } else if (msg.type === 'openLink' && msg.href) { if (msg.currentPosition) { - await this.stateManager.saveReadingLocation(this.loadedBook.currentChapterPath, { + await this.stateManager.saveReadingLocation(loadedBook.currentChapterPath, { scrollRatio: msg.currentPosition.scrollRatio, scrollY: msg.currentPosition.scrollY, anchorId: msg.currentPosition.anchorId @@ -470,30 +562,31 @@ export class SidecarServer { } const [filePart, fragment] = msg.href.split('#'); - let targetPath = this.loadedBook.currentChapterPath; + let targetPath = loadedBook.currentChapterPath; if (filePart) { const decoded = decodeURIComponent(filePart); - targetPath = path.resolve(path.dirname(this.loadedBook.currentChapterPath), decoded); + targetPath = path.resolve(path.dirname(loadedBook.currentChapterPath), decoded); } - if (this.isSafePath(this.loadedBook.bookRootDir, targetPath)) { - if (this.loadedBook.isEpub && this.loadedBook.epubPackage) { - const foundIdx = this.loadedBook.epubPackage.spine.findIndex( + if (this.isSafePath(loadedBook.bookRootDir, targetPath)) { + if (loadedBook.isEpub && loadedBook.epubPackage) { + const foundIdx = loadedBook.epubPackage.spine.findIndex( (item) => path.resolve(item.uri.fsPath || item.uri.path) === path.resolve(targetPath) ); if (foundIdx >= 0) { - this.loadedBook.currentSpineIndex = foundIdx; + loadedBook.currentSpineIndex = foundIdx; } } - this.loadedBook.currentChapterPath = targetPath; - this.loadedBook.currentFragment = fragment; - this.loadedBook.resetToTop = !fragment; - this.loadedBook.startAtBottom = false; + loadedBook.currentChapterPath = targetPath; + loadedBook.currentFragment = fragment; + loadedBook.resetToTop = !fragment; + loadedBook.startAtBottom = false; chapterChanged = true; this.broadcastEvent('chapterChanged', { - spineIndex: this.loadedBook.currentSpineIndex, - chapterPath: this.loadedBook.currentChapterPath, - fragment: this.loadedBook.currentFragment + workspace: wsPath, + spineIndex: loadedBook.currentSpineIndex, + chapterPath: loadedBook.currentChapterPath, + fragment: loadedBook.currentFragment }); } } else if (msg.type === 'savePreferences') { @@ -501,13 +594,22 @@ export class SidecarServer { await this.stateManager.savePreferences(msg.preferences); } } else if (msg.type === 'saveReadingPosition') { - await this.stateManager.saveReadingLocation(this.loadedBook.currentChapterPath, { + await this.stateManager.saveReadingLocation(loadedBook.currentChapterPath, { scrollRatio: msg.scrollRatio, scrollY: msg.scrollY, anchorId: msg.anchorId }); } else if (msg.type === 'requestFootnote') { - await this.handleFootnoteRequest(msg); + await this.handleFootnoteRequest(msg, loadedBook); + } else if (msg.type === 'closeBook') { + this.loadedBooks.delete(wsKey); + if (this.lastActiveWorkspace === wsKey) { + this.lastActiveWorkspace = undefined; + } + this.broadcastEvent('bookLoaded', { workspace: wsPath, book: null }); + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ received: true, chapterChanged: true })); + return; } res.writeHead(200, { 'Content-Type': 'application/json' }); @@ -519,9 +621,7 @@ export class SidecarServer { } } - private async handleFootnoteRequest(msg: { href: string; requestId: string }): Promise { - if (!this.loadedBook) return; - + private async handleFootnoteRequest(msg: { href: string; requestId: string }, book: LoadedBookState): Promise { try { const parts = msg.href.split('#'); const filePart = parts[0]; @@ -532,13 +632,13 @@ export class SidecarServer { return; } - let targetPath = this.loadedBook.currentChapterPath; + let targetPath = book.currentChapterPath; if (filePart) { const decoded = decodeURIComponent(filePart); - targetPath = path.resolve(path.dirname(this.loadedBook.currentChapterPath), decoded); + targetPath = path.resolve(path.dirname(book.currentChapterPath), decoded); } - if (!this.isSafePath(this.loadedBook.bookRootDir, targetPath)) { + if (!this.isSafePath(book.bookRootDir, targetPath)) { this.lastFootnoteResponse = { requestId: msg.requestId, error: 'Path traversal blocked' }; return; } @@ -551,25 +651,70 @@ export class SidecarServer { return; } - const rewritten = await this.rewriteAssets(extracted, path.dirname(targetPath), this.loadedBook.bookRootDir); + const rewritten = await this.rewriteAssets(extracted, path.dirname(targetPath), book.bookRootDir); this.lastFootnoteResponse = { requestId: msg.requestId, html: rewritten }; } catch (err) { this.lastFootnoteResponse = { requestId: msg.requestId, error: String(err) }; } } - private async serveAsset(assetRelPath: string, res: http.ServerResponse): Promise { - if (!this.loadedBook) { + private async serveLogo(res: http.ServerResponse): Promise { + const candidatePaths = [ + path.resolve(__dirname, '../assets/logo.png'), + path.resolve(__dirname, '../plugin/assets/logo.png'), + path.resolve(__dirname, '../media/icon.png'), + path.resolve(process.cwd(), 'plugin/assets/logo.png'), + path.resolve(process.cwd(), 'media/icon.png') + ]; + + for (const p of candidatePaths) { + try { + await fsp.access(p, fs.constants.R_OK); + const stat = await fsp.stat(p); + res.writeHead(200, { + 'Content-Type': 'image/png', + 'Content-Length': stat.size, + 'Cache-Control': 'public, max-age=86400' + }); + fs.createReadStream(p).pipe(res); + return; + } catch { + // try next candidate path + } + } + + res.writeHead(404, { 'Content-Type': 'text/plain' }); + res.end('Logo Not Found'); + } + + private async serveAsset(assetRelPath: string, res: http.ServerResponse, req?: http.IncomingMessage): Promise { + const rawUrl = req?.url || ''; + const parsed = new URL(rawUrl, `http://${this.host}:${this.port}`); + const wsHint = parsed.searchParams.get('workspace') || undefined; + let book = this.getLoadedBook(wsHint); + + if (!book) { + const decodedRel = decodeURIComponent(assetRelPath); + for (const b of this.loadedBooks.values()) { + const fullCandidate = path.resolve(b.bookRootDir, decodedRel); + if (fs.existsSync(fullCandidate)) { + book = b; + break; + } + } + } + + if (!book) { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('No book loaded'); return; } const decoded = decodeURIComponent(assetRelPath); - const fullPath = path.resolve(this.loadedBook.bookRootDir, decoded); + const fullPath = path.resolve(book.bookRootDir, decoded); // Strict Path Traversal Guard - if (!this.isSafePath(this.loadedBook.bookRootDir, fullPath)) { + if (!this.isSafePath(book.bookRootDir, fullPath)) { res.writeHead(403, { 'Content-Type': 'text/plain' }); res.end('Forbidden: Access outside book directory is blocked'); return; @@ -599,47 +744,1177 @@ export class SidecarServer { } } - private async serveReaderUi(_req: http.IncomingMessage, res: http.ServerResponse): Promise { + private async handleUploadApi(req: http.IncomingMessage, res: http.ServerResponse): Promise { + try { + const fileNameHeader = req.headers['x-file-name']; + let fileName = 'uploaded.epub'; + if (typeof fileNameHeader === 'string' && fileNameHeader.trim()) { + fileName = path.basename(decodeURIComponent(fileNameHeader)); + } + + const uploadDir = path.join(this.cacheDir, 'uploads'); + await fsp.mkdir(uploadDir, { recursive: true }); + const targetPath = path.join(uploadDir, fileName); + + const writeStream = fs.createWriteStream(targetPath); + await new Promise((resolve, reject) => { + req.pipe(writeStream); + req.on('error', reject); + writeStream.on('finish', () => resolve()); + writeStream.on('error', reject); + }); + + const book = await this.openBook(targetPath); + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end( + JSON.stringify({ + success: true, + title: book.title, + totalChapters: book.epubPackage?.spine.length ?? 1 + }) + ); + } catch (err: any) { + console.error('[Sidecar] Upload error:', err); + res.writeHead(500, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ success: false, error: err.message || String(err) })); + } + } + + public uriToFsPath(uri: string): string { + if (!uri) return ''; + try { + if (uri.startsWith('file://') || uri.startsWith('file:')) { + return fileURLToPath(uri); + } + } catch { + // fallback + } + return uri; + } + + public normalizeWorkspaceKey(dirPath?: string): string { + if (!dirPath) { + const roots = this.resolveWorkspaceDirs(); + if (roots.length > 0) { + return path.resolve(roots[0]).toLowerCase().replace(/\\/g, '/'); + } + return 'default'; + } + const fsPath = this.uriToFsPath(dirPath); + return path.resolve(fsPath).toLowerCase().replace(/\\/g, '/'); + } + + public findWorkspaceForPath(targetPath: string): string | undefined { + const normTarget = path.resolve(this.uriToFsPath(targetPath)).toLowerCase().replace(/\\/g, '/'); + const knownRoots = this.resolveWorkspaceDirs(); + for (const r of knownRoots) { + const normRoot = path.resolve(r).toLowerCase().replace(/\\/g, '/'); + if (normTarget === normRoot || normTarget.startsWith(normRoot + '/')) { + return path.resolve(r); + } + } + return undefined; + } + + public resolveTargetWorkspace(hint?: string): string { + if (hint) { + const fsPath = this.uriToFsPath(hint); + const found = this.findWorkspaceForPath(fsPath); + if (found) return found; + if (fs.existsSync(fsPath)) { + try { + const stat = fs.statSync(fsPath); + return stat.isDirectory() ? fsPath : path.dirname(fsPath); + } catch { + // ignore + } + } + } + const roots = this.resolveWorkspaceDirs(); + return roots.length > 0 ? roots[0] : process.cwd(); + } + + public sortWorkspaceFiles( + files: Array<{ fullPath: string; relPath: string; name: string; isEpub: boolean }> + ): Array<{ fullPath: string; relPath: string; name: string; isEpub: boolean }> { + return [...files].sort((a, b) => { + const isActualEpubA = a.fullPath.toLowerCase().endsWith('.epub'); + const isActualEpubB = b.fullPath.toLowerCase().endsWith('.epub'); + if (isActualEpubA && !isActualEpubB) return -1; + if (!isActualEpubA && isActualEpubB) return 1; + + return a.relPath.localeCompare(b.relPath, undefined, { numeric: true, sensitivity: 'base' }); + }); + } + + public async scanWorkspaceDir( + workspaceDir: string + ): Promise> { + const root = path.resolve(workspaceDir); + if (!fs.existsSync(root)) return []; + const files = await this.scanWorkspaceFiles(root, 0, 3, root); + return this.sortWorkspaceFiles(files); + } + + public resolveWorkspaceDirs(): string[] { + const dirs: string[] = []; + const seen = new Set(); + + const addDir = (dirPath: string | undefined | null) => { + if (!dirPath) return; + try { + const resolved = path.resolve(dirPath); + if (fs.existsSync(resolved) && !seen.has(resolved)) { + seen.add(resolved); + dirs.push(resolved); + } + } catch { + // ignore invalid paths + } + }; + + // 1. Explicitly configured or dynamically pushed workspaceDirs + for (const d of this.workspaceDirs) { + addDir(d); + } + + // 2. Discover from active Antigravity Project (~/.gemini/config/projects/.json) + try { + const projectsDir = path.join(os.homedir(), '.gemini', 'config', 'projects'); + if (fs.existsSync(projectsDir)) { + const activeProjectId = process.env.ANTIGRAVITY_PROJECT_ID; + let targetFiles: string[] = []; + + if (activeProjectId) { + const directFile = path.join(projectsDir, `${activeProjectId}.json`); + if (fs.existsSync(directFile)) { + targetFiles.push(directFile); + } + } + + // If no active project ID or file not found, check the most recently modified project + if (targetFiles.length === 0 && dirs.length === 0) { + const entries = fs.readdirSync(projectsDir, { withFileTypes: true }); + const sorted = entries + .filter((e) => e.isFile() && e.name.endsWith('.json') && e.name !== 'outside-of-project.json') + .map((e) => { + const fullPath = path.join(projectsDir, e.name); + const mtime = fs.statSync(fullPath).mtimeMs; + return { fullPath, mtime }; + }) + .sort((a, b) => b.mtime - a.mtime); + + if (sorted.length > 0) { + targetFiles.push(sorted[0].fullPath); + } + } + + for (const filePath of targetFiles) { + try { + const content = fs.readFileSync(filePath, 'utf-8'); + const data = JSON.parse(content); + const resources = data.projectResources?.resources; + if (Array.isArray(resources)) { + for (const r of resources) { + const folderUri = r.gitFolder?.folderUri || r.folder?.folderUri || r.folderUri; + if (typeof folderUri === 'string') { + const localPath = this.uriToFsPath(folderUri); + addDir(localPath); + } + } + } + } catch { + // ignore bad project json + } + } + } + } catch { + // ignore discovery error + } + + // 3. Fallback to process.cwd() if nothing else found + if (dirs.length === 0) { + addDir(process.cwd()); + } + + return dirs; + } + + public async scanAllWorkspaceFiles(): Promise< + Array<{ fullPath: string; relPath: string; name: string; isEpub: boolean }> + > { + const root = this.resolveTargetWorkspace(); + return this.scanWorkspaceDir(root); + } + + private async scanWorkspaceFiles( + dir = process.cwd(), + depth = 0, + maxDepth = 3, + rootDir?: string + ): Promise> { + if (depth > maxDepth) return []; + const effectiveRoot = rootDir ?? dir; + try { + const entries = await fsp.readdir(dir, { withFileTypes: true }); + const results: Array<{ fullPath: string; relPath: string; name: string; isEpub: boolean }> = []; + + for (const entry of entries) { + if ( + entry.name.startsWith('.') || + entry.name === 'node_modules' || + entry.name === 'dist' || + entry.name === 'tasks' || + entry.name === 'coverage' + ) { + continue; + } + const fullPath = path.join(dir, entry.name); + if (entry.isDirectory()) { + const sub = await this.scanWorkspaceFiles(fullPath, depth + 1, maxDepth, effectiveRoot); + results.push(...sub); + } else if (entry.isFile()) { + const ext = path.extname(entry.name).toLowerCase(); + if (['.epub', '.xhtml', '.html', '.htm'].includes(ext)) { + const relPath = path.relative(effectiveRoot, fullPath).replace(/\\/g, '/'); + results.push({ + fullPath, + relPath, + name: entry.name, + isEpub: ext === '.epub' + }); + } + } + } + return results; + } catch { + return []; + } + } + + private renderFilesHtml( + workspaceFiles: Array<{ fullPath: string; relPath: string; name: string; isEpub: boolean }> + ): string { + if (workspaceFiles.length > 0) { + const showSearch = workspaceFiles.length > 6; + const searchBoxHtml = showSearch + ? ` +
+ + +
` + : ''; + + return ` +
+
+ + Berkas di Workspace + ${workspaceFiles.length} +
+ ${searchBoxHtml} +
+ ${workspaceFiles + .map( + (f) => ` +
+ + ${f.isEpub ? 'EPUB' : 'XHTML'} + +
+ ${this.escapeText(f.name)} + ${this.escapeText(f.relPath)} +
+ +
` + ) + .join('')} +
+
`; + } + return ` +
+

Tidak ada berkas .epub atau .xhtml di workspace saat ini.

+
`; + } + + private escapeText(text: string): string { + return text + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); + } + + private async serveReaderUi(req: http.IncomingMessage, res: http.ServerResponse): Promise { const preferences = this.stateManager.getPreferences(); + const parsedUrl = new URL(req.url || '/', `http://${this.host}:${this.port}`); + const wsParam = parsedUrl.searchParams.get('workspace'); + const wsPath = this.resolveTargetWorkspace(wsParam || undefined); + const wsKey = this.normalizeWorkspaceKey(wsPath); + const loadedBook = + this.loadedBooks.get(wsKey) || + (this.loadedBooks.size === 1 && !wsParam ? this.loadedBooks.values().next().value : undefined); + + if (!loadedBook) { + const workspaceFiles = await this.scanWorkspaceDir(wsPath); + const filesListHtml = this.renderFilesHtml(workspaceFiles); - if (!this.loadedBook) { // Empty state const emptyHtml = ` - XHTML Reader Previewer + + XHTML & EPUB Reader -
-
📖
-

XHTML & EPUB Reader

-

Belum ada buku atau berkas XHTML yang dimuat ke dalam Auxiliary Pane.

-
Gunakan perintah Agent atau panggil /api/open
+
+
+
+
+ XHTML Reader +
+

XHTML & EPUB Reader

+

Belum ada buku atau berkas XHTML yang dimuat.

+

Pilih naskah di bawah atau unggah berkas untuk mulai membaca.

+
+ +
${filesListHtml}
+ +
+ + atau + +
+ + +
+ +
+ +
+
+ Pilih Berkas dari Komputer + atau seret dan lepas (.epub, .xhtml) ke panel ini +
+
+ + +
+ + + +
+ +
+ + Gunakan perintah Agent atau panggil /api/open +
+
`; @@ -649,52 +1924,52 @@ export class SidecarServer { } try { - const chapterContentRaw = await fsp.readFile(this.loadedBook.currentChapterPath, 'utf-8'); + const chapterContentRaw = await fsp.readFile(loadedBook.currentChapterPath, 'utf-8'); const sanitized = sanitizeXhtml(chapterContentRaw); - const chapterDir = path.dirname(this.loadedBook.currentChapterPath); - const rewrittenContent = await this.rewriteAssets(sanitized, chapterDir, this.loadedBook.bookRootDir); + const chapterDir = path.dirname(loadedBook.currentChapterPath); + const rewrittenContent = await this.rewriteAssets(sanitized, chapterDir, loadedBook.bookRootDir); - const tocItems: ReaderTocItem[] | undefined = this.loadedBook.epubPackage?.toc.map((t) => ({ + const tocItems: ReaderTocItem[] | undefined = loadedBook.epubPackage?.toc.map((t) => ({ label: t.label, href: t.href, - active: t.href.includes(path.basename(this.loadedBook!.currentChapterPath)) + active: t.href.includes(path.basename(loadedBook.currentChapterPath)) })); const navInfo: ReaderNavInfo = { - hasPrev: this.loadedBook.isEpub ? this.loadedBook.currentSpineIndex > 0 : false, - hasNext: this.loadedBook.isEpub - ? this.loadedBook.currentSpineIndex < (this.loadedBook.epubPackage?.spine.length ?? 1) - 1 + hasPrev: loadedBook.isEpub ? loadedBook.currentSpineIndex > 0 : false, + hasNext: loadedBook.isEpub + ? loadedBook.currentSpineIndex < (loadedBook.epubPackage?.spine.length ?? 1) - 1 : false, - bookTitle: this.loadedBook.title, - chapterIndex: this.loadedBook.currentSpineIndex + 1, - totalChapters: this.loadedBook.epubPackage?.spine.length ?? 1, - currentFileName: path.basename(this.loadedBook.currentChapterPath), + bookTitle: loadedBook.title, + chapterIndex: loadedBook.currentSpineIndex + 1, + totalChapters: loadedBook.epubPackage?.spine.length ?? 1, + currentFileName: path.basename(loadedBook.currentChapterPath), isLinear: true, toc: tocItems }; - if (this.loadedBook.epubPackage) { - navInfo.spineItems = this.loadedBook.epubPackage.spine.map((sp, idx) => ({ + if (loadedBook.epubPackage) { + navInfo.spineItems = loadedBook.epubPackage.spine.map((sp, idx) => ({ index: idx + 1, idref: sp.idref, href: sp.href, fileName: path.basename(sp.href), linear: sp.linear !== false, - active: idx === this.loadedBook!.currentSpineIndex + active: idx === loadedBook.currentSpineIndex })); } - const initialLocation = this.stateManager.getReadingLocation(this.loadedBook.currentChapterPath); + const initialLocation = this.stateManager.getReadingLocation(loadedBook.currentChapterPath); - const resetToTop = Boolean(this.loadedBook.resetToTop); - const startAtBottom = Boolean(this.loadedBook.startAtBottom); - this.loadedBook.resetToTop = false; - this.loadedBook.startAtBottom = false; + const resetToTop = Boolean(loadedBook.resetToTop); + const startAtBottom = Boolean(loadedBook.startAtBottom); + loadedBook.resetToTop = false; + loadedBook.startAtBottom = false; const html = readerShell( rewrittenContent, - this.loadedBook.currentChapterPath, - this.loadedBook.currentFragment, + loadedBook.currentChapterPath, + loadedBook.currentFragment, { cspSource: `http://${this.host}:*` }, navInfo, preferences, @@ -703,8 +1978,13 @@ export class SidecarServer { startAtBottom ); + const injectedHtml = html.replace( + '