Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
feat(desktop): run each worktree's npm run dev beside the main Codync Dev
leepokaia00ec3dbceab
diff --git a/AGENTS.md b/AGENTS.mdindex 1b571647..01e991ff 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -20,7 +20,7 @@ Run from the repository root unless a command changes directories:- `xcodegen generate --spec apps/project.yml`: regenerate `apps/Codync.xcodeproj` after editing `apps/project.yml`; never edit `project.pbxproj` directly.- Use Xcode’s `iOS Dev` scheme for development and `iOS` for production; see [Dev app isolation](docs/guides/dev-app.md).-- `cd apps/desktop && npm ci && npm run dev`: run the desktop app while developing and for its e2e check (renderer reloads on save, restart after `src/main` or preload changes; unpackaged, unsigned). After a host change run `node tools/native-host.mjs dev` there first: `npm run dev` prefers that build over `host/target/debug`. Package `npm run dist:mac:dev` (about 45 s) only for what an unpackaged run lacks (bundled host install, Codync Screen / computer use, system permissions); `dist:*:main` only to check the production app. `npm run typecheck && npm test` for its CI checks.+- `cd apps/desktop && npm ci && npm run dev`: run the desktop app while developing and for its e2e check (renderer reloads on save, restart after `src/main` or preload changes; unpackaged, unsigned). In a linked worktree it runs a [sandbox](docs/guides/dev-app.md#worktree-sandboxes) beside the main checkout's Codync Dev; `--sandbox` does the same from the main checkout. In the main checkout, after a host change run `node tools/native-host.mjs dev` there first: `npm run dev` prefers that build over `host/target/debug`. Package `npm run dist:mac:dev` (about 45 s) only for what an unpackaged run lacks (bundled host install, Codync Screen / computer use, system permissions); `dist:*:main` only to check the production app. `npm run typecheck && npm test` for its CI checks.- `cd host && cargo build`: build the host; `cargo run -- serve` starts it in the foreground.- `cd host && cargo fmt --check && cargo clippy --all-targets -- -D warnings && cargo test`: run host CI checks.- `cd apps/android && ./gradlew :core:test :app:testDebugUnitTest :app:assembleDebug :app:lintDebug` (JDK 21, Android SDK 37): Android checks; `adb install -r app/build/outputs/apk/debug/app-debug.apk` installs Codync Dev.diff --git a/CLAUDE.md b/CLAUDE.mdindex aab3a6bb..4f8e443d 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -64,18 +64,11 @@ Keep only the latest build: in this checkout, Apple builds go to `build/dd` onlyAfter every change, test it end to end on the real apps, not just builds and unit tests: install the new build (old one stopped first) and walk through the changed flow. Drive the desktop app with Computer Use, the iPhone app on an iOS Simulator through Device Hub (Xcode's `DeviceHub.app`), and the Android app on an emulator (`adb`). Report any check that could not run and why.- **Minimal e2e** (default): only the platform of the computer you test on (on the Mac: macOS).- **Full e2e** (large changes: platform code, packaging, the desktop main process; or when asked): macOS, Linux (Lima `codync-linux`) and Windows (UTM, [Windows testing](docs/guides/windows-testing.md)). A platform whose VM isn't installed is skipped and reported, not set up.-- **Desktop build to use**: develop and e2e with `npm run dev` in `apps/desktop` (renderer reloads on save, restart it after `src/main` or preload changes; nothing packaged or signed). After a host change run `node tools/native-host.mjs dev` there first: `npm run dev` prefers that build over `host/target/debug`. Package `npm run dist:mac:dev` (about 45 s) only for what an unpackaged run lacks: the bundled host install, Codync Screen / computer use, system permissions. `dist:*:main` (universal, timestamped, minutes) only to check the production app.--## Project generation--- `apps/project.yml` + `xcodegen generate --spec apps/project.yml` produce `apps/Codync.xcodeproj`. Edit `project.yml`, not the pbxproj.--## App Store Upload--- Xcode Cloud archives the `iOS` scheme on every `v*` tag and uploads it to App Store Connect with its own build number, then the `Submit iOS` workflow submits it to App Review for the App Store; don't upload from the local machine or edit `CURRENT_PROJECT_VERSION` for it. Details: [development guide](docs/guides/development.md#ios-releases-xcode-cloud).+- **Desktop build to use**: develop and e2e with `npm run dev` in `apps/desktop` (renderer reloads on save, restart it after `src/main` or preload changes; nothing packaged or signed). In a linked worktree it runs a [sandbox](docs/guides/dev-app.md#worktree-sandboxes) beside the main checkout's Codync Dev (own host build, port and data); `--sandbox` does the same from the main checkout when another session's Codync Dev is running. In the main checkout, after a host change run `node tools/native-host.mjs dev` there first: `npm run dev` prefers that build over `host/target/debug`. Package `npm run dist:mac:dev` (about 45 s) only for what an unpackaged run lacks: the bundled host install, Codync Screen / computer use, system permissions. `dist:*:main` (universal, timestamped, minutes) only to check the production app.## Versioning+- Xcode Cloud archives the `iOS` scheme on every `v*` tag and uploads it to App Store Connect with its own build number, then the `Submit iOS` workflow submits it to App Review for the App Store; don't upload from the local machine or edit `CURRENT_PROJECT_VERSION` for it. Details: [development guide](docs/guides/development.md#ios-releases-xcode-cloud).- Phone ↔ host compatibility: each side names the oldest version of the other it works with (`minApp` in the host's `hello`, `minHost` in each client). Additive changes need nothing; a rename/removal raises `minApp` in the same release, and hosts hold that release until the App Store has the iPhone app: [docs/reference/compatibility.md](docs/reference/compatibility.md)- **Every source change ships as a release.** A version bump on `main` is the only release trigger (Auto Tag → desktop app for macOS, Linux and Windows, host, Homebrew, in-app update), so any change to shipped code (`apps/`, `host/`, `packaging/`) bumps the version before it reaches `main`, without being asked. Docs, `web/`, `cloud/`, `relay/` and CI-only changes don't bump.- Pick the bump yourself: patch for fixes and small tweaks, minor for new features or protocol additions. Never bump major (stay on 2.x). One bump per merge into `main`: if `MARKETING_VERSION` is already ahead of the latest `v*` tag, leave it. A change to `host/crates/memory` also raises `codync-mem`'s own 0.x version once per release (leave it if it's already ahead of `main`'s); CI blocks a PR into `main` that forgets, and the merge publishes it to crates.io ([codync-mem releases](docs/guides/development.md#codync-mem-releases)).@@ -85,6 +78,8 @@ After every change, test it end to end on the real apps, not just builds and uniBuild targets, folder layout, file naming and shared terms: [docs/architecture/file-structure.md](docs/architecture/file-structure.md). Follow it when adding or moving files.+`apps/project.yml` + `xcodegen generate --spec apps/project.yml` produce `apps/Codync.xcodeproj`. Edit `project.yml`, not the pbxproj.+## Several agents share `dev`- Several agents often work in this checkout on `dev` at once. When you start a task, name your session after its area (`/rename kit-markdown`, `host-voice`, …; ask the user if you can't rename yourself) so others can find you in `ListAgents`.diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 808aff36..4604910e 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -12,7 +12,7 @@"private": true,"main": "out/main/index.js","scripts": {- "dev": "node tools/account-config.mjs dev && electron-vite dev",+ "dev": "node --experimental-strip-types --disable-warning=ExperimentalWarning --disable-warning=MODULE_TYPELESS_PACKAGE_JSON tools/dev.mjs","build": "electron-vite build","build:demo": "vite build --config vite.demo.config.ts && mv ../../web/public/demo/desktop/index.html ../../web/public/demo/desktop.html","typecheck": "tsc --noEmit -p tsconfig.json",diff --git a/apps/desktop/src/main/environment.ts b/apps/desktop/src/main/environment.tsindex 62239a3b..5acecce6 100644--- a/apps/desktop/src/main/environment.ts+++ b/apps/desktop/src/main/environment.ts@@ -1,6 +1,7 @@import { readFileSync } from 'node:fs'import { join } from 'node:path'import { app } from 'electron'+import { sandboxLabel } from '../shared/dev-sandbox'import { environmentProfile } from '../shared/environment'interface BuildConfig {@@ -17,7 +18,10 @@ if (buildConfig.environment !== 'main' && buildConfig.environment !== 'dev') threxport const identity = environmentProfile(buildConfig.environment)// Before the single-instance lock, preferences, account restore or Chromium session is created.+// A development run against its own host data (`CODYNC_HOME`, a worktree's sandbox) keeps all of+// that there too, under its own name, so it runs beside the main checkout's Codync Dev.if (identity.environment === 'dev') {- app.setName(identity.name)- app.setPath('userData', join(app.getPath('appData'), identity.name))+ const sandbox = app.isPackaged ? undefined : process.env.CODYNC_HOME+ app.setName(sandbox ? sandboxLabel(identity.name, sandbox) : identity.name)+ app.setPath('userData', sandbox ? join(sandbox, 'desktop') : join(app.getPath('appData'), identity.name))}diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.tsindex 447b5556..5ea35259 100644--- a/apps/desktop/src/main/index.ts+++ b/apps/desktop/src/main/index.ts@@ -67,7 +67,7 @@ function openChat() {height: 760,minWidth: 760,minHeight: 500,- title: identity.name,+ title: app.getName(),show: false,backgroundColor: background(),titleBarStyle: isMac ? 'hidden' : 'default',@@ -141,7 +141,7 @@ function menu() {function registerIPC(tray: Tray) {registerHostProxy()ipcMain.on('app:hostPort', (e) => (e.returnValue = identity.port))- ipcMain.on('app:name', (e) => (e.returnValue = identity.name))+ ipcMain.on('app:name', (e) => (e.returnValue = app.getName()))ipcMain.on('app:scheme', (e) => (e.returnValue = identity.scheme))registerFileSaves()ipcMain.on('app:version', (e) => (e.returnValue = app.getVersion()))@@ -202,6 +202,7 @@ function registerIPC(tray: Tray) {}if (!app.requestSingleInstanceLock()) {+ if (!app.isPackaged) console.error(`${app.getName()} is already running. Quit it first, or run another copy beside it: npm run dev -- --name <name>`)app.quit()} else {registerSchemes()diff --git a/apps/desktop/src/main/ssh-command.ts b/apps/desktop/src/main/ssh-command.tsindex 77d01d9e..c1e29823 100644--- a/apps/desktop/src/main/ssh-command.ts+++ b/apps/desktop/src/main/ssh-command.ts@@ -13,11 +13,15 @@ export const remoteInfoCommand = (port: number, folder = '.codync') => {return `sh -lc 'PATH="${REMOTE_PATH}" codync-host info --json --port ${port}'`}-export const knownHostsFiles = (h: string, folder = '.codync') => [`${h}/.ssh/known_hosts`, `${h}/${folder}/ssh_known_hosts`]+/** `dir` is this app's host data folder (`~/.codync`, or a development sandbox's). */+export const knownHostsFiles = (h: string, dir = `${h}/.codync`) => [`${h}/.ssh/known_hosts`, `${dir}/ssh_known_hosts`]++/** `pkill -f` pattern for the tunnels that use `dir`'s known_hosts file: this copy's own, never another copy's. */+export const orphanTunnelPattern = (dir: string) => `^/usr/bin/ssh -N .*${dir.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}/ssh_known_hosts`/** ssh's config tokenizer splits `UserKnownHostsFile` on spaces, so each path carries literal quotes. */-export const hostKeyOptions = (h: string, folder = '.codync') => [- '-o', 'UserKnownHostsFile=' + knownHostsFiles(h, folder).map((f) => `"${f}"`).join(' '),+export const hostKeyOptions = (h: string, dir?: string) => [+ '-o', 'UserKnownHostsFile=' + knownHostsFiles(h, dir).map((f) => `"${f}"`).join(' '),'-o', 'StrictHostKeyChecking=yes',]@@ -37,19 +41,19 @@ export function resolveArguments(p: SSHProfile) {}/** The remote command is fixed; only the validated port number goes into it. */-export const infoArguments = (p: SSHProfile, h: string, folder = '.codync') => [+export const infoArguments = (p: SSHProfile, h: string, folder = '.codync', dir = `${h}/${folder}`) => ['-T', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=10', '-o', 'ForwardAgent=no', '-o', 'ForwardX11=no',- ...hostKeyOptions(h, folder), ...targetOptions(p),+ ...hostKeyOptions(h, dir), ...targetOptions(p),'--', p.host, remoteInfoCommand(p.remotePort, folder),]-export const tunnelArguments = (p: SSHProfile, localPort: number, h: string, folder = '.codync') => [+export const tunnelArguments = (p: SSHProfile, localPort: number, h: string, dir?: string) => ['-N', '-T', '-o', 'ExitOnForwardFailure=yes', '-o', 'ServerAliveInterval=15', '-o', 'ServerAliveCountMax=3',// A shared master owns the listener and lets this child exit. The app must own// its tunnel process to verify the listener and close the forward on disconnect.'-S', 'none','-o', 'ForwardAgent=no', '-o', 'ForwardX11=no', '-o', 'BatchMode=yes',- ...hostKeyOptions(h, folder),+ ...hostKeyOptions(h, dir),'-L', `127.0.0.1:${localPort}:127.0.0.1:${p.remotePort}`,...targetOptions(p), '--', p.host,]diff --git a/apps/desktop/src/main/ssh.ts b/apps/desktop/src/main/ssh.tsindex 7d5927c4..8b2c688f 100644--- a/apps/desktop/src/main/ssh.ts+++ b/apps/desktop/src/main/ssh.ts@@ -7,7 +7,8 @@ import { homedir, platform } from 'node:os'import { join } from 'node:path'import { app, dialog, ipcMain, type BrowserWindow } from 'electron'import type { SSHAttachment, SSHProfile, SSHState, SSHStatus } from '../shared/ssh'-import { infoArguments, knownHostsFiles, resolveArguments, tunnelArguments } from './ssh-command'+import { dataDir } from './host-controller'+import { infoArguments, knownHostsFiles, orphanTunnelPattern, resolveArguments, tunnelArguments } from './ssh-command'// SSH computers: profiles, host key checks and one// OpenSSH tunnel per connected profile. Arguments are always an argv array, never a shell string.@@ -134,7 +135,7 @@ function run(bin: string, args: string[], input?: string): Promise<Result> {}/** Tunnels a crashed or force-quit Codync left running: only Codync's tunnels carry this known_hosts file. */-const killOrphanTunnels = () => run('/usr/bin/pkill', ['-f', '--', `^/usr/bin/ssh -N .*\\${identity.dataFolder}/ssh_known_hosts`])+const killOrphanTunnels = () => run('/usr/bin/pkill', ['-f', '--', orphanTunnelPattern(dataDir)])/** Binds port 0 on loopback to learn a free port. */function freeLocalPort(): Promise<number | null> {@@ -302,9 +303,8 @@ class SSHComputers {const lines = this.pendingKeys.get(id)if (this.status.get(id)?.kind !== 'confirmHostKey' || !lines) returntry {- const dir = join(home, identity.dataFolder)- await fs.mkdir(dir, { recursive: true, mode: 0o700 })- await fs.appendFile(join(dir, 'ssh_known_hosts'), lines.join('\n') + '\n', { mode: 0o600 })+ await fs.mkdir(dataDir, { recursive: true, mode: 0o700 })+ await fs.appendFile(join(dataDir, 'ssh_known_hosts'), lines.join('\n') + '\n', { mode: 0o600 })} catch (e) {return this.setStatus(id, { kind: 'failed', message: `Couldn't save the host key: ${e instanceof Error ? e.message : String(e)}` })}@@ -370,7 +370,7 @@ class SSHComputers {}this.setStatus(id, { kind: 'connecting', step: 'Signing in…' })- const result = await run(SSH, infoArguments(profile, home, identity.dataFolder))+ const result = await run(SSH, infoArguments(profile, home, identity.dataFolder, dataDir))if (token.cancelled) return idleif (result.status === 255) {if (authRefused(result.stderr)) return stop({ kind: 'failed', message: signInRefused(profile) })@@ -459,7 +459,7 @@ class SSHComputers {private async recordedKeys(name: string, certAuthorities = true) {const keys = new Set<string>()- for (const file of knownHostsFiles(home, identity.dataFolder)) {+ for (const file of knownHostsFiles(home, dataDir)) {if (!existsSync(file)) continueconst found = await run(KEYGEN, ['-F', name, '-f', file])if (found.status === 0) for (const k of hostKeys(found.stdout, certAuthorities)) keys.add(k)@@ -473,7 +473,7 @@ class SSHComputers {let done = falselet child: ChildProcesstry {- child = spawn(SSH, tunnelArguments(profile, localPort, home, identity.dataFolder), { stdio: ['ignore', 'ignore', 'pipe'] })+ child = spawn(SSH, tunnelArguments(profile, localPort, home, dataDir), { stdio: ['ignore', 'ignore', 'pipe'] })} catch {return null}diff --git a/apps/desktop/src/shared/dev-sandbox.test.ts b/apps/desktop/src/shared/dev-sandbox.test.tsnew file mode 100644index 00000000..972b5a4e--- /dev/null+++ b/apps/desktop/src/shared/dev-sandbox.test.ts@@ -0,0 +1,16 @@+import assert from 'node:assert/strict'+import { test } from 'node:test'+import { sandboxLabel, sandboxName, sandboxPorts } from './dev-sandbox.ts'++test('sandbox ports skip the ones other sandboxes hold and never reach Codync or Codync Dev', () => {+ const ports = sandboxPorts([19300, 19302])+ assert.deepEqual(ports.slice(0, 2), [19301, 19303])+ assert.equal(ports.length, 98)+ assert.ok(ports.every((port) => port >= 19300 && port <= 19399))+})++test('a sandbox is named after its worktree folder', () => {+ assert.equal(sandboxName('feat details/panel'), 'feat-details-panel')+ assert.equal(sandboxLabel('Codync Dev', '/Users/me/.codync-dev-feat-x'), 'Codync Dev (feat-x)')+ assert.equal(sandboxLabel('Codync Dev', 'C:\\Users\\me\\box\\'), 'Codync Dev (box)')+})diff --git a/apps/desktop/src/shared/dev-sandbox.ts b/apps/desktop/src/shared/dev-sandbox.tsnew file mode 100644index 00000000..c8ec4c44--- /dev/null+++ b/apps/desktop/src/shared/dev-sandbox.ts@@ -0,0 +1,19 @@+// `npm run dev` in a linked worktree runs a sandbox beside the main checkout's Codync Dev: its own+// host data (`~/.codync-dev-<name>`), port, app data and host process (tools/dev.mjs).++export const SANDBOX_PREFIX = '.codync-dev-'++/** A worktree folder name made safe for a data folder and a window title. */+export const sandboxName = (folder: string) => folder.replace(/[^A-Za-z0-9._-]+/g, '-')++/** Ports for sandboxes, lowest first, without the ones other sandboxes hold; 19222/19223 stay with Codync and Codync Dev. */+export function sandboxPorts(claimed: Iterable<number>): number[] {+ const taken = new Set(claimed)+ return Array.from({ length: 100 }, (_, i) => 19300 + i).filter((port) => !taken.has(port))+}++/** `Codync Dev (feat-x)` for `~/.codync-dev-feat-x`; any other host data folder shows by its name. */+export function sandboxLabel(name: string, home: string) {+ const folder = home.split(/[\\/]/).filter(Boolean).pop() ?? home+ return `${name} (${folder.startsWith(SANDBOX_PREFIX) ? folder.slice(SANDBOX_PREFIX.length) : folder})`+}diff --git a/apps/desktop/src/shared/ssh-command.test.ts b/apps/desktop/src/shared/ssh-command.test.tsindex e9e25e1a..c064e9b2 100644--- a/apps/desktop/src/shared/ssh-command.test.ts+++ b/apps/desktop/src/shared/ssh-command.test.ts@@ -4,7 +4,7 @@ import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fimport { tmpdir } from 'node:os'import { join } from 'node:path'import { test } from 'node:test'-import { infoArguments, remoteInfoCommand, resolveArguments, tunnelArguments } from '../main/ssh-command.ts'+import { infoArguments, orphanTunnelPattern, remoteInfoCommand, resolveArguments, tunnelArguments } from '../main/ssh-command.ts'import type { SSHProfile } from './ssh.ts'// Remap absolute installation directories into an isolated filesystem fixture. Run the@@ -174,3 +174,12 @@ for (const [preferred, fallback] of [assert.equal(result.lines[0], join(result.root, preferred, 'codync-host'))})}++test('each copy of the app clears only its own leftover tunnels', () => {+ const tunnel = (dir: string) => ['/usr/bin/ssh', ...tunnelArguments(profile, 19333, '/Users/me', dir)].join(' ')+ const dev = new RegExp(orphanTunnelPattern('/Users/me/.codync-dev'))+ assert.match(tunnel('/Users/me/.codync-dev'), dev)+ assert.doesNotMatch(tunnel('/Users/me/.codync-dev-feat-x'), dev)+ assert.doesNotMatch(tunnel('/Users/me/xcodync-dev'), dev)+ assert.doesNotMatch(tunnel('/Users/me/.codync-dev'), new RegExp(orphanTunnelPattern('/Users/me/.codync-dev-feat-x')))+})diff --git a/apps/desktop/tools/dev.mjs b/apps/desktop/tools/dev.mjsnew file mode 100644index 00000000..a468ff25--- /dev/null+++ b/apps/desktop/tools/dev.mjs@@ -0,0 +1,177 @@+// `npm run dev`. The main checkout runs the default Codync Dev (its background host on 19223,+// ~/.codync-dev). A linked worktree runs a sandbox beside it instead: host data in+// ~/.codync-dev-<name>, a port kept in that folder's sandbox.json, its own app data, and a host+// this run builds, starts and stops. Flags (`npm run dev -- --list`): --shared takes the default+// Codync Dev from a worktree, --sandbox runs a sandbox from the main checkout, --name <name> runs+// the sandbox of that name, --cloud lets the sandbox host use the dev cloud, --cdp opens the+// DevTools protocol on the sandbox port + 10000, --list shows every sandbox, --prune deletes the+// ones whose worktree is gone.+import { spawn, spawnSync } from 'node:child_process'+import { existsSync, mkdirSync, openSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'+import { createServer } from 'node:net'+import { homedir } from 'node:os'+import { basename, dirname, join, resolve } from 'node:path'+import { setTimeout as delay } from 'node:timers/promises'+import { fileURLToPath } from 'node:url'+import { parseArgs } from 'node:util'+import { SANDBOX_PREFIX, sandboxName, sandboxPorts } from '../src/shared/dev-sandbox.ts'++const desktop = resolve(dirname(fileURLToPath(import.meta.url)), '..')+const root = resolve(desktop, '../..')+const windows = process.platform === 'win32'+const { values: flags } = parseArgs({+ options: {+ shared: { type: 'boolean' }, sandbox: { type: 'boolean' }, name: { type: 'string' },+ cloud: { type: 'boolean' }, cdp: { type: 'boolean' }, list: { type: 'boolean' }, prune: { type: 'boolean' },+ },+})++function fail(message) {+ console.error(message)+ process.exit(1)+}++function run(cmd, args, env = process.env) {+ if (spawnSync(cmd, args, { stdio: 'inherit', env }).status !== 0) fail(`${basename(cmd)} ${args.join(' ')} failed.`)+}++/** Every sandbox on this computer: a `~/.codync-dev-<name>` folder with a sandbox.json. */+function sandboxes() {+ return readdirSync(homedir())+ .filter((folder) => folder.startsWith(SANDBOX_PREFIX) && existsSync(join(homedir(), folder, 'sandbox.json')))+ .map((folder) => {+ const home = join(homedir(), folder)+ return { name: folder.slice(SANDBOX_PREFIX.length), home, ...JSON.parse(readFileSync(join(home, 'sandbox.json'), 'utf8')) }+ })+}++const answers = (port) => fetch(`http://127.0.0.1:${port}/health`, { signal: AbortSignal.timeout(1000) }).then((r) => r.ok, () => false)++/** The host listens on every IPv4 interface, so that is where the port must be free (`::` and loopback can bind beside it). */+const bindable = (port) => new Promise((done) => {+ const server = createServer().once('error', () => done(false))+ server.listen(port, '0.0.0.0', () => server.close(() => done(true)))+})+const isFree = async (port) => (await bindable(port)) && !(await answers(port))++async function firstFreePort() {+ for (const port of sandboxPorts(sandboxes().map((s) => s.port))) if (await isFree(port)) return port+ return fail('Every sandbox port (19300-19399) is taken. Delete old sandboxes: npm run dev -- --prune')+}++/** The host this worktree's code builds (or `CODYNC_HOST_BIN`), compiled for Codync Dev. */+function buildHost() {+ if (process.env.CODYNC_HOST_BIN) return process.env.CODYNC_HOST_BIN+ if (process.platform === 'linux') {+ run('cargo', ['build', '--manifest-path', join(root, 'host/Cargo.toml')], { ...process.env, CODYNC_ENV: 'dev' })+ return join(process.env.CARGO_TARGET_DIR ?? join(root, 'host/target'), 'debug/codync-host')+ }+ run(process.execPath, [join(desktop, 'tools/native-host.mjs'), 'dev'])+ return join(desktop, 'build/native', windows ? 'codync-host.exe' : 'codync-host')+}++/** electron-vite leaves Electron running when it stops alone, so the app gets its own process group and stops as a whole. */+function startApp(env = process.env) {+ const child = spawn('electron-vite', ['dev'], { env, stdio: 'inherit', shell: windows, detached: !windows })+ const stop = () => {+ if (windows) return void spawnSync('taskkill', ['/pid', String(child.pid), '/t', '/f'])+ try {+ process.kill(-child.pid, 'SIGTERM')+ } catch (e) {+ if (e.code !== 'ESRCH') throw e+ }+ }+ return { child, stop }+}++async function listAndPrune() {+ for (const s of sandboxes()) {+ const running = await answers(s.port)+ const gone = !existsSync(s.worktree)+ if (flags.prune && gone && !running) {+ rmSync(s.home, { recursive: true, force: true })+ console.log(`Deleted the sandbox ${s.name} (${s.home})`)+ } else if (flags.list) {+ console.log(`${s.name.padEnd(28)} ${String(s.port).padEnd(6)} ${(running ? 'running' : 'stopped').padEnd(8)} ${s.worktree}${gone ? ' (gone)' : ''}`)+ }+ }+}++async function sandbox() {+ const name = sandboxName(flags.name ?? basename(root))+ const home = join(homedir(), SANDBOX_PREFIX + name)+ const recordFile = join(home, 'sandbox.json')+ const record = existsSync(recordFile) ? JSON.parse(readFileSync(recordFile, 'utf8')) : null+ if (record && resolve(record.worktree) !== root) fail(`The sandbox ${name} belongs to ${record.worktree}. Pick another one: npm run dev -- --name <name>`)+ const port = record?.port ?? (await firstFreePort())+ if (!(await isFree(port))) {+ fail(`Port ${port} of the sandbox ${name} is in use: another npm run dev runs this sandbox, or an earlier run left its host running. Stop that process, or run another sandbox with --name <name>.`)+ }+ mkdirSync(home, { recursive: true })+ if (!record) writeFileSync(recordFile, `${JSON.stringify({ worktree: root, port }, null, 2)}\n`)++ const host = buildHost()+ const log = join(home, 'host.log')+ const hostEnv = { ...process.env, CODYNC_HOME: home, ...(flags.cloud ? {} : { CODYNC_CLOUD: 'off' }) }+ const out = openSync(log, 'a')+ const hostProcess = spawn(host, ['serve', '--port', String(port)], { env: hostEnv, stdio: ['ignore', out, out] })+ hostProcess.on('error', (e) => fail(`Couldn't start ${host}: ${e.message}`))+ let app = null+ let stopping = false+ const stop = (code) => {+ stopping = true+ hostProcess.kill()+ app?.stop()+ process.exitCode = code+ }+ hostProcess.on('exit', (code) => {+ if (stopping) return+ console.error(`The sandbox host stopped (exit ${code}). See ${log}`)+ stop(1)+ })+ for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(signal, () => stop(130))+ for (let tries = 0; !(await answers(port)); tries++) {+ if (stopping) return+ if (tries === 60) {+ console.error(`The sandbox host didn't answer within 30 seconds. See ${log}`)+ return stop(1)+ }+ await delay(500)+ }++ const cdp = flags.cdp ? port + 10000 : null+ const command = `CODYNC_HOME="${home}" "${host}"`+ console.log(`\nCodync Dev (${name}): a sandbox on port ${port}, data in ${home}${flags.cloud ? '' : ', dev cloud off'}`)+ console.log(` pair a phone or simulator ${command} pair --port ${port}`)+ console.log(` terminal UI ${command} tui --port ${port}`)+ if (cdp) console.log(` DevTools protocol 127.0.0.1:${cdp}`)+ console.log('')+ const appEnv = { ...process.env, CODYNC_HOME: home, CODYNC_PORT: String(port), ...(cdp ? { CODYNC_REMOTE_DEBUG: String(cdp) } : {}) }+ app = startApp(appEnv)+ app.child.on('exit', (code) => stop(code ?? 0))+ app.child.on('error', (e) => {+ console.error(`Couldn't start electron-vite: ${e.message}`)+ stop(1)+ })+}++if (flags.list || flags.prune) {+ await listAndPrune()+} else {+ if (flags.shared && (flags.sandbox || flags.name)) fail('--shared runs the default Codync Dev: leave out --sandbox and --name.')+ run(process.execPath, [join(desktop, 'tools/account-config.mjs'), 'dev'])+ // A fresh `npm ci` (a new worktree) can leave Electron's binary undownloaded.+ if (!existsSync(join(desktop, 'node_modules/electron/path.txt'))) run(process.execPath, [join(desktop, 'node_modules/electron/install.js')])+ const mainCheckout = statSync(join(root, '.git')).isDirectory()+ if (flags.sandbox || flags.name || (!mainCheckout && !flags.shared)) {+ await sandbox()+ } else {+ const { child, stop } = startApp()+ for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(signal, stop)+ child.on('error', (e) => fail(`Couldn't start electron-vite: ${e.message}`))+ child.on('exit', (code) => {+ stop()+ process.exitCode = code ?? 1+ })+ }+}diff --git a/docs/architecture/desktop-app.md b/docs/architecture/desktop-app.mdindex fd71d07e..ce89449a 100644--- a/docs/architecture/desktop-app.md+++ b/docs/architecture/desktop-app.md@@ -118,7 +118,8 @@ It uses port 19222 on the remote computer and leaves bots and settings unchangedcd apps/desktopnpm cinpm run icons # macOS: SF Symbol masks-npm run dev # Codync Dev, separate host on 19223+npm run dev # main checkout: Codync Dev, separate host on 19223+ # linked worktree: a sandbox beside it (docs/guides/dev-app.md)CODYNC_PORT=19333 CODYNC_HOME=/path/to/home npm run dev # against a manually run hostnpm run typecheck && npm test```diff --git a/docs/guides/dev-app.md b/docs/guides/dev-app.mdindex 3ac91d13..b158735f 100644--- a/docs/guides/dev-app.md+++ b/docs/guides/dev-app.md@@ -15,10 +15,23 @@ Desktop development and builds on macOS generate SF Symbols automatically, inclu| Desktop packaging | `npm run dist:<platform>:main` | `npm run dist:<platform>:dev` || Foreground host | `CODYNC_ENV=main cargo run -- serve` | `cargo run -- serve` |-`<platform>` is `mac`, `linux`, or `win`. Desktop `npm run dev` uses the development identity. An unpackaged run needs a matching development host binary; it takes the first that exists of `CODYNC_HOST_BIN`, `apps/desktop/build/native/codync-host` (left by `dist:mac:dev`, or rebuilt alone with `node tools/native-host.mjs dev`) and `host/target/debug/codync-host`, so after a `dist:mac:dev` a plain `cargo build` isn't picked up. On Linux, install a development host as `~/.local/bin/codync-dev-host`; the production binary remains `codync-host`.+`<platform>` is `mac`, `linux`, or `win`. Desktop `npm run dev` uses the development identity; in a linked worktree it runs a [sandbox](#worktree-sandboxes). In the main checkout, an unpackaged run needs a matching development host binary; it takes the first that exists of `CODYNC_HOST_BIN`, `apps/desktop/build/native/codync-host` (left by `dist:mac:dev`, or rebuilt alone with `node tools/native-host.mjs dev`) and `host/target/debug/codync-host`, so after a `dist:mac:dev` a plain `cargo build` isn't picked up. On Linux, install a development host as `~/.local/bin/codync-dev-host`; the production binary remains `codync-host`.Xcode configurations separate environment from optimization: `Debug` and `Release` use production; `DevDebug` and `DevRelease` use development. The `iOS` archive remains `Release`, preserving Xcode Cloud's existing production scheme. Configure schemes through `apps/project.yml`, then regenerate with `xcodegen generate --spec apps/project.yml`.+## Worktree sandboxes++`npm run dev` decides by checkout. The main checkout (its `.git` is a folder) runs the default Codync Dev: the launchd/systemd host on 19223 and `~/.codync-dev`, the one a physical iPhone pairs with. A linked worktree (its `.git` is a file) runs a sandbox beside it, so any number of worktrees and agents test at once:++- Host data in `~/.codync-dev-<worktree folder>`, which also holds the app's session, account and single-instance lock (`desktop/`). The window and menu bar read `Codync Dev (<name>)`.+- A port from 19300–19399, picked free on the first run and kept in that folder's `sandbox.json`, so a paired simulator stays paired.+- A host built from the worktree's own code (`node tools/native-host.mjs dev`; on Linux `cargo build`, honoring `CARGO_TARGET_DIR`; or `CODYNC_HOST_BIN`), started and stopped with the app, logging to `host.log`. No launchd/systemd service, and the dev cloud is off.+- The run prints the commands that pair a phone or simulator (`codync-host pair`) and open the terminal UI against the sandbox. Give each sandbox its own simulator: a simulator holds one Codync Dev.++Flags go after `npm run dev --`: `--shared` takes the default Codync Dev from a worktree (quit the main checkout's first); `--sandbox` runs a sandbox from the main checkout, for a second session on `dev`; `--name <name>` runs the sandbox of that name, for another copy of the same checkout; `--cloud` lets the sandbox host use the dev cloud (each sandbox then shows as another computer); `--cdp` opens the DevTools protocol on the sandbox port + 10000; `--list` shows every sandbox; `--prune` deletes the ones whose worktree is gone, so run it after removing worktrees.++Still shared: macOS sees every unpackaged run as the same Electron app, so permissions and notifications are shared and a `codync-dev://` sign-in callback may reach another copy (test sign-in on the default Codync Dev); Codync Screen and computer use need the packaged `Codync Dev.app`; a global shortcut (the approval island's) goes to whichever app registered it first.+## Resource ownership| Resource | Production | Development |