11import { app , contentTracing , screen , type BrowserWindow } from "electron"
22import { Schema } from "effect"
3- import { mkdir , readFile , writeFile } from "node:fs/promises"
3+ import { mkdir , readFile , stat , writeFile } from "node:fs/promises"
44import path from "node:path"
55import { getHeapSpaceStatistics , getHeapStatistics , writeHeapSnapshot } from "node:v8"
66import type { MainSetup } from "../sdk/main"
@@ -10,6 +10,8 @@ import { summarize, traceConfig } from "./memory-infra"
1010import { startMemoryLog } from "./memory-log"
1111import { debugBuild , memoryLogInterval } from "./options"
1212import { captureServer } from "./server-heap"
13+ import { signalIncludesServer , snapshotDirectory } from "./signal"
14+ import { ProcessSignal } from "@opencode/util/process-signal"
1315
1416/** A desktop process the manifest lists: the file written, or why there is none. */
1517type Snapshot = { readonly process : "main" | "window" ; readonly pid : number ; readonly window ?: number } & (
@@ -58,15 +60,12 @@ type Running = { stop?: () => void }
5860const setup : MainSetup < typeof definition > = ( ctx ) => {
5961 const queue : Queue = { tail : Promise . resolve ( ) }
6062
61- const capture = async ( ) => {
62- const directory = path . join (
63- app . getPath ( "downloads" ) ,
64- `opencode-heap-${ new Date ( ) . toISOString ( ) . replace ( / [: .] / g, "" ) } ` ,
65- )
63+ const capture = async ( root : string , includeServer : boolean ) => {
64+ const directory = path . join ( root , `opencode-heap-${ new Date ( ) . toISOString ( ) . replace ( / [: .] / g, "" ) } ` )
6665
6766 // Snapshots hold prompts, file contents and credentials. Recursive, because Downloads can be missing on Linux.
6867 await mkdir ( directory , { recursive : true , mode : 0o700 } )
69- ctx . log . write ( "info" , "capturing heap snapshots" , { directory } )
68+ ctx . log . write ( "info" , "capturing heap snapshots" , { directory, includeServer } )
7069
7170 // Measurements first: writing a heap snapshot raises the memory of the process it serializes.
7271 const before = {
@@ -85,7 +84,7 @@ const setup: MainSetup<typeof definition> = (ctx) => {
8584 // snapshot can double a process's memory, and a leaking app may not have room for every window at once. Main goes
8685 // last: writing its own heap blocks the loop that receives the others.
8786 const [ serverSnapshot , windowSnapshots ] = await Promise . all ( [
88- captureServer ( ctx . serverEndpoints . get ( "sidecar" ) , directory , ctx . scope . signal ) ,
87+ includeServer ? captureServer ( ctx . serverEndpoints . get ( "sidecar" ) , directory , ctx . scope . signal ) : undefined ,
8988 ( async ( ) => {
9089 const list : Snapshot [ ] = [ ]
9190
@@ -102,21 +101,39 @@ const setup: MainSetup<typeof definition> = (ctx) => {
102101 ( error : Error ) : Snapshot => ( { process : "main" , pid : process . pid , error : error . message } ) ,
103102 )
104103
105- const snapshots = [ serverSnapshot , ...windowSnapshots , main ]
104+ const snapshots = await Promise . all (
105+ [ ...( serverSnapshot ? [ serverSnapshot ] : [ ] ) , ...windowSnapshots , main ] . map ( async ( snapshot ) => {
106+ if ( "error" in snapshot ) return snapshot
107+ const file = "file" in snapshot ? path . join ( directory , snapshot . file ) : snapshot . path
108+
109+ const bytes = await stat ( file ) . then (
110+ ( info ) => info . size ,
111+ ( ) => null ,
112+ )
113+
114+ ctx . log . write ( "info" , "heap snapshot written" , { file, bytes } )
115+
116+ return { ...snapshot , bytes }
117+ } ) ,
118+ )
106119 const gpu = await app . getGPUInfo ( "basic" ) . catch ( ( error : Error ) => ( { error : error . message } ) )
107120
108121 // One readable answer to "where is the memory", per process, in MiB.
109122 await write ( directory , "memory.json" , {
110123 unit : "MiB" ,
111124 native : "summary" in native ? native . summary : native ,
112- server : "error" in serverSnapshot || ! serverSnapshot . memory ? undefined : mibs ( serverSnapshot . memory ) ,
125+ server :
126+ ! serverSnapshot || "error" in serverSnapshot || ! serverSnapshot . memory
127+ ? undefined
128+ : mibs ( serverSnapshot . memory ) ,
113129 pages,
114130 note : "native: Chromium's memory-infra dump per process, before the heap snapshots. Some allocators overlap: cc, skia, gpu and web_cache report memory that malloc, discardable or shared_memory also count. pages: what each app window's page held. server: the server's process.memoryUsage()." ,
115131 } )
116132 await write ( directory , "gpu.json" , gpu )
117133 // Written last, so a script can wait for it.
118134 await write ( directory , "manifest.json" , {
119135 created : new Date ( ) . toISOString ( ) ,
136+ includeServer,
120137 app : {
121138 name : app . getName ( ) ,
122139 version : app . getVersion ( ) ,
@@ -144,14 +161,16 @@ const setup: MainSetup<typeof definition> = (ctx) => {
144161 return { directory, complete }
145162 }
146163
164+ const enqueue = ( directory : string , includeServer : boolean ) => {
165+ const run = queue . tail . then ( ( ) => capture ( directory , includeServer ) )
166+ queue . tail = run . catch ( ( ) => undefined )
167+
168+ return run
169+ }
170+
147171 ctx . provide ( HeapSnapshots , {
148172 // A window that closes meanwhile does not cancel the capture.
149- write : ( ) => {
150- const run = queue . tail . then ( capture )
151- queue . tail = run . catch ( ( ) => undefined )
152-
153- return run
154- } ,
173+ write : ( ) => enqueue ( app . getPath ( "downloads" ) , true ) ,
155174 } )
156175
157176 if ( ! debugBuild ( ctx . build ) ) return
@@ -160,11 +179,41 @@ const setup: MainSetup<typeof definition> = (ctx) => {
160179 const envInterval = memoryLogInterval ( process . env . OPENCODE_DESKTOP_MEMORY_LOG )
161180 const stored = ctx . stores . memory
162181 const running : Running = { }
182+ const directory = process . platform === "win32" ? undefined : snapshotDirectory ( process . env )
183+ let capturing = false
184+
185+ const onSignal = ( ) => {
186+ // Signals coalesce while a capture is running; repeated signals must not fill the disk with queued dumps.
187+ if ( ! directory || capturing || ctx . scope . signal . aborted ) return
188+ capturing = true
189+ void enqueue ( directory , signalIncludesServer ( process . env ) )
190+ . catch ( ( error : Error ) => ctx . log . write ( "error" , "heap snapshot capture failed" , { error : error . message } ) )
191+ . finally ( ( ) => {
192+ capturing = false
193+ } )
194+ }
195+
196+ const start = ( ) => {
197+ const stopLog = startMemoryLog ( envInterval ?? 30_000 , ctx . log )
198+
199+ if ( ! directory ) return stopLog
200+
201+ // Installed the first time diagnostics turn on, and kept: a script's late signal while they are off, or while
202+ // the extension reloads, is logged and ignored instead of killing the app.
203+ ProcessSignal . install ( "SIGUSR2" , ( ) => ctx . log . write ( "warn" , "heap snapshot signal ignored: diagnostics are off" ) )
204+ const unsubscribe = ProcessSignal . subscribe ( "SIGUSR2" , onSignal )
205+ ctx . log . write ( "info" , "heap snapshot signal enabled" , { pid : process . pid , signal : "SIGUSR2" , directory } )
206+
207+ return ( ) => {
208+ unsubscribe ( )
209+ stopLog ( )
210+ }
211+ }
163212
164213 const sync = ( ) => {
165214 const on = envInterval !== undefined || stored . value
166215
167- if ( on && ! running . stop ) running . stop = startMemoryLog ( envInterval ?? 30_000 , ctx . log )
216+ if ( on && ! running . stop ) running . stop = start ( )
168217
169218 if ( on || ! running . stop ) return
170219 running . stop ( )
0 commit comments