From 7748999a8b0c3ab5e7b107bf7c42f24580cb23aa Mon Sep 17 00:00:00 2001 From: haoyuren <13851610112@163.com> Date: Sun, 15 Mar 2026 01:57:17 -0500 Subject: Real-time comment sync, MCP server expansion, multi-tab terminal, UI fixes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Fix Socket.IO v0.9 ack parser to handle acks without data (6:::N format), fixing comment creation stuck at "sending" - Rewrite comment sync to use local state updates from socket events (new-comment, resolve-thread, reopen-thread, delete-thread, edit-message, delete-message) instead of REST re-fetches — instant UI updates - Optimistic updates for all comment actions (resolve, reopen, delete, reply, edit) - Fetch threads + contexts on project connect so editor highlights are correct from startup, not only when review panel is opened - Add comment context to store immediately after creation for instant highlight - Rename MCP server from overleaf-comments to lattex, add 6 new tools: reopen_comment, delete_comment, get_chat_messages, send_chat_message, list_project_files, compile_latex — all auto-granted permissions - Refactor terminal from fixed Terminal/Claude tabs to dynamic multi-tab with bottom tab bar and unlimited new terminal creation - Fix chat panel layout overflow pushing other components Co-Authored-By: Claude Opus 4.6 --- src/main/index.ts | 285 ++++++++------ src/main/overleafProtocol.ts | 17 +- src/main/overleafSocket.ts | 7 +- src/mcp/lattex.mjs | 560 ++++++++++++++++++++++++++++ src/preload/index.ts | 25 +- src/renderer/src/App.css | 79 +++- src/renderer/src/App.tsx | 11 + src/renderer/src/components/Editor.tsx | 17 +- src/renderer/src/components/ReviewPanel.tsx | 237 ++++++++++-- src/renderer/src/components/Terminal.tsx | 85 +++-- src/renderer/src/stores/appStore.ts | 5 + 11 files changed, 1132 insertions(+), 196 deletions(-) create mode 100644 src/mcp/lattex.mjs (limited to 'src') diff --git a/src/main/index.ts b/src/main/index.ts index 96a225c..6e0b40b 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -3,7 +3,7 @@ import { app, BrowserWindow, ipcMain, dialog, shell, net } from 'electron' import { join, basename } from 'path' -import { readFile, writeFile } from 'fs/promises' +import { readFile, writeFile, mkdir as mkdirAsync, unlink } from 'fs/promises' import { spawn } from 'child_process' import * as pty from 'node-pty' import { OverleafSocket, type RootFolder, type SubFolder, type JoinDocResult } from './overleafSocket' @@ -15,6 +15,24 @@ const ptyInstances = new Map() let overleafSock: OverleafSocket | null = null let compilationManager: CompilationManager | null = null let fileSyncBridge: FileSyncBridge | null = null +let mcpStateDir = '' // syncDir for .lattex-mcp.json +let mcpProjectId = '' +let mcpCommentContexts: Record = {} +let mcpPathDocMap: Record = {} // relPath → docId for MCP + +async function writeMcpState(): Promise { + if (!mcpStateDir || !mcpProjectId) return + try { + const state = { + projectId: mcpProjectId, + cookie: overleafSessionCookie, + csrf: overleafCsrfToken, + commentContexts: mcpCommentContexts, + pathDocMap: mcpPathDocMap + } + await writeFile(join(mcpStateDir, '.lattex-mcp.json'), JSON.stringify(state, null, 2)) + } catch { /* ignore */ } +} function createWindow(): void { mainWindow = new BrowserWindow({ @@ -45,6 +63,7 @@ function sendToRenderer(channel: string, ...args: unknown[]) { } } + ipcMain.handle('fs:readFile', async (_e, filePath: string) => { return readFile(filePath, 'utf-8') }) @@ -359,22 +378,27 @@ ipcMain.handle('overleaf:replyThread', async (_e, projectId: string, threadId: s }) // Resolve a thread -ipcMain.handle('overleaf:resolveThread', async (_e, projectId: string, threadId: string) => { +ipcMain.handle('overleaf:resolveThread', async (_e, projectId: string, threadId: string, docId?: string) => { if (!overleafSessionCookie) return { success: false } - const result = await overleafFetch(`/project/${projectId}/thread/${threadId}/resolve`, { + // docId is required in the URL path for resolve + const docSegment = docId ? `/doc/${docId}` : '' + const result = await overleafFetch(`/project/${projectId}${docSegment}/thread/${threadId}/resolve`, { method: 'POST', body: '{}' }) + if (!result.ok) console.log(`[resolveThread] failed: ${result.status}`, result.data) return { success: result.ok } }) // Reopen a thread -ipcMain.handle('overleaf:reopenThread', async (_e, projectId: string, threadId: string) => { +ipcMain.handle('overleaf:reopenThread', async (_e, projectId: string, threadId: string, docId?: string) => { if (!overleafSessionCookie) return { success: false } - const result = await overleafFetch(`/project/${projectId}/thread/${threadId}/reopen`, { + const docSegment = docId ? `/doc/${docId}` : '' + const result = await overleafFetch(`/project/${projectId}${docSegment}/thread/${threadId}/reopen`, { method: 'POST', body: '{}' }) + if (!result.ok) console.log(`[reopenThread] failed: ${result.status}`, result.data) return { success: result.ok } }) @@ -406,7 +430,7 @@ ipcMain.handle('overleaf:deleteThread', async (_e, projectId: string, docId: str return { success: result.ok } }) -// Add a new comment: create thread via REST then submit op via Socket.IO +// Add a new comment: create thread via REST then submit comment op via existing socket async function addComment( projectId: string, docId: string, @@ -415,6 +439,7 @@ async function addComment( content: string ): Promise<{ success: boolean; threadId?: string; message?: string }> { if (!overleafSessionCookie) return { success: false, message: 'not_logged_in' } + if (!overleafSock) return { success: false, message: 'not_connected' } // Generate a random threadId (24-char hex like Mongo ObjectId) const threadId = Array.from({ length: 24 }, () => Math.floor(Math.random() * 16).toString(16)).join('') @@ -426,123 +451,29 @@ async function addComment( }) if (!msgResult.ok) return { success: false, message: `REST failed: ${msgResult.status}` } - // Step 2: Submit the comment op via Socket.IO WebSocket - const hsRes = await overleafFetch(`/socket.io/1/?t=${Date.now()}&projectId=${projectId}`, { raw: true }) - if (!hsRes.ok) return { success: false, message: 'handshake failed' } - const sid = (hsRes.data as string).split(':')[0] - if (!sid) return { success: false, message: 'no sid' } - - const { session: electronSession } = await import('electron') - const ses = electronSession.fromPartition('overleaf-sio-add-' + Date.now()) - - ses.webRequest.onHeadersReceived((details, callback) => { - const headers = { ...details.responseHeaders } - delete headers['set-cookie'] - delete headers['Set-Cookie'] - callback({ responseHeaders: headers }) - }) - - const allCookieParts = overleafSessionCookie.split('; ') - for (const sc of hsRes.setCookies) { - allCookieParts.push(sc.split(';')[0]) - } - for (const pair of allCookieParts) { - const eqIdx = pair.indexOf('=') - if (eqIdx < 0) continue - try { - await ses.cookies.set({ - url: 'https://www.overleaf.com', - name: pair.substring(0, eqIdx), - value: pair.substring(eqIdx + 1), - domain: '.overleaf.com', - path: '/', - secure: true - }) - } catch { /* ignore */ } - } - - const win = new BrowserWindow({ - width: 800, height: 600, show: false, - webPreferences: { nodeIntegration: false, contextIsolation: false, session: ses } - }) - + // Step 2: Submit the comment op via the existing socket connection try { - win.webContents.on('console-message', (_e, _level, msg) => { - console.log('[overleaf-add-comment]', msg) - }) - await win.loadURL('https://www.overleaf.com/login') + // Join doc if not already joined, to get the current version + const alreadyJoined = docEventHandlers.has(docId) + const joinResult = await overleafSock.joinDoc(docId) + const version = joinResult.version - const script = ` - new Promise(async (mainResolve) => { - try { - var ws = new WebSocket('wss://' + location.host + '/socket.io/1/websocket/${sid}'); - var ackId = 0, ackCbs = {}, evtCbs = {}; - - ws.onmessage = function(e) { - var d = e.data; - if (d === '2::') { ws.send('2::'); return; } - if (d === '1::') return; - var am = d.match(/^6:::(\\d+)\\+([\\s\\S]*)/); - if (am) { - var cb = ackCbs[parseInt(am[1])]; - if (cb) { delete ackCbs[parseInt(am[1])]; try { cb(JSON.parse(am[2])); } catch(e2) { cb(null); } } - return; - } - var em2 = d.match(/^5:::(\\{[\\s\\S]*\\})/); - if (em2) { - try { - var evt = JSON.parse(em2[1]); - var ecb = evtCbs[evt.name]; - if (ecb) { delete evtCbs[evt.name]; ecb(evt.args); } - } catch(e3) {} - } - }; + // Send the comment op + const commentOp = { c: text, p: pos, t: threadId } + console.log('[addComment] submitting op:', JSON.stringify(commentOp), 'v:', version) - function emitAck(name, args) { - return new Promise(function(res) { ackId++; ackCbs[ackId] = res; - ws.send('5:' + ackId + '+::' + JSON.stringify({ name: name, args: args })); }); - } - function waitEvent(name) { - return new Promise(function(res) { evtCbs[name] = res; }); - } + await overleafSock.applyOtUpdate(docId, [commentOp], version, '') + console.log('[addComment] op applied successfully') + + // Leave doc if we joined it just for this + if (!alreadyJoined) { + await overleafSock.leaveDoc(docId) + } - ws.onerror = function() { mainResolve({ error: 'ws_error' }); }; - ws.onclose = function(ev) { console.log('ws closed: ' + ev.code); }; - - ws.onopen = async function() { - try { - var jpPromise = waitEvent('joinProjectResponse'); - ws.send('5:::' + JSON.stringify({ name: 'joinProject', args: [{ project_id: '${projectId}' }] })); - await jpPromise; - - // Join the doc to submit the op - await emitAck('joinDoc', ['${docId}']); - - // Submit the comment op - var commentOp = { c: ${JSON.stringify(text)}, p: ${pos}, t: '${threadId}' }; - console.log('submitting op: ' + JSON.stringify(commentOp)); - await emitAck('applyOtUpdate', ['${docId}', { doc: '${docId}', op: [commentOp], v: 0 }]); - - await emitAck('leaveDoc', ['${docId}']); - ws.close(); - mainResolve({ success: true }); - } catch (e) { ws.close(); mainResolve({ error: e.message }); } - }; - setTimeout(function() { ws.close(); mainResolve({ error: 'timeout' }); }, 30000); - } catch (e) { mainResolve({ error: e.message }); } - }); - ` - - const result = await win.webContents.executeJavaScript(script) - console.log('[overleaf] addComment result:', result) - - if (result?.error) return { success: false, message: result.error } return { success: true, threadId } } catch (e) { - console.log('[overleaf] addComment error:', e) + console.log('[addComment] error:', e) return { success: false, message: String(e) } - } finally { - win.close() } } @@ -663,6 +594,15 @@ ipcMain.handle('ot:connect', async (_e, projectId: string) => { sendToRenderer('cursor:remoteDisconnected', args[0]) } else if (name === 'new-chat-message') { sendToRenderer('chat:newMessage', args[0]) + } else if ( + name === 'new-comment' || + name === 'resolve-thread' || + name === 'reopen-thread' || + name === 'delete-thread' || + name === 'edit-message' || + name === 'delete-message' + ) { + sendToRenderer('comments:event', { type: name, args }) } }) @@ -677,6 +617,107 @@ ipcMain.handle('ot:connect', async (_e, projectId: string) => { fileSyncBridge = new FileSyncBridge(overleafSock, tmpDir, docPathMap, pathDocMap, fileRefs, mainWindow!, projectId, overleafSessionCookie, overleafCsrfToken) await fileSyncBridge.start() + // Write MCP state + config for Claude Code integration + mcpStateDir = tmpDir + mcpProjectId = projectId + mcpCommentContexts = {} + mcpPathDocMap = pathDocMap + writeMcpState() + // Write .mcp.json so Claude Code auto-discovers the MCP server + const appRoot = app.isPackaged ? join(app.getAppPath(), '..') : join(__dirname, '..', '..') + const mcpServerPath = join(appRoot, 'src', 'mcp', 'lattex.mjs') + writeFile(join(tmpDir, '.mcp.json'), JSON.stringify({ + mcpServers: { + lattex: { + command: 'node', + args: [mcpServerPath] + } + } + }, null, 2)).catch(() => {}) + // Write CLAUDE.md with project context + writeFile(join(tmpDir, 'CLAUDE.md'), `# LatteX Project — Overleaf Integration + +This is a LaTeX project synced from Overleaf via LatteX. Files here are bidirectionally synced — edits you make will appear on Overleaf. + +## MCP Tools + +You have MCP tools to interact with Overleaf. Use them proactively. + +### Comments +- **get_comments**: Read comments. Pass \`file\` to filter, \`include_resolved\` for all. +- **resolve_comment**: Resolve a comment by \`thread_id\`. +- **reopen_comment**: Reopen a resolved comment. +- **reply_to_comment**: Reply to a comment thread. +- **delete_comment**: Permanently delete a comment thread. + +### Chat +- **get_chat_messages**: Read project chat history. +- **send_chat_message**: Send a message to project chat. + +### Project +- **list_project_files**: List all files with sizes. +- **compile_latex**: Trigger LaTeX compilation. Pass \`main_file\` if needed. + +### Comment Workflow +1. Use \`get_comments\` to see what reviewers have flagged +2. Edit the .tex files to address the feedback +3. Use \`reply_to_comment\` to explain what you changed +4. Use \`resolve_comment\` to mark it as done +`).catch(() => {}) + // Write .claude/settings.json to auto-allow MCP tools + mkdirAsync(join(tmpDir, '.claude'), { recursive: true }).then(() => + writeFile(join(tmpDir, '.claude', 'settings.json'), JSON.stringify({ + permissions: { + allow: [ + 'mcp__lattex__get_comments', + 'mcp__lattex__resolve_comment', + 'mcp__lattex__reopen_comment', + 'mcp__lattex__reply_to_comment', + 'mcp__lattex__delete_comment', + 'mcp__lattex__get_chat_messages', + 'mcp__lattex__send_chat_message', + 'mcp__lattex__list_project_files', + 'mcp__lattex__compile_latex' + ] + } + }, null, 2)) + ).catch(() => {}) + + // Fetch threads + comment contexts in background so editor highlights are correct from the start + setTimeout(async () => { + if (!overleafSock?.projectData) return + + // Fetch threads (fast REST call) to know which are resolved + const threadResult = await overleafFetch(`/project/${projectId}/threads`) + if (threadResult.ok && threadResult.data) { + const threads = threadResult.data as Record + const resolvedIds: string[] = [] + for (const [tid, t] of Object.entries(threads)) { + if (t.resolved) resolvedIds.push(tid) + } + sendToRenderer('comments:initThreads', { threads: threadResult.data, resolvedIds }) + } + + // Fetch comment contexts from all docs + const { docPathMap: dp } = walkRootFolder(overleafSock.projectData.project.rootFolder) + const contexts: Record = {} + for (const [did, rp] of Object.entries(dp)) { + try { + const alreadyJoined = docEventHandlers.has(did) + const result = await overleafSock.joinDoc(did) + if (result.ranges?.comments) { + for (const c of result.ranges.comments) { + if (c.op?.t) contexts[c.op.t] = { file: rp, text: c.op.c || '', pos: c.op.p || 0 } + } + } + if (!alreadyJoined) await overleafSock.leaveDoc(did) + } catch { /* ignore */ } + } + mcpCommentContexts = contexts + writeMcpState() + sendToRenderer('comments:initContexts', { contexts }) + }, 3000) + return { success: true, files, @@ -697,6 +738,14 @@ ipcMain.handle('ot:connect', async (_e, projectId: string) => { }) ipcMain.handle('ot:disconnect', async () => { + // Clean up MCP state file + if (mcpStateDir) { + unlink(join(mcpStateDir, '.lattex-mcp.json')).catch(() => {}) + } + mcpStateDir = '' + mcpProjectId = '' + mcpCommentContexts = {} + await fileSyncBridge?.stop() fileSyncBridge = null overleafSock?.disconnect() @@ -1060,6 +1109,10 @@ ipcMain.handle('ot:fetchAllCommentContexts', async () => { } } + // Update MCP state with fresh comment contexts + mcpCommentContexts = contexts + writeMcpState() + return { success: true, contexts } }) diff --git a/src/main/overleafProtocol.ts b/src/main/overleafProtocol.ts index 884aff2..abee516 100644 --- a/src/main/overleafProtocol.ts +++ b/src/main/overleafProtocol.ts @@ -65,16 +65,21 @@ export function parseSocketMessage(raw: string): ParsedMessage | null { return null } case '6': { - // Ack: 6:::N+[jsonData] - const ackMatch = raw.match(/^6:::(\d+)\+([\s\S]*)/) - if (ackMatch) { + // Ack with data: 6:::N+[jsonData] + // Ack without data: 6:::N + const ackWithData = raw.match(/^6:::(\d+)\+([\s\S]*)/) + if (ackWithData) { try { - const data = JSON.parse(ackMatch[2]) - return { type: 'ack', id: parseInt(ackMatch[1]), data } + const data = JSON.parse(ackWithData[2]) + return { type: 'ack', id: parseInt(ackWithData[1]), data } } catch { - return { type: 'ack', id: parseInt(ackMatch[1]), data: null } + return { type: 'ack', id: parseInt(ackWithData[1]), data: null } } } + const ackNoData = raw.match(/^6:::(\d+)$/) + if (ackNoData) { + return { type: 'ack', id: parseInt(ackNoData[1]), data: null } + } return null } default: diff --git a/src/main/overleafSocket.ts b/src/main/overleafSocket.ts index 195eb05..96d9138 100644 --- a/src/main/overleafSocket.ts +++ b/src/main/overleafSocket.ts @@ -301,11 +301,8 @@ export class OverleafSocket extends EventEmitter { this.joinedDocs.delete(docId) } - async applyOtUpdate(docId: string, ops: unknown[], version: number, hash: string): Promise { - // Use emitWithAck so the server's callback response comes back as a Socket.IO ack - // Do NOT send hash — Overleaf's document-updater hash check causes disconnect + rollback on mismatch - const result = await this.emitWithAck('applyOtUpdate', [docId, { doc: docId, op: ops, v: version }]) - if (result) console.log(`[applyOtUpdate] ack for ${docId} v=${version}`) + async applyOtUpdate(docId: string, ops: unknown[], version: number, hash?: string): Promise { + await this.emitWithAck('applyOtUpdate', [docId, { doc: docId, op: ops, v: version }]) } /** Get list of connected users with their cursor positions */ diff --git a/src/mcp/lattex.mjs b/src/mcp/lattex.mjs new file mode 100644 index 0000000..50c4a0e --- /dev/null +++ b/src/mcp/lattex.mjs @@ -0,0 +1,560 @@ +#!/usr/bin/env node +// Copyright (c) 2026 Yuren Hao +// Licensed under AGPL-3.0 - see LICENSE file + +// MCP Server: LatteX +// Provides tools for Claude Code to interact with the Overleaf project: +// comments, chat, file listing, compilation + +import { Server } from '@modelcontextprotocol/sdk/server/index.js' +import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js' +import { + CallToolRequestSchema, + ListToolsRequestSchema +} from '@modelcontextprotocol/sdk/types.js' +import { readFileSync, readdirSync, statSync } from 'fs' +import { join, relative } from 'path' +import https from 'https' + +// ── State ────────────────────────────────────────────────────── + +function readState() { + const cwd = process.cwd() + const statePath = join(cwd, '.lattex-mcp.json') + try { + return JSON.parse(readFileSync(statePath, 'utf-8')) + } catch { + throw new Error( + 'Cannot read .lattex-mcp.json — is LatteX running and connected to an Overleaf project?' + ) + } +} + +// ── HTTP helper ──────────────────────────────────────────────── + +function overleafRequest(method, path, cookie, csrf, body) { + return new Promise((resolve, reject) => { + const options = { + hostname: 'www.overleaf.com', + path, + method, + headers: { + Cookie: cookie, + Accept: 'application/json', + 'User-Agent': + 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36' + } + } + if (body) { + options.headers['Content-Type'] = 'application/json' + } + if (csrf && method !== 'GET') { + options.headers['x-csrf-token'] = csrf + } + + const req = https.request(options, (res) => { + let data = '' + res.on('data', (chunk) => (data += chunk)) + res.on('end', () => { + let parsed + try { + parsed = JSON.parse(data) + } catch { + parsed = data + } + resolve({ + ok: res.statusCode >= 200 && res.statusCode < 300, + status: res.statusCode, + data: parsed + }) + }) + }) + req.on('error', reject) + if (body) req.write(JSON.stringify(body)) + req.end() + }) +} + +// ── Helpers ──────────────────────────────────────────────────── + +function fmtTime(ts) { + if (!ts) return '' + return new Date(ts).toLocaleString('en-US', { + month: 'short', + day: 'numeric', + hour: '2-digit', + minute: '2-digit' + }) +} + +function userName(user) { + if (!user) return '' + return [user.first_name, user.last_name].filter(Boolean).join(' ') || + user.email?.split('@')[0] || '' +} + +function textResult(text) { + return { content: [{ type: 'text', text }] } +} + +function errorResult(text) { + return { content: [{ type: 'text', text }], isError: true } +} + +// Walk a directory recursively and return relative paths +function walkDir(dir, base) { + const results = [] + try { + for (const entry of readdirSync(dir)) { + if (entry.startsWith('.')) continue + const full = join(dir, entry) + const rel = relative(base, full) + try { + const st = statSync(full) + if (st.isDirectory()) { + results.push({ path: rel + '/', size: 0, isDir: true }) + results.push(...walkDir(full, base)) + } else { + results.push({ path: rel, size: st.size, isDir: false }) + } + } catch { /* skip */ } + } + } catch { /* skip */ } + return results +} + +// ── Tool definitions ─────────────────────────────────────────── + +const TOOLS = [ + // ── Comments ── + { + name: 'get_comments', + description: + 'Get unresolved Overleaf comments. Optionally filter by file path. Returns comment text, position, author, time, and thread_id for each comment.', + inputSchema: { + type: 'object', + properties: { + file: { + type: 'string', + description: + 'Optional file path to filter comments (e.g. "latex/main.tex"). If omitted, returns all unresolved comments.' + }, + include_resolved: { + type: 'boolean', + description: 'If true, also include resolved comments. Default: false.' + } + } + } + }, + { + name: 'resolve_comment', + description: 'Resolve (close) an Overleaf comment thread by its thread_id.', + inputSchema: { + type: 'object', + properties: { + thread_id: { + type: 'string', + description: 'The thread_id of the comment to resolve.' + } + }, + required: ['thread_id'] + } + }, + { + name: 'reopen_comment', + description: 'Reopen a previously resolved Overleaf comment thread.', + inputSchema: { + type: 'object', + properties: { + thread_id: { + type: 'string', + description: 'The thread_id of the comment to reopen.' + } + }, + required: ['thread_id'] + } + }, + { + name: 'reply_to_comment', + description: 'Reply to an existing Overleaf comment thread.', + inputSchema: { + type: 'object', + properties: { + thread_id: { + type: 'string', + description: 'The thread_id to reply to.' + }, + content: { + type: 'string', + description: 'The reply message content.' + } + }, + required: ['thread_id', 'content'] + } + }, + { + name: 'delete_comment', + description: 'Delete an entire Overleaf comment thread and its highlight. This is permanent.', + inputSchema: { + type: 'object', + properties: { + thread_id: { + type: 'string', + description: 'The thread_id of the comment to delete.' + } + }, + required: ['thread_id'] + } + }, + // ── Chat ── + { + name: 'get_chat_messages', + description: 'Get recent chat messages from the Overleaf project.', + inputSchema: { + type: 'object', + properties: { + limit: { + type: 'number', + description: 'Max number of messages to return. Default: 50.' + } + } + } + }, + { + name: 'send_chat_message', + description: 'Send a message to the Overleaf project chat.', + inputSchema: { + type: 'object', + properties: { + content: { + type: 'string', + description: 'The message text to send.' + } + }, + required: ['content'] + } + }, + // ── Project ── + { + name: 'list_project_files', + description: 'List all files in the synced project directory with their paths and sizes.', + inputSchema: { + type: 'object', + properties: {} + } + }, + { + name: 'compile_latex', + description: 'Trigger LaTeX compilation of the project. Returns compilation status and log output.', + inputSchema: { + type: 'object', + properties: { + main_file: { + type: 'string', + description: 'Optional main .tex file path (e.g. "main.tex"). Uses project default if omitted.' + } + } + } + } +] + +// ── Server ───────────────────────────────────────────────────── + +const server = new Server( + { name: 'lattex', version: '2.0.0' }, + { capabilities: { tools: {} } } +) + +server.setRequestHandler(ListToolsRequestSchema, async () => ({ + tools: TOOLS +})) + +server.setRequestHandler(CallToolRequestSchema, async (request) => { + const { name, arguments: args } = request.params + + try { + const state = readState() + const { projectId, cookie, csrf, commentContexts, pathDocMap } = state + + switch (name) { + // ── Comments ────────────────────────────────── + + case 'get_comments': { + const filterFile = args?.file || null + const includeResolved = args?.include_resolved || false + + const result = await overleafRequest( + 'GET', + `/project/${projectId}/threads`, + cookie, + csrf + ) + if (!result.ok) { + return errorResult(`Failed to fetch comments: HTTP ${result.status}`) + } + + const threads = result.data + const lines = [] + + for (const [threadId, thread] of Object.entries(threads)) { + if (!includeResolved && thread.resolved) continue + const ctx = commentContexts?.[threadId] + if (!ctx) continue + if (filterFile && ctx.file !== filterFile) continue + + const firstMsg = thread.messages?.[0] + if (!firstMsg) continue + + const author = userName(firstMsg.user) + const time = fmtTime(firstMsg.timestamp) + const attribution = [author, time].filter(Boolean).join(', ') + const status = thread.resolved ? ' [RESOLVED]' : '' + + let entry = `Thread ${threadId}${status}:\n File: ${ctx.file}\n Position: ${ctx.pos}\n Highlighted text: "${ctx.text}"\n Comment: "${firstMsg.content}"${attribution ? ` — ${attribution}` : ''}` + + for (let i = 1; i < thread.messages.length; i++) { + const reply = thread.messages[i] + const rAuthor = userName(reply.user) + const rTime = fmtTime(reply.timestamp) + const rAttr = [rAuthor, rTime].filter(Boolean).join(', ') + entry += `\n Reply: "${reply.content}"${rAttr ? ` — ${rAttr}` : ''}` + } + + lines.push(entry) + } + + if (lines.length === 0) { + return textResult( + filterFile + ? `No ${includeResolved ? '' : 'unresolved '}comments in ${filterFile}.` + : `No ${includeResolved ? '' : 'unresolved '}comments.` + ) + } + + return textResult( + `${lines.length} comment(s):\n\n${lines.join('\n\n')}` + ) + } + + case 'resolve_comment': { + const threadId = args.thread_id + const ctx = commentContexts?.[threadId] + const docId = ctx ? pathDocMap?.[ctx.file] : null + const docSegment = docId ? `/doc/${docId}` : '' + const result = await overleafRequest( + 'POST', + `/project/${projectId}${docSegment}/thread/${threadId}/resolve`, + cookie, + csrf, + {} + ) + return textResult( + result.ok + ? `Comment ${threadId} resolved.` + : `Failed to resolve: HTTP ${result.status}` + ) + } + + case 'reopen_comment': { + const threadId = args.thread_id + const ctx = commentContexts?.[threadId] + const docId = ctx ? pathDocMap?.[ctx.file] : null + const docSegment = docId ? `/doc/${docId}` : '' + const result = await overleafRequest( + 'POST', + `/project/${projectId}${docSegment}/thread/${threadId}/reopen`, + cookie, + csrf, + {} + ) + return textResult( + result.ok + ? `Comment ${threadId} reopened.` + : `Failed to reopen: HTTP ${result.status}` + ) + } + + case 'reply_to_comment': { + const { thread_id: threadId, content } = args + const result = await overleafRequest( + 'POST', + `/project/${projectId}/thread/${threadId}/messages`, + cookie, + csrf, + { content } + ) + return textResult( + result.ok + ? `Replied to thread ${threadId}.` + : `Failed to reply: HTTP ${result.status}` + ) + } + + case 'delete_comment': { + const threadId = args.thread_id + const ctx = commentContexts?.[threadId] + const docId = ctx ? pathDocMap?.[ctx.file] : null + if (!docId) { + return errorResult(`Cannot delete: no doc found for thread ${threadId}`) + } + const result = await overleafRequest( + 'DELETE', + `/project/${projectId}/doc/${docId}/thread/${threadId}`, + cookie, + csrf + ) + return textResult( + result.ok + ? `Comment ${threadId} deleted.` + : `Failed to delete: HTTP ${result.status}` + ) + } + + // ── Chat ────────────────────────────────────── + + case 'get_chat_messages': { + const limit = args?.limit || 50 + const result = await overleafRequest( + 'GET', + `/project/${projectId}/messages?limit=${limit}`, + cookie, + csrf + ) + if (!result.ok) { + return errorResult(`Failed to fetch chat: HTTP ${result.status}`) + } + + const messages = result.data + if (!Array.isArray(messages) || messages.length === 0) { + return textResult('No chat messages.') + } + + const lines = messages.map((msg) => { + const author = userName(msg.user) + const time = fmtTime(msg.timestamp) + const attr = [author, time].filter(Boolean).join(', ') + return `${attr ? `[${attr}] ` : ''}${msg.content}` + }) + + // Messages come newest-first from API, reverse for chronological + lines.reverse() + + return textResult( + `${messages.length} chat message(s):\n\n${lines.join('\n')}` + ) + } + + case 'send_chat_message': { + const { content } = args + const result = await overleafRequest( + 'POST', + `/project/${projectId}/messages`, + cookie, + csrf, + { content } + ) + return textResult( + result.ok + ? 'Message sent.' + : `Failed to send: HTTP ${result.status}` + ) + } + + // ── Project ─────────────────────────────────── + + case 'list_project_files': { + const cwd = process.cwd() + const files = walkDir(cwd, cwd) + .filter(f => !f.path.startsWith('.')) + + if (files.length === 0) { + return textResult('No files found in project directory.') + } + + const lines = files.map(f => { + if (f.isDir) return `📁 ${f.path}` + const sizeKb = (f.size / 1024).toFixed(1) + return ` ${f.path} (${sizeKb} KB)` + }) + + return textResult( + `${files.filter(f => !f.isDir).length} files in project:\n\n${lines.join('\n')}` + ) + } + + case 'compile_latex': { + // Compilation happens via the LatteX app's local LaTeX installation + // We trigger it by writing a signal file that the app watches, + // or we can call the Overleaf compile endpoint + const mainFile = args?.main_file || null + + // Use Overleaf's server-side compilation + const body = { + check: 'silent', + draft: false, + incrementalCompilesEnabled: true, + rootDoc_id: null, + stopOnFirstError: false + } + + // If a specific main file is given, find its docId + if (mainFile && pathDocMap) { + const docId = pathDocMap[mainFile] + if (docId) body.rootDoc_id = docId + } + + const result = await overleafRequest( + 'POST', + `/project/${projectId}/compile`, + cookie, + csrf, + body + ) + + if (!result.ok) { + return errorResult(`Compilation request failed: HTTP ${result.status}`) + } + + const compileData = result.data + const status = compileData?.status || 'unknown' + + if (status === 'success') { + return textResult('Compilation successful.') + } else if (status === 'failure' || status === 'error') { + // Try to extract error info from output files + const outputFiles = compileData?.outputFiles || [] + const logFile = outputFiles.find(f => f.path === 'output.log') + if (logFile) { + // Fetch the log + const logUrl = `/project/${projectId}/output/${logFile.path}?build=${logFile.build}` + const logResult = await overleafRequest('GET', logUrl, cookie, csrf) + if (logResult.ok && typeof logResult.data === 'string') { + // Extract just the error lines + const logLines = logResult.data.split('\n') + const errorLines = logLines.filter(l => + l.startsWith('!') || l.includes('Error') || l.includes('error') + ).slice(0, 20) + + return textResult( + `Compilation failed.\n\nErrors:\n${errorLines.join('\n') || 'See full log for details.'}` + ) + } + } + return textResult(`Compilation failed with status: ${status}`) + } else { + return textResult(`Compilation status: ${status}`) + } + } + + default: + return errorResult(`Unknown tool: ${name}`) + } + } catch (e) { + return errorResult(`Error: ${e.message}`) + } +}) + +// ── Start ────────────────────────────────────────────────────── + +const transport = new StdioServerTransport() +await server.connect(transport) diff --git a/src/preload/index.ts b/src/preload/index.ts index 7b23d27..2be6e0b 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -43,10 +43,10 @@ const api = { ipcRenderer.invoke('overleaf:getThreads', projectId) as Promise<{ success: boolean; threads?: Record; message?: string }>, overleafReplyThread: (projectId: string, threadId: string, content: string) => ipcRenderer.invoke('overleaf:replyThread', projectId, threadId, content) as Promise<{ success: boolean }>, - overleafResolveThread: (projectId: string, threadId: string) => - ipcRenderer.invoke('overleaf:resolveThread', projectId, threadId) as Promise<{ success: boolean }>, - overleafReopenThread: (projectId: string, threadId: string) => - ipcRenderer.invoke('overleaf:reopenThread', projectId, threadId) as Promise<{ success: boolean }>, + overleafResolveThread: (projectId: string, threadId: string, docId?: string) => + ipcRenderer.invoke('overleaf:resolveThread', projectId, threadId, docId) as Promise<{ success: boolean }>, + overleafReopenThread: (projectId: string, threadId: string, docId?: string) => + ipcRenderer.invoke('overleaf:reopenThread', projectId, threadId, docId) as Promise<{ success: boolean }>, overleafDeleteMessage: (projectId: string, threadId: string, messageId: string) => ipcRenderer.invoke('overleaf:deleteMessage', projectId, threadId, messageId) as Promise<{ success: boolean }>, overleafEditMessage: (projectId: string, threadId: string, messageId: string, content: string) => @@ -182,6 +182,23 @@ const api = { return () => ipcRenderer.removeListener('chat:newMessage', handler) }, + // Comments real-time events + onCommentsEvent: (cb: (event: { type: string; args: unknown[] }) => void) => { + const handler = (_e: Electron.IpcRendererEvent, event: { type: string; args: unknown[] }) => cb(event) + ipcRenderer.on('comments:event', handler) + return () => ipcRenderer.removeListener('comments:event', handler) + }, + onCommentsInitThreads: (cb: (data: { threads: Record; resolvedIds: string[] }) => void) => { + const handler = (_e: Electron.IpcRendererEvent, data: { threads: Record; resolvedIds: string[] }) => cb(data) + ipcRenderer.on('comments:initThreads', handler) + return () => ipcRenderer.removeListener('comments:initThreads', handler) + }, + onCommentsInitContexts: (cb: (data: { contexts: Record }) => void) => { + const handler = (_e: Electron.IpcRendererEvent, data: { contexts: Record }) => cb(data) + ipcRenderer.on('comments:initContexts', handler) + return () => ipcRenderer.removeListener('comments:initContexts', handler) + }, + // Shell openExternal: (url: string) => ipcRenderer.invoke('shell:openExternal', url), showInFinder: (path: string) => ipcRenderer.invoke('shell:showInFinder', path) diff --git a/src/renderer/src/App.css b/src/renderer/src/App.css index aae0b4b..a6a4003 100644 --- a/src/renderer/src/App.css +++ b/src/renderer/src/App.css @@ -1465,10 +1465,14 @@ html, body, #root { min-width: 280px; height: 100%; border-left: 1px solid var(--border); + display: flex; + flex-direction: column; + overflow: hidden; } .review-panel { - height: 100%; + flex: 1; + min-height: 0; display: flex; flex-direction: column; background: var(--bg-primary); @@ -1812,17 +1816,6 @@ html, body, #root { gap: 4px; } -.terminal-toolbar .pdf-tab { - color: #A09880; -} -.terminal-toolbar .pdf-tab:hover { - color: #C8BFA0; -} -.terminal-toolbar .pdf-tab.active { - background: #3D3830; - color: #E8DFC0; -} - .terminal-content { flex: 1; padding: 4px; @@ -1850,6 +1843,68 @@ html, body, #root { color: #E8DFC0 !important; } +.terminal-tab-bar { + display: flex; + align-items: center; + height: 28px; + background: #1E1B15; + border-top: 1px solid #3D3830; + padding: 0 4px; + gap: 2px; + flex-shrink: 0; +} + +.terminal-tab { + display: flex; + align-items: center; + gap: 4px; + padding: 2px 10px; + font-size: 11px; + color: #8B7D5E; + cursor: pointer; + border-radius: 4px; + user-select: none; +} +.terminal-tab:hover { + color: #C8BFA0; + background: #2D2A24; +} +.terminal-tab.active { + color: #E8DFC0; + background: #3D3830; +} + +.terminal-tab-close { + font-size: 13px; + line-height: 1; + opacity: 0; + cursor: pointer; + padding: 0 2px; + border-radius: 2px; +} +.terminal-tab:hover .terminal-tab-close { + opacity: 0.6; +} +.terminal-tab-close:hover { + opacity: 1 !important; + background: #5C5040; +} + +.terminal-tab-add { + background: none; + border: none; + color: #6B5B3E; + font-size: 16px; + cursor: pointer; + padding: 0 6px; + line-height: 1; + border-radius: 4px; +} +.terminal-tab-add:hover { + color: #E8DFC0; + background: #2D2A24; +} + /* ── Status Bar ──────────────────────────────────────────────── */ .status-bar { diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index 82306c9..ca2fc1e 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -111,6 +111,15 @@ export default function App() { } }) + // Listen for initial comment data (threads + contexts) from background fetch on connect + const unsubInitThreads = window.api.onCommentsInitThreads?.((data) => { + const store = useAppStore.getState() + store.setResolvedThreadIds(new Set(data.resolvedIds)) + }) + const unsubInitContexts = window.api.onCommentsInitContexts?.((data) => { + useAppStore.getState().setCommentContexts(data.contexts) + }) + // Listen for remote cursor updates const unsubCursorUpdate = window.api.onCursorRemoteUpdate((raw) => { const data = raw as { @@ -168,6 +177,8 @@ export default function App() { unsubRejoined() unsubExternalEdit() unsubNewDoc() + unsubInitThreads?.() + unsubInitContexts?.() unsubCursorUpdate() unsubCursorDisconnected() remoteCursors.clear() diff --git a/src/renderer/src/components/Editor.tsx b/src/renderer/src/components/Editor.tsx index 75b3872..4252464 100644 --- a/src/renderer/src/components/Editor.tsx +++ b/src/renderer/src/components/Editor.tsx @@ -79,6 +79,7 @@ export default function Editor() { const pendingGoTo = useAppStore((s) => s.pendingGoTo) const commentContexts = useAppStore((s) => s.commentContexts) + const resolvedThreadIds = useAppStore((s) => s.resolvedThreadIds) const hoveredThreadId = useAppStore((s) => s.hoveredThreadId) const overleafProjectId = useAppStore((s) => s.overleafProjectId) const pathDocMap = useAppStore((s) => s.pathDocMap) @@ -118,10 +119,18 @@ export default function Editor() { ) setSubmittingComment(false) if (result.success) { + // Add context immediately so highlight + review panel update without re-fetch + if (result.threadId && activeTab) { + const store = useAppStore.getState() + store.setCommentContexts({ + ...store.commentContexts, + [result.threadId]: { file: activeTab, text: newComment.text, pos: newComment.from } + }) + } setNewComment(null) setCommentInput('') } - }, [newComment, commentInput, overleafProjectId, getDocIdForFile]) + }, [newComment, commentInput, overleafProjectId, activeTab, getDocIdForFile]) // Handle goTo when file is already open useEffect(() => { @@ -325,12 +334,12 @@ export default function Editor() { } }, [activeTab, pathDocMap]) - // Sync comment ranges to CodeMirror + // Sync comment ranges to CodeMirror (exclude resolved threads) useEffect(() => { if (!viewRef.current || !activeTab) return const ranges: CommentRange[] = [] for (const [threadId, ctx] of Object.entries(commentContexts)) { - if (ctx.file === activeTab && ctx.text) { + if (ctx.file === activeTab && ctx.text && !resolvedThreadIds.has(threadId)) { ranges.push({ threadId, from: ctx.pos, @@ -340,7 +349,7 @@ export default function Editor() { } } viewRef.current.dispatch({ effects: setCommentRangesEffect.of(ranges) }) - }, [commentContexts, activeTab]) + }, [commentContexts, activeTab, resolvedThreadIds]) // Sync hover state useEffect(() => { diff --git a/src/renderer/src/components/ReviewPanel.tsx b/src/renderer/src/components/ReviewPanel.tsx index 7edac50..7e6c9e5 100644 --- a/src/renderer/src/components/ReviewPanel.tsx +++ b/src/renderer/src/components/ReviewPanel.tsx @@ -45,24 +45,36 @@ export default function ReviewPanel() { const [editText, setEditText] = useState('') const threadRefs = useRef>({}) + // Initial fetch — threads from REST, contexts only if not cached const fetchThreads = useCallback(async () => { if (!overleafProjectId) return setLoading(true) setError('') - const [threadResult, ctxResult] = await Promise.all([ - window.api.overleafGetThreads(overleafProjectId), - window.api.otFetchAllCommentContexts() - ]) + const hasContexts = Object.keys(useAppStore.getState().commentContexts).length > 0 + const threadPromise = window.api.overleafGetThreads(overleafProjectId) + const ctxPromise = !hasContexts ? window.api.otFetchAllCommentContexts() : null + + const threadResult = await threadPromise setLoading(false) if (threadResult.success && threadResult.threads) { - setThreads(threadResult.threads as ThreadMap) + const tm = threadResult.threads as ThreadMap + setThreads(tm) + const resolved = new Set() + for (const [tid, t] of Object.entries(tm)) { + if (t.resolved) resolved.add(tid) + } + useAppStore.getState().setResolvedThreadIds(resolved) } else { setError(threadResult.message || 'Failed to fetch comments') } - if (ctxResult.success && ctxResult.contexts) { - useAppStore.getState().setCommentContexts(ctxResult.contexts) + + if (ctxPromise) { + const ctxResult = await ctxPromise + if (ctxResult.success && ctxResult.contexts) { + useAppStore.getState().setCommentContexts(ctxResult.contexts) + } } }, [overleafProjectId]) @@ -70,38 +82,188 @@ export default function ReviewPanel() { fetchThreads() }, [fetchThreads]) + // Handle real-time comment events from Overleaf socket — update state locally + useEffect(() => { + if (!window.api.onCommentsEvent) return + return window.api.onCommentsEvent((event) => { + const { type, args } = event + switch (type) { + case 'new-comment': { + const threadId = args[0] as string + const comment = args[1] as Message + setThreads(prev => { + if (prev[threadId]) { + // Reply to existing thread + return { + ...prev, + [threadId]: { + ...prev[threadId], + messages: [...prev[threadId].messages, comment] + } + } + } + // New thread — add it + return { ...prev, [threadId]: { messages: [comment] } } + }) + break + } + case 'resolve-thread': { + const threadId = args[0] as string + const user = args[1] as User | undefined + setThreads(prev => { + if (!prev[threadId]) return prev + return { + ...prev, + [threadId]: { + ...prev[threadId], + resolved: true, + resolved_by_user: user, + resolved_at: new Date().toISOString() + } + } + }) + const store = useAppStore.getState() + store.setResolvedThreadIds(new Set([...store.resolvedThreadIds, threadId])) + break + } + case 'reopen-thread': { + const threadId = args[0] as string + setThreads(prev => { + if (!prev[threadId]) return prev + const t = { ...prev[threadId] } + delete t.resolved + delete t.resolved_by_user + delete t.resolved_at + return { ...prev, [threadId]: t } + }) + const store = useAppStore.getState() + const ids = new Set(store.resolvedThreadIds) + ids.delete(threadId) + store.setResolvedThreadIds(ids) + break + } + case 'delete-thread': { + const threadId = args[0] as string + setThreads(prev => { + const next = { ...prev } + delete next[threadId] + return next + }) + // Remove context so highlight disappears + const store = useAppStore.getState() + const newCtx = { ...store.commentContexts } + delete newCtx[threadId] + store.setCommentContexts(newCtx) + const ids = new Set(store.resolvedThreadIds) + ids.delete(threadId) + store.setResolvedThreadIds(ids) + break + } + case 'edit-message': { + const threadId = args[0] as string + const messageId = args[1] as string + const content = args[2] as string + setThreads(prev => { + if (!prev[threadId]) return prev + return { + ...prev, + [threadId]: { + ...prev[threadId], + messages: prev[threadId].messages.map(m => + m.id === messageId ? { ...m, content } : m + ) + } + } + }) + break + } + case 'delete-message': { + const threadId = args[0] as string + const messageId = args[1] as string + setThreads(prev => { + if (!prev[threadId]) return prev + return { + ...prev, + [threadId]: { + ...prev[threadId], + messages: prev[threadId].messages.filter(m => m.id !== messageId) + } + } + }) + break + } + } + }) + }, []) + useEffect(() => { if (!focusedThreadId) return const el = threadRefs.current[focusedThreadId] if (el) el.scrollIntoView({ behavior: 'smooth', block: 'nearest' }) }, [focusedThreadId]) + // --- Local actions: optimistic updates, no REST re-fetch --- + const handleReply = async (threadId: string) => { if (!replyText.trim() || !overleafProjectId) return - const result = await window.api.overleafReplyThread(overleafProjectId, threadId, replyText.trim()) - if (result.success) { - setReplyText('') - setReplyingTo(null) - fetchThreads() - } + const content = replyText.trim() + setReplyText('') + setReplyingTo(null) + // Server will broadcast new-comment event which updates state + await window.api.overleafReplyThread(overleafProjectId, threadId, content) + } + + const getDocIdForThread = (threadId: string): string | undefined => { + const ctx = contexts[threadId] + if (!ctx) return undefined + const { pathDocMap } = useAppStore.getState() + return pathDocMap[ctx.file] } const handleResolve = async (threadId: string) => { if (!overleafProjectId) return - await window.api.overleafResolveThread(overleafProjectId, threadId) - fetchThreads() + // Optimistic: mark resolved immediately + setThreads(prev => { + if (!prev[threadId]) return prev + return { ...prev, [threadId]: { ...prev[threadId], resolved: true, resolved_at: new Date().toISOString() } } + }) + const store = useAppStore.getState() + store.setResolvedThreadIds(new Set([...store.resolvedThreadIds, threadId])) + await window.api.overleafResolveThread(overleafProjectId, threadId, getDocIdForThread(threadId)) } const handleReopen = async (threadId: string) => { if (!overleafProjectId) return - await window.api.overleafReopenThread(overleafProjectId, threadId) - fetchThreads() + // Optimistic: mark unresolved immediately + setThreads(prev => { + if (!prev[threadId]) return prev + const t = { ...prev[threadId] } + delete t.resolved + delete t.resolved_by_user + delete t.resolved_at + return { ...prev, [threadId]: t } + }) + const store = useAppStore.getState() + const ids = new Set(store.resolvedThreadIds) + ids.delete(threadId) + store.setResolvedThreadIds(ids) + await window.api.overleafReopenThread(overleafProjectId, threadId, getDocIdForThread(threadId)) } const handleDeleteMessage = async (threadId: string, messageId: string) => { if (!overleafProjectId) return + // Optimistic: remove message immediately + setThreads(prev => { + if (!prev[threadId]) return prev + return { + ...prev, + [threadId]: { + ...prev[threadId], + messages: prev[threadId].messages.filter(m => m.id !== messageId) + } + } + }) await window.api.overleafDeleteMessage(overleafProjectId, threadId, messageId) - fetchThreads() } const handleStartEdit = (threadId: string, msg: Message) => { @@ -111,25 +273,51 @@ export default function ReviewPanel() { const handleSaveEdit = async () => { if (!editingMsg || !editText.trim() || !overleafProjectId) return - await window.api.overleafEditMessage(overleafProjectId, editingMsg.threadId, editingMsg.messageId, editText.trim()) + const { threadId, messageId } = editingMsg + const content = editText.trim() + // Optimistic: update message immediately + setThreads(prev => { + if (!prev[threadId]) return prev + return { + ...prev, + [threadId]: { + ...prev[threadId], + messages: prev[threadId].messages.map(m => + m.id === messageId ? { ...m, content } : m + ) + } + } + }) setEditingMsg(null) setEditText('') - fetchThreads() + await window.api.overleafEditMessage(overleafProjectId, threadId, messageId, content) } const handleDeleteThread = async (threadId: string) => { if (!overleafProjectId) return const ctx = contexts[threadId] const store = useAppStore.getState() + + // Optimistic: remove thread, context, and highlight immediately + setThreads(prev => { + const next = { ...prev } + delete next[threadId] + return next + }) + const newCtx = { ...store.commentContexts } + delete newCtx[threadId] + store.setCommentContexts(newCtx) + const ids = new Set(store.resolvedThreadIds) + ids.delete(threadId) + store.setResolvedThreadIds(ids) + if (ctx) { const docId = store.pathDocMap[ctx.file] if (docId) { await window.api.overleafDeleteThread(overleafProjectId, docId, threadId) - fetchThreads() return } } - fetchThreads() } const getUserName = (msg: Message) => { @@ -137,7 +325,7 @@ export default function ReviewPanel() { return msg.user.last_name ? `${msg.user.first_name} ${msg.user.last_name}` : msg.user.first_name } if (msg.user?.email) return msg.user.email.split('@')[0] - return msg.user_id.slice(-6) + return msg.user_id?.slice(-6) || '?' } const formatTime = (ts: number) => { @@ -154,12 +342,10 @@ export default function ReviewPanel() { return d.toLocaleDateString() } - // Navigate to comment position — always works for current file since it's already open const handleClickContext = (threadId: string) => { const ctx = contexts[threadId] if (!ctx) return const store = useAppStore.getState() - // File should already be open since we only show current file's comments store.setPendingGoTo({ file: ctx.file, pos: ctx.pos, highlight: ctx.text }) } @@ -172,7 +358,6 @@ export default function ReviewPanel() { ) } - // Filter threads to only show ones belonging to the current file const threadEntries = Object.entries(threads) const fileThreads = activeTab ? threadEntries.filter(([threadId]) => { diff --git a/src/renderer/src/components/Terminal.tsx b/src/renderer/src/components/Terminal.tsx index bc29633..ea54343 100644 --- a/src/renderer/src/components/Terminal.tsx +++ b/src/renderer/src/components/Terminal.tsx @@ -124,39 +124,78 @@ function TerminalInstance({ id, cwd, cmd, args, visible }: { ) } +interface TabInfo { + id: string + name: string +} + +let nextTabId = 0 + export default function Terminal() { - const [mode, setMode] = useState<'terminal' | 'claude'>('terminal') - const [claudeSpawned, setClaudeSpawned] = useState(false) + const [tabs, setTabs] = useState(() => [ + { id: `term-${++nextTabId}`, name: 'Terminal' } + ]) + const [activeTabId, setActiveTabId] = useState(() => `term-${nextTabId}`) const syncDir = useAppStore((s) => s.syncDir) || '/tmp' - const launchClaude = useCallback(() => { - setClaudeSpawned(true) - setMode('claude') + const addTab = useCallback(() => { + const id = `term-${++nextTabId}` + setTabs((prev) => { + const name = `Terminal ${prev.length + 1}` + return [...prev, { id, name }] + }) + setActiveTabId(id) }, []) + const closeTab = useCallback((tabId: string) => { + setTabs((prev) => { + if (prev.length <= 1) return prev + const idx = prev.findIndex((t) => t.id === tabId) + const next = prev.filter((t) => t.id !== tabId) + // If closing the active tab, switch to adjacent + if (tabId === activeTabId) { + const newIdx = Math.min(idx, next.length - 1) + setActiveTabId(next[newIdx].id) + } + return next + }) + }, [activeTabId]) + return (
- - -
- +
- - {claudeSpawned && ( - - )} + {tabs.map((tab) => ( + + ))} + +
+ {tabs.map((tab) => ( +
setActiveTabId(tab.id)} + > + {tab.name} + {tabs.length > 1 && ( + { e.stopPropagation(); closeTab(tab.id) }} + > + × + + )} +
+ ))} + +
) } diff --git a/src/renderer/src/stores/appStore.ts b/src/renderer/src/stores/appStore.ts index e9c47ed..ff56c28 100644 --- a/src/renderer/src/stores/appStore.ts +++ b/src/renderer/src/stores/appStore.ts @@ -109,6 +109,8 @@ interface AppState { // Comment data commentContexts: Record setCommentContexts: (c: Record) => void + resolvedThreadIds: Set + setResolvedThreadIds: (ids: Set) => void overleafDocs: Record setOverleafDocs: (d: Record) => void hoveredThreadId: string | null @@ -219,6 +221,8 @@ export const useAppStore = create((set) => ({ commentContexts: {}, setCommentContexts: (c) => set({ commentContexts: c }), + resolvedThreadIds: new Set(), + setResolvedThreadIds: (ids) => set({ resolvedThreadIds: ids }), overleafDocs: {}, setOverleafDocs: (d) => set({ overleafDocs: d }), hoveredThreadId: null, @@ -251,6 +255,7 @@ export const useAppStore = create((set) => ({ rootFolderId: '', syncDir: '', commentContexts: {}, + resolvedThreadIds: new Set(), overleafDocs: {}, hoveredThreadId: null, focusedThreadId: null, -- cgit v1.2.3