mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-21 04:12:08 +03:00
fix(desktop): restore fast cold dev startup (#54060)
This commit is contained in:
committed by
GitHub
Unverified
parent
40cc0f377b
commit
3e3a9b3a49
@@ -437,6 +437,7 @@
|
||||
"electron": "44.4.5",
|
||||
"electron-builder": "26.15.7",
|
||||
"electron-vite": "6.0.0-beta.1",
|
||||
"magic-string": "0.30.21",
|
||||
"solid-js": "catalog:",
|
||||
"typescript": "~5.6.2",
|
||||
"vite": "8.2.2",
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { Service } from "@opencode/client/service"
|
||||
import { chromium, expect, type Browser, type Page, type TestInfo } from "@playwright/test"
|
||||
import { Schema } from "effect"
|
||||
import { spawn, spawnSync, type ChildProcess } from "node:child_process"
|
||||
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"
|
||||
import { tmpdir } from "node:os"
|
||||
import { homedir, tmpdir } from "node:os"
|
||||
import { join, resolve } from "node:path"
|
||||
import { startChromeTrace } from "../chrome-trace"
|
||||
|
||||
@@ -43,7 +44,9 @@ type Milestone = (typeof milestones)[number]
|
||||
|
||||
type Phase = (typeof phases)[number]
|
||||
|
||||
type ServiceInfo = { id: string; version: string; url: string; pid: number }
|
||||
const ServiceInfo = Schema.Struct({ id: Schema.String, version: Schema.String, url: Schema.String, pid: Schema.Number })
|
||||
|
||||
type ServiceInfo = typeof ServiceInfo.Type
|
||||
|
||||
export type DesktopStartupSample = {
|
||||
run: number
|
||||
@@ -168,10 +171,7 @@ async function initializeColdProfile(root: string) {
|
||||
),
|
||||
)
|
||||
await Promise.all([
|
||||
writeFile(
|
||||
join(root, "desktop", "opencode.settings"),
|
||||
JSON.stringify({ firstLaunchOnboardingComplete: true }),
|
||||
),
|
||||
writeFile(join(root, "desktop", "opencode.settings"), JSON.stringify({ firstLaunchOnboardingComplete: true })),
|
||||
writeFile(join(root, "desktop", "opencode.global.dat"), JSON.stringify({ language: '{"locale":"en"}' })),
|
||||
])
|
||||
const registration = join(root, "desktop", "opencode", "service-local.json")
|
||||
@@ -195,6 +195,9 @@ function startDesktop(profile: Awaited<ReturnType<typeof createColdProfile>>) {
|
||||
OPENCODE_DESKTOP_TEST_ROOT: profile.root,
|
||||
OPENCODE_DESKTOP_REMOTE_DEBUGGING_PORT: "0",
|
||||
OPENCODE_DESKTOP_DISABLE_PROTOCOL_REGISTRATION: "1",
|
||||
// The test root also redirects XDG_CACHE_HOME, which would move Bun's transpiler cache and make
|
||||
// every sample transpile the source CLI from scratch. A dev start reuses the developer's cache.
|
||||
BUN_RUNTIME_TRANSPILER_CACHE_PATH: process.env.BUN_RUNTIME_TRANSPILER_CACHE_PATH ?? bunTranspilerCache(),
|
||||
},
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
})
|
||||
@@ -303,6 +306,15 @@ function startDesktop(profile: Awaited<ReturnType<typeof createColdProfile>>) {
|
||||
}
|
||||
}
|
||||
|
||||
// Bun's default location for its runtime transpiler cache.
|
||||
function bunTranspilerCache() {
|
||||
if (process.env.XDG_CACHE_HOME) return join(process.env.XDG_CACHE_HOME, "bun", "@t@")
|
||||
|
||||
if (process.platform === "darwin") return join(homedir(), "Library", "Caches", "bun", "@t@")
|
||||
|
||||
return join(homedir(), ".bun", "install", "cache", "@t@")
|
||||
}
|
||||
|
||||
async function waitForHome(page: Page, mark: (name: Milestone) => void) {
|
||||
await expect.poll(() => page.evaluate(() => document.visibilityState), { timeout: 120_000 }).toBe("visible")
|
||||
|
||||
@@ -331,6 +343,7 @@ async function startThemeObservation(page: Page) {
|
||||
|
||||
async function requireStableTheme(page: Page) {
|
||||
const states = await page.evaluate(() => {
|
||||
// SAFETY: only `installThemeObservation` writes these optional globals, in the declared shapes.
|
||||
const target = window as ThemeWindow
|
||||
target.__OPENCODE_THEME_OBSERVER__?.disconnect()
|
||||
|
||||
@@ -341,6 +354,7 @@ async function requireStableTheme(page: Page) {
|
||||
}
|
||||
|
||||
function installThemeObservation() {
|
||||
// SAFETY: this function is the only writer of these optional globals, in the declared shapes.
|
||||
const target = window as ThemeWindow
|
||||
|
||||
const observeRoot = () => {
|
||||
@@ -384,12 +398,13 @@ function installThemeObservation() {
|
||||
}
|
||||
|
||||
async function observeOutput(stream: NodeJS.ReadableStream, record: (line: string) => void) {
|
||||
const decoder = new TextDecoder()
|
||||
// The stream decodes UTF-8 itself, keeping characters split across chunks intact.
|
||||
stream.setEncoding("utf8")
|
||||
const output: string[] = []
|
||||
let pending = ""
|
||||
|
||||
for await (const chunk of stream) {
|
||||
const text = typeof chunk === "string" ? chunk : decoder.decode(chunk, { stream: true })
|
||||
const text = String(chunk)
|
||||
output.push(text)
|
||||
pending += text
|
||||
const lines = pending.split(/\r?\n/)
|
||||
@@ -397,23 +412,21 @@ async function observeOutput(stream: NodeJS.ReadableStream, record: (line: strin
|
||||
lines.forEach(record)
|
||||
}
|
||||
|
||||
const final = decoder.decode()
|
||||
output.push(final)
|
||||
pending += final
|
||||
|
||||
if (pending) record(pending)
|
||||
|
||||
return output.join("")
|
||||
}
|
||||
|
||||
async function readService(profile: Awaited<ReturnType<typeof createColdProfile>>) {
|
||||
const value: unknown = JSON.parse(await readFile(profile.registration, "utf8"))
|
||||
const value = Schema.decodeUnknownSync(Schema.fromJsonString(ServiceInfo))(
|
||||
await readFile(profile.registration, "utf8"),
|
||||
)
|
||||
|
||||
if (!isServiceInfo(value)) throw new Error("Desktop service registration is invalid")
|
||||
const url = new URL(value.url)
|
||||
const port = Number(url.port)
|
||||
|
||||
if (url.hostname !== "127.0.0.1" || !Number.isInteger(port) || port <= 0)
|
||||
// The isolated dev service listens on every interface so paired devices can reach it.
|
||||
if (!["127.0.0.1", "0.0.0.0"].includes(url.hostname) || !Number.isInteger(port) || port <= 0)
|
||||
throw new Error(`Desktop service used unexpected endpoint ${value.url}`)
|
||||
|
||||
if (!value.version.startsWith("2.0.0-local-"))
|
||||
@@ -422,21 +435,6 @@ async function readService(profile: Awaited<ReturnType<typeof createColdProfile>
|
||||
return value
|
||||
}
|
||||
|
||||
function isServiceInfo(value: unknown): value is ServiceInfo {
|
||||
return (
|
||||
typeof value === "object" &&
|
||||
value !== null &&
|
||||
"id" in value &&
|
||||
typeof value.id === "string" &&
|
||||
"version" in value &&
|
||||
typeof value.version === "string" &&
|
||||
"url" in value &&
|
||||
typeof value.url === "string" &&
|
||||
"pid" in value &&
|
||||
typeof value.pid === "number"
|
||||
)
|
||||
}
|
||||
|
||||
function requireMilestones(observed: Partial<Record<Milestone, number>>) {
|
||||
const get = (name: Milestone) => {
|
||||
const value = observed[name]
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { defineConfig } from "electron-vite"
|
||||
import type { Plugin } from "vite"
|
||||
import { pickerPlugin } from "./scripts/picker"
|
||||
|
||||
const channel = (() => {
|
||||
@@ -35,32 +36,19 @@ const sentry =
|
||||
// Every module the entry reaches through static imports lands in one chunk. Automatic splitting
|
||||
// otherwise fragments the initial graph into ~50 files shared with lazy routes, and each file costs
|
||||
// the renderer a main-thread request round trip through the main process before first paint.
|
||||
type ChunkingContext = { getModuleInfo(id: string): { isEntry: boolean; importers: readonly string[] } | null }
|
||||
// Rolldown hands every chunk-name call a fresh context, so the graph is walked once per output.
|
||||
const initialGraph = new Set<string>()
|
||||
|
||||
const initialGraph = new WeakMap<ChunkingContext, Map<string, boolean>>()
|
||||
const initialChunk: Plugin = {
|
||||
name: "opencode-desktop:initial-chunk",
|
||||
renderStart() {
|
||||
const entries = [...this.getModuleIds()].filter((id) => this.getModuleInfo(id)?.isEntry)
|
||||
initialGraph.clear()
|
||||
entries.forEach((id) => initialGraph.add(id))
|
||||
|
||||
function inInitialGraph(id: string, ctx: ChunkingContext) {
|
||||
const memo = initialGraph.get(ctx) ?? new Map<string, boolean>()
|
||||
initialGraph.set(ctx, memo)
|
||||
|
||||
const visit = (id: string, path: Set<string>): boolean => {
|
||||
const known = memo.get(id)
|
||||
|
||||
if (known !== undefined) return known
|
||||
|
||||
if (path.has(id)) return false
|
||||
const info = ctx.getModuleInfo(id)
|
||||
|
||||
if (!info) return false
|
||||
path.add(id)
|
||||
const result = info.isEntry || info.importers.some((importer) => visit(importer, path))
|
||||
path.delete(id)
|
||||
memo.set(id, result)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
return visit(id, new Set())
|
||||
// A Set's iterator also visits members added while iterating, so this reaches every static import.
|
||||
for (const id of initialGraph) this.getModuleInfo(id)?.importedIds.forEach((imported) => initialGraph.add(imported))
|
||||
},
|
||||
}
|
||||
|
||||
export default defineConfig(({ command }) => ({
|
||||
@@ -136,7 +124,7 @@ const require = __cjs_mod__.createRequire(import.meta.url);
|
||||
command === "serve" && process.env.OPENCODE_TEST_ONBOARDING === "1",
|
||||
),
|
||||
},
|
||||
plugins: [pickerPlugin(), appPlugin, sentry],
|
||||
plugins: [pickerPlugin(), appPlugin, initialChunk, sentry],
|
||||
publicDir: "../../../app/public",
|
||||
root: "src/renderer",
|
||||
build: {
|
||||
@@ -148,7 +136,7 @@ const require = __cjs_mod__.createRequire(import.meta.url);
|
||||
},
|
||||
output: {
|
||||
codeSplitting: {
|
||||
groups: [{ name: (id, ctx) => (inInitialGraph(id, ctx) ? "app" : null), priority: 10 }],
|
||||
groups: [{ name: (id) => (initialGraph.has(id) ? "app" : null), priority: 10 }],
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -53,6 +53,7 @@
|
||||
"electron": "44.4.5",
|
||||
"electron-builder": "26.15.7",
|
||||
"electron-vite": "6.0.0-beta.1",
|
||||
"magic-string": "0.30.21",
|
||||
"solid-js": "catalog:",
|
||||
"typescript": "~5.6.2",
|
||||
"vite": "8.2.2"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { $ } from "bun"
|
||||
import { constants, setPriority } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import { fileURLToPath } from "node:url"
|
||||
import { prepareDevElectron } from "./dev-electron"
|
||||
@@ -51,18 +52,37 @@ function selectOptions(): DevOptions {
|
||||
async function prepareServer(source: ServerSource) {
|
||||
if (source.type === "download")
|
||||
return downloadCliToResources(source.version, windowsify("resources/opencode-cli-dev"))
|
||||
await $`bun run --cwd ${join(import.meta.dirname, "../../app")} build`.env({
|
||||
...process.env,
|
||||
VITE_OPENCODE_SERVER_MODE: "origin",
|
||||
})
|
||||
buildWebUi()
|
||||
process.env.OPENCODE_DESKTOP_CLI_DEV = join(import.meta.dirname, "../../cli")
|
||||
await $`bun run --cwd ${process.env.OPENCODE_DESKTOP_CLI_DEV} --define=OPENCODE_VERSION=${JSON.stringify(process.env.OPENCODE_VERSION)} src/index.ts --version`
|
||||
|
||||
if (process.platform !== "win32") return
|
||||
process.env.OPENCODE_DESKTOP_WSL_CLI_BUILD = join(import.meta.dirname, "../../cli/script/build.ts")
|
||||
process.env.OPENCODE_DESKTOP_WSL_CLI_OUTPUT = join(import.meta.dirname, "../resources/opencode-cli-wsl")
|
||||
}
|
||||
|
||||
// The source CLI serves packages/app/dist only to paired devices, and nothing on the way to the
|
||||
// desktop window reads it, so it builds alongside startup instead of before it. Idle priority also
|
||||
// lowers its disk and memory priority on Windows; below-normal still delayed the window by seconds.
|
||||
function buildWebUi() {
|
||||
const started = performance.now()
|
||||
|
||||
const build = Bun.spawn(["bun", "run", "build"], {
|
||||
cwd: join(import.meta.dirname, "../../app"),
|
||||
env: { ...process.env, VITE_OPENCODE_SERVER_MODE: "origin" },
|
||||
stdio: ["ignore", "ignore", "ignore"],
|
||||
})
|
||||
|
||||
setPriority(build.pid, constants.priority.PRIORITY_LOW)
|
||||
build.unref()
|
||||
void build.exited.then((code) =>
|
||||
console.log(
|
||||
code === 0
|
||||
? `Built the pairing web UI in ${((performance.now() - started) / 1000).toFixed(1)} s`
|
||||
: `Pairing web UI build failed with code ${code}; run 'bun run --cwd packages/app build' to see why`,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
async function startDesktop(args: string[]) {
|
||||
// Bun's implicit spawn environment omits values set during preparation.
|
||||
process.exitCode = await Bun.spawn(
|
||||
|
||||
@@ -1,11 +1,22 @@
|
||||
import picker from "@brendonovich/vite-plugin-opencode"
|
||||
import MagicString from "magic-string"
|
||||
import { existsSync } from "node:fs"
|
||||
import { dirname, join, relative, resolve, sep } from "node:path"
|
||||
import { parseSync, Visitor } from "vite"
|
||||
|
||||
const attribute = "data-opencode-picker-source"
|
||||
|
||||
export function pickerPlugin() {
|
||||
const plugin = picker()
|
||||
const client = "/__vite_opencode_picker_client.js"
|
||||
let workspaceRoot = ""
|
||||
|
||||
return {
|
||||
...plugin,
|
||||
configResolved(config: Parameters<typeof plugin.configResolved>[0]) {
|
||||
plugin.configResolved(config)
|
||||
workspaceRoot = gitRoot(config.root)
|
||||
},
|
||||
resolveId(id: string) {
|
||||
return plugin.resolveId(id === client ? "virtual:vite-opencode-picker/client" : id)
|
||||
},
|
||||
@@ -23,5 +34,44 @@ export function pickerPlugin() {
|
||||
return [{ tag: "script", attrs: { type: "module", src: client }, injectTo: "body" as const }]
|
||||
},
|
||||
},
|
||||
// The package tags elements through a Babel parse and print of every component, a second Babel
|
||||
// pass on top of Solid's. Inserting the attribute where Oxc finds each element gives the same tags
|
||||
// at about a quarter of the cost, which the first renderer bundle waits on.
|
||||
transform(code: string, id: string) {
|
||||
const file = id.split("?", 1)[0]
|
||||
|
||||
if (!/\.[jt]sx$/.test(file) || file.includes("/node_modules/")) return
|
||||
const source = relative(workspaceRoot, file).replaceAll(sep, "/")
|
||||
|
||||
if (source.startsWith("../")) return
|
||||
const parsed = parseSync(file, code)
|
||||
|
||||
if (parsed.errors.length) return
|
||||
const lines = [0, ...Array.from(code.matchAll(/\n/g), (match) => match.index + 1)]
|
||||
const output = new MagicString(code)
|
||||
|
||||
new Visitor({
|
||||
JSXOpeningElement(node) {
|
||||
if (node.name.type !== "JSXIdentifier" || !/^[a-z]/.test(node.name.name)) return
|
||||
|
||||
if (node.attributes.some((item) => item.type === "JSXAttribute" && item.name.name === attribute)) return
|
||||
const line = lines.findLastIndex((start) => start <= node.start) + 1
|
||||
output.appendLeft(node.selfClosing ? node.end - 2 : node.end - 1, ` ${attribute}="${source}:${line}"`)
|
||||
},
|
||||
}).visit(parsed.program)
|
||||
|
||||
if (!output.hasChanged()) return
|
||||
|
||||
return { code: output.toString(), map: output.generateMap({ hires: "boundary", source: file }) }
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// The package's own root: the nearest directory with a .git entry, so tags name the same paths.
|
||||
function gitRoot(root: string) {
|
||||
for (let dir = resolve(root); ; dir = dirname(dir)) {
|
||||
if (existsSync(join(dir, ".git"))) return dir
|
||||
|
||||
if (dirname(dir) === dir) return resolve(root)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,12 +57,14 @@ const make = Effect.fn("DesktopCli.resolve")(function* () {
|
||||
const cli = development
|
||||
? {
|
||||
version,
|
||||
// Bun's transpiler cache key includes the define table, and the dev version changes on every
|
||||
// run. Reading it from the inherited environment keeps the define fixed and the cache warm.
|
||||
command: [
|
||||
"bun",
|
||||
"run",
|
||||
"--cwd",
|
||||
development,
|
||||
`--define=OPENCODE_VERSION=${JSON.stringify(version)}`,
|
||||
"--define=OPENCODE_VERSION=process.env.OPENCODE_VERSION",
|
||||
"src/index.ts",
|
||||
],
|
||||
binary: undefined,
|
||||
|
||||
Reference in New Issue
Block a user