easy-claude 1.0.3 → 1.2.0

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.
@@ -3,6 +3,7 @@ import SwiftUI
3
3
  import CoreGraphics
4
4
  import Darwin
5
5
  import UserNotifications
6
+ import Network
6
7
 
7
8
  // 语言与地区/小时制独立:只保存用户选择,不改系统设置。
8
9
  enum AppLanguage: String, CaseIterable {
@@ -150,7 +151,7 @@ struct UsageRefreshSchedule {
150
151
  mutating func receive(rateLimited: Bool, succeeded: Bool, now: Double) {
151
152
  if rateLimited {
152
153
  rateLimitCount = min(rateLimitCount + 1, 2)
153
- nextAllowedAt = now + min(900, usageRefreshInterval * pow(2, Double(rateLimitCount)))
154
+ nextAllowedAt = now + min(900, usageRateLimitBase * pow(2, Double(rateLimitCount)))
154
155
  } else if succeeded {
155
156
  rateLimitCount = 0
156
157
  nextAllowedAt = 0
@@ -521,8 +522,8 @@ enum LoginStartup {
521
522
  let controlProduct = "Claude"
522
523
  let controlLoginName = "Claude Code"
523
524
  let controlLoginCommand = "claude auth login"
524
- let usageRefreshInterval: TimeInterval = 300
525
- let controlStaleSeconds: Double = usageRefreshInterval * 2
525
+ let usageRateLimitBase: TimeInterval = 300
526
+ let controlStaleSeconds: Double = 600
526
527
  func controlQuotas(_ windows: [UsageWindow]) -> [ControlQuota] { return [windows.first { $0.id == "five_hour:primary" }.map { ControlQuota(window: $0, weekly: false) }, windows.first { $0.id == "seven_day:primary" }.map { ControlQuota(window: $0, weekly: true) }].compactMap { $0 } }
527
528
 
528
529
  struct ControlQuota: Identifiable {
@@ -554,7 +555,7 @@ func controlState(snapshot: Snapshot?, error: String?, code: String?, weeklySele
554
555
  let title = code == "auth_required" ? L("未登录", "Not signed in") : code == "auth_expired" ? L("登录已过期", "Login expired") : L("查询失败", "Query failed")
555
556
  return ControlState(mode: auth ? code! : "failed", text: title, headline: title, detail: displayMessage(error), quotas: [])
556
557
  }
557
- guard let snapshot else { return ControlState(mode: "loading", text: "—", headline: L("正在读取", "Loading"), detail: L("正在查询本机CLI账号额度", "Reading local CLI account usage"), quotas: []) }
558
+ guard let snapshot else { return ControlState(mode: "unknown", text: "—", headline: L("尚未读取额度", "Usage not loaded"), detail: L("点击刷新额度,或开启额度自动刷新。", "Refresh usage or enable automatic usage refresh."), quotas: []) }
558
559
  guard now - snapshot.fetchedAt <= controlStaleSeconds, snapshot.fetchedAt <= now + 5,
559
560
  !rows.isEmpty, rows.allSatisfy({ row in
560
561
  guard let remaining = row.window.remaining, remaining.isFinite, (0...100).contains(remaining) else { return false }
@@ -651,6 +652,8 @@ struct ControlPanelView: View {
651
652
  }
652
653
  }
653
654
  Divider()
655
+ setting(L("额度自动刷新", "Automatic usage refresh"), value: owner.automaticUsageRefresh) { owner.toggleAutomaticUsageRefresh() }
656
+ Divider()
654
657
  HStack(spacing: 7) {
655
658
  Image(systemName: "clock").foregroundStyle(.secondary)
656
659
  let clockParts = floatingClockLines(at: Date(), zone: owner.clock.zone)
@@ -663,15 +666,7 @@ struct ControlPanelView: View {
663
666
  Text(cityLabel(owner.clock.cityName)).font(.system(size: 11)).foregroundStyle(.secondary).lineLimit(1).truncationMode(.tail)
664
667
  }.accessibilityElement(children: .combine)
665
668
  Divider()
666
- HStack(alignment: .center, spacing: 9) {
667
- Image(systemName: "network").foregroundStyle(.secondary)
668
- VStack(alignment: .leading, spacing: 4) {
669
- Text(L("网络出口", "Network exit")).font(.system(size: 12, weight: .medium))
670
- Text(displayMessage(owner.ipText)).font(.system(size: 11)).foregroundStyle(.secondary).textSelection(.enabled).lineLimit(1).minimumScaleFactor(0.7)
671
- }
672
- Spacer(minLength: 3)
673
- iconButton(L("刷新公网IP", "Refresh public IP"), "arrow.clockwise") { owner.refreshIP() }.disabled(owner.ipQuery != nil)
674
- }
669
+ protection
675
670
  if owner.controlsExpanded { settings }
676
671
  }.padding(16)
677
672
  }.scrollIndicators(.hidden)
@@ -682,6 +677,8 @@ struct ControlPanelView: View {
682
677
  }
683
678
  .buttonStyle(.plain).accessibilityIdentifier("moreSettings")
684
679
  Spacer()
680
+ Button { owner.launchClaudeApp() } label: { Label(L("启动 Claude", "Launch Claude"), systemImage: "play") }
681
+ .buttonStyle(.plain).accessibilityIdentifier("launchClaudeApp")
685
682
  Divider().frame(height: 17)
686
683
  Button { owner.quit() } label: { Label(L("退出", "Quit"), systemImage: "power") }.buttonStyle(.plain)
687
684
  }.font(.system(size: 12)).padding(.horizontal, 16).padding(.vertical, 12)
@@ -695,6 +692,75 @@ struct ControlPanelView: View {
695
692
  Button(action: action) { Image(systemName: image).frame(width: 20, height: 20) }
696
693
  .buttonStyle(.plain).help(label).accessibilityLabel(label)
697
694
  }
695
+ var protection: some View {
696
+ VStack(alignment: .leading, spacing: 10) {
697
+ HStack {
698
+ Label(L("网络与保护", "Network & protection"), systemImage: "shield")
699
+ .font(.system(size: 12, weight: .semibold))
700
+ Spacer()
701
+ Toggle(L("出口 IP 保护", "Exit IP protection"), isOn: Binding(
702
+ get: { owner.protectionEnabled }, set: { owner.setProtectionEnabled($0) }))
703
+ .toggleStyle(.switch).tint(.green).controlSize(.mini).font(.system(size: 10))
704
+ .accessibilityIdentifier("ipProtectionToggle")
705
+ }
706
+ Label(owner.protectionStateText, systemImage: "circle.fill")
707
+ .font(.system(size: 10)).foregroundStyle(owner.protectionIsAllowed ? .green : (owner.protectionEnabled ? .orange : .secondary))
708
+ networkRow(L("当前出口", "Current exit"), owner.networkIPText)
709
+ networkRow(L("允许出口", "Allowed exits"), owner.allowedIPSummary)
710
+ HStack {
711
+ Text(owner.protectionCheckedText).font(.system(size: 10)).foregroundStyle(.secondary)
712
+ Spacer()
713
+ Button(L("重新检测", "Check again")) { owner.refreshNetworkIP() }
714
+ .controlSize(.small).disabled(owner.protectionEnabled ? owner.protectionReport?.state == "checking" : owner.ipQuery != nil)
715
+ }
716
+ if owner.protectionEnabled, let reason = owner.protectionReport?.reason, !reason.isEmpty {
717
+ Text(AppLanguage.current == .zh ? reason : "Access is blocked until a current IP check matches the allowlist.")
718
+ .font(.system(size: 10)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
719
+ }
720
+ if owner.controlsExpanded {
721
+ Divider()
722
+ Text(L("保护设置", "Protection settings")).font(.system(size: 11, weight: .semibold))
723
+ TextField(L("允许的 IPv4,逗号分隔", "Allowed IPv4 addresses, comma-separated"), text: $owner.protectionIPs)
724
+ .textFieldStyle(.roundedBorder).font(.system(size: 11))
725
+ .onChange(of: owner.protectionIPs) { _, _ in owner.protectionConfigurationChanged() }
726
+ .accessibilityIdentifier("ipProtectionAddresses")
727
+ HStack {
728
+ Text(L("复查间隔", "Check interval"))
729
+ Spacer()
730
+ Picker("", selection: $owner.protectionInterval) {
731
+ ForEach([60, 120, 300], id: \.self) { value in Text("\(value)s").tag(value) }
732
+ }.labelsHidden().frame(width: 85)
733
+ .onChange(of: owner.protectionInterval) { _, _ in owner.protectionConfigurationChanged() }
734
+ }.font(.system(size: 11)).controlSize(.small)
735
+ networkRow(L("本机代理", "Local proxy"), "127.0.0.1:18197")
736
+ HStack {
737
+ Button { owner.changeClaudeProxy() } label: {
738
+ Text(owner.proxyActionText).font(.system(size: 11, weight: .medium)).foregroundColor(.black)
739
+ .padding(.horizontal, 10).padding(.vertical, 5)
740
+ .background(RoundedRectangle(cornerRadius: 5).fill(owner.proxyReport?.active == true ? Color.yellow : Color.green))
741
+ }.buttonStyle(.plain)
742
+ .disabled(owner.proxyProcess != nil || owner.proxyReport == nil)
743
+ .accessibilityIdentifier("claudeProxyAction")
744
+ if owner.proxyProcess != nil { ProgressView().controlSize(.small) }
745
+ }
746
+ if let message = owner.proxyMessage {
747
+ Text(message).font(.system(size: 10)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
748
+ }
749
+ Text(L("Claude指向本机代理时,关闭保护或退出工具会阻断连接。配置变更需手动重开Claude生效。", "While Claude uses this proxy, turning off protection or quitting blocks connections. Reopen Claude manually after configuration changes."))
750
+ .font(.system(size: 10)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
751
+ }
752
+ if let error = owner.protectionError {
753
+ Text(error).font(.system(size: 10)).foregroundStyle(.orange).fixedSize(horizontal: false, vertical: true)
754
+ }
755
+ }
756
+ }
757
+ func networkRow(_ label: String, _ value: String) -> some View {
758
+ HStack(alignment: .top) {
759
+ Text(label).font(.system(size: 11)).foregroundStyle(.secondary).frame(width: 66, alignment: .leading)
760
+ Text(value).font(.system(size: 11, design: .monospaced)).textSelection(.enabled)
761
+ .frame(maxWidth: .infinity, alignment: .leading).fixedSize(horizontal: false, vertical: true)
762
+ }
763
+ }
698
764
  func quota(_ row: ControlQuota) -> some View {
699
765
  let valid = state.mode == "ready" || state.mode == "waiting"
700
766
  let value = valid ? row.window.remaining : nil
@@ -733,19 +799,9 @@ struct ControlPanelView: View {
733
799
  }
734
800
  var settings: some View {
735
801
  VStack(alignment: .leading, spacing: 12) {
736
- HStack {
737
- Text(L("语言", "Language")).font(.system(size: 12))
738
- Spacer()
739
- Picker(L("语言", "Language"), selection: Binding(get: { UserDefaults.standard.string(forKey: "interfaceLanguage") ?? "system" }, set: { owner.setLanguage($0) })) {
740
- Text(L("跟随系统", "System default")).tag("system")
741
- Text("简体中文").tag("zh")
742
- Text("English").tag("en")
743
- }.labelsHidden().frame(width: 155).accessibilityIdentifier("interfaceLanguage")
744
- }
745
- Divider()
746
802
  Text(L("浮窗与时间", "Overlay & time")).font(.system(size: 10)).foregroundStyle(.secondary)
747
803
  setting(L("显示时间", "Show time"), value: owner.clockEnabled) { owner.toggleClock() }
748
- setting(L("跟随IP时区", "Follow IP time zone"), value: owner.followIPTimeZone) { owner.toggleFollowIPTimeZone() }
804
+ setting(L("跟随IP时区:ipinfo.io", "Follow IP time zone: ipinfo.io"), value: owner.followIPTimeZone) { owner.toggleFollowIPTimeZone() }
749
805
  if owner.followIPTimeZone && owner.ipClock.zone == nil {
750
806
  Text(L("IP时区不可用,暂用自定义时间", "IP time zone unavailable; using manual time")).font(.system(size: 10)).foregroundStyle(.secondary)
751
807
  }
@@ -777,7 +833,17 @@ struct ControlPanelView: View {
777
833
  if let reminder = owner.reminder { Text(L("等待恢复:", "Waiting: ") + recoveryCountdown(reminder.due, now: Date().timeIntervalSince1970)).font(.system(size: 10)).foregroundStyle(.secondary) }
778
834
  setting(L("开机启动", "Launch at login"), value: LoginStartup.enabled()) { owner.toggleLoginStartup() }
779
835
  Divider()
780
- Text(L("版本与更新", "Version & updates")).font(.system(size: 10)).foregroundStyle(.secondary)
836
+ Text(L("通用与更新", "General & updates")).font(.system(size: 10)).foregroundStyle(.secondary)
837
+ HStack {
838
+ Text(L("语言", "Language")).font(.system(size: 12))
839
+ Spacer()
840
+ Picker(L("语言", "Language"), selection: Binding(get: { UserDefaults.standard.string(forKey: "interfaceLanguage") ?? "system" }, set: { owner.setLanguage($0) })) {
841
+ Text(L("跟随系统", "System default")).tag("system")
842
+ Text("简体中文").tag("zh")
843
+ Text("English").tag("en")
844
+ }.labelsHidden().frame(width: 155).accessibilityIdentifier("interfaceLanguage")
845
+ }
846
+
781
847
  setting(L("自动更新", "Automatic updates"), value: UserDefaults.standard.bool(forKey: "automaticUpdatesEnabled")) { owner.toggleAutomaticUpdates() }
782
848
  HStack {
783
849
  Text("v\(owner.appVersion)").font(.system(size: 11))
@@ -792,6 +858,122 @@ struct ControlPanelView: View {
792
858
 
793
859
  @MainActor
794
860
  final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNotificationCenterDelegate, ObservableObject {
861
+ struct ProtectionReport: Decodable {
862
+ var state: String
863
+ var reason: String?
864
+ var ip: String?
865
+ var checkedAt: String?
866
+ var ready: Bool?
867
+ }
868
+ struct ProxyReport: Decodable {
869
+ var active: Bool
870
+ var configured: Bool
871
+ var hasBackup: Bool?
872
+ var machinePolicy: Bool?
873
+ var needsDefaultRestore: Bool?
874
+ var needsRestart: Bool?
875
+ var restoredDefault: Bool?
876
+ var error: String?
877
+ }
878
+ @Published var proxyReport: ProxyReport?
879
+ @Published var proxyMessage: String?
880
+ @Published var proxyProcess: Process?
881
+ var proxyActionText: String {
882
+ guard proxyReport != nil else { return L("检查代理中…", "Checking proxy…") }
883
+ return proxyReport?.active == true ? L("停止Claude代理", "Stop Claude proxy") : L("启动Claude代理", "Start Claude proxy")
884
+ }
885
+ func checkProxyConfiguration() { runProxyAction("status") }
886
+ func changeClaudeProxy() { runProxyAction(proxyReport?.active == true ? "stop" : "start") }
887
+ func runProxyAction(_ action: String) {
888
+ guard proxyProcess == nil else { return }
889
+ let process = Process(), pipe = Pipe()
890
+ process.executableURL = URL(fileURLWithPath: node)
891
+ process.arguments = [URL(fileURLWithPath: script).deletingLastPathComponent().appendingPathComponent("overlay-proxy.js").path, action]
892
+ var env = ProcessInfo.processInfo.environment
893
+ env["PATH"] = searchPath
894
+ if !claudeHome.isEmpty { env["CLAUDE_CONFIG_DIR"] = claudeHome }
895
+ process.environment = env
896
+ process.standardOutput = pipe; process.standardError = FileHandle.nullDevice
897
+ process.terminationHandler = { [weak self] process in
898
+ let data = pipe.fileHandleForReading.readDataToEndOfFile()
899
+ Task { @MainActor in
900
+ guard let self, self.proxyProcess === process else { return }
901
+ self.proxyProcess = nil
902
+ guard data.count <= 8192, let result = try? JSONDecoder().decode(ProxyReport.self, from: data) else {
903
+ self.proxyReport = nil
904
+ self.proxyMessage = L("无法检查代理配置,请重开面板后重试。", "Cannot verify proxy settings. Reopen the panel to retry.")
905
+ return
906
+ }
907
+ self.proxyReport = result
908
+ if let error = result.error {
909
+ self.proxyMessage = AppLanguage.current == .zh ? error : "Proxy configuration failed. Check permissions and saved backups."
910
+ } else if result.machinePolicy == true {
911
+ self.proxyMessage = L("存在机器级代理策略,请由管理员处理。", "A machine-level proxy policy requires administrator management.")
912
+ } else if result.needsDefaultRestore == true {
913
+ let alert = NSAlert()
914
+ alert.messageText = L("旧配置缺少原始备份", "Original settings were not saved")
915
+ alert.informativeText = L("这份代理配置并非由新按钮保存。无法确认原来的自定义代理;可以只移除 easy-claude 的代理字段,恢复应用默认网络。其他字段保留,Claude 不会自动重开。", "These settings have no saved original proxy. You may remove only easy-claude proxy fields and restore application defaults. Other settings stay intact; Claude will not restart.")
916
+ alert.addButton(withTitle: L("恢复默认", "Restore defaults")); alert.addButton(withTitle: L("取消", "Cancel"))
917
+ if alert.runModal() == .alertFirstButtonReturn { self.runProxyAction("stop-default") }
918
+ } else if result.needsRestart == true {
919
+ self.proxyMessage = result.active ? L("代理配置成功。请确认保护开启且IP验证通过,再手动重开Claude。", "Proxy configured. Ensure protection is enabled and the IP is verified, then reopen Claude manually.") : (result.restoredDefault == true ? L("已恢复默认配置,请手动重开Claude生效。", "Defaults restored. Reopen Claude manually to apply.") : L("已恢复原代理配置,请手动重开Claude生效。", "Original proxy settings restored. Reopen Claude manually to apply."))
920
+ } else { self.proxyMessage = nil }
921
+ self.resizeControls()
922
+ }
923
+ }
924
+ proxyProcess = process
925
+ do { try process.run() }
926
+ catch { proxyProcess = nil; proxyReport = nil; proxyMessage = L("无法启动代理配置组件。", "Cannot start the proxy configuration helper.") }
927
+ }
928
+ @Published var automaticUsageRefresh = UserDefaults.standard.bool(forKey: "automaticUsageRefresh")
929
+ var protectionIsAllowed: Bool { protectionEnabled && proxyReport?.configured == true && protectionError == nil && protectionReport?.ready == true && protectionReport?.state == "allowed" }
930
+ var networkIPText: String {
931
+ guard protectionEnabled else { return displayMessage(ipText) }
932
+ guard protectionError == nil, let report = protectionReport else { return L("IP 未知", "IP unknown") }
933
+ // 保护检测是地址展示的唯一来源,独立地理查询不能覆盖它。
934
+ if let ip = report.ip, report.state == "allowed" || (report.state == "blocked" && report.reason == "出口不在白名单") { return ip }
935
+ return report.state == "checking" ? L("正在检测…", "Checking…") : L("IP 未知", "IP unknown")
936
+ }
937
+ var allowedIPSummary: String {
938
+ let values = protectionIPs.components(separatedBy: CharacterSet(charactersIn: ",,\n ")).filter { !$0.isEmpty }
939
+ return values.isEmpty ? L("尚未设置", "Not configured") : values.joined(separator: ", ")
940
+ }
941
+ var protectionCheckedText: String {
942
+ let parser = ISO8601DateFormatter()
943
+ parser.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
944
+ guard protectionEnabled, let raw = protectionReport?.checkedAt,
945
+ let date = parser.date(from: raw) ?? ISO8601DateFormatter().date(from: raw) else {
946
+ return L("最近检测:—", "Last check: —")
947
+ }
948
+ let formatter = DateFormatter(); formatter.timeStyle = .medium
949
+ return L("最近检测:", "Last check: ") + formatter.string(from: date)
950
+ }
951
+ @Published var protectionEnabled = UserDefaults.standard.bool(forKey: "ipProtectionEnabled")
952
+ @Published var protectionIPs = UserDefaults.standard.string(forKey: "ipProtectionAddresses") ?? ""
953
+ @Published var protectionInterval = max(60, UserDefaults.standard.object(forKey: "ipProtectionInterval") as? Int ?? 60)
954
+ @Published var protectionReport: ProtectionReport?
955
+ @Published var protectionError: String?
956
+ var protectionProcess: Process?
957
+ var protectionInput: FileHandle?
958
+ var protectionOutput: FileHandle?
959
+ var protectionBuffer = Data()
960
+ var protectionEditTimer: Timer?
961
+ var protectionHeartbeat: TimeInterval = 0
962
+ let protectionPathMonitor = NWPathMonitor()
963
+ var protectionStateText: String {
964
+ if let protectionError { return L("未受保护:", "Unprotected: ") + protectionError }
965
+ if !protectionEnabled {
966
+ return protectionProcess != nil && protectionReport?.state != "off" ? L("正在阻断代理…", "Blocking proxy…") : L("保护已关闭 · 代理已阻断", "Protection off · proxy blocked")
967
+ }
968
+ guard proxyReport?.configured == true else { return L("Claude代理未配置完成 · 未受保护", "Claude proxy is not configured · unprotected") }
969
+ switch protectionReport?.state {
970
+ case "allowed": return L("代理已放通 · 出口 IP 符合白名单", "Proxy allowed · exit IP matches the allowlist")
971
+ case "checking": return L("验证中 · 代理已阻断", "Verifying · proxy blocked")
972
+ case "blocked": return L("代理已阻断 · 等待有效 IP 验证", "Proxy blocked · waiting for valid IP verification")
973
+ case "fault": return L("保护故障 · 未受保护", "Protection fault · unprotected")
974
+ default: return L("未受保护 · 正在建立保护服务", "Unprotected · starting protection service")
975
+ }
976
+ }
795
977
  let panel = NSPanel(contentRect: CGRect(x: 0, y: 0, width: 32, height: 32),
796
978
  styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
797
979
  let ring = RingView(frame: CGRect(x: 0, y: 0, width: 32, height: 32))
@@ -812,13 +994,14 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
812
994
  var controlHeight: CGFloat {
813
995
  let state = currentControlState()
814
996
  let quotaHeight: CGFloat = state.login ? 155 : CGFloat(max(1, state.quotas.count)) * 62 + (state.mode == "ready" ? 0 : 65)
815
- let total: CGFloat = (controlsExpanded ? 198 : 174) + quotaHeight + (controlsExpanded ? (followIPTimeZone ? 355 : 420) : 0)
997
+ let total = quotaHeight + 310 + (controlsExpanded ? (followIPTimeZone ? 455 : 520) : 0)
816
998
  return min(total, max(280, (status?.button?.window?.screen?.visibleFrame.height ?? NSScreen.main?.visibleFrame.height ?? 900) - 65))
817
999
  }
818
1000
  var status: NSStatusItem?
819
1001
  var timer: Timer?
820
1002
  var ipQuery: Process?
821
1003
  var ipLastAttempt = Date.distantPast
1004
+ var ipLastProbeUptime = -Double.infinity
822
1005
  var ipText = L("正在获取IP…", "Fetching IP…")
823
1006
  var query: Process?
824
1007
  var updater: Process?
@@ -850,6 +1033,9 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
850
1033
  node = args[1]; script = args[2]; searchPath = args[3]
851
1034
  claudeHome = args.count > 4 ? args[4] : ""
852
1035
  let prefs = UserDefaults.standard
1036
+ if let previous = prefs.object(forKey: "ipProtectionInterval") as? Int, previous < 60 {
1037
+ prefs.set(60, forKey: "ipProtectionInterval")
1038
+ }
853
1039
  if prefs.object(forKey: "leftInset") != nil {
854
1040
  inset = CGPoint(x: prefs.double(forKey: "leftInset"), y: prefs.double(forKey: "bottomInset"))
855
1041
  }
@@ -911,14 +1097,121 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
911
1097
  controlPopover.animates = !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion
912
1098
  controlPopover.contentViewController = NSHostingController(rootView: ControlPanelView(owner: self))
913
1099
  timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(tick), userInfo: nil, repeats: true)
1100
+ // 授权确认或菜单跟踪期间也要维持保护心跳。
1101
+ if let timer { RunLoop.main.add(timer, forMode: .common) }
914
1102
  NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(hide), name: NSWorkspace.didDeactivateApplicationNotification, object: nil)
1103
+ NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(protectionNetworkChanged), name: NSWorkspace.didWakeNotification, object: nil)
1104
+ protectionPathMonitor.pathUpdateHandler = { [weak self] _ in
1105
+ Task { @MainActor in self?.protectionNetworkChanged() }
1106
+ }
1107
+ protectionPathMonitor.start(queue: DispatchQueue(label: "easy-claude.network"))
1108
+ startProtectionService()
1109
+ checkProxyConfiguration()
915
1110
  tick()
916
1111
  }
1112
+ func setProtectionEnabled(_ enabled: Bool) {
1113
+ if enabled && protectionIPs.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
1114
+ protectionError = L("请先在更多设置中输入允许的 IPv4。", "Enter an allowed IPv4 address in More settings first.")
1115
+ resizeControls(); return
1116
+ }
1117
+ protectionEnabled = enabled
1118
+ UserDefaults.standard.set(enabled, forKey: "ipProtectionEnabled")
1119
+ protectionError = nil
1120
+ if enabled && protectionProcess == nil { startProtectionService() }
1121
+ else if protectionProcess != nil { configureProtection() }
1122
+ resizeControls()
1123
+ }
1124
+ func protectionConfigurationChanged() {
1125
+ UserDefaults.standard.set(protectionIPs, forKey: "ipProtectionAddresses")
1126
+ UserDefaults.standard.set(protectionInterval, forKey: "ipProtectionInterval")
1127
+ guard protectionEnabled else { return }
1128
+ sendProtection(["action": "hold"])
1129
+ protectionEditTimer?.invalidate()
1130
+ protectionEditTimer = Timer.scheduledTimer(withTimeInterval: 0.4, repeats: false) { [weak self] _ in
1131
+ Task { @MainActor in self?.configureProtection() }
1132
+ }
1133
+ }
1134
+ func configureProtection() {
1135
+ let ips = protectionIPs.components(separatedBy: CharacterSet(charactersIn: ",,\n "))
1136
+ .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty }
1137
+ sendProtection(["action": "configure", "enabled": protectionEnabled, "ips": ips, "interval": protectionInterval])
1138
+ }
1139
+ func sendProtection(_ command: [String: Any]) {
1140
+ guard let input = protectionInput, protectionProcess?.isRunning == true else { return }
1141
+ do {
1142
+ var data = try JSONSerialization.data(withJSONObject: command); data.append(10)
1143
+ try input.write(contentsOf: data)
1144
+ } catch { protectionError = L("保护控制通信失败。", "Protection control connection failed."); protectionProcess?.terminate() }
1145
+ }
1146
+ @objc func protectionNetworkChanged() {
1147
+ if protectionEnabled { sendProtection(["action": "invalidate"]) }
1148
+ ipQuery?.terminate(); ipQuery = nil
1149
+ ipText = L("正在获取IP…", "Fetching IP…")
1150
+ receiveIPTimeZone(nil)
1151
+ refreshIP()
1152
+ }
1153
+ func startProtectionService() {
1154
+ guard protectionProcess == nil else { return }
1155
+ let process = Process(), input = Pipe(), output = Pipe()
1156
+ process.executableURL = URL(fileURLWithPath: node)
1157
+ process.arguments = [URL(fileURLWithPath: script).deletingLastPathComponent().appendingPathComponent("overlay-guard.js").path]
1158
+ process.standardInput = input; process.standardOutput = output; process.standardError = FileHandle.nullDevice
1159
+ var env = ProcessInfo.processInfo.environment; env["PATH"] = searchPath
1160
+ process.environment = env
1161
+ protectionBuffer.removeAll(); protectionReport = nil; protectionError = nil
1162
+ protectionInput = input.fileHandleForWriting; protectionOutput = output.fileHandleForReading
1163
+ output.fileHandleForReading.readabilityHandler = { [weak self] handle in
1164
+ let data = handle.availableData
1165
+ Task { @MainActor in
1166
+ guard let self, self.protectionProcess === process else { return }
1167
+ self.protectionBuffer.append(data)
1168
+ if self.protectionBuffer.count > 16384 {
1169
+ self.protectionError = L("保护服务响应无效。", "Invalid protection service response."); process.terminate(); return
1170
+ }
1171
+ while let end = self.protectionBuffer.firstIndex(of: 10) {
1172
+ let line = self.protectionBuffer.prefix(upTo: end)
1173
+ self.protectionBuffer.removeSubrange(...end)
1174
+ do {
1175
+ self.protectionReport = try JSONDecoder().decode(ProtectionReport.self, from: line)
1176
+ if self.protectionReport?.state == "fault" {
1177
+ self.protectionError = AppLanguage.current == .zh ? self.protectionReport?.reason : "Protection failed. Check the allowlist, sandbox and service."
1178
+ } else { self.protectionError = nil }
1179
+ } catch { self.protectionError = L("保护服务响应无效。", "Invalid protection service response."); process.terminate() }
1180
+ self.resizeControls()
1181
+ }
1182
+ }
1183
+ }
1184
+ process.terminationHandler = { [weak self] process in
1185
+ Task { @MainActor in
1186
+ guard let self, self.protectionProcess === process else { return }
1187
+ self.protectionOutput?.readabilityHandler = nil
1188
+ try? self.protectionInput?.close(); try? self.protectionOutput?.close()
1189
+ self.protectionInput = nil; self.protectionOutput = nil; self.protectionProcess = nil
1190
+ self.protectionReport = nil
1191
+ if self.protectionEnabled { self.protectionError = L("保护服务已退出,受保护连接不可用。", "Protection service stopped; protected connections are unavailable.") }
1192
+ self.resizeControls()
1193
+ }
1194
+ }
1195
+ protectionProcess = process
1196
+ do { try process.run(); configureProtection(); protectionHeartbeat = ProcessInfo.processInfo.systemUptime }
1197
+ catch {
1198
+ output.fileHandleForReading.readabilityHandler = nil
1199
+ try? protectionInput?.close(); try? protectionOutput?.close()
1200
+ protectionInput = nil; protectionOutput = nil; protectionProcess = nil
1201
+ protectionError = L("无法启动保护服务。", "Cannot start protection service.")
1202
+ }
1203
+ }
1204
+ @objc func launchClaudeApp() {
1205
+ guard let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: "com.anthropic.claudefordesktop") else {
1206
+ protectionError = L("未找到 Claude App。", "Claude App was not found."); resizeControls(); return
1207
+ }
1208
+ NSWorkspace.shared.openApplication(at: url, configuration: NSWorkspace.OpenConfiguration())
1209
+ }
917
1210
  func currentControlState(now: Double = Date().timeIntervalSince1970) -> ControlState {
918
1211
  if !usageSchedule.allows(now) {
919
1212
  let remaining = recoveryCountdown(usageSchedule.nextAllowedAt, now: now)
920
1213
  return ControlState(mode: "rate_limited", text: L("限流", "Rate limited"), headline: L("请求过于频繁", "Too many requests"),
921
- detail: L("服务限流,\(remaining)后自动重试;手动刷新也会等待。", "Rate limited. Retrying in \(remaining); manual refresh also waits."), quotas: [])
1214
+ detail: L("服务限流,\(remaining)后可手动重试。", "Rate limited. Refresh manually after \(remaining)."), quotas: [])
922
1215
  }
923
1216
  return controlState(snapshot: snapshot, error: error, code: controlErrorCode, weeklySelected: ring.showWeeklyPercentage, now: now)
924
1217
  }
@@ -948,6 +1241,7 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
948
1241
  if controlPopover.contentSize != size { controlPopover.contentSize = size }
949
1242
  }
950
1243
  @objc func openControls() {
1244
+ checkProxyConfiguration()
951
1245
  guard let button = status?.button else { return }
952
1246
  if NSApp.currentEvent?.type == .rightMouseUp {
953
1247
  let menu = makeMenu(); status?.menu = menu; button.performClick(nil); status?.menu = nil
@@ -961,12 +1255,17 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
961
1255
  }
962
1256
  @objc func hide() { panel.orderOut(nil); clockPanel.orderOut(nil) }
963
1257
  @objc func tick() {
1258
+ if protectionProcess?.isRunning == true && ProcessInfo.processInfo.systemUptime - protectionHeartbeat >= 5 {
1259
+ sendProtection(["action": "heartbeat"]); protectionHeartbeat = ProcessInfo.processInfo.systemUptime
1260
+ }
964
1261
  checkVersionIfNeeded()
965
1262
  if Date().timeIntervalSince(ipLastAttempt) >= 300 { refreshIP() }
966
- let now = Date()
967
- let resetDue = snapshot?.windows.contains { $0.resetsAt.map { $0 <= now.timeIntervalSince1970 } ?? false } ?? false
968
- let reminderDue = reminder.map { $0.due <= now.timeIntervalSince1970 } ?? false
969
- if now.timeIntervalSince(lastAttempt) >= (resetDue || reminderDue ? 60 : usageRefreshInterval) { refresh() }
1263
+ if automaticUsageRefresh {
1264
+ let now = Date().timeIntervalSince1970
1265
+ let resetDue = snapshot?.windows.contains { $0.resetsAt.map { $0 <= now } ?? false } ?? false
1266
+ let reminderDue = reminder.map { $0.due <= now } ?? false
1267
+ if Date().timeIntervalSince(lastAttempt) >= (resetDue || reminderDue ? 60 : 300) { refresh() }
1268
+ }
970
1269
  refreshControls()
971
1270
  guard let rect = targetWindow() else { hide(); lastRect = nil; return }
972
1271
  lastRect = rect
@@ -1009,6 +1308,16 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
1009
1308
  ring.setAccessibilityLabel("Claude \(summary)")
1010
1309
  ring.needsDisplay = true
1011
1310
  }
1311
+ @objc func toggleAutomaticUsageRefresh() {
1312
+ automaticUsageRefresh.toggle()
1313
+ UserDefaults.standard.set(automaticUsageRefresh, forKey: "automaticUsageRefresh")
1314
+ if automaticUsageRefresh { refresh() }
1315
+ }
1316
+ @objc func refreshNetworkIPMenu() { refreshNetworkIP() }
1317
+ func refreshNetworkIP() {
1318
+ if protectionEnabled { sendProtection(["action": "verify"]) }
1319
+ else { refreshIP() }
1320
+ }
1012
1321
  @objc func refresh() {
1013
1322
  guard query == nil, usageSchedule.allows(Date().timeIntervalSince1970) else { return }
1014
1323
  lastAttempt = Date()
@@ -1063,7 +1372,9 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
1063
1372
  if followIPTimeZone { refreshIP() }
1064
1373
  }
1065
1374
  @objc func refreshIP() {
1066
- guard ipQuery == nil else { return }
1375
+ let uptime = ProcessInfo.processInfo.systemUptime
1376
+ guard ipQuery == nil, uptime - ipLastProbeUptime >= 60 else { return }
1377
+ ipLastProbeUptime = uptime
1067
1378
  ipLastAttempt = Date()
1068
1379
  let process = Process(), pipe = Pipe()
1069
1380
  process.executableURL = URL(fileURLWithPath: node)
@@ -1082,6 +1393,7 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
1082
1393
  let city = process.terminationStatus == 0 ? value?.city : nil
1083
1394
  Task { @MainActor in
1084
1395
  guard let self else { return }
1396
+ guard self.ipQuery === process else { return }
1085
1397
  self.ipQuery = nil; self.ipText = text
1086
1398
  self.receiveIPTimeZone(timezone, city: city)
1087
1399
  }
@@ -1172,7 +1484,7 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
1172
1484
  menu.addItem(item(lastRect == nil ? L("等待 Claude 前台窗口", "Waiting for Claude foreground window") : L("拖动圆环可调整位置", "Drag the ring to reposition"), nil))
1173
1485
  if let error { menu.addItem(item(error, nil)) }
1174
1486
  if snapshot?.restricted == true { menu.addItem(item(L("服务端提示:当前使用受限", "Server reports restricted usage"), nil)) }
1175
- let address = item(ipText, ipQuery == nil ? #selector(refreshIP) : nil)
1487
+ let address = item(networkIPText, #selector(refreshNetworkIPMenu))
1176
1488
  address.toolTip = L("点击刷新公网IP;城市为网络出口位置", "Click to refresh public IP; city is the network exit location")
1177
1489
  menu.addItem(address)
1178
1490
  menu.addItem(.separator())
@@ -1186,6 +1498,9 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
1186
1498
  menu.addItem(option)
1187
1499
  }
1188
1500
  menu.addItem(item(query == nil ? L("立即刷新", "Refresh now") : L("正在刷新…", "Refreshing…"), query == nil ? #selector(refresh) : nil))
1501
+ let automaticUsage = item(L("额度自动刷新", "Automatic usage refresh"), #selector(toggleAutomaticUsageRefresh))
1502
+ automaticUsage.state = automaticUsageRefresh ? .on : .off
1503
+ menu.addItem(automaticUsage)
1189
1504
  let alarm = item(L("额度可用提醒", "Usage available alert"), reminderAuthorizing ? nil : #selector(toggleReminder))
1190
1505
  alarm.state = reminder == nil ? .off : .on
1191
1506
  menu.addItem(alarm)
@@ -1198,7 +1513,7 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
1198
1513
  let toggle = item(L("显示时间", "Show time"), #selector(toggleClock))
1199
1514
  toggle.state = clockEnabled ? .on : .off
1200
1515
  menu.addItem(toggle)
1201
- let follow = item(L("跟随IP时区", "Follow IP time zone"), #selector(toggleFollowIPTimeZone))
1516
+ let follow = item(L("跟随IP时区:ipinfo.io", "Follow IP time zone: ipinfo.io"), #selector(toggleFollowIPTimeZone))
1202
1517
  follow.state = followIPTimeZone ? .on : .off
1203
1518
  menu.addItem(follow)
1204
1519
  if followIPTimeZone && ipClock.zone == nil {
@@ -1442,6 +1757,9 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
1442
1757
  }
1443
1758
  @objc func quit() { NSApp.terminate(nil) }
1444
1759
  func applicationWillTerminate(_ notification: Notification) {
1760
+ protectionEditTimer?.invalidate(); protectionPathMonitor.cancel()
1761
+ protectionOutput?.readabilityHandler = nil
1762
+ try? protectionInput?.close()
1445
1763
  ipQuery?.terminate()
1446
1764
  timer?.invalidate()
1447
1765
  query?.terminate()
@@ -1473,7 +1791,7 @@ func runControlChecks() {
1473
1791
  func state(_ snapshot: Snapshot?, error: String? = nil, code: String? = nil, weekly: Bool = false) -> ControlState {
1474
1792
  controlState(snapshot: snapshot, error: error, code: code, weeklySelected: weekly, now: now)
1475
1793
  }
1476
- precondition(state(nil).mode == "loading")
1794
+ precondition(state(nil).mode == "unknown")
1477
1795
  precondition(state(sample()).text == "94%")
1478
1796
  precondition(state(sample(), weekly: true).text == "77%")
1479
1797
  var onlyWeek = sample(); onlyWeek.windows = controlQuotas(onlyWeek.windows).filter { $0.weekly }.map { $0.window }
@@ -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>1.0.3</string>
8
+ <key>CFBundleShortVersionString</key><string>1.2.0</string>
9
9
  <key>LSMinimumSystemVersion</key><string>14.0</string>
10
10
  <key>CFBundleLocalizations</key><array><string>en</string><string>zh-Hans</string><string>zh-Hant</string></array>
11
11
  <key>LSUIElement</key><true/>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "easy-claude",
3
- "version": "1.0.3",
3
+ "version": "1.2.0",
4
4
  "description": "Claude Code quota rings and transparent world clock for Claude desktop",
5
5
  "type": "module",
6
6
  "bin": {
@@ -28,6 +28,8 @@
28
28
  "test:reminder": "python3 scripts/test-native-reminder.py",
29
29
  "test:controls": "python3 scripts/test-controls.py",
30
30
  "test:refresh": "python3 scripts/test-refresh.py",
31
+ "test:protection": "node --test --test-timeout=15000 scripts/ip-guard-proof/verify.mjs scripts/ip-guard-proof/service-check.mjs",
32
+ "test:protection-ui": "python3 scripts/test-protection-ui.py",
31
33
  "test:focus": "python3 scripts/test-focus.py",
32
34
  "test:polling": "python3 scripts/test-polling.py"
33
35
  },