diff --git a/README.md b/README.md index b5889998..033ee5da 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ Mobile-first web interface for OpenCode AI agents. Manage, control, and code wit - **File Operations** - Create files/folders, rename, delete - **Drag-and-Drop Upload** - Upload files by dragging into the browser - **Large File Support** - Virtualization for large files +- **ZIP Download** - Download repos as ZIP excluding gitignored files ### Chat & Session Features - **Slash Commands** - Built-in commands (`/help`, `/new`, `/models`, `/export`, `/compact`, etc.) @@ -54,6 +55,8 @@ Mobile-first web interface for OpenCode AI agents. Manage, control, and code wit - **Mobile-First Design** - Responsive UI optimized for mobile use - **PWA Support** - Installable as Progressive Web App - **iOS Keyboard Support** - Proper keyboard handling on iOS +- **Enter Key Send** - Press Enter to automatically close keyboard and send messages +- **Swipe-to-Navigate** - Swipe right from left edge to navigate back ### Text-to-Speech (TTS) - **AI Message Playback** - Listen to assistant responses with TTS diff --git a/backend/package.json b/backend/package.json index 7931806d..dcef1c60 100644 --- a/backend/package.json +++ b/backend/package.json @@ -15,12 +15,14 @@ "dependencies": { "@hono/node-server": "^1.19.5", "@opencode-manager/shared": "workspace:*", + "archiver": "^7.0.1", "dotenv": "^17.2.3", "hono": "^4.10.1", "strip-json-comments": "^3.1.1", "zod": "^4.1.12" }, "devDependencies": { + "@types/archiver": "^7.0.0", "@types/better-sqlite3": "^7.6.13", "@types/bun": "latest", "@vitest/ui": "^3.2.4", diff --git a/backend/src/routes/repos.ts b/backend/src/routes/repos.ts index 585fc2d3..01461811 100644 --- a/backend/src/routes/repos.ts +++ b/backend/src/routes/repos.ts @@ -3,11 +3,11 @@ import type { Database } from 'bun:sqlite' import * as db from '../db/queries' import * as repoService from '../services/repo' import * as gitOperations from '../services/git-operations' +import * as archiveService from '../services/archive' import { SettingsService } from '../services/settings' import { writeFileContent } from '../services/file-operations' import { opencodeServerManager } from '../services/opencode-single-server' import { logger } from '../utils/logger' -import { withTransactionAsync } from '../db/transactions' import { getOpenCodeConfigFilePath, getReposPath } from '@opencode-manager/shared' import path from 'path' @@ -256,6 +256,44 @@ export function createRepoRoutes(database: Database) { return c.json({ error: error.message }, 500) } }) + + app.get('/:id/download', async (c) => { + try { + const id = parseInt(c.req.param('id')) + const repo = db.getRepoById(database, id) + + if (!repo) { + return c.json({ error: 'Repo not found' }, 404) + } + + const repoPath = path.resolve(getReposPath(), repo.localPath) + const repoName = path.basename(repo.localPath) + + logger.info(`Starting archive creation for repo ${id}: ${repoPath}`) + const archivePath = await archiveService.createRepoArchive(repoPath) + const archiveSize = await archiveService.getArchiveSize(archivePath) + const archiveStream = archiveService.getArchiveStream(archivePath) + + archiveStream.on('end', () => { + archiveService.deleteArchive(archivePath) + }) + + archiveStream.on('error', () => { + archiveService.deleteArchive(archivePath) + }) + + return new Response(archiveStream as unknown as ReadableStream, { + headers: { + 'Content-Type': 'application/zip', + 'Content-Disposition': `attachment; filename="${repoName}.zip"`, + 'Content-Length': archiveSize.toString(), + } + }) + } catch (error: any) { + logger.error('Failed to create repo archive:', error) + return c.json({ error: error.message }, 500) + } + }) return app } diff --git a/backend/src/services/archive.ts b/backend/src/services/archive.ts new file mode 100644 index 00000000..16e6e28a --- /dev/null +++ b/backend/src/services/archive.ts @@ -0,0 +1,172 @@ +import archiver from 'archiver' +import { createWriteStream, createReadStream } from 'fs' +import { readdir, stat, unlink } from 'fs/promises' +import path from 'path' +import os from 'os' +import { logger } from '../utils/logger' + +async function getIgnoredPaths(repoPath: string, paths: string[]): Promise> { + if (paths.length === 0) return new Set() + + try { + const { spawn } = await import('child_process') + + return new Promise((resolve) => { + const ignored = new Set() + const proc = spawn('git', ['check-ignore', '--stdin'], { + cwd: repoPath, + shell: false + }) + + let stdout = '' + + proc.stdout?.on('data', (data: Buffer) => { + stdout += data.toString() + }) + + proc.stdin?.write(paths.join('\n')) + proc.stdin?.end() + + proc.on('close', () => { + const ignoredPaths = stdout.split('\n').filter(p => p.trim()) + for (const p of ignoredPaths) { + ignored.add(p) + } + resolve(ignored) + }) + + proc.on('error', () => { + resolve(new Set()) + }) + }) + } catch { + return new Set() + } +} + +async function collectFiles( + repoPath: string, + relativePath: string = '' +): Promise { + const fullPath = path.join(repoPath, relativePath) + const entries = await readdir(fullPath, { withFileTypes: true }) + const files: string[] = [] + + for (const entry of entries) { + const entryRelPath = relativePath ? path.join(relativePath, entry.name) : entry.name + + if (entry.name === '.git') continue + + if (entry.isDirectory()) { + files.push(entryRelPath + '/') + const subFiles = await collectFiles(repoPath, entryRelPath) + files.push(...subFiles) + } else { + files.push(entryRelPath) + } + } + + return files +} + +async function filterIgnoredPaths(repoPath: string, allPaths: string[]): Promise { + const batchSize = 1000 + const ignoredSet = new Set() + + for (let i = 0; i < allPaths.length; i += batchSize) { + const batch = allPaths.slice(i, i + batchSize) + const ignored = await getIgnoredPaths(repoPath, batch) + for (const p of ignored) { + ignoredSet.add(p) + if (p.endsWith('/')) { + ignoredSet.add(p.slice(0, -1)) + } else { + ignoredSet.add(p + '/') + } + } + } + + const filteredPaths: string[] = [] + const ignoredDirs = new Set() + + for (const p of allPaths) { + const isDir = p.endsWith('/') + const cleanPath = isDir ? p.slice(0, -1) : p + + let isUnderIgnoredDir = false + for (const ignoredDir of ignoredDirs) { + if (cleanPath.startsWith(ignoredDir + '/')) { + isUnderIgnoredDir = true + break + } + } + + if (isUnderIgnoredDir) continue + + if (ignoredSet.has(p) || ignoredSet.has(cleanPath)) { + if (isDir) { + ignoredDirs.add(cleanPath) + } + continue + } + + filteredPaths.push(p) + } + + return filteredPaths +} + +export async function createRepoArchive(repoPath: string): Promise { + const repoName = path.basename(repoPath) + const tempFile = path.join(os.tmpdir(), `${repoName}-${Date.now()}.zip`) + + logger.info(`Creating archive for ${repoPath} at ${tempFile}`) + + const allPaths = await collectFiles(repoPath) + const filteredPaths = await filterIgnoredPaths(repoPath, allPaths) + + const output = createWriteStream(tempFile) + const archive = archiver('zip', { zlib: { level: 5 } }) + + return new Promise((resolve, reject) => { + output.on('close', () => { + logger.info(`Archive created: ${tempFile} (${archive.pointer()} bytes)`) + resolve(tempFile) + }) + + archive.on('error', (err) => { + logger.error('Archive error:', err) + reject(err) + }) + + archive.pipe(output) + + for (const relativePath of filteredPaths) { + if (relativePath.endsWith('/')) continue + + const fullPath = path.join(repoPath, relativePath) + const archivePath = path.join(repoName, relativePath) + archive.file(fullPath, { name: archivePath }) + } + + archive.finalize() + }) +} + +export async function deleteArchive(filePath: string): Promise { + try { + await unlink(filePath) + logger.info(`Deleted temp archive: ${filePath}`) + } catch (error) { + logger.warn(`Failed to delete temp archive: ${filePath}`, error) + } +} + +export function getArchiveStream(filePath: string) { + return createReadStream(filePath) +} + +export async function getArchiveSize(filePath: string): Promise { + const stats = await stat(filePath) + return stats.size +} diff --git a/frontend/src/api/repos.ts b/frontend/src/api/repos.ts index b3d4ecbf..0bde92a6 100644 --- a/frontend/src/api/repos.ts +++ b/frontend/src/api/repos.ts @@ -139,3 +139,22 @@ export async function listBranches(id: number): Promise<{ local: string[], remot return response.json() } + +export async function downloadRepo(id: number, repoName: string): Promise { + const response = await fetch(`${API_BASE_URL}/api/repos/${id}/download`) + + if (!response.ok) { + const error = await response.json() + throw new Error(error.error || 'Failed to download repo') + } + + const blob = await response.blob() + const url = window.URL.createObjectURL(blob) + const a = document.createElement('a') + a.href = url + a.download = `${repoName}.zip` + document.body.appendChild(a) + a.click() + document.body.removeChild(a) + window.URL.revokeObjectURL(url) +} diff --git a/frontend/src/components/repo/RepoCard.tsx b/frontend/src/components/repo/RepoCard.tsx index 54ea186a..8b293021 100644 --- a/frontend/src/components/repo/RepoCard.tsx +++ b/frontend/src/components/repo/RepoCard.tsx @@ -1,8 +1,11 @@ +import { useState } from "react"; import { Button } from "@/components/ui/button"; import { Badge } from "@/components/ui/badge"; import { Checkbox } from "@/components/ui/checkbox"; -import { Loader2, Trash2, ExternalLink } from "lucide-react"; +import { Loader2, Trash2, ExternalLink, Download } from "lucide-react"; import { useNavigate } from "react-router-dom"; +import { downloadRepo } from "@/api/repos"; +import { showToast } from "@/lib/toast"; import { BranchSwitcher } from "./BranchSwitcher"; @@ -31,6 +34,7 @@ export function RepoCard({ onSelect, }: RepoCardProps) { const navigate = useNavigate(); + const [isDownloading, setIsDownloading] = useState(false); const repoName = repo.repoUrl ? repo.repoUrl.split("/").slice(-1)[0].replace(".git", "") @@ -127,6 +131,32 @@ export function RepoCard({ /> )} + +