easy-claude 0.2.6 → 0.2.8

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/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # 更新记录
2
2
 
3
+ ## v0.2.8(2026-10-21)
4
+
5
+ - 当前时间浮窗和城市菜单跟随系统12/24小时制及地区格式,保留所选城市时区;字体自动适应宽度,避免上午/下午标记截断。
6
+
7
+ ## v0.2.7(2026-10-21)
8
+
9
+ - 修复旧浮窗退出后日志清理失效;检查失败保留上次成功的新版提示并显示检查失败状态。
10
+
11
+ - 新增菜单“自动更新”开关,默认关闭并保存选择;开启后每日检查到新版自动安装并重开,失败只在菜单提示。更新锁防止同一安装前缀的多个Easy更新进程并发安装。
12
+
13
+ - 额度菜单重置时间跟随系统12/24小时制及AM/PM显示,保持原时区、日期和倒计时规则。
14
+
15
+ - 更新前在线判断版本,已最新时提示“已经是最新版本”,不安装也不重开;有新版并安装成功才自动重开。
16
+
3
17
  ## v0.2.6(2026-10-19)
4
18
 
5
19
  - 菜单显示“更新版本·当前版本号”,每天检查一次官方 npm,有新版时右侧显示绿色圆点;检查记录跨重启保存,只提示、不自动安装。
package/README.md CHANGED
@@ -4,11 +4,10 @@
4
4
 
5
5
  需要 Node.js 22+ 与 Claude Code 订阅登录;不支持把 API Key 账单余额当作订阅额度。
6
6
 
7
- ## v0.2.6 更新说明
7
+ ## v0.2.8 更新说明
8
8
 
9
- - 菜单显示“更新版本·0.2.6”,每24小时检查一次官方 npm,有新版本时右侧显示绿色圆点;重启后保留检查记录,只提示、不自动安装。
10
- - 命令行 `easy-claude update` 成功后自动重开浮窗,与菜单更新一致,保留已有时区、城市、位置和显示设置。
11
- - 新增 `easy-claude -V` 显示版本号,兼容 `-v`、`--version`。
9
+ - 当前时间浮窗与城市菜单跟随系统12/24小时制及地区格式,继续使用所选城市时区。
10
+ - 浮窗文字自动适应宽度,12小时制的上午/下午标记不会被截断;保留位置、配色和显示设置。
12
11
 
13
12
  历史版本更新记录见 [CHANGELOG](CHANGELOG.md)。
14
13
 
@@ -73,3 +72,9 @@ npm run build:overlay
73
72
  命令更新:`easy-claude update`,成功后会自动退出旧浮窗并打开新版。旧版本尚未提供 update 时,可先执行 `npm i -g easy-claude@latest`。更新过程中需要正常网络及原安装目录写入权限,不会自动使用 sudo。
74
73
 
75
74
  菜单中的“更新版本”会后台检查并更新,成功后自动重开浮窗;失败时保留当前浮窗并提示原因。更新期间不能重复点击,已保存设置保持不变。
75
+
76
+ 更新前会在线核对版本;已经是最新版本时只提示,不重复安装或重开浮窗。有更高正式版本并安装成功后,才自动重开。
77
+
78
+ 额度菜单的重置时刻跟随系统的12/24小时制和AM/PM格式,时区仍使用电脑系统时区。
79
+
80
+ 菜单“自动更新”默认关闭,开启后在浮窗运行期间每天检查一次,有新正式版本时自动安装并重开,保留设置;关闭后仍每天检查并显示新版提示,但不自动安装。开启时如已发现新版,会立即更新。自动更新失败仅在菜单提示,可点击“更新版本”查看原因或重试。
@@ -158,15 +158,19 @@ func versionCheckDue(lastAttempt: Double, checkedVersion: String?, currentVersio
158
158
  checkedVersion != currentVersion || now - lastAttempt >= 86400
159
159
  }
160
160
 
161
- func resetDescription(_ resetsAt: Double?, weekly: Bool, now: Date = Date(), zone: TimeZone = .current) -> String {
161
+ func resetDescription(_ resetsAt: Double?, weekly: Bool, now: Date = Date(), zone: TimeZone = .current,
162
+ locale: Locale = .autoupdatingCurrent) -> String {
162
163
  guard let resetsAt, resetsAt.isFinite, abs(resetsAt) < 8.64e12 else { return "重置时间未知" }
163
164
  let remaining = resetsAt - now.timeIntervalSince1970
164
165
  guard remaining > 0 else { return "已到重置时间,等待更新" }
165
166
  let formatter = DateFormatter()
166
- formatter.locale = Locale(identifier: "zh_CN")
167
+ formatter.locale = locale
167
168
  formatter.timeZone = zone
168
- formatter.dateFormat = weekly ? "d'日' HH:mm" : "HH:mm"
169
- let time = formatter.string(from: Date(timeIntervalSince1970: resetsAt))
169
+ formatter.setLocalizedDateFormatFromTemplate("jm")
170
+ let date = Date(timeIntervalSince1970: resetsAt)
171
+ let clock = formatter.string(from: date)
172
+ formatter.dateFormat = "d'日'"
173
+ let time = weekly ? "\(formatter.string(from: date)) \(clock)" : clock
170
174
  let duration: String
171
175
  if weekly {
172
176
  if remaining >= 86400 { duration = "\(Int(remaining / 86400))天" }
@@ -181,14 +185,23 @@ func resetDescription(_ resetsAt: Double?, weekly: Bool, now: Date = Date(), zon
181
185
  return "\(duration)后 \(time) 重置"
182
186
  }
183
187
 
184
- func clockText(at date: Date, zone: TimeZone) -> String {
188
+ func clockText(at date: Date, zone: TimeZone, locale: Locale = .autoupdatingCurrent) -> String {
185
189
  let formatter = DateFormatter()
186
- formatter.locale = Locale(identifier: "en_US_POSIX")
190
+ formatter.locale = locale
187
191
  formatter.timeZone = zone
188
- formatter.dateFormat = "HH:mm"
192
+ formatter.setLocalizedDateFormatFromTemplate("jm")
189
193
  return formatter.string(from: date)
190
194
  }
191
195
 
196
+
197
+ @MainActor
198
+ func fittedClockFont(for text: String, width: CGFloat, baseSize: CGFloat) -> NSFont {
199
+ let base = NSFont.monospacedDigitSystemFont(ofSize: baseSize, weight: .medium)
200
+ let measured = max(1, (text as NSString).size(withAttributes: [.font: base]).width)
201
+ let size = min(baseSize, baseSize * max(1, width - 2) / measured)
202
+ return NSFont.monospacedDigitSystemFont(ofSize: size, weight: .medium)
203
+ }
204
+
192
205
  func clockState(at date: Date, zone: TimeZone) -> RingState {
193
206
  var calendar = Calendar(identifier: .gregorian)
194
207
  calendar.timeZone = zone
@@ -208,7 +221,7 @@ final class ClockView: RingView {
208
221
  let now = Date()
209
222
  let time = clockText(at: now, zone: zone)
210
223
  (time as NSString).draw(in: CGRect(x: 0, y: 17, width: bounds.width, height: 25),
211
- withAttributes: [.font: NSFont.monospacedDigitSystemFont(ofSize: 20, weight: .medium),
224
+ withAttributes: [.font: fittedClockFont(for: time, width: bounds.width, baseSize: 20),
212
225
  .foregroundColor: clockState(at: now, zone: zone).color, .paragraphStyle: style])
213
226
  let city = cityName
214
227
  (city as NSString).draw(in: CGRect(x: 0, y: 1, width: bounds.width, height: 15),
@@ -233,6 +246,8 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate {
233
246
  var updater: Process?
234
247
  var versionCheck: Process?
235
248
  var updateAvailable = false
249
+ var automaticUpdateError: String?
250
+ var versionCheckError: String?
236
251
  let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "未知"
237
252
  var snapshot: Snapshot?
238
253
  var error: String?
@@ -433,6 +448,11 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate {
433
448
  updateItem.setAccessibilityHelp("有新版本可更新")
434
449
  }
435
450
  menu.addItem(updateItem)
451
+ let automatic = item("自动更新", #selector(toggleAutomaticUpdates))
452
+ automatic.state = UserDefaults.standard.bool(forKey: "automaticUpdatesEnabled") ? .on : .off
453
+ menu.addItem(automatic)
454
+ if let automaticUpdateError { menu.addItem(item(automaticUpdateError, nil)) }
455
+ if let versionCheckError { menu.addItem(item(versionCheckError, nil)) }
436
456
  menu.addItem(item("退出浮窗", #selector(quit)))
437
457
  return menu
438
458
  }
@@ -499,10 +519,13 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate {
499
519
  guard versionCheck == nil, !script.isEmpty,
500
520
  versionCheckDue(lastAttempt: last, checkedVersion: prefs.string(forKey: "updateCheckedVersion"),
501
521
  currentVersion: appVersion) else { return }
522
+ if prefs.string(forKey: "updateCheckedVersion") != appVersion {
523
+ prefs.set(false, forKey: "updateAvailable")
524
+ updateAvailable = false
525
+ }
502
526
  prefs.set(appVersion, forKey: "updateCheckedVersion")
503
527
  prefs.set(Date().timeIntervalSince1970, forKey: "updateLastAttempt")
504
- prefs.set(false, forKey: "updateAvailable")
505
- updateAvailable = false
528
+ versionCheckError = nil
506
529
  let process = Process(), pipe = Pipe()
507
530
  process.executableURL = URL(fileURLWithPath: node)
508
531
  process.arguments = [URL(fileURLWithPath: script).deletingLastPathComponent()
@@ -515,20 +538,36 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate {
515
538
  process.terminationHandler = { [weak self] process in
516
539
  let data = pipe.fileHandleForReading.readDataToEndOfFile()
517
540
  let value = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
518
- let available = process.terminationStatus == 0 && value?["available"] as? Bool == true
541
+ let available = process.terminationStatus == 0 ? value?["available"] as? Bool : nil
519
542
  Task { @MainActor in
520
543
  guard let self else { return }
521
544
  self.versionCheck = nil
545
+ guard let available else {
546
+ self.versionCheckError = "版本检查失败,保留上次结果"
547
+ return
548
+ }
549
+ self.versionCheckError = nil
522
550
  self.updateAvailable = available
523
551
  UserDefaults.standard.set(available, forKey: "updateAvailable")
552
+ if available && UserDefaults.standard.bool(forKey: "automaticUpdatesEnabled") {
553
+ self.startUpdate(automatic: true)
554
+ }
524
555
  }
525
556
  }
526
557
  versionCheck = process
527
558
  do { try process.run() }
528
- catch { versionCheck = nil }
559
+ catch { versionCheck = nil; versionCheckError = "版本检查失败,保留上次结果" }
560
+ }
561
+ @objc func toggleAutomaticUpdates() {
562
+ let prefs = UserDefaults.standard
563
+ let enabled = !prefs.bool(forKey: "automaticUpdatesEnabled")
564
+ prefs.set(enabled, forKey: "automaticUpdatesEnabled")
565
+ if enabled && updateAvailable { startUpdate(automatic: true) }
529
566
  }
530
- @objc func updateVersion() {
567
+ @objc func updateVersion() { startUpdate(automatic: false) }
568
+ func startUpdate(automatic: Bool) {
531
569
  guard updater == nil else { return }
570
+ automaticUpdateError = nil
532
571
  let cli = URL(fileURLWithPath: script).deletingLastPathComponent()
533
572
  .appendingPathComponent("overlay-update.js")
534
573
  let process = Process()
@@ -540,22 +579,35 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate {
540
579
  // npm 输出可能超过管道容量,写临时文件以免等待退出时死锁。
541
580
  let output = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
542
581
  guard FileManager.default.createFile(atPath: output.path, contents: nil,
543
- attributes: [.posixPermissions: 0o600]), let handle = try? FileHandle(forWritingTo: output) else {
544
- showUpdateResult("无法创建更新日志,请检查临时目录权限。")
582
+ attributes: [.posixPermissions: 0o600]), let handle = try? FileHandle(forUpdating: output) else {
583
+ if automatic { automaticUpdateError = "自动更新失败:无法创建更新日志" }
584
+ else { showUpdateResult("无法创建更新日志,请检查临时目录权限。") }
585
+ return
586
+ }
587
+ // 先取消文件名,描述符仍可读写;旧浮窗退出后也不会遗留日志。
588
+ do { try FileManager.default.removeItem(at: output) }
589
+ catch {
590
+ try? handle.close()
591
+ if automatic { automaticUpdateError = "自动更新失败:无法清理临时日志" }
592
+ else { showUpdateResult("无法清理临时更新日志,请检查临时目录权限。") }
545
593
  return
546
594
  }
547
595
  process.standardOutput = handle
548
596
  process.standardError = handle
549
597
  process.terminationHandler = { [weak self] process in
598
+ try? handle.seek(toOffset: 0)
599
+ let data = (try? handle.readToEnd()) ?? Data()
550
600
  try? handle.close()
551
- let data = (try? Data(contentsOf: output)) ?? Data()
552
- try? FileManager.default.removeItem(at: output)
553
601
  let message = String(decoding: data.suffix(4096), as: UTF8.self)
554
602
  Task { @MainActor in
555
603
  guard let self else { return }
556
604
  self.updater = nil
557
- self.showUpdateResult(process.terminationStatus == 0
558
- ? message : "更新失败,请检查网络或安装目录权限。\n" + message)
605
+ if automatic {
606
+ if process.terminationStatus != 0 { self.automaticUpdateError = "自动更新失败,请点击更新版本查看原因" }
607
+ } else {
608
+ self.showUpdateResult(process.terminationStatus == 0
609
+ ? message : "更新失败,请检查网络或安装目录权限。\n" + message)
610
+ }
559
611
  }
560
612
  }
561
613
  updater = process
@@ -563,8 +615,8 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate {
563
615
  catch {
564
616
  updater = nil
565
617
  try? handle.close()
566
- try? FileManager.default.removeItem(at: output)
567
- showUpdateResult("无法启动更新,请重新运行 easy-claude show。")
618
+ if automatic { automaticUpdateError = "自动更新失败:无法启动更新" }
619
+ else { showUpdateResult("无法启动更新,请重新运行 easy-claude show。") }
568
620
  }
569
621
  }
570
622
  func showUpdateResult(_ message: String) {
@@ -588,6 +640,14 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate {
588
640
  struct Main {
589
641
  @MainActor static func main() {
590
642
  if CommandLine.arguments.contains("--self-test") {
643
+ let preferenceSuite = "easy-auto-update-self-test-" + UUID().uuidString
644
+ let preferences = UserDefaults(suiteName: preferenceSuite)!
645
+ precondition(!preferences.bool(forKey: "automaticUpdatesEnabled"))
646
+ preferences.set(true, forKey: "automaticUpdatesEnabled")
647
+ precondition(UserDefaults(suiteName: preferenceSuite)!.bool(forKey: "automaticUpdatesEnabled"))
648
+ preferences.set(false, forKey: "automaticUpdatesEnabled")
649
+ precondition(!preferences.bool(forKey: "automaticUpdatesEnabled"))
650
+ preferences.removePersistentDomain(forName: preferenceSuite)
591
651
  precondition(!versionCheckDue(lastAttempt: 100, checkedVersion: "1.0.0", currentVersion: "1.0.0", now: 86499))
592
652
  precondition(versionCheckDue(lastAttempt: 100, checkedVersion: "1.0.0", currentVersion: "1.0.0", now: 86500))
593
653
  precondition(versionCheckDue(lastAttempt: 100, checkedVersion: nil, currentVersion: "1.0.0", now: 100))
@@ -596,17 +656,41 @@ struct Main {
596
656
  precondition(ClockCity.presets.allSatisfy { TimeZone(identifier: $0.identifier) != nil })
597
657
  let countdownStart = ISO8601DateFormatter().date(from: "2026-10-15T04:57:00Z")!
598
658
  let countdownUTC = TimeZone(secondsFromGMT: 0)!
599
- precondition(resetDescription(countdownStart.timeIntervalSince1970 + 10920, weekly: false, now: countdownStart, zone: countdownUTC) == "3小时2分后 07:59 重置")
659
+ let afternoon = ISO8601DateFormatter().date(from: "2026-10-21T14:30:00Z")!
660
+ for identifier in ["en_US", "en_GB", "zh_CN"] {
661
+ let text = clockText(at: afternoon, zone: countdownUTC, locale: Locale(identifier: identifier))
662
+ if identifier == "en_US" { precondition(text.contains("PM") && !text.contains("14:30")) }
663
+ else { precondition(text == "14:30") }
664
+ let font = fittedClockFont(for: text, width: 96, baseSize: 20)
665
+ precondition((text as NSString).size(withAttributes: [.font: font]).width <= 96 - 1)
666
+ }
667
+ let laClock = clockText(at: afternoon, zone: TimeZone(identifier: "America/Los_Angeles")!, locale: Locale(identifier: "en_US"))
668
+ precondition(laClock.contains("7:30") && laClock.contains("AM"))
669
+
670
+ let morning = ISO8601DateFormatter().date(from: "2026-10-21T02:30:00Z")!
671
+ for weekly in [false, true] {
672
+ let us = resetDescription(afternoon.timeIntervalSince1970, weekly: weekly,
673
+ now: morning, zone: countdownUTC, locale: Locale(identifier: "en_US"))
674
+ precondition(us.contains("2:30") && us.contains("PM") && !us.contains("14:30"))
675
+ precondition(!weekly || us.contains("21日"))
676
+ let gb = resetDescription(afternoon.timeIntervalSince1970, weekly: weekly,
677
+ now: morning, zone: countdownUTC, locale: Locale(identifier: "en_GB"))
678
+ precondition(gb.contains("14:30") && !gb.contains("PM"))
679
+ let am = resetDescription(morning.timeIntervalSince1970, weekly: weekly,
680
+ now: morning.addingTimeInterval(-60), zone: countdownUTC, locale: Locale(identifier: "en_US"))
681
+ precondition(am.contains("2:30") && am.contains("AM"))
682
+ }
683
+ precondition(resetDescription(countdownStart.timeIntervalSince1970 + 10920, weekly: false, now: countdownStart, zone: countdownUTC, locale: Locale(identifier: "en_GB")) == "3小时2分后 07:59 重置")
600
684
  let weekStart = ISO8601DateFormatter().date(from: "2026-10-14T08:03:00Z")!
601
- precondition(resetDescription(weekStart.timeIntervalSince1970 + 345360, weekly: true, now: weekStart, zone: countdownUTC) == "3天后 18日 07:59 重置")
685
+ precondition(resetDescription(weekStart.timeIntervalSince1970 + 345360, weekly: true, now: weekStart, zone: countdownUTC, locale: Locale(identifier: "en_GB")) == "3天后 18日 07:59 重置")
602
686
  precondition(resetDescription(nil, weekly: true) == "重置时间未知")
603
687
  precondition(resetDescription(countdownStart.timeIntervalSince1970, weekly: false, now: countdownStart) == "已到重置时间,等待更新")
604
- precondition(resetDescription(countdownStart.timeIntervalSince1970 + 1, weekly: false, now: countdownStart, zone: countdownUTC) == "1分后 04:57 重置")
605
- precondition(resetDescription(countdownStart.timeIntervalSince1970 + 86160, weekly: true, now: countdownStart, zone: countdownUTC) == "23小时后 16日 04:53 重置")
606
- precondition(resetDescription(countdownStart.timeIntervalSince1970 + 120, weekly: true, now: countdownStart, zone: countdownUTC) == "2分钟后 15日 04:59 重置")
607
- precondition(resetDescription(countdownStart.timeIntervalSince1970 + 86400, weekly: true, now: countdownStart, zone: countdownUTC) == "1天后 16日 04:57 重置")
608
- precondition(resetDescription(countdownStart.timeIntervalSince1970 + 86399, weekly: true, now: countdownStart, zone: countdownUTC) == "23小时后 16日 04:56 重置")
609
- precondition(resetDescription(countdownStart.timeIntervalSince1970 + 3599, weekly: false, now: countdownStart, zone: countdownUTC) == "1小时后 05:56 重置")
688
+ precondition(resetDescription(countdownStart.timeIntervalSince1970 + 1, weekly: false, now: countdownStart, zone: countdownUTC, locale: Locale(identifier: "en_GB")) == "1分后 04:57 重置")
689
+ precondition(resetDescription(countdownStart.timeIntervalSince1970 + 86160, weekly: true, now: countdownStart, zone: countdownUTC, locale: Locale(identifier: "en_GB")) == "23小时后 16日 04:53 重置")
690
+ precondition(resetDescription(countdownStart.timeIntervalSince1970 + 120, weekly: true, now: countdownStart, zone: countdownUTC, locale: Locale(identifier: "en_GB")) == "2分钟后 15日 04:59 重置")
691
+ precondition(resetDescription(countdownStart.timeIntervalSince1970 + 86400, weekly: true, now: countdownStart, zone: countdownUTC, locale: Locale(identifier: "en_GB")) == "1天后 16日 04:57 重置")
692
+ precondition(resetDescription(countdownStart.timeIntervalSince1970 + 86399, weekly: true, now: countdownStart, zone: countdownUTC, locale: Locale(identifier: "en_GB")) == "23小时后 16日 04:56 重置")
693
+ precondition(resetDescription(countdownStart.timeIntervalSince1970 + 3599, weekly: false, now: countdownStart, zone: countdownUTC, locale: Locale(identifier: "en_GB")) == "1小时后 05:56 重置")
610
694
  let testRing = RingView()
611
695
  testRing.showFiveHourRing = false
612
696
  precondition(testRing.displaysWeeklyPercentage)
@@ -618,9 +702,9 @@ struct Main {
618
702
  let singapore = TimeZone(identifier: "Asia/Singapore")!
619
703
  let winter = ISO8601DateFormatter().date(from: "2026-01-15T12:00:00Z")!
620
704
  let summer = ISO8601DateFormatter().date(from: "2026-07-15T12:00:00Z")!
621
- precondition(clockText(at: winter, zone: la) == "04:00")
622
- precondition(clockText(at: summer, zone: la) == "05:00")
623
- precondition(clockText(at: winter, zone: singapore) == "20:00")
705
+ precondition(clockText(at: winter, zone: la, locale: Locale(identifier: "en_GB")) == "04:00")
706
+ precondition(clockText(at: summer, zone: la, locale: Locale(identifier: "en_GB")) == "05:00")
707
+ precondition(clockText(at: winter, zone: singapore, locale: Locale(identifier: "en_GB")) == "20:00")
624
708
  precondition(TimeZone(identifier: "Invalid/Zone") == nil)
625
709
  let utc = TimeZone(secondsFromGMT: 0)!
626
710
  for (hour, state) in [(0, RingState.red), (6, .red), (8, .red), (9, .green), (14, .green), (15, .green), (17, .green), (18, .orange), (23, .orange)] {
@@ -5,7 +5,7 @@
5
5
  <key>CFBundleIdentifier</key><string>com.unionschool.easy-claude.overlay</string>
6
6
  <key>CFBundleName</key><string>Easy Claude Overlay</string>
7
7
  <key>CFBundlePackageType</key><string>APPL</string>
8
- <key>CFBundleShortVersionString</key><string>0.2.6</string>
8
+ <key>CFBundleShortVersionString</key><string>0.2.8</string>
9
9
  <key>LSMinimumSystemVersion</key><string>14.0</string>
10
10
  <key>LSUIElement</key><true/>
11
11
  <key>NSHighResolutionCapable</key><true/>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "easy-claude",
3
- "version": "0.2.6",
3
+ "version": "0.2.8",
4
4
  "description": "Claude Code quota rings and transparent world clock for Claude desktop",
5
5
  "type": "module",
6
6
  "bin": {
@@ -21,7 +21,8 @@
21
21
  "scripts": {
22
22
  "test": "node --test",
23
23
  "start": "node bin/easy-claude.js",
24
- "build:overlay": "node scripts/build-overlay.mjs"
24
+ "build:overlay": "node scripts/build-overlay.mjs",
25
+ "test:native": "python3 scripts/test-native-update.py"
25
26
  },
26
27
  "license": "MIT",
27
28
  "author": "UnionSchool",
@@ -1,10 +1,12 @@
1
1
  import { pathToFileURL } from 'node:url';
2
2
  import { updatePackage } from './update.js';
3
+ import { withUpdateLock } from './update-lock.js';
3
4
 
4
5
  export async function updateAndShow({ update = updatePackage,
5
- show = async () => (await import('./overlay.js')).launchOverlay() } = {}) {
6
- await update('easy-claude');
7
- await show();
6
+ show = async () => (await import('./overlay.js')).launchOverlay(), lock = withUpdateLock } = {}) {
7
+ await lock(async () => {
8
+ if (await update('easy-claude')) await show();
9
+ });
8
10
  }
9
11
 
10
12
  if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
@@ -0,0 +1,22 @@
1
+ import { mkdir, rmdir } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { tmpdir } from 'node:os';
4
+ import { createHash } from 'node:crypto';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { installedPrefix } from './update.js';
7
+
8
+ const root = fileURLToPath(new URL('../', import.meta.url));
9
+ const prefix = installedPrefix(root) ?? root;
10
+ const key = createHash('sha256').update(prefix).digest('hex').slice(0, 24);
11
+ const defaultLock = join(tmpdir(), `easy-tools-update-${key}.lock`);
12
+
13
+ export async function withUpdateLock(action, { lock = defaultLock } = {}) {
14
+ try { await mkdir(lock, { mode: 0o700 }); }
15
+ catch (error) {
16
+ // shortcut: 异常强退可能留下锁;为避免误删在用锁,不自动按时间清除。
17
+ if (error.code === 'EEXIST') throw new Error(`另一个 Easy 工具正在更新。若确认无更新进程,可删除遗留锁目录后重试:${lock}`);
18
+ throw new Error('无法建立更新锁,请检查临时目录权限。');
19
+ }
20
+ try { return await action(); }
21
+ finally { await rmdir(lock); }
22
+ }
package/src/update.js CHANGED
@@ -54,14 +54,17 @@ function runNpm(command, args) {
54
54
  }
55
55
 
56
56
  export async function updatePackage(name, { root = fileURLToPath(new URL('../', import.meta.url)),
57
- getNpmCli = findNpmCli, getLatest = readLatest, currentVersion = version,
57
+ getNpmCli = findNpmCli, getLatest = readLatest,
58
+ currentVersion = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version,
58
59
  run = runNpm, platform = process.platform } = {}) {
59
60
  if (!['easy-codex', 'easy-claude'].includes(name)) throw new Error('不支持的更新包名。');
60
61
  const npmCli = await getNpmCli();
61
62
  const latest = await getLatest(npmCli, name);
62
63
  if (!isNewer(latest, currentVersion)) {
63
- console.log(`${name} 当前 ${currentVersion},npm 最新 ${latest},无需更新。`);
64
- return;
64
+ console.log(currentVersion === latest
65
+ ? `${name} 已经是最新版本(${currentVersion})。`
66
+ : `${name} 当前版本 ${currentVersion} 高于 npm 最新版本 ${latest},无需更新。`);
67
+ return false;
65
68
  }
66
69
  const prefix = installedPrefix(root, platform);
67
70
  // 先在线检查再锁定版本,避免安装阶段复用旧 latest 缓存而降级。
@@ -69,6 +72,7 @@ export async function updatePackage(name, { root = fileURLToPath(new URL('../',
69
72
  '--prefer-online', '--registry=https://registry.npmjs.org', `${name}@${latest}`];
70
73
  await run(process.execPath, args);
71
74
  console.log(`${name} 已更新到 ${latest}。`);
75
+ return true;
72
76
  }
73
77
 
74
78
  export async function checkUpdate(name, { getNpmCli = findNpmCli, getLatest = readLatest,