From 764eb201089c70f11896febd25eb8b0df75431bc Mon Sep 17 00:00:00 2001 From: Hussein Faez <257576459+H0777@users.noreply.github.com> Date: Mon, 2 Nov 2026 16:51:34 +0300 Subject: [PATCH 1/7] Keep AI usage current with incremental scans and automatic account refresh --- CHANGELOG.md | 17 +++ Checks/RunChecks.swift | 189 ++++++++++++++++++++++++- FEATURES.md | 8 ++ PERFORMANCE.md | 11 ++ README.ar.md | 10 +- README.md | 6 + Sources/Notchest/CodexLiveReader.swift | 15 +- Sources/Notchest/DeveloperModel.swift | 181 +++++++++++++++++++---- Sources/Notchest/DeveloperView.swift | 63 ++++++--- Sources/Notchest/IslandView.swift | 10 +- Sources/Notchest/UsageReader.swift | 159 +++++++++++++++------ 11 files changed, 568 insertions(+), 101 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 234cb15..6e59143 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,23 @@ All notable changes to Notchest are documented here. The format follows ## [Unreleased] +### Fixed + +- Refresh local AI usage every five seconds in common run-loop modes, on + returning to the usage view, and after wake. Cancel outdated provider/folder + reads so their results cannot overwrite the current selection. +- Add opt-in automatic Codex account-limit refresh every minute, independently + of local tracking. Retry failed connections with bounded backoff and keep + the last successful snapshot visibly marked as stale. +- Read appended JSONL records incrementally, retry unfinished records, and + rebuild the baseline after log truncation, replacement, or a day change. + Keep cached numeric data during transient read failures; bound individual + records to 8 MiB and disclose skipped data as a partial scan. +- Show the last local scan and recorded activity separately from the account + fetch time. Keep connection errors in the current interface language. +- Update the compact island from fresh live limits and hide expired or stale + percentages instead of continuing to show an old local snapshot. + ### Documentation - Add prominent bilingual first-launch guidance beside download links, in the diff --git a/Checks/RunChecks.swift b/Checks/RunChecks.swift index cd5ee6e..14383a6 100644 --- a/Checks/RunChecks.swift +++ b/Checks/RunChecks.swift @@ -1,8 +1,41 @@ import Foundation +private final class UsageCheckService: @unchecked Sendable { + private let lock = NSLock() + private var scans = 0 + private var lives = 0 + private var scanFailure = false + private var liveFailure = false + var scanCount: Int { lock.withLock { scans } } + var liveCount: Int { lock.withLock { lives } } + var failScan: Bool { + get { lock.withLock { scanFailure } } + set { lock.withLock { scanFailure = newValue } } + } + var failLive: Bool { + get { lock.withLock { liveFailure } } + set { lock.withLock { liveFailure = newValue } } + } + func scan(_ provider: AIProvider, directory: URL) -> UsageSnapshot { + let (number, failure) = lock.withLock { scans += 1; return (scans, scanFailure) } + // Keep the first result in flight while the test switches providers. + if number == 1 { Thread.sleep(forTimeInterval: 0.15) } + var snapshot = UsageSnapshot() + if failure { snapshot.unreadableFiles = 1; return snapshot } + snapshot.fileCount = 1; snapshot.scannedAt = Date() + snapshot.today.input = directory.path == "/fixture-new" ? 333 : provider == .codex ? 111 : 222 + return snapshot + } + func live() throws -> CodexLiveSnapshot { + let failure = lock.withLock { lives += 1; return liveFailure } + if failure { throw CodexLiveError.timeout } + return CodexLiveSnapshot(primary: UsageWindow(usedPercent: 25, minutes: 300, resetsAt: nil), secondary: nil, lifetimeTokens: nil, fetchedAt: Date()) + } +} + @main struct RunChecks { - @MainActor static func main() throws { + @MainActor static func main() async throws { var count = 0 func check(_ name: String, _ body: () throws -> Void) rethrows { try body() @@ -13,6 +46,13 @@ struct RunChecks { let value = try condition() precondition(value) } + func waitFor(_ condition: @MainActor () -> Bool) async throws { + let deadline = Date().addingTimeInterval(3) + while !condition() { + guard Date() < deadline else { throw CocoaError(.executableRuntimeMismatch) } + try await Task.sleep(nanoseconds: 10_000_000) + } + } let start = Date(timeIntervalSince1970: 1_000) check("Timer uses elapsed wall time, including missed ticks") { var clock = FocusClock() @@ -122,6 +162,153 @@ struct RunChecks { precondition(snapshot.today == TokenTally(input: 11, cached: 10, output: 5)) precondition(snapshot.eventCount == 1 && snapshot.primary == nil) } + try check("Growing logs read only appended bytes and retry an incomplete final record") { + let root = FileManager.default.temporaryDirectory.appendingPathComponent("notchest-append-\(UUID())") + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + let file = root.appendingPathComponent("active.jsonl") + let now = Date() + func row(_ tokens: Int) throws -> Data { + try JSONSerialization.data(withJSONObject: ["timestamp": ISO8601DateFormatter().string(from: now), "type": "event_msg", "payload": ["type": "token_count", "info": ["total_token_usage": ["input_tokens": tokens, "output_tokens": 10]]]]) + } + try (Data((String(repeating: " ", count: 10_000) + "\n").utf8) + row(100) + Data([10])).write(to: file) + let first = UsageReader.scan(provider: .codex, directory: root, now: now) + precondition(first.today.total == 110 && first.bytesRead > 10_000) + precondition(UsageReader.scan(provider: .codex, directory: root, now: now).bytesRead == 0) + let next = try row(180) + let split = next.count / 2 + let writer = try FileHandle(forWritingTo: file) + defer { try? writer.close() } + try writer.seekToEnd() + try writer.write(contentsOf: next.prefix(split)) + let partial = UsageReader.scan(provider: .codex, directory: root, now: now) + precondition(partial.today.total == 110 && partial.bytesRead == split) + try writer.write(contentsOf: next.suffix(from: split) + Data([10])) + let complete = UsageReader.scan(provider: .codex, directory: root, now: now) + precondition(complete.today.total == 190 && complete.eventCount == 2) + precondition(complete.bytesRead == next.count + 1 && complete.lastEventAt != nil) + } + try check("Truncated and atomically replaced logs rebuild their token baseline") { + let root = FileManager.default.temporaryDirectory.appendingPathComponent("notchest-replace-\(UUID())") + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + let file = root.appendingPathComponent("active.jsonl") + let now = Date() + func data(_ input: Int) throws -> Data { + try JSONSerialization.data(withJSONObject: ["timestamp": ISO8601DateFormatter().string(from: now), "type": "assistant", "message": ["id": "message", "usage": ["input_tokens": input]]]) + } + try data(9999).write(to: file) + precondition(UsageReader.scan(provider: .claude, directory: root, now: now).today.total == 9999) + let handle = try FileHandle(forWritingTo: file) + try handle.truncate(atOffset: 0); try handle.write(contentsOf: data(1)); try handle.close() + precondition(UsageReader.scan(provider: .claude, directory: root, now: now).today.total == 1) + try data(22222).write(to: file, options: .atomic) + precondition(UsageReader.scan(provider: .claude, directory: root, now: now).today.total == 22222) + let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: now)! + let rolled = UsageReader.scan(provider: .claude, directory: root, now: tomorrow) + precondition(rolled.today.total == 0 && rolled.week.total == 22222) + } + try check("Oversized transcript records stay bounded and do not hide later usage") { + let root = FileManager.default.temporaryDirectory.appendingPathComponent("notchest-large-\(UUID())") + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + let file = root.appendingPathComponent("large.jsonl") + let now = Date() + try Data(repeating: 32, count: 8 * 1024 * 1024 + 1).write(to: file) + let initial = UsageReader.scan(provider: .claude, directory: root, now: now) + precondition(initial.partial && initial.today.total == 0) + let writer = try FileHandle(forWritingTo: file) + try writer.seekToEnd() + let record = try JSONSerialization.data(withJSONObject: ["timestamp": ISO8601DateFormatter().string(from: now), "type": "assistant", "message": ["id": "message", "usage": ["input_tokens": 12]]]) + try writer.write(contentsOf: Data([10]) + record + Data([10])); try writer.close() + let recovered = UsageReader.scan(provider: .claude, directory: root, now: now) + precondition(recovered.partial && recovered.today.total == 12 && recovered.bytesRead == record.count + 2) + } + check("Live refresh retries back off and success restores the one-minute cadence") { + var schedule = UsageRefreshSchedule() + let now = Date() + for delay in [30.0, 60, 120, 240, 300, 300] { + schedule.failed(at: now) + precondition(schedule.nextAttempt.timeIntervalSince(now) == delay) + } + schedule.succeeded(at: now) + precondition(schedule.failures == 0 && schedule.nextAttempt.timeIntervalSince(now) == 60) + } + check("The compact island uses fresh live limits and hides expired or stale percentages") { + let suite = "dev.notchest.compact-usage.\(UUID())" + let defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite) } + defaults.set(true, forKey: "aiLiveAutoRefresh") + let model = DeveloperModel(defaults: defaults) + let now = Date() + model.usage.primary = UsageWindow(usedPercent: 90, minutes: 300, resetsAt: now.addingTimeInterval(500)) + model.usage.observedAt = now + model.liveCodex = CodexLiveSnapshot(primary: UsageWindow(usedPercent: 25, minutes: 300, resetsAt: now.addingTimeInterval(500)), secondary: nil, lifetimeTokens: nil, fetchedAt: now) + precondition(model.compactUsageWindow(at: now)?.usedPercent == 25) + precondition(model.compactUsageWindow(at: now.addingTimeInterval(121)) == nil) + model.liveAutoRefreshEnabled = false + precondition(model.compactUsageWindow(at: now)?.usedPercent == 90) + precondition(model.compactUsageWindow(at: now.addingTimeInterval(501)) == nil) + model.stop() + } + do { + let suite = "dev.notchest.usage-race.\(UUID())" + let defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite) } + let service = UsageCheckService() + let model = DeveloperModel(defaults: defaults, scanUsage: { service.scan($0, directory: $1) }, fetchLive: { try service.live() }) + defer { model.stop() } + model.refreshUsage() + try await waitFor { service.scanCount > 0 } + model.changeProvider(.claude) + try await waitFor { !model.refreshing } + precondition(model.usage.today.total == 222) + try await Task.sleep(nanoseconds: 200_000_000) + precondition(model.usage.today.total == 222) + model.setUsageDirectory(URL(fileURLWithPath: "/fixture-new")) + try await waitFor { !model.refreshing } + precondition(model.usage.today.total == 333) + model.refreshUsage(); model.trackingEnabled = false; model.trackingEnabled = true + try await waitFor { !model.refreshing } + precondition(model.usage.today.total == 333) + service.failScan = true + model.refreshUsage() + try await waitFor { !model.refreshing } + precondition(model.usage.today.total == 333 && model.localReadFailed) + model.changeProvider(.codex) + model.trackingEnabled = false + precondition(service.liveCount == 0 && !model.liveAutoRefreshEnabled) + model.liveAutoRefreshEnabled = true + try await waitFor { !model.liveCodexLoading } + precondition(model.liveCodex?.primary?.usedPercent == 25 && service.liveCount == 1) + model.refreshAutomatically() + precondition(!model.liveCodexLoading && service.liveCount == 1) + service.failLive = true + model.refreshAutomatically(at: Date().addingTimeInterval(61)) + try await waitFor { !model.liveCodexLoading } + precondition(model.liveCodex?.primary?.usedPercent == 25 && model.liveCodexError != nil) + service.failLive = false + model.refreshAllUsage() + try await waitFor { !model.liveCodexLoading } + precondition(model.liveCodexError == nil) + model.liveAutoRefreshEnabled = false + let liveCount = service.liveCount + model.refreshAutomatically(at: .distantFuture) + precondition(service.liveCount == liveCount) + count += 1; print("PASS: Provider/folder changes reject stale scans; live refresh is opt-in, scheduled, recoverable and independent") + let pending = DeveloperModel(defaults: defaults, scanUsage: { _, _ in UsageSnapshot() }, fetchLive: { + Thread.sleep(forTimeInterval: 0.15) + return try service.live() + }) + pending.refreshLiveCodex() + pending.stop() + try await Task.sleep(nanoseconds: 200_000_000) + precondition(!pending.liveCodexLoading && pending.liveCodex == nil) + let restored = DeveloperModel(defaults: defaults) + precondition(!restored.liveAutoRefreshEnabled && !restored.trackingEnabled) + restored.stop() + count += 1; print("PASS: Stopping rejects in-flight live results and tracking preferences survive relaunch") + } check("Missing limits stay unknown rather than reporting zero") { precondition(UsageReader.parseWindow(NSNull()) == nil) precondition(UsageReader.parseWindow(["window_minutes": 300]) == nil) diff --git a/FEATURES.md b/FEATURES.md index 6ca689b..d2b0cbd 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -4,6 +4,14 @@ هذا السجل يميز بين المزايا الموجودة والمزايا التي تتطلب إعدادًا أو ما تزال قيد التطوير. لا تعني إضافة واجهة لتكامل أن جميع الأجهزة والخدمات قد اختُبرت. +## تطوير غير منشور بعد 0.6.0 — AI Usage + +- قراءة محلية كل 5 ثوانٍ، مع مؤقّت يستمر أثناء التفاعل وتحديث بعد الاستيقاظ والعودة للقسم. +- تحديث اختياري لحدود حساب Codex كل دقيقة، مستقل عن القراءة المحلية. تُحفظ التفضيلات وتُعرض حالة الاتصال ووقت آخر نجاح، مع إعادة المحاولة المتدرجة وإبقاء آخر بيانات متاحة عند الفشل. +- قراءة تزايدية للملفات، وإكمال السجلات التي كانت قيد الكتابة، وإبطال نتائج الطلبات القديمة عند تغيير المزوّد أو المجلّد أو إيقاف القراءة. +- إعادة بناء الحساب عند تبديل الملف أو اقتطاعه أو تغيّر اليوم. حد السطر 8 ميجابايت مع تنبيه القراءة الجزئية؛ لا يُخزّن نص المحادثة في الذاكرة المؤقتة. +- نجح الاتصال الفعلي لحدود Codex وقراءة السجلات المحلية؛ لا توجد سجلات Claude على جهاز التحقق، لذا تحقّقنا من صيغته وتحديث سجلاته ببيانات اختبار معزولة. نجحت 45 عملية فحص، وبناء نسخة الإنتاج، وفحص الواجهة باللغتين واستمرار التحديث التلقائي في النافذة. + ## تحديث 0.6 - هوية Aurora Orbit وأيقونة نابضة متعددة الأحجام، مع توحيد الشعار وأيقونة الموقع والغلاف. diff --git a/PERFORMANCE.md b/PERFORMANCE.md index 3395663..9331623 100644 --- a/PERFORMANCE.md +++ b/PERFORMANCE.md @@ -33,3 +33,14 @@ Notes: - Timers keep running while the island is collapsed. If a future release pauses non-essential work when collapsed, idle CPU should drop below this baseline — record the improvement here. + +## Unreleased AI usage reader — 2026-11-02 + +Local polling now runs every five seconds; the 0.6.0 idle baseline above is +historical and must not be taken as a measurement of this build. An actual +Codex log scan read about 423 MiB in 13.4 seconds on its initial pass; an +immediate incremental pass read about 64 KiB in 0.0024 seconds while logs were +still growing. These are reader timings, not whole-app CPU or memory figures. +Some records/files exceeded the reader limits and were disclosed as partial. +Live Codex account limits fetched successfully. No Claude logs were present on +the test machine; automated fixtures cover its parsing and growing records. diff --git a/README.ar.md b/README.ar.md index 242fc41..fde686c 100644 --- a/README.ar.md +++ b/README.ar.md @@ -43,12 +43,14 @@ ## أدوات المطوّر والذكاء الاصطناعي +تطوير غير منشور بعد 0.6.0: فعّل **Auto-refresh every minute** في قسم AI usage لتحديث حدود Codex باستمرار. القراءة المحلية مستقلة وتعمل كل 5 ثوانٍ؛ قد تتأخر الأرقام حتى يكتب المزوّد حدث الاستهلاك في سجلاته. + | الأداة | ما تفعله | | --- | --- | | استهلاك Codex | يقرأ أحداث الاستهلاك من السجلّات المحلية: رموز اليوم وآخر سبعة أيام، رموز الخرج، وإعادة استخدام الكاش | | حدود Codex | يعرض أحدث لقطة متاحة للنوافذ ونسبة الحد المتبقية وموعد التجديد، مع وقت اللقطة والتنبيه إذا تقادمت | | استهلاك Claude Code | يقرأ أرقام الاستخدام من سجلّاته المحلية عند وجودها؛ لا يفترض وجود حدود حساب غير مذكورة فيها | -| رسم النشاط | أعمدة لأيام الأسبوع من السجلّات المقروءة، مع تحديث كل 30 ثانية وتخزين نتائج الملفات التي لم تتغيّر لتقليل العمل | +| رسم النشاط | أعمدة لأيام الأسبوع من السجلّات المقروءة، مع تحديث كل 5 ثوانٍ وقراءة الإضافات الجديدة فقط من الملفات التي تنمو | | اختيار المصدر | تبديل المزوّد واختيار مجلّد مخصّص، وإيقاف القراءة المحلية بمفتاح داخل اللوحة | | JSON | التحقق من الصيغة، التنسيق وترتيب المفاتيح، أو التصغير | | تحويل النصوص | Base64 ذهابًا وإيابًا، وترميز الروابط وفكّه | @@ -57,7 +59,7 @@ | تشغيل الأوامر | تشغيل أمر zsh غير تفاعلي داخل مجلّد تختاره، وعرض الخرج ورمز الخروج والتنبيه عند الاكتمال؛ زر لإرسال الإيقاف لمجموعة العملية | | Terminal | طرفية تفاعلية مدمجة تبدأ عند الضغط على زر التشغيل، مع إمكان فتح تطبيق Terminal الخارجي | | GitHub PR | عرض طلبات سحب المستودع المختار باستخدام GitHub CLI بعد تسجيل الدخول | -| حدود Codex الحية | استعلام اختياري عبر Codex CLI، ويُعرض وقت جلب البيانات | +| حدود Codex الحية | تحديث تلقائي اختياري كل دقيقة عبر Codex CLI، مع وقت آخر اتصال وإعادة المحاولة عند الفشل | | النشاط | واجهة محلية اختيارية للسكربتات ومراقبة التنزيلات والأقراص القابلة للإزالة | | Git | قراءة الفرع وحالة الملفات وملخص الفرق وآخر خمسة التزامات، دون تعديل المستودع | | المقتطفات | حفظ مقاطع نصية وكود ونسخها بنقرة | @@ -66,7 +68,7 @@ اللقطة القديمة لحدود الحساب لا تتحوّل تلقائيًا إلى رصيد جديد. عند توقف الأداة عن كتابة سجلّاتها قد تبقى لقطة الحدود قديمة. صيغة سجلّات الطرف الثالث قابلة للتغيّر، ولذلك هذا التكامل يحتاج صيانة مع تحديثاتها. -المسار الافتراضي لـ Codex هو `CODEX_HOME/sessions` عندما يكون المتغيّر متاحًا للتطبيق، وإلا `~/.codex/sessions`. مسار Claude Code هو `~/.claude/projects`. قارئ السجلات لا يقرأ ملفات كلمات المرور أو مفاتيح API، ولا يحفظ أو يعرض نصوص المحادثات. مفتاح الأسهم الذي تدخله يُحفظ في سلسلة مفاتيح macOS. حدود القراءة: أحدث 1500 ملف، وبحد قراءة يقارب 1 جيجابايت في الدورة؛ عند تجاوز الحدود أو تعذّر القراءة تظهر عبارة «قراءة جزئية». +المسار الافتراضي لـ Codex هو `CODEX_HOME/sessions` عندما يكون المتغيّر متاحًا للتطبيق، وإلا `~/.codex/sessions`. مسار Claude Code هو `~/.claude/projects`. قارئ السجلات لا يقرأ ملفات كلمات المرور أو مفاتيح API، ولا يحفظ أو يعرض نصوص المحادثات. مفتاح الأسهم الذي تدخله يُحفظ في سلسلة مفاتيح macOS. حدود القراءة: أحدث 1500 ملف، وبحد قراءة يقارب 1 جيجابايت في الدورة، و8 ميجابايت للسجل الواحد داخل الملف؛ عند تجاوز الحدود أو تعذّر القراءة تظهر عبارة «قراءة جزئية». مرجع معنى حقول حدود Codex: [توثيق OpenAI الرسمي](https://learn.chatgpt.com/docs/app-server). @@ -107,7 +109,7 @@ الكاميرا والتقويم والتذكيرات والتحكم بتطبيق الموسيقى وتنظيم النوافذ تُستخدم عند اختيار أدواتها. قد يعرض macOS طلب الإذن المناسب. تصوير الشاشة يخضع لصلاحيات macOS. بعض أجهزة الصوت لا تتيح التحكم البرمجي بالصوت أو الكتم؛ الواجهة تبين عدم التوفر. -تحويلات الكود والملاحظات والملفات تُعالج محليًا. قراءة حدود Codex الحية تتصل بحساب Codex عند طلبها؛ الطقس يرسل المدينة إلى Open-Meteo، والكلمات ترسل اسم الأغنية والفنان إلى LRCLIB عند طلبها، والأسهم تتصل بـ Alpha Vantage عند التحديث. البحث والترجمة يفتحان خدمة خارجية عند ضغط زرهما؛ وقد تتصل تطبيقات الموسيقى أو الاختصارات بخدماتها وفق إعداداتها. Notchest لا يضمّن مفاتيح حسابات أو خدمات مدفوعة. +تحويلات الكود والملاحظات والملفات تُعالج محليًا. قراءة حدود Codex الحية تتصل بحساب Codex كل دقيقة بعد تفعيل التحديث التلقائي، مع تقليل تكرار المحاولات عند فشل الاتصال؛ الطقس يرسل المدينة إلى Open-Meteo، والكلمات ترسل اسم الأغنية والفنان إلى LRCLIB عند طلبها، والأسهم تتصل بـ Alpha Vantage عند التحديث. البحث والترجمة يفتحان خدمة خارجية عند ضغط زرهما؛ وقد تتصل تطبيقات الموسيقى أو الاختصارات بخدماتها وفق إعداداتها. Notchest لا يضمّن مفاتيح حسابات أو خدمات مدفوعة. ## حالة النسخة diff --git a/README.md b/README.md index 72b616e..8efacc1 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,12 @@ account usage, system readings, notes, music, and task events are illustrative.* | Mac utilities | Current weather, Apple Translation, stock watchlist, music and lyrics, system readings, supported audio controls, window tiling, image conversion, capture, OCR, ZIP, calculator, Shortcuts, camera mirror, calendar and reminders | | Yours | Display selection, island dimensions, accent colors, motion, English or right-to-left Arabic, launch at login | +**Unreleased AI usage improvements:** local logs refresh every five seconds. Enable +**Auto-refresh every minute** in AI usage for recurring Codex account limits. +Failed requests retry automatically and retain the last successful data. Local +statistics update only after the provider writes usage records. These changes +are in development and are not in the published 0.6.0 download. + Connected features have setup requirements. The [feature guide](https://h0777.github.io/Notchest/guide.html) and [status tracker](FEATURES.md) distinguish what is implemented, what needs permission, and what remains on the roadmap. diff --git a/Sources/Notchest/CodexLiveReader.swift b/Sources/Notchest/CodexLiveReader.swift index 36750c8..9e8a090 100644 --- a/Sources/Notchest/CodexLiveReader.swift +++ b/Sources/Notchest/CodexLiveReader.swift @@ -15,8 +15,8 @@ enum CodexLiveError: Error { var text: ServiceText { switch self { - case .missing: return ServiceText("تعذّر العثور على Codex CLI", "Codex CLI not found") - case .failed: return ServiceText("حساب Codex غير متاح", "Codex account is unavailable") + case .missing: return ServiceText("ثبّت Codex CLI ثم سجّل الدخول إليه لعرض حدود الحساب", "Install Codex CLI and sign in to view account limits") + case .failed: return ServiceText("تعذّر تحديث Codex؛ تحقّق من تسجيل الدخول واتصال الإنترنت", "Could not refresh Codex. Check your sign-in and internet connection") case .timeout: return ServiceText("انتهت مهلة اتصال Codex", "Codex did not respond in time") case .invalid: return ServiceText("لم يُرجع Codex حدود الاستخدام", "Codex returned no usage limits") } @@ -53,6 +53,7 @@ enum CodexLiveReader { } static func fetch() throws -> CodexLiveSnapshot { + try Task.checkCancellation() guard let executable = executable() else { throw CodexLiveError.missing } let process = Process() let input = Pipe(), output = Pipe() @@ -62,7 +63,14 @@ enum CodexLiveReader { do { try process.run() } catch { throw CodexLiveError.failed } defer { try? input.fileHandleForWriting.close() - if process.isRunning { process.terminate() } + if process.isRunning { + process.terminate() + // A stopped reader must not leave an app-server child alive forever. + let processToStop = process + DispatchQueue.global().asyncAfter(deadline: .now() + 1) { + if processToStop.isRunning { kill(processToStop.processIdentifier, SIGKILL) } + } + } try? output.fileHandleForReading.close() } let fd = output.fileHandleForReading.fileDescriptor @@ -76,6 +84,7 @@ enum CodexLiveReader { func readUntil(ids: Set) throws -> [Int: [String: Any]] { var results: [Int: [String: Any]] = [:] while !ids.isSubset(of: Set(results.keys)) { + try Task.checkCancellation() while let newline = buffer.firstIndex(of: 10) { let line = Data(buffer[.. Void)? @@ -47,9 +64,21 @@ final class DeveloperModel: ObservableObject { @Published var refreshing = false @Published var liveCodex: CodexLiveSnapshot? @Published var liveCodexLoading = false - @Published var liveCodexError: String? - @Published var trackingEnabled = UserDefaults.standard.object(forKey: "aiTracking") as? Bool ?? true { - didSet { UserDefaults.standard.set(trackingEnabled, forKey: "aiTracking"); if trackingEnabled { refreshUsage() } else { usage = UsageSnapshot() } } + @Published private var liveError: ServiceText? + var liveCodexError: String? { liveError?.resolved(arabicUI: arabicUI) } + @Published var localReadFailed = false + @Published var liveAutoRefreshEnabled: Bool { + didSet { + defaults.set(liveAutoRefreshEnabled, forKey: "aiLiveAutoRefresh") + if liveAutoRefreshEnabled { refreshLiveCodex() } else { cancelLiveRefresh() } + } + } + @Published var trackingEnabled: Bool { + didSet { + defaults.set(trackingEnabled, forKey: "aiTracking") + if trackingEnabled { refreshUsage() } + else { cancelUsageRefresh(); usage = UsageSnapshot(); localReadFailed = false } + } } @Published var workbenchInput = "" @Published var workbenchOutput = "" @@ -73,29 +102,111 @@ final class DeveloperModel: ObservableObject { private var timer: Timer? private var usageTask: Task? private var usageGeneration = UUID() + private var liveTask: Task? + private var liveGeneration = UUID() + private var liveSchedule = UsageRefreshSchedule() + private var wakeObserver: NSObjectProtocol? + private var activeObserver: NSObjectProtocol? + private let defaults: UserDefaults + private let scanUsage: @Sendable (AIProvider, URL) -> UsageSnapshot + private let fetchLive: @Sendable () throws -> CodexLiveSnapshot - init() { - snippets = UserDefaults.standard.data(forKey: "snippets").flatMap { try? JSONDecoder().decode([Snippet].self, from: $0) } ?? [] + init(defaults: UserDefaults = .standard, + scanUsage: @escaping @Sendable (AIProvider, URL) -> UsageSnapshot = { UsageReader.scan(provider: $0, directory: $1) }, + fetchLive: @escaping @Sendable () throws -> CodexLiveSnapshot = { try CodexLiveReader.fetch() }) { + self.defaults = defaults + self.scanUsage = scanUsage + self.fetchLive = fetchLive + trackingEnabled = defaults.object(forKey: "aiTracking") as? Bool ?? true + liveAutoRefreshEnabled = defaults.bool(forKey: "aiLiveAutoRefresh") + snippets = defaults.data(forKey: "snippets").flatMap { try? JSONDecoder().decode([Snippet].self, from: $0) } ?? [] } var usageDirectory: URL { - if let path = UserDefaults.standard.string(forKey: "usageDirectory.\(provider.rawValue)") { return URL(fileURLWithPath: path) } + if let path = defaults.string(forKey: "usageDirectory.\(provider.rawValue)") { return URL(fileURLWithPath: path) } return provider.defaultDirectory } + func compactUsageWindow(at date: Date) -> UsageWindow? { + guard provider == .codex else { return nil } + let window: UsageWindow? + if liveAutoRefreshEnabled { + guard liveCodexError == nil, let liveCodex, date.timeIntervalSince(liveCodex.fetchedAt) <= 120 else { return nil } + window = liveCodex.primary + } else { + guard trackingEnabled, !localReadFailed, let observed = usage.observedAt, date.timeIntervalSince(observed) <= 120 else { return nil } + window = usage.primary + } + guard let window, (window.resetsAt ?? .distantFuture) > date else { return nil } + return window + } + func start() { - refreshUsage() - timer = Timer.scheduledTimer(withTimeInterval: 30, repeats: true) { [weak self] _ in - Task { @MainActor in self?.refreshUsage() } + guard timer == nil else { return } + refreshAutomatically() + let timer = Timer(timeInterval: UsageRefreshSchedule.localInterval, repeats: true) { [weak self] _ in + Task { @MainActor in + guard let self, self.timer != nil else { return } + self.refreshAutomatically() + } + } + timer.tolerance = 1 + RunLoop.main.add(timer, forMode: .common) + self.timer = timer + wakeObserver = NSWorkspace.shared.notificationCenter.addObserver(forName: NSWorkspace.didWakeNotification, object: nil, queue: .main) { [weak self] _ in + Task { @MainActor in + guard let self, self.timer != nil else { return } + self.resumeUsageUpdates() + } + } + activeObserver = NotificationCenter.default.addObserver(forName: NSApplication.didBecomeActiveNotification, object: nil, queue: .main) { [weak self] _ in + Task { @MainActor in + guard let self, self.timer != nil else { return } + self.refreshAutomatically() + } } } func stop() { timer?.invalidate() - usageTask?.cancel() + timer = nil + if let wakeObserver { NSWorkspace.shared.notificationCenter.removeObserver(wakeObserver) } + if let activeObserver { NotificationCenter.default.removeObserver(activeObserver) } + wakeObserver = nil; activeObserver = nil + cancelUsageRefresh() + cancelLiveRefresh() cancelCommand() } + func refreshAutomatically(at date: Date = Date()) { + refreshUsage() + if liveAutoRefreshEnabled, provider == .codex, date >= liveSchedule.nextAttempt { refreshLiveCodex() } + } + + func resumeUsageUpdates() { + // A request begun before sleep may have a dead pipe or stale filesystem view. + cancelUsageRefresh() + cancelLiveRefresh() + refreshAutomatically() + } + + func refreshAllUsage() { + refreshUsage() + if liveAutoRefreshEnabled { refreshLiveCodex() } + } + + private func cancelUsageRefresh() { + usageGeneration = UUID() + usageTask?.cancel(); usageTask = nil + refreshing = false + } + + private func cancelLiveRefresh() { + liveGeneration = UUID() + liveTask?.cancel(); liveTask = nil + liveCodexLoading = false + } + func refreshUsage() { guard trackingEnabled, !refreshing else { return } refreshing = true @@ -103,34 +214,48 @@ final class DeveloperModel: ObservableObject { usageGeneration = generation let provider = provider let directory = usageDirectory + let scan = scanUsage usageTask = Task { [weak self] in - let snapshot = await Task.detached(priority: .utility) { UsageReader.scan(provider: provider, directory: directory) }.value + let worker = Task.detached(priority: .utility) { scan(provider, directory) } + let snapshot = await withTaskCancellationHandler(operation: { await worker.value }, onCancel: { worker.cancel() }) guard let self else { return } guard self.usageGeneration == generation else { return } defer { self.refreshing = false } - guard !Task.isCancelled, self.provider == provider, self.trackingEnabled else { return } + guard !Task.isCancelled, self.provider == provider, self.usageDirectory == directory, self.trackingEnabled else { return } + self.localReadFailed = snapshot.missingDirectory || snapshot.unreadableFiles > 0 || (snapshot.partial && snapshot.fileCount == 0) + if self.localReadFailed, snapshot.fileCount == 0, self.usage.fileCount > 0 { return } self.usage = snapshot } } func changeProvider(_ provider: AIProvider) { - usageTask?.cancel() - refreshing = false + guard provider != self.provider else { refreshAllUsage(); return } + cancelUsageRefresh() + cancelLiveRefresh() self.provider = provider usage = UsageSnapshot() - refreshUsage() + localReadFailed = false + refreshAutomatically() } func refreshLiveCodex() { - guard !liveCodexLoading else { return } - liveCodexLoading = true; liveCodexError = nil - Task { [weak self] in - let result = await Task.detached(priority: .utility) { Result { try CodexLiveReader.fetch() } }.value - guard let self else { return } + guard provider == .codex, !liveCodexLoading else { return } + liveCodexLoading = true + let generation = UUID() + liveGeneration = generation + let fetch = fetchLive + liveTask = Task { [weak self] in + let worker = Task.detached(priority: .utility) { Result { try fetch() } } + let result = await withTaskCancellationHandler(operation: { await worker.value }, onCancel: { worker.cancel() }) + guard let self, !Task.isCancelled, self.liveGeneration == generation else { return } self.liveCodexLoading = false switch result { - case .success(let snapshot): self.liveCodex = snapshot - case .failure(let error): self.liveCodexError = (error as? CodexLiveError)?.message(arabicUI: self.arabicUI) ?? error.localizedDescription + case .success(let snapshot): + self.liveCodex = snapshot; self.liveError = nil + self.liveSchedule.succeeded(at: Date()) + case .failure(let error): + self.liveError = (error as? CodexLiveError)?.text ?? CodexLiveError.failed.text + self.liveSchedule.failed(at: Date()) } } } @@ -142,11 +267,17 @@ final class DeveloperModel: ObservableObject { panel.canChooseFiles = false panel.directoryURL = usageDirectory if panel.runModal() == .OK, let url = panel.url { - UserDefaults.standard.set(url.path, forKey: "usageDirectory.\(provider.rawValue)") - refreshUsage() + setUsageDirectory(url) } } + func setUsageDirectory(_ url: URL) { + cancelUsageRefresh() + defaults.set(url.path, forKey: "usageDirectory.\(provider.rawValue)") + usage = UsageSnapshot(); localReadFailed = false + refreshUsage() + } + func transform(_ operation: String) { workbenchError = false do { workbenchOutput = try Self.transform(operation, text: workbenchInput, pattern: regexPattern, arabicUI: arabicUI) } @@ -373,5 +504,5 @@ final class DeveloperModel: ObservableObject { } func deleteSnippet(_ snippet: Snippet) { snippets.removeAll { $0.id == snippet.id }; saveSnippets() } - private func saveSnippets() { if let data = try? JSONEncoder().encode(snippets) { UserDefaults.standard.set(data, forKey: "snippets") } } + private func saveSnippets() { if let data = try? JSONEncoder().encode(snippets) { defaults.set(data, forKey: "snippets") } } } diff --git a/Sources/Notchest/DeveloperView.swift b/Sources/Notchest/DeveloperView.swift index 11755fe..4600bfd 100644 --- a/Sources/Notchest/DeveloperView.swift +++ b/Sources/Notchest/DeveloperView.swift @@ -52,15 +52,11 @@ struct DeveloperView: View { } Spacer() if dev.refreshing { ProgressView().controlSize(.mini) } - if dev.provider == .codex { - Button(dev.liveCodexLoading ? app.text("جارٍ الاتصال…", "Connecting…") : app.text("حدود الحساب الحيّة", "Live account limits")) { dev.refreshLiveCodex() } - .buttonStyle(.plain).font(.system(size: 9)).foregroundStyle(notchestAccent).disabled(dev.liveCodexLoading) - } Toggle(app.text("قراءة الإحصاءات المحلية", "Read local usage"), isOn: $dev.trackingEnabled).labelsHidden().toggleStyle(.switch).controlSize(.mini).tint(notchestAccent) - smallButton("arrow.clockwise", app.text("تحديث", "Refresh")) { dev.refreshUsage() } + smallButton("arrow.clockwise", app.text("تحديث", "Refresh")) { dev.refreshAllUsage() } smallButton("folder", app.text("مجلّد السجلّات", "Logs folder")) { dev.chooseUsageFolder() } } - if dev.provider == .codex, dev.liveCodex != nil || dev.liveCodexError != nil { + if dev.provider == .codex { liveLimits } if !dev.trackingEnabled { @@ -68,11 +64,14 @@ struct DeveloperView: View { Text(app.text("قراءة الإحصاءات متوقّفة", "Usage tracking is paused")) Button(app.text("تفعيل القراءة المحلية", "Enable local tracking")) { dev.trackingEnabled = true }.buttonStyle(.borderedProminent).tint(notchestAccent).foregroundStyle(.black) }.padding(25) - } else if dev.usage.missingDirectory || (dev.usage.fileCount == 0 && !dev.refreshing) { + } else if dev.usage.fileCount == 0 && dev.refreshing { + ProgressView(app.text("جارٍ قراءة السجلات…", "Reading usage logs…")) + .font(.system(size: 11)).padding(25) + } else if dev.usage.fileCount == 0 { VStack(spacing: 10) { Image(systemName: "chart.bar.xaxis").font(.system(size: 27, weight: .light)).foregroundStyle(notchestAccent) - Text(app.text("لم نعثر على سجلّات \(dev.provider.rawValue)", "No \(dev.provider.rawValue) logs found" )).font(.system(size: 15, weight: .semibold)) - Text(app.text("استخدم الأداة محليًا، أو اختر مجلّد سجلّاتها من الزر أعلاه.", "Use the tool locally, or select its log folder above.")) + Text(dev.localReadFailed && !dev.usage.missingDirectory ? app.text("تعذّرت قراءة السجلات", "Could not read usage logs") : app.text("لم نعثر على سجلّات \(dev.provider.rawValue)", "No \(dev.provider.rawValue) logs found" )).font(.system(size: 15, weight: .semibold)) + Text(dev.usage.partial ? app.text("تجاوزت السجلات حدود القراءة. اختر مجلداً أصغر أو سجلات أحدث.", "The logs exceed the reading limits. Choose a smaller folder or more recent logs.") : app.text("استخدم الأداة محليًا، أو اختر مجلّد سجلّاتها من الزر أعلاه. إذا كان المجلّد موجوداً، تحقّق من صلاحيات القراءة.", "Use the tool locally, or select its log folder above. If the folder exists, check read permissions.")) .font(.system(size: 11)).foregroundStyle(.white.opacity(0.6)) }.frame(maxWidth: .infinity).padding(.vertical, 32) } else { @@ -83,6 +82,7 @@ struct DeveloperView: View { } HStack(alignment: .top, spacing: 12) { VStack(alignment: .leading, spacing: 11) { + Text(app.text("حدود من السجلات المحلية", "LIMITS FROM LOCAL LOGS")).font(.system(size: 9, weight: .medium)).foregroundStyle(.white.opacity(0.6)) if let primary = dev.usage.primary { window(primary) } if let secondary = dev.usage.secondary { window(secondary) } if dev.usage.primary == nil && dev.usage.secondary == nil { @@ -105,20 +105,26 @@ struct DeveloperView: View { }.padding(11).notchestPanel(cornerRadius: 13) VStack(alignment: .leading, spacing: 4) { HStack { - Text(app.text("\(dev.usage.fileCount) سجلّات • تحديث كل 30 ثانية", "\(dev.usage.fileCount) logs • refreshes every 30 seconds")) + Label(app.text("تلقائي · كل 5 ثوانٍ", "Auto · every 5 seconds"), systemImage: "arrow.triangle.2.circlepath") Spacer() - if let observed = dev.usage.observedAt { - Text(app.text("لقطة الحدود: ", "Limits snapshot: ")) + Text(observed, style: .relative) + if let scanned = dev.usage.scannedAt { + Text(app.text("آخر قراءة: ", "Last checked: ")) + Text(scanned, style: .relative) } } + if let event = dev.usage.lastEventAt { + Text(app.text("آخر نشاط مسجّل: ", "Last recorded activity: ")) + Text(event, style: .relative) + } Text(app.text("الرموز المحلية ليست فاتورة أو رصيد اشتراك. لا نستخرج نصوص المحادثات أو مفاتيح الدخول.", "Local tokens are not a bill or subscription balance. Conversation text and credentials are not extracted.")) - if dev.usage.partial || dev.usage.unreadableFiles > 0 { + if dev.localReadFailed { + Text(app.text("تعذّرت قراءة بعض السجلات؛ نعرض آخر بيانات متاحة ونعيد المحاولة تلقائياً. تحقّق من المجلّد وصلاحيات القراءة.", "Some logs could not be read. Showing available data and retrying automatically. Check the folder and read permissions.")).foregroundStyle(.orange) + } else if dev.usage.partial || dev.usage.unreadableFiles > 0 { Text(app.text("القراءة جزئية؛ بعض السجلّات كبيرة أو غير قابلة للقراءة.", "Partial scan: some logs were too large or unreadable.")).foregroundStyle(.orange) } }.font(.system(size: 9)).foregroundStyle(.white.opacity(0.55)).frame(maxWidth: .infinity, alignment: .leading) } } } + .onAppear { dev.refreshAutomatically() } } /// Live account limits come from the Codex CLI connection and must stay @@ -128,20 +134,33 @@ struct DeveloperView: View { HStack { Text(app.text("حدود الحساب الحيّة", "Live account limits")).font(.system(size: 10, weight: .semibold)).foregroundStyle(notchestAccent) Spacer() - if let live = dev.liveCodex { - (Text(app.text("حدود حيّة ", "Live ")) + Text(live.fetchedAt, style: .relative)).font(.system(size: 9)).foregroundStyle(.white.opacity(0.55)) - } + if dev.liveCodexLoading { ProgressView().controlSize(.mini) } + Toggle(app.text("تحديث تلقائي كل دقيقة", "Auto-refresh every minute"), isOn: $dev.liveAutoRefreshEnabled) + .toggleStyle(.switch).controlSize(.mini).tint(notchestAccent).font(.system(size: 9)) + } + if let error = dev.liveCodexError { + Text(error).font(.system(size: 10)).foregroundStyle(.orange) + if dev.liveAutoRefreshEnabled { Text(app.text("سنعيد المحاولة تلقائياً؛ يمكنك أيضاً ضغط تحديث.", "Retrying automatically. You can also press Refresh.")).font(.system(size: 9)).foregroundStyle(.white.opacity(0.55)) } } - if let error = dev.liveCodexError { Text(error).font(.system(size: 10)).foregroundStyle(.orange) } if let live = dev.liveCodex { VStack(alignment: .leading, spacing: 11) { - if let primary = live.primary { window(primary) } - if let secondary = live.secondary { window(secondary) } + let stale = app.now.timeIntervalSince(live.fetchedAt) > 120 || dev.liveCodexError != nil || !dev.liveAutoRefreshEnabled + HStack { + Text(stale ? app.text("آخر بيانات متاحة", "Last available data") : app.text("متصل · تحديث تلقائي", "Connected · auto-refresh")) + .foregroundStyle(stale ? .orange : notchestAccent) + Spacer() + Text(app.text("آخر اتصال: ", "Last fetched: ")) + Text(live.fetchedAt, style: .relative) + }.font(.system(size: 9)).foregroundStyle(.white.opacity(0.55)) + if let primary = live.primary { window(primary, stale: stale) } + if let secondary = live.secondary { window(secondary, stale: stale) } if let lifetime = live.lifetimeTokens { Text(app.text("إجمالي رموز الحساب المسجّل: \(short(lifetime))", "Account lifetime tokens: \(short(lifetime))")) .font(.system(size: 9)).foregroundStyle(.white.opacity(0.55)) } } + } else if !dev.liveCodexLoading && dev.liveCodexError == nil { + Text(app.text("فعّل التحديث التلقائي لقراءة حدود حسابك عبر Codex CLI المسجّل دخوله. يعمل بشكل مستقل عن السجلات المحلية.", "Enable auto-refresh to read account limits through your signed-in Codex CLI, independently of local logs.")) + .font(.system(size: 10)).foregroundStyle(.white.opacity(0.55)) } }.padding(11).notchestPanel(cornerRadius: 13) } @@ -155,12 +174,12 @@ struct DeveloperView: View { }.frame(maxWidth: .infinity, alignment: .leading).padding(11).notchestPanel(cornerRadius: 13) } - private func window(_ window: UsageWindow) -> some View { + private func window(_ window: UsageWindow, stale: Bool = false) -> some View { let remaining = max(0, 100 - window.usedPercent) - let expired = window.resetsAt.map { $0 < Date() } ?? false + let expired = stale || (window.resetsAt.map { $0 <= app.now } ?? false) return VStack(spacing: 6) { HStack { - Text(window.minutes >= 1440 ? app.text("نافذة \(window.minutes / 1440) أيام", "\(window.minutes / 1440)-day window") : app.text("نافذة \(window.minutes / 60) ساعات", "\(window.minutes / 60)-hour window")) + Text(window.minutes >= 1440 ? app.text("نافذة \(window.minutes / 1440) أيام", "\(window.minutes / 1440)-day window") : window.minutes >= 60 && window.minutes % 60 == 0 ? app.text("نافذة \(window.minutes / 60) ساعات", "\(window.minutes / 60)-hour window") : app.text("نافذة \(window.minutes) دقيقة", "\(window.minutes)-minute window")) Spacer() Text(expired ? app.text("لقطة قديمة", "Stale snapshot") : app.text("\(Int(remaining))% متبقٍ", "\(Int(remaining))% remaining")).foregroundStyle(expired ? .orange : notchestAccent) }.font(.system(size: 10)) diff --git a/Sources/Notchest/IslandView.swift b/Sources/Notchest/IslandView.swift index 3429c33..3337553 100644 --- a/Sources/Notchest/IslandView.swift +++ b/Sources/Notchest/IslandView.swift @@ -7,6 +7,7 @@ private let notchestCard = Color.white.opacity(0.055) struct IslandView: View { @ObservedObject var model: AppModel + @ObservedObject private var developer: DeveloperModel let onHover: (Bool) -> Void let activate: () -> Void private var search: String { model.clipboardSearch } @@ -24,6 +25,13 @@ struct IslandView: View { } private var contentIdentity: String { model.paletteVisible ? "palette" : model.tab.rawValue } + init(model: AppModel, onHover: @escaping (Bool) -> Void, activate: @escaping () -> Void) { + self.model = model + self.developer = model.developer + self.onHover = onHover + self.activate = activate + } + var body: some View { VStack(spacing: 0) { Button { model.expanded.toggle(); activate() } label: { @@ -94,7 +102,7 @@ struct IslandView: View { Text(model.timeLabel).font(.system(size: 11, weight: .semibold, design: .monospaced)).foregroundStyle(notchestAccent) } else if model.stopwatchStarted != nil { Text(model.stopwatchLabel).font(.system(size: 9, weight: .semibold, design: .monospaced)).foregroundStyle(notchestAccent) - } else if let window = model.developer.usage.primary, (window.resetsAt ?? .distantFuture) > model.now { + } else if let window = developer.compactUsageWindow(at: model.now) { Text("\(Int(100 - window.usedPercent))% AI").font(.system(size: 10, weight: .semibold, design: .monospaced)).foregroundStyle(notchestAccent) } else if model.awake { Image(systemName: "cup.and.saucer.fill").font(.system(size: 12)).foregroundStyle(notchestAccent) diff --git a/Sources/Notchest/UsageReader.swift b/Sources/Notchest/UsageReader.swift index 329bd06..b46c68a 100644 --- a/Sources/Notchest/UsageReader.swift +++ b/Sources/Notchest/UsageReader.swift @@ -37,11 +37,14 @@ struct UsageSnapshot { var secondary: UsageWindow? var observedAt: Date? var scannedAt: Date? + var lastEventAt: Date? var fileCount = 0 var eventCount = 0 var missingDirectory = false var partial = false var unreadableFiles = 0 + /// Disk bytes read this pass; unchanged files and appended tails stay cheap. + var bytesRead = 0 } enum UsageReader { @@ -53,11 +56,17 @@ enum UsageReader { private struct ParsedFile { var modified: Date var size: Int + var identity: String var weekStart: Date + var offset: UInt64 = 0 + var previous = TokenTally() + var discardingOversizedLine = false + var skippedOversizedLine = false var entries: [String: Entry] = [:] var primary: UsageWindow? var secondary: UsageWindow? var observedAt: Date? + var lastEventAt: Date? } private static let cacheLock = NSLock() private static var cache: [String: ParsedFile] = [:] @@ -67,53 +76,65 @@ enum UsageReader { snapshot.scannedAt = now let fm = FileManager.default guard fm.fileExists(atPath: directory.path) else { snapshot.missingDirectory = true; return snapshot } - guard let enumerator = fm.enumerator(at: directory, includingPropertiesForKeys: [.contentModificationDateKey, .fileSizeKey, .isRegularFileKey], options: [.skipsHiddenFiles], errorHandler: { _, _ in false }) else { + var enumerationErrors = 0 + guard let enumerator = fm.enumerator(at: directory, includingPropertiesForKeys: [.contentModificationDateKey, .fileSizeKey, .isRegularFileKey], options: [.skipsHiddenFiles], errorHandler: { _, _ in enumerationErrors += 1; return true }) else { snapshot.unreadableFiles = 1 return snapshot } var files: [(URL, Date, Int)] = [] for case let url as URL in enumerator { - guard url.pathExtension == "jsonl", let values = try? url.resourceValues(forKeys: [.contentModificationDateKey, .fileSizeKey, .isRegularFileKey]), values.isRegularFile == true else { continue } + if Task.isCancelled { return snapshot } + guard url.pathExtension == "jsonl" else { continue } + guard let values = try? url.resourceValues(forKeys: [.contentModificationDateKey, .fileSizeKey, .isRegularFileKey]), values.isRegularFile == true else { snapshot.unreadableFiles += 1; continue } files.append((url, values.contentModificationDate ?? .distantPast, values.fileSize ?? 0)) } + snapshot.unreadableFiles += enumerationErrors files.sort { $0.1 > $1.1 } if files.count > 1500 { snapshot.partial = true } let calendar = Calendar.current let day = calendar.startOfDay(for: now) let weekStart = calendar.date(byAdding: .day, value: -6, to: day)! var entries: [String: Entry] = [:] - var bytesRead = 0 let formatter = ISO8601DateFormatter() formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds] let fallbackFormatter = ISO8601DateFormatter() for (file, modified, size) in files.prefix(1500) { + if Task.isCancelled { return snapshot } // Old unmodified transcripts cannot contribute to this seven-day view. if modified < weekStart { continue } - guard size < 1024 * 1024 * 1024, bytesRead + size < 1024 * 1024 * 1024 else { snapshot.partial = true; continue } + guard size < 1024 * 1024 * 1024 else { snapshot.partial = true; continue } + let attributes = try? fm.attributesOfItem(atPath: file.path) + let identity = "\(attributes?[.systemNumber] ?? 0):\(attributes?[.systemFileNumber] ?? 0)" let key = provider.rawValue + file.path cacheLock.lock() let cached = cache[key] cacheLock.unlock() let parsed: ParsedFile - if let cached, cached.modified == modified, cached.size == size, cached.weekStart <= weekStart { + if let cached, cached.identity == identity, cached.modified == modified, cached.size == size, cached.weekStart == weekStart { parsed = cached } else { - guard let data = try? Data(contentsOf: file, options: .mappedIfSafe) else { snapshot.unreadableFiles += 1; continue } - bytesRead += size - parsed = parseFile(data, provider: provider, modified: modified, size: size, weekStart: weekStart, now: now, formatter: formatter, fallback: fallbackFormatter) + // JSONL writers append. Reuse only complete records from the same inode; + // truncation, replacement, or a new day requires a fresh baseline. + let base = cached.flatMap { $0.identity == identity && size > $0.size && $0.weekStart == weekStart ? $0 : nil } + let offset = base?.offset ?? 0 + let needed = max(0, size - Int(offset)) + guard snapshot.bytesRead + needed < 1024 * 1024 * 1024 else { snapshot.partial = true; continue } + do { + parsed = try readFile(file, provider: provider, base: base, modified: modified, size: size, identity: identity, weekStart: weekStart, now: now, formatter: formatter, fallback: fallbackFormatter) + snapshot.bytesRead += needed + } catch { + snapshot.unreadableFiles += 1 + // Keep the last good contribution during a transient read failure. + if let cached { merge(cached, into: &snapshot, entries: &entries, weekStart: weekStart, now: now) } + continue + } cacheLock.lock() if cache.count > 2000 { cache.removeAll() } cache[key] = parsed cacheLock.unlock() } - snapshot.fileCount += 1 - if let date = parsed.observedAt, snapshot.observedAt == nil || date > snapshot.observedAt! { - snapshot.primary = parsed.primary; snapshot.secondary = parsed.secondary; snapshot.observedAt = date - } - for (key, entry) in parsed.entries where entry.date >= weekStart { - if entries[key] == nil || entry.tally.total > entries[key]!.tally.total { entries[key] = entry } - } + merge(parsed, into: &snapshot, entries: &entries, weekStart: weekStart, now: now) } var daily: [Date: Int] = [:] for entry in entries.values { @@ -130,41 +151,89 @@ enum UsageReader { return snapshot } - private static func parseFile(_ data: Data, provider: AIProvider, modified: Date, size: Int, weekStart: Date, now: Date, formatter: ISO8601DateFormatter, fallback: ISO8601DateFormatter) -> ParsedFile { - var parsed = ParsedFile(modified: modified, size: size, weekStart: weekStart) - var previous = TokenTally() - let marker = Data((provider == .codex ? "\"token_count\"" : "\"usage\"").utf8) - for line in data.split(separator: 10) { - guard line.range(of: marker) != nil, - let object = (try? JSONSerialization.jsonObject(with: Data(line))) as? [String: Any], - let timestamp = object["timestamp"] as? String, - let date = formatter.date(from: timestamp) ?? fallback.date(from: timestamp) else { continue } - if provider == .codex { - guard let payload = object["payload"] as? [String: Any], payload["type"] as? String == "token_count" else { continue } - if let limits = payload["rate_limits"] as? [String: Any], parsed.observedAt == nil || date >= parsed.observedAt! { - parsed.primary = parseWindow(limits["primary"]) - parsed.secondary = parseWindow(limits["secondary"]) - parsed.observedAt = date - } - guard let info = payload["info"] as? [String: Any], let total = info["total_token_usage"] as? [String: Any] else { continue } - let current = TokenTally(input: integer(total["input_tokens"]), cached: integer(total["cached_input_tokens"]), output: integer(total["output_tokens"])) - let delta = TokenTally(input: max(0, current.input - previous.input), cached: max(0, current.cached - previous.cached), output: max(0, current.output - previous.output)) - previous = current - if delta.total == 0 || date < weekStart || date > now.addingTimeInterval(60) { continue } - let key = "\(timestamp):\(current.input):\(current.output)" - parsed.entries[key] = Entry(date: date, tally: delta, key: key) - } else { - guard object["type"] as? String == "assistant", let message = object["message"] as? [String: Any], let usage = message["usage"] as? [String: Any], date >= weekStart, date <= now.addingTimeInterval(60) else { continue } - let cached = integer(usage["cache_read_input_tokens"]) - let input = integer(usage["input_tokens"]) + cached + integer(usage["cache_creation_input_tokens"]) - let tally = TokenTally(input: input, cached: cached, output: integer(usage["output_tokens"])) - let key = message["id"] as? String ?? "\(timestamp):\(input):\(tally.output)" - if parsed.entries[key] == nil || tally.total > parsed.entries[key]!.tally.total { parsed.entries[key] = Entry(date: date, tally: tally, key: key) } + private static func merge(_ parsed: ParsedFile, into snapshot: inout UsageSnapshot, entries: inout [String: Entry], weekStart: Date, now: Date) { + snapshot.fileCount += 1 + snapshot.partial = snapshot.partial || parsed.skippedOversizedLine + if let date = parsed.observedAt, snapshot.observedAt == nil || date > snapshot.observedAt! { + snapshot.primary = parsed.primary; snapshot.secondary = parsed.secondary; snapshot.observedAt = date + } + if let date = parsed.lastEventAt, snapshot.lastEventAt == nil || date > snapshot.lastEventAt! { snapshot.lastEventAt = date } + for (key, entry) in parsed.entries where entry.date >= weekStart && entry.date <= now.addingTimeInterval(60) { + if entries[key] == nil || entry.tally.total > entries[key]!.tally.total { entries[key] = entry } + } + } + + private static func readFile(_ url: URL, provider: AIProvider, base: ParsedFile?, modified: Date, size: Int, identity: String, weekStart: Date, now: Date, formatter: ISO8601DateFormatter, fallback: ISO8601DateFormatter) throws -> ParsedFile { + var parsed = base ?? ParsedFile(modified: modified, size: size, identity: identity, weekStart: weekStart) + parsed.modified = modified; parsed.size = size + let handle = try FileHandle(forReadingFrom: url) + defer { try? handle.close() } + try handle.seek(toOffset: parsed.offset) + var remaining = size - Int(parsed.offset) + var pending = Data() + // Read bounded chunks, and cache only numeric entries, never transcript text. + while remaining > 0 { + try Task.checkCancellation() + let chunk = try handle.read(upToCount: min(262_144, remaining)) ?? Data() + guard !chunk.isEmpty else { throw CocoaError(.fileReadUnknown) } + remaining -= chunk.count + pending.append(chunk) + while let newline = pending.firstIndex(of: 10) { + let consumed = pending.distance(from: pending.startIndex, to: newline) + 1 + if !parsed.discardingOversizedLine, consumed <= 8 * 1024 * 1024 { + parseLine(Data(pending[.. 8 * 1024 * 1024 || parsed.discardingOversizedLine { + parsed.skippedOversizedLine = true + parsed.discardingOversizedLine = true + parsed.offset += UInt64(pending.count) + pending.removeAll(keepingCapacity: false) } } + // A valid final record does not need a trailing newline. An incomplete + // one is left on disk and retried after the writer finishes it. + if !pending.isEmpty, (try? JSONSerialization.jsonObject(with: pending)) != nil { + parseLine(pending, provider: provider, parsed: &parsed, weekStart: weekStart, now: now, formatter: formatter, fallback: fallback) + parsed.offset += UInt64(pending.count) + } return parsed } + private static func parseLine(_ line: Data, provider: AIProvider, parsed: inout ParsedFile, weekStart: Date, now: Date, formatter: ISO8601DateFormatter, fallback: ISO8601DateFormatter) { + let marker = Data((provider == .codex ? "\"token_count\"" : "\"usage\"").utf8) + guard line.range(of: marker) != nil, + let object = (try? JSONSerialization.jsonObject(with: Data(line))) as? [String: Any], + let timestamp = object["timestamp"] as? String, + let date = formatter.date(from: timestamp) ?? fallback.date(from: timestamp) else { return } + if provider == .codex { + guard let payload = object["payload"] as? [String: Any], payload["type"] as? String == "token_count" else { return } + if date <= now.addingTimeInterval(60), let limits = payload["rate_limits"] as? [String: Any], parseWindow(limits["primary"]) != nil || parseWindow(limits["secondary"]) != nil, parsed.observedAt == nil || date >= parsed.observedAt! { + parsed.primary = parseWindow(limits["primary"]) + parsed.secondary = parseWindow(limits["secondary"]) + parsed.observedAt = date + } + guard let info = payload["info"] as? [String: Any], let total = info["total_token_usage"] as? [String: Any] else { return } + let current = TokenTally(input: integer(total["input_tokens"]), cached: integer(total["cached_input_tokens"]), output: integer(total["output_tokens"])) + let delta = TokenTally(input: max(0, current.input - parsed.previous.input), cached: max(0, current.cached - parsed.previous.cached), output: max(0, current.output - parsed.previous.output)) + parsed.previous = current + if delta.total == 0 || date < weekStart || date > now.addingTimeInterval(60) { return } + let key = "\(timestamp):\(current.input):\(current.output)" + parsed.entries[key] = Entry(date: date, tally: delta, key: key) + } else { + guard object["type"] as? String == "assistant", let message = object["message"] as? [String: Any], let usage = message["usage"] as? [String: Any], date >= weekStart, date <= now.addingTimeInterval(60) else { return } + let cached = integer(usage["cache_read_input_tokens"]) + let input = integer(usage["input_tokens"]) + cached + integer(usage["cache_creation_input_tokens"]) + let tally = TokenTally(input: input, cached: cached, output: integer(usage["output_tokens"])) + let key = message["id"] as? String ?? "\(timestamp):\(input):\(tally.output)" + if parsed.entries[key] == nil || tally.total > parsed.entries[key]!.tally.total { parsed.entries[key] = Entry(date: date, tally: tally, key: key) } + } + if parsed.lastEventAt == nil || date > parsed.lastEventAt! { parsed.lastEventAt = date } + } + static func parseWindow(_ value: Any?) -> UsageWindow? { guard let dict = value as? [String: Any], let percent = (dict["used_percent"] as? NSNumber)?.doubleValue, percent.isFinite else { return nil } let reset = (dict["resets_at"] as? NSNumber).map { Date(timeIntervalSince1970: $0.doubleValue) } From 9919dbf3bd4f6593fef167451bda5e38e11b65d3 Mon Sep 17 00:00:00 2001 From: Hussein Faez <257576459+H0777@users.noreply.github.com> Date: Mon, 2 Nov 2026 22:05:44 +0300 Subject: [PATCH 2/7] Add transparent glass, workspace setup and project activity --- CHANGELOG.md | 17 +++ Checks/RunChecks.swift | 98 +++++++++++- Docs/INTEGRATIONS.md | 88 +++++++++++ Docs/VALIDATION.md | 28 ++++ FEATURES.md | 10 ++ README.ar.md | 4 + README.md | 5 + ROADMAP.md | 16 +- Scripts/gallery/DemoData.swift | 19 ++- Scripts/gallery/prepare.py | 2 +- Scripts/measure.sh | 45 +++--- Sources/Notchest/ActivityCenter.swift | 40 ++++- Sources/Notchest/ActivityView.swift | 153 ++++++++++++------- Sources/Notchest/AppModel.swift | 24 ++- Sources/Notchest/DeveloperModel.swift | 47 +++++- Sources/Notchest/DeveloperView.swift | 30 +++- Sources/Notchest/HookIntegration.swift | 79 ++++++++++ Sources/Notchest/IslandSettingsView.swift | 4 + Sources/Notchest/IslandSizing.swift | 2 +- Sources/Notchest/IslandView.swift | 34 +++-- Sources/Notchest/NotchestApp.swift | 35 +++-- Sources/Notchest/NotchestDesign.swift | 47 ++++-- Sources/Notchest/ProjectMonitor.swift | 103 +++++++++++++ Sources/Notchest/SetupModel.swift | 70 +++++++++ Sources/Notchest/SetupView.swift | 64 ++++++++ Sources/Notchest/UpdateModel.swift | 83 ++++++++++ Sources/Notchest/UsageAlerts.swift | 25 +++ Sources/Notchest/WorkspacePreferences.swift | 59 +++++++ Sources/Notchest/WorkspaceSettingsView.swift | 72 +++++++++ Sources/NotchestCommand/HookPayload.swift | 26 ++++ Sources/NotchestCommand/main.swift | 41 +++++ check.sh | 2 +- 32 files changed, 1238 insertions(+), 134 deletions(-) create mode 100644 Docs/INTEGRATIONS.md create mode 100644 Docs/VALIDATION.md create mode 100644 Sources/Notchest/HookIntegration.swift create mode 100644 Sources/Notchest/ProjectMonitor.swift create mode 100644 Sources/Notchest/SetupModel.swift create mode 100644 Sources/Notchest/SetupView.swift create mode 100644 Sources/Notchest/UpdateModel.swift create mode 100644 Sources/Notchest/UsageAlerts.swift create mode 100644 Sources/Notchest/WorkspacePreferences.swift create mode 100644 Sources/Notchest/WorkspaceSettingsView.swift create mode 100644 Sources/NotchestCommand/HookPayload.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 6e59143..c78ff4e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,23 @@ All notable changes to Notchest are documented here. The format follows ## [Unreleased] +### Added + +- First-run connection checks and Developer/Focus/Everyday presets, with + persistent, reorderable home cards and a background-transparency control. +- Native clear `NSGlassEffectView` on macOS 26+, preserving the notch outline + and providing a behind-window material fallback on older macOS versions. +- Side-by-side local Codex/Claude summaries and optional 80%/95% usage alerts. +- Opt-in native agent hooks for task states, with private configuration + backups and removal, metadata-only local delivery and no approval decisions. +- Opt-in GitHub Actions tracking for the selected project, plus local command + start/exit activities that preserve the active tab. +- Manual and opt-in six-hour stable-release checks with official download-page + links. Developer ID, notarization and unattended installation are deferred + until the owner prepares Apple Developer membership. +- Integration instructions and a validation matrix distinguishing automated, + native UI, real-account and pending hardware coverage. + ### Fixed - Refresh local AI usage every five seconds in common run-loop modes, on diff --git a/Checks/RunChecks.swift b/Checks/RunChecks.swift index 14383a6..eaee873 100644 --- a/Checks/RunChecks.swift +++ b/Checks/RunChecks.swift @@ -53,6 +53,102 @@ struct RunChecks { try await Task.sleep(nanoseconds: 10_000_000) } } + check("Workspace presets keep a visible card and constrain background opacity") { + var prefs = WorkspacePreferences() + prefs.cards = [.usage, .usage, .focus] + precondition(prefs.validated().cards == [.usage, .focus]) + prefs.cards = [.focus]; prefs.setVisible(.focus, false) + precondition(prefs.cards == [.focus]) + prefs.setVisible(.notes, true); prefs.move(.notes, by: -1) + precondition(prefs.cards == [.notes, .focus]) + prefs.backgroundOpacity = .nan + precondition(prefs.validated().backgroundOpacity == 0.42) + prefs.backgroundOpacity = 9 + precondition(prefs.validated().backgroundOpacity == 0.75) + } + check("Setup completion and workspace changes survive relaunch without resetting dimensions") { + let suite = "dev.notchest.workspace.\(UUID())" + let store = UserDefaults(suiteName: suite)! + defer { store.removePersistentDomain(forName: suite) } + let first = AppModel(defaults: store, startServices: false) + precondition(!first.setupCompleted) + first.workspace.cards = WorkspacePreset.focus.cards + first.workspace.backgroundOpacity = 0.35 + first.islandPreferences.expandedWidth = 900 + first.finishSetup() + let restored = AppModel(defaults: store, startServices: false) + precondition(restored.setupCompleted && restored.workspace.cards == WorkspacePreset.focus.cards) + precondition(restored.workspace.backgroundOpacity == 0.35 && restored.islandPreferences.expandedWidth == 900) + first.shutdown(); restored.shutdown() + } + try check("Release checks compare numeric versions and reject untrusted or preview release pages") { + precondition(ReleaseVersion("v0.10.0")! > ReleaseVersion("0.9.9")!) + precondition(ReleaseVersion("0.7.0-beta") == nil && ReleaseVersion("0.7") == nil) + func data(_ page: String, preview: Bool = false) throws -> Data { + try JSONSerialization.data(withJSONObject: ["tag_name": "v0.7.0", "html_url": page, "draft": false, "prerelease": preview]) + } + let valid = try AvailableRelease.parse(data("https://github.com/H0777/Notchest/releases/tag/v0.7.0")) + precondition(valid.version == "0.7.0") + for page in ["https://github.com.evil.example/H0777/Notchest/releases/tag/v0.7.0", "https://github.com/another/repo/releases/tag/v0.7.0"] { + do { _ = try AvailableRelease.parse(data(page)); preconditionFailure("Untrusted release accepted") } catch {} + } + do { _ = try AvailableRelease.parse(data("https://github.com/H0777/Notchest/releases/tag/v0.7.0", preview: true)); preconditionFailure("Preview accepted as stable") } catch {} + } + try check("Agent hooks expose metadata only and never return an approval decision") { + let input: [String: Any] = ["hook_event_name": "PermissionRequest", "session_id": "private-session", "cwd": "/tmp/Example", "prompt": "private-prompt", "tool_input": ["command": "private-command"], "last_assistant_message": "private-answer"] + let payload = HookPayload.make(input, provider: "codex")! + precondition(payload["state"] as? String == "waiting" && payload["project"] as? String == "Example") + let text = String(decoding: try JSONSerialization.data(withJSONObject: payload), as: UTF8.self) + precondition(!text.contains("private-") && !text.contains("decision") && !text.contains("/tmp")) + precondition(HookPayload.make(input, provider: "unsupported") == nil) + var stopped = input; stopped["hook_event_name"] = "Stop" + precondition(HookPayload.make(stopped, provider: "claude")?["state"] as? String == "success") + } + try check("Hook installation preserves user settings, backs up privately, removes only its own hooks") { + let folder = FileManager.default.temporaryDirectory.appendingPathComponent("notchest-hooks-\(UUID())") + defer { try? FileManager.default.removeItem(at: folder) } + let file = folder.appendingPathComponent("settings.json") + let original = Data("{\"theme\":\"dark\",\"hooks\":{\"Stop\":[{\"hooks\":[{\"type\":\"command\",\"command\":\"other-hook\"}]}]}}".utf8) + try PrivateFile.write(original, to: file) + let helper = URL(fileURLWithPath: "/Applications/Preview's.app/Contents/MacOS/NotchestCommand") + let backup = try HookInstaller.install(.claude, helper: helper, configuration: file)! + try expect(try Data(contentsOf: backup) == original) + let installed = try Data(contentsOf: file) + let root = try JSONSerialization.jsonObject(with: installed) as! [String: Any] + precondition(root["theme"] as? String == "dark") + precondition(String(decoding: installed, as: UTF8.self).contains("other-hook")) + try expect(try HookInstaller.install(.claude, helper: helper, configuration: file) == nil) + let mode = try FileManager.default.attributesOfItem(atPath: file.path)[.posixPermissions] as! NSNumber + precondition(mode.intValue & 0o077 == 0) + try HookInstaller.install(.claude, helper: helper, configuration: file, remove: true) + let removed = String(decoding: try Data(contentsOf: file), as: UTF8.self) + precondition(removed.contains("other-hook") && !removed.contains("--activity-hook")) + let invalid = Data("invalid settings".utf8) + try PrivateFile.write(invalid, to: file) + do { try HookInstaller.install(.codex, helper: helper, configuration: file); preconditionFailure("Invalid settings overwritten") } catch {} + try expect(try Data(contentsOf: file) == invalid) + } + check("Usage alerts fire once per threshold and reset window, and ignore expired snapshots") { + var policy = UsageAlertPolicy() + let now = Date(), reset = Date().addingTimeInterval(3600) + func window(_ percent: Double, _ reset: Date) -> UsageWindow { UsageWindow(usedPercent: percent, minutes: 300, resetsAt: reset) } + precondition(policy.evaluate([window(79, reset)], at: now).isEmpty) + precondition(policy.evaluate([window(82, reset)], at: now).count == 1) + precondition(policy.evaluate([window(84, reset)], at: now).isEmpty) + precondition(policy.evaluate([window(96, reset)], at: now).count == 1) + precondition(policy.evaluate([window(99, reset)], at: now).isEmpty) + precondition(policy.evaluate([window(99, now.addingTimeInterval(-1))], at: now).isEmpty) + precondition(policy.evaluate([window(99, reset.addingTimeInterval(3600))], at: now).count == 1) + } + try check("Project workflow parsing handles unfinished results and excludes unsafe links") { + let base: [String: Any] = ["databaseId": 123, "name": "Build", "displayTitle": "Check change", "status": "in_progress", "conclusion": NSNull(), "headBranch": "main", "url": "https://github.com/H0777/Notchest/actions/runs/123"] + let runs = try ProjectRun.parse(JSONSerialization.data(withJSONObject: [base])) + precondition(runs.count == 1 && runs[0].activityState == "running") + var done = base; done["status"] = "completed"; done["conclusion"] = "failure" + try expect(try ProjectRun.parse(JSONSerialization.data(withJSONObject: [done]))[0].activityState == "failure") + done["url"] = "javascript:alert(1)" + try expect(try ProjectRun.parse(JSONSerialization.data(withJSONObject: [done])).isEmpty) + } let start = Date(timeIntervalSince1970: 1_000) check("Timer uses elapsed wall time, including missed ticks") { var clock = FocusClock() @@ -384,7 +480,7 @@ struct RunChecks { preferences.compactWidth = 200 preferences.compactHeight = 34 let frame = display.windowFrame(preferences: preferences, expanded: false) - precondition(frame.width >= 263 && frame.height >= 35) + precondition(frame.width >= display.notchWidth + 120 && frame.height >= 35) precondition(frame.midX == display.frame.midX && frame.maxY == display.frame.maxY) } check("Island dimensions fit small and external displays") { diff --git a/Docs/INTEGRATIONS.md b/Docs/INTEGRATIONS.md new file mode 100644 index 0000000..65ad20d --- /dev/null +++ b/Docs/INTEGRATIONS.md @@ -0,0 +1,88 @@ +# Set up your Notchest workspace + +These features are in the development build after 0.6.0. The published 0.6.0 +DMG does not contain them yet. English is the default; Arabic is optional. + +## First launch and your overview + +First launch offers Developer, Focus and Everyday presets. Each selects four +home cards. Settings lets you show, hide and reorder individual cards, reopen +setup, choose log/project folders, and adjust background transparency. +At least one home card remains visible. Existing notes and island dimensions +are preserved. Reduce Transparency and Increase Contrast override the glass +appearance for readability. + +## AI usage and limits + +Local Codex and Claude Code summaries appear together. Each log directory can +be selected independently. Scans run every five seconds; their results depend +on the provider writing usage records. Enable recurring Codex account limits +to query the signed-in CLI every minute. Local tracking and account access +remain independent. No inference request is made to read limits. + +Optional alerts appear inside Notchest at 80% and 95% usage. A threshold is +reported once per observed reset window. Expired snapshots do not generate +alerts. The app does not invent account limits for Claude or other providers. +Tokens from local logs are not a financial bill or subscription balance. + +## Agent task states + +1. Move the application to its intended permanent location first, normally + Applications. Hook commands point to its bundled `NotchestCommand` helper. +2. Open Developer > Activity and enable Local API. It listens on loopback + only, uses a rotating token, and remains off on the next app launch. +3. Choose Codex or Claude Code > Install integration. The app shows the scope + before changing configuration and saves an owner-readable local backup. +4. Restart the coding tool. Codex requires review and trust of new hooks in + `/hooks` or Settings > Hooks. Complete that review inside Codex yourself. + Use a tool version that supports lifecycle hooks; older versions may need + upgrading. Managed policies can prevent hooks from running. +5. Start a task. Notchest displays Working, Needs attention, Turn completed, + or Stopped, using the task-state events it receives. Return to the original + coding tool to review and approve requests. + +Codex configuration: `CODEX_HOME/hooks.json`, otherwise `~/.codex/hooks.json`. +Claude configuration: `CLAUDE_CONFIG_DIR/settings.json`, otherwise +`~/.claude/settings.json`. Existing hooks and other settings are preserved. +Remove integration removes only the Notchest hook entries and keeps a backup. +Reinstall the integration after moving/renaming the app bundle. + +The helper discards prompts, tool arguments, answers and transcript paths. It +posts only provider, hashed session identity, project basename and event state +on this Mac. It always prints empty JSON and never returns an approval, +rejection or continuation decision. This is an observer, not a remote-control +interface. A hook `Stop` describes a turn-stop event; it does not prove that +all tests passed. Build results come from explicit command exits or GitHub +workflow results. If the app is unavailable the helper exits without blocking +the coding tool. + +The API token is stored only while enabled in an owner-readable runtime file +under `~/Library/Application Support/Notchest/Runtime`. It is removed on +normal shutdown/disable and replaced with a new token next time. + +References: [Codex hooks](https://learn.chatgpt.com/docs/hooks), +[Claude Code hooks](https://code.claude.com/docs/en/hooks). + +## Project builds and tests + +Choose a local Git repository, sign in with GitHub CLI (`gh auth login`), and +enable GitHub Actions in Developer > Activity. The app checks up to eight +recent workflow runs every minute, shows four in the card, and opens their +GitHub results on click. State changes produce local activities. The initial +scan does not announce historical completed runs. Local command runs also +report start/exit status without changing the active tab on completion. + +This reads workflow status; it does not execute or modify repository code. +See [GitHub CLI run list](https://cli.github.com/manual/gh_run_list). + +## Releases and Apple signing + +Settings > Updates can check the repository's latest stable release manually, +or every six hours after you opt in. It opens the official release download +page. Installation remains manual. + +Developer ID signing, Apple notarization and unattended installation are +**deferred at the project owner's request** until an Apple Developer account +is ready. Development packaging keeps the existing local ad-hoc signature; +no Apple credentials, paid membership, notarization submission or new +security exception is requested by this work. diff --git a/Docs/VALIDATION.md b/Docs/VALIDATION.md new file mode 100644 index 0000000..a1e6c1b --- /dev/null +++ b/Docs/VALIDATION.md @@ -0,0 +1,28 @@ +# Development validation matrix — 2026-11-02 + +Scope: workspace/onboarding, transparent native glass, agent activity, +project tracking, AI summaries and release checks after 0.6.0. This is a +record of evidence, not a claim that every supported Mac has been tested. + +| Scenario | Evidence/status | +| --- | --- | +| Core correctness | 52 project checks passed locally | +| Preference migration | Setup completion, home order, transparency and dimensions survive model relaunch | +| AI lifecycle | Append/incomplete records, log replacement/day rollover, provider/folder races, retry backoff, cancellation and stale compact limits covered | +| AI alerts | Once per 80%/95% threshold and reset window; expired data ignored | +| Hooks/configuration | Metadata filtering, private backups, existing settings preservation, idempotent install, removal and invalid-file rejection covered in temporary directories | +| Project results | Queued/running/null conclusion and failed runs decoded; unsafe links excluded; actual GitHub runs displayed in the native UI | +| Release metadata | Numeric versions, stable-only results, official repository URLs covered | +| Website | Existing 39-feature gallery remains the released UI baseline; new screenshots are development previews | +| Native UI English/Arabic, glass and preference controls | Passed on the local Mac: English/Arabic setup, presets, card reordering, both provider summaries, glass slider and live release checks | +| Native helper to loopback API | Passed: synthetic PermissionRequest → working → Stop through the packaged helper; empty JSON replies; runtime token removed on disable | +| Whole-app performance | New measurement recorded separately in PERFORMANCE.md when taken | +| Multiple physical displays, hot-plug and mixed scaling | Pending access to additional displays; sizing geometry has automated coverage | +| Intel and macOS 13–25 material fallback | Pending hardware/OS testing; build targets macOS 13 and guards newer APIs | +| macOS 26 native glass | API is availability-guarded; CI builds against the macOS 26 SDK | +| Real sleep/wake, prolonged battery use and full-screen combinations | Pending device soak testing; wake handling and window policy remain in source | +| Apple Developer ID/notarization and unattended installation | Deferred by owner | + +Before a broad release, exercise the pending hardware cases and repeat the +performance measurement with real provider logs. No claim of zero CPU, +zero battery impact, full device coverage or Apple approval is made. diff --git a/FEATURES.md b/FEATURES.md index d2b0cbd..d8ef542 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -4,6 +4,16 @@ هذا السجل يميز بين المزايا الموجودة والمزايا التي تتطلب إعدادًا أو ما تزال قيد التطوير. لا تعني إضافة واجهة لتكامل أن جميع الأجهزة والخدمات قد اختُبرت. +## تطوير غير منشور — مساحة العمل والزجاج + +- خامة Liquid Glass أصلية صافية في خلفية النافذة على macOS 26+، مع بديل للإصدارات الأقدم ومنزلق للشفافية واحترام إعدادات تسهيلات الاستخدام. +- إعداد أول تشغيل وفحص اتصالات الأدوات، وقوالب للبرمجة والتركيز واليوميات، وترتيب بطاقات الرئيسية وإظهارها وإخفائها دون فقد أبعاد الجزيرة أو الملاحظات. +- ملخصا Codex وClaude معاً، وتنبيهات اختيارية داخل الجزيرة عند 80% و95% من حدود الاستخدام المعروفة. +- ربط اختياري بحالات مهام Codex وClaude، يحفظ نسخة احتياطية من إعدادات الخطافات، ويعرض الانتظار والاكتمال دون اتخاذ قرارات موافقة. يتطلب إصداراً يدعم الخطافات ومراجعتها في الأداة الأصلية. +- متابعة اختيارية لـGitHub Actions كل دقيقة، وأنشطة لبدء الأوامر وانتهائها. الموافقات وتنفيذ مهام الوكيل تبقى في أداة البرمجة. +- فحص إصدارات مستقرّة يدوياً أو كل 6 ساعات اختيارياً. توقيع Developer ID وتصديق Apple والتثبيت دون تدخل مؤجّلة بطلب المالك. +- نجحت 52 عملية فحص؛ نطاق الأدلة وما يحتاج أجهزة إضافية موضّح في [مصفوفة التحقق](Docs/VALIDATION.md)، والإعداد في [دليل التكاملات](Docs/INTEGRATIONS.md). + ## تطوير غير منشور بعد 0.6.0 — AI Usage - قراءة محلية كل 5 ثوانٍ، مع مؤقّت يستمر أثناء التفاعل وتحديث بعد الاستيقاظ والعودة للقسم. diff --git a/README.ar.md b/README.ar.md index fde686c..f2b5f7f 100644 --- a/README.ar.md +++ b/README.ar.md @@ -41,6 +41,10 @@ يضم قسم الحركة ثلاثة أنماط للسرعة: هادئة ومتوازنة وسريعة، مع خيار لإيقاف الحركة. يشمل التحريك فتح الجزيرة وطيّها والتنقّل بين التبويبات وأقسام الأدوات، ويحترم إعداد «تقليل الحركة» في macOS. تُحفظ التغييرات محليًا عند الإغلاق. +## تطوير مساحة العمل غير المنشور + +خلفية زجاجية أصلية أكثر شفافية وتحكم مباشر بها، وإعداد أول تشغيل، وتخصيص بطاقات الرئيسية، ومتابعة مهام AI وGitHub Actions اختيارياً، وتنبيهات الاستهلاك وفحص الإصدارات. توقيع Apple وتصديقها مؤجّلان حتى تجهيز حساب المطوّر. [دليل الإعداد](Docs/INTEGRATIONS.md) · [نطاق التحقق](Docs/VALIDATION.md). + ## أدوات المطوّر والذكاء الاصطناعي تطوير غير منشور بعد 0.6.0: فعّل **Auto-refresh every minute** في قسم AI usage لتحديث حدود Codex باستمرار. القراءة المحلية مستقلة وتعمل كل 5 ثوانٍ؛ قد تتأخر الأرقام حتى يكتب المزوّد حدث الاستهلاك في سجلاته. diff --git a/README.md b/README.md index 8efacc1..d53c517 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,11 @@ account usage, system readings, notes, music, and task events are illustrative.* | Mac utilities | Current weather, Apple Translation, stock watchlist, music and lyrics, system readings, supported audio controls, window tiling, image conversion, capture, OCR, ZIP, calculator, Shortcuts, camera mirror, calendar and reminders | | Yours | Display selection, island dimensions, accent colors, motion, English or right-to-left Arabic, launch at login | +**Unreleased workspace improvements:** native clear glass and a transparency +control, first-run connection checks, customizable home cards, opt-in task +hooks and GitHub Actions tracking, usage alerts and stable-release checks. +[Setup and scope →](Docs/INTEGRATIONS.md) · [Validation →](Docs/VALIDATION.md) + **Unreleased AI usage improvements:** local logs refresh every five seconds. Enable **Auto-refresh every minute** in AI usage for recurring Codex account limits. Failed requests retry automatically and retain the last successful data. Local diff --git a/ROADMAP.md b/ROADMAP.md index 0c6b908..61cdbbb 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -10,6 +10,18 @@ visibility. English remains the default interface; Arabic remains optional. Advanced audio, hardware, and system integrations follow separate feasibility gates. +## Current development direction — 2026-11-02 + +The owner approved onboarding, project/agent activity, better AI summaries, +workspace presets, reliability work and a more transparent Liquid Glass +surface. These are being validated in the development branch after 0.6.0. +See [integration setup](Docs/INTEGRATIONS.md) and the +[validation matrix](Docs/VALIDATION.md). + +**Deferred by owner:** Developer ID signing and Apple notarization until an +Apple Developer account is ready. Release checks can be used now; unattended +installation remains deferred with the distribution trust work. + ## Current gaps - Visual polish is implemented, but screen configurations, sleep/wake, older @@ -17,8 +29,8 @@ gates. - Core service messages now follow the selected language. OS-provided errors and already-displayed errors or activity entries still need consistent handling when the language changes during a session. -- Cursor/Copilot, trustworthy cost reporting, and native agent-hook and - approval flows are incomplete or unimplemented. +- Cursor/Copilot, trustworthy cost reporting, and additional provider connectors are incomplete. Native task-state hooks are + observers; approvals remain in their original coding tools. - Daily integrations need account, permission, offline, and unsupported-device testing. - Developer-ID signing, notarization, and automatic updates are not diff --git a/Scripts/gallery/DemoData.swift b/Scripts/gallery/DemoData.swift index e3391ae..edf449d 100644 --- a/Scripts/gallery/DemoData.swift +++ b/Scripts/gallery/DemoData.swift @@ -10,7 +10,24 @@ import Foundation defaults.set(true, forKey: "aiTracking") defaults.set(true, forKey: "clipboardEnabled") defaults.set("aurora", forKey: "accentTheme") - return AppModel(startServices: false) + defaults.removeObject(forKey: "workspace") + defaults.set(true, forKey: "setupCompleted.v1") + defaults.set(false, forKey: "aiLiveAutoRefresh") + defaults.set(false, forKey: "automaticUpdateChecks") + defaults.set(false, forKey: "watchProjectActions") + let dev = DeveloperModel(scanUsage: { provider, _ in GalleryDemo.usageFixture(provider) }, fetchLive: { + CodexLiveSnapshot(primary: UsageWindow(usedPercent: 28, minutes: 300, resetsAt: Date().addingTimeInterval(3600)), secondary: UsageWindow(usedPercent: 42, minutes: 10080, resetsAt: Date().addingTimeInterval(86400)), lifetimeTokens: nil, fetchedAt: Date()) + }) + return AppModel(startServices: false, developer: dev) + } + nonisolated static func usageFixture(_ provider: AIProvider) -> UsageSnapshot { + var value = UsageSnapshot() + value.today = provider == .codex ? TokenTally(input: 142800, cached: 101200, output: 18400) : TokenTally(input: 48000, cached: 26000, output: 6500) + value.week = TokenTally(input: 780000, cached: 524000, output: 96000) + let day = Calendar.current.startOfDay(for: Date()) + value.daily = (0..<7).map { (Calendar.current.date(byAdding: .day, value: $0 - 6, to: day)!, 120000) } + value.fileCount = 7; value.scannedAt = Date(); value.lastEventAt = Date().addingTimeInterval(-30) + return value } static func apply(_ app: AppModel) { app.expanded = true; app.pinned = true; app.hoverEnabled = false diff --git a/Scripts/gallery/prepare.py b/Scripts/gallery/prepare.py index 1f4da09..ff1b6ef 100644 --- a/Scripts/gallery/prepare.py +++ b/Scripts/gallery/prepare.py @@ -15,7 +15,7 @@ s = p.read_text().replace('private let model = AppModel()', 'private let model = GalleryDemo.makeModel()') assert 'GalleryDemo.makeModel()' in s s = s.replace(' setupHotKey()', ' GalleryDemo.apply(model)') -for line in [' model.developer.start()\n', ' model.monitor.start()\n', ' model.weather.start()\n', ' model.tools.start()\n']: +for line in [' model.developer.start()\n', ' model.monitor.start()\n', ' model.weather.start()\n', ' model.tools.start()\n', ' model.updates.start()\n', ' model.project.start()\n']: assert line in s s = s.replace(line, '') # Keep the application's normal navigation callbacks intact. diff --git a/Scripts/measure.sh b/Scripts/measure.sh index 6e4a4be..44dc41a 100755 --- a/Scripts/measure.sh +++ b/Scripts/measure.sh @@ -1,20 +1,29 @@ #!/bin/zsh -# Samples CPU and memory of the running Notchest app. -# Usage: ./Scripts/measure.sh [seconds] [label] +# Samples an explicitly selected running app, retaining fractional CPU readings. +# Usage: NOTCHEST_PID=123 ./Scripts/measure.sh [seconds] [label] set -euo pipefail -DURATION="${1:-60}" -LABEL="${2:-sample}" -APP_PID=$(pgrep -x Notchest | head -1) -[[ -n "$APP_PID" ]] || { print "Notchest is not running"; exit 1 } -print "Sampling Notchest (pid $APP_PID) for ${DURATION}s — $LABEL" -CPU_SUM=0; RSS_MAX=0; N=0 -for _ in {1..$DURATION}; do - STATS=$(ps -o %cpu=,rss= -p "$APP_PID" | tr -s ' ' | sed 's/^ //') - CPU=${STATS%% *}; RSS=${STATS##* } - CPU_SUM=$(( CPU_SUM + ${CPU%.*} )); (( RSS > RSS_MAX )) && RSS_MAX=$RSS; N=$(( N + 1 )) - sleep 1 -done -print "label: $LABEL" -print "samples: $N" -print "avg_cpu_percent: $(( CPU_SUM / N ))" -print "peak_rss_mb: $(( RSS_MAX / 1024 ))" +python3 - "${1:-60}" "${2:-sample}" "${NOTCHEST_PID:-}" <<'PY' +import json, statistics, subprocess, sys, time +seconds=int(sys.argv[1]) +if not 1 <= seconds <= 3600: + raise SystemExit('Duration must be between 1 and 3600 seconds') +label=sys.argv[2] +pid=sys.argv[3] +if not pid: + found=subprocess.run(['pgrep','-x','Notchest'],capture_output=True,text=True).stdout.split() + if len(found)!=1: + raise SystemExit('Run one Notchest instance or set NOTCHEST_PID to the intended process') + pid=found[0] +if not pid.isdigit(): + raise SystemExit('Invalid process ID') +rows=[] +for _ in range(seconds): + start=time.monotonic() + response=subprocess.run(['ps','-o','%cpu=,rss=','-p',pid],capture_output=True,text=True,check=True) + values=response.stdout.split() + if len(values)!=2: + raise SystemExit('The process ended during sampling') + rows.append((float(values[0]),int(values[1]))) + time.sleep(max(0,1-(time.monotonic()-start))) +print(json.dumps({'label':label,'pid':int(pid),'samples':len(rows),'average_cpu_percent':round(statistics.mean(x[0] for x in rows),2),'peak_rss_mb':round(max(x[1] for x in rows)/1024,2)},indent=2)) +PY diff --git a/Sources/Notchest/ActivityCenter.swift b/Sources/Notchest/ActivityCenter.swift index 52ec939..aa4c7af 100644 --- a/Sources/Notchest/ActivityCenter.swift +++ b/Sources/Notchest/ActivityCenter.swift @@ -20,6 +20,8 @@ struct ActivityRequest: Decodable { var message: String? var state: String? var progress: Double? + var source: String? + var project: String? } enum ActivityHTTP { @@ -54,7 +56,9 @@ enum ActivityHTTP { !request.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, request.title.count <= 100, (request.message?.count ?? 0) <= 500, (request.id?.count ?? 0) <= 80, - ["running", "success", "failure", "info"].contains(request.state ?? "info"), + ["running", "waiting", "success", "failure", "info"].contains(request.state ?? "info"), + request.source.map({ ["Codex", "Claude Code"].contains($0) }) ?? true, + (request.project?.count ?? 0) <= 100, request.progress.map({ $0.isFinite && (0...1).contains($0) }) ?? true else { return .failure(400) } return .success(request) } @@ -148,16 +152,29 @@ final class ActivityCenter: ObservableObject { @Published var activities: [NotchestActivity] = [] @Published var apiEnabled = false @Published var apiError: String? + @Published var hookMessage: ServiceText? private var server: LocalActivityServer? + private let runtimeFile: URL private(set) var token = "" var onRecord: ((NotchestActivity) -> Void)? + init(runtimeDirectory: URL = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Library/Application Support/Notchest/Runtime")) { + runtimeFile = runtimeDirectory.appendingPathComponent("activity.json") + } + func startAPI() { guard server == nil else { return } var bytes = [UInt8](repeating: 0, count: 32) guard SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) == errSecSuccess else { apiError = "Could not generate a secure token"; return } token = Data(bytes).base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "") let server = LocalActivityServer(token: token) + server.onReady = { [weak self, weak server] in + Task { @MainActor in + guard let self, self.server === server else { return } + do { try PrivateFile.write(JSONSerialization.data(withJSONObject: ["port": 9999, "token": self.token]), to: self.runtimeFile) } + catch { self.apiError = error.localizedDescription; self.stopAPI() } + } + } server.onActivity = { [weak self] request in Task { @MainActor in self?.accept(request) } } server.onFailure = { [weak self, weak server] error in Task { @MainActor in @@ -177,20 +194,37 @@ final class ActivityCenter: ObservableObject { func stopAPI() { server?.stop() server = nil + if let data = try? Data(contentsOf: runtimeFile), let value = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any], value["token"] as? String == token { + try? FileManager.default.removeItem(at: runtimeFile) + } token = "" apiEnabled = false } func accept(_ request: ActivityRequest) { - record(id: request.id ?? UUID().uuidString, title: request.title, message: request.message ?? "", state: request.state ?? "info", progress: request.progress) + record(id: request.id ?? UUID().uuidString, title: request.source.map { $0 + (request.project.map { " · " + $0 } ?? "") } ?? request.title, message: request.message ?? "", state: request.state ?? "info", progress: request.progress, kind: request.source == nil ? "message" : "agent") + } + + func configureHooks(_ provider: AgentIntegration, remove: Bool = false, arabic: Bool) { + guard let helper = HookInstaller.helper else { hookMessage = ServiceText("أعد بناء حزمة التطبيق لتوفير أداة الربط", "Rebuild the application bundle to include the integration helper"); return } + let alert = NSAlert() + alert.messageText = remove ? (arabic ? "إزالة ربط \(provider.title)؟" : "Remove \(provider.title) integration?") : (arabic ? "ربط \(provider.title)؟" : "Connect \(provider.title)?") + alert.informativeText = arabic ? "ثبّت الربط بعد نقل التطبيق إلى Applications. يتطلب إصداراً يدعم الخطافات. نعدّل ملف إعداداتها مع حفظ نسخة احتياطية محلية. الربط يرسل حالة المهمة واسم المشروع إلى Notchest على هذا الجهاز. تبقى الموافقات في الأداة الأصلية. أعد تشغيل الأداة وراجع الخطافات فيها عند الطلب." : "Install after moving the app to Applications. Requires a tool version with hooks support. Updates the hooks configuration and saves a local backup. Hooks send task state and project name to Notchest on this Mac. Approvals stay in the original tool. Restart the tool and review its hooks when prompted." + alert.addButton(withTitle: arabic ? "متابعة" : "Continue"); alert.addButton(withTitle: arabic ? "إلغاء" : "Cancel") + guard alert.runModal() == .alertFirstButtonReturn else { return } + do { + try HookInstaller.install(provider, helper: helper, configuration: provider.configuration(), remove: remove) + hookMessage = remove ? ServiceText("أُزيل ربط Notchest فقط؛ أعد تشغيل الأداة", "Removed only the Notchest hooks; restart the tool") : ServiceText("تم الربط. فعّل الواجهة المحلية وأعد تشغيل الأداة وراجع الخطافات فيها عند الطلب.", "Connected. Enable the local API, restart the tool, and review its hooks when prompted.") + } catch { hookMessage = ServiceText("تعذّر تعديل الإعدادات؛ لم نستبدل الملف غير الصالح", "Could not update settings; an invalid configuration is never overwritten") } } func record(id: String = UUID().uuidString, title: String, message: String, state: String = "info", progress: Double? = nil, url: URL? = nil, kind: String = "message") { + let previous = activities.first { $0.id == id } activities.removeAll { $0.id == id } let item = NotchestActivity(id: id, title: title, message: message, state: state, progress: progress, url: url, kind: kind) activities.insert(item, at: 0) activities = Array(activities.prefix(40)) - onRecord?(item) + if kind != "agent" || previous?.state != state { onRecord?(item) } } func copyExample() { diff --git a/Sources/Notchest/ActivityView.swift b/Sources/Notchest/ActivityView.swift index 28b2cf4..115c0f1 100644 --- a/Sources/Notchest/ActivityView.swift +++ b/Sources/Notchest/ActivityView.swift @@ -6,80 +6,121 @@ struct ActivityView: View { @ObservedObject private var monitor: SystemMonitor init(app: AppModel, activity: ActivityCenter) { self.app = app; self.activity = activity; self.monitor = app.monitor } var body: some View { - VStack(spacing: 10) { - HStack { - VStack(alignment: .leading, spacing: 4) { - Text(app.text("نشاط أدواتك", "Your activity")) - .font(.system(size: 16, weight: .semibold, design: .rounded)) - Text(app.text("إشعارات محلية من البرامج والمهام.", "Local updates from scripts and tasks.")) - .font(.system(size: 10)).foregroundStyle(.white.opacity(0.6)) - } - Spacer() - if !activity.activities.isEmpty { - Button(app.text("مسح", "Clear")) { activity.activities.removeAll() } - .buttonStyle(.plain).font(.system(size: 10)).foregroundStyle(.white.opacity(0.5)) - } - } - HStack(spacing: 10) { - Image(systemName: "network").foregroundStyle(notchestAccent) - VStack(alignment: .leading, spacing: 4) { - Text(app.text("واجهة محلية للمطوّر", "Local developer API")).font(.system(size: 11, weight: .medium)) - Text(activity.apiEnabled ? app.text("تعمل على 127.0.0.1 فقط • الرمز يتغيّر عند الإيقاف", "127.0.0.1 only • token rotates when stopped") : app.text("متوقفة افتراضيًا؛ تتيح للسكربت إرسال نشاط", "Off by default; lets scripts post an activity")) - .font(.system(size: 9)).foregroundStyle(.white.opacity(0.6)) + ScrollView { + VStack(spacing: 11) { + HStack { + VStack(alignment: .leading, spacing: 4) { + Text(app.text("نشاط مشاريعك", "Your projects, in motion")).font(.system(size: 17, weight: .semibold, design: .rounded)) + Text(app.text("المهام والنتائج في مكان واحد.", "Tasks and results, together.")).font(.system(size: 10)).foregroundStyle(.white.opacity(0.7)) + } + Spacer() + if !activity.activities.isEmpty { Button(app.text("مسح السجل", "Clear history")) { activity.activities.removeAll() }.buttonStyle(.plain).font(.system(size: 10)) } } - Spacer() - if activity.apiEnabled { - Button(app.text("نسخ مثال", "Copy example")) { activity.copyExample(); app.showToast(app.text("نُسخ المثال والرمز", "Example and token copied")) } - .buttonStyle(.plain).font(.system(size: 10)).foregroundStyle(notchestAccent) + ProjectActivityCard(app: app) + VStack(alignment: .leading, spacing: 10) { + HStack { + Label(app.text("ربط مهام AI محلياً", "Connect AI tasks locally"), systemImage: "waveform.path").font(.system(size: 12, weight: .semibold)) + Spacer() + Toggle(app.text("الواجهة المحلية", "Local API"), isOn: Binding(get: { activity.apiEnabled }, set: { $0 ? activity.startAPI() : activity.stopAPI() })).font(.system(size: 10)).toggleStyle(.switch).controlSize(.mini) + } + Text(app.text("الربط اختياري؛ يعرض حالة المهمة واسم المشروع. عند طلب موافقة، ارجع إلى أداة البرمجة.", "Optional hooks show task state and project name. Return to your coding tool for approvals.")).font(.system(size: 10)).foregroundStyle(.white.opacity(0.7)) + HStack(spacing: 10) { + ForEach(AgentIntegration.allCases) { provider in + Menu(provider.title) { + Button(app.text("تثبيت الربط…", "Install integration…")) { activity.configureHooks(provider, arabic: app.arabic) } + Button(app.text("إزالة الربط…", "Remove integration…")) { activity.configureHooks(provider, remove: true, arabic: app.arabic) } + }.font(.system(size: 11)) + } + Spacer() + if activity.apiEnabled { + Button(app.text("نسخ مثال للسكربتات", "Copy script example")) { activity.copyExample(); app.showToast(app.text("نُسخ المثال والرمز", "Example and token copied")) }.font(.system(size: 10)).buttonStyle(.plain).foregroundStyle(notchestAccent) + } + } + if let message = activity.hookMessage { Text(message.resolved(arabicUI: app.arabic)).font(.system(size: 10)).foregroundStyle(notchestAccent) } + if let error = activity.apiError { Text(error).font(.system(size: 10)).foregroundStyle(.orange) } + }.padding(13).notchestPanel(cornerRadius: 14) + HStack(spacing: 12) { + Toggle(app.text("التنزيلات", "Downloads"), isOn: $monitor.watchDownloads) + Toggle(app.text("الأقراص", "Drives"), isOn: $monitor.watchVolumes) + Toggle("Caps Lock", isOn: $monitor.watchCapsLock) + Spacer() + }.font(.system(size: 10)).toggleStyle(.checkbox) + if let problem = monitor.problem { Text(problem).font(.system(size: 9)).foregroundStyle(.orange) } + if activity.activities.isEmpty { + Text(app.text("ستظهر حالات المهام هنا بعد ربط أدواتك.", "Task updates appear here after connecting your tools.")).font(.system(size: 11)).foregroundStyle(.white.opacity(0.65)).padding(20) } - Toggle(app.text("واجهة المطوّر", "Developer API"), isOn: Binding(get: { activity.apiEnabled }, set: { $0 ? activity.startAPI() : activity.stopAPI() })) - .labelsHidden().toggleStyle(.switch).controlSize(.small).tint(notchestAccent) - }.padding(12).notchestPanel(cornerRadius: 12) - if let error = activity.apiError { Text(error).font(.system(size: 10)).foregroundStyle(.orange).frame(maxWidth: .infinity, alignment: .leading) } - HStack(spacing: 12) { - Toggle(app.text("التنزيلات", "Downloads"), isOn: $monitor.watchDownloads) - Toggle(app.text("الأقراص", "Drives"), isOn: $monitor.watchVolumes) - Toggle("Caps Lock", isOn: $monitor.watchCapsLock) - }.font(.system(size: 10)).toggleStyle(.checkbox) - if let problem = monitor.problem { Text(problem).font(.system(size: 9)).foregroundStyle(.orange) } - ScrollView { LazyVStack(spacing: 7) { - if activity.activities.isEmpty { - VStack(spacing: 8) { - Image(systemName: "waveform.path").font(.system(size: 23, weight: .light)).foregroundStyle(notchestAccent.opacity(0.7)) - Text(app.text("ستظهر الأنشطة الجديدة هنا.", "New activities will appear here.")) - .font(.system(size: 11)).foregroundStyle(.white.opacity(0.6)) - }.frame(maxWidth: .infinity).padding(25) - } ForEach(activity.activities) { item in HStack(spacing: 10) { - Image(systemName: icon(item.state)).foregroundStyle(color(item.state)).frame(width: 23) + Image(systemName: icon(item.state)).foregroundStyle(item.state == "failure" || item.state == "waiting" ? .orange : notchestAccent).frame(width: 23) VStack(alignment: .leading, spacing: 4) { Text(item.title).font(.system(size: 11, weight: .medium)) - if !item.message.isEmpty { Text(item.message).font(.system(size: 10)).foregroundStyle(.white.opacity(0.65)).lineLimit(2) } + if item.kind == "agent" { Text(stateTitle(item.state, app: app)).font(.system(size: 10)).foregroundStyle(.white.opacity(0.75)) } + if !item.message.isEmpty { Text(item.message).font(.system(size: 10)).foregroundStyle(.white.opacity(0.7)).lineLimit(2) } if let progress = item.progress { ProgressView(value: progress).tint(notchestAccent) } } Spacer() if let url = item.url { if item.kind == "volume" { - Button { - do { try NSWorkspace.shared.unmountAndEjectDevice(at: url); app.showToast(app.text("يمكن فصل القرص", "Safe to disconnect")) } - catch { app.showToast(error.localizedDescription) } - } label: { Image(systemName: "eject") } - .buttonStyle(.plain).help(app.text("إخراج القرص", "Eject drive")) + Button { do { try NSWorkspace.shared.unmountAndEjectDevice(at: url); app.showToast(app.text("يمكن فصل القرص", "Safe to disconnect")) } catch { app.showToast(error.localizedDescription) } } label: { Image(systemName: "eject") }.buttonStyle(.plain) } - Button { NSWorkspace.shared.activateFileViewerSelecting([url]) } label: { Image(systemName: "folder") } - .buttonStyle(.plain).help(app.text("إظهار في Finder", "Reveal in Finder")) + Button { if url.scheme == "https" { NSWorkspace.shared.open(url) } else { NSWorkspace.shared.activateFileViewerSelecting([url]) } } label: { Image(systemName: url.scheme == "https" ? "arrow.up.right" : "folder") }.buttonStyle(.plain).help(app.text("فتح النتيجة", "Open result")) } - Text(item.updated, style: .time).font(.system(size: 9)).foregroundStyle(.white.opacity(0.3)) - }.padding(11).notchestPanel(cornerRadius: 10) + Text(item.updated, style: .relative).font(.system(size: 9)).foregroundStyle(.white.opacity(0.55)) + }.padding(11).notchestPanel(cornerRadius: 12) } } - } + }.padding(.horizontal, 3).padding(.bottom, 8) } } private func icon(_ state: String) -> String { - switch state { case "running": return "hourglass"; case "success": return "checkmark.circle.fill"; case "failure": return "exclamationmark.circle.fill"; default: return "bell.badge" } + switch state { case "running": return "hourglass"; case "waiting": return "hand.raised.fill"; case "success": return "checkmark.circle.fill"; case "failure": return "exclamationmark.circle.fill"; default: return "bell.badge" } + } +} + +@MainActor private func stateTitle(_ state: String, app: AppModel) -> String { + switch state { + case "running": return app.text("قيد العمل", "Working") + case "waiting": return app.text("بانتظار تدخّلك في الأداة", "Needs your attention in the tool") + case "success": return app.text("اكتملت الجولة", "Turn completed") + case "failure": return app.text("تعذّر التنفيذ", "Failed") + default: return app.text("متوقف أو منتهٍ", "Stopped or finished") + } +} + +private struct ProjectActivityCard: View { + @ObservedObject var app: AppModel + @ObservedObject private var project: ProjectMonitor + @ObservedObject private var dev: DeveloperModel + init(app: AppModel) { self.app = app; project = app.project; dev = app.developer } + var body: some View { + VStack(alignment: .leading, spacing: 10) { + HStack { + Image(systemName: "folder").foregroundStyle(notchestAccent) + Button(dev.workingDirectory.lastPathComponent) { dev.chooseWorkingDirectory() }.font(.system(size: 12, weight: .semibold)).buttonStyle(.plain).help(app.text("اختر المشروع", "Choose project")) + Spacer() + if project.loading { ProgressView().controlSize(.mini) } + Button { project.refresh() } label: { Image(systemName: "arrow.clockwise") }.buttonStyle(.plain).disabled(!project.enabled || project.loading).help(app.text("تحديث", "Refresh")) + Toggle("GitHub Actions", isOn: $project.enabled).font(.system(size: 10)).toggleStyle(.switch).controlSize(.mini) + } + if let error = project.error { Text(error.resolved(arabicUI: app.arabic)).font(.system(size: 10)).foregroundStyle(.orange) } + if project.enabled { + ForEach(project.runs.prefix(4)) { run in + Button { NSWorkspace.shared.open(run.url) } label: { + HStack { + Image(systemName: run.activityState == "success" ? "checkmark.circle.fill" : run.activityState == "failure" ? "xmark.circle.fill" : "circle.dotted").foregroundStyle(run.activityState == "failure" ? .orange : notchestAccent) + Text(run.displayTitle.isEmpty ? run.name : run.displayTitle).lineLimit(1) + Spacer() + Text(run.headBranch).foregroundStyle(.white.opacity(0.65)).lineLimit(1) + Image(systemName: "arrow.up.right") + }.font(.system(size: 10)) + }.buttonStyle(.plain) + } + if project.runs.isEmpty && !project.loading && project.error == nil { Text(app.text("لم نجد عمليات في هذا المستودع.", "No workflow runs found for this repository.")).font(.system(size: 10)).foregroundStyle(.white.opacity(0.65)) } + HStack { Text(app.text("تحديث كل دقيقة", "Refreshes every minute")); Spacer(); if let checked = project.checkedAt { Text(checked, style: .relative) } }.font(.system(size: 9)).foregroundStyle(.white.opacity(0.6)) + } else { + Text(app.text("اختر مستودعاً وفعّل المتابعة لعرض نتائج البناء والاختبارات من GitHub.", "Choose a repository and enable tracking to see GitHub build and test results.")).font(.system(size: 10)).foregroundStyle(.white.opacity(0.7)) + } + }.padding(13).notchestPanel(cornerRadius: 14) } - private func color(_ state: String) -> Color { state == "failure" ? .orange : notchestAccent.opacity(0.8) } } diff --git a/Sources/Notchest/AppModel.swift b/Sources/Notchest/AppModel.swift index 8909378..656472d 100644 --- a/Sources/Notchest/AppModel.swift +++ b/Sources/Notchest/AppModel.swift @@ -65,12 +65,22 @@ struct ShelfItem: Identifiable, Codable { @MainActor final class AppModel: ObservableObject { - let developer = DeveloperModel() + let developer: DeveloperModel let tools = NativeTools() let activity = ActivityCenter() let monitor = SystemMonitor() let weather = WeatherModel() let stocks = StocksModel() + let setup = SetupModel() + let updates = UpdateModel() + let project = ProjectMonitor() + @Published var showingSetup = false + @Published var setupCompleted: Bool { + didSet { defaults.set(setupCompleted, forKey: "setupCompleted.v1") } + } + @Published var workspace: WorkspacePreferences { + didSet { if let data = try? JSONEncoder().encode(workspace.validated()) { defaults.set(data, forKey: "workspace") } } + } @Published var activityFlash: NotchestActivity? @Published var display = IslandDisplay() @Published var availableDisplays: [NotchestDisplayOption] = [] @@ -134,8 +144,11 @@ final class AppModel: ObservableObject { private var toastTask: Task? private var activityFlashTask: Task? - init(defaults: UserDefaults = .standard, startServices: Bool = true) { + init(defaults: UserDefaults = .standard, startServices: Bool = true, developer: DeveloperModel? = nil) { self.defaults = defaults + self.developer = developer ?? DeveloperModel(defaults: defaults) + setupCompleted = defaults.bool(forKey: "setupCompleted.v1") + workspace = (defaults.data(forKey: "workspace").flatMap { try? JSONDecoder().decode(WorkspacePreferences.self, from: $0) } ?? WorkspacePreferences()).validated() selectedDisplayID = defaults.string(forKey: "selectedDisplayID") ?? "auto" accentTheme = defaults.string(forKey: "accentTheme") ?? "aurora" launchAtLogin = SMAppService.mainApp.status == .enabled @@ -203,11 +216,18 @@ final class AppModel: ObservableObject { func resetStopwatch() { stopwatchStarted = nil; stopwatchElapsed = 0 } func select(_ tab: NotchestTab) { + showingSetup = false self.tab = tab paletteVisible = false expanded = true } + func finishSetup() { + setupCompleted = true + showingSetup = false + select(.home) + } + func toggleTimer() { now = Date() if clock.isRunning { clock.pause(at: now) } else { clock.start(at: now) } diff --git a/Sources/Notchest/DeveloperModel.swift b/Sources/Notchest/DeveloperModel.swift index 32be884..ddf2b29 100644 --- a/Sources/Notchest/DeveloperModel.swift +++ b/Sources/Notchest/DeveloperModel.swift @@ -58,9 +58,15 @@ struct UsageRefreshSchedule { @MainActor final class DeveloperModel: ObservableObject { var onCommandFinished: ((Int32) -> Void)? + var onUsageAlert: ((UsageLimitAlert) -> Void)? @Published var section: DeveloperSection = .usage @Published var provider: AIProvider = .codex @Published var usage = UsageSnapshot() + @Published private(set) var usageByProvider: [AIProvider: UsageSnapshot] = [:] + @Published var usageAlertsEnabled: Bool { + didSet { defaults.set(usageAlertsEnabled, forKey: "usageAlertsEnabled") } + } + private var alertPolicy = UsageAlertPolicy() @Published var refreshing = false @Published var liveCodex: CodexLiveSnapshot? @Published var liveCodexLoading = false @@ -77,7 +83,7 @@ final class DeveloperModel: ObservableObject { didSet { defaults.set(trackingEnabled, forKey: "aiTracking") if trackingEnabled { refreshUsage() } - else { cancelUsageRefresh(); usage = UsageSnapshot(); localReadFailed = false } + else { cancelUsageRefresh(); usage = UsageSnapshot(); usageByProvider = [:]; localReadFailed = false } } } @Published var workbenchInput = "" @@ -87,7 +93,9 @@ final class DeveloperModel: ObservableObject { @Published var commandOutput = "" @Published var commandRunning = false @Published var commandExit: Int32? - @Published var workingDirectory = FileManager.default.homeDirectoryForCurrentUser + @Published var workingDirectory = FileManager.default.homeDirectoryForCurrentUser { + didSet { defaults.set(workingDirectory.path, forKey: "workingDirectory") } + } @Published var gitOutput = "" @Published var gitBusy = false @Published var showingPulls = false @@ -117,12 +125,17 @@ final class DeveloperModel: ObservableObject { self.defaults = defaults self.scanUsage = scanUsage self.fetchLive = fetchLive + usageAlertsEnabled = defaults.bool(forKey: "usageAlertsEnabled") trackingEnabled = defaults.object(forKey: "aiTracking") as? Bool ?? true liveAutoRefreshEnabled = defaults.bool(forKey: "aiLiveAutoRefresh") + workingDirectory = defaults.string(forKey: "workingDirectory").map { URL(fileURLWithPath: $0) } ?? FileManager.default.homeDirectoryForCurrentUser snippets = defaults.data(forKey: "snippets").flatMap { try? JSONDecoder().decode([Snippet].self, from: $0) } ?? [] } var usageDirectory: URL { + directory(for: provider) + } + func directory(for provider: AIProvider) -> URL { if let path = defaults.string(forKey: "usageDirectory.\(provider.rawValue)") { return URL(fileURLWithPath: path) } return provider.defaultDirectory } @@ -180,7 +193,7 @@ final class DeveloperModel: ObservableObject { func refreshAutomatically(at date: Date = Date()) { refreshUsage() - if liveAutoRefreshEnabled, provider == .codex, date >= liveSchedule.nextAttempt { refreshLiveCodex() } + if liveAutoRefreshEnabled, date >= liveSchedule.nextAttempt { refreshLiveCodex() } } func resumeUsageUpdates() { @@ -214,32 +227,48 @@ final class DeveloperModel: ObservableObject { usageGeneration = generation let provider = provider let directory = usageDirectory + let directories = Dictionary(uniqueKeysWithValues: AIProvider.allCases.map { ($0, self.directory(for: $0)) }) let scan = scanUsage usageTask = Task { [weak self] in - let worker = Task.detached(priority: .utility) { scan(provider, directory) } - let snapshot = await withTaskCancellationHandler(operation: { await worker.value }, onCancel: { worker.cancel() }) + let worker = Task.detached(priority: .utility) { + var result: [AIProvider: UsageSnapshot] = [:] + for item in AIProvider.allCases { + guard !Task.isCancelled else { break } + result[item] = scan(item, directories[item]!) + } + return result + } + let snapshots = await withTaskCancellationHandler(operation: { await worker.value }, onCancel: { worker.cancel() }) guard let self else { return } guard self.usageGeneration == generation else { return } defer { self.refreshing = false } guard !Task.isCancelled, self.provider == provider, self.usageDirectory == directory, self.trackingEnabled else { return } + for (item, snapshot) in snapshots { + let failed = snapshot.missingDirectory || snapshot.unreadableFiles > 0 || (snapshot.partial && snapshot.fileCount == 0) + if failed, snapshot.fileCount == 0, (self.usageByProvider[item]?.fileCount ?? 0) > 0 { continue } + self.usageByProvider[item] = snapshot + } + guard let snapshot = snapshots[provider] else { return } self.localReadFailed = snapshot.missingDirectory || snapshot.unreadableFiles > 0 || (snapshot.partial && snapshot.fileCount == 0) if self.localReadFailed, snapshot.fileCount == 0, self.usage.fileCount > 0 { return } self.usage = snapshot + if self.usageAlertsEnabled, !self.liveAutoRefreshEnabled, provider == .codex { + self.alertPolicy.evaluate([snapshot.primary, snapshot.secondary].compactMap { $0 }).forEach { self.onUsageAlert?($0) } + } } } func changeProvider(_ provider: AIProvider) { guard provider != self.provider else { refreshAllUsage(); return } cancelUsageRefresh() - cancelLiveRefresh() self.provider = provider - usage = UsageSnapshot() + usage = usageByProvider[provider] ?? UsageSnapshot() localReadFailed = false refreshAutomatically() } func refreshLiveCodex() { - guard provider == .codex, !liveCodexLoading else { return } + guard !liveCodexLoading else { return } liveCodexLoading = true let generation = UUID() liveGeneration = generation @@ -253,6 +282,7 @@ final class DeveloperModel: ObservableObject { case .success(let snapshot): self.liveCodex = snapshot; self.liveError = nil self.liveSchedule.succeeded(at: Date()) + if self.usageAlertsEnabled { self.alertPolicy.evaluate([snapshot.primary, snapshot.secondary].compactMap { $0 }).forEach { self.onUsageAlert?($0) } } case .failure(let error): self.liveError = (error as? CodexLiveError)?.text ?? CodexLiveError.failed.text self.liveSchedule.failed(at: Date()) @@ -274,6 +304,7 @@ final class DeveloperModel: ObservableObject { func setUsageDirectory(_ url: URL) { cancelUsageRefresh() defaults.set(url.path, forKey: "usageDirectory.\(provider.rawValue)") + usageByProvider[provider] = nil usage = UsageSnapshot(); localReadFailed = false refreshUsage() } diff --git a/Sources/Notchest/DeveloperView.swift b/Sources/Notchest/DeveloperView.swift index 4600bfd..1a74d1d 100644 --- a/Sources/Notchest/DeveloperView.swift +++ b/Sources/Notchest/DeveloperView.swift @@ -40,16 +40,22 @@ struct DeveloperView: View { private var usage: some View { ScrollView { VStack(spacing: 9) { - HStack(spacing: 8) { + HStack(spacing: 9) { ForEach(AIProvider.allCases) { provider in + let snapshot = dev.usageByProvider[provider] Button { dev.changeProvider(provider) } label: { - HStack(spacing: 6) { - Circle().fill(dev.provider == provider ? notchestAccent : .white.opacity(0.2)).frame(width: 5, height: 5) - Text(provider.rawValue).font(.system(size: 12, weight: .semibold)) - }.padding(.horizontal, 12).padding(.vertical, 8) - .background(dev.provider == provider ? .white.opacity(0.08) : .clear, in: RoundedRectangle(cornerRadius: 9)) + VStack(alignment: .leading, spacing: 6) { + HStack { Text(provider.rawValue).font(.system(size: 12, weight: .semibold)); Spacer(); if dev.provider == provider { Image(systemName: "checkmark.circle.fill").foregroundStyle(notchestAccent) } } + Text(usageSummaryStatus(snapshot)) + .font(.system(size: 11)).foregroundStyle(.white.opacity(0.8)) + if let date = snapshot?.scannedAt { (Text(app.text("آخر قراءة: ", "Checked: ")) + Text(date, style: .relative)).font(.system(size: 9)).foregroundStyle(.white.opacity(0.65)) } + }.padding(12).frame(maxWidth: .infinity, alignment: .leading).notchestPanel(cornerRadius: 14, tint: dev.provider == provider ? notchestAccent : nil) }.buttonStyle(.plain) } + } + HStack(spacing: 8) { + Text(dev.provider.rawValue).font(.system(size: 11, weight: .semibold)) + Toggle(app.text("تنبيهات Codex عند 80% و95%", "Codex alerts at 80% and 95%"), isOn: $dev.usageAlertsEnabled).toggleStyle(.checkbox).font(.system(size: 10)) Spacer() if dev.refreshing { ProgressView().controlSize(.mini) } Toggle(app.text("قراءة الإحصاءات المحلية", "Read local usage"), isOn: $dev.trackingEnabled).labelsHidden().toggleStyle(.switch).controlSize(.mini).tint(notchestAccent) @@ -127,6 +133,18 @@ struct DeveloperView: View { .onAppear { dev.refreshAutomatically() } } + private func usageSummaryStatus(_ snapshot: UsageSnapshot?) -> String { + guard dev.trackingEnabled else { return app.text("القراءة متوقفة", "Tracking paused") } + guard let snapshot else { return app.text("بانتظار القراءة", "Waiting for scan") } + if snapshot.missingDirectory { return app.text("اختر مجلّد السجلات", "Choose log folder") } + if snapshot.fileCount == 0 { + if snapshot.unreadableFiles > 0 { return app.text("تعذّرت قراءة السجلات", "Could not read logs") } + if snapshot.partial { return app.text("تجاوزت حدود القراءة", "Reading limits exceeded") } + return app.text("لا توجد سجلات استخدام", "No usage logs yet") + } + return app.text("\(short(snapshot.today.total)) رموز اليوم", "\(short(snapshot.today.total)) tokens today") + } + /// Live account limits come from the Codex CLI connection and must stay /// visible whether or not local log reading is enabled or logs exist. private var liveLimits: some View { diff --git a/Sources/Notchest/HookIntegration.swift b/Sources/Notchest/HookIntegration.swift new file mode 100644 index 0000000..a8b29f7 --- /dev/null +++ b/Sources/Notchest/HookIntegration.swift @@ -0,0 +1,79 @@ +import Foundation +import Darwin + +/// Writes token/config files atomically with owner-only permissions, including backups. +enum PrivateFile { + static func write(_ data: Data, to url: URL) throws { + let fm = FileManager.default + try fm.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) + let temporary = url.deletingLastPathComponent().appendingPathComponent(".notchest-\(UUID())") + let fd = open(temporary.path, O_WRONLY | O_CREAT | O_EXCL, 0o600) + guard fd >= 0 else { throw CocoaError(.fileWriteNoPermission) } + let handle = FileHandle(fileDescriptor: fd, closeOnDealloc: true) + defer { try? handle.close(); try? fm.removeItem(at: temporary) } + try handle.write(contentsOf: data) + guard fsync(fd) == 0, rename(temporary.path, url.path) == 0 else { throw CocoaError(.fileWriteUnknown) } + } +} + +enum AgentIntegration: String, CaseIterable, Identifiable { + case codex, claude + var id: String { rawValue } + var title: String { self == .codex ? "Codex" : "Claude Code" } + func configuration(home: URL = FileManager.default.homeDirectoryForCurrentUser, environment: [String: String] = ProcessInfo.processInfo.environment) -> URL { + if self == .codex { + return (environment["CODEX_HOME"].map { URL(fileURLWithPath: $0) } ?? home.appendingPathComponent(".codex")).appendingPathComponent("hooks.json") + } + return (environment["CLAUDE_CONFIG_DIR"].map { URL(fileURLWithPath: $0) } ?? home.appendingPathComponent(".claude")).appendingPathComponent("settings.json") + } +} + +enum HookInstaller { + static var helper: URL? { + let url = Bundle.main.executableURL?.deletingLastPathComponent().appendingPathComponent("NotchestCommand") + return url.flatMap { FileManager.default.isExecutableFile(atPath: $0.path) ? $0 : nil } + } + static func shellQuote(_ text: String) -> String { "'" + text.replacingOccurrences(of: "'", with: "'\\''") + "'" } + static func isOwned(_ item: [String: Any], provider: AgentIntegration) -> Bool { + (item["hooks"] as? [[String: Any]] ?? []).contains { + guard let command = $0["command"] as? String else { return false } + return command.contains("NotchestCommand") && command.hasSuffix("--activity-hook " + provider.rawValue) + } + } + @discardableResult static func install(_ provider: AgentIntegration, helper: URL, configuration: URL, remove: Bool = false) throws -> URL? { + let fm = FileManager.default + if let type = try? fm.attributesOfItem(atPath: configuration.path)[.type] as? FileAttributeType, type != .typeRegular { throw CocoaError(.fileReadInvalidFileName) } + let original = fm.fileExists(atPath: configuration.path) ? try Data(contentsOf: configuration) : nil + var root: [String: Any] = [:] + if let original { + guard original.count <= 2_000_000, let parsed = try JSONSerialization.jsonObject(with: original) as? [String: Any] else { throw CocoaError(.propertyListReadCorrupt) } + root = parsed + } + if let value = root["hooks"], !(value is [String: Any]) { throw CocoaError(.propertyListReadCorrupt) } + var hooks = root["hooks"] as? [String: Any] ?? [:] + for event in Array(hooks.keys) { + guard let entries = hooks[event] as? [[String: Any]] else { throw CocoaError(.propertyListReadCorrupt) } + let kept = entries.filter { !isOwned($0, provider: provider) } + if kept.isEmpty { hooks.removeValue(forKey: event) } else { hooks[event] = kept } + } + if !remove { + let events = ["UserPromptSubmit", "PermissionRequest", "PreToolUse", "PostToolUse", "Stop", "SessionEnd"] + (provider == .codex ? ["Interrupt"] : ["Notification"]) + for event in events { + var entry: [String: Any] = ["hooks": [["type": "command", "command": shellQuote(helper.path) + " --activity-hook " + provider.rawValue, "timeout": 2]]] + if event == "Notification" { entry["matcher"] = "permission_prompt" } + var entries = hooks[event] as? [[String: Any]] ?? [] + entries.append(entry); hooks[event] = entries + } + } + root["hooks"] = hooks + let data = try JSONSerialization.data(withJSONObject: root, options: [.prettyPrinted, .sortedKeys]) + guard data != original else { return nil } + var backup: URL? + if let original { + let url = configuration.appendingPathExtension("notchest-backup-\(UUID().uuidString)") + try PrivateFile.write(original, to: url); backup = url + } + try PrivateFile.write(data, to: configuration) + return backup + } +} diff --git a/Sources/Notchest/IslandSettingsView.swift b/Sources/Notchest/IslandSettingsView.swift index 07a1e70..ca00675 100644 --- a/Sources/Notchest/IslandSettingsView.swift +++ b/Sources/Notchest/IslandSettingsView.swift @@ -34,6 +34,10 @@ struct IslandSettingsView: View { } languageRow + WorkspaceSettingsView(app: model) + Button(model.text("إعداد الاتصالات والأدوات", "Set up connections & tools")) { model.showingSetup = true } + .buttonStyle(.plain).font(.system(size: 11)).foregroundStyle(notchestAccent) + UpdateSettingsView(app: model) HStack(alignment: .top, spacing: 10) { dimensionCard( diff --git a/Sources/Notchest/IslandSizing.swift b/Sources/Notchest/IslandSizing.swift index 57fab39..082c8d7 100644 --- a/Sources/Notchest/IslandSizing.swift +++ b/Sources/Notchest/IslandSizing.swift @@ -59,7 +59,7 @@ struct IslandDisplay: Equatable { var notchWidth: CGFloat = 120 var safeTop: CGFloat = 0 - var minimumCompactWidth: CGFloat { min(max(1, frame.width - 16), max(200, notchWidth + 84)) } + var minimumCompactWidth: CGFloat { min(max(1, frame.width - 16), max(200, notchWidth + 120)) } var minimumCompactHeight: CGFloat { min(max(1, frame.height - 16), max(34, safeTop + 3)) } func size(preferences raw: IslandPreferences, expanded: Bool) -> CGSize { diff --git a/Sources/Notchest/IslandView.swift b/Sources/Notchest/IslandView.swift index 3337553..b8ec1bd 100644 --- a/Sources/Notchest/IslandView.swift +++ b/Sources/Notchest/IslandView.swift @@ -8,6 +8,7 @@ private let notchestCard = Color.white.opacity(0.055) struct IslandView: View { @ObservedObject var model: AppModel @ObservedObject private var developer: DeveloperModel + @ObservedObject private var activities: ActivityCenter let onHover: (Bool) -> Void let activate: () -> Void private var search: String { model.clipboardSearch } @@ -23,11 +24,12 @@ struct IslandView: View { guard motionAllowed else { return nil } return .easeInOut(duration: model.islandPreferences.motion.navigationDuration) } - private var contentIdentity: String { model.paletteVisible ? "palette" : model.tab.rawValue } + private var contentIdentity: String { model.showingSetup ? "setup" : model.paletteVisible ? "palette" : model.tab.rawValue } init(model: AppModel, onHover: @escaping (Bool) -> Void, activate: @escaping () -> Void) { self.model = model self.developer = model.developer + self.activities = model.activity self.onHover = onHover self.activate = activate } @@ -65,7 +67,7 @@ struct IslandView: View { } } .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) - .background { NotchestIslandSurface(expanded: model.expanded) } + .background { NotchestIslandSurface(expanded: model.expanded, opacity: model.workspace.validated().backgroundOpacity) } .clipShape(IslandShape(radius: model.expanded ? 30 : 17)) .overlay { if targeted { @@ -102,6 +104,9 @@ struct IslandView: View { Text(model.timeLabel).font(.system(size: 11, weight: .semibold, design: .monospaced)).foregroundStyle(notchestAccent) } else if model.stopwatchStarted != nil { Text(model.stopwatchLabel).font(.system(size: 9, weight: .semibold, design: .monospaced)).foregroundStyle(notchestAccent) + } else if let task = activities.activities.first(where: { $0.kind == "agent" && ["waiting", "running"].contains($0.state) && model.now.timeIntervalSince($0.updated) < 1800 }) { + Label(model.text(task.state == "waiting" ? "تدخّلك" : "يعمل", task.state == "waiting" ? "Action" : "Working"), systemImage: task.state == "waiting" ? "hand.raised.fill" : "ellipsis") + .font(.system(size: 9, weight: .medium)).foregroundStyle(task.state == "waiting" ? NotchestPalette.amber : notchestAccent).help(task.title) } else if let window = developer.compactUsageWindow(at: model.now) { Text("\(Int(100 - window.usedPercent))% AI").font(.system(size: 10, weight: .semibold, design: .monospaced)).foregroundStyle(notchestAccent) } else if model.awake { @@ -112,6 +117,8 @@ struct IslandView: View { } } .padding(.horizontal, model.expanded ? 29 : 17) + .lineLimit(1) + .minimumScaleFactor(0.8) .environment(\.layoutDirection, .leftToRight) } @@ -166,7 +173,8 @@ struct IslandView: View { } @ViewBuilder private var content: some View { - if model.paletteVisible { CommandPalette(app: model) } + if model.showingSetup { SetupView(app: model) } + else if model.paletteVisible { CommandPalette(app: model) } else { switch model.tab { case .home: ScrollView { home } @@ -199,16 +207,24 @@ struct IslandView: View { }.environment(\.locale, Locale(identifier: model.arabic ? "ar" : "en")) }.padding(.top, 2).padding(.bottom, 3) LazyVGrid(columns: [GridItem(.flexible(), spacing: 10), GridItem(.flexible(), spacing: 10)], spacing: 10) { - dashboardCard(icon: "chart.bar.xaxis", title: model.text("استهلاك الذكاء الاصطناعي", "AI usage at a glance"), value: "Codex · Claude Code", color: NotchestPalette.cyan) { model.tab = .developer; model.developer.section = .usage } - dashboardCard(icon: "chevron.left.forwardslash.chevron.right", title: model.text("مساحة المطوّر", "Developer workspace"), value: model.text("JSON، الأوامر، Git والمقتطفات", "JSON, commands, Git & snippets"), color: NotchestPalette.violet) { model.tab = .developer; model.developer.section = .text } - dashboardCard(icon: "timer", title: model.text("وقت للتركيز", "Make room for focus"), value: model.clock.isRunning ? model.timeLabel : model.text("ابدأ جلستك الأولى", "Find your flow"), color: NotchestPalette.coral) { model.tab = .focus } - dashboardCard(icon: "doc.on.clipboard", title: model.text("الحافظة", "Clipboard"), value: model.clipboardEnabled ? model.text("\(model.clips.count) عناصر هذا التشغيل", "\(model.clips.count) items this launch") : model.text("فعّلها عندما تحتاجها", "Ready when you are"), color: NotchestPalette.mint) { model.tab = .clipboard } - dashboardCard(icon: "tray", title: model.text("رفّ الملفات", "A place for your files"), value: model.text("\(model.shelf.count) ملفات في متناولك", "\(model.shelf.count) items within reach"), color: NotchestPalette.amber) { model.tab = .shelf } - dashboardCard(icon: "cup.and.saucer", title: model.text("إبقاء الجهاز مستيقظًا", "Keep Mac awake"), value: model.awake ? model.text("مفعّل لمدة ساعة", "On for one hour") : model.text("جاهز لجلسة طويلة", "For the longer sessions"), color: NotchestPalette.rose) { model.toggleAwake() } + ForEach(model.workspace.validated().cards) { card in homeCard(card) } } } } + @ViewBuilder private func homeCard(_ card: HomeCard) -> some View { + switch card { + case .usage: dashboardCard(icon: "chart.bar.xaxis", title: model.text("استهلاك الذكاء الاصطناعي", "AI usage at a glance"), value: "Codex · Claude Code", color: NotchestPalette.cyan) { model.tab = .developer; model.developer.section = .usage } + case .activity: dashboardCard(icon: "waveform.path", title: model.text("المشروع والمهام", "Project & tasks"), value: developer.workingDirectory.lastPathComponent, color: NotchestPalette.mint) { model.tab = .developer; developer.section = .activity } + case .code: dashboardCard(icon: "chevron.left.forwardslash.chevron.right", title: model.text("مساحة المطوّر", "Developer workspace"), value: model.text("JSON، الأوامر، Git والمقتطفات", "JSON, commands, Git & snippets"), color: NotchestPalette.violet) { model.tab = .developer; model.developer.section = .text } + case .focus: dashboardCard(icon: "timer", title: model.text("وقت للتركيز", "Make room for focus"), value: model.clock.isRunning ? model.timeLabel : model.text("ابدأ جلستك الأولى", "Find your flow"), color: NotchestPalette.coral) { model.tab = .focus } + case .clipboard: dashboardCard(icon: "doc.on.clipboard", title: model.text("الحافظة", "Clipboard"), value: model.clipboardEnabled ? model.text("\(model.clips.count) عناصر هذا التشغيل", "\(model.clips.count) items this launch") : model.text("فعّلها عندما تحتاجها", "Ready when you are"), color: NotchestPalette.mint) { model.tab = .clipboard } + case .shelf: dashboardCard(icon: "tray", title: model.text("رفّ الملفات", "A place for your files"), value: model.text("\(model.shelf.count) ملفات في متناولك", "\(model.shelf.count) items within reach"), color: NotchestPalette.amber) { model.tab = .shelf } + case .notes: dashboardCard(icon: "square.and.pencil", title: model.text("ملاحظاتك", "Your notes"), value: model.note.isEmpty ? model.text("فكرة تستحق الحفظ", "A place for your next idea") : String(model.note.prefix(40)), color: NotchestPalette.rose) { model.tab = .notes } + case .awake: dashboardCard(icon: "cup.and.saucer", title: model.text("إبقاء الجهاز مستيقظًا", "Keep Mac awake"), value: model.awake ? model.text("مفعّل لمدة ساعة", "On for one hour") : model.text("جاهز لجلسة طويلة", "For the longer sessions"), color: NotchestPalette.rose) { model.toggleAwake() } + } + } + private func dashboardCard(icon: String, title: String, value: String, color: Color, action: @escaping () -> Void) -> some View { Button(action: action) { HStack(spacing: 12) { diff --git a/Sources/Notchest/NotchestApp.swift b/Sources/Notchest/NotchestApp.swift index 3b075b1..097e7d2 100644 --- a/Sources/Notchest/NotchestApp.swift +++ b/Sources/Notchest/NotchestApp.swift @@ -37,6 +37,16 @@ final class AppDelegate: NSObject, NSApplicationDelegate { setupMenu() setupHotKey() model.developer.start() + model.developer.onUsageAlert = { [weak self] alert in + guard let self else { return } + self.model.activity.record(id: alert.id, title: "Codex", message: self.model.text("استهلكت \(alert.percent)% من حد النافذة (\(alert.minutes) دقيقة)", "\(alert.percent)% of the \(alert.minutes)-minute limit is used"), kind: "usage") + } + model.updates.start() + model.project.onChanged = { [weak self] run in + self?.model.activity.record(id: "github-run-\(run.id)", title: run.name, message: run.headBranch, state: run.activityState, url: run.url, kind: "build") + } + model.developer.$workingDirectory.removeDuplicates().sink { [weak self] directory in self?.model.project.select(directory) }.store(in: &subscriptions) + model.project.start() model.activity.onRecord = { [weak self] item in self?.model.flashActivity(item) } model.monitor.onEvent = { [weak self] title, message, url, kind in self?.model.activity.record(title: title, message: message, url: url, kind: kind) @@ -49,9 +59,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate { model.developer.onCommandFinished = { [weak self] code in guard let self else { return } self.model.showToast(self.model.text("انتهى الأمر • رمز الخروج \(code)", "Command finished • exit \(code)")) - self.model.developer.section = .command - self.model.select(.developer) + self.model.activity.record(id: "local-command", title: self.model.developer.workingDirectory.lastPathComponent, message: self.model.text("انتهى الأمر • رمز الخروج \(code)", "Command finished • exit \(code)"), state: code == 0 ? "success" : "failure", kind: "build") } + model.developer.$commandRunning.removeDuplicates().sink { [weak self] running in + guard let self, running else { return } + self.model.activity.record(id: "local-command", title: self.model.developer.workingDirectory.lastPathComponent, message: self.model.text("الأمر قيد التنفيذ", "Command is running"), state: "running", kind: "build") + }.store(in: &subscriptions) model.tools.notify = { [weak self] message in self?.model.showToast(message) } model.tools.collapse = { [weak self] in self?.model.expanded = false } model.tools.start() @@ -91,7 +104,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate { } return event } - model.select(.developer) + model.select(.home) + if !model.setupCompleted { model.showingSetup = true } resizePanel(animate: false) panel.orderFrontRegardless() } @@ -149,12 +163,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate { host.layer?.isOpaque = false host.layer?.backgroundColor = NSColor.clear.cgColor host.translatesAutoresizingMaskIntoConstraints = false - background.addSubview(host) + background.contentContainer.addSubview(host) NSLayoutConstraint.activate([ - host.leadingAnchor.constraint(equalTo: background.leadingAnchor), - host.trailingAnchor.constraint(equalTo: background.trailingAnchor), - host.topAnchor.constraint(equalTo: background.topAnchor), - host.bottomAnchor.constraint(equalTo: background.bottomAnchor) + host.leadingAnchor.constraint(equalTo: background.contentContainer.leadingAnchor), + host.trailingAnchor.constraint(equalTo: background.contentContainer.trailingAnchor), + host.topAnchor.constraint(equalTo: background.contentContainer.topAnchor), + host.bottomAnchor.constraint(equalTo: background.contentContainer.bottomAnchor) ]) backdrop = background panel.contentView = background @@ -192,7 +206,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { } else if !model.pinned { closeTask = Task { [weak self] in try? await Task.sleep(nanoseconds: 850_000_000) - guard !Task.isCancelled, let self, !self.hovered, !self.model.pinned, NSApp.modalWindow == nil else { return } + guard !Task.isCancelled, let self, !self.hovered, !self.model.pinned, !self.model.showingSetup, NSApp.modalWindow == nil else { return } // Never collapse while the user is entering a note or a clipboard query. if self.panel.isKeyWindow && (self.model.tab == .notes || self.model.tab == .clipboard || self.model.tab == .settings) { return } self.model.expanded = false @@ -288,6 +302,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate { func applicationWillTerminate(_ notification: Notification) { model.shutdown() + model.setup.stop() + model.updates.stop() + model.project.stop() model.developer.stop() model.tools.stop() model.monitor.stop() diff --git a/Sources/Notchest/NotchestDesign.swift b/Sources/Notchest/NotchestDesign.swift index 388e125..853155b 100644 --- a/Sources/Notchest/NotchestDesign.swift +++ b/Sources/Notchest/NotchestDesign.swift @@ -109,21 +109,35 @@ struct NotchestMark: View { } /// The material is a sibling below the SwiftUI host, keeping all content above AppKit's backdrop layer. -final class NotchestWindowBackdrop: NSVisualEffectView { +final class NotchestWindowBackdrop: NSView { + let contentContainer = NSView() + private var legacyBackdrop: NSVisualEffectView? var islandRadius: CGFloat = 30 { didSet { needsLayout = true } } override init(frame: NSRect) { super.init(frame: frame) - material = .hudWindow - blendingMode = .behindWindow - state = .active appearance = NSAppearance(named: .darkAqua) wantsLayer = true layer?.masksToBounds = true - let tint = NSView(frame: bounds) - tint.wantsLayer = true - tint.layer?.backgroundColor = NSColor(calibratedRed: 0.035, green: 0.055, blue: 0.095, alpha: 0.48).cgColor - tint.autoresizingMask = [.width, .height] - addSubview(tint) + contentContainer.frame = bounds + contentContainer.autoresizingMask = [.width, .height] + if #available(macOS 26, *) { + let glass = NSGlassEffectView(frame: bounds) + glass.style = .clear + glass.cornerRadius = 0 + glass.tintColor = NSColor(calibratedRed: 0.035, green: 0.055, blue: 0.095, alpha: 0.04) + glass.contentView = contentContainer + glass.autoresizingMask = [.width, .height] + addSubview(glass) + } else { + let visual = NSVisualEffectView(frame: bounds) + visual.material = .underWindowBackground + visual.blendingMode = .behindWindow + visual.state = .active + visual.autoresizingMask = [.width, .height] + visual.addSubview(contentContainer) + legacyBackdrop = visual + addSubview(visual) + } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layout() { @@ -135,7 +149,7 @@ final class NotchestWindowBackdrop: NSVisualEffectView { layer?.mask = mask // Clip the system backdrop itself as well as the content layer; otherwise blur can leak as a rectangular frame. if bounds.width > 0, bounds.height > 0 { - maskImage = NSImage(size: bounds.size, flipped: false) { _ in + legacyBackdrop?.maskImage = NSImage(size: bounds.size, flipped: false) { _ in guard let context = NSGraphicsContext.current?.cgContext else { return false } context.addPath(outline) context.setFillColor(NSColor.black.cgColor) @@ -148,6 +162,7 @@ final class NotchestWindowBackdrop: NSVisualEffectView { struct NotchestIslandSurface: View { let expanded: Bool + var opacity: Double = 0.42 @Environment(\.accessibilityReduceTransparency) private var reduceTransparency @Environment(\.colorSchemeContrast) private var contrast @@ -158,12 +173,12 @@ struct NotchestIslandSurface: View { } else if reduceTransparency || contrast == .increased { NotchestPalette.ink } else { - NotchestPalette.ink.opacity(0.62) + NotchestPalette.ink.opacity(opacity) GeometryReader { geometry in ZStack { - RadialGradient(colors: [NotchestPalette.cyan.opacity(0.28), .clear], center: UnitPoint(x: 0, y: 0.15), startRadius: 0, endRadius: geometry.size.width * 0.7) - RadialGradient(colors: [NotchestPalette.violet.opacity(0.35), .clear], center: UnitPoint(x: 1, y: 0.35), startRadius: 0, endRadius: geometry.size.width * 0.72) - RadialGradient(colors: [NotchestPalette.rose.opacity(0.19), .clear], center: UnitPoint(x: 0.45, y: 1.1), startRadius: 0, endRadius: geometry.size.width * 0.6) + RadialGradient(colors: [NotchestPalette.cyan.opacity(0.18), .clear], center: UnitPoint(x: 0, y: 0.15), startRadius: 0, endRadius: geometry.size.width * 0.7) + RadialGradient(colors: [NotchestPalette.violet.opacity(0.22), .clear], center: UnitPoint(x: 1, y: 0.35), startRadius: 0, endRadius: geometry.size.width * 0.72) + RadialGradient(colors: [NotchestPalette.rose.opacity(0.10), .clear], center: UnitPoint(x: 0.45, y: 1.1), startRadius: 0, endRadius: geometry.size.width * 0.6) LinearGradient(colors: [.black.opacity(0.5), .clear], startPoint: .top, endPoint: UnitPoint(x: 0.5, y: 0.17)) } } @@ -179,7 +194,7 @@ private struct NotchestInsetSurface: View { @Environment(\.colorSchemeContrast) private var contrast var body: some View { RoundedRectangle(cornerRadius: radius, style: .continuous) - .fill(reduceTransparency ? NotchestPalette.ink : Color.white.opacity(0.045)) + .fill(reduceTransparency ? NotchestPalette.ink : Color.black.opacity(0.14)) .overlay { RoundedRectangle(cornerRadius: radius, style: .continuous) .fill(LinearGradient(colors: [(tint ?? .white).opacity(tint == nil ? 0.035 : 0.20), (tint ?? .white).opacity(tint == nil ? 0 : 0.035)], startPoint: .topLeading, endPoint: .bottomTrailing)) @@ -207,7 +222,7 @@ private struct NotchestGlassControl: ViewModifier { content.background(selected ? color.opacity(0.25) : Color(white: 0.15), in: shape) .overlay(shape.strokeBorder(.white.opacity(contrast == .increased ? 0.5 : 0.16), lineWidth: 0.8)) } else if #available(macOS 26, *) { - content.glassEffect(.regular.tint(selected ? color.opacity(0.26) : nil).interactive(!reduceMotion && motionEnabled), in: shape) + content.glassEffect(.regular.tint(selected ? color.opacity(0.16) : nil).interactive(!reduceMotion && motionEnabled), in: shape) } else { content.background(.ultraThinMaterial, in: shape) .background(selected ? color.opacity(0.23) : .clear, in: shape) diff --git a/Sources/Notchest/ProjectMonitor.swift b/Sources/Notchest/ProjectMonitor.swift new file mode 100644 index 0000000..ed94b0a --- /dev/null +++ b/Sources/Notchest/ProjectMonitor.swift @@ -0,0 +1,103 @@ +import Foundation +import Combine + +struct ProjectRun: Decodable, Identifiable { + let databaseId: Int + let name: String + let displayTitle: String + let status: String + let conclusion: String + let headBranch: String + let url: URL + var id: Int { databaseId } + var activityState: String { + if status != "completed" { return status == "waiting" || status == "pending" ? "waiting" : "running" } + if conclusion == "success" { return "success" } + if ["failure", "timed_out", "action_required", "startup_failure"].contains(conclusion) { return "failure" } + return "info" + } + static func parse(_ data: Data) throws -> [Self] { + try JSONDecoder().decode([Self].self, from: data).filter { + $0.url.scheme == "https" && $0.url.host == "github.com" && $0.url.path.contains("/actions/runs/") && $0.url.query == nil + } + } +} + +extension ProjectRun { + private enum CodingKeys: String, CodingKey { case databaseId, name, displayTitle, status, conclusion, headBranch, url } + init(from decoder: Decoder) throws { + let values = try decoder.container(keyedBy: CodingKeys.self) + databaseId = try values.decode(Int.self, forKey: .databaseId) + name = try values.decode(String.self, forKey: .name) + displayTitle = try values.decodeIfPresent(String.self, forKey: .displayTitle) ?? name + status = try values.decode(String.self, forKey: .status) + conclusion = try values.decodeIfPresent(String.self, forKey: .conclusion) ?? "" + headBranch = try values.decodeIfPresent(String.self, forKey: .headBranch) ?? "" + url = try values.decode(URL.self, forKey: .url) + } +} + +@MainActor final class ProjectMonitor: ObservableObject { + @Published private(set) var directory: URL + @Published private(set) var runs: [ProjectRun] = [] + @Published private(set) var loading = false + @Published private(set) var error: ServiceText? + @Published private(set) var checkedAt: Date? + @Published var enabled: Bool { + didSet { defaults.set(enabled, forKey: "watchProjectActions"); if started { schedule() } } + } + var onChanged: ((ProjectRun) -> Void)? + private var previous: [Int: String] = [:] + private let defaults: UserDefaults + private var timer: Timer? + private var task: Task? + private var generation = UUID() + private var started = false + init(defaults: UserDefaults = .standard) { + self.defaults = defaults + directory = defaults.string(forKey: "workingDirectory").map { URL(fileURLWithPath: $0) } ?? FileManager.default.homeDirectoryForCurrentUser + enabled = defaults.bool(forKey: "watchProjectActions") + } + func select(_ directory: URL) { + guard directory != self.directory else { return } + cancel(); self.directory = directory; runs = []; previous = [:]; error = nil; checkedAt = nil + if enabled && started { refresh() } + } + func start() { guard !started else { return }; started = true; schedule() } + private func schedule() { + timer?.invalidate(); timer = nil + guard enabled else { cancel(); return } + refresh() + let timer = Timer(timeInterval: 60, repeats: true) { [weak self] _ in Task { @MainActor in if self?.started == true { self?.refresh() } } } + timer.tolerance = 5; RunLoop.main.add(timer, forMode: .common); self.timer = timer + } + func refresh() { + guard enabled, !loading else { return } + loading = true; error = nil + let directory = directory, generation = UUID(); self.generation = generation + task = Task { [weak self] in + let result = await Task.detached(priority: .utility) { Result { () throws -> [ProjectRun] in + guard let gh = DeveloperModel.githubExecutable() else { throw CocoaError(.executableNotLoadable) } + let reply = try ToolProcess.read(gh, ["run", "list", "--limit", "8", "--json", "databaseId,name,displayTitle,status,conclusion,headBranch,url"], timeout: 12, directory: directory) + guard reply.status == 0 else { throw CocoaError(.fileReadNoPermission) } + return try ProjectRun.parse(reply.data) + } }.value + guard let self, !Task.isCancelled, self.generation == generation else { return } + self.loading = false + switch result { + case .success(let runs): + for run in runs { + let state = run.status + ":" + run.conclusion + if let prior = self.previous[run.id], prior != state { self.onChanged?(run) } + else if self.previous[run.id] == nil && run.status != "completed" { self.onChanged?(run) } + } + self.previous = Dictionary(uniqueKeysWithValues: runs.map { ($0.id, $0.status + ":" + $0.conclusion) }) + self.runs = runs; self.checkedAt = Date() + case .failure: + self.error = ServiceText("تعذّرت قراءة GitHub Actions. تحقّق من مجلّد المستودع وتسجيل الدخول في gh واتصال الإنترنت.", "Could not read GitHub Actions. Check the repository folder, gh sign-in and internet connection.") + } + } + } + private func cancel() { generation = UUID(); task?.cancel(); task = nil; loading = false } + func stop() { started = false; timer?.invalidate(); timer = nil; cancel() } +} diff --git a/Sources/Notchest/SetupModel.swift b/Sources/Notchest/SetupModel.swift new file mode 100644 index 0000000..78d0845 --- /dev/null +++ b/Sources/Notchest/SetupModel.swift @@ -0,0 +1,70 @@ +import Foundation +import Combine +import Darwin + +struct SetupCheck: Identifiable { + let id: String + let name: String + let available: Bool + let detail: ServiceText +} + +enum ToolProcess { + static func executable(_ name: String, environment: [String: String] = ProcessInfo.processInfo.environment, home: URL = FileManager.default.homeDirectoryForCurrentUser) -> URL? { + let paths = (environment["PATH"] ?? "").split(separator: ":").map { String($0) + "/" + name } + + [home.appendingPathComponent(".local/bin/" + name).path, "/opt/homebrew/bin/" + name, "/usr/local/bin/" + name, "/usr/bin/" + name] + return paths.first(where: { FileManager.default.isExecutableFile(atPath: $0) }).map { URL(fileURLWithPath: $0) } + } + static func read(_ executable: URL, _ arguments: [String], timeout: TimeInterval = 10, directory: URL? = nil) throws -> (status: Int32, data: Data) { + let process = Process(), output = Pipe() + process.executableURL = executable; process.arguments = arguments + process.currentDirectoryURL = directory + process.standardInput = FileHandle.nullDevice; process.standardOutput = output; process.standardError = FileHandle.nullDevice + var environment = ProcessInfo.processInfo.environment + environment["GH_PROMPT_DISABLED"] = "1"; environment["GIT_TERMINAL_PROMPT"] = "0" + process.environment = environment + try process.run() + let deadline = DispatchWorkItem { + if process.isRunning { + process.terminate() + DispatchQueue.global().asyncAfter(deadline: .now() + 1) { if process.isRunning { kill(process.processIdentifier, SIGKILL) } } + } + } + DispatchQueue.global().asyncAfter(deadline: .now() + timeout, execute: deadline) + defer { deadline.cancel(); try? output.fileHandleForReading.close() } + let data = output.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + return (process.terminationStatus, Data(data.prefix(1_000_000))) + } +} + +@MainActor final class SetupModel: ObservableObject { + @Published private(set) var checks: [SetupCheck] = [] + @Published private(set) var checking = false + private var task: Task? + func refresh(codexDirectory: URL, claudeDirectory: URL) { + guard !checking else { return } + checking = true + task = Task { [weak self] in + let checks = await Task.detached(priority: .utility) { + let fm = FileManager.default + let codex = CodexLiveReader.executable() != nil + let claude = ToolProcess.executable("claude") != nil + let gh = DeveloperModel.githubExecutable() + let signedIn = gh.flatMap { try? ToolProcess.read($0, ["auth", "status"], timeout: 6).status } == 0 + func logDetail(_ url: URL) -> ServiceText { + fm.isReadableFile(atPath: url.path) ? ServiceText("مجلّد السجلات متاح؛ تتجدد الأرقام عند كتابة الاستخدام", "Log folder is readable; numbers update when usage is recorded") : ServiceText("اختر مجلّد السجلات أو استخدم الأداة لإنشائه", "Choose the log folder or use the tool to create it") + } + return [ + SetupCheck(id: "codex", name: "Codex", available: codex, detail: codex ? ServiceText("الأداة متاحة؛ فعّل حدود الحساب لاختبار الاتصال", "CLI found; enable account limits to test your connection") : ServiceText("ثبّت Codex CLI أو استخدم نسخته المرفقة مع تطبيق Codex", "Install Codex CLI or use the copy bundled with the Codex app")), + SetupCheck(id: "codex-logs", name: "Codex · local logs", available: fm.isReadableFile(atPath: codexDirectory.path), detail: logDetail(codexDirectory)), + SetupCheck(id: "claude", name: "Claude Code", available: claude || fm.isReadableFile(atPath: claudeDirectory.path), detail: logDetail(claudeDirectory)), + SetupCheck(id: "github", name: "GitHub", available: signedIn, detail: gh == nil ? ServiceText("ثبّت GitHub CLI ثم سجّل الدخول", "Install GitHub CLI, then sign in") : signedIn ? ServiceText("الحساب جاهز لمتابعة مشاريعك", "Account is ready for your projects") : ServiceText("افتح Terminal ونفّذ gh auth login ثم أعد الفحص", "Run gh auth login in Terminal, then check again")) + ] + }.value + guard let self, !Task.isCancelled else { return } + self.checks = checks; self.checking = false + } + } + func stop() { task?.cancel(); task = nil; checking = false } +} diff --git a/Sources/Notchest/SetupView.swift b/Sources/Notchest/SetupView.swift new file mode 100644 index 0000000..6b9210f --- /dev/null +++ b/Sources/Notchest/SetupView.swift @@ -0,0 +1,64 @@ +import SwiftUI + +struct SetupView: View { + @ObservedObject var app: AppModel + @ObservedObject private var setup: SetupModel + @ObservedObject private var dev: DeveloperModel + init(app: AppModel) { self.app = app; setup = app.setup; dev = app.developer } + private func refresh() { setup.refresh(codexDirectory: dev.directory(for: .codex), claudeDirectory: dev.directory(for: .claude)) } + var body: some View { + ScrollView { + VStack(alignment: .leading, spacing: 13) { + HStack { + VStack(alignment: .leading, spacing: 5) { + Text(app.text("لنجهّز مساحتك.", "Make room for your day.")).font(.system(size: 23, weight: .semibold, design: .rounded)) + Text(app.text("اختر أدواتك؛ يمكنك تغيير كل شيء من الإعدادات.", "Choose your tools. Everything can be changed in Settings.")).font(.system(size: 11)).foregroundStyle(.white.opacity(0.7)) + } + Spacer() + Picker(app.text("اللغة", "Language"), selection: $app.arabic) { Text("English").tag(false); Text("العربية").tag(true) }.labelsHidden().frame(width: 115) + } + HStack { + ForEach(WorkspacePreset.allCases) { preset in + Button(preset.title(app.arabic)) { app.workspace.cards = preset.cards } + .buttonStyle(.plain).font(.system(size: 12, weight: .medium)).padding(12) + .frame(maxWidth: .infinity).notchestGlass(selected: app.workspace.cards == preset.cards, radius: 15) + } + } + VStack(alignment: .leading, spacing: 12) { + HStack { + Text(app.text("اتصالاتك", "Your connections")).font(.system(size: 12, weight: .semibold)) + Spacer() + if setup.checking { ProgressView().controlSize(.mini) } + Button(app.text("إعادة الفحص", "Check again"), action: refresh).buttonStyle(.plain).foregroundStyle(notchestAccent).disabled(setup.checking) + } + ForEach(setup.checks) { check in + HStack(alignment: .top, spacing: 10) { + Image(systemName: check.available ? "checkmark.circle.fill" : "circle.dashed").foregroundStyle(check.available ? NotchestPalette.mint : NotchestPalette.amber) + VStack(alignment: .leading, spacing: 4) { + Text(check.id == "codex-logs" ? app.text("Codex · السجلات المحلية", "Codex · local logs") : check.name).font(.system(size: 11, weight: .semibold)) + Text(check.detail.resolved(arabicUI: app.arabic)).font(.system(size: 10)).foregroundStyle(.white.opacity(0.7)) + } + Spacer() + if check.id == "codex-logs" || check.id == "claude" { + Button(app.text("المجلّد", "Folder")) { dev.changeProvider(check.id == "claude" ? .claude : .codex); dev.chooseUsageFolder(); refresh() } + .buttonStyle(.plain).font(.system(size: 10)).foregroundStyle(notchestAccent) + } + } + } + Toggle(app.text("قراءة إحصاءات AI المحلية", "Read local AI statistics"), isOn: $dev.trackingEnabled) + Toggle(app.text("تحديث حدود حساب Codex كل دقيقة", "Refresh Codex account limits every minute"), isOn: $dev.liveAutoRefreshEnabled) + Toggle(app.text("تنبيه عند اقتراب حد Codex", "Alert when approaching a Codex limit"), isOn: $dev.usageAlertsEnabled) + Text(app.text("الأرقام المحلية من هذا الجهاز؛ الاتصال الحي يتطلب حساب Codex متاحاً.", "Local statistics come from this Mac; live limits require an available Codex account.")).font(.system(size: 9)).foregroundStyle(.white.opacity(0.6)) + }.toggleStyle(.checkbox).font(.system(size: 11)).padding(14).notchestPanel(cornerRadius: 16) + HStack { + Button(app.text("اختر مجلّد المشروع", "Choose project folder")) { dev.chooseWorkingDirectory() }.buttonStyle(.bordered) + Text(dev.workingDirectory.lastPathComponent).font(.system(size: 10, design: .monospaced)).foregroundStyle(.white.opacity(0.65)) + Spacer() + Button(app.text("ابدأ الاستخدام", "Start using Notchest")) { app.finishSetup() }.buttonStyle(.borderedProminent).tint(notchestAccent).foregroundStyle(.black) + } + Text(app.text("الحافظة والتكاملات الإضافية متاحة عند اختيارها. لا نطلب أذونات الكاميرا أو التقويم أثناء الإعداد.", "Clipboard and other integrations are available when you choose them. Setup does not request camera or calendar access.")) + .font(.system(size: 9)).foregroundStyle(.white.opacity(0.65)) + }.padding(.horizontal, 5).padding(.bottom, 8) + }.onAppear(perform: refresh) + } +} diff --git a/Sources/Notchest/UpdateModel.swift b/Sources/Notchest/UpdateModel.swift new file mode 100644 index 0000000..5e46ee9 --- /dev/null +++ b/Sources/Notchest/UpdateModel.swift @@ -0,0 +1,83 @@ +import Foundation +import Combine + +struct ReleaseVersion: Comparable, Equatable { + let parts: [Int] + init?(_ text: String) { + let cleaned = text.hasPrefix("v") ? String(text.dropFirst()) : text + let pieces = cleaned.split(separator: ".", omittingEmptySubsequences: false) + guard pieces.count == 3, pieces.allSatisfy({ !$0.isEmpty && $0.allSatisfy(\.isNumber) }), pieces.allSatisfy({ Int($0) != nil }) else { return nil } + parts = pieces.map { Int($0)! } + } + static func < (lhs: Self, rhs: Self) -> Bool { lhs.parts.lexicographicallyPrecedes(rhs.parts) } +} + +struct AvailableRelease { + let version: String + let page: URL + static func parse(_ data: Data) throws -> Self { + struct Release: Decodable { let tag_name: String; let html_url: URL; let draft: Bool; let prerelease: Bool } + let release = try JSONDecoder().decode(Release.self, from: data) + guard !release.draft, !release.prerelease, ReleaseVersion(release.tag_name) != nil, + release.html_url.scheme == "https", release.html_url.host == "github.com", + release.html_url.path == "/H0777/Notchest/releases/tag/\(release.tag_name)", release.html_url.query == nil else { throw URLError(.badServerResponse) } + return Self(version: release.tag_name.hasPrefix("v") ? String(release.tag_name.dropFirst()) : release.tag_name, page: release.html_url) + } +} + +@MainActor final class UpdateModel: ObservableObject { + @Published private(set) var checking = false + @Published private(set) var latest: AvailableRelease? + @Published private(set) var lastChecked: Date? + @Published private(set) var error: ServiceText? + @Published var automaticChecks: Bool { + didSet { defaults.set(automaticChecks, forKey: "automaticUpdateChecks"); if started { configureTimer() } } + } + let currentVersion: String + private let defaults: UserDefaults + private var timer: Timer? + private var task: Task? + private var started = false + private var generation = UUID() + var updateAvailable: Bool { + guard let latest, let current = ReleaseVersion(currentVersion), let next = ReleaseVersion(latest.version) else { return false } + return next > current + } + init(defaults: UserDefaults = .standard, currentVersion: String = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "0.6.0") { + self.defaults = defaults; self.currentVersion = currentVersion + automaticChecks = defaults.bool(forKey: "automaticUpdateChecks") + } + func start() { guard !started else { return }; started = true; configureTimer() } + private func configureTimer() { + timer?.invalidate(); timer = nil + guard automaticChecks else { return } + check() + let timer = Timer(timeInterval: 6 * 3600, repeats: true) { [weak self] _ in Task { @MainActor in if self?.started == true { self?.check() } } } + timer.tolerance = 300; RunLoop.main.add(timer, forMode: .common); self.timer = timer + } + func check() { + guard !checking else { return } + checking = true; error = nil + let generation = UUID(); self.generation = generation + task = Task { [weak self] in + do { + let config = URLSessionConfiguration.ephemeral + config.timeoutIntervalForRequest = 15; config.timeoutIntervalForResource = 20 + let session = URLSession(configuration: config) + defer { session.invalidateAndCancel() } + var request = URLRequest(url: URL(string: "https://api.github.com/repos/H0777/Notchest/releases/latest")!) + request.setValue("application/vnd.github+json", forHTTPHeaderField: "Accept") + request.setValue("Notchest", forHTTPHeaderField: "User-Agent") + let (data, response) = try await session.data(for: request) + guard (response as? HTTPURLResponse)?.statusCode == 200, data.count <= 512_000 else { throw URLError(.badServerResponse) } + let latest = try AvailableRelease.parse(data) + guard let self, !Task.isCancelled, self.generation == generation else { return } + self.latest = latest; self.lastChecked = Date(); self.checking = false + } catch { + guard let self, !Task.isCancelled, self.generation == generation else { return } + self.error = ServiceText.network(error); self.checking = false + } + } + } + func stop() { started = false; generation = UUID(); task?.cancel(); task = nil; timer?.invalidate(); timer = nil; checking = false } +} diff --git a/Sources/Notchest/UsageAlerts.swift b/Sources/Notchest/UsageAlerts.swift new file mode 100644 index 0000000..7ce9c45 --- /dev/null +++ b/Sources/Notchest/UsageAlerts.swift @@ -0,0 +1,25 @@ +import Foundation + +struct UsageLimitAlert { + let id: String + let percent: Int + let minutes: Int +} +struct UsageAlertPolicy { + private var emitted = Set() + mutating func evaluate(_ windows: [UsageWindow], at now: Date = Date()) -> [UsageLimitAlert] { + var alerts: [UsageLimitAlert] = [] + for window in windows { + guard (window.resetsAt ?? .distantFuture) > now else { continue } + let reset = window.resetsAt?.timeIntervalSince1970 ?? Calendar.current.startOfDay(for: now).timeIntervalSince1970 + let key = "\(window.minutes):\(Int(reset))" + let threshold = window.usedPercent >= 95 ? 95 : window.usedPercent >= 80 ? 80 : nil + guard let threshold, !emitted.contains("\(key):\(threshold)") else { continue } + emitted.insert("\(key):80") + if threshold == 95 { emitted.insert("\(key):95") } + alerts.append(UsageLimitAlert(id: "limit:\(key):\(threshold)", percent: Int(window.usedPercent), minutes: window.minutes)) + } + if emitted.count > 256 { emitted = Set(emitted.sorted().suffix(128)) } + return alerts + } +} diff --git a/Sources/Notchest/WorkspacePreferences.swift b/Sources/Notchest/WorkspacePreferences.swift new file mode 100644 index 0000000..384985a --- /dev/null +++ b/Sources/Notchest/WorkspacePreferences.swift @@ -0,0 +1,59 @@ +import Foundation + +enum HomeCard: String, Codable, CaseIterable, Identifiable { + case usage, activity, code, focus, clipboard, shelf, notes, awake + var id: String { rawValue } + func title(_ ar: Bool) -> String { + switch self { + case .usage: return ar ? "استهلاك AI" : "AI usage" + case .activity: return ar ? "المشروع والمهام" : "Project & tasks" + case .code: return ar ? "أدوات الكود" : "Code tools" + case .focus: return ar ? "التركيز" : "Focus" + case .clipboard: return ar ? "الحافظة" : "Clipboard" + case .shelf: return ar ? "الملفات" : "File shelf" + case .notes: return ar ? "الملاحظات" : "Notes" + case .awake: return ar ? "إبقاء الجهاز مستيقظاً" : "Keep awake" + } + } +} + +enum WorkspacePreset: String, CaseIterable, Identifiable { + case developer, focus, everyday + var id: String { rawValue } + var cards: [HomeCard] { + switch self { + case .developer: return [.usage, .activity, .code, .focus] + case .focus: return [.focus, .notes, .awake, .shelf] + case .everyday: return [.clipboard, .shelf, .focus, .notes] + } + } + func title(_ ar: Bool) -> String { + switch self { + case .developer: return ar ? "البرمجة" : "Developer" + case .focus: return ar ? "التركيز" : "Focus" + case .everyday: return ar ? "الاستخدام اليومي" : "Everyday" + } + } +} + +struct WorkspacePreferences: Codable, Equatable { + var cards: [HomeCard] = WorkspacePreset.developer.cards + /// The dark readability layer above the system's behind-window material. + var backgroundOpacity = 0.42 + func validated() -> Self { + var result = self + var seen = Set() + result.cards = cards.filter { seen.insert($0).inserted } + if result.cards.isEmpty { result.cards = [.usage] } + result.backgroundOpacity = backgroundOpacity.isFinite ? min(0.75, max(0.08, backgroundOpacity)) : 0.42 + return result + } + mutating func setVisible(_ card: HomeCard, _ visible: Bool) { + if visible && !cards.contains(card) { cards.append(card) } + if !visible && cards.count > 1 { cards.removeAll { $0 == card } } + } + mutating func move(_ card: HomeCard, by offset: Int) { + guard let index = cards.firstIndex(of: card), cards.indices.contains(index + offset) else { return } + cards.swapAt(index, index + offset) + } +} diff --git a/Sources/Notchest/WorkspaceSettingsView.swift b/Sources/Notchest/WorkspaceSettingsView.swift new file mode 100644 index 0000000..ef92a87 --- /dev/null +++ b/Sources/Notchest/WorkspaceSettingsView.swift @@ -0,0 +1,72 @@ +import SwiftUI + +struct WorkspaceSettingsView: View { + @ObservedObject var app: AppModel + @Environment(\.accessibilityReduceTransparency) private var reduceTransparency + @Environment(\.colorSchemeContrast) private var contrast + var body: some View { + VStack(alignment: .leading, spacing: 12) { + Label(app.text("الزجاج والشفافية", "Glass & transparency"), systemImage: "drop.halffull").font(.system(size: 12, weight: .semibold)) + Slider(value: Binding(get: { 1 - app.workspace.backgroundOpacity }, set: { app.workspace.backgroundOpacity = 1 - $0 }), in: 0.25...0.92) { + Text(app.text("شفافية الخلفية", "Background transparency")) + }.tint(notchestAccent).disabled(reduceTransparency || contrast == .increased) + HStack { Text(app.text("أكثر تعتيماً", "More solid")); Spacer(); Text(app.text("أكثر شفافية", "More transparent")) }.font(.system(size: 9)).foregroundStyle(.white.opacity(0.65)) + if reduceTransparency || contrast == .increased { + Text(app.text("إعدادات تسهيلات الاستخدام في macOS تمنح الوضوح الأولوية.", "macOS accessibility settings take priority for readability.")).font(.system(size: 10)).foregroundStyle(.orange) + } + }.padding(13).notchestPanel(cornerRadius: 14) + VStack(alignment: .leading, spacing: 12) { + Label(app.text("صفحتك الرئيسية", "Your overview"), systemImage: "square.grid.2x2").font(.system(size: 12, weight: .semibold)) + HStack { + ForEach(WorkspacePreset.allCases) { preset in + Button(preset.title(app.arabic)) { app.workspace.cards = preset.cards } + .buttonStyle(.plain).font(.system(size: 11, weight: .medium)).padding(.horizontal, 12).padding(.vertical, 8) + .notchestGlass(selected: app.workspace.cards == preset.cards, radius: 12) + } + } + ForEach(app.workspace.cards + HomeCard.allCases.filter { !app.workspace.cards.contains($0) }) { card in + HStack { + Toggle(card.title(app.arabic), isOn: Binding(get: { app.workspace.cards.contains(card) }, set: { app.workspace.setVisible(card, $0) })) + .toggleStyle(.checkbox).font(.system(size: 11)) + .disabled(app.workspace.cards.count == 1 && app.workspace.cards.contains(card)) + Spacer() + Button { app.workspace.move(card, by: -1) } label: { Image(systemName: "arrow.up") } + .disabled(app.workspace.cards.firstIndex(of: card).map { $0 == 0 } ?? true) + .help(app.text("تحريك لأعلى", "Move up")) + Button { app.workspace.move(card, by: 1) } label: { Image(systemName: "arrow.down") } + .disabled(app.workspace.cards.firstIndex(of: card).map { $0 == app.workspace.cards.count - 1 } ?? true) + .help(app.text("تحريك لأسفل", "Move down")) + }.buttonStyle(.plain).foregroundStyle(.white.opacity(0.8)) + } + }.padding(13).notchestPanel(cornerRadius: 14) + } +} + +struct UpdateSettingsView: View { + @ObservedObject var app: AppModel + @ObservedObject private var updates: UpdateModel + init(app: AppModel) { self.app = app; self.updates = app.updates } + var body: some View { + VStack(alignment: .leading, spacing: 10) { + HStack { + Label(app.text("التحديثات", "Updates"), systemImage: "arrow.down.circle").font(.system(size: 12, weight: .semibold)) + Spacer() + Text("v\(updates.currentVersion)").font(.system(size: 10, design: .monospaced)).foregroundStyle(.white.opacity(0.6)) + Button(app.text("تحقق الآن", "Check now")) { updates.check() }.disabled(updates.checking).buttonStyle(.plain).foregroundStyle(notchestAccent) + } + Toggle(app.text("التحقق التلقائي كل 6 ساعات", "Check automatically every 6 hours"), isOn: $updates.automaticChecks).font(.system(size: 11)).toggleStyle(.switch).controlSize(.mini) + if updates.checking { ProgressView().controlSize(.small) } + if let error = updates.error { Text(error.resolved(arabicUI: app.arabic)).foregroundStyle(.orange).font(.system(size: 10)) } + if let latest = updates.latest { + HStack { + Text(updates.updateAvailable ? app.text("الإصدار \(latest.version) متاح", "Version \(latest.version) is available") : app.text("أنت تستخدم أحدث إصدار متاح أو نسخة تطوير أحدث", "You have the latest release or a newer development build")) + .font(.system(size: 10)) + Spacer() + Button(app.text("صفحة التنزيل", "Download page")) { NSWorkspace.shared.open(latest.page) }.buttonStyle(.plain).foregroundStyle(notchestAccent) + } + } + Text(app.text("توقيع Developer ID وتصديق Apple مؤجّلان. يتم تثبيت التحديثات يدوياً من صفحة الإصدار حالياً.", "Developer ID signing and Apple notarization are deferred. Updates are currently installed manually from the release page.")) + .font(.system(size: 9)).foregroundStyle(.white.opacity(0.65)) + }.padding(13).notchestPanel(cornerRadius: 14) + } +} diff --git a/Sources/NotchestCommand/HookPayload.swift b/Sources/NotchestCommand/HookPayload.swift new file mode 100644 index 0000000..5cc64b4 --- /dev/null +++ b/Sources/NotchestCommand/HookPayload.swift @@ -0,0 +1,26 @@ +import Foundation + +/// Only state, provider, session identity and the project name leave the input. +/// Prompt text, tool arguments, answers, transcript paths and credentials are ignored. +enum HookPayload { + static func make(_ object: [String: Any], provider: String) -> [String: Any]? { + guard ["codex", "claude"].contains(provider), let event = object["hook_event_name"] as? String else { return nil } + let state: String + switch event { + case "UserPromptSubmit", "PreToolUse", "PostToolUse": state = "running" + case "PermissionRequest": state = "waiting" + case "Notification": + guard object["notification_type"] as? String == "permission_prompt" else { return nil } + state = "waiting" + case "Stop": state = "success" + case "SessionEnd", "Interrupt": state = "info" + default: return nil + } + let source = provider == "codex" ? "Codex" : "Claude Code" + let cwd = object["cwd"] as? String ?? "" + let project = String(URL(fileURLWithPath: cwd.isEmpty ? "/" : cwd).lastPathComponent.prefix(100)) + let session = object["session_id"] as? String ?? cwd + let hash = session.utf8.reduce(UInt64(14695981039346656037)) { ($0 ^ UInt64($1)) &* 1099511628211 } + return ["id": "agent-\(provider)-\(String(hash, radix: 16))", "title": source, "source": source, "project": project, "state": state] + } +} diff --git a/Sources/NotchestCommand/main.swift b/Sources/NotchestCommand/main.swift index 06246e3..d91117e 100644 --- a/Sources/NotchestCommand/main.swift +++ b/Sources/NotchestCommand/main.swift @@ -1,6 +1,47 @@ import Foundation import Darwin +// Hooks are observers. Always return empty JSON, including on failure, so they +// never approve, block, rewrite or continue an agent operation. +if CommandLine.arguments.count == 3, CommandLine.arguments[1] == "--activity-hook" { + do { + var input = Data() + while input.count <= 1_048_576 { + let chunk = try FileHandle.standardInput.read(upToCount: min(65_536, 1_048_577 - input.count)) ?? Data() + if chunk.isEmpty { break } + input.append(chunk) + } + guard input.count <= 1_048_576 else { print("{}"); exit(0) } + let object = try JSONSerialization.jsonObject(with: input) as? [String: Any] ?? [:] + if let payload = HookPayload.make(object, provider: CommandLine.arguments[2]) { + let runtime = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Library/Application Support/Notchest/Runtime/activity.json") + let attributes = try FileManager.default.attributesOfItem(atPath: runtime.path) + if attributes[.type] as? FileAttributeType == .typeRegular, + (attributes[.ownerAccountID] as? NSNumber)?.uint32Value == getuid(), + let mode = attributes[.posixPermissions] as? NSNumber, mode.intValue & 0o077 == 0, + ((attributes[.size] as? NSNumber)?.intValue ?? 5000) <= 4096 { + let descriptor = try JSONSerialization.jsonObject(with: Data(contentsOf: runtime)) as? [String: Any] ?? [:] + if let token = descriptor["token"] as? String, !token.isEmpty, let port = descriptor["port"] as? Int, (1...65535).contains(port) { + var request = URLRequest(url: URL(string: "http://127.0.0.1:\(port)/v1/activity")!) + request.httpMethod = "POST"; request.timeoutInterval = 0.8 + request.setValue("Bearer " + token, forHTTPHeaderField: "Authorization") + request.setValue("application/json", forHTTPHeaderField: "Content-Type") + request.httpBody = try JSONSerialization.data(withJSONObject: payload) + let config = URLSessionConfiguration.ephemeral + config.httpShouldSetCookies = false + let session = URLSession(configuration: config) + let done = DispatchSemaphore(value: 0) + let task = session.dataTask(with: request) { _, _, _ in done.signal() } + task.resume(); _ = done.wait(timeout: .now() + 1) + session.invalidateAndCancel() + } + } + } + } catch { /* Optional observer: an unavailable app must not interrupt work. */ } + print("{}") + exit(0) +} + // Each explicit Run command gets its own process group, so Stop can interrupt // the shell and its ordinary children without signalling the app's group. guard CommandLine.arguments.count == 2 else { exit(64) } diff --git a/check.sh b/check.sh index a07e2e4..6d7a127 100755 --- a/check.sh +++ b/check.sh @@ -3,5 +3,5 @@ set -euo pipefail PROJECT_DIR="${0:A:h}" CHECK_DIR="$(mktemp -d "${TMPDIR:-/tmp}/notchest-checks.XXXXXX")" trap 'rm -rf "$CHECK_DIR"' EXIT -swiftc -parse-as-library "$PROJECT_DIR/Sources/Notchest/FocusClock.swift" "$PROJECT_DIR/Sources/Notchest/IslandSizing.swift" "$PROJECT_DIR/Sources/Notchest/ActivityCenter.swift" "$PROJECT_DIR/Sources/Notchest/SystemMonitor.swift" "$PROJECT_DIR/Sources/Notchest/WeatherModel.swift" "$PROJECT_DIR/Sources/Notchest/StocksModel.swift" "$PROJECT_DIR/Sources/Notchest/LyricsService.swift" "$PROJECT_DIR/Sources/Notchest/MusicService.swift" "$PROJECT_DIR/Sources/Notchest/UsageReader.swift" "$PROJECT_DIR/Sources/Notchest/CodexLiveReader.swift" "$PROJECT_DIR/Sources/Notchest/DeveloperModel.swift" "$PROJECT_DIR/Sources/Notchest/NativeTools.swift" "$PROJECT_DIR/Sources/Notchest/AppModel.swift" "$PROJECT_DIR/Sources/Notchest/ServiceText.swift" "$PROJECT_DIR/Checks/RunChecks.swift" -o "$CHECK_DIR/NotchestChecks" +swiftc -parse-as-library "$PROJECT_DIR/Sources/Notchest/FocusClock.swift" "$PROJECT_DIR/Sources/Notchest/IslandSizing.swift" "$PROJECT_DIR/Sources/Notchest/ActivityCenter.swift" "$PROJECT_DIR/Sources/Notchest/SystemMonitor.swift" "$PROJECT_DIR/Sources/Notchest/WeatherModel.swift" "$PROJECT_DIR/Sources/Notchest/StocksModel.swift" "$PROJECT_DIR/Sources/Notchest/LyricsService.swift" "$PROJECT_DIR/Sources/Notchest/MusicService.swift" "$PROJECT_DIR/Sources/Notchest/UsageReader.swift" "$PROJECT_DIR/Sources/Notchest/CodexLiveReader.swift" "$PROJECT_DIR/Sources/Notchest/DeveloperModel.swift" "$PROJECT_DIR/Sources/Notchest/NativeTools.swift" "$PROJECT_DIR/Sources/Notchest/AppModel.swift" "$PROJECT_DIR/Sources/Notchest/ServiceText.swift" "$PROJECT_DIR/Sources/Notchest/WorkspacePreferences.swift" "$PROJECT_DIR/Sources/Notchest/SetupModel.swift" "$PROJECT_DIR/Sources/Notchest/UpdateModel.swift" "$PROJECT_DIR/Sources/Notchest/UsageAlerts.swift" "$PROJECT_DIR/Sources/Notchest/ProjectMonitor.swift" "$PROJECT_DIR/Sources/Notchest/HookIntegration.swift" "$PROJECT_DIR/Sources/NotchestCommand/HookPayload.swift" "$PROJECT_DIR/Checks/RunChecks.swift" -o "$CHECK_DIR/NotchestChecks" "$CHECK_DIR/NotchestChecks" From 7b74ad482cdeaaafc246ea7e7deefc2b94aca116 Mon Sep 17 00:00:00 2001 From: Hussein Faez <257576459+H0777@users.noreply.github.com> Date: Mon, 2 Nov 2026 22:08:56 +0300 Subject: [PATCH 3/7] Balance glass readability on light backgrounds --- Checks/RunChecks.swift | 2 +- Sources/Notchest/NotchestDesign.swift | 4 ++-- Sources/Notchest/WorkspacePreferences.swift | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Checks/RunChecks.swift b/Checks/RunChecks.swift index eaee873..3843032 100644 --- a/Checks/RunChecks.swift +++ b/Checks/RunChecks.swift @@ -62,7 +62,7 @@ struct RunChecks { prefs.setVisible(.notes, true); prefs.move(.notes, by: -1) precondition(prefs.cards == [.notes, .focus]) prefs.backgroundOpacity = .nan - precondition(prefs.validated().backgroundOpacity == 0.42) + precondition(prefs.validated().backgroundOpacity == 0.62) prefs.backgroundOpacity = 9 precondition(prefs.validated().backgroundOpacity == 0.75) } diff --git a/Sources/Notchest/NotchestDesign.swift b/Sources/Notchest/NotchestDesign.swift index 853155b..7137109 100644 --- a/Sources/Notchest/NotchestDesign.swift +++ b/Sources/Notchest/NotchestDesign.swift @@ -57,7 +57,7 @@ enum NotchestPalette { Color(red: 0.72, green: 0.18, blue: 0.82) ] static let ink = Color(red: 0.045, green: 0.065, blue: 0.105) - static let secondary = Color.white.opacity(0.66) + static let secondary = Color.white.opacity(0.78) static func menuImage() -> NSImage { let image = NSImage(size: NSSize(width: 20, height: 20), flipped: false) { rect in @@ -162,7 +162,7 @@ final class NotchestWindowBackdrop: NSView { struct NotchestIslandSurface: View { let expanded: Bool - var opacity: Double = 0.42 + var opacity: Double = 0.62 @Environment(\.accessibilityReduceTransparency) private var reduceTransparency @Environment(\.colorSchemeContrast) private var contrast diff --git a/Sources/Notchest/WorkspacePreferences.swift b/Sources/Notchest/WorkspacePreferences.swift index 384985a..ca860b0 100644 --- a/Sources/Notchest/WorkspacePreferences.swift +++ b/Sources/Notchest/WorkspacePreferences.swift @@ -39,13 +39,13 @@ enum WorkspacePreset: String, CaseIterable, Identifiable { struct WorkspacePreferences: Codable, Equatable { var cards: [HomeCard] = WorkspacePreset.developer.cards /// The dark readability layer above the system's behind-window material. - var backgroundOpacity = 0.42 + var backgroundOpacity = 0.62 func validated() -> Self { var result = self var seen = Set() result.cards = cards.filter { seen.insert($0).inserted } if result.cards.isEmpty { result.cards = [.usage] } - result.backgroundOpacity = backgroundOpacity.isFinite ? min(0.75, max(0.08, backgroundOpacity)) : 0.42 + result.backgroundOpacity = backgroundOpacity.isFinite ? min(0.75, max(0.08, backgroundOpacity)) : 0.62 return result } mutating func setVisible(_ card: HomeCard, _ visible: Bool) { From be574bb3e534bfae1f7df027d33df17343398565 Mon Sep 17 00:00:00 2001 From: Hussein Faez <257576459+H0777@users.noreply.github.com> Date: Mon, 2 Nov 2026 22:16:29 +0300 Subject: [PATCH 4/7] Drain temporary log buffers between scan chunks --- Sources/Notchest/UsageReader.swift | 41 +++++++++++++++++------------- 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/Sources/Notchest/UsageReader.swift b/Sources/Notchest/UsageReader.swift index b46c68a..7ce4cdd 100644 --- a/Sources/Notchest/UsageReader.swift +++ b/Sources/Notchest/UsageReader.swift @@ -174,24 +174,29 @@ enum UsageReader { // Read bounded chunks, and cache only numeric entries, never transcript text. while remaining > 0 { try Task.checkCancellation() - let chunk = try handle.read(upToCount: min(262_144, remaining)) ?? Data() - guard !chunk.isEmpty else { throw CocoaError(.fileReadUnknown) } - remaining -= chunk.count - pending.append(chunk) - while let newline = pending.firstIndex(of: 10) { - let consumed = pending.distance(from: pending.startIndex, to: newline) + 1 - if !parsed.discardingOversizedLine, consumed <= 8 * 1024 * 1024 { - parseLine(Data(pending[.. 8 * 1024 * 1024 || parsed.discardingOversizedLine { - parsed.skippedOversizedLine = true - parsed.discardingOversizedLine = true - parsed.offset += UInt64(pending.count) - pending.removeAll(keepingCapacity: false) + // Swift concurrency workers need an explicit pool for Foundation's + // temporary NSData/JSON objects; otherwise a large first scan can + // retain hundreds of MiB after the numeric result is published. + try autoreleasepool { + let chunk = try handle.read(upToCount: min(262_144, remaining)) ?? Data() + guard !chunk.isEmpty else { throw CocoaError(.fileReadUnknown) } + remaining -= chunk.count + pending.append(chunk) + while let newline = pending.firstIndex(of: 10) { + let consumed = pending.distance(from: pending.startIndex, to: newline) + 1 + if !parsed.discardingOversizedLine, consumed <= 8 * 1024 * 1024 { + parseLine(Data(pending[.. 8 * 1024 * 1024 || parsed.discardingOversizedLine { + parsed.skippedOversizedLine = true + parsed.discardingOversizedLine = true + parsed.offset += UInt64(pending.count) + pending.removeAll(keepingCapacity: false) + } } } // A valid final record does not need a trailing newline. An incomplete From 4f448aca6498959424a6736c65524baef9ddd4f5 Mon Sep 17 00:00:00 2001 From: Hussein Faez <257576459+H0777@users.noreply.github.com> Date: Mon, 2 Nov 2026 22:19:11 +0300 Subject: [PATCH 5/7] Record workspace integration and resource validation --- CHANGELOG.md | 3 +++ Docs/VALIDATION.md | 2 +- PERFORMANCE.md | 26 ++++++++++++++++++++++++++ 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c78ff4e..c329d56 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,9 @@ All notable changes to Notchest are documented here. The format follows ### Fixed +- Bound temporary Foundation log-read buffers between chunks; a local large-log + sample reduced peak sampled RSS from 535.92 to 103.28 MiB after warm-up. + - Refresh local AI usage every five seconds in common run-loop modes, on returning to the usage view, and after wake. Cancel outdated provider/folder reads so their results cannot overwrite the current selection. diff --git a/Docs/VALIDATION.md b/Docs/VALIDATION.md index a1e6c1b..c286235 100644 --- a/Docs/VALIDATION.md +++ b/Docs/VALIDATION.md @@ -16,7 +16,7 @@ record of evidence, not a claim that every supported Mac has been tested. | Website | Existing 39-feature gallery remains the released UI baseline; new screenshots are development previews | | Native UI English/Arabic, glass and preference controls | Passed on the local Mac: English/Arabic setup, presets, card reordering, both provider summaries, glass slider and live release checks | | Native helper to loopback API | Passed: synthetic PermissionRequest → working → Stop through the packaged helper; empty JSON replies; runtime token removed on disable | -| Whole-app performance | New measurement recorded separately in PERFORMANCE.md when taken | +| Whole-app performance | 60-second warm/collapsed sample: 0.12% CPU, 103.28 MiB peak RSS after bounding temporary scan buffers; see PERFORMANCE.md | | Multiple physical displays, hot-plug and mixed scaling | Pending access to additional displays; sizing geometry has automated coverage | | Intel and macOS 13–25 material fallback | Pending hardware/OS testing; build targets macOS 13 and guards newer APIs | | macOS 26 native glass | API is availability-guarded; CI builds against the macOS 26 SDK | diff --git a/PERFORMANCE.md b/PERFORMANCE.md index 9331623..2486c1d 100644 --- a/PERFORMANCE.md +++ b/PERFORMANCE.md @@ -44,3 +44,29 @@ still growing. These are reader timings, not whole-app CPU or memory figures. Some records/files exceeded the reader limits and were disclosed as partial. Live Codex account limits fetched successfully. No Claude logs were present on the test machine; automated fixtures cover its parsing and growing records. + +## Workspace build — 2026-11-02 + +Local Apple Silicon Mac (`Mac16,12`), macOS 27.2, release build. One +60-second sample per build, island collapsed after the initial real Codex +log scan. Local usage polling every five seconds; live account polling, +GitHub Actions and update checks off. Claude logs were absent. The runtime +used real logs with partial-scan limits disclosed in the UI. + +| Build | Average sampled CPU | Peak sampled RSS | +| --- | --- | --- | +| Workspace draft before bounding Foundation temporary objects | 0.11% | 535.92 MiB | +| Same workload with a per-chunk autorelease pool (`be574bb`) | 0.12% | 103.28 MiB | + +The pool bounds temporary Foundation objects on the Swift concurrency worker +between 256 KiB read chunks. This removes the elevated retained RSS observed +after large scans. The CPU difference is sampling noise; no speed or battery +improvement is inferred from it. These are local samples, not guarantees for +all hardware or log sizes, and the historical integer-rounded 0.6 baseline +uses a different reporting precision. + +`Scripts/measure.sh` now preserves fractional CPU values and accepts +`NOTCHEST_PID` to distinguish multiple running app instances. RSS is the +process's resident set, not an allocation-leak measurement. Prolonged battery, +multiple-display and older-system scenarios remain pending in +[the validation matrix](Docs/VALIDATION.md). From fe4ad0750460c15d6fdeff768a270cc24fddefd7 Mon Sep 17 00:00:00 2001 From: Hussein Faez <257576459+H0777@users.noreply.github.com> Date: Tue, 3 Nov 2026 19:26:05 +0300 Subject: [PATCH 6/7] Unify the collapsed island with the glass surface and cut 0.7.0 The slim collapsed bar rendered as solid Color.black, hiding the behind-window glass that the expanded island shows. Both states now share one transparent surface with a stronger top scrim for status text; reduce-transparency and increased-contrast keep the solid fallback. Version bumps to 0.7.0 (build 7) with the release recorded in the changelog. --- CHANGELOG.md | 11 ++++- Resources/Info.plist | 63 ++++++++++++++++++--------- Sources/Notchest/NotchestDesign.swift | 12 ++--- 3 files changed, 59 insertions(+), 27 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 75fc9e1..7876a18 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,11 +3,11 @@ All notable changes to Notchest are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). -## [Unreleased] +## [0.7.0] — 2026-11-03 ### Added -- Opt-in system notifications via UNUserNotificationCenter for the app's own events: focus completion, new files in Downloads, connected drives, and stock alerts. Opt-in from Settings; authorization is requested only when enabled; wording follows the interface language; checks grow to 37+. +- Opt-in system notifications via UNUserNotificationCenter for the app's own events: focus completion, new files in Downloads, connected drives, and stock alerts. Opt-in from Settings; authorization is requested only when enabled; wording follows the interface language. - First-run connection checks and Developer/Focus/Everyday presets, with persistent, reorderable home cards and a background-transparency control. - Native clear `NSGlassEffectView` on macOS 26+, preserving the notch outline @@ -23,6 +23,13 @@ All notable changes to Notchest are documented here. The format follows - Integration instructions and a validation matrix distinguishing automated, native UI, real-account and pending hardware coverage. +### Changed + +- The collapsed island now shares the same transparent-glass surface as the + expanded island instead of rendering as a solid black block, with a + slightly stronger top scrim so status text stays readable; the + reduce-transparency and increased-contrast fallbacks are unchanged. + ### Fixed - Bound temporary Foundation log-read buffers between chunks; a local large-log diff --git a/Resources/Info.plist b/Resources/Info.plist index ab86ae8..4035206 100644 --- a/Resources/Info.plist +++ b/Resources/Info.plist @@ -2,25 +2,48 @@ - CFBundleNameNotchest - CFBundleDisplayNameNotchest - CFBundleDevelopmentRegionen - CFBundleLocalizationsenar - CFBundleIdentifierdev.notchest.island - CFBundleExecutableNotchest - CFBundlePackageTypeAPPL - CFBundleShortVersionString0.6.0 - CFBundleVersion6 - CFBundleIconFileNotchest - LSMinimumSystemVersion13.0 - LSUIElement - NSHighResolutionCapable - NSPrincipalClassNSApplication - NSCameraUsageDescriptionNotchest uses the camera only when you open the local camera mirror. - NSAppleEventsUsageDescriptionNotchest can read and control Apple Music or Spotify when you connect a player. - NSCalendarsUsageDescriptionNotchest shows upcoming events when you choose to connect your calendar. - NSCalendarsFullAccessUsageDescriptionNotchest reads upcoming events when you choose to connect your calendar. - NSRemindersUsageDescriptionNotchest creates reminders only when you submit a new reminder. - NSRemindersFullAccessUsageDescriptionNotchest creates reminders only when you submit a new reminder. + CFBundleDevelopmentRegion + en + CFBundleDisplayName + Notchest + CFBundleExecutable + Notchest + CFBundleIconFile + Notchest + CFBundleIdentifier + dev.notchest.island + CFBundleLocalizations + + en + ar + + CFBundleName + Notchest + CFBundlePackageType + APPL + CFBundleShortVersionString + 0.7.0 + CFBundleVersion + 7 + LSMinimumSystemVersion + 13.0 + LSUIElement + + NSAppleEventsUsageDescription + Notchest can read and control Apple Music or Spotify when you connect a player. + NSCalendarsFullAccessUsageDescription + Notchest reads upcoming events when you choose to connect your calendar. + NSCalendarsUsageDescription + Notchest shows upcoming events when you choose to connect your calendar. + NSCameraUsageDescription + Notchest uses the camera only when you open the local camera mirror. + NSHighResolutionCapable + + NSPrincipalClass + NSApplication + NSRemindersFullAccessUsageDescription + Notchest creates reminders only when you submit a new reminder. + NSRemindersUsageDescription + Notchest creates reminders only when you submit a new reminder. diff --git a/Sources/Notchest/NotchestDesign.swift b/Sources/Notchest/NotchestDesign.swift index 7137109..0e8fd0e 100644 --- a/Sources/Notchest/NotchestDesign.swift +++ b/Sources/Notchest/NotchestDesign.swift @@ -168,18 +168,20 @@ struct NotchestIslandSurface: View { var body: some View { ZStack { - if !expanded { - Color.black - } else if reduceTransparency || contrast == .increased { + if reduceTransparency || contrast == .increased { NotchestPalette.ink } else { - NotchestPalette.ink.opacity(opacity) + // One glass family for both states: the slim collapsed bar shows + // the same transparency as the expanded island instead of a + // solid black block, with a stronger top scrim so the status + // text stays readable at the bar's height. + NotchestPalette.ink.opacity(expanded ? opacity : opacity * 0.8) GeometryReader { geometry in ZStack { RadialGradient(colors: [NotchestPalette.cyan.opacity(0.18), .clear], center: UnitPoint(x: 0, y: 0.15), startRadius: 0, endRadius: geometry.size.width * 0.7) RadialGradient(colors: [NotchestPalette.violet.opacity(0.22), .clear], center: UnitPoint(x: 1, y: 0.35), startRadius: 0, endRadius: geometry.size.width * 0.72) RadialGradient(colors: [NotchestPalette.rose.opacity(0.10), .clear], center: UnitPoint(x: 0.45, y: 1.1), startRadius: 0, endRadius: geometry.size.width * 0.6) - LinearGradient(colors: [.black.opacity(0.5), .clear], startPoint: .top, endPoint: UnitPoint(x: 0.5, y: 0.17)) + LinearGradient(colors: [.black.opacity(expanded ? 0.5 : 0.6), .clear], startPoint: .top, endPoint: UnitPoint(x: 0.5, y: expanded ? 0.17 : 0.55)) } } } From 519a72c14f818c21fa570ac67ae95f2a1d38e324 Mon Sep 17 00:00:00 2001 From: Hussein Faez <257576459+H0777@users.noreply.github.com> Date: Tue, 3 Nov 2026 19:50:08 +0300 Subject: [PATCH 7/7] Regenerate site pages for the 0.7.0 bundle version --- site/ar.html | 8 ++++---- site/index.html | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/site/ar.html b/site/ar.html index 9b89e2f..72891d5 100644 --- a/site/ar.html +++ b/site/ar.html @@ -10,17 +10,17 @@ - +
Notchest.
-
صُمّم للماك · مفتوح المصدر/0.6.0
+
صُمّم للماك · مفتوح المصدر/0.7.0

أدواتك اليومية.
أعلى الشاشة.

جزيرة صغيرة للأدوات التي تحتاجها.
ركّز، وأنجز، واجعل يومك أكثر انسيابًا.

- +

Apple Silicon · يستهدف macOS 13+ · مجاني ومفتوح المصدر

تطبيق أصلي. إمكانات أقرب.الواجهة الفعلية
الصفحة الرئيسية في Notchest ببطاقات ملونة وانحناءات النوتش
صور من التطبيق أثناء تشغيله. تستخدم معاينات التوثيق بيانات توضيحية موسومة بوضوح.
@@ -148,7 +148,7 @@

أدواتك اليومية.
أعلى الشاشة.

39 / التخصيص

جاهز عندما تحتاجه

اختر التشغيل عند تسجيل الدخول والفتح عند مرور المؤشر.

قد يحتاج التشغيل عند الدخول موافقة في إعدادات النظام.
-

خطوات قليلة وتبدأ

مكان صغير
على جهازك.

حمّل صورة القرص، واسحب Notchest إلى Applications، واضبط الجزيرة على طريقتك.

احصل على Notchest 0.6.0

إصدار تطوير · لم يُوقّع بعد بهوية Developer ID أو يُصدّق من Apple. ملاحظات الإصدار · مساعدة أول تشغيل

01

حمّل التطبيق

DMG لتجربة الماك المعتادة، أو ZIP محمول من صفحة الإصدارات.

02

اضبطه على طريقتك

اختر الشاشة والحجم والألوان ولغة الواجهة.

03

اربط ما تحتاجه

يوضح دليل الميزات الخدمات الاختيارية وصلاحيات macOS المطلوبة.

+

خطوات قليلة وتبدأ

مكان صغير
على جهازك.

حمّل صورة القرص، واسحب Notchest إلى Applications، واضبط الجزيرة على طريقتك.

احصل على Notchest 0.7.0

إصدار تطوير · لم يُوقّع بعد بهوية Developer ID أو يُصدّق من Apple. ملاحظات الإصدار · مساعدة أول تشغيل

01

حمّل التطبيق

DMG لتجربة الماك المعتادة، أو ZIP محمول من صفحة الإصدارات.

02

اضبطه على طريقتك

اختر الشاشة والحجم والألوان ولغة الواجهة.

03

اربط ما تحتاجه

يوضح دليل الميزات الخدمات الاختيارية وصلاحيات macOS المطلوبة.

معلومات مفيدة

التفاصيل التي تهمك.

تظهر رسالة تعذّر تحقق Apple من Notchest. ما الحل؟

نسخة التطوير الحالية موقّعة محليًا، ولم تحصل بعد على توقيع Developer ID أو تصديق Apple. إذا حمّلتها من إصدار GitHub الرسمي وتثق بالمصدر، يمكنك الموافقة على فتح هذا التطبيق بصورة منفردة.

  1. انقل Notchest إلى Applications، ثم حاول فتحه مرة واحدة.
  2. افتح إعدادات النظام ← الخصوصية والأمان، ثم انتقل إلى قسم الأمان.
  3. اضغط فتح على أي حال بجانب Notchest، ثم أكّد الفتح. إذا لم يظهر الزر، حاول فتح التطبيق مرة أخرى ثم عد إلى هذا الإعداد.

تعليمات Apple الرسمية ↗

ما الأجهزة والأنظمة المطلوبة؟

الحزمة مخصصة لـApple Silicon. يستهدف المصدر macOS 13+؛ الترجمة تحتاج 15+ وLiquid Glass يحتاج 26+. اختبار الأنظمة الأقدم وIntel ما زال ضمن خطة العمل.

diff --git a/site/index.html b/site/index.html index 1f7ae79..9275a61 100644 --- a/site/index.html +++ b/site/index.html @@ -10,17 +10,17 @@ - +
Notchest.
-
Made for Mac · Open source/0.6.0
+
Made for Mac · Open source/0.7.0

Your tools.
A little closer.

A small island for the things you reach for.
Focus, build, and keep your day in flow.

- +

Apple Silicon · macOS 13+ target · Free & open source

A real app. A little more possibility.ACTUAL INTERFACE
Notchest overview with colorful tool cards and curved notch shoulders
Captured from the running app. Documentation previews use clearly labeled sample data.
@@ -148,7 +148,7 @@

Your tools.
A little closer.

39 / Make it yours

Ready when you are

Choose whether Notchest starts at login and opens on hover.

Login items may need approval in System Settings.
-

A FEW SECONDS FROM HERE

A small home
on your Mac.

Download the disk image, drag Notchest into Applications, and make the island yours.

Get Notchest 0.6.0

Development release · not yet Developer-ID signed or notarized. Release notes · First-launch help

01

Download

A DMG for the familiar Mac experience, or a portable ZIP from Releases.

02

Make it yours

Choose your display, island size, colors, and preferred language.

03

Connect what you need

Optional services and macOS permissions are explained in the feature guide.

+

A FEW SECONDS FROM HERE

A small home
on your Mac.

Download the disk image, drag Notchest into Applications, and make the island yours.

Get Notchest 0.7.0

Development release · not yet Developer-ID signed or notarized. Release notes · First-launch help

01

Download

A DMG for the familiar Mac experience, or a portable ZIP from Releases.

02

Make it yours

Choose your display, island size, colors, and preferred language.

03

Connect what you need

Optional services and macOS permissions are explained in the feature guide.

GOOD TO KNOW

The details, without the noise.

macOS says Apple could not verify Notchest. What do I do?

This development release uses ad-hoc signing and has not been Developer-ID signed or notarized by Apple. If you downloaded it from the official GitHub release and trust that source, you can approve this app individually.

  1. Move Notchest into Applications, then try opening it once.
  2. Open System Settings → Privacy & Security and scroll to Security.
  3. Click Open Anyway beside Notchest, then confirm Open. If the button is missing, try opening the app again and return to this setting.

Read Apple’s instructions ↗

Which Mac and macOS versions?

The packaged build is for Apple Silicon. Source targets macOS 13+, with Apple Translation on 15+ and Liquid Glass on 26+. Earlier-system and Intel validation remain on the roadmap.