Skip to content
Open
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
2 changes: 1 addition & 1 deletion packages/desktop/electron.vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export default defineConfig({
},
build: {
rollupOptions: {
input: { index: "src/main/index.ts" },
input: { index: "src/main/index.ts", sidecar: "src/main/sidecar.ts" },
},
externalizeDeps: { include: [nodePtyPkg] },
},
Expand Down
55 changes: 31 additions & 24 deletions packages/desktop/src/main/apps.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,22 @@
import { execFileSync } from "node:child_process"
import { existsSync, readFileSync, readdirSync } from "node:fs"
import { execFile, execFileSync } from "node:child_process"
import { access, readFile, readdir } from "node:fs/promises"
import { dirname, extname, join } from "node:path"
import util from "node:util"

export function checkAppExists(appName: string): boolean {
const execFilePromise = util.promisify(execFile)

const exists = (path: string) =>
access(path)
.then(() => true)
.catch(() => false)

export function checkAppExists(appName: string) {
if (process.platform === "win32") return true
if (process.platform === "linux") return true
return checkMacosApp(appName)
}

export function resolveAppPath(appName: string): string | null {
export function resolveAppPath(appName: string) {
if (process.platform !== "win32") return appName
return resolveWindowsAppPath(appName)
}
Expand All @@ -32,26 +40,25 @@ export function wslPath(path: string, mode: "windows" | "linux" | null): string
}
}

function checkMacosApp(appName: string) {
async function checkMacosApp(appName: string) {
const locations = [`/Applications/${appName}.app`, `/System/Applications/${appName}.app`]

const home = process.env.HOME
if (home) locations.push(`${home}/Applications/${appName}.app`)

if (locations.some((location) => existsSync(location))) return true

try {
execFileSync("which", [appName])
return true
} catch {
return false
for (const location of locations) {
if (await exists(location)) return true
}

return execFilePromise("which", [appName])
.then(() => true)
.catch(() => false)
}

function resolveWindowsAppPath(appName: string): string | null {
async function resolveWindowsAppPath(appName: string): Promise<string | null> {
let output: string
try {
output = execFileSync("where", [appName]).toString()
output = execFilePromise("where", [appName]).toString()
} catch {
return null
}
Expand All @@ -66,8 +73,8 @@ function resolveWindowsAppPath(appName: string): string | null {
const exe = paths.find((path) => hasExt(path, "exe"))
if (exe) return exe

const resolveCmd = (path: string) => {
const content = readFileSync(path, "utf8")
const resolveCmd = async (path: string) => {
const content = await readFile(path, "utf8")
for (const token of content.split('"').map((value: string) => value.trim())) {
const lower = token.toLowerCase()
if (!lower.includes(".exe")) continue
Expand All @@ -85,31 +92,31 @@ function resolveWindowsAppPath(appName: string): string | null {
return join(current, part)
}, base)

if (existsSync(resolved)) return resolved
if (await exists(resolved)) return resolved
}

if (existsSync(token)) return token
if (await exists(token)) return token
}

return null
}

for (const path of paths) {
if (hasExt(path, "cmd") || hasExt(path, "bat")) {
const resolved = resolveCmd(path)
const resolved = await resolveCmd(path)
if (resolved) return resolved
}

if (!extname(path)) {
const cmd = `${path}.cmd`
if (existsSync(cmd)) {
const resolved = resolveCmd(cmd)
if (await exists(cmd)) {
const resolved = await resolveCmd(cmd)
if (resolved) return resolved
}

const bat = `${path}.bat`
if (existsSync(bat)) {
const resolved = resolveCmd(bat)
if (await exists(bat)) {
const resolved = await resolveCmd(bat)
if (resolved) return resolved
}
}
Expand All @@ -126,7 +133,7 @@ function resolveWindowsAppPath(appName: string): string | null {
const dirs = [dirname(path), dirname(dirname(path)), dirname(dirname(dirname(path)))]
for (const dir of dirs) {
try {
for (const entry of readdirSync(dir)) {
for (const entry of await readdir(dir)) {
const candidate = join(dir, entry)
if (!hasExt(candidate, "exe")) continue
const stem = entry.replace(/\.exe$/i, "")
Expand Down
1 change: 1 addition & 0 deletions packages/desktop/src/main/env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ interface ImportMetaEnv {
interface ImportMeta {
readonly env: ImportMetaEnv
}

declare module "virtual:opencode-server" {
export namespace Server {
export const listen: typeof import("../../../opencode/dist/types/src/node").Server.listen
Expand Down
76 changes: 38 additions & 38 deletions packages/desktop/src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,23 +47,28 @@ import { registerIpcHandlers, sendDeepLinks, sendMenuCommand, sendSqliteMigratio
import { initLogging } from "./logging"
import { parseMarkdown } from "./markdown"
import { createMenu } from "./menu"
import { getDefaultServerUrl, getWslConfig, setDefaultServerUrl, setWslConfig, spawnLocalServer } from "./server"
import {
getDefaultServerUrl,
getWslConfig,
setDefaultServerUrl,
setWslConfig,
spawnLocalServer,
type SidecarListener,
} from "./server"
import {
createLoadingWindow,
createMainWindow,
registerRendererProtocol,
setBackgroundColor,
setDockIcon,
} from "./windows"
import { drizzle } from "drizzle-orm/node-sqlite/driver"
import type { Server } from "virtual:opencode-server"
import { migrate } from "./migrate"

const initEmitter = new EventEmitter()
let initStep: InitStep = { phase: "server_waiting" }

let mainWindow: BrowserWindow | null = null
let server: Server.Listener | null = null
let server: SidecarListener | null = null
const loadingComplete = defer<void>()

const pendingDeepLinks: string[] = []
Expand Down Expand Up @@ -123,17 +128,16 @@ function setupApp() {
})

app.on("before-quit", () => {
killSidecar()
void killSidecar()
})

app.on("will-quit", () => {
killSidecar()
void killSidecar()
})

for (const signal of ["SIGINT", "SIGTERM"] as const) {
process.on(signal, () => {
killSidecar()
app.exit(0)
void killSidecar().finally(() => app.exit(0))
})
}

Expand Down Expand Up @@ -184,7 +188,6 @@ function setInitStep(step: InitStep) {

async function initialize() {
const needsMigration = !sqliteFileExists()
const sqliteDone = needsMigration ? defer<void>() : undefined
let overlay: BrowserWindow | null = null

const port = await getSidecarPort()
Expand All @@ -199,31 +202,26 @@ async function initialize() {
setInitStep({ phase: "sqlite_waiting" })
if (overlay) sendSqliteMigrationProgress(overlay, progress)
if (mainWindow) sendSqliteMigrationProgress(mainWindow, progress)
if (progress.type === "Done") sqliteDone?.resolve()
})

if (needsMigration) {
const { Database, JsonMigration } = await import("virtual:opencode-server")
await JsonMigration.run(drizzle({ client: Database.Client().$client }), {
progress: (event: { current: number; total: number }) => {
const percent = Math.round(event.current / event.total) * 100
initEmitter.emit("sqlite", { type: "InProgress", value: percent })
},
})
initEmitter.emit("sqlite", { type: "Done" })

sqliteDone?.resolve()
}

if (needsMigration) {
await sqliteDone?.promise
}

logger.log("spawning sidecar", { url })
const { listener, health } = await spawnLocalServer(hostname, port, password, () => {
ensureLoopbackNoProxy()
useEnvProxy()
})
const { listener, health } = await spawnLocalServer(
hostname,
port,
password,
() => {
ensureLoopbackNoProxy()
useEnvProxy()
},
{
needsMigration,
userDataPath: app.getPath("userData"),
onSqliteProgress: (progress) => initEmitter.emit("sqlite", progress),
onStdout: (message) => logger.log("sidecar stdout", { message }),
onStderr: (message) => logger.warn("sidecar stderr", { message }),
onExit: (code) => logger.warn("sidecar exited", { code }),
},
)
server = listener
serverReady.resolve({
url,
Expand Down Expand Up @@ -273,9 +271,10 @@ function wireMenu() {
},
reload: () => mainWindow?.reload(),
relaunch: () => {
killSidecar()
app.relaunch()
app.exit(0)
void killSidecar().finally(() => {
app.relaunch()
app.exit(0)
})
},
})
}
Expand Down Expand Up @@ -304,7 +303,7 @@ registerIpcHandlers({
getDisplayBackend: async () => null,
setDisplayBackend: async () => undefined,
parseMarkdown: async (markdown) => parseMarkdown(markdown),
checkAppExists: async (appName) => checkAppExists(appName),
checkAppExists: (appName) => checkAppExists(appName),
wslPath: async (path, mode) => wslPath(path, mode),
resolveAppPath: async (appName) => resolveAppPath(appName),
loadingWindowComplete: () => loadingComplete.resolve(),
Expand All @@ -314,10 +313,11 @@ registerIpcHandlers({
setBackgroundColor: (color) => setBackgroundColor(color),
})

function killSidecar() {
async function killSidecar() {
if (!server) return
server.stop()
const current = server
server = null
await current.stop()
}

function ensureLoopbackNoProxy() {
Expand Down Expand Up @@ -440,7 +440,7 @@ async function installUpdate() {
logger.log("installing downloaded update", {
version: downloadedUpdateVersion,
})
killSidecar()
await killSidecar()
autoUpdater.quitAndInstall()
}

Expand Down
2 changes: 1 addition & 1 deletion packages/desktop/src/main/ipc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const pickerFilters = (ext?: string[]) => {
}

type Deps = {
killSidecar: () => void
killSidecar: () => Promise<void> | void
awaitInitialization: (sendStep: (step: InitStep) => void) => Promise<ServerReadyData>
getWindowConfig: () => Promise<WindowConfig> | WindowConfig
consumeInitialDeepLinks: () => Promise<string[]> | string[]
Expand Down
Loading
Loading