GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(desktop): add opt-in v2 sidecar (#39286) · jethrolarson/opencode@9e432a6

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • .github/workflows
    • publish.yml
  • packages/desktop
    • electron-builder.config.test.ts
    • electron-builder.config.ts
    • scripts
      • prebuild.ts
      • predev.ts
      • utils.ts
    • src/main
      • background-cli.ts
      • index.ts
      • server.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎.github/workflows/publish.yml‎

Copy file name to clipboardExpand all lines: .github/workflows/publish.yml
-4Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,6 @@ jobs:
219219
220220
build-electron:
221221
needs:
222-
- build-cli
223222
- version
224223
if: github.repository == 'anomalyco/opencode'
225224
continue-on-error: false
@@ -316,10 +315,7 @@ jobs:
316315
env:
317316
OPENCODE_VERSION: ${{ needs.version.outputs.version }}
318317
OPENCODE_CHANNEL: ${{ (github.ref_name == 'beta' && 'beta') || 'prod' }}
319-
OPENCODE_CLI_ARTIFACT: ${{ (runner.os == 'Windows' && 'opencode-cli-windows') || 'opencode-cli' }}
320318
RUST_TARGET: ${{ matrix.settings.target }}
321-
GH_TOKEN: ${{ github.token }}
322-
GITHUB_RUN_ID: ${{ github.run_id }}
323319

324320
- name: Build
325321
run: bun run build
Collapse file

‎packages/desktop/electron-builder.config.test.ts‎

Copy file name to clipboardExpand all lines: packages/desktop/electron-builder.config.test.ts
+33Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,3 +56,36 @@ test("keeps a hidden prod launcher for old Linux pins", async () => {
5656
expect(desktop).toContain("StartupWMClass=ai.opencode.desktop")
5757
expect(desktop).toContain("NoDisplay=true")
5858
})
59+
60+
test("bundles the CLI outside the dev app archive", async () => {
61+
const previous = process.env.OPENCODE_CHANNEL
62+
process.env.OPENCODE_CHANNEL = "dev"
63+
const module = await import("./electron-builder.config.ts?cli-resource")
64+
const config = module.default as Configuration
65+
if (previous === undefined) delete process.env.OPENCODE_CHANNEL
66+
else process.env.OPENCODE_CHANNEL = previous
67+
68+
expect(config.files).toContain("!resources/opencode-cli*")
69+
expect(config.extraResources).toContainEqual({
70+
from: "resources/",
71+
to: "",
72+
filter: ["opencode-cli*"],
73+
})
74+
})
75+
76+
for (const channel of ["beta", "prod"] as const) {
77+
test(`does not bundle the CLI in ${channel} builds`, async () => {
78+
const previous = process.env.OPENCODE_CHANNEL
79+
process.env.OPENCODE_CHANNEL = channel
80+
const module = await import(`./electron-builder.config.ts?no-cli-resource=${channel}`)
81+
const config = module.default as Configuration
82+
if (previous === undefined) delete process.env.OPENCODE_CHANNEL
83+
else process.env.OPENCODE_CHANNEL = previous
84+
85+
expect(config.extraResources).not.toContainEqual({
86+
from: "resources/",
87+
to: "",
88+
filter: ["opencode-cli*"],
89+
})
90+
})
91+
}
Collapse file

‎packages/desktop/electron-builder.config.ts‎

Copy file name to clipboardExpand all lines: packages/desktop/electron-builder.config.ts
+10-1Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,17 @@ const getBase = (appId: string): Configuration => ({
5555
extraMetadata: {
5656
desktopName: `${appId}.desktop`,
5757
},
58-
files: ["out/**/*", "resources/**/*"],
58+
files: ["out/**/*", "resources/**/*", "!resources/opencode-cli*"],
5959
extraResources: [
60+
...(channel === "dev"
61+
? [
62+
{
63+
from: "resources/",
64+
to: "",
65+
filter: ["opencode-cli*"],
66+
},
67+
]
68+
: []),
6069
{
6170
from: "native/",
6271
to: "native/",
Collapse file

‎packages/desktop/scripts/prebuild.ts‎

Copy file name to clipboard
+2-1Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
#!/usr/bin/env bun
22
import { $ } from "bun"
33

4-
import { resolveChannel } from "./utils"
4+
import { downloadCliToResources, resolveChannel } from "./utils"
55

66
const channel = resolveChannel()
77
await $`bun ./scripts/copy-icons.ts ${channel}`
88
await $`bun ./scripts/copy-metainfo.ts ${channel}`
99

1010
await $`cd ../opencode && bun script/build-node.ts`
11+
if (channel === "dev") await downloadCliToResources()
Collapse file

‎packages/desktop/scripts/predev.ts‎

Copy file name to clipboard
+2Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import { $ } from "bun"
2+
import { downloadCliToResources } from "./utils"
23

34
await $`bun run install-electron`
45

56
await $`bun ./scripts/copy-icons.ts ${process.env.OPENCODE_CHANNEL ?? "dev"}`
67

78
await $`cd ../opencode && bun script/build-node.ts`
9+
await downloadCliToResources()
Collapse file

‎packages/desktop/scripts/utils.ts‎

Copy file name to clipboardExpand all lines: packages/desktop/scripts/utils.ts
+42-22Lines changed: 42 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
11
import { $ } from "bun"
2+
import { chmod, copyFile, mkdtemp, rm } from "node:fs/promises"
3+
import { tmpdir } from "node:os"
4+
import { join } from "node:path"
5+
6+
const CLI_VERSION = "0.0.0-next-16350"
27

38
export type Channel = "dev" | "beta" | "prod"
49

@@ -8,36 +13,42 @@ export function resolveChannel(): Channel {
813
return "dev"
914
}
1015

11-
export const SIDECAR_BINARIES: Array<{ rustTarget: string; ocBinary: string; assetExt: string }> = [
16+
export const CLI_BINARIES: Array<{ rustTarget: string; package: string; os: string; cpu: string }> = [
1217
{
1318
rustTarget: "aarch64-apple-darwin",
14-
ocBinary: "opencode-darwin-arm64",
15-
assetExt: "zip",
19+
package: "@opencode-ai/cli-darwin-arm64",
20+
os: "darwin",
21+
cpu: "arm64",
1622
},
1723
{
1824
rustTarget: "x86_64-apple-darwin",
19-
ocBinary: "opencode-darwin-x64-baseline",
20-
assetExt: "zip",
25+
package: "@opencode-ai/cli-darwin-x64-baseline",
26+
os: "darwin",
27+
cpu: "x64",
2128
},
2229
{
2330
rustTarget: "aarch64-pc-windows-msvc",
24-
ocBinary: "opencode-windows-arm64",
25-
assetExt: "zip",
31+
package: "@opencode-ai/cli-windows-arm64",
32+
os: "win32",
33+
cpu: "arm64",
2634
},
2735
{
2836
rustTarget: "x86_64-pc-windows-msvc",
29-
ocBinary: "opencode-windows-x64-baseline",
30-
assetExt: "zip",
37+
package: "@opencode-ai/cli-windows-x64-baseline",
38+
os: "win32",
39+
cpu: "x64",
3140
},
3241
{
3342
rustTarget: "x86_64-unknown-linux-gnu",
34-
ocBinary: "opencode-linux-x64-baseline",
35-
assetExt: "tar.gz",
43+
package: "@opencode-ai/cli-linux-x64-baseline",
44+
os: "linux",
45+
cpu: "x64",
3646
},
3747
{
3848
rustTarget: "aarch64-unknown-linux-gnu",
39-
ocBinary: "opencode-linux-arm64",
40-
assetExt: "tar.gz",
49+
package: "@opencode-ai/cli-linux-arm64",
50+
os: "linux",
51+
cpu: "arm64",
4152
},
4253
]
4354

@@ -51,24 +62,33 @@ function nativeTarget() {
5162
throw new Error(`Unsupported platform: ${platform}/${arch}`)
5263
}
5364

54-
export function getCurrentSidecar(target = RUST_TARGET ?? nativeTarget()) {
55-
const binaryConfig = SIDECAR_BINARIES.find((b) => b.rustTarget === target)
56-
if (!binaryConfig) throw new Error(`Sidecar configuration not available for Rust target '${target}'`)
65+
export function getCurrentCli(target = RUST_TARGET ?? nativeTarget()) {
66+
const binaryConfig = CLI_BINARIES.find((item) => item.rustTarget === target)
67+
if (!binaryConfig) throw new Error(`CLI configuration not available for target '${target}'`)
5768

5869
return binaryConfig
5970
}
6071

61-
export async function copyBinaryToSidecarFolder(source: string) {
62-
const dir = `resources`
63-
await $`mkdir -p ${dir}`
64-
const dest = windowsify(`${dir}/opencode-cli`)
65-
await $`cp ${source} ${dest}`
72+
export async function downloadCliToResources() {
73+
const cli = getCurrentCli()
74+
const directory = await mkdtemp(join(tmpdir(), "opencode-cli-"))
75+
const dest = windowsify("resources/opencode-cli")
76+
try {
77+
await $`bun install --no-save --cwd ${directory} ${`${cli.package}@${CLI_VERSION}`} ${`--os=${cli.os}`} ${`--cpu=${cli.cpu}`}`
78+
await copyFile(
79+
join(directory, "node_modules", cli.package, "bin", cli.os === "win32" ? "opencode2.exe" : "opencode2"),
80+
dest,
81+
)
82+
} finally {
83+
await rm(directory, { recursive: true, force: true })
84+
}
85+
if (process.platform !== "win32") await chmod(dest, 0o755)
6686
if (process.platform === "win32" && process.env.GITHUB_ACTIONS === "true") {
6787
await $`pwsh -NoLogo -NoProfile -ExecutionPolicy Bypass -File ../../script/sign-windows.ps1 ${dest}`
6888
}
6989
if (process.platform === "darwin") await $`codesign --force --sign - ${dest}`
7090

71-
console.log(`Copied ${source} to ${dest}`)
91+
console.log(`Copied ${cli.package} to ${dest}`)
7292
}
7393

7494
export function windowsify(path: string) {
Collapse file

‎packages/desktop/src/main/background-cli.ts‎

Copy file name to clipboard
+125Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
import { execFile } from "node:child_process"
2+
import { existsSync } from "node:fs"
3+
import { chmod, copyFile, mkdir, rename, rm } from "node:fs/promises"
4+
import { dirname, join } from "node:path"
5+
import { fileURLToPath } from "node:url"
6+
import { promisify } from "node:util"
7+
import { app } from "electron"
8+
9+
const execFileAsync = promisify(execFile)
10+
const root = dirname(fileURLToPath(import.meta.url))
11+
const stateHome = process.env.XDG_STATE_HOME
12+
const desktopStateNames = ["ai.opencode.desktop.dev", "ai.opencode.desktop.beta", "ai.opencode.desktop"]
13+
14+
type Logger = {
15+
log(message: string, meta?: Record<string, unknown>): void
16+
error(message: string, meta?: Record<string, unknown>): void
17+
}
18+
19+
export async function startBackgroundCli(logger: Logger, shellStateHome?: string) {
20+
const bundled = app.isPackaged
21+
? join(process.resourcesPath, executableName())
22+
: join(root, "../../resources", executableName())
23+
logger.log("v2 CLI executable resolved", { bundled, packaged: app.isPackaged })
24+
const version = await run(bundled, ["--version"], logger)
25+
const binary = app.isPackaged ? await installCli(bundled, version, logger) : bundled
26+
27+
const candidates = [
28+
...new Set([stateHome, shellStateHome, ...desktopStateNames.map((name) => join(app.getPath("appData"), name))]),
29+
].filter((candidate) => candidate === undefined || existsSync(candidate))
30+
const discovered = await Promise.all(
31+
candidates.map(async (candidate) => ({
32+
stateHome: candidate,
33+
url: serviceUrl(await run(binary, ["service", "status"], logger, { stateHome: candidate })),
34+
})),
35+
)
36+
const found = discovered.find((candidate) => candidate.url !== undefined)
37+
logger.log("v2 CLI background instance checked", {
38+
detected: Boolean(found),
39+
...endpoint(found?.url),
40+
})
41+
42+
const daemonStateHome = found?.stateHome ?? stateHome
43+
const url = await run(binary, ["service", "start"], logger, { stateHome: daemonStateHome })
44+
const password = await run(binary, ["service", "get", "password"], logger, {
45+
redact: true,
46+
stateHome: daemonStateHome,
47+
})
48+
logger.log("v2 CLI background service ready", {
49+
existing: Boolean(found),
50+
username: "opencode",
51+
...endpoint(url),
52+
})
53+
return {
54+
url,
55+
username: "opencode",
56+
password,
57+
}
58+
}
59+
60+
async function installCli(source: string, version: string, logger: Logger) {
61+
const directory = join(app.getPath("userData"), "cli", version.replace(/[^a-zA-Z0-9._-]/g, "-"))
62+
const destination = join(directory, executableName())
63+
if (existsSync(destination)) {
64+
logger.log("v2 CLI staged executable reused", { path: destination, version })
65+
return destination
66+
}
67+
68+
const temp = destination + `.${process.pid}.tmp`
69+
await mkdir(directory, { recursive: true })
70+
await copyFile(source, temp)
71+
if (process.platform !== "win32") await chmod(temp, 0o755)
72+
await rename(temp, destination).catch(async (error) => {
73+
await rm(temp, { force: true })
74+
throw error
75+
})
76+
logger.log("v2 CLI executable staged", { source, path: destination, version })
77+
return destination
78+
}
79+
80+
async function run(
81+
binary: string,
82+
args: string[],
83+
logger: Logger,
84+
options: { redact?: boolean; stateHome?: string } = {},
85+
) {
86+
logger.log("v2 CLI command started", { binary, args })
87+
const env = { ...process.env }
88+
if (options.stateHome === undefined) delete env.XDG_STATE_HOME
89+
else env.XDG_STATE_HOME = options.stateHome
90+
return execFileAsync(binary, args, { env, windowsHide: true }).then(
91+
(result) => {
92+
const stdout = result.stdout.trim()
93+
const stderr = result.stderr.trim()
94+
logger.log("v2 CLI command completed", { args, stdout: options.redact ? "[redacted]" : stdout, stderr })
95+
return stdout
96+
},
97+
(error: unknown) => {
98+
const output = error as { stdout?: string; stderr?: string }
99+
logger.error("v2 CLI command failed", {
100+
args,
101+
error: error instanceof Error ? error.message : String(error),
102+
stdout: options.redact && output.stdout ? "[redacted]" : (output.stdout?.trim() ?? ""),
103+
stderr: output.stderr?.trim() ?? "",
104+
})
105+
throw error
106+
},
107+
)
108+
}
109+
110+
function serviceUrl(status: string) {
111+
if (URL.canParse(status)) return status
112+
if (!status.startsWith("running ")) return
113+
const url = status.slice("running ".length).trim()
114+
return URL.canParse(url) ? url : undefined
115+
}
116+
117+
function endpoint(url: string | undefined) {
118+
if (!url || !URL.canParse(url)) return {}
119+
const parsed = new URL(url)
120+
return { url, hostname: parsed.hostname, port: parsed.port }
121+
}
122+
123+
function executableName() {
124+
return process.platform === "win32" ? "opencode-cli.exe" : "opencode-cli"
125+
}

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.