{"record":{"id":"590f570b2f8a56e8","repo":"github/copilot-sdk","slug":"response-error-failed-to-set-foreground-sessi","errorCode":null,"errorMessage":"{response.Error ?? \"Failed to set foreground session\"}","messagePattern":"\\{response\\.Error \\?\\? \"Failed to set foreground session\"\\}","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"dotnet/src/Client.cs","lineNumber":1874,"sourceCode":"    /// <param name=\"cancellationToken\">A token to cancel the operation.</param>\n    /// <exception cref=\"InvalidOperationException\">Thrown if the operation fails.</exception>\n    /// <example>\n    /// <code>\n    /// await client.SetForegroundSessionIdAsync(\"session-123\");\n    /// </code>\n    /// </example>\n    public async Task SetForegroundSessionIdAsync(string sessionId, CancellationToken cancellationToken = default)\n    {\n        ArgumentNullException.ThrowIfNull(sessionId);\n\n        var connection = await EnsureConnectedAsync(cancellationToken);\n\n        var response = await InvokeRpcAsync<SetForegroundSessionResponse>(\n            connection.Rpc, \"session.setForeground\", [new SetForegroundSessionRequest(sessionId)], cancellationToken);\n\n        if (!response.Success)\n        {\n            throw new InvalidOperationException(response.Error ?? \"Failed to set foreground session\");\n        }\n    }\n\n    /// <summary>\n    /// Subscribes to session lifecycle events of a specific kind.\n    /// </summary>\n    /// <typeparam name=\"T\">\n    /// The lifecycle event type to listen for. Pass a derived type such as\n    /// <see cref=\"SessionCreatedEvent\"/> to filter by kind, or\n    /// <see cref=\"SessionLifecycleEvent\"/> to receive every lifecycle event.\n    /// </typeparam>\n    /// <param name=\"handler\">A callback invoked when a matching lifecycle event arrives.</param>\n    /// <returns>An <see cref=\"IDisposable\"/> that, when disposed, unsubscribes the handler.</returns>\n    /// <example>\n    /// <code>\n    /// using var sub = client.OnLifecycle&lt;SessionForegroundEvent&gt;(evt =&gt;\n    /// {\n    ///     Console.WriteLine($\"Session {evt.SessionId} is now in foreground\");","sourceCodeStart":1856,"sourceCodeEnd":1892,"githubUrl":"https://github.com/github/copilot-sdk/blob/cd8cf15dc3f9e762615790aaed0a771a0f392755/dotnet/src/Client.cs#L1856-L1892","documentation":"Thrown when the session.setForeground RPC returns Success=false; the server's response.Error text is used if present, otherwise the generic 'Failed to set foreground session' message. Foreground designation tells the CLI which session receives user input/events, so a false response means the operation was rejected.","triggerScenarios":"Calling SetForegroundSessionAsync with a sessionId the server does not recognize, a session that already ended, or when the server refuses the foreground switch for lifecycle reasons.","commonSituations":"Setting foreground for a session after it completed/errored; using a session ID from another connection; racing session disposal with the foreground call.","solutions":["Verify the sessionId is a live session created via this client and not yet deleted","Wrap the call so you can fall back or no-op when the session already ended","Call SetForegroundSessionAsync immediately after session creation, before any disposal","Update the Copilot CLI if the server consistently rejects valid sessions"],"exampleFix":"// before\nawait client.SetForegroundSessionAsync(sessionId);\n// after\nif (!session.IsCompleted)\n{\n    await client.SetForegroundSessionAsync(sessionId);\n}","handlingStrategy":"try-catch","validationCode":"if (!activeSessions.Contains(sessionId)) throw new InvalidOperationException(\"cannot set foreground on unknown/ended session\");","typeGuard":null,"tryCatchPattern":"try { await client.SetForegroundSessionAsync(sessionId); }\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"foreground\"))\n{ logger.LogWarning(\"foreground switch rejected: {Reason}\", ex.Message); }","preventionTips":["Set foreground right after session creation","Don't call after session delete/complete","Keep session lifecycle in one owner component","Capture and log the server-provided error text"],"tags":["session","rpc","foreground","dotnet"],"backgroundTag":"api-error-response","analyzedSha":"cd8cf15dc3f9e762615790aaed0a771a0f392755","analyzedAt":"2026-09-09T18:32:31.973Z","contentChangedAt":"2026-09-09T18:32:31.973Z","schemaVersion":2},"datasetVersion":"2026-09-15T23:17:13.987Z"}