# Desktop window lifecycle

One process, one main window. Torn-off windows are extra and short-lived.

1. **app.whenReady, activate, second-instance** launch, Dock click, click while starting
2. **ensureMainWindow** one in-flight create
3. **Main window**

`createWindow` is async. Until its first `BrowserWindow` exists, `getAllWindows()` is empty, so unguarded events would each create a window with id `main`, leaving two identical windows.

| Event | Action |
| --- | --- |
| Ready, no live main | Create one |
| Any of the three, create in flight | Join it |
| Live main exists | Restore, show, focus |
| Main was destroyed | Create one |
| Second OS process | Quit; the first handles the click |
| Torn-off window | Not a main: own id, no persisted bounds |

## Code

- **`windows.get("main")`**: The live main
- **`createMainWindowGate({ windows, createWindow })`**: Returns `ensureMainWindow`, the only entry that creates or reuses it
- **`registerSingleMainWindow({ app, BrowserWindow, ensureMainWindow, recoverErroredWindows, onReady })`**: Takes the single-instance lock and wires the events. `onReady` (IPC, menu, theme) runs once, before the first `ensureMainWindow()`.
- **`createWindow({ detached: true })`**: The tear-off path

`apps/desktop/main/windows/window-lifecycle.js`, `apps/desktop/main.js`. Harness: `apps/desktop/tests/windows/check-window-lifecycle.js`.

## Not windows

- The LaunchAgent `ai.openprogram.worker` keeps the worker on port 18100. A slow worker may flash the error page and reload, in one window.
- Worker start, `ui.open_browser` and packing the `.app` do not create the main `BrowserWindow`. With the desktop shell as UI, do not open the system browser to `127.0.0.1:18100`.

[Window state](https://fzkuji.github.io/OpenProgram/docs/reference/design/ui/desktop/window-state.html) · [Moving tabs between windows](https://fzkuji.github.io/OpenProgram/docs/reference/design/ui/desktop/window-tab-transfer.html)
