# Port Smith - Application Documentation

This document provides an overview of each file in the Port Smith application, its expected scope of work, and categorization based on Swift app architecture best practices.

---

## 📁 File Categories

### 1. **App Entry Point & Lifecycle**
Files responsible for application initialization, lifecycle management, and system integration.

### 2. **Core Business Logic**
Files containing the main application logic, data processing, and state management.

### 3. **UI Components (Views)**
SwiftUI views and UI-related components that compose the user interface.

### 4. **Utilities & Helpers**
Supporting files that provide reusable functionality, integrations, and helper methods.

### 5. **Data Models**
Data structures and models used throughout the application.

### 6. **Configuration**
Configuration files, entitlements, and setup files.

---

## 📄 File Documentation

### 1. App Entry Point & Lifecycle

#### `port_smith_selfApp.swift`
**Scope:** Application entry point and main app structure
- Defines the main `App` struct using `@main` attribute
- Integrates `AppDelegate` using `@NSApplicationDelegateAdaptor`
- Provides minimal `Settings` scene to satisfy SwiftUI App protocol
- **Category:** App Entry Point & Lifecycle
- **Best Practice:** Entry point should remain minimal; delegate complex initialization to `AppDelegate`

#### `AppDelegate.swift`
**Scope:** Application lifecycle management and system integration
- Handles application launch (`applicationDidFinishLaunching`)
- Manages status bar (menu bar) icon and popover
- Initializes Sentry for error tracking
- Sets up notification delegate for handling user notification actions
- Creates and manages `PortScanner` instance
- Handles popover show/hide logic
- Processes notification actions (VIEW_ACTION, KILL_ACTION)
- Tracks app usage via `InstallTracker`
- **Category:** App Entry Point & Lifecycle
- **Best Practice:** Centralizes system-level integrations (notifications, status bar, error tracking)

---

### 2. Core Business Logic

#### `PortScanner.swift`
**Scope:** Core port scanning functionality and port management
- Scans system for listening TCP ports using `lsof` command
- Parses `lsof` output to extract port information (PID, port number, command)
- Manages auto-scanning with configurable intervals
- Detects new ports and sends notifications
- Handles port filtering by range
- Provides process termination (kill) functionality
- Manages notification permissions and cooldown periods
- Highlights ports from notification interactions
- Opens process working directory in Finder
- Retrieves app icons for processes
- **Category:** Core Business Logic
- **Best Practice:** ObservableObject pattern for reactive state management; async/await for concurrent operations

#### `InstallTracker.swift`
**Scope:** Application installation tracking and analytics
- Generates and manages unique install IDs
- Tracks first install vs. subsequent launches
- Collects system information (OS version, CPU architecture, language, country)
- Syncs installation data with Supabase backend
- Tracks user metrics (ports killed, notification preferences, launch at login)
- Implements debounced updates to reduce API calls
- Handles network retries with exponential backoff
- Manages UserDefaults for local state persistence
- **Category:** Core Business Logic
- **Best Practice:** Background queue operations to avoid blocking main thread; debouncing for performance

#### `VersionManager.swift`
**Scope:** Application version checking and update management
- Fetches version information from Supabase
- Compares current app version with latest and minimum supported versions
- Determines if app is deprecated (force update required)
- Determines if update is available (optional update)
- Handles version string parsing and comparison
- Returns update URLs for user downloads
- **Category:** Core Business Logic
- **Best Practice:** Singleton pattern for shared state; async operations for network calls

#### `LaunchAtLoginManager.swift`
**Scope:** Launch at login functionality
- Manages app registration in macOS login items
- Uses modern `SMAppService` API for macOS 13+
- Falls back to legacy `LSSharedFileList` for older macOS versions
- Checks current launch at login status
- Updates Supabase with user preference changes
- **Category:** Core Business Logic
- **Best Practice:** Version-specific API usage with fallback support; singleton pattern

---

### 3. UI Components (Views)

#### `ContentView.swift`
**Scope:** Main content view orchestrating the entire UI
- Coordinates all UI components and overlays
- Manages view state (settings, welcome, tracking info, deprecated overlay)
- Handles user preferences via `@AppStorage`
- Applies settings to `PortScanner` on appear
- Manages initial loader animation
- Handles version validation and update banners
- Coordinates copy-to-clipboard functionality
- Manages kill confirmation dialogs
- **Category:** UI Components (Views)
- **Best Practice:** View composition; state management via `@State` and `@Binding`; separation of concerns

#### `LoaderView.swift`
**Scope:** Loading indicator component
- Displays animated loading triangle icon
- Shows customizable loading messages
- Provides visual feedback during port scanning
- **Category:** UI Components (Views)
- **Best Practice:** Reusable component with customizable properties

#### `VisualEffectView.swift`
**Scope:** macOS visual effect wrapper for SwiftUI
- Bridges `NSVisualEffectView` to SwiftUI
- Provides blur and material effects for modern macOS appearance
- Supports different materials and blending modes
- **Category:** UI Components (Views)
- **Best Practice:** NSViewRepresentable pattern for AppKit integration

#### `views/PortsListView.swift`
**Scope:** List view displaying all active ports
- Displays scrollable list of port rows
- Shows loading state when scanning
- Shows empty state when no ports found
- Delegates individual port rendering to `PortRowView`
- **Category:** UI Components (Views)
- **Best Practice:** Lazy loading with `LazyVStack` for performance

#### `views/PortRowView.swift`
**Scope:** Individual port row component
- Displays port information (port number, PID, command)
- Shows process icon if available
- Provides hover effects and interactions
- Handles copy and kill actions
- **Category:** UI Components (Views)
- **Best Practice:** Component composition; callback-based actions

#### `views/PortInfoView.swift`
**Scope:** Detailed port information display
- Shows expanded port details
- Displays process information
- **Category:** UI Components (Views)
- **Best Practice:** Detail view pattern

#### `views/PortIconView.swift`
**Scope:** Process icon display component
- Renders process-specific icons
- Falls back to default icons when process icon unavailable
- **Category:** UI Components (Views)
- **Best Practice:** Icon provider pattern

#### `views/PortActionsView.swift`
**Scope:** Action buttons for port operations
- Provides kill, copy, and other port-specific actions
- **Category:** UI Components (Views)
- **Best Practice:** Action button composition

#### `views/SettingsView.swift`
**Scope:** Settings/configuration interface
- User name input with validation
- Notification toggle
- Launch at login toggle
- Version display
- Links to website, bug reports, and analytics info
- Donation button
- Quit button
- **Category:** UI Components (Views)
- **Best Practice:** Form-style layout; preference management

#### `views/HeaderView.swift`
**Scope:** Application header with navigation
- Displays "Port Smith" title
- Shows breadcrumb navigation (Port Smith / Settings)
- Provides back button for navigation
- Settings gear icon toggle
- **Category:** UI Components (Views)
- **Best Practice:** Navigation header pattern; conditional rendering

#### `views/WelcomeView.swift`
**Scope:** First-time user welcome screen
- Collects user name on first launch
- Introduces app functionality
- **Category:** UI Components (Views)
- **Best Practice:** Onboarding flow

#### `views/InitialLoaderView.swift`
**Scope:** Initial app loading screen
- Shows during first port scan
- Displays animated loading messages
- **Category:** UI Components (Views)
- **Best Practice:** Loading state management

#### `views/DeprecatedOverlayView.swift`
**Scope:** Force update overlay
- Blocks app usage when deprecated
- Shows update message and download link
- **Category:** UI Components (Views)
- **Best Practice:** Modal overlay pattern

#### `views/UpdateBannerView.swift`
**Scope:** Optional update notification banner
- Shows when update is available (non-blocking)
- Provides update download link
- **Category:** UI Components (Views)
- **Best Practice:** Banner notification pattern

#### `views/KillConfirmationOverlay.swift`
**Scope:** Process kill confirmation dialog
- Asks user to confirm before killing process
- Shows process details
- **Category:** UI Components (Views)
- **Best Practice:** Confirmation dialog pattern

#### `views/CopyStatusOverlay.swift`
**Scope:** Copy-to-clipboard feedback
- Shows temporary success message after copying
- Auto-dismisses after timeout
- **Category:** UI Components (Views)
- **Best Practice:** Toast notification pattern

#### `views/TrackingInfoView.swift`
**Scope:** Analytics and data tracking information
- Displays what data is collected
- Privacy transparency information
- **Category:** UI Components (Views)
- **Best Practice:** Privacy disclosure pattern

#### `views/GridBackgroundView.swift`
**Scope:** Decorative grid background
- Provides visual grid pattern for UI
- Customizable grid size and colors
- **Category:** UI Components (Views)
- **Best Practice:** Background decoration component

---

### 4. Utilities & Helpers

#### `Supabase.swift`
**Scope:** Supabase client initialization and data models
- Initializes Supabase client with URL and API key
- Defines `AppVersion` data model for version checking
- Defines enums for deprecation status and platform
- **Category:** Utilities & Helpers
- **Best Practice:** Centralized API client; shared data models

#### `ProcessIconProvider.swift`
**Scope:** Process icon mapping and retrieval
- Maps process commands to icon asset names
- Provides fallback icon logic
- Handles case-insensitive matching
- Supports path-based command matching
- **Category:** Utilities & Helpers
- **Best Practice:** Provider pattern; enum-based utility

---

### 5. Data Models

#### `PortInfo.swift`
**Scope:** Port information data structure
- Represents a listening port with associated process
- Contains: command name, PID, port number, raw lsof line
- Conforms to `Identifiable` for SwiftUI list rendering
- **Category:** Data Models
- **Best Practice:** Value type (struct); identifiable for SwiftUI

#### `Item.swift`
**Scope:** SwiftData model (legacy/unused)
- Basic SwiftData model with timestamp
- Appears to be unused in current implementation
- **Category:** Data Models
- **Best Practice:** May be removed if unused

---

### 6. Configuration

#### `port_smith_self.entitlements`
**Scope:** App capabilities and security settings
- Disables app sandbox (required for system-level operations)
- Enables user-selected file read access
- **Category:** Configuration
- **Best Practice:** Minimal entitlements; security-conscious configuration

---

## 🏗️ Architecture Overview

### Design Patterns Used

1. **MVVM (Model-View-ViewModel)**
   - `PortScanner` acts as ViewModel (ObservableObject)
   - Views observe scanner state
   - Models (`PortInfo`) represent data

2. **Singleton Pattern**
   - `InstallTracker.shared`
   - `VersionManager.shared`
   - `LaunchAtLoginManager.shared`

3. **Provider Pattern**
   - `ProcessIconProvider` for icon mapping

4. **Delegate Pattern**
   - `AppDelegate` conforms to `NSApplicationDelegate`
   - `AppDelegate` conforms to `UNUserNotificationCenterDelegate`

5. **Factory Pattern**
   - `PortScanner` creates and manages processes

### State Management

- **@Published properties** in `PortScanner` for reactive updates
- **@AppStorage** for user preferences persistence
- **@State** and **@Binding** for local view state
- **UserDefaults** for cross-session persistence

### Concurrency

- **async/await** for asynchronous operations
- **Task** for concurrent work
- **MainActor** for UI updates
- **DispatchQueue** for background operations

---

## 📊 File Organization Recommendations

### Current Structure
```
port-smith-self/
├── Core Files (root level)
├── views/ (UI components)
└── Assets.xcassets/
```

### Suggested Improvements

1. **Group by Feature:**
   ```
   port-smith-self/
   ├── App/
   │   ├── port_smith_selfApp.swift
   │   └── AppDelegate.swift
   ├── Core/
   │   ├── PortScanner.swift
   │   ├── InstallTracker.swift
   │   ├── VersionManager.swift
   │   └── LaunchAtLoginManager.swift
   ├── Models/
   │   ├── PortInfo.swift
   │   └── Item.swift
   ├── Services/
   │   └── Supabase.swift
   ├── Utilities/
   │   └── ProcessIconProvider.swift
   ├── Views/
   │   ├── ContentView.swift
   │   ├── LoaderView.swift
   │   ├── VisualEffectView.swift
   │   └── Components/ (subdirectory for smaller components)
   └── Configuration/
       └── port_smith_self.entitlements
   ```

2. **Benefits:**
   - Clearer separation of concerns
   - Easier navigation
   - Better scalability
   - Follows Swift project conventions

---

## 🔧 Dependencies

- **SwiftUI** - UI framework
- **AppKit** - macOS system integration
- **Supabase** - Backend database and API
- **Sentry** - Error tracking and monitoring
- **UserNotifications** - Local notifications
- **ServiceManagement** - Launch at login (macOS 13+)
- **CoreServices** - Legacy launch at login (pre-macOS 13)

---

## 📝 Notes

- The app requires non-sandboxed execution for system-level port scanning
- Network operations are performed on background queues to avoid blocking UI
- Version checking is debounced to reduce API calls
- User preferences are persisted via `@AppStorage` and `UserDefaults`
- The app uses modern Swift concurrency (async/await) throughout

---

## 🚀 Best Practices Followed

✅ **Separation of Concerns** - Clear boundaries between UI, business logic, and data  
✅ **Reactive Programming** - ObservableObject and @Published for state management  
✅ **Async/Await** - Modern concurrency patterns  
✅ **Error Handling** - Comprehensive error handling with logging  
✅ **User Experience** - Loading states, empty states, error states  
✅ **Performance** - Background queues, debouncing, lazy loading  
✅ **Accessibility** - Help text, hover states, keyboard navigation  
✅ **Privacy** - Transparent data tracking disclosure  

---

## 🔗 Call Stack & File Dependencies

This section maps the call relationships between files, showing how components interact throughout the application lifecycle.

### Application Startup Flow

```
port_smith_selfApp.swift
  └─> AppDelegate.swift
        ├─> InstallTracker.shared.trackInstallWithDelay()
        │     └─> Supabase.swift (via supabase client)
        ├─> PortScanner() [creates instance]
        │     ├─> PortInfo.swift [uses model]
        │     └─> ProcessIconProvider.swift [uses for icons]
        └─> ContentView(scanner:)
              ├─> VersionManager.shared.checkVersionStatus()
              │     └─> Supabase.swift (via supabase client)
              ├─> LaunchAtLoginManager.shared.isEnabled
              └─> [Various View Components]
```

### Main Call Chains

#### 1. **App Initialization Chain**
```
port_smith_selfApp.swift
  └─> AppDelegate.applicationDidFinishLaunching()
        ├─> InstallTracker.shared.trackInstallWithDelay()
        │     └─> InstallTracker._trackInstall()
        │           ├─> LaunchAtLoginManager.shared.isEnabled
        │           └─> supabase.from("app_installs").upsert()
        │                 └─> Supabase.swift
        ├─> PortScanner.init()
        │     └─> PortScanner.startAutoScan()
        │           └─> PortScanner.runScan()
        │                 └─> PortScanner.parseLsofOutput()
        │                       └─> PortInfo [creates instances]
        └─> ContentView(scanner:)
              └─> ContentView.onAppear
                    ├─> LaunchAtLoginManager.shared.isEnabled
                    ├─> VersionManager.shared.checkVersionStatus()
                    └─> PortScanner.applySettings()
```

#### 2. **Port Scanning Chain**
```
PortScanner.startAutoScan()
  └─> PortScanner.runScan() [periodic]
        ├─> Process.run() [executes lsof command]
        └─> PortScanner.parseLsofOutput()
              └─> PortInfo [creates instances]
                    └─> PortScanner.detectNewPorts()
                          └─> PortScanner.sendPortNotification()
                                └─> UNUserNotificationCenter
                                      └─> AppDelegate.userNotificationCenter(didReceive:)
```

#### 3. **User Interaction Chain**
```
AppDelegate.togglePopover()
  └─> InstallTracker.shared.updateLastSeen()
        └─> InstallTracker._updateLastSeen()
              └─> supabase.from("app_installs").update()
                    └─> Supabase.swift

ContentView
  └─> PortsListView
        └─> PortRowView
              ├─> PortScanner.killProcess()
              │     ├─> InstallTracker.shared.incrementPortsKilled()
              │     └─> InstallTracker.shared.updateLastSeen()
              └─> PortScanner.openProcessFolder()
```

#### 4. **Settings & Preferences Chain**
```
ContentView
  └─> SettingsView
        ├─> LaunchAtLoginManager.shared.setLaunchAtLogin()
        │     └─> InstallTracker.shared.updateLastSeen()
        └─> PortScanner.setNotificationsEnabled()
              └─> InstallTracker.shared.updateLastSeen()
```

#### 5. **Version Check Chain**
```
ContentView.loadNotifications()
  └─> VersionManager.shared.checkVersionStatus()
        └─> supabase.from("port_smith_app_versions").select()
              └─> Supabase.swift
                    └─> AppVersion [decodes model]
```

### View Component Hierarchy

```
ContentView
  ├─> GridBackgroundView
  ├─> VisualEffectView
  ├─> HeaderView
  │     └─> [Navigation logic]
  ├─> UpdateBannerView [conditional]
  ├─> PortsListView [default view]
  │     ├─> LoaderView [when scanning]
  │     └─> PortRowView [for each port]
  │           ├─> PortIconView
  │           ├─> PortInfoView
  │           └─> PortActionsView
  ├─> SettingsView [when settings shown]
  │     └─> [Settings components]
  ├─> DeprecatedOverlayView [when deprecated]
  ├─> InitialLoaderView [on first load]
  ├─> WelcomeView [on first launch]
  ├─> TrackingInfoView [when info shown]
  ├─> KillConfirmationOverlay [on kill action]
  └─> CopyStatusOverlay [on copy action]
```

### Service Dependencies

#### **InstallTracker Dependencies**
```
InstallTracker
  ├─> Supabase.swift (via supabase client)
  ├─> LaunchAtLoginManager.shared [reads status]
  └─> UserDefaults [local storage]
```

#### **PortScanner Dependencies**
```
PortScanner
  ├─> PortInfo.swift [data model]
  ├─> ProcessIconProvider.swift [icon mapping]
  ├─> InstallTracker.shared [tracks metrics]
  └─> UNUserNotificationCenter [notifications]
```

#### **VersionManager Dependencies**
```
VersionManager
  └─> Supabase.swift (via supabase client)
        └─> AppVersion [data model from Supabase.swift]
```

#### **LaunchAtLoginManager Dependencies**
```
LaunchAtLoginManager
  └─> InstallTracker.shared [updates preferences]
```

### Notification Flow

```
PortScanner.sendPortNotification()
  └─> UNUserNotificationCenter.add()
        └─> [System shows notification]
              └─> User taps notification action
                    └─> AppDelegate.userNotificationCenter(didReceive:)
                          ├─> PortScanner.highlightPort()
                          └─> InstallTracker.shared.updateLastSeen()
```

### Data Flow Summary

**Upward Flow (User → System):**
- User interactions → Views → PortScanner/Managers → Supabase/System APIs

**Downward Flow (System → UI):**
- PortScanner scans → PortInfo models → Views observe → UI updates
- VersionManager checks → ContentView updates → Overlays shown
- InstallTracker syncs → Background operation → No UI impact

### Key Singleton Access Points

```
InstallTracker.shared
  ├─> AppDelegate (app launch tracking)
  ├─> PortScanner (ports killed tracking)
  ├─> LaunchAtLoginManager (preference updates)
  └─> ContentView (indirect via PortScanner)

VersionManager.shared
  └─> ContentView (version checking)

LaunchAtLoginManager.shared
  ├─> ContentView (status check, toggle)
  └─> InstallTracker (reads status for tracking)
```

### Circular Dependencies

⚠️ **Note:** There is a circular dependency pattern:
- `LaunchAtLoginManager` → `InstallTracker` (updates preferences)
- `InstallTracker` → `LaunchAtLoginManager` (reads launch at login status)

This is managed safely through:
- Singleton pattern (shared instances)
- Optional/nil parameter passing
- Background queue operations (non-blocking)

---

*Last Updated: Based on current codebase structure*

