From 8fece984816711e46cc698042e9897987a1bb9c1 Mon Sep 17 00:00:00 2001 From: Benedikt Ritter Date: Fri, 13 Nov 2026 16:04:22 +0100 Subject: [PATCH] refactor: create a unified TUI with screen routing - tui mode is started when testlens is called without a command - all sub commands commands render CLI mode now - hide the --mode flag --- .../java/app/testlens/cli/CommandSupport.java | 8 +- .../java/app/testlens/cli/FlakesCommand.java | 46 +- .../java/app/testlens/cli/GitHubClient.java | 58 ++ src/main/java/app/testlens/cli/Mode.java | 9 + src/main/java/app/testlens/cli/PrCommand.java | 63 +- .../app/testlens/cli/StatisticsCommand.java | 54 +- .../java/app/testlens/cli/TestCommand.java | 56 +- src/main/java/app/testlens/cli/Testlens.java | 95 +- .../java/app/testlens/cli/tui/ApiErrors.java | 18 + .../java/app/testlens/cli/tui/FlakesTui.java | 41 - .../java/app/testlens/cli/tui/GlobalKeys.java | 43 + .../java/app/testlens/cli/tui/HomeScreen.java | 754 ++++++++++++++++ .../java/app/testlens/cli/tui/PrScreen.java | 39 + src/main/java/app/testlens/cli/tui/PrTui.java | 30 - .../app/testlens/cli/tui/ScreenRouter.java | 35 + .../app/testlens/cli/tui/StatisticsTui.java | 84 -- .../testlens/cli/tui/TestExecutionsTui.java | 58 -- .../testlens/cli/tui/TestSearchScreen.java | 175 ++++ .../app/testlens/cli/tui/TestlensTui.java | 94 ++ .../java/app/testlens/cli/tui/TuiSession.java | 29 + .../cli/tui/controller/FlakesController.java | 14 +- .../controller/FlakinessTableController.java | 18 +- .../tui/controller/ListPaneController.java | 85 ++ .../cli/tui/controller/PrTuiController.java | 29 +- .../tui/controller/TestSearchController.java | 81 ++ ...inessView.java => FlakinessTableView.java} | 98 +- .../app/testlens/cli/GitHubClientTest.java | 46 + .../java/app/testlens/cli/TestlensTest.java | 32 + .../testlens/cli/tui/FlakinessViewTest.java | 121 --- .../app/testlens/cli/tui/HomeScreenTest.java | 853 ++++++++++++++++++ .../testlens/cli/tui/ScreenRouterTest.java | 127 +++ 31 files changed, 2668 insertions(+), 625 deletions(-) create mode 100644 src/main/java/app/testlens/cli/GitHubClient.java create mode 100644 src/main/java/app/testlens/cli/Mode.java create mode 100644 src/main/java/app/testlens/cli/tui/ApiErrors.java delete mode 100644 src/main/java/app/testlens/cli/tui/FlakesTui.java create mode 100644 src/main/java/app/testlens/cli/tui/GlobalKeys.java create mode 100644 src/main/java/app/testlens/cli/tui/HomeScreen.java create mode 100644 src/main/java/app/testlens/cli/tui/PrScreen.java delete mode 100644 src/main/java/app/testlens/cli/tui/PrTui.java delete mode 100644 src/main/java/app/testlens/cli/tui/StatisticsTui.java delete mode 100644 src/main/java/app/testlens/cli/tui/TestExecutionsTui.java create mode 100644 src/main/java/app/testlens/cli/tui/TestSearchScreen.java create mode 100644 src/main/java/app/testlens/cli/tui/TestlensTui.java create mode 100644 src/main/java/app/testlens/cli/tui/TuiSession.java create mode 100644 src/main/java/app/testlens/cli/tui/controller/ListPaneController.java create mode 100644 src/main/java/app/testlens/cli/tui/controller/TestSearchController.java rename src/main/java/app/testlens/cli/tui/view/{FlakinessView.java => FlakinessTableView.java} (76%) create mode 100644 src/test/java/app/testlens/cli/GitHubClientTest.java create mode 100644 src/test/java/app/testlens/cli/TestlensTest.java delete mode 100644 src/test/java/app/testlens/cli/tui/FlakinessViewTest.java create mode 100644 src/test/java/app/testlens/cli/tui/HomeScreenTest.java diff --git a/src/main/java/app/testlens/cli/CommandSupport.java b/src/main/java/app/testlens/cli/CommandSupport.java index 42ee55a..f591ab2 100644 --- a/src/main/java/app/testlens/cli/CommandSupport.java +++ b/src/main/java/app/testlens/cli/CommandSupport.java @@ -9,6 +9,7 @@ import java.util.List; import java.util.regex.Pattern; import org.jspecify.annotations.Nullable; +import picocli.CommandLine.Model.CommandSpec; /** * Shared plumbing of the commands: repository resolution, token handling and API client setup. The convention @@ -25,6 +26,11 @@ private CommandSupport() {} return repoOption != null ? repoOption.split("/", 2) : parseRemote(gitRemoteUrl()); } + /** The root command instance, which holds the inherited connection options ({@code --repo} &c.). */ + static Testlens root(@Nullable CommandSpec spec) { + return (Testlens) requireNonNull(spec).root().userObject(); + } + /** Parses owner/repo from a GitHub remote URL. */ static String @Nullable [] parseRemote(@Nullable String url) { if (url == null) { @@ -54,7 +60,7 @@ public static String filterSuffix(@Nullable String branch, @Nullable String work } /** Display name of a test, skipping the first display name which denotes the test engine. */ - static String testName(List displayNames) { + public static String testName(List displayNames) { return String.join(" > ", displayNames.subList(Math.min(1, displayNames.size()), displayNames.size())); } diff --git a/src/main/java/app/testlens/cli/FlakesCommand.java b/src/main/java/app/testlens/cli/FlakesCommand.java index 50e6228..f2d8c16 100644 --- a/src/main/java/app/testlens/cli/FlakesCommand.java +++ b/src/main/java/app/testlens/cli/FlakesCommand.java @@ -3,7 +3,6 @@ import static app.testlens.cli.CommandSupport.apiClient; import static app.testlens.cli.CommandSupport.filterSuffix; -import static app.testlens.cli.CommandSupport.isInteractiveTerminal; import static app.testlens.cli.CommandSupport.resolveRepo; import static app.testlens.cli.util.Console.clearProgress; import static app.testlens.cli.util.Console.showProgress; @@ -11,12 +10,10 @@ import static java.util.Comparator.comparing; import static java.util.Objects.requireNonNull; -import app.testlens.cli.TestCommand.Mode; import app.testlens.cli.client.ApiException; import app.testlens.cli.client.api.TestsApi; import app.testlens.cli.client.model.FlakeResponse; import app.testlens.cli.client.model.TestExecutionResponse; -import app.testlens.cli.tui.FlakesTui; import app.testlens.cli.tui.controller.FlakesController; import app.testlens.cli.tui.model.TestInfo; import app.testlens.cli.util.Console; @@ -64,41 +61,15 @@ public class FlakesCommand implements Callable { @Nullable String job; - @Option( - names = "--repo", - description = "Repository as owner/repo (defaults to the GitHub remote 'origin' of the current directory)" - ) - @Nullable - String repo; - - @Option( - names = "--token", - description = "GitHub access token (defaults to $GITHUB_TOKEN or $GH_TOKEN)", - defaultValue = "${env:GITHUB_TOKEN:-${env:GH_TOKEN}}" - ) - @Nullable - String token; - - @Option( - names = "--mode", - description = "Output mode: ${COMPLETION-CANDIDATES} (default: ${DEFAULT-VALUE}, uses the TUI in an interactive terminal)", - defaultValue = "auto" - ) - Mode mode = Mode.AUTO; - - @Option( - names = "--base-url", - description = "API base URL", - defaultValue = "https://api.testlens.app", - hidden = true - ) - @Nullable - String baseUrl; - @Override public Integer call() throws Exception { var out = requireNonNull(spec).commandLine().getOut(); var err = spec.commandLine().getErr(); + var root = CommandSupport.root(spec); + var repo = root.repo; + var token = root.token; + var baseUrl = root.baseUrl; + var mode = root.mode; if (token == null || token.isBlank()) { err.println("No GitHub token provided (use --token or set GITHUB_TOKEN)"); return 2; @@ -113,18 +84,13 @@ public Integer call() throws Exception { var ansi = spec.commandLine().getColorScheme().ansi(); var api = new TestsApi(apiClient(token, requireNonNull(baseUrl))); try { - var tui = mode == Mode.TUI || (mode == Mode.AUTO && isInteractiveTerminal()); showProgress(out, ansi, "Fetching test..."); var test = TestInfo.of(api.getTest(owner, repoName, id)); clearProgress(out, ansi); showProgress(out, ansi, "Fetching flakes..."); var flakes = fetchFlakes(api, owner, repoName, id, branch, workUnit, job); clearProgress(out, ansi); - if (tui) { - FlakesTui.run(test, branch, workUnit, job, flakes); - } else { - printFlakes(out, ansi, test, branch, workUnit, job, flakes); - } + printFlakes(out, ansi, test, branch, workUnit, job, flakes); return 0; } catch (ApiException e) { clearProgress(out, ansi); diff --git a/src/main/java/app/testlens/cli/GitHubClient.java b/src/main/java/app/testlens/cli/GitHubClient.java new file mode 100644 index 0000000..174f300 --- /dev/null +++ b/src/main/java/app/testlens/cli/GitHubClient.java @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: Apache-2.0 +package app.testlens.cli; + +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse.BodyHandlers; +import java.time.Duration; +import java.util.List; +import org.jspecify.annotations.Nullable; + +/** + * The minimal GitHub REST client for the TUI's discovery panes: only what the testlens API cannot serve (the list of + * open pull requests). Failures are expected and surfaced as "unavailable" panes, never as errors. + */ +public final class GitHubClient { + + /** One open pull request, as shown in the home screen's PR pane. */ + public record OpenPullRequest(long number, String title, boolean draft) {} + + private static final Duration TIMEOUT = Duration.ofSeconds(10); + + private final String baseUrl; + private final @Nullable String token; + private final HttpClient http = HttpClient.newBuilder().connectTimeout(TIMEOUT).build(); + + public GitHubClient(String baseUrl, @Nullable String token) { + this.baseUrl = baseUrl; + this.token = token; + } + + /** The repository's open pull requests, newest first as GitHub returns them. */ + public List openPullRequests(String owner, String repo) throws IOException, InterruptedException { + var uri = baseUrl + "/repos/" + owner + "/" + repo + "/pulls?state=open&per_page=25"; + var builder = HttpRequest.newBuilder(URI.create(uri)) + .timeout(TIMEOUT) + .header("Accept", "application/vnd.github+json") + .header("X-GitHub-Api-Version", "2022-11-28"); + if (token != null && !token.isBlank()) { + builder.header("Authorization", "Bearer " + token); + } + var request = builder.GET().build(); + var response = http.send(request, BodyHandlers.ofString()); + if (response.statusCode() != 200) { + throw new IOException("GitHub returned HTTP " + response.statusCode()); + } + return parsePullRequests(response.body()); + } + + static List parsePullRequests(String json) throws IOException { + try { + return List.of(new tools.jackson.databind.json.JsonMapper().readValue(json, OpenPullRequest[].class)); + } catch (tools.jackson.core.JacksonException e) { + throw new IOException("Parsing the GitHub pull requests failed", e); + } + } +} diff --git a/src/main/java/app/testlens/cli/Mode.java b/src/main/java/app/testlens/cli/Mode.java new file mode 100644 index 0000000..1a82925 --- /dev/null +++ b/src/main/java/app/testlens/cli/Mode.java @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: Apache-2.0 +package app.testlens.cli; + +/** Whether a command renders the TUI or prints plain output; exposed via the hidden {@code --mode} escape hatch. */ +public enum Mode { + AUTO, + TUI, + CLI, +} diff --git a/src/main/java/app/testlens/cli/PrCommand.java b/src/main/java/app/testlens/cli/PrCommand.java index a30f392..b7d1eb8 100644 --- a/src/main/java/app/testlens/cli/PrCommand.java +++ b/src/main/java/app/testlens/cli/PrCommand.java @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 package app.testlens.cli; -import static app.testlens.cli.CommandSupport.isInteractiveTerminal; +import static app.testlens.cli.CommandSupport.apiClient; import static app.testlens.cli.CommandSupport.resolveRepo; import static app.testlens.cli.util.Console.clearProgress; import static app.testlens.cli.util.Console.diffLine; @@ -12,14 +12,12 @@ import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.toList; -import app.testlens.cli.client.ApiClient; import app.testlens.cli.client.ApiException; import app.testlens.cli.client.api.PullRequestsApi; import app.testlens.cli.client.model.ExecutedTest; import app.testlens.cli.client.model.Execution; import app.testlens.cli.client.model.PullRequestResponse; import app.testlens.cli.client.model.PullRequestTestsResponse; -import app.testlens.cli.tui.PrTui; import app.testlens.cli.util.Console; import app.testlens.cli.util.TextDiff; import app.testlens.cli.util.TimeFormat; @@ -52,46 +50,19 @@ public static boolean isStackFrame(String line) { @Parameters(description = "Pull request number", arity = "1") int number; - @Option( - names = "--repo", - description = "Repository as owner/repo (defaults to the GitHub remote 'origin' of the current directory)" - ) - @Nullable - String repo; - - @Option( - names = "--token", - description = "GitHub access token (defaults to $GITHUB_TOKEN or $GH_TOKEN)", - defaultValue = "${env:GITHUB_TOKEN:-${env:GH_TOKEN}}" - ) - @Nullable - String token; - @Option(names = "--sha", description = "Commit sha to show the tests of (defaults to the head of the pull request)") @Nullable String sha; - @Option( - names = "--mode", - description = "Output mode: ${COMPLETION-CANDIDATES} (default: ${DEFAULT-VALUE}, uses the TUI in an interactive terminal)", - defaultValue = "auto" - ) - Mode mode = Mode.AUTO; - - @Option( - names = "--base-url", - description = "API base URL", - defaultValue = "https://api.testlens.app", - hidden = true - ) - @Nullable - String baseUrl; - @Override public Integer call() throws Exception { var commandLine = requireNonNull(spec).commandLine(); var out = commandLine.getOut(); var err = commandLine.getErr(); + var root = CommandSupport.root(spec); + var repo = root.repo; + var token = root.token; + var baseUrl = root.baseUrl; if (token == null || token.isBlank()) { err.println("No GitHub token provided (use --token or set GITHUB_TOKEN)"); return 2; @@ -101,30 +72,20 @@ public Integer call() throws Exception { err.println("Cannot determine repository (use --repo owner/repo)"); return 2; } - var apiClient = new ApiClient(); - apiClient.updateBaseUri(requireNonNull(baseUrl)); - apiClient.setRequestInterceptor(request -> request.header("Authorization", "Bearer " + token)); - var api = new PullRequestsApi(apiClient); + var api = new PullRequestsApi(apiClient(token, requireNonNull(baseUrl))); var ansi = commandLine.getColorScheme().ansi(); try { - var tui = mode == Mode.TUI || (mode == Mode.AUTO && isInteractiveTerminal()); showProgress(out, ansi, "Fetching pull request..."); var pr = api.getPullRequest(ownerAndRepo[0], ownerAndRepo[1], number); clearProgress(out, ansi); var prUrl = "https://github.com/" + ownerAndRepo[0] + "/" + ownerAndRepo[1] + "/pull/" + pr.getNumber(); - if (!tui) { - printPullRequest(out, ansi, pr, prUrl); - out.println(); - } + printPullRequest(out, ansi, pr, prUrl); + out.println(); showProgress(out, ansi, "Fetching tests..."); var tests = api.getPullRequestTests(ownerAndRepo[0], ownerAndRepo[1], number, sha != null ? sha : pr.getHeadSha()); clearProgress(out, ansi); - if (tui) { - PrTui.run(pr, tests); - } else { - printTests(out, ansi, tests); - } + printTests(out, ansi, tests); return 0; } catch (ApiException e) { clearProgress(out, ansi); @@ -139,12 +100,6 @@ public Integer call() throws Exception { } } - enum Mode { - AUTO, - TUI, - CLI - } - static String testName(ExecutedTest test) { // skip the first display name which denotes the test engine, like in the PR comment var displayNames = test.getDisplayNames(); diff --git a/src/main/java/app/testlens/cli/StatisticsCommand.java b/src/main/java/app/testlens/cli/StatisticsCommand.java index 64000d0..3e591e9 100644 --- a/src/main/java/app/testlens/cli/StatisticsCommand.java +++ b/src/main/java/app/testlens/cli/StatisticsCommand.java @@ -2,7 +2,6 @@ package app.testlens.cli; import static app.testlens.cli.CommandSupport.apiClient; -import static app.testlens.cli.CommandSupport.isInteractiveTerminal; import static app.testlens.cli.CommandSupport.resolveRepo; import static app.testlens.cli.util.Console.clearProgress; import static app.testlens.cli.util.Console.showProgress; @@ -11,10 +10,8 @@ import app.testlens.cli.client.ApiException; import app.testlens.cli.client.api.StatisticsApi; -import app.testlens.cli.client.api.TestsApi; import app.testlens.cli.client.model.FlakinessStatisticResponse; import app.testlens.cli.client.model.FlakyCount; -import app.testlens.cli.tui.StatisticsTui; import app.testlens.cli.tui.model.TestInfo; import java.util.List; import java.util.concurrent.Callable; @@ -56,41 +53,14 @@ static class Flakiness implements Callable { @Nullable String branch; - @Option( - names = "--repo", - description = "Repository as owner/repo (defaults to the GitHub remote 'origin' of the current directory)" - ) - @Nullable - String repo; - - @Option( - names = "--token", - description = "GitHub access token (defaults to $GITHUB_TOKEN or $GH_TOKEN)", - defaultValue = "${env:GITHUB_TOKEN:-${env:GH_TOKEN}}" - ) - @Nullable - String token; - - @Option( - names = "--mode", - description = "Output mode: ${COMPLETION-CANDIDATES} (default: ${DEFAULT-VALUE}, uses the TUI in an interactive terminal)", - defaultValue = "auto" - ) - Mode mode = Mode.AUTO; - - @Option( - names = "--base-url", - description = "API base URL", - defaultValue = "https://api.testlens.app", - hidden = true - ) - @Nullable - String baseUrl; - @Override public Integer call() throws Exception { var out = requireNonNull(spec).commandLine().getOut(); var err = spec.commandLine().getErr(); + var root = CommandSupport.root(spec); + var repo = root.repo; + var token = root.token; + var baseUrl = root.baseUrl; if (token == null || token.isBlank()) { err.println("No GitHub token provided (use --token or set GITHUB_TOKEN)"); return 2; @@ -103,10 +73,8 @@ public Integer call() throws Exception { var owner = ownerAndRepo[0]; var repoName = ownerAndRepo[1]; var ansi = spec.commandLine().getColorScheme().ansi(); - var apiClient = apiClient(token, requireNonNull(baseUrl)); + var api = new StatisticsApi(apiClient(token, requireNonNull(baseUrl))); try { - var api = new StatisticsApi(apiClient); - var tui = mode == Mode.TUI || (mode == Mode.AUTO && isInteractiveTerminal()); showProgress(out, ansi, "Fetching statistics..."); var statistics = api.getFlakinessStatistics(owner, repoName, branch, null, null); clearProgress(out, ansi); @@ -114,11 +82,7 @@ public Integer call() throws Exception { var shownBranch = branch != null ? branch : statistics.stream().findFirst().map(FlakinessStatisticResponse::getBranch).orElse(null); - if (tui) { - StatisticsTui.run(new TestsApi(apiClient), owner, repoName, shownBranch, statistics); - } else { - printStatistics(out, ansi, shownBranch, statistics); - } + printStatistics(out, ansi, shownBranch, statistics); return 0; } catch (ApiException e) { clearProgress(out, ansi); @@ -132,12 +96,6 @@ public Integer call() throws Exception { return 1; } } - - enum Mode { - AUTO, - TUI, - CLI - } } static void printStatistics( diff --git a/src/main/java/app/testlens/cli/TestCommand.java b/src/main/java/app/testlens/cli/TestCommand.java index 13966e6..68ae1da 100644 --- a/src/main/java/app/testlens/cli/TestCommand.java +++ b/src/main/java/app/testlens/cli/TestCommand.java @@ -3,7 +3,6 @@ import static app.testlens.cli.CommandSupport.apiClient; import static app.testlens.cli.CommandSupport.filterSuffix; -import static app.testlens.cli.CommandSupport.isInteractiveTerminal; import static app.testlens.cli.CommandSupport.resolveRepo; import static app.testlens.cli.util.Console.clearProgress; import static app.testlens.cli.util.Console.diffLine; @@ -16,7 +15,6 @@ import app.testlens.cli.client.api.TestsApi; import app.testlens.cli.client.model.TestExecutionResponse; import app.testlens.cli.client.model.TestResponse; -import app.testlens.cli.tui.TestExecutionsTui; import app.testlens.cli.tui.model.TestInfo; import app.testlens.cli.util.Console; import app.testlens.cli.util.TextDiff; @@ -78,41 +76,14 @@ public class TestCommand implements Callable { @Nullable String job; - @Option( - names = "--repo", - description = "Repository as owner/repo (defaults to the GitHub remote 'origin' of the current directory)" - ) - @Nullable - String repo; - - @Option( - names = "--token", - description = "GitHub access token (defaults to $GITHUB_TOKEN or $GH_TOKEN)", - defaultValue = "${env:GITHUB_TOKEN:-${env:GH_TOKEN}}" - ) - @Nullable - String token; - - @Option( - names = "--mode", - description = "Output mode: ${COMPLETION-CANDIDATES} (default: ${DEFAULT-VALUE}, uses the TUI in an interactive terminal)", - defaultValue = "auto" - ) - Mode mode = Mode.AUTO; - - @Option( - names = "--base-url", - description = "API base URL", - defaultValue = "https://api.testlens.app", - hidden = true - ) - @Nullable - String baseUrl; - @Override public Integer call() throws Exception { var out = requireNonNull(spec).commandLine().getOut(); var err = spec.commandLine().getErr(); + var root = CommandSupport.root(spec); + var repo = root.repo; + var token = root.token; + var baseUrl = root.baseUrl; if (id != null && (uniqueId != null || query != null)) { err.println("Provide either a test id or a search filter (--unique-id/--query), not both"); return 2; @@ -170,20 +141,15 @@ private int showTest( long testId ) throws Exception { try { - var tui = mode == Mode.TUI || (mode == Mode.AUTO && isInteractiveTerminal()); showProgress(out, ansi, "Fetching test..."); var test = api.getTest(owner, repoName, testId); clearProgress(out, ansi); var info = TestInfo.of(test); var loader = new ExecutionsLoader(api, owner, repoName, testId, branch, workUnit, job); - if (tui) { - TestExecutionsTui.run(info, loader, branch, workUnit, job); - } else { - showProgress(out, ansi, "Fetching executions..."); - var executions = loader.first(); - clearProgress(out, ansi); - printTest(out, ansi, info, branch, workUnit, job, executions.executions()); - } + showProgress(out, ansi, "Fetching executions..."); + var executions = loader.first(); + clearProgress(out, ansi); + printTest(out, ansi, info, branch, workUnit, job, executions.executions()); return 0; } catch (ApiException e) { clearProgress(out, ansi); @@ -312,10 +278,4 @@ static Style color(TestExecutionResponse.OutcomeEnum outcome) { case SKIPPED, MUTED, ABORTED -> Style.fg_yellow; }; } - - enum Mode { - AUTO, - TUI, - CLI - } } diff --git a/src/main/java/app/testlens/cli/Testlens.java b/src/main/java/app/testlens/cli/Testlens.java index b41b4e6..c50cddf 100644 --- a/src/main/java/app/testlens/cli/Testlens.java +++ b/src/main/java/app/testlens/cli/Testlens.java @@ -2,10 +2,19 @@ package app.testlens.cli; import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.Objects.requireNonNull; +import app.testlens.cli.tui.TestlensTui; +import app.testlens.cli.tui.TuiSession; import java.io.IOException; +import java.util.concurrent.Callable; +import org.jspecify.annotations.Nullable; import picocli.CommandLine; import picocli.CommandLine.Command; +import picocli.CommandLine.Model.CommandSpec; +import picocli.CommandLine.Option; +import picocli.CommandLine.ScopeType; +import picocli.CommandLine.Spec; @Command( name = "testlens", @@ -14,7 +23,91 @@ CompletionCommand.class, }, versionProvider = Testlens.VersionResourceReader.class ) -public class Testlens { +public class Testlens implements Callable { + + @Spec + @Nullable + CommandSpec spec; + + // the connection options are inherited by all subcommands, so they can be specified + // before or after the subcommand name; they also serve the no-argument TUI launch + @Option( + names = "--repo", + description = "Repository as owner/repo (defaults to the GitHub remote 'origin' of the current directory)", + scope = ScopeType.INHERIT + ) + @Nullable + String repo; + + @Option( + names = "--token", + description = "GitHub access token (defaults to $GITHUB_TOKEN or $GH_TOKEN)", + defaultValue = "${env:GITHUB_TOKEN:-${env:GH_TOKEN}}", + scope = ScopeType.INHERIT + ) + @Nullable + String token; + + @Option( + names = "--base-url", + description = "API base URL", + defaultValue = "https://api.testlens.app", + hidden = true, + scope = ScopeType.INHERIT + ) + @Nullable + String baseUrl; + + @Option( + names = "--github-url", + description = "GitHub API base URL", + defaultValue = "https://api.github.com", + hidden = true, + scope = ScopeType.INHERIT + ) + @Nullable + String githubUrl; + + // hidden escape hatch (see docs/debugging.md and the plain-output twins of the commands); the visible + // switch is the terminal interactivity: interactive terminals get the TUI, pipes and redirects get plain output + @Option( + names = "--mode", + description = "Output mode: ${COMPLETION-CANDIDATES}", + defaultValue = "auto", + hidden = true, + scope = ScopeType.INHERIT + ) + Mode mode = Mode.AUTO; + + @Override + public Integer call() throws Exception { + // reached only when no subcommand was given: open the TUI in an interactive terminal, otherwise show the usage + var commandLine = requireNonNull(spec).commandLine(); + var err = commandLine.getErr(); + var tui = mode == Mode.TUI || (mode == Mode.AUTO && CommandSupport.isInteractiveTerminal()); + if (!tui) { + commandLine.usage(err); + return 2; + } + if (token == null || token.isBlank()) { + err.println("No GitHub token provided (use --token or set GITHUB_TOKEN)"); + return 2; + } + var ownerAndRepo = CommandSupport.resolveRepo(repo); + if (ownerAndRepo == null || ownerAndRepo.length != 2) { + err.println("Cannot determine repository (use --repo owner/repo)"); + return 2; + } + var session = new TuiSession( + ownerAndRepo[0], + ownerAndRepo[1], + CommandSupport.apiClient(token, requireNonNull(baseUrl)), + requireNonNull(githubUrl), + token + ); + TestlensTui.runHome(session); + return 0; + } static void main(String[] args) { System.exit(new CommandLine(new Testlens()).setCaseInsensitiveEnumValuesAllowed(true).execute(args)); diff --git a/src/main/java/app/testlens/cli/tui/ApiErrors.java b/src/main/java/app/testlens/cli/tui/ApiErrors.java new file mode 100644 index 0000000..2db805a --- /dev/null +++ b/src/main/java/app/testlens/cli/tui/ApiErrors.java @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: Apache-2.0 +package app.testlens.cli.tui; + +import app.testlens.cli.client.ApiException; + +/** User-facing messages for API errors, shared by the screens that fetch asynchronously. */ +public final class ApiErrors { + + private ApiErrors() {} + + public static String message(ApiException e, String notFoundMessage) { + return switch (e.getCode()) { + case 401 -> "Invalid GitHub token"; + case 404 -> notFoundMessage; + default -> "Request failed (HTTP " + e.getCode() + ")"; + }; + } +} diff --git a/src/main/java/app/testlens/cli/tui/FlakesTui.java b/src/main/java/app/testlens/cli/tui/FlakesTui.java deleted file mode 100644 index fa67613..0000000 --- a/src/main/java/app/testlens/cli/tui/FlakesTui.java +++ /dev/null @@ -1,41 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -package app.testlens.cli.tui; - -import app.testlens.cli.client.model.FlakeResponse; -import app.testlens.cli.tui.controller.FlakesController; -import app.testlens.cli.tui.model.TestInfo; -import app.testlens.cli.tui.view.FlakesView; -import dev.tamboui.toolkit.app.ToolkitRunner; -import dev.tamboui.toolkit.event.EventResult; -import dev.tamboui.tui.event.KeyEvent; -import java.util.List; -import org.jspecify.annotations.Nullable; - -/** The flakes screen of the TUI, entered directly via {@code testlens flakes }. */ -public final class FlakesTui { - - private FlakesTui() {} - - public static void run( - TestInfo test, - @Nullable String branch, - @Nullable String workUnit, - @Nullable String job, - List flakes - ) throws Exception { - try (var runner = ToolkitRunner.create()) { - var controller = new FlakesController(runner.focusManager(), test, flakes); - var router = - new ScreenRouter(new FlakesView(controller, test, branch, workUnit, job), runner.focusManager()); - // the modal "no flakes" dialog consumes all keys before unfocused-element routing, - // so back/quit has to be handled globally, ahead of the dialog - runner.eventRouter().addGlobalHandler(event -> { - if (event instanceof KeyEvent keyEvent) { - return router.handleBackOrQuit(keyEvent, runner::quit); - } - return EventResult.UNHANDLED; - }); - runner.run(router::render); - } - } -} diff --git a/src/main/java/app/testlens/cli/tui/GlobalKeys.java b/src/main/java/app/testlens/cli/tui/GlobalKeys.java new file mode 100644 index 0000000..8b0cf5a --- /dev/null +++ b/src/main/java/app/testlens/cli/tui/GlobalKeys.java @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: Apache-2.0 +package app.testlens.cli.tui; + +import app.testlens.cli.tui.ScreenRouter.Screen; +import dev.tamboui.toolkit.event.EventResult; +import dev.tamboui.tui.event.KeyEvent; +import org.jspecify.annotations.Nullable; + +/** + * Global key handling of the unified TUI, registered ahead of the modal dialogs (which consume all keys once routed + * to unfocused elements). Order: screens with a modal input keep every key; then the current screen's global keys + * (the home screen's quick actions); then {@code g} for the home screen; then back/quit. + */ +public final class GlobalKeys { + + /** Key that pushes (or reveals) the home screen; only meaningful when a home screen exists. */ + public static final char HOME = 'g'; + + private GlobalKeys() {} + + public static EventResult handle( + KeyEvent event, + ScreenRouter router, + @Nullable Screen home, + Runnable quit + ) { + if (router.screen().modalInputActive()) { + return EventResult.UNHANDLED; + } + var screenResult = router.screen().handleGlobalKey(event); + if (screenResult.isHandled()) { + return screenResult; + } + if (home != null && event.isChar(HOME) && router.screen() != home) { + // g reveals home, discarding the screens above it; at the home screen itself the key is inert + if (!router.reveal(home)) { + router.push(home); + } + return EventResult.HANDLED; + } + return router.handleBackOrQuit(event, quit); + } +} diff --git a/src/main/java/app/testlens/cli/tui/HomeScreen.java b/src/main/java/app/testlens/cli/tui/HomeScreen.java new file mode 100644 index 0000000..825fa3b --- /dev/null +++ b/src/main/java/app/testlens/cli/tui/HomeScreen.java @@ -0,0 +1,754 @@ +// SPDX-License-Identifier: Apache-2.0 +package app.testlens.cli.tui; + +import static app.testlens.cli.tui.controller.FlakinessTableController.VIEW_ID; +import static dev.tamboui.style.Color.DARK_GRAY; +import static dev.tamboui.style.Color.RED; +import static dev.tamboui.toolkit.Toolkit.column; +import static dev.tamboui.toolkit.Toolkit.dialog; +import static dev.tamboui.toolkit.Toolkit.panel; +import static dev.tamboui.toolkit.Toolkit.row; +import static dev.tamboui.toolkit.Toolkit.stack; +import static dev.tamboui.toolkit.Toolkit.table; +import static dev.tamboui.toolkit.Toolkit.text; +import static dev.tamboui.toolkit.Toolkit.textInput; +import static java.util.Objects.requireNonNull; +import static java.util.Objects.requireNonNullElse; +import static java.util.stream.Collectors.groupingBy; +import static java.util.stream.Collectors.summingLong; + +import app.testlens.cli.GitHubClient; +import app.testlens.cli.client.ApiException; +import app.testlens.cli.client.model.FlakeResponse; +import app.testlens.cli.client.model.FlakiestJob; +import app.testlens.cli.client.model.FlakinessStatisticResponse; +import app.testlens.cli.client.model.FlakyCount; +import app.testlens.cli.client.model.Severity; +import app.testlens.cli.client.model.StatisticsSummaryResponse; +import app.testlens.cli.client.model.TestResponse; +import app.testlens.cli.tui.ScreenRouter.Screen; +import app.testlens.cli.tui.controller.FlakesController; +import app.testlens.cli.tui.controller.FlakinessTableController; +import app.testlens.cli.tui.controller.ListPaneController; +import app.testlens.cli.tui.controller.PrTuiController; +import app.testlens.cli.tui.model.TestInfo; +import app.testlens.cli.tui.view.FlakesView; +import app.testlens.cli.tui.view.FlakinessTableView; +import app.testlens.cli.tui.view.PrTuiView; +import dev.tamboui.layout.Constraint; +import dev.tamboui.layout.Rect; +import dev.tamboui.style.Color; +import dev.tamboui.style.Style; +import dev.tamboui.terminal.Frame; +import dev.tamboui.text.Span; +import dev.tamboui.toolkit.element.Element; +import dev.tamboui.toolkit.element.RenderContext; +import dev.tamboui.toolkit.element.Size; +import dev.tamboui.toolkit.event.EventResult; +import dev.tamboui.toolkit.focus.FocusManager; +import dev.tamboui.tui.event.KeyEvent; +import dev.tamboui.widgets.input.TextInputState; +import dev.tamboui.widgets.table.Cell; +import dev.tamboui.widgets.table.Row; +import dev.tamboui.widgets.table.TableState; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ExecutorService; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import org.jspecify.annotations.Nullable; + +/** + * The home screen of the unified TUI: the ranked flakiness statistics of the default (or selected) branch, with a + * client-side summary strip and quick actions (open a pull request, search tests, switch branch). Started by + * {@code testlens} without arguments and by {@code testlens statistics flakiness}; also pushed via {@code g} from any + * other screen. The ranking is loaded asynchronously, and so is the drill-down into a test's flakes. + */ +public final class HomeScreen implements Screen { + + /** Loads the ranked flakiness statistics of a branch; {@code null} means the repository's default branch. */ + @FunctionalInterface + public interface RankingLoader { + + List load(@Nullable String branch) throws ApiException; + } + + /** Fetches all flakes of the selected statistic, scoped to its branch, work unit and job. */ + @FunctionalInterface + public interface FlakesFetcher { + + List fetch(FlakinessStatisticResponse statistic) throws ApiException; + } + + /** Fetches a pull request and its tests for the PR prompt. */ + @FunctionalInterface + public interface PullRequestLoader { + + PullRequestWithTests load(long number) throws ApiException; + } + + /** Searches tests for the home screen's test search prompt. */ + @FunctionalInterface + public interface TestSearcher { + + List search(String query) throws ApiException; + } + + /** Loads the dashboard-grade summary of a branch; {@code null} means the repository's default branch. */ + @FunctionalInterface + public interface SummaryLoader { + + StatisticsSummaryResponse load(@Nullable String branch) throws ApiException; + } + + /** + * Loads the repository's open pull requests from GitHub for the discovery pane; any failure means "unavailable". + */ + @FunctionalInterface + public interface PullRequestsLoader { + + List load() throws Exception; + } + + /** A pull request together with its tests, as needed for the PR screen. */ + public record PullRequestWithTests( + app.testlens.cli.client.model.PullRequestResponse pr, + app.testlens.cli.client.model.PullRequestTestsResponse tests + ) {} + + /** The asynchronous data loaders of the home screen, wired by {@link TestlensTui} in production. */ + public record HomeLoaders( + RankingLoader ranking, + FlakesFetcher flakes, + PullRequestLoader pullRequest, + TestSearcher tests, + SummaryLoader summary, + PullRequestsLoader pullRequests + ) {} + + private enum State { + LOADING, + LOADED, + FAILED + } + + private static final String PROMPT_INPUT_ID = "prompt-input"; + + /** A modal prompt shown over the home screen: title, its input state and the action on submit. */ + record Prompt(String title, TextInputState input, Consumer onSubmit) {} + + private final TuiSession session; + private final FocusManager focusManager; + private final ExecutorService executor; + private final Consumer publish; + private final HomeLoaders loaders; + private final FlakinessTableController listController; + private final FlakinessTableView table; + private final ListPaneController pullRequestsController; + private final ListPaneController jobsController; + private final ListPaneController branchesController; + + private State state; + private @Nullable List statistics; + private @Nullable StatisticsSummaryResponse summary; + private @Nullable List pullRequests; + private @Nullable String pullRequestsError; + private @Nullable String error; + private @Nullable String branch; + private @Nullable String pending; + private @Nullable Prompt prompt; + private @Nullable ScreenRouter router; + private boolean loadStarted; + private int generation; + + public HomeScreen( + TuiSession session, + FocusManager focusManager, + ExecutorService executor, + Consumer publish, + HomeLoaders loaders + ) { + this.session = session; + this.focusManager = focusManager; + this.executor = executor; + this.publish = publish; + this.loaders = loaders; + this.listController = new FlakinessTableController(focusManager, List.of()); + this.table = new FlakinessTableView(listController); + this.pullRequestsController = new ListPaneController<>(focusManager, "pull-requests", 5); + this.jobsController = new ListPaneController<>(focusManager, "jobs", 5); + this.branchesController = new ListPaneController<>(focusManager, "branches", 5); + this.state = State.LOADING; + } + + /** The open prompt, for tests; {@code null} when none. */ + @Nullable + Prompt prompt() { + return prompt; + } + + /** The branches pane controller, for tests. */ + ListPaneController branchesForTesting() { + return branchesController; + } + + /** + * Wires the router and the drill-down callbacks, before the first render or key event; needed for drill-down + * pushes and the footer hint. + */ + public void openWith(ScreenRouter router) { + this.router = router; + listController.onOpenTest(this::openFlakes); + pullRequestsController.onEnter(pullRequest -> openPullRequest(pullRequest.number())); + branchesController.onEnter(this::switchBranch); + } + + @Override + public String focusId() { + return VIEW_ID; + } + + @Override + public Element render() { + loadIfPending(); + Element content = switch (state) { + case LOADING -> column(header(), text("Fetching flakiness ranking...").dim().length(1)); + case FAILED -> column(header()); + case LOADED -> loadedContent(); + }; + var drillDownError = listController.error(); + if (drillDownError != null) { + content = withDialog(content, drillDownError); + } else if (state == State.FAILED) { + content = withDialog(content, requireNonNullElse(error, "Loading the statistics failed")); + } + if (pending != null) { + content = stack(content, dialog(text(pending)).rounded()); + } + if (prompt != null) { + content = stack(content, promptDialog(prompt)); + } + return content; + } + + @Override + public boolean modalInputActive() { + // while a fetch runs or a prompt is open, its modal dialog must receive quit/back keys + return pending != null || prompt != null; + } + + /** + * The home screen's quick actions, handled globally so they work while no pane is focused: {@code p} opens a pull + * request, {@code /} searches tests, {@code b} switches the branch. + */ + @Override + public EventResult handleGlobalKey(KeyEvent event) { + if (state != State.LOADED || pending != null) { + return EventResult.UNHANDLED; + } + if (event.isChar('p')) { + openPrompt(new Prompt("Open pull request", new TextInputState(), this::submitPullRequestPrompt)); + return EventResult.HANDLED; + } + if (event.isChar('/')) { + openPrompt(new Prompt("Search tests", new TextInputState(), this::submitSearchPrompt)); + return EventResult.HANDLED; + } + if (event.isChar('b')) { + openPrompt( + new Prompt("Branch", new TextInputState(requireNonNullElse(branch, "")), this::submitBranchPrompt) + ); + return EventResult.HANDLED; + } + return EventResult.UNHANDLED; + } + + private void openPrompt(Prompt newPrompt) { + prompt = newPrompt; + focusManager.setFocus(PROMPT_INPUT_ID); + } + + private Element promptDialog(Prompt openPrompt) { + var hint = "Enter confirm · Esc cancel"; + return dialog( + textInput(openPrompt.input()).id(PROMPT_INPUT_ID).onSubmit(() -> submitPrompt(openPrompt)), + text(hint).dim() + ) + .title(openPrompt.title()) + .rounded() + .width(Math.max(openPrompt.title().length(), hint.length()) + 4) + .onCancel(this::closePrompt); + } + + private void closePrompt() { + prompt = null; + } + + void submitPrompt(Prompt closed) { + prompt = null; + closed.onSubmit().accept(closed.input().text().strip()); + } + + private void submitPullRequestPrompt(String value) { + if (!value.matches("\\d+")) { + listController.openFailed("Enter a pull request number, e.g. 42"); + return; + } + openPullRequest(Long.parseLong(value)); + } + + private void openPullRequest(long number) { + pending = "Fetching pull request #" + number + "..."; + executor.submit(() -> { + try { + var withTests = loaders.pullRequest().load(number); + publish.accept(() -> { + pending = null; + var controller = new PrTuiController(withTests.pr(), withTests.tests(), focusManager); + requireNonNull(router, "home screen is not wired to a router") + .push(new PrScreen(controller, new PrTuiView(controller))); + }); + } catch (ApiException e) { + publish.accept(() -> { + pending = null; + listController.openFailed(ApiErrors.message(e, "Pull request not found")); + }); + } + }); + } + + private void submitSearchPrompt(String value) { + if (value.isEmpty()) { + return; + } + pending = "Searching tests..."; + executor.submit(() -> { + try { + var tests = loaders.tests().search(value); + publish.accept(() -> { + pending = null; + var screenRouter = requireNonNull(router, "home screen is not wired to a router"); + if (tests.isEmpty()) { + listController.openFailed("No tests found."); + } else { + var searchScreen = new TestSearchScreen( + session, + focusManager, + executor, + publish, + screenRouter::push, + value, + tests + ); + searchScreen.openWith(); + screenRouter.push(searchScreen); + } + }); + } catch (ApiException e) { + publish.accept(() -> { + pending = null; + listController.openFailed(ApiErrors.message(e, "Repository not found")); + }); + } + }); + } + + private void submitBranchPrompt(String value) { + var summary = this.summary; + if (summary != null && !summary.getBranches().contains(value)) { + var known = summary.getBranches().stream().limit(5).collect(Collectors.joining(", ")); + if (summary.getBranches().size() > 5) { + known += ", …"; + } + listController.openFailed("No statistics for branch " + value + " · known: " + known); + return; + } + switchBranch(value.isEmpty() ? null : value); + } + + private Element loadedContent() { + List current = requireNonNullElse(statistics, List.of()); + return column( + header(), + statStrip(current), + row( + column(table.element()).percent(50).fill(), + jobsPane().fill() + ).fill(), + // one flexible blank cell between the dashboard rows: it takes the terminal's odd leftover, so the + // two rows split an even share and all panels render at the same height + text("").length(1), + row( + branchesPane().percent(50), + pullRequestsPane().fill() + ).fill(), + footer() + ); + } + + /** The open pull requests from GitHub, or the reason they are unavailable. */ + private dev.tamboui.toolkit.elements.Panel pullRequestsPane() { + var pullRequests = this.pullRequests; + Element inner; + if (pullRequests == null) { + inner = text(pullRequestsError == null ? "Loading..." : "Pull requests unavailable (GitHub).").dim(); + } else if (pullRequests.isEmpty()) { + inner = text("No open pull requests.").dim(); + } else { + inner = listTable( + "pull-requests", + Row.from(Cell.from("PR"), Cell.from("Title")), + pullRequests + .stream() + .map( + pullRequest -> Row.from( + Cell.from("#" + pullRequest.number()), + Cell.from(pullRequest.draft() ? "[draft] " + pullRequest.title() : pullRequest.title()) + ) + ) + .toList(), + List.of(Constraint.length(8), Constraint.fill()), + pullRequestsController + ); + } + return panel("Open pull requests", inner).rounded().borderColor(DARK_GRAY); + } + + /** The jobs with the most flaky runs, from the summary; informational, not selectable. */ + private dev.tamboui.toolkit.elements.Panel jobsPane() { + var summary = this.summary; + Element inner; + if (summary == null) { + inner = text("Statistics unavailable.").dim(); + } else { + var jobs = summary.getFlakiestJobs(); + if (jobs.isEmpty()) { + inner = text("No flaky jobs.").dim(); + } else { + inner = listTable( + "jobs", + Row.from(Cell.from("Job"), Cell.from("Flaky"), Cell.from("Worst")), + jobs + .stream() + .limit(10) + .map( + job -> Row.from( + Cell.from(job.getJob()), + Cell.from(Long.toString(job.getFlakyTests())), + Cell.from(job.getWorstPercentage() + "%") + ) + ) + .toList(), + List.of(Constraint.fill(), Constraint.length(7), Constraint.length(6)), + null + ); + } + } + return panel("Flakiest jobs", inner).rounded().borderColor(DARK_GRAY); + } + + /** The branches with rolled-up statistics, from the summary; Enter switches to the selected branch. */ + private dev.tamboui.toolkit.elements.Panel branchesPane() { + var summary = this.summary; + Element inner; + if (summary == null) { + inner = text("Statistics unavailable.").dim(); + } else if (summary.getBranches().isEmpty()) { + inner = text("No branches with statistics.").dim(); + } else { + inner = listTable( + "branches", + Row.from(Cell.from("Branch")), + summary + .getBranches() + .stream() + .map( + name -> Row.from( + Cell.from( + Span.styled(name, Style.EMPTY.fg(Objects.equals(name, branch) ? Color.CYAN : null)) + ) + ) + ) + .toList(), + List.of(Constraint.fill()), + branchesController + ); + } + return panel("Branches", inner).rounded().borderColor(DARK_GRAY); + } + + /** + * A selection table for a pane: no border of its own, the enclosing panel draws the frame. With a controller the + * pane is selectable — the cursor shows only while the pane is focused, and only when there is something to + * select; without one (e.g. the jobs pane) it renders plain rows. + */ + private Element listTable( + String id, + Row header, + List rows, + List widths, + @Nullable ListPaneController controller + ) { + var base = table().id(id).header(header).rows(rows).widths(widths.toArray(Constraint[]::new)); + final dev.tamboui.toolkit.elements.TableElement table; + if (controller == null) { + table = base.state(new TableState()); + } else { + var styled = base + .state(controller.tableState()) + .highlightStyle(controller.isFocused() ? Style.EMPTY.reversed() : Style.EMPTY); + table = controller.items().isEmpty() ? styled : styled.focusable().onKeyEvent(controller::handleKey); + } + return new Element() { + @Override + public void render(Frame frame, Rect area, RenderContext context) { + context.renderChild(table, frame, area); + } + + @Override + public Size preferredSize(int availableWidth, int availableHeight, RenderContext context) { + return Size.UNKNOWN; + } + + @Override + public Constraint constraint() { + return Constraint.fill(); + } + }; + } + + private Element withDialog(Element content, String message) { + return stack(content, dialog(text(message)).rounded().borderColor(RED).width(message.length() + 4)); + } + + private Element header() { + var title = "TestLens · " + session.owner() + "/" + session.repo() + + (branch == null ? "" : " · branch " + branch); + return text(title).bold().cyan().length(1); + } + + private Element footer() { + var line = new StringBuilder(); + var action = focusedAction(); + if (action != null) { + line.append(action).append(" · "); + } + var backOrQuit = router != null && router.canGoBack() ? "Esc/q back" : "q quit"; + line.append("↑/↓ select · Tab pane · p PR · / search · b branch · ").append(backOrQuit); + return text(line.toString()).dim().length(1); + } + + /** + * What Enter would do in the focused pane, so a selection always announces its meaning before it is committed; + * {@code null} when the focused pane has nothing to act on. + */ + private @Nullable String focusedAction() { + if (listController.isFocused() && !listController.statistics().isEmpty()) { + var selected = listController.statistics().get(listController.tableState().selected()); + return "Enter: flakes of " + TestInfo.of(selected).displayName(); + } + if (pullRequestsController.isFocused() && !pullRequestsController.items().isEmpty()) { + var selected = pullRequestsController.items().get(pullRequestsController.tableState().selected()); + return "Enter: open #" + selected.number(); + } + if (branchesController.isFocused() && !branchesController.items().isEmpty()) { + var selected = branchesController.items().get(branchesController.tableState().selected()); + return Objects.equals(selected, branch) + ? "Enter: reload " + selected + : "Enter: switch to " + selected; + } + return null; + } + + /** + * The stat strip: the server-grade summary when the summary endpoint answered, otherwise a client-side reduction + * of the ranking, and a plain empty-state line when there is nothing to summarize. + */ + private Element statStrip(List statistics) { + if (statistics.isEmpty()) { + return text("No flaky or failing tests in the last 30 days.").dim().length(1); + } + var summary = this.summary; + if (summary != null) { + var line = new StringBuilder() + .append(summary.getFlakyTests()) + .append(" flaky tests") + .append(" · ") + .append(requireNonNullElse(summary.getSeverity(), new Severity()).getHigh()) + .append(" high") + .append(" · ") + .append(summary.getConsistentlyFailingTests()) + .append(" consistently failing"); + var flakiestJobs = summary.getFlakiestJobs(); + if (!flakiestJobs.isEmpty()) { + line.append(" · worst job: ").append(flakiestJobs.getFirst().getJob()); + } + if (requireNonNullElse(summary.getStatisticsIncomplete(), false)) { + line.append(" · statistics incomplete"); + } + return text(line.toString()).dim().length(1); + } + var flakyTests = statistics.stream().map(FlakinessStatisticResponse::getUniqueId).distinct().count(); + var highSeverity = statistics + .stream() + .filter(statistic -> statistic.getFlaky().getSeverity() == FlakyCount.SeverityEnum.HIGH) + .map(FlakinessStatisticResponse::getUniqueId) + .distinct() + .count(); + var line = flakyTests + " flaky tests · " + highSeverity + " high severity"; + var worstJob = worstJob(statistics); + if (worstJob != null) { + line += " · worst job: " + worstJob; + } + return text(line).dim().length(1); + } + + private @Nullable String worstJob(List statistics) { + Map flakyRunsByJob = statistics + .stream() + .filter(statistic -> statistic.getJob() != null) + .collect( + groupingBy( + FlakinessStatisticResponse::getJob, + summingLong(statistic -> statistic.getFlaky().getCount()) + ) + ); + return flakyRunsByJob + .entrySet() + .stream() + .max(Map.Entry.comparingByValue()) + .map(Map.Entry::getKey) + .orElse(null); + } + + private void loadIfPending() { + if (loadStarted) { + return; + } + loadStarted = true; + load(); + } + + private void load() { + state = State.LOADING; + error = null; + summary = null; + generation++; + var requestedGeneration = generation; + var requestedBranch = branch; + executor.submit(() -> { + try { + var fetched = loaders.ranking().load(requestedBranch); + publish.accept(() -> { + if (stale(requestedGeneration)) { + return; + } + statistics = fetched; + // without a branch, the server reports on the default branch, which the statistics name + branch = requestedBranch != null + ? requestedBranch + : fetched.stream() + .findFirst() + .map(FlakinessStatisticResponse::getBranch) + .orElse(requestedBranch); + listController.setStatistics(fetched); + table.dataChanged(); + state = State.LOADED; + }); + } catch (ApiException e) { + publish.accept(() -> { + if (stale(requestedGeneration)) { + return; + } + error = ApiErrors.message(e, "Repository not found"); + state = State.FAILED; + }); + } + }); + executor.submit(() -> { + try { + var fetched = loaders.summary().load(requestedBranch); + publish.accept(() -> { + if (stale(requestedGeneration)) { + return; + } + summary = fetched; + jobsController.setItems( + fetched.getFlakiestJobs().stream().limit(4).toList() + ); + branchesController.setItems(fetched.getBranches()); + var currentBranchIndex = fetched.getBranches().indexOf(branch); + if (currentBranchIndex >= 0) { + branchesController.tableState().select(currentBranchIndex); + } + }); + } catch (ApiException e) { + // the summary enriches the stat strip; without it, the client-side strip stands in + } + }); + executor.submit(() -> { + try { + var fetched = loaders.pullRequests().load(); + publish.accept(() -> { + if (stale(requestedGeneration)) { + return; + } + pullRequests = fetched; + pullRequestsError = null; + pullRequestsController.setItems(fetched); + }); + } catch (Exception e) { + publish.accept(() -> { + if (stale(requestedGeneration)) { + return; + } + pullRequests = null; + pullRequestsError = "failed"; + }); + } + }); + } + + /** + * Whether another load was issued since the fetch (a branch switch), which invalidates the fetch's results. + * A generation counter instead of a branch comparison, because deriving the default branch in the ranking's + * publish must not invalidate the summary arriving in the same generation. + */ + private boolean stale(int requestedGeneration) { + return generation != requestedGeneration; + } + + private void switchBranch(@Nullable String value) { + branch = value; + load(); + } + + private void openFlakes(FlakinessStatisticResponse statistic) { + var test = TestInfo.of(statistic); + pending = "Fetching flakes of " + test.displayName() + "..."; + executor.submit(() -> { + try { + var flakes = loaders.flakes().fetch(statistic); + publish.accept(() -> { + pending = null; + var screenRouter = requireNonNull(router, "home screen is not wired to a router"); + screenRouter.push( + new FlakesView( + new FlakesController(focusManager, test, flakes), + test, + statistic.getBranch(), + statistic.getWorkUnit(), + statistic.getJob() + ) + ); + }); + } catch (ApiException e) { + publish.accept(() -> { + pending = null; + listController.openFailed(ApiErrors.message(e, "Test not found")); + }); + } + }); + } +} diff --git a/src/main/java/app/testlens/cli/tui/PrScreen.java b/src/main/java/app/testlens/cli/tui/PrScreen.java new file mode 100644 index 0000000..b9f7bf1 --- /dev/null +++ b/src/main/java/app/testlens/cli/tui/PrScreen.java @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: Apache-2.0 +package app.testlens.cli.tui; + +import app.testlens.cli.tui.ScreenRouter.Screen; +import app.testlens.cli.tui.controller.PrTestsTableController; +import app.testlens.cli.tui.controller.PrTuiController; +import app.testlens.cli.tui.view.PrTuiView; +import dev.tamboui.toolkit.element.Element; + +/** + * The pull request screen of the unified TUI: the tests of the PR and the tabbed details pane of the selected test. + * Reached via {@code testlens pr } and pushed by the home screen's PR prompt. + */ +public final class PrScreen implements Screen { + + private final PrTuiController controller; + private final PrTuiView view; + + public PrScreen(PrTuiController controller, PrTuiView view) { + this.controller = controller; + this.view = view; + } + + @Override + public String focusId() { + return PrTestsTableController.VIEW_ID; + } + + @Override + public Element render() { + return view.render(); + } + + @Override + public boolean modalInputActive() { + // while the test table search is open, q must be typed into the search, not quit the TUI + return controller.isSearching(); + } +} diff --git a/src/main/java/app/testlens/cli/tui/PrTui.java b/src/main/java/app/testlens/cli/tui/PrTui.java deleted file mode 100644 index 6527b4f..0000000 --- a/src/main/java/app/testlens/cli/tui/PrTui.java +++ /dev/null @@ -1,30 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -package app.testlens.cli.tui; - -import app.testlens.cli.client.model.PullRequestResponse; -import app.testlens.cli.client.model.PullRequestTestsResponse; -import app.testlens.cli.tui.controller.PrTuiController; -import app.testlens.cli.tui.view.PrTuiView; -import dev.tamboui.toolkit.app.ToolkitRunner; -import dev.tamboui.toolkit.event.EventResult; -import dev.tamboui.tui.event.KeyEvent; - -public final class PrTui { - - public static void run(PullRequestResponse prResponse, PullRequestTestsResponse testsResponse) throws Exception { - try (var runner = ToolkitRunner.create()) { - var controller = new PrTuiController(prResponse, testsResponse, runner.focusManager()); - var view = new PrTuiView(controller); - // the modal "no tests" dialog consumes all keys before unfocused-element routing, - // so quit has to be handled globally, ahead of the dialog - runner.eventRouter().addGlobalHandler(event -> { - if (event instanceof KeyEvent keyEvent && keyEvent.isQuit() && !controller.isSearching()) { - runner.quit(); - return EventResult.HANDLED; - } - return EventResult.UNHANDLED; - }); - runner.run(view::render); - } - } -} diff --git a/src/main/java/app/testlens/cli/tui/ScreenRouter.java b/src/main/java/app/testlens/cli/tui/ScreenRouter.java index 88f552e..0205041 100644 --- a/src/main/java/app/testlens/cli/tui/ScreenRouter.java +++ b/src/main/java/app/testlens/cli/tui/ScreenRouter.java @@ -21,6 +21,22 @@ public interface Screen { String focusId(); Element render(); + + /** + * Whether a modal input of this screen (e.g. an active search or a prompt) must receive keys that the TUI + * would otherwise treat as global keys, such as {@code q} for quit. + */ + default boolean modalInputActive() { + return false; + } + + /** + * Screen-specific global keys, handled ahead of the back/quit handling. Used by the home screen's quick + * actions, which must work while no pane is focused. + */ + default EventResult handleGlobalKey(KeyEvent event) { + return EventResult.UNHANDLED; + } } private final FocusManager focusManager; @@ -63,6 +79,25 @@ public Element render() { return screen().render(); } + /** Whether the given screen is anywhere on the stack (identity comparison). */ + public boolean isDisplayed(Screen screen) { + return stack.contains(screen); + } + + /** + * Makes an already displayed screen the top of the stack, restoring each intermediate screen's focus on the way, + * like repeated {@link #back()}; returns whether the screen was displayed. + */ + public boolean reveal(Screen screen) { + if (!isDisplayed(screen)) { + return false; + } + while (screen() != screen) { + back(); + } + return true; + } + /** The back/quit handling shared by all router-based TUIs: Esc/q go back, and quit at the root screen. */ public EventResult handleBackOrQuit(KeyEvent event, Runnable quit) { if (event.isQuit()) { diff --git a/src/main/java/app/testlens/cli/tui/StatisticsTui.java b/src/main/java/app/testlens/cli/tui/StatisticsTui.java deleted file mode 100644 index 23cc479..0000000 --- a/src/main/java/app/testlens/cli/tui/StatisticsTui.java +++ /dev/null @@ -1,84 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -package app.testlens.cli.tui; - -import static app.testlens.cli.tui.model.TestInfo.of; - -import app.testlens.cli.FlakesCommand; -import app.testlens.cli.client.ApiException; -import app.testlens.cli.client.api.TestsApi; -import app.testlens.cli.client.model.FlakinessStatisticResponse; -import app.testlens.cli.tui.controller.FlakesController; -import app.testlens.cli.tui.controller.FlakinessTableController; -import app.testlens.cli.tui.view.FlakesView; -import app.testlens.cli.tui.view.FlakinessView; -import dev.tamboui.toolkit.app.ToolkitRunner; -import dev.tamboui.toolkit.event.EventResult; -import dev.tamboui.toolkit.focus.FocusManager; -import dev.tamboui.tui.event.KeyEvent; -import java.util.List; -import org.jspecify.annotations.Nullable; - -/** - * The ranked flakiness list screen of the TUI, entered via {@code testlens statistics flakiness}. Selecting a test - * drills down into the flakes of the test on the statistic's branch and work unit by pushing them onto the router. - */ -public final class StatisticsTui { - - private StatisticsTui() {} - - public static void run( - TestsApi testsApi, - String owner, - String repo, - @Nullable String branch, - List statistics - ) throws Exception { - try (var runner = ToolkitRunner.create()) { - var focusManager = runner.focusManager(); - var listController = new FlakinessTableController(focusManager, statistics); - var router = new ScreenRouter(new FlakinessView(listController, branch), focusManager); - listController.onOpenTest( - statistic -> openFlakes(testsApi, owner, repo, focusManager, listController, router, statistic) - ); - // the modal error dialog consumes all keys before unfocused-element routing, - // so back/quit has to be handled globally, ahead of the dialog - runner.eventRouter().addGlobalHandler(event -> { - if (event instanceof KeyEvent keyEvent) { - return router.handleBackOrQuit(keyEvent, runner::quit); - } - return EventResult.UNHANDLED; - }); - runner.run(router::render); - } - } - - private static void openFlakes( - TestsApi testsApi, - String owner, - String repo, - FocusManager focusManager, - FlakinessTableController listController, - ScreenRouter router, - FlakinessStatisticResponse statistic - ) { - try { - var test = of(statistic); - var branch = statistic.getBranch(); - var workUnit = statistic.getWorkUnit(); - var job = statistic.getJob(); - var flakes = FlakesCommand.fetchFlakes(testsApi, owner, repo, test.id(), branch, workUnit, job); - var controller = new FlakesController(focusManager, test, flakes); - router.push(new FlakesView(controller, test, branch, workUnit, job)); - } catch (ApiException e) { - listController.openFailed(errorMessage(e)); - } - } - - static String errorMessage(ApiException e) { - return switch (e.getCode()) { - case 401 -> "Invalid GitHub token"; - case 404 -> "Test not found"; - default -> "Fetching flakes failed (HTTP " + e.getCode() + ")"; - }; - } -} diff --git a/src/main/java/app/testlens/cli/tui/TestExecutionsTui.java b/src/main/java/app/testlens/cli/tui/TestExecutionsTui.java deleted file mode 100644 index 430d421..0000000 --- a/src/main/java/app/testlens/cli/tui/TestExecutionsTui.java +++ /dev/null @@ -1,58 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -package app.testlens.cli.tui; - -import app.testlens.cli.ExecutionsLoader; -import app.testlens.cli.client.ApiException; -import app.testlens.cli.tui.controller.ExecutionsController; -import app.testlens.cli.tui.model.ExecutionsModel; -import app.testlens.cli.tui.model.TestInfo; -import app.testlens.cli.tui.view.ExecutionsView; -import dev.tamboui.toolkit.app.ToolkitRunner; -import dev.tamboui.toolkit.event.EventResult; -import dev.tamboui.tui.event.KeyEvent; -import org.jspecify.annotations.Nullable; - -/** The test executions screen of the TUI, entered directly via {@code testlens test }. */ -public final class TestExecutionsTui { - - private TestExecutionsTui() {} - - public static void run( - TestInfo test, - ExecutionsLoader loader, - @Nullable String branch, - @Nullable String workUnit, - @Nullable String job - ) throws Exception { - try (var runner = ToolkitRunner.create()) { - var first = loader.first(); - var model = new ExecutionsModel(test, first.executions(), first.hasMore()); - var controller = new ExecutionsController(runner.focusManager(), model, () -> { - try { - var next = loader.next(); - if (next != null) { - model.append(next); - return true; - } - return false; - } catch (ApiException e) { - // without a dedicated error dialog, the next page is simply not appended - return false; - } - }); - var router = new ScreenRouter( - new ExecutionsView(controller, model, branch, workUnit, job), - runner.focusManager() - ); - // the modal "no executions" dialog consumes all keys before unfocused-element routing, - // so back/quit has to be handled globally, ahead of the dialog - runner.eventRouter().addGlobalHandler(event -> { - if (event instanceof KeyEvent keyEvent) { - return router.handleBackOrQuit(keyEvent, runner::quit); - } - return EventResult.UNHANDLED; - }); - runner.run(router::render); - } - } -} diff --git a/src/main/java/app/testlens/cli/tui/TestSearchScreen.java b/src/main/java/app/testlens/cli/tui/TestSearchScreen.java new file mode 100644 index 0000000..87b00e2 --- /dev/null +++ b/src/main/java/app/testlens/cli/tui/TestSearchScreen.java @@ -0,0 +1,175 @@ +// SPDX-License-Identifier: Apache-2.0 +package app.testlens.cli.tui; + +import static app.testlens.cli.CommandSupport.testName; +import static app.testlens.cli.tui.controller.TestSearchController.VIEW_ID; +import static dev.tamboui.style.Color.DARK_GRAY; +import static dev.tamboui.style.Color.RED; +import static dev.tamboui.toolkit.Toolkit.column; +import static dev.tamboui.toolkit.Toolkit.dialog; +import static dev.tamboui.toolkit.Toolkit.stack; +import static dev.tamboui.toolkit.Toolkit.table; +import static dev.tamboui.toolkit.Toolkit.text; + +import app.testlens.cli.ExecutionsLoader; +import app.testlens.cli.client.ApiException; +import app.testlens.cli.client.model.TestResponse; +import app.testlens.cli.tui.ScreenRouter.Screen; +import app.testlens.cli.tui.controller.ExecutionsController; +import app.testlens.cli.tui.controller.TestSearchController; +import app.testlens.cli.tui.model.ExecutionsModel; +import app.testlens.cli.tui.model.TestInfo; +import app.testlens.cli.tui.view.ExecutionsView; +import dev.tamboui.layout.Constraint; +import dev.tamboui.style.Style; +import dev.tamboui.toolkit.element.Element; +import dev.tamboui.toolkit.focus.FocusManager; +import dev.tamboui.widgets.table.Cell; +import dev.tamboui.widgets.table.Row; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.function.Consumer; +import org.jspecify.annotations.Nullable; + +/** + * The results of a test search on the home screen: one row per test, drilling down into the executions screen of the + * selected test. Pushed by the home screen's {@code /} action. + */ +public final class TestSearchScreen implements Screen { + + private final TuiSession session; + private final FocusManager focusManager; + private final ExecutorService executor; + private final Consumer publish; + private final Consumer opener; + private final String query; + private final TestSearchController listController; + + private @Nullable String pending; + private @Nullable String error; + + public TestSearchScreen( + TuiSession session, + FocusManager focusManager, + ExecutorService executor, + Consumer publish, + Consumer opener, + String query, + List tests + ) { + this.session = session; + this.focusManager = focusManager; + this.executor = executor; + this.publish = publish; + this.opener = opener; + this.query = query; + this.listController = new TestSearchController(focusManager, tests); + } + + /** Wires the drill-down callback, before the first key event. */ + public void openWith() { + listController.onOpenTest(this::openExecutions); + } + + @Override + public String focusId() { + return VIEW_ID; + } + + @Override + public Element render() { + Element content = column( + header(), + tableElement(), + text("↑/↓ select · Enter executions · Esc/q back").dim().length(1) + ); + if (error != null) { + content = stack(content, dialog(text(error)).rounded().borderColor(RED).width(error.length() + 4)); + } + if (pending != null) { + content = stack(content, dialog(text(pending)).rounded()); + } + return content; + } + + @Override + public boolean modalInputActive() { + // while the executions fetch runs, its modal dialog must receive quit/back keys + return pending != null; + } + + private Element header() { + return text("Tests matching \"" + query + "\"").bold().cyan().length(1); + } + + private Element tableElement() { + var tests = listController.tests(); + var visibleRows = Math.min(tests.size(), 10); + return table() + .id(VIEW_ID) + .title("Tests") + .rounded() + .borderColor(DARK_GRAY) + .header(Row.from(Cell.from("Test"), Cell.from("ID"), Cell.from("Unique ID"))) + .rows( + tests.stream() + .map(TestSearchScreen::testRow) + .toList() + ) + .widths(Constraint.fill(), Constraint.length(9), Constraint.fill()) + .state(listController.tableState()) + .highlightStyle(Style.EMPTY.reversed()) + .focusable() + .onKeyEvent(listController::handleKey) + .constraint(Constraint.length(Math.max(visibleRows + 3, 1))); + } + + private static Row testRow(TestResponse test) { + return Row.from( + Cell.from(testName(test.getDisplayNames())), + Cell.from(Long.toString(test.getId())), + Cell.from(test.getUniqueId()) + ); + } + + private void openExecutions(TestInfo test) { + pending = "Fetching executions of " + test.displayName() + "..."; + executor.submit(() -> { + try { + var loader = new ExecutionsLoader( + session.testsApi(), + session.owner(), + session.repo(), + test.id(), + null, + null, + null + ); + var first = loader.first(); + publish.accept(() -> { + pending = null; + var model = new ExecutionsModel(test, first.executions(), first.hasMore()); + var controller = new ExecutionsController(focusManager, model, () -> { + try { + var next = loader.next(); + if (next != null) { + model.append(next); + return true; + } + return false; + } catch (ApiException e) { + // without a dedicated error dialog, the next page is simply not appended + return false; + } + }); + opener.accept(new ExecutionsView(controller, model, null, null, null)); + }); + } catch (ApiException e) { + publish.accept(() -> { + pending = null; + error = ApiErrors.message(e, "Test not found"); + }); + } + }); + } +} diff --git a/src/main/java/app/testlens/cli/tui/TestlensTui.java b/src/main/java/app/testlens/cli/tui/TestlensTui.java new file mode 100644 index 0000000..593e4b3 --- /dev/null +++ b/src/main/java/app/testlens/cli/tui/TestlensTui.java @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: Apache-2.0 +package app.testlens.cli.tui; + +import static app.testlens.cli.tui.model.TestInfo.of; + +import app.testlens.cli.FlakesCommand; +import app.testlens.cli.GitHubClient; +import app.testlens.cli.tui.ScreenRouter.Screen; +import dev.tamboui.toolkit.app.ToolkitRunner; +import dev.tamboui.toolkit.event.EventResult; +import dev.tamboui.tui.event.KeyEvent; +import dev.tamboui.tui.event.TickEvent; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.function.Consumer; + +/** + * The single TUI of the CLI: all screens share one runner, one router and one executor for asynchronous loads. Only + * {@code testlens} without arguments starts it, at the home screen; {@code g} pushes the home screen again from any + * other one (see {@link GlobalKeys}). + */ +public final class TestlensTui { + + private TestlensTui() {} + + /** Runs the TUI at the home screen; the ranking is fetched asynchronously. */ + public static void runHome(TuiSession session) throws Exception { + try (var runner = ToolkitRunner.create()) { + var executor = newExecutor(); + try { + var home = homeScreen(session, runner, executor); + var router = new ScreenRouter(home, runner.focusManager()); + home.openWith(router); + runLoop(runner, router, home); + } finally { + executor.shutdown(); + } + } + } + + private static HomeScreen homeScreen(TuiSession session, ToolkitRunner runner, ExecutorService executor) { + var loaders = new HomeScreen.HomeLoaders( + requested -> session.statisticsApi() + .getFlakinessStatistics(session.owner(), session.repo(), requested, null, null), + statistic -> FlakesCommand.fetchFlakes( + session.testsApi(), + session.owner(), + session.repo(), + of(statistic).id(), + statistic.getBranch(), + statistic.getWorkUnit(), + statistic.getJob() + ), + number -> { + var api = session.pullRequestsApi(); + var pr = api.getPullRequest(session.owner(), session.repo(), (int) number); + return new HomeScreen.PullRequestWithTests( + pr, + api.getPullRequestTests(session.owner(), session.repo(), (int) number, pr.getHeadSha()) + ); + }, + query -> session.testsApi().searchTests(session.owner(), session.repo(), null, query, null, null), + requested -> session.statisticsApi().getStatisticsSummary(session.owner(), session.repo(), requested), + () -> new GitHubClient(session.githubUrl(), session.githubToken()) + .openPullRequests(session.owner(), session.repo()) + ); + return new HomeScreen(session, runner.focusManager(), executor, publisherOf(runner), loaders); + } + + private static void runLoop(ToolkitRunner runner, ScreenRouter router, Screen home) throws Exception { + // the modal dialogs consume all keys before unfocused-element routing, + // so back/quit and the home key have to be handled globally, ahead of the dialogs + runner.eventRouter().addGlobalHandler(event -> { + if (event instanceof KeyEvent keyEvent) { + return GlobalKeys.handle(keyEvent, router, home, runner::quit); + } + return EventResult.UNHANDLED; + }); + runner.run(router::render); + } + + private static Consumer publisherOf(ToolkitRunner runner) { + // publish model updates on the render thread, then request a repaint right away + // (without it, the next tick would repaint within 40 ms) + return update -> { + runner.runOnRenderThread(update); + runner.tuiRunner().dispatch(TickEvent.of(0)); + }; + } + + private static ExecutorService newExecutor() { + return Executors.newFixedThreadPool(2, Thread.ofPlatform().name("testlens-tui-", 0).daemon(true).factory()); + } +} diff --git a/src/main/java/app/testlens/cli/tui/TuiSession.java b/src/main/java/app/testlens/cli/tui/TuiSession.java new file mode 100644 index 0000000..9a15498 --- /dev/null +++ b/src/main/java/app/testlens/cli/tui/TuiSession.java @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: Apache-2.0 +package app.testlens.cli.tui; + +import app.testlens.cli.client.ApiClient; +import app.testlens.cli.client.api.PullRequestsApi; +import app.testlens.cli.client.api.StatisticsApi; +import app.testlens.cli.client.api.TestsApi; +import org.jspecify.annotations.Nullable; + +/** + * The repository context of one TUI session: the resolved repository, an authenticated API client for the testlens API + * and the GitHub credentials for the discovery panes. Screens create the API interfaces they need from it on demand. + */ +public record TuiSession( + String owner, String repo, ApiClient apiClient, String githubUrl, @Nullable String githubToken +) { + + public TestsApi testsApi() { + return new TestsApi(apiClient); + } + + public StatisticsApi statisticsApi() { + return new StatisticsApi(apiClient); + } + + public PullRequestsApi pullRequestsApi() { + return new PullRequestsApi(apiClient); + } +} diff --git a/src/main/java/app/testlens/cli/tui/controller/FlakesController.java b/src/main/java/app/testlens/cli/tui/controller/FlakesController.java index 431d686..ea0b244 100644 --- a/src/main/java/app/testlens/cli/tui/controller/FlakesController.java +++ b/src/main/java/app/testlens/cli/tui/controller/FlakesController.java @@ -12,7 +12,6 @@ import app.testlens.cli.tui.view.FlakesView; import dev.tamboui.toolkit.event.EventResult; import dev.tamboui.toolkit.focus.FocusManager; -import dev.tamboui.tui.event.KeyCode; import dev.tamboui.tui.event.KeyEvent; import dev.tamboui.widgets.table.TableState; import java.util.List; @@ -143,17 +142,6 @@ private void select(int index) { // Tab moves from the table to the details pane, Shift+Tab back private EventResult navigate(KeyEvent event) { - if (!event.isKey(KeyCode.TAB)) { - return EventResult.UNHANDLED; - } - if (!event.hasShift() && isFocused()) { - focusManager.setFocus(PrDetailsController.VIEW_ID); - return EventResult.HANDLED; - } - if (event.hasShift() && focusManager.isFocused(PrDetailsController.VIEW_ID)) { - focusManager.setFocus(VIEW_ID); - return EventResult.HANDLED; - } - return EventResult.UNHANDLED; + return PaneSwitcher.switchFocus(focusManager, List.of(VIEW_ID, PrDetailsController.VIEW_ID), event); } } diff --git a/src/main/java/app/testlens/cli/tui/controller/FlakinessTableController.java b/src/main/java/app/testlens/cli/tui/controller/FlakinessTableController.java index 4131600..03de64c 100644 --- a/src/main/java/app/testlens/cli/tui/controller/FlakinessTableController.java +++ b/src/main/java/app/testlens/cli/tui/controller/FlakinessTableController.java @@ -4,7 +4,7 @@ import static java.util.Objects.requireNonNull; import app.testlens.cli.client.model.FlakinessStatisticResponse; -import app.testlens.cli.tui.view.FlakinessView; +import app.testlens.cli.tui.view.FlakinessTableView; import dev.tamboui.toolkit.event.EventResult; import dev.tamboui.toolkit.focus.FocusManager; import dev.tamboui.tui.event.KeyEvent; @@ -22,7 +22,7 @@ public final class FlakinessTableController { public static final String VIEW_ID = "flakiness"; private final FocusManager focusManager; - private final List statistics; + private List statistics; private final TableState tableState = new TableState(); private Consumer onOpenTest = statistic -> {}; private @Nullable String error; @@ -38,6 +38,16 @@ public FlakinessTableController( } } + /** + * Replaces the statistics after an asynchronous load or a branch switch, resetting the selection to the first row. + */ + public void setStatistics(List statistics) { + this.statistics = List.copyOf(statistics); + if (!statistics.isEmpty()) { + tableState.select(0); + } + } + /** Registers the callback invoked when the user opens the flakes of the selected statistic. */ public void onOpenTest(Consumer onOpenTest) { this.onOpenTest = requireNonNull(onOpenTest); @@ -83,9 +93,9 @@ public EventResult handleKey(KeyEvent event) { } else if (event.isDown() || event.isChar('j')) { target = selected + 1; } else if (event.isPageUp()) { - target = selected - FlakinessView.MAX_VISIBLE_STATISTICS; + target = selected - FlakinessTableView.MAX_VISIBLE_STATISTICS; } else if (event.isPageDown()) { - target = selected + FlakinessView.MAX_VISIBLE_STATISTICS; + target = selected + FlakinessTableView.MAX_VISIBLE_STATISTICS; } else if (event.isHome()) { target = 0; } else if (event.isEnd()) { diff --git a/src/main/java/app/testlens/cli/tui/controller/ListPaneController.java b/src/main/java/app/testlens/cli/tui/controller/ListPaneController.java new file mode 100644 index 0000000..562cfcd --- /dev/null +++ b/src/main/java/app/testlens/cli/tui/controller/ListPaneController.java @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: Apache-2.0 +package app.testlens.cli.tui.controller; + +import static java.util.Objects.requireNonNull; + +import dev.tamboui.toolkit.event.EventResult; +import dev.tamboui.toolkit.focus.FocusManager; +import dev.tamboui.tui.event.KeyEvent; +import dev.tamboui.widgets.table.TableState; +import java.util.List; +import java.util.function.Consumer; + +/** + * Input handling for one list pane of the home dashboard: a selectable list with an enter action. The pane's table is + * built by the view; this controller owns the selection state and the keys. + */ +public final class ListPaneController { + + private final FocusManager focusManager; + private final String viewId; + private final int pageStep; + private List items = List.of(); + private final TableState tableState = new TableState(); + private Consumer onEnter = item -> {}; + + public ListPaneController(FocusManager focusManager, String viewId, int pageStep) { + this.focusManager = focusManager; + this.viewId = viewId; + this.pageStep = pageStep; + } + + /** Registers the callback invoked when the user presses Enter on the selected item. */ + public void onEnter(Consumer onEnter) { + this.onEnter = requireNonNull(onEnter); + } + + /** Replaces the items, resetting the selection to the first row. */ + public void setItems(List items) { + this.items = List.copyOf(items); + if (!items.isEmpty()) { + tableState.select(0); + } + } + + public List items() { + return items; + } + + public TableState tableState() { + return tableState; + } + + public boolean isFocused() { + return focusManager.isFocused(viewId); + } + + public EventResult handleKey(KeyEvent event) { + if (items.isEmpty() || !isFocused()) { + return EventResult.UNHANDLED; + } + if (event.isSelect()) { + onEnter.accept(items.get(tableState.selected())); + return EventResult.HANDLED; + } + var selected = tableState.selected(); + int target; + if (event.isUp() || event.isChar('k')) { + target = selected - 1; + } else if (event.isDown() || event.isChar('j')) { + target = selected + 1; + } else if (event.isPageUp()) { + target = selected - pageStep; + } else if (event.isPageDown()) { + target = selected + pageStep; + } else if (event.isHome()) { + target = 0; + } else if (event.isEnd()) { + target = items.size() - 1; + } else { + return EventResult.UNHANDLED; + } + tableState.select(Math.clamp(target, 0, items.size() - 1)); + return EventResult.HANDLED; + } +} diff --git a/src/main/java/app/testlens/cli/tui/controller/PrTuiController.java b/src/main/java/app/testlens/cli/tui/controller/PrTuiController.java index 7480e96..59a7900 100644 --- a/src/main/java/app/testlens/cli/tui/controller/PrTuiController.java +++ b/src/main/java/app/testlens/cli/tui/controller/PrTuiController.java @@ -6,10 +6,8 @@ import app.testlens.cli.tui.model.PrTuiModel; import dev.tamboui.toolkit.event.EventResult; import dev.tamboui.toolkit.focus.FocusManager; -import dev.tamboui.tui.event.KeyCode; import dev.tamboui.tui.event.KeyEvent; import java.util.List; -import org.jspecify.annotations.Nullable; public final class PrTuiController { @@ -66,31 +64,6 @@ public boolean isFocused(String id) { } public EventResult navigate(KeyEvent event, String viewId) { - if (!isFocused(viewId)) { - return EventResult.UNHANDLED; - } - var index = VIEW_IDS.indexOf(viewId); - if (index == -1) { - return EventResult.UNHANDLED; - } - String target = null; - if (event.isKey(KeyCode.TAB) && !event.hasShift()) { - target = nextViewId(index); - } else if (event.isKey(KeyCode.TAB) && event.hasShift()) { - target = previousViewId(index); - } - if (target == null) { - return EventResult.UNHANDLED; - } - focusManager.setFocus(target); - return EventResult.HANDLED; - } - - private static @Nullable String previousViewId(int index) { - return index > 0 ? VIEW_IDS.get(index - 1) : null; - } - - private static @Nullable String nextViewId(int index) { - return index + 1 < VIEW_IDS.size() ? VIEW_IDS.get(index + 1) : null; + return PaneSwitcher.switchFocus(focusManager, VIEW_IDS, event); } } diff --git a/src/main/java/app/testlens/cli/tui/controller/TestSearchController.java b/src/main/java/app/testlens/cli/tui/controller/TestSearchController.java new file mode 100644 index 0000000..c35f4fb --- /dev/null +++ b/src/main/java/app/testlens/cli/tui/controller/TestSearchController.java @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: Apache-2.0 +package app.testlens.cli.tui.controller; + +import static java.util.Objects.requireNonNull; + +import app.testlens.cli.client.model.TestResponse; +import app.testlens.cli.tui.model.TestInfo; +import dev.tamboui.toolkit.event.EventResult; +import dev.tamboui.toolkit.focus.FocusManager; +import dev.tamboui.tui.event.KeyEvent; +import dev.tamboui.widgets.table.TableState; +import java.util.List; +import java.util.function.Consumer; + +/** + * Input handling of the test search results table; opening a test is delegated to the callback registered via + * {@link #onOpenTest(Consumer)}, which fetches the test's executions and pushes the executions screen. + */ +public final class TestSearchController { + + public static final String VIEW_ID = "search-results"; + + private final FocusManager focusManager; + private List tests; + private final TableState tableState = new TableState(); + private Consumer onOpenTest = test -> {}; + + public TestSearchController(FocusManager focusManager, List tests) { + this.focusManager = focusManager; + this.tests = List.copyOf(tests); + if (!tests.isEmpty()) { + tableState.select(0); + } + } + + /** Registers the callback invoked when the user opens the executions of the selected test. */ + public void onOpenTest(Consumer onOpenTest) { + this.onOpenTest = requireNonNull(onOpenTest); + } + + public List tests() { + return tests; + } + + public TableState tableState() { + return tableState; + } + + public boolean isFocused() { + return focusManager.isFocused(VIEW_ID); + } + + public EventResult handleKey(KeyEvent event) { + if (tests.isEmpty() || !isFocused()) { + return EventResult.UNHANDLED; + } + if (event.isSelect()) { + onOpenTest.accept(TestInfo.of(tests.get(tableState.selected()))); + return EventResult.HANDLED; + } + var selected = tableState.selected(); + int target; + if (event.isUp() || event.isChar('k')) { + target = selected - 1; + } else if (event.isDown() || event.isChar('j')) { + target = selected + 1; + } else if (event.isPageUp()) { + target = selected - 10; + } else if (event.isPageDown()) { + target = selected + 10; + } else if (event.isHome()) { + target = 0; + } else if (event.isEnd()) { + target = tests.size() - 1; + } else { + return EventResult.UNHANDLED; + } + tableState.select(Math.clamp(target, 0, tests.size() - 1)); + return EventResult.HANDLED; + } +} diff --git a/src/main/java/app/testlens/cli/tui/view/FlakinessView.java b/src/main/java/app/testlens/cli/tui/view/FlakinessTableView.java similarity index 76% rename from src/main/java/app/testlens/cli/tui/view/FlakinessView.java rename to src/main/java/app/testlens/cli/tui/view/FlakinessTableView.java index c43603b..d0d19c6 100644 --- a/src/main/java/app/testlens/cli/tui/view/FlakinessView.java +++ b/src/main/java/app/testlens/cli/tui/view/FlakinessTableView.java @@ -1,19 +1,12 @@ // SPDX-License-Identifier: Apache-2.0 package app.testlens.cli.tui.view; -import static app.testlens.cli.tui.controller.FlakinessTableController.VIEW_ID; import static app.testlens.cli.tui.view.PrTuiUtils.abbreviatedTestName; import static app.testlens.cli.tui.view.PrTuiUtils.truncate; -import static dev.tamboui.style.Color.RED; -import static dev.tamboui.toolkit.Toolkit.column; -import static dev.tamboui.toolkit.Toolkit.dialog; -import static dev.tamboui.toolkit.Toolkit.stack; import static dev.tamboui.toolkit.Toolkit.table; -import static dev.tamboui.toolkit.Toolkit.text; import app.testlens.cli.client.model.FlakinessStatisticResponse; import app.testlens.cli.client.model.FlakyCount; -import app.testlens.cli.tui.ScreenRouter; import app.testlens.cli.tui.controller.FlakinessTableController; import dev.tamboui.layout.Constraint; import dev.tamboui.layout.Rect; @@ -35,11 +28,10 @@ import org.jspecify.annotations.Nullable; /** - * The ranked flakiness list: one turn table row per statistic (test and work unit), ranked by flakiness. Selecting a - * row and pressing Enter drills down into the flakes screen of the entry's test, pushed onto the - * {@link ScreenRouter}. + * The ranked flakiness table: one row per statistic (test and work unit), ranked by flakiness, with the visible-row + * scrollbar and memoized column widths. Extracted from the former FlakinessView, shared by the home screen. */ -public final class FlakinessView implements ScreenRouter.Screen { +public final class FlakinessTableView { /** Visible rows of the statistics table, shared with the controller for page-wise selection. */ public static final int MAX_VISIBLE_STATISTICS = 10; @@ -53,17 +45,17 @@ public final class FlakinessView implements ScreenRouter.Screen { private static final int COLUMN_SPACING = 3; private static final int TABLE_DECORATION_WIDTH = 2 + 2 + 5 * COLUMN_SPACING; private static final int TABLE_CHROME_HEIGHT = 3; + private static final int MAX_WORK_UNIT_WIDTH = 32; private final FlakinessTableController controller; - private final @Nullable String branch; private final TableElement table; + // the statistics do not change while the screen is visible, so the layout is memoized by width only private int tableWidth = -1; - public FlakinessView(FlakinessTableController controller, @Nullable String branch) { + public FlakinessTableView(FlakinessTableController controller) { this.controller = controller; - this.branch = branch; this.table = table() - .id(VIEW_ID) + .id(FlakinessTableController.VIEW_ID) .title("Flakiest tests") .rounded() .borderColor(Color.DARK_GRAY) @@ -85,37 +77,19 @@ public FlakinessView(FlakinessTableController controller, @Nullable String branc .onKeyEvent(controller::handleKey); } - @Override - public String focusId() { - return VIEW_ID; - } - - @Override - public Element render() { - var statistics = controller.statistics(); - var rowCount = Math.min(statistics.size(), MAX_VISIBLE_STATISTICS) + TABLE_CHROME_HEIGHT; - var content = column(header(), statisticsTable(Constraint.length(Math.max(rowCount, 1))), footer()); - var error = controller.error(); - if (error == null) { - return content; - } - return stack(content, dialog(text(error)).rounded().borderColor(RED).width(error.length() + 4)); - } - - private Element header() { - var title = branch == null ? "Flakiness ranking" : "Flakiness ranking · branch " + branch; - return text(title).bold().cyan().length(1); - } - - private Element footer() { - return text("↑/↓ select · Enter view flakes · Esc/q quit").dim().length(1); + /** Invalidates the memoized column widths; call after the statistics changed. */ + public void dataChanged() { + tableWidth = -1; } - private Element statisticsTable(Constraint constraint) { + /** The table element, sized to the visible rows plus chrome, with a scrollbar when rows overflow. */ + public Element element() { + var constraint = Constraint.fill(); return new Element() { @Override public void render(Frame frame, Rect area, RenderContext context) { fitColumns(area.width()); + table.highlightStyle(controller.isFocused() ? Style.EMPTY.reversed() : Style.EMPTY); context.renderChild(table, frame, area); var statistics = controller.statistics(); var visibleRows = area.height() - TABLE_CHROME_HEIGHT; @@ -144,7 +118,6 @@ public Constraint constraint() { }; } - // the statistics do not change while the screen is visible, so the layout is memoized by width only private void fitColumns(int width) { if (width == tableWidth) { return; @@ -156,19 +129,25 @@ private void fitColumns(int width) { statistics, statistic -> severityLabel(statistic.getFlaky().getSeverity()) ); - var flakyWidth = maxColumnWidth(FLAKY_HEADER, statistics, FlakinessView::flakyLabel); + var flakyWidth = maxColumnWidth(FLAKY_HEADER, statistics, FlakinessTableView::flakyLabel); var failedWidth = maxColumnWidth(FAILED_HEADER, statistics, statistic -> failedLabel(statistic.getFailed().getCount())); var available = Math.max(0, width - TABLE_DECORATION_WIDTH - severityWidth - flakyWidth - failedWidth); - // job and work unit are de-emphasized to the last columns and capped, so the test name keeps the leftovers - var jobWidth = Math.min( - maxColumnWidth(JOB_HEADER, statistics, FlakinessStatisticResponse::getJob), - Math.min(MAX_WORK_UNIT_WIDTH, Math.max(1, available)) - ); - var workUnitWidth = Math.min( - maxColumnWidth(WORK_UNIT_HEADER, statistics, FlakinessStatisticResponse::getWorkUnit), - Math.min(MAX_WORK_UNIT_WIDTH, Math.max(1, available - jobWidth)) - ); + // in narrow panes (the dashboard split) the de-emphasized job and work unit columns drop out — the jobs + // pane next to the ranking covers jobs — and the test name abbreviates to its innermost segment + var compact = available < 34; + var jobWidth = compact + ? 0 + : Math.min( + maxColumnWidth(JOB_HEADER, statistics, FlakinessStatisticResponse::getJob), + Math.min(MAX_WORK_UNIT_WIDTH, Math.max(1, available)) + ); + var workUnitWidth = compact + ? 0 + : Math.min( + maxColumnWidth(WORK_UNIT_HEADER, statistics, FlakinessStatisticResponse::getWorkUnit), + Math.min(MAX_WORK_UNIT_WIDTH, Math.max(1, available - jobWidth)) + ); var testWidth = Math.max(1, available - jobWidth - workUnitWidth); var finalWorkUnitWidth = workUnitWidth; @@ -188,8 +167,6 @@ private void fitColumns(int width) { ); } - private static final int MAX_WORK_UNIT_WIDTH = 32; - private static int maxColumnWidth( String header, List statistics, @@ -210,11 +187,12 @@ private static Row statisticRow( int testWidth ) { var severity = statistic.getFlaky().getSeverity(); + var compact = jobWidth == 0 && workUnitWidth == 0; return Row.from( Cell.from(Span.styled(severityLabel(severity), Style.EMPTY.fg(severityColor(severity)))), Cell.from(flakyLabel(statistic)), Cell.from(failedLabel(statistic.getFailed().getCount())), - Cell.from(abbreviatedTestName(statistic.getDisplayNames(), testWidth)), + Cell.from(testNameCell(statistic.getDisplayNames(), testWidth, compact)), // de-emphasized: job and work unit differentiate the rows of one test (e.g. a JDK matrix) but are the // least relevant part of the ranking scan Cell.from( @@ -232,6 +210,18 @@ private static Row statisticRow( ); } + /** + * The test cell of a ranking row. Wide layouts keep the class prefix and abbreviate the middle; narrow dashboard + * panes truncate to the innermost segment, which is the identity worth scanning. + */ + private static String testNameCell(List displayNames, int width, boolean compact) { + if (compact) { + var name = String.join(" > ", displayNames.subList(Math.min(1, displayNames.size()), displayNames.size())); + return truncate(name, width, CharWidth.TruncatePosition.START); + } + return abbreviatedTestName(displayNames, width); + } + private static String severityLabel(FlakyCount.@Nullable SeverityEnum severity) { return severity == null ? "" : severity.name(); } diff --git a/src/test/java/app/testlens/cli/GitHubClientTest.java b/src/test/java/app/testlens/cli/GitHubClientTest.java new file mode 100644 index 0000000..84380b0 --- /dev/null +++ b/src/test/java/app/testlens/cli/GitHubClientTest.java @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: Apache-2.0 +package app.testlens.cli; + +import static org.assertj.core.api.Assertions.assertThat; + +import app.testlens.cli.GitHubClient.OpenPullRequest; +import java.io.IOException; +import java.util.List; +import org.junit.jupiter.api.Test; + +class GitHubClientTest { + + @Test + void parses_github_shaped_pull_request_payloads_ignoring_unknown_fields() throws IOException { + // a realistic slice of GET /repos/{owner}/{repo}/pulls — the CLI only needs number, title and draft + var json = """ + [ + { + "url": "https://api.github.com/repos/some-org/some-repo/pulls/42", + "id": 1234, + "number": 42, + "title": "Fix the flaky timeout", + "draft": false, + "state": "open", + "user": { "login": "someone" }, + "head": { "ref": "fix-timeout", "sha": "0123456789abcdef" }, + "base": { "ref": "main" }, + "created_at": "2026-11-01T10:00:00Z", + "updated_at": "2026-11-10T10:00:00Z" + }, + { + "number": 43, + "title": "Upgrade the build cache", + "draft": true + } + ] + """; + + List pullRequests = GitHubClient.parsePullRequests(json); + + assertThat(pullRequests).containsExactly( + new OpenPullRequest(42, "Fix the flaky timeout", false), + new OpenPullRequest(43, "Upgrade the build cache", true) + ); + } +} diff --git a/src/test/java/app/testlens/cli/TestlensTest.java b/src/test/java/app/testlens/cli/TestlensTest.java new file mode 100644 index 0000000..8b42f1e --- /dev/null +++ b/src/test/java/app/testlens/cli/TestlensTest.java @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: Apache-2.0 +package app.testlens.cli; + +import static app.testlens.cli.TestUtil.run; +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; + +/** + * The no-argument launch of the root command: it opens the TUI in an interactive terminal (not testable here, since + * tests have no TTY) and shows the usage otherwise. + */ +class TestlensTest { + + @Test + void without_a_tty_the_root_shows_the_usage() { + var result = run(); + + assertThat(result.exitCode()).isEqualTo(2); + assertThat(result.stderr()).contains("Usage: testlens", "--repo=", "pr", "statistics"); + } + + @Test + void the_root_lists_the_inherited_connection_options_in_subcommand_help() { + var result = run("pr", "--help"); + + assertThat(result.exitCode()).isZero(); + assertThat(result.stdout()).contains("--repo=", "--token="); + // the hidden escape hatch stays undocumented + assertThat(result.stdout()).doesNotContain("--mode", "--base-url"); + } +} diff --git a/src/test/java/app/testlens/cli/tui/FlakinessViewTest.java b/src/test/java/app/testlens/cli/tui/FlakinessViewTest.java deleted file mode 100644 index f69e252..0000000 --- a/src/test/java/app/testlens/cli/tui/FlakinessViewTest.java +++ /dev/null @@ -1,121 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -package app.testlens.cli.tui; - -import static org.assertj.core.api.Assertions.assertThat; - -import app.testlens.cli.client.model.FailedCount; -import app.testlens.cli.client.model.FlakinessStatisticResponse; -import app.testlens.cli.client.model.FlakyCount; -import app.testlens.cli.client.model.Link; -import app.testlens.cli.client.model.StatisticLinks; -import app.testlens.cli.tui.controller.FlakinessTableController; -import app.testlens.cli.tui.view.FlakinessView; -import dev.tamboui.buffer.Buffer; -import dev.tamboui.layout.Rect; -import dev.tamboui.toolkit.element.DefaultRenderContext; -import dev.tamboui.toolkit.focus.FocusManager; -import dev.tamboui.tui.RenderThreadTestHelper; -import dev.tamboui.tui.event.KeyCode; -import dev.tamboui.tui.event.KeyEvent; -import java.util.ArrayList; -import java.util.List; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -class FlakinessViewTest { - - @BeforeEach - void markAsRenderThread() { - RenderThreadTestHelper.markAsRenderThread(); - } - - @AfterEach - void clearRenderThread() { - RenderThreadTestHelper.clearRenderThread(); - } - - @Test - void shows_the_ranked_statistics_table() { - var view = view( - "main", - statistic(1729, "NetworkTests", "connects()", ":core:test", 20L, 10, FlakyCount.SeverityEnum.HIGH), - statistic(1703, "CalculatorTests", "adds()", ":core:testJava21", 4L, 2, FlakyCount.SeverityEnum.LOW) - ); - - assertThat(render(view)).contains( - "Flakiness ranking · branch main", - "Flakiest tests", - "Job", - "CI / build", - "connects()", - "adds()" - ); - // the first row is selected by default - assertThat(render(view)).contains(":core:test"); - } - - @Test - void enter_notifies_the_drill_down_callback() { - var focusManager = new FocusManager(); - var controller = new FlakinessTableController( - focusManager, - List.of( - statistic(1729, "NetworkTests", "connects()", ":core:test", 20L, 10, FlakyCount.SeverityEnum.HIGH) - ) - ); - var view = new FlakinessView(controller, null); - var opened = new ArrayList(); - controller.onOpenTest(opened::add); - focusManager.setFocus(FlakinessTableController.VIEW_ID); - - assertThat(render(view)).contains("connects()"); - - controller.handleKey(KeyEvent.ofKey(KeyCode.ENTER)); - assertThat(opened).hasSize(1); - } - - private static FlakinessView view(String branch, FlakinessStatisticResponse... statistics) { - var controller = new FlakinessTableController(new FocusManager(), List.of(statistics)); - return new FlakinessView(controller, branch); - } - - private static String render(FlakinessView view) { - var buffer = renderBuffer(view); - var screen = new StringBuilder(); - for (int y = 0; y < buffer.height(); y++) { - for (int x = 0; x < buffer.width(); x++) { - screen.append(buffer.get(x, y).symbol()); - } - screen.append('\n'); - } - return screen.toString(); - } - - private static Buffer renderBuffer(FlakinessView view) { - var buffer = Buffer.empty(Rect.of(120, 24)); - var frame = dev.tamboui.terminal.Frame.forTesting(buffer); - view.render().render(frame, frame.area(), DefaultRenderContext.createEmpty()); - return buffer; - } - - private static FlakinessStatisticResponse statistic( - long id, - String className, - String method, - String workUnit, - Long flakyCount, - Integer percentage, - FlakyCount.SeverityEnum severity - ) { - return new FlakinessStatisticResponse() - .uniqueId("[engine:junit-jupiter]/[class:" + className + "]/[method:" + method + "]") - .displayNames(List.of("JUnit Jupiter", className, method)) - .workUnit(workUnit) - .job("CI / build") - .branch("main") - .failed(new FailedCount().count(1L).total(200L).percentage(1)) - .flaky(new FlakyCount().count(flakyCount).total(200L).percentage(percentage).severity(severity)) - .links(new StatisticLinks().test(new Link().href("/v1/repos/some-org/some-repo/tests/" + id))); - } -} diff --git a/src/test/java/app/testlens/cli/tui/HomeScreenTest.java b/src/test/java/app/testlens/cli/tui/HomeScreenTest.java new file mode 100644 index 0000000..10b845a --- /dev/null +++ b/src/test/java/app/testlens/cli/tui/HomeScreenTest.java @@ -0,0 +1,853 @@ +// SPDX-License-Identifier: Apache-2.0 +package app.testlens.cli.tui; + +import static java.util.Objects.requireNonNull; +import static org.assertj.core.api.Assertions.assertThat; + +import app.testlens.cli.GitHubClient; +import app.testlens.cli.client.ApiClient; +import app.testlens.cli.client.ApiException; +import app.testlens.cli.client.model.FailedCount; +import app.testlens.cli.client.model.FlakiestJob; +import app.testlens.cli.client.model.FlakinessStatisticResponse; +import app.testlens.cli.client.model.FlakyCount; +import app.testlens.cli.client.model.Link; +import app.testlens.cli.client.model.PullRequestResponse; +import app.testlens.cli.client.model.PullRequestTestsResponse; +import app.testlens.cli.client.model.Severity; +import app.testlens.cli.client.model.StatisticLinks; +import app.testlens.cli.client.model.StatisticsSummaryResponse; +import app.testlens.cli.client.model.TestResponse; +import app.testlens.cli.tui.controller.FlakinessTableController; +import app.testlens.cli.tui.view.FlakesView; +import dev.tamboui.buffer.Buffer; +import dev.tamboui.layout.Rect; +import dev.tamboui.toolkit.element.DefaultRenderContext; +import dev.tamboui.toolkit.element.ElementRegistry; +import dev.tamboui.toolkit.event.EventResult; +import dev.tamboui.toolkit.event.EventRouter; +import dev.tamboui.toolkit.focus.FocusManager; +import dev.tamboui.tui.RenderThreadTestHelper; +import dev.tamboui.tui.event.KeyCode; +import dev.tamboui.tui.event.KeyEvent; +import java.net.http.HttpHeaders; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.AbstractExecutorService; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class HomeScreenTest { + + private static final ExecutorService DIRECT_EXECUTOR = new DirectExecutor(); + + @BeforeEach + void markAsRenderThread() { + RenderThreadTestHelper.markAsRenderThread(); + } + + @AfterEach + void clearRenderThread() { + RenderThreadTestHelper.clearRenderThread(); + } + + @Test + void shows_the_ranked_statistics_table_with_the_summary_strip() { + var view = home( + DIRECT_EXECUTOR, + new FocusManager(), + loaded -> List.of( + statistic(1729, "NetworkTests", "connects()", ":core:test", 20L, 10, FlakyCount.SeverityEnum.HIGH), + statistic(1703, "CalculatorTests", "adds()", ":core:testJava21", 4L, 2, FlakyCount.SeverityEnum.LOW) + ) + ); + + // the ranking pane is half the dashboard width: compact columns, the innermost test segment visible + assertThat(render(view)).contains( + "TestLens · some-org/some-repo · branch main", + "2 flaky tests · 1 high severity · worst job: CI / build", + "Flakiest tests", + "connects()", + "adds()" + ); + // the job column drops out in the compact ranking; jobs live in the pane beside it + assertThat(render(view)).doesNotContain("Severity Flaky Failed Test Job"); + } + + @Test + void shows_a_placeholder_until_the_ranking_is_loaded() { + var executor = new QueueingExecutor(); + var view = home( + executor, + new FocusManager(), + loaded -> List.of( + statistic(1729, "NetworkTests", "connects()", ":core:test", 20L, 10, FlakyCount.SeverityEnum.HIGH) + ) + ); + + assertThat(render(view)).contains("TestLens · some-org/some-repo", "Fetching flakiness ranking..."); + assertThat(render(view)).doesNotContain("connects()"); + } + + @Test + void loads_the_ranking_asynchronously_and_derives_the_default_branch() { + var executor = new QueueingExecutor(); + var view = home( + executor, + new FocusManager(), + loaded -> List.of( + statistic(1729, "NetworkTests", "connects()", ":core:test", 20L, 10, FlakyCount.SeverityEnum.HIGH) + ) + ); + render(view); + + executor.runAll(); + + assertThat(render(view)).contains("· branch main", "1 flaky tests", "connects()"); + } + + @Test + void shows_an_error_when_the_load_fails() { + var executor = new QueueingExecutor(); + var view = home(executor, new FocusManager(), loaded -> { + throw new ApiException("not found", 404, HttpHeaders.of(Map.of(), (key, value) -> true), ""); + }); + render(view); + + executor.runAll(); + + assertThat(render(view)).contains("TestLens · some-org/some-repo", "Repository not found"); + } + + @Test + void enter_fetches_the_flakes_of_the_selected_statistic_and_pushes_their_screen() { + var focusManager = new FocusManager(); + var fetched = new ArrayList(); + var view = home( + DIRECT_EXECUTOR, + focusManager, + loaded -> List.of( + statistic(1729, "NetworkTests", "connects()", ":core:test", 20L, 10, FlakyCount.SeverityEnum.HIGH) + ), + statistic -> { + fetched.add(statistic); + return List.of(); + } + ); + var eventRouter = new EventRouter(focusManager, new ElementRegistry()); + var context = new DefaultRenderContext(focusManager, eventRouter); + var router = new ScreenRouter(view, focusManager); + view.openWith(router); + renderFrame(view, context, focusManager, eventRouter); + assertThat(focusManager.focusedId()).isEqualTo(FlakinessTableController.VIEW_ID); + + assertThat(eventRouter.route(KeyEvent.ofKey(KeyCode.ENTER))).isEqualTo(EventResult.HANDLED); + + // the direct executor fetched the flakes and pushed their screen within the routed key event + assertThat(router.screen()).isInstanceOf(FlakesView.class); + assertThat(fetched).hasSize(1); + } + + @Test + void enter_shows_an_error_when_the_flakes_fetch_fails() { + var focusManager = new FocusManager(); + var view = home( + DIRECT_EXECUTOR, + focusManager, + loaded -> List.of( + statistic(1729, "NetworkTests", "connects()", ":core:test", 20L, 10, FlakyCount.SeverityEnum.HIGH) + ), + statistic -> { + throw new ApiException("not found", 404, HttpHeaders.of(Map.of(), (key, value) -> true), ""); + } + ); + var eventRouter = new EventRouter(focusManager, new ElementRegistry()); + var context = new DefaultRenderContext(focusManager, eventRouter); + var router = new ScreenRouter(view, focusManager); + view.openWith(router); + renderFrame(view, context, focusManager, eventRouter); + + eventRouter.route(KeyEvent.ofKey(KeyCode.ENTER)); + + assertThat(router.screen()).isEqualTo(view); + assertThat(render(view)).contains("Test not found"); + } + + @Test + void p_opens_the_pull_request_prompt() { + var view = home( + DIRECT_EXECUTOR, + new FocusManager(), + loaded -> List.of( + statistic(1729, "NetworkTests", "connects()", ":core:test", 20L, 10, FlakyCount.SeverityEnum.HIGH) + ) + ); + render(view); // completes the load, so the quick actions are available + + assertThat(view.handleGlobalKey(KeyEvent.ofChar('p'))).isEqualTo(EventResult.HANDLED); + assertThat(render(view)).contains("Open pull request", "Enter confirm · Esc cancel"); + // the prompt is a modal input + assertThat(view.modalInputActive()).isTrue(); + } + + @Test + void the_pr_prompt_rejects_input_that_is_not_a_number() { + var view = home( + DIRECT_EXECUTOR, + new FocusManager(), + loaded -> List.of( + statistic(1729, "NetworkTests", "connects()", ":core:test", 20L, 10, FlakyCount.SeverityEnum.HIGH) + ) + ); + render(view); + view.handleGlobalKey(KeyEvent.ofChar('p')); + var prompt = requireNonNull(view.prompt(), "the p action opens a prompt"); + + prompt.input().setText("abc"); + view.submitPrompt(prompt); + + assertThat(render(view)).contains("Enter a pull request number, e.g. 42"); + assertThat(view.prompt()).isNull(); + } + + @Test + void the_pr_prompt_fetches_and_pushes_the_pull_request_screen() { + var focusManager = new FocusManager(); + var view = home( + DIRECT_EXECUTOR, + focusManager, + loaded -> List.of( + statistic(1729, "NetworkTests", "connects()", ":core:test", 20L, 10, FlakyCount.SeverityEnum.HIGH) + ), + statistic -> List.of(), + number -> new HomeScreen.PullRequestWithTests( + new PullRequestResponse().number(42).title("Some PR"), + new PullRequestTestsResponse().sha("SHA") + ), + query -> List.of(), + branch -> { + throw new AssertionError("unexpected summary fetch"); + }, + () -> List.of() + ); + var router = new ScreenRouter(view, focusManager); + view.openWith(router); + render(view); + view.handleGlobalKey(KeyEvent.ofChar('p')); + var prompt = requireNonNull(view.prompt(), "the p action opens a prompt"); + + prompt.input().setText("42"); + view.submitPrompt(prompt); + + assertThat(router.screen()).isInstanceOf(PrScreen.class); + } + + @Test + void the_search_prompt_pushes_the_results_screen() { + var focusManager = new FocusManager(); + var view = home( + DIRECT_EXECUTOR, + focusManager, + loaded -> List.of( + statistic(1729, "NetworkTests", "connects()", ":core:test", 20L, 10, FlakyCount.SeverityEnum.HIGH) + ), + statistic -> List.of(), + number -> { + throw new AssertionError("unexpected pull request fetch"); + }, + query -> List.of( + new TestResponse().id(7L) + .uniqueId("[engine:junit-jupiter]/[class:FooTests]/[method:bar()]") + .displayNames(List.of("JUnit Jupiter", "FooTests", "bar()")) + ), + branch -> { + throw new AssertionError("unexpected summary fetch"); + }, + () -> List.of() + ); + var router = new ScreenRouter(view, focusManager); + view.openWith(router); + render(view); + view.handleGlobalKey(KeyEvent.ofChar('/')); + var prompt = requireNonNull(view.prompt(), "the / action opens a prompt"); + + prompt.input().setText("FooTests"); + view.submitPrompt(prompt); + + assertThat(router.screen()).isInstanceOf(TestSearchScreen.class); + } + + @Test + void escape_closes_the_prompt() { + var focusManager = new FocusManager(); + var view = home( + DIRECT_EXECUTOR, + focusManager, + loaded -> List.of( + statistic(1729, "NetworkTests", "connects()", ":core:test", 20L, 10, FlakyCount.SeverityEnum.HIGH) + ) + ); + var eventRouter = new EventRouter(focusManager, new ElementRegistry()); + var context = new DefaultRenderContext(focusManager, eventRouter); + renderFrame(view, context, focusManager, eventRouter); + view.handleGlobalKey(KeyEvent.ofChar('p')); + renderFrame(view, context, focusManager, eventRouter); // registers the prompt input + + // Escape with the focused input declining the key reaches the modal dialog, which cancels + assertThat(eventRouter.route(KeyEvent.ofKey(KeyCode.ESCAPE))).isEqualTo(EventResult.HANDLED); + + assertThat(view.prompt()).isNull(); + assertThat(view.modalInputActive()).isFalse(); + } + + @Test + void the_summary_enriches_the_stat_strip() { + var view = home( + DIRECT_EXECUTOR, + new FocusManager(), + loaded -> List.of( + statistic(1729, "NetworkTests", "connects()", ":core:test", 20L, 10, FlakyCount.SeverityEnum.HIGH) + ), + statistic -> List.of(), + number -> { + throw new AssertionError("unexpected pull request fetch"); + }, + query -> { + throw new AssertionError("unexpected test search"); + }, + branch -> summary(), + () -> List.of() + ); + + assertThat(render(view)).contains( + "TestLens · some-org/some-repo · branch main", + "42 flaky tests · 7 high · 3 consistently failing · worst job: CI / build" + ); + } + + @Test + void the_stat_strip_falls_back_when_the_summary_fails() { + var view = home( + DIRECT_EXECUTOR, + new FocusManager(), + loaded -> List.of( + statistic(1729, "NetworkTests", "connects()", ":core:test", 20L, 10, FlakyCount.SeverityEnum.HIGH) + ), + statistic -> List.of(), + number -> { + throw new AssertionError("unexpected pull request fetch"); + }, + query -> { + throw new AssertionError("unexpected test search"); + }, + branch -> { + throw new ApiException("boom", 502, HttpHeaders.of(Map.of(), (key, value) -> true), ""); + }, + () -> List.of() + ); + + // the client-side reduction of the ranking stands in for the failed summary + assertThat(render(view)).contains("1 flaky tests · 1 high severity · worst job: CI / build"); + } + + @Test + void the_branch_prompt_rejects_unknown_branches() { + var focusManager = new FocusManager(); + var rankings = new ArrayList(); + var view = home( + DIRECT_EXECUTOR, + focusManager, + branch -> { + rankings.add(branch); + return List.of( + statistic(1729, "NetworkTests", "connects()", ":core:test", 20L, 10, FlakyCount.SeverityEnum.HIGH) + ); + }, + statistic -> List.of(), + number -> { + throw new AssertionError("unexpected pull request fetch"); + }, + query -> { + throw new AssertionError("unexpected test search"); + }, + branch -> summary(), + () -> List.of() + ); + var router = new ScreenRouter(view, focusManager); + view.openWith(router); + render(view); + view.handleGlobalKey(KeyEvent.ofChar('b')); + var prompt = requireNonNull(view.prompt(), "the b action opens a prompt"); + + prompt.input().setText("nope"); + view.submitPrompt(prompt); + + assertThat(render(view)).contains("No statistics for branch nope · known: main, release/1.2"); + assertThat(view.prompt()).isNull(); + // the unknown branch did not trigger a reload + assertThat(rankings).hasSize(1); + } + + @Test + void the_branch_prompt_accepts_known_branches_and_reloads() { + var focusManager = new FocusManager(); + var rankings = new ArrayList(); + var view = home( + DIRECT_EXECUTOR, + focusManager, + branch -> { + rankings.add(branch); + return List.of( + statistic(1729, "NetworkTests", "connects()", ":core:test", 20L, 10, FlakyCount.SeverityEnum.HIGH) + ); + }, + statistic -> List.of(), + number -> { + throw new AssertionError("unexpected pull request fetch"); + }, + query -> { + throw new AssertionError("unexpected test search"); + }, + branch -> summary(), + () -> List.of() + ); + var router = new ScreenRouter(view, focusManager); + view.openWith(router); + render(view); + view.handleGlobalKey(KeyEvent.ofChar('b')); + var prompt = requireNonNull(view.prompt(), "the b action opens a prompt"); + + prompt.input().setText("release/1.2"); + view.submitPrompt(prompt); + + // the direct executor reloaded ranking and summary for the known branch + assertThat(rankings).containsExactly(null, "release/1.2"); + assertThat(render(view)).contains("· branch release/1.2"); + } + + @Test + void the_panes_render_the_discovery_data() { + var view = home( + DIRECT_EXECUTOR, + new FocusManager(), + loaded -> List.of( + statistic(1729, "NetworkTests", "connects()", ":core:test", 20L, 10, FlakyCount.SeverityEnum.HIGH) + ), + statistic -> List.of(), + number -> { + throw new AssertionError("unexpected pull request fetch"); + }, + query -> { + throw new AssertionError("unexpected test search"); + }, + branch -> summary(), + () -> List.of( + new GitHubClient.OpenPullRequest(42, "Fix the flaky timeout", false), + new GitHubClient.OpenPullRequest(43, "Upgrade the build cache", true) + ) + ); + + assertThat(render(view)).contains( + "Open pull requests", + "#42", + "Fix the flaky timeout", + "[draft] Upgrade the build cache", + "Flakiest jobs", + "CI / build", + "Branches", + "release/1.2" + ); + } + + @Test + void enter_on_a_pull_request_opens_its_screen() { + var focusManager = new FocusManager(); + var view = home( + DIRECT_EXECUTOR, + focusManager, + loaded -> List.of( + statistic(1729, "NetworkTests", "connects()", ":core:test", 20L, 10, FlakyCount.SeverityEnum.HIGH) + ), + statistic -> List.of(), + number -> new HomeScreen.PullRequestWithTests( + new PullRequestResponse().number(42).title("Some PR"), + new PullRequestTestsResponse().sha("SHA") + ), + query -> { + throw new AssertionError("unexpected test search"); + }, + branch -> summary(), + () -> List.of(new GitHubClient.OpenPullRequest(42, "Some PR", false)) + ); + var eventRouter = new EventRouter(focusManager, new ElementRegistry()); + var context = new DefaultRenderContext(focusManager, eventRouter); + var router = new ScreenRouter(view, focusManager); + view.openWith(router); + renderFrame(view, context, focusManager, eventRouter); + // Tab moves the focus from the ranking table past the branches pane to the PR pane + assertThat(eventRouter.route(KeyEvent.ofKey(KeyCode.TAB))).isEqualTo(EventResult.HANDLED); + assertThat(eventRouter.route(KeyEvent.ofKey(KeyCode.TAB))).isEqualTo(EventResult.HANDLED); + assertThat(focusManager.focusedId()).isEqualTo("pull-requests"); + + assertThat(eventRouter.route(KeyEvent.ofKey(KeyCode.ENTER))).isEqualTo(EventResult.HANDLED); + + // the direct executor fetched the PR and pushed its screen within the routed key event + assertThat(router.screen()).isInstanceOf(PrScreen.class); + } + + @Test + void enter_on_a_branch_switches_to_it() { + var focusManager = new FocusManager(); + var rankings = new ArrayList(); + var view = home( + DIRECT_EXECUTOR, + focusManager, + branch -> { + rankings.add(branch); + return List.of( + statistic(1729, "NetworkTests", "connects()", ":core:test", 20L, 10, FlakyCount.SeverityEnum.HIGH) + ); + }, + statistic -> List.of(), + number -> { + throw new AssertionError("unexpected pull request fetch"); + }, + query -> { + throw new AssertionError("unexpected test search"); + }, + branch -> summary(), + () -> List.of() + ); + var eventRouter = new EventRouter(focusManager, new ElementRegistry()); + var context = new DefaultRenderContext(focusManager, eventRouter); + var router = new ScreenRouter(view, focusManager); + view.openWith(router); + render(view); + focusManager.setFocus("branches"); + renderFrame(view, context, focusManager, eventRouter); + // select the second branch, then Enter + view.branchesForTesting().tableState().select(1); + + assertThat(eventRouter.route(KeyEvent.ofKey(KeyCode.ENTER))).isEqualTo(EventResult.HANDLED); + + assertThat(rankings).containsExactly(null, "release/1.2"); + assertThat(render(view)).contains("· branch release/1.2"); + } + + @Test + void unavailable_pull_requests_render_a_dim_note() { + var view = home( + DIRECT_EXECUTOR, + new FocusManager(), + loaded -> List.of( + statistic(1729, "NetworkTests", "connects()", ":core:test", 20L, 10, FlakyCount.SeverityEnum.HIGH) + ), + statistic -> List.of(), + number -> { + throw new AssertionError("unexpected pull request fetch"); + }, + query -> { + throw new AssertionError("unexpected test search"); + }, + branch -> summary(), + () -> { + throw new java.io.IOException("no network"); + } + ); + + assertThat(render(view)).contains("Open pull requests", "Pull requests unavailable (GitHub)."); + } + + @Test + void tab_cycles_through_the_actionable_panes_only() { + var focusManager = new FocusManager(); + var view = home( + DIRECT_EXECUTOR, + focusManager, + loaded -> List.of( + statistic(1729, "NetworkTests", "connects()", ":core:test", 20L, 10, FlakyCount.SeverityEnum.HIGH) + ), + statistic -> List.of(), + number -> { + throw new AssertionError("unexpected pull request fetch"); + }, + query -> { + throw new AssertionError("unexpected test search"); + }, + branch -> summary(), + () -> List.of(new GitHubClient.OpenPullRequest(42, "Some PR", false)) + ); + var eventRouter = new EventRouter(focusManager, new ElementRegistry()); + var context = new DefaultRenderContext(focusManager, eventRouter); + var router = new ScreenRouter(view, focusManager); + view.openWith(router); + renderFrame(view, context, focusManager, eventRouter); + + // the jobs pane is informational and not part of the focus cycle; Tab follows visual order + assertThat(focusManager.focusOrder()).containsExactly("flakiness", "branches", "pull-requests"); + + assertThat(eventRouter.route(KeyEvent.ofKey(KeyCode.TAB))).isEqualTo(EventResult.HANDLED); + assertThat(focusManager.focusedId()).isEqualTo("branches"); + assertThat(eventRouter.route(KeyEvent.ofKey(KeyCode.TAB))).isEqualTo(EventResult.HANDLED); + assertThat(focusManager.focusedId()).isEqualTo("pull-requests"); + } + + @Test + void the_footer_announces_the_pending_action_of_the_focused_pane() { + var focusManager = new FocusManager(); + var view = home( + DIRECT_EXECUTOR, + focusManager, + loaded -> List.of( + statistic(1729, "NetworkTests", "connects()", ":core:test", 20L, 10, FlakyCount.SeverityEnum.HIGH) + ), + statistic -> List.of(), + number -> { + throw new AssertionError("unexpected pull request fetch"); + }, + query -> { + throw new AssertionError("unexpected test search"); + }, + branch -> summary(), + () -> List.of() + ); + var eventRouter = new EventRouter(focusManager, new ElementRegistry()); + var context = new DefaultRenderContext(focusManager, eventRouter); + var router = new ScreenRouter(view, focusManager); + view.openWith(router); + renderFrame(view, context, focusManager, eventRouter); + + // ranking focused: the drill-down target + assertThat(render(view)).contains("Enter: flakes of NetworkTests > connects()"); + + // branches focused on another branch: the pending switch + focusManager.setFocus("branches"); + view.branchesForTesting().tableState().select(1); + renderFrame(view, context, focusManager, eventRouter); + assertThat(render(view)).contains("Enter: switch to release/1.2"); + } + + @Test + void quick_actions_are_inert_while_loading() { + var executor = new QueueingExecutor(); + var view = home( + executor, + new FocusManager(), + loaded -> List.of( + statistic(1729, "NetworkTests", "connects()", ":core:test", 20L, 10, FlakyCount.SeverityEnum.HIGH) + ) + ); + render(view); + + assertThat(view.handleGlobalKey(KeyEvent.ofChar('p'))).isEqualTo(EventResult.UNHANDLED); + assertThat(render(view)).doesNotContain("Open pull request"); + } + + private static StatisticsSummaryResponse summary() { + return new StatisticsSummaryResponse() + .branch("main") + .windowDays(30) + .flakyTests(42L) + .severity(new Severity().low(20L).medium(15L).high(7L)) + .flakiestJobs(List.of(new FlakiestJob().job("CI / build").flakyTests(10L).worstPercentage(10))) + .branches(List.of("main", "release/1.2")) + .totalTests(1234L) + .sessionCount(512L) + .activeBranches(8L) + .consistentlyFailingTests(3L) + .statisticsIncomplete(false); + } + + private static HomeScreen home(ExecutorService executor, FocusManager focusManager) { + return home( + executor, + focusManager, + loaded -> { + throw new AssertionError("unexpected ranking fetch"); + }, + statistic -> List.of() + ); + } + + private static HomeScreen home( + ExecutorService executor, + FocusManager focusManager, + HomeScreen.RankingLoader loader + ) { + return home(executor, focusManager, loader, statistic -> List.of()); + } + + private static HomeScreen home( + ExecutorService executor, + FocusManager focusManager, + HomeScreen.RankingLoader loader, + HomeScreen.FlakesFetcher flakesFetcher + ) { + return home( + executor, + focusManager, + loader, + flakesFetcher, + number -> { + throw new AssertionError("unexpected pull request fetch"); + }, + query -> { + throw new AssertionError("unexpected test search"); + }, + branch -> { + throw new AssertionError("unexpected summary fetch"); + }, + () -> List.of() + ); + } + + private static HomeScreen home( + ExecutorService executor, + FocusManager focusManager, + HomeScreen.RankingLoader loader, + HomeScreen.FlakesFetcher flakesFetcher, + HomeScreen.PullRequestLoader pullRequestLoader, + HomeScreen.TestSearcher testSearcher, + HomeScreen.SummaryLoader summaryLoader, + HomeScreen.PullRequestsLoader pullRequestsLoader + ) { + var session = new TuiSession("some-org", "some-repo", new ApiClient(), "https://api.github.com", null); + return new HomeScreen( + session, + focusManager, + executor, + Runnable::run, + new HomeScreen.HomeLoaders( + loader, + flakesFetcher, + pullRequestLoader, + testSearcher, + summaryLoader, + pullRequestsLoader + ) + ); + } + + private static String render(HomeScreen screen) { + var buffer = Buffer.empty(Rect.of(120, 24)); + var frame = dev.tamboui.terminal.Frame.forTesting(buffer); + screen.render().render(frame, frame.area(), DefaultRenderContext.createEmpty()); + var rendered = new StringBuilder(); + for (int y = 0; y < buffer.height(); y++) { + for (int x = 0; x < buffer.width(); x++) { + rendered.append(buffer.get(x, y).symbol()); + } + rendered.append('\n'); + } + return rendered.toString(); + } + + private static void renderFrame( + HomeScreen screen, + DefaultRenderContext context, + FocusManager focusManager, + EventRouter eventRouter + ) { + focusManager.clearFocusables(); + eventRouter.clear(); + var buffer = Buffer.empty(Rect.of(120, 24)); + var frame = dev.tamboui.terminal.Frame.forTesting(buffer); + screen.render().render(frame, frame.area(), context); + } + + private static FlakinessStatisticResponse statistic( + long id, + String className, + String method, + String workUnit, + Long flakyCount, + Integer percentage, + FlakyCount.SeverityEnum severity + ) { + return new FlakinessStatisticResponse() + .uniqueId("[engine:junit-jupiter]/[class:" + className + "]/[method:" + method + "]") + .displayNames(List.of("JUnit Jupiter", className, method)) + .workUnit(workUnit) + .job("CI / build") + .branch("main") + .failed(new FailedCount().count(1L).total(200L).percentage(1)) + .flaky(new FlakyCount().count(flakyCount).total(200L).percentage(percentage).severity(severity)) + .links(new StatisticLinks().test(new Link().href("/v1/repos/some-org/some-repo/tests/" + id))); + } + + /** Runs every submitted task inline, so asynchronous loads complete within the test call. */ + private static final class DirectExecutor extends AbstractExecutorService { + + @Override + public void execute(Runnable command) { + command.run(); + } + + @Override + public void shutdown() {} + + @Override + public List shutdownNow() { + return List.of(); + } + + @Override + public boolean isShutdown() { + return true; + } + + @Override + public boolean isTerminated() { + return true; + } + + @Override + public boolean awaitTermination(long timeout, TimeUnit unit) { + return true; + } + } + + /** Queues submitted tasks until {@link #runAll()}, simulating an in-flight asynchronous fetch. */ + private static final class QueueingExecutor extends AbstractExecutorService { + + private final List tasks = new ArrayList<>(); + + void runAll() { + var queued = List.copyOf(tasks); + tasks.clear(); + queued.forEach(Runnable::run); + } + + @Override + public void execute(Runnable command) { + tasks.add(command); + } + + @Override + public void shutdown() {} + + @Override + public List shutdownNow() { + return List.of(); + } + + @Override + public boolean isShutdown() { + return true; + } + + @Override + public boolean isTerminated() { + return true; + } + + @Override + public boolean awaitTermination(long timeout, TimeUnit unit) { + return true; + } + } +} diff --git a/src/test/java/app/testlens/cli/tui/ScreenRouterTest.java b/src/test/java/app/testlens/cli/tui/ScreenRouterTest.java index 3c00728..dc9339b 100644 --- a/src/test/java/app/testlens/cli/tui/ScreenRouterTest.java +++ b/src/test/java/app/testlens/cli/tui/ScreenRouterTest.java @@ -79,10 +79,137 @@ void escape_goes_back_when_there_is_a_screen_below() { assertThat(router.canGoBack()).isFalse(); } + @Test + void isDisplayed_and_reveal_work_by_identity() { + var focusManager = new FocusManager(); + var list = new MarkerScreen("list"); + var router = new ScreenRouter(list, focusManager); + var pr = new MarkerScreen("pr"); + var flakes = new MarkerScreen("flakes"); + + assertThat(router.isDisplayed(list)).isTrue(); + assertThat(router.isDisplayed(pr)).isFalse(); + + router.push(pr); + router.push(flakes); + assertThat(router.screen().focusId()).isEqualTo("flakes"); + focusManager.setFocus("details"); + + assertThat(router.reveal(pr)).isTrue(); + assertThat(router.screen().focusId()).isEqualTo("pr"); + assertThat(router.canGoBack()).isTrue(); + + assertThat(router.reveal(list)).isTrue(); + assertThat(router.screen().focusId()).isEqualTo("list"); + assertThat(router.canGoBack()).isFalse(); + + assertThat(router.reveal(pr)).isFalse(); + assertThat(router.screen().focusId()).isEqualTo("list"); + } + + @Test + void global_keys_push_home_once_and_g_is_inert_there() { + var focusManager = new FocusManager(); + var router = new ScreenRouter(new MarkerScreen("pr"), focusManager); + var home = new MarkerScreen("home"); + var quits = new ArrayList(); + + // g pushes home on top of the deep link + assertThat(GlobalKeys.handle(KeyEvent.ofChar('g'), router, home, () -> quits.add("quit"))) + .isEqualTo(EventResult.HANDLED); + assertThat(router.screen().focusId()).isEqualTo("home"); + assertThat(router.canGoBack()).isTrue(); + + // g on the home screen is inert: it routes to the focused pane, which ignores it + assertThat(GlobalKeys.handle(KeyEvent.ofChar('g'), router, home, () -> quits.add("quit"))) + .isEqualTo(EventResult.UNHANDLED); + assertThat(router.screen().focusId()).isEqualTo("home"); + assertThat(quits).isEmpty(); + + // q goes back to the deep link first + assertThat(GlobalKeys.handle(KeyEvent.ofChar('q'), router, home, () -> quits.add("quit"))) + .isEqualTo(EventResult.HANDLED); + assertThat(router.screen().focusId()).isEqualTo("pr"); + assertThat(quits).isEmpty(); + + // q at the deep-link root quits + assertThat(GlobalKeys.handle(KeyEvent.ofChar('q'), router, home, () -> quits.add("quit"))) + .isEqualTo(EventResult.HANDLED); + assertThat(quits).containsExactly("quit"); + } + + @Test + void global_keys_reveal_home_when_it_is_below_the_stack() { + var focusManager = new FocusManager(); + var home = new MarkerScreen("home"); + var router = new ScreenRouter(home, focusManager); + router.push(new MarkerScreen("pr")); + router.push(new MarkerScreen("flakes")); + + assertThat(GlobalKeys.handle(KeyEvent.ofChar('g'), router, home, () -> {})) + .isEqualTo(EventResult.HANDLED); + assertThat(router.screen().focusId()).isEqualTo("home"); + // going home discards the screens above it + assertThat(router.canGoBack()).isFalse(); + } + + @Test + void global_keys_yield_to_modal_inputs_and_screen_keys() { + var focusManager = new FocusManager(); + var modal = new ModalScreen("list"); + var router = new ScreenRouter(modal, focusManager); + var quits = new ArrayList(); + + // a modal input keeps all keys, including g and q + assertThat(GlobalKeys.handle(KeyEvent.ofChar('g'), router, null, () -> {})) + .isEqualTo(EventResult.UNHANDLED); + assertThat(GlobalKeys.handle(KeyEvent.ofChar('q'), router, null, () -> {})) + .isEqualTo(EventResult.UNHANDLED); + + modal.modal = false; + // the screen's own global keys win over back/quit + assertThat(GlobalKeys.handle(KeyEvent.ofChar('p'), router, null, () -> {})) + .isEqualTo(EventResult.HANDLED); + // unhandled screen keys fall through to back/quit, which quits at the root + assertThat(GlobalKeys.handle(KeyEvent.ofChar('q'), router, null, () -> quits.add("quit"))) + .isEqualTo(EventResult.HANDLED); + assertThat(quits).containsExactly("quit"); + } + private record MarkerScreen(String focusId) implements Screen { @Override public Element render() { throw new UnsupportedOperationException(); } } + + /** A screen that either swallows every key as a modal input or handles {@code p} as a global key. */ + private static final class ModalScreen implements Screen { + private final String id; + boolean modal = true; + + ModalScreen(String id) { + this.id = id; + } + + @Override + public String focusId() { + return id; + } + + @Override + public Element render() { + throw new UnsupportedOperationException(); + } + + @Override + public boolean modalInputActive() { + return modal; + } + + @Override + public EventResult handleGlobalKey(KeyEvent event) { + return event.isChar('p') ? EventResult.HANDLED : EventResult.UNHANDLED; + } + } }