@@ -25,7 +25,9 @@ internal sealed class AuxiliaryBackchannelMonitor(
2525{
2626 private static readonly TimeSpan s_maxRetryElapsed = TimeSpan . FromSeconds ( 3 ) ;
2727 private static readonly TimeSpan s_maxRetryDelay = TimeSpan . FromSeconds ( 1 ) ;
28- private readonly ConcurrentDictionary < string , AppHostAuxiliaryBackchannel > _connections = new ( ) ;
28+
29+ // Outer key: hash (prefix), Inner key: socketPath, Value: connection
30+ private readonly ConcurrentDictionary < string , ConcurrentDictionary < string , AppHostAuxiliaryBackchannel > > _connectionsByHash = new ( ) ;
2931 private readonly string _backchannelsDirectory = GetBackchannelsDirectory ( ) ;
3032
3133 // Track known socket files to detect additions and removals
@@ -34,9 +36,18 @@ internal sealed class AuxiliaryBackchannelMonitor(
3436 private readonly TimeProvider _timeProvider = timeProvider ;
3537
3638 /// <summary>
37- /// Gets the collection of active AppHost connections.
39+ /// Gets all active AppHost connections, flattened from all hashes .
3840 /// </summary>
39- public IReadOnlyDictionary < string , AppHostAuxiliaryBackchannel > Connections => _connections ;
41+ public IEnumerable < AppHostAuxiliaryBackchannel > Connections =>
42+ _connectionsByHash . Values . SelectMany ( d => d . Values ) ;
43+
44+ /// <summary>
45+ /// Gets connections for a specific AppHost hash (prefix).
46+ /// </summary>
47+ /// <param name="hash">The AppHost hash.</param>
48+ /// <returns>All connections for the given hash, or empty if none.</returns>
49+ public IEnumerable < AppHostAuxiliaryBackchannel > GetConnectionsByHash ( string hash ) =>
50+ _connectionsByHash . TryGetValue ( hash , out var connections ) ? connections . Values : [ ] ;
4051
4152 /// <summary>
4253 /// Gets or sets the path to the selected AppHost. When set, this AppHost will be used for MCP operations.
@@ -50,7 +61,7 @@ public AppHostAuxiliaryBackchannel? SelectedConnection
5061 {
5162 get
5263 {
53- var connections = _connections . Values . ToList ( ) ;
64+ var connections = Connections . ToList ( ) ;
5465
5566 if ( connections . Count == 0 )
5667 {
@@ -91,7 +102,7 @@ public AppHostAuxiliaryBackchannel? SelectedConnection
91102 /// </summary>
92103 public IReadOnlyList < AppHostAuxiliaryBackchannel > GetConnectionsForWorkingDirectory ( DirectoryInfo workingDirectory )
93104 {
94- return _connections . Values
105+ return Connections
95106 . Where ( c => IsAppHostInScopeOfDirectory ( c . AppHostInfo ? . AppHostPath , workingDirectory . FullName ) )
96107 . ToList ( ) ;
97108 }
@@ -174,12 +185,10 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
174185 }
175186 finally
176187 {
177- // Clean up all connections
178- foreach ( var connection in _connections . Values )
179- {
180- await DisconnectAsync ( connection ) . ConfigureAwait ( false ) ;
181- }
182- _connections . Clear ( ) ;
188+ // Clean up all connections in parallel
189+ var disconnectTasks = Connections . Select ( DisconnectAsync ) ;
190+ await Task . WhenAll ( disconnectTasks ) . ConfigureAwait ( false ) ;
191+ _connectionsByHash . Clear ( ) ;
183192 }
184193 }
185194
@@ -221,9 +230,17 @@ private async Task<IReadOnlyList<Task>> ProcessDirectoryChangesAsync(Cancellatio
221230 {
222231 logger . LogDebug ( "Socket deleted: {SocketPath}" , removedFile ) ;
223232 var hash = AppHostHelper . ExtractHashFromSocketPath ( removedFile ) ;
224- if ( ! string . IsNullOrEmpty ( hash ) && _connections . TryRemove ( hash , out var connection ) )
233+ if ( ! string . IsNullOrEmpty ( hash ) &&
234+ _connectionsByHash . TryGetValue ( hash , out var connectionsForHash ) &&
235+ connectionsForHash . TryRemove ( removedFile , out var connection ) )
225236 {
226237 _ = Task . Run ( async ( ) => await DisconnectAsync ( connection ) . ConfigureAwait ( false ) , CancellationToken . None ) ;
238+
239+ // Clean up empty hash entries
240+ if ( connectionsForHash . IsEmpty )
241+ {
242+ _connectionsByHash . TryRemove ( hash , out _ ) ;
243+ }
227244 }
228245 }
229246
@@ -271,10 +288,34 @@ private async Task TryConnectToSocketAsync(string socketPath, ConcurrentBag<stri
271288 return ;
272289 }
273290
274- // Check if we're already connected
275- if ( _connections . ContainsKey ( hash ) )
291+ // Check if we're already connected to this specific socket
292+ if ( _connectionsByHash . TryGetValue ( hash , out var existingConnections ) &&
293+ existingConnections . ContainsKey ( socketPath ) )
276294 {
277- logger . LogDebug ( "Already connected to AppHost with hash {Hash}" , hash ) ;
295+ logger . LogDebug ( "Already connected to socket: {SocketPath}" , socketPath ) ;
296+ return ;
297+ }
298+
299+ // PID-based orphan detection (for new format sockets with PID in filename)
300+ var pid = AppHostHelper . ExtractPidFromSocketPath ( socketPath ) ;
301+ if ( pid is { } pidValue && ! AppHostHelper . ProcessExists ( pidValue ) )
302+ {
303+ logger . LogDebug ( "Socket is orphaned (PID {Pid} not running), skipping: {SocketPath}" , pidValue , socketPath ) ;
304+ // Clean up the orphaned socket with double-check to minimize TOCTOU race window
305+ // (A new process could theoretically start with the same PID between our checks)
306+ try
307+ {
308+ if ( ! AppHostHelper . ProcessExists ( pidValue ) )
309+ {
310+ File . Delete ( socketPath ) ;
311+ logger . LogDebug ( "Deleted orphaned socket: {SocketPath}" , socketPath ) ;
312+ }
313+ }
314+ catch ( Exception ex )
315+ {
316+ logger . LogDebug ( ex , "Failed to delete orphaned socket: {SocketPath}" , socketPath ) ;
317+ }
318+ failedSockets . Add ( socketPath ) ;
278319 return ;
279320 }
280321
@@ -317,14 +358,12 @@ private async Task TryConnectToSocketAsync(string socketPath, ConcurrentBag<stri
317358 socket ? . Dispose ( ) ;
318359 socket = null ;
319360
320- // If connection is refused on first attempt, the socket file is likely stale
321- // (AppHost crashed without cleaning up). However, there's a narrow race condition:
322- // when an AppHost creates its socket file (bind) but hasn't called listen() yet,
323- // we'd get ConnectionRefused. To avoid false positives, check if the socket file
324- // was created very recently - if so, allow retries. If the file is older, it's
325- // genuinely stale and we fail fast.
326- if ( isFirstAttempt )
361+ // For sockets without PID (old format from versions before 9.3), if connection is refused and file is old, it's stale.
362+ // For sockets with PID, we already checked process existence above, so this is transient.
363+ // TODO: Remove old format support after 9.3 is widely adopted (target: 10.0 release)
364+ if ( isFirstAttempt && ! pid . HasValue )
327365 {
366+ // Old format socket - use file age heuristic for backward compatibility
328367 var fileInfo = new FileInfo ( socketPath ) ;
329368 if ( fileInfo . Exists )
330369 {
@@ -343,6 +382,7 @@ private async Task TryConnectToSocketAsync(string socketPath, ConcurrentBag<stri
343382 }
344383
345384 logger . LogDebug ( "Socket not ready yet, will retry: {SocketPath}" , socketPath ) ;
385+ isFirstAttempt = false ;
346386 }
347387 catch ( Exception ex )
348388 {
@@ -380,23 +420,35 @@ private async Task TryConnectToSocketAsync(string socketPath, ConcurrentBag<stri
380420 // Set up disconnect handler
381421 rpc . Disconnected += ( sender , args ) =>
382422 {
383- logger . LogInformation ( "Disconnected from AppHost {Hash}: {Reason}" , hash , args . Reason ) ;
384- if ( _connections . TryRemove ( hash , out var conn ) )
423+ logger . LogInformation ( "Disconnected from AppHost at {SocketPath}: {Reason}" , socketPath , args . Reason ) ;
424+ if ( _connectionsByHash . TryGetValue ( hash , out var connectionsForHash ) &&
425+ connectionsForHash . TryRemove ( socketPath , out var conn ) )
385426 {
386427 _ = Task . Run ( async ( ) => await DisconnectAsync ( conn ) . ConfigureAwait ( false ) ) ;
428+
429+ // Clean up empty hash entries
430+ if ( connectionsForHash . IsEmpty )
431+ {
432+ _connectionsByHash . TryRemove ( hash , out _ ) ;
433+ }
387434 }
388435 } ;
389436
390- if ( _connections . TryAdd ( hash , connection ) )
437+ // Get or create the inner dictionary for this hash
438+ var connectionsDict = _connectionsByHash . GetOrAdd ( hash , _ => new ConcurrentDictionary < string , AppHostAuxiliaryBackchannel > ( ) ) ;
439+
440+ if ( connectionsDict . TryAdd ( socketPath , connection ) )
391441 {
392442 logger . LogInformation (
393- "Successfully connected to AppHost {Hash}. " +
443+ "Successfully connected to AppHost at {SocketPath}. " +
444+ "Hash: {Hash}, " +
394445 "AppHost Path: {AppHostPath}, " +
395446 "AppHost PID: {AppHostPid}, " +
396447 "CLI PID: {CliPid}, " +
397448 "Dashboard URL: {DashboardUrl}, " +
398449 "Dashboard Token: {DashboardToken}, " +
399450 "In Scope: {InScope}" ,
451+ socketPath ,
400452 hash ,
401453 appHostInfo ? . AppHostPath ?? "N/A" ,
402454 appHostInfo ? . ProcessId . ToString ( CultureInfo . InvariantCulture ) ?? "N/A" ,
@@ -407,7 +459,7 @@ private async Task TryConnectToSocketAsync(string socketPath, ConcurrentBag<stri
407459 }
408460 else
409461 {
410- logger . LogWarning ( "Failed to add connection for AppHost {Hash }" , hash ) ;
462+ logger . LogWarning ( "Failed to add connection for socket {SocketPath }" , socketPath ) ;
411463 await DisconnectAsync ( connection ) . ConfigureAwait ( false ) ;
412464 }
413465 }
0 commit comments