diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 58568cd..e7327b1 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,8 +1,9 @@ name: Release -# Publishing a GitHub release builds the Apple Silicon app and attaches it, plus -# the signed update bundle and `latest.json` the in-app updater reads, to that -# same release. The app version comes from the tag, so there is nothing to bump. +# Publishing a GitHub release builds the Apple Silicon app and the Windows x64 +# app, and attaches both, plus the signed update bundles and the `latest.json` +# the in-app updater reads, to that same release. The app version comes from the +# tag, so there is nothing to bump. on: release: @@ -81,3 +82,67 @@ jobs: dmg="$(ls apps/desktop/src-tauri/target/aarch64-apple-darwin/release/bundle/dmg/*.dmg | head -1)" cp "$dmg" Sheet-macos-arm64.dmg gh release upload "$TAG" Sheet-macos-arm64.dmg --clobber --repo "${{ github.repository }}" + + # Serialized after macOS so both tauri-action runs merge their platform entry + # into the same `latest.json` instead of each writing a file with one platform. + build-windows: + name: Windows x64 + needs: build-macos + runs-on: windows-latest + timeout-minutes: 60 + steps: + - uses: actions/checkout@v4 + + - name: Resolve version from tag + id: version + shell: bash + env: + TAG: ${{ github.event.release.tag_name || inputs.tag }} + run: | + if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + echo "::error::Tag must use the vX.Y.Z format, got $TAG" + exit 1 + fi + echo "tag=$TAG" >> "$GITHUB_OUTPUT" + echo "version=${TAG#v}" >> "$GITHUB_OUTPUT" + + - uses: oven-sh/setup-bun@v2 + + - uses: dtolnay/rust-toolchain@stable + with: + targets: x86_64-pc-windows-msvc + + - uses: swatinem/rust-cache@v2 + with: + workspaces: apps/desktop/src-tauri + + - run: bun install --frozen-lockfile + + # NSIS only: the updater reads the NSIS entry from `latest.json`, and a + # single installer keeps the fixed-name download unambiguous. Updates use + # the same minisign key as macOS. + - name: Build and attach to the release + uses: tauri-apps/tauri-action@v0 + env: + GITHUB_TOKEN: ${{ github.token }} + TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} + TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }} + with: + projectPath: apps/desktop + tauriScript: bunx tauri + tagName: ${{ steps.version.outputs.tag }} + releaseDraft: false + uploadUpdaterJson: true + updaterJsonPreferNsis: true + args: --target x86_64-pc-windows-msvc --bundles nsis --config '{"version":"${{ steps.version.outputs.version }}"}' + + # The installer is named after its version; the website links to a fixed name. + - name: Add the fixed-name download + shell: bash + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ steps.version.outputs.tag }} + run: | + installer="$(ls apps/desktop/src-tauri/target/x86_64-pc-windows-msvc/release/bundle/nsis/*.exe | head -1)" + cp "$installer" Sheet-windows-x64.exe + gh release upload "$TAG" Sheet-windows-x64.exe --clobber --repo "${{ github.repository }}" diff --git a/README.md b/README.md index 15b82c0..6f45ff2 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,8 @@ the app shows ready-made snippets. `bun run build:desktop` produces the packaged app with the server compiled in. +Windows users: see [windows/README.md](./windows/README.md) for quick setup, PowerShell scripts (`setup.ps1`, `run.ps1`, `build.ps1`), and development workflows. + ## Design guide skill Teaches an agent to use the canvas tools well. Add `-g` to install globally. diff --git a/apps/desktop/package.json b/apps/desktop/package.json index cf14f71..ff62f20 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -7,8 +7,9 @@ }, "scripts": { "dev": "tauri dev --config src-tauri/tauri.dev.conf.json", + "dev:web": "vite dev --mode web --strictPort --host 127.0.0.1", "build:app": "vite build", - "build:server": "bun run --cwd ../../packages/db embed && mkdir -p src-tauri/binaries && bun build --compile ../mcp/src/local.ts --outfile src-tauri/binaries/sheet-server", + "build:server": "bun run ../../scripts/build-server.ts", "build": "tauri build", "check": "tsc --noEmit && cargo check --manifest-path src-tauri/Cargo.toml", "generate-routes": "tsr generate" diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index f71b3f8..d7ad3b9 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -33,7 +33,7 @@ }, "bundle": { "active": true, - "targets": ["app", "dmg"], + "targets": "all", "createUpdaterArtifacts": true, "macOS": { "signingIdentity": "-", diff --git a/apps/desktop/vite.config.ts b/apps/desktop/vite.config.ts index e1cde94..c3a52e0 100644 --- a/apps/desktop/vite.config.ts +++ b/apps/desktop/vite.config.ts @@ -1,15 +1,11 @@ import { defineConfig, type Plugin } from 'vite' -import { readFile } from 'node:fs/promises' -import { cp } from 'node:fs/promises' +import { cp, readFile } from 'node:fs/promises' +import { isAbsolute, relative, resolve, sep } from 'node:path' import { fileURLToPath } from 'node:url' import viteReact from '@vitejs/plugin-react' import tailwindcss from '@tailwindcss/vite' import { tanstackRouter } from '@tanstack/router-plugin/vite' -const hostPort = process.env.SHEET_DESKTOP_PORT ?? '4300' -const appPort = process.env.SHEET_DESKTOP_APP_PORT ?? '1421' -const host = `http://127.0.0.1:${hostPort}` - /** Self-hosted vendor files live with the desktop app; served + bundled. */ const fontsDirectory = fileURLToPath(new URL('./public/vendor/', import.meta.url)) @@ -20,13 +16,16 @@ function vendorFonts(): Plugin { server.middlewares.use(async (request, response, next) => { const path = request.url?.split('?')[0] if (!path?.startsWith('/vendor/')) return next() + const file = resolve(fontsDirectory, path.slice('/vendor/'.length)) + const inside = relative(fontsDirectory, file) + if (inside === '..' || inside.startsWith(`..${sep}`) || isAbsolute(inside)) return next() try { - const file = await readFile(fontsDirectory + path.slice('/vendor/'.length)) + const bytes = await readFile(file) response.setHeader( 'content-type', path.endsWith('.css') ? 'text/css; charset=utf-8' : 'font/woff2', ) - response.end(file) + response.end(bytes) } catch { next() } @@ -40,53 +39,61 @@ function vendorFonts(): Plugin { } } -export default defineConfig({ - clearScreen: false, - resolve: { tsconfigPaths: true }, - plugins: [ - vendorFonts(), - tailwindcss(), - tanstackRouter({ target: 'react', quoteStyle: 'single', autoCodeSplitting: true }), - viteReact(), - ], - build: { - outDir: 'dist/app', - emptyOutDir: true, - // The window loads from a loopback server, never from a CDN, so a source - // map costs nothing to ship and makes a stack trace readable. - sourcemap: true, - }, - server: { - host: '127.0.0.1', - port: Number(appPort), - strictPort: true, - // `tauri dev` spends seconds compiling the Rust host before the window - // exists. Warming the entry, every route and the stylesheet here moves - // that work into that gap, so the first paint finds a transformed module - // graph instead of compiling 240 modules while the window sits on the - // boot splash. Warmup runs in the background and does not delay `ready`. - warmup: { - clientFiles: [ - './src/main.tsx', - './src/styles.css', - './src/routes/**/*.tsx', - ], +export default defineConfig(({ mode }) => { + // `bun run dev:web` proxies straight to the local server; the Tauri window goes + // through the Rust host on :4300 instead. + const hostPort = process.env.SHEET_DESKTOP_PORT ?? (mode === 'web' ? '4100' : '4300') + const appPort = process.env.SHEET_DESKTOP_APP_PORT ?? '1421' + const host = `http://127.0.0.1:${hostPort}` + + return { + clearScreen: false, + resolve: { tsconfigPaths: true }, + plugins: [ + vendorFonts(), + tailwindcss(), + tanstackRouter({ target: 'react', quoteStyle: 'single', autoCodeSplitting: true }), + viteReact(), + ], + build: { + outDir: 'dist/app', + emptyOutDir: true, + // The window loads from a loopback server, never from a CDN, so a source + // map costs nothing to ship and makes a stack trace readable. + sourcemap: true, }, - watch: { ignored: ['**/src-tauri/**'] }, - // The Tauri window stays on the Rust host (:4300) and reverse-proxies this - // server. HMR still talks to Vite directly so the host does not have to - // bridge websockets. - hmr: { - protocol: 'ws', + server: { host: '127.0.0.1', port: Number(appPort), + strictPort: true, + // `tauri dev` spends seconds compiling the Rust host before the window + // exists. Warming the entry, every route and the stylesheet here moves + // that work into that gap, so the first paint finds a transformed module + // graph instead of compiling 240 modules while the window sits on the + // boot splash. Warmup runs in the background and does not delay `ready`. + warmup: { + clientFiles: [ + './src/main.tsx', + './src/styles.css', + './src/routes/**/*.tsx', + ], + }, + watch: { ignored: ['**/src-tauri/**'] }, + // The Tauri window stays on the Rust host (:4300) and reverse-proxies this + // server. HMR still talks to Vite directly so the host does not have to + // bridge websockets. + hmr: { + protocol: 'ws', + host: '127.0.0.1', + port: Number(appPort), + }, + // Kept for opening the interface in a regular browser during development. + proxy: { + '/api': { target: host, changeOrigin: false }, + '/desktop': { target: host, changeOrigin: false }, + '/callback': { target: host, changeOrigin: false }, + '/realtime': { target: host, ws: true, changeOrigin: false }, + }, }, - // Kept for opening the interface in a regular browser during development. - proxy: { - '/api': { target: host, changeOrigin: false }, - '/desktop': { target: host, changeOrigin: false }, - '/callback': { target: host, changeOrigin: false }, - '/realtime': { target: host, ws: true, changeOrigin: false }, - }, - }, + } }) diff --git a/apps/mcp/src/agent-install.test.ts b/apps/mcp/src/agent-install.test.ts new file mode 100644 index 0000000..ab0a788 --- /dev/null +++ b/apps/mcp/src/agent-install.test.ts @@ -0,0 +1,59 @@ +import { mkdtemp, readFile, readdir, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { writeAtomic } from './agent-install' + +/** Windows locks the target briefly while an indexer or antivirus reads it. */ +const lock = vi.hoisted(() => ({ failures: 0, code: 'EPERM' })) + +vi.mock('node:fs/promises', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + rename: async (from: string, to: string) => { + if (lock.failures > 0) { + lock.failures -= 1 + throw Object.assign(new Error(`locked: ${to}`), { code: lock.code }) + } + return actual.rename(from, to) + }, + } +}) + +let dir = '' + +beforeEach(async () => { + dir = await mkdtemp(join(tmpdir(), 'sheet-write-atomic-')) + lock.failures = 0 + lock.code = 'EPERM' +}) + +afterEach(async () => { + await rm(dir, { recursive: true, force: true }) +}) + +describe('writeAtomic', () => { + it('replaces a locked file once the lock clears, and leaves no temporary file', async () => { + const path = join(dir, 'config.json') + await writeAtomic(path, '{"version":1}') + + lock.failures = 2 + await writeAtomic(path, '{"version":2}') + + expect(await readFile(path, 'utf8')).toBe('{"version":2}') + expect(await readdir(dir)).toEqual(['config.json']) + expect(lock.failures).toBe(0) + }) + + it('keeps the existing file when the lock never clears', async () => { + const path = join(dir, 'config.json') + await writeAtomic(path, '{"version":1}') + + lock.failures = 50 + await expect(writeAtomic(path, '{"version":2}')).rejects.toThrow('locked') + + expect(await readFile(path, 'utf8')).toBe('{"version":1}') + expect(await readdir(dir)).toEqual(['config.json']) + }) +}) diff --git a/apps/mcp/src/agent-install.ts b/apps/mcp/src/agent-install.ts index 4841c42..3ae321e 100644 --- a/apps/mcp/src/agent-install.ts +++ b/apps/mcp/src/agent-install.ts @@ -1,4 +1,5 @@ -import { mkdir, readFile, rename, writeFile } from 'node:fs/promises' +import { randomUUID } from 'node:crypto' +import { mkdir, open, readFile, rename, rm } from 'node:fs/promises' import { homedir, platform } from 'node:os' import { dirname, join } from 'node:path' @@ -76,12 +77,55 @@ async function readText(path: string) { } } -/** Write beside the target, then rename, so a crash never leaves half a config. */ +/** Windows returns these while an indexer or an antivirus scan holds the file. */ +const LOCK_CODES = new Set(['EBUSY', 'EACCES', 'EPERM']) +const REPLACE_ATTEMPTS = 5 + +function isLockError(error: unknown) { + return ( + error instanceof Error && + 'code' in error && + typeof error.code === 'string' && + LOCK_CODES.has(error.code) + ) +} + +/** + * Renames over the target, retrying while Windows holds a transient lock on it. + * The target is never removed first: a failed replacement has to leave the + * previous configuration exactly where it was. + */ +async function replaceFile(temp: string, path: string) { + for (let attempt = 0; ; attempt += 1) { + try { + await rename(temp, path) + return + } catch (error) { + if (!isLockError(error) || attempt + 1 >= REPLACE_ATTEMPTS) throw error + await new Promise((resolve) => setTimeout(resolve, 25 * 2 ** attempt)) + } + } +} + +/** + * Write beside the target, then rename, so a crash never leaves half a config. + * Each call writes its own exclusively created temporary file, so concurrent + * installs cannot publish each other's content. + */ export async function writeAtomic(path: string, text: string) { await mkdir(dirname(path), { recursive: true }) - const temp = `${path}.sheet-${process.pid}.tmp` - await writeFile(temp, text, 'utf8') - await rename(temp, path) + const temp = `${path}.sheet-${process.pid}-${randomUUID()}.tmp` + const handle = await open(temp, 'wx') + try { + try { + await handle.writeFile(text, 'utf8') + } finally { + await handle.close() + } + await replaceFile(temp, path) + } finally { + await rm(temp, { force: true }).catch(() => {}) + } } async function installJson(target: JsonTarget): Promise { diff --git a/apps/mcp/src/local.ts b/apps/mcp/src/local.ts index 2ce608e..2dda01d 100644 --- a/apps/mcp/src/local.ts +++ b/apps/mcp/src/local.ts @@ -1,5 +1,6 @@ import { RPCHandler } from '@orpc/server/fetch' import { and, eq } from 'drizzle-orm' +import { extname, isAbsolute, join, relative, resolve, sep } from 'node:path' import { LOCAL_USER_ID, db, ensureLocalUser } from '@sheet/db' import { asset } from '@sheet/db/schema' import { appRouter } from '@sheet/rpc' @@ -26,11 +27,67 @@ import { createAppState, handleRequest } from './handler' * - `/api/canvas-events` — live canvas/branch/agent events over SSE, * backed by the in-process bus (no socket service, no Redis) * + * With `SHEET_APP_DIR` set (the portable Windows bundle, or any build of the + * interface) it also serves the built interface from disk, so a browser can + * open the canvas without the Tauri host. + * * The Tauri host spawns this on startup; `bun run dev:mcp` runs it directly. */ const LOCAL_SESSION_ID = 'local' +/** The built interface, when this process is also the web server. */ +const appDirEnv = process.env.SHEET_APP_DIR?.trim() +const appDir = appDirEnv ? resolve(appDirEnv) : null + +const APP_CONTENT_TYPES: Record = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.mjs': 'text/javascript; charset=utf-8', + '.css': 'text/css; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.map': 'application/json; charset=utf-8', + '.svg': 'image/svg+xml', + '.png': 'image/png', + '.jpg': 'image/jpeg', + '.jpeg': 'image/jpeg', + '.webp': 'image/webp', + '.ico': 'image/x-icon', + '.woff': 'font/woff', + '.woff2': 'font/woff2', + '.wasm': 'application/wasm', + '.txt': 'text/plain; charset=utf-8', +} + +/** + * Serves one file from the built interface. Routes without an extension fall + * back to `index.html` so client-side navigation keeps working on refresh. + */ +async function serveAppFile(pathname: string) { + if (!appDir) return null + let decoded: string + try { + decoded = decodeURIComponent(pathname) + } catch { + return new Response('Bad path', { status: 400 }) + } + if (decoded.includes('\0')) return new Response('Bad path', { status: 400 }) + const file = resolve(appDir, `.${decoded}`) + const inside = relative(appDir, file) + if (inside === '..' || inside.startsWith(`..${sep}`) || isAbsolute(inside)) { + return new Response('Not found', { status: 404 }) + } + const target = extname(file) ? file : join(appDir, 'index.html') + const body = Bun.file(target) + if (!(await body.exists())) return null + return new Response(body, { + headers: { + 'content-type': APP_CONTENT_TYPES[extname(target).toLowerCase()] ?? 'application/octet-stream', + 'cache-control': extname(file) ? 'no-cache' : 'no-store', + }, + }) +} + const rpc = new RPCHandler(appRouter) function sseEvent(event: string, data: unknown) { @@ -264,7 +321,7 @@ async function route(request: Request, state: ReturnType) const url = new URL(request.url) const path = url.pathname.replace(/\/+$/, '') || '/' - if (path === '/mcp' || path === '/ready' || path === '/health' || path === '/') { + if (path === '/mcp' || path === '/ready' || path === '/health' || (path === '/' && !appDir)) { return handleRequest(request, state) } if (path.startsWith('/api/rpc')) { @@ -328,6 +385,11 @@ async function route(request: Request, state: ReturnType) { headers: { 'cache-control': 'no-store' } }, ) } + if (path.startsWith('/api/')) return new Response('Not found', { status: 404 }) + if (request.method === 'GET' || request.method === 'HEAD') { + const asset = await serveAppFile(path) + if (asset) return asset + } return new Response('Not found', { status: 404 }) } diff --git a/apps/mcp/src/tools.test.ts b/apps/mcp/src/tools.test.ts index 6125d40..5528cf3 100644 --- a/apps/mcp/src/tools.test.ts +++ b/apps/mcp/src/tools.test.ts @@ -15,7 +15,7 @@ describe('MCP tool manifest', () => { expect(names).toHaveLength(32) expect(names[0]).toBe('getUsage') expect(names).not.toContain('getScreenshot') - expect(names).not.toContain('createPage') + expect(names).not.toContain('patchNodes') expect(names).not.toContain('insertNodes') expect(names).toContain('getWebDocument') expect(names).toContain('getWebHTML') diff --git a/apps/site/src/app.tsx b/apps/site/src/app.tsx index 98313bc..1363898 100644 --- a/apps/site/src/app.tsx +++ b/apps/site/src/app.tsx @@ -10,12 +10,10 @@ import { } from './diagrams' import { prefersReducedMotion, trackPointer, useInView } from './hooks' import { DownloadDialog } from './download-dialog' +import { downloadLabel, downloadTarget, downloadUrl, REPO, type DownloadTarget } from './download' +import { PlatformMark } from './marks' import { chooseTheme, currentTheme, followSystem } from './theme' -const REPO = 'https://github.com/DeepanshuMishraa/sheet' -/** A fixed name, so the link keeps working across versions: the release workflow uploads the DMG under it. */ -const DOWNLOAD = `${REPO}/releases/latest/download/Sheet-macos-arm64.dmg` - /** One agent step: when it fires, what the log says. */ const script = [ { at: 700, tool: 'createFrame', detail: 'Pricing · 1280 × 800' }, @@ -280,13 +278,17 @@ function Card({ className, children }: { className?: string; children: ReactNode export function App() { const detected = useMemo(detectPlatform, []) const [platform, setPlatform] = useState(detected) - const [downloadOpen, setDownloadOpen] = useState(false) + /** The build being downloaded; null while the dialog is closed. */ + const [download, setDownload] = useState(null) + const target = downloadTarget(detected) + /** The platforms section offers whichever tab is open, so the two agree. */ + const shownTarget = downloadTarget(platform) /** Plain clicks open the dialog; a modified click (new tab, save link) keeps the real link. */ - const openDownload = (event: MouseEvent) => { + const openDownload = (next: DownloadTarget) => (event: MouseEvent) => { if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return event.preventDefault() - setDownloadOpen(true) + setDownload(next) } return ( @@ -305,7 +307,13 @@ export function App() { GitHub - + + Download @@ -324,8 +332,14 @@ export function App() { build beside you, live, in the same file.

- - Download for macOS + + + {downloadLabel(shownTarget)} @@ -430,8 +450,9 @@ export function App() {

Open a canvas. Invite your agent.

- - Download for macOS + + + {downloadLabel(target)}
@@ -447,7 +468,11 @@ export function App() { GitHub - setDownloadOpen(false)} /> + setDownload(null)} + /> ) } diff --git a/apps/site/src/download-dialog.tsx b/apps/site/src/download-dialog.tsx index 6bcfea4..03dd251 100644 --- a/apps/site/src/download-dialog.tsx +++ b/apps/site/src/download-dialog.tsx @@ -1,5 +1,6 @@ import { useEffect, useRef, useState } from 'react' import { play } from 'cuelume' +import { downloadUrl, type DownloadTarget } from './download' /** Sheet is ad-hoc signed, not notarized, so macOS quarantines the first copy it downloads. */ export const UNQUARANTINE = 'sudo xattr -rd com.apple.quarantine /Applications/Sheet.app' @@ -17,23 +18,25 @@ function startDownload(href: string) { } /** - * Shown when Download is pressed. It says why macOS will object to the app and - * gives the one command that fixes it, then starts the download itself after a - * short countdown, so the command is read before the file arrives. + * Shown when Download is pressed. It says why the system will object to the app + * and, on macOS, gives the one command that fixes it, then starts the download + * itself after a short countdown, so the instruction is read before the file + * arrives. */ export function DownloadDialog({ open, - href, + target, onClose, }: { open: boolean - href: string + target: DownloadTarget onClose: () => void }) { const ref = useRef(null) const [left, setLeft] = useState(COUNTDOWN_SECONDS) const [started, setStarted] = useState(false) const [copied, setCopied] = useState(false) + const href = downloadUrl(target) useEffect(() => { const dialog = ref.current @@ -84,20 +87,37 @@ export function DownloadDialog({ >

Before you open Sheet

-

- Sheet is not signed by Apple yet, so macOS will refuse to open it the first time. After - you drag it into Applications, run this once in Terminal: -

+ {target === 'macos' ? ( + <> +

+ Sheet is not signed by Apple yet, so macOS will refuse to open it the first time. After + you drag it into Applications, run this once in Terminal: +

-
- {UNQUARANTINE} - -
+
+ {UNQUARANTINE} + +
+ + ) : ( +

+ Sheet is not code-signed yet, so Windows SmartScreen will warn about an unrecognised app + the first time. Click More info in the warning, then{' '} + Run anyway. +

+ )}

- Only the first install needs it. After that, Sheet updates itself. Apple Silicon Macs only. + Only the first {target === 'macos' ? 'install' : 'launch'} needs it. After that, Sheet + updates itself.{' '} + {target === 'macos' ? 'Apple Silicon Macs only.' : 'Windows 10 or 11, 64-bit.'}

diff --git a/apps/site/src/download.ts b/apps/site/src/download.ts new file mode 100644 index 0000000..509db28 --- /dev/null +++ b/apps/site/src/download.ts @@ -0,0 +1,36 @@ +import type { Platform } from './diagrams' + +export const REPO = 'https://github.com/DeepanshuMishraa/sheet' + +/** + * Fixed names, so the links keep working across versions: the release workflow + * uploads both builds under these names. + */ +const FILES = { + macos: 'Sheet-macos-arm64.dmg', + windows: 'Sheet-windows-x64.exe', +} as const + +export type DownloadTarget = keyof typeof FILES + +export const targetName: Record = { + macos: 'macOS', + windows: 'Windows', +} + +/** + * Which build the visitor can actually run. Linux is detected for the window + * mockups but has no build of its own yet, so it is offered the Mac app. + */ +export function downloadTarget(platform: Platform): DownloadTarget { + return platform === 'Windows' ? 'windows' : 'macos' +} + +export function downloadUrl(target: DownloadTarget) { + return `${REPO}/releases/latest/download/${FILES[target]}` +} + +/** The link text: `Download for Windows`, and so on. */ +export function downloadLabel(target: DownloadTarget) { + return `Download for ${targetName[target]}` +} diff --git a/apps/site/src/marks.tsx b/apps/site/src/marks.tsx new file mode 100644 index 0000000..62661b1 --- /dev/null +++ b/apps/site/src/marks.tsx @@ -0,0 +1,29 @@ +import type { DownloadTarget } from './download' + +/** The Apple mark, at its own tall aspect ratio. */ +export function AppleMark() { + return ( + + ) +} + +/** The Windows mark, in its own blue. */ +export function WindowsMark() { + return ( + + ) +} + +export function PlatformMark({ target }: { target: DownloadTarget }) { + return target === 'windows' ? : +} diff --git a/apps/site/src/styles.css b/apps/site/src/styles.css index 1b2c189..54b84e3 100644 --- a/apps/site/src/styles.css +++ b/apps/site/src/styles.css @@ -167,6 +167,7 @@ main > section, display: inline-flex; align-items: center; justify-content: center; + gap: 0.5rem; height: 2.75rem; padding-inline: 1.5rem; border: 1px solid var(--input); @@ -178,6 +179,13 @@ main > section, transform var(--duration-fast) ease; } +/* The platform mark on a download button, sized to the label's cap height. */ +.mark { + flex: none; + width: 0.875em; + height: 0.875em; +} + .button:hover { border-color: var(--foreground); } diff --git a/boot-probe.mjs b/boot-probe.mjs index 47d6e17..87eccb3 100644 --- a/boot-probe.mjs +++ b/boot-probe.mjs @@ -1,10 +1,27 @@ import { chromium } from 'playwright-core' +import { existsSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' const url = process.argv[2] ?? 'http://127.0.0.1:1421/' -const browser = await chromium.launch({ - executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', - headless: true, -}) +// Only a browser that actually exists is used; a configured path wins over the +// platform defaults. +const executable = [ + process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH?.trim(), + process.env.CHROMIUM_PATH?.trim(), + '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', + '/Applications/Chromium.app/Contents/MacOS/Chromium', + '/usr/bin/chromium', + '/usr/bin/chromium-browser', + process.env.PROGRAMFILES && `${process.env.PROGRAMFILES}\\Google\\Chrome\\Application\\chrome.exe`, + process.env['PROGRAMFILES(X86)'] && `${process.env['PROGRAMFILES(X86)']}\\Google\\Chrome\\Application\\chrome.exe`, + process.env.LOCALAPPDATA && `${process.env.LOCALAPPDATA}\\Google\\Chrome\\Application\\chrome.exe`, + 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe', + 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe', +].find((p) => p && existsSync(p)) + +const launchOptions = executable ? { executablePath: executable, headless: true } : { headless: true } +const browser = await chromium.launch(launchOptions) const page = await browser.newPage({ viewport: { width: 1440, height: 900 } }) const t0 = Date.now() const events = [] @@ -59,5 +76,7 @@ const timing = await page.evaluate(() => { }) console.log('\nperf:', timing) -await page.screenshot({ path: '/tmp/boot-final.png' }) +const screenshotPath = join(tmpdir(), 'boot-final.png') +await page.screenshot({ path: screenshotPath }) +console.log(`Saved screenshot to: ${screenshotPath}`) await browser.close() diff --git a/package.json b/package.json index 5c0e783..40d2750 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,7 @@ "private": true, "scripts": { "dev": "bun run scripts/dev.ts", + "dev:web": "bun run scripts/dev.ts --web", "dev:desktop": "bun run --cwd apps/desktop dev", "dev:stdio": "bun run --cwd apps/mcp dev:stdio", "build:desktop": "bun run --cwd apps/desktop build", diff --git a/packages/canvas/src/web-stage.test.ts b/packages/canvas/src/web-stage.test.ts index 6725f81..b7a1b62 100644 --- a/packages/canvas/src/web-stage.test.ts +++ b/packages/canvas/src/web-stage.test.ts @@ -48,7 +48,7 @@ describe('page name and stage colour', () => { { type: 'node.insert', node: page }, { type: 'node.insert', node: bounded }, ]).document - expect(compileWebCodeHtml(plain)).not.toContain('background:#') + expect(compileWebCodeHtml(plain)).not.toContain('body{background:') expect(compileWebStandaloneHtml(plain)).not.toContain('!important') const colored = apply(plain, [ diff --git a/packages/canvas/src/web-test-browser.ts b/packages/canvas/src/web-test-browser.ts index f362ae9..95d9f2f 100644 --- a/packages/canvas/src/web-test-browser.ts +++ b/packages/canvas/src/web-test-browser.ts @@ -1,4 +1,5 @@ import { existsSync } from 'node:fs' +import { join } from 'node:path' /** * Test-only Chromium resolution, shared by browser proof suites. Mirrors the @@ -6,13 +7,33 @@ import { existsSync } from 'node:fs' * exists so CI without Chrome stays green. */ export function findChromiumExecutable() { - const candidates = [ + // Check both overrides on their own: a stale PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH + // must not hide a working CHROMIUM_PATH. + const configured = [ process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH?.trim(), process.env.CHROMIUM_PATH?.trim(), + ].filter((value): value is string => Boolean(value)) + for (const candidate of configured) { + if (existsSync(candidate)) return candidate + } + + const programFiles = process.env.PROGRAMFILES?.trim() + const programFilesX86 = process.env['PROGRAMFILES(X86)']?.trim() + const localAppData = process.env.LOCALAPPDATA?.trim() + + const candidates = [ + // macOS '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/Applications/Chromium.app/Contents/MacOS/Chromium', + // Linux '/usr/bin/chromium', '/usr/bin/chromium-browser', + // Windows + programFiles && join(programFiles, 'Google', 'Chrome', 'Application', 'chrome.exe'), + programFilesX86 && join(programFilesX86, 'Google', 'Chrome', 'Application', 'chrome.exe'), + localAppData && join(localAppData, 'Google', 'Chrome', 'Application', 'chrome.exe'), + programFiles && join(programFiles, 'Microsoft', 'Edge', 'Application', 'msedge.exe'), + programFilesX86 && join(programFilesX86, 'Microsoft', 'Edge', 'Application', 'msedge.exe'), ].filter((value): value is string => Boolean(value)) return candidates.find((candidate) => existsSync(candidate)) ?? null } diff --git a/packages/rpc/src/web-mcp.test.ts b/packages/rpc/src/web-mcp.test.ts index 5a318cb..9793ec2 100644 --- a/packages/rpc/src/web-mcp.test.ts +++ b/packages/rpc/src/web-mcp.test.ts @@ -122,6 +122,8 @@ describe('MCP web transactions', () => { designId, expectedRevision: 0, transaction, + // The tool returns only the summary unless the full document is asked for. + verbose: true, }) const body = textResult(result) expect(body).toMatchObject({ applied: true, revision: 1 }) @@ -188,6 +190,8 @@ describe('MCP web transactions', () => { const result = textResult(await execute('applyWebTransaction', { designId, expectedRevision: 0, + // This assertion reads the document back, which needs the verbose reply. + verbose: true, transaction: { id: 'resize-page', label: 'Resize page', diff --git a/packages/rpc/src/web-screenshot.test.ts b/packages/rpc/src/web-screenshot.test.ts index 9a09b80..6dc50ff 100644 --- a/packages/rpc/src/web-screenshot.test.ts +++ b/packages/rpc/src/web-screenshot.test.ts @@ -32,8 +32,10 @@ function fakeWindow() { const unregister = registerCapturer({ send: (request) => { requests.push(request) + // A subtree capture is only as wide as the subtree; the window measures it. + const width = request.rootId === null ? request.width : 400 queueMicrotask(() => - completeCapture(request.id, { ok: true, bytes, mimeType: 'image/png', width: request.width, height: 600 }), + completeCapture(request.id, { ok: true, bytes, mimeType: 'image/png', width, height: 600 }), ) }, }) @@ -129,59 +131,65 @@ describe('web screenshots', () => { .where(and(eq(designVersion.designId, designId), eq(designVersion.userId, LOCAL_USER_ID))) const window = fakeWindow() - const { renderWebScreenshot } = await import('@sheet/rpc/mcp-screenshot') - const full = await renderWebScreenshot(LOCAL_USER_ID, document, { width: 800 }) - expect(full.png.byteLength).toBeGreaterThan(1_000) - expect(full.width).toBe(800) - expect(full.height).toBeGreaterThan(0) - expect(full.rootId).toBeNull() - expect(window.requests[0]?.html).toContain('data-sheet-export-root="true"') + try { + const { renderWebScreenshot } = await import('@sheet/rpc/mcp-screenshot') + const full = await renderWebScreenshot(LOCAL_USER_ID, document, { width: 800 }) + expect(full.png.byteLength).toBeGreaterThan(1_000) + expect(full.width).toBe(800) + expect(full.height).toBeGreaterThan(0) + expect(full.rootId).toBeNull() + expect(window.requests[0]?.html).toContain('data-sheet-export-root="true"') - const scoped = await renderWebScreenshot(LOCAL_USER_ID, document, { rootId: 'title' }) - expect(scoped.rootId).toBe('title') - expect(window.requests[1]?.rootId).toBe('title') - expect(scoped.width).toBeLessThanOrEqual(full.width) - await expect( - renderWebScreenshot(LOCAL_USER_ID, document, { rootId: 'missing' }), - ).rejects.toThrow('does not exist') + const scoped = await renderWebScreenshot(LOCAL_USER_ID, document, { rootId: 'title' }) + expect(scoped.rootId).toBe('title') + expect(window.requests[1]?.rootId).toBe('title') + expect(scoped.width).toBeLessThanOrEqual(full.width) + await expect( + renderWebScreenshot(LOCAL_USER_ID, document, { rootId: 'missing' }), + ).rejects.toThrow('does not exist') - const stored = await db - .select({ revision: design.revision, document: design.canvasDocument }) - .from(design) - .where(and(eq(design.id, designId), eq(design.userId, LOCAL_USER_ID))) - .limit(1) - .then((rows) => rows[0]) - expect(stored?.revision).toBe(0) - expect(JSON.stringify(stored?.document)).toBe(before) - const versionsAfter = await db - .select({ id: designVersion.id }) - .from(designVersion) - .where(and(eq(designVersion.designId, designId), eq(designVersion.userId, LOCAL_USER_ID))) - expect(versionsAfter).toEqual(versionsBefore) - window.unregister() + const stored = await db + .select({ revision: design.revision, document: design.canvasDocument }) + .from(design) + .where(and(eq(design.id, designId), eq(design.userId, LOCAL_USER_ID))) + .limit(1) + .then((rows) => rows[0]) + expect(stored?.revision).toBe(0) + expect(JSON.stringify(stored?.document)).toBe(before) + const versionsAfter = await db + .select({ id: designVersion.id }) + .from(designVersion) + .where(and(eq(designVersion.designId, designId), eq(designVersion.userId, LOCAL_USER_ID))) + expect(versionsAfter).toEqual(versionsBefore) + } finally { + window.unregister() + } }, 60_000) it('exposes the render through the MCP envelope with revision metadata', async () => { const designId = await seedDesign(shotFixture()) const execute = createSheetToolExecutor(LOCAL_USER_ID, usage()) const window = fakeWindow() - const result = await execute('getWebScreenshot', { designId, width: 800 }) as { - isError?: boolean - content: Array<{ type: string; text?: string; data?: string; mimeType?: string }> + try { + const result = await execute('getWebScreenshot', { designId, width: 800 }) as { + isError?: boolean + content: Array<{ type: string; text?: string; data?: string; mimeType?: string }> + } + expect(result.isError).not.toBe(true) + const metadata = JSON.parse(result.content[0]?.text ?? '{}') as Record + expect(metadata).toMatchObject({ + mimeType: 'image/png', + width: 800, + revision: 0, + target: { designId, draftId: null, rootId: null }, + }) + const image = result.content[1] + expect(image?.type).toBe('image') + expect(image?.mimeType).toBe('image/png') + expect((image?.data ?? '').length).toBeGreaterThan(1_000) + } finally { + window.unregister() } - expect(result.isError).not.toBe(true) - const metadata = JSON.parse(result.content[0]?.text ?? '{}') as Record - expect(metadata).toMatchObject({ - mimeType: 'image/png', - width: 800, - revision: 0, - target: { designId, draftId: null, rootId: null }, - }) - const image = result.content[1] - expect(image?.type).toBe('image') - expect(image?.mimeType).toBe('image/png') - expect((image?.data ?? '').length).toBeGreaterThan(1_000) - window.unregister() }, 60_000) it('says so plainly when no Sheet window is open', async () => { diff --git a/scripts/build-server.ts b/scripts/build-server.ts new file mode 100644 index 0000000..b4f4e87 --- /dev/null +++ b/scripts/build-server.ts @@ -0,0 +1,41 @@ +import { mkdirSync } from 'node:fs' +import { join } from 'node:path' + +/** + * Cross-platform server compilation script for Sheet. + * Embeds DB migrations, creates the binaries folder if missing, + * and compiles apps/mcp/src/local.ts to a standalone sidecar binary + * (sheet-server.exe on Windows, sheet-server on macOS/Linux). + */ + +const isWindows = process.platform === 'win32' +const root = join(import.meta.dir, '..') +const binDir = join(root, 'apps/desktop/src-tauri/binaries') +mkdirSync(binDir, { recursive: true }) + +const outFile = join(binDir, isWindows ? 'sheet-server.exe' : 'sheet-server') +const bunBin = process.execPath + +console.log('[build:server] Embedding migrations...') +const embedProc = Bun.spawnSync([bunBin, 'run', '--cwd', 'packages/db', 'embed'], { + cwd: root, + stdio: ['inherit', 'inherit', 'inherit'], +}) +if (embedProc.exitCode !== 0) { + process.exit(embedProc.exitCode ?? 1) +} + +console.log(`[build:server] Compiling local server to ${outFile}...`) +const compileProc = Bun.spawnSync( + [bunBin, 'build', '--compile', 'apps/mcp/src/local.ts', '--outfile', outFile], + { + cwd: root, + stdio: ['inherit', 'inherit', 'inherit'], + }, +) + +if (compileProc.exitCode !== 0) { + process.exit(compileProc.exitCode ?? 1) +} + +console.log(`[build:server] Successfully built server sidecar: ${outFile}`) diff --git a/scripts/dev.ts b/scripts/dev.ts index fd4d97b..b8bdfdc 100644 --- a/scripts/dev.ts +++ b/scripts/dev.ts @@ -10,6 +10,7 @@ import { join } from 'node:path' * Flags: * --server-only just the local server (API + MCP) * --desktop-only just the Tauri window (expects a server already up) + * --web the visual canvas in a browser (no Rust toolchain) * * Env: SHEET_MCP_PORT (4100), SHEET_SQLITE_PATH (./data/sheet.db). * If a server is already listening, it is reused, not replaced. @@ -20,6 +21,8 @@ const port = process.env.SHEET_MCP_PORT?.trim() || '4100' const serverUrl = `http://127.0.0.1:${port}` const serverOnly = process.argv.includes('--server-only') const desktopOnly = process.argv.includes('--desktop-only') +const webOnly = process.argv.includes('--web') +const bunBin = process.execPath process.env.SHEET_SQLITE_PATH ??= join(root, 'data', 'sheet.db') @@ -78,15 +81,23 @@ if (!desktopOnly) { if (await serverUp()) { console.info('[dev] local server already running — reusing it') } else { - spawn('local server', ['bun', 'run', '--cwd', 'apps/mcp', 'dev']) + spawn('local server', [bunBin, 'run', '--cwd', 'apps/mcp', 'dev']) await waitForServer() console.info('[dev] local server ready') } } -if (!serverOnly) { +if (webOnly) { await waitForServer() - const desktop = spawn('desktop', ['bun', 'run', '--cwd', 'apps/desktop', 'dev']) + // The browser interface talks to the local server directly, so its proxy has + // to follow SHEET_MCP_PORT instead of the Tauri host's fixed :4300. + process.env.SHEET_DESKTOP_PORT = port + const web = spawn('web interface', [bunBin, 'run', '--cwd', 'apps/desktop', 'dev:web']) + await web.exited + await shutdown(web.exitCode ?? 0) +} else if (!serverOnly) { + await waitForServer() + const desktop = spawn('desktop', [bunBin, 'run', '--cwd', 'apps/desktop', 'dev']) await desktop.exited await shutdown(desktop.exitCode ?? 0) } else { diff --git a/windows/README.md b/windows/README.md new file mode 100644 index 0000000..1e7a7e9 --- /dev/null +++ b/windows/README.md @@ -0,0 +1,189 @@ +# Sheet for Windows + +First-class Windows support for [Sheet](https://github.com/DeepanshuMishraa/sheet), the local-first visual design canvas that lets AI coding agents create and edit interfaces using real HTML and CSS. + +--- + +## System Requirements + +- **Operating System**: Windows 10 (build 1903 or later, 64-bit) or Windows 11 x64. +- **Runtime**: [Bun](https://bun.sh) for Windows (v1.3.0 or later). +- **Browser**: Google Chrome or Microsoft Edge (Chromium-based, included in Windows 10/11). +- **Optional**: + - [Node.js](https://nodejs.org) (v20+ / v22+ / v24+). + - [Rust](https://rustup.rs) & Visual Studio C++ Build Tools (required only if compiling the native Tauri desktop window from source). + +--- + +## Quick Start + +### 1. Prerequisites & Setup +Clone the repository and run the automated Windows setup script in PowerShell: + +```powershell +# In PowerShell, from the repository root. +# Only this session needs the relaxed policy; the machine setting is untouched. +Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass +.\windows\setup.ps1 +``` + +This verifies toolchains, checks browser availability, installs workspace dependencies via Bun preserving `bun.lock`, and prepares database migrations. + +### 2. Development Workflows + +Sheet provides three distinct workflows on Windows: + +#### A. Web Visual Canvas (Recommended for most contributors) +Starts the local server (oRPC + MCP + SSE) on `:4100`, starts the Vite visual canvas on `:1421`, and opens it in your default browser: + +```powershell +.\windows\run.ps1 -Web +``` + +*Note: Does not require Rust or C++ Build Tools. Full visual canvas and MCP server functionality are available.* + +If a Sheet server is already listening on `:4100`, `run.ps1` refuses to start a second one. Pass `-ReuseServer` to attach to the running server, or `-Port` / `-AppPort` to move the server or the canvas: + +```powershell +.\windows\run.ps1 -Web -ReuseServer +.\windows\run.ps1 -Web -Port 4101 -AppPort 1422 +``` + +#### B. Server-Only (MCP AI Agent Host) +Starts only the local backend server and MCP JSON-RPC endpoint on loopback `:4100`: + +```powershell +.\windows\run.ps1 -ServerOnly +``` + +#### C. Native Desktop Window (Tauri) +Spawns the native Tauri desktop window using the Windows WebView2 runtime (requires Rust and MSVC C++ Build Tools): + +```powershell +.\windows\run.ps1 -Desktop +``` + +Press `Ctrl+C` in the PowerShell window to stop all child processes and free the loopback ports. + +--- + +## Connecting AI Agents over MCP + +Sheet provides 32+ typed design tools over standard JSON-RPC HTTP on `http://127.0.0.1:4100/mcp`. + +### Cursor +Add to `%USERPROFILE%\.cursor\mcp.json`: +```json +{ + "mcpServers": { + "sheet": { + "url": "http://127.0.0.1:4100/mcp" + } + } +} +``` + +### Claude Code +Add to `%USERPROFILE%\.claude.json`: +```json +{ + "mcpServers": { + "sheet": { + "type": "http", + "url": "http://127.0.0.1:4100/mcp" + } + } +} +``` + +### VS Code / GitHub Copilot +Add to `%APPDATA%\Code\User\mcp.json`: +```json +{ + "servers": { + "sheet": { + "type": "http", + "url": "http://127.0.0.1:4100/mcp" + } + } +} +``` + +### Codex +Add to `%USERPROFILE%\.codex\config.toml`: +```toml +[mcp_servers.sheet] +url = "http://127.0.0.1:4100/mcp" +``` + +--- + +## Testing + +Run tests from the repository root: + +```bash +# Run all Vitest suites +bun run test + +# Run Windows platform adapter test suite +bun run test windows/tests/windows-platform.test.ts +``` + +--- + +## Building & Packaging + +Use `windows/build.ps1` to produce Windows distributions: + +```powershell +# 1. Portable Distribution (server, built interface, and launcher) +.\windows\build.ps1 -Portable +# Output: dist/windows-portable/ +# launch.bat runs sheet-server.exe with SHEET_APP_DIR pointing at the bundled +# interface, so http://127.0.0.1:4100 opens the canvas and /mcp stays available. +# Data lives in %APPDATA%\Sheet\sheet.db; close the "Sheet" console window to stop. + +# 2. Server Sidecar Only (Compiles sheet-server.exe) +.\windows\build.ps1 -ServerOnly +# Output: apps/desktop/src-tauri/binaries/sheet-server.exe + +# 3. Native Tauri Desktop Installer (.msi / .exe via NSIS, requires Rust) +.\windows\build.ps1 -Package +``` + +Running `.\windows\build.ps1` with no switches builds the server and interface, then packages the portable distribution. + +--- + +## Persistent Data & Storage + +- **Production**: `%APPDATA%\Sheet\` (`sheet.db` and `handoff.key`) +- **Development**: `%APPDATA%\Sheet Dev\` (`sheet.db` and `handoff.key`) +- **Override**: Set `SHEET_DATA_DIR` for the launchers, which pass the database path to the server as `SHEET_SQLITE_PATH`. + +The database runs in WAL mode, so recent writes can live in `sheet.db-wal` until a checkpoint. To back up safely, close Sheet first, then copy all three files together if they exist: + +```powershell +$backup = "$env:USERPROFILE\Desktop\sheet-backup" +New-Item -ItemType Directory -Path $backup -Force | Out-Null +Copy-Item "$env:APPDATA\Sheet\sheet.db*" -Destination $backup +``` + +--- + +## Architecture & Windows Boundaries + +- **Cross-Platform Boundaries**: + - `windows/src/platform-adapter.ts`: Windows path normalization (`win32` semantics and `file:///C:/...` URLs), `%APPDATA%` resolution, browser discovery, and loopback port checks. + - `apps/desktop/src-tauri/tauri.conf.json`: Configured with cross-platform bundle targets (`"targets": "all"`). + - `apps/mcp/src/agent-install.ts`: writes agent configs through a unique temporary file renamed into place, retrying the rename while Windows indexers or antivirus hold the target. If the lock never clears, the previous file is left exactly as it was. + - `apps/mcp/src/local.ts`: with `SHEET_APP_DIR` set, serves the built interface (SPA fallback included) so the portable bundle opens the canvas, not just the MCP endpoint. + - `scripts/build-server.ts`: Replaces Unix shell commands with cross-platform binary compilation. +- **macOS packaging**: the `.dmg` is still built by `.github/workflows/release.yml` on `macos-latest` (`aarch64-apple-darwin`); the same workflow builds the Windows NSIS installer on `windows-latest` and attaches both to the release. + +--- + +## Reporting Issues + +If you encounter Windows-specific issues (e.g. port binding errors, path normalization bugs, or WebView2 glitches), please report them on the [GitHub Issues](https://github.com/DeepanshuMishraa/sheet/issues) page with the `[windows]` label. diff --git a/windows/build.ps1 b/windows/build.ps1 new file mode 100644 index 0000000..156e74d --- /dev/null +++ b/windows/build.ps1 @@ -0,0 +1,234 @@ +<# +.SYNOPSIS + Build and packaging script for Sheet on Windows. +.DESCRIPTION + Compiles the standalone backend server (sheet-server.exe), builds the + Vite desktop web interface (dist/app), and creates either a portable + distribution or a packaged native installer (via Tauri if the Rust + toolchain is installed). + + With no switches it builds both parts and packages the portable + distribution. + +.PARAMETER ServerOnly + Builds only the backend server sidecar + (apps/desktop/src-tauri/binaries/sheet-server.exe). Cannot be combined + with -AppOnly. +.PARAMETER AppOnly + Builds only the frontend interface (apps/desktop/dist/app). Cannot be + combined with -ServerOnly. +.PARAMETER Portable + Packages a standalone portable distribution into dist/windows-portable. + This is the default when neither -Portable nor -Package is given. +.PARAMETER Package + Builds the native Tauri Windows installer (.msi / .exe). Requires Rust. +#> + +[CmdletBinding()] +param( + [switch]$ServerOnly, + [switch]$AppOnly, + [switch]$Portable, + [switch]$Package +) + +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version Latest + +if ($ServerOnly -and $AppOnly) { + Write-Host '[Error] -ServerOnly and -AppOnly build different halves of the app.' -ForegroundColor Red + Write-Host ' Pick one, or run without either switch to build everything.' -ForegroundColor Yellow + exit 1 +} + +$RepoRoot = $PSScriptRoot +if ((Split-Path -Leaf $RepoRoot) -eq 'windows') { + $RepoRoot = Split-Path -Parent $RepoRoot +} + +Write-Host '========================================' -ForegroundColor Cyan +Write-Host ' Sheet for Windows — Build Script ' -ForegroundColor Cyan +Write-Host '========================================' -ForegroundColor Cyan +Write-Host '' + +# Locate Bun +$BunExe = $null +if (Get-Command 'bun.exe' -ErrorAction SilentlyContinue) { + $BunExe = (Get-Command 'bun.exe').Source +} elseif (Get-Command 'bun' -ErrorAction SilentlyContinue) { + $BunExe = (Get-Command 'bun').Source +} else { + $DefaultBunPath = Join-Path $env:USERPROFILE '.bun\bin\bun.exe' + if (Test-Path $DefaultBunPath) { + $BunExe = $DefaultBunPath + } +} + +if (-not $BunExe) { + Write-Host '[Error] Bun is required to build Sheet on Windows. Run .\windows\setup.ps1 first.' -ForegroundColor Red + exit 1 +} + +$BuildServer = -not $AppOnly +$BuildApp = -not $ServerOnly +$TotalSteps = [int]$BuildServer + [int]$BuildApp + 1 +$Step = 0 + +Push-Location $RepoRoot +try { + # 1. Build Server + if ($BuildServer) { + $Step += 1 + Write-Host "[$Step/$TotalSteps] Building backend server sidecar (sheet-server.exe)..." -ForegroundColor Cyan + & $BunExe run scripts/build-server.ts + if ($LASTEXITCODE -ne 0) { + Write-Host "[Error] Server build failed with exit code $LASTEXITCODE" -ForegroundColor Red + Write-Host ' Fix the compiler error above, then run the build again.' -ForegroundColor Yellow + exit $LASTEXITCODE + } + Write-Host '[OK] Server binary compiled successfully.' -ForegroundColor Green + } + + if ($ServerOnly) { + Write-Host '' + Write-Host '[OK] Server-only build complete: apps/desktop/src-tauri/binaries/sheet-server.exe' -ForegroundColor Green + exit 0 + } + + # 2. Build Frontend + if ($BuildApp) { + $Step += 1 + Write-Host '' + Write-Host "[$Step/$TotalSteps] Building frontend application bundle (dist/app)..." -ForegroundColor Cyan + & $BunExe run --cwd apps/desktop build:app + if ($LASTEXITCODE -ne 0) { + Write-Host "[Error] Frontend build failed with exit code $LASTEXITCODE" -ForegroundColor Red + Write-Host ' Fix the bundler error above, then run the build again.' -ForegroundColor Yellow + exit $LASTEXITCODE + } + Write-Host '[OK] Frontend bundle built successfully.' -ForegroundColor Green + } + + if ($AppOnly) { + Write-Host '' + Write-Host '[OK] App-only build complete: apps/desktop/dist/app' -ForegroundColor Green + exit 0 + } + + # 3. Packaging + $Step += 1 + Write-Host '' + Write-Host "[$Step/$TotalSteps] Packaging distribution..." -ForegroundColor Cyan + + if ($Package) { + # Native Tauri build + if (-not (Get-Command 'cargo.exe' -ErrorAction SilentlyContinue)) { + Write-Host '[Error] Rust/Cargo is required to build the native Tauri package.' -ForegroundColor Red + Write-Host ' Install Rust from https://rustup.rs, or run .\windows\build.ps1 -Portable instead.' -ForegroundColor Yellow + exit 1 + } + Write-Host '[package] Building native Tauri Windows bundle (NSIS/MSI)...' -ForegroundColor Cyan + Push-Location (Join-Path $RepoRoot 'apps\desktop') + try { + & $BunExe run build + if ($LASTEXITCODE -ne 0) { + Write-Host "[Error] Tauri build failed with exit code $LASTEXITCODE" -ForegroundColor Red + exit $LASTEXITCODE + } + Write-Host '[OK] Native Windows bundle built in apps/desktop/src-tauri/target/release/bundle' -ForegroundColor Green + } finally { + Pop-Location + } + } else { + # Create Portable Distribution + $PortableDir = Join-Path $RepoRoot 'dist\windows-portable' + Write-Host "[package] Creating portable distribution at: $PortableDir" -ForegroundColor Cyan + + if (Test-Path $PortableDir) { + # A portable server left running holds sheet-server.exe open; deleting + # the directory would fail with a bare "file in use" error. + $RunningServer = $null + try { + $RunningServer = Get-Process -Name 'sheet-server' -ErrorAction SilentlyContinue | + Where-Object { + $_.Path -and $_.Path.StartsWith($PortableDir, [System.StringComparison]::OrdinalIgnoreCase) + } | + Select-Object -First 1 + } catch { + $RunningServer = $null + } + if ($RunningServer) { + Write-Host "[Error] A previous portable Sheet server is still running from $PortableDir." -ForegroundColor Red + Write-Host ' Close its window (or stop sheet-server.exe) and run the build again.' -ForegroundColor Yellow + Write-Host ' Nothing was removed or overwritten.' -ForegroundColor Yellow + exit 1 + } + Remove-Item -Path $PortableDir -Recurse -Force + } + $null = New-Item -ItemType Directory -Path $PortableDir -Force + + # Copy server binary + $ServerBinSource = Join-Path $RepoRoot 'apps\desktop\src-tauri\binaries\sheet-server.exe' + if (-not (Test-Path $ServerBinSource)) { + Write-Host "[Error] sheet-server.exe was not found at $ServerBinSource." -ForegroundColor Red + Write-Host ' Run .\windows\build.ps1 (without -AppOnly) to compile it first.' -ForegroundColor Yellow + exit 1 + } + Copy-Item -Path $ServerBinSource -Destination (Join-Path $PortableDir 'sheet-server.exe') -Force + + # Copy web frontend assets + $AppSource = Join-Path $RepoRoot 'apps\desktop\dist\app' + if (-not (Test-Path (Join-Path $AppSource 'index.html'))) { + Write-Host "[Error] The built interface was not found at $AppSource." -ForegroundColor Red + Write-Host ' Run .\windows\build.ps1 (without -ServerOnly) to build it first.' -ForegroundColor Yellow + exit 1 + } + Copy-Item -Path $AppSource -Destination (Join-Path $PortableDir 'app') -Recurse -Force + + # The server serves the interface itself: SHEET_APP_DIR points at the + # copied bundle, and the database lives where the README promises. + $LauncherContent = @" +@echo off +setlocal +set SHEET_MCP_PORT=4100 +set SHEET_SQLITE_PATH=%APPDATA%\Sheet\sheet.db +set SHEET_APP_DIR=%~dp0app +title Sheet Local Server +echo ======================================== +echo Sheet for Windows Portable +echo Canvas: http://127.0.0.1:4100 +echo MCP endpoint: http://127.0.0.1:4100/mcp +echo Database: %SHEET_SQLITE_PATH% +echo ======================================== +echo. +start "Sheet" "%~dp0sheet-server.exe" +echo Waiting for the local server... +for /l %%i in (1,1,40) do ( + powershell -NoProfile -Command "try { `$r = Invoke-RestMethod -Uri 'http://127.0.0.1:4100/ready' -TimeoutSec 1; if (`$r.ready) { exit 0 } } catch {}; exit 1" >nul 2>&1 + if not errorlevel 1 goto ready + timeout /t 1 /nobreak >nul +) +echo [Error] Sheet did not become ready on port 4100. +echo The server window shows why; close it and run launch.bat again. +pause +exit /b 1 +:ready +start "" http://127.0.0.1:4100 +echo Sheet is running in the "Sheet" console window. +echo Close that window to stop the server. +timeout /t 5 /nobreak >nul +"@ + Set-Content -Path (Join-Path $PortableDir 'launch.bat') -Value $LauncherContent -Encoding Ascii + + Write-Host '[OK] Portable distribution ready in dist/windows-portable' -ForegroundColor Green + Write-Host ' Run launch.bat to start Sheet and connect agents over MCP.' -ForegroundColor White + } + + Write-Host '' + Write-Host '========================================' -ForegroundColor Green + Write-Host ' Windows Build Complete! ' -ForegroundColor Green + Write-Host '========================================' -ForegroundColor Green + exit 0 +} finally { + Pop-Location +} diff --git a/windows/run.ps1 b/windows/run.ps1 new file mode 100644 index 0000000..2f71acc --- /dev/null +++ b/windows/run.ps1 @@ -0,0 +1,277 @@ +<# +.SYNOPSIS + Development and runtime launcher for Sheet on Windows. +.DESCRIPTION + Launches Sheet components with port checking, readiness probing, + and process cleanup on exit. + + Three modes: + -Web local server + browser canvas (default) + -ServerOnly just the local server and MCP endpoint + -Desktop local server + native Tauri window (needs Rust) + + The database lives at \sheet.db, set through SHEET_SQLITE_PATH. +.PARAMETER ReuseServer + Attach to a Sheet server that is already listening on -Port instead of + rebuilding. Without this, an occupied port is reported as an error. +.PARAMETER Port + Loopback port for the local server (oRPC + MCP + SSE). Default 4100. +.PARAMETER AppPort + Loopback port for the Vite canvas in -Web mode. Default 1421. +.PARAMETER DataDir + Data directory for sheet.db. Default %APPDATA%\Sheet Dev. +#> + +[CmdletBinding(DefaultParameterSetName = 'Web')] +param( + [Parameter(ParameterSetName = 'Web')] + [switch]$Web, + + [Parameter(ParameterSetName = 'ServerOnly')] + [switch]$ServerOnly, + + [Parameter(ParameterSetName = 'Desktop')] + [switch]$Desktop, + + [Parameter()] + [switch]$ReuseServer, + + [Parameter()] + [int]$Port = 4100, + + [Parameter()] + [int]$AppPort = 1421, + + [Parameter()] + [string]$DataDir +) + +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version Latest + +$RepoRoot = $PSScriptRoot +if ((Split-Path -Leaf $RepoRoot) -eq 'windows') { + $RepoRoot = Split-Path -Parent $RepoRoot +} + +# Child process tracking for graceful shutdown +$Script:Processes = [System.Collections.Generic.List[System.Diagnostics.Process]]::new() + +function Stop-AllChildren { + if ($Script:Processes.Count -eq 0) { return } + Write-Host '' + Write-Host '[shutdown] Stopping child processes...' -ForegroundColor Yellow + foreach ($proc in $Script:Processes) { + if (-not $proc.HasExited) { + try { + Stop-Process -Id $proc.Id -Force -ErrorAction SilentlyContinue + } catch {} + } + } + Write-Host '[shutdown] Clean exit.' -ForegroundColor Green +} + +# Locate Bun +$BunExe = $null +if (Get-Command 'bun.exe' -ErrorAction SilentlyContinue) { + $BunExe = (Get-Command 'bun.exe').Source +} elseif (Get-Command 'bun' -ErrorAction SilentlyContinue) { + $BunExe = (Get-Command 'bun').Source +} else { + $DefaultBunPath = Join-Path $env:USERPROFILE '.bun\bin\bun.exe' + if (Test-Path $DefaultBunPath) { + $BunExe = $DefaultBunPath + } +} + +if (-not $BunExe) { + Write-Host '[Error] Bun executable not found. Run .\windows\setup.ps1 first.' -ForegroundColor Red + exit 1 +} + +# Configure environment +$env:SHEET_MCP_PORT = "$Port" +$env:SHEET_DESKTOP_APP_PORT = "$AppPort" +# The browser canvas proxies straight to the local server. The native window +# goes through the Rust host, which keeps its own port. +if (-not $Desktop) { + $env:SHEET_DESKTOP_PORT = "$Port" +} + +if ($DataDir) { + $env:SHEET_DATA_DIR = $DataDir +} else { + $AppDataRoot = if ($env:APPDATA) { $env:APPDATA } else { Join-Path $env:USERPROFILE 'AppData\Roaming' } + $env:SHEET_DATA_DIR = Join-Path $AppDataRoot 'Sheet Dev' +} +# The database reads SHEET_SQLITE_PATH, not SHEET_DATA_DIR. +$env:SHEET_SQLITE_PATH = Join-Path $env:SHEET_DATA_DIR 'sheet.db' +$null = New-Item -ItemType Directory -Path $env:SHEET_DATA_DIR -Force + +$ServerUrl = "http://127.0.0.1:$Port" +$AppUrl = "http://127.0.0.1:$AppPort" + +$ModeName = 'Web Canvas' +if ($ServerOnly) { + $ModeName = 'Server-Only' +} elseif ($Desktop) { + $ModeName = 'Native Desktop' +} + +Write-Host '========================================' -ForegroundColor Cyan +Write-Host ' Sheet for Windows ' -ForegroundColor Cyan +Write-Host '========================================' -ForegroundColor Cyan +Write-Host "Mode: $ModeName" -ForegroundColor White +Write-Host "MCP Port: $Port ($ServerUrl/mcp)" -ForegroundColor White +Write-Host "Data Dir: $($env:SHEET_DATA_DIR)" -ForegroundColor White +Write-Host "Database: $($env:SHEET_SQLITE_PATH)" -ForegroundColor White +Write-Host '' + +function Test-ServerReady { + try { + $res = Invoke-RestMethod -Uri "$ServerUrl/ready" -TimeoutSec 1 -ErrorAction SilentlyContinue + return ($null -ne $res -and $res.ready -eq $true) + } catch { + return $false + } +} + +# 1. Start Server if needed +$ServerAlreadyRunning = Test-ServerReady +$ServerProc = $null + +if ($ServerAlreadyRunning -and -not $ReuseServer) { + Write-Host "[Error] A Sheet server is already listening on $ServerUrl." -ForegroundColor Red + Write-Host ' Stop it, pick another -Port, or pass -ReuseServer to attach to it.' -ForegroundColor Yellow + exit 1 +} + +if ($ServerAlreadyRunning) { + Write-Host "[info] Local server already running at $ServerUrl (reusing it)." -ForegroundColor Green +} else { + Write-Host "[start] Starting local Sheet server on $ServerUrl..." -ForegroundColor Cyan + $ServerPsi = [System.Diagnostics.ProcessStartInfo]::new($BunExe) + $ServerPsi.Arguments = 'run src/local.ts' + $ServerPsi.WorkingDirectory = Join-Path $RepoRoot 'apps\mcp' + $ServerPsi.UseShellExecute = $false + + $ServerProc = [System.Diagnostics.Process]::Start($ServerPsi) + $Script:Processes.Add($ServerProc) + + # Wait for /ready + $Deadline = (Get-Date).AddSeconds(20) + $Ready = $false + while ((Get-Date) -lt $Deadline) { + Start-Sleep -Milliseconds 250 + if (Test-ServerReady) { + $Ready = $true + break + } + if ($ServerProc.HasExited) { + Write-Host "[Error] The local server exited with code $($ServerProc.ExitCode) before it was ready." -ForegroundColor Red + Write-Host ' Run the command below to see the failure:' -ForegroundColor Yellow + Write-Host " cd $RepoRoot\apps\mcp; bun run src/local.ts" -ForegroundColor DarkGray + Stop-AllChildren + exit 1 + } + } + + if (-not $Ready) { + Write-Host '[Error] Server failed to become ready within 20 seconds.' -ForegroundColor Red + Write-Host ' Another process may be holding the port. Try -Port 4101.' -ForegroundColor Yellow + Stop-AllChildren + exit 1 + } + Write-Host "[OK] Local server ready at $ServerUrl" -ForegroundColor Green + Write-Host " MCP Endpoint: $ServerUrl/mcp" -ForegroundColor Green +} + +if ($ServerOnly) { + if (-not $ServerProc) { + Write-Host '[info] Attached to the running server. Stop it from the window that started it.' -ForegroundColor White + exit 0 + } + Write-Host '' + Write-Host '[info] Server is running. Press Ctrl+C to stop.' -ForegroundColor White + try { + while ($true) { + Start-Sleep -Seconds 1 + if ($ServerProc.HasExited) { + Write-Host '[!] Server process exited.' -ForegroundColor Yellow + break + } + } + } finally { + Stop-AllChildren + } + exit 0 +} + +# 2. Launch Interface +if ($Desktop) { + if (-not (Get-Command 'cargo.exe' -ErrorAction SilentlyContinue)) { + Write-Host '[Error] Cargo/Rust is required for -Desktop mode.' -ForegroundColor Red + Write-Host ' Install Rust from https://rustup.rs or use -Web mode.' -ForegroundColor Yellow + Stop-AllChildren + exit 1 + } + + Write-Host '[start] Launching native desktop window via Tauri...' -ForegroundColor Cyan + Push-Location (Join-Path $RepoRoot 'apps\desktop') + try { + $DesktopProc = Start-Process -FilePath $BunExe -ArgumentList 'run dev' -PassThru -NoNewWindow + $Script:Processes.Add($DesktopProc) + $DesktopProc.WaitForExit() + } finally { + Pop-Location + Stop-AllChildren + } +} else { + Write-Host "[start] Starting visual canvas Vite server on $AppUrl..." -ForegroundColor Cyan + $VitePsi = [System.Diagnostics.ProcessStartInfo]::new($BunExe) + $VitePsi.Arguments = 'run dev:web' + $VitePsi.WorkingDirectory = Join-Path $RepoRoot 'apps\desktop' + $VitePsi.UseShellExecute = $false + + $ViteProc = [System.Diagnostics.Process]::Start($VitePsi) + $Script:Processes.Add($ViteProc) + + # Wait for Vite dev server + $ViteReady = $false + $Deadline = (Get-Date).AddSeconds(30) + while ((Get-Date) -lt $Deadline) { + Start-Sleep -Milliseconds 300 + try { + $testReq = Invoke-WebRequest -Uri $AppUrl -TimeoutSec 1 -UseBasicParsing -ErrorAction SilentlyContinue + if ($testReq.StatusCode -eq 200) { + $ViteReady = $true + break + } + } catch {} + if ($ViteProc.HasExited) { break } + } + + if (-not $ViteReady) { + Write-Host "[Error] The canvas did not come up at $AppUrl." -ForegroundColor Red + Write-Host " Check that port $AppPort is free, or pass -AppPort ." -ForegroundColor Yellow + Stop-AllChildren + exit 1 + } + + Write-Host "[OK] Sheet Visual Canvas is live at: $AppUrl" -ForegroundColor Green + Write-Host '[info] Opening in your default browser...' -ForegroundColor Cyan + Start-Process $AppUrl + + Write-Host '' + Write-Host 'Press Ctrl+C to shut down Sheet.' -ForegroundColor DarkGray + try { + while ($true) { + Start-Sleep -Seconds 1 + if ($ViteProc.HasExited) { break } + } + } finally { + Stop-AllChildren + } +} + +exit 0 diff --git a/windows/setup.ps1 b/windows/setup.ps1 new file mode 100644 index 0000000..3f72f38 --- /dev/null +++ b/windows/setup.ps1 @@ -0,0 +1,181 @@ +<# +.SYNOPSIS + Setup script for Sheet on Windows. +.DESCRIPTION + Checks prerequisites, validates repository root, verifies toolchains, + installs workspace dependencies via Bun preserving bun.lock, and embeds database migrations. +.PARAMETER SkipInstall + Skip `bun install` and only verify the toolchain and embed migrations. +#> + +[CmdletBinding()] +param( + [switch]$SkipInstall +) + +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version Latest + +Write-Host '========================================' -ForegroundColor Cyan +Write-Host ' Sheet for Windows - Setup Check ' -ForegroundColor Cyan +Write-Host '========================================' -ForegroundColor Cyan +Write-Host '' + +# 1. Verify Repository Root +$RepoRoot = $PSScriptRoot +if ((Split-Path -Leaf $RepoRoot) -eq 'windows') { + $RepoRoot = Split-Path -Parent $RepoRoot +} + +$PackageJsonPath = Join-Path $RepoRoot 'package.json' +if (-not (Test-Path -LiteralPath $PackageJsonPath)) { + Write-Host "[Error] Run this from inside the Sheet repository; $PackageJsonPath was not found." -ForegroundColor Red + exit 1 +} + +try { + $PackageData = Get-Content -LiteralPath $PackageJsonPath -Raw | ConvertFrom-Json +} catch { + Write-Host "[Error] Could not read $PackageJsonPath as JSON: $_" -ForegroundColor Red + exit 1 +} + +$PackageName = if ($PackageData.PSObject.Properties['name']) { $PackageData.name } else { $null } +if ($PackageName -ne 'sheet') { + Write-Host "[Error] package.json does not look like the Sheet repository (found name '$PackageName')." -ForegroundColor Red + exit 1 +} + +Write-Host '[OK] Repository root verified at: ' -NoNewline -ForegroundColor Green +Write-Host $RepoRoot + +# 2. Locate Bun Runtime +$BunExe = $null +if (Get-Command 'bun.exe' -ErrorAction SilentlyContinue) { + $BunExe = (Get-Command 'bun.exe').Source +} elseif (Get-Command 'bun' -ErrorAction SilentlyContinue) { + $BunExe = (Get-Command 'bun').Source +} else { + $DefaultBunPath = Join-Path $env:USERPROFILE '.bun\bin\bun.exe' + if (Test-Path -LiteralPath $DefaultBunPath) { + $BunExe = $DefaultBunPath + } +} + +if (-not $BunExe) { + Write-Host '[!] Bun is required but was not found on your system.' -ForegroundColor Red + Write-Host ' Install Bun for Windows by running in PowerShell:' -ForegroundColor Yellow + Write-Host ' powershell -c "irm bun.sh/install.ps1 | iex"' -ForegroundColor Yellow + exit 1 +} + +$BunVersion = (& $BunExe --version).Trim() +Write-Host '[OK] Bun found: ' -NoNewline -ForegroundColor Green +Write-Host "$BunExe (v$BunVersion)" + +# The workspace lockfile and `bun:sqlite` usage need Bun 1.3 or newer. +$BunSemver = $null +if ($BunVersion -match '^(\d+)\.(\d+)\.(\d+)') { + $BunSemver = [version]"$($Matches[1]).$($Matches[2]).$($Matches[3])" +} +if ($BunSemver -and $BunSemver -lt [version]'1.3.0') { + Write-Host "[!] Bun $BunVersion is too old; Sheet needs 1.3.0 or newer." -ForegroundColor Red + Write-Host ' Update with: bun upgrade' -ForegroundColor Yellow + exit 1 +} + +# 3. Check Node.js +if (Get-Command 'node' -ErrorAction SilentlyContinue) { + $NodeVersion = & node --version + Write-Host '[OK] Node.js found: ' -NoNewline -ForegroundColor Green + Write-Host $NodeVersion +} else { + Write-Host '[info] Node.js not found in PATH (Bun runs the workspace scripts).' -ForegroundColor DarkGray +} + +# 4. Check Web Browsers (Chrome / Edge) +$ChromePaths = @( + "$env:ProgramFiles\Google\Chrome\Application\chrome.exe", + "${env:ProgramFiles(x86)}\Google\Chrome\Application\chrome.exe", + "$env:LOCALAPPDATA\Google\Chrome\Application\chrome.exe", + "${env:ProgramFiles(x86)}\Microsoft\Edge\Application\msedge.exe", + "$env:ProgramFiles\Microsoft\Edge\Application\msedge.exe" +) | Where-Object { $_ -and (Test-Path -LiteralPath $_) } + +$FoundBrowser = $null +foreach ($Path in $ChromePaths) { + if (Test-Path -LiteralPath $Path) { + $FoundBrowser = $Path + break + } +} + +if ($FoundBrowser) { + Write-Host '[OK] Chromium-based browser found: ' -NoNewline -ForegroundColor Green + Write-Host $FoundBrowser +} else { + Write-Host '[!] No standard Chrome or Edge found. Set PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH if needed.' -ForegroundColor Yellow +} + +# 5. Check Rust and Tauri prerequisites (optional; only for the native window) +$HasCargo = $null -ne (Get-Command 'cargo.exe' -ErrorAction SilentlyContinue) +if ($HasCargo) { + $CargoVersion = & cargo --version + Write-Host '[OK] Rust/Cargo found: ' -NoNewline -ForegroundColor Green + Write-Host $CargoVersion + Write-Host ' Native Tauri builds also need the MSVC C++ build tools and WebView2:' -ForegroundColor DarkGray + Write-Host ' https://tauri.app/start/prerequisites/' -ForegroundColor DarkGray +} else { + Write-Host '[info] Rust/Cargo not detected.' -ForegroundColor Yellow + Write-Host ' Web development mode (.\windows\run.ps1 -Web) works without Rust.' -ForegroundColor Cyan + Write-Host ' For the native window, install Rust (https://rustup.rs) plus the' -ForegroundColor DarkGray + Write-Host ' "Desktop development with C++" workload from Visual Studio Build Tools.' -ForegroundColor DarkGray +} + +# 6. Install Dependencies +if (-not $SkipInstall) { + Write-Host '' + Write-Host '[setup] Installing workspace dependencies via Bun...' -ForegroundColor Cyan + Push-Location $RepoRoot + try { + & $BunExe install --frozen-lockfile + if ($LASTEXITCODE -ne 0) { + Write-Host "[Error] bun install failed with exit code $LASTEXITCODE" -ForegroundColor Red + Write-Host ' Check the error above; bun.lock is kept as-is.' -ForegroundColor Yellow + exit $LASTEXITCODE + } + Write-Host '[OK] Dependencies installed successfully.' -ForegroundColor Green + } finally { + Pop-Location + } +} + +# 7. Embed Migrations +Write-Host '' +Write-Host '[setup] Embedding database migrations...' -ForegroundColor Cyan +Push-Location $RepoRoot +try { + & $BunExe run --cwd packages/db embed + if ($LASTEXITCODE -ne 0) { + Write-Host "[Error] Database migration embed failed with exit code $LASTEXITCODE" -ForegroundColor Red + Write-Host ' The compiled server would start without migrations; fix the error above.' -ForegroundColor Yellow + exit $LASTEXITCODE + } + Write-Host '[OK] Migrations embedded.' -ForegroundColor Green +} finally { + Pop-Location +} + +Write-Host '' +Write-Host '========================================' -ForegroundColor Green +Write-Host ' Sheet Windows Setup Complete! ' -ForegroundColor Green +Write-Host '========================================' -ForegroundColor Green +Write-Host '' +Write-Host 'To start developing:' -ForegroundColor Cyan +Write-Host ' .\windows\run.ps1 -Web # Canvas in your browser (no Rust needed)' -ForegroundColor White +Write-Host ' .\windows\run.ps1 -ServerOnly # Local server and MCP endpoint on :4100' -ForegroundColor White +if ($HasCargo) { + Write-Host ' .\windows\run.ps1 -Desktop # Native Tauri window' -ForegroundColor White +} +Write-Host '' +exit 0 diff --git a/windows/src/platform-adapter.ts b/windows/src/platform-adapter.ts new file mode 100644 index 0000000..3d6f6a6 --- /dev/null +++ b/windows/src/platform-adapter.ts @@ -0,0 +1,132 @@ +import { existsSync } from 'node:fs' +import { createServer } from 'node:net' +import { homedir, platform } from 'node:os' +import { join, resolve, win32 } from 'node:path' + +/** + * Windows platform adapter for Sheet. + * Provides safe path normalization, application data path resolution, + * Chromium/Edge detection, and loopback port helpers. + * + * Path parsing uses `win32` explicitly so the behaviour is identical when the + * helpers are exercised from a non-Windows host (tests, CI). + */ + +export function isWindows(): boolean { + return platform() === 'win32' +} + +/** + * Resolves the persistent application data directory on Windows. + * Follows the same contract as Sheet's Rust desktop host: + * %APPDATA%\Sheet in production + * %APPDATA%\Sheet Dev in development / debug mode + * Overridable with SHEET_DATA_DIR. + */ +export function resolveAppDataDir(options: { isDev?: boolean; customDir?: string } = {}): string { + const customDir = options.customDir?.trim() + if (customDir) return resolve(customDir) + const fromEnv = process.env.SHEET_DATA_DIR?.trim() + if (fromEnv) return resolve(fromEnv) + + const base = process.env.APPDATA || join(homedir(), 'AppData', 'Roaming') + const folderName = options.isDev ? 'Sheet Dev' : 'Sheet' + return join(base, folderName) +} + +/** + * Normalizes filesystem paths on Windows, handling drive letters, + * forward/backward slashes, and spaces safely. + */ +export function normalizeWindowsPath(inputPath: string): string { + const trimmed = inputPath.trim() + if (!trimmed) return '' + return win32.normalize(win32.isAbsolute(trimmed) ? trimmed : win32.resolve(trimmed)) +} + +/** + * Converts a Windows filesystem path to a valid file:// URL, including UNC + * shares and drive letters. `pathToFileURL` cannot do this off Windows: it + * reads `C:\...` as a relative path. + */ +export function windowsPathToFileUrl(inputPath: string): string { + const normalized = normalizeWindowsPath(inputPath) + if (!normalized) throw new Error('Cannot convert an empty path to a file URL') + + if (normalized.startsWith('\\\\')) { + const [host, ...rest] = normalized.slice(2).split('\\') + return `file://${encodeURIComponent(host ?? '')}/${rest.map(encodeURIComponent).join('/')}` + } + + const segments = normalized.replace(/\\/g, '/').split('/') + const encoded = segments + .map((segment, index) => (/^[A-Za-z]:$/.test(segment) && index === 0 ? segment : encodeURIComponent(segment))) + .join('/') + return `file:///${encoded.replace(/^\/+/, '')}` +} + +/** + * Discovers available Chromium-based browser binaries on Windows. + * Prioritizes Google Chrome, followed by Microsoft Edge. + */ +export function findWindowsChromium(): string | null { + const custom = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH?.trim() || process.env.CHROMIUM_PATH?.trim() + if (custom && existsSync(custom)) return custom + + const programFiles = process.env.PROGRAMFILES || 'C:\\Program Files' + const programFilesX86 = process.env['PROGRAMFILES(X86)'] || 'C:\\Program Files (x86)' + const localAppData = process.env.LOCALAPPDATA || join(homedir(), 'AppData', 'Local') + + const candidates = [ + join(programFiles, 'Google', 'Chrome', 'Application', 'chrome.exe'), + join(programFilesX86, 'Google', 'Chrome', 'Application', 'chrome.exe'), + join(localAppData, 'Google', 'Chrome', 'Application', 'chrome.exe'), + join(programFilesX86, 'Microsoft', 'Edge', 'Application', 'msedge.exe'), + join(programFiles, 'Microsoft', 'Edge', 'Application', 'msedge.exe'), + ] + + for (const candidate of candidates) { + if (existsSync(candidate)) { + return candidate + } + } + + return null +} + +type BindOutcome = 'free' | 'in-use' | 'unavailable' + +/** + * Tries to bind the port on loopback. `EADDRINUSE` means something is already + * listening; any other bind error means the port cannot be used, which is + * different from being occupied. + */ +function bindLoopback(port: number): Promise { + return new Promise((settle) => { + const server = createServer() + server.once('error', (error: NodeJS.ErrnoException) => { + settle(error.code === 'EADDRINUSE' ? 'in-use' : 'unavailable') + }) + server.once('listening', () => { + server.close(() => settle('free')) + }) + server.listen(port, '127.0.0.1') + }) +} + +/** + * Tests if a given TCP port is already listening on loopback (127.0.0.1). + */ +export async function isPortInUse(port: number): Promise { + return (await bindLoopback(port)) === 'in-use' +} + +/** + * Discovers a free TCP port starting from the requested port. + */ +export async function findFreePort(startPort = 4100): Promise { + for (let port = startPort; port <= 65535; port += 1) { + if ((await bindLoopback(port)) === 'free') return port + } + throw new Error(`No free TCP port on 127.0.0.1 at or above ${startPort}`) +} diff --git a/windows/tests/windows-platform.test.ts b/windows/tests/windows-platform.test.ts new file mode 100644 index 0000000..7dce944 --- /dev/null +++ b/windows/tests/windows-platform.test.ts @@ -0,0 +1,151 @@ +import { describe, expect, it, afterEach, beforeEach, vi } from 'vitest' +import { existsSync, readFileSync } from 'node:fs' +import { mkdtemp, rm } from 'node:fs/promises' +import { join } from 'node:path' +import { tmpdir } from 'node:os' +import { Database } from 'bun:sqlite' +import { writeAtomic } from '../../apps/mcp/src/agent-install' +import { + findFreePort, + findWindowsChromium, + isPortInUse, + isWindows, + normalizeWindowsPath, + resolveAppDataDir, + windowsPathToFileUrl, +} from '../src/platform-adapter' + +let dir = '' + +beforeEach(async () => { + dir = await mkdtemp(join(tmpdir(), 'sheet-windows-test-')) +}) + +afterEach(async () => { + vi.unstubAllEnvs() + await rm(dir, { recursive: true, force: true }) +}) + +describe('Windows Platform Adapter', () => { + it('correctly detects Windows platform', () => { + expect(isWindows()).toBe(process.platform === 'win32') + }) + + describe('Path handling', () => { + it('normalizes Windows paths with forward and backward slashes', () => { + const input = 'C:/Users/TestUser/AppData/Roaming/Sheet' + const normalized = normalizeWindowsPath(input) + expect(normalized).toBe('C:\\Users\\TestUser\\AppData\\Roaming\\Sheet') + }) + + it('handles paths with spaces safely', () => { + const input = 'C:\\Program Files\\Sheet Design App\\sheet.db' + const normalized = normalizeWindowsPath(input) + expect(normalized).toBe('C:\\Program Files\\Sheet Design App\\sheet.db') + }) + + it('converts Windows paths to valid file:// URLs', () => { + const input = 'C:\\Program Files\\Sheet\\assets\\logo.png' + expect(windowsPathToFileUrl(input)).toBe('file:///C:/Program%20Files/Sheet/assets/logo.png') + }) + + it('converts UNC paths to a host-rooted file URL', () => { + expect(windowsPathToFileUrl('\\\\server\\share\\Sheet\\sheet.db')).toBe( + 'file://server/share/Sheet/sheet.db', + ) + }) + }) + + describe('Application Data Directory resolution', () => { + it('resolves production AppData path as %APPDATA%\\Sheet', () => { + vi.stubEnv('SHEET_DATA_DIR', '') + expect(resolveAppDataDir({ isDev: false }).endsWith('Sheet')).toBe(true) + }) + + it('resolves development AppData path as %APPDATA%\\Sheet Dev', () => { + vi.stubEnv('SHEET_DATA_DIR', '') + expect(resolveAppDataDir({ isDev: true }).endsWith('Sheet Dev')).toBe(true) + }) + + it('respects SHEET_DATA_DIR override', () => { + const custom = join(dir, 'custom-sheet-test-dir') + vi.stubEnv('SHEET_DATA_DIR', custom) + expect(resolveAppDataDir()).toBe(custom) + }) + + it('prefers an explicit custom directory over the environment', () => { + vi.stubEnv('SHEET_DATA_DIR', join(dir, 'from-env')) + const custom = join(dir, 'from-option') + expect(resolveAppDataDir({ customDir: custom })).toBe(custom) + }) + }) + + describe('Chromium discovery on Windows', () => { + it.skipIf(process.platform !== 'win32')( + 'discovers installed Chrome or Edge executable when available', + () => { + const chromium = findWindowsChromium() + if (!chromium) return + expect(existsSync(chromium)).toBe(true) + expect(chromium.toLowerCase().endsWith('.exe')).toBe(true) + }, + ) + }) + + describe('Atomic file writes', () => { + it('writes and overwrites files without leaving a temporary file behind', async () => { + const testFile = join(dir, 'state.json') + const payload1 = JSON.stringify({ version: '1.0.0', state: 'initial' }) + const payload2 = JSON.stringify({ version: '1.0.1', state: 'updated' }) + + await writeAtomic(testFile, payload1) + expect(readFileSync(testFile, 'utf8')).toBe(payload1) + + // Overwrite immediately (tests Windows overwrite resilience) + await writeAtomic(testFile, payload2) + expect(readFileSync(testFile, 'utf8')).toBe(payload2) + }) + }) + + describe('Port utilities', () => { + it('correctly discovers a free loopback port', async () => { + const port = await findFreePort(49152) + expect(port).toBeGreaterThanOrEqual(49152) + expect(await isPortInUse(port)).toBe(false) + }) + }) + + describe('Windows SQLite Engine', () => { + it('creates database file and executes WAL transactions cleanly on Windows', () => { + const dbPath = join(dir, 'sheet-test-sqlite.db') + const sqlite = new Database(dbPath, { create: true }) + + try { + sqlite.exec('PRAGMA journal_mode = WAL') + sqlite.exec('PRAGMA foreign_keys = ON') + + sqlite.exec(` + CREATE TABLE IF NOT EXISTS test_doc ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + data TEXT NOT NULL, + updated_at NUMERIC NOT NULL + ) + `) + + const insert = sqlite.prepare('INSERT INTO test_doc (id, name, data, updated_at) VALUES (?, ?, ?, ?)') + insert.run('doc-1', 'Windows Board', '{"nodes":{}}', Date.now()) + + const query = sqlite.query<{ id: string; name: string }, [string]>('SELECT id, name FROM test_doc WHERE id = ?') + const row = query.get('doc-1') + + expect(row).toBeDefined() + expect(row?.name).toBe('Windows Board') + } finally { + // WAL leaves `-wal` and `-shm` beside the database; closing releases them. + sqlite.close() + } + expect(existsSync(dbPath)).toBe(true) + }) + }) +})