Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

fix(macos): surface a failed server start in the menu extra

Nícolas Brandãob027f3cb9b67
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c0229db6..6273d9fe 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
provider. (#1026)
### Fixed
+- Fixed the macOS menu-bar app showing only a red status item when the bundled
+ server cannot start (for example a port already in use, such as OpenCode v2's
+ default `127.0.0.1:49374`). The menu extra now surfaces the server's fatal
+ `stderr.log` line, and `docs/macos.md` documents the port collision and how to
+ move one side. (#1044)
- Fixed interrupted launchers blocking an immediate managed-workstream restart
by adding explicit `ai-memory run --force-unlock` recovery. The server
atomically expires and replaces only a lease attributed to the same
diff --git a/companions/ai-memory-macos/Sources/AIMemoryMenu/AppModel.swift b/companions/ai-memory-macos/Sources/AIMemoryMenu/AppModel.swift
index 2fb705fa..f62c3cf7 100644
--- a/companions/ai-memory-macos/Sources/AIMemoryMenu/AppModel.swift
+++ b/companions/ai-memory-macos/Sources/AIMemoryMenu/AppModel.swift
@@ -108,7 +108,11 @@ final class AppModel {
lastHTTPStatus = code
fetchFailed = code != 401 && code != 403
}
- lastError = (error as? HealthError).map(Self.describe) ?? error.localizedDescription
+ lastError = StartFailure.message(
+ health: (error as? HealthError).map(Self.describe) ?? error.localizedDescription,
+ launchd: launchd,
+ logURL: logURL
+ )
}
let derived = IconState.derived(
launchd: launchd,
diff --git a/companions/ai-memory-macos/Sources/AIMemoryMenu/MenuBarView.swift b/companions/ai-memory-macos/Sources/AIMemoryMenu/MenuBarView.swift
index 10886ab7..b3fca585 100644
--- a/companions/ai-memory-macos/Sources/AIMemoryMenu/MenuBarView.swift
+++ b/companions/ai-memory-macos/Sources/AIMemoryMenu/MenuBarView.swift
@@ -12,6 +12,17 @@ struct MenuBarView: View {
.onAppear {
Task { await model.poll() }
}
+ if let error = model.lastError {
+ // Surface the server's own fatal error (e.g. "binding ... Address
+ // already in use") instead of leaving the reason only in
+ // ~/Library/Logs/ai-memory/stderr.log behind a red status item.
+ Text(error)
+ .font(.system(.caption, design: .monospaced))
+ .foregroundStyle(.secondary)
+ .lineLimit(12)
+ .frame(maxWidth: 460, alignment: .leading)
+ .disabled(true)
+ }
ForEach(Array(model.statisticLines.enumerated()), id: \.offset) { _, line in
Text(line)
.font(.system(.body, design: .monospaced))
diff --git a/companions/ai-memory-macos/Sources/AIMemoryMenuCore/ServerLog.swift b/companions/ai-memory-macos/Sources/AIMemoryMenuCore/ServerLog.swift
new file mode 100644
index 00000000..c8ede2b9
--- /dev/null
+++ b/companions/ai-memory-macos/Sources/AIMemoryMenuCore/ServerLog.swift
@@ -0,0 +1,60 @@
+import Foundation
+
+/// Reads the tail of the bundled server's log so the menu extra can show the
+/// reason the LaunchAgent exited — for example a port it cannot bind — instead
+/// of only a red status item.
+///
+/// The server writes its fatal error last, the way `anyhow` renders it:
+///
+/// Error: <context>
+///
+/// Caused by:
+/// <cause>
+public enum ServerLog {
+ /// Returns the trailing `Error:` block from `url`, or `nil` when the file
+ /// is missing/unreadable or holds no `Error:` line.
+ ///
+ /// `maxBytes` bounds the read so an unbounded log cannot be pulled into
+ /// memory just to show one message.
+ public static func recentError(at url: URL, maxBytes: Int = 64 * 1024) -> String? {
+ guard let handle = try? FileHandle(forReadingFrom: url) else { return nil }
+ defer { try? handle.close() }
+ let size = (try? handle.seekToEnd()) ?? 0
+ let offset = size > UInt64(maxBytes) ? size - UInt64(maxBytes) : 0
+ try? handle.seek(toOffset: offset)
+ guard let data = try? handle.readToEnd() else { return nil }
+ // The tail can start mid-scalar; lossy decoding keeps the visible text.
+ return extractError(from: String(decoding: data, as: UTF8.self))
+ }
+
+ /// Last `Error:` line and everything after it, trimmed. Split out so a test
+ /// can exercise the parsing without the filesystem.
+ static func extractError(from log: String) -> String? {
+ let lines = log.components(separatedBy: "\n")
+ guard let start = lines.lastIndex(where: { $0.hasPrefix("Error:") }) else {
+ return nil
+ }
+ let block = lines[start...]
+ .joined(separator: "\n")
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ return block.isEmpty ? nil : block
+ }
+}
+
+/// Picks the message the menu extra shows when the server is unreachable.
+public enum StartFailure {
+ /// Prefers the server's own fatal log line over the transport/decode error
+ /// the health poll produced: `Address already in use` explains the failure,
+ /// `Could not read /admin/status` does not.
+ ///
+ /// Only when the agent is installed but stopped — the exit-loop the bind
+ /// failure produces. While it is `.running` (or never installed) a log line
+ /// left over from an earlier attempt would be misreported over the live
+ /// health error.
+ public static func message(health: String, launchd: LaunchdState, logURL: URL) -> String {
+ guard launchd == .stopped,
+ let logged = ServerLog.recentError(at: logURL)
+ else { return health }
+ return logged
+ }
+}
diff --git a/companions/ai-memory-macos/Tests/AIMemoryMenuTests/ServerLogTests.swift b/companions/ai-memory-macos/Tests/AIMemoryMenuTests/ServerLogTests.swift
new file mode 100644
index 00000000..6c8cfce1
--- /dev/null
+++ b/companions/ai-memory-macos/Tests/AIMemoryMenuTests/ServerLogTests.swift
@@ -0,0 +1,95 @@
+import Foundation
+import Testing
+@testable import AIMemoryMenuCore
+
+struct ServerLogTests {
+ @Test func extractsTheTrailingErrorBlock() {
+ let log = """
+ 2026-10-02T02:20:53Z INFO ai_memory_cli: ai-memory starting version="2.5.2"
+ 2026-10-02T02:20:53Z INFO ai_memory_cli::commands::serve: MCP Streamable HTTP transport mode stateful=false
+ Error: binding 127.0.0.1:49374
+
+ Caused by:
+ Address already in use (os error 48)
+ """
+ let error = ServerLog.extractError(from: log)
+ #expect(error?.hasPrefix("Error: binding 127.0.0.1:49374") == true)
+ #expect(error?.contains("Address already in use") == true)
+ }
+
+ @Test func keepsOnlyTheLastError() {
+ let log = """
+ Error: binding 127.0.0.1:49374
+
+ Error: could not open store
+ """
+ #expect(ServerLog.extractError(from: log) == "Error: could not open store")
+ }
+
+ @Test func returnsNilWhenNoErrorIsLogged() {
+ #expect(ServerLog.extractError(from: "just some INFO lines\n") == nil)
+ }
+
+ @Test func readsOnlyTheTailOfTheFile() throws {
+ let dir = FileManager.default.temporaryDirectory
+ .appending(path: "aimem-log-test-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let logURL = dir.appending(path: "stderr.log")
+ let filler = String(repeating: "x", count: 100_000)
+ try (filler + "\nError: binding 127.0.0.1:49374\n")
+ .write(to: logURL, atomically: true, encoding: .utf8)
+
+ let error = ServerLog.recentError(at: logURL, maxBytes: 4096)
+ #expect(error?.contains("binding 127.0.0.1:49374") == true)
+ }
+
+ @Test func returnsNilForAMissingFile() {
+ #expect(ServerLog.recentError(at: URL(fileURLWithPath: "/nonexistent/stderr.log")) == nil)
+ }
+}
+
+struct StartFailureTests {
+ @Test func prefersTheLoggedErrorOverTheHealthError() throws {
+ let logURL = try makeLog("""
+ Error: binding 127.0.0.1:49374
+
+ Caused by:
+ Address already in use (os error 48)
+ """)
+ let message = StartFailure.message(
+ health: "Could not read /admin/status",
+ launchd: .stopped,
+ logURL: logURL
+ )
+ #expect(message.contains("Address already in use"))
+ }
+
+ @Test func fallsBackToHealthWhenNotInstalled() {
+ let message = StartFailure.message(
+ health: "Connection refused",
+ launchd: .notInstalled,
+ logURL: URL(fileURLWithPath: "/nonexistent/stderr.log")
+ )
+ #expect(message == "Connection refused")
+ }
+
+ @Test func fallsBackToHealthWhileRunning() throws {
+ let logURL = try makeLog("Error: binding 127.0.0.1:49374\n")
+ let message = StartFailure.message(
+ health: "Could not read /admin/status",
+ launchd: .running,
+ logURL: logURL
+ )
+ #expect(message == "Could not read /admin/status")
+ }
+
+ private func makeLog(_ contents: String) throws -> URL {
+ let dir = FileManager.default.temporaryDirectory
+ .appending(path: "aimem-start-failure-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ let logURL = dir.appending(path: "stderr.log")
+ try contents.write(to: logURL, atomically: true, encoding: .utf8)
+ return logURL
+ }
+}
diff --git a/docs/macos.md b/docs/macos.md
index be4fec66..1d699e79 100644
--- a/docs/macos.md
+++ b/docs/macos.md
@@ -407,6 +407,16 @@ wrapper's `posix` shell-script path does not. Re-run `install-hooks --agent
`launchctl print gui/$(id -u)/com.github.akitaonrails.ai-memory`. The app
never writes into its own bundle; a missing `config.toml` is created under
`~/Library/Application Support/ai-memory` by bundled `ai-memory init`.
+- **`Error: binding 127.0.0.1:49374` / `Address already in use` (the server
+ exits immediately and the menu extra stays red):** another process already
+ holds the port. **OpenCode v2's background service also defaults to 49374**,
+ so the two collide when both run on defaults. Move one side — start
+ ai-memory elsewhere (`bind = "127.0.0.1:<free-port>"` in
+ `~/Library/Application Support/ai-memory/config.toml`, then update the app's
+ server URL in Settings to match), or move the other service
+ (`opencode service set port <free-port>`). Find the current holder with
+ `lsof -nP -iTCP:49374 -sTCP:LISTEN`. The menu extra now surfaces this error
+ instead of showing only a red status item.
## Suggested Test Checklist