Purpose: give future AI agents an accurate mental model of macfuseGui so changes remain safe, predictable, and aligned with current UX and reliability guarantees.
macfuseGui is a macOS menu-bar accessory app (LSUIElement=true) that manages SSHFS mounts through macFUSE.
Core user-facing capabilities:
- Multiple remotes with independent connect/disconnect.
- Three auth modes (SSH private key, System SSH, password) and optional ProxyJump jump hosts.
- Passwords in Keychain; config in JSON.
- Per-remote cache mode (freshness vs speed) and favorite remotes pinned to the top of the menu.
- Per-remote startup intent (
Auto-connect on app launch). - Recovery after sleep/wake, network restore, and external unmount events.
- Finder-style remote folder browser (directories-only) with sticky data and auto-recovery.
- Diagnostics snapshot and copy-to-clipboard for support/debugging.
Primary targets:
- macOS 13+
- Apple Silicon first (
arm64), Intel viaARCH_OVERRIDE=x86_64
Entry points:
macfuseGui/App/macfuseGuiApp.swiftmacfuseGui/App/AppDelegate.swiftmacfuseGui/App/AppEnvironment.swift
Dependency wiring (AppEnvironment):
- Diagnostics, redaction, process runner, dependency checker
- Launch-at-login service
- Store + keychain + validation
- Mount stack (
MountCommandBuilder,UnmountService,MountManager) - Browser stack (
LibSSH2SFTPTransport->RemoteBrowserSessionManager->RemoteDirectoryBrowserService) RemotesViewModelSettingsWindowController
Single orchestrator:
macfuseGui/ViewModels/RemotesViewModel.swift- All remote lifecycle state flows through this VM.
Startup (AppDelegate.applicationDidFinishLaunching):
- App runs in accessory mode (no Dock icon).
- Main menu is installed: app menu (Cmd+Q) plus a standard
Editmenu (Undo/Redo/Cut/Copy/Paste/Delete/Select All). Accessory apps get no default menu, so without theEditmenu Cmd+C/V/X/A/Z do not work in text fields. AppEnvironmentis created.- Menu bar controller is created.
- Background startup sequence runs:
refreshAllStatuses()runStartupAutoConnect()
Duplicate-instance protection (startup hardening):
- App acquires a singleton lock file
com.visualweb.macfusegui.instance.lockin the per-user temp directory (NSTemporaryDirectory(), not/tmp) usingflock. - App also checks already running apps by bundle ID, executable name, and localized app name.
- If another real instance is already alive, current process activates the existing instance and terminates.
- Xcode
DerivedDatatest-host processes are excluded from duplicate-instance matching.
XCTest host guard:
- Startup returns early when running as XCTest host (
XCTestConfigurationFilePath,XCTestBundlePath,XCTestSessionIdentifier, runtime XCTest class check, and process-name check). - This prevents test-host launches from creating extra menu bar status items or starting recovery loops.
Reopen behavior:
- Opening the same app bundle again while it runs (Finder, Spotlight, Launchpad,
open) makes LaunchServices send a reopen event to the running instance. No second process starts. - Opening a different copy of the app (another path, same bundle ID) starts a second process instead. The duplicate-instance guard activates the running instance and exits, and Settings does not open.
applicationShouldHandleReopenshows the Settings window and returnsfalse, so AppKit/SwiftUI add no default reopen handling. It does nothing during termination or beforeAppEnvironmentexists.- Why: the status item is the only other entry point, and macOS hides it without notifying the app when the menu bar is full. On notched MacBooks the items next to the notch go first.
- A fresh launch, including launch at login, never opens Settings.
- The LaunchAgent fallback uses a background URL open targeted at the app bundle. LaunchServices delivers a URL event instead of a reopen event, so a running instance keeps its current windows.
Quit hardening (forceQuit):
- Posts
.forceQuitRequestedso SwiftUI sheets/panels close themselves. - Tears down modal loops and attached sheets explicitly.
- Calls
RemotesViewModel.prepareForTermination(). - Calls
NSApp.terminate. - Hard fallback
_exit(0)after timeout to avoid hung quit states.
This is intentionally aggressive because stale app/process state previously caused relaunch failures.
RemoteConfig (macfuseGui/Models/RemoteConfig.swift):
id,displayName,host,port,usernameauthMode(RemoteAuth:.privateKey/.systemSSH/.password),privateKeyPathproxyJumpEnabled,proxyJump(OpenSSH ProxyJump spec; Finder mounts + Test Connection only)remoteDirectory,localMountPointisFavorite(pins the remote to the top of lists; see §9)autoConnectOnLaunchdisableLocalCaches(defaulttrue; see §6 cache modes)favoriteRemoteDirectories,recentRemoteDirectories
RemoteAuth (macfuseGui/Models/RemoteAuth.swift):
- Case order is the picker display order:
privateKey,systemSSH,password. .privateKey: requires an absolute key path; appendsIdentityFile=.....systemSSH: no explicit key; OpenSSH resolves auth from agent,~/.ssh/config, Tailscale SSH, etc..password: requires a stored or draft password; auth is pinned (see §6).
RemoteDraft:
- Editor-only mutable model.
- Includes plaintext draft password (never persisted to JSON).
RemoteStatus:
state:disconnected,connecting,connected,disconnecting,errormountedPath,lastError,updatedAt
Browser models:
BrowserConnectionHealth: includesstate,retryCount,lastError,lastSuccessAt,lastLatencyMsRemoteBrowserSnapshot: includesisStale,isConfirmedEmpty,fromCache,requestID,latencyMs
Backward compatibility:
RemoteConfigdecodes missing newer fields with defaults so legacyremotes.jsonfiles keep loading.- Notable defaults:
authMode→.privateKey,proxyJumpEnabled→false,isFavorite→false,disableLocalCaches→true,remoteDirectory→/.
Config store:
macfuseGui/Services/RemoteStore.swift~/Library/Application Support/macfuseGui/remotes.jsonRemoteStore+JSONRemoteStoreare@MainActorto enforce single-threaded persistence access.
Secrets:
macfuseGui/Services/KeychainService.swift- Keychain service:
com.visualweb.macfusegui.password - Account key: remote UUID string
Password read contract:
KeychainService.readPasswordtrims leading/trailing whitespace before returning.- Returns
nilif the stored value is whitespace-only after trimming. - Policy: SSH passwords with intentional surrounding whitespace are not a real-world case; trimming prevents silent auth failures from clipboard-pasted trailing newlines.
Security invariants:
- Never write passwords to JSON.
- Never log passwords/secrets.
- External commands always execute as argument arrays (
Process), no shell interpolation.
Redaction:
RedactionServicemasks askpass secrets in logged command strings.
Main files:
macfuseGui/Services/MountManager.swiftmacfuseGui/Services/UnmountService.swiftmacfuseGui/Services/MountCommandBuilder.swiftmacfuseGui/Services/MountStateParser.swift
Connect flow highlights:
- Dependency gate (
sshfs, macFUSE at/Library/Filesystems/macfuse.fs,/usr/bin/ssh,/usr/bin/sftp). - sshfs backend resolution (
DependencyChecker):- User override path from Settings (
mount.backend.sshfs.override_path) - Previously pinned backend (
mount.backend.sshfs.pinned_path/pinned_source) /opt/homebrew/bin/sshfs,/usr/local/bin/sshfs,/opt/local/bin/sshfs(MacPorts),/usr/bin/sshfs- Absolute
$PATHsegments
- The first executable hit is pinned in
UserDefaultsfor later launches.
- User override path from Settings (
SSHFSCapabilities.detectrunssshfs -honce per binary path (cached inMountManager) to pick supported cache options.- Pre-connect cleanup if mountpoint already mounted.
- Auto-create missing local mount folder.
- Retry once for transient failures (
resource busy, reset/timeout/network-type failures). - A silent foreground sshfs timeout can trigger one empty-local-directory reset and a short (up to 6s) retry. The failed child must have exited first.
MountPointRecoveryuses bounded probes to require an unmounted, user-owned directory on APFS/HFS, with no symlink ancestors, and uses non-recursivermdir/mkdir. Automatic reset is limited to subfolders below the user's home (excluding its immediate children) or direct children of/Volumes. No backups, moves, or recursive deletion. Local contents are left untouched and produce a localized actionable error that stops auto-reconnect. A successful connection re-arms reset for a later outage. - Minimum transition visibility (~0.8s) to keep UI from appearing frozen or skipping states.
- sshfs runs in the foreground (
-f) as a detached child fromProcessRunner.launchDetached:posix_spawnwithPOSIX_SPAWN_SETSID(own session and process group), stdin/dev/null, stdout/stderr to a private temp log.- Why: macFUSE 5.4+ libfuse no longer forks after the mount has started, and sshfs starts the mount before it daemonizes, so a non-
-fsshfs never returns control (issue #8). - Success means the mount appears while sshfs is still running. The handle is then released, the process is reaped when it exits (on unmount), and the mount outlives the app like a self-daemonized sshfs did.
- A non-zero exit before the mount appears fails the connect with the sshfs/ssh output. Foreground mode keeps ssh's stderr, so errors like
Permission denied (publickey)reach the user and are classified as permanent.MountManager.removingBenignSSHFSOutputstrips macFUSE fork warnings and ssh "Permanently added" notices. - A clean exit before the mount appears (sshfs builds that still detach) falls back to the post-exit
waitForMountAppearanceverification. - On timeout (sshfs connect command timeout, 20s) or cancellation the whole process group is terminated.
- When the sshfs leader exits, leftover members of its process group are killed before it is reaped. This clears an orphaned
mount_macfusehelper that would otherwise block the mount point for about a minute.
- Why: macFUSE 5.4+ libfuse no longer forks after the mount has started, and sshfs starts the mount before it daemonizes, so a non-
Disconnect flow highlights:
- Unmount via
UnmountServicewith multiple command rounds (diskutil,umount, force variants). - Minimum transition visibility (~0.7s).
- If outer disconnect times out, VM can trigger
forceStopProcessesfor scoped sshfs cleanup.
Busy unmount UX:
- On busy/resource-busy,
lsofblockers are parsed and surfaced as user-facing process hints. - No kill action for arbitrary user processes.
Mount inspection anti-flap logic (important):
refreshStatusdoes not immediately downgrade a previously-connected mount on one probe miss.- Uses
dffallback + responsive path check (stat) + brief (250ms) retry before declaring disconnect. - If the mount is missing from the mount table but the path is still responsive, connected state is preserved for up to
maxConnectedPreserveMisses = 4consecutive checks, then status becomeserror("Mount could not be verified") so reconnect performs cleanup. - If the refresh task is cancelled (routine supersession during recovery bursts),
refreshStatusreturns the cached status instead of synthesizing an error fromCancellationError. - This avoids false reconnect storms from transient mount table probe failures.
Command builder nuances:
- Base options:
reconnect,ServerAliveInterval=15,ServerAliveCountMax=3,defer_permissions,auto_cache,StrictHostKeyChecking=accept-new,ConnectTimeout=10,volname=.... - Do not add
noappledouble/noapplexattr. They were removed in v0.1.36 because they broke Finder andcpcopies that need the AppleDouble/xattr fallback. - Cache modes (per remote
disableLocalCaches, editor labelPrioritize freshness over speed):true(default):nolocalcaches.false(fast mode):attr_timeout/entry_timeout/cache_timeout=120,cache_max_size=50000, plusdir_cache=yes+dcache_*(newer sshfs) orcache_stat/dir/link_timeout(older sshfs), depending on detectedSSHFSCapabilities.
- The sshfs source path always ends in
/(user@host:/path/) so a remote directory that is a symlink mounts its target directory rather than the link itself. - ProxyJump (when
proxyJumpEnabledand non-empty):.privateKey/.systemSSH: added as-o ProxyJump=.....password: appended inside the pinnedssh_command=...string.ValidationServicerejects empty values, control characters, and whitespace (multi-hop uses commas).
- Windows path normalization for sshfs source path.
- Stable
volnamederivation from display name + remote path leaf. - Password mode now disables public-key fallback and prefers password-style auth
(
keyboard-interactive,password) with a single prompt so a wrong password cannot silently succeed through agent/config-driven auth. - On the current Homebrew macOS sshfs build, these password-mode auth controls
are injected through
ssh_command=/usr/bin/ssh -o ..., not as raw-o PubkeyAuthentication=...mount options, because that binary rejects the latter at the FUSE parser layer. - Keep
keyboard-interactiveenabled unless you are intentionally dropping support for servers that expose password prompts through that path. - IPv6 host addresses are bracketed (
[::1]) viasshHostArgument()in both the sshfs source arg (MountCommandBuilder) and the process-search connection needle (MountManager.forceStopProcesses).ValidationServiceenforces pre-bracketed input at the save boundary;sshHostArgument()is defence-in-depth for any path that bypasses validation.
df path decoding:
MountStateParser.decodeEscapedMountFieldis the canonical decoder for macOSmountanddfescape sequences.- Handles the full octal range
\001–\377. Do not replace with ad-hoc single-character substitution (\040→ space only). - Used by both
MountManager(df-path comparison incurrentMountRecordViaDF) andUnmountService(df-based mount confirmation).
RemotesViewModel replaced global serialization with per-remote supervision.
Key structures:
RemoteOperationIntent:connect,disconnect,refresh,testConnectionRemoteOperationTrigger:manual,recovery,startup,terminationRemoteOperationConflictPolicy:latestIntentWinsskipIfBusy
remoteOperations: [UUID: RemoteOperationState]OperationLimiter(maxConcurrent: 4)for cross-remote capacquire()isasync throwsand cancellation-aware: a task cancelled while queued is removed from the FIFO and resumed withCancellationError, so superseded operations do not delay the ones behind them.runOperationbails out on that error without registering arelease()for a slot it never held.
Behavior contract:
- At most one active operation per remote.
- Same-remote conflict:
- Manual connect/disconnect uses
latestIntentWins(new intent cancels old). - Recovery/status probes use
skipIfBusy(don’t stomp manual work).
- Manual connect/disconnect uses
- Cross-remote operations run in parallel (up to 4).
- Operation watchdogs are keyed by operation ID; stale completions cannot overwrite newer intents.
Timeout/watchdog defaults:
- Connect watchdog:
45s - Disconnect watchdog:
10s - Refresh watchdog:
18s - Connect inner timeout path:
35s - Disconnect inner timeout path:
8s - sshfs connect command timeout:
20s - Unmount total / per-command cap:
10s/3s
Most of these live in RuntimeConfiguration (macfuseGui/App/AppEnvironment.swift), which also holds the 15s periodic recovery interval, the 60s healthy-probe interval, and the browser circuit-breaker threshold and window. The inner connect/disconnect timeouts are constants in RemotesViewModel.
Diagnostics logs every operation start/end/cancel/timeout with:
remoteID,operationID,intent,trigger, elapsed ms, cancellation/supersession details.limiterWaitMs(time spent waiting forOperationLimiter.acquire()).mount calllines withqueuedAtMs,nowMs,preAwaitDelayMs, andopAgeMsbefore enteringMountManager.
Mount actor queueing instrumentation:
MountManagerlogsactor enter op=... remoteID=... operationID=... queueDelayMs=....- Probe logs include
remoteIDandoperationIDfor:mount-inspectdf-inspectmount-responsive-checksshfs-connect
- This allows production log proof of true cross-remote overlap versus actor funneling.
desiredConnections is the core intent set:
- Means “user wants this remote kept connected.”
- Recovery acts only on remotes in this set.
Where it is updated:
- Added on successful connect and startup auto-connect intent.
- Removed on manual disconnect, certain permanent failures, remote deletion, termination.
Recovery triggers:
- Timer pass every 15s (backup safety pass).
- Sleep/wake notifications.
- Network reachability changes (
NWPathMonitor). - External volume unmount (
NSWorkspace.didUnmountNotification).
Recovery burst schedules:
- Wake:
[0s, 1s, 3s, 8s] - Network restored:
[0s, 2s, 6s]
Event handling details:
- Wake:
handleSystemDidWakestores a singlewakePreflightTask, cancelling any earlier one first. It runs a parallel fast force-unmount of desired remotes (performWakePreflightCleanup), then schedules the wake burst.- While
wakePreflightInProgressis set, external-unmount notifications are ignored.
- While
- Network lost: debounce
0.5s, cancel scheduled reconnects and any recovery burst, then run fast cleanup innetworkLossCleanupTask. - Network restored: debounce
1.5s, cancel pending network-loss cleanup, run deferred startup auto-connect first, then schedule the network-restored burst. - External unmount: ignored for remotes not in
desiredConnections, during wake preflight, or while a connect/disconnect is active. Otherwise the remote is marked disconnected andscheduleAutoReconnectruns. - Sleep, termination, and deinit cancel
wakePreflightTask,networkLossCleanupTask, and bursts.
Periodic skip optimization:
- If all desired remotes are healthy, no in-flight reconnects, and last periodic full probe was recent, periodic deep probe is skipped.
healthyPeriodicProbeInterval = 60s
Reconnect scheduling:
- Backoff matrix from
reconnectDelaySeconds(...)with trigger-aware behavior. - Current first reconnect delay commonly starts at
0sfor fast recovery. - Permanent failure classifier halts auto-reconnect for non-recoverable cases (auth errors, shared mountpoint, macFUSE-on-macFUSE errors, missing deps).
Why polling still exists:
- macOS does not provide a single reliable push event for all “SSHFS became stale” cases.
- Design is event-first (wake/network/unmount) with periodic polling as a safety net.
statusBadgeRawValue(for:) can return synthetic reconnecting:
- computed from reconnect tasks/in-flight markers + desired intent + recovery indicator context
- not solely from
RemoteStatus.state
Menu bar icon behavior (MenuBarController):
- Icon animates when:
- active connect/disconnect operations exist, or
- recovery indicator active, or
- wake pulse active, or
- reconnecting remotes > 0
- Connected count text color:
- orange during sleep/recovery/reconnecting
- green when stable
Tooltip includes:
- Active operations with elapsed durations
- Recovery reason/pending/queued
- Aggregate C/A/E/D counts
Favorite remotes:
- Each remote row in the menu popover has a star toggle (
RemotesViewModel.toggleFavorite) that persistsRemoteConfig.isFavorite. RemotesViewModel.sortedRemotesorders favorites first, then by display name (case-insensitive), then by UUID for stability.- Not to be confused with
favoriteRemoteDirectories, which are per-remote browser path favorites (§15).
Settings window:
- Opens only on explicit user action: the menu's Settings action, or reopening the running app (§3).
- Shows launch-at-login state, including approval/fallback details.
- Optional custom sshfs path override field (see §6 backend resolution).
- Includes entry point button that opens a dedicated
Editor Pluginswindow. BaseSettingsWindowControllerusesNSHostingController.sizingOptions = [.minSize, .maxSize].- Do not add
.preferredContentSize. Binding SwiftUI's preferred size back into AppKit constraints caused the settings window sizing bug on macOS betas. - Size windows from SwiftUI
.frame(min…/ideal…/max…), not hardcoded pixel sizes.
- Do not add
Remote detail panel:
- Edit, Duplicate, Delete, Refresh, Connect, Disconnect.
- Connect/Disconnect buttons are state-aware and disabled appropriately.
Editor (RemoteEditorView):
- Add/Edit title, password eye toggle, auth mode picker (SSH Private Key / System SSH / Password).
Auto-connect on app launchtoggle.Prioritize freshness over speedtoggle (disableLocalCaches; on by default, turn off for faster dev/code mounts).Use jump host (ProxyJump)toggle + value field.Browse Remote…is disabled forSystem SSHand when ProxyJump is active, with an inline callout explaining why (see §12 auth support).Test Connectionbutton with in-place progress/result.- Both Cancel button and top-right close icon are present.
- Remote browser opens in sheet; session closed on sheet dismiss.
- Responds to
.forceQuitRequestedto close cleanly during hard quit.
Validation + uniqueness:
- Display name unique (case-insensitive).
- Local mountpoint unique (normalized, case-insensitive).
- Remote path supports UNIX and Windows drive forms.
- Validation is lexical only. Do not add
fileExists/isReadableFileprobes, because they can block the main actor on stale FUSE paths.MountManagerdoes bounded filesystem checks during connect/test.
Localization:
- User-facing strings go through
L10n.tr/L10n.format(macfuseGui/App/L10n.swift) backed bymacfuseGui/Resources/Localizable.xcstrings. - Development region
en. Shipped locales:de,es,fr,ja,ko,pt-BR,zh-Hans. - Diagnostics log messages and raw external command output stay unlocalized so support data is stable.
- Translation rules:
docs/LOCALIZATION_GLOSSARY.md.LocalizationTestschecks declared locales and core translated keys.
Menu actions support opening connected remotes in a configurable editor plugin set.
Core behavior:
- Primary action uses preferred plugin with fallback across active plugins.
- Secondary
Open In…picker allows explicit plugin selection. - If all attempts fail, app opens the folder in Finder and emits alert + diagnostics warning.
Built-in plugins:
vscode(default active)vscodiumcursorzed- Built-in manifest source-of-truth in repo:
macfuseGui/Resources/EditorPlugins/vscode/plugin.jsonmacfuseGui/Resources/EditorPlugins/vscodium/plugin.jsonmacfuseGui/Resources/EditorPlugins/cursor/plugin.jsonmacfuseGui/Resources/EditorPlugins/zed/plugin.json
Built-in vscode attempts are VS Code-only:
open -b com.microsoft.VSCodeopen -b com.microsoft.VSCodeInsidersopen -a Visual Studio Codevariantscode --reuse-window
Cross-editor fallback is handled by plugin ordering across active plugins, not mixed attempts inside one plugin manifest.
Plugin registry:
- Service:
macfuseGui/Services/EditorPluginRegistry.swift - Model:
macfuseGui/Models/EditorPlugin.swift - Persisted toggle overrides:
editor.plugins.activation_overrides - Persisted preferred plugin:
editor.plugins.preferred_id - External manifests path:
~/Library/Application Support/macfuseGui/editor-plugins/*.json - On first load, registry auto-creates scaffold files:
README.mdexamples/custom-editor.json.templatebuiltin-reference/*.json(reference docs for shipped built-ins; non-recursive loader means these are not loaded as external manifests)
Manifest safety contract:
- Allowed executables:
/usr/bin/open,/usr/bin/env - Must include
{folderPath}placeholder in arguments /usr/bin/openforms require-aor-b/usr/bin/envforms require a bare command token first arg
Settings UX:
- Real-time check/uncheck plugin toggles (no restart)
- Preferred editor picker from active plugins
- Manual
Reload Pluginsaction to rescan manifest files - Buttons to open plugin root, examples, and built-in reference folders in Finder
New Plugin JSONaction creates a template manifest directly in the external plugin folder- Per-plugin inline JSON editor loads/saves manifests directly inside the plugin settings window
- Per-plugin external remove action (
trash) deletes external manifest files (built-ins are non-removable)
Main API (RemoteDirectoryBrowserService):
openSession(remote:password:)closeSession(sessionID)listDirectories(sessionID:path:requestID)goUp(sessionID:currentPath:requestID)retryCurrentPath(sessionID:requestID)health(sessionID:)
Implementation chain:
RemoteDirectoryBrowserServiceRemoteBrowserSessionManager(actor)LibSSH2SessionActor(actor per browser sheet)LibSSH2SFTPTransport(single bridge queue)LibSSH2Bridge.c/.h(native libssh2)
Transport details:
- Persistent per-remote libssh2 sessions cached in transport.
- List timeout:
8s - Ping timeout:
2s - On list failure, transport invalidates session and retries once by reopening.
- Swift transport calls remain serialized on one bridge queue, but each C call is deadline-bounded and returns on timeout.
Auth support:
- Browser supports
.passwordand.privateKeyonly. .systemSSHis rejected inLibSSH2SFTPTransportbecause libssh2 cannot use the OpenSSH agent/config resolution.- ProxyJump is not tunnelled by libssh2. The editor disables
Browse Remote…when ProxyJump is active.
Host-key verification (macfusegui_verify_host_key in LibSSH2Bridge.c):
- Runs after the SSH handshake and before any authentication.
- Checks the server key against
~/.ssh/known_hosts([host]:portform for non-22 ports). - Match: proceed.
- Mismatch: hard failure with the offered key's SHA256 fingerprint and a possible-MITM warning.
- Not found: trust on first use. The key is added and written back to
~/.ssh/known_hosts, creating~/.sshif needed. This matches theStrictHostKeyChecking=accept-newpolicy used by sshfs mounts. - A missing
known_hostsfile is treated as empty (trust on first use). Any other read failure, a write failure, or an unsupported key type is a hard error. It never silently skips verification.
C bridge reliability details:
- Non-blocking connect with select-based timeout.
- Socket-level
SO_RCVTIMEO+SO_SNDTIMEOare configured during session open; failure to configure is a hard open-session error. - Socket is kept non-blocking for libssh2 session lifetime.
- Password auth with keyboard-interactive fallback.
- Private-key auth path.
- Deadline-driven EAGAIN loops are used for handshake/auth/sftp-init/realpath/opendir/readdir/stat.
- Timeout errors are stage-specific and user-visible (for example:
SSH handshake,password authentication,SFTP readdir) and include timeout seconds. - Session close path uses
shutdown(sock, SHUT_RDWR)before libssh2 teardown to break pending waits quickly. - Directory classification checks permission flags and Windows
<DIR>/[DIR]markers.
LibSSH2SessionActor guarantees:
- No silent failure states.
- Cached data preferred over blank UI during transient failures.
- Recovery loop is autonomous when needed.
Important internals:
cache[path]sticky entries.requestRetrySchedule = [0.3s, 0.8s]for foreground list.recoveryRetrySchedule = [0.2s, 0.8s, 2s, 5s]for background recovery.- Keepalive every
12s, idle-only (activeListRequests == 0and no recovery in flight). - Keepalive failure is non-destructive; schedules recovery.
- Circuit breaker threshold
8, window30s.
Empty-list policy (critical):
- If list returns empty and cache exists: keep cached entries, mark stale/reconnecting.
- If first-load empty and no cache: do immediate confirm-list before declaring healthy-empty.
isConfirmedEmptydifferentiates true empty folder from uncertain empty response.
Health model usage:
healthy,degraded,reconnecting,failed,closedstates drive VM/UI.lastSuccessAt+lastLatencyMsshown in footer and diagnostics.
ViewModel (RemoteBrowserViewModel):
- State machine:
idle,loadingFirstPage,ready,degradedWithCache,recovering,fatal - Monotonic
requestIDprevents stale response overwrite. - Degraded auto-retry loop every
2.5suntil healthy/closed. - Health poll loop every
3s. - Unconfirmed empty snapshot must not wipe previously visible entries.
View (RemoteBrowserView):
- Finder-like
NavigationSplitView - Sidebar: Favorites, Recents, Roots
- Detail: breadcrumbs, search, sort, table columns (Name, Date, Kind, Size)
- Degraded reconnect banner with
Retry now - Confirmed-empty panel and degraded panel when no visible data
- Footer shows item count, health, last success, latency
- Keyboard actions: refresh (
Cmd+R), open (Return), up (Delete)
Column width persistence:
- Stored in
UserDefaultskeys:browser.column.namebrowser.column.datebrowser.column.kindbrowser.column.size
Per-remote path memory:
- Favorites limit:
20 - Recents limit:
15 - Case-insensitive dedupe
- Mandatory normalization before persistence
Normalization handles:
- Windows drive artifacts (
/D::,D::\\x, etc.) - slash normalization and canonical root handling
Persistence behavior:
- Saved remote (
id != nil): persisted toRemoteConfigvia store. - Unsaved draft: lives in editor session until save.
Service:
LaunchAtLoginServiceinRemotesViewModel.swift
Primary path:
SMAppService.mainApp.register/unregister
Fallback path:
- LaunchAgent plist at
~/Library/LaunchAgents/com.visualweb.macfusegui.launchagent.plist launchctlbootstrap/enable/bootout flows- Used when SMAppService registration is unavailable or not taking effect
- App startup updates the arguments of older fallback plists on disk. An already-loaded job picks up the new arguments the next time it is loaded.
UI state:
LaunchAtLoginStateincludesenabled,requiresApproval,detail- Toggle displays approval/fallback guidance text.
Diagnostics snapshot includes:
- Environment + dependency readiness
- Per-remote status summary
- Recent logs (redacted)
Operationssection (active operation table)Browser Sessionssection (health, retries, path, latency, last success)
Expected categories:
store,mount,mount-test,unmount,recovery,operations,remote-browser,startup,editor,vscode,diagnostics,app
No secrets in diagnostics:
- Askpass and passwords are redacted or omitted.
Primary scripts:
scripts/build.shscripts/run.shscripts/clean.shscripts/build_libssh2.shscripts/release.sh
Build arch modes:
ARCH_OVERRIDE=arm64|x86_64|both|universalscripts/build.shdefaults toarm64scripts/release.shdefaults toboth(publishes separate arm64 and x86_64 DMGs)
libssh2 prep:
- Output roots:
build/third_party/libssh2-arm64build/third_party/libssh2-x86_64build/third_party/libssh2-universal
- OpenSSL output roots:
build/third_party/openssl-arm64build/third_party/openssl-x86_64build/third_party/openssl-universal
scripts/build_libssh2.shbuilds OpenSSL and libssh2 from source for the active arch/deployment target- Single-arch
x86_64third-party builds run under Rosetta on Apple Silicon (arch -x86_64) - Source tarballs are cached under
third_party/src(openssl-<version>.tar.gz,libssh2-<version>.tar.gz) and auto-downloaded if missing - Tarballs are pinned by SHA256 (
OPENSSL_SHA256/LIBSSH2_SHA256inscripts/build_libssh2.sh, overridable via env).- Both cached and freshly downloaded tarballs are verified.
- On mismatch the tarball is deleted and the build aborts.
- When bumping
OPENSSL_VERSIONorLIBSSH2_VERSION, update the matching hash in the same change.
- Build artifacts are cached by a fingerprint (
version,arch,min target) so repeated builds are fast scripts/build.shalso updates compatibility symlinks:build/third_party/openssl-> selectedopenssl-<arch>build/third_party/libssh2-> selectedlibssh2-<arch>
App output:
- Single-arch modes (
arm64,x86_64,universal):build/macfuseGui.app - Dual-arch mode (
both):build/macfuseGui-arm64.appbuild/macfuseGui-x86_64.app
- DerivedData roots are arch-specific:
build/DerivedData-arm64build/DerivedData-x86_64build/DerivedData-universal
Release automation:
scripts/release.shis the single source of truth for versioning, DMG creation, Homebrew cask update, release notes, tags, and GitHub Release publishing..github/workflows/release-macos.yml(workflow_dispatch,macos-26runner) runsscripts/release.sh, passing arch, configuration, version, dry-run, and packaging options as env/args.- Windows entry point:
scripts\release.cmd→scripts/release.ps1. It requires a clean work tree and a non-detached branch, checks origin reachability andgh auth status, pushes the current branch, then dispatchesrelease-macos.ymlon that ref.- Supports
-Arch,-ReleaseVersion,-DryRun,-SkipBuild,-NoHomebrewCask, and related options.
- Supports
- Neither the workflow nor
scripts/release.shrunsaudit_mount_calls.pyor the XCTest suite, andxcodebuildis not available on Windows. Run the reliability gate on a Mac before dispatching a release.
Tests:
ARCH_OVERRIDE=arm64 ./scripts/build.shthenxcodebuild ... test CODE_SIGNING_ALLOWED=NO- Reliability gate:
ARCH_OVERRIDE=arm64 ./scripts/build.sh && scripts/audit_mount_calls.py && xcodebuild -project macfuseGui.xcodeproj -scheme macfuseGui -configuration Debug -derivedDataPath build/DerivedData -destination 'platform=macOS,arch=arm64' test CODE_SIGNING_ALLOWED=NO - After tests complete, remove temporary DerivedData roots under
build/(for example:build/DerivedData*) to keep the workspace clean. - Key tests cover:
- Remote store legacy defaults/new fields
- Path normalization and memory limits
- Browser empty confirmation + recovery behavior
- Keepalive-triggered recovery
- Unmount blocker parsing
- Mount arg safety and Windows path normalization
- Auth-mode and ProxyJump arg building, trailing-slash source path, capability-based cache options (
MountArgBuilderTests) - ProxyJump, IPv6, and auth validation rules (
ValidationServiceTests) OperationLimitercancellation and wake-preflight dedup (RemotesViewModelHelpersTests)- Recovery flows (
RemotesViewModelRecoveryTests) - Cancelled refresh preserving cached status and mount-detection edge cases (
ProcessRunnerTests) - LaunchAgent fallback bootstrap/verification failures (
LaunchAtLoginServiceTests) - Localization catalog locales and core keys (
LocalizationTests)
- Force-quit path with modal/sheet teardown +
_exit(0)fallback. - Per-remote operation supervision with cross-remote parallel cap.
- Operation-instance watchdogs and stale-completion suppression.
- Anti-flap mount refresh (responsive-path +
dffallback + retry). - Transitional visibility delays for connect/disconnect UI fidelity.
- Browser request ordering via monotonic request IDs.
- Sticky cache with explicit degraded/reconnecting states (never silent blank).
- Empty-list confirmation before clearing data.
- Idle-only keepalive and non-destructive ping failures.
- Deadline-bounded libssh2 bridge calls (no indefinite C-level browser waits).
- Launch-at-login dual-path support (SMAppService + LaunchAgent fallback).
- ProcessRunner capture shutdown before terminate/SIGKILL to avoid post-timeout stdout/stderr races.
KeychainService.readPasswordtrims whitespace before returning — prevents silent auth failures from clipboard-pasted trailing newlines without changing the stored credential.sshHostArgument()brackets IPv6 host addresses in both the sshfs source arg and the connection-needle process search — prevents ambiguoususer@::1:/pathcolons from breaking sshfs and process matching.if !Task.isCancelledguards in the defer blocks ofscheduleRecoveryBurst,scheduleAutoReconnect,wakePreflightTask, andnetworkLossCleanupTask— prevents a cancelled task's cleanup from clobbering the replacement task's reference on the next main-actor turn.- Cancellation-aware
OperationLimiter.acquire()— cancelled waiters leave the FIFO immediately instead of delaying later operations. - Cancelled
refreshStatusreturns the cached status — superseded recovery refreshes never flash a synthetic error chip. - Password-mode auth pinning inside
ssh_command=/usr/bin/ssh -o ...— a wrong password cannot silently succeed via key/agent fallback. - Trailing
/on the sshfs source path — directory symlinks mount their target, not the link. - Browser host-key verification against
~/.ssh/known_hostsbefore authentication (trust-on-first-use, hard fail on mismatch). - SHA256-pinned OpenSSL/libssh2 source tarballs — builds refuse unexpected inputs.
- Foreground
sshfs -flaunched in its own session with process-group cleanup — works with macFUSE 5.4+ (no fork after mount), keeps mounts alive after the app quits, and never leaves orphaned mount helpers.
- Keep
desiredConnectionssemantics as the source of recovery intent. - Do not reintroduce global serialized mount operation bottlenecks.
- Preserve one-active-operation-per-remote invariant.
- Preserve
latestIntentWinsfor manual conflicts andskipIfBusyfor recovery refresh. - Keep operation limiter cap behavior unless explicitly changing concurrency policy.
- Preserve connect/disconnect watchdog behavior and explicit timeout messaging.
- Preserve uniqueness checks for display name + local mountpoint.
- Preserve anti-flap status refresh behavior in
MountManager.refreshStatus. - Preserve browser requestID stale-write protection.
- Preserve sticky-cache + empty-confirmation browser contracts.
- Keep keepalive idle-only and non-destructive.
- Keep deadline-driven libssh2 timeout stages and bounded list/ping behavior.
- Keep path-memory normalization and limits.
- Keep command execution as argument arrays only.
- Never log secrets.
- Preserve plugin registry safety rules (
/usr/bin/open//usr/bin/env,{folderPath}placeholder requirement). - Preserve preferred-plugin + fallback semantics and Finder fallback on complete editor-open failure.
- Keep
KeychainService.readPasswordtrimming — do not return the raw stored value with surrounding whitespace intact. - Keep
sshHostArgument()wrapping inMountCommandBuilder.buildandMountManager.forceStopProcesses— do not interpolateremote.hostdirectly intouser@host:pathstrings. - Keep
if !Task.isCancelledguards in the defer blocks ofscheduleRecoveryBurst,scheduleAutoReconnect,wakePreflightTask, andnetworkLossCleanupTask— removing them reintroduces the stale-defer clobber of replacement task references. - When taking fixes from an external PR, preserve contributor attribution in commit bodies, release notes, and PR comments. Do not call Xcode-generated
.xcstringsor.pbxprojchanges "churn"; Xcode 15+ can rewrite those files as normal project metadata. - Keep password-mode auth controls inside
ssh_command=...; do not move them to raw-o PubkeyAuthentication=...mount options (the Homebrew sshfs build rejects them). - Do not re-add
noappledouble/noapplexattrto base mount options; they break Finder/cpcopies. - Keep the trailing
/on the sshfs source path. - Keep browser host-key verification before authentication; never skip it on read/write errors.
- Keep SHA256 pinning in
scripts/build_libssh2.sh; update the hash whenever the OpenSSL or libssh2 version changes. - Keep
OperationLimiter.acquire()cancellation-aware and do notrelease()a slot that was never acquired. - Keep
ValidationServicelexical-only; no synchronous filesystem probes on the main actor. - Route new user-facing strings through
L10n; keep diagnostics log messages unlocalized. - Keep
-finMountCommandBuilderand launch sshfs throughProcessRunning.launchDetached. Do not go back to waiting for sshfs to exit, and do not run the mount through FoundationProcess: the child would share the app's process group, where launchd's job cleanup can kill it. - Only signal a detached process group while its leader is unreaped (
SpawnedDetachedProcess.exitStateusesWNOWAIT), so a reused PID is never signalled. - Keep reopen showing the Settings window and returning
false. It is the way back into the app when macOS hides the status item. Never open Settings on a fresh launch.