diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml
new file mode 100644
index 0000000..64fb899
--- /dev/null
+++ b/.github/workflows/macos.yml
@@ -0,0 +1,73 @@
+name: macOS
+
+# The native macOS app (macos/, Swift + SwiftUI). Separate from the Tauri
+# CI so a change to one doesn't wait for the other.
+on:
+ push:
+ branches: [main]
+ paths: ["macos/**", ".github/workflows/macos.yml"]
+ pull_request:
+ paths: ["macos/**", ".github/workflows/macos.yml"]
+ workflow_dispatch:
+
+concurrency:
+ group: macos-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ build:
+ runs-on: macos-15
+ defaults:
+ run:
+ working-directory: macos
+ steps:
+ - uses: actions/checkout@v5
+ - run: swift --version
+ - name: Build
+ run: swift build
+ - name: Test
+ run: swift test
+ - name: Bundle
+ run: scripts/bundle.sh 0.0.0-ci
+
+ # Start the real app and make sure it's still running after 20 s.
+ - name: Smoke test
+ run: |
+ open -n dist/MoonTask.app
+ sleep 20
+ if ! pgrep -x MoonTask > /dev/null; then
+ echo "MoonTask exited during start-up"
+ log show --last 2m --predicate 'process == "MoonTask"' --style compact | tail -50 || true
+ exit 1
+ fi
+
+ # Screenshots of each section, for reviewing the design.
+ - name: Screenshots
+ continue-on-error: true
+ run: |
+ mkdir -p screenshots
+ osascript -e 'tell application "MoonTask" to activate' || true
+ sleep 2
+ i=1
+ for key in 1 2 3 4 5 6; do
+ osascript -e "tell application \"System Events\" to keystroke \"$key\" using command down" || true
+ sleep 3
+ screencapture -x "screenshots/$i-section.png" || true
+ i=$((i+1))
+ done
+ pkill -x MoonTask || true
+ # The disk image's window, as Finder shows it.
+ hdiutil attach dist/*.dmg -mountpoint /Volumes/MoonTask > /dev/null
+ open /Volumes/MoonTask
+ sleep 4
+ screencapture -x "screenshots/7-disk-image.png" || true
+ osascript -e 'tell application "Finder" to close every window' || true
+ hdiutil detach /Volumes/MoonTask > /dev/null || true
+ ls -la screenshots
+ - uses: actions/upload-artifact@v4
+ with:
+ name: macos-app
+ path: |
+ macos/dist/*.dmg
+ macos/screenshots
+ if-no-files-found: warn
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index ee3fbb0..6bd3806 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -78,8 +78,31 @@ jobs:
src-tauri/target/release/bundle/nsis/*.exe
checksums-windows.txt
+ build-macos:
+ runs-on: macos-15
+ steps:
+ - uses: actions/checkout@v5
+ - name: Version
+ id: version
+ run: |
+ tag="${{ github.event.inputs.version }}"
+ [ -n "$tag" ] || tag="${GITHUB_REF_NAME}"
+ echo "version=${tag#v}" >> "$GITHUB_OUTPUT"
+ - name: Build the app and disk image
+ working-directory: macos
+ run: scripts/bundle.sh "${{ steps.version.outputs.version }}"
+ - name: Checksums
+ working-directory: macos/dist
+ run: shasum -a 256 *.dmg > ../../checksums-macos.txt
+ - uses: actions/upload-artifact@v4
+ with:
+ name: moontask-macos
+ path: |
+ macos/dist/*.dmg
+ checksums-macos.txt
+
publish:
- needs: [build-linux, build-windows]
+ needs: [build-linux, build-windows, build-macos]
runs-on: ubuntu-latest
permissions:
contents: write
@@ -93,6 +116,10 @@ jobs:
with:
name: moontask-windows
path: dist/windows
+ - uses: actions/download-artifact@v5
+ with:
+ name: moontask-macos
+ path: dist/macos
- name: Determine version
id: version
@@ -115,3 +142,5 @@ jobs:
dist/linux/checksums-linux.txt
dist/windows/**/*.exe
dist/windows/checksums-windows.txt
+ dist/macos/**/*.dmg
+ dist/macos/checksums-macos.txt
diff --git a/README.md b/README.md
index 3a4326d..0a34471 100644
--- a/README.md
+++ b/README.md
@@ -2,7 +2,7 @@
> Every process, calmly under the moon.
-MoonTask is a modern, open-source task manager for Windows and Linux — in the spirit of
+MoonTask is a modern, open-source task manager for Windows, Linux and macOS — in the spirit of
[TaskExplorer](https://github.com/DavidXanatos/TaskExplorer) and Process Explorer, but calmer,
better organized and in the same night-sky design as [MoonDisk](https://github.com/Luna-OS/MoonDisk).
@@ -83,7 +83,8 @@ UI:
## Installation
-Installers for Windows (`.exe`) and Linux (`.deb`/`.rpm`) are published on the [Releases](https://github.com/Luna-OS/Moon-Task/releases)
+Installers for Windows (`.exe`), Linux (`.deb`/`.rpm`) and macOS (`.dmg`, Apple silicon and
+Intel, macOS 14 or newer) are published on the [Releases](https://github.com/Luna-OS/Moon-Task/releases)
page.
MoonTask runs as a normal user. It then sees every process, but can only act on your own and
@@ -91,25 +92,33 @@ can't look inside other users' processes (their modules, handles and environment
everything, start it with administrator rights (Windows: *Run as administrator*; Linux:
e.g. `sudo -E moontask`).
-A macOS version is planned. The macOS code paths (libproc, launchd) are already in the tree
-but aren't built, tested or released yet.
+### macOS
+
+On the Mac, MoonTask is a native app written in Swift and SwiftUI (`macos/`), with the same night
+sky, the same views and the same safety rules. Open the disk image and drag MoonTask into
+Applications. The app isn't notarized by Apple yet, so macOS asks once before the first start:
+open it, then allow it under **System Settings → Privacy & Security → Open Anyway**.
+
+macOS shows the command line, environment, open files and network connections only for your own
+processes; the system's and other users' processes show their CPU and memory, but not those
+details. launchd agents of your session appear under *Services*.
## Platform notes
-| Feature | Linux | Windows |
-|-------------------------------|:-----:|:-------:|
-| Process tree, CPU, memory, disk I/O | ✓ | ✓ |
-| End, kill, end tree | ✓ | ✓ (end = kill) |
-| Suspend / resume | ✓ | ✓ |
-| Priority | ✓ (nice, all threads) | ✓ (priority class) |
-| Threads / modules | ✓ | ✓ |
-| Open handles | ✓ | planned |
-| GPU load, memory | ✓ (NVIDIA, AMD; Intel: name, temperature) | ✓ (all vendors) |
-| GPU load per process | ✓ (NVIDIA) | ✓ |
-| GPU temperature | ✓ | ✓ (where the driver reports it, as in Task Manager) |
-| Network connections | ✓ | ✓ |
-| Services | systemd | Service Control Manager |
-| CPU and other sensor temperatures | ✓ | – |
+| Feature | Linux | Windows | macOS |
+|-------------------------------|:-----:|:-------:|:-----:|
+| Process tree, CPU, memory, disk I/O | ✓ | ✓ | ✓ (disk I/O: your processes) |
+| End, kill, end tree | ✓ | ✓ (end = kill) | ✓ |
+| Suspend / resume | ✓ | ✓ | ✓ |
+| Priority | ✓ (nice, all threads) | ✓ (priority class) | ✓ (nice) |
+| Threads / modules | ✓ | ✓ | thread count |
+| Open handles | ✓ | planned | ✓ (open files, your processes) |
+| GPU load, memory | ✓ (NVIDIA, AMD; Intel: name, temperature) | ✓ (all vendors) | ✓ |
+| GPU load per process | ✓ (NVIDIA) | ✓ | – |
+| GPU temperature | ✓ | ✓ (where the driver reports it, as in Task Manager) | – |
+| Network connections | ✓ | ✓ | ✓ (your processes) |
+| Services | systemd | Service Control Manager | launchd agents |
+| CPU and other sensor temperatures | ✓ | – | thermal state |
## Development
@@ -130,6 +139,25 @@ src/
views/ Overview, Processes, Performance, Network, Services, Settings
```
+The macOS app is a Swift package in `macos/`:
+
+```
+macos/Sources/
+ MoonTaskCore/ models, process tree/list/apps, sorting, safety rules (pure Swift, tested)
+ CDarwin/ a thin C layer over libproc, sysctl, Mach and IOKit
+ MoonTaskSystem/ reads the Mac and acts on processes
+ MoonTask/ the SwiftUI app
+```
+
+```sh
+cd macos
+swift test # tests
+swift run # run the app
+scripts/bundle.sh 0.3.0 # MoonTask.app and a .dmg in dist/
+```
+
+The Windows/Linux app:
+
```sh
npm install
npm run tauri dev # run the app
diff --git a/macos/.gitignore b/macos/.gitignore
new file mode 100644
index 0000000..c632776
--- /dev/null
+++ b/macos/.gitignore
@@ -0,0 +1,4 @@
+.build/
+dist/
+.swiftpm/
+*.xcodeproj
diff --git a/macos/Package.swift b/macos/Package.swift
new file mode 100644
index 0000000..6a437cf
--- /dev/null
+++ b/macos/Package.swift
@@ -0,0 +1,56 @@
+// swift-tools-version:5.9
+//
+// MoonTask for macOS: a native SwiftUI app.
+//
+// - MoonTaskCore pure Swift (models, process tree, sorting, formatting,
+// the safety rules); builds and tests on any platform
+// - CDarwin a thin C layer over libproc, sysctl, Mach and IOKit
+// - MoonTaskSystem reads the machine and acts on processes (macOS only)
+// - MoonTask the app itself (macOS only)
+import PackageDescription
+
+var targets: [Target] = [
+ .target(name: "MoonTaskCore", path: "Sources/MoonTaskCore"),
+ .testTarget(
+ name: "MoonTaskCoreTests",
+ dependencies: ["MoonTaskCore"],
+ path: "Tests/MoonTaskCoreTests"
+ ),
+]
+var products: [Product] = []
+
+#if os(macOS)
+targets += [
+ .target(
+ name: "CDarwin",
+ path: "Sources/CDarwin",
+ linkerSettings: [
+ .linkedFramework("IOKit"),
+ .linkedFramework("CoreFoundation"),
+ ]
+ ),
+ .target(
+ name: "MoonTaskSystem",
+ dependencies: ["MoonTaskCore", "CDarwin"],
+ path: "Sources/MoonTaskSystem"
+ ),
+ .executableTarget(
+ name: "MoonTask",
+ dependencies: ["MoonTaskCore", "MoonTaskSystem"],
+ path: "Sources/MoonTask"
+ ),
+ .testTarget(
+ name: "MoonTaskSystemTests",
+ dependencies: ["MoonTaskSystem"],
+ path: "Tests/MoonTaskSystemTests"
+ ),
+]
+products.append(.executable(name: "MoonTask", targets: ["MoonTask"]))
+#endif
+
+let package = Package(
+ name: "MoonTask",
+ platforms: [.macOS(.v14)],
+ products: products,
+ targets: targets
+)
diff --git a/macos/Resources/AppIcon.icns b/macos/Resources/AppIcon.icns
new file mode 100644
index 0000000..3fe3214
Binary files /dev/null and b/macos/Resources/AppIcon.icns differ
diff --git a/macos/Resources/Info.plist b/macos/Resources/Info.plist
new file mode 100644
index 0000000..548fd53
--- /dev/null
+++ b/macos/Resources/Info.plist
@@ -0,0 +1,36 @@
+
+
+
+
+ CFBundleDevelopmentRegion
+ en
+ CFBundleDisplayName
+ MoonTask
+ CFBundleExecutable
+ MoonTask
+ CFBundleIconFile
+ AppIcon
+ CFBundleIdentifier
+ io.moontask.mac
+ CFBundleInfoDictionaryVersion
+ 6.0
+ CFBundleName
+ MoonTask
+ CFBundlePackageType
+ APPL
+ CFBundleShortVersionString
+ __VERSION__
+ CFBundleVersion
+ __VERSION__
+ LSApplicationCategoryType
+ public.app-category.utilities
+ LSMinimumSystemVersion
+ 14.0
+ NSHighResolutionCapable
+
+ NSHumanReadableCopyright
+ © 2026 Luna · MIT License
+ NSSupportsAutomaticGraphicsSwitching
+
+
+
diff --git a/macos/Resources/dmg/background.png b/macos/Resources/dmg/background.png
new file mode 100644
index 0000000..ddeebd1
Binary files /dev/null and b/macos/Resources/dmg/background.png differ
diff --git a/macos/Resources/dmg/background.svg b/macos/Resources/dmg/background.svg
new file mode 100644
index 0000000..7eb1bc5
--- /dev/null
+++ b/macos/Resources/dmg/background.svg
@@ -0,0 +1,68 @@
+
diff --git a/macos/Resources/dmg/background@2x.png b/macos/Resources/dmg/background@2x.png
new file mode 100644
index 0000000..6110256
Binary files /dev/null and b/macos/Resources/dmg/background@2x.png differ
diff --git a/macos/Sources/CDarwin/darwin.c b/macos/Sources/CDarwin/darwin.c
new file mode 100644
index 0000000..668ca6d
--- /dev/null
+++ b/macos/Sources/CDarwin/darwin.c
@@ -0,0 +1,407 @@
+#include "CDarwin.h"
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+// ---------------------------------------------------------------- helpers
+
+static void copy_string(char *out, size_t size, const char *in) {
+ if (size == 0) return;
+ strncpy(out, in, size - 1);
+ out[size - 1] = '\0';
+}
+
+/// Mach absolute time units to nanoseconds (1:1 on Intel, 125:3 on Apple
+/// silicon).
+static uint64_t ticks_to_ns(uint64_t ticks) {
+ static mach_timebase_info_data_t timebase;
+ if (timebase.denom == 0) mach_timebase_info(&timebase);
+ return (uint64_t)((__uint128_t)ticks * timebase.numer / timebase.denom);
+}
+
+// ---------------------------------------------------------------- processes
+
+int mt_list_processes(mt_kinfo *out, int max) {
+ int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0};
+ size_t size = 0;
+ if (sysctl(mib, 4, NULL, &size, NULL, 0) != 0) return -1;
+ // Processes may start between the two calls.
+ size += size / 8 + 16 * sizeof(struct kinfo_proc);
+ struct kinfo_proc *procs = malloc(size);
+ if (procs == NULL) return -1;
+ if (sysctl(mib, 4, procs, &size, NULL, 0) != 0) {
+ free(procs);
+ return -1;
+ }
+ int count = (int)(size / sizeof(struct kinfo_proc));
+ int written = 0;
+ for (int i = 0; i < count && written < max; i++) {
+ struct kinfo_proc *kp = &procs[i];
+ mt_kinfo *k = &out[written++];
+ memset(k, 0, sizeof *k);
+ k->pid = kp->kp_proc.p_pid;
+ k->ppid = kp->kp_eproc.e_ppid;
+ k->uid = kp->kp_eproc.e_ucred.cr_uid;
+ k->state = kp->kp_proc.p_stat;
+ k->nice = kp->kp_proc.p_nice;
+ k->start_sec = kp->kp_proc.p_starttime.tv_sec;
+ k->start_usec = kp->kp_proc.p_starttime.tv_usec;
+ // proc_name gives up to 32 characters, p_comm only 16.
+ char name[2 * MAXCOMLEN + 1] = {0};
+ if (proc_name(k->pid, name, sizeof name) > 0) {
+ copy_string(k->comm, sizeof k->comm, name);
+ } else {
+ copy_string(k->comm, sizeof k->comm, kp->kp_proc.p_comm);
+ }
+ }
+ free(procs);
+ return written;
+}
+
+void mt_process_usage(int32_t pid, mt_usage *out) {
+ memset(out, 0, sizeof *out);
+ out->threads = -1;
+ out->virtual_size = -1;
+ // proc_pid_rusage works for every process, not only the user's own.
+ struct rusage_info_v4 ri;
+ if (proc_pid_rusage(pid, RUSAGE_INFO_V4, (rusage_info_t *)&ri) == 0) {
+ out->ok = 1;
+ out->cpu_ns = ticks_to_ns(ri.ri_user_time + ri.ri_system_time);
+ out->footprint = ri.ri_phys_footprint;
+ out->resident = ri.ri_resident_size;
+ out->disk_read = ri.ri_diskio_bytesread;
+ out->disk_written = ri.ri_diskio_byteswritten;
+ }
+ // Task info needs the same user (or root).
+ struct proc_taskinfo ti;
+ if (proc_pidinfo(pid, PROC_PIDTASKINFO, 0, &ti, sizeof ti) == (int)sizeof ti) {
+ out->threads = ti.pti_threadnum;
+ out->virtual_size = (int64_t)ti.pti_virtual_size;
+ }
+}
+
+int mt_process_path(int32_t pid, char *out, int size) {
+ if (size <= 0) return 0;
+ out[0] = '\0';
+ int len = proc_pidpath(pid, out, (uint32_t)size);
+ return len > 0 ? len : 0;
+}
+
+int mt_process_args(int32_t pid, char *out, int size) {
+ int mib[3] = {CTL_KERN, KERN_PROCARGS2, pid};
+ size_t len = (size_t)size;
+ if (sysctl(mib, 3, out, &len, NULL, 0) != 0) return -1;
+ return (int)len;
+}
+
+static struct proc_fdinfo *list_fds(int32_t pid, int *count) {
+ int size = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, NULL, 0);
+ if (size <= 0) return NULL;
+ size += 32 * (int)sizeof(struct proc_fdinfo);
+ struct proc_fdinfo *fds = malloc((size_t)size);
+ if (fds == NULL) return NULL;
+ size = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, fds, size);
+ if (size <= 0) {
+ free(fds);
+ return NULL;
+ }
+ *count = size / (int)sizeof(struct proc_fdinfo);
+ return fds;
+}
+
+int mt_open_files(int32_t pid, char *out, int size) {
+ int count = 0;
+ struct proc_fdinfo *fds = list_fds(pid, &count);
+ if (fds == NULL) return -1;
+ int written = 0;
+ for (int i = 0; i < count; i++) {
+ if (fds[i].proc_fdtype != PROX_FDTYPE_VNODE) continue;
+ struct vnode_fdinfowithpath vi;
+ int n = proc_pidfdinfo(pid, fds[i].proc_fd, PROC_PIDFDVNODEPATHINFO, &vi,
+ PROC_PIDFDVNODEPATHINFO_SIZE);
+ if (n != PROC_PIDFDVNODEPATHINFO_SIZE || vi.pvip.vip_path[0] == '\0') continue;
+ int len = (int)strnlen(vi.pvip.vip_path, sizeof vi.pvip.vip_path);
+ if (written + len + 1 > size) break;
+ memcpy(out + written, vi.pvip.vip_path, (size_t)len);
+ out[written + len] = '\0';
+ written += len + 1;
+ }
+ free(fds);
+ return written;
+}
+
+static void format_address(const struct in_sockinfo *in, int is_local, char *out,
+ size_t size) {
+ if (in->insi_vflag & INI_IPV4) {
+ const struct in_addr *a = is_local ? &in->insi_laddr.ina_46.i46a_addr4
+ : &in->insi_faddr.ina_46.i46a_addr4;
+ inet_ntop(AF_INET, a, out, (socklen_t)size);
+ } else {
+ const struct in6_addr *a = is_local ? &in->insi_laddr.ina_6 : &in->insi_faddr.ina_6;
+ inet_ntop(AF_INET6, a, out, (socklen_t)size);
+ }
+}
+
+int mt_sockets(int32_t pid, mt_socket *out, int max) {
+ int count = 0;
+ struct proc_fdinfo *fds = list_fds(pid, &count);
+ if (fds == NULL) return -1;
+ int written = 0;
+ for (int i = 0; i < count && written < max; i++) {
+ if (fds[i].proc_fdtype != PROX_FDTYPE_SOCKET) continue;
+ struct socket_fdinfo si;
+ int n = proc_pidfdinfo(pid, fds[i].proc_fd, PROC_PIDFDSOCKETINFO, &si,
+ PROC_PIDFDSOCKETINFO_SIZE);
+ if (n != PROC_PIDFDSOCKETINFO_SIZE) continue;
+ int family = si.psi.soi_family;
+ if (family != AF_INET && family != AF_INET6) continue;
+
+ const struct in_sockinfo *in;
+ int protocol;
+ int state = -1;
+ if (si.psi.soi_kind == SOCKINFO_TCP) {
+ in = &si.psi.soi_proto.pri_tcp.tcpsi_ini;
+ protocol = 1;
+ state = si.psi.soi_proto.pri_tcp.tcpsi_state;
+ } else if (si.psi.soi_kind == SOCKINFO_IN && si.psi.soi_protocol == IPPROTO_UDP) {
+ in = &si.psi.soi_proto.pri_in;
+ protocol = 2;
+ } else {
+ continue;
+ }
+
+ mt_socket *s = &out[written++];
+ memset(s, 0, sizeof *s);
+ s->fd = fds[i].proc_fd;
+ s->family = (in->insi_vflag & INI_IPV4) ? 4 : 6;
+ s->protocol = protocol;
+ s->tcp_state = state;
+ format_address(in, 1, s->local_address, sizeof s->local_address);
+ format_address(in, 0, s->remote_address, sizeof s->remote_address);
+ s->local_port = ntohs((uint16_t)in->insi_lport);
+ s->remote_port = ntohs((uint16_t)in->insi_fport);
+ }
+ free(fds);
+ return written;
+}
+
+// ---------------------------------------------------------------- machine
+
+int mt_cpu_ticks(uint64_t *out, int max_cores) {
+ natural_t cores = 0;
+ processor_info_array_t info = NULL;
+ mach_msg_type_number_t info_count = 0;
+ kern_return_t kr = host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &cores,
+ &info, &info_count);
+ if (kr != KERN_SUCCESS) return -1;
+ processor_cpu_load_info_t loads = (processor_cpu_load_info_t)info;
+ int n = (int)cores < max_cores ? (int)cores : max_cores;
+ for (int i = 0; i < n; i++) {
+ out[4 * i + 0] = loads[i].cpu_ticks[CPU_STATE_USER];
+ out[4 * i + 1] = loads[i].cpu_ticks[CPU_STATE_SYSTEM];
+ out[4 * i + 2] = loads[i].cpu_ticks[CPU_STATE_IDLE];
+ out[4 * i + 3] = loads[i].cpu_ticks[CPU_STATE_NICE];
+ }
+ vm_deallocate(mach_task_self(), (vm_address_t)info,
+ (vm_size_t)info_count * sizeof(integer_t));
+ return n;
+}
+
+int mt_memory_stats(mt_memory *out) {
+ memset(out, 0, sizeof *out);
+ uint64_t total = 0;
+ size_t len = sizeof total;
+ if (sysctlbyname("hw.memsize", &total, &len, NULL, 0) != 0) return -1;
+ out->total = total;
+
+ vm_statistics64_data_t vm;
+ mach_msg_type_number_t count = HOST_VM_INFO64_COUNT;
+ if (host_statistics64(mach_host_self(), HOST_VM_INFO64, (host_info64_t)&vm, &count) !=
+ KERN_SUCCESS)
+ return -1;
+ vm_size_t page = 0;
+ host_page_size(mach_host_self(), &page);
+ uint64_t p = (uint64_t)page;
+ uint64_t internal = (uint64_t)vm.internal_page_count;
+ uint64_t purgeable = (uint64_t)vm.purgeable_count;
+ out->app = (internal > purgeable ? internal - purgeable : 0) * p;
+ out->wired = (uint64_t)vm.wire_count * p;
+ out->compressed = (uint64_t)vm.compressor_page_count * p;
+ out->cached = ((uint64_t)vm.external_page_count + purgeable) * p;
+ out->free = (uint64_t)vm.free_count * p;
+
+ struct xsw_usage swap;
+ len = sizeof swap;
+ if (sysctlbyname("vm.swapusage", &swap, &len, NULL, 0) == 0) {
+ out->swap_total = swap.xsu_total;
+ out->swap_used = swap.xsu_used;
+ }
+ return 0;
+}
+
+int mt_network_totals(uint64_t *received, uint64_t *sent) {
+ *received = 0;
+ *sent = 0;
+ int mib[6] = {CTL_NET, PF_ROUTE, 0, 0, NET_RT_IFLIST2, 0};
+ size_t size = 0;
+ if (sysctl(mib, 6, NULL, &size, NULL, 0) != 0) return -1;
+ char *buf = malloc(size);
+ if (buf == NULL) return -1;
+ if (sysctl(mib, 6, buf, &size, NULL, 0) != 0) {
+ free(buf);
+ return -1;
+ }
+ for (char *next = buf; next < buf + size;) {
+ struct if_msghdr *ifm = (struct if_msghdr *)next;
+ if (ifm->ifm_msglen == 0) break;
+ next += ifm->ifm_msglen;
+ if (ifm->ifm_type != RTM_IFINFO2) continue;
+ struct if_msghdr2 *if2 = (struct if_msghdr2 *)ifm;
+ if (if2->ifm_flags & IFF_LOOPBACK) continue;
+ *received += if2->ifm_data.ifi_ibytes;
+ *sent += if2->ifm_data.ifi_obytes;
+ }
+ free(buf);
+ return 0;
+}
+
+static int64_t dict_int(CFDictionaryRef dict, const char *key) {
+ CFStringRef k = CFStringCreateWithCString(kCFAllocatorDefault, key, kCFStringEncodingUTF8);
+ CFTypeRef value = CFDictionaryGetValue(dict, k);
+ CFRelease(k);
+ int64_t result = -1;
+ if (value != NULL && CFGetTypeID(value) == CFNumberGetTypeID()) {
+ CFNumberGetValue((CFNumberRef)value, kCFNumberSInt64Type, &result);
+ }
+ return result;
+}
+
+int mt_disk_totals(uint64_t *read, uint64_t *written) {
+ *read = 0;
+ *written = 0;
+ io_iterator_t it;
+ if (IOServiceGetMatchingServices(MACH_PORT_NULL, IOServiceMatching("IOBlockStorageDriver"),
+ &it) != KERN_SUCCESS)
+ return -1;
+ io_registry_entry_t entry;
+ while ((entry = IOIteratorNext(it)) != 0) {
+ CFTypeRef stats = IORegistryEntryCreateCFProperty(entry, CFSTR("Statistics"),
+ kCFAllocatorDefault, 0);
+ if (stats != NULL) {
+ if (CFGetTypeID(stats) == CFDictionaryGetTypeID()) {
+ int64_t r = dict_int((CFDictionaryRef)stats, "Bytes (Read)");
+ int64_t w = dict_int((CFDictionaryRef)stats, "Bytes (Write)");
+ if (r > 0) *read += (uint64_t)r;
+ if (w > 0) *written += (uint64_t)w;
+ }
+ CFRelease(stats);
+ }
+ IOObjectRelease(entry);
+ }
+ IOObjectRelease(it);
+ return 0;
+}
+
+static void registry_string(io_registry_entry_t entry, const char *key, char *out, size_t size) {
+ CFStringRef k = CFStringCreateWithCString(kCFAllocatorDefault, key, kCFStringEncodingUTF8);
+ CFTypeRef value = IORegistryEntrySearchCFProperty(
+ entry, kIOServicePlane, k, kCFAllocatorDefault,
+ kIORegistryIterateRecursively | kIORegistryIterateParents);
+ CFRelease(k);
+ if (value == NULL) return;
+ if (CFGetTypeID(value) == CFStringGetTypeID()) {
+ CFStringGetCString((CFStringRef)value, out, (CFIndex)size, kCFStringEncodingUTF8);
+ } else if (CFGetTypeID(value) == CFDataGetTypeID()) {
+ // Intel Macs keep the model name as a NUL-terminated byte string.
+ CFIndex len = CFDataGetLength((CFDataRef)value);
+ if (len > (CFIndex)size - 1) len = (CFIndex)size - 1;
+ memcpy(out, CFDataGetBytePtr((CFDataRef)value), (size_t)len);
+ out[len] = '\0';
+ }
+ CFRelease(value);
+}
+
+int mt_gpus(mt_gpu *out, int max) {
+ io_iterator_t it;
+ if (IOServiceGetMatchingServices(MACH_PORT_NULL, IOServiceMatching("IOAccelerator"), &it) !=
+ KERN_SUCCESS)
+ return -1;
+ int written = 0;
+ io_registry_entry_t entry;
+ while ((entry = IOIteratorNext(it)) != 0) {
+ if (written < max) {
+ mt_gpu *g = &out[written++];
+ memset(g, 0, sizeof *g);
+ g->utilization = -1;
+ g->memory_used = -1;
+ g->cores = -1;
+ registry_string(entry, "model", g->name, sizeof g->name);
+
+ CFTypeRef perf = IORegistryEntryCreateCFProperty(
+ entry, CFSTR("PerformanceStatistics"), kCFAllocatorDefault, 0);
+ if (perf != NULL) {
+ if (CFGetTypeID(perf) == CFDictionaryGetTypeID()) {
+ CFDictionaryRef d = (CFDictionaryRef)perf;
+ int64_t util = dict_int(d, "Device Utilization %");
+ if (util < 0) util = dict_int(d, "GPU Activity(%)");
+ if (util >= 0) g->utilization = (double)(util > 100 ? 100 : util);
+ int64_t used = dict_int(d, "In use system memory");
+ if (used < 0) used = dict_int(d, "vramUsedBytes");
+ g->memory_used = used;
+ }
+ CFRelease(perf);
+ }
+ CFTypeRef cores = IORegistryEntryCreateCFProperty(entry, CFSTR("gpu-core-count"),
+ kCFAllocatorDefault, 0);
+ if (cores != NULL) {
+ if (CFGetTypeID(cores) == CFNumberGetTypeID()) {
+ int32_t n = -1;
+ CFNumberGetValue((CFNumberRef)cores, kCFNumberSInt32Type, &n);
+ g->cores = n;
+ }
+ CFRelease(cores);
+ }
+ }
+ IOObjectRelease(entry);
+ }
+ IOObjectRelease(it);
+ return written;
+}
+
+int mt_sysctl_string(const char *name, char *out, int size) {
+ if (size <= 0) return 0;
+ size_t len = (size_t)size;
+ if (sysctlbyname(name, out, &len, NULL, 0) != 0) {
+ out[0] = '\0';
+ return 0;
+ }
+ out[size - 1] = '\0';
+ return (int)strlen(out);
+}
+
+int64_t mt_sysctl_int(const char *name) {
+ int64_t value = 0;
+ size_t len = sizeof value;
+ if (sysctlbyname(name, &value, &len, NULL, 0) != 0) return -1;
+ if (len == sizeof(int32_t)) {
+ int32_t small;
+ memcpy(&small, &value, sizeof small);
+ return small;
+ }
+ return value;
+}
diff --git a/macos/Sources/CDarwin/include/CDarwin.h b/macos/Sources/CDarwin/include/CDarwin.h
new file mode 100644
index 0000000..cdc65ed
--- /dev/null
+++ b/macos/Sources/CDarwin/include/CDarwin.h
@@ -0,0 +1,123 @@
+// A thin, flat C layer over the Darwin APIs MoonTask reads the machine with
+// (libproc, sysctl, Mach host statistics, the routing socket and IOKit).
+//
+// Everything is returned in plain structs of fixed-size fields, so the Swift
+// side never touches the kernel's unions and variable-length records.
+
+#ifndef MOONTASK_CDARWIN_H
+#define MOONTASK_CDARWIN_H
+
+#include
+#include
+
+// ---------------------------------------------------------------- processes
+
+/// One process as the BSD layer lists it (readable for every process).
+typedef struct {
+ int32_t pid;
+ int32_t ppid;
+ uint32_t uid;
+ /// SIDL 1, SRUN 2, SSLEEP 3, SSTOP 4, SZOMB 5
+ int32_t state;
+ int32_t nice;
+ int64_t start_sec;
+ int64_t start_usec;
+ char comm[33];
+} mt_kinfo;
+
+/// All processes. Returns how many were written (at most `max`), or -1.
+int mt_list_processes(mt_kinfo *out, int max);
+
+/// Resource usage of one process. `ok` is 0 when the process is gone or
+/// not readable.
+typedef struct {
+ int ok;
+ /// Nanoseconds of CPU time, user + system.
+ uint64_t cpu_ns;
+ /// The memory Activity Monitor calls "Memory" (physical footprint).
+ uint64_t footprint;
+ uint64_t resident;
+ uint64_t disk_read;
+ uint64_t disk_written;
+ /// Only for processes of the current user (or as root); -1 otherwise.
+ int32_t threads;
+ int64_t virtual_size;
+} mt_usage;
+
+void mt_process_usage(int32_t pid, mt_usage *out);
+
+/// The executable's path; returns its length, or 0.
+int mt_process_path(int32_t pid, char *out, int size);
+
+/// The raw KERN_PROCARGS2 block (argc, exec path, argv, envp). Returns the
+/// number of bytes written, or -1 (other users' processes need root).
+int mt_process_args(int32_t pid, char *out, int size);
+
+/// Paths of the process' open files, each NUL-terminated, one after
+/// another. Returns the number of bytes written, or -1.
+int mt_open_files(int32_t pid, char *out, int size);
+
+/// An open socket of a process.
+typedef struct {
+ int32_t fd;
+ /// 4 or 6
+ int32_t family;
+ /// 1 = TCP, 2 = UDP
+ int32_t protocol;
+ char local_address[46];
+ int32_t local_port;
+ char remote_address[46];
+ int32_t remote_port;
+ /// TCPS_* for TCP (0 closed … 10 time-wait), -1 for UDP
+ int32_t tcp_state;
+} mt_socket;
+
+/// The process' TCP and UDP sockets. Returns how many, or -1.
+int mt_sockets(int32_t pid, mt_socket *out, int max);
+
+// ---------------------------------------------------------------- machine
+
+/// CPU ticks per core: user, system, idle, nice — 4 values per core.
+/// Returns the number of cores, or -1.
+int mt_cpu_ticks(uint64_t *out, int max_cores);
+
+typedef struct {
+ uint64_t total;
+ uint64_t free;
+ /// What Activity Monitor calls "App Memory".
+ uint64_t app;
+ uint64_t wired;
+ uint64_t compressed;
+ /// File cache and purgeable memory, which macOS gives back on demand.
+ uint64_t cached;
+ uint64_t swap_total;
+ uint64_t swap_used;
+} mt_memory;
+
+int mt_memory_stats(mt_memory *out);
+
+/// Bytes received and sent on all interfaces but loopback, since boot.
+int mt_network_totals(uint64_t *received, uint64_t *sent);
+
+/// Bytes read from and written to all block storage devices, since boot.
+int mt_disk_totals(uint64_t *read, uint64_t *written);
+
+typedef struct {
+ char name[128];
+ /// 0–100, or -1 when the driver doesn't say.
+ double utilization;
+ /// Bytes, or -1.
+ int64_t memory_used;
+ /// GPU cores (Apple silicon), or -1.
+ int32_t cores;
+} mt_gpu;
+
+/// The machine's GPUs (IOAccelerator). Returns how many, or -1.
+int mt_gpus(mt_gpu *out, int max);
+
+/// A sysctl string such as "machdep.cpu.brand_string"; returns its length.
+int mt_sysctl_string(const char *name, char *out, int size);
+/// A sysctl integer such as "hw.memsize"; returns -1 when unknown.
+int64_t mt_sysctl_int(const char *name);
+
+#endif
diff --git a/macos/Sources/MoonTask/AppModel.swift b/macos/Sources/MoonTask/AppModel.swift
new file mode 100644
index 0000000..5a2350d
--- /dev/null
+++ b/macos/Sources/MoonTask/AppModel.swift
@@ -0,0 +1,152 @@
+import Foundation
+import MoonTaskCore
+import MoonTaskSystem
+import Observation
+import SwiftUI
+
+enum AppSection: String, CaseIterable, Identifiable {
+ case overview, processes, performance, network, services, settings
+ var id: String { rawValue }
+
+ var title: String {
+ switch self {
+ case .overview: return "Overview"
+ case .processes: return "Processes"
+ case .performance: return "Performance"
+ case .network: return "Network"
+ case .services: return "Services"
+ case .settings: return "Settings"
+ }
+ }
+
+ var subtitle: String {
+ switch self {
+ case .overview: return "Your Mac at a glance"
+ case .processes: return "Everything that runs, as a tree, a list or by app"
+ case .performance: return "CPU, memory, GPU, disk and network over time"
+ case .network: return "Open connections and listening ports"
+ case .services: return "The launchd agents of your session"
+ case .settings: return "How MoonTask looks and behaves"
+ }
+ }
+
+ var symbol: String {
+ switch self {
+ case .overview: return "moon.stars"
+ case .processes: return "list.bullet.indent"
+ case .performance: return "waveform.path.ecg"
+ case .network: return "network"
+ case .services: return "gearshape.2"
+ case .settings: return "slider.horizontal.3"
+ }
+ }
+}
+
+/// The app's live state: the latest snapshot, its history, and what's
+/// selected. Sampling runs on a background queue; everything the views read
+/// is updated on the main actor.
+@MainActor
+@Observable
+final class AppModel {
+ var section: AppSection = .overview
+ private(set) var snapshot = Snapshot()
+ private(set) var hasSnapshot = false
+ private(set) var history = History()
+ private(set) var systemInfo = SystemInfo()
+ private(set) var events: [ActivityEvent] = []
+ /// Processes that started in the last few seconds (highlighted).
+ private(set) var fresh: Set = []
+ private(set) var connections: [Connection] = []
+ private(set) var jobs: [LaunchJob] = []
+ var paused = false
+ var message: String?
+
+ private let sampler = Sampler()
+ private let queue = DispatchQueue(label: "io.moontask.sampler", qos: .utility)
+ @ObservationIgnored private var loop: Task?
+ @ObservationIgnored private var freshSince: [ProcessIdentity: Date] = [:]
+
+ init() {}
+
+ func start() {
+ guard loop == nil else { return }
+ systemInfo = SystemInfoReader.read()
+ loop = Task { [weak self] in
+ while !Task.isCancelled {
+ await self?.refresh()
+ let interval = UserDefaults.standard.double(forKey: SettingKey.refreshInterval)
+ try? await Task.sleep(for: .milliseconds(Int((interval > 0 ? interval : 1) * 1000)))
+ }
+ }
+ }
+
+ func refresh(force: Bool = false) async {
+ if paused && !force { return }
+ let sampler = self.sampler
+ let next = await withCheckedContinuation { (continuation: CheckedContinuation) in
+ queue.async { continuation.resume(returning: sampler.sample()) }
+ }
+ apply(next)
+ if section == .network { await refreshConnections() }
+ if section == .services && jobs.isEmpty { await refreshJobs() }
+ }
+
+ private func apply(_ next: Snapshot) {
+ let now = next.timestamp
+ if hasSnapshot {
+ let new = activity(from: snapshot.processes, to: next.processes, at: now)
+ if !new.isEmpty {
+ events = Array((new + events).prefix(60))
+ for event in new where event.kind == .started {
+ if let p = next.processes.first(where: { $0.pid == event.pid }) {
+ freshSince[p.identity] = now
+ }
+ }
+ }
+ }
+ freshSince = freshSince.filter { now.timeIntervalSince($0.value) < 3 }
+ fresh = Set(freshSince.keys)
+ history.record(next)
+ snapshot = next
+ hasSnapshot = true
+ }
+
+ func refreshConnections() async {
+ let processes = snapshot.processes
+ connections = await Task.detached(priority: .utility) {
+ ProcessInspector.allConnections(processes)
+ }.value
+ }
+
+ func refreshJobs() async {
+ jobs = await Task.detached(priority: .utility) { LaunchAgents.list() }.value
+ }
+
+ // MARK: - Actions
+
+ func perform(_ action: ProcessAction, on row: ProcessRow) {
+ let tree = snapshot.processes
+ do {
+ try ProcessControl.perform(action, on: row, tree: tree)
+ message = nil
+ } catch {
+ message = error.localizedDescription
+ }
+ Task { await refresh(force: true) }
+ }
+
+ func startJob(_ job: LaunchJob) {
+ if !LaunchAgents.start(job) { message = "launchd couldn't start \(job.label)." }
+ Task { await refreshJobs() }
+ }
+
+ func stopJob(_ job: LaunchJob) {
+ if !LaunchAgents.stop(job) { message = "launchd couldn't stop \(job.label)." }
+ Task { await refreshJobs() }
+ }
+
+ func process(pid: Int32) -> ProcessRow? {
+ snapshot.processes.first { $0.pid == pid }
+ }
+}
+
diff --git a/macos/Sources/MoonTask/Components.swift b/macos/Sources/MoonTask/Components.swift
new file mode 100644
index 0000000..be944b9
--- /dev/null
+++ b/macos/Sources/MoonTask/Components.swift
@@ -0,0 +1,270 @@
+import MoonTaskCore
+import SwiftUI
+
+/// A frosted night-glass panel — the card every section is built from.
+struct GlassCard: View {
+ var title: String?
+ var padding: CGFloat = 16
+ @ViewBuilder var content: Content
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 12) {
+ if let title {
+ Text(title)
+ .font(.system(size: 13, weight: .semibold))
+ .foregroundStyle(Palette.text)
+ }
+ content
+ }
+ .padding(padding)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .glass()
+ }
+}
+
+extension View {
+ /// The glass surface: a soft gradient, a hairline border and rounded
+ /// corners.
+ func glass(cornerRadius: CGFloat = 16) -> some View {
+ background(
+ RoundedRectangle(cornerRadius: cornerRadius, style: .continuous)
+ .fill(LinearGradient(
+ colors: [Palette.glassTop, Palette.glassBottom], startPoint: .top, endPoint: .bottom
+ ))
+ .overlay(
+ RoundedRectangle(cornerRadius: cornerRadius, style: .continuous)
+ .strokeBorder(Palette.border, lineWidth: 1)
+ )
+ )
+ }
+
+ func inset(cornerRadius: CGFloat = 10) -> some View {
+ background(
+ RoundedRectangle(cornerRadius: cornerRadius, style: .continuous).fill(Palette.inset)
+ )
+ }
+}
+
+/// Small caps label above a value.
+struct Eyebrow: View {
+ var text: String
+
+ var body: some View {
+ Text(text.uppercased())
+ .font(.system(size: 10.5, weight: .semibold))
+ .tracking(0.8)
+ .foregroundStyle(Palette.textMuted)
+ }
+}
+
+/// A headline measure with its moon, a line of context and a sparkline.
+struct StatTile: View {
+ var label: String
+ var value: String
+ var detail: String
+ var fraction: Double
+ var series: [Double]
+ var max: Double?
+ var tone: Color = Palette.chart1
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 10) {
+ HStack(spacing: 12) {
+ MoonPhase(fraction: fraction, size: 44)
+ VStack(alignment: .leading, spacing: 2) {
+ Eyebrow(text: label)
+ Text(value)
+ .font(.figure(22, weight: .semibold))
+ .foregroundStyle(Palette.text)
+ .lineLimit(1)
+ .minimumScaleFactor(0.7)
+ }
+ }
+ Text(detail)
+ .font(.system(size: 11.5))
+ .foregroundStyle(Palette.textMuted)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ Sparkline(values: series, max: max, tone: tone)
+ .frame(height: 34)
+ }
+ .padding(14)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .glass()
+ .accessibilityElement(children: .combine)
+ .accessibilityLabel("\(label): \(value)")
+ }
+}
+
+/// The sidebar's compact moon gauges.
+struct SideGauge: View {
+ var label: String
+ var value: String
+ var fraction: Double
+
+ var body: some View {
+ HStack(spacing: 10) {
+ MoonPhase(fraction: fraction, size: 28)
+ VStack(alignment: .leading, spacing: 1) {
+ Eyebrow(text: label)
+ Text(value)
+ .font(.figure(12))
+ .foregroundStyle(Palette.text)
+ .lineLimit(1)
+ }
+ Spacer(minLength: 0)
+ }
+ .padding(.horizontal, 10)
+ .padding(.vertical, 7)
+ .inset()
+ }
+}
+
+/// A tiny area chart without axes.
+struct Sparkline: View {
+ var values: [Double]
+ var max: Double?
+ var tone: Color = Palette.chart1
+
+ var body: some View {
+ GeometryReader { geo in
+ let top = Swift.max(max ?? (values.max() ?? 0), 1e-9)
+ let count = Swift.max(values.count, 2)
+ let step = geo.size.width / CGFloat(count - 1)
+ let points = values.enumerated().map { i, v in
+ CGPoint(
+ x: CGFloat(i + count - values.count) * step,
+ y: geo.size.height * (1 - CGFloat(Swift.min(1, v / top)))
+ )
+ }
+ if points.count > 1 {
+ let line = Path { p in p.addLines(points) }
+ let area = Path { p in
+ p.move(to: CGPoint(x: points[0].x, y: geo.size.height))
+ p.addLines(points)
+ p.addLine(to: CGPoint(x: points[points.count - 1].x, y: geo.size.height))
+ p.closeSubpath()
+ }
+ area.fill(LinearGradient(
+ colors: [tone.opacity(0.35), tone.opacity(0.02)], startPoint: .top, endPoint: .bottom
+ ))
+ line.stroke(tone, style: StrokeStyle(lineWidth: 1.5, lineJoin: .round))
+ }
+ }
+ .accessibilityHidden(true)
+ }
+}
+
+/// A slim horizontal bar.
+struct Meter: View {
+ var fraction: Double
+ var tone: Color = Palette.lavender
+
+ var body: some View {
+ GeometryReader { geo in
+ ZStack(alignment: .leading) {
+ Capsule().fill(Palette.inset)
+ Capsule()
+ .fill(LinearGradient(
+ colors: [tone.opacity(0.75), tone], startPoint: .leading, endPoint: .trailing
+ ))
+ .frame(width: Swift.max(0, geo.size.width * CGFloat(Swift.min(1, fraction))))
+ }
+ }
+ .frame(height: 6)
+ .accessibilityValue(Format.percent(fraction * 100, digits: 0))
+ }
+}
+
+/// Label/value pairs in two aligned columns.
+struct Facts: View {
+ var items: [(String, String)]
+
+ var body: some View {
+ Grid(alignment: .leading, horizontalSpacing: 16, verticalSpacing: 7) {
+ ForEach(Array(items.enumerated()), id: \.offset) { _, item in
+ GridRow {
+ Text(item.0)
+ .foregroundStyle(Palette.textMuted)
+ Text(item.1)
+ .foregroundStyle(Palette.text)
+ .textSelection(.enabled)
+ .lineLimit(2)
+ .truncationMode(.middle)
+ }
+ .font(.system(size: 12))
+ }
+ }
+ }
+}
+
+extension Owner {
+ var color: Color {
+ switch self {
+ case .current: return Palette.ownerCurrent
+ case .system: return Palette.ownerSystem
+ case .other: return Palette.ownerOther
+ case .kernel: return Palette.textFaint
+ }
+ }
+}
+
+struct OwnerDot: View {
+ var owner: Owner
+
+ var body: some View {
+ Circle()
+ .fill(owner.color)
+ .frame(width: 7, height: 7)
+ .help(owner.label)
+ .accessibilityLabel(owner.label)
+ }
+}
+
+struct Chip: View {
+ var text: String
+ var tone: Color = Palette.lavender
+
+ var body: some View {
+ Text(text)
+ .font(.system(size: 10.5, weight: .semibold))
+ .padding(.horizontal, 7)
+ .padding(.vertical, 2)
+ .foregroundStyle(tone)
+ .background(Capsule().fill(tone.opacity(0.14)))
+ }
+}
+
+/// An empty state that explains itself.
+struct EmptyNote: View {
+ var symbol: String
+ var title: String
+ var text: String
+
+ var body: some View {
+ VStack(spacing: 8) {
+ Image(systemName: symbol)
+ .font(.system(size: 26))
+ .foregroundStyle(Palette.lavender)
+ Text(title).font(.headline).foregroundStyle(Palette.text)
+ Text(text)
+ .font(.callout)
+ .foregroundStyle(Palette.textMuted)
+ .multilineTextAlignment(.center)
+ .frame(maxWidth: 380)
+ }
+ .padding(30)
+ .frame(maxWidth: .infinity)
+ }
+}
+
+extension ProcessState {
+ var tone: Color {
+ switch self {
+ case .running: return Palette.success
+ case .stopped: return Palette.warning
+ case .zombie: return Palette.danger
+ default: return Palette.textMuted
+ }
+ }
+}
diff --git a/macos/Sources/MoonTask/ContentView.swift b/macos/Sources/MoonTask/ContentView.swift
new file mode 100644
index 0000000..1a5f880
--- /dev/null
+++ b/macos/Sources/MoonTask/ContentView.swift
@@ -0,0 +1,98 @@
+import MoonTaskCore
+import SwiftUI
+
+struct ContentView: View {
+ @Environment(AppModel.self) private var model
+
+ var body: some View {
+ @Bindable var model = model
+ NavigationSplitView {
+ Sidebar()
+ .navigationSplitViewColumnWidth(min: 200, ideal: 220, max: 260)
+ } detail: {
+ ZStack {
+ SkyBackground()
+ detail
+ }
+ .navigationTitle(model.section.title)
+ .navigationSubtitle(model.section.subtitle)
+ .toolbar {
+ ToolbarItem(placement: .primaryAction) {
+ Button {
+ model.paused.toggle()
+ } label: {
+ Label(model.paused ? "Resume" : "Pause", systemImage: model.paused ? "play.fill" : "pause.fill")
+ }
+ .help(model.paused ? "Resume live updates (⇧⌘P)" : "Pause live updates (⇧⌘P)")
+ }
+ }
+ }
+ .alert(
+ "MoonTask",
+ isPresented: Binding(get: { model.message != nil }, set: { if !$0 { model.message = nil } }),
+ actions: { Button("OK") { model.message = nil } },
+ message: { Text(model.message ?? "") }
+ )
+ }
+
+ @ViewBuilder private var detail: some View {
+ if !model.hasSnapshot {
+ ProgressView("Looking at your Mac …")
+ .foregroundStyle(Palette.textMuted)
+ } else {
+ switch model.section {
+ case .overview: OverviewView()
+ case .processes: ProcessesView()
+ case .performance: PerformanceView()
+ case .network: NetworkView()
+ case .services: ServicesView()
+ case .settings: SettingsView()
+ }
+ }
+ }
+}
+
+struct Sidebar: View {
+ @Environment(AppModel.self) private var model
+
+ var body: some View {
+ @Bindable var model = model
+ List(selection: Binding(get: { model.section }, set: { if let s = $0 { model.section = s } })) {
+ SwiftUI.Section {
+ ForEach(AppSection.allCases) { section in
+ Label(section.title, systemImage: section.symbol)
+ .tag(section)
+ }
+ } header: {
+ HStack(spacing: 8) {
+ MoonPhase(fraction: 0.35, size: 22)
+ Text("MoonTask")
+ .font(.system(size: 15, weight: .semibold, design: .rounded))
+ .foregroundStyle(Palette.text)
+ }
+ .padding(.bottom, 6)
+ }
+ }
+ .listStyle(.sidebar)
+ .safeAreaInset(edge: .bottom) { gauges }
+ }
+
+ private var gauges: some View {
+ let s = model.snapshot
+ return VStack(spacing: 6) {
+ SideGauge(label: "CPU", value: Format.percent(s.cpu.total, digits: 0), fraction: s.cpu.total / 100)
+ SideGauge(
+ label: "Memory",
+ value: "\(Format.bytes(s.memory.used)) / \(Format.bytes(s.memory.total, precision: 0))",
+ fraction: s.memory.fraction
+ )
+ if let gpu = s.primaryGPU, let load = gpu.utilization {
+ SideGauge(label: "GPU", value: Format.percent(load, digits: 0), fraction: load / 100)
+ }
+ if model.paused {
+ Chip(text: "Paused", tone: Palette.warning)
+ }
+ }
+ .padding(10)
+ }
+}
diff --git a/macos/Sources/MoonTask/MoonPhase.swift b/macos/Sources/MoonTask/MoonPhase.swift
new file mode 100644
index 0000000..36835e0
--- /dev/null
+++ b/macos/Sources/MoonTask/MoonPhase.swift
@@ -0,0 +1,95 @@
+import SwiftUI
+
+/// A small moon whose lit part grows with `fraction` (0…1) — MoonTask's gauge
+/// for CPU, memory and disk load, the same moon as the Windows/Linux app.
+struct MoonPhase: View {
+ var fraction: Double
+ var size: CGFloat = 40
+
+ var body: some View {
+ let f = (min(1, max(0, fraction)) * 100).rounded() / 100
+ Canvas { context, canvasSize in
+ let scale = canvasSize.width / 40
+ context.scaleBy(x: scale, y: scale)
+ let r: CGFloat = 17
+ let center = CGPoint(x: 20, y: 20)
+ let disc = Path(ellipseIn: CGRect(x: 3, y: 3, width: 2 * r, height: 2 * r))
+
+ // Glow, stronger as the moon fills.
+ let glowRect = CGRect(x: 0, y: 0, width: 40, height: 40)
+ context.fill(
+ Path(ellipseIn: glowRect),
+ with: .radialGradient(
+ Gradient(stops: [
+ .init(color: Color(hex: 0xB9AEFB).opacity(0.3 * f), location: 0.7),
+ .init(color: Color(hex: 0xB9AEFB).opacity(0), location: 1),
+ ]),
+ center: center, startRadius: 0, endRadius: 20
+ )
+ )
+ // The dark side.
+ context.fill(disc, with: .color(Color(hex: 0x221B47)))
+ context.stroke(disc, with: .color(Color(hex: 0xB9AEFB).opacity(0.35)), lineWidth: 1)
+
+ // Lit area: the right half of the disc, closed by an elliptical
+ // terminator that bulges right for a crescent (f < 0.5) and left
+ // for a gibbous moon (f > 0.5).
+ guard f > 0 else { return }
+ let rx = r * abs(1 - 2 * f)
+ var lit = Path()
+ // Down the right edge of the disc, from the top (y grows downwards)…
+ let steps = 32
+ for i in 0...steps {
+ let angle = -Double.pi / 2 + Double(i) / Double(steps) * Double.pi // -90° … +90°
+ let point = CGPoint(
+ x: center.x + r * CGFloat(cos(angle)), y: center.y + r * CGFloat(sin(angle))
+ )
+ if i == 0 { lit.move(to: point) } else { lit.addLine(to: point) }
+ }
+ // …and back up along the terminator (an ellipse of width rx).
+ for i in 0...steps {
+ let t = Double(i) / Double(steps)
+ let angle = Double.pi / 2 - t * Double.pi // +90° … -90°
+ let x = center.x + (f > 0.5 ? -1 : 1) * rx * CGFloat(cos(angle))
+ let y = center.y + r * CGFloat(sin(angle))
+ lit.addLine(to: CGPoint(x: x, y: y))
+ }
+ lit.closeSubpath()
+
+ context.drawLayer { layer in
+ layer.clip(to: lit)
+ layer.fill(
+ disc,
+ with: .radialGradient(
+ Gradient(stops: [
+ .init(color: Color(hex: 0xFDFBFF), location: 0),
+ .init(color: Color(hex: 0xDDD6FF), location: 0.55),
+ .init(color: Color(hex: 0xA89CF2), location: 1),
+ ]),
+ center: CGPoint(x: 15.2, y: 12.8), startRadius: 0, endRadius: 31
+ )
+ )
+ // Craters.
+ for (x, y, cr, o) in [(25.0, 14.0, 2.6, 0.28), (29, 24, 1.8, 0.25), (20, 27, 3.2, 0.2), (15, 17, 1.6, 0.22)] {
+ layer.fill(
+ Path(ellipseIn: CGRect(x: x - cr, y: y - cr, width: 2 * cr, height: 2 * cr)),
+ with: .color(Color(hex: 0x8F82E0).opacity(o))
+ )
+ }
+ }
+ }
+ .frame(width: size, height: size)
+ .accessibilityHidden(true)
+ }
+}
+
+extension Color {
+ init(hex: UInt32) {
+ self.init(
+ .sRGB,
+ red: Double((hex >> 16) & 0xFF) / 255,
+ green: Double((hex >> 8) & 0xFF) / 255,
+ blue: Double(hex & 0xFF) / 255
+ )
+ }
+}
diff --git a/macos/Sources/MoonTask/MoonTaskApp.swift b/macos/Sources/MoonTask/MoonTaskApp.swift
new file mode 100644
index 0000000..ddb37d0
--- /dev/null
+++ b/macos/Sources/MoonTask/MoonTaskApp.swift
@@ -0,0 +1,59 @@
+import AppKit
+import MoonTaskCore
+import SwiftUI
+
+@main
+struct MoonTaskApp: App {
+ @NSApplicationDelegateAdaptor(AppDelegate.self) private var delegate
+ @State private var model = AppModel()
+ @AppStorage(SettingKey.theme) private var theme = ThemeChoice.dark.rawValue
+
+ var body: some Scene {
+ Window("MoonTask", id: "main") {
+ ContentView()
+ .environment(model)
+ .preferredColorScheme(ThemeChoice(rawValue: theme)?.colorScheme)
+ .frame(minWidth: 980, minHeight: 620)
+ .onAppear { model.start() }
+ }
+ .defaultSize(width: 1280, height: 800)
+ .commands { MoonTaskCommands(model: model) }
+ }
+}
+
+final class AppDelegate: NSObject, NSApplicationDelegate {
+ func applicationDidFinishLaunching(_ notification: Notification) {
+ // Also a regular app when started as a bare executable (swift run).
+ NSApp.setActivationPolicy(.regular)
+ NSApp.activate(ignoringOtherApps: true)
+ UserDefaults.standard.register(defaults: [
+ SettingKey.refreshInterval: 1.0,
+ SettingKey.showKernel: true,
+ SettingKey.confirmOwn: true,
+ ])
+ }
+
+ func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
+ true
+ }
+}
+
+struct MoonTaskCommands: Commands {
+ var model: AppModel
+
+ var body: some Commands {
+ CommandGroup(before: .sidebar) {
+ ForEach(Array(AppSection.allCases.enumerated()), id: \.element) { index, section in
+ Button(section.title) { model.section = section }
+ .keyboardShortcut(KeyEquivalent(Character("\(index + 1)")), modifiers: .command)
+ }
+ Divider()
+ }
+ CommandMenu("Monitor") {
+ Button(model.paused ? "Resume Updates" : "Pause Updates") { model.paused.toggle() }
+ .keyboardShortcut("p", modifiers: [.command, .shift])
+ Button("Refresh Now") { Task { await model.refresh(force: true) } }
+ .keyboardShortcut("r", modifiers: .command)
+ }
+ }
+}
diff --git a/macos/Sources/MoonTask/NetworkView.swift b/macos/Sources/MoonTask/NetworkView.swift
new file mode 100644
index 0000000..09959c4
--- /dev/null
+++ b/macos/Sources/MoonTask/NetworkView.swift
@@ -0,0 +1,82 @@
+import MoonTaskCore
+import SwiftUI
+
+struct NetworkView: View {
+ @Environment(AppModel.self) private var model
+ @State private var query = ""
+ @State private var listeningOnly = false
+ @State private var sortOrder = [KeyPathComparator(\Connection.processName)]
+
+ var body: some View {
+ let rows = model.connections
+ .filter { !listeningOnly || $0.isListening }
+ .filter { matches($0) }
+ .sorted(using: sortOrder)
+
+ VStack(alignment: .leading, spacing: 12) {
+ HStack(spacing: 12) {
+ Chip(text: "\(model.connections.filter { $0.proto == .tcp }.count) TCP")
+ Chip(text: "\(model.connections.filter { $0.proto == .udp }.count) UDP", tone: Palette.ownerSystem)
+ Chip(text: "\(model.connections.filter(\.isListening).count) listening", tone: Palette.success)
+ Spacer()
+ Toggle("Listening only", isOn: $listeningOnly)
+ .toggleStyle(.switch)
+ .controlSize(.small)
+ }
+ if model.connections.isEmpty {
+ GlassCard {
+ EmptyNote(
+ symbol: "network",
+ title: "Looking for connections …",
+ text: "MoonTask lists the sockets of your own processes. The system's and other users' connections need administrator rights on macOS."
+ )
+ }
+ } else {
+ Table(rows, sortOrder: $sortOrder) {
+ TableColumn("Process", value: \Connection.processName) { c in
+ HStack(spacing: 6) {
+ Text(c.processName).foregroundStyle(Palette.text)
+ Text(String(c.pid)).font(.figure(11, weight: .regular)).foregroundStyle(Palette.textFaint)
+ }
+ }
+ .width(min: 140, ideal: 200)
+ TableColumn("Protocol", value: \Connection.proto.rawValue) { c in
+ Chip(text: c.proto.rawValue + (c.isIPv6 ? "6" : ""), tone: c.proto == .tcp ? Palette.lavender : Palette.ownerSystem)
+ }
+ .width(70)
+ TableColumn("Local", value: \Connection.localPort) { c in
+ Text(endpoint(c.localAddress, c.localPort))
+ .font(.system(size: 11.5, design: .monospaced))
+ .textSelection(.enabled)
+ }
+ .width(min: 140, ideal: 200)
+ TableColumn("Remote", value: \Connection.remoteAddress) { c in
+ Text(c.remotePort == 0 ? "–" : endpoint(c.remoteAddress, c.remotePort))
+ .font(.system(size: 11.5, design: .monospaced))
+ .foregroundStyle(c.remotePort == 0 ? Palette.textFaint : Palette.text)
+ .textSelection(.enabled)
+ }
+ .width(min: 140, ideal: 220)
+ TableColumn("State", value: \Connection.state) { c in
+ Text(c.state).foregroundStyle(c.isListening ? Palette.success : Palette.textMuted)
+ }
+ .width(min: 80, ideal: 100)
+ }
+ .scrollContentBackground(.hidden)
+ .alternatingRowBackgrounds(.disabled)
+ .glass(cornerRadius: 14)
+ }
+ }
+ .padding(16)
+ .searchable(text: $query, placement: .toolbar, prompt: "Process, address or port")
+ .task { await model.refreshConnections() }
+ }
+
+ private func matches(_ c: Connection) -> Bool {
+ let q = query.trimmingCharacters(in: .whitespaces).lowercased()
+ if q.isEmpty { return true }
+ return c.processName.lowercased().contains(q)
+ || c.localAddress.contains(q) || c.remoteAddress.contains(q)
+ || String(c.localPort) == q || String(c.remotePort) == q || String(c.pid) == q
+ }
+}
diff --git a/macos/Sources/MoonTask/OverviewView.swift b/macos/Sources/MoonTask/OverviewView.swift
new file mode 100644
index 0000000..7cbc8e3
--- /dev/null
+++ b/macos/Sources/MoonTask/OverviewView.swift
@@ -0,0 +1,167 @@
+import MoonTaskCore
+import SwiftUI
+
+struct OverviewView: View {
+ @Environment(AppModel.self) private var model
+
+ var body: some View {
+ let s = model.snapshot
+ let h = model.history
+ ScrollView {
+ VStack(alignment: .leading, spacing: 16) {
+ LazyVGrid(columns: [GridItem(.adaptive(minimum: 200), spacing: 14)], spacing: 14) {
+ StatTile(
+ label: "CPU",
+ value: Format.percent(s.cpu.total),
+ detail: "\(model.systemInfo.cores) cores · user \(Format.percent(s.cpu.user, digits: 0)) · system \(Format.percent(s.cpu.system, digits: 0))",
+ fraction: s.cpu.total / 100,
+ series: h.cpu.values,
+ max: 100
+ )
+ StatTile(
+ label: "Memory",
+ value: Format.bytes(s.memory.used),
+ detail: "of \(Format.bytes(s.memory.total, precision: 0)) · \(Format.bytes(s.memory.cached)) cached",
+ fraction: s.memory.fraction,
+ series: h.memory.values,
+ max: Double(s.memory.total)
+ )
+ StatTile(
+ label: "Disk",
+ value: Format.rate(s.diskRead + s.diskWrite),
+ detail: "read \(Format.rate(s.diskRead)) · write \(Format.rate(s.diskWrite))",
+ fraction: min(1, (s.diskRead + s.diskWrite) / 200_000_000),
+ series: zip(h.diskRead.values, h.diskWrite.values).map { $0 + $1 },
+ max: nil
+ )
+ StatTile(
+ label: "Network",
+ value: Format.rate(s.networkIn + s.networkOut),
+ detail: "↓ \(Format.rate(s.networkIn)) · ↑ \(Format.rate(s.networkOut))",
+ fraction: min(1, (s.networkIn + s.networkOut) / 12_500_000),
+ series: zip(h.networkIn.values, h.networkOut.values).map { $0 + $1 },
+ max: nil,
+ tone: Palette.chart2
+ )
+ if let gpu = s.primaryGPU {
+ StatTile(
+ label: "GPU",
+ value: gpu.utilization.map { Format.percent($0) } ?? "–",
+ detail: [gpu.name, gpu.cores.map { "\($0) cores" }]
+ .compactMap { $0 }.joined(separator: " · "),
+ fraction: (gpu.utilization ?? 0) / 100,
+ series: h.gpu[gpu.id]?.values ?? [],
+ max: 100
+ )
+ }
+ }
+
+ HStack(alignment: .top, spacing: 14) {
+ GlassCard(title: "Busiest right now") {
+ TopList(rows: Array(s.processes.sorted { $0.cpu > $1.cpu }.prefix(6))) {
+ Format.percent($0.cpu)
+ }
+ }
+ GlassCard(title: "Largest in memory") {
+ TopList(rows: Array(s.processes.sorted { $0.memory > $1.memory }.prefix(6))) {
+ Format.bytes($0.memory)
+ }
+ }
+ GlassCard(title: "This Mac") {
+ Facts(items: machineFacts(s))
+ }
+ }
+
+ HStack(alignment: .top, spacing: 14) {
+ GlassCard(title: "Storage") {
+ if s.volumes.isEmpty {
+ Text("No volumes found.").foregroundStyle(Palette.textMuted)
+ }
+ ForEach(s.volumes) { v in
+ VStack(alignment: .leading, spacing: 5) {
+ HStack {
+ Image(systemName: v.isInternal ? "internaldrive" : "externaldrive")
+ .foregroundStyle(Palette.lavender)
+ Text(v.name).foregroundStyle(Palette.text)
+ Spacer()
+ Text("\(Format.bytes(v.available)) free of \(Format.bytes(v.total, precision: 0))")
+ .font(.figure(11.5, weight: .regular))
+ .foregroundStyle(Palette.textMuted)
+ }
+ .font(.system(size: 12.5))
+ Meter(fraction: v.fraction, tone: v.fraction > 0.9 ? Palette.warning : Palette.lavender)
+ }
+ }
+ }
+ GlassCard(title: "Coming and going") {
+ if model.events.isEmpty {
+ Text("Processes that start or end show up here.")
+ .font(.callout)
+ .foregroundStyle(Palette.textMuted)
+ }
+ ForEach(model.events.prefix(8)) { e in
+ HStack(spacing: 8) {
+ Image(systemName: e.kind == .started ? "arrow.up.right.circle.fill" : "xmark.circle")
+ .foregroundStyle(e.kind == .started ? Palette.success : Palette.textFaint)
+ Text(e.name).foregroundStyle(Palette.text).lineLimit(1)
+ Text(String(e.pid)).font(.figure(11, weight: .regular)).foregroundStyle(Palette.textFaint)
+ Spacer()
+ Text(e.time, style: .time)
+ .font(.figure(11, weight: .regular))
+ .foregroundStyle(Palette.textMuted)
+ }
+ .font(.system(size: 12.5))
+ }
+ }
+ }
+ }
+ .padding(20)
+ }
+ }
+
+ private func machineFacts(_ s: Snapshot) -> [(String, String)] {
+ let info = model.systemInfo
+ var facts: [(String, String)] = [
+ ("Name", info.hostName),
+ ("System", info.osVersion),
+ ("Chip", info.chip.isEmpty ? info.model : info.chip),
+ ]
+ if let p = info.performanceCores, let e = info.efficiencyCores {
+ facts.append(("Cores", "\(info.cores) (\(p) performance, \(e) efficiency)"))
+ } else {
+ facts.append(("Cores", "\(info.cores)"))
+ }
+ facts.append(("Memory", Format.bytes(info.memory, precision: 0)))
+ facts.append(("Up for", Format.duration(s.uptime)))
+ facts.append(("Processes", Format.count(s.processes.count)))
+ facts.append(("Temperature", s.thermal.label))
+ return facts
+ }
+}
+
+/// A short ranked list of processes with one measure.
+struct TopList: View {
+ var rows: [ProcessRow]
+ var value: (ProcessRow) -> String
+
+ init(rows: [ProcessRow], value: @escaping (ProcessRow) -> String) {
+ self.rows = rows
+ self.value = value
+ }
+
+ var body: some View {
+ VStack(spacing: 6) {
+ ForEach(rows) { p in
+ HStack(spacing: 8) {
+ OwnerDot(owner: p.owner)
+ Text(p.name).foregroundStyle(Palette.text).lineLimit(1)
+ Spacer()
+ Text(value(p))
+ .font(.figure(12))
+ .foregroundStyle(Palette.text)
+ }
+ .font(.system(size: 12.5))
+ }
+ }
+ }
+}
diff --git a/macos/Sources/MoonTask/PerformanceView.swift b/macos/Sources/MoonTask/PerformanceView.swift
new file mode 100644
index 0000000..817d745
--- /dev/null
+++ b/macos/Sources/MoonTask/PerformanceView.swift
@@ -0,0 +1,228 @@
+import Charts
+import MoonTaskCore
+import SwiftUI
+
+struct PerformanceView: View {
+ @Environment(AppModel.self) private var model
+
+ var body: some View {
+ let s = model.snapshot
+ let h = model.history
+ ScrollView {
+ VStack(alignment: .leading, spacing: 16) {
+ GlassCard(title: "CPU") {
+ AreaChart(
+ series: [
+ ChartSeries(label: "User", values: h.cpuUser.values, color: Palette.chart1),
+ ChartSeries(label: "System", values: h.cpuSystem.values, color: Palette.chart2),
+ ],
+ stacked: true, max: 100, format: { Format.percent($0, digits: 0) }
+ )
+ .frame(height: 170)
+ Facts(items: [
+ ("Total", Format.percent(s.cpu.total)),
+ ("User", Format.percent(s.cpu.user)),
+ ("System", Format.percent(s.cpu.system)),
+ ("Chip", model.systemInfo.chip),
+ ])
+ }
+
+ GlassCard(title: "Cores") {
+ LazyVGrid(columns: [GridItem(.adaptive(minimum: 120), spacing: 10)], spacing: 10) {
+ ForEach(Array(h.perCore.enumerated()), id: \.offset) { index, series in
+ VStack(alignment: .leading, spacing: 4) {
+ HStack {
+ Text("Core \(index + 1)").foregroundStyle(Palette.textMuted)
+ Spacer()
+ Text(Format.percent(series.last ?? 0, digits: 0)).foregroundStyle(Palette.text)
+ }
+ .font(.figure(11, weight: .regular))
+ Sparkline(values: series.values, max: 100)
+ .frame(height: 30)
+ }
+ .padding(8)
+ .inset()
+ }
+ }
+ }
+
+ HStack(alignment: .top, spacing: 16) {
+ GlassCard(title: "Memory") {
+ AreaChart(
+ series: [ChartSeries(label: "Used", values: h.memory.values, color: Palette.chart1)],
+ stacked: false, max: Double(s.memory.total), format: { Format.bytes($0) }
+ )
+ .frame(height: 150)
+ Facts(items: [
+ ("Used", "\(Format.bytes(s.memory.used)) of \(Format.bytes(s.memory.total, precision: 0))"),
+ ("App memory", Format.bytes(s.memory.app)),
+ ("Wired", Format.bytes(s.memory.wired)),
+ ("Compressed", Format.bytes(s.memory.compressed)),
+ ("Cached files", Format.bytes(s.memory.cached)),
+ ("Swap", s.memory.swapTotal > 0
+ ? "\(Format.bytes(s.memory.swapUsed)) of \(Format.bytes(s.memory.swapTotal))"
+ : "not used"),
+ ])
+ }
+ ForEach(s.gpus) { gpu in
+ GlassCard(title: gpu.name) {
+ if gpu.utilization != nil {
+ AreaChart(
+ series: [ChartSeries(label: "GPU", values: h.gpu[gpu.id]?.values ?? [], color: Palette.chart1)],
+ stacked: false, max: 100, format: { Format.percent($0, digits: 0) }
+ )
+ .frame(height: 150)
+ } else {
+ Text("This GPU's driver doesn't report its load.")
+ .foregroundStyle(Palette.textMuted)
+ }
+ Facts(items: gpuFacts(gpu))
+ }
+ }
+ }
+
+ HStack(alignment: .top, spacing: 16) {
+ GlassCard(title: "Disk") {
+ AreaChart(
+ series: [
+ ChartSeries(label: "Read", values: h.diskRead.values, color: Palette.chart1),
+ ChartSeries(label: "Write", values: h.diskWrite.values, color: Palette.chart2),
+ ],
+ stacked: false, max: nil, format: { Format.rate($0) }
+ )
+ .frame(height: 150)
+ }
+ GlassCard(title: "Network") {
+ AreaChart(
+ series: [
+ ChartSeries(label: "Received", values: h.networkIn.values, color: Palette.chart1),
+ ChartSeries(label: "Sent", values: h.networkOut.values, color: Palette.chart2),
+ ],
+ stacked: false, max: nil, format: { Format.rate($0) }
+ )
+ .frame(height: 150)
+ }
+ }
+
+ GlassCard(title: "Temperature") {
+ HStack(spacing: 10) {
+ Image(systemName: s.thermal == .nominal ? "thermometer.low" : "thermometer.high")
+ .foregroundStyle(s.thermal == .nominal ? Palette.success : Palette.warning)
+ Text(s.thermal.label).foregroundStyle(Palette.text)
+ Spacer()
+ Text("macOS reports how hot the Mac runs as a level, not in degrees.")
+ .font(.caption)
+ .foregroundStyle(Palette.textMuted)
+ }
+ }
+ }
+ .padding(20)
+ }
+ }
+
+ private func gpuFacts(_ gpu: GPUStats) -> [(String, String)] {
+ var items: [(String, String)] = [("Load", gpu.utilization.map { Format.percent($0) } ?? "not reported")]
+ if let used = gpu.memoryUsed { items.append(("Memory in use", Format.bytes(used))) }
+ if let cores = gpu.cores { items.append(("Cores", "\(cores)")) }
+ return items
+ }
+}
+
+struct ChartSeries: Identifiable {
+ var id: String { label }
+ var label: String
+ var values: [Double]
+ var color: Color
+}
+
+/// A calm area chart over the last two minutes, with hover read-outs.
+struct AreaChart: View {
+ var series: [ChartSeries]
+ var stacked: Bool
+ var max: Double?
+ var format: (Double) -> String
+
+ @State private var hover: Int?
+
+ private struct Point: Identifiable {
+ var id: String { "\(series)-\(index)" }
+ var series: String
+ var index: Int
+ var value: Double
+ }
+
+ var body: some View {
+ let length = series.map(\.values.count).max() ?? 0
+ let points = series.flatMap { s in
+ s.values.enumerated().map { Point(series: s.label, index: length - s.values.count + $0.offset, value: $0.element) }
+ }
+ Chart {
+ ForEach(points) { p in
+ AreaMark(
+ x: .value("Time", p.index),
+ y: .value("Value", p.value),
+ stacking: stacked ? .standard : .unstacked
+ )
+ .foregroundStyle(by: .value("Series", p.series))
+ .opacity(0.35)
+ .interpolationMethod(.monotone)
+ // Lines don't stack, so stacked charts show the areas only.
+ if !stacked {
+ LineMark(x: .value("Time", p.index), y: .value("Value", p.value))
+ .foregroundStyle(by: .value("Series", p.series))
+ .interpolationMethod(.monotone)
+ .lineStyle(StrokeStyle(lineWidth: 1.5))
+ }
+ }
+ if let hover {
+ RuleMark(x: .value("Time", hover))
+ .foregroundStyle(Palette.borderStrong)
+ }
+ }
+ .chartForegroundStyleScale(
+ domain: series.map(\.label),
+ range: series.map(\.color)
+ )
+ .chartXAxis(.hidden)
+ .chartXScale(domain: 0...Swift.max(1, length - 1))
+ .chartYScale(domain: 0...Swift.max(max ?? (points.map(\.value).max() ?? 0) * 1.15, 1e-9))
+ .chartYAxis {
+ AxisMarks(position: .leading, values: .automatic(desiredCount: 3)) { value in
+ AxisGridLine().foregroundStyle(Palette.grid)
+ AxisValueLabel {
+ if let v = value.as(Double.self) {
+ Text(format(v)).font(.system(size: 9.5)).foregroundStyle(Palette.textFaint)
+ }
+ }
+ }
+ }
+ .chartLegend(series.count > 1 ? .visible : .hidden)
+ .chartOverlay { proxy in
+ Rectangle().fill(.clear).contentShape(Rectangle())
+ .onContinuousHover { phase in
+ switch phase {
+ case .active(let location):
+ hover = proxy.value(atX: location.x, as: Int.self)
+ case .ended:
+ hover = nil
+ }
+ }
+ }
+ .overlay(alignment: .topTrailing) {
+ if let hover {
+ VStack(alignment: .trailing, spacing: 2) {
+ ForEach(series) { s in
+ let i = hover - (length - s.values.count)
+ if i >= 0 && i < s.values.count {
+ Text("\(s.label): \(format(s.values[i]))")
+ }
+ }
+ }
+ .font(.figure(10.5, weight: .regular))
+ .foregroundStyle(Palette.text)
+ .padding(6)
+ .inset(cornerRadius: 6)
+ }
+ }
+ }
+}
diff --git a/macos/Sources/MoonTask/ProcessDetailView.swift b/macos/Sources/MoonTask/ProcessDetailView.swift
new file mode 100644
index 0000000..c0d35da
--- /dev/null
+++ b/macos/Sources/MoonTask/ProcessDetailView.swift
@@ -0,0 +1,312 @@
+import AppKit
+import MoonTaskCore
+import MoonTaskSystem
+import SwiftUI
+import UniformTypeIdentifiers
+
+/// The detail panel of the selected process.
+struct ProcessDetailView: View {
+ @Environment(AppModel.self) private var model
+ var row: ProcessRow
+ var onAction: (ProcessAction, ProcessRow) -> Void
+
+ @State private var tab: DetailTab = .general
+ @State private var details = ProcessDetails()
+ @State private var loadedFor: ProcessIdentity?
+
+ enum DetailTab: String, CaseIterable, Identifiable {
+ case general = "General", files = "Files", network = "Network", environment = "Environment"
+ var id: String { rawValue }
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 14) {
+ header
+ actions
+ Picker("", selection: $tab) {
+ ForEach(DetailTab.allCases) { Text($0.rawValue).tag($0) }
+ }
+ .pickerStyle(.segmented)
+ .labelsHidden()
+
+ ScrollView {
+ VStack(alignment: .leading, spacing: 14) {
+ switch tab {
+ case .general: general
+ case .files: files
+ case .network: network
+ case .environment: environment
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ }
+ .padding(16)
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
+ .background(SkyBackground())
+ .task(id: row.identity) { await load() }
+ .task(id: tab) { await load() }
+ }
+
+ private func load() async {
+ let current = row
+ details = await Task.detached(priority: .userInitiated) {
+ ProcessInspector.details(of: current)
+ }.value
+ loadedFor = current.identity
+ }
+
+ // MARK: - Parts
+
+ private var header: some View {
+ HStack(spacing: 12) {
+ AppIcon(path: row.path)
+ VStack(alignment: .leading, spacing: 3) {
+ Text(row.name)
+ .font(.system(size: 17, weight: .semibold))
+ .foregroundStyle(Palette.text)
+ .lineLimit(1)
+ HStack(spacing: 6) {
+ OwnerDot(owner: row.owner)
+ Text(verbatim: "PID \(row.pid) · \(row.user ?? row.owner.label)")
+ .font(.system(size: 11.5))
+ .foregroundStyle(Palette.textMuted)
+ Chip(text: row.state.label, tone: row.state.tone)
+ }
+ }
+ }
+ }
+
+ private var actions: some View {
+ HStack(spacing: 8) {
+ Button("End") { onAction(.end, row) }
+ .disabled(!Safety.isAllowed(.end, on: row))
+ Button("Force Quit") { onAction(.forceQuit, row) }
+ .disabled(!Safety.isAllowed(.forceQuit, on: row))
+ if row.state == .stopped {
+ Button("Resume") { onAction(.resume, row) }
+ } else {
+ Button("Suspend") { onAction(.suspend, row) }
+ .disabled(!Safety.isAllowed(.suspend, on: row))
+ }
+ Menu("More") {
+ Button("End Process Tree") { onAction(.endTree, row) }
+ Menu("Priority") {
+ ForEach(PriorityLevel.allCases) { level in
+ Button(level.label) { onAction(.setPriority(level.nice), row) }
+ }
+ }
+ if let path = row.path {
+ Button("Show in Finder") {
+ NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)])
+ }
+ }
+ }
+ .disabled(row.isProtected)
+ .fixedSize()
+ }
+ .controlSize(.small)
+ }
+
+ private var general: some View {
+ let cpu = model.history.processCPU[row.identity]?.values ?? []
+ let memory = model.history.processMemory[row.identity]?.values ?? []
+ return VStack(alignment: .leading, spacing: 14) {
+ HStack(spacing: 10) {
+ MiniStat(label: "CPU", value: Format.percent(row.cpu), series: cpu, max: nil)
+ MiniStat(label: "Memory", value: Format.bytes(row.memory), series: memory, max: nil, tone: Palette.chart2)
+ }
+ GlassCard(title: "About") {
+ Facts(items: facts)
+ }
+ if let args = details.arguments, !args.isEmpty {
+ GlassCard(title: "Command line") {
+ Text(args.joined(separator: " "))
+ .font(.system(size: 11.5, design: .monospaced))
+ .foregroundStyle(Palette.text)
+ .textSelection(.enabled)
+ }
+ }
+ if row.isProtected {
+ Label("Protected: ending it would take macOS or MoonTask down.", systemImage: "lock.shield")
+ .font(.callout)
+ .foregroundStyle(Palette.textMuted)
+ }
+ }
+ }
+
+ private var facts: [(String, String)] {
+ var items: [(String, String)] = [
+ ("Started", Format.dateTime(Date(timeIntervalSince1970: row.startTime))),
+ ("Running for", Format.duration(Date().timeIntervalSince1970 - row.startTime)),
+ ("CPU time", Format.cpuTime(row.cpuTime)),
+ ("Threads", row.threads.map(String.init) ?? "not readable"),
+ ("Disk", "read \(Format.rate(row.diskRead)) · write \(Format.rate(row.diskWrite))"),
+ ("Priority", "nice \(row.nice)"),
+ ]
+ if let parent = row.parentPid {
+ let name = model.process(pid: parent)?.name ?? "–"
+ items.append(("Parent", "\(name) (\(parent))"))
+ }
+ items.append(("Path", row.path ?? "not readable"))
+ return items
+ }
+
+ private var files: some View {
+ Group {
+ if let files = details.openFiles {
+ if files.isEmpty {
+ EmptyNote(symbol: "doc", title: "No open files", text: "This process has no files open right now.")
+ } else {
+ GlassCard(title: "\(files.count) open files") {
+ ForEach(files, id: \.self) { path in
+ Text(path)
+ .font(.system(size: 11.5, design: .monospaced))
+ .foregroundStyle(Palette.text)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ .help(path)
+ .textSelection(.enabled)
+ }
+ }
+ }
+ } else {
+ notReadable
+ }
+ }
+ }
+
+ private var network: some View {
+ Group {
+ if let connections = details.connections {
+ if connections.isEmpty {
+ EmptyNote(symbol: "network.slash", title: "No connections", text: "This process has no network sockets open.")
+ } else {
+ GlassCard(title: "\(connections.count) sockets") {
+ ForEach(connections) { c in
+ VStack(alignment: .leading, spacing: 2) {
+ HStack {
+ Chip(text: c.proto.rawValue, tone: c.proto == .tcp ? Palette.lavender : Palette.ownerSystem)
+ Text(c.state).foregroundStyle(Palette.textMuted)
+ }
+ Text("\(endpoint(c.localAddress, c.localPort)) → \(c.remotePort == 0 ? "–" : endpoint(c.remoteAddress, c.remotePort))")
+ .font(.system(size: 11.5, design: .monospaced))
+ .foregroundStyle(Palette.text)
+ .textSelection(.enabled)
+ }
+ .font(.system(size: 11.5))
+ }
+ }
+ }
+ } else {
+ notReadable
+ }
+ }
+ }
+
+ private var environment: some View {
+ Group {
+ if let env = details.environment {
+ GlassCard(title: "\(env.count) variables") {
+ ForEach(env) { v in
+ VStack(alignment: .leading, spacing: 1) {
+ Text(v.name).font(.system(size: 11, weight: .semibold)).foregroundStyle(Palette.accent)
+ Text(v.value)
+ .font(.system(size: 11.5, design: .monospaced))
+ .foregroundStyle(Palette.text)
+ .lineLimit(3)
+ .textSelection(.enabled)
+ }
+ }
+ }
+ } else {
+ notReadable
+ }
+ }
+ }
+
+ private var notReadable: some View {
+ EmptyNote(
+ symbol: "lock",
+ title: "Not readable",
+ text: "macOS shows this only for your own processes. Other users' and system processes need administrator rights."
+ )
+ }
+}
+
+func endpoint(_ address: String, _ port: Int) -> String {
+ address.contains(":") ? "[\(address)]:\(port)" : "\(address):\(port)"
+}
+
+/// The details of an app group in the Apps view.
+struct GroupDetailView: View {
+ var row: VisibleRow
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 14) {
+ HStack(spacing: 12) {
+ AppIcon(path: row.process.path)
+ VStack(alignment: .leading) {
+ Text(row.process.name).font(.system(size: 17, weight: .semibold)).foregroundStyle(Palette.text)
+ Text("\(row.members.count) processes").font(.callout).foregroundStyle(Palette.textMuted)
+ }
+ }
+ GlassCard(title: "Together") {
+ Facts(items: [
+ ("CPU", Format.percent(row.process.cpu)),
+ ("Memory", Format.bytes(row.process.memory)),
+ ("Threads", "\(row.process.threads ?? 0)"),
+ ("Users", row.process.user ?? "–"),
+ ])
+ }
+ Text("Open the group to act on single processes.")
+ .font(.callout)
+ .foregroundStyle(Palette.textMuted)
+ Spacer()
+ }
+ .padding(16)
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
+ .background(SkyBackground())
+ }
+}
+
+/// A process' app icon, or a generic one.
+struct AppIcon: View {
+ var path: String?
+
+ var body: some View {
+ Image(nsImage: icon)
+ .resizable()
+ .frame(width: 36, height: 36)
+ .accessibilityHidden(true)
+ }
+
+ private var icon: NSImage {
+ guard let path else { return NSWorkspace.shared.icon(for: .unixExecutable) }
+ // Use the app bundle's icon for executables inside an .app.
+ if let range = path.range(of: ".app/", options: .backwards) {
+ return NSWorkspace.shared.icon(forFile: String(path[.. = []
+ @State private var openGroups: Set = []
+ @State private var selection: VisibleRow.ID?
+ @State private var showDetail = true
+ @State private var pending: PendingAction?
+
+ struct PendingAction: Identifiable {
+ let id = UUID()
+ let action: ProcessAction
+ let row: ProcessRow
+ let descendants: Int
+ }
+
+ var body: some View {
+ let processes = model.snapshot.processes
+ let rows = visibleRows(processes, VisibleOptions(
+ mode: mode, sort: sort, query: query, owner: owner, showKernel: showKernel,
+ collapsed: collapsed, openGroups: openGroups
+ ))
+ let selected = rows.first { $0.id == selection }
+
+ table(rows)
+ .scrollContentBackground(.hidden)
+ .alternatingRowBackgrounds(.disabled)
+ .glass(cornerRadius: 14)
+ .padding(16)
+ .searchable(text: $query, placement: .toolbar, prompt: "Name, PID, user or path")
+ .toolbar { toolbar(selected) }
+ .inspector(isPresented: $showDetail) {
+ Group {
+ if let selected, selected.kind == .process {
+ ProcessDetailView(row: selected.process, onAction: request)
+ } else if let selected {
+ GroupDetailView(row: selected)
+ } else {
+ EmptyNote(
+ symbol: "cursorarrow.click",
+ title: "No process selected",
+ text: "Select a process to see what it is, what it has open and what you can do with it."
+ )
+ }
+ }
+ .inspectorColumnWidth(min: 280, ideal: 330, max: 460)
+ }
+ .onChange(of: sortOrder) { _, order in
+ if let first = order.first { sort = SortState(key: key(for: first.keyPath), ascending: first.order == .forward) }
+ }
+ .onDeleteCommand {
+ if let selected, selected.kind == .process { request(.end, selected.process) }
+ }
+ .confirmationDialog(
+ pending.map { "\($0.action.label) \($0.row.name)?" } ?? "",
+ isPresented: Binding(get: { pending != nil }, set: { if !$0 { pending = nil } }),
+ presenting: pending
+ ) { p in
+ Button(p.action.label, role: .destructive) { model.perform(p.action, on: p.row) }
+ Button("Cancel", role: .cancel) {}
+ } message: { p in
+ Text(Safety.consequence(p.action, on: p.row, descendants: p.descendants)
+ + (p.row.owner == .current ? "" : "\n\nIt belongs to \(p.row.user ?? p.row.owner.label.lowercased()), not to you."))
+ }
+ }
+
+ // MARK: - Table
+
+ private func table(_ rows: [VisibleRow]) -> some View {
+ Table(rows, selection: $selection, sortOrder: $sortOrder) {
+ TableColumn("Name", value: \VisibleRow.sortName) { row in
+ NameCell(row: row, isFresh: model.fresh.contains(row.process.identity)) { toggle(row) }
+ }
+ .width(min: 160, ideal: 220)
+ TableColumn("PID", value: \VisibleRow.sortPid) { row in
+ Text(row.kind == .group ? "" : String(row.process.pid))
+ .font(.figure(12, weight: .regular))
+ .foregroundStyle(Palette.textMuted)
+ }
+ .width(min: 50, ideal: 64, max: 80)
+ TableColumn("CPU", value: \VisibleRow.sortCPU) { row in
+ HeatCell(text: row.process.cpu < 0.05 ? "0.0" : String(format: "%.1f", row.process.cpu), load: row.process.cpu)
+ }
+ .width(min: 54, ideal: 64, max: 90)
+ TableColumn("Memory", value: \VisibleRow.sortMemory) { row in
+ Text(Format.bytes(row.process.memory))
+ .font(.figure(12, weight: .regular))
+ .frame(maxWidth: .infinity, alignment: .trailing)
+ }
+ .width(min: 70, ideal: 86, max: 120)
+ TableColumn("Threads", value: \VisibleRow.sortThreads) { row in
+ Text(row.process.threads.map(String.init) ?? "–")
+ .font(.figure(12, weight: .regular))
+ .foregroundStyle(Palette.textMuted)
+ .frame(maxWidth: .infinity, alignment: .trailing)
+ }
+ .width(min: 50, ideal: 60, max: 80)
+ TableColumn("Disk", value: \VisibleRow.sortDisk) { row in
+ let total = row.process.diskRead + row.process.diskWrite
+ Text(total > 0 ? Format.rate(total) : "")
+ .font(.figure(12, weight: .regular))
+ .foregroundStyle(Palette.textMuted)
+ .frame(maxWidth: .infinity, alignment: .trailing)
+ }
+ .width(min: 60, ideal: 80, max: 110)
+ TableColumn("User", value: \VisibleRow.sortUser) { row in
+ Text(row.process.user ?? "–").foregroundStyle(Palette.textMuted).lineLimit(1)
+ }
+ .width(min: 60, ideal: 84, max: 160)
+ TableColumn("State", value: \VisibleRow.sortState) { row in
+ Text(row.process.state.label)
+ .foregroundStyle(row.process.state.tone)
+ }
+ .width(min: 60, ideal: 80, max: 100)
+ }
+ .contextMenu(forSelectionType: VisibleRow.ID.self) { ids in
+ if let id = ids.first, let row = rows.first(where: { $0.id == id }), row.kind == .process {
+ actionMenu(row.process)
+ }
+ } primaryAction: { ids in
+ if let id = ids.first, let row = rows.first(where: { $0.id == id }) { toggle(row) }
+ }
+ }
+
+ private static let sortKeys: [PartialKeyPath: SortKey] = [
+ \VisibleRow.sortName: .name,
+ \VisibleRow.sortPid: .pid,
+ \VisibleRow.sortUser: .user,
+ \VisibleRow.sortCPU: .cpu,
+ \VisibleRow.sortMemory: .memory,
+ \VisibleRow.sortThreads: .threads,
+ \VisibleRow.sortDisk: .disk,
+ \VisibleRow.sortState: .state,
+ ]
+
+ private func key(for keyPath: PartialKeyPath) -> SortKey {
+ Self.sortKeys[keyPath] ?? .cpu
+ }
+
+ private func toggle(_ row: VisibleRow) {
+ guard row.hasChildren else { return }
+ if row.kind == .group {
+ if openGroups.contains(row.id) { openGroups.remove(row.id) } else { openGroups.insert(row.id) }
+ } else {
+ let pid = row.process.pid
+ if collapsed.contains(pid) { collapsed.remove(pid) } else { collapsed.insert(pid) }
+ }
+ }
+
+ // MARK: - Actions
+
+ @ViewBuilder private func actionMenu(_ p: ProcessRow) -> some View {
+ Button("End") { request(.end, p) }.disabled(!Safety.isAllowed(.end, on: p))
+ Button("Force Quit") { request(.forceQuit, p) }.disabled(!Safety.isAllowed(.forceQuit, on: p))
+ Button("End Process Tree") { request(.endTree, p) }.disabled(!Safety.isAllowed(.endTree, on: p))
+ Divider()
+ if p.state == .stopped {
+ Button("Resume") { request(.resume, p) }
+ } else {
+ Button("Suspend") { request(.suspend, p) }.disabled(!Safety.isAllowed(.suspend, on: p))
+ }
+ Menu("Priority") {
+ ForEach(PriorityLevel.allCases) { level in
+ Button(level.label) { request(.setPriority(level.nice), p) }
+ }
+ }
+ .disabled(p.isProtected)
+ Divider()
+ if let path = p.path {
+ Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)]) }
+ }
+ Button("Copy PID") { copy("\(p.pid)") }
+ }
+
+ private func request(_ action: ProcessAction, _ row: ProcessRow) {
+ guard Safety.isAllowed(action, on: row) else {
+ model.message = ControlError.protected(row.name).errorDescription
+ return
+ }
+ if Safety.needsConfirmation(action, on: row, confirmOwn: confirmOwn) {
+ pending = PendingAction(
+ action: action, row: row,
+ descendants: countDescendants(model.snapshot.processes, of: row.pid)
+ )
+ } else {
+ model.perform(action, on: row)
+ }
+ }
+
+ @ToolbarContentBuilder private func toolbar(_ selected: VisibleRow?) -> some ToolbarContent {
+ ToolbarItem(placement: .principal) {
+ Picker("View", selection: $mode) {
+ ForEach(ViewMode.allCases, id: \.self) { Text($0.label).tag($0) }
+ }
+ .pickerStyle(.segmented)
+ .help("Tree: parents and children · List: flat · Apps: grouped by name")
+ }
+ ToolbarItem {
+ Picker("Owner", selection: $owner) {
+ ForEach(OwnerFilter.allCases, id: \.self) { Text($0.label).tag($0) }
+ }
+ .help("Whose processes to show")
+ }
+ ToolbarItem {
+ Button {
+ if let p = selected?.process, selected?.kind == .process { request(.end, p) }
+ } label: {
+ Label("End", systemImage: "xmark.circle")
+ }
+ .disabled(selected?.kind != .process || !(selected.map { Safety.isAllowed(.end, on: $0.process) } ?? false))
+ .help("End the selected process (⌫)")
+ }
+ ToolbarItem {
+ Button { showDetail.toggle() } label: { Label("Details", systemImage: "sidebar.right") }
+ .help("Show or hide the details")
+ }
+ }
+
+ private func copy(_ text: String) {
+ NSPasteboard.general.clearContents()
+ NSPasteboard.general.setString(text, forType: .string)
+ }
+}
+
+enum PriorityLevel: Int32, CaseIterable, Identifiable {
+ case normal = 0, belowNormal = 5, low = 10, lowest = 20
+ var id: Int32 { rawValue }
+ var nice: Int32 { rawValue }
+
+ var label: String {
+ switch self {
+ case .normal: return "Normal"
+ case .belowNormal: return "Below normal"
+ case .low: return "Low"
+ case .lowest: return "Lowest (background)"
+ }
+ }
+}
+
+/// The name column: indentation, disclosure, owner dot, name and badges.
+private struct NameCell: View {
+ var row: VisibleRow
+ var isFresh: Bool
+ var onToggle: () -> Void
+
+ var body: some View {
+ HStack(spacing: 5) {
+ if row.depth > 0 { Spacer().frame(width: CGFloat(row.depth) * 14) }
+ if row.hasChildren {
+ Button(action: onToggle) {
+ Image(systemName: row.isExpanded ? "chevron.down" : "chevron.right")
+ .font(.system(size: 9, weight: .bold))
+ .foregroundStyle(Palette.textMuted)
+ .frame(width: 12)
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel(row.isExpanded ? "Collapse \(row.process.name)" : "Expand \(row.process.name)")
+ } else {
+ Spacer().frame(width: 12)
+ }
+ OwnerDot(owner: row.process.owner)
+ Text(row.process.name)
+ .fontWeight(.medium)
+ .foregroundStyle(Palette.text)
+ .lineLimit(1)
+ if row.kind == .group {
+ Chip(text: "\(row.members.count)")
+ }
+ if row.process.isProtected && row.kind == .process {
+ Image(systemName: "lock.shield")
+ .font(.system(size: 10))
+ .foregroundStyle(Palette.textFaint)
+ .help("Protected — ending it would take macOS or MoonTask down")
+ }
+ }
+ .opacity(row.isDimmed ? 0.45 : 1)
+ .padding(.vertical, 1)
+ .background(isFresh ? Palette.fresh : Color.clear)
+ .help(row.process.path ?? row.process.name)
+ }
+}
+
+/// A load cell with a calm heat tint, like Task Manager's columns.
+private struct HeatCell: View {
+ var text: String
+ var load: Double
+
+ var body: some View {
+ Text(text)
+ .font(.figure(12, weight: .regular))
+ .frame(maxWidth: .infinity, alignment: .trailing)
+ .padding(.horizontal, 4)
+ .background(
+ RoundedRectangle(cornerRadius: 4)
+ .fill(Palette.chart1.opacity(load < 0.5 ? 0 : 0.08 + min(load, 50) * 0.008))
+ )
+ }
+}
diff --git a/macos/Sources/MoonTask/ServicesView.swift b/macos/Sources/MoonTask/ServicesView.swift
new file mode 100644
index 0000000..fe39e10
--- /dev/null
+++ b/macos/Sources/MoonTask/ServicesView.swift
@@ -0,0 +1,80 @@
+import MoonTaskCore
+import SwiftUI
+
+struct ServicesView: View {
+ @Environment(AppModel.self) private var model
+ @State private var query = ""
+ @State private var hideApple = true
+ @State private var selection: LaunchJob.ID?
+ @State private var pending: (job: LaunchJob, stop: Bool)?
+
+ var body: some View {
+ let jobs = model.jobs
+ .filter { !hideApple || !$0.isApple }
+ .filter { query.isEmpty || $0.label.localizedCaseInsensitiveContains(query) }
+ let selected = jobs.first { $0.id == selection }
+
+ VStack(alignment: .leading, spacing: 12) {
+ HStack(spacing: 10) {
+ Chip(text: "\(model.jobs.filter(\.isRunning).count) running", tone: Palette.success)
+ Chip(text: "\(model.jobs.count) jobs")
+ Spacer()
+ Toggle("Hide Apple's", isOn: $hideApple)
+ .toggleStyle(.switch)
+ .controlSize(.small)
+ Button("Start") { if let selected { pending = (selected, false) } }
+ .disabled(selected == nil)
+ Button("Stop") { if let selected { pending = (selected, true) } }
+ .disabled(selected?.isRunning != true)
+ Button { Task { await model.refreshJobs() } } label: { Image(systemName: "arrow.clockwise") }
+ .help("Reload")
+ }
+ .controlSize(.small)
+
+ Table(jobs, selection: $selection) {
+ TableColumn("Label") { job in
+ HStack(spacing: 6) {
+ Circle()
+ .fill(job.isRunning ? Palette.success : Palette.textFaint)
+ .frame(width: 7, height: 7)
+ Text(job.label).foregroundStyle(Palette.text).lineLimit(1)
+ }
+ }
+ .width(min: 260, ideal: 420)
+ TableColumn("State") { job in
+ Text(job.isRunning ? "Running" : "Not running")
+ .foregroundStyle(job.isRunning ? Palette.success : Palette.textMuted)
+ }
+ .width(min: 90, ideal: 110)
+ TableColumn("PID") { job in
+ Text(job.pid.map(String.init) ?? "–").font(.figure(12, weight: .regular))
+ }
+ .width(min: 50, ideal: 70)
+ TableColumn("Last exit") { job in
+ Text(job.lastExitStatus.map { $0 == 0 ? "OK" : "code \($0)" } ?? "–")
+ .foregroundStyle((job.lastExitStatus ?? 0) == 0 ? Palette.textMuted : Palette.warning)
+ }
+ .width(min: 70, ideal: 90)
+ }
+ .scrollContentBackground(.hidden)
+ .alternatingRowBackgrounds(.disabled)
+ .glass(cornerRadius: 14)
+ }
+ .padding(16)
+ .searchable(text: $query, placement: .toolbar, prompt: "Label")
+ .task { await model.refreshJobs() }
+ .confirmationDialog(
+ pending.map { ($0.stop ? "Stop " : "Start ") + $0.job.label + "?" } ?? "",
+ isPresented: Binding(get: { pending != nil }, set: { if !$0 { pending = nil } })
+ ) {
+ if let pending {
+ Button(pending.stop ? "Stop" : "Start", role: pending.stop ? .destructive : nil) {
+ if pending.stop { model.stopJob(pending.job) } else { model.startJob(pending.job) }
+ }
+ }
+ Button("Cancel", role: .cancel) {}
+ } message: {
+ Text("launchd will \(pending?.stop == true ? "stop" : "start") this agent of your session. Agents that are set to keep running start again by themselves.")
+ }
+ }
+}
diff --git a/macos/Sources/MoonTask/SettingsView.swift b/macos/Sources/MoonTask/SettingsView.swift
new file mode 100644
index 0000000..254482c
--- /dev/null
+++ b/macos/Sources/MoonTask/SettingsView.swift
@@ -0,0 +1,55 @@
+import MoonTaskCore
+import SwiftUI
+
+struct SettingsView: View {
+ @AppStorage(SettingKey.theme) private var theme = ThemeChoice.dark.rawValue
+ @AppStorage(SettingKey.refreshInterval) private var interval = 1.0
+ @AppStorage(SettingKey.showKernel) private var showKernel = true
+ @AppStorage(SettingKey.confirmOwn) private var confirmOwn = true
+
+ var body: some View {
+ ScrollView {
+ VStack(alignment: .leading, spacing: 16) {
+ GlassCard(title: "Look") {
+ Picker("Theme", selection: $theme) {
+ ForEach(ThemeChoice.allCases) { Text($0.label).tag($0.rawValue) }
+ }
+ .pickerStyle(.segmented)
+ .frame(maxWidth: 360)
+ }
+ GlassCard(title: "Updates") {
+ Picker("Refresh every", selection: $interval) {
+ Text("0.5 s").tag(0.5)
+ Text("1 s").tag(1.0)
+ Text("2 s").tag(2.0)
+ Text("5 s").tag(5.0)
+ }
+ .pickerStyle(.segmented)
+ .frame(maxWidth: 360)
+ Text("MoonTask measures once per interval. Longer intervals use even less energy.")
+ .font(.callout)
+ .foregroundStyle(Palette.textMuted)
+ }
+ GlassCard(title: "Processes") {
+ Toggle("Show kernel_task", isOn: $showKernel)
+ Toggle("Ask before ending my own processes", isOn: $confirmOwn)
+ Text("Ending another user's or a system process, and ending a whole tree, always asks first. The kernel, launchd, WindowServer, loginwindow and MoonTask itself can't be ended at all.")
+ .font(.callout)
+ .foregroundStyle(Palette.textMuted)
+ }
+ GlassCard(title: "About") {
+ Facts(items: [
+ ("Version", Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "dev"),
+ ("Source", "github.com/Luna-OS/Moon-Task"),
+ ("License", "MIT"),
+ ])
+ Text("No telemetry and no network access of its own. Everything MoonTask shows stays on your Mac.")
+ .font(.callout)
+ .foregroundStyle(Palette.textMuted)
+ }
+ }
+ .padding(20)
+ .frame(maxWidth: 720, alignment: .leading)
+ }
+ }
+}
diff --git a/macos/Sources/MoonTask/SkyBackground.swift b/macos/Sources/MoonTask/SkyBackground.swift
new file mode 100644
index 0000000..e80b96b
--- /dev/null
+++ b/macos/Sources/MoonTask/SkyBackground.swift
@@ -0,0 +1,73 @@
+import SwiftUI
+
+/// The fixed, decorative night sky behind the app: a lavender glow, a few
+/// stars and a crescent moon in the corner. In the day theme it fades to a
+/// soft lavender wash.
+struct SkyBackground: View {
+ @Environment(\.colorScheme) private var scheme
+
+ var body: some View {
+ ZStack {
+ Palette.background
+ GeometryReader { geo in
+ let w = geo.size.width, h = geo.size.height
+ ZStack {
+ RadialGradient(
+ colors: [Color(hex: 0xB9AEFB).opacity(scheme == .dark ? 0.16 : 0.22), .clear],
+ center: UnitPoint(x: 0.85, y: -0.05), startRadius: 0, endRadius: max(w, h) * 0.6
+ )
+ RadialGradient(
+ colors: [Color(hex: 0x3B2E6B).opacity(scheme == .dark ? 0.55 : 0.10), .clear],
+ center: UnitPoint(x: 0, y: 0), startRadius: 0, endRadius: max(w, h) * 0.55
+ )
+ if scheme == .dark {
+ Canvas { context, size in
+ for star in Self.stars {
+ let rect = CGRect(
+ x: star.x * size.width, y: star.y * size.height,
+ width: star.r * 2, height: star.r * 2
+ )
+ context.fill(Path(ellipseIn: rect), with: .color(.white.opacity(star.o)))
+ }
+ }
+ Crescent()
+ .frame(width: 90, height: 90)
+ .position(x: w - 90, y: 70)
+ .opacity(0.5)
+ }
+ }
+ }
+ }
+ .ignoresSafeArea()
+ .accessibilityHidden(true)
+ }
+
+ /// Fixed positions, so the sky doesn't change between launches.
+ private static let stars: [(x: Double, y: Double, r: Double, o: Double)] = {
+ var seed: UInt64 = 0x4D6F_6F6E
+ func next() -> Double {
+ seed = seed &* 6364136223846793005 &+ 1442695040888963407
+ return Double(seed >> 33) / Double(UInt64(1) << 31)
+ }
+ return (0..<70).map { _ in (next(), next(), 0.4 + next() * 0.9, 0.15 + next() * 0.5) }
+ }()
+}
+
+/// A soft crescent moon.
+private struct Crescent: View {
+ var body: some View {
+ ZStack {
+ Circle()
+ .fill(RadialGradient(
+ colors: [Color(hex: 0xFDFBFF), Color(hex: 0xDDD6FF), Color(hex: 0xA89CF2)],
+ center: UnitPoint(x: 0.35, y: 0.3), startRadius: 0, endRadius: 50
+ ))
+ .mask {
+ Rectangle()
+ .overlay(Circle().offset(x: 22, y: -14).blendMode(.destinationOut))
+ .compositingGroup()
+ }
+ .shadow(color: Color(hex: 0xB9AEFB).opacity(0.6), radius: 18)
+ }
+ }
+}
diff --git a/macos/Sources/MoonTask/Theme.swift b/macos/Sources/MoonTask/Theme.swift
new file mode 100644
index 0000000..0e8ff0a
--- /dev/null
+++ b/macos/Sources/MoonTask/Theme.swift
@@ -0,0 +1,88 @@
+import AppKit
+import SwiftUI
+
+/// MoonTask's palette — the night-sky colors of src/styles/tokens.css, with
+/// their light-theme counterparts. Every color resolves per appearance, so
+/// the theme switch (or the system's) recolors everything at once.
+enum Palette {
+ static let background = dynamic(dark: 0x0B0920, light: 0xF5F2FB)
+ static let night900 = dynamic(dark: 0x141030, light: 0xFFFFFF)
+ static let text = dynamic(dark: 0xFBF7F0, light: 0x1C1733)
+ static let textMuted = dynamic(dark: 0xFBF7F0, light: 0x1C1733, darkAlpha: 0.62, lightAlpha: 0.64)
+ static let textFaint = dynamic(dark: 0xFBF7F0, light: 0x1C1733, darkAlpha: 0.40, lightAlpha: 0.42)
+ static let accent = dynamic(dark: 0xD6CFFD, light: 0x5B4BC4)
+ static let lavender = dynamic(dark: 0xB9AEFB, light: 0x7D6DE0)
+ static let border = dynamic(dark: 0xB9AEFB, light: 0x3B2E6B, darkAlpha: 0.18, lightAlpha: 0.16)
+ static let borderStrong = dynamic(dark: 0xB9AEFB, light: 0x3B2E6B, darkAlpha: 0.36, lightAlpha: 0.32)
+ static let glassTop = dynamic(dark: 0x1D1742, light: 0xFFFFFF, darkAlpha: 0.62, lightAlpha: 0.82)
+ static let glassBottom = dynamic(dark: 0x141030, light: 0xFFFFFF, darkAlpha: 0.70, lightAlpha: 0.70)
+ static let inset = dynamic(dark: 0x0B0920, light: 0xF1EEF8, darkAlpha: 0.55)
+ static let selected = dynamic(dark: 0xB9AEFB, light: 0x7D6DE0, darkAlpha: 0.15, lightAlpha: 0.14)
+ static let fresh = dynamic(dark: 0x7FE3C6, light: 0x23967A, darkAlpha: 0.12, lightAlpha: 0.12)
+ static let chart1 = dynamic(dark: 0x8676E3, light: 0x7D6DE0)
+ static let chart2 = dynamic(dark: 0x33AB8B, light: 0x23967A)
+ static let grid = dynamic(dark: 0xB9AEFB, light: 0x3B2E6B, darkAlpha: 0.10, lightAlpha: 0.10)
+ static let warning = dynamic(dark: 0xF3C766, light: 0xA86B00)
+ static let danger = dynamic(dark: 0xF28B92, light: 0xC2323D)
+ static let success = dynamic(dark: 0x7FE3C6, light: 0x1D7D65)
+
+ static let ownerCurrent = dynamic(dark: 0xB9AEFB, light: 0x7D6DE0)
+ static let ownerSystem = dynamic(dark: 0x9AD7F5, light: 0x2F86B5)
+ static let ownerOther = dynamic(dark: 0xF7B89A, light: 0xC7663B)
+
+ static func dynamic(
+ dark: UInt32, light: UInt32, darkAlpha: CGFloat = 1, lightAlpha: CGFloat = 1
+ ) -> Color {
+ Color(nsColor: NSColor(name: nil) { appearance in
+ let isDark = appearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua
+ return isDark ? NSColor(hex: dark, alpha: darkAlpha) : NSColor(hex: light, alpha: lightAlpha)
+ })
+ }
+}
+
+extension NSColor {
+ convenience init(hex: UInt32, alpha: CGFloat = 1) {
+ self.init(
+ srgbRed: CGFloat((hex >> 16) & 0xFF) / 255,
+ green: CGFloat((hex >> 8) & 0xFF) / 255,
+ blue: CGFloat(hex & 0xFF) / 255,
+ alpha: alpha
+ )
+ }
+}
+
+enum ThemeChoice: String, CaseIterable, Identifiable {
+ case system, dark, light
+ var id: String { rawValue }
+
+ var label: String {
+ switch self {
+ case .system: return "Follow macOS"
+ case .dark: return "Night"
+ case .light: return "Day"
+ }
+ }
+
+ var colorScheme: ColorScheme? {
+ switch self {
+ case .system: return nil
+ case .dark: return .dark
+ case .light: return .light
+ }
+ }
+}
+
+/// Keys of the user's settings (UserDefaults).
+enum SettingKey {
+ static let theme = "theme"
+ static let refreshInterval = "refreshInterval"
+ static let showKernel = "showKernel"
+ static let confirmOwn = "confirmOwn"
+}
+
+extension Font {
+ /// Numbers that line up in columns.
+ static func figure(_ size: CGFloat, weight: Font.Weight = .medium) -> Font {
+ .system(size: size, weight: weight, design: .rounded).monospacedDigit()
+ }
+}
diff --git a/macos/Sources/MoonTaskCore/Format.swift b/macos/Sources/MoonTaskCore/Format.swift
new file mode 100644
index 0000000..cfe0708
--- /dev/null
+++ b/macos/Sources/MoonTaskCore/Format.swift
@@ -0,0 +1,68 @@
+import Foundation
+
+/// Number formatting shared by every view — fixed English units, like the
+/// Windows and Linux app, so screenshots and docs match.
+public enum Format {
+ private static let units = ["B", "KB", "MB", "GB", "TB", "PB"]
+
+ /// 1024-based sizes, as Activity Monitor and Finder's memory figures use.
+ public static func bytes(_ value: Double, precision: Int? = nil) -> String {
+ if value < 1024 { return "\(Int(max(0, value))) B" }
+ var v = value
+ var unit = 0
+ while v >= 1024 && unit < units.count - 1 {
+ v /= 1024
+ unit += 1
+ }
+ let digits = precision ?? (v >= 100 ? 0 : 1)
+ return String(format: "%.\(digits)f %@", v, units[unit])
+ }
+
+ public static func bytes(_ value: UInt64, precision: Int? = nil) -> String {
+ bytes(Double(value), precision: precision)
+ }
+
+ public static func rate(_ bytesPerSecond: Double) -> String {
+ bytesPerSecond < 1 ? "0 B/s" : bytes(bytesPerSecond) + "/s"
+ }
+
+ public static func percent(_ value: Double, digits: Int = 1) -> String {
+ String(format: "%.\(digits)f %%", value)
+ }
+
+ public static func temperature(_ celsius: Double) -> String {
+ String(format: "%.0f °C", celsius)
+ }
+
+ /// "3 d 4 h", "2 h 5 min", "12 min", "40 s"
+ public static func duration(_ seconds: Double) -> String {
+ let s = Int(max(0, seconds))
+ let days = s / 86_400
+ let hours = (s % 86_400) / 3_600
+ let minutes = (s % 3_600) / 60
+ if days > 0 { return "\(days) d \(hours) h" }
+ if hours > 0 { return "\(hours) h \(minutes) min" }
+ if minutes > 0 { return "\(minutes) min" }
+ return "\(s) s"
+ }
+
+ /// CPU time as h:mm:ss.
+ public static func cpuTime(_ seconds: Double) -> String {
+ let s = Int(max(0, seconds))
+ return String(format: "%d:%02d:%02d", s / 3600, (s % 3600) / 60, s % 60)
+ }
+
+ public static func count(_ n: Int) -> String {
+ let f = NumberFormatter()
+ f.numberStyle = .decimal
+ f.locale = Locale(identifier: "en_US")
+ return f.string(from: NSNumber(value: n)) ?? "\(n)"
+ }
+
+ public static func dateTime(_ date: Date) -> String {
+ let f = DateFormatter()
+ f.dateStyle = .medium
+ f.timeStyle = .medium
+ return f.string(from: date)
+ }
+}
diff --git a/macos/Sources/MoonTaskCore/History.swift b/macos/Sources/MoonTaskCore/History.swift
new file mode 100644
index 0000000..646f089
--- /dev/null
+++ b/macos/Sources/MoonTaskCore/History.swift
@@ -0,0 +1,104 @@
+import Foundation
+
+/// The last `capacity` values of a measure, oldest first — the data behind
+/// every chart and sparkline.
+public struct Series: Sendable, Equatable {
+ public private(set) var values: [Double] = []
+ public let capacity: Int
+
+ public init(capacity: Int = 120) {
+ self.capacity = capacity
+ }
+
+ public mutating func append(_ value: Double) {
+ values.append(value)
+ if values.count > capacity { values.removeFirst(values.count - capacity) }
+ }
+
+ public var last: Double? { values.last }
+ public var peak: Double { values.max() ?? 0 }
+}
+
+/// Everything the charts keep between refreshes.
+public struct History: Sendable {
+ public var cpu = Series()
+ public var cpuUser = Series()
+ public var cpuSystem = Series()
+ public var perCore: [Series] = []
+ public var memory = Series()
+ public var swap = Series()
+ public var diskRead = Series()
+ public var diskWrite = Series()
+ public var networkIn = Series()
+ public var networkOut = Series()
+ public var gpu: [Int: Series] = [:]
+ /// Per process (by identity), for the detail panel's sparklines.
+ public var processCPU: [ProcessIdentity: Series] = [:]
+ public var processMemory: [ProcessIdentity: Series] = [:]
+ public var timestamps: [Date] = []
+
+ public init() {}
+
+ public mutating func record(_ s: Snapshot) {
+ cpu.append(s.cpu.total)
+ cpuUser.append(s.cpu.user)
+ cpuSystem.append(s.cpu.system)
+ if perCore.count != s.cpu.perCore.count {
+ perCore = s.cpu.perCore.map { _ in Series() }
+ }
+ for (i, value) in s.cpu.perCore.enumerated() { perCore[i].append(value) }
+ memory.append(Double(s.memory.used))
+ swap.append(Double(s.memory.swapUsed))
+ diskRead.append(s.diskRead)
+ diskWrite.append(s.diskWrite)
+ networkIn.append(s.networkIn)
+ networkOut.append(s.networkOut)
+ for gpu in s.gpus {
+ self.gpu[gpu.id, default: Series()].append(gpu.utilization ?? 0)
+ }
+ timestamps.append(s.timestamp)
+ if timestamps.count > cpu.capacity { timestamps.removeFirst(timestamps.count - cpu.capacity) }
+
+ // Short per-process histories, only for processes still alive.
+ var alive = Set()
+ for p in s.processes {
+ let id = p.identity
+ alive.insert(id)
+ processCPU[id, default: Series(capacity: 60)].append(p.cpu)
+ processMemory[id, default: Series(capacity: 60)].append(Double(p.memory))
+ }
+ processCPU = processCPU.filter { alive.contains($0.key) }
+ processMemory = processMemory.filter { alive.contains($0.key) }
+ }
+}
+
+/// A process that started or ended, for the overview's activity feed.
+public struct ActivityEvent: Identifiable, Sendable {
+ public enum Kind: Sendable { case started, ended }
+ public var id = UUID()
+ public var kind: Kind
+ public var name: String
+ public var pid: Int32
+ public var time: Date
+
+ public init(kind: Kind, name: String, pid: Int32, time: Date) {
+ self.kind = kind
+ self.name = name
+ self.pid = pid
+ self.time = time
+ }
+}
+
+/// Processes that appeared and disappeared between two snapshots.
+public func activity(from old: [ProcessRow], to new: [ProcessRow], at time: Date) -> [ActivityEvent] {
+ let before = Dictionary(old.map { ($0.identity, $0) }, uniquingKeysWith: { a, _ in a })
+ let after = Dictionary(new.map { ($0.identity, $0) }, uniquingKeysWith: { a, _ in a })
+ var events: [ActivityEvent] = []
+ for (id, p) in after where before[id] == nil {
+ events.append(ActivityEvent(kind: .started, name: p.name, pid: p.pid, time: time))
+ }
+ for (id, p) in before where after[id] == nil {
+ events.append(ActivityEvent(kind: .ended, name: p.name, pid: p.pid, time: time))
+ }
+ return events.sorted { $0.name < $1.name }
+}
diff --git a/macos/Sources/MoonTaskCore/Models.swift b/macos/Sources/MoonTaskCore/Models.swift
new file mode 100644
index 0000000..0b53daf
--- /dev/null
+++ b/macos/Sources/MoonTaskCore/Models.swift
@@ -0,0 +1,340 @@
+import Foundation
+
+/// Who a process belongs to, which decides its color and how careful
+/// MoonTask is with it.
+public enum Owner: String, Sendable, CaseIterable {
+ /// The signed-in user.
+ case current
+ /// root and the system's service accounts (_windowserver, _mdnsresponder …).
+ case system
+ /// Another person's account.
+ case other
+ /// kernel_task.
+ case kernel
+
+ public var label: String {
+ switch self {
+ case .current: return "You"
+ case .system: return "System"
+ case .other: return "Other user"
+ case .kernel: return "Kernel"
+ }
+ }
+}
+
+public enum ProcessState: String, Sendable {
+ case running, sleeping, stopped, zombie, idle, unknown
+
+ public var label: String {
+ switch self {
+ case .running: return "Running"
+ case .sleeping: return "Sleeping"
+ case .stopped: return "Suspended"
+ case .zombie: return "Zombie"
+ case .idle: return "Starting"
+ case .unknown: return "Unknown"
+ }
+ }
+
+ /// From the BSD `p_stat` value.
+ public init(bsdState: Int32) {
+ switch bsdState {
+ case 1: self = .idle
+ case 2: self = .running
+ case 3: self = .sleeping
+ case 4: self = .stopped
+ case 5: self = .zombie
+ default: self = .unknown
+ }
+ }
+}
+
+public struct ProcessRow: Identifiable, Hashable, Sendable {
+ public var id: Int32 { pid }
+ public var pid: Int32
+ public var parentPid: Int32?
+ public var name: String
+ public var user: String?
+ public var uid: UInt32
+ public var owner: Owner
+ public var state: ProcessState
+ /// Share of the whole machine, 0–100, so the column adds up to the total.
+ public var cpu: Double
+ /// Physical footprint in bytes (Activity Monitor's "Memory").
+ public var memory: UInt64
+ public var threads: Int?
+ /// Bytes per second.
+ public var diskRead: Double
+ public var diskWrite: Double
+ public var nice: Int32
+ /// Seconds since 1970.
+ public var startTime: Double
+ /// Total CPU time used, seconds.
+ public var cpuTime: Double
+ public var path: String?
+ /// Ending it would take the system (or MoonTask) down.
+ public var isProtected: Bool
+
+ public init(
+ pid: Int32, parentPid: Int32?, name: String, user: String?, uid: UInt32, owner: Owner,
+ state: ProcessState, cpu: Double = 0, memory: UInt64 = 0, threads: Int? = nil,
+ diskRead: Double = 0, diskWrite: Double = 0, nice: Int32 = 0, startTime: Double = 0,
+ cpuTime: Double = 0, path: String? = nil, isProtected: Bool = false
+ ) {
+ self.pid = pid
+ self.parentPid = parentPid
+ self.name = name
+ self.user = user
+ self.uid = uid
+ self.owner = owner
+ self.state = state
+ self.cpu = cpu
+ self.memory = memory
+ self.threads = threads
+ self.diskRead = diskRead
+ self.diskWrite = diskWrite
+ self.nice = nice
+ self.startTime = startTime
+ self.cpuTime = cpuTime
+ self.path = path
+ self.isProtected = isProtected
+ }
+
+ /// Identifies this process instance: a PID with its start time, so a
+ /// PID the system has since handed to another process never matches.
+ public var identity: ProcessIdentity { ProcessIdentity(pid: pid, startTime: startTime) }
+}
+
+public struct ProcessIdentity: Hashable, Sendable {
+ public var pid: Int32
+ public var startTime: Double
+
+ public init(pid: Int32, startTime: Double) {
+ self.pid = pid
+ self.startTime = startTime
+ }
+}
+
+public struct CPUStats: Sendable {
+ /// 0–100
+ public var total: Double
+ public var perCore: [Double]
+ public var user: Double
+ public var system: Double
+
+ public init(total: Double = 0, perCore: [Double] = [], user: Double = 0, system: Double = 0) {
+ self.total = total
+ self.perCore = perCore
+ self.user = user
+ self.system = system
+ }
+}
+
+public struct MemoryStats: Sendable {
+ public var total: UInt64
+ public var app: UInt64
+ public var wired: UInt64
+ public var compressed: UInt64
+ public var cached: UInt64
+ public var free: UInt64
+ public var swapTotal: UInt64
+ public var swapUsed: UInt64
+
+ public init(
+ total: UInt64 = 0, app: UInt64 = 0, wired: UInt64 = 0, compressed: UInt64 = 0,
+ cached: UInt64 = 0, free: UInt64 = 0, swapTotal: UInt64 = 0, swapUsed: UInt64 = 0
+ ) {
+ self.total = total
+ self.app = app
+ self.wired = wired
+ self.compressed = compressed
+ self.cached = cached
+ self.free = free
+ self.swapTotal = swapTotal
+ self.swapUsed = swapUsed
+ }
+
+ /// "Memory Used" as Activity Monitor counts it: app + wired + compressed.
+ public var used: UInt64 { app + wired + compressed }
+ public var fraction: Double { total > 0 ? min(1, Double(used) / Double(total)) : 0 }
+}
+
+public struct GPUStats: Identifiable, Sendable {
+ public var id: Int
+ public var name: String
+ /// 0–100, nil when the driver doesn't report it.
+ public var utilization: Double?
+ public var memoryUsed: UInt64?
+ public var cores: Int?
+
+ public init(id: Int, name: String, utilization: Double?, memoryUsed: UInt64?, cores: Int?) {
+ self.id = id
+ self.name = name
+ self.utilization = utilization
+ self.memoryUsed = memoryUsed
+ self.cores = cores
+ }
+}
+
+public struct Volume: Identifiable, Sendable {
+ public var id: String { mountPoint }
+ public var name: String
+ public var mountPoint: String
+ public var total: UInt64
+ public var available: UInt64
+ public var isInternal: Bool
+
+ public init(name: String, mountPoint: String, total: UInt64, available: UInt64, isInternal: Bool) {
+ self.name = name
+ self.mountPoint = mountPoint
+ self.total = total
+ self.available = available
+ self.isInternal = isInternal
+ }
+
+ public var used: UInt64 { total > available ? total - available : 0 }
+ public var fraction: Double { total > 0 ? Double(used) / Double(total) : 0 }
+}
+
+public enum ThermalLevel: String, Sendable {
+ case nominal, fair, serious, critical
+
+ public var label: String {
+ switch self {
+ case .nominal: return "Normal"
+ case .fair: return "Warm"
+ case .serious: return "Hot — slowed down"
+ case .critical: return "Critical"
+ }
+ }
+}
+
+/// One refresh worth of machine data.
+public struct Snapshot: Sendable {
+ public var timestamp: Date
+ public var cpu: CPUStats
+ public var memory: MemoryStats
+ /// Bytes per second.
+ public var diskRead: Double
+ public var diskWrite: Double
+ public var networkIn: Double
+ public var networkOut: Double
+ public var gpus: [GPUStats]
+ public var volumes: [Volume]
+ public var processes: [ProcessRow]
+ public var thermal: ThermalLevel
+ public var uptime: TimeInterval
+
+ public init(
+ timestamp: Date = Date(), cpu: CPUStats = CPUStats(), memory: MemoryStats = MemoryStats(),
+ diskRead: Double = 0, diskWrite: Double = 0, networkIn: Double = 0, networkOut: Double = 0,
+ gpus: [GPUStats] = [], volumes: [Volume] = [], processes: [ProcessRow] = [],
+ thermal: ThermalLevel = .nominal, uptime: TimeInterval = 0
+ ) {
+ self.timestamp = timestamp
+ self.cpu = cpu
+ self.memory = memory
+ self.diskRead = diskRead
+ self.diskWrite = diskWrite
+ self.networkIn = networkIn
+ self.networkOut = networkOut
+ self.gpus = gpus
+ self.volumes = volumes
+ self.processes = processes
+ self.thermal = thermal
+ self.uptime = uptime
+ }
+
+ /// The GPU to feature: the busiest one.
+ public var primaryGPU: GPUStats? {
+ gpus.max { ($0.utilization ?? -1) < ($1.utilization ?? -1) }
+ }
+}
+
+public struct SystemInfo: Sendable {
+ public var hostName: String
+ public var osVersion: String
+ public var model: String
+ public var chip: String
+ public var cores: Int
+ public var performanceCores: Int?
+ public var efficiencyCores: Int?
+ public var memory: UInt64
+ public var bootTime: Date?
+
+ public init(
+ hostName: String = "", osVersion: String = "", model: String = "", chip: String = "",
+ cores: Int = 0, performanceCores: Int? = nil, efficiencyCores: Int? = nil,
+ memory: UInt64 = 0, bootTime: Date? = nil
+ ) {
+ self.hostName = hostName
+ self.osVersion = osVersion
+ self.model = model
+ self.chip = chip
+ self.cores = cores
+ self.performanceCores = performanceCores
+ self.efficiencyCores = efficiencyCores
+ self.memory = memory
+ self.bootTime = bootTime
+ }
+}
+
+public enum TransportProtocol: String, Sendable {
+ case tcp = "TCP"
+ case udp = "UDP"
+}
+
+public struct Connection: Identifiable, Hashable, Sendable {
+ public var id: String { "\(pid):\(fd):\(proto.rawValue)" }
+ public var pid: Int32
+ public var processName: String
+ public var fd: Int32
+ public var proto: TransportProtocol
+ public var isIPv6: Bool
+ public var localAddress: String
+ public var localPort: Int
+ public var remoteAddress: String
+ public var remotePort: Int
+ public var state: String
+
+ public init(
+ pid: Int32, processName: String, fd: Int32, proto: TransportProtocol, isIPv6: Bool,
+ localAddress: String, localPort: Int, remoteAddress: String, remotePort: Int, state: String
+ ) {
+ self.pid = pid
+ self.processName = processName
+ self.fd = fd
+ self.proto = proto
+ self.isIPv6 = isIPv6
+ self.localAddress = localAddress
+ self.localPort = localPort
+ self.remoteAddress = remoteAddress
+ self.remotePort = remotePort
+ self.state = state
+ }
+
+ public var isListening: Bool {
+ state == "Listen" || (proto == .udp && remotePort == 0)
+ }
+}
+
+/// A launchd job of the user's session.
+public struct LaunchJob: Identifiable, Hashable, Sendable {
+ public var id: String { label }
+ public var label: String
+ public var pid: Int32?
+ /// The last exit status; nil while running or never run.
+ public var lastExitStatus: Int32?
+
+ public init(label: String, pid: Int32?, lastExitStatus: Int32?) {
+ self.label = label
+ self.pid = pid
+ self.lastExitStatus = lastExitStatus
+ }
+
+ public var isRunning: Bool { pid != nil }
+ /// Apple's own jobs, which are part of macOS.
+ public var isApple: Bool {
+ label.hasPrefix("com.apple.") || label.hasPrefix("application.com.apple.")
+ }
+}
diff --git a/macos/Sources/MoonTaskCore/ProcessList.swift b/macos/Sources/MoonTaskCore/ProcessList.swift
new file mode 100644
index 0000000..b8df754
--- /dev/null
+++ b/macos/Sources/MoonTaskCore/ProcessList.swift
@@ -0,0 +1,337 @@
+import Foundation
+
+/// Turns the flat process list of a snapshot into the rows the process table
+/// shows: as a parent/child tree, as a flat list, or grouped by app —
+/// filtered, sorted and with collapsed branches left out. Pure functions, so
+/// every rule here is unit-tested (the same rules as the Windows/Linux app).
+
+public enum ViewMode: String, CaseIterable, Sendable {
+ case tree, list, apps
+
+ public var label: String {
+ switch self {
+ case .tree: return "Tree"
+ case .list: return "List"
+ case .apps: return "Apps"
+ }
+ }
+}
+
+public enum SortKey: String, CaseIterable, Sendable {
+ case name, pid, user, cpu, memory, threads, disk, state
+}
+
+public struct SortState: Equatable, Sendable {
+ public var key: SortKey
+ public var ascending: Bool
+
+ public init(key: SortKey, ascending: Bool) {
+ self.key = key
+ self.ascending = ascending
+ }
+
+ /// What a click on a column header does: the same column flips the
+ /// direction, a new one starts with the natural direction (numbers
+ /// largest first, text A–Z).
+ public func toggled(_ newKey: SortKey) -> SortState {
+ if newKey == key { return SortState(key: key, ascending: !ascending) }
+ let text: Set = [.name, .user, .state, .pid]
+ return SortState(key: newKey, ascending: text.contains(newKey))
+ }
+}
+
+public enum OwnerFilter: String, CaseIterable, Sendable {
+ case all, mine, others
+
+ public var label: String {
+ switch self {
+ case .all: return "Everyone"
+ case .mine: return "Mine"
+ case .others: return "System & others"
+ }
+ }
+}
+
+public struct VisibleRow: Identifiable, Hashable, Sendable {
+ public enum Kind: Hashable, Sendable { case process, group }
+
+ /// `p:` for a process, `g:` for an app group.
+ public var id: String
+ public var kind: Kind
+ public var depth: Int
+ /// For groups: a synthesized row with the members' sums.
+ public var process: ProcessRow
+ public var hasChildren: Bool
+ public var isExpanded: Bool
+ /// Only shown as the ancestor of a match, not a match itself.
+ public var isDimmed: Bool
+ /// Group members (groups only).
+ public var members: [ProcessRow]
+
+ // Sort values for SwiftUI's table columns.
+ public var sortName: String { process.name.lowercased() }
+ public var sortPid: Int32 { process.pid }
+ public var sortUser: String { (process.user ?? "").lowercased() }
+ public var sortCPU: Double { process.cpu }
+ public var sortMemory: UInt64 { process.memory }
+ public var sortThreads: Int { process.threads ?? 0 }
+ public var sortDisk: Double { process.diskRead + process.diskWrite }
+ public var sortState: String { process.state.rawValue }
+}
+
+public struct VisibleOptions: Sendable {
+ public var mode: ViewMode
+ public var sort: SortState
+ public var query: String
+ public var owner: OwnerFilter
+ public var showKernel: Bool
+ /// Tree mode: PIDs whose children are hidden.
+ public var collapsed: Set
+ /// App mode: group ids that are open.
+ public var openGroups: Set
+
+ public init(
+ mode: ViewMode = .tree, sort: SortState = SortState(key: .cpu, ascending: false),
+ query: String = "", owner: OwnerFilter = .all, showKernel: Bool = true,
+ collapsed: Set = [], openGroups: Set = []
+ ) {
+ self.mode = mode
+ self.sort = sort
+ self.query = query
+ self.owner = owner
+ self.showKernel = showKernel
+ self.collapsed = collapsed
+ self.openGroups = openGroups
+ }
+}
+
+public func processRowID(_ pid: Int32) -> String { "p:\(pid)" }
+public func groupRowID(_ name: String) -> String { "g:\(name.lowercased())" }
+
+/// Case-insensitive search over name, PID, user and executable path.
+public func matchesQuery(_ row: ProcessRow, _ query: String) -> Bool {
+ let q = query.trimmingCharacters(in: .whitespaces).lowercased()
+ if q.isEmpty { return true }
+ return row.name.lowercased().contains(q)
+ || String(row.pid) == q
+ || (row.user?.lowercased().contains(q) ?? false)
+ || (row.path?.lowercased().contains(q) ?? false)
+}
+
+func matchesOwner(_ row: ProcessRow, _ owner: OwnerFilter) -> Bool {
+ switch owner {
+ case .all: return true
+ case .mine: return row.owner == .current
+ case .others: return row.owner != .current
+ }
+}
+
+/// Orders two rows by the sort state; equal values fall back to the PID so
+/// rows don't jump around between refreshes.
+public func compareRows(_ a: ProcessRow, _ b: ProcessRow, _ sort: SortState) -> Bool {
+ let result: Int
+ switch sort.key {
+ case .name: result = compare(a.name.lowercased(), b.name.lowercased())
+ case .pid: result = compare(a.pid, b.pid)
+ case .user: result = compare((a.user ?? "").lowercased(), (b.user ?? "").lowercased())
+ case .cpu: result = compare(a.cpu, b.cpu)
+ case .memory: result = compare(a.memory, b.memory)
+ case .threads: result = compare(a.threads ?? 0, b.threads ?? 0)
+ case .disk: result = compare(a.diskRead + a.diskWrite, b.diskRead + b.diskWrite)
+ case .state: result = compare(a.state.rawValue, b.state.rawValue)
+ }
+ if result != 0 { return sort.ascending ? result < 0 : result > 0 }
+ return a.pid < b.pid
+}
+
+private func compare(_ a: T, _ b: T) -> Int {
+ a < b ? -1 : (a > b ? 1 : 0)
+}
+
+/// A process' children, keyed by parent PID; processes whose parent isn't
+/// listed (or is themselves) are roots.
+public func buildChildren(_ rows: [ProcessRow]) -> (roots: [ProcessRow], children: [Int32: [ProcessRow]]) {
+ let pids = Set(rows.map(\.pid))
+ var children: [Int32: [ProcessRow]] = [:]
+ var roots: [ProcessRow] = []
+ for row in rows {
+ if let parent = row.parentPid, parent != row.pid, pids.contains(parent) {
+ children[parent, default: []].append(row)
+ } else {
+ roots.append(row)
+ }
+ }
+ // PID reuse can produce parent cycles that no root reaches; promote one
+ // member of each such cycle to a root so nothing silently disappears.
+ var reached = Set()
+ func reach(from start: [ProcessRow]) {
+ var stack = start
+ while let row = stack.popLast() {
+ if !reached.insert(row.pid).inserted { continue }
+ stack.append(contentsOf: children[row.pid] ?? [])
+ }
+ }
+ reach(from: roots)
+ for row in rows where !reached.contains(row.pid) {
+ roots.append(row)
+ reach(from: [row])
+ }
+ return (roots, children)
+}
+
+public func visibleRows(_ rows: [ProcessRow], _ opts: VisibleOptions) -> [VisibleRow] {
+ let pool = opts.showKernel ? rows : rows.filter { $0.owner != .kernel }
+ let filtering = !opts.query.trimmingCharacters(in: .whitespaces).isEmpty || opts.owner != .all
+ let isMatch: (ProcessRow) -> Bool = { matchesQuery($0, opts.query) && matchesOwner($0, opts.owner) }
+ let less: (ProcessRow, ProcessRow) -> Bool = { compareRows($0, $1, opts.sort) }
+
+ switch opts.mode {
+ case .list:
+ return pool.filter(isMatch).sorted(by: less).map { processRow($0, depth: 0) }
+ case .apps:
+ return appRows(pool.filter(isMatch), opts, less)
+ case .tree:
+ return treeRows(pool, opts, filtering, isMatch, less)
+ }
+}
+
+private func processRow(
+ _ process: ProcessRow, depth: Int, hasChildren: Bool = false, expanded: Bool = false,
+ dimmed: Bool = false
+) -> VisibleRow {
+ VisibleRow(
+ id: processRowID(process.pid), kind: .process, depth: depth, process: process,
+ hasChildren: hasChildren, isExpanded: expanded, isDimmed: dimmed, members: []
+ )
+}
+
+private func treeRows(
+ _ pool: [ProcessRow], _ opts: VisibleOptions, _ filtering: Bool,
+ _ isMatch: (ProcessRow) -> Bool, _ less: @escaping (ProcessRow, ProcessRow) -> Bool
+) -> [VisibleRow] {
+ let (roots, children) = buildChildren(pool)
+
+ // While filtering, keep each match plus the chain of its ancestors (as
+ // dimmed context) and show every branch open.
+ var keep: Set? = nil
+ var matched = Set()
+ if filtering {
+ var kept = Set()
+ let byPid = Dictionary(pool.map { ($0.pid, $0) }, uniquingKeysWith: { a, _ in a })
+ for row in pool where isMatch(row) {
+ matched.insert(row.pid)
+ var current: ProcessRow? = row
+ while let c = current, !kept.contains(c.pid) {
+ kept.insert(c.pid)
+ if let parent = c.parentPid, parent != c.pid {
+ current = byPid[parent]
+ } else {
+ current = nil
+ }
+ }
+ }
+ keep = kept
+ }
+
+ var out: [VisibleRow] = []
+ var visited = Set()
+ func walk(_ row: ProcessRow, _ depth: Int) {
+ if !visited.insert(row.pid).inserted { return }
+ let kids = (children[row.pid] ?? []).filter { keep?.contains($0.pid) ?? true }
+ let expanded = filtering || !opts.collapsed.contains(row.pid)
+ out.append(processRow(
+ row, depth: depth, hasChildren: !kids.isEmpty, expanded: expanded,
+ dimmed: filtering && !matched.contains(row.pid)
+ ))
+ if !expanded { return }
+ for kid in kids.sorted(by: less) { walk(kid, depth + 1) }
+ }
+ for root in roots.filter({ keep?.contains($0.pid) ?? true }).sorted(by: less) {
+ walk(root, 0)
+ }
+ return out
+}
+
+/// Sums a group of processes into one synthetic row.
+public func aggregate(_ name: String, _ members: [ProcessRow]) -> ProcessRow {
+ var summary = members.min { $0.pid < $1.pid }!
+ let users = Set(members.map { $0.user ?? "" })
+ summary.name = name
+ summary.user = users.count == 1 ? summary.user : "\(users.count) users"
+ if members.contains(where: { $0.state == .running }) { summary.state = .running }
+ summary.cpu = members.reduce(0) { $0 + $1.cpu }
+ summary.memory = members.reduce(0) { $0 + $1.memory }
+ summary.threads = members.reduce(0) { $0 + ($1.threads ?? 0) }
+ summary.diskRead = members.reduce(0) { $0 + $1.diskRead }
+ summary.diskWrite = members.reduce(0) { $0 + $1.diskWrite }
+ summary.cpuTime = members.reduce(0) { $0 + $1.cpuTime }
+ summary.isProtected = members.allSatisfy(\.isProtected)
+ return summary
+}
+
+private func appRows(
+ _ matches: [ProcessRow], _ opts: VisibleOptions,
+ _ less: @escaping (ProcessRow, ProcessRow) -> Bool
+) -> [VisibleRow] {
+ var groups: [String: [ProcessRow]] = [:]
+ var order: [String] = []
+ for row in matches {
+ let key = row.name.lowercased()
+ if groups[key] == nil { order.append(key) }
+ groups[key, default: []].append(row)
+ }
+ let entries: [(members: [ProcessRow], summary: ProcessRow)] = order.map { key in
+ let members = groups[key]!
+ return (members, members.count == 1 ? members[0] : aggregate(members[0].name, members))
+ }
+
+ var out: [VisibleRow] = []
+ for entry in entries.sorted(by: { less($0.summary, $1.summary) }) {
+ if entry.members.count == 1 {
+ out.append(processRow(entry.summary, depth: 0))
+ continue
+ }
+ let id = groupRowID(entry.summary.name)
+ let open = opts.openGroups.contains(id)
+ out.append(VisibleRow(
+ id: id, kind: .group, depth: 0, process: entry.summary, hasChildren: true,
+ isExpanded: open, isDimmed: false, members: entry.members
+ ))
+ if open {
+ for member in entry.members.sorted(by: less) {
+ out.append(processRow(member, depth: 1))
+ }
+ }
+ }
+ return out
+}
+
+/// How many processes `pid` started, directly or indirectly.
+public func countDescendants(_ rows: [ProcessRow], of pid: Int32) -> Int {
+ let (_, children) = buildChildren(rows)
+ var count = 0
+ var seen: Set = [pid]
+ var stack = children[pid] ?? []
+ while let row = stack.popLast() {
+ if !seen.insert(row.pid).inserted { continue }
+ count += 1
+ stack.append(contentsOf: children[row.pid] ?? [])
+ }
+ return count
+}
+
+/// `pid` and everything it started, children before their parents — the
+/// order to end a tree in.
+public func descendantsFirst(_ rows: [ProcessRow], of pid: Int32) -> [ProcessRow] {
+ let (_, children) = buildChildren(rows)
+ guard let root = rows.first(where: { $0.pid == pid }) else { return [] }
+ var out: [ProcessRow] = []
+ var seen = Set()
+ func visit(_ row: ProcessRow) {
+ if !seen.insert(row.pid).inserted { return }
+ for child in children[row.pid] ?? [] { visit(child) }
+ out.append(row)
+ }
+ visit(root)
+ return out
+}
diff --git a/macos/Sources/MoonTaskCore/Safety.swift b/macos/Sources/MoonTaskCore/Safety.swift
new file mode 100644
index 0000000..8588f77
--- /dev/null
+++ b/macos/Sources/MoonTaskCore/Safety.swift
@@ -0,0 +1,93 @@
+import Foundation
+
+/// What MoonTask can do to a process.
+public enum ProcessAction: Hashable, Sendable {
+ /// SIGTERM: ask it to quit, so it can save its work.
+ case end
+ /// SIGKILL: stop it at once.
+ case forceQuit
+ /// End it and everything it started.
+ case endTree
+ /// SIGSTOP
+ case suspend
+ /// SIGCONT
+ case resume
+ /// A new nice value, -20 (highest) … 20 (lowest).
+ case setPriority(Int32)
+
+ public var label: String {
+ switch self {
+ case .end: return "End"
+ case .forceQuit: return "Force Quit"
+ case .endTree: return "End Process Tree"
+ case .suspend: return "Suspend"
+ case .resume: return "Resume"
+ case .setPriority: return "Change Priority"
+ }
+ }
+}
+
+/// The safety rules, shared by the menus (which grey actions out) and the
+/// system layer (which refuses them again right before acting).
+public enum Safety {
+ /// Processes whose end takes the whole session down.
+ public static let protectedNames: Set = [
+ "kernel_task", "launchd", "WindowServer", "loginwindow", "logind", "opendirectoryd",
+ "configd", "notifyd", "securityd", "syslogd", "UserEventAgent", "coreservicesd",
+ ]
+
+ public static func isProtected(pid: Int32, name: String, ownPid: Int32) -> Bool {
+ pid <= 1 || pid == ownPid || protectedNames.contains(name)
+ }
+
+ public static func isAllowed(_ action: ProcessAction, on row: ProcessRow) -> Bool {
+ if row.isProtected { return false }
+ if case .setPriority(let nice) = action {
+ // Raising priority (a lower nice value) needs root; MoonTask
+ // never tries to go below 0 on its own.
+ return nice >= -20 && nice <= 20
+ }
+ return true
+ }
+
+ /// Actions that always ask first, whatever the settings say.
+ public static func isHighRisk(_ action: ProcessAction, on row: ProcessRow) -> Bool {
+ switch action {
+ case .endTree:
+ return true
+ case .end, .forceQuit, .suspend:
+ return row.owner != .current
+ case .resume, .setPriority:
+ return false
+ }
+ }
+
+ public static func needsConfirmation(
+ _ action: ProcessAction, on row: ProcessRow, confirmOwn: Bool
+ ) -> Bool {
+ if isHighRisk(action, on: row) { return true }
+ switch action {
+ case .end, .forceQuit, .suspend: return confirmOwn
+ default: return false
+ }
+ }
+
+ /// Human words for what the action will do, for the confirmation.
+ public static func consequence(_ action: ProcessAction, on row: ProcessRow, descendants: Int) -> String {
+ switch action {
+ case .end:
+ return "\(row.name) is asked to quit and can save its work first."
+ case .forceQuit:
+ return "\(row.name) stops at once. Anything it hasn't saved is lost."
+ case .endTree:
+ let others = descendants == 1 ? "1 process it started" : "\(descendants) processes it started"
+ return "\(row.name) and \(others) are asked to quit."
+ case .suspend:
+ return "\(row.name) is paused until you resume it. Windows of a paused app stop responding."
+ case .resume:
+ return "\(row.name) continues where it was paused."
+ case .setPriority:
+ return "\(row.name) gets a different share of the CPU when it's busy."
+ }
+ }
+}
diff --git a/macos/Sources/MoonTaskSystem/LaunchAgents.swift b/macos/Sources/MoonTaskSystem/LaunchAgents.swift
new file mode 100644
index 0000000..6eaf067
--- /dev/null
+++ b/macos/Sources/MoonTaskSystem/LaunchAgents.swift
@@ -0,0 +1,58 @@
+import Darwin
+import Foundation
+import MoonTaskCore
+
+/// The launchd jobs of the user's session — macOS' counterpart of Windows
+/// services and systemd units — through `launchctl`, the supported way.
+public enum LaunchAgents {
+ public static func list() -> [LaunchJob] {
+ guard let output = run(["list"]) else { return [] }
+ return parseList(output)
+ }
+
+ /// `launchctl list` prints "PID\tStatus\tLabel" with "-" for none.
+ static func parseList(_ output: String) -> [LaunchJob] {
+ output.split(separator: "\n").dropFirst().compactMap { line in
+ let parts = line.split(separator: "\t", omittingEmptySubsequences: false)
+ guard parts.count >= 3 else { return nil }
+ let label = String(parts[2]).trimmingCharacters(in: .whitespaces)
+ guard !label.isEmpty else { return nil }
+ return LaunchJob(
+ label: label,
+ pid: Int32(parts[0].trimmingCharacters(in: .whitespaces)),
+ lastExitStatus: Int32(parts[1].trimmingCharacters(in: .whitespaces))
+ )
+ }
+ .sorted { $0.label.localizedCaseInsensitiveCompare($1.label) == .orderedAscending }
+ }
+
+ private static var domain: String { "gui/\(getuid())" }
+
+ /// Starts the job, or restarts it when it runs.
+ public static func start(_ job: LaunchJob) -> Bool {
+ run(["kickstart", job.isRunning ? "-k" : "", "\(domain)/\(job.label)"].filter { !$0.isEmpty }) != nil
+ }
+
+ public static func stop(_ job: LaunchJob) -> Bool {
+ run(["kill", "SIGTERM", "\(domain)/\(job.label)"]) != nil
+ }
+
+ /// Runs launchctl; nil when it fails.
+ private static func run(_ arguments: [String]) -> String? {
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: "/bin/launchctl")
+ process.arguments = arguments
+ let pipe = Pipe()
+ process.standardOutput = pipe
+ process.standardError = Pipe()
+ do {
+ try process.run()
+ } catch {
+ return nil
+ }
+ let data = pipe.fileHandleForReading.readDataToEndOfFile()
+ process.waitUntilExit()
+ guard process.terminationStatus == 0 else { return nil }
+ return String(decoding: data, as: UTF8.self)
+ }
+}
diff --git a/macos/Sources/MoonTaskSystem/ProcessControl.swift b/macos/Sources/MoonTaskSystem/ProcessControl.swift
new file mode 100644
index 0000000..8706732
--- /dev/null
+++ b/macos/Sources/MoonTaskSystem/ProcessControl.swift
@@ -0,0 +1,85 @@
+import CDarwin
+import Darwin
+import Foundation
+import MoonTaskCore
+
+public enum ControlError: LocalizedError, Equatable {
+ case protected(String)
+ case gone(String)
+ case permission(String)
+ case failed(String, Int32)
+
+ public var errorDescription: String? {
+ switch self {
+ case .protected(let name):
+ return "\(name) is protected: ending it would take macOS or MoonTask down."
+ case .gone(let name):
+ return "\(name) has already ended."
+ case .permission(let name):
+ return "macOS doesn't allow MoonTask to do that to \(name). Processes of other users and the system need administrator rights."
+ case .failed(let name, let code):
+ return "That didn't work for \(name): \(String(cString: strerror(code)))."
+ }
+ }
+}
+
+/// Acts on processes. Every action names the process by PID *and* start
+/// time and checks both right before it runs, so a PID macOS has meanwhile
+/// given to another process is never touched.
+public enum ProcessControl {
+ public static func perform(_ action: ProcessAction, on row: ProcessRow, tree: [ProcessRow] = []) throws {
+ guard Safety.isAllowed(action, on: row) else { throw ControlError.protected(row.name) }
+ switch action {
+ case .end: try signal(SIGTERM, row)
+ case .forceQuit: try signal(SIGKILL, row)
+ case .suspend: try signal(SIGSTOP, row)
+ case .resume: try signal(SIGCONT, row)
+ case .setPriority(let nice):
+ try verify(row)
+ errno = 0
+ if setpriority(PRIO_PROCESS, id_t(row.pid), nice) != 0 { throw error(for: row) }
+ case .endTree:
+ // Children first, so a parent can't restart what just ended.
+ var firstError: Error?
+ for member in descendantsFirst(tree, of: row.pid) {
+ guard Safety.isAllowed(.end, on: member) else { continue }
+ do { try signal(SIGTERM, member) } catch ControlError.gone(_) {
+ } catch {
+ if firstError == nil { firstError = error }
+ }
+ }
+ if let firstError { throw firstError }
+ }
+ }
+
+ private static func signal(_ sig: Int32, _ row: ProcessRow) throws {
+ try verify(row)
+ if kill(row.pid, sig) != 0 { throw error(for: row) }
+ }
+
+ /// Is `row` still the process it was when it was listed?
+ static func verify(_ row: ProcessRow) throws {
+ var kinfo = kinfo_proc()
+ var size = MemoryLayout.stride
+ var mib: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, row.pid]
+ let ok = sysctl(&mib, 4, &kinfo, &size, nil, 0) == 0 && size > 0
+ guard ok, kinfo.kp_proc.p_pid == row.pid else { throw ControlError.gone(row.name) }
+ // p_starttime is a C macro for this field.
+ let start = kinfo.kp_proc.p_un.__p_starttime
+ let startTime = Double(start.tv_sec) + Double(start.tv_usec) / 1_000_000
+ if abs(startTime - row.startTime) > 0.001 { throw ControlError.gone(row.name) }
+ }
+
+ private static func error(for row: ProcessRow) -> ControlError {
+ switch errno {
+ case ESRCH: return .gone(row.name)
+ case EPERM, EACCES: return .permission(row.name)
+ default: return .failed(row.name, errno)
+ }
+ }
+
+ /// Shows the executable in Finder.
+ public static func revealInFinder(_ path: String) -> URL {
+ URL(fileURLWithPath: path)
+ }
+}
diff --git a/macos/Sources/MoonTaskSystem/ProcessDetails.swift b/macos/Sources/MoonTaskSystem/ProcessDetails.swift
new file mode 100644
index 0000000..f937de7
--- /dev/null
+++ b/macos/Sources/MoonTaskSystem/ProcessDetails.swift
@@ -0,0 +1,149 @@
+import CDarwin
+import Darwin
+import Foundation
+import MoonTaskCore
+
+public struct EnvironmentVariable: Hashable, Sendable, Identifiable {
+ public var id: String { name }
+ public var name: String
+ public var value: String
+}
+
+/// What the detail panel shows beyond the table's columns. Most of it is
+/// only readable for the user's own processes (or as root).
+public struct ProcessDetails: Sendable {
+ public var arguments: [String]?
+ public var environment: [EnvironmentVariable]?
+ public var openFiles: [String]?
+ public var connections: [Connection]?
+
+ public init(
+ arguments: [String]? = nil, environment: [EnvironmentVariable]? = nil,
+ openFiles: [String]? = nil, connections: [Connection]? = nil
+ ) {
+ self.arguments = arguments
+ self.environment = environment
+ self.openFiles = openFiles
+ self.connections = connections
+ }
+}
+
+public enum ProcessInspector {
+ public static func details(of row: ProcessRow) -> ProcessDetails {
+ let (arguments, environment) = argumentsAndEnvironment(of: row.pid)
+ return ProcessDetails(
+ arguments: arguments,
+ environment: environment,
+ openFiles: openFiles(of: row.pid),
+ connections: connections(of: row.pid, name: row.name)
+ )
+ }
+
+ /// Parses the KERN_PROCARGS2 block: argc, the executable path, padding,
+ /// the arguments, then the environment.
+ static func argumentsAndEnvironment(of pid: Int32) -> ([String]?, [EnvironmentVariable]?) {
+ let size = max(4096, Int(mt_sysctl_int("kern.argmax")))
+ var buffer = [CChar](repeating: 0, count: size)
+ let len = Int(buffer.withUnsafeMutableBufferPointer {
+ mt_process_args(pid, $0.baseAddress, Int32($0.count))
+ })
+ guard len > MemoryLayout.size else { return (nil, nil) }
+ let bytes = buffer.prefix(len).map { UInt8(bitPattern: $0) }
+ return parseProcArgs(bytes)
+ }
+
+ static func parseProcArgs(_ bytes: [UInt8]) -> ([String]?, [EnvironmentVariable]?) {
+ guard bytes.count > 4 else { return (nil, nil) }
+ let argc = Int(bytes.withUnsafeBytes { $0.loadUnaligned(as: Int32.self) })
+ var i = 4
+ // Skip the executable path and the NULs after it.
+ while i < bytes.count && bytes[i] != 0 { i += 1 }
+ while i < bytes.count && bytes[i] == 0 { i += 1 }
+
+ var strings: [String] = []
+ var start = i
+ while i < bytes.count {
+ if bytes[i] == 0 {
+ if i == start { break } // two NULs: the end
+ strings.append(String(decoding: bytes[start.. [String]? {
+ var buffer = [CChar](repeating: 0, count: 256 * 1024)
+ let len = Int(buffer.withUnsafeMutableBufferPointer {
+ mt_open_files(pid, $0.baseAddress, Int32($0.count))
+ })
+ guard len >= 0 else { return nil }
+ var files: [String] = []
+ var start = 0
+ for i in 0.. [Connection]? {
+ var sockets = [mt_socket](repeating: mt_socket(), count: 1024)
+ let n = Int(sockets.withUnsafeMutableBufferPointer {
+ mt_sockets(pid, $0.baseAddress, Int32($0.count))
+ })
+ guard n >= 0 else { return nil }
+ return (0.. [Connection] {
+ var out: [Connection] = []
+ for p in processes where p.pid > 0 {
+ if let c = connections(of: p.pid, name: p.name) { out.append(contentsOf: c) }
+ }
+ return out
+ }
+
+ static func tcpState(_ state: Int32) -> String {
+ switch state {
+ case 0: return "Closed"
+ case 1: return "Listen"
+ case 2: return "SYN sent"
+ case 3: return "SYN received"
+ case 4: return "Established"
+ case 5: return "Close wait"
+ case 6: return "FIN wait 1"
+ case 7: return "Closing"
+ case 8: return "Last ACK"
+ case 9: return "FIN wait 2"
+ case 10: return "Time wait"
+ default: return "Unknown"
+ }
+ }
+}
diff --git a/macos/Sources/MoonTaskSystem/Sampler.swift b/macos/Sources/MoonTaskSystem/Sampler.swift
new file mode 100644
index 0000000..e4e0f80
--- /dev/null
+++ b/macos/Sources/MoonTaskSystem/Sampler.swift
@@ -0,0 +1,351 @@
+import CDarwin
+import Darwin
+import Foundation
+import MoonTaskCore
+
+/// Reads the machine once per refresh. Rates (CPU %, bytes/s) are the
+/// difference to the previous call, so the first call reports zeros.
+///
+/// Not thread-safe: one sampler is used by one background queue.
+public final class Sampler {
+ private var lastCPUTicks: [UInt64] = []
+ private var lastProcessCPU: [ProcessIdentity: UInt64] = [:]
+ private var lastProcessDisk: [ProcessIdentity: (read: UInt64, written: UInt64)] = [:]
+ private var lastDisk: (read: UInt64, written: UInt64)?
+ private var lastNetwork: (received: UInt64, sent: UInt64)?
+ private var lastTime: UInt64 = 0
+ private var paths: [ProcessIdentity: String] = [:]
+ private var userNames: [UInt32: String] = [:]
+ private var volumes: [Volume] = []
+ private var lastVolumeRead: Date = .distantPast
+ private var kinfo = [mt_kinfo](repeating: mt_kinfo(), count: 8192)
+
+ private let ownUID = getuid()
+ private let ownPid = getpid()
+ private let coreCount = max(1, Int(mt_sysctl_int("hw.logicalcpu")))
+
+ public init() {}
+
+ public func sample() -> Snapshot {
+ let now = DispatchTime.now().uptimeNanoseconds
+ let elapsed = lastTime == 0 ? 0 : Double(now - lastTime)
+ lastTime = now
+
+ var snapshot = Snapshot(timestamp: Date())
+ snapshot.cpu = readCPU()
+ snapshot.memory = readMemory()
+ snapshot.processes = readProcesses(elapsedNs: elapsed)
+ (snapshot.diskRead, snapshot.diskWrite) = readDisk(elapsedNs: elapsed)
+ (snapshot.networkIn, snapshot.networkOut) = readNetwork(elapsedNs: elapsed)
+ snapshot.gpus = readGPUs()
+ snapshot.volumes = readVolumes()
+ snapshot.thermal = Self.thermal()
+ snapshot.uptime = ProcessInfo.processInfo.systemUptime
+ return snapshot
+ }
+
+ // MARK: - CPU
+
+ private func readCPU() -> CPUStats {
+ var ticks = [UInt64](repeating: 0, count: 4 * 256)
+ let cores = Int(ticks.withUnsafeMutableBufferPointer { mt_cpu_ticks($0.baseAddress, 256) })
+ guard cores > 0 else { return CPUStats() }
+ ticks = Array(ticks.prefix(4 * cores))
+ defer { lastCPUTicks = ticks }
+ guard lastCPUTicks.count == ticks.count else {
+ return CPUStats(perCore: Array(repeating: 0, count: cores))
+ }
+
+ var perCore: [Double] = []
+ var busy = 0.0, all = 0.0, user = 0.0, system = 0.0
+ for core in 0.. Double {
+ let now = ticks[4 * core + i], before = lastCPUTicks[4 * core + i]
+ return now >= before ? Double(now - before) : 0
+ }
+ let u = delta(0), s = delta(1), idle = delta(2), n = delta(3)
+ let total = u + s + idle + n
+ perCore.append(total > 0 ? (u + s + n) / total * 100 : 0)
+ busy += u + s + n
+ all += total
+ user += u + n
+ system += s
+ }
+ return CPUStats(
+ total: all > 0 ? busy / all * 100 : 0,
+ perCore: perCore,
+ user: all > 0 ? user / all * 100 : 0,
+ system: all > 0 ? system / all * 100 : 0
+ )
+ }
+
+ // MARK: - Memory
+
+ private func readMemory() -> MemoryStats {
+ var m = mt_memory()
+ guard mt_memory_stats(&m) == 0 else { return MemoryStats() }
+ return MemoryStats(
+ total: m.total, app: m.app, wired: m.wired, compressed: m.compressed,
+ cached: m.cached, free: m.free, swapTotal: m.swap_total, swapUsed: m.swap_used
+ )
+ }
+
+ // MARK: - Processes
+
+ private func readProcesses(elapsedNs: Double) -> [ProcessRow] {
+ let count = Int(kinfo.withUnsafeMutableBufferPointer {
+ mt_list_processes($0.baseAddress, Int32($0.count))
+ })
+ guard count > 0 else { return [] }
+
+ // macOS only shows the resource usage of other users' processes to
+ // root. /bin/ps is allowed to read it (it's setuid root), so for
+ // those processes MoonTask asks ps, once per refresh.
+ var others: [Int32: PSUsage]?
+
+ var rows: [ProcessRow] = []
+ rows.reserveCapacity(count)
+ var cpuNow: [ProcessIdentity: UInt64] = [:]
+ var diskNow: [ProcessIdentity: (read: UInt64, written: UInt64)] = [:]
+ let machineNs = elapsedNs * Double(coreCount)
+
+ for i in 0.. 0, let before = lastProcessCPU[identity], usage.cpu_ns >= before {
+ cpu = min(100, Double(usage.cpu_ns - before) / machineNs * 100)
+ }
+ if elapsedNs > 0, let before = lastProcessDisk[identity] {
+ let seconds = elapsedNs / 1e9
+ if usage.disk_read >= before.read {
+ read = Double(usage.disk_read - before.read) / seconds
+ }
+ if usage.disk_written >= before.written {
+ written = Double(usage.disk_written - before.written) / seconds
+ }
+ }
+ }
+
+ let owner: Owner
+ if pid == 0 {
+ owner = .kernel
+ } else if k.uid == ownUID {
+ owner = .current
+ } else if k.uid < 500 {
+ owner = .system
+ } else {
+ owner = .other
+ }
+
+ rows.append(ProcessRow(
+ pid: pid,
+ parentPid: pid == 0 ? nil : k.ppid,
+ name: pid == 0 ? "kernel_task" : name,
+ user: userName(k.uid),
+ uid: k.uid,
+ owner: owner,
+ state: ProcessState(bsdState: k.state),
+ cpu: cpu,
+ memory: usage.footprint > 0 ? usage.footprint : usage.resident,
+ threads: usage.threads >= 0 ? Int(usage.threads) : nil,
+ diskRead: read,
+ diskWrite: written,
+ nice: k.nice,
+ startTime: start,
+ cpuTime: Double(usage.cpu_ns) / 1e9,
+ path: path(for: identity),
+ isProtected: Safety.isProtected(pid: pid, name: pid == 0 ? "kernel_task" : name, ownPid: ownPid)
+ ))
+ }
+ lastProcessCPU = cpuNow
+ lastProcessDisk = diskNow
+ let alive = Set(rows.map(\.identity))
+ paths = paths.filter { alive.contains($0.key) }
+ return rows
+ }
+
+ struct PSUsage {
+ var resident: UInt64
+ var cpuNs: UInt64
+ }
+
+ /// Resident memory and CPU time of every process, from `ps`.
+ static func psUsage() -> [Int32: PSUsage] {
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: "/bin/ps")
+ process.arguments = ["-axo", "pid=,rss=,time="]
+ let pipe = Pipe()
+ process.standardOutput = pipe
+ process.standardError = FileHandle.nullDevice
+ do { try process.run() } catch { return [:] }
+ let data = pipe.fileHandleForReading.readDataToEndOfFile()
+ process.waitUntilExit()
+ return parsePS(String(decoding: data, as: UTF8.self))
+ }
+
+ static func parsePS(_ output: String) -> [Int32: PSUsage] {
+ var out: [Int32: PSUsage] = [:]
+ for line in output.split(separator: "\n") {
+ let fields = line.split(separator: " ", omittingEmptySubsequences: true)
+ guard fields.count >= 3, let pid = Int32(fields[0]), let rssKB = UInt64(fields[1]),
+ let seconds = parseCPUTime(String(fields[2]))
+ else { continue }
+ out[pid] = PSUsage(resident: rssKB * 1024, cpuNs: UInt64(seconds * 1e9))
+ }
+ return out
+ }
+
+ /// ps' CPU time: "[[dd-]hh:]mm:ss.ss".
+ static func parseCPUTime(_ text: String) -> Double? {
+ var days = 0.0
+ var rest = Substring(text)
+ if let dash = rest.firstIndex(of: "-") {
+ guard let d = Double(rest[.. String? {
+ if let known = paths[identity] { return known.isEmpty ? nil : known }
+ var buffer = [CChar](repeating: 0, count: 4096)
+ let len = buffer.withUnsafeMutableBufferPointer {
+ mt_process_path(identity.pid, $0.baseAddress, Int32($0.count))
+ }
+ let path = len > 0 ? String(cString: buffer) : ""
+ paths[identity] = path
+ return path.isEmpty ? nil : path
+ }
+
+ private func userName(_ uid: UInt32) -> String? {
+ if let known = userNames[uid] { return known }
+ guard let pw = getpwuid(uid) else { return nil }
+ let name = String(cString: pw.pointee.pw_name)
+ userNames[uid] = name
+ return name
+ }
+
+ // MARK: - Disk & network
+
+ private func readDisk(elapsedNs: Double) -> (Double, Double) {
+ var read: UInt64 = 0, written: UInt64 = 0
+ guard mt_disk_totals(&read, &written) == 0 else { return (0, 0) }
+ defer { lastDisk = (read, written) }
+ guard let last = lastDisk, elapsedNs > 0 else { return (0, 0) }
+ let seconds = elapsedNs / 1e9
+ return (
+ read >= last.read ? Double(read - last.read) / seconds : 0,
+ written >= last.written ? Double(written - last.written) / seconds : 0
+ )
+ }
+
+ private func readNetwork(elapsedNs: Double) -> (Double, Double) {
+ var received: UInt64 = 0, sent: UInt64 = 0
+ guard mt_network_totals(&received, &sent) == 0 else { return (0, 0) }
+ defer { lastNetwork = (received, sent) }
+ guard let last = lastNetwork, elapsedNs > 0 else { return (0, 0) }
+ let seconds = elapsedNs / 1e9
+ return (
+ received >= last.received ? Double(received - last.received) / seconds : 0,
+ sent >= last.sent ? Double(sent - last.sent) / seconds : 0
+ )
+ }
+
+ // MARK: - GPU, volumes, thermal state
+
+ private func readGPUs() -> [GPUStats] {
+ var gpus = [mt_gpu](repeating: mt_gpu(), count: 8)
+ let n = Int(gpus.withUnsafeMutableBufferPointer { mt_gpus($0.baseAddress, 8) })
+ guard n > 0 else { return [] }
+ return (0..= 0 ? g.utilization : nil,
+ memoryUsed: g.memory_used >= 0 ? UInt64(g.memory_used) : nil,
+ cores: g.cores > 0 ? Int(g.cores) : nil
+ )
+ }
+ }
+
+ private func readVolumes() -> [Volume] {
+ // Volume sizes change slowly; every 10 s is plenty.
+ guard Date().timeIntervalSince(lastVolumeRead) > 10 else { return volumes }
+ lastVolumeRead = Date()
+ let keys: [URLResourceKey] = [
+ .volumeNameKey, .volumeTotalCapacityKey, .volumeAvailableCapacityForImportantUsageKey,
+ .volumeAvailableCapacityKey, .volumeIsInternalKey, .volumeIsBrowsableKey,
+ ]
+ let urls = FileManager.default.mountedVolumeURLs(
+ includingResourceValuesForKeys: keys, options: [.skipHiddenVolumes]
+ ) ?? []
+ volumes = urls.compactMap { url in
+ guard let v = try? url.resourceValues(forKeys: Set(keys)),
+ v.volumeIsBrowsable ?? true,
+ let total = v.volumeTotalCapacity, total > 0
+ else { return nil }
+ let available = v.volumeAvailableCapacityForImportantUsage.map { UInt64(max(0, $0)) }
+ ?? UInt64(max(0, v.volumeAvailableCapacity ?? 0))
+ return Volume(
+ name: v.volumeName ?? url.lastPathComponent,
+ mountPoint: url.path,
+ total: UInt64(total),
+ available: min(UInt64(total), available),
+ isInternal: v.volumeIsInternal ?? false
+ )
+ }
+ return volumes
+ }
+
+ static func thermal() -> ThermalLevel {
+ switch ProcessInfo.processInfo.thermalState {
+ case .nominal: return .nominal
+ case .fair: return .fair
+ case .serious: return .serious
+ case .critical: return .critical
+ @unknown default: return .nominal
+ }
+ }
+}
+
+// The sampler is only ever used from one queue at a time (see above).
+extension Sampler: @unchecked Sendable {}
+
+/// A C `char[N]` field (imported as a tuple) as a String.
+func cString(_ tuple: T) -> String {
+ withUnsafeBytes(of: tuple) { raw in
+ let bytes = raw.bindMemory(to: UInt8.self)
+ let end = bytes.firstIndex(of: 0) ?? bytes.count
+ return String(decoding: bytes[.. SystemInfo {
+ let info = ProcessInfo.processInfo
+ let perf = mt_sysctl_int("hw.perflevel0.logicalcpu")
+ let eff = mt_sysctl_int("hw.perflevel1.logicalcpu")
+ let memory = mt_sysctl_int("hw.memsize")
+ return SystemInfo(
+ hostName: Host.current().localizedName ?? info.hostName,
+ osVersion: "macOS " + info.operatingSystemVersionString
+ .replacingOccurrences(of: "Version ", with: ""),
+ model: sysctlString("hw.model"),
+ chip: sysctlString("machdep.cpu.brand_string"),
+ cores: info.activeProcessorCount,
+ performanceCores: perf > 0 ? Int(perf) : nil,
+ efficiencyCores: eff > 0 ? Int(eff) : nil,
+ memory: memory > 0 ? UInt64(memory) : 0,
+ bootTime: Date(timeIntervalSinceNow: -info.systemUptime)
+ )
+ }
+
+ static func sysctlString(_ name: String) -> String {
+ var buffer = [CChar](repeating: 0, count: 256)
+ _ = buffer.withUnsafeMutableBufferPointer {
+ mt_sysctl_string(name, $0.baseAddress, Int32($0.count))
+ }
+ return String(cString: buffer)
+ }
+}
diff --git a/macos/Tests/MoonTaskCoreTests/ProcessListTests.swift b/macos/Tests/MoonTaskCoreTests/ProcessListTests.swift
new file mode 100644
index 0000000..d10151c
--- /dev/null
+++ b/macos/Tests/MoonTaskCoreTests/ProcessListTests.swift
@@ -0,0 +1,158 @@
+import XCTest
+@testable import MoonTaskCore
+
+private func row(
+ _ pid: Int32, parent: Int32?, _ name: String, cpu: Double = 0, memory: UInt64 = 0,
+ owner: Owner = .current, user: String = "luna"
+) -> ProcessRow {
+ ProcessRow(
+ pid: pid, parentPid: parent, name: name, user: user, uid: 501, owner: owner,
+ state: .sleeping, cpu: cpu, memory: memory, threads: 4
+ )
+}
+
+private let sample: [ProcessRow] = [
+ row(0, parent: nil, "kernel_task", cpu: 3, owner: .kernel, user: "root"),
+ row(1, parent: 0, "launchd", owner: .system, user: "root"),
+ row(300, parent: 1, "WindowServer", cpu: 8, memory: 400, owner: .system, user: "_windowserver"),
+ row(500, parent: 1, "Safari", cpu: 5, memory: 900),
+ row(501, parent: 500, "Safari Web Content", cpu: 12, memory: 300),
+ row(502, parent: 500, "Safari Web Content", cpu: 1, memory: 200),
+ row(600, parent: 1, "Terminal", cpu: 0.5, memory: 100),
+ row(601, parent: 600, "zsh", memory: 10),
+]
+
+final class ProcessListTests: XCTestCase {
+ func testTreeNestsChildrenUnderParentsSortedByCPU() {
+ let rows = visibleRows(sample, VisibleOptions(mode: .tree))
+ XCTAssertEqual(rows.map(\.process.pid), [0, 1, 300, 500, 501, 502, 600, 601])
+ XCTAssertEqual(rows.map(\.depth), [0, 1, 2, 2, 3, 3, 2, 3])
+ XCTAssertTrue(rows[1].hasChildren)
+ }
+
+ func testCollapsedBranchesHideTheirChildren() {
+ let rows = visibleRows(sample, VisibleOptions(mode: .tree, collapsed: [500]))
+ XCTAssertFalse(rows.contains { $0.process.pid == 501 })
+ XCTAssertEqual(rows.first { $0.process.pid == 500 }?.isExpanded, false)
+ }
+
+ func testSearchKeepsAncestorsDimmed() {
+ let rows = visibleRows(sample, VisibleOptions(mode: .tree, query: "zsh"))
+ XCTAssertEqual(rows.map(\.process.pid), [0, 1, 600, 601])
+ XCTAssertEqual(rows.map(\.isDimmed), [true, true, true, false])
+ }
+
+ func testListIsFlatAndSorted() {
+ let opts = VisibleOptions(mode: .list, sort: SortState(key: .memory, ascending: false))
+ let rows = visibleRows(sample, opts)
+ XCTAssertEqual(rows.first?.process.name, "Safari")
+ XCTAssertTrue(rows.allSatisfy { $0.depth == 0 })
+ }
+
+ func testAppsGroupSameNamedProcessesAndSumThem() {
+ let opts = VisibleOptions(mode: .apps, sort: SortState(key: .cpu, ascending: false))
+ let rows = visibleRows(sample, opts)
+ let group = rows.first { $0.kind == .group }
+ XCTAssertEqual(group?.process.name, "Safari Web Content")
+ XCTAssertEqual(group?.process.cpu, 13)
+ XCTAssertEqual(group?.process.memory, 500)
+ XCTAssertEqual(group?.members.count, 2)
+ XCTAssertEqual(rows.first?.id, group?.id, "the busiest app comes first")
+ }
+
+ func testOpenGroupsListTheirMembers() {
+ let opts = VisibleOptions(mode: .apps, openGroups: [groupRowID("Safari Web Content")])
+ let rows = visibleRows(sample, opts)
+ XCTAssertEqual(rows.filter { $0.depth == 1 }.count, 2)
+ }
+
+ func testOwnerFilterAndHiddenKernel() {
+ let mine = visibleRows(sample, VisibleOptions(mode: .list, owner: .mine))
+ XCTAssertTrue(mine.allSatisfy { $0.process.owner == .current })
+ let noKernel = visibleRows(sample, VisibleOptions(mode: .list, showKernel: false))
+ XCTAssertFalse(noKernel.contains { $0.process.owner == .kernel })
+ }
+
+ func testParentCyclesStillShowEveryProcess() {
+ let cyclic = [row(10, parent: 11, "a"), row(11, parent: 10, "b")]
+ let rows = visibleRows(cyclic, VisibleOptions(mode: .tree))
+ XCTAssertEqual(Set(rows.map(\.process.pid)), [10, 11])
+ }
+
+ func testDescendants() {
+ XCTAssertEqual(countDescendants(sample, of: 500), 2)
+ XCTAssertEqual(descendantsFirst(sample, of: 600).map(\.pid), [601, 600])
+ }
+
+ func testSortToggle() {
+ let cpu = SortState(key: .cpu, ascending: false)
+ XCTAssertEqual(cpu.toggled(.cpu), SortState(key: .cpu, ascending: true))
+ XCTAssertEqual(cpu.toggled(.name), SortState(key: .name, ascending: true))
+ XCTAssertEqual(cpu.toggled(.memory), SortState(key: .memory, ascending: false))
+ }
+}
+
+final class SafetyTests: XCTestCase {
+ func testProtectedProcesses() {
+ XCTAssertTrue(Safety.isProtected(pid: 0, name: "kernel_task", ownPid: 999))
+ XCTAssertTrue(Safety.isProtected(pid: 1, name: "launchd", ownPid: 999))
+ XCTAssertTrue(Safety.isProtected(pid: 300, name: "WindowServer", ownPid: 999))
+ XCTAssertTrue(Safety.isProtected(pid: 999, name: "MoonTask", ownPid: 999))
+ XCTAssertFalse(Safety.isProtected(pid: 500, name: "Safari", ownPid: 999))
+ }
+
+ func testConfirmation() {
+ let own = sample[3]
+ let system = sample[2]
+ XCTAssertFalse(Safety.needsConfirmation(.end, on: own, confirmOwn: false))
+ XCTAssertTrue(Safety.needsConfirmation(.end, on: own, confirmOwn: true))
+ XCTAssertTrue(Safety.needsConfirmation(.end, on: system, confirmOwn: false))
+ XCTAssertTrue(Safety.needsConfirmation(.endTree, on: own, confirmOwn: false))
+ XCTAssertFalse(Safety.needsConfirmation(.resume, on: system, confirmOwn: true))
+ }
+
+ func testProtectedRowsAllowNothing() {
+ var p = sample[3]
+ p.isProtected = true
+ XCTAssertFalse(Safety.isAllowed(.end, on: p))
+ XCTAssertFalse(Safety.isAllowed(.suspend, on: p))
+ }
+}
+
+final class FormatTests: XCTestCase {
+ func testBytes() {
+ XCTAssertEqual(Format.bytes(UInt64(512)), "512 B")
+ XCTAssertEqual(Format.bytes(UInt64(1536)), "1.5 KB")
+ XCTAssertEqual(Format.bytes(UInt64(3) * 1024 * 1024 * 1024), "3.0 GB")
+ XCTAssertEqual(Format.bytes(UInt64(200) * 1024 * 1024), "200 MB")
+ }
+
+ func testOthers() {
+ XCTAssertEqual(Format.rate(0), "0 B/s")
+ XCTAssertEqual(Format.percent(37), "37.0 %")
+ XCTAssertEqual(Format.percent(37, digits: 0), "37 %")
+ XCTAssertEqual(Format.duration(3 * 86_400 + 4 * 3_600), "3 d 4 h")
+ XCTAssertEqual(Format.duration(125), "2 min")
+ XCTAssertEqual(Format.cpuTime(3_725), "1:02:05")
+ XCTAssertEqual(Format.temperature(58.4), "58 °C")
+ }
+}
+
+final class HistoryTests: XCTestCase {
+ func testSeriesKeepsCapacity() {
+ var s = Series(capacity: 3)
+ for v in 1...5 { s.append(Double(v)) }
+ XCTAssertEqual(s.values, [3, 4, 5])
+ XCTAssertEqual(s.peak, 5)
+ }
+
+ func testActivity() {
+ let now = Date()
+ let old = [sample[3], sample[4]]
+ let new = [sample[3], sample[6]]
+ let events = activity(from: old, to: new, at: now)
+ XCTAssertEqual(events.count, 2)
+ XCTAssertTrue(events.contains { $0.kind == .started && $0.pid == 600 })
+ XCTAssertTrue(events.contains { $0.kind == .ended && $0.pid == 501 })
+ }
+}
diff --git a/macos/Tests/MoonTaskSystemTests/SystemTests.swift b/macos/Tests/MoonTaskSystemTests/SystemTests.swift
new file mode 100644
index 0000000..4c660c8
--- /dev/null
+++ b/macos/Tests/MoonTaskSystemTests/SystemTests.swift
@@ -0,0 +1,134 @@
+import Darwin
+import XCTest
+@testable import MoonTaskCore
+@testable import MoonTaskSystem
+
+final class SamplerTests: XCTestCase {
+ func testSamplesTheMachine() {
+ let sampler = Sampler()
+ _ = sampler.sample()
+ Thread.sleep(forTimeInterval: 0.3)
+ let s = sampler.sample()
+
+ XCTAssertGreaterThan(s.memory.total, 0)
+ XCTAssertGreaterThan(s.memory.used, 0)
+ XCTAssertFalse(s.cpu.perCore.isEmpty)
+ XCTAssertTrue((0...100).contains(s.cpu.total))
+ XCTAssertGreaterThan(s.processes.count, 10)
+
+ let me = s.processes.first { $0.pid == getpid() }
+ XCTAssertNotNil(me, "the test runner lists itself")
+ XCTAssertEqual(me?.owner, .current)
+ XCTAssertTrue(me?.isProtected ?? false, "MoonTask never ends itself")
+ XCTAssertNotNil(me?.threads)
+ XCTAssertGreaterThan(me?.memory ?? 0, 0)
+
+ let launchd = s.processes.first { $0.pid == 1 }
+ XCTAssertEqual(launchd?.name, "launchd")
+ XCTAssertTrue(launchd?.isProtected ?? false)
+ XCTAssertGreaterThan(launchd?.memory ?? 0, 0, "other users' processes have their memory (via ps)")
+
+ XCTAssertFalse(s.volumes.isEmpty)
+ }
+
+ func testParsesPS() {
+ let usage = Sampler.parsePS("""
+ 1 12345 0:42.50
+ 412 2048 1-02:03:04.00
+ 7 10 123:45.67
+ """)
+ XCTAssertEqual(usage[1]?.resident, 12345 * 1024)
+ XCTAssertEqual(usage[1]?.cpuNs, 42_500_000_000)
+ // 1 day, 2 h, 3 min, 4 s
+ let expected: UInt64 = 93_784_000_000_000
+ XCTAssertEqual(usage[412]?.cpuNs, expected)
+ XCTAssertEqual(Sampler.parseCPUTime("123:45.67")!, 7425.67, accuracy: 0.001)
+ }
+
+ func testSystemInfo() {
+ let info = SystemInfoReader.read()
+ XCTAssertGreaterThan(info.cores, 0)
+ XCTAssertGreaterThan(info.memory, 0)
+ XCTAssertFalse(info.osVersion.isEmpty)
+ }
+}
+
+final class InspectorTests: XCTestCase {
+ func testOwnProcessDetails() throws {
+ let sampler = Sampler()
+ let me = try XCTUnwrap(sampler.sample().processes.first { $0.pid == getpid() })
+ let details = ProcessInspector.details(of: me)
+ XCTAssertFalse(details.arguments?.isEmpty ?? true)
+ XCTAssertNotNil(details.environment)
+ XCTAssertNotNil(details.openFiles)
+ XCTAssertNotNil(details.connections)
+ }
+
+ func testParsesProcArgs() {
+ var bytes: [UInt8] = []
+ withUnsafeBytes(of: Int32(2)) { bytes.append(contentsOf: $0) }
+ bytes += Array("/bin/zsh".utf8) + [0, 0, 0]
+ bytes += Array("zsh".utf8) + [0] + Array("-l".utf8) + [0]
+ bytes += Array("HOME=/Users/luna".utf8) + [0] + Array("A=b=c".utf8) + [0, 0]
+ let (args, env) = ProcessInspector.parseProcArgs(bytes)
+ XCTAssertEqual(args, ["zsh", "-l"])
+ XCTAssertEqual(env?.map(\.name), ["HOME", "A"])
+ XCTAssertEqual(env?.last?.value, "b=c")
+ }
+
+ func testTCPStates() {
+ XCTAssertEqual(ProcessInspector.tcpState(1), "Listen")
+ XCTAssertEqual(ProcessInspector.tcpState(4), "Established")
+ }
+}
+
+final class ControlTests: XCTestCase {
+ func testActsOnlyOnTheSameProcessInstance() throws {
+ let child = Process()
+ child.executableURL = URL(fileURLWithPath: "/bin/sleep")
+ child.arguments = ["30"]
+ try child.run()
+ defer { if child.isRunning { child.terminate() } }
+ Thread.sleep(forTimeInterval: 0.2)
+
+ let row = try XCTUnwrap(Sampler().sample().processes.first { $0.pid == child.processIdentifier })
+ var stale = row
+ stale.startTime -= 60
+ XCTAssertThrowsError(try ProcessControl.perform(.end, on: stale)) { error in
+ XCTAssertEqual(error as? ControlError, .gone("sleep"))
+ }
+ XCTAssertTrue(child.isRunning)
+
+ try ProcessControl.perform(.suspend, on: row)
+ try ProcessControl.perform(.resume, on: row)
+ try ProcessControl.perform(.setPriority(10), on: row)
+ try ProcessControl.perform(.end, on: row)
+ child.waitUntilExit()
+ XCTAssertFalse(child.isRunning)
+ }
+
+ func testRefusesProtectedProcesses() throws {
+ let launchd = try XCTUnwrap(Sampler().sample().processes.first { $0.pid == 1 })
+ XCTAssertThrowsError(try ProcessControl.perform(.end, on: launchd))
+ }
+}
+
+final class LaunchAgentTests: XCTestCase {
+ func testParsesLaunchctlList() {
+ let jobs = LaunchAgents.parseList("""
+ PID\tStatus\tLabel
+ 412\t0\tcom.apple.Finder
+ -\t0\tcom.example.backup
+ -\t78\tcom.example.broken
+ """)
+ XCTAssertEqual(jobs.map(\.label), ["com.apple.Finder", "com.example.backup", "com.example.broken"])
+ XCTAssertEqual(jobs[0].pid, 412)
+ XCTAssertTrue(jobs[0].isApple)
+ XCTAssertNil(jobs[1].pid)
+ XCTAssertEqual(jobs[2].lastExitStatus, 78)
+ }
+
+ func testListsTheSessionsJobs() {
+ XCTAssertFalse(LaunchAgents.list().isEmpty)
+ }
+}
diff --git a/macos/scripts/bundle.sh b/macos/scripts/bundle.sh
new file mode 100755
index 0000000..8cb0150
--- /dev/null
+++ b/macos/scripts/bundle.sh
@@ -0,0 +1,39 @@
+#!/bin/bash
+# Builds MoonTask.app (universal: Apple silicon + Intel) and a disk image.
+#
+# usage: scripts/bundle.sh [output dir]
+set -euo pipefail
+cd "$(dirname "$0")/.."
+
+VERSION=${1:?version, e.g. 0.3.0}
+OUT=${2:-dist}
+APP="$OUT/MoonTask.app"
+
+swift build -c release --arch arm64 --arch x86_64
+BIN=$(swift build -c release --arch arm64 --arch x86_64 --show-bin-path)/MoonTask
+
+rm -rf "$APP"
+mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
+cp "$BIN" "$APP/Contents/MacOS/MoonTask"
+cp Resources/AppIcon.icns "$APP/Contents/Resources/AppIcon.icns"
+sed "s/__VERSION__/$VERSION/g" Resources/Info.plist > "$APP/Contents/Info.plist"
+printf 'APPL????' > "$APP/Contents/PkgInfo"
+
+# Ad-hoc signature: required to run on Apple silicon. Not notarized, so
+# macOS asks once before the first start (see the README).
+codesign --force --deep --sign - "$APP"
+codesign --verify --verbose=2 "$APP"
+
+# The disk image: the night-sky window with the app and a shortcut to
+# Applications (laid out by dmgbuild, which needs no Finder scripting).
+DMG="$OUT/MoonTask_${VERSION}_macos_universal.dmg"
+rm -f "$DMG"
+BG="$OUT/background.tiff"
+tiffutil -cathidpicheck Resources/dmg/background.png Resources/dmg/background@2x.png -out "$BG"
+if [ ! -x "$OUT/.venv/bin/dmgbuild" ]; then
+ python3 -m venv "$OUT/.venv"
+ "$OUT/.venv/bin/pip" install --quiet dmgbuild
+fi
+"$OUT/.venv/bin/dmgbuild" -s scripts/dmg-settings.py \
+ -D app="$APP" -D background="$BG" "MoonTask" "$DMG"
+echo "Built $APP and $DMG"
diff --git a/macos/scripts/dmg-settings.py b/macos/scripts/dmg-settings.py
new file mode 100644
index 0000000..f8a691b
--- /dev/null
+++ b/macos/scripts/dmg-settings.py
@@ -0,0 +1,26 @@
+# dmgbuild settings for MoonTask's disk image: the night-sky background,
+# the app on the left, Applications on the right.
+# Used by scripts/bundle.sh: dmgbuild -s scripts/dmg-settings.py -D app=… -D background=… …
+import os.path
+
+app = defines["app"] # noqa: F821 (provided by dmgbuild)
+background = defines["background"] # noqa: F821
+
+format = "UDZO"
+filesystem = "HFS+"
+files = [app]
+symlinks = {"Applications": "/Applications"}
+icon_locations = {
+ os.path.basename(app): (170, 190),
+ "Applications": (490, 190),
+}
+window_rect = ((200, 140), (660, 400))
+default_view = "icon-view"
+icon_size = 112
+text_size = 13
+show_status_bar = False
+show_tab_view = False
+show_toolbar = False
+show_pathbar = False
+show_sidebar = False
+include_icon_view_settings = True
diff --git a/package-lock.json b/package-lock.json
index ea37167..89a6a9e 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "moontask",
- "version": "0.2.2",
+ "version": "0.3.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "moontask",
- "version": "0.2.2",
+ "version": "0.3.0",
"license": "MIT",
"dependencies": {
"@tauri-apps/api": "^2.11.1",
diff --git a/package.json b/package.json
index e5002aa..452fb07 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "moontask",
"private": true,
- "version": "0.2.2",
+ "version": "0.3.0",
"description": "MoonTask – every process, calmly under the moon.",
"license": "MIT",
"type": "module",
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 914233b..2197a04 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -1922,7 +1922,7 @@ dependencies = [
[[package]]
name = "moontask"
-version = "0.2.2"
+version = "0.3.0"
dependencies = [
"libc",
"netstat2",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 8c943cb..23e93db 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "moontask"
-version = "0.2.2"
+version = "0.3.0"
description = "MoonTask – every process, calmly under the moon. A local, open-source task manager."
authors = ["MoonTask contributors"]
license = "MIT"
diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json
index 2489c6e..8ebfea6 100644
--- a/src-tauri/tauri.conf.json
+++ b/src-tauri/tauri.conf.json
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "MoonTask",
- "version": "0.2.2",
+ "version": "0.3.0",
"identifier": "io.moontask.app",
"build": {
"beforeDevCommand": "npm run dev",