before_code
stringlengths
14
465k
reviewer_comment
stringlengths
16
64.5k
after_code
stringlengths
9
467k
diff_context
stringlengths
0
97k
file_path
stringlengths
5
226
comment_line
int32
0
26
language
stringclasses
37 values
quality_score
float32
0.07
1
comment_type
stringclasses
9 values
comment_length
int32
16
64.5k
before_lines
int32
1
17.2k
after_lines
int32
1
12.1k
is_negative
bool
2 classes
pr_title
stringlengths
1
308
pr_number
int32
1
299k
repo_name
stringclasses
533 values
repo_stars
int64
321
419k
repo_language
stringclasses
27 values
reviewer_username
stringlengths
0
39
author_username
stringlengths
2
39
return (.useCredential, credential, nil) } open func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { ...
No issues found.
return (.useCredential, credential, nil) } open func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { ...
@@ -29,6 +29,7 @@ public protocol SessionStateProvider: AnyObject { func didCompleteTask(_ task: URLSessionTask) var serverTrustManager: ServerTrustManager? { get } var redirectHandler: RedirectHandler? { get } + var cachedResponseHandler: CachedResponseHandler? { get } func credential(for task: ...
Source/SessionStateProvider.swift
0
Swift
1
none
16
51
51
true
Feature - Cached Responses
2,701
Alamofire/Alamofire
41,690
Swift
cnoon
// Then XCTAssertNotNil(response?.request) XCTAssertNotNil(response?.response) XCTAssertNotNil(response?.data) XCTAssertNil(response?.error) XCTAssertEqual(response?.response?.url?.absoluteString, redirectURLString) XCTAssertEqual(response?.response?.statusCode, ...
No issues found.
// Then XCTAssertNotNil(response?.request) XCTAssertNotNil(response?.response) XCTAssertNotNil(response?.data) XCTAssertNil(response?.error) XCTAssertEqual(response?.response?.url?.absoluteString, redirectURLString) XCTAssertEqual(response?.response?.statusCode, ...
@@ -96,37 +96,71 @@ class SessionDelegateTestCase: BaseTestCase { func testThatAppropriateNotificationsAreCalledWithRequestForDataRequest() { // Given - var request: Request? - _ = expectation(forNotification: Request.didResume, object: nil, handler: nil) - _ = expectation(forNotifi...
Tests/SessionDelegateTests.swift
0
Swift
1
none
16
51
51
true
Fix #2682: Cancel all requests on session invalidation or deinit.
2,728
Alamofire/Alamofire
41,690
Swift
jshier
/// A type that intercepts requests to potentially adapt and retry them. public protocol RequestInterceptor: RequestAdapter, RequestRetrier {} extension RequestInterceptor { public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest>) -> Void) { completion(.s...
No issues found.
/// A type that intercepts requests to potentially adapt and retry them. public protocol RequestInterceptor: RequestAdapter, RequestRetrier {} extension RequestInterceptor { public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest>) -> Void) { completion(.s...
@@ -101,8 +101,8 @@ extension RequestInterceptor { } } -public typealias AdaptHandler = (URLRequest, Session, _ completion: (Result<URLRequest>) -> Void) -> Void -public typealias RetryHandler = (Request, Session, Error, _ completion: (RetryResult) -> Void) -> Void +public typealias AdaptHandler = (URLRequest, ...
Source/RequestInterceptor.swift
0
Swift
1
none
16
51
51
true
Mark RequestInterceptor closure callback arguments escaping
2,747
Alamofire/Alamofire
41,690
Swift
cysp
// MARK: Validate Certificate Chain Without Validating Host func testThatPinnedLeafCertificatePassesEvaluationWithoutHostValidation() { // Given let host = "test.alamofire.org" let serverTrust = TestTrusts.leafValidDNSName.trust let certificates = [TestCertificates.leafValidDNSN...
No issues found.
// MARK: Validate Certificate Chain Without Validating Host func testThatPinnedLeafCertificatePassesEvaluationWithoutHostValidation() { // Given let host = "test.alamofire.org" let serverTrust = TestTrusts.leafValidDNSName.trust let certificates = [TestCertificates.leafValidDNSN...
@@ -1110,7 +1110,7 @@ class ServerTrustPolicyPinPublicKeysTestCase: ServerTrustPolicyTestCase { // Given let host = "test.alamofire.org" let serverTrust = TestTrusts.leafValidDNSName.trust - let keys = [TestCertificates.leafValidDNSName].publicKeys + let keys = [TestCertificates...
Tests/ServerTrustEvaluatorTests.swift
0
Swift
1
none
16
51
51
true
[Alamofire 5]: AlamofireExtended extension point.
2,758
Alamofire/Alamofire
41,690
Swift
jshier
} /// Returns whether the instance is `requestRetryFailed`. When `true`, the `underlyingError` property will /// contain the associated value. public var isRequestRetryError: Bool { if case .requestRetryFailed = self { return true } return false } } // MARK: - Convenience Propertie...
No issues found.
} /// Returns whether the instance is `requestRetryFailed`. When `true`, the `underlyingError` property will /// contain the associated value. public var isRequestRetryError: Bool { if case .requestRetryFailed = self { return true } return false } } // MARK: - Convenience Propertie...
@@ -294,22 +294,14 @@ extension AFError { extension AFError { /// The `URLConvertible` associated with the error. public var urlConvertible: URLConvertible? { - switch self { - case .invalidURL(let url): - return url - default: - return nil - } + guard...
Source/AFError.swift
0
Swift
1
none
16
51
51
true
Refactor - Switches and Queues
2,765
Alamofire/Alamofire
41,690
Swift
cnoon
// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LI...
No issues found.
// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LI...
@@ -46,6 +46,14 @@ extension URLRequest { return request } + + static func make(url: URL = URL(string: "https://httpbin.org/get")!, method: HTTPMethod = .get, headers: HTTPHeaders = .init()) -> URLRequest { + var request = URLRequest(url:url) + request.method = method + request.h...
Tests/HTTPBin.swift
0
Swift
1
none
16
51
51
true
[#2270]: Fix emptyResponseAllowed logic.
2,772
Alamofire/Alamofire
41,690
Swift
jshier
manager.request(urlString) .response { resp in response = resp expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNotNil(response?.response) ...
No issues found.
manager.request(urlString) .response { resp in response = resp expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNotNil(response?.response) ...
@@ -94,26 +94,42 @@ class SessionDelegateTestCase: BaseTestCase { XCTAssertEqual(response?.response?.statusCode, 200) } + // MARK: - Tests - Notification + func testThatAppropriateNotificationsAreCalledWithRequestForDataRequest() { // Given let session = Session(startRequestsIm...
Tests/SessionDelegateTests.swift
0
Swift
1
none
16
51
51
true
Audit - Notification Names
2,803
Alamofire/Alamofire
41,690
Swift
cnoon
request.suspend() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertEqual(request.state, .suspended) } func testThatRequestManuallyCancelledManyTimesAfterAutomaticResumeOnlyReceivesAppropriateLifetimeEvents() { // Given let even...
No issues found.
request.suspend() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertEqual(request.state, .suspended) } func testThatRequestManuallyCancelledManyTimesAfterAutomaticResumeOnlyReceivesAppropriateLifetimeEvents() { // Given let even...
@@ -491,36 +491,112 @@ class RequestResponseTestCase: BaseTestCase { // Then XCTAssertEqual(request.state, .cancelled) } - + func testThatRequestManuallyCancelledManyTimesOnManyQueuesOnlyReceivesAppropriateLifetimeEvents() { // Given let eventMonitor = ClosureEventMonit...
Tests/RequestTests.swift
0
Swift
1
none
16
51
51
true
Bugfix: DownloadRequest event duplication and missing events.
2,807
Alamofire/Alamofire
41,690
Swift
jshier
waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertEqual(request.state, .cancelled) } func testThatRequestManuallyCancelledManyTimesOnlyReceivesAppropriateLifetimeEvents() { // Given let eventMonitor = ClosureEventMonitor() let session = Sessio...
No issues found.
waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertEqual(request.state, .cancelled) } func testThatRequestManuallyCancelledManyTimesOnlyReceivesAppropriateLifetimeEvents() { // Given let eventMonitor = ClosureEventMonitor() let session = Sessio...
@@ -26,8 +26,6 @@ import Alamofire import Foundation import XCTest -// MARK: - - class RequestResponseTestCase: BaseTestCase { func testRequestResponse() { // Given @@ -263,7 +261,7 @@ class RequestResponseTestCase: BaseTestCase { XCTAssertEqual(receivedResponse?.result.value?.form, ["proper...
Tests/RequestTests.swift
0
Swift
1
none
16
51
51
true
Feature - Terminal Response Serializers
2,810
Alamofire/Alamofire
41,690
Swift
cnoon
let encoder = URLEncodedFormEncoder() let parameters = ManuallyEncodableSubclass() // When let result = AFResult<String> { try encoder.encode(parameters) } // Then let expected = "five%5Ba%5D=a&five%5Bb%5D=b&four%5Bfour%5D=one&four%5Bfive%5D=2" XCTAssertQueryEqu...
No issues found.
let encoder = URLEncodedFormEncoder() let parameters = ManuallyEncodableSubclass() // When let result = AFResult<String> { try encoder.encode(parameters) } // Then let expected = "five%5Ba%5D=a&five%5Bb%5D=b&four%5Bfour%5D=one&four%5Bfive%5D=2" XCTAssertQueryEqu...
@@ -472,6 +472,97 @@ final class URLEncodedFormEncoderTests: BaseTestCase { XCTAssertEqual(result.value, "bool=true") } + func testThatDatesCanBeEncoded() { + // Given + let encoder = URLEncodedFormEncoder(dateEncoding: .deferredToDate) + let parameters = ["date": Date(timeInterv...
Tests/ParameterEncoderTests.swift
0
Swift
1
none
16
51
51
true
Date encoding strategies for URLEncodedFormEncoder
2,813
Alamofire/Alamofire
41,690
Swift
almazrafi
let expectation1 = self.expectation(description: "Request 1 created") monitor.requestDidFailToAdaptURLRequestWithError = { _, _, _ in expectation1.fulfill() } let request1 = session.request(urlString) waitForExpectations(timeout: timeout, handler: nil) let expectation2 = self.e...
No issues found.
let expectation1 = self.expectation(description: "Request 1 created") monitor.requestDidFailToAdaptURLRequestWithError = { _, _, _ in expectation1.fulfill() } let request1 = session.request(urlString) waitForExpectations(timeout: timeout, handler: nil) let expectation2 = self.e...
@@ -26,7 +26,7 @@ import Foundation import XCTest -class SessionTestCase: BaseTestCase { +final class SessionTestCase: BaseTestCase { // MARK: Helper Types @@ -895,7 +895,10 @@ class SessionTestCase: BaseTestCase { XCTAssertEqual(handler.retryCount, 3) XCTAssertEqual(request.retryCount, 1...
Tests/SessionTests.swift
0
Swift
1
none
16
51
51
true
Add cancelAllRequests API
2,890
Alamofire/Alamofire
41,690
Swift
jshier
data: data, metrics: metrics, serializationDuration: serializationDuration, result: result.mapError(transform) ) } /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter. /// /// Use th...
No issues found.
data: data, metrics: metrics, serializationDuration: serializationDuration, result: result.mapError(transform) ) } /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter. /// /// Use th...
@@ -25,7 +25,7 @@ import Foundation /// Used to store all data associated with a serialized response of a data or upload request. -public struct DataResponse<Value> { +public struct DataResponse<Success> { /// The URL request sent to the server. public let request: URLRequest? @@ -42,10 +42,10 @@ public...
Source/Response.swift
0
Swift
1
none
16
51
51
true
Rename internal `flatMap` to `tryMap`
2,892
Alamofire/Alamofire
41,690
Swift
philtre
// MARK: Tests - Request Retrier func testThatSessionCallsRequestRetrierWhenRequestEncountersError() { // Given let handler = RequestHandler() let session = Session() let expectation = self.expectation(description: "request should eventually fail") var response: DataRe...
No issues found.
// MARK: Tests - Request Retrier func testThatSessionCallsRequestRetrierWhenRequestEncountersError() { // Given let handler = RequestHandler() let session = Session() let expectation = self.expectation(description: "request should eventually fail") var response: DataRe...
@@ -321,9 +321,9 @@ final class SessionTestCase: BaseTestCase { let brotliExpectation = expectation(description: "brotli request should complete") let gzipExpectation = expectation(description: "gzip request should complete") let deflateExpectation = expectation(description: "deflate request ...
Tests/SessionTests.swift
0
Swift
1
none
16
51
51
true
Add failure constraint to *Response
2,893
Alamofire/Alamofire
41,690
Swift
philtre
/// Creates an instance with the provided `JSONEncoder`. /// /// - Parameter encoder: The `JSONEncoder`. `JSONEncoder()` by default. public init(encoder: JSONEncoder = JSONEncoder()) { self.encoder = encoder } open func encode<Parameters: Encodable>(_ parameters: Parameters?, ...
No issues found.
/// Creates an instance with the provided `JSONEncoder`. /// /// - Parameter encoder: The `JSONEncoder`. `JSONEncoder()` by default. public init(encoder: JSONEncoder = JSONEncoder()) { self.encoder = encoder } open func encode<Parameters: Encodable>(_ parameters: Parameters?, ...
@@ -153,7 +153,7 @@ open class URLEncodedFormParameterEncoder: ParameterEncoder { throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.url)) } - guard let rawMethod = request.httpMethod, let method = HTTPMethod(rawValue: rawMethod) else { + guard let method = req...
Source/ParameterEncoder.swift
0
Swift
1
none
16
51
51
true
Unfreeze HTTPMethod
2,901
Alamofire/Alamofire
41,690
Swift
jshier
let response = HTTPURLResponse(statusCode: 205) // When let result = Result { try serializer.serialize(request: request, response: response, data: nil, error: nil) } // Then XCTAssertTrue(result.isSuccess) XCTAssertNotNil(result.value) XCTAssertNil(result.error)...
No issues found.
let response = HTTPURLResponse(statusCode: 205) // When let result = Result { try serializer.serialize(request: request, response: response, data: nil, error: nil) } // Then XCTAssertTrue(result.isSuccess) XCTAssertNotNil(result.value) XCTAssertNil(result.error)...
@@ -119,10 +119,7 @@ final class DataResponseSerializationTestCase: BaseTestCase { XCTAssertTrue(result.isSuccess) XCTAssertNotNil(result.value) XCTAssertNil(result.error) - - if let data = result.value { - XCTAssertEqual(data.count, 0) - } + XCTAssertEqual(res...
Tests/ResponseSerializationTests.swift
0
Swift
1
none
16
51
51
true
Add DataPreprocessor API
2,903
Alamofire/Alamofire
41,690
Swift
jshier
manager?.stopListening() manager?.startListening { (status) in second.fulfill() } wait(for: [second], timeout: timeout) // Then XCTAssertEqual(manager?.status, .reachable(.ethernetOrWiFi)) } func testThatHostManagerCanBeDeinitialized() { // ...
No issues found.
manager?.stopListening() manager?.startListening { (status) in second.fulfill() } wait(for: [second], timeout: timeout) // Then XCTAssertEqual(manager?.status, .reachable(.ethernetOrWiFi)) } func testThatHostManagerCanBeDeinitialized() { // ...
@@ -27,7 +27,7 @@ import Foundation import SystemConfiguration import XCTest -class NetworkReachabilityManagerTestCase: BaseTestCase { +final class NetworkReachabilityManagerTestCase: BaseTestCase { // MARK: - Tests - Initialization @@ -52,9 +52,9 @@ class NetworkReachabilityManagerTestCase: BaseTestCase {...
Tests/NetworkReachabilityManagerTests.swift
0
Swift
1
none
16
51
51
true
Refactor Reachability
2,915
Alamofire/Alamofire
41,690
Swift
jshier
// Then XCTAssertFalse(result.isSuccess) } func testThatOptionalValuesCannotBeEncoded() { // Given let encoder = URLEncodedFormEncoder() let parameters: [String: String?] = ["string": nil] // When let result = Result<String, Error> { try encoder.encode(p...
No issues found.
// Then XCTAssertFalse(result.isSuccess) } func testThatOptionalValuesCannotBeEncoded() { // Given let encoder = URLEncodedFormEncoder() let parameters: [String: String?] = ["string": nil] // When let result = Result<String, Error> { try encoder.encode(p...
@@ -382,8 +382,8 @@ final class URLEncodedFormEncoderTests: BaseTestCase { let result = Result<String, Error> { try encoder.encode(parameters) } // Then - let expected = "four%5B%5D=1&four%5B%5D=2&four%5B%5D=3&three=1&one=one&two=2&five%5Ba%5D=a&six%5Ba%5D%5Bb%5D=b&seven%5Ba%5D=a" - XC...
Tests/ParameterEncoderTests.swift
0
Swift
1
none
16
51
51
true
Stable encoded parameter order for URLEncodedFormEncoder
2,961
Alamofire/Alamofire
41,690
Swift
jshier
private let performDefaultValidation: Bool private let validateHost: Bool /// Creates a `PublicKeysTrustEvaluator`. /// /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use /// `PinnedCertificatesTrustEvaluator` if you need to us...
No issues found.
private let performDefaultValidation: Bool private let validateHost: Bool /// Creates a `PublicKeysTrustEvaluator`. /// /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use /// `PinnedCertificatesTrustEvaluator` if you need to us...
@@ -35,14 +35,14 @@ open class ServerTrustManager { /// Initializes the `ServerTrustManager` instance with the given evaluators. /// /// Since different servers and web services can have different leaf certificates, intermediate and even root - /// certficates, it is important to have the flexibility ...
Source/ServerTrustEvaluation.swift
0
Swift
1
none
16
51
51
true
Move Automatic Resume Behavior to After the First Response Handler is Added
2,965
Alamofire/Alamofire
41,690
Swift
jshier
} var isHostURLError: Bool { guard let errorCode = (underlyingError as? URLError)?.code else { return false } return [.cannotConnectToHost, .cannotFindHost].contains(errorCode) } } // MARK: - extension AFError.ParameterEncodingFailureReason { var isMissingURL: Bool { if ca...
No issues found.
} var isHostURLError: Bool { guard let errorCode = (underlyingError as? URLError)?.code else { return false } return [.cannotConnectToHost, .cannotFindHost].contains(errorCode) } } // MARK: - extension AFError.ParameterEncodingFailureReason { var isMissingURL: Bool { if ca...
@@ -174,6 +174,11 @@ extension AFError { if case let .urlRequestValidationFailed(reason) = self, reason.isBodyDataInGETRequest { return true } return false } + + var isHostURLError: Bool { + guard let errorCode = (underlyingError as? URLError)?.code else { return false } + re...
Tests/AFError+AlamofireTests.swift
0
Swift
1
none
16
51
51
true
Response test host error fix
3,003
Alamofire/Alamofire
41,690
Swift
tronthomas
// Copyright (c) 2020 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rig...
No issues found.
// Copyright (c) 2020 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rig...
@@ -0,0 +1,55 @@ +// +// StringEncoding+Alamofire.swift +// +// Copyright (c) 2020 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the ...
Source/StringEncoding+Alamofire.swift
0
Swift
1
none
16
51
51
true
Linux Preparation
3,115
Alamofire/Alamofire
41,690
Swift
jshier
// // InternalRequestTests.swift // // Copyright (c) 2020 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction,...
No issues found.
// // InternalRequestTests.swift // // Copyright (c) 2020 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction,...
@@ -0,0 +1,49 @@ +// +// InternalRequestTests.swift +// +// Copyright (c) 2020 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Soft...
Tests/InternalRequestTests.swift
0
Swift
1
none
16
50
50
true
Prevent Multiple finish() Calls
3,116
Alamofire/Alamofire
41,690
Swift
jshier
let certificates = [TestCertificates.leafValidDNSName] let serverTrustPolicy = PinnedCertificatesTrustEvaluator(certificates: certificates, performDefaultValidation: false, v...
No issues found.
let certificates = [TestCertificates.leafValidDNSName] let serverTrustPolicy = PinnedCertificatesTrustEvaluator(certificates: certificates, performDefaultValidation: false, v...
@@ -1309,7 +1309,7 @@ class ServerTrustPolicyDisableEvaluationTestCase: ServerTrustPolicyTestCase { // Given let host = "test.alamofire.org" let serverTrust = TestTrusts.leafValidDNSNameMissingIntermediate.trust - let serverTrustPolicy = DisabledEvaluator() + let serverTrustPoli...
Tests/ServerTrustEvaluatorTests.swift
0
Swift
1
none
16
51
51
true
Changed DisabledEvaluator to DisabledTrustEvaluator
3,162
Alamofire/Alamofire
41,690
Swift
MrCloud
} func asURLRequest() throws -> URLRequest { try request.asURLRequest() } } // MARK: Data /// Creates an `UploadRequest` for the given `Data`, `URLRequest` components, and `RequestInterceptor`. /// /// - Parameters: /// - data: The `Data` to up...
No issues found.
} func asURLRequest() throws -> URLRequest { try request.asURLRequest() } } // MARK: Data /// Creates an `UploadRequest` for the given `Data`, `URLRequest` components, and `RequestInterceptor`. /// /// - Parameters: /// - data: The `Data` to up...
@@ -963,75 +963,67 @@ open class Session { // MARK: Perform - /// Perform `Request`. - /// - /// - Note: Called during retry. + /// Starts performing the provided `Request`. /// /// - Parameter request: The `Request` to perform. func perform(_ request: Request) { - // Leaf typ...
Source/Session.swift
0
Swift
1
none
16
51
51
true
Fix threading issue: activeRequests could be accessed off of the rootQueue.
3,179
Alamofire/Alamofire
41,690
Swift
jshier
XCTAssertEqual(results[2]?.retryRequired, false) XCTAssertNil(results[2]?.delay) XCTAssertNil(results[2]?.error) } } func testThatRetryPolicyRetriesIdempotentRequests() { // Given let retryPolicy = RetryPolicy() var results: [HTTPMethod: Retry...
No issues found.
XCTAssertEqual(results[2]?.retryRequired, false) XCTAssertNil(results[2]?.delay) XCTAssertNil(results[2]?.error) } } func testThatRetryPolicyRetriesIdempotentRequests() { // Given let retryPolicy = RetryPolicy() var results: [HTTPMethod: Retry...
@@ -76,6 +76,7 @@ class BaseRetryPolicyTestCase: BaseTestCase { lazy var unknownError = AFError.sessionTaskFailed(error: unknown) let retryableStatusCodes: Set<Int> = [408, 500, 502, 503, 504] + let statusCodes = Set(100...599) let retryableErrorCodes: Set<URLError.Code> = [.backgroundSessionInUse...
Tests/RetryPolicyTests.swift
0
Swift
1
none
16
51
51
true
adding more flexibility in reusing RetryPolicy
3,181
Alamofire/Alamofire
41,690
Swift
Skoti
// When let request = session.request("https://httpbin.org/basic-auth/user/password", interceptor: requestHandler) .validate() .responseJSON { jsonResponse in response = jsonResponse expectation.fulfill() } waitForExpectations(...
No issues found.
// When let request = session.request("https://httpbin.org/basic-auth/user/password", interceptor: requestHandler) .validate() .responseJSON { jsonResponse in response = jsonResponse expectation.fulfill() } waitForExpectations(...
@@ -1473,11 +1473,90 @@ final class SessionTestCase: BaseTestCase { XCTAssertEqual(request.state, .finished) XCTAssertEqual(response?.result.isSuccess, true) } + + // MARK: Invalid Requests + + func testThatGETRequestsWithBodyDataAreConsideredInvalid() { + // Given + let sessi...
Tests/SessionTests.swift
0
Swift
1
none
16
51
51
true
On Hold: Add withAllRequests API
3,200
Alamofire/Alamofire
41,690
Swift
jshier
executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: false) } func testThatUploadingMultipartFormDataWhileStreamingFromDiskMonitorsProgress() { executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: true) } func testThatUploadingMultipartFormDataBelowMemoryThres...
No issues found.
executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: false) } func testThatUploadingMultipartFormDataWhileStreamingFromDiskMonitorsProgress() { executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: true) } func testThatUploadingMultipartFormDataBelowMemoryThres...
@@ -280,9 +280,9 @@ class UploadMultipartFormDataTestCase: BaseTestCase { // When AF.upload(multipartFormData: { multipartFormData in - multipartFormData.append(uploadData, withName: "upload_data") - formData = multipartFormData - }, + multipartFormD...
Tests/UploadTests.swift
0
Swift
1
none
16
51
51
true
Lifetime Event APIs
3,219
Alamofire/Alamofire
41,690
Swift
jshier
var response: HTTPBinResponse? // When store { AF.streamRequest(URLRequest.makeHTTPBinRequest()) .publishDecodable(type: HTTPBinResponse.self) .value() .sink(receiveCompletion: { _ in completionReceived.fulfill() }, ...
No issues found.
var response: HTTPBinResponse? // When store { AF.streamRequest(URLRequest.makeHTTPBinRequest()) .publishDecodable(type: HTTPBinResponse.self) .value() .sink(receiveCompletion: { _ in completionReceived.fulfill() }, ...
@@ -306,14 +306,14 @@ final class DataRequestCombineTests: CombineTestCase { AF.request(URLRequest.makeHTTPBinRequest()) .publishDecodable(type: HTTPBinResponse.self, queue: queue) .sink(receiveCompletion: { _ in - dispatchPrecondition(condition: .onQueu...
Tests/CombineTests.swift
0
Swift
1
none
16
51
51
true
Fix to throw an error in MultipartUpload when copying a file to a temporary path fails.
3,306
Alamofire/Alamofire
41,690
Swift
sudopark
eventMonitor.requestDidCreateTask = { _, _ in didCreateTask.fulfill() } eventMonitor.requestDidGatherMetrics = { _, _ in didGatherMetrics.fulfill() } eventMonitor.requestDidCompleteTaskWithError = { _, _, _ in didComplete.fulfill() } eventMonitor.requestDidFinish = { _ in didFinish.fulfi...
No issues found.
eventMonitor.requestDidCreateTask = { _, _ in didCreateTask.fulfill() } eventMonitor.requestDidGatherMetrics = { _, _ in didGatherMetrics.fulfill() } eventMonitor.requestDidCompleteTaskWithError = { _, _, _ in didComplete.fulfill() } eventMonitor.requestDidFinish = { _ in didFinish.fulfi...
@@ -1204,7 +1204,7 @@ class RequestInvalidURLTestCase: BaseTestCase { // Then XCTAssertEqual(response?.error?.isInvalidURLError, true) } - + func testThatDownloadRequestWithFileURLThrowsError() { // Given let fileURL = url(forResource: "valid_data", withExtension: "json...
Tests/RequestTests.swift
0
Swift
1
none
16
51
51
true
Fix Double Lock in AuthenticationInterceptor
3,322
Alamofire/Alamofire
41,690
Swift
jshier
} request.resume() waitForExpectations(timeout: timeout) // Then XCTAssertEqual(request.state, .cancelled) } } // MARK: - final class DownloadResumeDataTestCase: BaseTestCase { func testThatCancelledDownloadRequestDoesNotProduceResumeData() { // Given ...
No issues found.
} request.resume() waitForExpectations(timeout: timeout) // Then XCTAssertEqual(request.state, .cancelled) } } // MARK: - final class DownloadResumeDataTestCase: BaseTestCase { func testThatCancelledDownloadRequestDoesNotProduceResumeData() { // Given ...
@@ -500,8 +500,6 @@ final class DownloadRequestEventsTestCase: BaseTestCase { // MARK: - final class DownloadResumeDataTestCase: BaseTestCase { - let endpoint = Endpoint.largeImage - func testThatCancelledDownloadRequestDoesNotProduceResumeData() { // Given let expectation = self.expectati...
Tests/DownloadTests.swift
0
Swift
1
none
16
51
51
true
Add Support for Resume Data on Error
3,419
Alamofire/Alamofire
41,690
Swift
jshier
.invalidURL, .sessionDeinitialized, .urlRequestValidationFailed: return nil } } /// The acceptable `Content-Type`s of a `.responseValidationFailed` error. public var acceptableContentTypes: [String]? { guard case let .responseValidationFail...
No issues found.
.invalidURL, .sessionDeinitialized, .urlRequestValidationFailed: return nil } } /// The acceptable `Content-Type`s of a `.responseValidationFailed` error. public var acceptableContentTypes: [String]? { guard case let .responseValidationFail...
@@ -129,7 +129,7 @@ public enum AFError: Error { case invalidEmptyResponse(type: String) } - #if !os(Linux) + #if !(os(Linux) || os(Windows)) /// Underlying reason a server trust evaluation error occurred. public enum ServerTrustFailureReason { /// The output of a server trust e...
Source/AFError.swift
0
Swift
1
none
16
51
51
true
Initial Windows Support
3,462
Alamofire/Alamofire
41,690
Swift
alex-taffe
}) } waitForExpectations(timeout: timeout) // Then XCTAssertNotNil(response) } @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) func testThatDataStreamRequestCanPublishValueWithFailure() { // Given let completionReceived = expect...
No issues found.
}) } waitForExpectations(timeout: timeout) // Then XCTAssertNotNil(response) } @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) func testThatDataStreamRequestCanPublishValueWithFailure() { // Given let completionReceived = expect...
@@ -22,7 +22,7 @@ // THE SOFTWARE. // -#if canImport(Combine) +#if !((os(iOS) && (arch(i386) || arch(arm))) || os(Windows) || os(Linux)) import Alamofire import Combine
Tests/CombineTests.swift
0
Swift
1
none
16
51
51
true
Xcode 13 Support
3,486
Alamofire/Alamofire
41,690
Swift
jshier
open func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @escaping (Result<URLRequest, Error>) -> Void) { adaptHandler(urlRequest, state.session, completion) } } #if swift(>=5.5) extension RequestAdapter where Self == Adapter { /// Creates an `Adapter` using the provi...
No issues found.
open func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @escaping (Result<URLRequest, Error>) -> Void) { adaptHandler(urlRequest, state.session, completion) } } #if swift(>=5.5) extension RequestAdapter where Self == Adapter { /// Creates an `Adapter` using the provi...
@@ -24,6 +24,17 @@ import Foundation +/// Stores all state associated with a `URLRequest` being adapted. +public struct RequestAdapterState { + /// The `UUID` of the `Request` associated with the `URLRequest` to adapt. + public let requestID: UUID + + /// The `Session` associated with the `URLRequest` to ...
Source/RequestInterceptor.swift
0
Swift
1
none
16
51
51
true
Request Adapter State
3,504
Alamofire/Alamofire
41,690
Swift
cnoon
} struct Upload: UploadConvertible { let request: URLRequestConvertible let uploadable: UploadableConvertible func createUploadable() throws -> UploadRequest.Uploadable { try uploadable.createUploadable() } func asURLRequest() throws -> URLRequest { ...
No issues found.
} struct Upload: UploadConvertible { let request: URLRequestConvertible let uploadable: UploadableConvertible func createUploadable() throws -> UploadRequest.Uploadable { try uploadable.createUploadable() } func asURLRequest() throws -> URLRequest { ...
@@ -312,15 +312,17 @@ open class Session { /// `RequestInterceptor`. /// /// - Parameters: - /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. - /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. - /// - parameters: `Encodable` value t...
Source/Session.swift
0
Swift
1
none
16
51
51
true
Fixes for parameters in doc comments throughout the project
3,511
Alamofire/Alamofire
41,690
Swift
evnik
// When let result = Result<String, Error> { try encoder.encode(parameters) } // Then let expected = "five%5Ba%5D=a&five%5Bb%5D=b&four%5Bfive%5D=2&four%5Bfour%5D=one" XCTAssertEqual(result.success, expected) } func testThatEncodableStructCanBeEncodedWithIndexInBrack...
No issues found.
// When let result = Result<String, Error> { try encoder.encode(parameters) } // Then let expected = "five%5Ba%5D=a&five%5Bb%5D=b&four%5Bfive%5D=2&four%5Bfour%5D=one" XCTAssertEqual(result.success, expected) } func testThatEncodableStructCanBeEncodedWithIndexInBrack...
@@ -511,6 +511,106 @@ final class URLEncodedFormEncoderTests: BaseTestCase { // Then XCTAssertFalse(result.isSuccess) } + + func testThatEncodableSuperclassCanBeEncodedWithIndexInBrackets() { + // Given + let encoder = URLEncodedFormEncoder(arrayEncoding: .indexInBrackets) + ...
Tests/ParameterEncoderTests.swift
0
Swift
1
none
16
51
51
true
Add .indexInBrackets array serialization option for URL parameters
3,516
Alamofire/Alamofire
41,690
Swift
TiagoMaiaL
let expectedQuery = "reserved=%3A%23%5B%5D%40%21%24%26%27%28%29%2A%2B%2C%3B%3D" XCTAssertEqual(urlRequest.url?.query, expectedQuery) } func testThatReservedCharactersQuestionMarkAndForwardSlashAreNotPercentEscaped() throws { // Given let parameters = ["reserved": "?/"] ...
No issues found.
let expectedQuery = "reserved=%3A%23%5B%5D%40%21%24%26%27%28%29%2A%2B%2C%3B%3D" XCTAssertEqual(urlRequest.url?.query, expectedQuery) } func testThatReservedCharactersQuestionMarkAndForwardSlashAreNotPercentEscaped() throws { // Given let parameters = ["reserved": "?/"] ...
@@ -186,6 +186,20 @@ final class URLParameterEncodingTestCase: ParameterEncodingTestCase { XCTAssertEqual(urlRequest.url?.query, "foo=a&foo=1&foo=1") } + func testURLParameterEncodeStringKeyArrayValueParameterWithCustomClosure() throws { + // Given + let encoding = URLEncoding(arrayEnco...
Tests/ParameterEncodingTests.swift
0
Swift
1
none
16
51
51
true
Add ArrayEncoding.custom to URLEncodedFormEncoder and ParameterEncoding
3,699
Alamofire/Alamofire
41,690
Swift
naquin
self.set_runtime_status(RuntimeStatus.STARTING_RUNTIME) await call_sync_from_async(self.wait_until_alive) if not self.attach_to_existing: self.log('info', 'Runtime is ready.') if not self.attach_to_existing: await call_sync_from_async(self.setup_initial_env...
```suggestion f'Error: Failed to connect instance {self.container_name} to network {network_name}', ```
self.maybe_build_runtime_container_image() self.log( 'info', f'Starting runtime with image: {self.runtime_container_image}' ) await call_sync_from_async(self.init_container) self.log( 'info', f'Container started:...
@@ -196,6 +196,17 @@ async def connect(self) -> None: self.set_runtime_status(RuntimeStatus.READY) self._runtime_initialized = True + for network_name in self.config.sandbox.additional_networks: + try: + network = self.docker_client.networks.get(network_name) + ...
openhands/runtime/impl/docker/docker_runtime.py
26
Python
0.857
bug
125
51
51
false
Add additional networks
9,566
All-Hands-AI/OpenHands
55,974
Python
enyst
Joeoc2001
'o3-2025-04-16', 'o4-mini', 'o4-mini-2025-04-16', 'gemini-2.5-pro', 'gpt-4.1', ] REASONING_EFFORT_SUPPORTED_MODELS = [ 'o1-2024-12-17', 'o1', 'o3', 'o3-2025-04-16', 'o3-mini-2025-01-31', 'o3-mini', 'o4-mini', 'o4-mini-2025-04-16', 'gemini-2.5-flash', 'gemini-...
```suggestion 'xai/grok-4-0709', ```
'o3-2025-04-16', 'o4-mini', 'o4-mini-2025-04-16', 'gemini-2.5-pro', 'gpt-4.1', ] REASONING_EFFORT_SUPPORTED_MODELS = [ 'o1-2024-12-17', 'o1', 'o3', 'o3-2025-04-16', 'o3-mini-2025-01-31', 'o3-mini', 'o4-mini', 'o4-mini-2025-04-16', 'gemini-2.5-flash', 'gemini-...
@@ -104,6 +104,7 @@ 'o1-preview', 'o1', 'o1-2024-12-17', + 'xai/grok-4-0709', # Grok-4 doesn't support stop parameter
openhands/llm/llm.py
26
Python
0.429
suggestion
42
51
51
false
Fix issue #9655: [Bug]: CodeActAgent is incompatible with xAI Grok-4 due to hardcoded stop parameter
9,666
All-Hands-AI/OpenHands
55,974
Python
enyst
openhands-agent
self._update_branch_in_conversation(conversation, current_branch) except Exception as e: self._log_branch_update_error(e, conversation.conversation_id) def _get_session_and_runtime( self, conversation_id: str ) -> tuple[Session | None, Any | None]: """ ...
Once we've detected that the agent has executed a command to switch branches, can we figure out the branch name from the command itself rather than using the runtime?
command = event.command.lower() # Check if any git command that changes branches is present anywhere in the command # This handles compound commands like "cd workspace && git checkout feature-branch" git_commands = [ 'git checkout', 'git s...
@@ -521,6 +527,160 @@ async def _update_conversation_for_event( await conversation_store.save_metadata(conversation) + def _is_git_related_event(self, event) -> bool: + """ + Determine if an event is related to git operations that could change the branch. + + Args: + even...
openhands/server/conversation_manager/standalone_conversation_manager.py
26
Python
0.357
question
166
51
51
false
fix(backend): show name of created branch in conversation list.
10,208
All-Hands-AI/OpenHands
55,974
Python
malhotra5
hieptl
event=None, ): conversation_store = await self._get_conversation_store(user_id) conversation = await conversation_store.get_metadata(conversation_id) conversation.last_updated_at = datetime.now(timezone.utc) # Update cost/token metrics if event has llm_metrics if eve...
nice! we also have docker nested runtimes; the server is spun inside the docker containers and actions are contained within the container itself so we'll need a webhook back to the main server to request an update to the branch name; I think tracing the logic for storing accumulated cost in the convo metadata for ne...
) def _create_conversation_update_callback( self, user_id: str | None, conversation_id: str, settings: Settings, llm_registry: LLMRegistry, ) -> Callable: def callback(event, *args, **kwargs): call_async_from_sync( self._update...
@@ -489,6 +490,11 @@ async def _update_conversation_for_event( conversation.total_tokens = ( token_usage.prompt_tokens + token_usage.completion_tokens ) + + # Check for branch changes if this is a git-related event + if event and self._is_git_related_...
openhands/server/conversation_manager/standalone_conversation_manager.py
26
Python
0.429
suggestion
351
51
51
false
fix(backend): show name of created branch in conversation list.
10,208
All-Hands-AI/OpenHands
55,974
Python
malhotra5
hieptl
new_branch: The new branch from the workspace Returns: True if the branch should be updated, False otherwise """ return new_branch is not None and new_branch != current_branch def _update_branch_in_conversation( self, conversation: ConversationMetadata, new_...
Can we just log in-place instead of this method? It doesn't seem to do anything but log a warning
Args: conversation_id: The conversation ID Returns: Tuple of (session, runtime) or (None, None) if not found """ session = self._local_agent_loops_by_sid.get(conversation_id) if not session or not session.agent_session.runtime: return None, N...
@@ -521,6 +527,160 @@ async def _update_conversation_for_event( await conversation_store.save_metadata(conversation) + def _is_git_related_event(self, event) -> bool: + """ + Determine if an event is related to git operations that could change the branch. + + Args: + even...
openhands/server/conversation_manager/standalone_conversation_manager.py
26
Python
0.286
question
97
51
51
false
fix(backend): show name of created branch in conversation list.
10,208
All-Hands-AI/OpenHands
55,974
Python
enyst
hieptl
Get the current branch from the workspace. Args: runtime: The runtime instance selected_repository: The selected repository path or None Returns: The current branch name or None if not found """ primary_repo_path = self._extract_repository_na...
Nit: maybe same here, could do it in-place? Small methods are nice, but 1-3 lines that we always do in-place, idk, seems a bit much decomposition ☺️
""" Update the conversation's current branch if it has changed. Args: conversation: The conversation metadata to update """ try: # Get the session and runtime for this conversation session, runtime = self._get_session_and_runtime( ...
@@ -521,6 +527,160 @@ async def _update_conversation_for_event( await conversation_store.save_metadata(conversation) + def _is_git_related_event(self, event) -> bool: + """ + Determine if an event is related to git operations that could change the branch. + + Args: + even...
openhands/server/conversation_manager/standalone_conversation_manager.py
26
Python
0.429
nitpick
148
51
51
false
fix(backend): show name of created branch in conversation list.
10,208
All-Hands-AI/OpenHands
55,974
Python
enyst
hieptl
default_title = get_default_conversation_title(conversation_id) if ( conversation.title == default_title ): # attempt to autogenerate if default title is in use title = await auto_generate_title( conversation_id, user_id, self.file_store, settings ...
(not a review comment) Just a small note here: this is in a callback from an eventstream subscriber that gets run every event, I _think_ it's really any event, regardless if agent, user, environment, state changes. I always get a little concerned to return as soon as possible, if the event is not applicable. I th...
llm_registry: LLMRegistry, event=None, ): conversation_store = await self._get_conversation_store(user_id) conversation = await conversation_store.get_metadata(conversation_id) conversation.last_updated_at = datetime.now(timezone.utc) # Update cost/token metrics if e...
@@ -489,6 +490,11 @@ async def _update_conversation_for_event( conversation.total_tokens = ( token_usage.prompt_tokens + token_usage.completion_tokens ) + + # Check for branch changes if this is a git-related event + if event and self._is_git_related_...
openhands/server/conversation_manager/standalone_conversation_manager.py
26
Python
0.5
suggestion
529
51
51
false
fix(backend): show name of created branch in conversation list.
10,208
All-Hands-AI/OpenHands
55,974
Python
enyst
hieptl
) if not session or not runtime: return # Get the current branch from the workspace current_branch = self._get_current_workspace_branch( runtime, conversation.selected_repository ) # Update branch if it has changed...
Could we check this against `conversation.selected_branch` instead?
logger.debug( f'Detected git-related command: {command} with exit code {event.metadata.exit_code}', extra={'command': command, 'exit_code': event.metadata.exit_code}, ) return is_git_related return False async def _update...
@@ -548,6 +554,142 @@ async def _update_conversation_for_event( await conversation_store.save_metadata(conversation) + def _is_git_related_event(self, event) -> bool: + """ + Determine if an event is related to git operations that could change the branch. + + Args: + even...
openhands/server/conversation_manager/standalone_conversation_manager.py
26
Python
0.429
question
67
51
51
false
fix(backend): show name of created branch in conversation list.
10,208
All-Hands-AI/OpenHands
55,974
Python
enyst
hieptl
) model_config = ConfigDict(extra='forbid') def model_post_init(self, __context) -> None: """Validate that selected_branch and selected_repository are provided together.""" if (self.selected_branch is None) != (self.selected_repository is None): raise ValueError( ...
If we're getting the branch information directly from the runtime by running a git command, do we have to validate that the branch exists again? Sometimes the agent may make a local branch that hasn't been pushed yet, so would this fail in those scenarios? Also NIT: lets move the `json response` objects to wheth...
conversation_id: The ID of the conversation to update data: The conversation update data (title, etc.) user_id: The authenticated user ID conversation_store: The conversation store dependency Returns: bool: True if the conversation was updated successfully Raises: ...
@@ -597,28 +597,203 @@ def _get_contextual_events(event_store: EventStore, event_id: int) -> str: class UpdateConversationRequest(BaseModel): """Request model for updating conversation metadata.""" - title: str = Field( - ..., min_length=1, max_length=200, description='New conversation title' + tit...
openhands/server/routes/manage_conversations.py
26
Python
0.643
bug
390
51
51
false
fix(backend): show name of created branch in conversation list.
10,208
All-Hands-AI/OpenHands
55,974
Python
malhotra5
hieptl
branches = await service.get_branches(repository) all_branches.extend(branches) # If we found branches, no need to check other providers if all_branches: break except Exception as e: logger.warning(f'Error fe...
if this is unused then lets remove it (including the methods to get a branch in the service classes); besides this PR LGTM
branches = await service.get_branches(repository) all_branches.extend(branches) # If we found branches, no need to check other providers if all_branches: break except Exception as e: logger.warning(f'Error fe...
@@ -466,6 +466,48 @@ async def get_branches( return main_branches + other_branches + async def get_branch(
openhands/integrations/provider.py
26
Python
0.429
suggestion
125
51
51
false
fix(backend): show name of created branch in conversation list.
10,208
All-Hands-AI/OpenHands
55,974
Python
malhotra5
hieptl
import { useState } from "react"; import { useTranslation } from "react-i18next"; import { TaskGroup } from "./task-group"; import { useSuggestedTasks } from "#/hooks/query/use-suggested-tasks"; import { TaskSuggestionsSkeleton } from "./task-suggestions-skeleton"; import { cn } from "#/utils/utils"; import { I18nKey }...
You can move these helper functions to a separate file to do a little clean up
import { useState } from "react"; import { useTranslation } from "react-i18next"; import { TaskGroup } from "./task-group"; import { useSuggestedTasks } from "#/hooks/query/use-suggested-tasks"; import { TaskSuggestionsSkeleton } from "./task-suggestions-skeleton"; import { cn, getDisplayedTaskGroups, getTotalTaskCount...
frontend/src/components/features/home/tasks/task-suggestions.tsx
1
TypeScript
0.286
refactor
78
26
26
false
refactor(frontend): update the styling for suggested tasks.
10,322
All-Hands-AI/OpenHands
55,974
Python
amanape
hieptl
import { type ClassValue, clsx } from "clsx"; import { twMerge } from "tailwind-merge"; import { Provider } from "#/types/settings"; import { SuggestedTaskGroup } from "#/components/features/home/tasks/task.types"; export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)); } interface EventActionHi...
To avoid a cyclic dependency (Component imports Utils imports Component), it is a good idea to move this type into a shared file as well, and have both the Utils and Components import the type
import { type ClassValue, clsx } from "clsx"; import { twMerge } from "tailwind-merge"; import { Provider } from "#/types/settings"; import { SuggestedTaskGroup } from "#/utils/types"; export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)); } interface EventActionHistory { args?: { LLM_API...
@@ -1,6 +1,7 @@ import { type ClassValue, clsx } from "clsx"; import { twMerge } from "tailwind-merge"; import { Provider } from "#/types/settings"; +import { SuggestedTaskGroup } from "#/components/features/home/tasks/task.types";
frontend/src/utils/utils.ts
4
TypeScript
0.571
refactor
192
29
29
false
refactor(frontend): update the styling for suggested tasks.
10,322
All-Hands-AI/OpenHands
55,974
Python
amanape
hieptl
# Search in each organization for org in user_orgs: org_query = f'{query} org:{org}' org_params = params.copy() org_params['q'] = org_query logger.info(f'Searching org {org} with query: {org_query}') ...
We dedup in the provider handler, so not necessary here
user_orgs = await self.get_user_organizations() # Search in user repos and org repos separately all_repos = [] # Search in user repositories user_query = f'{query} user:{user.login}' user_params = params.copy() user_params['q'] = user...
@@ -341,18 +353,65 @@ async def search_repositories( # Add is:public to the query to ensure we only search for public repositories params['q'] = f'in:name {org}/{repo_name} is:public' - # Perhaps we should go through all orgs and the search for repos under every org - # Current...
openhands/integrations/github/github_service.py
26
Python
0.357
suggestion
55
51
51
false
fix: Enhance GitHub repository search to include user organizations
10,324
All-Hands-AI/OpenHands
55,974
Python
malhotra5
amanape
try: user_response, _ = await self._make_request(url, user_params) user_items = user_response.get('items', []) all_repos.extend(user_items) logger.info(f'Found {len(user_items)} repos in user search') except Exception as e: ...
Nice! We should also filter against the org name So if we have a partial match on the org name, get the first 2 repos inside the org Currently if I type `All-Hands` it will search for the repo `All-Hands` under every org, whereas we could try matching against `All-Hands` org as well and list a couple of repos f...
if not public and '/' in query: org, repo_query = query.split('/', 1) query_with_user = f'org:{org} in:name {repo_query}' params['q'] = query_with_user elif not public: # Expand search scope to include user's repositories and organizations they're a member...
@@ -341,18 +353,65 @@ async def search_repositories( # Add is:public to the query to ensure we only search for public repositories params['q'] = f'in:name {org}/{repo_name} is:public' - # Perhaps we should go through all orgs and the search for repos under every org - # Current...
openhands/integrations/github/github_service.py
26
Python
0.786
suggestion
329
51
51
false
fix: Enhance GitHub repository search to include user organizations
10,324
All-Hands-AI/OpenHands
55,974
Python
malhotra5
amanape
self.runtime_container_image_id, self.config.sandbox.runtime_extra_deps, ) if self.attach_to_existing: if self.sid in MODAL_RUNTIME_IDS: sandbox_id = MODAL_RUNTIME_IDS[self.sid] self.log("debug", f"Attaching to existing Modal sandbox: ...
```suggestion self.log("info", "Waiting 20 secs for the container to be ready... (avoiding RemoteProtocolError)") ```
self.runtime_container_image_id, self.config.sandbox.runtime_extra_deps, ) if self.attach_to_existing: if self.sid in MODAL_RUNTIME_IDS: sandbox_id = MODAL_RUNTIME_IDS[self.sid] self.log("debug", f"Attaching to existing Modal sandbox: ...
@@ -149,6 +150,8 @@ async def connect(self): raise Exception("Sandbox not initialized") tunnel = self.sandbox.tunnels()[self.container_port] self.api_url = tunnel.url + print("Waiting 20 secs for the container to be ready... (avoiding RemoteProtocolError)")
third_party/runtime/impl/modal/modal_runtime.py
26
Python
0.929
suggestion
126
51
51
false
Update modal runtime for modal>=1.0
10,479
All-Hands-AI/OpenHands
55,974
Python
ryanhoangt
Zacharias030
self.runtime_container_image_id, self.config.sandbox.runtime_extra_deps, ) if self.attach_to_existing: if self.sid in MODAL_RUNTIME_IDS: sandbox_id = MODAL_RUNTIME_IDS[self.sid] self.log("debug", f"Attaching to existing Modal sandbox: ...
```suggestion self.log("info", "Waiting 20 secs for the container to be ready... (avoiding RemoteProtocolError)") ```
self.runtime_container_image_id, self.config.sandbox.runtime_extra_deps, ) if self.attach_to_existing: if self.sid in MODAL_RUNTIME_IDS: sandbox_id = MODAL_RUNTIME_IDS[self.sid] self.log("debug", f"Attaching to existing Modal sandbox: ...
@@ -149,6 +150,8 @@ async def connect(self): raise Exception("Sandbox not initialized") tunnel = self.sandbox.tunnels()[self.container_port] self.api_url = tunnel.url + self.log("info", "Waiting 20 secs for the container to be ready... (avoiding RemoteProtocolError)")
third_party/runtime/impl/modal/modal_runtime.py
26
Python
0.929
suggestion
127
51
51
false
Update modal runtime for modal>=1.0
10,479
All-Hands-AI/OpenHands
55,974
Python
ryanhoangt
Zacharias030
) ) # Load microagents from directory repo_microagents = self._load_microagents_from_directory( microagents_dir, 'repository' ) loaded_microagents.extend(repo_microagents) return loaded_microagents def run_action(self, action: Action...
can you use maybe os.path.joint for this?
file_content=obs.content, ) ) # Load microagents from directory repo_microagents = self._load_microagents_from_directory( microagents_dir, 'repository' ) loaded_microagents.extend(repo_microagents) return loaded_microa...
@@ -876,8 +877,14 @@ def run_action(self, action: Action) -> Observation: if isinstance(action, AgentThinkAction): return AgentThinkObservation('Your thought has been logged.') elif isinstance(action, TaskTrackingAction): - # If `command` is `plan`, write the se...
openhands/runtime/base.py
26
Python
0.143
question
41
51
51
false
Move TASKS.md to session-specific directory in `~/.openhands`
10,493
All-Hands-AI/OpenHands
55,974
Python
xingyaoww
ryanhoangt
if '\x00' in conversation_id: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail='Conversation ID contains invalid characters', ) # Check for path traversal attempts if '..' in conversation_id or '/' in conversation_id or '\\' in conversation_id: ...
Maybe we don’t need a custom type? I wonder, as long as the Depends was on the endpoint, it would be nice to continue working with a str if we can
raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail='Conversation ID contains invalid characters', ) # Check for path traversal attempts if '..' in conversation_id or '/' in conversation_id or '\\' in conversation_id: raise HTTPException( ...
@@ -13,6 +14,63 @@ from openhands.storage.data_models.conversation_metadata import ConversationMetadata +def validate_conversation_id(conversation_id: str) -> str: + """ + Validate conversation ID format and length. + + Args: + conversation_id: The conversation ID to validate + + Returns: + ...
openhands/server/utils.py
26
Python
0.5
suggestion
149
51
51
false
Fix conversation ID validation to return 400 instead of 500 for long IDs
10,496
All-Hands-AI/OpenHands
55,974
Python
enyst
amanape
import { afterAll, afterEach, beforeAll, vi } from "vitest"; import { cleanup } from "@testing-library/react"; import { server } from "#/mocks/node"; import "@testing-library/jest-dom/vitest"; HTMLCanvasElement.prototype.getContext = vi.fn(); HTMLElement.prototype.scrollTo = vi.fn(); // Mock the i18n provider vi.mock...
I think it would be better to: ```ts beforeAll(() => { vi.stubGlobal(“ResizeObserver”, MockResizeObserver); }); afterAll(() => { vi.unstubAllGlobals(); }); ``` Source: https://vitest.dev/api/vi.html#vi-stubglobal
import { afterAll, afterEach, beforeAll, vi } from "vitest"; import { cleanup } from "@testing-library/react"; import { server } from "#/mocks/node"; import "@testing-library/jest-dom/vitest"; HTMLCanvasElement.prototype.getContext = vi.fn(); HTMLElement.prototype.scrollTo = vi.fn(); // Mock ResizeObserver for test e...
@@ -7,11 +7,13 @@ HTMLCanvasElement.prototype.getContext = vi.fn(); HTMLElement.prototype.scrollTo = vi.fn(); // Mock ResizeObserver for test environment -global.ResizeObserver = vi.fn().mockImplementation(() => ({ - observe: vi.fn(), - unobserve: vi.fn(), - disconnect: vi.fn(), -})); +class MockResizeObserver {...
frontend/vitest.setup.ts
16
TypeScript
0.857
suggestion
231
33
41
false
feat(frontend): add the scroll buttons to scroll the git control bar
10,498
All-Hands-AI/OpenHands
55,974
Python
amanape
hieptl
def __enter__(self): start = time.time() while True: try: fd = os.open(self.lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY) os.write(fd, str(os.getpid()).encode('utf-8')) os.close(fd) self._acquired = True r...
```suggestion """TOML writer for OpenHands config. ```
def __enter__(self): start = time.time() while True: try: fd = os.open(self.lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY) os.write(fd, str(os.getpid()).encode('utf-8')) os.close(fd) self._acquired = True r...
@@ -38,142 +52,211 @@ def _serialize_dict(d: dict[str, Any]) -> dict[str, Any]: return {k: _serialize_value(v) for k, v in d.items()} +class _SimpleFileLock: + def __init__(self, path: str, timeout: float = 5.0, poll_interval: float = 0.1): + self.lock_path = path + '.lock' + self.timeout = ti...
openhands/core/config/toml_writer.py
26
Python
0.571
suggestion
60
51
51
false
feat(config-writer): tomlkit-based writer with comment preservation, explicit APIs, atomic writes + add tomlkit dep
10,512
All-Hands-AI/OpenHands
55,974
Python
enyst
enyst
return response['html_url'] async def get_microagent_content( self, repository: str, file_path: str ) -> MicroagentContentResponse: """Fetch individual file content from GitHub repository. Args: repository: Repository name in format 'owner/repo' file_pat...
@openhands write a method that gets the comments from a review thread in a PR given the pr_number, thread_id, and repo_name then use the $GITHUB_TOKEN in your env to test that this method works as expected. Use the github api to curl for a review thread and use those same params to call this method
url=labels_url, params=labels_payload, method=RequestMethod.POST ) # Return the HTML URL of the created PR return response['html_url'] async def get_microagent_content( self, repository: str, file_path: str ) -> MicroagentContentResponse: """Fetch in...
@@ -695,6 +695,104 @@ async def get_microagent_content( # Parse the content to extract triggers from frontmatter return self._parse_microagent_content(file_content, file_path) + async def get_issue_comments(
openhands/integrations/github/github_service.py
26
Python
0.643
suggestion
302
51
51
false
[Bug, GitHub]: fix missing context in cloud resolver
10,517
All-Hands-AI/OpenHands
55,974
Python
malhotra5
malhotra5
updated_at=datetime.fromisoformat( comment.get('updated_at', '').replace('Z', '+00:00') ) if comment.get('updated_at') else datetime.fromtimestamp(0), system=False, # GitHub doesn't have system c...
should we put any reasonable limits on this? It could be a lot of data/tokens...
if 'rel="next"' not in link_header: break page += 1 return self._process_raw_comments(all_comments) async def get_issue_or_pr_title_and_body( self, repository: str, issue_number: int ) -> tuple[str, str]: """Get the title and body of an issue. ...
@@ -695,6 +699,207 @@ async def get_microagent_content( # Parse the content to extract triggers from frontmatter return self._parse_microagent_content(file_content, file_path) + async def get_issue_comments( + self, repository: str, issue_number: int, discussion_id: str | None = None + ...
openhands/integrations/github/github_service.py
26
Python
0.286
question
80
51
51
false
[Bug, GitHub]: fix missing context in cloud resolver
10,517
All-Hands-AI/OpenHands
55,974
Python
rbren
malhotra5
knowledge_agents = {} # Load all agents from microagents directory logger.debug(f'Loading agents from {microagent_dir}') # Always check for .cursorrules and AGENTS.md files in repo root, regardless of whether microagents_dir exists special_files = [] repo_root = microagent_dir.parent.parent ...
Good question… I tend to agree it’s unlikely the user has _different_ information in two of these, and needs it all. 🤷‍♂️ We could go with this, and iterate as needed.
Returns: Tuple of (repo_agents, knowledge_agents) dictionaries """ if isinstance(microagent_dir, str): microagent_dir = Path(microagent_dir) repo_agents = {} knowledge_agents = {} # Load all agents from microagents directory logger.debug(f'Loading agents from {microagent_di...
@@ -276,31 +288,44 @@ def load_microagents_from_dir( # Load all agents from microagents directory logger.debug(f'Loading agents from {microagent_dir}') - if microagent_dir.exists(): - # Collect .cursorrules file from repo root and .md files from microagents dir - cursorrules_files = [] - ...
openhands/microagent/microagent.py
26
Python
0.429
style
170
49
51
false
Add support for AGENTS.md files in microagent system
10,528
All-Hands-AI/OpenHands
55,974
Python
enyst
ryanhoangt
if path.name == '.cursorrules': return RepoMicroagent( name='cursorrules', content=file_content, metadata=MicroagentMetadata(name='cursorrules'), source=str(path), type=MicroagentType.REPO_KNOWLEDGE, ) ...
I wonder if we can handle ALL these cursorrules/agents/agent.md into a separate function that can be called here? e.g. something like `handle_third_party` that will returns a RepoMicroAgent given a `path` and `file_content`
if microagent_dir is not None: # Special handling for files which are not in microagent_dir derived_name = cls.PATH_TO_THIRD_PARTY_MICROAGENT_NAME.get( path.name.lower() ) or str(path.relative_to(microagent_dir).with_suffix('')) # Only load directly f...
@@ -71,6 +73,16 @@ def load( type=MicroagentType.REPO_KNOWLEDGE, ) + # Handle AGENTS.md files (case-insensitive) + if path.name.lower() in ['agents.md', 'agent.md']: + return RepoMicroagent( + name='agents', + content=file_content, +...
openhands/microagent/microagent.py
26
Python
0.714
suggestion
224
51
51
false
Add support for AGENTS.md files in microagent system
10,528
All-Hands-AI/OpenHands
55,974
Python
xingyaoww
ryanhoangt
) return None @classmethod def load( cls, path: Union[str, Path], microagent_dir: Path | None = None, file_content: str | None = None, ) -> 'BaseMicroagent': """Load a microagent from a markdown file with frontmatter. The agent's name is...
can we factor this into `cls._path_to_microagent_name` and reuse it in `_handle_third_party` also?
source=str(path), type=MicroagentType.REPO_KNOWLEDGE, ) return None @classmethod def load( cls, path: Union[str, Path], microagent_dir: Path | None = None, file_content: str | None = None, ) -> 'BaseMicroagent': ""...
@@ -40,9 +63,11 @@ def load( # Otherwise, we will rely on the name from metadata later derived_name = None if microagent_dir is not None: - # Special handling for .cursorrules files which are not in microagent_dir + # Special handling for files which are not in microagen...
openhands/microagent/microagent.py
26
Python
0.571
question
98
51
51
false
Add support for AGENTS.md files in microagent system
10,528
All-Hands-AI/OpenHands
55,974
Python
xingyaoww
ryanhoangt
import React from "react"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "#/utils/utils"; const contextMenuVariants = cva( "absolute bg-tertiary rounded-[6px] text-white overflow-hidden z-50 shadow-[0_10px_15px_-3px_rgba(0,0,0,0.10),0_4px_6px_-2px_rgba(0,0,0,0.05),0_0_0_1px_rg...
Are we certain that all the styles defined here are being used? For example, I don’t see us use `size=“wide”`, but it is defined here. We should remove any unused variants until implemented
import React from "react"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "#/utils/utils"; const contextMenuVariants = cva( "absolute bg-tertiary rounded-[6px] text-white overflow-hidden z-50 shadow-[0_10px_15px_-3px_rgba(0,0,0,0.10),0_4px_6px_-2px_rgba(0,0,0,0.05),0_0_0_1px_rg...
@@ -0,0 +1,78 @@ +import React from "react"; +import { cva, type VariantProps } from "class-variance-authority"; +import { cn } from "#/utils/utils"; + +const contextMenuVariants = cva( + "absolute bg-tertiary rounded-[6px] text-white overflow-hidden z-50 shadow-[0_10px_15px_-3px_rgba(0,0,0,0.10),0_4px_6px_-2px_rgba(0...
frontend/src/ui/context-menu.tsx
8
TypeScript
0.571
question
189
33
33
false
refactor(frontend): context menu into a reusable component
10,546
All-Hands-AI/OpenHands
55,974
Python
amanape
hieptl
# Backward-compatible import for the web server-bound session wrapper. # The canonical name is WebSession; Session remains as an alias for BC. from openhands.server.session.session import WebSession from openhands.server.session.session import WebSession as Session __all__ = ['WebSession', 'Session']
```suggestion # The canonical name is WebSession; Session is an alias to be removed later. ```
# Backward-compatible import for the web server-bound session wrapper. # The canonical name is WebSession; Session is an alias to be removed later. from openhands.server.session.session import WebSession from openhands.server.session.session import WebSession as Session __all__ = ['WebSession', 'Session']
@@ -1,3 +1,6 @@ -from openhands.server.session.session import Session +# Backward-compatible import for the web server-bound session wrapper. +# The canonical name is WebSession; Session remains as an alias for BC.
openhands/server/session/__init__.py
2
Python
0.643
suggestion
96
7
7
false
chore(server): rename Session to WebSession
10,565
All-Hands-AI/OpenHands
55,974
Python
enyst
enyst
supports_function_calling: bool supports_reasoning_effort: bool supports_prompt_cache: bool supports_stop_words: bool # Pattern tables capturing current behavior. Keep patterns lowercase. FUNCTION_CALLING_PATTERNS: list[str] = [ # Anthropic families 'claude-3-7-sonnet*', 'claude-3.7-sonnet...
I think the patterns above should work for bedrock too?
supports_function_calling: bool supports_reasoning_effort: bool supports_prompt_cache: bool supports_stop_words: bool # Pattern tables capturing current behavior. Keep patterns lowercase. FUNCTION_CALLING_PATTERNS: list[str] = [ # Anthropic families 'claude-3-7-sonnet*', 'claude-3.7-sonnet...
@@ -69,6 +69,15 @@ class ModelFeatures: 'claude-3-5-haiku*', 'claude-sonnet-4*', 'claude-opus-4*', + # Bedrock Anthropic families (with bedrock/ prefix) + 'bedrock/anthropic.claude-3-7-sonnet*', + 'bedrock/anthropic.claude-3.7-sonnet*', + 'bedrock/anthropic.claude-sonnet-3-7-latest', + 'be...
openhands/llm/model_features.py
26
Python
0.286
question
55
51
51
false
fix: resolve empty API keys to None and add Bedrock model support
10,573
All-Hands-AI/OpenHands
55,974
Python
enyst
JAxeAddepar
raise FunctionCallValidationError( f'Missing required argument "command" in tool call {tool_call.function.name}' ) if arguments['command'] == 'plan' and 'task_list' not in arguments: raise FunctionCallValidationError( ...
I think we can probably just raise fn call validation error here, no need to try to recover?
raise FunctionCallValidationError( f'Missing required argument "command" in tool call {tool_call.function.name}' ) if arguments['command'] == 'plan' and 'task_list' not in arguments: raise FunctionCallValidationError( ...
@@ -263,9 +263,44 @@ def response_to_actions( f'Missing required argument "task_list" for "plan" command in tool call {tool_call.function.name}' ) + raw_task_list = arguments.get('task_list', []) + if not isinstance(raw_task_list, list): + ...
openhands/agenthub/codeact_agent/function_calling.py
26
Python
0.357
bug
92
51
51
false
fix: validate `task_list` schema for task tracker
10,624
All-Hands-AI/OpenHands
55,974
Python
xingyaoww
ryanhoangt
logger.debug('Adding env vars to bash') # don't log the values obs = self.run(CmdRunAction(cmd)) if not isinstance(obs, CmdOutputObservation) or obs.exit_code != 0: raise RuntimeError( f'Failed to add env vars [{env_vars.keys()}] to environment: ...
Not sure why this is being removed, is it checked outside this method?
logger.debug('Adding env vars to bash') # don't log the values obs = self.run(CmdRunAction(cmd)) if not isinstance(obs, CmdOutputObservation) or obs.exit_code != 0: raise RuntimeError( f'Failed to add env vars [{env_vars.keys()}] to environment: ...
@@ -323,18 +323,24 @@ def on_event(self, event: Event) -> None: async def _export_latest_git_provider_tokens(self, event: Action) -> None: """Refresh runtime provider tokens when agent attemps to run action with provider token""" - if not self.user_id: - return -
openhands/runtime/base.py
26
Python
0.286
question
70
51
51
false
[Fix]: token refresh for nested runtimes
10,637
All-Hands-AI/OpenHands
55,974
Python
raymyers
malhotra5
# save content if any, to thought if action.thought: if action.thought != content: action.thought += '\n' + content else: action.thought = content # remove the tool call metadata ...
I was wondering if we need this at all..
# save content if any, to thought if action.thought: if action.thought != content: action.thought += '\n' + content else: action.thought = content # remove the tool call metadata ...
@@ -302,10 +302,12 @@ def _process_action( elif isinstance(action, MessageAction): role = 'user' if action.source == 'user' else 'assistant' content = [TextContent(text=action.content or '')] - if vision_is_active and action.image_urls: + if action.image_urls: ...
openhands/memory/conversation_memory.py
26
Python
0.071
suggestion
40
51
51
false
Remove image content filtering in ConversationMemory
10,645
All-Hands-AI/OpenHands
55,974
Python
xingyaoww
ryanhoangt
if ('claude-opus-4-1' in _model_lower) and ( 'temperature' in kwargs and 'top_p' in kwargs ): kwargs.pop('top_p', None) self._completion = partial( litellm_completion, model=self.config.model, api_key=self.config.api_key.get_secret_val...
nit: actually, i wonder in what case we will send in single Message/dict? Maybe we can get rid of these two type and their code..
base_url=self.config.base_url, api_version=self.config.api_version, custom_llm_provider=self.config.custom_llm_provider, timeout=self.config.timeout, drop_params=self.config.drop_params, seed=self.config.seed, **kwargs, ) ...
@@ -209,7 +209,9 @@ def wrapper(*args: Any, **kwargs: Any) -> Any: """Wrapper for the litellm completion function. Logs the input and output of the completion function.""" from openhands.io import json - messages_kwarg: list[dict[str, Any]] | dict[str, Any] = [] + messa...
openhands/llm/llm.py
26
Python
0.5
nitpick
129
51
51
false
Add support for passing list of `Message` into LLM `completion`
10,650
All-Hands-AI/OpenHands
55,974
Python
xingyaoww
ryanhoangt
function ConversationSkeleton() { return ( <div className="flex flex-col gap-1 py-[14px]"> <div className="flex items-center gap-2"> <div className="w-3 h-3 rounded-full skeleton" /> <div className="w-20 h-3 skeleton" /> </div> <div className="flex items-center justify-between"> ...
Do we really need to mark these styles important? (`!`)
function ConversationSkeleton() { return ( <div className="flex flex-col gap-1 py-[14px]"> <div className="flex items-center gap-2"> <div className="w-3 h-3 rounded-full skeleton" /> <div className="w-27 h-3 skeleton !rounded-sm" /> </div> <div className="flex items-center justif...
@@ -3,18 +3,20 @@ function ConversationSkeleton() { <div className="flex flex-col gap-1 py-[14px]"> <div className="flex items-center gap-2"> <div className="w-3 h-3 rounded-full skeleton" /> - <div className="w-20 h-3 skeleton" /> + <div className="w-27 h-3 skeleton !rounded-sm" />
frontend/src/components/features/home/recent-conversations/recent-conversations-skeleton.tsx
6
TypeScript
0.357
question
55
31
31
false
refactor(frontend): improve loading skeleton (conversation UX improvements)
10,652
All-Hands-AI/OpenHands
55,974
Python
amanape
hieptl
# prefix events from the head, minus one for the summarization event events_from_tail = target_size - len(head) - 1 summary_event = ( view[self.keep_first] if isinstance(view[self.keep_first], AgentCondensationObservation) else AgentCondensationObservation('N...
If I understand correctly, this will not include the descriptions, just the task ids and pending/done?
# prefix events from the head, minus one for the summarization event events_from_tail = target_size - len(head) - 1 summary_event = ( view[self.keep_first] if isinstance(view[self.keep_first], AgentCondensationObservation) else AgentCondensationObservation('N...
@@ -69,10 +69,17 @@ def get_condensation(self, view: View) -> Condensation: forgotten_events.append(event) # Construct prompt for summarization - prompt = """You are maintaining a context-aware state summary for an interactive agent. You will be given a list of events corresponding to...
openhands/memory/condenser/impl/llm_summarizing_condenser.py
26
Python
0.357
question
102
51
51
false
fix: Linking condensation and task tracking prompts
10,656
All-Hands-AI/OpenHands
55,974
Python
enyst
csmith49
} if (!isSaas && SAAS_ONLY_PATHS.includes(pathname)) { // if in OSS mode, do not allow access to saas-only paths return redirect("/settings"); } return null; }; function SettingsScreen() { const { t } = useTranslation(); const { data: config } = useConfig(); const { data: subscriptionAccess } =...
```suggestion const navItems = useMemo(() => { const items = []; if (config?.APP_MODE === "saas") { if (subscriptionAccess) items.push({ to: "/settings", text: "SETTINGS$NAV_LLM" }); items.push(...SAAS_NAV_ITEMS); } else { items.push(...OSS_NAV_ITEMS); } return items; }, [config?.APP_MODE, subscri...
return redirect("/settings/user"); } if (!isSaas && SAAS_ONLY_PATHS.includes(pathname)) { // if in OSS mode, do not allow access to saas-only paths return redirect("/settings"); } return null; }; function SettingsScreen() { const { t } = useTranslation(); const { data: config } = useConfig();...
@@ -62,10 +63,19 @@ export const clientLoader = async ({ request }: Route.ClientLoaderArgs) => { function SettingsScreen() { const { t } = useTranslation(); const { data: config } = useConfig(); + const { data: subscriptionAccess } = useSubscriptionAccess(); const isSaas = config?.APP_MODE === "saas"; /...
frontend/src/routes/settings.tsx
26
TypeScript
0.857
suggestion
489
51
51
false
UI for determining if llm options are enabled
10,665
All-Hands-AI/OpenHands
55,974
Python
amanape
tofarr
): self.metrics_path = get_conversation_stats_filename(conversation_id, user_id) self.file_store = file_store self.conversation_id = conversation_id self.user_id = user_id self._save_lock = Lock() self.service_to_metrics: dict[str, Metrics] = {} self.restore...
Is a `ValueError` a bit harsh? Thinking a warning is nicer, unless you think we need to crash
): self.metrics_path = get_conversation_stats_filename(conversation_id, user_id) self.file_store = file_store self.conversation_id = conversation_id self.user_id = user_id self._save_lock = Lock() self.service_to_metrics: dict[str, Metrics] = {} self.restore...
@@ -36,7 +36,25 @@ def save_metrics(self): return with self._save_lock: - pickled = pickle.dumps(self.service_to_metrics) + # Check for duplicate service IDs between restored and service metrics + duplicate_services = set(self.restored_metrics.keys()) & set( + ...
openhands/server/services/conversation_stats.py
26
Python
0.5
bug
93
51
51
false
(Hotfix): ConversationStats metrics loss for unregistered services
10,676
All-Hands-AI/OpenHands
55,974
Python
enyst
malhotra5
import { useTranslation } from "react-i18next"; import { useMemo, useState } from "react"; import { FaTriangleExclamation } from "react-icons/fa6"; import CloseIcon from "#/icons/close.svg?react"; import { cn } from "#/utils/utils"; interface MaintenanceBannerProps { startTime: string; } export function Maintenance...
Doesn’t this imply that we will show the banner every time we reload the page? We should persist the user’s decision here for now. In the future, I want to consider storing the user’s preference in a userPref cookie or something
import { useTranslation } from "react-i18next"; import { useMemo } from "react"; import { useLocalStorage } from "@uidotdev/usehooks"; import { FaTriangleExclamation } from "react-icons/fa6"; import CloseIcon from "#/icons/close.svg?react"; import { cn } from "#/utils/utils"; interface MaintenanceBannerProps { start...
@@ -11,11 +9,9 @@ interface MaintenanceBannerProps { } export function MaintenanceBanner({ startTime }: MaintenanceBannerProps) { + const [isBannerShown, setIsBannerShown] = useState<boolean>(true);
frontend/src/components/features/maintenance/maintenance-banner.tsx
12
TypeScript
0.5
suggestion
228
37
37
false
fix(frontend): maintenance banner cannot be dismissed (conversation UX improvements)
10,677
All-Hands-AI/OpenHands
55,974
Python
amanape
hieptl
<button type="button" className="py-3 flex items-center gap-3 cursor-pointer hover:bg-[#5C5D62] transition-all duration-300 rounded-lg px-2" onClick={handleLaunchConversation} > <TaskIssueNumber issueNumber={task.issue_number} href={href} /> <div className="w-full flex flex-col ga...
Let’s change the previous button element to something else since it is bad practice to nest a button within a button
return ( <button type="button" data-testid="task-launch-button" className={cn( "pt-[6px] pb-3 text-left flex items-center gap-3 cursor-pointer hover:bg-[#5C5D62] transition-all duration-300 rounded-lg px-2", isCreatingConversation && "cursor-not-allowed", )} disabled=...
@@ -83,6 +87,6 @@ export function TaskCard({ task }: TaskCardProps) { {!isPending && t("HOME$LAUNCH")} {isPending && t("HOME$LOADING")} </button>
frontend/src/components/features/home/tasks/task-card.tsx
26
TypeScript
0.429
suggestion
116
30
30
false
refactor(frontend): make whole suggested tasks clickable (conversation UX improvements)
10,679
All-Hands-AI/OpenHands
55,974
Python
amanape
hieptl
url = f'{self.BASE_URL}/projects/{encoded_name}/repository/branches' params = {'per_page': str(per_page), 'page': str(page)} response, headers = await self._make_request(url, params) branches: list[Branch] = [] for branch_data in response: branch = Branch( ...
Isn't branches just one page, and total meaning total of all pages?
) -> PaginatedBranchesResponse: """Get branches for a repository with pagination""" encoded_name = repository.replace('/', '%2F') url = f'{self.BASE_URL}/projects/{encoded_name}/repository/branches' params = {'per_page': str(per_page), 'page': str(page)} response, headers = ...
@@ -599,24 +599,17 @@ async def get_paginated_branches( ) branches.append(branch) - # Parse pagination headers has_next_page = False - total_count = None - - if 'X-Next-Page' in headers and headers['X-Next-Page']: + if headers.get('Link', ''): ...
openhands/integrations/gitlab/gitlab_service.py
26
Python
0.214
question
67
51
51
false
(Hotfix): Branch pagination for GitLab
10,710
All-Hands-AI/OpenHands
55,974
Python
raymyers
malhotra5
The class is instantiated via get_impl() in openhands.server.shared.py. """ BASE_URL = 'https://api.github.com' token: SecretStr = SecretStr('') refresh = False def __init__( self, user_id: str | None = None, external_auth_id: str | None = None, external_auth_to...
Interestingly, I think OH-GPT-5 noticed something like this. I actually love the level of detail it goes into, whether I like it or not, OpenAI made a darn good model. 😅
The class is instantiated via get_impl() in openhands.server.shared.py. """ BASE_URL = 'https://api.github.com' GRAPHQL_URL = 'https://api.github.com/graphql' token: SecretStr = SecretStr('') refresh = False def __init__( self, user_id: str | None = None, external_a...
@@ -62,6 +63,7 @@ def __init__( if base_domain and base_domain != 'github.com': self.BASE_URL = f'https://{base_domain}/api/v3' + self.GRAPHQL_URL = f'https://{base_domain}/api/graphql'
openhands/integrations/github/github_service.py
26
Python
0.357
suggestion
170
39
41
false
Fix GraphQL URL configuration for GitHub Enterprise Server
10,725
All-Hands-AI/OpenHands
55,974
Python
enyst
malhotra5
"""Unit tests for HTTPClient protocol.""" from unittest.mock import AsyncMock, Mock import httpx import pytest from pydantic import SecretStr from openhands.integrations.protocols.http_client import HTTPClient from openhands.integrations.service_types import ( AuthenticationError, RateLimitError, Request...
@openhands please fix the mocking for this; make sure `TestableHTTPClient` is implementing the `HTTPClient` protocol so that we aren't duplicating so much code also remove the abstract method require `get_user` from the `HTTPClient` protocol; the base mixins should remain unchanged though they should still implement...
"""Unit tests for HTTPClient abstract base class (ABC).""" from typing import Any from unittest.mock import AsyncMock, Mock import httpx import pytest from pydantic import SecretStr from openhands.integrations.protocols.http_client import HTTPClient from openhands.integrations.service_types import ( Authenticati...
@@ -0,0 +1,369 @@ +"""Unit tests for HTTPClient protocol.""" + +from unittest.mock import AsyncMock, Mock + +import httpx +import pytest +from pydantic import SecretStr + +from openhands.integrations.protocols.http_client import HTTPClient +from openhands.integrations.service_types import ( + AuthenticationError, + ...
tests/unit/integrations/protocols/test_http_client.py
20
Python
0.643
refactor
331
45
45
false
refactor: introduce HTTPClient protocol for git service integrations
10,731
All-Hands-AI/OpenHands
55,974
Python
malhotra5
malhotra5
GitHubReposMixin, GitHubResolverMixin, BaseGitService, GitService, InstallationsService, ): """ Assembled GitHub service class combining mixins by feature area. TODO: This doesn't seem a good candidate for the get_impl() pattern. What are the abstract methods we should actually separate...
This and the token above seem new in this PR, was that intended? Why?
GitHubReposMixin, GitHubResolverMixin, BaseGitService, GitService, InstallationsService, ): """ Assembled GitHub service class combining mixins by feature area. TODO: This doesn't seem a good candidate for the get_impl() pattern. What are the abstract methods we should actually separate...
@@ -44,7 +44,11 @@ class GitHubService( BASE_URL = 'https://api.github.com' GRAPHQL_URL = 'https://api.github.com/graphql' token: SecretStr = SecretStr('') - refresh = False + refresh: bool = False + external_auth_id: str | None = None + external_auth_token: SecretStr | None = None + exter...
openhands/integrations/github/github_service.py
26
Python
0.214
question
69
51
51
false
refactor: introduce HTTPClient protocol for git service integrations
10,731
All-Hands-AI/OpenHands
55,974
Python
enyst
malhotra5
"""Tests for Bitbucket repository service URL parsing.""" from unittest.mock import patch import pytest from pydantic import SecretStr from openhands.integrations.bitbucket.bitbucket_service import BitBucketService from openhands.integrations.service_types import OwnerType, Repository from openhands.integrations.ser...
@openhands lets simplify this test file 1. let's only add tests for `search_repository` for now where we're correctly parsing the URL 2. remove all the other tests from here 3. check the parameters during the API call and verify that the right workspace repo combination was included in the call
"""Tests for Bitbucket repository service URL parsing.""" from unittest.mock import patch import pytest from pydantic import SecretStr from openhands.integrations.bitbucket.bitbucket_service import BitBucketService from openhands.integrations.service_types import OwnerType, Repository from openhands.integrations.ser...
@@ -0,0 +1,391 @@ +"""Tests for Bitbucket repository service URL parsing."""
tests/unit/integrations/bitbucket/test_bitbucket_repos.py
1
Python
0.643
refactor
300
26
26
false
Fix fragile URL parsing in Bitbucket service search_repositories method
10,733
All-Hands-AI/OpenHands
55,974
Python
malhotra5
malhotra5
import ReactDOM from "react-dom"; interface ConversationPanelWrapperProps { isOpen: boolean; } export function ConversationPanelWrapper({ isOpen, children, }: React.PropsWithChildren<ConversationPanelWrapperProps>) { if (!isOpen) return null; const portalTarget = document.getElementById("root-outlet"); i...
Why does this style depend on the path?
import ReactDOM from "react-dom"; import { useLocation } from "react-router"; import { cn } from "#/utils/utils"; interface ConversationPanelWrapperProps { isOpen: boolean; } export function ConversationPanelWrapper({ isOpen, children, }: React.PropsWithChildren<ConversationPanelWrapperProps>) { const { pathn...
@@ -8,13 +10,20 @@ export function ConversationPanelWrapper({ isOpen, children, }: React.PropsWithChildren<ConversationPanelWrapperProps>) { + const { pathname } = useLocation(); + if (!isOpen) return null; const portalTarget = document.getElementById("root-outlet"); if (!portalTarget) return null; ...
frontend/src/components/features/conversation-panel/conversation-panel-wrapper.tsx
23
TypeScript
0.071
question
39
23
32
false
refactor(frontend): add margin at both the top and bottom of the conversation list panel
10,741
All-Hands-AI/OpenHands
55,974
Python
amanape
hieptl
) { // Fetch user repositories with pagination const { data: repoData, fetchNextPage, hasNextPage, isLoading, isFetchingNextPage, isError, } = useGitRepositories({ provider, enabled: !disabled, }); // Determine if we should skip search (when input matches selected repository) ...
Hmm, this should work but I’d prefer we pass it to the `disabled` property of the query hook instead of modify the search value. We can address this in a follow-up
) { // Fetch user repositories with pagination const { data: repoData, fetchNextPage, hasNextPage, isLoading, isFetchingNextPage, isError, } = useGitRepositories({ provider, enabled: !disabled, }); // Determine if we should skip search (when input matches selected repository) ...
@@ -25,9 +26,18 @@ export function useRepositoryData( enabled: !disabled, }); + // Determine if we should skip search (when input matches selected repository) + const shouldSkipSearch = useMemo( + () => inputValue === repositoryName, + [repositoryName, inputValue], + ); + // Search repositories wh...
frontend/src/components/features/home/git-repo-dropdown/use-repository-data.tsx
26
TypeScript
0.571
suggestion
163
51
51
false
fix(frontend): double loading spinner after selecting a repo
10,742
All-Hands-AI/OpenHands
55,974
Python
amanape
hieptl
import { Link } from "react-router"; import { useTranslation } from "react-i18next"; import { BrandButton } from "#/components/features/settings/brand-button"; import { useSettings } from "#/hooks/query/use-settings"; export function ConnectToProviderMessage() { const { isLoading } = useSettings(); const { t } = u...
I’d prefer to avoid using absolute positioning here. Maybe we can make the container p-5, flex, and space between the top and button and the bottom instead?
import { Link } from "react-router"; import { useTranslation } from "react-i18next"; import { BrandButton } from "#/components/features/settings/brand-button"; import { useSettings } from "#/hooks/query/use-settings"; export function ConnectToProviderMessage() { const { isLoading } = useSettings(); const { t } = u...
@@ -15,7 +15,12 @@ export function ConnectToProviderMessage() { to="/settings/integrations" className="self-start" > - <BrandButton type="button" variant="primary" isDisabled={isLoading}> + <BrandButton + type="button" + variant="primary" + isDisabled={i...
frontend/src/components/features/home/connect-to-provider-message.tsx
22
TypeScript
0.429
question
156
31
31
false
fix(frontend): home screen component sizes
10,763
All-Hands-AI/OpenHands
55,974
Python
amanape
hieptl
/> ); const renderEmptyState = (emptyInputValue: string) => ( <EmptyState inputValue={emptyInputValue} searchMessage={t(I18nKey.MICROAGENT$NO_REPOSITORY_FOUND)} emptyMessage={t(I18nKey.COMMON$NO_REPOSITORY)} testId="git-repo-dropdown-empty" /> ); return ( <div className...
**Suggestion:** I noticed that this logic is duplicated in both dropdowns. We could extract it into a small shared component to be reused by both. Thank you! 🙏
isHighlighted={itemHighlightedIndex === index} isSelected={itemSelectedItem?.id === item.id} getItemProps={itemGetItemProps} getDisplayText={(repo) => repo.full_name} getItemKey={(repo) => repo.id} /> ); const renderEmptyState = (emptyInputValue: string) => ( <EmptyState ...
@@ -256,7 +261,11 @@ export function GitRepoDropdown({ <div className={cn("relative", className)}> <div className="relative"> <div className="absolute left-2 top-1/2 transform -translate-y-1/2 z-10"> - <RepoIcon width={16} height={16} /> + {isLoadingState ? ( + <div cla...
frontend/src/components/features/home/git-repo-dropdown/git-repo-dropdown.tsx
26
TypeScript
0.429
refactor
160
51
51
false
Fix add repos button
10,788
All-Hands-AI/OpenHands
55,974
Python
hieptl
amanape
llm_config.log_completions = True # modify_params must be False for evaluation purpose, for reproducibility and accurancy of results llm_config.modify_params = False if llm_config is None: raise ValueError(f'Could not find LLM config: --llm_config {args.llm_config}') # Get cond...
We handle the agent_config, which defaults to `None` in `make_metadata` below in the same way like for most other benchmarks. These lines are taken straight from those modules.
llm_config = get_llm_config_arg(args.llm_config, args.config_file) llm_config.log_completions = True # modify_params must be False for evaluation purpose, for reproducibility and accurancy of results llm_config.modify_params = False if llm_config is None: raise ValueError(f'...
@@ -811,20 +812,25 @@ def filter_dataset(dataset: pd.DataFrame, filter_column: str) -> pd.DataFrame: 'No Condenser config provided via EVAL_CONDENSER, using NoOpCondenser.' ) + agent_config = None + if args.agent_config: + agent_config = get_agent_config_arg(args.agent_config, args....
evaluation/benchmarks/swe_bench/run_infer.py
26
Python
0.643
suggestion
177
51
51
false
Fix swe-bench `run_infer.py` config parsing from config.toml
10,792
All-Hands-AI/OpenHands
55,974
Python
Zacharias030
Zacharias030
import { useTranslation } from "react-i18next"; import { useAIConfigOptions } from "#/hooks/query/use-ai-config-options"; import { I18nKey } from "#/i18n/declaration"; import { LoadingSpinner } from "../../loading-spinner"; import { ModalBackdrop } from "../modal-backdrop"; import { SettingsForm } from "./settings-form...
Let’s create a new tailwind class for the shadow style and use it here
import { useTranslation } from "react-i18next"; import { useAIConfigOptions } from "#/hooks/query/use-ai-config-options"; import { I18nKey } from "#/i18n/declaration"; import { LoadingSpinner } from "../../loading-spinner"; import { ModalBackdrop } from "../modal-backdrop"; import { SettingsForm } from "./settings-form...
@@ -21,25 +22,24 @@ export function SettingsModal({ onClose, settings }: SettingsModalProps) { <ModalBackdrop> <div data-testid="ai-config-modal" - className="bg-base-secondary min-w-[384px] m-4 p-6 rounded-xl flex flex-col gap-2 border border-tertiary" + className="bg-[#25272D] min-w...
frontend/src/components/shared/modals/settings/settings-modal.tsx
25
TypeScript
0.286
style
70
50
50
false
feat(frontend): update API provider configuration modal
10,840
All-Hands-AI/OpenHands
55,974
Python
amanape
hieptl
base0A: "#ffcb6b", // booleans, yellow base0B: "#c3e88d", // strings, green base0C: "#89ddff", // support, cyan base0D: "#82aaff", // functions, blue base0E: "#c792ea", // keywords, purple base0F: "#ff5370", // deprecated, red }; export const DOCUMENTATION_URL = { MICROAGENTS: { MICROAGENTS_OVERVIEW:...
Maybe we can create a new `<OpenHandsHelpLink>` component that extends `<HelpLink>` and contains these styles. WDYT?
base0A: "#ffcb6b", // booleans, yellow base0B: "#c3e88d", // strings, green base0C: "#89ddff", // support, cyan base0D: "#82aaff", // functions, blue base0E: "#c792ea", // keywords, purple base0F: "#ff5370", // deprecated, red }; export const DOCUMENTATION_URL = { MICROAGENTS: { MICROAGENTS_OVERVIEW:...
@@ -37,3 +37,13 @@ export const DOCUMENTATION_URL = { "https://docs.all-hands.dev/usage/prompting/microagents-org", }, }; + +export const PRODUCT_URL = { + PRODUCTION: "https://app.all-hands.dev", +}; + +export const SETTINGS_FORM = { + LABEL_CLASSNAME: "text-[11px] font-medium leading-4 tracking-[0.11px]"...
frontend/src/utils/constants.ts
26
TypeScript
0.5
question
116
27
47
false
feat(frontend): update API provider configuration modal
10,840
All-Hands-AI/OpenHands
55,974
Python
amanape
hieptl
conversation_id: str = Depends(validate_conversation_id), user_settings: SettingsStore = Depends(get_user_settings_store), metadata: ConversationMetadata = Depends(get_conversation_metadata), ): # get event store for the conversation event_store = EventStore( sid=conversation_id, file_store=...
I assume there are no other uses to change
user_settings: SettingsStore = Depends(get_user_settings_store), metadata: ConversationMetadata = Depends(get_conversation_metadata), ): # get event store for the conversation event_store = EventStore( sid=conversation_id, file_store=file_store, user_id=metadata.user_id ) # retrieve the...
@@ -397,7 +396,7 @@ async def get_prompt( ) prompt_template = generate_prompt_template(stringified_events) - prompt = generate_prompt(llm_config, prompt_template, conversation_id)
openhands/server/routes/manage_conversations.py
26
Python
0.143
suggestion
42
51
51
false
More Type Safety
10,848
All-Hands-AI/OpenHands
55,974
Python
raymyers
tofarr
has_write_access = await self._user_has_write_access_to_repo( project_id=str(project_id), user_id=user_id ) logger.info( f'[GitLab]: {username} access in {selected_project}: {has_write_access}' ) # Check if the user has write access to the repository ...
In other places we raise when it's the wrong class, which is arguably better, but still just one runtime error vs another because it would soon try to call a non-existent method.
) has_write_access = await self._user_has_write_access_to_repo( project_id=str(project_id), user_id=user_id ) logger.info( f'[GitLab]: {username} access in {selected_project}: {has_write_access}' ) # Check if the user has write access to the repo...
@@ -119,7 +123,9 @@ async def send_message(self, message: Message, gitlab_view: ResolverViewInterfac gitlab_view: The GitLab view object containing issue/PR/comment info """ keycloak_user_id = gitlab_view.user_info.keycloak_user_id - gitlab_service = GitLabServiceImpl(external_auth...
enterprise/integrations/gitlab/gitlab_manager.py
26
Python
0.571
bug
178
51
51
false
chore - MyPy check Enterprise with OpenHands
10,858
All-Hands-AI/OpenHands
55,974
Python
raymyers
raymyers
if (isDisabled) return; e.preventDefault(); setIsDragOver(true); }; const handleDragLeave = (e: React.DragEvent) => { if (isDisabled) return; e.preventDefault(); // Only remove drag-over class if we're leaving the container entirely if (!chatContainerRef.current?.contains(e.relatedTarge...
Can we just pass this to the disabled prop of the button where this handler is called instead?
if (isDisabled) return; e.preventDefault(); setIsDragOver(true); }; const handleDragLeave = (e: React.DragEvent) => { if (isDisabled) return; e.preventDefault(); // Only remove drag-over class if we're leaving the container entirely if (!chatContainerRef.current?.contains(e.relatedTarge...
@@ -198,6 +198,10 @@ export function CustomChatInput({ // Send button click handler const handleSubmit = () => { + if (disabled) {
frontend/src/components/features/chat/custom-chat-input.tsx
26
TypeScript
0.429
question
94
51
51
false
refactor(frontend): enable message drafting during page load
10,879
All-Hands-AI/OpenHands
55,974
Python
amanape
hieptl
self._vscode_enabled = any( isinstance(plugin, VSCodeRequirement) for plugin in self.plugins ) # Load mixins FileEditRuntimeMixin.__init__( self, enable_llm_editor=config.get_agent_config().enable_llm_editor, llm_registry=llm_registry, ...
I'm pretty sure that because the base security analyzer has a `set_event_stream` method this conditional will always be true.
self._vscode_enabled = any( isinstance(plugin, VSCodeRequirement) for plugin in self.plugins ) # Load mixins FileEditRuntimeMixin.__init__( self, enable_llm_editor=config.get_agent_config().enable_llm_editor, llm_registry=llm_registry, ...
@@ -199,6 +199,10 @@ def __init__( self.config.security.security_analyzer, SecurityAnalyzer ) self.security_analyzer = analyzer_cls() + if self.event_stream and hasattr( + self.security_analyzer, 'set_event_stream' + ):
openhands/runtime/base.py
26
Python
0.714
security
125
51
51
false
feat: Add Cygnal integration
10,898
All-Hands-AI/OpenHands
55,974
Python
csmith49
eliotjones1
"""GraySwan security analyzer for OpenHands.""" import asyncio import os from typing import Any, Optional import aiohttp from fastapi import Request from openhands.core.logger import openhands_logger as logger from openhands.events.action.action import Action, ActionSecurityRisk from openhands.events.event_store_abc...
Minor nit, but we prefer `* | None` to `Optional[*]`.
"""GraySwan security analyzer for OpenHands.""" import asyncio import os from typing import Any import aiohttp from fastapi import Request from openhands.core.logger import openhands_logger as logger from openhands.events.action.action import Action, ActionSecurityRisk from openhands.events.event_store_abc import Ev...
@@ -0,0 +1,197 @@ +"""GraySwan security analyzer for OpenHands.""" + +import asyncio +import os +from typing import Any, Optional + +import aiohttp +from fastapi import Request + +from openhands.core.logger import openhands_logger as logger +from openhands.events.action.action import Action, ActionSecurityRisk +from op...
openhands/security/grayswan/analyzer.py
25
Python
0.429
suggestion
53
50
50
false
feat: Add Cygnal integration
10,898
All-Hands-AI/OpenHands
55,974
Python
csmith49
eliotjones1
class GraySwanAnalyzer(SecurityAnalyzer): """Security analyzer using GraySwan's Cygnal API for AI safety monitoring.""" def __init__( self, history_limit: int = 20, max_message_chars: int = 30000, timeout: int = 30, session: Optional[aiohttp.ClientSession] = None, ...
Any particular reason to keep these as environment variables instead of some config-level arg like `history_limit`?
from openhands.security.grayswan.utils import convert_events_to_openai_messages class GraySwanAnalyzer(SecurityAnalyzer): """Security analyzer using GraySwan's Cygnal API for AI safety monitoring.""" def __init__( self, history_limit: int = 20, max_message_chars: int = 30000, ...
@@ -0,0 +1,197 @@ +"""GraySwan security analyzer for OpenHands.""" + +import asyncio +import os +from typing import Any, Optional + +import aiohttp +from fastapi import Request + +from openhands.core.logger import openhands_logger as logger +from openhands.events.action.action import Action, ActionSecurityRisk +from op...
openhands/security/grayswan/analyzer.py
26
Python
0.571
question
115
51
51
false
feat: Add Cygnal integration
10,898
All-Hands-AI/OpenHands
55,974
Python
csmith49
eliotjones1
return ActionSecurityRisk.UNKNOWN except Exception as e: logger.error(f'GraySwan security analysis failed: {e}') return ActionSecurityRisk.UNKNOWN async def handle_api_request(self, request: Request) -> Any: """Handle incoming API requests for configuration or we...
I think the assumption being made here is that the events in the stream are exactly what the LLM in the agent sees -- but that's not quite correct! Our context management system acts between the event stream and the agent to trim extra events, insert summaries, and sometimes mask out big observations. If you want to...
logger.error(f'GraySwan API error {resp.status}: {error_text}') return ActionSecurityRisk.UNKNOWN except asyncio.TimeoutError: logger.error('GraySwan API request timed out') return ActionSecurityRisk.UNKNOWN except Exception as e: ...
@@ -0,0 +1,197 @@ +"""GraySwan security analyzer for OpenHands.""" + +import asyncio +import os +from typing import Any, Optional + +import aiohttp +from fastapi import Request + +from openhands.core.logger import openhands_logger as logger +from openhands.events.action.action import Action, ActionSecurityRisk +from op...
openhands/security/grayswan/analyzer.py
26
Python
1
bug
717
48
51
false
feat: Add Cygnal integration
10,898
All-Hands-AI/OpenHands
55,974
Python
csmith49
eliotjones1
import { useTranslation } from "react-i18next"; export function GuideMessage() { const { t } = useTranslation(); return ( <div className="w-full flex items-center justify-center"> <div className="w-fit flex items-center justify-center gap-1 px-[15px] rounded-[12px] bg-[#454545] leading-5 text-white text...
Do you think we can reduce the nested elements and join the common styles? Would prefer to have a single wrapper element than 3 divs.
import { useTranslation } from "react-i18next"; export function GuideMessage() { const { t } = useTranslation(); return ( <div className="w-fit flex flex-col md:flex-row items-start md:items-center justify-center gap-1 rounded-[12px] bg-[#454545] leading-5 text-white text-[15px] font-normal m-1 md:h-9.5 px-4 ...
@@ -0,0 +1,22 @@ +import { useTranslation } from "react-i18next"; + +export function GuideMessage() { + const { t } = useTranslation(); + + return ( + <div className="w-full flex items-center justify-center"> + <div className="w-fit flex items-center justify-center gap-1 px-[15px] rounded-[12px] bg-[#454545] ...
frontend/src/components/features/home/home-header/guide-message.tsx
9
TypeScript
0.429
suggestion
133
23
19
false
refactor(frontend): home header component
10,930
All-Hands-AI/OpenHands
55,974
Python
amanape
hieptl
gap: "default", minHeight: "default", }, }, ); interface CardProps extends VariantProps<typeof cardVariants> { children: ReactNode; className?: string; testId?: string; } export function Card({ children, className = "", testId, gap, minHeight, }: CardProps) { return ( <section ...
```suggestion <div data-testid={testId} className={cn(cardVariants({ gap, minHeight }), className)} > {children} </div> ``` Prefer `<section>` only when the card represents a document section with its own heading and role in page structure
gap: "default", minHeight: "default", }, }, ); interface CardProps extends VariantProps<typeof cardVariants> { children: ReactNode; className?: string; testId?: string; } export function Card({ children, className = "", testId, gap, minHeight, }: CardProps) { return ( <div ...
@@ -0,0 +1,46 @@ +import { ReactNode } from "react"; +import { cva, type VariantProps } from "class-variance-authority"; +import { cn } from "#/utils/utils"; + +const cardVariants = cva( + "w-full flex flex-col rounded-[12px] p-[20px] border border-[#727987] bg-[#26282D] relative", + { + variants: { + gap: { ...
frontend/src/ui/card.tsx
26
TypeScript
0.857
suggestion
270
29
29
false
refactor(frontend): new conversation component
10,937
All-Hands-AI/OpenHands
55,974
Python
amanape
hieptl
* The `old_str` parameter should match EXACTLY one or more consecutive lines from the original file. Be mindful of whitespaces! * If the `old_str` parameter is not unique in the file, the replacement will not be performed. Make sure to include enough context in `old_str` to make it unique * The `new_str` parameter shou...
```suggestion parts = mount.split(':') if parts: return parts[0] ```
* The `old_str` parameter should match EXACTLY one or more consecutive lines from the original file. Be mindful of whitespaces! * If the `old_str` parameter is not unique in the file, the replacement will not be performed. Make sure to include enough context in `old_str` to make it unique * The `new_str` parameter shou...
@@ -52,9 +55,38 @@ """ +def _get_workspace_mount_path_from_env() -> str: + """Get the workspace mount path from SANDBOX_VOLUMES environment variable. + + Returns: + The workspace mount path in sandbox, defaults to '/workspace' if not found. + """ + sandbox_volumes = os.environ.get('SANDBOX_VOLUM...
openhands/agenthub/codeact_agent/tools/str_replace_editor.py
26
Python
0.714
suggestion
100
51
51
false
Update str_replace_editor tool to use dynamic workspace path from SANDBOX_VOLUMES
10,965
All-Hands-AI/OpenHands
55,974
Python
li-boxuan
li-boxuan
{t(I18nKey.CONVERSATION$CACHE_HIT)} </span> <span className="text-right"> {usage.cache_read_tokens.toLocaleString()} </span> <span className="text-neutral-400"> {t(I18nKey.CONVERSATION$CACHE_WRITE)} </span> <span className="text-right"> ...
These two components look like they can be a shareable component
</span> <span className="text-right"> {usage.cache_read_tokens.toLocaleString()} </span> <span className="text-neutral-400"> {t(I18nKey.CONVERSATION$CACHE_WRITE)} </span> <span className="text-right"> {usage.cache_write_tokens.toLocaleString(...
@@ -0,0 +1,55 @@ +import { useTranslation } from "react-i18next"; +import { I18nKey } from "#/i18n/declaration"; + +interface UsageSectionProps { + usage: { + prompt_tokens: number; + completion_tokens: number; + cache_read_tokens: number; + cache_write_tokens: number; + }; +} + +export function UsageSect...
frontend/src/components/features/conversation/metrics-modal/usage-section.tsx
26
TypeScript
0.214
suggestion
64
30
27
false
refactor(frontend): metrics modal
10,968
All-Hands-AI/OpenHands
55,974
Python
amanape
hieptl
import { useSelector } from "react-redux"; import { useWindowSize } from "@uidotdev/usehooks"; import { RootState } from "#/store"; import { MobileLayout } from "./mobile-layout"; import { DesktopLayoutWithPanel } from "./desktop-layout-with-panel"; import { DesktopLayoutWithoutPanel } from "./desktop-layout-without-pa...
I think we can merge these two since they contain duplicate elements. It really is just conditionally hiding the right panel
import { useSelector } from "react-redux"; import { useWindowSize } from "@uidotdev/usehooks"; import { RootState } from "#/store"; import { MobileLayout } from "./mobile-layout"; import { DesktopLayout } from "./desktop-layout"; export function ConversationMain() { const { width } = useWindowSize(); const isRight...
@@ -0,0 +1,23 @@ +import { useSelector } from "react-redux"; +import { useWindowSize } from "@uidotdev/usehooks"; +import { RootState } from "#/store"; +import { MobileLayout } from "./mobile-layout"; +import { DesktopLayoutWithPanel } from "./desktop-layout-with-panel"; +import { DesktopLayoutWithoutPanel } from "./de...
frontend/src/components/features/conversation/conversation-main/conversation-main.tsx
22
TypeScript
0.357
refactor
124
24
19
false
refactor(frontend): conversation main
10,985
All-Hands-AI/OpenHands
55,974
Python
amanape
hieptl
import { screen, waitFor, within } from "@testing-library/react"; import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; import { QueryClientConfig } from "@tanstack/react-query"; import userEvent from "@testing-library/user-event"; import { createRoutesStub } from "react-router"; import React from "...
I think you can just replace the `renderWithProviders` function with the regular `render` from the testing library now
import { screen, waitFor, within } from "@testing-library/react"; import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; import userEvent from "@testing-library/user-event"; import { createRoutesStub } from "react-router"; import React from "react"; import { renderWithQueryAndI18n } from "test-utils"...
@@ -20,13 +20,7 @@ describe("ConversationPanel", () => { const renderConversationPanel = (config?: QueryClientConfig) => renderWithProviders(<RouterStub />, { - preloadedState: { - metrics: { - cost: null, - max_budget_per_task: null, - usage: null, - }, - },...
frontend/__tests__/components/features/conversation-panel/conversation-panel.test.tsx
24
TypeScript
0.571
suggestion
118
49
49
false
refactor(frontend): migration of metrics-slice.ts to zustand
11,018
All-Hands-AI/OpenHands
55,974
Python
amanape
hieptl
raise async def connect_stdio(self, server: MCPStdioServerConfig, timeout: float = 30.0): """Connect to MCP server using stdio transport""" try: transport = StdioTransport( command=server.command, args=server.args or [], env=server.env ) ...
Do we need this `timeout` param? I think we only use `server_timeout`.
) raise async def connect_stdio(self, server: MCPStdioServerConfig, timeout: float = 30.0): """Connect to MCP server using stdio transport.""" try: transport = StdioTransport( command=server.command, args=server.args or [], env=server.env ...
@@ -144,13 +145,40 @@ async def connect_stdio(self, server: MCPStdioServerConfig, timeout: float = 30. ) raise - async def call_tool(self, tool_name: str, args: dict) -> CallToolResult: - """Call a tool on the MCP server.""" + async def call_tool( + self, tool_name: str, ...
openhands/mcp/client.py
26
Python
0.429
question
70
51
51
false
feat: Add configurable timeouts for MCP tool invocations (Good first issues: #10684)
11,029
All-Hands-AI/OpenHands
55,974
Python
ryanhoangt
tejas-goyal
server_name=server_name, server_type='stdio', error_message=error_msg, exception_details=str(e), ) raise async def call_tool( self, tool_name: str, args: dict, timeout: float | None = None ) -> CallToolResult: ...
I think we should prefer top-level import here.
mcp_error_collector.add_error( server_name=server_name, server_type='stdio', error_message=error_msg, exception_details=str(e), ) raise async def call_tool(self, tool_name: str, args: dict) -> CallToolResult: ...
@@ -144,13 +145,40 @@ async def connect_stdio(self, server: MCPStdioServerConfig, timeout: float = 30. ) raise - async def call_tool(self, tool_name: str, args: dict) -> CallToolResult: - """Call a tool on the MCP server.""" + async def call_tool( + self, tool_name: str, ...
openhands/mcp/client.py
26
Python
0.143
suggestion
47
45
39
false
feat: Add configurable timeouts for MCP tool invocations (Good first issues: #10684)
11,029
All-Hands-AI/OpenHands
55,974
Python
ryanhoangt
tejas-goyal