centralu 0.1.0-beta.2 → 0.1.0-beta.20

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/bin/centralu.mjs CHANGED
@@ -1,22 +1,61 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * Centralu 실행기.
3
+ * The Centralu launcher.
4
4
  *
5
- * **왜 npm으로 주는가:** macOS는 앱을 검사해서 위험하다고 판정하는 게 아니라,
6
- * 파일에 붙은 `com.apple.quarantine` 딱지를 보고 개발자 신원을 따진다. 그 딱지는
7
- * **받아온 프로그램이** 붙인다 — 브라우저는 붙이고 npm은 안 붙인다. 그래서 npm으로
8
- * 설치하면 서명이 애드혹이어도 경고 없이 그냥 열린다 (docs/plans/beta-release-checklist.md §2).
5
+ * **Why this ships through npm:** macOS does not inspect the app and decide it is dangerous —
6
+ * it looks at the `com.apple.quarantine` flag attached to the file and checks the developer's
7
+ * identity from that. That flag is attached **by the program that downloaded it** — a browser
8
+ * attaches it, npm does not. So an npm install just opens with no warning even with an ad hoc
9
+ * signature (docs/plans/beta-release-checklist.md §2).
9
10
  *
10
- * 앱 본체는 아키텍처별 패키지(`centralu-darwin-arm64`)에 들어 있다. 이 패키지는
11
- * 그것을 찾아 띄우는 얇은 껍데기다 — esbuild·swc가 쓰는 것과 같은 구조.
11
+ * The app itself lives inside an architecture-specific package (`@centralu/darwin-arm64`). This
12
+ * package is a thin shell that finds it and launches it — the same structure esbuild and swc
13
+ * use.
12
14
  *
13
15
  * Linux is served from the same shim (issue #14). The two platforms disagree about what
14
16
  * "the app" even is — macOS hands a `.app` directory to LaunchServices, Linux runs a
15
17
  * self-contained AppImage itself — so that difference lives in one table (`TARGETS`)
16
18
  * instead of being rediscovered in every function.
19
+ *
20
+ * Windows joined in W3 of #14. Its decisions — the exe inside the folder, a detached start,
21
+ * where `install` copies to, the WebView2 check — live in `platform.mjs` as functions of the
22
+ * platform, so they are tested on macOS CI (tooling/launcher-platform.test.ts) instead of
23
+ * being first exercised on someone's laptop.
17
24
  */
18
25
  import { execFileSync, spawn } from 'node:child_process'
19
- import { chmodSync, existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
26
+ import { copyDiffers, isNewer } from './semver.mjs'
27
+ import {
28
+ asideCopies,
29
+ busyMessage,
30
+ earlyExitMessage,
31
+ executableIn,
32
+ findHostEntry,
33
+ installedPaths,
34
+ isBusyError,
35
+ launchPlan,
36
+ npmCommand,
37
+ regExe,
38
+ shortcutCommand,
39
+ targetFor,
40
+ TARGETS,
41
+ webview2MissingMessage,
42
+ webview2Status,
43
+ windowsInstall,
44
+ } from './platform.mjs'
45
+ import {
46
+ decodeChildSpec,
47
+ parseServeArgs,
48
+ printConnection,
49
+ rotateToken,
50
+ runAutostart,
51
+ runDetach,
52
+ runDetachedChild,
53
+ runServe,
54
+ runStop,
55
+ SERVE_HELP,
56
+ } from './serve.mjs'
57
+ import { swapInto } from './swap.mjs'
58
+ import { chmodSync, cpSync, existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'
20
59
  import { createRequire } from 'node:module'
21
60
  import { homedir } from 'node:os'
22
61
  import { dirname, join } from 'node:path'
@@ -28,68 +67,95 @@ const APP_NAME = 'Centralu'
28
67
  const BUNDLE = `${APP_NAME}.app`
29
68
  const INSTALLED = `/Applications/${BUNDLE}`
30
69
 
70
+ const PLATFORM = process.platform
71
+ const HOME = homedir()
72
+
31
73
  /** Where a menu entry for the app goes on freedesktop desktops */
32
- const DESKTOP_ENTRY = join(homedir(), '.local/share/applications/centralu.desktop')
74
+ const DESKTOP_ENTRY = join(HOME, '.local/share/applications/centralu.desktop')
33
75
 
34
- /**
35
- * The arch package for this machine, and what the app is called inside it.
36
- *
37
- * `artifact` must match `scripts/release-npm.mts` exactly — that script renames what
38
- * Tauri produced (`Centralu_0.1.0-beta.2_amd64.AppImage`) to a fixed name precisely so
39
- * this file does not have to know version or architecture. If the two ever disagree the
40
- * symptom is "installed fine, does nothing", so keep them in one place mentally.
41
- *
42
- * Only combinations that are actually published belong here. Listing a package that was
43
- * never released would turn "not supported yet" into "your install is broken", which
44
- * sends the user off to reinstall something that can never appear.
45
- */
46
- const TARGETS = {
47
- 'darwin-arm64': { pkg: 'centralu-darwin-arm64', artifact: BUNDLE },
48
- 'linux-x64': { pkg: 'centralu-linux-x64', artifact: `${APP_NAME}.AppImage` },
49
- }
76
+ /** Where `centralu install` copies the app on Windows (see `windowsInstall`) */
77
+ const WIN = PLATFORM === 'win32' ? windowsInstall(process.env, HOME) : null
50
78
 
51
- const TARGET = TARGETS[`${process.platform}-${process.arch}`]
79
+ /** The arch package for this machine (the table lives in platform.mjs) */
80
+ const TARGET = targetFor(PLATFORM, process.arch)
52
81
 
53
- /** 아키텍처별 패키지 안의 앱. 못 찾으면 null */
82
+ /** The app inside the architecture-specific package. null if it cannot be found. */
54
83
  function bundledApp() {
55
84
  if (!TARGET) return null
56
85
  let root
57
86
  try {
58
87
  root = dirname(require.resolve(`${TARGET.pkg}/package.json`))
59
88
  } catch {
60
- return null // 이 아키텍처용 패키지가 안 깔린 것 — 아래에서 이유를 말한다
89
+ return null // The package for this architecture is not installed — the reason is explained below.
61
90
  }
62
91
  const app = join(root, TARGET.artifact)
63
- return existsSync(app) ? app : null
92
+ return existsSync(executableIn(PLATFORM, app)) ? app : null
64
93
  }
65
94
 
66
95
  /**
67
- * 지금 이 기계에서 왜 못 쓰는지를 **구체적으로** 말한다.
68
- * "설치가 안 됐습니다"만 뜨면 사용자가 할 수 있는 일이 없다.
96
+ * States **specifically** why this machine cannot run it right now.
97
+ * If all that shows is "not installed", there is nothing the person can act on.
69
98
  */
70
99
  function explainMissing() {
71
100
  if (!TARGET) {
72
101
  // Kept as its own case: "not published for your machine" and "not published for
73
102
  // Intel Macs, and here is the reason" send the user to different places.
74
- if (process.platform === 'darwin') {
103
+ if (PLATFORM === 'darwin') {
75
104
  return (
76
- `${APP_NAME}는 아직 Apple Silicon 전용입니다 (지금 아키텍처: ${process.arch}).\n` +
77
- 'Intel 맥 지원은 네이티브 애드온까지 함께 묶어야 해서 별도 작업으로 잡혀 있습니다.'
105
+ `${APP_NAME} is Apple Silicon only for now (current architecture: ${process.arch}).\n` +
106
+ 'Intel Mac support needs native addons bundled in as well, and is tracked as separate work.'
78
107
  )
79
108
  }
80
109
  const supported = Object.keys(TARGETS).join(', ')
81
110
  return (
82
- `${APP_NAME}는 아직 ${process.platform}/${process.arch}를 지원하지 않습니다.\n` +
83
- `지금 지원하는 조합: ${supported}\n` +
84
- 'https://github.com/ijun17/centralu/issues/14 에 진행 상황이 있습니다.'
111
+ `${APP_NAME} does not support ${PLATFORM}/${process.arch} yet.\n` +
112
+ `Currently supported combinations: ${supported}\n` +
113
+ 'Progress is tracked at https://github.com/ijun17/centralu/issues/14.'
85
114
  )
86
115
  }
87
116
  return (
88
- `앱 본체 패키지(${TARGET.pkg})를 찾지 못했습니다.\n` +
89
- '설치가 중간에 끊겼을 수 있습니다 — `npm i -g centralu`로 다시 설치해 주세요.'
117
+ `Could not find the app package (${TARGET.pkg}).\n` +
118
+ 'The install may have been interrupted — please reinstall with `npm i -g centralu`.'
90
119
  )
91
120
  }
92
121
 
122
+ /**
123
+ * The bundled host's entry (`resources/host/main.mjs`) for `centralu serve`, or exit with why not:
124
+ * from the platform package, or from the host-only package where a hub installed this (`findHostEntry`).
125
+ *
126
+ * `CENTRALU_HOST_ENTRY` points it at another host instead: a source checkout's
127
+ * `packages/agent-host/src/main.ts` while developing, or a freshly bundled `resources/host/main.mjs`.
128
+ * The tests start `serve` that way (tooling/launcher-serve.test.ts).
129
+ */
130
+ function requireHostEntry() {
131
+ if (process.env.CENTRALU_HOST_ENTRY) return process.env.CENTRALU_HOST_ENTRY
132
+ if (!TARGET) {
133
+ console.error(explainMissing())
134
+ process.exit(1)
135
+ }
136
+ // The platform package of an npm install, else the host-only package a hub installed (platform.mjs)
137
+ const found = findHostEntry(PLATFORM, process.arch, {
138
+ resolveRoot: (name) => {
139
+ try {
140
+ return dirname(require.resolve(`${name}/package.json`))
141
+ } catch {
142
+ return null
143
+ }
144
+ },
145
+ exists: existsSync,
146
+ })
147
+ if (found.entry) return found.entry
148
+ if (found.missingHost) {
149
+ console.error(
150
+ `The host is missing from ${found.missingHost.pkg} (looked for ${found.missingHost.entry}).\n` +
151
+ 'Linux packages published before `centralu serve` existed do not carry it. Update with `npm i -g centralu`.',
152
+ )
153
+ process.exit(1)
154
+ }
155
+ console.error(explainMissing())
156
+ process.exit(1)
157
+ }
158
+
93
159
  function requireApp() {
94
160
  const app = bundledApp()
95
161
  if (!app) {
@@ -100,20 +166,27 @@ function requireApp() {
100
166
  }
101
167
 
102
168
  /**
103
- * 앱을 띄운다. `/Applications`에 설치돼 있으면 그쪽을 먼저 쓴다.
169
+ * Launches the app. If it is installed in `/Applications` (macOS) or
170
+ * `%LOCALAPPDATA%\Programs\Centralu` (Windows), that copy is used first.
104
171
  *
105
- * That preference is macOS-only, and not for lack of an equivalent: `centralu install`
172
+ * Linux has no such preference, and not for lack of an equivalent: `centralu install`
106
173
  * on Linux writes a launcher that points back at this same package, so there is never a
107
174
  * second copy to prefer.
175
+ *
176
+ * Resolves once the launcher has nothing more to wait for. Only Windows waits at all —
177
+ * briefly, to report an exe that dies on start (see runWindows).
108
178
  */
109
- function run(args) {
110
- if (process.platform === 'darwin') {
179
+ async function run(args) {
180
+ if (PLATFORM === 'darwin') {
111
181
  const app = existsSync(INSTALLED) ? INSTALLED : requireApp()
112
- // `open`은 LaunchServices를 거친다 — Dock 아이콘·단일 인스턴스가 그래야 제대로 산다
113
- const r = spawn('open', ['-a', app, ...(args.length ? ['--args', ...args] : [])], { stdio: 'inherit' })
182
+ // `open` goes through LaunchServices — the dock icon and single-instance behavior only
183
+ // work correctly that way.
184
+ const plan = launchPlan(PLATFORM, app, args, HOME)
185
+ const r = spawn(plan.command, plan.args, plan.options)
114
186
  r.on('exit', (code) => process.exit(code ?? 0))
115
187
  return
116
188
  }
189
+ if (PLATFORM === 'win32') return runWindows(args)
117
190
  // Linux has no LaunchServices — the AppImage is its own launcher, so run it directly.
118
191
  //
119
192
  // Staying attached to the terminal is on purpose. The two usual first failures on
@@ -122,34 +195,101 @@ function run(args) {
122
195
  // missing system library from the loader. Detaching would hand back the shell prompt
123
196
  // and throw away the one line that says what to do.
124
197
  const app = requireApp()
125
- const r = spawn(app, args, { stdio: 'inherit' })
198
+ const plan = launchPlan(PLATFORM, app, args, HOME)
199
+ const r = spawn(plan.command, plan.args, plan.options)
126
200
  r.on('error', (e) => {
127
- console.error(`${app}를 실행하지 못했습니다: ${e.message}`)
201
+ console.error(`Failed to run ${app}: ${e.message}`)
128
202
  // EACCES here means the executable bit did not survive the trip through npm, which
129
203
  // is invisible from the message alone.
130
- if (e.code === 'EACCES') console.error(`실행 권한이 없습니다 — \`chmod +x "${app}"\` 뒤에 다시 시도해 주세요.`)
204
+ if (e.code === 'EACCES') console.error(`No execute permission — run \`chmod +x "${app}"\` then try again.`)
131
205
  process.exit(1)
132
206
  })
133
207
  r.on('exit', (code) => process.exit(code ?? 0))
134
208
  }
135
209
 
210
+ /** How long to watch a freshly started exe for an immediate exit */
211
+ const EARLY_EXIT_MS = 3000
212
+
136
213
  /**
137
- * 앱을 시스템 메뉴에 등록한다.
214
+ * Windows: check WebView2, start `centralu.exe` detached, and watch it for a few seconds.
138
215
  *
139
- * **postinstall로 몰래 하지 않는다.** 남의 `/Applications`에 조용히 쓰는 것은 신뢰를 깎고,
140
- * pnpm은 postinstall을 기본 차단한다. 사용자가 원할 때 명시적으로 부르게 한다.
216
+ * The app is a GUI program, so a failure to start has nowhere to print. Without WebView2
217
+ * the exe ends before it has a window, and the person sees nothing happen at all — the
218
+ * registry check turns that into a message with the download link before anything starts.
219
+ * The short watch afterwards catches whatever the registry cannot see (a broken runtime, a
220
+ * blocked exe), then lets go so the app outlives this launcher.
221
+ */
222
+ async function runWindows(args) {
223
+ const webview = webview2Status(process.env, queryRegistry)
224
+ if (webview.state === 'missing') {
225
+ console.error(webview2MissingMessage())
226
+ process.exit(1)
227
+ }
228
+ const app = existsSync(WIN.exe) ? WIN.dir : requireApp()
229
+ const plan = launchPlan(PLATFORM, app, args, HOME)
230
+ const child = spawn(plan.command, plan.args, plan.options)
231
+ await new Promise((resolve) => {
232
+ const done = () => {
233
+ clearTimeout(timer)
234
+ child.removeAllListeners()
235
+ child.unref()
236
+ resolve()
237
+ }
238
+ const timer = setTimeout(done, EARLY_EXIT_MS)
239
+ child.on('error', (e) => {
240
+ console.error(`Failed to start ${plan.command}: ${e.message}`)
241
+ process.exitCode = 1
242
+ done()
243
+ })
244
+ child.on('exit', (code) => {
245
+ // 0 is a normal answer this early: a second start hands over to the window that is
246
+ // already open and leaves.
247
+ if (code !== 0 && code !== null) {
248
+ console.error(earlyExitMessage(code, HOME))
249
+ process.exitCode = 1
250
+ }
251
+ done()
252
+ })
253
+ })
254
+ }
255
+
256
+ /**
257
+ * `reg query <key> /v pv`: stdout, null when the key or value does not exist (reg exits 1),
258
+ * undefined when reg itself could not run.
259
+ */
260
+ function queryRegistry(key) {
261
+ try {
262
+ return execFileSync(regExe(process.env), ['query', key, '/v', 'pv'], {
263
+ encoding: 'utf8',
264
+ stdio: ['ignore', 'pipe', 'ignore'],
265
+ windowsHide: true,
266
+ })
267
+ } catch (e) {
268
+ return typeof e?.status === 'number' ? null : undefined
269
+ }
270
+ }
271
+
272
+ /**
273
+ * Registers the app in the system menu.
274
+ *
275
+ * **Never done quietly through postinstall.** Writing silently into someone's `/Applications`
276
+ * erodes trust, and pnpm blocks postinstall by default anyway. This is only run when the
277
+ * person explicitly asks for it.
141
278
  */
142
279
  function install() {
143
280
  const app = requireApp()
144
- if (process.platform !== 'darwin') return installDesktopEntry(app)
145
- if (existsSync(INSTALLED)) {
146
- console.log(`기존 ${INSTALLED}를 새 버전으로 교체합니다.`)
147
- rmSync(INSTALLED, { recursive: true, force: true })
148
- }
149
- // cp가 아니라 ditto — 번들의 권한·확장속성을 그대로 옮긴다 (서명이 깨지지 않게)
150
- execFileSync('/usr/bin/ditto', [app, INSTALLED], { stdio: 'inherit' })
151
- console.log(`설치했습니다: ${INSTALLED}`)
152
- console.log('이제 Launchpad·Spotlight에서도 찾을 수 있습니다.')
281
+ if (PLATFORM === 'win32') return installWindows(app)
282
+ if (PLATFORM !== 'darwin') return installDesktopEntry(app)
283
+ if (existsSync(INSTALLED)) console.log(`Replacing the existing ${INSTALLED} with the new version.`)
284
+ // Copied beside the old one and swapped in by rename (swap.mjs): a copy that fails leaves the
285
+ // old app in place rather than none. ditto, not cp — carries over the bundle's permissions and
286
+ // extended attributes unchanged (so the signature does not break).
287
+ const { leftAt } = swapInto(INSTALLED, (staging) => {
288
+ execFileSync('/usr/bin/ditto', [app, staging], { stdio: 'inherit' })
289
+ })
290
+ if (leftAt) console.log(`The previous copy could not be removed and was left at ${leftAt}. Delete it yourself.`)
291
+ console.log(`Installed: ${INSTALLED}`)
292
+ console.log('It can now be found in Launchpad and Spotlight too.')
153
293
  }
154
294
 
155
295
  /**
@@ -182,27 +322,117 @@ function installDesktopEntry(app) {
182
322
  mkdirSync(dirname(DESKTOP_ENTRY), { recursive: true })
183
323
  writeFileSync(DESKTOP_ENTRY, entry)
184
324
  chmodSync(DESKTOP_ENTRY, 0o755)
185
- console.log(`등록했습니다: ${DESKTOP_ENTRY}`)
186
- console.log('이제 앱 목록에서도 찾을 수 있습니다 (데스크톱에 따라 다시 로그인해야 보일 수 있습니다).')
325
+ console.log(`Registered: ${DESKTOP_ENTRY}`)
326
+ console.log('It can now be found in the app list too (some desktops require logging back in before it shows up).')
327
+ }
328
+
329
+ /**
330
+ * The Windows answer to "copy it into /Applications": copy the folder into
331
+ * `%LOCALAPPDATA%\Programs\Centralu` and put a shortcut in the Start menu.
332
+ *
333
+ * A copy rather than a shortcut into the npm package (the Linux shape), because Windows
334
+ * will not replace a running program's files: with the app running from the package,
335
+ * `npm i -g centralu@newer` fails. Running from the copy leaves the package free to update.
336
+ *
337
+ * The old copy is never deleted before the new one is complete. The new folder is
338
+ * assembled beside it, the old one is renamed aside, and only then is the new one moved in
339
+ * — so a copy that fails halfway, or an app that is still running, leaves the working
340
+ * install untouched rather than a folder with half its files.
341
+ */
342
+ function installWindows(app) {
343
+ const staging = `${WIN.dir}.new`
344
+ const aside = `${WIN.dir}.old-${Date.now()}`
345
+ sweepAsideCopies()
346
+ rmSync(staging, { recursive: true, force: true })
347
+ mkdirSync(dirname(WIN.dir), { recursive: true })
348
+ cpSync(app, staging, { recursive: true })
349
+ writeFileSync(join(staging, 'centralu-version.txt'), `${pkg.version}\n`)
350
+ if (existsSync(WIN.dir)) {
351
+ console.log(`Replacing the existing ${WIN.dir} with the new version.`)
352
+ try {
353
+ renameSync(WIN.dir, aside)
354
+ } catch (e) {
355
+ rmSync(staging, { recursive: true, force: true })
356
+ if (!isBusyError(e)) throw e
357
+ console.error(busyMessage(WIN.dir))
358
+ process.exit(1)
359
+ }
360
+ }
361
+ renameSync(staging, WIN.dir)
362
+ try {
363
+ rmSync(aside, { recursive: true, force: true })
364
+ } catch {
365
+ // A rename can succeed while the old copy is running; its files then stay locked until
366
+ // it quits. Harmless — it is no longer the one anything starts — but worth a line.
367
+ console.log(`The previous copy is still in use and was left at ${aside}. Delete it after quitting ${APP_NAME}.`)
368
+ }
369
+ const sc = shortcutCommand(process.env, { shortcut: WIN.shortcut, target: WIN.exe, workdir: HOME })
370
+ try {
371
+ execFileSync(sc.command, sc.args, { env: sc.env, stdio: ['ignore', 'ignore', 'inherit'], windowsHide: true })
372
+ } catch (e) {
373
+ console.log(`Installed: ${WIN.dir}`)
374
+ console.error(`Could not create the Start menu shortcut (${e.message}). Start ${WIN.exe} directly, or run \`centralu\`.`)
375
+ process.exit(1)
376
+ }
377
+ console.log(`Installed: ${WIN.dir}`)
378
+ console.log(`Start menu: ${WIN.shortcut}`)
379
+ console.log('It can now be found in Start and Windows search, and `centralu` starts this copy too.')
380
+ }
381
+
382
+ /**
383
+ * Removes the copies earlier installs renamed aside (`Centralu.old-<time>`), whichever can go.
384
+ *
385
+ * An update from inside the app renames the running copy aside, and Windows will not delete a
386
+ * running exe, so that copy stays until the app quits. Nothing else would ever remove it, and
387
+ * each in-app update would leave one more (about 70 files each, measured 2026-10-08). One still
388
+ * in use is left for the next install; deleting what can be deleted from it does not disturb the
389
+ * app running from it, which reaches its files by the folder's original path, now the new copy.
390
+ */
391
+ function sweepAsideCopies() {
392
+ const parent = dirname(WIN.dir)
393
+ let names
394
+ try {
395
+ names = readdirSync(parent)
396
+ } catch {
397
+ return
398
+ }
399
+ for (const name of asideCopies(names)) {
400
+ try {
401
+ rmSync(join(parent, name), { recursive: true, force: true })
402
+ } catch {
403
+ // Still in use: the next install tries again
404
+ }
405
+ }
187
406
  }
188
407
 
189
408
  function uninstall() {
190
- const installed = process.platform === 'darwin' ? INSTALLED : DESKTOP_ENTRY
191
- if (!existsSync(installed)) {
192
- console.log(`${installed}가 없습니다 — 지울 것이 없습니다.`)
409
+ const paths = installedPaths(PLATFORM, process.env, HOME)
410
+ const present = paths.filter((p) => existsSync(p))
411
+ if (present.length === 0) {
412
+ console.log(`${paths[0]} does not exist — nothing to remove.`)
193
413
  return
194
414
  }
195
- rmSync(installed, { recursive: true, force: true })
196
- console.log(`지웠습니다: ${installed}`)
197
- console.log('패키지 자체를 지우려면: npm uninstall -g centralu')
198
- console.log(`대화 기록은 그대로 남아 있습니다 (~/.centralu). 지우려면 직접 지우세요.`)
415
+ for (const installed of present) {
416
+ try {
417
+ rmSync(installed, { recursive: true, force: true })
418
+ } catch (e) {
419
+ if (PLATFORM !== 'win32' || !isBusyError(e)) throw e
420
+ console.error(busyMessage(installed))
421
+ process.exit(1)
422
+ }
423
+ console.log(`Removed: ${installed}`)
424
+ }
425
+ console.log('To remove the package itself: npm uninstall -g centralu')
426
+ const data = PLATFORM === 'win32' ? '%USERPROFILE%\\.centralu' : '~/.centralu'
427
+ console.log(`Conversation history is left in place (${data}). Remove it yourself if you want to.`)
199
428
  }
200
429
 
201
430
  /**
202
- * npm 레지스트리가 곧 업데이트 채널이다 — 서버도 서명 키도 따로 필요 없다.
431
+ * The npm registry itself is the update channel — no separate server or signing key needed.
203
432
  *
204
- * 실패를 뭉뚱그리지 않는다. 못 닿은 것(네트워크)과 없는 것(404)은 **사용자가 할 일이 다르다** —
205
- * 앞은 연결을 보라는 말이고, 뒤는 봐도 소용없다는 말이다.
433
+ * Failures are not lumped together. Being unreachable (network) and not existing (404) call
434
+ * for **different actions from the person** — the first says to check the connection, the
435
+ * second says checking will not help.
206
436
  */
207
437
  async function latestVersion(timeoutMs = 2000) {
208
438
  try {
@@ -215,71 +445,130 @@ async function latestVersion(timeoutMs = 2000) {
215
445
  const version = body?.version
216
446
  return typeof version === 'string' ? { ok: true, version } : { ok: false, reason: 'bad-response' }
217
447
  } catch {
218
- return { ok: false, reason: 'network' } // 네트워크가 없어도 앱은 떠야 한다
448
+ return { ok: false, reason: 'network' } // The app has to launch even with no network.
219
449
  }
220
450
  }
221
451
 
222
- /** `1.2.10` > `1.2.9` — 문자열 비교로는 틀린다 */
223
- function isNewer(a, b) {
224
- const pa = String(a).split('.').map(Number)
225
- const pb = String(b).split('.').map(Number)
226
- for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
227
- const x = pa[i] ?? 0
228
- const y = pb[i] ?? 0
229
- if (x !== y) return x > y
230
- }
231
- return false
232
- }
233
452
 
234
453
  async function update() {
235
454
  const res = await latestVersion(8000)
236
455
  if (!res.ok) {
237
456
  if (res.reason === 'missing') {
238
- console.error(`레지스트리에 ${pkg.name}가 없습니다. 이름이 바뀌었거나 아직 발행 전입니다.`)
239
- console.error('https://github.com/ijun17/centralu/releases 를 확인해 주세요.')
457
+ console.error(`${pkg.name} is not on the registry. The name may have changed, or it has not been published yet.`)
458
+ console.error('Please check https://github.com/ijun17/centralu/releases.')
240
459
  } else if (res.reason === 'network') {
241
- console.error('레지스트리에 닿지 못했습니다. 네트워크를 확인하고 다시 시도해 주세요.')
460
+ console.error('Could not reach the registry. Please check your network and try again.')
242
461
  } else {
243
- console.error(`레지스트리가 예상 밖의 응답을 했습니다 (${res.reason}).`)
462
+ console.error(`The registry gave an unexpected response (${res.reason}).`)
244
463
  }
245
464
  process.exit(1)
246
465
  }
247
466
  const latest = res.version
248
467
  if (!isNewer(latest, pkg.version)) {
249
- console.log(`이미 최신입니다 (${pkg.version}).`)
468
+ console.log(`Already up to date (${pkg.version}).`)
469
+ // The package can be up to date while the copy is not — that is exactly the state of
470
+ // someone who upgraded with `npm i -g`.
471
+ notifyIfCopyStale()
250
472
  return
251
473
  }
252
- console.log(`${pkg.version} → ${latest} 로 올립니다.`)
253
- execFileSync('npm', ['i', '-g', `${pkg.name}@${latest}`], { stdio: 'inherit' })
254
- // /Applications에 넣어둔 사람은 그쪽도 함께 갱신해야 옛 버전이 남지 않는다.
474
+ console.log(`Upgrading ${pkg.version} → ${latest}.`)
475
+ const npm = npmCommand(PLATFORM, ['i', '-g', `${pkg.name}@${latest}`])
476
+ try {
477
+ execFileSync(npm.command, npm.args, npm.options)
478
+ } catch (e) {
479
+ // On Windows the usual cause is the app running from inside the package: its files are
480
+ // locked, and npm cannot replace them. npm's own output (above) has the details.
481
+ if (PLATFORM === 'win32') console.error(`\n${busyMessage('the npm package')}`)
482
+ process.exit(typeof e?.status === 'number' ? e.status : 1)
483
+ }
484
+ // Someone with a copy in /Applications (or %LOCALAPPDATA%\Programs) needs that updated
485
+ // too, or the old version stays behind.
255
486
  // On Linux the menu entry points at the package instead of a copy, so rewriting it is
256
487
  // cheap — but it is still worth doing, because the Exec path is what would go stale.
257
- const installed = process.platform === 'darwin' ? INSTALLED : DESKTOP_ENTRY
488
+ //
489
+ // The *new* launcher does the refresh: this file has just been replaced on disk. It is
490
+ // run through `node` rather than as a script, because Windows cannot execute a `.mjs`.
491
+ const installed = installedPaths(PLATFORM, process.env, HOME)[0]
258
492
  if (existsSync(installed)) {
259
- console.log(`${installed}도 갱신합니다.`)
260
- execFileSync(process.argv[1], ['install'], { stdio: 'inherit' })
493
+ console.log(`Updating ${installed} too.`)
494
+ execFileSync(process.execPath, [process.argv[1], 'install'], { stdio: 'inherit' })
261
495
  }
262
- console.log('끝났습니다. 앱이 떠 있다면 다시 시작해 주세요.')
496
+ console.log('Done. If the app is open, please restart it.')
263
497
  }
264
498
 
265
- /** 앱을 띄운 뒤에만 알린다 — 업데이트 확인 때문에 실행이 늦어지면 안 된다 */
499
+ /**
500
+ * The version of the copy placed in /Applications. null if there is nothing to compare.
501
+ *
502
+ * `defaults` is used because there is no guarantee Info.plist stays XML — Tauri just happens
503
+ * to write it as XML today, and if it ever switches to a binary plist, anything reading it
504
+ * with a regex would silently stop working. `defaults` is always present on a Mac and reads
505
+ * both formats.
506
+ *
507
+ * On Windows it is the file `centralu install` wrote beside the copy (see `windowsInstall`
508
+ * for why not the exe's own version).
509
+ */
510
+ function installedCopyVersion() {
511
+ if (PLATFORM === 'win32') {
512
+ try {
513
+ return readFileSync(WIN.versionFile, 'utf8').trim()
514
+ } catch {
515
+ return null
516
+ }
517
+ }
518
+ if (PLATFORM !== 'darwin' || !existsSync(INSTALLED)) return null
519
+ try {
520
+ const out = execFileSync('/usr/bin/defaults', ['read', join(INSTALLED, 'Contents/Info.plist'), 'CFBundleShortVersionString'], {
521
+ encoding: 'utf8',
522
+ stdio: ['ignore', 'pipe', 'ignore'],
523
+ })
524
+ return out.trim()
525
+ } catch {
526
+ // Failing to read this is not worth mentioning — the app has already launched, and there
527
+ // is nothing useful to say here.
528
+ return null
529
+ }
530
+ }
531
+
532
+ /**
533
+ * One line, if the package and the /Applications copy have drifted apart.
534
+ *
535
+ * `npm i -g centralu` only changes the package. So a state quietly forms where the launcher is
536
+ * new but the app that opens from Spotlight is old — this actually happened (beta.1 stayed in
537
+ * /Applications while only the package moved to beta.3), and nothing on screen said so.
538
+ *
539
+ * **Says it, does not do it.** The same rule as the in-app update line. Overwriting someone's
540
+ * /Applications without asking is the exact reason this package keeps `install` as a separate
541
+ * step.
542
+ */
543
+ function notifyIfCopyStale() {
544
+ const version = installedCopyVersion()
545
+ if (!copyDiffers(pkg.version, version)) return
546
+ const where = PLATFORM === 'win32' ? WIN.dir : '/Applications'
547
+ console.log(`\nThe ${where} copy is ${version} (this package is ${pkg.version}).\n centralu install`)
548
+ }
549
+
550
+ /** Only announced after the app has launched — checking for updates must never delay startup. */
266
551
  async function notifyIfOutdated() {
267
- // 여기서는 실패를 **전부 삼킨다.** 앱을 띄우러 온 사람에게 레지스트리 사정을 말할 이유가 없다
552
+ // Every failure here is **swallowed entirely.** Someone who came here to launch the app has
553
+ // no reason to be told about registry troubles.
268
554
  const res = await latestVersion()
269
555
  if (res.ok && isNewer(res.version, pkg.version)) {
270
- console.log(`\n새 버전이 있습니다: ${pkg.version} → ${res.version}\n centralu update`)
556
+ console.log(`\nA new version is available: ${pkg.version} → ${res.version}\n centralu update`)
271
557
  }
272
558
  }
273
559
 
274
560
  const HELP = `${APP_NAME} ${pkg.version}
275
561
 
276
- centralu 앱을 실행합니다
277
- centralu install 앱 목록에 등록합니다 (macOS는 /Applications, Linux는 메뉴 항목)
278
- centralu uninstall 그 등록을 지웁니다 (대화 기록은 남습니다)
279
- centralu update 새 버전이 있으면 올립니다
280
- centralu --version 버전을 출력합니다
562
+ centralu Launches the app
563
+ centralu install Registers it in the app list (macOS: /Applications, Linux: a menu entry,
564
+ Windows: %LOCALAPPDATA%\\Programs\\Centralu and a Start menu shortcut)
565
+ centralu uninstall Removes that registration (conversation history is kept)
566
+ centralu update Upgrades if a new version is available
567
+ centralu serve Runs the host alone on this machine, for the app on another computer
568
+ to reach over SSH (\`centralu serve --help\`)
569
+ centralu --version Prints the version
281
570
 
282
- 필요한 것: Node 22+, 그리고 claude 또는 codex CLI (앱 첫 화면이 상태를 알려줍니다)`
571
+ Requires: Node 22+, and the claude or codex CLI (the app's first screen reports the status)`
283
572
 
284
573
  const [cmd, ...rest] = process.argv.slice(2)
285
574
  switch (cmd) {
@@ -292,6 +581,46 @@ switch (cmd) {
292
581
  case 'update':
293
582
  await update()
294
583
  break
584
+ case 'serve': {
585
+ // No update notice here: `--connection`'s stdout is read by a program, and a foreground
586
+ // server's terminal is a log.
587
+ const args = parseServeArgs(rest)
588
+ if (args.error) {
589
+ console.error(args.error)
590
+ process.exit(2)
591
+ }
592
+ if (args.mode === 'help') {
593
+ console.log(SERVE_HELP)
594
+ break
595
+ }
596
+ try {
597
+ if (args.mode === 'rotate') {
598
+ process.exitCode = rotateToken({ env: process.env, home: HOME })
599
+ break
600
+ }
601
+ // A launcher `--detach` started: what it carried (the data folder, a host entry) applies before
602
+ // anything below reads the environment
603
+ const spec = args.child !== undefined ? decodeChildSpec(args.child) : null
604
+ if (args.child !== undefined && !spec) {
605
+ console.error('centralu serve: --detached-child is how --detach starts serve; this one could not be read')
606
+ process.exit(2)
607
+ }
608
+ if (spec) Object.assign(process.env, spec.env)
609
+ // realpath: npm's bin is a symlink to this file, and the launcher must not depend on the link
610
+ const opts = { env: process.env, home: HOME, entry: requireHostEntry(), version: pkg.version, cliPath: realpathSync(process.argv[1]) }
611
+ if (args.mode === 'connection') process.exitCode = await printConnection(opts)
612
+ else if (args.mode === 'detach') process.exitCode = await runDetach({ ...opts, port: args.port })
613
+ else if (args.mode === 'stop') process.exitCode = await runStop(opts)
614
+ else if (args.mode === 'autostart') process.exitCode = await runAutostart({ ...opts, action: args.autostart })
615
+ else if (spec) process.exitCode = await runDetachedChild({ ...opts, spec, port: args.port })
616
+ else process.exitCode = await runServe({ ...opts, port: args.port })
617
+ } catch (e) {
618
+ // A state file that cannot be read or written: one sentence, not a stack, and nothing on stdout
619
+ console.error(`centralu serve: ${e?.message ?? e}`)
620
+ process.exitCode = 1
621
+ }
622
+ break
623
+ }
295
624
  case '--version':
296
625
  case '-v':
297
626
  console.log(pkg.version)
@@ -301,7 +630,10 @@ switch (cmd) {
301
630
  case 'help':
302
631
  console.log(HELP)
303
632
  break
304
- default:
305
- run(cmd ? [cmd, ...rest] : [])
306
- await notifyIfOutdated()
633
+ default: {
634
+ // Started before the update check, never after it: the check must not delay startup.
635
+ const launched = run(cmd ? [cmd, ...rest] : [])
636
+ notifyIfCopyStale()
637
+ await Promise.all([launched, notifyIfOutdated()])
638
+ }
307
639
  }