@acryldev/blends 1.7.31 → 1.7.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@acryldev/blends",
3
- "version": "1.7.31",
3
+ "version": "1.7.33",
4
4
  "description": "The Acryl web framework (import { Acryl } from \"acrylblends\") and the acrylblends command that scaffolds Cordis apps.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -38,13 +38,22 @@ export function nextRestart(
38
38
 
39
39
  const KEEP_DAYS = 14
40
40
 
41
- /** The host's output, one file a day (`host-YYYY-MM-DD.log`) in the app's logs folder; files older than two weeks go. Never throws: a log must not stop the app. */
42
- export function appendHostLog(dir: string, text: string, now: Date = new Date()): void {
41
+ /**
42
+ * The host's output, one file a day (`host-YYYY-MM-DD.log`) in the app's logs folder; files older than two weeks go. Never throws: a log must not stop the app.
43
+ * `prefix` names another log of the same kind (the window's own start, `desktop-YYYY-MM-DD.log`).
44
+ */
45
+ export function appendHostLog(
46
+ dir: string,
47
+ text: string,
48
+ now: Date = new Date(),
49
+ prefix: 'host' | 'desktop' = 'host',
50
+ ): void {
43
51
  try {
44
52
  mkdirSync(dir, { recursive: true })
45
- appendFileSync(join(dir, `host-${now.toISOString().slice(0, 10)}.log`), text)
53
+ appendFileSync(join(dir, `${prefix}-${now.toISOString().slice(0, 10)}.log`), text)
54
+ const own = new RegExp(`^${prefix}-\\d{4}-\\d{2}-\\d{2}\\.log$`, 'u')
46
55
  for (const name of readdirSync(dir)) {
47
- if (!/^host-\d{4}-\d{2}-\d{2}\.log$/u.test(name)) continue
56
+ if (!own.test(name)) continue
48
57
  const file = join(dir, name)
49
58
  if (now.getTime() - statSync(file).mtimeMs > KEEP_DAYS * 86_400_000)
50
59
  rmSync(file, { force: true })
@@ -7,9 +7,10 @@ import { type ChildProcess, spawn } from 'node:child_process'
7
7
  import { existsSync, readFileSync } from 'node:fs'
8
8
  import { createRequire } from 'node:module'
9
9
  import { join } from 'node:path'
10
+ import { selectInstance } from '@acryldev/instance'
10
11
  import { acrylRoot, appIdOf, personHome } from '@acryldev/instance/home'
11
12
  import { APP_ROOT_ENV } from './app-root.ts'
12
- import { appTitle, brandedElectron, iconFile } from './brand.ts'
13
+ import { brandedElectron, iconFile } from './brand.ts'
13
14
 
14
15
  /** The sysctl that makes the sandbox fail for an Electron without an AppArmor profile; its value, or `undefined` where it does not exist (every system but a recent Ubuntu). */
15
16
  export const RESTRICT_USERNS = '/proc/sys/kernel/apparmor_restrict_unprivileged_userns'
@@ -78,6 +79,23 @@ function mainFile(): string {
78
79
  return existsSync(compiled) ? compiled : join(import.meta.dirname, 'main.ts')
79
80
  }
80
81
 
82
+ /**
83
+ * What the branded Electron of an app is made from: where it lives, its id, the name the Dock and Cmd+Tab show and its icon. The name is the one the instance gives
84
+ * (the app's Blend name in `blend.yaml`, else its package's, or ACRYLBLENDS_NAME): the window's title and About say the same, so the Dock never reads differently.
85
+ */
86
+ export function brandingOf(
87
+ projectRoot: string,
88
+ env: Record<string, string | undefined>,
89
+ platform: NodeJS.Platform,
90
+ ): { folder: string; id: string; name: string; icon: string } {
91
+ return {
92
+ folder: join(acrylRoot(platform, env, personHome(env, platform)), 'electron'),
93
+ id: appIdOf(projectRoot),
94
+ name: selectInstance({ projectRoot, env }).name,
95
+ icon: iconFile(projectRoot),
96
+ }
97
+ }
98
+
81
99
  /**
82
100
  * Start the app in `projectRoot` as a desktop app: `npm run desktop` (bin.ts) with the app's folder, `extra` its arguments. Electron's main learns the
83
101
  * app from ACRYLBLENDS_APP_ROOT (app-root.ts), since the shell is installed in node_modules, outside the app's tree.
@@ -91,13 +109,7 @@ export function launchDesktop(projectRoot: string, extra: readonly string[]): Ch
91
109
  // macOS: the Dock and Cmd+Tab name the app and draw its icon only when the bundle says so (brand.ts); a copy that cannot be made leaves the stock Electron, with a note.
92
110
  const branded = brandedElectron({
93
111
  binary: electron,
94
- folder: join(
95
- acrylRoot(process.platform, process.env, personHome(process.env, process.platform)),
96
- 'electron',
97
- ),
98
- id: appIdOf(projectRoot),
99
- name: appTitle(projectRoot),
100
- icon: iconFile(projectRoot),
112
+ ...brandingOf(projectRoot, process.env, process.platform),
101
113
  })
102
114
  if (branded.problem !== undefined)
103
115
  console.warn(`desktop: the Dock shows Electron's own name and icon (${branded.problem})`)
@@ -9,7 +9,7 @@
9
9
  */
10
10
 
11
11
  import { mkdirSync, readFileSync, unwatchFile, watchFile } from 'node:fs'
12
- import { join } from 'node:path'
12
+ import { dirname, join } from 'node:path'
13
13
  import { fileURLToPath, pathToFileURL } from 'node:url'
14
14
  import { readAppVersions } from '@acryldev/blends-core'
15
15
  import {
@@ -51,12 +51,34 @@ import {
51
51
  import { productGit, withGitFirst } from './git.ts'
52
52
  import { appendHostLog, hostCrashed, hostRestarting, nextRestart } from './host-supervisor.ts'
53
53
  import { aboutPlacement, aboutText, hasSettings, settingsPlacement } from './menu.ts'
54
- import { openProductApp, seedSource } from './product.ts'
54
+ import { openProductAppForStart, seedSource } from './product.ts'
55
55
  import { createDesktopShutdown, installShutdownRequests } from './shutdown.ts'
56
+ import {
57
+ COPY_DEADLINE_MS,
58
+ captureConsole,
59
+ createStartupLog,
60
+ endsWithLastWindow,
61
+ retryLocked,
62
+ updateFailureText,
63
+ updateWindowUrl,
64
+ waitAtMost,
65
+ } from './startup.ts'
56
66
  import { offerUpdates } from './update-menu.ts'
57
67
  import { resolveDesktopUserDataOverride } from './user-data.ts'
58
68
  import { cascade, windowOptions, windowSize } from './window.ts'
59
69
 
70
+ // The start's own log, from the first line: kept in memory until the product's logs folder is known (`startup.attach`), and everything the shell prints goes in it.
71
+ const startup = createStartupLog()
72
+ captureConsole(console, startup)
73
+ process.on('uncaughtExceptionMonitor', (cause, origin) => {
74
+ startup.line(
75
+ `error: ${origin}: ${cause instanceof Error ? (cause.stack ?? cause.message) : String(cause)}`,
76
+ )
77
+ })
78
+ console.log(
79
+ `desktop: starting ${app.getName()} ${app.getVersion()} (pid ${String(process.pid)}, ${process.platform} ${process.arch}, electron ${process.versions.electron ?? '?'})`,
80
+ )
81
+
60
82
  /** The app shipped inside the bundle (a packaged product) or checked out by the person (an app made with `acrylblends init`); as an installed package, Electron names it. */
61
83
  const bundledRoot = appRootFor(import.meta.url, () => app.getAppPath())
62
84
  // A product build keeps its apps in its own root in the OS per-user data folder, one sealed folder each, and runs on the source of the one it opens: the
@@ -67,6 +89,8 @@ const git = product === undefined ? undefined : productGit(process.resourcesPath
67
89
  let storage: AppStorage | undefined
68
90
  /** The app the window shows. A product can switch to another of its apps (Settings > App: import, start over, open). */
69
91
  let chosen: AppInstance
92
+ /** The update's copy over the source, when this start is the first of a new build: run after the single-instance lock, behind a window. */
93
+ let update: (() => Promise<void>) | undefined
70
94
  try {
71
95
  storage =
72
96
  product === undefined
@@ -80,13 +104,21 @@ try {
80
104
  shell.showItemInFolder(path)
81
105
  },
82
106
  })
83
- chosen =
84
- storage === undefined || product === undefined
85
- ? selectInstance({ projectRoot: bundledRoot, env: process.env })
86
- : withRunEnv(openProductApp(storage, product, bundledRoot), process.env)
107
+ if (storage === undefined || product === undefined) {
108
+ chosen = selectInstance({ projectRoot: bundledRoot, env: process.env })
109
+ } else {
110
+ const started = openProductAppForStart(storage, product, bundledRoot)
111
+ update = started.update
112
+ chosen = withRunEnv(started.app, process.env)
113
+ }
114
+ // Beside the host's own log: the app's data/logs. What was said until now is written first.
115
+ startup.attach(join(chosen.home, 'logs'))
87
116
  } catch (cause) {
88
117
  // A root of a newer version, or one this version cannot read: said once, in a dialog, and nothing is started or written.
89
118
  const message = cause instanceof Error ? cause.message : String(cause)
119
+ // The app is not known yet: the product's own logs folder. An app run from its own folder has no product storage: its start was in its
120
+ // terminal, and the dialog below says the reason (where an app keeps anything is the AppInstance family's decision alone, bulkhead rule).
121
+ if (storage !== undefined) startup.attach(join(dirname(storage.electron), 'logs'))
90
122
  console.error(`desktop: ${message}`)
91
123
  dialog.showErrorBox(`${product?.product ?? 'The app'} cannot open`, message)
92
124
  app.exit(1)
@@ -106,9 +138,9 @@ function ownVersions(): {
106
138
  ...readAppVersions(chosen.root, programRoot),
107
139
  }
108
140
  }
109
- {
141
+ /** macOS's About panel: the version, then in parentheses the Blend's and the framework's. Again after an update, which changes them. */
142
+ const applyAbout = (): void => {
110
143
  const own = ownVersions()
111
- // macOS's About panel: the version, then in parentheses the Blend's and the framework's.
112
144
  app.setAboutPanelOptions({
113
145
  applicationVersion: own.product ?? own.blend ?? '',
114
146
  version: [
@@ -125,6 +157,7 @@ function ownVersions(): {
125
157
  }),
126
158
  })
127
159
  }
160
+ applyAbout()
128
161
 
129
162
  /** Where the window opens: `acrylblends.desktopPath` in package.json (the todo template sets `/todo`), else the root. */
130
163
  function startPath(): string {
@@ -147,7 +180,8 @@ app.setPath('userData', userData)
147
180
  app.setName(product?.product ?? appTitle(projectRoot))
148
181
 
149
182
  if (!app.requestSingleInstanceLock()) {
150
- // The same app is already open: its window takes focus (see `second-instance` below) and this process ends.
183
+ // The same app is already open, or starting, or updating: it is told (`second-instance` below shows its window, or queues that until it has one) and this process ends.
184
+ console.log('desktop: the app is already running: asking it to show its window; this start ends')
151
185
  app.quit()
152
186
  } else {
153
187
  /** The app the window shows: what the app's own `src/app.ts` returns (`createApp`). */
@@ -155,6 +189,10 @@ if (!app.requestSingleInstanceLock()) {
155
189
  let host: FrameHost | undefined
156
190
  let window: BrowserWindow | undefined
157
191
  let stopDoorShell: (() => void) | undefined
192
+ /** The small window shown while the update copies, and whether it does; the app's own window does not exist yet then. */
193
+ let updateWindow: BrowserWindow | undefined
194
+ /** A second start came before any window was open: the window is brought forward as soon as there is one. */
195
+ let focusQueued = false
158
196
 
159
197
  const shutdown = createDesktopShutdown(
160
198
  async () => {
@@ -181,16 +219,84 @@ if (!app.requestSingleInstanceLock()) {
181
219
  })
182
220
 
183
221
  app.on('second-instance', () => {
184
- if (window === undefined) return
185
- if (window.isMinimized()) window.restore()
186
- window.focus()
222
+ const shown = window ?? updateWindow
223
+ if (shown === undefined || shown.isDestroyed()) {
224
+ // Nothing to show yet (the update, or the host, is still starting): a silent return here made a second double-click look like a start that did nothing.
225
+ console.log(
226
+ 'desktop: a second start asked for the window; none is open yet, so its focus is queued',
227
+ )
228
+ focusQueued = true
229
+ return
230
+ }
231
+ console.log('desktop: a second start asked for the window; bringing it forward')
232
+ if (shown.isMinimized()) shown.restore()
233
+ shown.focus()
187
234
  })
188
235
  // The window is the app: closing it ends the process on every platform, after the server has stopped.
189
236
  app.on('window-all-closed', () => {
237
+ // Closing the update's own window (before the app's exists) must not end the app: found on a walk of the update on Windows, where the start ended there.
238
+ if (!endsWithLastWindow(window !== undefined)) return
190
239
  void shutdown.request(0)
191
240
  })
192
241
 
193
- void app.whenReady().then(async () => {
242
+ const started = app.whenReady().then(async () => {
243
+ if (update !== undefined && product !== undefined) {
244
+ // The first start of a new build copies it over the app's source: behind a window that says so (a copy can take many seconds on a slow disk), after the
245
+ // lock (so a second start never copies at the same time), and a file another program holds is tried again and then said in words, never an exit with nothing shown.
246
+ const copying = update
247
+ const shown = new BrowserWindow({
248
+ width: 420,
249
+ height: 180,
250
+ title: product.product,
251
+ show: false,
252
+ resizable: false,
253
+ minimizable: false,
254
+ maximizable: false,
255
+ fullscreenable: false,
256
+ autoHideMenuBar: true,
257
+ icon: iconFile(projectRoot),
258
+ })
259
+ updateWindow = shown
260
+ shown.removeMenu()
261
+ shown.once('ready-to-show', () => {
262
+ shown.show()
263
+ if (focusQueued) shown.focus()
264
+ })
265
+ void shown.loadURL(updateWindowUrl(product.product))
266
+ try {
267
+ await waitAtMost(
268
+ retryLocked(
269
+ () =>
270
+ copying().catch((cause: unknown) => {
271
+ console.warn(
272
+ `desktop: the update's copy stopped: ${cause instanceof Error ? cause.message : String(cause)}`,
273
+ )
274
+ throw cause
275
+ }),
276
+ { attempts: 3, delayMs: 2000 },
277
+ ),
278
+ COPY_DEADLINE_MS,
279
+ )
280
+ console.log('desktop: the update was copied')
281
+ applyAbout()
282
+ } catch (cause) {
283
+ console.error(
284
+ `desktop: the update could not be copied: ${cause instanceof Error ? (cause.stack ?? cause.message) : String(cause)}`,
285
+ )
286
+ const said = updateFailureText(product.product, cause, join(chosen.home, 'logs'))
287
+ await dialog.showMessageBox({
288
+ type: 'warning',
289
+ title: product.product,
290
+ message: said.message,
291
+ detail: said.detail,
292
+ buttons: ['Start'],
293
+ defaultId: 0,
294
+ })
295
+ } finally {
296
+ if (!shown.isDestroyed()) shown.destroy()
297
+ updateWindow = undefined
298
+ }
299
+ }
194
300
  // The Dock shows the app's own icon even when the bundle could not be branded (brand.ts); a no-op where there is no Dock.
195
301
  app.dock?.setIcon(iconFile(projectRoot))
196
302
  // An icon chosen in Settings > App (written to assets/icon.png by the frame's host) shows at once, in the Dock and on every window.
@@ -330,7 +436,13 @@ if (!app.requestSingleInstanceLock()) {
330
436
  try {
331
437
  url = await startHost()
332
438
  } catch (cause) {
333
- console.error(`desktop: ${cause instanceof Error ? cause.message : String(cause)}`)
439
+ const reason = cause instanceof Error ? cause.message : String(cause)
440
+ console.error(`desktop: ${reason}`)
441
+ // A start that ends with nothing on screen looks like an app that does not open: the reason is shown, and where the logs are.
442
+ dialog.showErrorBox(
443
+ `${chosen.name} cannot start`,
444
+ `${reason.slice(-1200)}\n\nThe details are in ${join(chosen.home, 'logs')}`,
445
+ )
334
446
  await shutdown.request(1)
335
447
  return
336
448
  }
@@ -427,6 +539,10 @@ if (!app.requestSingleInstanceLock()) {
427
539
  return created
428
540
  }
429
541
  window = createWindow(frame ? undefined : startPath())
542
+ if (focusQueued) {
543
+ focusQueued = false
544
+ window.once('ready-to-show', () => window?.focus())
545
+ }
430
546
  // The door (development) reaches the windows and the menu through this port: `acryl window list`, `acryl menu click`.
431
547
  const live = (): BrowserWindow[] =>
432
548
  BrowserWindow.getAllWindows().filter((candidate) => !candidate.isDestroyed())
@@ -631,4 +747,11 @@ if (!app.requestSingleInstanceLock()) {
631
747
  })
632
748
  }
633
749
  })
750
+ // Anything the start throws after the window machinery is up: said in a dialog and kept in the log, then the app ends (it cannot run half started).
751
+ started.catch((cause: unknown) => {
752
+ const reason = cause instanceof Error ? (cause.stack ?? cause.message) : String(cause)
753
+ console.error(`desktop: the start failed: ${reason}`)
754
+ dialog.showErrorBox(`${product?.product ?? 'The app'} cannot start`, reason.slice(0, 1500))
755
+ void shutdown.request(1)
756
+ })
634
757
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@acryldev/desktop-shell",
3
- "version": "0.1.11",
3
+ "version": "0.1.14",
4
4
  "description": "Run the app as a desktop app: an Electron window on the app's own server. `npm run desktop`; the app's code never imports electron.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -7,6 +7,7 @@
7
7
  */
8
8
 
9
9
  import { appendFileSync, cpSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
10
+ import { cp } from 'node:fs/promises'
10
11
  import { join, relative, sep } from 'node:path'
11
12
  import type { AppInstance } from '@acryldev/instance'
12
13
  import { inProgram, type Product } from '@acryldev/instance/bundle'
@@ -74,13 +75,30 @@ export function seedSource(
74
75
  program: readonly string[],
75
76
  refresh = false,
76
77
  ): void {
77
- cpSync(bundle, source, {
78
+ cpSync(bundle, source, copyOptions(bundle, program))
79
+ finishSeed(bundle, source, refresh)
80
+ }
81
+
82
+ /** `seedSource` without holding the event loop: a window can paint ("Updating...") while a big tree is copied. Same files, same result. */
83
+ export async function seedSourceAsync(
84
+ bundle: string,
85
+ source: string,
86
+ program: readonly string[],
87
+ refresh = false,
88
+ ): Promise<void> {
89
+ await cp(bundle, source, copyOptions(bundle, program))
90
+ finishSeed(bundle, source, refresh)
91
+ }
92
+
93
+ /** What `cp` and `cpSync` copy: the bundle's own files, never the Program (which stays in the bundle) or the packager's carriers. */
94
+ function copyOptions(bundle: string, program: readonly string[]) {
95
+ return {
78
96
  recursive: true,
79
97
  dereference: true,
80
98
  errorOnExist: false,
81
99
  force: true,
82
100
  // The bundled root arrives as a URL's directory and can end in a separator: paths are taken relative to it, never by index.
83
- filter: (path) => {
101
+ filter: (path: string): boolean => {
84
102
  const parts = relative(bundle, path).split(sep)
85
103
  if (parts[0] === '') return true
86
104
  if (SKIPPED.has(parts[0] ?? '')) return false
@@ -88,7 +106,11 @@ export function seedSource(
88
106
  const tree = parts.join('/')
89
107
  return !inProgram(program, tree) && !inProgram(program, `${tree}/`)
90
108
  },
91
- })
109
+ }
110
+ }
111
+
112
+ /** The small files after the tree: the repository (a new app only) and the files the packager carried under other names. */
113
+ function finishSeed(bundle: string, source: string, refresh: boolean): void {
92
114
  const templateGit = join(bundle, 'template-git')
93
115
  // A refresh keeps the source's own history: the new build's files arrive as changes in it, never as a replaced repository.
94
116
  if (!refresh && existsSync(templateGit))
@@ -110,12 +132,54 @@ export function openProductApp(
110
132
  bundle: string,
111
133
  log: (line: string) => void = console.log,
112
134
  ): AppInstance {
135
+ const { app, created } = openProductInstance(storage, product, bundle, log)
136
+ if (product.named === true && product.build !== undefined)
137
+ refreshFinishedApp(app, product, bundle, created, log)
138
+ return app
139
+ }
140
+
141
+ /**
142
+ * `openProductApp` for the window's start: the same app, but the update's copy over its source is returned, not run. The shell runs it after it holds the
143
+ * single-instance lock and shows a window ("Updating..."), so a second start never copies at the same time and a person sees what is happening. Without
144
+ * an update to run, `update` is undefined.
145
+ */
146
+ export function openProductAppForStart(
147
+ storage: AppStorage,
148
+ product: Product,
149
+ bundle: string,
150
+ log: (line: string) => void = console.log,
151
+ ): { readonly app: AppInstance; readonly update: (() => Promise<void>) | undefined } {
152
+ const { app, created } = openProductInstance(storage, product, bundle, log)
153
+ if (product.named !== true || product.build === undefined) return { app, update: undefined }
154
+ const build = product.build
155
+ const state = buildState(app, build, created)
156
+ if (state.kind === 'record') writeBuild(app, build)
157
+ if (state.kind !== 'copy') return { app, update: undefined }
158
+ return {
159
+ app,
160
+ update: async () => {
161
+ log(
162
+ `product: updating "${app.name}" to build ${build} (it was made from ${state.made ?? 'an earlier build'})`,
163
+ )
164
+ await seedSourceAsync(sourceOf(product, bundle), app.root, product.program, true)
165
+ // Written only after the copy finished: a start that could not copy tries again at the next start.
166
+ writeBuild(app, build)
167
+ },
168
+ }
169
+ }
170
+
171
+ function openProductInstance(
172
+ storage: AppStorage,
173
+ product: Product,
174
+ bundle: string,
175
+ log: (line: string) => void,
176
+ ): { readonly app: AppInstance; readonly created: boolean } {
113
177
  let app = storage.last()
114
178
  const created = app === undefined
115
179
  if (app === undefined) {
116
180
  log(`product: making the app "${product.appName}" from the bundled app (first start, one time)`)
117
181
  // A product that is one Blend carries it in a folder of its bundle; the Blank product's starting app is the bundle's own tree.
118
- const from = product.seed === undefined ? bundle : join(bundle, product.seed)
182
+ const from = sourceOf(product, bundle)
119
183
  // A product that is one finished Blend (ACRYL Control Center, ACRYL ADE) has its name: only the Blank product asks for one (product.json `named`).
120
184
  app = storage.create(
121
185
  product.appName,
@@ -128,12 +192,12 @@ export function openProductApp(
128
192
  // An app a named product made before it carried the mark (ACRYL Control Center 0.1.0-0.1.3): keep its name and stop asking.
129
193
  app = storage.rename(app.id, app.name)
130
194
  }
131
- const opened = storage.open(app.id)
132
- if (product.named === true && product.build !== undefined)
133
- refreshFinishedApp(opened, product, bundle, created, log)
134
- return opened
195
+ return { app: storage.open(app.id), created }
135
196
  }
136
197
 
198
+ const sourceOf = (product: Product, bundle: string): string =>
199
+ product.seed === undefined ? bundle : join(bundle, product.seed)
200
+
137
201
  /** The file in a named product's app data that says which build its source was made from. */
138
202
  export const PRODUCT_BUILD_FILE = 'product-build'
139
203
 
@@ -149,16 +213,32 @@ function refreshFinishedApp(
149
213
  created: boolean,
150
214
  log: (line: string) => void,
151
215
  ): void {
152
- const record = join(app.home, PRODUCT_BUILD_FILE)
153
- const made = existsSync(record) ? readFileSync(record, 'utf8').trim() : undefined
154
- if (made === product.build) return
155
- if (!created) {
216
+ const build = product.build as string
217
+ const state = buildState(app, build, created)
218
+ if (state.kind === 'copy') {
156
219
  log(
157
- `product: updating "${app.name}" to build ${product.build} (it was made from ${made ?? 'an earlier build'})`,
220
+ `product: updating "${app.name}" to build ${build} (it was made from ${state.made ?? 'an earlier build'})`,
158
221
  )
159
- const from = product.seed === undefined ? bundle : join(bundle, product.seed)
160
- seedSource(from, app.root, product.program, true)
222
+ seedSource(sourceOf(product, bundle), app.root, product.program, true)
161
223
  }
224
+ if (state.kind !== 'current') writeBuild(app, build)
225
+ }
226
+
227
+ /** What the record says about the source: made from this build ('current'), new (only the record is written), or from another build (its files are copied over). */
228
+ function buildState(
229
+ app: AppInstance,
230
+ build: string,
231
+ created: boolean,
232
+ ):
233
+ | { readonly kind: 'current' | 'record' }
234
+ | { readonly kind: 'copy'; readonly made: string | undefined } {
235
+ const record = join(app.home, PRODUCT_BUILD_FILE)
236
+ const made = existsSync(record) ? readFileSync(record, 'utf8').trim() : undefined
237
+ if (made === build) return { kind: 'current' }
238
+ return created ? { kind: 'record' } : { kind: 'copy', made }
239
+ }
240
+
241
+ function writeBuild(app: AppInstance, build: string): void {
162
242
  mkdirSync(app.home, { recursive: true })
163
- writeFileSync(record, `${product.build}\n`)
243
+ writeFileSync(join(app.home, PRODUCT_BUILD_FILE), `${build}\n`)
164
244
  }
@@ -0,0 +1,167 @@
1
+ /**
2
+ * What the window does before and around its start, as small rules without Electron, so they are tested without a window (found on a Windows 11 report,
3
+ * 2026-11: "I updated ACRYL Control Center and it refuses to start when clicking the .exe", with nothing on screen and nothing on disk to say why):
4
+ * - the start's own log (`desktop-YYYY-MM-DD.log` in the product's logs folder), from the first line, mirroring what the main process prints;
5
+ * - a copy that meets a locked file is tried again, and when it cannot be done it is said in words, never as an exit with nothing shown;
6
+ * - the small window shown while the update's copy runs.
7
+ */
8
+ import { format } from 'node:util'
9
+ import { appendHostLog } from './host-supervisor.ts'
10
+
11
+ export interface StartupLog {
12
+ /** One timestamped line; kept in memory until `attach` says where the logs folder is. */
13
+ line(text: string): void
14
+ /** The logs folder is known: what was said so far is written, and every line from now on. */
15
+ attach(dir: string): void
16
+ }
17
+
18
+ /** Never throws (a log must not stop the app). `echo` is where the line also goes (the terminal, when there is one). */
19
+ export function createStartupLog(
20
+ now: () => Date = () => new Date(),
21
+ echo: (text: string) => void = () => {},
22
+ ): StartupLog {
23
+ let dir: string | undefined
24
+ let pending: string[] = []
25
+ return {
26
+ line(text) {
27
+ const stamped = `${now().toISOString()} ${text}\n`
28
+ echo(stamped)
29
+ if (dir === undefined) pending.push(stamped)
30
+ else appendHostLog(dir, stamped, now(), 'desktop')
31
+ },
32
+ attach(folder) {
33
+ dir = folder
34
+ for (const stamped of pending) appendHostLog(folder, stamped, now(), 'desktop')
35
+ pending = []
36
+ },
37
+ }
38
+ }
39
+
40
+ type Level = 'log' | 'info' | 'warn' | 'error'
41
+ const LEVELS: readonly Level[] = ['log', 'info', 'warn', 'error']
42
+
43
+ /** The console's output also goes into the log: every `desktop: ...` line the shell prints is kept without touching each call. Returns the way back. */
44
+ export function captureConsole(
45
+ target: Pick<Console, Level>,
46
+ log: Pick<StartupLog, 'line'>,
47
+ ): () => void {
48
+ const originals = new Map<Level, (...args: unknown[]) => void>()
49
+ for (const level of LEVELS) {
50
+ const original = target[level].bind(target) as (...args: unknown[]) => void
51
+ originals.set(level, target[level] as (...args: unknown[]) => void)
52
+ target[level] = (...args: unknown[]) => {
53
+ try {
54
+ log.line(
55
+ level === 'log' || level === 'info' ? format(...args) : `${level}: ${format(...args)}`,
56
+ )
57
+ } catch {
58
+ // The log never stops the app.
59
+ }
60
+ original(...args)
61
+ }
62
+ }
63
+ return () => {
64
+ for (const level of LEVELS) target[level] = originals.get(level) as never
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Whether the last window closing ends the app. Only once the app's own window has been opened: the update's window closes before it does, and the host takes
70
+ * seconds to serve, so a window count of zero is the normal state of a start (a Windows walk found the app ending itself right after its update).
71
+ */
72
+ export const endsWithLastWindow = (appWindowOpened: boolean): boolean => appWindowOpened
73
+
74
+ const LOCKED = new Set(['EBUSY', 'EPERM', 'EACCES', 'EMFILE', 'ENOTEMPTY'])
75
+
76
+ /** A file another program holds (the old version still closing, a virus scanner, a sync client): Windows answers EBUSY or EPERM. */
77
+ export const isLockedFileError = (cause: unknown): boolean =>
78
+ typeof cause === 'object' && cause !== null && LOCKED.has((cause as { code?: string }).code ?? '')
79
+
80
+ /** Run `step`; a locked file is tried again after `delayMs`, `attempts` times in all. Any other error, and the last locked one, is thrown. */
81
+ export async function retryLocked<T>(
82
+ step: () => Promise<T>,
83
+ options: {
84
+ readonly attempts?: number
85
+ readonly delayMs?: number
86
+ readonly sleep?: (ms: number) => Promise<void>
87
+ } = {},
88
+ ): Promise<T> {
89
+ const attempts = options.attempts ?? 3
90
+ const delayMs = options.delayMs ?? 1500
91
+ const sleep = options.sleep ?? ((ms: number) => new Promise<void>((done) => setTimeout(done, ms)))
92
+ for (let attempt = 1; ; attempt += 1) {
93
+ try {
94
+ return await step()
95
+ } catch (cause) {
96
+ if (attempt >= attempts || !isLockedFileError(cause)) throw cause
97
+ await sleep(delayMs)
98
+ }
99
+ }
100
+ }
101
+
102
+ /** How long the update's copy may take before the person is told and the old version starts: it takes seconds; a file another program holds can make it wait without an error. */
103
+ export const COPY_DEADLINE_MS = 60_000
104
+
105
+ const TIMED_OUT = 'UPDATE_TIMEOUT'
106
+
107
+ /** `work`, or an error with code UPDATE_TIMEOUT after `ms`; `work` keeps running (a copy cannot be cancelled) and its later failure is not reported twice. */
108
+ export function waitAtMost<T>(work: Promise<T>, ms: number): Promise<T> {
109
+ work.catch(() => undefined)
110
+ return new Promise<T>((resolve, reject) => {
111
+ const timer = setTimeout(
112
+ () =>
113
+ reject(
114
+ Object.assign(new Error(`did not finish in ${String(Math.round(ms / 1000))} seconds`), {
115
+ code: TIMED_OUT,
116
+ }),
117
+ ),
118
+ ms,
119
+ )
120
+ work.then(
121
+ (value) => {
122
+ clearTimeout(timer)
123
+ resolve(value)
124
+ },
125
+ (cause: unknown) => {
126
+ clearTimeout(timer)
127
+ reject(cause)
128
+ },
129
+ )
130
+ })
131
+ }
132
+
133
+ /** What a person is told when the update could not be copied: which file, why in words, what happens next, where the details are. */
134
+ export function updateFailureText(
135
+ product: string,
136
+ cause: unknown,
137
+ logs: string,
138
+ ): { readonly message: string; readonly detail: string } {
139
+ const error = cause as { code?: string; path?: string; message?: string }
140
+ const file = typeof error?.path === 'string' ? ` (${error.path})` : ''
141
+ const why =
142
+ isLockedFileError(cause) || error?.code === TIMED_OUT
143
+ ? `A file is in use by another program${file}: usually ${product} still closing, or a virus scanner. Close every ${product} window and process (Task Manager on Windows), then open it again and the update runs again.`
144
+ : `${error?.message ?? String(cause)}${file}`
145
+ return {
146
+ message: `${product} could not finish its update`,
147
+ detail: `${why}\n\nIt starts now with what is there: the old version, with the files that were already copied. Nothing of yours is changed.\n\nThe details are in ${logs}`,
148
+ }
149
+ }
150
+
151
+ const escapeHtml = (text: string): string =>
152
+ text
153
+ .replace(/&/gu, '&amp;')
154
+ .replace(/</gu, '&lt;')
155
+ .replace(/>/gu, '&gt;')
156
+ .replace(/"/gu, '&quot;')
157
+
158
+ /** The page of the window shown while the update copies: the product's name and one line, system fonts, light and dark. */
159
+ export function updateWindowUrl(product: string): string {
160
+ const html = `<!doctype html><meta charset="utf-8"><title>${escapeHtml(product)}</title><style>
161
+ html,body{height:100%;margin:0}body{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px;font:15px system-ui,sans-serif;background:#fff;color:#1b1b1f;-webkit-user-select:none;user-select:none}
162
+ @media(prefers-color-scheme:dark){body{background:#17171a;color:#ececf1}}
163
+ .bar{width:220px;height:4px;border-radius:2px;background:rgba(127,127,127,.25);overflow:hidden}.bar i{display:block;width:40%;height:100%;border-radius:2px;background:#6d5efc;animation:go 1.2s ease-in-out infinite alternate}
164
+ @keyframes go{from{margin-left:0}to{margin-left:60%}}small{opacity:.65}</style>
165
+ <div>Updating ${escapeHtml(product)}...</div><div class="bar"><i></i></div><small>This takes a moment, once.</small>`
166
+ return `data:text/html;charset=utf-8,${encodeURIComponent(html)}`
167
+ }