feat(desktop): capture app and server heap snapshots into one folder (#58259)

This commit is contained in:
Luke Parker
2026-10-23 10:25:37 +10:00
committed by GitHub
Unverified
parent 91a7fe54cf
commit 199ad46421
25 changed files with 508 additions and 25 deletions
+3 -1
View File
@@ -130,7 +130,9 @@ On every platform, including Windows, capture the running background server with
opencode debug heap-dump
```
It discovers the already-running service (never starts or replaces one), calls `POST /api/debug/heap-dump`, waits until the file is complete, and prints its server-local path. Pass `--server <url>` (with `OPENCODE_PASSWORD`) for a server started with `serve`. A 404 means the running server predates the endpoint.
It discovers the already-running service (never starts or replaces one), calls `POST /api/debug/heap-dump`, waits until the file is complete, and prints its server-local path. Pass `--server <url>` (with `OPENCODE_PASSWORD`) for a server started with `serve`, and `--directory <dir>` to write somewhere other than the server's log directory (the server creates it; a server that predates the option ignores it and the CLI warns). A 404 means the running server predates the endpoint.
For desktop memory, run **Capture heap snapshots** from the desktop command palette (`packages/gui-extensions/src/debug/main.ts`). It writes `~/Downloads/opencode-heap-<time>/` with the desktop's own (local) server, which writes straight into the folder, every app window renderer, and the Electron main process, plus a `manifest.json` (PIDs and `app.getAppMetrics()`) written last. In a dev desktop build you can drive it over CDP (`OPENCODE_DESKTOP_REMOTE_DEBUGGING_PORT`, default 9222): press `Control+Shift+P`, type `heap snapshots`, press Enter.
The Unix `SIGUSR1` listener in `packages/cli/src/heap.ts` shares the same writer (`packages/util/src/heap-snapshot.ts`) and is still useful for a process that is not an HTTP server, such as a TUI client:
+4
View File
@@ -120,6 +120,10 @@ const Root = Spec.make(typeof OPENCODE_CLI_NAME === "string" ? OPENCODE_CLI_NAME
Spec.make("heap-dump", {
description: "Write a heap snapshot of the running server and print its path",
params: {
directory: Flag.String("directory").pipe(
Flag.withDescription("Directory to write the snapshot into instead of the server's log directory"),
Flag.optional,
),
server: Flag.String("server").pipe(
Flag.withDescription("Connect to a server URL instead of the background service"),
Flag.optional,
@@ -2,6 +2,7 @@ import { ClientError, OpenCode } from "@opencode/client"
import { Service } from "@opencode/client/effect/service"
import { Effect, Option, Predicate } from "effect"
import { EOL } from "node:os"
import path from "node:path"
import { Commands } from "../../commands"
import { Runtime } from "../../../framework/runtime"
import { ServerConnection } from "../../../services/server-connection"
@@ -13,8 +14,14 @@ const handler = Effect.fn("cli.debug.heap-dump")(function* (
) {
const endpoint = yield* running(Option.getOrUndefined(input.server))
const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })
// The server writes the file, so a relative directory resolves against this shell. An absolute one passes through
// untouched, which keeps a POSIX path for a remote server intact on Windows.
const directory = Option.match(input.directory, {
onNone: () => undefined,
onSome: (value) => (path.isAbsolute(value) ? value : path.resolve(value)),
})
const snapshot = yield* Effect.tryPromise({
try: (signal) => client.debug.heapDump({ signal }),
try: (signal) => client.debug.heapDump({ directory }, { signal }),
catch: (cause) =>
cause instanceof ClientError &&
cause.reason === "UnexpectedStatus" &&
@@ -23,6 +30,12 @@ const handler = Effect.fn("cli.debug.heap-dump")(function* (
? new Error(`The server at ${endpoint.url} does not support heap dumps. Update and restart it first.`)
: cause,
})
// Servers released before `directory` existed ignore it and write into their log directory. The server joins the
// directory and file name, so join the same way, with the path style of the server's machine: that tolerates a
// trailing separator and keeps a POSIX path from a remote server intact on Windows.
const style = /^([A-Za-z]:|\\\\)/.test(snapshot.path) ? path.win32 : path.posix
if (directory !== undefined && style.join(directory, style.basename(snapshot.path)) !== snapshot.path)
process.stderr.write(`The server ignored --directory. Update and restart it to choose where snapshots go.${EOL}`)
process.stdout.write(snapshot.path + EOL)
})
+27
View File
@@ -35,6 +35,33 @@ test("prints the snapshot path from the registered server without replacing it",
expect(await Bun.file(registration.file).json()).toEqual(registration.info)
})
test("sends --directory as an absolute path and warns only when the server ignores it", async () => {
await using root = await tmpdir()
// The command runs from packages/cli (see `cli`), so a relative directory resolves there.
const directory = path.join(import.meta.dir, "..", "snapshots")
const sent: Array<string | null> = []
using server = fake((request) => {
const requested = new URL(request.url).searchParams.get("directory") ?? ""
sent.push(requested)
// Answer like a current server, which joins the directory and file name, for the first request, and like one
// that predates `directory` for the second.
const folder = sent.length === 1 ? requested : "/server/log"
return Response.json({ path: path.join(folder, "heap-1-2.heapsnapshot"), pid: process.pid })
})
await register(root.path, server.url.href)
// A trailing separator is not a different directory.
const current = await cli(root.path, ["debug", "heap-dump", "--directory", directory + path.sep])
const old = await cli(root.path, ["debug", "heap-dump", "--directory", "snapshots"])
expect(sent).toEqual([directory + path.sep, directory])
expect([current, old].map((result) => ({ code: result.code, stderr: result.stderr.trim() }))).toEqual([
{ code: 0, stderr: "" },
{ code: 0, stderr: "The server ignored --directory. Update and restart it to choose where snapshots go." },
])
expect(current.stdout.trim()).toBe(path.join(directory, "heap-1-2.heapsnapshot"))
})
test("fails without starting a server when none is registered", async () => {
await using root = await tmpdir()
+2 -1
View File
@@ -2269,8 +2269,9 @@ export interface VcsApi<E = never> {
readonly diff: VcsDiffOperation<E>
}
export type DebugHeapDumpInput = { readonly directory?: string | undefined }
export type DebugHeapDumpOutput = { readonly path: string; readonly pid: number }
export type DebugHeapDumpOperation<E = never> = () => Effect.Effect<DebugHeapDumpOutput, E>
export type DebugHeapDumpOperation<E = never> = (input?: DebugHeapDumpInput) => Effect.Effect<DebugHeapDumpOutput, E>
export type DebugLocationListOutput = ReadonlyArray<Location.PublicRef>
export type DebugLocationListOperation<E = never> = () => Effect.Effect<DebugLocationListOutput, E>
@@ -266,6 +266,7 @@ import type {
VcsBranchListOutput,
VcsDiffInput,
VcsDiffOutput,
DebugHeapDumpInput,
DebugHeapDumpOutput,
DebugLocationListOutput,
DebugLocationEvictInput,
@@ -1625,8 +1626,10 @@ const adaptGroupVcs = (raw: RawClient["server.vcs"]) => ({
diff: EndpointVcsDiff(raw),
})
const EndpointDebugHeapDump = (raw: RawClient["server.debug"]) => () =>
preserveEffect<DebugHeapDumpOutput>()(raw["debug.heapDump"]({}).pipe(Effect.mapError(mapClientError)))
const EndpointDebugHeapDump = (raw: RawClient["server.debug"]) => (input?: DebugHeapDumpInput) =>
preserveEffect<DebugHeapDumpOutput>()(
raw["debug.heapDump"]({ query: { directory: input?.["directory"] } }).pipe(Effect.mapError(mapClientError)),
)
const EndpointDebugLocationList = (raw: RawClient["server.debug"]) => () =>
preserveEffect<DebugLocationListOutput>()(raw["debug.location"]({}).pipe(Effect.mapError(mapClientError)))
@@ -264,6 +264,7 @@ import type {
VcsBranchListOutput,
VcsDiffInput,
VcsDiffOutput,
DebugHeapDumpInput,
DebugHeapDumpOutput,
DebugLocationListOutput,
DebugLocationEvictInput,
@@ -2221,11 +2222,12 @@ export function make(options: ClientOptions) {
),
},
debug: {
heapDump: (requestOptions?: RequestOptions) =>
heapDump: (input?: DebugHeapDumpInput, requestOptions?: RequestOptions) =>
request<DebugHeapDumpOutput>(
{
method: "POST",
path: `/api/debug/heap-dump`,
query: { directory: input?.["directory"] },
successStatus: 200,
declaredStatuses: [400, 401, 500],
empty: false,
@@ -6019,6 +6019,8 @@ export type VcsDiffInput = {
export type VcsDiffOutput = { location: LocationPublicRef; data: Array<FileDiffInfo> }
export type DebugHeapDumpInput = { readonly directory?: { readonly directory?: string | undefined }["directory"] }
export type DebugHeapDumpOutput = { path: string; pid: number }
export type DebugLocationListOutput = Array<LocationPublicRef>
+1 -1
View File
@@ -663,7 +663,7 @@ export default setup
export const builtins = Extension.compose(
context,
btw,
debug,
{ ...debug, main: () => import("./debug/main") },
terminal,
file,
review,
@@ -0,0 +1,25 @@
import { Schema } from "effect"
import { Ipc } from "../sdk"
/**
* Captures memory for debugging leaks. Heap snapshots of the main process and every app window can only be taken
* from main, and the desktop server's snapshot is moved next to them, so one folder holds the whole app.
*/
export const HeapSnapshots = Ipc.define({
id: "debug.heap",
methods: {
/**
* Writes heap snapshots of the desktop's own server, every app window and the main process into a new folder,
* with a `manifest.json` written last. One capture runs at a time; a second call waits for the first. A snapshot
* that fails is recorded in the manifest and the others are still written.
*/
write: {
output: Schema.Struct({
/** The new folder. */
directory: Schema.String,
/** Whether every snapshot was written. */
complete: Schema.Boolean,
}),
},
},
})
@@ -1,5 +1,12 @@
export default {
"command.toggle": "Toggle debug bar",
"command.heap": "Capture heap snapshots",
"command.heap.description": "Saves the memory of the app and its server to a folder",
"heap.loading": "Capturing heap snapshots…",
"heap.done": "Heap snapshots saved",
"heap.partial": "Some heap snapshots failed. See manifest.json.",
"heap.failed": "Could not capture heap snapshots",
"heap.reveal": "Show in folder",
"status.toggle": "Toggle debug tools",
ariaLabel: "Development performance diagnostics",
providerAriaLabel: "Provider performance diagnostics",
@@ -1,8 +1,10 @@
import { Extension } from "../sdk"
import { HeapSnapshots } from "./contract"
import en from "./i18n/en"
export default Extension.define({
id: "debug",
provides: { heap: HeapSnapshots },
i18n: {
en,
am: () => import("./i18n/am"),
+108
View File
@@ -0,0 +1,108 @@
import { app, type BrowserWindow } from "electron"
import { mkdir, writeFile } from "node:fs/promises"
import path from "node:path"
import { writeHeapSnapshot } from "node:v8"
import type { MainSetup } from "../sdk/main"
import { HeapSnapshots } from "./contract"
import type definition from "./index"
import { captureServer } from "./server-heap"
/** A desktop process the manifest lists: the file written, or why there is none. */
type Snapshot = { readonly process: "main" | "window"; readonly pid: number; readonly window?: number } & (
| { readonly file: string }
| { readonly error: string }
)
/** The last capture; the next one starts after it settles. */
type Queue = { tail: Promise<unknown> }
const setup: MainSetup<typeof definition> = (ctx) => {
const queue: Queue = { tail: Promise.resolve() }
const capture = async () => {
const directory = path.join(
app.getPath("downloads"),
`opencode-heap-${new Date().toISOString().replace(/[:.]/g, "")}`,
)
// Snapshots hold prompts, file contents and credentials. Recursive, because Downloads can be missing on Linux.
await mkdir(directory, { recursive: true, mode: 0o700 })
ctx.log.write("info", "capturing heap snapshots", { directory })
// The server is another process, so it serializes its heap while the windows do. Windows go one at a time: a
// snapshot can double a process's memory, and a leaking app may not have room for every window at once. Main goes
// last: writing its own heap blocks the loop that receives the others.
const [serverSnapshot, windows] = await Promise.all([
captureServer(ctx.serverEndpoints.get("sidecar"), directory, ctx.scope.signal),
(async () => {
const list: Snapshot[] = []
for (const window of ctx.windows.list()) list.push(await captureWindow(window, directory))
return list
})(),
])
const main = await Promise.resolve()
.then(() => writeHeapSnapshot(path.join(directory, `main-${process.pid}.heapsnapshot`)))
.then(
(file): Snapshot => ({ process: "main", pid: process.pid, file: path.basename(file) }),
(error: Error): Snapshot => ({ process: "main", pid: process.pid, error: error.message }),
)
const snapshots = [serverSnapshot, ...windows, main]
// Written last, so a script can wait for it.
await writeFile(
path.join(directory, "manifest.json"),
JSON.stringify(
{
created: new Date().toISOString(),
app: {
name: app.getName(),
version: app.getVersion(),
packaged: app.isPackaged,
platform: process.platform,
arch: process.arch,
versions: process.versions,
},
snapshots,
// Per-process memory as the OS sees it: a process that grows while its heap does not leaks native memory.
metrics: app.getAppMetrics(),
metricsMemoryUnit: "KiB",
mainMemory: process.memoryUsage(),
},
null,
2,
),
{ mode: 0o600 },
)
const complete = snapshots.every((snapshot) => !("error" in snapshot))
ctx.log.write(complete ? "info" : "warn", "heap snapshots captured", { directory, complete })
return { directory, complete }
}
ctx.provide(HeapSnapshots, {
// A window that closes meanwhile does not cancel the capture.
write: () => {
const run = queue.tail.then(capture)
queue.tail = run.catch(() => undefined)
return run
},
})
}
function captureWindow(window: BrowserWindow, directory: string) {
const contents = window.webContents
const pid = contents.getOSProcessId()
const file = `window-${window.id}-${pid}.heapsnapshot`
return contents.takeHeapSnapshot(path.join(directory, file)).then(
(): Snapshot => ({ process: "window", pid, window: window.id, file }),
(error: Error): Snapshot => ({ process: "window", pid, window: window.id, error: error.message }),
)
}
export default setup
+40 -1
View File
@@ -1,5 +1,6 @@
import { showToast, toaster } from "@opencode/ui/toast"
import { createSignal, lazy, Show, Suspense } from "solid-js"
import { Command, Slot, TitlebarItem, type Setup } from "../sdk"
import { createKeyed, Command, Slot, TitlebarItem, type Setup } from "../sdk"
import type Debug from "./index"
const setup: Setup<typeof Debug> = (ctx) => {
@@ -22,6 +23,44 @@ const setup: Setup<typeof Debug> = (ctx) => {
}),
)
const desktop = ctx.desktop
// Offered only while main answers: never on the web, and not while the extension restarts.
if (desktop)
createKeyed(ctx.uses.heap, (heap) =>
ctx.add(Command, {
id: "heap",
get title() {
return ctx.t("command.heap")
},
get description() {
return ctx.t("command.heap.description")
},
get group() {
return ctx.t("command.category.settings")
},
run: async () => {
const loading = showToast({ variant: "loading", title: ctx.t("heap.loading"), persistent: true })
const result = await heap.write({ signal: ctx.signal }).catch(() => undefined)
toaster.dismiss(loading)
if (ctx.signal.aborted) return
if (!result) return void showToast({ variant: "error", title: ctx.t("heap.failed") })
showToast({
variant: result.complete ? "success" : "error",
title: ctx.t(result.complete ? "heap.done" : "heap.partial"),
description: result.directory,
persistent: true,
actions: [{ label: ctx.t("heap.reveal"), onClick: () => void desktop.reveal(result.directory) }],
})
},
}),
)
ctx.add(Slot, {
at: "window.bottom",
render: () => (
@@ -0,0 +1,56 @@
import { GlobalRegistrator } from "@happy-dom/global-registrator"
import { afterAll, beforeAll, expect, test } from "bun:test"
import os from "node:os"
import path from "node:path"
import { captureServer } from "./server-heap"
// Main-process code: run it with the runtime's own fetch and Response, as Electron's main process has, not happy-dom's.
beforeAll(() => GlobalRegistrator.unregister())
afterAll(() => GlobalRegistrator.register())
test("asks the server to write into the folder, and records where an older server wrote instead", async () => {
const directory = path.join(os.tmpdir(), "opencode-heap-capture")
const requests: string[] = []
using server = Bun.serve({
hostname: "127.0.0.1",
port: 0,
fetch: (request) => {
const url = new URL(request.url)
requests.push(
`${request.method} ${url.pathname} ${url.searchParams.get("directory")} ${request.headers.get("authorization")}`,
)
// The first answer is a current server's; the second is one that predates `directory` and used its log folder.
const folder = requests.length === 1 ? (url.searchParams.get("directory") ?? "") : path.join(os.tmpdir(), "log")
return Response.json({ path: path.join(folder, "heap-42-1.heapsnapshot"), pid: 42 })
},
})
const endpoint = { id: "sidecar", url: server.url.href, headers: { authorization: "Basic secret" }, local: true }
const current = await captureServer(endpoint, directory, AbortSignal.timeout(10_000))
const old = await captureServer(endpoint, directory, AbortSignal.timeout(10_000))
expect({ current, old, requests }).toEqual({
current: { process: "server", pid: 42, file: "heap-42-1.heapsnapshot" },
old: { process: "server", pid: 42, path: path.join(os.tmpdir(), "log", "heap-42-1.heapsnapshot") },
requests: [
`POST /api/debug/heap-dump ${directory} Basic secret`,
`POST /api/debug/heap-dump ${directory} Basic secret`,
],
})
})
test("records why the server has no snapshot", async () => {
using server = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response(null, { status: 404 }) })
const endpoint = { id: "sidecar", url: server.url.href, headers: {}, local: true }
expect([
await captureServer(undefined, os.tmpdir(), AbortSignal.timeout(10_000)),
await captureServer(endpoint, os.tmpdir(), AbortSignal.timeout(10_000)),
]).toEqual([
{ process: "server", error: "The server is not running." },
{ process: "server", error: "The server does not support heap dumps. Update and restart it." },
])
})
@@ -0,0 +1,58 @@
import { ClientError, OpenCode } from "@opencode/client/promise"
import { Predicate } from "effect"
import path from "node:path"
import type { ServerEndpoint } from "../sdk/main"
/**
* What the manifest records about the desktop server's snapshot.
* - `file`: the server wrote it into the folder.
* - `path`: the server wrote it elsewhere, because it predates choosing a directory and used its log directory.
* Snapshots are large, so it is not moved or copied.
* - `error`: nothing was captured.
*/
export type ServerSnapshot =
| { readonly process: "server"; readonly pid: number; readonly file: string }
| { readonly process: "server"; readonly pid: number; readonly path: string }
| { readonly process: "server"; readonly error: string }
/**
* Asks the desktop's own server to write a heap snapshot into `directory`. Never rejects: a failure becomes an
* `error` entry.
*
* @param endpoint - The desktop's server, or undefined while it is not running.
* @param directory - An absolute folder on this machine; the server creates it when missing.
* @param signal - Aborts the request; the server still finishes the file it started.
*/
export async function captureServer(
endpoint: ServerEndpoint | undefined,
directory: string,
signal: AbortSignal,
): Promise<ServerSnapshot> {
if (!endpoint) return { process: "server", error: "The server is not running." }
return OpenCode.make({ baseUrl: endpoint.url, headers: endpoint.headers })
.debug.heapDump({ directory }, { signal })
.then(
(snapshot): ServerSnapshot =>
// The server joins the directory and file name, so the same join recognizes a snapshot it wrote there.
path.join(directory, path.basename(snapshot.path)) === snapshot.path
? { process: "server", pid: snapshot.pid, file: path.basename(snapshot.path) }
: { process: "server", pid: snapshot.pid, path: snapshot.path },
(error: Error): ServerSnapshot => ({
process: "server",
error: unsupported(error)
? "The server does not support heap dumps. Update and restart it."
: error.message || String(error),
}),
)
}
// Servers released before the endpoint answer 404.
function unsupported(error: Error) {
return (
error instanceof ClientError &&
error.reason === "UnexpectedStatus" &&
Predicate.hasProperty(error.cause, "status") &&
error.cause.status === 404
)
}
+1 -1
View File
@@ -20,7 +20,7 @@ import microsoftOffice from "./microsoft-office"
export const builtins = Extension.compose(
context,
btw,
debug,
{ ...debug, main: () => import("./debug/main") },
terminal,
file,
review,
+19 -2
View File
@@ -13420,7 +13420,24 @@
"post": {
"tags": ["debug"],
"operationId": "debug.heapDump",
"parameters": [],
"parameters": [
{
"name": "directory",
"in": "query",
"schema": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"description": "Absolute server-local directory to write the snapshot into, created when missing. Defaults to the server's log directory."
},
"required": false
}
],
"security": [],
"responses": {
"200": {
@@ -13474,7 +13491,7 @@
}
}
},
"description": "Write a JavaScript heap snapshot of the server process into its log directory and return the server-local path once the file is complete. Pauses the server while the heap serializes and can temporarily increase its memory use. The snapshot can contain credentials, prompts, and file contents.",
"description": "Write a JavaScript heap snapshot of the server process into its log directory, or the requested directory, and return the server-local path once the file is complete. Pauses the server while the heap serializes and can temporarily increase its memory use. The snapshot can contain credentials, prompts, and file contents.",
"summary": "Write a heap snapshot"
}
},
+12 -3
View File
@@ -1,20 +1,29 @@
import { Location } from "@opencode/schema/location"
import { Schema } from "effect"
import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from "effect/http-api"
import { UnknownError } from "../errors.js"
import { InvalidRequestError, UnknownError } from "../errors.js"
import { LocationQuery, locationQueryOpenApi } from "./location.js"
export const DebugGroup = HttpApiGroup.make("server.debug")
.add(
HttpApiEndpoint.post("debug.heapDump", "/api/debug/heap-dump", {
query: Schema.Struct({
directory: Schema.String.pipe(
Schema.optional,
Schema.annotate({
description:
"Absolute server-local directory to write the snapshot into, created when missing. Defaults to the server's log directory.",
}),
),
}),
success: Schema.Struct({ path: Schema.String, pid: Schema.Int }),
error: UnknownError,
error: [InvalidRequestError, UnknownError],
}).annotateMerge(
OpenApi.annotations({
identifier: "debug.heapDump",
summary: "Write a heap snapshot",
description:
"Write a JavaScript heap snapshot of the server process into its log directory and return the server-local path once the file is complete. Pauses the server while the heap serializes and can temporarily increase its memory use. The snapshot can contain credentials, prompts, and file contents.",
"Write a JavaScript heap snapshot of the server process into its log directory, or the requested directory, and return the server-local path once the file is complete. Pauses the server while the heap serializes and can temporarily increase its memory use. The snapshot can contain credentials, prompts, and file contents.",
}),
),
)
+12 -4
View File
@@ -1,9 +1,10 @@
import { LocationServiceMap } from "@opencode/core/location-service-map"
import { UnknownError } from "@opencode/protocol/errors"
import { InvalidRequestError, UnknownError } from "@opencode/protocol/errors"
import { Global } from "@opencode/util/global"
import { HeapSnapshot } from "@opencode/util/heap-snapshot"
import { Effect, Option, RcMap } from "effect"
import { HttpApiBuilder } from "effect/http-api"
import path from "node:path"
import { Api } from "../api"
import { requestRef } from "../location"
@@ -13,15 +14,22 @@ export const DebugHandler = HttpApiBuilder.group(Api, "server.debug", (handlers)
return handlers
.handle(
"debug.heapDump",
Effect.fn("server.debug.heapDump")(function* () {
return yield* HeapSnapshot.write(global.log).pipe(
Effect.fn("server.debug.heapDump")(function* (ctx) {
const directory = ctx.query.directory
if (directory !== undefined && !path.isAbsolute(directory))
return yield* new InvalidRequestError({ message: "directory must be an absolute path", field: "directory" })
return yield* HeapSnapshot.write(directory ?? global.log).pipe(
Effect.catch((cause) => {
const ref = `err_${crypto.randomUUID().slice(0, 8)}`
return Effect.logError("failed to write heap snapshot", { cause }).pipe(
Effect.annotateLogs({ ref }),
Effect.andThen(
// The reason (a missing permission, a file where the directory should be) is usually the caller's to fix.
Effect.fail(
new UnknownError({ message: "Failed to write heap snapshot. Check server logs for details.", ref }),
new UnknownError({
message: `Failed to write heap snapshot: ${cause.cause instanceof Error ? cause.cause.message : cause.message}`,
ref,
}),
),
),
)
+39 -3
View File
@@ -22,8 +22,18 @@ const server = Effect.fnUntraced(function* (root: string) {
},
{ overrides: [Global.node.replace(Global.layerWith({ config: path.join(root, "config"), log }))] },
)
const dump = (headers: Record<string, string> = { authorization }) =>
Effect.promise(() => handler(new Request("http://opencode.local/api/debug/heap-dump", { method: "POST", headers })))
const dump = (headers: Record<string, string> = { authorization }, directory?: string) =>
Effect.promise(() =>
handler(
new Request(
`http://opencode.local/api/debug/heap-dump${directory === undefined ? "" : `?directory=${encodeURIComponent(directory)}`}`,
{
method: "POST",
headers,
},
),
),
)
return { log, dump }
})
@@ -74,7 +84,10 @@ it.live(
expect(failed.status).toBe(500)
expect(yield* Effect.promise(() => failed.json())).toMatchObject({
_tag: "UnknownError",
message: "Failed to write heap snapshot. Check server logs for details.",
// The filesystem's own reason, naming the path it could not create.
message: expect.stringMatching(
new RegExp(`^Failed to write heap snapshot: E[A-Z]+: .*${RegExp.escape(api.log)}`),
),
ref: expect.stringMatching(/^err_/),
})
@@ -86,3 +99,26 @@ it.live(
}),
30_000,
)
it.live(
"writes into a requested directory, creating it, and rejects a relative one",
() =>
Effect.gen(function* () {
const root = yield* Effect.acquireDisposable(Effect.promise(() => tmpdir("opencode-heap-dump-")))
const api = yield* server(root.path)
const directory = path.join(root.path, "capture", "nested")
const relative = yield* api.dump(undefined, "capture")
expect(relative.status).toBe(400)
expect(yield* Effect.promise(() => relative.json())).toMatchObject({ _tag: "InvalidRequestError" })
const written = yield* api.dump(undefined, directory)
expect(written.status).toBe(200)
const result: { path: string } = yield* Effect.promise(() => written.json())
expect(path.dirname(result.path)).toBe(directory)
expect(yield* Effect.promise(() => fs.readdir(directory))).toEqual([path.basename(result.path)])
const logged = yield* Effect.promise(() => fs.readdir(api.log).catch(() => []))
expect(logged.filter((file) => file.endsWith(".heapsnapshot"))).toEqual([])
}),
30_000,
)
+19 -2
View File
@@ -13420,7 +13420,24 @@
"post": {
"tags": ["debug"],
"operationId": "debug.heapDump",
"parameters": [],
"parameters": [
{
"name": "directory",
"in": "query",
"schema": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"description": "Absolute server-local directory to write the snapshot into, created when missing. Defaults to the server's log directory."
},
"required": false
}
],
"security": [],
"responses": {
"200": {
@@ -13474,7 +13491,7 @@
}
}
},
"description": "Write a JavaScript heap snapshot of the server process into its log directory and return the server-local path once the file is complete. Pauses the server while the heap serializes and can temporarily increase its memory use. The snapshot can contain credentials, prompts, and file contents.",
"description": "Write a JavaScript heap snapshot of the server process into its log directory, or the requested directory, and return the server-local path once the file is complete. Pauses the server while the heap serializes and can temporarily increase its memory use. The snapshot can contain credentials, prompts, and file contents.",
"summary": "Write a heap snapshot"
}
},
+19 -2
View File
@@ -13420,7 +13420,24 @@
"post": {
"tags": ["debug"],
"operationId": "debug.heapDump",
"parameters": [],
"parameters": [
{
"name": "directory",
"in": "query",
"schema": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"description": "Absolute server-local directory to write the snapshot into, created when missing. Defaults to the server's log directory."
},
"required": false
}
],
"security": [],
"responses": {
"200": {
@@ -13474,7 +13491,7 @@
}
}
},
"description": "Write a JavaScript heap snapshot of the server process into its log directory and return the server-local path once the file is complete. Pauses the server while the heap serializes and can temporarily increase its memory use. The snapshot can contain credentials, prompts, and file contents.",
"description": "Write a JavaScript heap snapshot of the server process into its log directory, or the requested directory, and return the server-local path once the file is complete. Pauses the server while the heap serializes and can temporarily increase its memory use. The snapshot can contain credentials, prompts, and file contents.",
"summary": "Write a heap snapshot"
}
},
@@ -531,6 +531,12 @@ Write a heap snapshot of the running background server and print its path.
$ opencode debug heap-dump
```
Write the snapshot into a directory of your choice.
```bash
$ opencode debug heap-dump --directory ./snapshots
```
Show global paths.
```bash
@@ -125,8 +125,15 @@ The command waits until the snapshot is complete, then prints its path:
/home/me/.local/share/opencode/log/heap-48213-2026-10-23T013012345Z.heapsnapshot
```
Write it somewhere else with `--directory`. The server creates the directory when it is missing:
```bash
opencode debug heap-dump --directory ./snapshots
```
- It only uses a server that is already running. It never starts, replaces, or restarts one.
- Use `--server <url>` to capture a server you started with `opencode serve`. Set `OPENCODE_PASSWORD` if it has one.
`--directory` is then a path on the server's machine.
- Open the file in the Memory panel of Chrome DevTools.
<Callout type="warning">
@@ -134,6 +141,23 @@ The command waits until the snapshot is complete, then prints its path:
contain prompts, file contents, and credentials. Do not share it publicly.
</Callout>
### In the desktop app
Run **Capture heap snapshots** from the command palette. It writes one folder in your Downloads folder with a snapshot of
each part of the app:
```text
opencode-heap-2026-10-23T013012345Z/
heap-48213-….heapsnapshot the desktop's own server
window-1-48390.heapsnapshot one per app window
main-48102.heapsnapshot the desktop main process
manifest.json processes, PIDs, and per-process memory; written last
```
- Remote servers are not captured. Use `opencode debug heap-dump` on that machine instead.
- The server writes its snapshot straight into the folder, so nothing large is moved or copied.
- Browser tabs are not included, because their snapshots contain the content of the pages you visited.
## Capture CPU and memory profiles
On macOS and Linux, you can signal a running OpenCode process to capture diagnostic data. Get the background server PID