Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 68 additions & 3 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -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:
Expand Down Expand Up @@ -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 }}"
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
3 changes: 2 additions & 1 deletion apps/desktop/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
2 changes: 1 addition & 1 deletion apps/desktop/src-tauri/tauri.conf.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
},
"bundle": {
"active": true,
"targets": ["app", "dmg"],
"targets": "all",
"createUpdaterArtifacts": true,
"macOS": {
"signingIdentity": "-",
Expand Down
113 changes: 60 additions & 53 deletions apps/desktop/vite.config.ts
Original file line number Diff line number Diff line change
@@ -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))

Expand All @@ -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()
}
Expand All @@ -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 },
},
},
}
})
59 changes: 59 additions & 0 deletions apps/mcp/src/agent-install.test.ts
Original file line number Diff line number Diff line change
@@ -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<typeof import('node:fs/promises')>()
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'])
})
})
54 changes: 49 additions & 5 deletions apps/mcp/src/agent-install.ts
Original file line number Diff line number Diff line change
@@ -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'

Expand Down Expand Up @@ -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(() => {})
}
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
}

async function installJson(target: JsonTarget): Promise<InstallResult> {
Expand Down
Loading