Compare commits

...
Author SHA1 Message Date
Theo Browne 39ed592f4c fix(server): keep Grok effort and rewind aligned with the live session
Do not carry an old effort onto a new model. Count steered prompts when rewinding. Lock rollback against a replaced session. Keep one default effort in the composer menu.

Made with Grok 4.6.
2026-08-12 14:51:27 -07:00
Theo Browne 5f56ea5fb9 fix(server): allow undefined Grok effort on session/set_model
exactOptionalPropertyTypes rejected passing string | undefined into the optional effort fields, which also leaked unknown into the adapter Effect error channel.

Made with Grok 4.6.
2026-08-12 14:49:39 -07:00
Theo Browne fbd04178e1 feat(server): wire Grok Build effort, auth, rewind, and usage
Grok already advertised reasoning effort and rewind over ACP. T3 dropped the metadata and forced a new thread for model changes.

Map the live effort menu into composer options, send session/set_model _meta.reasoningEffort, probe login, roll back turns through _x.ai/rewind, and emit thread token usage.

Made with Grok 4.6.
2026-08-12 14:42:38 -07:00
GianmarcoandCursor ac1264e2ca feat(web): project favicon and workspace icons in command subtitles (#6330)
Co-authored-by: Cursor <[email protected]>
2026-08-12 17:32:58 -04:00
Theo Browne 2eb099fdc8 fix(web): cmd+click sidebar PR numbers open in the browser (#6378) 2026-08-12 14:28:37 -07:00
Bilal BakrandJulius Marminge b28f9bf0a1 feat(web): pull request surfaces — filters & qualifiers, all-server listing, update branch, reactions, in-place editing, smarter diffs (#6039)
Co-authored-by: Julius Marminge <[email protected]>
2026-08-12 22:58:36 +02:00
d0b8d6306b feat(connect): deregister account environments from any client (#4844)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-08-12 22:46:23 +02:00
Exotic 9666b87516 fix(web): preserve appearance mode when changing themes (#6343) 2026-08-12 16:43:40 -04:00
Alex e3a9c2518d test(mobile): seed snoozed showcase threads (#5155) 2026-08-12 16:43:18 -04:00
Julius Marminge 18918d1c4d Fix mobile command popover glass rendering (#6370) 2026-08-12 22:21:45 +02:00
t3-code[bot]andmaria 8d24b5131f fix(web): open modified PR clicks in browser (#6278)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
Co-authored-by: maria <[email protected]>
2026-08-12 14:32:44 -04:00
Exotic 770946d026 fix(web): render tooltips above dropdowns (#6241) 2026-08-12 14:32:20 -04:00
8601797233 fix(web): align update toast release notes link (#6322)
Co-authored-by: t3-code[bot] <219304759+t3-code[bot]@users.noreply.github.com>
Co-authored-by: Utkarsh Patil <[email protected]>
Co-authored-by: Exotic <[email protected]>
2026-08-12 14:32:10 -04:00
Exotic b73232bdd3 feat(web): reset sidebar width on double click (#6320) 2026-08-12 10:07:39 -04:00
Wout Stiens f131228a59 fix(web): theme Clerk surfaces (#6300) 2026-08-12 19:36:04 +05:30
t3-code[bot]andWout Stiens e321667b10 fix(web): prevent changed files header overlap (#6314)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
Co-authored-by: Wout Stiens <[email protected]>
2026-08-12 08:56:13 -04:00
Julius Marminge 849bac8946 fix(connect): preserve CLI OAuth parameters through browser sign-in (#6285) 2026-08-12 12:58:34 +02:00
t3-code[bot]andUtkarsh Patil 6fd088af9f fix(web): align mobile onboarding header (#6293)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
Co-authored-by: Utkarsh Patil <[email protected]>
2026-08-12 16:07:44 +05:30
Wout Stiens b54bfc9312 feat(web): a better right panel empty state (#6258) 2026-08-12 15:28:46 +05:30
Nick Anisimovandshivam e1378a1f4d fix(mobile): keep ordered lists inside user bubbles (#6154)
Co-authored-by: shivam <[email protected]>
2026-08-12 14:39:51 +05:30
t3-code[bot]andmaria 5a84614809 fix(web): align the composer model picker (#6252)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
Co-authored-by: maria <[email protected]>
2026-08-11 22:38:45 -04:00
148 changed files with 14542 additions and 902 deletions

No files matched your search

@@ -1,4 +1,3 @@
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
import type { ComposerTriggerKind } from "@t3tools/shared/composerTrigger";
import type { ServerProviderSkill, ServerProviderSlashCommand } from "@t3tools/contracts";
import { SymbolView } from "../../components/AppSymbol";
@@ -6,6 +5,7 @@ import { memo } from "react";
import { Pressable, ScrollView, useColorScheme, View, type ViewStyle } from "react-native";
import { AppText as Text } from "../../components/AppText";
import { GlassSurface } from "../../components/GlassSurface";
import { PierreEntryIcon } from "../../components/PierreEntryIcon";
export type ComposerCommandItem =
| {
@@ -56,33 +56,14 @@ function PopoverSurface(props: {
...props.style,
};
if (isLiquidGlassSupported) {
return (
<LiquidGlassView
effect="clear"
interactive={false}
tintColor={props.isDarkMode ? "rgba(30,30,32,0.95)" : "rgba(255,255,255,0.92)"}
colorScheme={props.isDarkMode ? "dark" : "light"}
style={baseStyle}
>
{props.children}
</LiquidGlassView>
);
}
return (
<View
style={[
baseStyle,
{
backgroundColor: props.isDarkMode ? "rgba(44,44,46,0.96)" : "rgba(255,255,255,0.96)",
borderWidth: 1,
borderColor: props.isDarkMode ? "rgba(255,255,255,0.08)" : "rgba(0,0,0,0.06)",
},
]}
<GlassSurface
glassEffectStyle="clear"
tintColor={props.isDarkMode ? "rgba(30,30,32,0.95)" : "rgba(255,255,255,0.92)"}
style={baseStyle}
>
{props.children}
</View>
</GlassSurface>
);
}
@@ -104,6 +104,10 @@ import { useMarkdownCodeHighlight } from "./markdownCodeHighlightState";
import { useAssetUrl } from "../../state/assets";
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
const WIDE_MARKDOWN_BLOCK_OPTIONS = {
includeOrderedLists: Platform.OS === "android",
} as const;
const MESSAGE_TIME_FORMATTER = new Intl.DateTimeFormat(undefined, {
hour: "numeric",
minute: "2-digit",
@@ -888,7 +892,7 @@ function renderFeedEntry(
// children during the unclamped pass and never moves them once the width
// is clamped, so the paragraphs around the block end up drawn on top of
// each other. Pinning the width removes that pass.
const hasWideBlock = hasWideMarkdownBlock(message.text);
const hasWideBlock = hasWideMarkdownBlock(message.text, WIDE_MARKDOWN_BLOCK_OPTIONS);
const assistantTurnStillInProgress =
message.role === "assistant" &&
props.unsettledTurnId !== null &&
@@ -17,6 +17,30 @@ describe("hasWideMarkdownBlock", () => {
expect(hasWideMarkdownBlock(" ```\ncode\n```")).toBe(true);
});
it("detects top-level and blockquoted ordered-list markers", () => {
expect(hasWideMarkdownBlock("1. One\n2. Two\n3. Three\n4. Four\n5. Five")).toBe(true);
expect(hasWideMarkdownBlock("before\n3) Three")).toBe(true);
expect(hasWideMarkdownBlock("> 1. One\n> 2. Two")).toBe(true);
expect(hasWideMarkdownBlock("> > 3) Three")).toBe(true);
});
it("detects nested ordered lists without treating indented code as a list", () => {
expect(hasWideMarkdownBlock("- Parent\n 1. Child\n 2. Child")).toBe(true);
expect(hasWideMarkdownBlock("> - Parent\n> 1. Child")).toBe(true);
expect(hasWideMarkdownBlock(" 1. indented code")).toBe(false);
expect(hasWideMarkdownBlock(" - code-like bullet\n 1. indented code")).toBe(false);
});
it("can limit ordered-list width pinning to Android", () => {
const orderedList = "1. One\n2. Two";
expect(hasWideMarkdownBlock(orderedList, { includeOrderedLists: true })).toBe(true);
expect(hasWideMarkdownBlock(orderedList, { includeOrderedLists: false })).toBe(false);
expect(hasWideMarkdownBlock("```\ncode\n```", { includeOrderedLists: false })).toBe(true);
expect(hasWideMarkdownBlock("| a | b |\n| --- | --- |", { includeOrderedLists: false })).toBe(
true,
);
});
it("detects GFM tables", () => {
expect(hasWideMarkdownBlock("| a | b |\n| --- | --- |\n| 1 | 2 |")).toBe(true);
expect(hasWideMarkdownBlock("a | b\n:-- | --:\n1 | 2")).toBe(true);
+60 -8
View File
@@ -1,9 +1,10 @@
/**
* Detects markdown that the JS renderer draws as a standalone block View
* wrapping a horizontal ScrollView — fenced code blocks and GFM tables.
* Detects markdown that the JS renderer draws as a block requiring a definite
* user-bubble width — fenced code blocks, GFM tables, and ordered lists.
*
* Those blocks report an intrinsic width equal to their widest line, which is
* effectively unbounded. A user bubble sizes itself from its content
* Fenced code blocks and tables report an intrinsic width equal to their
* widest line, which is effectively unbounded. A user bubble sizes itself
* from its content
* (`maxWidth` with no `width`), so Android lays the bubble's children out
* during the unclamped intrinsic pass — where the surrounding paragraphs
* collapse to a single line — and never repositions them once the width is
@@ -12,12 +13,57 @@
* intrinsic pass entirely, which is the same reason review-comment bubbles
* already carry an explicit width.
*
* Indented (four-space) code blocks are deliberately not detected: they are
* vanishingly rare in chat input and the check would fire on ordinary nested
* list continuations.
* Ordered lists hit the same Android layout bug because each item contains a
* flexing content column inside a shrink-to-fit row.
*
* A four-space ordered marker is only treated as a list when the preceding
* non-empty line is a less-indented list item. This keeps standalone indented
* code out of the heuristic while covering nested lists.
*/
const FENCED_CODE_BLOCK = /^ {0,3}(?:```|~~~)/m;
// Trades some precision for a simple check, favoring false positives over false
// negatives: list-shaped paragraph may get a wider bubble
const ORDERED_LIST_ITEM = /^ {0,3}\d{1,9}[.)](?:[ \t]+|$)/;
const INDENTED_ORDERED_LIST_ITEM = /^( {4,})\d{1,9}[.)](?:[ \t]+|$)/;
const ANY_LIST_ITEM = /^( *)(?:[-+*]|\d{1,9}[.)])(?:[ \t]+|$)/;
const BLOCKQUOTE_PREFIX = /^ {0,3}>[ \t]?/;
export interface WideMarkdownBlockOptions {
readonly includeOrderedLists?: boolean;
}
function stripBlockquotePrefixes(line: string): string {
let content = line;
while (BLOCKQUOTE_PREFIX.test(content)) {
content = content.replace(BLOCKQUOTE_PREFIX, "");
}
return content;
}
function hasOrderedListItem(text: string): boolean {
let previousNonEmptyLine: string | null = null;
for (const rawLine of text.split("\n")) {
const line = stripBlockquotePrefixes(rawLine);
if (ORDERED_LIST_ITEM.test(line)) {
return true;
}
const nestedMatch = INDENTED_ORDERED_LIST_ITEM.exec(line);
const parentMatch =
previousNonEmptyLine === null ? null : ANY_LIST_ITEM.exec(previousNonEmptyLine);
if (nestedMatch && parentMatch && parentMatch[1].length < nestedMatch[1].length) {
return true;
}
if (line.trim().length > 0) {
previousNonEmptyLine = line;
}
}
return false;
}
function isTableDelimiterRow(line: string): boolean {
const trimmed = line.trim();
@@ -27,10 +73,16 @@ function isTableDelimiterRow(line: string): boolean {
return /^[|\-: \t]+$/.test(trimmed);
}
export function hasWideMarkdownBlock(text: string): boolean {
export function hasWideMarkdownBlock(
text: string,
options: WideMarkdownBlockOptions = {},
): boolean {
if (FENCED_CODE_BLOCK.test(text)) {
return true;
}
if (options.includeOrderedLists !== false && hasOrderedListItem(text)) {
return true;
}
if (!text.includes("|")) {
return false;
}
+66 -3
View File
@@ -279,9 +279,26 @@ function modeState(): AcpSchema.SessionModeState {
}
const grokAcpModels: ReadonlyArray<AcpSchema.ModelInfo> = [
{ modelId: "grok-build", name: "Grok Build" },
{
modelId: "grok-build",
name: "Grok Build",
_meta: {
supportsReasoningEffort: true,
reasoningEffort: "high",
totalContextTokens: 500000,
reasoningEfforts: [
{ id: "xhigh", value: "xhigh", label: "Extra High Effort" },
{ id: "high", value: "high", label: "High Effort", default: true },
{ id: "medium", value: "medium", label: "Medium Effort" },
{ id: "low", value: "low", label: "Low Effort" },
],
},
},
{ modelId: "grok-mock-alt", name: "Grok Mock Alt" },
];
const enableRewind = process.env.T3_ACP_ENABLE_REWIND === "1";
const emitUsage = process.env.T3_ACP_EMIT_USAGE === "1";
let rewindPoints: Array<{ prompt_index: number; prompt_preview: string }> = [];
function modelState(): AcpSchema.SessionModelState {
const modelId = grokAcpModels.some((model) => model.modelId === currentModelId)
@@ -392,7 +409,12 @@ const program = Effect.gen(function* () {
);
}
currentModelId = request.modelId;
return {};
return {
_meta: {
model: { Ok: request.modelId },
...(request._meta ?? {}),
},
};
}),
);
@@ -873,11 +895,52 @@ const program = Effect.gen(function* () {
},
});
return { stopReason: "end_turn" };
if (enableRewind) {
const preview =
request.prompt.find((block) => block.type === "text" && "text" in block)?.text ?? "";
rewindPoints.push({
prompt_index: rewindPoints.length,
prompt_preview: typeof preview === "string" ? preview : "",
});
}
return {
stopReason: "end_turn",
...(emitUsage
? {
_meta: {
usage: {
input_tokens: 10,
output_tokens: 4,
reasoning_tokens: 3,
},
},
}
: {}),
};
}),
);
yield* agent.handleUnknownExtRequest((method, params) => {
if (method === "_x.ai/rewind/points") {
return Effect.succeed({ rewind_points: rewindPoints });
}
if (method === "_x.ai/rewind/execute") {
const record = typeof params === "object" && params !== null ? params : {};
const target =
"targetPromptIndex" in record && typeof record.targetPromptIndex === "number"
? record.targetPromptIndex
: undefined;
if (target === undefined) {
return Effect.succeed({ success: false, error: "missing targetPromptIndex" });
}
rewindPoints = rewindPoints.filter((point) => point.prompt_index < target);
return Effect.succeed({
success: true,
target_prompt_index: target,
mode: "conversation_only",
});
}
if (method === "cursor/list_available_models") {
return Effect.succeed({
models: availableModels(),
+3
View File
@@ -58,10 +58,13 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.pullRequestsActivity]: AuthOrchestrationReadScope,
[WS_METHODS.pullRequestsDiffFileContents]: AuthOrchestrationReadScope,
[WS_METHODS.pullRequestsRunAction]: AuthOrchestrationOperateScope,
[WS_METHODS.pullRequestsUpdate]: AuthOrchestrationOperateScope,
[WS_METHODS.pullRequestsComment]: AuthOrchestrationOperateScope,
[WS_METHODS.pullRequestsUpdateComment]: AuthOrchestrationOperateScope,
[WS_METHODS.pullRequestsSubmitReview]: AuthOrchestrationOperateScope,
[WS_METHODS.pullRequestsReplyToThread]: AuthOrchestrationOperateScope,
[WS_METHODS.pullRequestsSetThreadResolution]: AuthOrchestrationOperateScope,
[WS_METHODS.pullRequestsSetReaction]: AuthOrchestrationOperateScope,
// Read scope like the reads it un-caches: refreshing is part of reading, and a read-only
// client pressing refresh must not be told it may not look again.
[WS_METHODS.pullRequestsInvalidate]: AuthOrchestrationReadScope,
+9 -7
View File
@@ -26,7 +26,6 @@ import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
import {
buildConnectAuthorizeRequestUrl,
buildConnectClerkAuthorizeUrl,
checkConnectAuthCode,
connectCallbackUrl,
} from "@t3tools/shared/connectAuth";
@@ -367,6 +366,7 @@ export const make = Effect.gen(function* () {
const login = Effect.fn("cloud.cli_token.login")(function* () {
const metadata = yield* cloudCliOAuthConfig;
const hostedAppUrl = yield* hostedAppUrlConfig;
const { verifier, challenge, state } = yield* makePkceRequest;
const callback = yield* Deferred.make<string>();
const callbackRoute = HttpRouter.add(
@@ -392,19 +392,21 @@ export const make = Effect.gen(function* () {
Layer.provide(
NodeHttpServer.layer(NodeHttp.createServer, {
host: "127.0.0.1",
port: 34338,
port: metadata.loopbackPort,
disablePreemptiveShutdown: true,
}),
),
Layer.build,
);
const authorizationUrl = buildConnectClerkAuthorizeUrl({
authorizationEndpoint: metadata.authorizationEndpoint,
clientId: metadata.clientId,
redirectUri: metadata.redirectUri,
scopes: metadata.scopes,
// The hosted /connect page establishes a Clerk session before forwarding
// the request to /oauth/authorize with the loopback redirect URI. Sending
// a signed-out browser to /oauth/authorize directly loses the authorize
// parameters across Clerk's sign-in redirect (#5051).
const authorizationUrl = buildConnectAuthorizeRequestUrl({
hostedAppUrl,
state,
challenge,
loopbackPort: metadata.loopbackPort,
});
yield* Console.log(formatLoopbackAuthorizationPrompt(authorizationUrl));
const authorization = yield* waitForLoopbackAuthorization({
+1 -2
View File
@@ -90,9 +90,9 @@ it.effect("derives direct Clerk OAuth endpoints from statically injected public
}).pipe(provideEnv({}));
assert.deepEqual(config, {
authorizationEndpoint: "https://clerk.example.test/oauth/authorize",
tokenEndpoint: "https://clerk.example.test/oauth/token",
clientId: "oauth_client_embedded",
loopbackPort: 34338,
redirectUri: "http://127.0.0.1:34338/callback",
scopes: ["openid", "profile", "email"],
});
@@ -111,7 +111,6 @@ it.effect("prefers runtime Clerk OAuth config overrides over statically injected
}),
);
assert.equal(config.authorizationEndpoint, "https://runtime.example.test/oauth/authorize");
assert.equal(config.tokenEndpoint, "https://runtime.example.test/oauth/token");
assert.equal(config.clientId, "oauth_client_runtime");
}),
+15 -5
View File
@@ -1,4 +1,8 @@
import { CONNECT_OAUTH_SCOPES, DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth";
import {
connectLoopbackRedirectUri,
CONNECT_OAUTH_SCOPES,
DEFAULT_HOSTED_APP_URL,
} from "@t3tools/shared/connectAuth";
import { clerkFrontendApiUrlFromPublishableKey } from "@t3tools/shared/relayAuth";
import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";
import * as Config from "effect/Config";
@@ -14,7 +18,7 @@ declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_URL__: string | undefined;
declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_DATASET__: string | undefined;
declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_TOKEN__: string | undefined;
const CLOUD_CLI_OAUTH_REDIRECT_URI = "http://127.0.0.1:34338/callback";
const CLOUD_CLI_OAUTH_LOOPBACK_PORT = 34338;
const CLOUD_CLI_OAUTH_SCOPES = CONNECT_OAUTH_SCOPES;
function validateRelayUrl(value: string) {
@@ -145,10 +149,16 @@ function makePublicValueConfig(name: string, fallback: string) {
);
}
/**
* The CLI never calls Clerk's /oauth/authorize itself: the browser leg goes
* through the hosted /connect page, which builds the authorize URL after a
* Clerk session exists (see CliTokenManager.login). Only the token endpoint
* is contacted directly.
*/
export interface CloudCliOAuthConfig {
readonly authorizationEndpoint: string;
readonly tokenEndpoint: string;
readonly clientId: string;
readonly loopbackPort: number;
readonly redirectUri: string;
readonly scopes: typeof CLOUD_CLI_OAUTH_SCOPES;
}
@@ -184,10 +194,10 @@ export function makeCloudCliOAuthConfig({
Effect.map(
(clerkFrontendApiUrl) =>
({
authorizationEndpoint: `${clerkFrontendApiUrl}/oauth/authorize`,
tokenEndpoint: `${clerkFrontendApiUrl}/oauth/token`,
clientId,
redirectUri: CLOUD_CLI_OAUTH_REDIRECT_URI,
loopbackPort: CLOUD_CLI_OAUTH_LOOPBACK_PORT,
redirectUri: connectLoopbackRedirectUri(CLOUD_CLI_OAUTH_LOOPBACK_PORT),
scopes: CLOUD_CLI_OAUTH_SCOPES,
}) satisfies CloudCliOAuthConfig,
),
+54
View File
@@ -9,8 +9,10 @@ import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as References from "effect/References";
import * as Scope from "effect/Scope";
import { ChildProcessSpawner } from "effect/unstable/process";
import { expect } from "vite-plus/test";
@@ -1386,6 +1388,58 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("status logs actionable provider detail without exposing the upstream cause", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/status-rate-limited"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-rate-limited"]);
const upstreamCause = "GraphQL rate limit for user ID 51714798 and token secret-value";
const { manager } = yield* makeManager({
ghScenario: {
failWith: new GitHubCli.GitHubCliRateLimitError({
command: "gh",
cwd: repoDir,
cause: new Error(upstreamCause),
}),
},
});
const logs: Array<{ message: string; annotations: Record<string, unknown> }> = [];
const logger = Logger.make<unknown, void>(({ fiber, message }) => {
logs.push({
message: String(message),
annotations: { ...fiber.getRef(References.CurrentLogAnnotations) },
});
});
const status = yield* manager
.status({ cwd: repoDir })
.pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
expect(status.pr).toBeNull();
const warning = logs.find((entry) => entry.message.includes("PR lookup failed"));
expect(warning?.annotations).toMatchObject({
operation: "lookupStatusPr",
branch: "feature/status-rate-limited",
errorTag: "SourceControlProviderError",
provider: "github",
providerOperation: "listChangeRequests",
providerCommand: "gh",
errorDetail:
"GitHub API rate limit exceeded. Run `gh api rate_limit` to inspect the quota and reset time.",
});
const loggedText = [
warning?.message ?? "",
...Object.values(warning?.annotations ?? {}).map(String),
].join("\n");
expect(loggedText).not.toContain(upstreamCause);
expect(loggedText).not.toContain("secret-value");
}),
);
it.effect("status keeps the last known PR when a later lookup fails", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
+11
View File
@@ -12,6 +12,7 @@ import * as Option from "effect/Option";
import * as Order from "effect/Order";
import * as Path from "effect/Path";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import {
GitActionProgressEvent,
GitActionProgressPhase,
@@ -28,6 +29,7 @@ import {
type VcsStatusRemoteResult,
VcsStatusResult,
ModelSelection,
SourceControlProviderError,
type SourceControlWritingStyleSettings,
} from "@t3tools/contracts";
import {
@@ -113,6 +115,7 @@ const PR_LOOKUP_CACHE_TTL = Duration.minutes(2);
const PR_LOOKUP_FAILURE_BASE_TTL = Duration.seconds(20);
const PR_LOOKUP_FAILURE_MAX_TTL = Duration.minutes(15);
const PR_LOOKUP_CACHE_CAPACITY = 2_048;
const isSourceControlProviderError = Schema.is(SourceControlProviderError);
/**
* How long a failed PR lookup is cached, given the number of consecutive
@@ -1048,6 +1051,14 @@ export const make = Effect.gen(function* () {
typeof error === "object" && error !== null && "_tag" in error
? String(error._tag)
: typeof error,
...(isSourceControlProviderError(error)
? {
provider: error.provider,
providerOperation: error.operation,
providerCommand: error.command ?? "unknown",
errorDetail: error.detail,
}
: {}),
}),
Effect.andThen(resolveBranchHeadContext(cwd, details)),
Effect.map((headContext) =>
@@ -1197,4 +1197,120 @@ it.layer(grokAdapterTestLayer)("GrokAdapterLive", (it) => {
yield* adapter.stopSession(threadId);
}),
);
it.effect("sends session/set_model _meta.reasoningEffort", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-effort-set-model");
const tempDir = yield* Effect.promise(() =>
NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "grok-effort-")),
);
const requestLogPath = NodePath.join(tempDir, "requests.ndjson");
const wrapperPath = yield* Effect.promise(() =>
makeMockGrokWrapper({ T3_ACP_REQUEST_LOG_PATH: requestLogPath }),
);
const adapter = yield* makeTestAdapter(wrapperPath);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: {
instanceId: ProviderInstanceId.make("grok"),
model: "grok-build",
options: [{ id: "reasoningEffort", value: "xhigh" }],
},
});
yield* waitForFileContent(requestLogPath, 80, "session/set_model");
const lines = yield* Effect.promise(() => readJsonLines(requestLogPath));
const setModel = lines.find((line) => line.method === "session/set_model");
assert.isDefined(setModel);
assert.equal(
(setModel?.params as { _meta?: { reasoningEffort?: string } } | undefined)?._meta
?.reasoningEffort,
"xhigh",
);
yield* adapter.stopSession(threadId);
}),
);
it.effect("emits token usage from the Grok prompt result", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-usage");
const wrapperPath = yield* Effect.promise(() =>
makeMockGrokWrapper({ T3_ACP_EMIT_USAGE: "1" }),
);
const adapter = yield* makeTestAdapter(wrapperPath);
const usage = yield* Deferred.make<ProviderRuntimeEvent>();
const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
event.type === "thread.token-usage.updated" ? Deferred.succeed(usage, event) : Effect.void,
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
});
yield* adapter.sendTurn({ threadId, input: "count tokens", attachments: [] });
const event = yield* Deferred.await(usage);
assert.equal(event.type, "thread.token-usage.updated");
if (event.type === "thread.token-usage.updated") {
assert.equal(event.payload.usage.usedTokens, 17);
assert.equal(event.payload.usage.inputTokens, 10);
}
yield* Fiber.interrupt(eventsFiber);
yield* adapter.stopSession(threadId);
}),
);
it.effect("rolls back Grok conversation turns through rewind", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-rewind");
const wrapperPath = yield* Effect.promise(() =>
makeMockGrokWrapper({ T3_ACP_ENABLE_REWIND: "1" }),
);
const adapter = yield* makeTestAdapter(wrapperPath);
const firstTurnDone = yield* Deferred.make<void>();
const secondTurnDone = yield* Deferred.make<void>();
const completedTurns = yield* Ref.make(0);
const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
event.type === "turn.completed"
? Ref.updateAndGet(completedTurns, (count) => count + 1).pipe(
Effect.flatMap((count) => {
if (count === 1) {
return Deferred.succeed(firstTurnDone, undefined);
}
if (count === 2) {
return Deferred.succeed(secondTurnDone, undefined);
}
return Effect.void;
}),
)
: Effect.void,
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
});
yield* adapter.sendTurn({ threadId, input: "first", attachments: [] });
yield* Deferred.await(firstTurnDone);
yield* adapter.sendTurn({ threadId, input: "second", attachments: [] });
yield* Deferred.await(secondTurnDone);
const rolled = yield* adapter.rollbackThread(threadId, 1);
assert.equal(rolled.turns.length, 1);
yield* Fiber.interrupt(eventsFiber);
yield* adapter.stopSession(threadId);
}),
);
});
+155 -21
View File
@@ -54,15 +54,26 @@ import {
import { parsePermissionRequest } from "../acp/AcpRuntimeModel.ts";
import { makeAcpNativeLoggerFactory } from "../acp/AcpNativeLogging.ts";
import {
advertisedGrokReasoningEffortsFromSessionSetup,
applyGrokAcpModelSelection,
currentGrokMaxTokensFromSessionSetup,
currentGrokModelIdFromSessionSetup,
currentGrokReasoningEffortFromSessionSetup,
grokMaxTokensByModelFromSessionSetup,
grokReasoningEffortMenusFromSessionSetup,
makeGrokAcpRuntime,
requestedGrokReasoningEffort,
resolveGrokAcpBaseModelId,
} from "../acp/GrokAcpSupport.ts";
import {
extractGrokTokenUsage,
extractXAiAskUserQuestions,
grokPromptCountForTurns,
grokRewindTargetForTurnCount,
makeXAiAskUserQuestionCancelledResponse,
makeXAiAskUserQuestionResponse,
parseGrokRewindExecute,
parseGrokRewindPoints,
promptResponseHasMissingXAiStopReason,
XAiAskUserQuestionRequest,
} from "../acp/XAiAcpExtension.ts";
@@ -117,6 +128,10 @@ interface GrokSessionContext {
* continues it, and only the last remaining prompt settles the turn. */
promptsInFlight: number;
currentModelId: string | undefined;
currentReasoningEffort: string | undefined;
reasoningEffortMenus: Map<string, ReadonlyArray<string>>;
maxTokensByModel: Map<string, number>;
maxTokens: number | undefined;
stopped: boolean;
}
@@ -549,6 +564,10 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
const cwd = path.resolve(input.cwd.trim());
const grokModelSelection =
input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;
const requestedStartModelId = grokModelSelection?.model
? resolveGrokAcpBaseModelId(grokModelSelection.model)
: undefined;
const requestedStartEffort = requestedGrokReasoningEffort(grokModelSelection, []);
const existing = sessions.get(input.threadId);
if (existing && !existing.stopped) {
yield* stopSessionInternal(existing);
@@ -573,6 +592,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
const acp = yield* makeGrokAcpRuntime({
grokSettings,
...(options?.environment ? { environment: options.environment } : {}),
...(requestedStartEffort ? { reasoningEffort: requestedStartEffort } : {}),
childProcessSpawner,
cwd,
...(resumeSessionId ? { resumeSessionId } : {}),
@@ -735,16 +755,27 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
),
);
const requestedStartModelId = grokModelSelection?.model
? resolveGrokAcpBaseModelId(grokModelSelection.model)
: undefined;
const boundModelId = yield* applyGrokAcpModelSelection({
const startedModelId = currentGrokModelIdFromSessionSetup(started.sessionSetupResult);
const advertisedStartEfforts = advertisedGrokReasoningEffortsFromSessionSetup(
started.sessionSetupResult,
requestedStartModelId ?? startedModelId,
);
const boundSelection = yield* applyGrokAcpModelSelection({
runtime: acp,
currentModelId: currentGrokModelIdFromSessionSetup(started.sessionSetupResult),
currentModelId: startedModelId,
requestedModelId: requestedStartModelId,
currentReasoningEffort: currentGrokReasoningEffortFromSessionSetup(
started.sessionSetupResult,
),
requestedReasoningEffort: requestedGrokReasoningEffort(
grokModelSelection,
advertisedStartEfforts,
),
mapError: (cause) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_model", cause),
});
const boundModelId = boundSelection.modelId;
const maxTokensByModel = grokMaxTokensByModelFromSessionSetup(started.sessionSetupResult);
const now = yield* nowIso;
const session: ProviderSession = {
@@ -778,6 +809,14 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
interruptedTurnIds: new Set(),
promptsInFlight: 0,
currentModelId: boundModelId,
currentReasoningEffort: boundSelection.reasoningEffort,
reasoningEffortMenus: grokReasoningEffortMenusFromSessionSetup(
started.sessionSetupResult,
),
maxTokensByModel,
maxTokens:
(boundModelId ? maxTokensByModel.get(boundModelId) : undefined) ??
currentGrokMaxTokensFromSessionSetup(started.sessionSetupResult),
stopped: false,
};
@@ -942,13 +981,29 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
const requestedTurnModelId = turnModelSelection?.model
? resolveGrokAcpBaseModelId(turnModelSelection.model)
: undefined;
const currentModelId = yield* applyGrokAcpModelSelection({
const advertisedTurnEfforts = requestedTurnModelId
? (ctx.reasoningEffortMenus.get(requestedTurnModelId) ?? [])
: ctx.currentModelId
? (ctx.reasoningEffortMenus.get(ctx.currentModelId) ?? [])
: [];
const turnSelection = yield* applyGrokAcpModelSelection({
runtime: ctx.acp,
currentModelId: ctx.currentModelId,
requestedModelId: requestedTurnModelId,
currentReasoningEffort: ctx.currentReasoningEffort,
requestedReasoningEffort: requestedGrokReasoningEffort(
turnModelSelection,
advertisedTurnEfforts,
),
mapError: (cause) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_model", cause),
});
const currentModelId = turnSelection.modelId;
ctx.currentModelId = currentModelId;
ctx.currentReasoningEffort = turnSelection.reasoningEffort;
if (currentModelId) {
ctx.maxTokens = ctx.maxTokensByModel.get(currentModelId) ?? ctx.maxTokens;
}
const text = input.input?.trim();
const imagePromptParts = yield* Effect.forEach(
@@ -1143,6 +1198,17 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
}
appendPromptResultToTurn(ctx, prepared.turnId, prepared.promptParts, result);
const tokenUsage = extractGrokTokenUsage(result._meta, ctx.maxTokens);
if (tokenUsage) {
yield* offerRuntimeEvent({
type: "thread.token-usage.updated",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: prepared.turnId,
payload: { usage: tokenUsage },
});
}
ctx.session = {
...ctx.session,
status: "running",
@@ -1398,21 +1464,89 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
});
const rollbackThread: GrokAdapterShape["rollbackThread"] = (threadId, numTurns) =>
Effect.gen(function* () {
yield* requireSession(threadId);
if (!Number.isInteger(numTurns) || numTurns < 1) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "rollbackThread",
issue: "numTurns must be an integer >= 1.",
});
}
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "thread/rollback",
detail: "Grok ACP sessions do not support provider-side rollback yet.",
});
});
withThreadLock(
threadId,
Effect.gen(function* () {
const ctx = yield* requireSession(threadId);
if (!Number.isInteger(numTurns) || numTurns < 1) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "rollbackThread",
issue: "numTurns must be an integer >= 1.",
});
}
const promptCount = grokPromptCountForTurns(ctx.turns, numTurns);
if (promptCount < 1) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "_x.ai/rewind/execute",
detail: "Grok has no rewind point for that many turns.",
});
}
const acpSessionId = ctx.acpSessionId;
const pointsPayload = yield* ctx.acp
.request("_x.ai/rewind/points", {
sessionId: acpSessionId,
})
.pipe(
Effect.mapError((error) =>
mapAcpToAdapterError(PROVIDER, threadId, "_x.ai/rewind/points", error),
),
);
const liveCtx = yield* requireSession(threadId);
if (liveCtx.acpSessionId !== acpSessionId) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "_x.ai/rewind/execute",
detail: "Grok session changed before rewind completed.",
});
}
const target = grokRewindTargetForTurnCount(
parseGrokRewindPoints(pointsPayload),
promptCount,
);
if (!target) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "_x.ai/rewind/execute",
detail: "Grok has no rewind point for that many turns.",
});
}
const executePayload = yield* liveCtx.acp
.request("_x.ai/rewind/execute", {
sessionId: acpSessionId,
targetPromptIndex: target.promptIndex,
mode: "conversation_only",
force: true,
})
.pipe(
Effect.mapError((error) =>
mapAcpToAdapterError(PROVIDER, threadId, "_x.ai/rewind/execute", error),
),
);
const committedCtx = yield* requireSession(threadId);
if (committedCtx.acpSessionId !== acpSessionId) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "_x.ai/rewind/execute",
detail: "Grok session changed before rewind completed.",
});
}
const executed = parseGrokRewindExecute(executePayload);
if (!executed?.success) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "_x.ai/rewind/execute",
detail: executed?.error ?? "Grok rewind did not succeed.",
});
}
committedCtx.turns = committedCtx.turns.slice(
0,
Math.max(0, committedCtx.turns.length - numTurns),
);
return { threadId, turns: committedCtx.turns };
}),
);
const stopSession: GrokAdapterShape["stopSession"] = (threadId) =>
withThreadLock(
@@ -31,7 +31,8 @@ describe("buildInitialGrokProviderSnapshot", () => {
expect(snapshot.status).toBe("warning");
expect(snapshot.version).toBeNull();
expect(snapshot.message).toContain("Checking Grok");
expect(snapshot.requiresNewThreadForModelChange).toBe(true);
expect(snapshot.requiresNewThreadForModelChange).toBe(false);
expect(snapshot.models[0]?.capabilities?.optionDescriptors?.[0]?.id).toBe("reasoningEffort");
}),
);
});
+26 -12
View File
@@ -14,7 +14,6 @@ import * as Option from "effect/Option";
import * as Result from "effect/Result";
import { HttpClient } from "effect/unstable/http";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { createModelCapabilities } from "@t3tools/shared/model";
import { resolveSpawnCommand } from "@t3tools/shared/shell";
import {
@@ -29,27 +28,33 @@ import {
enrichProviderSnapshotWithVersionAdvisory,
type ProviderMaintenanceCapabilities,
} from "../providerMaintenance.ts";
import { makeGrokAcpRuntime, resolveGrokAcpBaseModelId } from "../acp/GrokAcpSupport.ts";
import {
fallbackGrokReasoningEffortCapabilities,
grokReasoningEffortCapabilities,
isGrokAcpAuthFailure,
makeGrokAcpRuntime,
parseGrokAcpModelMeta,
resolveGrokAcpBaseModelId,
} from "../acp/GrokAcpSupport.ts";
const GROK_PRESENTATION = {
displayName: "Grok",
badgeLabel: "Early Access",
showInteractionModeToggle: false,
requiresNewThreadForModelChange: true,
requiresNewThreadForModelChange: false,
} as const;
const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({
optionDescriptors: [],
});
const FALLBACK_CAPABILITIES: ModelCapabilities = fallbackGrokReasoningEffortCapabilities();
const VERSION_PROBE_TIMEOUT_MS = 4_000;
const GROK_ACP_MODEL_DISCOVERY_TIMEOUT_MS = 15_000;
const GROK_API_KEY_ENV = "XAI_API_KEY";
const GROK_BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
{
slug: "grok-build",
name: "Grok Build",
isCustom: false,
capabilities: EMPTY_CAPABILITIES,
capabilities: FALLBACK_CAPABILITIES,
},
];
@@ -96,7 +101,7 @@ function grokModelsFromSettings(
customModels: ReadonlyArray<string> | undefined,
builtInModels: ReadonlyArray<ServerProviderModel> = GROK_BUILT_IN_MODELS,
): ReadonlyArray<ServerProviderModel> {
return providerModelsFromSettings(builtInModels, customModels ?? [], EMPTY_CAPABILITIES);
return providerModelsFromSettings(builtInModels, customModels ?? [], FALLBACK_CAPABILITIES);
}
function buildGrokDiscoveredModelsFromSessionModelState(
@@ -113,11 +118,14 @@ function buildGrokDiscoveredModelsFromSessionModelState(
return undefined;
}
seen.add(slug);
const meta = parseGrokAcpModelMeta(model._meta);
return {
slug,
name: model.name.trim() || slug,
isCustom: false,
capabilities: EMPTY_CAPABILITIES,
capabilities: meta.supportsReasoningEffort
? grokReasoningEffortCapabilities(meta.reasoningEfforts)
: FALLBACK_CAPABILITIES,
};
})
.filter((model): model is ServerProviderModel => model !== undefined);
@@ -256,8 +264,10 @@ export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(func
Effect.exit,
);
if (Exit.isFailure(discoveryExit)) {
const authFailed = isGrokAcpAuthFailure(discoveryExit.cause);
yield* Effect.logWarning("Grok ACP model discovery failed", {
errorTag: causeErrorTag(discoveryExit.cause),
authFailed,
});
return buildServerProvider({
presentation: GROK_PRESENTATION,
@@ -268,8 +278,10 @@ export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(func
installed: true,
version,
status: "error",
auth: { status: "unknown" },
message: "Grok CLI is installed but ACP startup failed. Check server logs for details.",
auth: { status: authFailed ? "unauthenticated" : "unknown" },
message: authFailed
? "Grok CLI is not authenticated. Run `grok login` and try again."
: "Grok CLI is installed but ACP startup failed. Check server logs for details.",
},
});
}
@@ -306,7 +318,9 @@ export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(func
installed: true,
version,
status: "ready",
auth: { status: "unknown" },
auth: environment[GROK_API_KEY_ENV]?.trim()
? { status: "authenticated", type: "api_key", label: "XAI_API_KEY" }
: { status: "authenticated", type: "session", label: "grok.com" },
},
});
});
@@ -226,6 +226,7 @@ export class AcpSessionRuntime extends Context.Service<
*/
readonly setSessionModel: (
modelId: string,
options?: { readonly _meta?: { readonly [x: string]: unknown } },
) => Effect.Effect<EffectAcpSchema.SetSessionModelResponse, EffectAcpErrors.AcpError>;
/**
* Sends a generic ACP extension request and records it through the request logger.
@@ -789,12 +790,13 @@ export const make = (
Effect.flatMap((started) => setConfigOption(started.modelConfigId ?? "model", model)),
Effect.asVoid,
),
setSessionModel: (modelId) =>
setSessionModel: (modelId, options) =>
getStartedState.pipe(
Effect.flatMap((started) => {
const requestPayload = {
sessionId: started.sessionId,
modelId,
...(options?._meta ? { _meta: options._meta } : {}),
} satisfies EffectAcpSchema.SetSessionModelRequest;
return runLoggedRequest(
"session/set_model",
@@ -5,8 +5,14 @@ import * as EffectAcpErrors from "effect-acp/errors";
import {
applyGrokAcpModelSelection,
buildGrokAcpSpawnInput,
GROK_REASONING_EFFORT_OPTION_ID,
grokReasoningEffortCapabilities,
isGrokAcpAuthFailure,
parseGrokAcpModelMeta,
requestedGrokReasoningEffort,
resolveGrokAcpBaseModelId,
} from "./GrokAcpSupport.ts";
import { ProviderInstanceId } from "@t3tools/contracts";
describe("resolveGrokAcpBaseModelId", () => {
it("normalizes empty and custom Grok model ids", () => {
@@ -33,15 +39,79 @@ describe("buildGrokAcpSpawnInput", () => {
},
});
});
it("puts --reasoning-effort before stdio", () => {
const spawn = buildGrokAcpSpawnInput({ binaryPath: "grok" }, "/tmp/project", undefined, "high");
expect(spawn.args).toEqual(["agent", "--reasoning-effort", "high", "stdio"]);
});
it("ignores spawn effort values the CLI rejects", () => {
const spawn = buildGrokAcpSpawnInput({ binaryPath: "grok" }, "/tmp/project", undefined, "max");
expect(spawn.args).toEqual(["agent", "stdio"]);
});
});
describe("parseGrokAcpModelMeta", () => {
it("reads the live Grok effort menu", () => {
const meta = parseGrokAcpModelMeta({
supportsReasoningEffort: true,
reasoningEffort: "high",
totalContextTokens: 500000,
reasoningEfforts: [
{ id: "xhigh", value: "xhigh", label: "Extra High Effort", default: true },
{ id: "high", value: "high", label: "High Effort", default: true },
{ id: "medium", value: "medium", label: "Medium Effort" },
],
});
expect(meta.supportsReasoningEffort).toBe(true);
expect(meta.reasoningEffort).toBe("high");
expect(meta.totalContextTokens).toBe(500000);
expect(meta.reasoningEfforts.map((choice) => choice.id)).toEqual(["xhigh", "high", "medium"]);
expect(
meta.reasoningEfforts.filter((choice) => choice.isDefault).map((choice) => choice.id),
).toEqual(["high"]);
expect(grokReasoningEffortCapabilities(meta.reasoningEfforts).optionDescriptors?.[0]?.id).toBe(
GROK_REASONING_EFFORT_OPTION_ID,
);
});
});
describe("requestedGrokReasoningEffort", () => {
it("drops effort values the current model does not advertise", () => {
expect(
requestedGrokReasoningEffort(
{
instanceId: ProviderInstanceId.make("grok"),
model: "grok-4.5",
options: [{ id: GROK_REASONING_EFFORT_OPTION_ID, value: "xhigh" }],
},
["high", "medium", "low"],
),
).toBeUndefined();
});
});
describe("isGrokAcpAuthFailure", () => {
it("recognizes authenticate failures", () => {
expect(isGrokAcpAuthFailure(new Error("authenticate failed: cached_token"))).toBe(true);
expect(isGrokAcpAuthFailure(new Error("session/new timed out"))).toBe(false);
});
});
describe("applyGrokAcpModelSelection", () => {
const makeRecordingRuntime = (failure?: EffectAcpErrors.AcpError) => {
const modelCalls: Array<string> = [];
const modelCalls: Array<{ modelId: string; effort?: string }> = [];
const runtime = {
setSessionModel: (modelId: string) =>
setSessionModel: (
modelId: string,
options?: { readonly _meta?: { readonly [x: string]: unknown } },
) =>
Effect.gen(function* () {
modelCalls.push(modelId);
const effort = options?._meta?.reasoningEffort;
modelCalls.push({
modelId,
...(typeof effort === "string" ? { effort } : {}),
});
if (failure) return yield* failure;
return {};
}),
@@ -58,8 +128,8 @@ describe("applyGrokAcpModelSelection", () => {
requestedModelId: "grok-mock-alt",
mapError: (cause) => cause.message,
});
expect(modelCalls).toEqual(["grok-mock-alt"]);
expect(result).toBe("grok-mock-alt");
expect(modelCalls).toEqual([{ modelId: "grok-mock-alt" }]);
expect(result).toEqual({ modelId: "grok-mock-alt", reasoningEffort: undefined });
}),
);
@@ -73,7 +143,38 @@ describe("applyGrokAcpModelSelection", () => {
mapError: (cause) => cause.message,
});
expect(modelCalls).toEqual([]);
expect(result).toBe("grok-build");
expect(result).toEqual({ modelId: "grok-build", reasoningEffort: undefined });
}),
);
it.effect("does not carry the previous effort across a model switch", () =>
Effect.gen(function* () {
const { runtime, modelCalls } = makeRecordingRuntime();
const result = yield* applyGrokAcpModelSelection({
runtime,
currentModelId: "grok-4.6",
requestedModelId: "grok-4.5",
currentReasoningEffort: "xhigh",
mapError: (cause) => cause.message,
});
expect(modelCalls).toEqual([{ modelId: "grok-4.5" }]);
expect(result).toEqual({ modelId: "grok-4.5", reasoningEffort: undefined });
}),
);
it.effect("calls session/set_model when only effort changes", () =>
Effect.gen(function* () {
const { runtime, modelCalls } = makeRecordingRuntime();
const result = yield* applyGrokAcpModelSelection({
runtime,
currentModelId: "grok-4.6",
requestedModelId: "grok-4.6",
currentReasoningEffort: "high",
requestedReasoningEffort: "xhigh",
mapError: (cause) => cause.message,
});
expect(modelCalls).toEqual([{ modelId: "grok-4.6", effort: "xhigh" }]);
expect(result).toEqual({ modelId: "grok-4.6", reasoningEffort: "xhigh" });
}),
);
@@ -87,7 +188,7 @@ describe("applyGrokAcpModelSelection", () => {
mapError: (cause) => cause.message,
});
expect(modelCalls).toEqual([]);
expect(result).toBe("grok-build");
expect(result).toEqual({ modelId: "grok-build", reasoningEffort: undefined });
}),
);
+306 -9
View File
@@ -1,4 +1,9 @@
import { type GrokSettings, ProviderDriverKind } from "@t3tools/contracts";
import {
type GrokSettings,
type ModelCapabilities,
type ModelSelection,
ProviderDriverKind,
} from "@t3tools/contracts";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -6,7 +11,11 @@ import * as Scope from "effect/Scope";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import * as EffectAcpErrors from "effect-acp/errors";
import type * as EffectAcpSchema from "effect-acp/schema";
import { normalizeModelSlug } from "@t3tools/shared/model";
import {
createModelCapabilities,
getModelSelectionStringOptionValue,
normalizeModelSlug,
} from "@t3tools/shared/model";
import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
import { makeXAiPromptCompletionRuntime } from "./XAiAcpExtension.ts";
@@ -18,6 +27,18 @@ const GROK_AUTH_METHOD_API_KEY = "xai.api_key";
const GROK_AUTH_METHOD_CACHED_TOKEN = "cached_token";
const GROK_DRIVER_KIND = ProviderDriverKind.make("grok");
/** Composer option id for Grok reasoning effort. Same shape as Codex. */
export const GROK_REASONING_EFFORT_OPTION_ID = "reasoningEffort";
const GROK_SPAWN_EFFORT_LEVELS = new Set(["none", "minimal", "low", "medium", "high", "xhigh"]);
export const FALLBACK_GROK_REASONING_EFFORTS = [
{ id: "xhigh", label: "Extra High", description: "Highest effort and reasoning level" },
{ id: "high", label: "High", description: "Higher implementation quality", isDefault: true },
{ id: "medium", label: "Medium", description: "Balanced effort" },
{ id: "low", label: "Low", description: "Quick implementations" },
] as const;
type GrokAcpRuntimeGrokSettings = Pick<GrokSettings, "binaryPath">;
interface GrokAcpRuntimeInput extends Omit<
@@ -27,16 +48,38 @@ interface GrokAcpRuntimeInput extends Omit<
readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
readonly grokSettings: GrokAcpRuntimeGrokSettings | null | undefined;
readonly environment?: NodeJS.ProcessEnv;
readonly reasoningEffort?: string;
}
export interface GrokReasoningEffortChoice {
readonly id: string;
readonly label: string;
readonly description?: string;
readonly isDefault?: boolean;
}
export interface GrokAcpModelMeta {
readonly supportsReasoningEffort: boolean;
readonly reasoningEffort?: string;
readonly reasoningEfforts: ReadonlyArray<GrokReasoningEffortChoice>;
readonly totalContextTokens?: number;
}
export interface GrokAcpSelection {
readonly modelId: string | undefined;
readonly reasoningEffort: string | undefined;
}
export function buildGrokAcpSpawnInput(
grokSettings: GrokAcpRuntimeGrokSettings | null | undefined,
cwd: string,
environment?: NodeJS.ProcessEnv,
reasoningEffort?: string,
): AcpSessionRuntime.AcpSpawnInput {
const spawnEffort = spawnableGrokReasoningEffort(reasoningEffort);
return {
command: grokSettings?.binaryPath || "grok",
args: ["agent", "stdio"],
args: spawnEffort ? ["agent", "--reasoning-effort", spawnEffort, "stdio"] : ["agent", "stdio"],
cwd,
env: {
...environment,
@@ -62,7 +105,12 @@ export const makeGrokAcpRuntime = (
const acpContext = yield* Layer.build(
AcpSessionRuntime.layer({
...input,
spawn: buildGrokAcpSpawnInput(input.grokSettings, input.cwd, input.environment),
spawn: buildGrokAcpSpawnInput(
input.grokSettings,
input.cwd,
input.environment,
input.reasoningEffort,
),
authMethodId: resolveGrokAuthMethodId(input.environment),
}).pipe(
Layer.provide(
@@ -91,18 +139,267 @@ export function currentGrokModelIdFromSessionSetup(
return sessionSetupResult.models?.currentModelId?.trim() || undefined;
}
export function spawnableGrokReasoningEffort(value: string | undefined): string | undefined {
const trimmed = value?.trim();
if (!trimmed || !GROK_SPAWN_EFFORT_LEVELS.has(trimmed)) {
return undefined;
}
return trimmed;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function trimmedString(value: unknown): string | undefined {
if (typeof value !== "string") {
return undefined;
}
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
function parseGrokReasoningEffortChoice(value: unknown): GrokReasoningEffortChoice | undefined {
if (typeof value === "string") {
const id = value.trim();
return id.length > 0 ? { id, label: id } : undefined;
}
if (!isRecord(value)) {
return undefined;
}
const id = trimmedString(value.value) ?? trimmedString(value.id);
if (!id) {
return undefined;
}
const label = trimmedString(value.label) ?? trimmedString(value.name) ?? id;
const description = trimmedString(value.description);
return {
id,
label,
...(description ? { description } : {}),
...(value.default === true || value.isDefault === true ? { isDefault: true } : {}),
};
}
/** Reads the per-model effort menu Grok stamps onto ACP `models._meta`. */
export function parseGrokAcpModelMeta(meta: unknown): GrokAcpModelMeta {
if (!isRecord(meta)) {
return { supportsReasoningEffort: false, reasoningEfforts: [] };
}
const reasoningEfforts = Array.isArray(meta.reasoningEfforts)
? meta.reasoningEfforts.flatMap((entry) => {
const choice = parseGrokReasoningEffortChoice(entry);
return choice ? [choice] : [];
})
: [];
const unique = new Map<string, GrokReasoningEffortChoice>();
for (const choice of reasoningEfforts) {
if (!unique.has(choice.id)) {
unique.set(choice.id, choice);
}
}
const choices = [...unique.values()];
const current = trimmedString(meta.reasoningEffort);
const defaultId = current ?? choices.find((choice) => choice.isDefault)?.id;
const supportsReasoningEffort = meta.supportsReasoningEffort === true || choices.length > 0;
const totalContextTokens =
typeof meta.totalContextTokens === "number" &&
Number.isFinite(meta.totalContextTokens) &&
meta.totalContextTokens > 0
? Math.trunc(meta.totalContextTokens)
: undefined;
return {
supportsReasoningEffort,
...(current ? { reasoningEffort: current } : {}),
reasoningEfforts: choices.map((choice) => ({
id: choice.id,
label: choice.label,
...(choice.description ? { description: choice.description } : {}),
...(choice.id === defaultId ? { isDefault: true } : {}),
})),
...(totalContextTokens !== undefined ? { totalContextTokens } : {}),
};
}
export function grokReasoningEffortCapabilities(
efforts: ReadonlyArray<GrokReasoningEffortChoice>,
): ModelCapabilities {
if (efforts.length === 0) {
return createModelCapabilities({ optionDescriptors: [] });
}
const defaultId = efforts.find((choice) => choice.isDefault)?.id ?? efforts[0]?.id;
return createModelCapabilities({
optionDescriptors: [
{
id: GROK_REASONING_EFFORT_OPTION_ID,
label: "Reasoning",
type: "select",
options: efforts.map((choice) => ({
id: choice.id,
label: choice.label,
...(choice.description ? { description: choice.description } : {}),
...(choice.isDefault ? { isDefault: true } : {}),
})),
...(defaultId ? { currentValue: defaultId } : {}),
},
],
});
}
export function fallbackGrokReasoningEffortCapabilities(): ModelCapabilities {
return grokReasoningEffortCapabilities([...FALLBACK_GROK_REASONING_EFFORTS]);
}
export function requestedGrokReasoningEffort(
modelSelection: ModelSelection | null | undefined,
advertised: ReadonlyArray<string>,
): string | undefined {
const requested = getModelSelectionStringOptionValue(
modelSelection,
GROK_REASONING_EFFORT_OPTION_ID,
)?.trim();
if (!requested) {
return undefined;
}
if (advertised.includes(requested)) {
return requested;
}
return undefined;
}
export function grokMaxTokensByModelFromSessionSetup(
sessionSetupResult:
| EffectAcpSchema.LoadSessionResponse
| EffectAcpSchema.NewSessionResponse
| EffectAcpSchema.ResumeSessionResponse,
): Map<string, number> {
const maxTokens = new Map<string, number>();
for (const model of sessionSetupResult.models?.availableModels ?? []) {
const tokens = parseGrokAcpModelMeta(model._meta).totalContextTokens;
if (tokens === undefined) {
continue;
}
const slug = resolveGrokAcpBaseModelId(model.modelId);
maxTokens.set(slug, tokens);
maxTokens.set(model.modelId, tokens);
}
return maxTokens;
}
export function grokReasoningEffortMenusFromSessionSetup(
sessionSetupResult:
| EffectAcpSchema.LoadSessionResponse
| EffectAcpSchema.NewSessionResponse
| EffectAcpSchema.ResumeSessionResponse,
): Map<string, ReadonlyArray<string>> {
const menus = new Map<string, ReadonlyArray<string>>();
for (const model of sessionSetupResult.models?.availableModels ?? []) {
const slug = resolveGrokAcpBaseModelId(model.modelId);
const efforts = parseGrokAcpModelMeta(model._meta).reasoningEfforts.map((choice) => choice.id);
if (efforts.length > 0) {
menus.set(slug, efforts);
menus.set(model.modelId, efforts);
}
}
return menus;
}
export function advertisedGrokReasoningEffortsFromSessionSetup(
sessionSetupResult:
| EffectAcpSchema.LoadSessionResponse
| EffectAcpSchema.NewSessionResponse
| EffectAcpSchema.ResumeSessionResponse,
modelId: string | undefined,
): ReadonlyArray<string> {
const menus = grokReasoningEffortMenusFromSessionSetup(sessionSetupResult);
if (modelId && menus.has(modelId)) {
return menus.get(modelId) ?? [];
}
const current = sessionSetupResult.models?.currentModelId;
return (current ? menus.get(current) : undefined) ?? [];
}
export function currentGrokReasoningEffortFromSessionSetup(
sessionSetupResult:
| EffectAcpSchema.LoadSessionResponse
| EffectAcpSchema.NewSessionResponse
| EffectAcpSchema.ResumeSessionResponse,
): string | undefined {
const currentModelId = sessionSetupResult.models?.currentModelId;
const current = sessionSetupResult.models?.availableModels.find(
(model) => model.modelId === currentModelId,
);
return parseGrokAcpModelMeta(current?._meta).reasoningEffort;
}
export function currentGrokMaxTokensFromSessionSetup(
sessionSetupResult:
| EffectAcpSchema.LoadSessionResponse
| EffectAcpSchema.NewSessionResponse
| EffectAcpSchema.ResumeSessionResponse,
): number | undefined {
const currentModelId = sessionSetupResult.models?.currentModelId;
const current = sessionSetupResult.models?.availableModels.find(
(model) => model.modelId === currentModelId,
);
return parseGrokAcpModelMeta(current?._meta).totalContextTokens;
}
export function isGrokAcpAuthFailure(error: unknown): boolean {
const text = [
error instanceof Error ? `${error.name} ${error.message}` : "",
typeof error === "string" ? error : "",
String(error),
].join(" ");
return /authenticat|unauthorized|not logged in|login required|no credentials|cached_token|xai\.api_key|401\b/i.test(
text,
);
}
export function applyGrokAcpModelSelection<E>(input: {
readonly runtime: Pick<AcpSessionRuntime.AcpSessionRuntime["Service"], "setSessionModel">;
readonly currentModelId: string | undefined;
readonly requestedModelId: string | undefined;
readonly currentReasoningEffort?: string | undefined;
readonly requestedReasoningEffort?: string | undefined;
readonly mapError: (cause: EffectAcpErrors.AcpError) => E;
}): Effect.Effect<string | undefined, E> {
}): Effect.Effect<GrokAcpSelection, E> {
const nextModelId = input.requestedModelId ?? input.currentModelId;
const shouldSwitchModel =
input.requestedModelId !== undefined && input.requestedModelId !== input.currentModelId;
if (!shouldSwitchModel) {
return Effect.succeed(input.currentModelId);
const nextEffort = shouldSwitchModel
? input.requestedReasoningEffort
: (input.requestedReasoningEffort ?? input.currentReasoningEffort);
const shouldSwitchEffort =
input.requestedReasoningEffort !== undefined &&
input.requestedReasoningEffort !== input.currentReasoningEffort;
if (!shouldSwitchModel && !shouldSwitchEffort) {
return Effect.succeed({
modelId: input.currentModelId,
reasoningEffort: input.currentReasoningEffort,
});
}
if (nextModelId === undefined) {
return Effect.succeed({
modelId: undefined,
reasoningEffort: nextEffort,
});
}
return input.runtime
.setSessionModel(input.requestedModelId)
.pipe(Effect.mapError(input.mapError), Effect.as(input.requestedModelId));
.setSessionModel(
nextModelId,
nextEffort ? { _meta: { reasoningEffort: nextEffort } } : undefined,
)
.pipe(
Effect.mapError(input.mapError),
Effect.as({
modelId: nextModelId,
reasoningEffort: nextEffort,
}),
);
}
@@ -9,10 +9,14 @@ import * as Schema from "effect/Schema";
import { describe, expect } from "vite-plus/test";
import {
extractGrokTokenUsage,
extractXAiAskUserQuestions,
grokPromptCountForTurns,
grokRewindTargetForTurnCount,
makeXAiAskUserQuestionCancelledResponse,
makeXAiAskUserQuestionResponse,
makeXAiPromptCompletionRuntime,
parseGrokRewindPoints,
XAiAskUserQuestionRequest,
} from "./XAiAcpExtension.ts";
import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
@@ -330,3 +334,32 @@ describe("XAiAcpExtension", () => {
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
});
describe("Grok rewind and usage helpers", () => {
it("picks the rewind target that drops the last N turns", () => {
const points = parseGrokRewindPoints({
rewind_points: [
{ prompt_index: 0, prompt_preview: "first" },
{ prompt_index: 1, prompt_preview: "second" },
{ prompt_index: 2, prompt_preview: "third" },
],
});
expect(grokRewindTargetForTurnCount(points, 1)?.promptIndex).toBe(2);
expect(grokRewindTargetForTurnCount(points, 2)?.promptIndex).toBe(1);
expect(grokRewindTargetForTurnCount(points, 4)).toBeUndefined();
expect(grokPromptCountForTurns([{ items: [1] }, { items: [2, 3] }], 1)).toBe(2);
});
it("reads Grok token usage from prompt _meta", () => {
expect(
extractGrokTokenUsage({
usage: { input_tokens: 10, output_tokens: 4, reasoning_tokens: 3 },
}),
).toMatchObject({
usedTokens: 17,
inputTokens: 10,
outputTokens: 4,
reasoningOutputTokens: 3,
});
});
});
+207 -1
View File
@@ -1,4 +1,8 @@
import type { ProviderUserInputAnswers, UserInputQuestion } from "@t3tools/contracts";
import type {
ProviderUserInputAnswers,
ThreadTokenUsageSnapshot,
UserInputQuestion,
} from "@t3tools/contracts";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Ref from "effect/Ref";
@@ -430,3 +434,205 @@ function normalizeXAiStopReason(value: string | undefined): EffectAcpSchema.Stop
return "end_turn";
}
}
export interface GrokRewindPoint {
readonly promptIndex: number;
readonly promptPreview: string;
}
export interface GrokRewindExecuteResult {
readonly success: boolean;
readonly error: string | null;
}
function asRecord(value: unknown): Record<string, unknown> | undefined {
return typeof value === "object" && value !== null && !Array.isArray(value)
? (value as Record<string, unknown>)
: undefined;
}
function unwrapExtResult(value: unknown): unknown {
const record = asRecord(value);
return record && "result" in record ? record.result : value;
}
function nonNegativeInt(value: unknown): number | undefined {
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
return undefined;
}
return Math.trunc(value);
}
/** Parses `_x.ai/rewind/points` into chronological prompt indexes. */
export function parseGrokRewindPoints(payload: unknown): ReadonlyArray<GrokRewindPoint> {
const unwrapped = unwrapExtResult(payload);
const list = Array.isArray(unwrapped)
? unwrapped
: (asRecord(unwrapped)?.rewind_points ??
asRecord(unwrapped)?.rewindPoints ??
asRecord(unwrapped)?.points);
if (!Array.isArray(list)) {
return [];
}
return list.flatMap((entry) => {
const record = asRecord(entry);
if (!record) {
return [];
}
const promptIndex = nonNegativeInt(record.prompt_index ?? record.promptIndex);
if (promptIndex === undefined) {
return [];
}
const preview =
(typeof record.prompt_preview === "string" ? record.prompt_preview : undefined) ??
(typeof record.promptPreview === "string" ? record.promptPreview : undefined) ??
"";
if (
/^\s*<system-reminder>/.test(preview) ||
/^\s*\[Plan (approved|rejected|cancelled)\]\s*$/i.test(preview.trim())
) {
return [];
}
return [{ promptIndex, promptPreview: preview }];
});
}
/** Target for rolling back the last `numTurns` user prompts. Execute discards the target and everything after it. */
export function grokRewindTargetForTurnCount(
points: ReadonlyArray<GrokRewindPoint>,
numTurns: number,
): GrokRewindPoint | undefined {
if (!Number.isInteger(numTurns) || numTurns < 1 || points.length === 0) {
return undefined;
}
const ordered = [...points].sort((left, right) => left.promptIndex - right.promptIndex);
if (numTurns > ordered.length) {
return undefined;
}
return ordered[ordered.length - numTurns];
}
export function grokPromptCountForTurns(
turns: ReadonlyArray<{ readonly items: ReadonlyArray<unknown> }>,
numTurns: number,
): number {
if (!Number.isInteger(numTurns) || numTurns < 1) {
return 0;
}
return turns.slice(-numTurns).reduce((count, turn) => count + turn.items.length, 0);
}
export function parseGrokRewindExecute(payload: unknown): GrokRewindExecuteResult | undefined {
const record = asRecord(unwrapExtResult(payload));
if (!record || typeof record.success !== "boolean") {
return undefined;
}
return {
success: record.success,
error:
typeof record.error === "string"
? record.error
: record.error == null
? null
: String(record.error),
};
}
function readTokenCount(...values: ReadonlyArray<unknown>): number | undefined {
for (const value of values) {
const parsed = nonNegativeInt(value);
if (parsed !== undefined) {
return parsed;
}
}
return undefined;
}
function usageRecordFromUnknown(value: unknown): Record<string, unknown> | undefined {
const record = asRecord(value);
if (!record) {
return undefined;
}
if (isRecord(record.usage)) {
return record.usage;
}
if (isRecord(record.tokenUsage)) {
return record.tokenUsage;
}
if (isRecord(record.token_usage)) {
return record.token_usage;
}
if (isRecord(record.agentResult)) {
return usageRecordFromUnknown(record.agentResult);
}
return record;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
/** Pulls a T3 usage snapshot from a Grok prompt result or prompt-complete payload. */
export function extractGrokTokenUsage(
payload: unknown,
maxTokens?: number,
): ThreadTokenUsageSnapshot | undefined {
const usage = usageRecordFromUnknown(payload);
if (!usage) {
return undefined;
}
const inputTokens = readTokenCount(
usage.inputTokens,
usage.input_tokens,
usage.promptTokens,
usage.prompt_tokens,
);
const outputTokens = readTokenCount(
usage.outputTokens,
usage.output_tokens,
usage.completionTokens,
usage.completion_tokens,
);
const reasoningOutputTokens = readTokenCount(
usage.reasoningOutputTokens,
usage.reasoning_tokens,
usage.reasoningTokens,
);
const cachedInputTokens = readTokenCount(
usage.cachedInputTokens,
usage.cache_read_input_tokens,
usage.cacheReadInputTokens,
);
const usedTokens = readTokenCount(
usage.usedTokens,
usage.used_tokens,
usage.totalTokens,
usage.total_tokens,
);
const inferredUsed =
usedTokens ??
(inputTokens !== undefined || outputTokens !== undefined
? (inputTokens ?? 0) + (outputTokens ?? 0) + (reasoningOutputTokens ?? 0)
: undefined);
if (inferredUsed === undefined || inferredUsed <= 0) {
return undefined;
}
return {
usedTokens: inferredUsed,
...(inputTokens !== undefined ? { inputTokens } : {}),
...(outputTokens !== undefined ? { outputTokens } : {}),
...(reasoningOutputTokens !== undefined ? { reasoningOutputTokens } : {}),
...(cachedInputTokens !== undefined ? { cachedInputTokens } : {}),
...(maxTokens !== undefined ? { maxTokens } : {}),
lastUsedTokens: inferredUsed,
...(inputTokens !== undefined ? { lastInputTokens: inputTokens } : {}),
...(outputTokens !== undefined ? { lastOutputTokens: outputTokens } : {}),
...(reasoningOutputTokens !== undefined
? { lastReasoningOutputTokens: reasoningOutputTokens }
: {}),
...(cachedInputTokens !== undefined ? { lastCachedInputTokens: cachedInputTokens } : {}),
};
}
@@ -342,7 +342,40 @@ layer("AzureDevOpsPullRequestCli.layer", (it) => {
}),
);
it.effect("stores the squash choice with an auto-completion, as a merge now does", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
yield* cli.runPullRequestAction({
cwd: "/w",
number: 42,
action: "enable-auto-merge",
mergeMethod: "squash",
});
expect(argsOfCall(0)).toEqual([
"repos",
"pr",
"update",
"--detect",
"true",
"--id",
"42",
"--auto-complete",
"true",
"--squash",
"true",
"--only-show-errors",
"--output",
"json",
]);
}),
);
it.effect.each([
{ action: "enable-auto-merge", expected: ["--auto-complete", "true", "--squash", "false"] },
{ action: "disable-auto-merge", expected: ["--auto-complete", "false"] },
{ action: "draft", expected: ["--draft", "true"] },
{ action: "ready", expected: ["--draft", "false"] },
{ action: "close", expected: ["--status", "abandoned"] },
@@ -370,6 +403,79 @@ layer("AzureDevOpsPullRequestCli.layer", (it) => {
}),
);
it.effect.each([
{ name: "a title", rewrite: { title: "Add the page" }, expected: ["--title=Add the page"] },
{
name: "a description",
rewrite: { body: "Why the page changed" },
expected: ["--description=Why the page changed"],
},
{
name: "both",
rewrite: { title: "Add the page", body: "Why the page changed" },
expected: ["--title=Add the page", "--description=Why the page changed"],
},
] as const)("rewrites $name, sending nothing it was not given", ({ rewrite, expected }) =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
yield* cli.updatePullRequest({ cwd: "/w", number: 42, ...rewrite });
expect(argsOfCall(0)).toEqual([
"repos",
"pr",
"update",
"--detect",
"true",
"--id",
"42",
...expected,
"--only-show-errors",
"--output",
"json",
]);
}),
);
it.effect("sends a description that starts with a dash as one value, not as a flag", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
yield* cli.updatePullRequest({
cwd: "/w",
number: 42,
body: "- rewrote the page\n- kept the rest",
});
// One argument, so the leading dash of an ordinary bullet list never reaches az as a flag,
// and the whole text stays together where `--description` would otherwise take several.
expect(argsOfCall(0)).toContain("--description=- rewrote the page\n- kept the rest");
}),
);
it.effect("rewrites through the provider, which says it takes one", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
const provider = yield* AzureDevOpsPullRequestProvider.make;
// False for a remark because nothing here can post one, so there is none to rewrite.
expect(provider.capabilities.edit).toEqual({ changeRequest: true, comment: false });
assert.isDefined(provider.updateChangeRequest);
yield* provider.updateChangeRequest({
cwd: "/w",
repository: "web",
host: "dev.azure.com",
number: 42,
title: "Add the page",
});
expect(argsOfCall(0)).toContain("--title=Add the page");
expect(argsOfCall(0)).not.toContain("--description");
}),
);
it.effect("reads the conversation through the REST API, pinned to a version", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
@@ -159,6 +159,14 @@ export class AzureDevOpsPullRequestCli extends Context.Service<
readonly mergeMethod?: PullRequestMergeMethod;
}) => Effect.Effect<void, AzureDevOpsPullRequestCliError>;
/** Rewrites the pull request's own words, through the same command that moves it. */
readonly updatePullRequest: (input: {
readonly cwd: string;
readonly number: number;
readonly title?: string | undefined;
readonly body?: string | undefined;
}) => Effect.Effect<void, AzureDevOpsPullRequestCliError>;
/**
* Adds reviewers to a pull request, or takes them off it. `az repos pr reviewer` is the whole
* of what Azure offers here: it adds and removes named identities, and has no counterpart that
@@ -212,12 +220,21 @@ function actionArgs(
switch (action) {
case "merge":
return ["--status", "completed", "--squash", mergeMethod === "squash" ? "true" : "false"];
// Auto-complete is Azure's own name for it: the pull request stays active and Azure completes
// it once its policies pass. The squash choice is stored with it, as it is for a merge now.
case "enable-auto-merge":
return ["--auto-complete", "true", "--squash", mergeMethod === "squash" ? "true" : "false"];
case "disable-auto-merge":
return ["--auto-complete", "false"];
case "ready":
return ["--draft", "false"];
case "draft":
return ["--draft", "true"];
case "close":
return ["--status", "abandoned"];
// Never reached: this host does not declare the action, so nothing offers it.
case "update-branch":
return [];
case "reopen":
return ["--status", "active"];
}
@@ -481,6 +498,29 @@ export const make = Effect.gen(function* () {
],
})
.pipe(Effect.asVoid),
updatePullRequest: (input) =>
azure
.execute({
cwd: input.cwd,
args: [
"repos",
"pr",
"update",
...detectArgs,
"--id",
String(input.number),
// One argument rather than a flag and a value beside it: a description usually opens
// with a bullet, and az reads a dash in the next argv slot as a flag of its own.
// `--description` also takes several strings, and this keeps the whole text as one.
...(input.title === undefined ? [] : [`--title=${input.title}`]),
...(input.body === undefined ? [] : [`--description=${input.body}`]),
"--only-show-errors",
"--output",
"json",
],
})
.pipe(Effect.asVoid),
});
});
@@ -9,7 +9,15 @@ describe("azure devops viewer permissions", () => {
// and an unknown permission is granted rather than guessed away. Azure refuses the ones it
// will not allow, at the moment they are taken, in words this could not have written.
expect(AZURE_DEVOPS_VIEWER_PERMISSIONS).toEqual({
actions: ["merge", "ready", "draft", "close", "reopen"],
actions: [
"merge",
"ready",
"draft",
"close",
"reopen",
"enable-auto-merge",
"disable-auto-merge",
],
// False because the host itself cannot post one, not because this viewer may not.
comment: false,
resolve: false,
@@ -18,11 +18,20 @@ const CAPABILITIES: PullRequestCapabilities = {
// Reading a conversation is a plain REST read, but posting one is not something this can
// claim without having run it, so the composer stays hidden.
comment: false,
actions: ["merge", "ready", "draft", "close", "reopen"],
actions: [
"merge",
"ready",
"draft",
"close",
"reopen",
"enable-auto-merge",
"disable-auto-merge",
],
// Azure squashes as a completion option; it has no rebase strategy of its own.
mergeMethods: ["merge", "squash"],
// `az repos pr list` filters by status, creator, reviewer and branch, and by no text at all.
search: false,
reactions: false,
// With no patch to show there are no lines to write against, so nothing here is offered.
review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
// `az repos pr reviewer add` and `remove` name identities, and nothing anywhere in `az repos`
@@ -30,6 +39,10 @@ const CAPABILITIES: PullRequestCapabilities = {
// different service with its own permissions. So the page takes a name here rather than being
// handed a menu built out of a guess.
reviewers: { request: true, listCandidates: false },
// A new title and description travel on the same `az repos pr update` that moves a pull request.
// Rewriting a remark is false for the same reason posting one is: this cannot put a remark on
// Azure DevOps at all, so there is nothing here it could rewrite either.
edit: { changeRequest: true, comment: false },
};
/**
@@ -153,6 +166,7 @@ export const make = Effect.gen(function* () {
checks: [],
mergeCapabilities: { merge: true, squash: true, rebase: false },
viewerPermissions: AZURE_DEVOPS_VIEWER_PERMISSIONS,
autoMergeEnabled: pullRequest.autoMergeEnabled,
}),
),
),
@@ -206,6 +220,16 @@ export const make = Effect.gen(function* () {
})
.pipe(Effect.mapError(fail("runAction"))),
updateChangeRequest: (input) =>
cli
.updatePullRequest({
cwd: input.cwd,
number: input.number,
title: input.title,
body: input.body,
})
.pipe(Effect.mapError(fail("updateChangeRequest"))),
// Never called: `capabilities.reviewers.listCandidates` is false, and the service refuses the
// list without it.
listReviewerCandidates: () =>
@@ -240,6 +264,8 @@ export const make = Effect.gen(function* () {
replyToThread: () => unsupported("replyToThread"),
setThreadResolution: () => unsupported("setThreadResolution"),
setReaction: () => unsupported("setReaction"),
};
return provider;
@@ -510,6 +510,74 @@ layer("BitbucketPullRequestApi.layer", (it) => {
}),
);
it.effect("rewrites a title alone, without touching anything else", () =>
Effect.gen(function* () {
mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
yield* api.updateChangeRequest({ repository: "acme/web", number: 7, title: "A new title" });
const call = callAt(0);
expect(call.method).toBe("PUT");
expect(call.url).toBe("/repositories/acme/web/pullrequests/7");
// Bitbucket's PUT is a partial update, so a field left out of the body is left as it was.
// @effect-diagnostics-next-line preferSchemaOverJson:off
expect(JSON.parse(call.body ?? "")).toEqual({ title: "A new title" });
}),
);
it.effect("leaves out the half of the pull request it was not asked about", () =>
Effect.gen(function* () {
mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
yield* api.updateChangeRequest({ repository: "acme/web", number: 7, body: "New body." });
// @effect-diagnostics-next-line preferSchemaOverJson:off
expect(JSON.parse(callAt(0).body ?? "")).toEqual({ description: "New body." });
}),
);
it.effect("writes both fields when both were rewritten", () =>
Effect.gen(function* () {
mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
yield* api.updateChangeRequest({
repository: "acme/web",
number: 7,
title: "A new title",
body: "New body.",
});
// @effect-diagnostics-next-line preferSchemaOverJson:off
expect(JSON.parse(callAt(0).body ?? "")).toEqual({
title: "A new title",
description: "New body.",
});
}),
);
it.effect("rewrites a comment where it stands, whichever kind it is", () =>
Effect.gen(function* () {
mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
yield* api.updateComment({
repository: "acme/web",
number: 7,
commentId: "10",
body: "Edited.",
});
expect(callAt(0)).toMatchObject({
method: "PUT",
url: "/repositories/acme/web/pullrequests/7/comments/10",
body: '{"content":{"raw":"Edited."}}',
});
}),
);
it.effect("fails the read when Bitbucket answers with something unreadable", () =>
Effect.gen(function* () {
mockedRequest.mockReturnValueOnce(
@@ -222,12 +222,26 @@ export class BitbucketPullRequestApi extends Context.Service<
readonly mergeMethod?: PullRequestMergeMethod;
}) => Effect.Effect<void, BitbucketPullRequestApiError>;
readonly updateChangeRequest: (input: {
readonly repository: string;
readonly number: number;
readonly title?: string | undefined;
readonly body?: string | undefined;
}) => Effect.Effect<void, BitbucketPullRequestApiError>;
readonly comment: (input: {
readonly repository: string;
readonly number: number;
readonly body: string;
}) => Effect.Effect<void, BitbucketPullRequestApiError>;
readonly updateComment: (input: {
readonly repository: string;
readonly number: number;
readonly commentId: string;
readonly body: string;
}) => Effect.Effect<void, BitbucketPullRequestApiError>;
readonly submitReview: (input: {
readonly repository: string;
readonly number: number;
@@ -701,6 +715,24 @@ export const make = Effect.gen(function* () {
.pipe(Effect.asVoid);
}),
updateChangeRequest: (input) =>
withRepository(input.repository, (path) =>
// Only the words this call rewrites travel in the body: as `setReviewerRequest` above
// relies on, Bitbucket's PUT is a partial update, so any field left out is left as it
// was — sending `reviewers` back here would overwrite a change another user made to it
// between this call being issued and the request landing.
bitbucket
.request({
method: "PUT",
url: `${path}/pullrequests/${input.number}`,
body: JSON.stringify({
...(input.title === undefined ? {} : { title: input.title }),
...(input.body === undefined ? {} : { description: input.body }),
}),
})
.pipe(Effect.asVoid),
),
comment: (input) =>
withRepository(input.repository, (path) =>
bitbucket
@@ -713,6 +745,21 @@ export const make = Effect.gen(function* () {
.pipe(Effect.asVoid),
),
updateComment: (input) =>
withRepository(input.repository, (path) =>
bitbucket
.request({
// Bitbucket keeps a pull request's remarks and its line comments in the one
// collection, so this endpoint rewrites either kind.
method: "PUT",
url: `${path}/pullrequests/${input.number}/comments/${encodeURIComponent(
input.commentId,
)}`,
body: JSON.stringify({ content: { raw: input.body } }),
})
.pipe(Effect.asVoid),
),
submitReview: (input) =>
withRepository(input.repository, (path) =>
Effect.gen(function* () {
@@ -19,6 +19,9 @@ const CAPABILITIES: PullRequestCapabilities = {
actions: ["merge", "close"],
mergeMethods: ["merge", "squash", "rebase"],
search: true,
// Bitbucket Cloud's API exposes no reaction on a pull request or on a comment, so none is
// read and none is offered.
reactions: false,
review: {
inlineComment: true,
reply: true,
@@ -26,6 +29,7 @@ const CAPABILITIES: PullRequestCapabilities = {
verdicts: ["comment", "approve", "request-changes"],
},
reviewers: { request: true, listCandidates: true },
edit: { changeRequest: true, comment: true },
};
/**
@@ -249,11 +253,31 @@ export const make = Effect.gen(function* () {
})
.pipe(Effect.mapError(fail("runAction"))),
updateChangeRequest: (input) =>
api
.updateChangeRequest({
repository: input.repository,
number: input.number,
title: input.title,
body: input.body,
})
.pipe(Effect.mapError(fail("updateChangeRequest"))),
comment: (input) =>
api
.comment({ repository: input.repository, number: input.number, body: input.body })
.pipe(Effect.mapError(fail("comment"))),
updateComment: (input) =>
api
.updateComment({
repository: input.repository,
number: input.number,
commentId: input.commentId,
body: input.body,
})
.pipe(Effect.mapError(fail("updateComment"))),
submitReview: (input) =>
api
.submitReview({
@@ -275,6 +299,17 @@ export const make = Effect.gen(function* () {
})
.pipe(Effect.mapError(fail("replyToThread"))),
// Never called: `capabilities.reactions` is false, and the service refuses without it.
setReaction: () =>
Effect.fail(
new PullRequestProviderError({
provider: "bitbucket",
operation: "setReaction",
reason: "failed",
detail: "Bitbucket does not support reactions.",
}),
),
setThreadResolution: (input) =>
api
.setCommentResolution({
@@ -5,6 +5,7 @@ import { ChildProcessSpawner } from "effect/unstable/process";
import * as GitHubCli from "../sourceControl/GitHubCli.ts";
import * as GitHubPullRequestCli from "./GitHubPullRequestCli.ts";
import { BASE_COMPARISON_GRAPHQL_QUERY } from "./gitHubPullRequestJson.ts";
const mockedExecute = vi.fn<GitHubCli.GitHubCli["Service"]["execute"]>();
@@ -551,6 +552,206 @@ layer("GitHubPullRequestCli.layer", (it) => {
}),
);
it.effect("carries the further narrowings into the search as qualifiers", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("[]")));
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
yield* cli.listPullRequests({
cwd: "/w",
repository: "acme/web",
host: "github.com",
state: "open",
involvement: "all",
viewer: "bilal",
limit: 10,
filters: {
draft: "hide",
review: "changes-requested",
checks: "failing",
labels: [["needs design"], ['quo"te']],
excludedLabels: ["wip"],
author: "octocat",
},
});
// Quotes around anything a reader typed, and the one character that could end a quoted
// value early dropped rather than escaped.
expect(searchOfCall(0)).toBe(
'label:"needs design" label:"quote" -label:"wip" author:"octocat" draft:false ' +
"review:changes_requested status:failure sort:updated-desc",
);
}),
);
it.effect('resolves an author filter of "me" to the viewer, not the literal word', () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("[]")));
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
yield* cli.listPullRequests({
cwd: "/w",
repository: "acme/web",
host: "github.com",
state: "open",
involvement: "all",
viewer: "bilal",
limit: 10,
filters: { author: "me" },
});
expect(searchOfCall(0)).toBe('author:"bilal" sort:updated-desc');
}),
);
it.effect("sends one label qualifier per group, its names joined the way GitHub ors them", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("[]")));
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
yield* cli.listPullRequests({
cwd: "/w",
repository: "acme/web",
host: "github.com",
state: "open",
involvement: "all",
viewer: "bilal",
limit: 10,
filters: { labels: [["size:S", "size:XS"], ["bug"]] },
});
// One qualifier satisfied by either size, and a second one that must hold as well.
expect(searchOfCall(0)).toBe('label:"size:S","size:XS" label:"bug" sort:updated-desc');
expect(callAt(0).args).toContain('label:"size:S","size:XS" label:"bug" sort:updated-desc');
}),
);
it.effect(
"falls back for a repository the index does not cover under a checks filter, keeping only the matching rows",
() =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
pullRequests(2, 1, (number) => ({
statusCheckRollup:
number === 1
? [{ name: "lint", status: "COMPLETED", conclusion: "SUCCESS" }]
: [{ name: "test", status: "COMPLETED", conclusion: "FAILURE" }],
})),
),
),
);
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
const batch = yield* cli.listPullRequests({
cwd: "/w",
repository: "acme/web",
host: "github.com",
state: "open",
involvement: "all",
viewer: "bilal",
limit: 10,
filters: { checks: "passing" },
});
// The fallback's rows carry `checksState` exactly as a search's rows do, so `checks` is
// now a filter the fallback judges itself, the same as `draft`: an empty search answer
// under it is still ambiguous, and the row picked out afterwards is the one whose own
// `checksState` reads "passing".
expect(searchOfCall(1)).toBeUndefined();
assert.deepStrictEqual(
batch.items.map((item) => item.number),
[1],
);
}),
);
it.effect("fails a checks filter for a row whose checks are still pending", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
pullRequests(1, 1, () => ({
statusCheckRollup: [{ name: "build", status: "IN_PROGRESS" }],
})),
),
),
);
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
const batch = yield* cli.listPullRequests({
cwd: "/w",
repository: "acme/web",
host: "github.com",
state: "open",
involvement: "all",
viewer: "bilal",
limit: 10,
filters: { checks: "passing" },
});
// Pending equals neither "passing" nor "failing", so it satisfies neither filter value —
// the same row would also be dropped by `checks: "failing"`.
assert.deepStrictEqual(batch.items, []);
}),
);
it.effect(
"falls back for a repository the index does not cover even under a judgeable filter",
() =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
mockedExecute.mockReturnValueOnce(
Effect.succeed(output(pullRequests(2, 1, (number) => ({ isDraft: number === 1 })))),
);
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
const batch = yield* cli.listPullRequests({
cwd: "/w",
repository: "acme/web",
host: "github.com",
state: "open",
involvement: "all",
viewer: "bilal",
limit: 10,
filters: { draft: "hide" },
});
// `draft` is a filter the fallback can judge over its own rows just as search judges it,
// so an empty search answer under it alone is still ambiguous between "nothing matches"
// and "this repository is not indexed" — and the fallback applies the filter itself,
// keeping only the non-draft row.
expect(searchOfCall(1)).toBeUndefined();
expect(batch.items.map((item) => item.number)).toEqual([2]);
}),
);
it.effect("carries the further narrowings into a batched search", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(searchPage([])));
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
yield* cli.searchPullRequests({
cwd: "/w",
host: "github.com",
repositories: ["acme/web"],
state: "open",
involvement: "all",
viewer: "bilal",
limit: 10,
filters: { draft: "only", review: "none", labels: [["bug"]] },
});
assert.strictEqual(
searchQueryOfCall(0),
'is:pr is:open label:"bug" draft:true review:none sort:updated-desc repo:acme/web',
);
}),
);
it.effect("quotes a search, so it cannot add a qualifier or a flag of its own", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("[]")));
@@ -819,6 +1020,40 @@ layer("GitHubPullRequestCli.layer", (it) => {
}),
);
it.effect("updates a stale branch with a merge commit unless asked to rebase", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("")));
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
yield* cli.runPullRequestAction({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
action: "update-branch",
});
// GitHub's own default, and `gh`'s: a merge commit unless the rebase flag says otherwise.
expect(callAt(0).args).toEqual(["pr", "update-branch", "7", "--repo", "github.com/acme/web"]);
yield* cli.runPullRequestAction({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
action: "update-branch",
updateMethod: "rebase",
});
expect(callAt(1).args).toEqual([
"pr",
"update-branch",
"7",
"--repo",
"github.com/acme/web",
"--rebase",
]);
}),
);
it.effect("merges with the strategy it was asked for", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("")));
@@ -844,6 +1079,74 @@ layer("GitHubPullRequestCli.layer", (it) => {
}),
);
it.effect("arms auto-merge with the same strategy a merge would have used", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("")));
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
yield* cli.runPullRequestAction({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
action: "enable-auto-merge",
mergeMethod: "squash",
});
expect(callAt(0).args).toEqual([
"pr",
"merge",
"7",
"--repo",
"github.com/acme/web",
"--auto",
"--squash",
]);
// No strategy asked for is GitHub's own default, exactly as it is for a merge now.
yield* cli.runPullRequestAction({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
action: "enable-auto-merge",
});
expect(callAt(1).args).toEqual([
"pr",
"merge",
"7",
"--repo",
"github.com/acme/web",
"--auto",
"--merge",
]);
}),
);
it.effect("takes auto-merge back off without naming a strategy", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("")));
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
yield* cli.runPullRequestAction({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
action: "disable-auto-merge",
mergeMethod: "squash",
});
expect(callAt(0).args).toEqual([
"pr",
"merge",
"7",
"--repo",
"github.com/acme/web",
"--disable-auto",
]);
}),
);
it.effect("returns a pull request to draft by undoing ready", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("")));
@@ -1406,6 +1709,279 @@ layer("GitHubPullRequestCli.layer", (it) => {
}),
);
it.effect("confirms a given subject belongs to the named pull request, then reacts to it", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify({
data: {
repository: { pullRequest: { id: "PR_kwDOA" } },
node: { id: "IC_1", pullRequest: { id: "PR_kwDOA" } },
},
}),
),
),
);
mockedExecute.mockReturnValueOnce(Effect.succeed(output("{}")));
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
yield* cli.setReaction({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
subjectId: "IC_1",
content: "heart",
reacted: true,
});
assert.strictEqual(mockedExecute.mock.calls.length, 2);
const scopeCheck = callAt(0).args;
expect(scopeCheck).toContain("owner=acme");
expect(scopeCheck).toContain("name=web");
expect(scopeCheck).toContain("number=7");
expect(scopeCheck).toContain("subjectId=IC_1");
// @effect-diagnostics-next-line preferSchemaOverJson:off
const request = JSON.parse(callAt(1).stdin ?? "") as {
query: string;
variables: Record<string, string>;
};
expect(request.query).toContain("addReaction(");
expect(request.variables).toEqual({ subjectId: "IC_1", content: "HEART" });
}),
);
it.effect("refuses a given subject that belongs to a different pull request", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify({
data: {
repository: { pullRequest: { id: "PR_thisOne" } },
// A comment on pull request #99 of a different repository, named as though it
// belonged to #7 here.
node: { id: "IC_99", pullRequest: { id: "PR_someOtherOne" } },
},
}),
),
),
);
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
const error = yield* Effect.flip(
cli.setReaction({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
subjectId: "IC_99",
content: "heart",
reacted: true,
}),
);
assert.strictEqual(error._tag, "GitHubSubjectScopeError");
// Refused before any mutation was sent.
assert.strictEqual(mockedExecute.mock.calls.length, 1);
}),
);
it.effect("looks up the pull request's own node id when no subject was given", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify({ data: { repository: { pullRequest: { id: "PR_kwDOA" } } } }),
),
),
);
mockedExecute.mockReturnValueOnce(Effect.succeed(output("{}")));
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
yield* cli.setReaction({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
content: "rocket",
reacted: true,
});
assert.strictEqual(mockedExecute.mock.calls.length, 2);
const lookup = callAt(0).args;
expect(lookup).toContain("owner=acme");
expect(lookup).toContain("name=web");
expect(lookup).toContain("number=7");
// @effect-diagnostics-next-line preferSchemaOverJson:off
const request = JSON.parse(callAt(1).stdin ?? "") as {
query: string;
variables: Record<string, string>;
};
expect(request.query).toContain("addReaction(");
expect(request.variables).toEqual({ subjectId: "PR_kwDOA", content: "ROCKET" });
}),
);
it.effect("takes a reaction back through the remove mutation", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify({
data: {
repository: { pullRequest: { id: "PR_kwDOA" } },
node: { id: "IC_1", pullRequest: { id: "PR_kwDOA" } },
},
}),
),
),
);
mockedExecute.mockReturnValueOnce(Effect.succeed(output("{}")));
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
yield* cli.setReaction({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
subjectId: "IC_1",
content: "heart",
reacted: false,
});
// @effect-diagnostics-next-line preferSchemaOverJson:off
const request = JSON.parse(callAt(1).stdin ?? "") as { query: string };
expect(request.query).toContain("removeReaction(");
}),
);
it.effect("rewrites only the words a request named", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(
Effect.succeed(
output(
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify({ data: { repository: { pullRequest: { id: "PR_kwDOA" } } } }),
),
),
);
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
const rewrite = (fields: { readonly title?: string; readonly body?: string }) =>
cli.updatePullRequest({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
...fields,
});
yield* rewrite({ title: "A better title" });
yield* rewrite({ body: "A better description." });
yield* rewrite({ title: "Both", body: "at once." });
// Each rewrite looks the pull request's node id up first, then mutates.
const variablesAt = (index: number) =>
(JSON.parse(callAt(index).stdin ?? "") as { variables: Record<string, string> }).variables;
expect(variablesAt(1)).toEqual({ pullRequestId: "PR_kwDOA", title: "A better title" });
expect(variablesAt(3)).toEqual({
pullRequestId: "PR_kwDOA",
body: "A better description.",
});
expect(variablesAt(5)).toEqual({
pullRequestId: "PR_kwDOA",
title: "Both",
body: "at once.",
});
// The reader's own words, so they travel the way every other body does.
expect(callAt(5).args.join(" ")).not.toContain("at once.");
}),
);
it.effect("rewrites a remark through the mutation its kind needs", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(
Effect.succeed(
output(
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify({
data: {
repository: { pullRequest: { id: "PR_kwDOA" } },
node: { id: "IC_1", pullRequest: { id: "PR_kwDOA" } },
},
}),
),
),
);
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
const rewrite = (kind: "issue-comment" | "review-comment") =>
cli.updateComment({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
commentId: "IC_1",
kind,
body: "Reworded.",
});
yield* rewrite("issue-comment");
yield* rewrite("review-comment");
const parse = (index: number) =>
JSON.parse(callAt(index).stdin ?? "") as {
query: string;
variables: Record<string, string>;
};
expect(callAt(0).args).toContain("subjectId=IC_1");
expect(parse(1).query).toContain("updateIssueComment(");
expect(parse(1).variables).toEqual({ commentId: "IC_1", body: "Reworded." });
expect(parse(3).query).toContain("updatePullRequestReviewComment(");
expect(parse(3).variables).toEqual({ commentId: "IC_1", body: "Reworded." });
}),
);
it.effect("refuses a comment that belongs to a different pull request", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify({
data: {
repository: { pullRequest: { id: "PR_thisOne" } },
node: { id: "IC_99", pullRequest: { id: "PR_someOtherOne" } },
},
}),
),
),
);
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
const error = yield* Effect.flip(
cli.updateComment({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
commentId: "IC_99",
kind: "issue-comment",
body: "Reworded.",
}),
);
assert.strictEqual(error._tag, "GitHubSubjectScopeError");
expect(error.message).toContain("updateComment");
// Refused before any mutation was sent.
assert.strictEqual(mockedExecute.mock.calls.length, 1);
}),
);
it.effect("fails the read when gh returns something unreadable", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(output('{"message":"not found"}')));
@@ -1472,7 +2048,7 @@ layer("GitHubPullRequestCli.layer", (it) => {
expect(detail.body).toBe("Core body");
expect(activity.author?.login).toBe("octocat");
expect(callAt(0).args.at(-1)).toBe(
"number,title,url,author,headRefName,baseRefName,state,isDraft,mergeable,additions,deletions,createdAt,updatedAt,mergedAt,reviewRequests,labels,body,changedFiles,closedAt,statusCheckRollup",
"number,title,url,author,headRefName,baseRefName,state,isDraft,mergeable,reviewDecision,additions,deletions,createdAt,updatedAt,mergedAt,reviewRequests,labels,statusCheckRollup,body,changedFiles,closedAt,headRepositoryOwner,autoMergeRequest",
);
expect(callAt(1).args.at(-1)).toBe("author,comments,reviews,commits");
}),
@@ -1634,6 +2210,58 @@ layer("GitHubPullRequestCli.layer", (it) => {
}),
);
it.effect("sends the base comparison's variables as gh flags, not as bare words", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(
Effect.succeed(
output(
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify({
data: {
repository: {
pullRequest: {
viewerCanUpdateBranch: true,
baseRef: { compare: { behindBy: 4 } },
},
},
},
}),
),
),
);
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
const comparison = yield* cli.getPullRequestBaseComparison({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
headRef: "fork:feat/page",
});
// The tuples are flattened straight into argv, so a variable without its flag is a
// positional argument gh refuses outright.
const args = callAt(0).args;
expect(args).toEqual([
"api",
"graphql",
"--hostname",
"github.com",
"-f",
"owner=acme",
"-f",
"name=web",
"-F",
"number=7",
"-f",
"headRef=fork:feat/page",
"-f",
`query=${BASE_COMPARISON_GRAPHQL_QUERY}`,
]);
expect(comparison).toEqual({ behindBy: 4, viewerCanUpdate: true });
}),
);
it.effect("reads the viewer's role off the same call as the merge settings", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(
@@ -3,22 +3,29 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import type {
PullRequestAction,
PullRequestActor,
PullRequestInvolvement,
PullRequestListState,
PullRequestMergeMethod,
PullRequestReviewCommentDraft,
PullRequestReviewVerdict,
PullRequestReviewerCandidateList,
PullRequestReviewerKind,
PullRequestThreadComment,
import {
resolvePullRequestAuthorFilter,
type PullRequestAction,
type PullRequestActor,
type PullRequestInvolvement,
type PullRequestListFilters,
type PullRequestListState,
type PullRequestMergeMethod,
type PullRequestOmittedFileStat,
type PullRequestReaction,
type PullRequestReactionContent,
type PullRequestReviewCommentDraft,
type PullRequestReviewVerdict,
type PullRequestReviewerCandidateList,
type PullRequestReviewerKind,
type PullRequestThreadComment,
type PullRequestUpdateMethod,
} from "@t3tools/contracts";
import * as GitHubCli from "../sourceControl/GitHubCli.ts";
import {
ACTOR_AVATARS_GRAPHQL_QUERY,
ADD_REACTION_GRAPHQL_MUTATION,
buildReviewSubmissionJson,
buildReviewerRequestJson,
decodeActorAvatarsJson,
@@ -26,10 +33,13 @@ import {
decodePullRequestDetailJson,
decodePullRequestFilesJson,
decodePullRequestListJson,
decodePullRequestNodeIdJson,
decodePullRequestSearchJson,
decodePullRequestStatsJson,
decodeReactionSubjectScopeJson,
decodeRepositoryAccessJson,
decodeReviewerCandidatesJson,
decodeReviewDismissalsJson,
decodeReviewThreadCommentsJson,
decodeReviewThreadsJson,
buildPullRequestStatsGraphQlQuery,
@@ -37,18 +47,29 @@ import {
pullRequestSearchGraphQlQuery,
PULL_REQUEST_SEARCH_MAX_ROWS,
PULL_REQUEST_ACTIVITY_JSON_FIELDS,
BASE_COMPARISON_GRAPHQL_QUERY,
decodeBaseComparisonJson,
PULL_REQUEST_DETAIL_JSON_FIELDS,
PULL_REQUEST_LIST_JSON_FIELDS,
PULL_REQUEST_NODE_ID_GRAPHQL_QUERY,
REACTION_SUBJECT_PULL_REQUEST_GRAPHQL_QUERY,
REMOVE_REACTION_GRAPHQL_MUTATION,
gitHubReactionContent,
REPOSITORY_ACCESS_JSON_FIELDS,
RESOLVE_REVIEW_THREAD_GRAPHQL_MUTATION,
REVIEWER_CANDIDATES_GRAPHQL_QUERY,
REVIEW_THREAD_COMMENTS_GRAPHQL_QUERY,
REVIEW_DISMISSALS_GRAPHQL_QUERY,
REVIEW_THREAD_REPLY_GRAPHQL_MUTATION,
REVIEW_THREADS_GRAPHQL_QUERY,
reviewThreadConversation,
UNRESOLVE_REVIEW_THREAD_GRAPHQL_MUTATION,
UPDATE_ISSUE_COMMENT_GRAPHQL_MUTATION,
UPDATE_PULL_REQUEST_GRAPHQL_MUTATION,
UPDATE_REVIEW_COMMENT_GRAPHQL_MUTATION,
VIEWER_PERMISSIONS_GRAPHQL_QUERY,
decodeViewerPermissionsJson,
type GitHubBaseComparison,
type GitHubPullRequestDetail,
type GitHubPullRequestActivity,
type GitHubPullRequestListItem,
@@ -199,6 +220,24 @@ export class GitHubRepositorySelectorError extends Schema.TaggedErrorClass<GitHu
}
}
/** Not a decode failure: the reader named a subject this pull request never handed out. */
export class GitHubSubjectScopeError extends Schema.TaggedErrorClass<GitHubSubjectScopeError>()(
"GitHubSubjectScopeError",
{
command: Schema.Literal("gh"),
cwd: Schema.String,
operation: Schema.String,
},
) {
get detail(): string {
return "The named subject did not belong to the named pull request.";
}
override get message(): string {
return `GitHub CLI failed in ${this.operation}: ${this.detail}`;
}
}
export type GitHubPullRequestCliError =
| GitHubCli.GitHubCliError
| GitHubPullRequestReadError
@@ -207,6 +246,7 @@ export type GitHubPullRequestCliError =
| GitHubDiffRevisionsUnavailableError
| GitHubDiffFileContentsUnavailableError
| GitHubRepositorySelectorError
| GitHubSubjectScopeError
| GitHubViewerLoginUnavailableError;
/** A large pull request can produce a multi-megabyte patch; past this it is truncated. */
@@ -270,6 +310,8 @@ export interface GitHubPullRequestDiffSlice {
readonly truncated: boolean;
/** Where the next slice starts, or null once the patch is whole. */
readonly nextCursor: string | null;
/** GitHub's own counts for the files whose hunks it withheld from this slice. */
readonly omittedFileStats?: ReadonlyArray<PullRequestOmittedFileStat>;
}
export class GitHubPullRequestCli extends Context.Service<
@@ -291,6 +333,8 @@ export class GitHubPullRequestCli extends Context.Service<
readonly query?: string | undefined;
/** Where to carry on from, as a `updated:` qualifier on the same search. */
readonly cursor?: ProviderListCursor | undefined;
/** Further narrowings, as qualifiers on the search and as a local pass on the fallback. */
readonly filters?: PullRequestListFilters | undefined;
}) => Effect.Effect<GitHubPullRequestListBatch, GitHubPullRequestCliError>;
/**
@@ -309,6 +353,7 @@ export class GitHubPullRequestCli extends Context.Service<
readonly limit: number;
readonly query?: string | undefined;
readonly cursor?: ProviderListCursor | undefined;
readonly filters?: PullRequestListFilters | undefined;
}) => Effect.Effect<GitHubPullRequestSearchBatch, GitHubPullRequestCliError>;
/** The line counts the search leaves out, for rows already on the page. */
@@ -328,6 +373,20 @@ export class GitHubPullRequestCli extends Context.Service<
readonly number: number;
}) => Effect.Effect<GitHubPullRequestDetail, GitHubPullRequestCliError>;
/**
* How far the branch trails its base, and whether this viewer may update it. Its own read
* because the comparison needs the head ref the detail answers with — a fork's branch is not
* addressable in the base repository by name alone.
*/
readonly getPullRequestBaseComparison: (input: {
readonly cwd: string;
readonly repository: string;
readonly host: string;
readonly number: number;
/** Qualified `owner:branch`, which is the only form a fork's head resolves under. */
readonly headRef: string;
}) => Effect.Effect<GitHubBaseComparison, GitHubPullRequestCliError>;
readonly getPullRequestActivity: (input: {
readonly cwd: string;
readonly repository: string;
@@ -418,6 +477,7 @@ export class GitHubPullRequestCli extends Context.Service<
readonly number: number;
readonly action: PullRequestAction;
readonly mergeMethod?: PullRequestMergeMethod;
readonly updateMethod?: PullRequestUpdateMethod;
}) => Effect.Effect<void, GitHubPullRequestCliError>;
readonly commentOnPullRequest: (input: {
@@ -453,6 +513,47 @@ export class GitHubPullRequestCli extends Context.Service<
readonly threadId: string;
readonly resolved: boolean;
}) => Effect.Effect<void, GitHubPullRequestCliError>;
/**
* Adds a reaction to a remark, or takes it back. `subjectId` is any node GitHub calls
* reactable — a comment, a review, or the pull request itself, which is looked up here
* because nothing in the conversation names it. A given `subjectId` is confirmed to belong
* to this pull request before the mutation runs, since nothing else ties the two together.
*/
readonly setReaction: (input: {
readonly cwd: string;
readonly repository: string;
readonly host: string;
readonly number: number;
readonly subjectId?: string | undefined;
readonly content: PullRequestReactionContent;
readonly reacted: boolean;
}) => Effect.Effect<void, GitHubPullRequestCliError>;
/** Rewrites the pull request's own words, leaving whichever of the two was not given. */
readonly updatePullRequest: (input: {
readonly cwd: string;
readonly repository: string;
readonly host: string;
readonly number: number;
readonly title?: string | undefined;
readonly body?: string | undefined;
}) => Effect.Effect<void, GitHubPullRequestCliError>;
/**
* Rewrites a remark. `commentId` is trusted to be whatever node it names, so it is confirmed
* to belong to this pull request before the mutation runs, the way a reaction subject is.
* Whether the remark is the reader's to rewrite is GitHub's own answer, not one asked here.
*/
readonly updateComment: (input: {
readonly cwd: string;
readonly repository: string;
readonly host: string;
readonly number: number;
readonly commentId: string;
readonly kind: "issue-comment" | "review-comment";
readonly body: string;
}) => Effect.Effect<void, GitHubPullRequestCliError>;
}
>()("t3/pullRequest/GitHubPullRequestCli") {}
@@ -501,6 +602,76 @@ function searchPhrase(query: string): string {
return `"${query.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
}
/** GitHub's own spelling of a review state, which is not the contract's. */
const REVIEW_QUALIFIERS = {
approved: "approved",
"changes-requested": "changes_requested",
"review-required": "required",
none: "none",
} as const;
/**
* The extra narrowings as GitHub search qualifiers. Values a reader typed are quoted, and the
* one character that could end the quoted value early is dropped rather than escaped: no GitHub
* label or login holds a double quote, so there is nothing to preserve and everything to lose.
*/
function qualifierValue(value: string): string {
return `"${value.replaceAll('"', "").trim()}"`;
}
function filterQualifiers(
filters: PullRequestListFilters | undefined,
viewer: string,
): ReadonlyArray<string> {
if (filters === undefined) return [];
return [
// One qualifier per group, its names joined by commas — GitHub's own OR.
...(filters.labels ?? []).flatMap((group) =>
group.length === 0 ? [] : [`label:${group.map(qualifierValue).join(",")}`],
),
...(filters.excludedLabels ?? []).map((label) => `-label:${qualifierValue(label)}`),
...(filters.author === undefined
? []
: [`author:${qualifierValue(resolvePullRequestAuthorFilter(filters.author, viewer))}`]),
...(filters.draft === undefined ? [] : [`draft:${filters.draft === "only"}`]),
...(filters.review === undefined ? [] : [`review:${REVIEW_QUALIFIERS[filters.review]}`]),
...(filters.checks === undefined
? []
: [`status:${filters.checks === "passing" ? "success" : "failure"}`]),
];
}
/**
* The same narrowings over a row that has already arrived, for the search-free fallback. Every
* listed row now carries its own `checksState`, so `checks` is judged the way `review` is: by
* equality against the row's field. Unlike `review`, `checks` has no `"none"` value to catch an
* absent state on purpose — a row with no checks configured, or whose checks are still `pending`,
* equals neither `"passing"` nor `"failing"` and so fails both, the same as a row search would
* not have surfaced for `status:success` or `status:failure`.
*/
function matchesFilters(
item: GitHubPullRequestListItem,
filters: PullRequestListFilters | undefined,
viewer: string,
): boolean {
if (filters === undefined) return true;
const labels = item.labels.map((label) => label.name.trim().toLowerCase());
const holds = (label: string) => labels.includes(label.trim().toLowerCase());
return (
(filters.draft === undefined || item.isDraft === (filters.draft === "only")) &&
(filters.review === undefined ||
(filters.review === "none"
? item.reviewDecision === null
: item.reviewDecision === filters.review)) &&
(filters.checks === undefined || item.checksState === filters.checks) &&
(filters.labels === undefined || filters.labels.every((group) => group.some(holds))) &&
(filters.excludedLabels === undefined || !filters.excludedLabels.some(holds)) &&
(filters.author === undefined ||
item.author?.login.toLowerCase() ===
resolvePullRequestAuthorFilter(filters.author, viewer).toLowerCase())
);
}
function involvementArgs(input: {
readonly state: PullRequestListState;
readonly involvement: PullRequestInvolvement;
@@ -513,6 +684,7 @@ function involvementArgs(input: {
* cannot use search at all and takes whatever order `gh pr list` answers in.
*/
readonly sorted: boolean;
readonly filters?: PullRequestListFilters | undefined;
}): ReadonlyArray<string> {
// `--state closed` includes merged pull requests, so the Closed tab additionally excludes
// them through search; `--author` and `review-requested:` are GitHub's own filters. `gh`
@@ -531,6 +703,7 @@ function involvementArgs(input: {
// sharing one instant are ordinary and the caller drops the ones it has already sent —
// asking for strictly older would lose the rest of them instead.
...(input.cursor === undefined ? [] : [`updated:<=${input.cursor.updatedBefore}`]),
...filterQualifiers(input.filters, input.viewer),
// `gh pr list` answers newest-created first, which is not the order the page reads rows in
// and not an order a continuation can carry on from: a change request opened last year and
// touched this morning belongs at the top of the list and at the front of the first slice.
@@ -550,6 +723,7 @@ function matchesUnsortedListing(
readonly state: PullRequestListState;
readonly involvement: PullRequestInvolvement;
readonly viewer: string;
readonly filters?: PullRequestListFilters | undefined;
},
): boolean {
const matchesState = input.state === "all" || item.state === input.state;
@@ -560,7 +734,7 @@ function matchesUnsortedListing(
? item.author?.login.toLowerCase() === viewer
: item.hasTeamReviewRequest ||
item.reviewRequestLogins.some((login) => login.toLowerCase() === viewer));
return matchesState && matchesInvolvement;
return matchesState && matchesInvolvement && matchesFilters(item, input.filters, input.viewer);
}
/** What a repository selector may hold before it goes into a search as itself. */
@@ -587,6 +761,7 @@ function searchQuery(input: {
readonly viewer: string;
readonly query?: string | undefined;
readonly cursor?: ProviderListCursor | undefined;
readonly filters?: PullRequestListFilters | undefined;
}): string | null {
if (input.repositories.length === 0) return null;
const repositories = input.repositories.map((repository) => repository.trim());
@@ -603,6 +778,7 @@ function searchQuery(input: {
...(query.length === 0 ? [] : [searchPhrase(query)]),
// Inclusive, and de-duplicated by the caller, for the reason the per-repository read gives.
...(input.cursor === undefined ? [] : [`updated:<=${input.cursor.updatedBefore}`]),
...filterQualifiers(input.filters, input.viewer),
// The order the page reads its rows in, and the only order a continuation can carry on from.
"sort:updated-desc",
...repositories.map((repository) => `repo:${repository}`),
@@ -621,10 +797,20 @@ function cursorVariable(cursor: string | null): readonly [string, string] {
function actionArgs(
action: PullRequestAction,
mergeMethod: PullRequestMergeMethod | undefined,
updateMethod: PullRequestUpdateMethod | undefined,
): ReadonlyArray<string> {
switch (action) {
case "merge":
return ["merge", `--${mergeMethod ?? "merge"}`];
// `--auto` arms the same command instead of running it, and still needs the strategy: GitHub
// stores the strategy with the standing instruction rather than choosing one at merge time.
case "enable-auto-merge":
return ["merge", "--auto", `--${mergeMethod ?? "merge"}`];
case "disable-auto-merge":
return ["merge", "--disable-auto"];
// `gh` updates with a merge commit unless asked to rebase, which is GitHub's own default.
case "update-branch":
return ["update-branch", ...(updateMethod === "rebase" ? ["--rebase"] : [])];
case "ready":
return ["ready"];
case "draft":
@@ -639,6 +825,62 @@ function actionArgs(
export const make = Effect.gen(function* () {
const github = yield* GitHubCli.GitHubCli;
/**
* The pull request's own node id, which is what a mutation against the pull request itself is
* addressed by: a reaction on its description, or a rewrite of its words.
*/
const pullRequestNodeId = (input: {
readonly cwd: string;
readonly repository: string;
readonly host: string;
readonly number: number;
readonly operation: string;
}) => {
const { owner, name } = parseRepositorySelector(input.repository);
return graphqlRead({
cwd: input.cwd,
host: input.host,
operation: input.operation,
variables: [
["-f", `owner=${owner}`],
["-f", `name=${name}`],
["-F", `number=${input.number}`],
],
query: PULL_REQUEST_NODE_ID_GRAPHQL_QUERY,
decode: decodePullRequestNodeIdJson,
});
};
/**
* Whether a client-given subject actually belongs to the pull request the request names. A
* subject id is trusted to be whatever node it names, and that node can hang off any pull
* request on the host — so the mutation itself would write wherever the id actually belongs,
* not wherever the request says it does, unless this confirms the two agree first.
*/
const subjectBelongsToPullRequest = (input: {
readonly cwd: string;
readonly repository: string;
readonly host: string;
readonly number: number;
readonly subjectId: string;
readonly operation: string;
}) => {
const { owner, name } = parseRepositorySelector(input.repository);
return graphqlRead({
cwd: input.cwd,
host: input.host,
operation: input.operation,
variables: [
["-f", `owner=${owner}`],
["-f", `name=${name}`],
["-F", `number=${input.number}`],
["-f", `subjectId=${input.subjectId}`],
],
query: REACTION_SUBJECT_PULL_REQUEST_GRAPHQL_QUERY,
decode: decodeReactionSubjectScopeJson,
});
};
// `gh` resolves a bare `owner/repo` against whichever host it defaults to, which is
// github.com. Naming the host makes a GitHub Enterprise repository resolve to its own
// install rather than to a same-named repository on github.com.
@@ -796,6 +1038,9 @@ export const make = Effect.gen(function* () {
patch: decoded.success.patch,
truncated: decoded.success.truncated,
nextCursor: morePages ? String(input.page + 1) : null,
...(decoded.success.omittedFileStats.length === 0
? {}
: { omittedFileStats: decoded.success.omittedFileStats }),
});
}),
);
@@ -977,10 +1222,15 @@ export const make = Effect.gen(function* () {
// repository's whole list, which is every row the reader did not search for. The fallback
// is for a repository the index does not cover, and a listing with no text to match is the
// only place an empty answer can mean that.
const searched = (input.query?.trim().length ?? 0) > 0;
// Every filter is a qualifier `matchesFilters` can judge over the fallback's own rows just
// as well as search judges them over its own, so carrying them into the fallback answers
// the same read rather than a wider one. Free text is the one thing the fallback cannot
// judge locally — it lists rows, it does not search their text — so a query still rules
// the fallback out: an empty answer under one is already the answer.
const hasQuery = (input.query?.trim().length ?? 0) > 0;
return read(true).pipe(
Effect.flatMap((batch) =>
batch.items.length === 0 && input.cursor === undefined && !searched
batch.items.length === 0 && input.cursor === undefined && !hasQuery
? read(false)
: Effect.succeed(batch),
),
@@ -1085,6 +1335,23 @@ export const make = Effect.gen(function* () {
}),
),
getPullRequestBaseComparison: (input) => {
const { owner, name } = parseRepositorySelector(input.repository);
return graphqlRead({
cwd: input.cwd,
host: input.host,
operation: "getPullRequestBaseComparison",
variables: [
["-f", `owner=${owner}`],
["-f", `name=${name}`],
["-F", `number=${input.number}`],
["-f", `headRef=${input.headRef}`],
],
query: BASE_COMPARISON_GRAPHQL_QUERY,
decode: decodeBaseComparisonJson,
});
},
getPullRequestActivity: (input) =>
github
.execute({
@@ -1216,8 +1483,12 @@ export const make = Effect.gen(function* () {
{ readonly additions: number; readonly deletions: number }
>();
let reviewers: ReadonlyArray<PullRequestActor> = [];
let reactions: GitHubReviewThreadPage["reactions"] = [];
const reactionsById = new Map<string, ReadonlyArray<PullRequestReaction>>();
let commits: GitHubReviewThreadPage["commits"] = [];
let viewer: GitHubReviewThreadPage["viewer"] = { canUpdate: true, didAuthor: false };
const dismissalsByReviewId = new Map<string, string>();
let dismissalCursor: string | null = null;
let cursor: string | null = null;
let page = 0;
do {
@@ -1229,14 +1500,46 @@ export const make = Effect.gen(function* () {
// first one already carries all of them.
if (page === 0) {
reviewers = read.reviewers;
reactions = read.reactions;
for (const [id, entry] of read.reactionsById) reactionsById.set(id, entry);
commits = read.commits;
viewer = read.viewer;
for (const [id, message] of read.dismissalsByReviewId)
dismissalsByReviewId.set(id, message);
dismissalCursor = read.nextDismissalCursor;
for (const [oid, stat] of read.commitStats) commitStats.set(oid, stat);
}
cursor = read.nextCursor;
page += 1;
} while (cursor !== null && page < REVIEW_THREAD_PAGES);
// Almost never entered: the embedded page already holds every dismissal a pull request
// ordinarily accrues. Followed so a review whose event fell past that page still finds
// its reason.
let dismissalPage = 0;
while (dismissalCursor !== null && dismissalPage < REVIEW_THREAD_PAGES) {
const read: {
readonly dismissalsByReviewId: ReadonlyMap<string, string>;
readonly nextCursor: string | null;
} = yield* graphqlRead({
cwd: input.cwd,
host: input.host,
operation: "listReviewThreadComments",
variables: [
["-f", `owner=${owner}`],
["-f", `name=${name}`],
["-F", `number=${input.number}`],
["-f", `cursor=${dismissalCursor}`],
],
query: REVIEW_DISMISSALS_GRAPHQL_QUERY,
decode: decodeReviewDismissalsJson,
});
for (const [id, message] of read.dismissalsByReviewId)
dismissalsByReviewId.set(id, message);
dismissalCursor = read.nextCursor;
dismissalPage += 1;
}
// Only the threads GitHub said were unfinished cost a request; the rest arrived whole
// with the page they were listed on.
const finished = yield* Effect.forEach(
@@ -1264,11 +1567,14 @@ export const make = Effect.gen(function* () {
const reviewThreads = finished.map((entry) => entry.thread);
return {
comments: reviewThreadConversation(reviewThreads),
dismissalsByReviewId,
reviewThreads,
// GitHub's own count of each thread, so the number the page shows is the host's even
// where a bound kept some of the words on GitHub.
commentCount: finished.reduce((total, entry) => total + entry.commentCount, 0),
truncated: cursor !== null || finished.some((entry) => entry.truncated),
reactions,
reactionsById,
reviewers,
avatarsByLogin,
commitStats,
@@ -1396,7 +1702,11 @@ export const make = Effect.gen(function* () {
},
runPullRequestAction: (input) => {
const [subcommand, ...flags] = actionArgs(input.action, input.mergeMethod);
const [subcommand, ...flags] = actionArgs(
input.action,
input.mergeMethod,
input.updateMethod,
);
return github
.execute({
cwd: input.cwd,
@@ -1467,6 +1777,91 @@ export const make = Effect.gen(function* () {
: UNRESOLVE_REVIEW_THREAD_GRAPHQL_MUTATION,
variables: { threadId: input.threadId },
}),
setReaction: (input) => {
const givenSubjectId = input.subjectId;
const subjectId =
givenSubjectId === undefined
? pullRequestNodeId({ ...input, operation: "setReaction" })
: subjectBelongsToPullRequest({
...input,
subjectId: givenSubjectId,
operation: "setReaction",
}).pipe(
Effect.flatMap((belongs) =>
belongs
? Effect.succeed(givenSubjectId)
: Effect.fail(
new GitHubSubjectScopeError({
command: "gh",
cwd: input.cwd,
operation: "setReaction",
}),
),
),
);
return subjectId.pipe(
Effect.flatMap((subjectId) =>
graphql({
cwd: input.cwd,
host: input.host,
query: input.reacted ? ADD_REACTION_GRAPHQL_MUTATION : REMOVE_REACTION_GRAPHQL_MUTATION,
variables: { subjectId, content: gitHubReactionContent(input.content) },
}),
),
);
},
updatePullRequest: (input) =>
pullRequestNodeId({ ...input, operation: "updatePullRequest" }).pipe(
Effect.flatMap((pullRequestId) =>
graphql({
cwd: input.cwd,
host: input.host,
query: UPDATE_PULL_REQUEST_GRAPHQL_MUTATION,
// A field the caller did not name is left out of the request entirely, so GitHub
// keeps the words that are there rather than being asked for an empty one.
variables: {
pullRequestId,
...(input.title === undefined ? {} : { title: input.title }),
...(input.body === undefined ? {} : { body: input.body }),
},
}),
),
),
updateComment: (input) =>
subjectBelongsToPullRequest({
cwd: input.cwd,
repository: input.repository,
host: input.host,
number: input.number,
subjectId: input.commentId,
operation: "updateComment",
}).pipe(
Effect.flatMap((belongs) =>
belongs
? Effect.succeed(input.commentId)
: Effect.fail(
new GitHubSubjectScopeError({
command: "gh",
cwd: input.cwd,
operation: "updateComment",
}),
),
),
Effect.flatMap((commentId) =>
graphql({
cwd: input.cwd,
host: input.host,
query:
input.kind === "issue-comment"
? UPDATE_ISSUE_COMMENT_GRAPHQL_MUTATION
: UPDATE_REVIEW_COMMENT_GRAPHQL_MUTATION,
variables: { commentId, body: input.body },
}),
),
),
});
});
@@ -1,6 +1,7 @@
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import type { PullRequestReaction } from "@t3tools/contracts";
import * as GitHubPullRequestCli from "./GitHubPullRequestCli.ts";
import { gitHubViewerPermissions, loginAvatarUrl, make } from "./GitHubPullRequestProvider.ts";
@@ -9,7 +10,16 @@ import type { GitHubReviewThreadComments } from "./gitHubPullRequestJson.ts";
describe("gitHubViewerPermissions", () => {
it("offers everything to a viewer who can write to the repository", () => {
expect(gitHubViewerPermissions({ canWrite: true, canUpdate: true, didAuthor: false })).toEqual({
actions: ["merge", "ready", "draft", "close", "reopen"],
// Arming a merge for later is the merge, so it travels with it.
actions: [
"merge",
"enable-auto-merge",
"disable-auto-merge",
"ready",
"draft",
"close",
"reopen",
],
comment: true,
resolve: true,
verdicts: ["comment", "approve", "request-changes"],
@@ -34,7 +44,7 @@ describe("gitHubViewerPermissions", () => {
it("keeps an author's own pull request theirs to close, with read access and no more", () => {
expect(gitHubViewerPermissions({ canWrite: false, canUpdate: true, didAuthor: true })).toEqual({
// Merging is the one thing writing is needed for; the rest an author may do.
// Merging is the one thing writing is needed for, now or later; the rest an author may do.
actions: ["ready", "draft", "close", "reopen"],
comment: true,
resolve: true,
@@ -71,17 +81,20 @@ describe("gitHubViewerPermissions", () => {
title: "Pull request 7",
url: "https://github.com/acme/web/pull/7",
author: null,
headRepositoryOwner: null,
headBranch: "feat/page",
baseBranch: "main",
state: "open",
isDraft: false,
mergeability: "mergeable",
reviewDecision: null,
additions: 1,
deletions: 1,
createdAt: "2026-07-01T00:00:00Z",
updatedAt: "2026-07-02T00:00:00Z",
reviewRequestLogins: [],
hasTeamReviewRequest: false,
checksState: null,
labels: [],
body: "",
changedFiles: 1,
@@ -104,6 +117,101 @@ describe("gitHubViewerPermissions", () => {
);
});
describe("getViewerPermissions", () => {
const openDetail = {
authorId: null,
number: 7,
title: "Pull request 7",
url: "https://github.com/acme/web/pull/7",
author: null,
headRepositoryOwner: "acme",
headBranch: "feat/page",
baseBranch: "main",
state: "open" as const,
isDraft: false,
mergeability: "mergeable" as const,
reviewDecision: null,
additions: 1,
deletions: 1,
createdAt: "2026-07-01T00:00:00Z",
updatedAt: "2026-07-02T00:00:00Z",
reviewRequestLogins: [],
hasTeamReviewRequest: false,
checksState: null,
labels: [],
body: "",
changedFiles: 1,
mergedAt: null,
closedAt: null,
checks: [],
comments: [],
commits: [],
};
const layerWithComparison = (
comparison: Effect.Effect<{
readonly behindBy: number | null;
readonly viewerCanUpdate: boolean;
}>,
) =>
Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
getPullRequestDetail: () => Effect.succeed(openDetail),
getPullRequestBaseComparison: () => comparison,
getViewerAccess: () => Effect.succeed({ canWrite: true, canUpdate: true, didAuthor: false }),
});
it.effect("offers update-branch when the comparison grants it", () =>
Effect.gen(function* () {
const provider = yield* make;
const permissions = yield* provider.getViewerPermissions({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
});
expect(permissions.actions).toContain("update-branch");
expect(permissions.updateMethods).toEqual(["merge", "rebase"]);
}).pipe(
Effect.provide(layerWithComparison(Effect.succeed({ behindBy: 3, viewerCanUpdate: true }))),
),
);
it.effect("withholds update-branch when the comparison cannot be read", () =>
Effect.gen(function* () {
const provider = yield* make;
const permissions = yield* provider.getViewerPermissions({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
});
expect(permissions.actions).not.toContain("update-branch");
expect(permissions.updateMethods).toBeUndefined();
// The rest of the answer survives a comparison nobody could make.
expect(permissions.actions).toContain("merge");
}).pipe(
Effect.provide(
Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
getPullRequestDetail: () => Effect.succeed(openDetail),
getPullRequestBaseComparison: () =>
Effect.fail(
new GitHubPullRequestCli.GitHubPullRequestReadError({
command: "gh",
cwd: "/w",
operation: "getPullRequestBaseComparison",
cause: new Error("unreadable"),
}),
),
getViewerAccess: () =>
Effect.succeed({ canWrite: true, canUpdate: true, didAuthor: false }),
}),
),
),
);
});
describe("getChangeRequest commits", () => {
const baseDetail = {
authorId: null,
@@ -122,6 +230,7 @@ describe("getChangeRequest commits", () => {
updatedAt: "2026-07-02T00:00:00Z",
reviewRequestLogins: [],
hasTeamReviewRequest: false,
checksState: null,
labels: [],
body: "",
changedFiles: 1,
@@ -133,9 +242,12 @@ describe("getChangeRequest commits", () => {
const baseThreadComments = {
comments: [],
dismissalsByReviewId: new Map<string, string>(),
reviewThreads: [],
commentCount: 0,
truncated: false,
reactions: [],
reactionsById: new Map<string, ReadonlyArray<PullRequestReaction>>(),
reviewers: [],
avatarsByLogin: new Map<string, string>(),
commitStats: new Map<string, { readonly additions: number; readonly deletions: number }>(),
@@ -200,6 +312,122 @@ describe("getChangeRequest commits", () => {
);
});
describe("getChangeRequestActivity dismissed reviews", () => {
const dismissedReview = (body: string) => ({
id: "PRR_1",
kind: "review" as const,
author: null,
body,
createdAt: "2026-07-03T00:00:00Z",
url: null,
path: null,
reviewState: "DISMISSED",
});
const threadComments: GitHubReviewThreadComments = {
comments: [],
dismissalsByReviewId: new Map([["PRR_1", "Dismissing prior approval to re-evaluate 9b66581"]]),
reviewThreads: [],
commentCount: 0,
truncated: false,
reactions: [],
reactionsById: new Map(),
reviewers: [],
avatarsByLogin: new Map(),
commitStats: new Map(),
commits: [],
viewer: { canUpdate: true, didAuthor: false },
};
const layerFor = (body: string) =>
Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
getPullRequestActivity: () =>
Effect.succeed({ author: null, comments: [dismissedReview(body)], commits: [] }),
listReviewThreadComments: () => Effect.succeed(threadComments),
});
const readActivity = Effect.gen(function* () {
const provider = yield* make;
return yield* provider.getChangeRequestActivity({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
});
});
it.effect("fills a marker-only dismissed review with the timeline's reason", () =>
// Macroscope's approvals carry only an HTML comment, which markdown renders as nothing —
// an empty-string check misses them and the card opens onto nothing.
readActivity.pipe(
Effect.map((activity) => {
expect(activity.comments[0]?.body).toBe("Dismissing prior approval to re-evaluate 9b66581");
}),
Effect.provide(layerFor("<!-- Macroscope (Approvability) review body marker -->")),
),
);
it.effect("keeps the words of a dismissed review that has its own", () =>
readActivity.pipe(
Effect.map((activity) => {
expect(activity.comments[0]?.body).toBe("These findings still stand.");
}),
Effect.provide(layerFor("These findings still stand.")),
),
);
});
describe("editing", () => {
const rewrites: Array<unknown> = [];
it.effect("hands a rewrite to the CLI as the request named it", () =>
Effect.gen(function* () {
const provider = yield* make;
expect(provider.capabilities.edit).toEqual({ changeRequest: true, comment: true });
yield* provider.updateChangeRequest!({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
title: "A better title",
});
yield* provider.updateComment!({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
commentId: "IC_1",
kind: "review-comment",
body: "Reworded.",
});
expect(rewrites).toEqual([
{
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
title: "A better title",
},
{
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
commentId: "IC_1",
kind: "review-comment",
body: "Reworded.",
},
]);
}).pipe(
Effect.provide(
Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
updatePullRequest: (input) => Effect.sync(() => void rewrites.push(input)),
updateComment: (input) => Effect.sync(() => void rewrites.push(input)),
}),
),
),
);
});
describe("loginAvatarUrl", () => {
it("serves a user's picture from the host they belong to", () => {
expect(loginAvatarUrl("octocat", "github.com")).toBe("https://github.com/octocat.png?size=80");
@@ -2,6 +2,7 @@ import * as Effect from "effect/Effect";
import type {
PullRequestActor,
PullRequestCapabilities,
PullRequestReaction,
PullRequestViewerPermissions,
} from "@t3tools/contracts";
@@ -17,9 +18,20 @@ import type { GitHubViewerAccess } from "./gitHubPullRequestJson.ts";
const CAPABILITIES: PullRequestCapabilities = {
diff: true,
comment: true,
actions: ["merge", "ready", "draft", "close", "reopen"],
actions: [
"merge",
"ready",
"draft",
"close",
"reopen",
"update-branch",
"enable-auto-merge",
"disable-auto-merge",
],
mergeMethods: ["merge", "squash", "rebase"],
updateMethods: ["merge", "rebase"],
search: true,
reactions: true,
review: {
inlineComment: true,
reply: true,
@@ -27,6 +39,7 @@ const CAPABILITIES: PullRequestCapabilities = {
verdicts: ["comment", "approve", "request-changes"],
},
reviewers: { request: true, listCandidates: true },
edit: { changeRequest: true, comment: true },
};
/**
@@ -49,8 +62,13 @@ const CAPABILITIES: PullRequestCapabilities = {
export function gitHubViewerPermissions(access: GitHubViewerAccess): PullRequestViewerPermissions {
return {
actions: [
...(access.canWrite ? (["merge"] as const) : []),
// Arming a merge and taking the arming back are the merge, deferred: whoever may not
// merge here may not leave an instruction to merge later either.
...(access.canWrite ? (["merge", "enable-auto-merge", "disable-auto-merge"] as const) : []),
...(access.canUpdate ? (["ready", "draft", "close", "reopen"] as const) : []),
// Whether this viewer may update the branch is GitHub's own answer, read with the
// comparison; without it the action is offered to nobody rather than to everybody.
...(access.canUpdateBranch === true ? (["update-branch"] as const) : []),
],
comment: true,
resolve: access.canWrite || access.didAuthor,
@@ -59,6 +77,7 @@ export function gitHubViewerPermissions(access: GitHubViewerAccess): PullRequest
// leaves them commenting, which is what an author has to say about their own change anyway.
verdicts: access.didAuthor ? (["comment"] as const) : CAPABILITIES.review.verdicts,
requestReviewers: access.canWrite,
...(access.canUpdateBranch === true ? { updateMethods: CAPABILITIES.updateMethods } : {}),
};
}
@@ -98,6 +117,10 @@ export function loginAvatarUrl(login: string, host: string): string | null {
return /^[a-z0-9][a-z0-9-]{0,38}$/iu.test(login) ? `https://${host}/${login}.png?size=80` : null;
}
/** True where markdown would render nothing: whitespace, or only HTML comments. */
const rendersEmpty = (body: string): boolean =>
body.replace(/<!--[\s\S]*?-->/g, "").trim().length === 0;
export const make = Effect.gen(function* () {
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
@@ -129,6 +152,7 @@ export const make = Effect.gen(function* () {
limit: input.limit,
query: input.query,
cursor: input.cursor,
filters: input.filters,
})
.pipe(
Effect.mapError(fail("listChangeRequests")),
@@ -172,6 +196,7 @@ export const make = Effect.gen(function* () {
limit: input.limit,
query: input.query,
cursor: input.cursor,
filters: input.filters,
})
.pipe(
Effect.mapError(fail("listChangeRequestsAcross")),
@@ -196,7 +221,24 @@ export const make = Effect.gen(function* () {
getChangeRequest: (input) =>
Effect.all(
[
cli.getPullRequestDetail(input),
cli.getPullRequestDetail(input).pipe(
Effect.flatMap((pullRequest) =>
// Only an open pull request can be behind anything worth saying so about, and only
// one whose head repository is known can be compared at all. A comparison that
// fails is left unknown: the banner is an offer, never a blocker.
pullRequest.state !== "open" || pullRequest.headRepositoryOwner === null
? Effect.succeed({ pullRequest, comparison: null })
: cli
.getPullRequestBaseComparison({
...input,
headRef: `${pullRequest.headRepositoryOwner}:${pullRequest.headBranch}`,
})
.pipe(
Effect.map((comparison) => ({ pullRequest, comparison })),
Effect.orElseSucceed(() => ({ pullRequest, comparison: null })),
),
),
),
cli.getRepositoryAccess({
cwd: input.cwd,
repository: input.repository,
@@ -210,15 +252,27 @@ export const make = Effect.gen(function* () {
).pipe(
Effect.mapError(fail("getChangeRequest")),
Effect.map(
([pullRequest, repository, viewerAccess]): ProviderChangeRequestDetail => ({
...pullRequest,
reviewers: pullRequest.reviewRequestLogins.map((login) => ({
([detail, repository, viewerAccess]): ProviderChangeRequestDetail => ({
...detail.pullRequest,
reviewers: detail.pullRequest.reviewRequestLogins.map((login) => ({
login,
name: null,
avatarUrl: null,
})),
mergeCapabilities: repository.mergeCapabilities,
viewerPermissions: gitHubViewerPermissions(viewerAccess),
viewerPermissions: gitHubViewerPermissions({
...viewerAccess,
canUpdateBranch: detail.comparison?.viewerCanUpdate === true,
}),
baseComparison:
detail.comparison === null || detail.comparison.behindBy === null
? "unknown"
: detail.comparison.behindBy > 0
? "behind"
: "up-to-date",
...(detail.comparison?.behindBy == null
? {}
: { behindBy: detail.comparison.behindBy }),
}),
),
),
@@ -232,6 +286,9 @@ export const make = Effect.gen(function* () {
cli.listReviewThreadComments(input).pipe(
Effect.orElseSucceed(() => ({
comments: [],
dismissalsByReviewId: new Map<string, string>(),
reactions: [],
reactionsById: new Map<string, ReadonlyArray<PullRequestReaction>>(),
reviewThreads: [],
commentCount: 0,
truncated: true,
@@ -253,6 +310,7 @@ export const make = Effect.gen(function* () {
([pullRequest, reviewThreads]): ProviderChangeRequestActivity => ({
author: withAvatar(pullRequest.author, reviewThreads.avatarsByLogin, input.host),
reviewers: reviewThreads.reviewers,
reactions: reviewThreads.reactions,
commits: (reviewThreads.commits.length > 0
? reviewThreads.commits
: pullRequest.commits
@@ -266,7 +324,20 @@ export const make = Effect.gen(function* () {
comments: [...pullRequest.comments, ...reviewThreads.comments]
.map((comment) => ({
...comment,
// GitHub keeps the dismissal reason on the timeline event, not on the review,
// so a dismissed review with nothing visible of its own reads its words from
// there. "Visible" and not "empty": bot reviews often carry only an HTML
// marker comment, which markdown renders as nothing.
body:
comment.kind === "review" &&
comment.reviewState?.toUpperCase() === "DISMISSED" &&
rendersEmpty(comment.body)
? (reviewThreads.dismissalsByReviewId.get(comment.id) ?? comment.body)
: comment.body,
author: withAvatar(comment.author, reviewThreads.avatarsByLogin, input.host),
// A comment out of `gh pr view --json` carries none of its own: that read
// reports no reaction at all, so they arrive from the GraphQL page by node id.
reactions: comment.reactions ?? reviewThreads.reactionsById.get(comment.id) ?? [],
}))
.toSorted((left, right) => left.createdAt.localeCompare(right.createdAt)),
// `gh pr view --json comments,reviews` follows GitHub's cursors itself, so those two
@@ -285,9 +356,34 @@ export const make = Effect.gen(function* () {
),
getViewerPermissions: (input) =>
cli
.getViewerAccess(input)
.pipe(Effect.mapError(fail("getViewerPermissions")), Effect.map(gitHubViewerPermissions)),
Effect.all(
[
cli.getViewerAccess(input),
// Whether this viewer may update the branch is only on the comparison, and the
// comparison only resolves through the head ref the detail carries. A failure here
// withholds that one action rather than the whole answer, the way the detail path
// leaves the banner unknown.
cli.getPullRequestDetail(input).pipe(
Effect.flatMap((pullRequest) =>
pullRequest.state !== "open" || pullRequest.headRepositoryOwner === null
? Effect.succeed(false)
: cli
.getPullRequestBaseComparison({
...input,
headRef: `${pullRequest.headRepositoryOwner}:${pullRequest.headBranch}`,
})
.pipe(Effect.map((comparison) => comparison.viewerCanUpdate === true)),
),
Effect.orElseSucceed(() => false),
),
],
{ concurrency: 2 },
).pipe(
Effect.mapError(fail("getViewerPermissions")),
Effect.map(([access, canUpdateBranch]) =>
gitHubViewerPermissions({ ...access, canUpdateBranch }),
),
),
getDiff: (input) => cli.getPullRequestDiff(input).pipe(Effect.mapError(fail("getDiff"))),
@@ -318,11 +414,37 @@ export const make = Effect.gen(function* () {
number: input.number,
action: input.action,
...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
...(input.updateMethod === undefined ? {} : { updateMethod: input.updateMethod }),
})
.pipe(Effect.mapError(fail("runAction"))),
updateChangeRequest: (input) =>
cli
.updatePullRequest({
cwd: input.cwd,
repository: input.repository,
host: input.host,
number: input.number,
...(input.title === undefined ? {} : { title: input.title }),
...(input.body === undefined ? {} : { body: input.body }),
})
.pipe(Effect.mapError(fail("updateChangeRequest"))),
comment: (input) => cli.commentOnPullRequest(input).pipe(Effect.mapError(fail("comment"))),
updateComment: (input) =>
cli
.updateComment({
cwd: input.cwd,
repository: input.repository,
host: input.host,
number: input.number,
commentId: input.commentId,
kind: input.kind,
body: input.body,
})
.pipe(Effect.mapError(fail("updateComment"))),
submitReview: (input) => cli.submitReview(input).pipe(Effect.mapError(fail("submitReview"))),
replyToThread: (input) =>
@@ -336,6 +458,19 @@ export const make = Effect.gen(function* () {
})
.pipe(Effect.mapError(fail("replyToThread"))),
setReaction: (input) =>
cli
.setReaction({
cwd: input.cwd,
repository: input.repository,
host: input.host,
number: input.number,
...(input.subjectId === undefined ? {} : { subjectId: input.subjectId }),
content: input.content,
reacted: input.reacted,
})
.pipe(Effect.mapError(fail("setReaction"))),
setThreadResolution: (input) =>
cli
.setReviewThreadResolution({
@@ -414,6 +414,69 @@ layer("GitLabPullRequestCli.layer", (it) => {
}),
);
it.effect("arms auto-merge with the same strategy a merge would have used", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(output("")));
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
yield* cli.runMergeRequestAction({
cwd: "/w",
repository: "acme/web",
number: 7,
action: "enable-auto-merge",
mergeMethod: "squash",
});
expect(argsOfCall(0)).toEqual([
"mr",
"merge",
"7",
"--repo",
"acme/web",
"--auto-merge=true",
"--yes",
"--squash",
]);
}),
);
it.effect("cancels an armed auto-merge through the API glab has no flag for", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(output("{}")));
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
yield* cli.runMergeRequestAction({
cwd: "/w",
repository: "acme/platform/web",
number: 7,
action: "disable-auto-merge",
});
expect(argsOfCall(0)).toEqual([
"api",
"projects/acme%2Fplatform%2Fweb/merge_requests/7/cancel_merge_when_pipeline_succeeds",
"--method",
"POST",
]);
}),
);
it.effect("brings a stale branch up to date by rebasing it, the only way GitLab has", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(output("")));
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
yield* cli.runMergeRequestAction({
cwd: "/w",
repository: "acme/web",
number: 7,
action: "update-branch",
});
expect(argsOfCall(0)).toEqual(["mr", "rebase", "7", "--repo", "acme/web"]);
}),
);
it.effect("moves a merge request back to draft through glab", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(output("")));
@@ -791,6 +854,21 @@ layer("GitLabPullRequestCli.layer", (it) => {
}),
);
it.effect("asks the detail read for the divergence GitLab withholds by default", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(output('{"message":"404 Not Found"}')));
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
yield* Effect.ignore(
cli.getMergeRequestDetail({ cwd: "/w", repository: "acme/web", number: 7 }),
);
expect(argsOfCall(0)[1]).toBe(
"projects/acme%2Fweb/merge_requests/7?include_diverged_commits_count=true",
);
}),
);
it.effect("fails the read when GitLab returns something unreadable", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(output('{"message":"404 Not Found"}')));
@@ -1008,6 +1086,89 @@ layer("GitLabPullRequestCli.layer", (it) => {
}),
);
it.effect("awards an emoji through a POST naming it, not a body", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
yield* cli.setReaction({
cwd: "/w",
repository: "acme/web",
number: 7,
content: "thumbs-up",
reacted: true,
});
assert.strictEqual(mockedExecute.mock.calls.length, 1);
expect(argsOfCall(0)).toEqual([
"api",
"projects/acme%2Fweb/merge_requests/7/award_emoji?name=thumbsup",
"--method",
"POST",
]);
}),
);
it.effect("removes an award by listing them and deleting the reader's own id", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
// @effect-diagnostics-next-line preferSchemaOverJson:off
Effect.succeed(output(JSON.stringify({ username: "bilal" }))),
);
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify([
{ id: 5, name: "thumbsup", user: { username: "bilal" } },
{ id: 6, name: "thumbsup", user: { username: "julius" } },
]),
),
),
);
mockedExecute.mockReturnValueOnce(Effect.succeed(output("{}")));
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
yield* cli.setReaction({
cwd: "/w",
repository: "acme/web",
number: 7,
content: "thumbs-up",
reacted: false,
});
assert.strictEqual(mockedExecute.mock.calls.length, 3);
expect(argsOfCall(2)).toEqual([
"api",
"projects/acme%2Fweb/merge_requests/7/award_emoji/5",
"--method",
"DELETE",
]);
}),
);
it.effect("does nothing when the reader has no award of that name to take back", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
// @effect-diagnostics-next-line preferSchemaOverJson:off
Effect.succeed(output(JSON.stringify({ username: "bilal" }))),
);
mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
yield* cli.setReaction({
cwd: "/w",
repository: "acme/web",
number: 7,
content: "thumbs-up",
reacted: false,
});
// Nothing to delete: the reaction the caller asked to take back is already gone.
assert.strictEqual(mockedExecute.mock.calls.length, 2);
}),
);
it.effect("names a merge request with no diff revisions rather than calling it unreadable", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
@@ -1141,4 +1302,99 @@ layer("GitLabPullRequestCli.layer", (it) => {
expect(JSON.parse(callAt(1).stdin ?? "")).toEqual({ reviewer_ids: [5] });
}),
);
it.effect("rewrites a title without touching the description", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
yield* cli.updateMergeRequest({
cwd: "/w",
repository: "acme/web",
number: 7,
title: "A better title",
});
expect(argsOfCall(0)).toEqual([
"api",
"projects/acme%2Fweb/merge_requests/7",
"--method",
"PUT",
"--input",
"-",
"--header",
"Content-Type: application/json",
]);
// @effect-diagnostics-next-line preferSchemaOverJson:off
expect(JSON.parse(callAt(0).stdin ?? "")).toEqual({ title: "A better title" });
}),
);
it.effect("sends a rewritten body as GitLab's description, and nothing else", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
yield* cli.updateMergeRequest({
cwd: "/w",
repository: "acme/web",
number: 7,
description: "What this changes.",
});
// A title sent as an empty string would wipe the one the merge request already has.
// @effect-diagnostics-next-line preferSchemaOverJson:off
expect(JSON.parse(callAt(0).stdin ?? "")).toEqual({ description: "What this changes." });
}),
);
it.effect("rewrites title and description together in one request", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
yield* cli.updateMergeRequest({
cwd: "/w",
repository: "acme/web",
number: 7,
title: "A better title",
description: "What this changes.",
});
assert.strictEqual(mockedExecute.mock.calls.length, 1);
// @effect-diagnostics-next-line preferSchemaOverJson:off
expect(JSON.parse(callAt(0).stdin ?? "")).toEqual({
title: "A better title",
description: "What this changes.",
});
}),
);
it.effect("rewrites a note in place through the note it names", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
yield* cli.updateNote({
cwd: "/w",
repository: "acme/web",
number: 7,
noteId: "42",
body: "true",
});
expect(argsOfCall(0)).toEqual([
"api",
"projects/acme%2Fweb/merge_requests/7/notes/42",
"--method",
"PUT",
"--input",
"-",
"--header",
"Content-Type: application/json",
]);
// A JSON body, so a note rewritten to a literal `true` stays text.
expect(callAt(0).stdin).toBe('{"body":"true"}');
}),
);
});
@@ -11,6 +11,8 @@ import type {
PullRequestListState,
PullRequestMergeCapabilities,
PullRequestMergeMethod,
PullRequestReaction,
PullRequestReactionContent,
PullRequestReviewCommentDraft,
PullRequestReviewThread,
PullRequestReviewVerdict,
@@ -19,6 +21,8 @@ import type {
import * as GitLabCli from "../sourceControl/GitLabCli.ts";
import {
AWARD_EMOJI_GRAPHQL_QUERY,
decodeAwardEmojiJson,
decodeCommitDiffRefsJson,
decodeCommitsJson,
decodeDiffRefsJson,
@@ -27,9 +31,11 @@ import {
decodeMergeRequestDiffsJson,
decodeMergeRequestListJson,
decodeNotesJson,
decodeOwnAwardIdJson,
decodeProjectMergeCapabilitiesJson,
decodeProjectUsersJson,
decodeViewerJson,
gitLabAwardName,
type GitLabDiffRefs,
type GitLabMergeRequestDetail,
type GitLabMergeRequestListItem,
@@ -303,6 +309,15 @@ export class GitLabPullRequestCli extends Context.Service<
readonly mergeMethod?: PullRequestMergeMethod;
}) => Effect.Effect<void, GitLabPullRequestCliError>;
/** Whichever of the two is given is sent. GitLab calls a merge request's body its description. */
readonly updateMergeRequest: (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
readonly title?: string | undefined;
readonly description?: string | undefined;
}) => Effect.Effect<void, GitLabPullRequestCliError>;
readonly commentOnMergeRequest: (input: {
readonly cwd: string;
readonly repository: string;
@@ -310,6 +325,14 @@ export class GitLabPullRequestCli extends Context.Service<
readonly body: string;
}) => Effect.Effect<void, GitLabPullRequestCliError>;
readonly updateNote: (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
readonly noteId: string;
readonly body: string;
}) => Effect.Effect<void, GitLabPullRequestCliError>;
readonly listDiscussions: (input: {
readonly cwd: string;
readonly repository: string;
@@ -343,6 +366,32 @@ export class GitLabPullRequestCli extends Context.Service<
readonly discussionId: string;
readonly resolved: boolean;
}) => Effect.Effect<void, GitLabPullRequestCliError>;
/** The awards on the merge request and on every note of it, keyed by the note's REST id. */
readonly listReactions: (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
}) => Effect.Effect<
{
readonly reactions: ReadonlyArray<PullRequestReaction>;
readonly reactionsByNoteId: ReadonlyMap<string, ReadonlyArray<PullRequestReaction>>;
},
GitLabPullRequestCliError
>;
/**
* Awards an emoji, or takes the award back. `noteId` is a note of the merge request; absent
* awards the merge request itself, which is where its description's reactions live.
*/
readonly setReaction: (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
readonly noteId?: string | undefined;
readonly content: PullRequestReactionContent;
readonly reacted: boolean;
}) => Effect.Effect<void, GitLabPullRequestCliError>;
}
>()("t3/pullRequest/GitLabPullRequestCli") {}
@@ -412,12 +461,30 @@ function actionArgs(
...(mergeMethod === "squash" ? ["--squash"] : []),
...(mergeMethod === "rebase" ? ["--rebase"] : []),
];
// The same command with the flag the other way up: here the wait is the whole point, so
// glab is told to arm the merge rather than talked out of it.
case "enable-auto-merge":
return [
"merge",
"--auto-merge=true",
"--yes",
...(mergeMethod === "squash" ? ["--squash"] : []),
...(mergeMethod === "rebase" ? ["--rebase"] : []),
];
// Never reached: taking the arming back has no `glab mr` command, so it goes to the API.
case "disable-auto-merge":
return [];
case "ready":
return ["update", "--ready"];
case "draft":
return ["update", "--draft"];
case "close":
return ["close"];
// A rebase, because GitLab has no other way to move a branch onto its target: there is no
// merge-the-target-in equivalent of GitHub's update button, which is why this host declares
// `rebase` alone and never has to read the method it was handed.
case "update-branch":
return ["rebase"];
case "reopen":
return ["reopen"];
}
@@ -819,7 +886,11 @@ export const make = Effect.gen(function* () {
}): Effect.Effect<GitLabMergeRequestDetail, GitLabPullRequestCliError> =>
api({
cwd: input.cwd,
path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}`,
// How far behind the target branch this one is comes only when asked for by name, and it
// is asked for here rather than on a second read because it is the same merge request.
path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}?${query([
["include_diverged_commits_count", "true"],
])}`,
}).pipe(
Effect.flatMap((result) => {
const decoded = decodeMergeRequestDetailJson(result.stdout.trim());
@@ -862,26 +933,104 @@ export const make = Effect.gen(function* () {
}),
);
/** Where an award is written: a note of the merge request, or the merge request itself. */
const awardSubjectPath = (input: {
readonly repository: string;
readonly number: number;
readonly noteId?: string | undefined;
}) => {
const mergeRequest = `projects/${projectPath(input.repository)}/merge_requests/${input.number}`;
return input.noteId === undefined
? `${mergeRequest}/award_emoji`
: `${mergeRequest}/notes/${encodeURIComponent(input.noteId)}/award_emoji`;
};
/**
* The awards on the merge request and its notes, a page of notes at a time. Bounded by the same
* count as the conversation itself: awards past the notes that were read belong to notes the
* page is not showing.
*/
const awardsPage = (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
readonly cursor: string | null;
readonly page: number;
readonly collected: {
readonly reactions: ReadonlyArray<PullRequestReaction>;
readonly reactionsByNoteId: Map<string, ReadonlyArray<PullRequestReaction>>;
} | null;
}): Effect.Effect<
{
readonly reactions: ReadonlyArray<PullRequestReaction>;
readonly reactionsByNoteId: ReadonlyMap<string, ReadonlyArray<PullRequestReaction>>;
},
GitLabPullRequestCliError
> =>
api({
cwd: input.cwd,
path: "graphql",
method: "POST",
stdin: JSON.stringify({
query: AWARD_EMOJI_GRAPHQL_QUERY,
variables: {
fullPath: input.repository,
iid: String(input.number),
cursor: input.cursor,
},
}),
}).pipe(
Effect.flatMap((result) => {
const decoded = decodeAwardEmojiJson(result.stdout.trim());
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitLabMergeRequestReadError({
command: "glab",
cwd: input.cwd,
operation: "listReactions",
cause: decoded.failure,
}),
);
}
const collected = input.collected ?? {
reactions: decoded.success.reactions,
reactionsByNoteId: new Map<string, ReadonlyArray<PullRequestReaction>>(),
};
for (const [id, reactions] of decoded.success.reactionsByNoteId)
collected.reactionsByNoteId.set(id, reactions);
return decoded.success.nextCursor === null || input.page >= CONVERSATION_PAGES
? Effect.succeed(collected)
: awardsPage({
...input,
cursor: decoded.success.nextCursor,
page: input.page + 1,
collected,
});
}),
);
const viewerUsername = (input: { readonly cwd: string }) =>
api({ cwd: input.cwd, path: "user" }).pipe(
Effect.flatMap((result): Effect.Effect<string, GitLabPullRequestCliError> => {
const decoded = decodeViewerJson(result.stdout.trim());
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitLabMergeRequestReadError({
command: "glab",
cwd: input.cwd,
operation: "getViewerUsername",
cause: decoded.failure,
}),
);
}
return decoded.success === null
? Effect.fail(new GitLabViewerUnavailableError({ command: "glab", cwd: input.cwd }))
: Effect.succeed(decoded.success);
}),
);
return GitLabPullRequestCli.of({
getViewerUsername: (input) =>
api({ cwd: input.cwd, path: "user" }).pipe(
Effect.flatMap((result): Effect.Effect<string, GitLabPullRequestCliError> => {
const decoded = decodeViewerJson(result.stdout.trim());
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitLabMergeRequestReadError({
command: "glab",
cwd: input.cwd,
operation: "getViewerUsername",
cause: decoded.failure,
}),
);
}
return decoded.success === null
? Effect.fail(new GitLabViewerUnavailableError({ command: "glab", cwd: input.cwd }))
: Effect.succeed(decoded.success);
}),
),
getViewerUsername: viewerUsername,
listMergeRequests: (input) => {
const perPage = Math.min(input.limit + 1, MAX_PAGE_SIZE);
@@ -893,6 +1042,44 @@ export const make = Effect.gen(function* () {
listNotes: (input) => notesPage({ ...input, page: 1, collected: [] }),
listReactions: (input) => awardsPage({ ...input, cursor: null, page: 1, collected: null }),
setReaction: (input) =>
Effect.gen(function* () {
const subject = awardSubjectPath(input);
if (input.reacted) {
yield* api({
cwd: input.cwd,
path: `${subject}?${query([["name", gitLabAwardName(input.content)]])}`,
method: "POST",
});
return;
}
// GitLab deletes an award by its id and takes no emoji name there, so the reader's own
// award of that name is looked up first. Nothing to delete is success: the reaction the
// caller asked to take back is already gone.
const viewer = yield* viewerUsername({ cwd: input.cwd });
const listed = yield* api({ cwd: input.cwd, path: subject });
const own = decodeOwnAwardIdJson(listed.stdout.trim(), {
content: input.content,
viewer,
});
if (!Result.isSuccess(own)) {
return yield* new GitLabMergeRequestReadError({
command: "glab",
cwd: input.cwd,
operation: "setReaction",
cause: own.failure,
});
}
if (own.success === null) return;
yield* api({
cwd: input.cwd,
path: `${subject}/${own.success}`,
method: "DELETE",
});
}),
listCommits: (input) =>
api({
cwd: input.cwd,
@@ -1053,6 +1240,16 @@ export const make = Effect.gen(function* () {
),
runMergeRequestAction: (input) => {
// `glab mr merge` arms auto-merge and never disarms it, so the one direction the CLI has
// no flag for is asked of GitLab directly through the same `api` passthrough the rest of
// this module writes with.
if (input.action === "disable-auto-merge") {
return api({
cwd: input.cwd,
path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/cancel_merge_when_pipeline_succeeds`,
method: "POST",
}).pipe(Effect.asVoid);
}
const [subcommand, ...flags] = actionArgs(input.action, input.mergeMethod);
return gitlab
.execute({
@@ -1062,6 +1259,20 @@ export const make = Effect.gen(function* () {
.pipe(Effect.asVoid);
},
updateMergeRequest: (input) =>
api({
cwd: input.cwd,
path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}`,
method: "PUT",
// Only the fields the caller asked to change: GitLab leaves out what it is not sent, and
// clears what it is sent empty — so a title corrected on its own must carry no
// description at all.
stdin: JSON.stringify({
...(input.title === undefined ? {} : { title: input.title }),
...(input.description === undefined ? {} : { description: input.description }),
}),
}).pipe(Effect.asVoid),
commentOnMergeRequest: (input) =>
api({
cwd: input.cwd,
@@ -1072,6 +1283,16 @@ export const make = Effect.gen(function* () {
stdin: JSON.stringify({ body: input.body }),
}).pipe(Effect.asVoid),
updateNote: (input) =>
api({
cwd: input.cwd,
path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/notes/${encodeURIComponent(
input.noteId,
)}`,
method: "PUT",
stdin: JSON.stringify({ body: input.body }),
}).pipe(Effect.asVoid),
listDiscussions: (input) => discussionsPage({ ...input, page: 1, collected: [] }),
submitReview: (input) =>
@@ -1,20 +1,36 @@
import { describe, expect, it } from "vite-plus/test";
import { assert, describe, expect, it, vi } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { gitLabViewerPermissions } from "./GitLabPullRequestProvider.ts";
import * as GitLabPullRequestCli from "./GitLabPullRequestCli.ts";
import { gitLabViewerPermissions, make } from "./GitLabPullRequestProvider.ts";
describe("gitLabViewerPermissions", () => {
it("offers everything to a viewer GitLab says can merge", () => {
expect(gitLabViewerPermissions({ viewerCanMerge: true })).toEqual({
actions: ["merge", "ready", "draft", "close", "reopen"],
// Arming a merge for later and taking the arming back answer to the same `can_merge`.
actions: [
"merge",
"ready",
"draft",
"close",
"reopen",
"update-branch",
"enable-auto-merge",
"disable-auto-merge",
],
comment: true,
resolve: true,
verdicts: ["comment", "approve"],
// GitLab says nothing about who may set a reviewer, and an unreported permission is granted.
requestReviewers: true,
// Rebase and nothing else: GitLab cannot merge a target branch into a source branch, so
// offering the choice would be offering something no request could carry out.
updateMethods: ["rebase"],
});
});
it("keeps merge from a viewer GitLab says cannot", () => {
it("keeps merge, now and later, from a viewer GitLab says cannot", () => {
// `user.can_merge` already accounts for the role, the approval rules and a protected target
// branch, so it is the one answer here that does not have to be inferred.
expect(gitLabViewerPermissions({ viewerCanMerge: false })).toEqual({
@@ -26,6 +42,12 @@ describe("gitLabViewerPermissions", () => {
});
});
it("names no way of updating a branch it will not let this viewer update", () => {
// The action and the strategy behind it go together: a button offered with nothing to press
// it with, or a strategy left standing next to a withheld button, is a half-refusal.
expect(gitLabViewerPermissions({ viewerCanMerge: false }).updateMethods).toBeUndefined();
});
it("treats an author with read access as any other reader, which is all GitLab says", () => {
// Its REST API names no relationship between the viewer and the merge request beyond
// `can_merge`, so the four an author keeps stay offered to everyone rather than being taken
@@ -38,3 +60,138 @@ describe("gitLabViewerPermissions", () => {
]);
});
});
describe("getChangeRequest base freshness", () => {
const detail = {
number: 7,
title: "Merge request 7",
url: "https://gitlab.com/acme/web/-/merge_requests/7",
author: null,
headBranch: "feat/page",
baseBranch: "main",
state: "open" as const,
isDraft: false,
mergeability: "mergeable" as const,
additions: 0,
deletions: 0,
createdAt: "2026-07-01T00:00:00Z",
updatedAt: "2026-07-02T00:00:00Z",
reviewRequestLogins: [],
labels: [],
body: "",
changedFiles: 1,
mergedAt: null,
closedAt: null,
reviewers: [],
checks: [],
viewerCanMerge: true,
reviewerIds: [],
};
const readWith = (divergence: { readonly divergedCommits?: number }) =>
Effect.gen(function* () {
const provider = yield* make;
return yield* provider.getChangeRequest({
cwd: "/w",
repository: "acme/web",
host: "gitlab.com",
number: 7,
});
}).pipe(
Effect.provide(
Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
getMergeRequestDetail: () => Effect.succeed({ ...detail, ...divergence }),
getProjectMergeCapabilities: () =>
Effect.succeed({ merge: true, squash: true, rebase: true }),
}),
),
);
it.effect("reads a counted divergence as a branch that has fallen behind", () =>
Effect.gen(function* () {
const changeRequest = yield* readWith({ divergedCommits: 3 });
expect(changeRequest.baseComparison).toBe("behind");
expect(changeRequest.behindBy).toBe(3);
}),
);
it.effect("reads a divergence of none as a branch that is current", () =>
Effect.gen(function* () {
const changeRequest = yield* readWith({ divergedCommits: 0 });
expect(changeRequest.baseComparison).toBe("up-to-date");
expect(changeRequest.behindBy).toBe(0);
}),
);
it.effect("says nothing at all where GitLab counted nothing", () =>
Effect.gen(function* () {
// An install too old to answer has to leave the page silent rather than let it claim the
// branch is current, which is the one wrong thing this banner could say.
const changeRequest = yield* readWith({});
expect(changeRequest.baseComparison).toBe("unknown");
expect(changeRequest.behindBy).toBeUndefined();
}),
);
});
describe("rewriting what has already been said", () => {
const updateMergeRequest = vi.fn(() => Effect.void);
const updateNote = vi.fn(() => Effect.void);
const providerWith = make.pipe(
Effect.provide(
Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({ updateMergeRequest, updateNote }),
),
);
it.effect("sends only the half of the merge request the reader rewrote", () =>
Effect.gen(function* () {
const provider = yield* providerWith;
assert.isDefined(provider.updateChangeRequest);
yield* provider.updateChangeRequest({
cwd: "/w",
repository: "acme/web",
host: "gitlab.com",
number: 7,
body: "What this changes.",
});
// GitLab calls it the description, and the title stays out of the request entirely.
expect(updateMergeRequest).toHaveBeenCalledWith({
cwd: "/w",
repository: "acme/web",
number: 7,
description: "What this changes.",
});
}),
);
it.effect("rewrites a positioned comment through the same note as any other", () =>
Effect.gen(function* () {
const provider = yield* providerWith;
assert.isDefined(provider.updateComment);
yield* provider.updateComment({
cwd: "/w",
repository: "acme/web",
host: "gitlab.com",
number: 7,
commentId: "42",
kind: "review-comment",
body: "Reworded.",
});
expect(updateNote).toHaveBeenCalledWith({
cwd: "/w",
repository: "acme/web",
number: 7,
noteId: "42",
body: "Reworded.",
});
}),
);
});
@@ -1,5 +1,9 @@
import * as Effect from "effect/Effect";
import type { PullRequestCapabilities, PullRequestViewerPermissions } from "@t3tools/contracts";
import type {
PullRequestCapabilities,
PullRequestReaction,
PullRequestViewerPermissions,
} from "@t3tools/contracts";
import * as GitLabPullRequestCli from "./GitLabPullRequestCli.ts";
import {
@@ -12,10 +16,24 @@ import {
const CAPABILITIES: PullRequestCapabilities = {
diff: true,
comment: true,
actions: ["merge", "ready", "draft", "close", "reopen"],
actions: [
"merge",
"ready",
"draft",
"close",
"reopen",
"update-branch",
"enable-auto-merge",
"disable-auto-merge",
],
// GitLab offers all three, though a project settles on one; `mergeCapabilities` narrows it.
mergeMethods: ["merge", "squash", "rebase"],
// Rebase alone: GitLab moves a stale branch onto its target by replaying it, and has nothing
// that merges the target back in the way GitHub's update button can. Declaring only what it
// does is what lets a request to merge the target in be refused instead of quietly rebasing.
updateMethods: ["rebase"],
search: true,
reactions: true,
review: {
inlineComment: true,
reply: true,
@@ -25,8 +43,21 @@ const CAPABILITIES: PullRequestCapabilities = {
verdicts: ["comment", "approve"],
},
reviewers: { request: true, listCandidates: true },
edit: { changeRequest: true, comment: true },
};
/**
* The actions `user.can_merge` answers for. Rebasing writes to the source branch rather than to
* the target, so it is not literally the same permission — but GitLab reports nothing narrower,
* and someone it will not let land this change has no business rewriting its branch either.
*/
const MERGE_ACTIONS: ReadonlySet<string> = new Set([
"merge",
"update-branch",
"enable-auto-merge",
"disable-auto-merge",
]);
/**
* What the signed-in account may do here. GitLab answers exactly one of these questions per
* viewer, on the merge request itself: `user.can_merge`, which is why merging is the only thing
@@ -45,11 +76,16 @@ export function gitLabViewerPermissions(input: {
readonly viewerCanMerge: boolean;
}): PullRequestViewerPermissions {
return {
actions: CAPABILITIES.actions.filter((action) => action !== "merge" || input.viewerCanMerge),
// Arming the merge and taking the arming back are the merge, deferred, so they answer to
// the same `can_merge` the merge itself does.
actions: CAPABILITIES.actions.filter(
(action) => !MERGE_ACTIONS.has(action) || input.viewerCanMerge,
),
comment: true,
resolve: true,
verdicts: CAPABILITIES.review.verdicts,
requestReviewers: true,
...(input.viewerCanMerge ? { updateMethods: CAPABILITIES.updateMethods } : {}),
};
}
@@ -114,6 +150,17 @@ export const make = Effect.gen(function* () {
...mergeRequest,
mergeCapabilities,
viewerPermissions: gitLabViewerPermissions(mergeRequest),
// A GitLab too old to count the divergence says nothing here rather than "up to
// date": the banner is worth missing, and a wrong all-clear is not worth showing.
baseComparison:
mergeRequest.divergedCommits === undefined
? "unknown"
: mergeRequest.divergedCommits > 0
? "behind"
: "up-to-date",
...(mergeRequest.divergedCommits === undefined
? {}
: { behindBy: mergeRequest.divergedCommits }),
}),
),
),
@@ -128,19 +175,37 @@ export const make = Effect.gen(function* () {
cli
.listDiscussions(input)
.pipe(Effect.orElseSucceed(() => ({ threads: [], truncated: true }))),
// The notes endpoint carries no award of any kind, so they are read alongside it. A
// failed read costs the conversation its reactions rather than its words.
cli.listReactions(input).pipe(
Effect.orElseSucceed(() => ({
reactions: [] as ReadonlyArray<PullRequestReaction>,
reactionsByNoteId: new Map<string, ReadonlyArray<PullRequestReaction>>(),
})),
),
],
{ concurrency: 3 },
{ concurrency: 4 },
).pipe(
Effect.mapError(fail("getChangeRequestActivity")),
Effect.map(
([notes, commits, discussions]): ProviderChangeRequestActivity => ({
comments: notes.comments,
([notes, commits, discussions, awards]): ProviderChangeRequestActivity => ({
reactions: awards.reactions,
comments: notes.comments.map((comment) => ({
...comment,
reactions: awards.reactionsByNoteId.get(comment.id) ?? [],
})),
// GitLab reports no count of its own, so the walk's own total is the host's: the
// notes endpoint carries every comment on the merge request, including the ones
// written under a discussion, and it is read until GitLab runs out.
commentCount: notes.comments.length,
commentsTruncated: notes.truncated || discussions.truncated,
reviewThreads: discussions.threads,
reviewThreads: discussions.threads.map((thread) => ({
...thread,
comments: thread.comments.map((comment) => ({
...comment,
reactions: awards.reactionsByNoteId.get(comment.id) ?? [],
})),
})),
commits,
}),
),
@@ -188,8 +253,32 @@ export const make = Effect.gen(function* () {
})
.pipe(Effect.mapError(fail("runAction"))),
updateChangeRequest: (input) =>
cli
.updateMergeRequest({
cwd: input.cwd,
repository: input.repository,
number: input.number,
...(input.title === undefined ? {} : { title: input.title }),
...(input.body === undefined ? {} : { description: input.body }),
})
.pipe(Effect.mapError(fail("updateChangeRequest"))),
comment: (input) => cli.commentOnMergeRequest(input).pipe(Effect.mapError(fail("comment"))),
// The kind is not read: every comment this provider hands out, positioned or not, carries a
// plain REST note id, and one endpoint rewrites both.
updateComment: (input) =>
cli
.updateNote({
cwd: input.cwd,
repository: input.repository,
number: input.number,
noteId: input.commentId,
body: input.body,
})
.pipe(Effect.mapError(fail("updateComment"))),
submitReview: (input) => cli.submitReview(input).pipe(Effect.mapError(fail("submitReview"))),
replyToThread: (input) =>
@@ -203,6 +292,18 @@ export const make = Effect.gen(function* () {
})
.pipe(Effect.mapError(fail("replyToThread"))),
setReaction: (input) =>
cli
.setReaction({
cwd: input.cwd,
repository: input.repository,
number: input.number,
...(input.subjectId === undefined ? {} : { noteId: input.subjectId }),
content: input.content,
reacted: input.reacted,
})
.pipe(Effect.mapError(fail("setReaction"))),
setThreadResolution: (input) =>
cli
.setDiscussionResolution({
@@ -3,22 +3,30 @@ import * as Schema from "effect/Schema";
import type {
PullRequestAction,
PullRequestActor,
PullRequestBaseComparison,
PullRequestCapabilities,
PullRequestChecksState,
PullRequestCheck,
PullRequestComment,
PullRequestCommit,
PullRequestInvolvement,
PullRequestLabel,
PullRequestListFilters,
PullRequestListState,
PullRequestMergeCapabilities,
PullRequestMergeMethod,
PullRequestMergeability,
PullRequestOmittedFileStat,
PullRequestReaction,
PullRequestReactionContent,
PullRequestReviewCommentDraft,
PullRequestReviewDecision,
PullRequestReviewThread,
PullRequestReviewVerdict,
PullRequestReviewerCandidateList,
PullRequestReviewerKind,
PullRequestState,
PullRequestUpdateMethod,
PullRequestViewerPermissions,
SourceControlProviderKind,
} from "@t3tools/contracts";
@@ -64,6 +72,10 @@ export interface ProviderChangeRequest {
/** Accounts with a review requested. Team-level requests are excluded by each provider. */
readonly reviewRequestLogins: ReadonlyArray<string>;
readonly labels: ReadonlyArray<PullRequestLabel>;
/** Absent from a host that does not summarise its reviews, which is every host but GitHub. */
readonly reviewDecision?: PullRequestReviewDecision | null | undefined;
/** Absent from a host that reports no check rollup on its listings. */
readonly checksState?: PullRequestChecksState | null | undefined;
}
export interface ProviderChangeRequestPage {
@@ -140,6 +152,11 @@ export interface ProviderChangeRequestDetail extends ProviderChangeRequest {
readonly checks: ReadonlyArray<PullRequestCheck>;
readonly mergeCapabilities: PullRequestMergeCapabilities;
readonly viewerPermissions: PullRequestViewerPermissions;
/** Absent from a host that cannot compare the branch with its base, which is most of them. */
readonly baseComparison?: PullRequestBaseComparison;
readonly behindBy?: number;
/** Absent from a host that does not report whether it is armed to merge this on its own. */
readonly autoMergeEnabled?: boolean;
}
/** The conversation-shaped half of a detail, loaded after the core can already render. */
@@ -158,6 +175,8 @@ export interface ProviderChangeRequestActivity {
readonly commentsTruncated: boolean;
readonly reviewThreads: ReadonlyArray<PullRequestReviewThread>;
readonly commits: ReadonlyArray<PullRequestCommit>;
/** The change request's own reactions, from a host that has them. */
readonly reactions?: ReadonlyArray<PullRequestReaction>;
}
export interface ProviderDiffSlice {
@@ -165,6 +184,8 @@ export interface ProviderDiffSlice {
/** Something in this slice could not be shown, as opposed to there being more slices. */
readonly truncated: boolean;
readonly nextCursor: string | null;
/** The host's own counts for the files whose hunks it withheld from this slice. */
readonly omittedFileStats?: ReadonlyArray<PullRequestOmittedFileStat>;
}
export interface ProviderDiffFileContents {
@@ -216,6 +237,12 @@ export interface PullRequestProviderApi {
* asks for the first slice, which is every listing that has not been continued.
*/
readonly cursor?: ProviderListCursor | undefined;
/**
* Further narrowings, which a host applies as far as it can and ignores the rest of —
* an unnarrowed page is a wider answer rather than a wrong one, and the caller narrows
* what it gets for the fields a row carries.
*/
readonly filters?: PullRequestListFilters | undefined;
},
) => Effect.Effect<ProviderChangeRequestPage, PullRequestProviderError>;
@@ -244,6 +271,7 @@ export interface PullRequestProviderApi {
readonly limit: number;
readonly query?: string | undefined;
readonly cursor?: ProviderListCursor | undefined;
readonly filters?: PullRequestListFilters | undefined;
}) => Effect.Effect<ProviderBatchedChangeRequestPage, PullRequestProviderError>;
/**
@@ -314,7 +342,23 @@ export interface PullRequestProviderApi {
input: ProviderRepositoryRef & {
readonly number: number;
readonly action: PullRequestAction;
/** Meaningful for `merge` and `enable-auto-merge`; absent takes the host's own default. */
readonly mergeMethod?: PullRequestMergeMethod;
/** Only meaningful for `update-branch`; absent takes the host's own default. */
readonly updateMethod?: PullRequestUpdateMethod;
},
) => Effect.Effect<void, PullRequestProviderError>;
/**
* Rewrites the change request's own words. Only called when `capabilities.edit.changeRequest`
* is true, and never with both fields absent — the caller refuses that before it gets here,
* because a host asked to change nothing answers differently on each of them.
*/
readonly updateChangeRequest?: (
input: ProviderRepositoryRef & {
readonly number: number;
readonly title?: string | undefined;
readonly body?: string | undefined;
},
) => Effect.Effect<void, PullRequestProviderError>;
@@ -322,6 +366,23 @@ export interface PullRequestProviderApi {
input: ProviderRepositoryRef & { readonly number: number; readonly body: string },
) => Effect.Effect<void, PullRequestProviderError>;
/**
* Rewrites a remark somebody already posted. Only called when `capabilities.edit.comment` is
* true, with an id exactly as the conversation carried it.
*
* Whether this remark is the reader's to rewrite is the host's own answer: no read here can
* settle it, since access can be taken away between the conversation being read and the
* rewrite being sent, and a host refuses a stranger's remark with a sentence saying so.
*/
readonly updateComment?: (
input: ProviderRepositoryRef & {
readonly number: number;
readonly commentId: string;
readonly kind: "issue-comment" | "review-comment";
readonly body: string;
},
) => Effect.Effect<void, PullRequestProviderError>;
/**
* Sends a whole review at once. Only called for a verdict the host declared in
* `capabilities.review.verdicts`, and with line comments only where it declared
@@ -376,6 +437,22 @@ export interface PullRequestProviderApi {
},
) => Effect.Effect<void, PullRequestProviderError>;
/**
* Adds a reaction, or takes it back. Only called when `capabilities.reactions` is true.
*
* `subjectId` is a remark's id as the conversation carried it; absent means the change request
* itself, whose reactions sit on its description. Whatever a host needs to address either of
* them is worked out here, because the id a conversation travels with is the one the reader has.
*/
readonly setReaction: (
input: ProviderRepositoryRef & {
readonly number: number;
readonly subjectId?: string | undefined;
readonly content: PullRequestReactionContent;
readonly reacted: boolean;
},
) => Effect.Effect<void, PullRequestProviderError>;
/** Only called when `capabilities.review.resolve` is true. */
readonly setThreadResolution: (
input: ProviderRepositoryRef & {
File diff suppressed because it is too large. Load diff
+323 -50
View File
@@ -10,11 +10,13 @@ import {
PullRequestUnavailableError,
pullRequestHostOf,
pullRequestProviderRequirement,
resolvePullRequestAuthorFilter,
type OrchestrationProjectShell,
type PullRequestAction,
type PullRequestActionInput,
type PullRequestActivity,
type PullRequestCommentInput,
type PullRequestCommentUpdateInput,
type PullRequestDetail,
type PullRequestDiffFileContentsInput,
type PullRequestDiffFileContentsResult,
@@ -23,12 +25,14 @@ import {
type PullRequestDiffResult,
type PullRequestInvalidateInput,
type PullRequestListEntry,
type PullRequestListFilters,
type PullRequestListInput,
type PullRequestListProjectError,
type PullRequestListResult,
type PullRequestListStatsInput,
type PullRequestListStatsResult,
type PullRequestProviderSummary,
type PullRequestReactionInput,
type PullRequestRef,
type PullRequestReviewVerdict,
type PullRequestReviewerCandidateList,
@@ -36,6 +40,7 @@ import {
type PullRequestSubmitReviewInput,
type PullRequestThreadReplyInput,
type PullRequestThreadResolutionInput,
type PullRequestUpdateInput,
type SourceControlProviderInfo,
type SourceControlProviderKind,
} from "@t3tools/contracts";
@@ -134,7 +139,11 @@ export class PullRequestService extends Context.Service<
input: PullRequestDiffFileContentsInput,
) => Effect.Effect<PullRequestDiffFileContentsResult, PullRequestError>;
readonly runAction: (input: PullRequestActionInput) => Effect.Effect<void, PullRequestError>;
readonly update: (input: PullRequestUpdateInput) => Effect.Effect<void, PullRequestError>;
readonly comment: (input: PullRequestCommentInput) => Effect.Effect<void, PullRequestError>;
readonly updateComment: (
input: PullRequestCommentUpdateInput,
) => Effect.Effect<void, PullRequestError>;
readonly submitReview: (
input: PullRequestSubmitReviewInput,
) => Effect.Effect<void, PullRequestError>;
@@ -144,6 +153,9 @@ export class PullRequestService extends Context.Service<
readonly setThreadResolution: (
input: PullRequestThreadResolutionInput,
) => Effect.Effect<void, PullRequestError>;
readonly setReaction: (
input: PullRequestReactionInput,
) => Effect.Effect<void, PullRequestError>;
readonly reviewerCandidates: (
input: PullRequestRef,
) => Effect.Effect<PullRequestReviewerCandidateList, PullRequestError>;
@@ -174,8 +186,14 @@ const ACTION_ACCESS_REFUSALS: Record<PullRequestAction, string> = {
"You need write access on this repository, or to have opened this change request, to return it to a draft.",
close:
"You need write access on this repository, or to have opened this change request, to close it.",
"update-branch":
"You need write access on this repository, or to have opened this change request, to update its branch.",
reopen:
"You need write access on this repository, or to have opened this change request, to reopen it.",
"enable-auto-merge":
"You need write access on this repository to have it merged for you once it is ready.",
"disable-auto-merge":
"You need write access on this repository to stop it being merged for you once it is ready.",
};
/**
@@ -349,13 +367,25 @@ function toPullRequestError(
}
/**
* The provider-native repository identity. `displayName` is the full path below the host, which
* is what nested GitLab groups and Azure project paths need; owner/name is the two-segment
* fallback for identities recorded before that field existed.
* The provider-native repository selector. `displayName` is the full path below the host, which
* is what nested GitLab groups need; owner/name is the two-segment fallback for identities
* recorded before that field existed.
*
* Azure DevOps is the exception: `az repos pr list --repository` takes a repository name, and
* takes the organisation and project from the checkout it detects — so the recorded
* `org/project/_git/repo` path is refused outright and the whole repository reads as
* unavailable. Its name is the last segment, which is what this hands over.
*
* One function because everything downstream is keyed by what it answers: the rows' own
* `repository`, the per-repository cursors, and the detail and diff reads a row leads to.
*/
function repositoryIdentityOf(project: OrchestrationProjectShell): string | null {
export function repositoryIdentityOf(project: OrchestrationProjectShell): string | null {
const identity = project.repositoryIdentity;
if (!identity) return null;
if (identity.provider === "azure-devops") {
const segments = (identity.displayName ?? "").split("/").filter((part) => part !== "_git");
return identity.name || segments.at(-1) || null;
}
if (identity.displayName) return identity.displayName;
return identity.owner && identity.name ? `${identity.owner}/${identity.name}` : null;
}
@@ -424,7 +454,7 @@ export const make = Effect.gen(function* () {
};
const listWorkspaceProjects = (
filter: Pick<PullRequestListInput, "projectId" | "host">,
filter: Pick<PullRequestListInput, "projectId" | "projectIds" | "host">,
): Effect.Effect<WorkspaceProjects, PullRequestError> =>
projections.getShellSnapshot().pipe(
Effect.mapError(
@@ -450,6 +480,7 @@ export const make = Effect.gen(function* () {
const seen = new Set<string>();
for (const project of snapshot.projects) {
if (filter.projectId !== undefined && project.id !== filter.projectId) continue;
if (filter.projectIds !== undefined && !filter.projectIds.includes(project.id)) continue;
const identity = project.repositoryIdentity;
let kind = identity?.provider as SourceControlProviderKind | undefined;
const repository = repositoryIdentityOf(project);
@@ -603,6 +634,43 @@ export const make = Effect.gen(function* () {
{ concurrency: REPOSITORY_CONCURRENCY },
);
/**
* The narrowings a row can be judged by from its own fields, applied here rather than trusted
* to the host. Only GitHub is asked to narrow a listing for itself; every other provider
* answers unnarrowed, and without this pass a draft filter or a label filter would be sent,
* accepted and quietly ignored. Idempotent for the hosts that did narrow.
*
* `checks` is absent because no listed row carries its check state: that one filter is the
* host's alone, and a row nobody narrowed stays rather than being guessed at.
*/
const matchesRowFilters = (
item: ProviderChangeRequest,
filters: PullRequestListFilters | undefined,
viewer: string,
): boolean => {
if (filters === undefined) return true;
const labels = item.labels.map((label) => label.name.trim().toLowerCase());
const holds = (label: string) => labels.includes(label.trim().toLowerCase());
return (
(filters.draft === undefined || item.isDraft === (filters.draft === "only")) &&
// Judged on the provider row rather than the entry, because the two absences mean
// different things and the entry keeps only one of them: `null` is a host that summarises
// its reviews saying there is no decision yet, which is what "none" asks for, while
// `undefined` is a host that does not summarise at all — an unjudgeable row, left alone
// the way an unreadable check state is.
(filters.review === undefined ||
item.reviewDecision === undefined ||
(filters.review === "none"
? item.reviewDecision === null
: item.reviewDecision === filters.review)) &&
(filters.labels === undefined || filters.labels.every((group) => group.some(holds))) &&
(filters.excludedLabels === undefined || !filters.excludedLabels.some(holds)) &&
(filters.author === undefined ||
item.author?.login.toLowerCase() ===
resolvePullRequestAuthorFilter(filters.author, viewer).toLowerCase())
);
};
const toEntry = (input: {
readonly project: SupportedProject;
readonly item: ProviderChangeRequest;
@@ -628,10 +696,16 @@ export const make = Effect.gen(function* () {
deletions: input.item.deletions,
createdAt: input.item.createdAt,
updatedAt: input.item.updatedAt,
...(input.item.checksState === undefined || input.item.checksState === null
? {}
: { checksState: input.item.checksState }),
viewerReviewRequested:
input.item.author?.login.toLowerCase() !== viewer &&
input.item.reviewRequestLogins.some((login) => login.toLowerCase() === viewer),
labels: input.item.labels,
...(input.item.reviewDecision === undefined || input.item.reviewDecision === null
? {}
: { reviewDecision: input.item.reviewDecision }),
};
};
@@ -755,6 +829,7 @@ export const make = Effect.gen(function* () {
// Each host matches this its own way, and one that cannot match text at all
// answers unnarrowed rather than failing.
query: input.query,
filters: input.filters,
// Only the two fields a host can act on: which rows have already been sent at the
// boundary instant is this service's business, not a provider's.
...(cursor === undefined
@@ -778,7 +853,9 @@ export const make = Effect.gen(function* () {
);
return {
key,
entries: items.map((item) => toEntry({ project, item, viewer })),
entries: items
.filter((item) => matchesRowFilters(item, input.filters, viewer))
.map((item) => toEntry({ project, item, viewer })),
errors: [],
truncated: page.truncated,
nextCursor:
@@ -836,6 +913,7 @@ export const make = Effect.gen(function* () {
viewer,
limit,
query: input.query,
filters: input.filters,
...(cursor === undefined
? {}
: { cursor: { updatedBefore: cursor.updatedBefore, delivered: cursor.delivered } }),
@@ -881,7 +959,9 @@ export const make = Effect.gen(function* () {
);
return Effect.succeed({
key: listCursorKey(project.host, project.repository),
entries: items.map((item) => toEntry({ project, item, viewer })),
entries: items
.filter((item) => matchesRowFilters(item, input.filters, viewer))
.map((item) => toEntry({ project, item, viewer })),
errors: [],
truncated: page.truncated,
nextCursor:
@@ -939,51 +1019,72 @@ export const make = Effect.gen(function* () {
};
});
/**
* Who this project's host says the reader is. Shared with the listing's own lookup — the same
* ten-minute answer per host — so a page that has already listed anything pays nothing for it,
* and a host that cannot say leaves it null rather than failing the read it decorates.
*/
const viewerOf = (project: SupportedProject): Effect.Effect<string | null> =>
resolveViewers([project], new Map()).pipe(Effect.map(([resolved]) => resolved?.viewer ?? null));
const detailUncached: PullRequestService["Service"]["detail"] = (input) =>
requireProject(input).pipe(
Effect.flatMap((project) =>
project.api
.getChangeRequest({
cwd: project.project.workspaceRoot,
repository: project.repository,
host: project.host,
number: input.number,
})
.pipe(
Effect.mapError(toPullRequestError("detail")),
Effect.map(
(changeRequest): PullRequestDetail => ({
provider: project.api.kind,
capabilities: project.api.capabilities,
projectId: project.project.id,
projectTitle: project.project.title,
workspaceRoot: project.project.workspaceRoot,
Effect.all(
[
project.api
.getChangeRequest({
cwd: project.project.workspaceRoot,
repository: project.repository,
number: changeRequest.number,
title: changeRequest.title,
body: changeRequest.body,
url: changeRequest.url,
author: changeRequest.author,
state: changeRequest.state,
isDraft: changeRequest.isDraft,
mergeability: changeRequest.mergeability,
additions: changeRequest.additions,
deletions: changeRequest.deletions,
changedFiles: changeRequest.changedFiles,
headBranch: changeRequest.headBranch,
baseBranch: changeRequest.baseBranch,
createdAt: changeRequest.createdAt,
updatedAt: changeRequest.updatedAt,
mergedAt: changeRequest.mergedAt,
closedAt: changeRequest.closedAt,
reviewers: changeRequest.reviewers,
labels: changeRequest.labels,
checks: changeRequest.checks,
mergeCapabilities: changeRequest.mergeCapabilities,
viewerPermissions: changeRequest.viewerPermissions,
}),
),
host: project.host,
number: input.number,
})
.pipe(Effect.mapError(toPullRequestError("detail"))),
viewerOf(project),
],
{ concurrency: 2 },
).pipe(
Effect.map(
([changeRequest, viewer]): PullRequestDetail => ({
provider: project.api.kind,
capabilities: project.api.capabilities,
projectId: project.project.id,
projectTitle: project.project.title,
workspaceRoot: project.project.workspaceRoot,
repository: project.repository,
number: changeRequest.number,
title: changeRequest.title,
body: changeRequest.body,
url: changeRequest.url,
author: changeRequest.author,
state: changeRequest.state,
isDraft: changeRequest.isDraft,
mergeability: changeRequest.mergeability,
additions: changeRequest.additions,
deletions: changeRequest.deletions,
changedFiles: changeRequest.changedFiles,
headBranch: changeRequest.headBranch,
baseBranch: changeRequest.baseBranch,
createdAt: changeRequest.createdAt,
updatedAt: changeRequest.updatedAt,
mergedAt: changeRequest.mergedAt,
closedAt: changeRequest.closedAt,
reviewers: changeRequest.reviewers,
labels: changeRequest.labels,
checks: changeRequest.checks,
mergeCapabilities: changeRequest.mergeCapabilities,
viewerPermissions: changeRequest.viewerPermissions,
...(viewer === null || viewer.trim().length === 0 ? {} : { viewer }),
...(changeRequest.baseComparison === undefined
? {}
: { baseComparison: changeRequest.baseComparison }),
...(changeRequest.behindBy === undefined ? {} : { behindBy: changeRequest.behindBy }),
...(changeRequest.autoMergeEnabled === undefined
? {}
: { autoMergeEnabled: changeRequest.autoMergeEnabled }),
}),
),
),
),
);
@@ -1008,6 +1109,7 @@ export const make = Effect.gen(function* () {
commentsTruncated: activity.commentsTruncated,
reviewThreads: activity.reviewThreads,
commits: activity.commits,
...(activity.reactions === undefined ? {} : { reactions: activity.reactions }),
}),
),
),
@@ -1088,6 +1190,19 @@ export const make = Effect.gen(function* () {
}),
);
}
// The same for the way a stale branch is brought up to date: a host that only merges
// must not be asked to rebase and left to pick something else.
if (
input.updateMethod !== undefined &&
!(project.api.capabilities.updateMethods ?? []).includes(input.updateMethod)
) {
return Effect.fail(
new PullRequestOperationError({
operation: "runAction",
detail: `This host cannot update a branch by ${input.updateMethod}.`,
}),
);
}
// What the host can do and what this account may ask of it are two questions, and both
// have to say yes. The second is asked last, because it costs a request and the checks
// above do not.
@@ -1101,6 +1216,17 @@ export const make = Effect.gen(function* () {
}),
);
}
if (
input.updateMethod !== undefined &&
!(viewer.updateMethods ?? []).includes(input.updateMethod)
) {
return Effect.fail(
new PullRequestOperationError({
operation: "runAction",
detail: ACTION_ACCESS_REFUSALS["update-branch"],
}),
);
}
return project.api
.runAction({
cwd: project.project.workspaceRoot,
@@ -1109,6 +1235,7 @@ export const make = Effect.gen(function* () {
number: input.number,
action: input.action,
...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
...(input.updateMethod === undefined ? {} : { updateMethod: input.updateMethod }),
})
.pipe(Effect.mapError(toPullRequestError("runAction")));
}),
@@ -1162,6 +1289,76 @@ export const make = Effect.gen(function* () {
}),
);
/**
* Rewriting the change request's own words, and rewriting a remark, are both left to the host to
* allow or refuse. Neither is a question a permission read answers: every host lets the person
* who wrote something rewrite it whatever access they have otherwise, and none of them reports
* that as a permission — so a check here could only guess, and a wrong guess takes the control
* away from the one person certain to be allowed.
*/
const update: PullRequestService["Service"]["update"] = (input) =>
requireProject(input).pipe(
Effect.flatMap((project): Effect.Effect<void, PullRequestError> => {
const rewrite = project.api.updateChangeRequest;
if (project.api.capabilities.edit?.changeRequest !== true || rewrite === undefined) {
return Effect.fail(
new PullRequestOperationError({
operation: "update",
detail: "This host cannot rewrite a change request.",
}),
);
}
if (input.title === undefined && input.body === undefined) {
return Effect.fail(
new PullRequestOperationError({
operation: "update",
detail: "Nothing was changed.",
}),
);
}
return rewrite({
cwd: project.project.workspaceRoot,
repository: project.repository,
host: project.host,
number: input.number,
...(input.title === undefined ? {} : { title: input.title }),
...(input.body === undefined ? {} : { body: input.body }),
}).pipe(Effect.mapError(toPullRequestError("update")));
}),
);
const updateComment: PullRequestService["Service"]["updateComment"] = (input) =>
(input.body.trim().length === 0
? Effect.fail(
new PullRequestOperationError({
operation: "updateComment",
detail: "A comment cannot be empty.",
}),
)
: requireProject(input)
).pipe(
Effect.flatMap((project): Effect.Effect<void, PullRequestError> => {
const rewrite = project.api.updateComment;
if (project.api.capabilities.edit?.comment !== true || rewrite === undefined) {
return Effect.fail(
new PullRequestOperationError({
operation: "updateComment",
detail: "This host cannot rewrite a comment.",
}),
);
}
return rewrite({
cwd: project.project.workspaceRoot,
repository: project.repository,
host: project.host,
number: input.number,
commentId: input.commentId,
kind: input.kind,
body: input.body,
}).pipe(Effect.mapError(toPullRequestError("updateComment")));
}),
);
const submitReview: PullRequestService["Service"]["submitReview"] = (input) =>
requireProject(input).pipe(
Effect.flatMap((project): Effect.Effect<void, PullRequestError> => {
@@ -1297,6 +1494,36 @@ export const make = Effect.gen(function* () {
}),
);
/**
* Reacting is gated on the host alone. Every host with reactions takes one from whoever can read
* the change request, so there is no access left to check that reading it has not already
* settled.
*/
const setReaction: PullRequestService["Service"]["setReaction"] = (input) =>
requireProject(input).pipe(
Effect.flatMap((project): Effect.Effect<void, PullRequestError> => {
if (project.api.capabilities.reactions !== true) {
return Effect.fail(
new PullRequestOperationError({
operation: "setReaction",
detail: "This host has no reactions.",
}),
);
}
return project.api
.setReaction({
cwd: project.project.workspaceRoot,
repository: project.repository,
host: project.host,
number: input.number,
...(input.subjectId === undefined ? {} : { subjectId: input.subjectId }),
content: input.content,
reacted: input.reacted,
})
.pipe(Effect.mapError(toPullRequestError("setReaction")));
}),
);
/**
* Who may be asked is only ever wanted by somebody about to ask, because the menu it fills is
* the one the request is made from. So the same permission guards both: a page that could open
@@ -1520,6 +1747,23 @@ export const make = Effect.gen(function* () {
refEpochs.set(scope, ++epochCounter);
};
/** The positional filter slot of a cache key, back as the record `listUncached` takes. */
const filtersOfKey = (
slots: ReadonlyArray<
string | ReadonlyArray<string> | ReadonlyArray<ReadonlyArray<string>> | null
>,
): PullRequestListFilters => {
const [draft, review, checks, author, labels, excludedLabels] = slots;
return {
...(typeof draft === "string" ? { draft: draft as "only" | "hide" } : {}),
...(typeof review === "string" ? { review: review as PullRequestListFilters["review"] } : {}),
...(typeof checks === "string" ? { checks: checks as PullRequestListFilters["checks"] } : {}),
...(typeof author === "string" ? { author } : {}),
...(Array.isArray(labels) ? { labels: labels as ReadonlyArray<ReadonlyArray<string>> } : {}),
...(Array.isArray(excludedLabels) ? { excludedLabels } : {}),
};
};
// Keys serialize positionally and parse back in the lookup, so the cache is the only holder
// of in-flight state: concurrent identical reads coalesce on the key into one host request.
// The continuation cursors are part of the key, entries sorted so one continuation is one
@@ -1528,13 +1772,24 @@ export const make = Effect.gen(function* () {
(key: string) => {
// The parse undoes this module's own serialization, so the shapes are known exactly;
// the cast restores the branded field types JSON cannot carry.
const [, state, involvement, projectId, host, limit, query, cursorEntries] = JSON.parse(
key,
) as [
const [
,
state,
involvement,
filters,
projectId,
projectIds,
host,
limit,
query,
cursorEntries,
] = JSON.parse(key) as [
number,
string,
string | null,
ReadonlyArray<string | ReadonlyArray<string> | null> | null,
string | null,
ReadonlyArray<string> | null,
string | null,
number | null,
string | null,
@@ -1543,7 +1798,9 @@ export const make = Effect.gen(function* () {
return listUncached({
state,
...(involvement === null ? {} : { involvement }),
...(filters === null ? {} : { filters: filtersOfKey(filters) }),
...(projectId === null ? {} : { projectId }),
...(projectIds === null ? {} : { projectIds }),
...(host === null ? {} : { host }),
...(limit === null ? {} : { limit }),
...(query === null ? {} : { query }),
@@ -1564,7 +1821,20 @@ export const make = Effect.gen(function* () {
listingsEpoch,
input.state,
input.involvement ?? null,
// Positional so two identical filter sets key alike however their record was assembled.
input.filters === undefined
? null
: [
input.filters.draft ?? null,
input.filters.review ?? null,
input.filters.checks ?? null,
input.filters.author ?? null,
input.filters.labels ?? null,
input.filters.excludedLabels ?? null,
],
input.projectId ?? null,
// Sorted so the same narrowing keys alike however the caller ordered it.
input.projectIds === undefined ? null : [...input.projectIds].sort(),
input.host ?? null,
input.limit ?? null,
input.query ?? null,
@@ -1726,10 +1996,13 @@ export const make = Effect.gen(function* () {
diff,
diffFileContents,
runAction: invalidatedByMutation(runAction),
update: invalidatedByMutation(update),
comment: invalidatedByMutation(comment),
updateComment: invalidatedByMutation(updateComment),
submitReview: invalidatedByMutation(submitReview),
replyToThread: invalidatedByMutation(replyToThread),
setThreadResolution: invalidatedByMutation(setThreadResolution),
setReaction: invalidatedByMutation(setReaction),
// The candidate list is deliberately read fresh per menu-open, so it stays uncached.
reviewerCandidates,
requestReviewers: invalidatedByMutation(requestReviewers),
@@ -144,6 +144,21 @@ describe("decodePullRequestJson", () => {
]);
});
it("reads auto-complete from whoever armed it, and its absence as nobody", () => {
const armed = expectSuccess(
decodePullRequestJson(
asJson(pullRequest({ autoCompleteSetBy: { displayName: "Bilal Hassan" } })),
),
);
expect(armed?.autoMergeEnabled).toBe(true);
// Azure leaves the field out entirely rather than sending it empty, so its absence is the
// whole of what it says about auto-complete being off.
expect(expectSuccess(decodePullRequestJson(asJson(pullRequest())))?.autoMergeEnabled).toBe(
false,
);
});
it("works out where the conversation lives from what Azure returned", () => {
const detail = expectSuccess(decodePullRequestJson(asJson(pullRequest())));
@@ -35,6 +35,12 @@ const RawPullRequestSchema = Schema.Struct({
description: Schema.optional(Schema.NullOr(Schema.String)),
status: Schema.optional(Schema.NullOr(Schema.String)),
isDraft: Schema.optional(Schema.NullOr(Schema.Boolean)),
/**
* Who armed auto-complete, which is the only thing Azure says about it: the field carries an
* identity while the pull request is set to complete on its own, and Azure leaves it out
* entirely once nobody has. So its presence is the answer, and there is no third state.
*/
autoCompleteSetBy: Schema.optional(Schema.NullOr(RawIdentitySchema)),
mergeStatus: Schema.optional(Schema.NullOr(Schema.String)),
createdBy: Schema.optional(Schema.NullOr(RawIdentitySchema)),
reviewers: Schema.optional(Schema.NullOr(Schema.Array(RawIdentitySchema))),
@@ -124,6 +130,8 @@ export interface AzureDevOpsPullRequest {
readonly reviewers: ReadonlyArray<PullRequestActor>;
/** Where this pull request's threads live, when Azure said enough to work it out. */
readonly threadsUrl: string | null;
/** Whether Azure is set to complete this on its own once its policies pass. */
readonly autoMergeEnabled: boolean;
}
function trimmed(value: string | null | undefined): string | null {
@@ -223,6 +231,7 @@ function toPullRequest(
reviewRequestLogins: reviewers.map((reviewer) => reviewer.login),
reviewers,
threadsUrl: toThreadsUrl(raw),
autoMergeEnabled: (raw.autoCompleteSetBy ?? null) !== null,
};
}
@@ -315,6 +315,22 @@ describe("decodeStatusesJson", () => {
expect(decoded.items[0]?.status).toBe(expected);
});
it("keeps two statuses that share a display name but have different keys", () => {
const decoded = expectSuccess(
decodeStatusesJson(
page([
{ key: "build", name: "Pipeline", state: "SUCCESSFUL" },
{ key: "deploy", name: "Pipeline", state: "FAILED" },
]),
),
);
expect(decoded.items.map((check) => [check.name, check.status])).toEqual([
["build / Pipeline", "success"],
["deploy / Pipeline", "failure"],
]);
});
});
describe("decodeDiffstatJson", () => {
@@ -18,6 +18,8 @@ import type {
import { TrimmedNonEmptyString } from "@t3tools/contracts";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
import { dedupeChecks } from "./pullRequestChecks.ts";
/**
* Bitbucket's enums are decoded as plain strings and normalized here, in the same tolerant
* style as the GitHub and GitLab decoders: a new pull request state or build status must not
@@ -547,21 +549,33 @@ export function decodeStatusesJson(
if (!Result.isSuccess(decoded)) {
return Result.fail(decoded.failure);
}
const checks: PullRequestCheck[] = [];
const checks: Array<{
readonly check: PullRequestCheck;
readonly workflowName: string | null;
readonly at: string | null;
}> = [];
for (const entry of decoded.success.values) {
const decodedStatus = decodeStatusEntry(entry);
if (Exit.isFailure(decodedStatus)) continue;
const status = decodedStatus.value;
const name = trimmed(status.name) ?? trimmed(status.key);
if (name === null) continue;
// Bitbucket re-uses a status key when a pipeline is run again, so the same check can appear
// twice on one page. Nothing decoded here says which copy is newer, so the later one wins,
// which is the order Bitbucket writes an update in. The key is kept as the workflow name so
// two different pipelines that display the same name are not folded into one.
checks.push({
name,
status: toBuildStatus(status.state),
description: trimmed(status.description),
url: trimmed(status.url),
check: {
name,
status: toBuildStatus(status.state),
description: trimmed(status.description),
url: trimmed(status.url),
},
workflowName: trimmed(status.key),
at: null,
});
}
return Result.succeed({ items: checks, next: trimmed(decoded.success.next) });
return Result.succeed({ items: dedupeChecks(checks), next: trimmed(decoded.success.next) });
}
export interface BitbucketDiffStat {
@@ -4,16 +4,20 @@ import { describe, expect, it } from "vite-plus/test";
import {
buildReviewSubmissionJson,
buildReviewerRequestJson,
decodeBaseComparisonJson,
decodePullRequestActivityJson,
decodePullRequestDetailJson,
decodePullRequestFilesJson,
decodePullRequestListJson,
decodePullRequestNodeIdJson,
decodePullRequestSearchJson,
decodeRepositoryAccessJson,
decodeReviewerCandidatesJson,
decodeReviewThreadCommentsJson,
decodeReviewThreadsJson,
decodeViewerPermissionsJson,
reviewThreadConversation,
REVIEW_THREADS_GRAPHQL_QUERY,
} from "./gitHubPullRequestJson.ts";
function listJson(entries: ReadonlyArray<Record<string, unknown>>): string {
@@ -67,6 +71,65 @@ describe("pull request list decoding", () => {
expect(entry?.reviewRequestLogins).toEqual(["octocat"]);
});
it("normalizes the review decision and reports nothing for one GitHub does not summarize", () => {
const batch = expectSuccess(
decodePullRequestListJson(
listJson([
{ reviewDecision: "APPROVED" },
{ reviewDecision: "CHANGES_REQUESTED" },
{ reviewDecision: "REVIEW_REQUIRED" },
{ reviewDecision: null },
]),
),
);
expect(batch.items.map((entry) => entry.reviewDecision)).toEqual([
"approved",
"changes-requested",
"review-required",
null,
]);
});
it("rolls the head commit's checks up to the one word a row has space for", () => {
const batch = expectSuccess(
decodePullRequestListJson(
listJson([
// A failure outranks a run still going, and a completed run has to be read through its
// conclusion rather than its status.
{
statusCheckRollup: [
{ name: "lint", status: "COMPLETED", conclusion: "SUCCESS" },
{ name: "build", status: "IN_PROGRESS" },
{ name: "test", status: "COMPLETED", conclusion: "FAILURE" },
],
},
{
statusCheckRollup: [
{ name: "lint", status: "COMPLETED", conclusion: "SUCCESS" },
{ name: "build", status: "QUEUED" },
],
},
{ statusCheckRollup: [{ name: "lint", status: "COMPLETED", conclusion: "SUCCESS" }] },
// A commit status reports one `state` and no `status` at all.
{ statusCheckRollup: [{ context: "ci/legacy", state: "ERROR" }] },
// Neither a pass, a failure nor a wait is no verdict rather than a green tick.
{ statusCheckRollup: [{ name: "lint", status: "COMPLETED", conclusion: "SKIPPED" }] },
{ statusCheckRollup: [] },
{},
]),
),
);
expect(batch.items.map((entry) => entry.checksState)).toEqual([
"failing",
"pending",
"passing",
"failing",
null,
null,
null,
]);
});
it("skips malformed entries but still counts them, so paging does not stop early", () => {
const raw = `[${listJson([{}]).slice(1, -1)},{"number":"not-a-number"}]`;
const batch = expectSuccess(decodePullRequestListJson(raw));
@@ -75,6 +138,49 @@ describe("pull request list decoding", () => {
});
});
describe("pull request search decoding", () => {
function searchJson(rollupStates: ReadonlyArray<string | null>): string {
return JSON.stringify({
data: {
search: {
pageInfo: { hasNextPage: false },
nodes: rollupStates.map((state, index) => ({
number: index + 1,
title: "Add the pull requests page",
url: "https://github.com/pingdotgg/t3code/pull/1",
headRefName: "feat/page",
baseRefName: "main",
createdAt: "2026-07-01T00:00:00Z",
updatedAt: "2026-07-02T00:00:00Z",
repository: { nameWithOwner: "pingdotgg/t3code" },
commits: {
nodes: [{ commit: { statusCheckRollup: state === null ? null : { state } } }],
},
})),
},
},
});
}
it("maps the rollup enum the search answers with onto the same three words", () => {
// The search asks GitHub for the verdict rather than the checks behind it, so this path sees
// one enum where the listing sees an array.
const batch = expectSuccess(
decodePullRequestSearchJson(
searchJson(["SUCCESS", "FAILURE", "ERROR", "PENDING", "EXPECTED", null]),
),
);
expect(batch.items.map((entry) => entry.checksState)).toEqual([
"passing",
"failing",
"failing",
"pending",
"pending",
null,
]);
});
});
describe("pull request detail decoding", () => {
const detailJson = JSON.stringify({
number: 7,
@@ -117,6 +223,58 @@ describe("pull request detail decoding", () => {
]);
});
it("reads an auto-merge request as armed, its null as off and its absence as neither", () => {
const raw = JSON.parse(detailJson) as Record<string, unknown>;
const armed = (entry: Record<string, unknown>) =>
expectSuccess(decodePullRequestDetailJson(JSON.stringify({ ...raw, ...entry })))
.autoMergeEnabled;
expect(
armed({ autoMergeRequest: { enabledBy: { login: "octocat" }, mergeMethod: "SQUASH" } }),
).toBe(true);
expect(armed({ autoMergeRequest: null })).toBe(false);
// `gh` not answering for the field at all is not GitHub saying the merge is unarmed.
expect(armed({})).toBeUndefined();
});
it("shows a re-running check once, as the run that is happening now", () => {
// What `statusCheckRollup` reports while a workflow is being re-run: the same check twice,
// the finished run and the one that replaced it, with no id to tell them apart.
const raw = JSON.parse(detailJson) as Record<string, unknown>;
const detail = expectSuccess(
decodePullRequestDetailJson(
JSON.stringify({
...raw,
statusCheckRollup: [
{
__typename: "CheckRun",
name: "Prepare PR size config",
workflowName: "PR Size",
status: "COMPLETED",
conclusion: "SUCCESS",
startedAt: "2026-08-11T16:06:20Z",
completedAt: "2026-08-11T16:06:25Z",
},
{
__typename: "CheckRun",
name: "Prepare PR size config",
workflowName: "PR Size",
status: "IN_PROGRESS",
conclusion: "",
startedAt: "2026-08-11T17:01:04Z",
completedAt: "0001-01-01T00:00:00Z",
},
],
}),
),
);
expect(detail.checks.map((check) => [check.name, check.status])).toEqual([
["Prepare PR size config", "pending"],
]);
expect(detail.checksState).toBe("pending");
});
it("merges reviews with comments in time order and keeps a bodyless approval", () => {
const detail = expectSuccess(decodePullRequestActivityJson(detailJson));
// r2 approved without writing anything, which is still the event worth seeing.
@@ -461,6 +619,89 @@ describe("review thread decoding", () => {
});
});
describe("reaction decoding", () => {
const commentWithGroups = (reactionGroups: ReadonlyArray<Record<string, unknown>>) =>
JSON.stringify({
data: {
node: {
comments: {
pageInfo: { hasNextPage: false, endCursor: null },
nodes: [{ id: "t1", body: "nice", createdAt: "2026-07-01T00:00:00Z", reactionGroups }],
},
},
},
});
it("keeps a named group, widens a group whose reactors were cut short, drops an unknown content and an empty group", () => {
const decoded = expectSuccess(
decodeReviewThreadCommentsJson(
commentWithGroups([
{
content: "THUMBS_UP",
viewerHasReacted: true,
reactors: { totalCount: 2, nodes: [{ login: "julius" }, { login: "bilal" }] },
},
// Not one of the eight the contract carries.
{
content: "PARTY_PARROT",
reactors: { totalCount: 1, nodes: [{ login: "hubot" }] },
},
// Nobody behind it, which GitHub still answers a group for.
{ content: "HEART", reactors: { totalCount: 0, nodes: [] } },
// More reactors than the bounded read named, and no `viewerHasReacted` at all.
{
content: "ROCKET",
reactors: { totalCount: 140, nodes: [{ login: "a" }, { login: "b" }, { login: "c" }] },
},
]),
),
);
expect(decoded.comments[0]?.reactions).toEqual([
{ content: "thumbs-up", count: 2, actors: ["julius", "bilal"], viewerHasReacted: true },
{ content: "rocket", count: 140, actors: ["a", "b", "c"], viewerHasReacted: false },
]);
});
it("leaves the viewer's own login out of actors, matched case-insensitively, while count still counts them", () => {
const decoded = expectSuccess(
decodeReviewThreadCommentsJson(
JSON.stringify({
data: {
viewer: { login: "Bilal" },
node: {
comments: {
pageInfo: { hasNextPage: false, endCursor: null },
nodes: [
{
id: "t1",
body: "nice",
createdAt: "2026-07-01T00:00:00Z",
reactionGroups: [
{
content: "HEART",
viewerHasReacted: true,
reactors: {
totalCount: 2,
nodes: [{ login: "bilal" }, { login: "julius" }],
},
},
],
},
],
},
},
},
}),
),
);
expect(decoded.comments[0]?.reactions).toEqual([
{ content: "heart", count: 2, actors: ["julius"], viewerHasReacted: true },
]);
});
});
describe("repository access decoding", () => {
const repositoryJson = (viewerPermission?: string | null) =>
JSON.stringify({
@@ -618,6 +859,7 @@ describe("review thread decoding", () => {
body: "first",
createdAt: "2026-07-01T00:00:00Z",
url: "https://github.com/acme/web/pull/1#discussion_rc1",
reactions: [],
},
{
id: "c2",
@@ -625,6 +867,7 @@ describe("review thread decoding", () => {
body: "second",
createdAt: "2026-07-01T00:00:00Z",
url: "https://github.com/acme/web/pull/1#discussion_rc2",
reactions: [],
},
],
},
@@ -676,6 +919,101 @@ describe("review thread decoding", () => {
expect(reviewThreadConversation(threads).map((comment) => comment.id)).toEqual(["c4"]);
expect(threads).toHaveLength(1);
});
it("puts an issue comment's and a review's reactions in reactionsById, and the pull request's own in reactions", () => {
const result = expectSuccess(
decodeReviewThreadsJson(
threadsJson([], {
reactionGroups: [
{
content: "HEART",
viewerHasReacted: true,
reactors: { totalCount: 1, nodes: [{ login: "bilal" }] },
},
],
comments: {
nodes: [
{
id: "c1",
reactionGroups: [
{
content: "THUMBS_UP",
reactors: { totalCount: 1, nodes: [{ login: "julius" }] },
},
],
},
],
},
reviews: {
nodes: [
{
id: "r1",
reactionGroups: [
{ content: "EYES", reactors: { totalCount: 1, nodes: [{ login: "hubot" }] } },
],
},
],
},
}),
),
);
expect(result.reactions).toEqual([
{ content: "heart", count: 1, actors: ["bilal"], viewerHasReacted: true },
]);
expect([...result.reactionsById]).toEqual([
["c1", [{ content: "thumbs-up", count: 1, actors: ["julius"], viewerHasReacted: false }]],
["r1", [{ content: "eyes", count: 1, actors: ["hubot"], viewerHasReacted: false }]],
]);
});
it("leaves the viewer's own login out of the pull request's own reactions, matched case-insensitively, while count still counts them", () => {
const result = expectSuccess(
decodeReviewThreadsJson(
JSON.stringify({
data: {
viewer: { login: "Bilal" },
repository: {
pullRequest: {
reviewThreads: { totalCount: 0, nodes: [] },
reactionGroups: [
{
content: "HEART",
viewerHasReacted: true,
reactors: { totalCount: 2, nodes: [{ login: "bilal" }, { login: "julius" }] },
},
],
},
},
},
}),
),
);
expect(result.reactions).toEqual([
{ content: "heart", count: 2, actors: ["julius"], viewerHasReacted: true },
]);
});
});
describe("decodePullRequestNodeIdJson", () => {
it("reads the pull request's own node id, which a reaction on its description is addressed by", () => {
expect(
expectSuccess(
decodePullRequestNodeIdJson(
JSON.stringify({ data: { repository: { pullRequest: { id: "PR_kwDOA" } } } }),
),
),
).toBe("PR_kwDOA");
});
});
describe("REVIEW_THREADS_GRAPHQL_QUERY", () => {
it("asks for reactionGroups on the pull request itself, its comments, its reviews and each thread's comments", () => {
expect(REVIEW_THREADS_GRAPHQL_QUERY.match(/reactionGroups/g)).toHaveLength(4);
// The reviews connection is new: only reactions were ever wanted off it.
expect(REVIEW_THREADS_GRAPHQL_QUERY).toContain("reviews(first:");
});
});
describe("reviewer candidate decoding", () => {
@@ -957,3 +1295,45 @@ describe("decodePullRequestFilesJson", () => {
expect(result.truncated).toBe(false);
});
});
describe("how far a branch trails its base", () => {
const comparison = (pullRequest: unknown) =>
JSON.stringify({ data: { repository: { pullRequest } } });
it("reads the commit count and whether this viewer may move the branch", () => {
const decoded = expectSuccess(
decodeBaseComparisonJson(
comparison({ viewerCanUpdateBranch: true, baseRef: { compare: { behindBy: 12 } } }),
),
);
expect(decoded).toEqual({ behindBy: 12, viewerCanUpdate: true });
});
it("reads a current branch as nothing to do", () => {
expect(
expectSuccess(
decodeBaseComparisonJson(
comparison({ viewerCanUpdateBranch: false, baseRef: { compare: { behindBy: 0 } } }),
),
),
).toEqual({ behindBy: 0, viewerCanUpdate: false });
});
it("answers unknown where the head could not be compared", () => {
// A pull request from a fork whose repository is gone, which GitHub answers with a null
// comparison beside a perfectly good pull request.
expect(
expectSuccess(
decodeBaseComparisonJson(comparison({ viewerCanUpdateBranch: true, baseRef: null })),
).behindBy,
).toBeNull();
expect(expectSuccess(decodeBaseComparisonJson(comparison(null)))).toEqual({
behindBy: null,
viewerCanUpdate: false,
});
});
it("refuses a body that is not the answer to this question", () => {
expect(Result.isSuccess(decodeBaseComparisonJson("{"))).toBe(false);
});
});
File diff suppressed because it is too large. Load diff
@@ -2,12 +2,15 @@ import * as Result from "effect/Result";
import { describe, expect, it } from "vite-plus/test";
import {
decodeAwardEmojiJson,
decodeCommitsJson,
decodeMergeRequestDetailJson,
decodeMergeRequestDiffsJson,
decodeMergeRequestListJson,
decodeNotesJson,
decodeOwnAwardIdJson,
decodeViewerJson,
gitLabAwardName,
} from "./gitLabMergeRequestJson.ts";
function listJson(entries: ReadonlyArray<Record<string, unknown>>): string {
@@ -177,6 +180,31 @@ describe("decodeMergeRequestDetailJson", () => {
expect(detail.changedFiles).toBe(0);
});
it("reads either auto-merge field, and says nothing where GitLab named neither", () => {
const armed = (entry: Record<string, unknown>) =>
expectSuccess(decodeMergeRequestDetailJson(detailJson(entry))).autoMergeEnabled;
expect(armed({ merge_when_pipeline_succeeds: true })).toBe(true);
// The newer name for the same fact, which older GitLab installs do not send.
expect(armed({ auto_merge_enabled: true })).toBe(true);
expect(armed({ merge_when_pipeline_succeeds: false })).toBe(false);
// Absent is GitLab not saying, which the page must not read as "not armed".
expect(armed({})).toBeUndefined();
});
it("keeps a divergence GitLab did not count apart from a divergence of none", () => {
const behind = (entry: Record<string, unknown>) =>
expectSuccess(decodeMergeRequestDetailJson(detailJson(entry))).divergedCommits;
expect(behind({ diverged_commits_count: 3 })).toBe(3);
// Counted and found level, which is the one answer that entitles the page to say so.
expect(behind({ diverged_commits_count: 0 })).toBe(0);
// An install that does not answer, and a null where the answer would have gone, are both
// silence: reading either as zero would tell a stale branch it is current.
expect(behind({})).toBeUndefined();
expect(behind({ diverged_commits_count: null })).toBeUndefined();
});
it("maps a pipeline waiting on a person to neutral, not failure", () => {
const detail = expectSuccess(
decodeMergeRequestDetailJson(detailJson({ head_pipeline: { status: "manual" } })),
@@ -453,3 +481,130 @@ describe("merge request viewer fields", () => {
).toBe(true);
});
});
describe("decodeAwardEmojiJson", () => {
it("reads MR-level awards, keys per-note awards by the REST id inside their gid, and ignores an award outside the eight", () => {
const result = expectSuccess(
decodeAwardEmojiJson(
JSON.stringify({
data: {
currentUser: { username: "bilal" },
project: {
mergeRequest: {
awardEmoji: {
nodes: [
{ name: "thumbsup", user: { username: "bilal" } },
{ name: "thumbsup", user: { username: "julius" } },
],
},
notes: {
pageInfo: { hasNextPage: false, endCursor: null },
nodes: [
{
id: "gid://gitlab/DiffNote/42",
awardEmoji: { nodes: [{ name: "heart", user: { username: "julius" } }] },
},
{
id: "gid://gitlab/Note/7",
// Not one of the eight the contract carries.
awardEmoji: {
nodes: [{ name: "partyparrot", user: { username: "bilal" } }],
},
},
],
},
},
},
},
}),
),
);
// `bilal` is `currentUser`, so the group they are in reads back as reacted, but their own
// username is left out of `actors` — the page names them "You" instead — while `count` still
// counts them; `julius` alone does not turn a group's own `viewerHasReacted` on.
expect(result.reactions).toEqual([
{ content: "thumbs-up", count: 2, actors: ["julius"], viewerHasReacted: true },
]);
// Note 7's only award named nobody the eight recognise, so it carries no reactions and is
// left out of the map rather than kept empty.
expect([...result.reactionsByNoteId]).toEqual([
["42", [{ content: "heart", count: 1, actors: ["julius"], viewerHasReacted: false }]],
]);
expect(result.nextCursor).toBeNull();
});
it("hands back a cursor when GitLab has more notes to page", () => {
const result = expectSuccess(
decodeAwardEmojiJson(
JSON.stringify({
data: {
currentUser: null,
project: {
mergeRequest: {
awardEmoji: { nodes: [] },
notes: { pageInfo: { hasNextPage: true, endCursor: "Y3Vyc29yOjE" }, nodes: [] },
},
},
},
}),
),
);
expect(result.nextCursor).toBe("Y3Vyc29yOjE");
});
it("matches the viewer's username case-insensitively, since GitLab is not consistent about case", () => {
const result = expectSuccess(
decodeAwardEmojiJson(
JSON.stringify({
data: {
currentUser: { username: "Bilal" },
project: {
mergeRequest: {
awardEmoji: {
nodes: [
{ name: "heart", user: { username: "bilal" } },
{ name: "heart", user: { username: "julius" } },
],
},
notes: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [] },
},
},
},
}),
),
);
expect(result.reactions).toEqual([
{ content: "heart", count: 2, actors: ["julius"], viewerHasReacted: true },
]);
});
});
describe("decodeOwnAwardIdJson", () => {
const awards = JSON.stringify([
{ id: 101, name: "thumbsup", user: { username: "julius" } },
{ id: 102, name: "thumbsup", user: { username: "bilal" } },
]);
it("finds the reader's own award of that name, which is the one a removal deletes", () => {
expect(
expectSuccess(decodeOwnAwardIdJson(awards, { content: "thumbs-up", viewer: "bilal" })),
).toBe(102);
});
it("returns nothing where the reader has no award of that name", () => {
expect(
expectSuccess(decodeOwnAwardIdJson(awards, { content: "heart", viewer: "bilal" })),
).toBeNull();
});
});
describe("gitLabAwardName", () => {
it("spells the contents whose GitLab award name is not their own kebab-case", () => {
expect(gitLabAwardName("thumbs-up")).toBe("thumbsup");
expect(gitLabAwardName("laugh")).toBe("laughing");
expect(gitLabAwardName("hooray")).toBe("tada");
});
});
@@ -11,6 +11,8 @@ import type {
PullRequestLabel,
PullRequestMergeability,
PullRequestMergeCapabilities,
PullRequestReaction,
PullRequestReactionContent,
PullRequestReviewThread,
PullRequestReviewerCandidate,
PullRequestState,
@@ -70,6 +72,21 @@ const RawMergeRequestSchema = Schema.Struct({
user: Schema.optional(
Schema.NullOr(Schema.Struct({ can_merge: Schema.optional(Schema.Boolean) })),
),
/**
* Whether GitLab is holding this merge request to merge it once its pipeline goes green.
* `merge_when_pipeline_succeeds` is the field every version answers with; newer ones also
* carry `auto_merge_enabled`, which is the same fact under the name GitLab settled on, so
* either one saying yes is a yes.
*/
merge_when_pipeline_succeeds: Schema.optional(Schema.NullOr(Schema.Boolean)),
auto_merge_enabled: Schema.optional(Schema.NullOr(Schema.Boolean)),
/**
* How far the target branch has moved on since this one left it, which is the same number
* GitLab's own "out of date" wording counts. It costs a walk of the two branches, so GitLab
* withholds it unless `include_diverged_commits_count` asks for it, and answers it only for a
* single merge request — a list never carries it, however it is asked for.
*/
diverged_commits_count: Schema.optional(Schema.NullOr(Schema.Int)),
});
const RawNoteSchema = Schema.Struct({
@@ -209,6 +226,13 @@ export interface GitLabMergeRequestDetail extends GitLabMergeRequestListItem {
readonly viewerCanMerge: boolean;
/** The reviewers as GitLab addresses them, which is what writing the set back takes. */
readonly reviewerIds: ReadonlyArray<number>;
/** Absent where GitLab named neither auto-merge field, which is not the same as off. */
readonly autoMergeEnabled?: boolean;
/**
* Absent where GitLab did not count, which is not the same as a branch that has nothing behind
* it: an install too old to answer must not be read as saying the branch is current.
*/
readonly divergedCommits?: number;
}
function trimmed(value: string | null | undefined): string | null {
@@ -334,6 +358,10 @@ function toListItem(
function toDetail(raw: Schema.Schema.Type<typeof RawMergeRequestSchema>): GitLabMergeRequestDetail {
const listItem = toListItem(raw);
const autoMerge =
raw.merge_when_pipeline_succeeds == null && raw.auto_merge_enabled == null
? undefined
: raw.merge_when_pipeline_succeeds === true || raw.auto_merge_enabled === true;
return {
...listItem,
body: raw.description ?? "",
@@ -350,6 +378,8 @@ function toDetail(raw: Schema.Schema.Type<typeof RawMergeRequestSchema>): GitLab
reviewerIds: (raw.reviewers ?? []).flatMap((reviewer) =>
reviewer.id === undefined ? [] : [reviewer.id],
),
...(autoMerge === undefined ? {} : { autoMergeEnabled: autoMerge }),
...(raw.diverged_commits_count == null ? {} : { divergedCommits: raw.diverged_commits_count }),
};
}
@@ -696,3 +726,215 @@ export function decodeMergeRequestDiffsJson(
rawCount: decoded.success.length,
});
}
/** GitLab's award names for the eight reactions the contract carries. */
const GITLAB_AWARD_BY_CONTENT: Readonly<Record<PullRequestReactionContent, string>> = {
"thumbs-up": "thumbsup",
"thumbs-down": "thumbsdown",
laugh: "laughing",
hooray: "tada",
confused: "confused",
heart: "heart",
rocket: "rocket",
eyes: "eyes",
};
const CONTENT_BY_GITLAB_AWARD: Readonly<Record<string, PullRequestReactionContent>> =
Object.fromEntries(
Object.entries(GITLAB_AWARD_BY_CONTENT).map(([content, name]) => [name, content]),
) as Readonly<Record<string, PullRequestReactionContent>>;
export function gitLabAwardName(content: PullRequestReactionContent): string {
return GITLAB_AWARD_BY_CONTENT[content];
}
/**
* Awards on the merge request and on every note of it, in one read. The REST notes endpoint the
* conversation comes from carries no award at all, and asking per note would be a request each.
*
* `currentUser` rides along because GitLab names who awarded but never says whether that is the
* reader — so the comparison is made here rather than paid for with a request of its own.
*/
export const AWARD_EMOJI_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!, $cursor: String) {
currentUser { username }
project(fullPath: $fullPath) {
mergeRequest(iid: $iid) {
awardEmoji { nodes { name user { username } } }
notes(first: 100, after: $cursor) {
pageInfo { hasNextPage endCursor }
nodes { id awardEmoji { nodes { name user { username } } } }
}
}
}
}`;
const RawAwardEmojiNodesSchema = Schema.optional(
Schema.NullOr(
Schema.Struct({
nodes: Schema.optional(
Schema.NullOr(
Schema.Array(
Schema.NullOr(
Schema.Struct({
name: Schema.optional(Schema.NullOr(Schema.String)),
user: Schema.optional(
Schema.NullOr(
Schema.Struct({ username: Schema.optional(Schema.NullOr(Schema.String)) }),
),
),
}),
),
),
),
),
}),
),
);
const RawAwardEmojiPageSchema = Schema.Struct({
data: Schema.Struct({
currentUser: Schema.optional(
Schema.NullOr(Schema.Struct({ username: Schema.optional(Schema.NullOr(Schema.String)) })),
),
project: Schema.NullOr(
Schema.Struct({
mergeRequest: Schema.NullOr(
Schema.Struct({
awardEmoji: RawAwardEmojiNodesSchema,
notes: Schema.optional(
Schema.NullOr(
Schema.Struct({
pageInfo: Schema.optional(
Schema.Struct({
hasNextPage: Schema.optional(Schema.Boolean),
endCursor: Schema.optional(Schema.NullOr(Schema.String)),
}),
),
nodes: Schema.Array(
Schema.NullOr(
Schema.Struct({
id: Schema.optional(Schema.NullOr(Schema.String)),
awardEmoji: RawAwardEmojiNodesSchema,
}),
),
),
}),
),
),
}),
),
}),
),
}),
});
const decodeAwardEmojiPage = decodeJsonResult(RawAwardEmojiPageSchema);
/**
* The awards on one subject, grouped the way a reaction pill is drawn. The viewer's own username
* is left out of `actors` — the page names them "You" instead, and leaving it in would name them
* twice — but `count` still counts them along with everyone else.
*/
function toReactions(
nodes: Schema.Schema.Type<typeof RawAwardEmojiNodesSchema>,
viewer: string | null,
): ReadonlyArray<PullRequestReaction> {
const normalizedViewer = viewer?.toLowerCase() ?? null;
const groups = new Map<
PullRequestReactionContent,
{ count: number; actors: string[]; viewer: boolean }
>();
for (const node of nodes?.nodes ?? []) {
// An award outside the eight is left out rather than shown under a name the picker has no
// way to take back: GitLab accepts any emoji, and the other hosts accept none of them.
const content = CONTENT_BY_GITLAB_AWARD[trimmed(node?.name)?.toLowerCase() ?? ""];
if (content === undefined) continue;
const username = trimmed(node?.user?.username);
if (username === null) continue;
const group = groups.get(content) ?? { count: 0, actors: [], viewer: false };
group.count++;
if (normalizedViewer !== null && username.toLowerCase() === normalizedViewer) {
group.viewer = true;
} else {
group.actors.push(username);
}
groups.set(content, group);
}
return [...groups].flatMap(([content, group]) =>
group.count === 0
? []
: [{ content, count: group.count, actors: group.actors, viewerHasReacted: group.viewer }],
);
}
/** `gid://gitlab/DiffNote/42` is note 42, which is the id the REST conversation carries. */
function noteIdOf(gid: string | null | undefined): string | null {
const id = trimmed(gid)?.split("/").at(-1);
return id !== undefined && /^\d+$/.test(id) ? id : null;
}
export interface GitLabAwardEmojiPage {
/** The merge request's own awards, which are the ones on its description. */
readonly reactions: ReadonlyArray<PullRequestReaction>;
readonly reactionsByNoteId: ReadonlyMap<string, ReadonlyArray<PullRequestReaction>>;
readonly nextCursor: string | null;
}
export function decodeAwardEmojiJson(
raw: string,
): Result.Result<GitLabAwardEmojiPage, DecodeFailure> {
const decoded = decodeAwardEmojiPage(raw);
if (!Result.isSuccess(decoded)) {
return Result.fail(decoded.failure);
}
const data = decoded.success.data;
const viewer = trimmed(data.currentUser?.username);
const mergeRequest = data.project?.mergeRequest;
const reactionsByNoteId = new Map<string, ReadonlyArray<PullRequestReaction>>();
for (const node of mergeRequest?.notes?.nodes ?? []) {
const id = noteIdOf(node?.id);
if (id === null) continue;
const reactions = toReactions(node?.awardEmoji, viewer);
if (reactions.length > 0) reactionsByNoteId.set(id, reactions);
}
const pageInfo = mergeRequest?.notes?.pageInfo;
return Result.succeed({
reactions: toReactions(mergeRequest?.awardEmoji, viewer),
reactionsByNoteId,
nextCursor: pageInfo?.hasNextPage === true ? (trimmed(pageInfo.endCursor) ?? null) : null,
});
}
const RawAwardSchema = Schema.Struct({
id: Schema.Int,
name: Schema.optional(Schema.NullOr(Schema.String)),
user: Schema.optional(
Schema.NullOr(Schema.Struct({ username: Schema.optional(Schema.NullOr(Schema.String)) })),
),
});
const decodeAward = Schema.decodeUnknownExit(RawAwardSchema);
/**
* The reader's own award of one name on a subject, which is what taking a reaction back is
* addressed by: GitLab deletes an award by its id and has no way to name one by its emoji.
*/
export function decodeOwnAwardIdJson(
raw: string,
input: { readonly content: PullRequestReactionContent; readonly viewer: string },
): Result.Result<number | null, DecodeFailure> {
const decoded = decodeUnknownList(raw);
if (!Result.isSuccess(decoded)) {
return Result.fail(decoded.failure);
}
const name = gitLabAwardName(input.content);
for (const entry of decoded.success) {
const award = decodeAward(entry);
if (Exit.isFailure(award)) continue;
const value = award.value;
if (trimmed(value.name)?.toLowerCase() !== name) continue;
if (trimmed(value.user?.username) !== input.viewer) continue;
return Result.succeed(value.id);
}
return Result.succeed(null);
}
@@ -0,0 +1,93 @@
import type { PullRequestCheck, PullRequestCheckStatus } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { dedupeChecks } from "./pullRequestChecks.ts";
function entry(
name: string,
status: PullRequestCheckStatus,
extra: { readonly workflowName?: string | null; readonly at?: string | null } = {},
): {
readonly check: PullRequestCheck;
readonly workflowName: string | null;
readonly at: string | null;
} {
return {
check: { name, status, description: null, url: null },
workflowName: extra.workflowName ?? null,
at: extra.at ?? null,
};
}
describe("dedupeChecks", () => {
it("keeps the newest run of a check the host listed twice", () => {
const checks = dedupeChecks([
entry("Prepare PR size config", "success", {
workflowName: "PR Size",
at: "2026-08-11T16:06:25Z",
}),
entry("Prepare PR size config", "pending", {
workflowName: "PR Size",
at: "2026-08-11T17:01:04Z",
}),
]);
expect(checks.map((check) => [check.name, check.status])).toEqual([
["Prepare PR size config", "pending"],
]);
});
it("holds a check at the place it first appeared, so a re-run does not reshuffle the list", () => {
const checks = dedupeChecks([
entry("lint", "success", { workflowName: "CI", at: "2026-08-11T16:00:00Z" }),
entry("test", "success", { workflowName: "CI", at: "2026-08-11T16:00:00Z" }),
entry("lint", "failure", { workflowName: "CI", at: "2026-08-11T18:00:00Z" }),
]);
expect(checks.map((check) => [check.name, check.status])).toEqual([
["lint", "failure"],
["test", "success"],
]);
});
it("loses a run that never said when it happened to one that did, whichever came first", () => {
const undated = dedupeChecks([
entry("build", "success", { at: "2026-08-11T16:00:00Z" }),
entry("build", "pending"),
]);
const dated = dedupeChecks([
entry("build", "pending"),
entry("build", "success", { at: "2026-08-11T16:00:00Z" }),
]);
expect([undated[0]?.status, dated[0]?.status]).toEqual(["success", "success"]);
});
it("takes the last copy when neither run is dated, which is how an update is listed", () => {
const checks = dedupeChecks([entry("build", "pending"), entry("build", "failure")]);
expect(checks.map((check) => check.status)).toEqual(["failure"]);
});
it("keeps two workflows that name a job the same thing, and says which is which", () => {
const checks = dedupeChecks([
entry("build", "success", { workflowName: "CI", at: "2026-08-11T16:00:00Z" }),
entry("build", "failure", { workflowName: "Release", at: "2026-08-11T16:00:00Z" }),
]);
expect(checks.map((check) => [check.name, check.status])).toEqual([
["CI / build", "success"],
["Release / build", "failure"],
]);
});
it("leaves a colliding check with no workflow of its own unqualified", () => {
// An app-provided check run belongs to no workflow, which GitHub reports as an empty name.
const checks = dedupeChecks([
entry("build", "success", { workflowName: "", at: "2026-08-11T16:00:00Z" }),
entry("build", "failure", { workflowName: "CI", at: "2026-08-11T16:00:00Z" }),
]);
expect(checks.map((check) => check.name)).toEqual(["build", "CI / build"]);
});
});
@@ -0,0 +1,55 @@
import type { PullRequestCheck } from "@t3tools/contracts";
/** ISO-8601 timestamps in UTC compare correctly as plain text, which is all the ordering needs. */
function isAtLeastAsNew(candidate: string | null, kept: string | null): boolean {
if (candidate === null) return kept === null;
return kept === null || candidate >= kept;
}
/**
* One row per check rather than one per run of it.
*
* A host's rollup is a list of runs, not a list of checks: while a workflow is being re-run — or
* while a second run of it is already live — the same check arrives twice, and both copies reach
* the reader as what looks like a duplicate. Nothing in a check carries an id, so the name is what
* identifies it, qualified by the workflow it belongs to since two workflows are free to name a
* job the same thing.
*
* Within a group the newest run is the one worth showing: a re-run is the answer that replaces the
* one before it, and a run that never said when it happened loses to one that did. A tie goes to
* whichever came last, because a host lists a re-run after the run it repeats.
*
* The order is the host's own, held at the place each check first appeared, so a re-run landing
* mid-read replaces a row where it stands instead of reshuffling the list under the reader.
*
* Two checks that survive under the same name are then genuinely different ones, since they came
* from different workflows — each is shown as `workflow / name`, the way GitHub writes it itself.
* A survivor whose workflow the host did not name keeps its bare name rather than being qualified
* with nothing.
*/
export function dedupeChecks(
entries: ReadonlyArray<{
readonly check: PullRequestCheck;
readonly workflowName: string | null;
readonly at: string | null;
}>,
): ReadonlyArray<PullRequestCheck> {
const newestByCheck = new Map<string, (typeof entries)[number]>();
for (const entry of entries) {
const key = `${entry.workflowName ?? ""} ${entry.check.name}`;
const kept = newestByCheck.get(key);
// Re-setting a key a Map already holds keeps its first position, which is the order wanted.
if (kept === undefined || isAtLeastAsNew(entry.at, kept.at)) newestByCheck.set(key, entry);
}
const survivors = [...newestByCheck.values()];
const countsByName = new Map<string, number>();
for (const entry of survivors) {
countsByName.set(entry.check.name, (countsByName.get(entry.check.name) ?? 0) + 1);
}
return survivors.map((entry) => {
const workflowName = entry.workflowName ?? "";
return workflowName.length > 0 && (countsByName.get(entry.check.name) ?? 0) > 1
? { ...entry.check, name: `${workflowName} / ${entry.check.name}` }
: entry.check;
});
}
@@ -373,4 +373,34 @@ describe("GitHubCli.layer", () => {
assert.equal(error.message.includes(cause.detail), false);
}).pipe(Effect.provide(layer)),
);
it.effect("surfaces an actionable rate-limit error without exposing provider stderr", () =>
Effect.gen(function* () {
const cause = new VcsProcessExitError({
operation: "GitHubCli.execute",
command: "gh",
cwd: "/repo",
exitCode: 1,
failureKind: "rate-limited",
detail: "API rate limit exceeded.",
stderrLength: 82,
stderrTruncated: false,
});
mockRun.mockReturnValueOnce(Effect.fail(cause));
const gh = yield* GitHubCli.GitHubCli;
const error = yield* gh
.listOpenPullRequests({
cwd: "/repo",
headSelector: "feature/rate-limited",
})
.pipe(Effect.flip);
assert.strictEqual(error._tag, "GitHubCliRateLimitError");
assert.include(error.detail, "GitHub API rate limit exceeded");
assert.include(error.detail, "gh api rate_limit");
assert.strictEqual(error.cause, cause);
assert.notInclude(error.message, "user ID");
}).pipe(Effect.provide(layer)),
);
});
@@ -51,6 +51,19 @@ export class GitHubCliAuthenticationError extends Schema.TaggedErrorClass<GitHub
}
}
export class GitHubCliRateLimitError extends Schema.TaggedErrorClass<GitHubCliRateLimitError>()(
"GitHubCliRateLimitError",
gitHubCliFailureFields,
) {
get detail(): string {
return "GitHub API rate limit exceeded. Run `gh api rate_limit` to inspect the quota and reset time.";
}
override get message(): string {
return `GitHub CLI failed in execute: ${this.detail}`;
}
}
export class GitHubPullRequestNotFoundError extends Schema.TaggedErrorClass<GitHubPullRequestNotFoundError>()(
"GitHubPullRequestNotFoundError",
gitHubCliFailureFields,
@@ -138,6 +151,7 @@ export class GitHubRepositoryDecodeError extends Schema.TaggedErrorClass<GitHubR
export const GitHubCliError = Schema.Union([
GitHubCliUnavailableError,
GitHubCliAuthenticationError,
GitHubCliRateLimitError,
GitHubPullRequestNotFoundError,
GitHubCliCommandError,
GitHubPullRequestListDecodeError,
@@ -170,6 +184,9 @@ export function fromVcsError(
if (error.failureKind === "authentication") {
return new GitHubCliAuthenticationError({ ...context, cause: error });
}
if (error.failureKind === "rate-limited") {
return new GitHubCliRateLimitError({ ...context, cause: error });
}
if (error.failureKind === "not-found") {
return new GitHubPullRequestNotFoundError({ ...context, cause: error });
}
@@ -127,6 +127,7 @@ export class GitLabCliCommandError extends Schema.TaggedErrorClass<GitLabCliComm
case "authentication":
return new GitLabCliAuthenticationError({ ...context, cause });
case "not-found":
case "rate-limited":
case "command-failed":
case undefined:
return new GitLabCliCommandError({ ...context, cause });
+25
View File
@@ -140,6 +140,31 @@ describe("VcsProcess.run", () => {
}).pipe(provideLive),
);
it.effect("classifies API rate limits without retaining provider stderr", () =>
Effect.gen(function* () {
const providerStderr =
"GraphQL: API rate limit already exceeded for user ID 51714798 and token secret-value.";
const error = yield* run({
operation: "test.rate-limit",
command: "node",
args: ["-e", "process.stderr.write(process.argv[1]); process.exit(1)", providerStderr],
cwd: process.cwd(),
}).pipe(Effect.flip);
expect(error).toBeInstanceOf(VcsProcessExitError);
expect(error).toMatchObject({
command: "node",
exitCode: 1,
detail: "API rate limit exceeded.",
failureKind: "rate-limited",
stderrLength: providerStderr.length,
stderrTruncated: false,
});
expect(error.message).not.toContain(providerStderr);
expect(error.message).not.toContain("secret-value");
}).pipe(provideLive),
);
it.effect("retains spawn causes without exposing process arguments in the error message", () =>
Effect.gen(function* () {
const secretArgument = "--token=super-secret-token";
+8
View File
@@ -69,6 +69,14 @@ const classifyNonZeroExit = (command: string, stderr: string): VcsProcessExitFai
return "authentication";
}
if (
normalized.includes("api rate limit") ||
normalized.includes("rate limit exceeded") ||
normalized.includes("secondary rate limit")
) {
return "rate-limited";
}
if (
(command === "gh" &&
(normalized.includes("could not resolve to a pullrequest") ||
+16
View File
@@ -1662,10 +1662,22 @@ const makeWsRpcLayer = (
observeRpcEffect(WS_METHODS.pullRequestsRunAction, pullRequests.runAction(input), {
"rpc.aggregate": "pull-requests",
}),
[WS_METHODS.pullRequestsUpdate]: (input) =>
observeRpcEffect(WS_METHODS.pullRequestsUpdate, pullRequests.update(input), {
"rpc.aggregate": "pull-requests",
}),
[WS_METHODS.pullRequestsComment]: (input) =>
observeRpcEffect(WS_METHODS.pullRequestsComment, pullRequests.comment(input), {
"rpc.aggregate": "pull-requests",
}),
[WS_METHODS.pullRequestsUpdateComment]: (input) =>
observeRpcEffect(
WS_METHODS.pullRequestsUpdateComment,
pullRequests.updateComment(input),
{
"rpc.aggregate": "pull-requests",
},
),
[WS_METHODS.pullRequestsSubmitReview]: (input) =>
observeRpcEffect(WS_METHODS.pullRequestsSubmitReview, pullRequests.submitReview(input), {
"rpc.aggregate": "pull-requests",
@@ -1682,6 +1694,10 @@ const makeWsRpcLayer = (
pullRequests.setThreadResolution(input),
{ "rpc.aggregate": "pull-requests" },
),
[WS_METHODS.pullRequestsSetReaction]: (input) =>
observeRpcEffect(WS_METHODS.pullRequestsSetReaction, pullRequests.setReaction(input), {
"rpc.aggregate": "pull-requests",
}),
[WS_METHODS.pullRequestsInvalidate]: (input) =>
observeRpcEffect(WS_METHODS.pullRequestsInvalidate, pullRequests.invalidate(input), {
"rpc.aggregate": "pull-requests",
+16
View File
@@ -46,6 +46,22 @@ describe("connectCliAuth", () => {
expect(url.searchParams.get("code_challenge_method")).toBe("S256");
});
it("redirects straight to the CLI's loopback listener when the request carries a port", () => {
vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", TEST_PUBLISHABLE_KEY);
vi.stubEnv("VITE_CLERK_CLI_OAUTH_CLIENT_ID", "oauthapp_123");
const authorizeUrl = buildConnectCliClerkAuthorizeUrl({
state: "state-1",
challenge: "challenge-1",
loopbackPort: 34338,
});
expect(authorizeUrl).not.toBeNull();
const url = new URL(authorizeUrl!);
expect(url.searchParams.get("redirect_uri")).toBe("http://127.0.0.1:34338/callback");
expect(url.searchParams.get("state")).toBe("state-1");
});
it("returns null when the CLI OAuth client id is not configured", () => {
vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", TEST_PUBLISHABLE_KEY);
expect(
+10 -1
View File
@@ -1,6 +1,7 @@
import {
buildConnectClerkAuthorizeUrl,
connectCallbackUrl,
connectLoopbackRedirectUri,
CONNECT_OAUTH_SCOPES,
type ConnectAuthorizeRequest,
} from "@t3tools/shared/connectAuth";
@@ -34,6 +35,11 @@ export function connectCliAuthRoutesEnabled(): boolean {
* Builds the Clerk authorize URL for a CLI-initiated connect request. The
* state is mirrored into sessionStorage so the callback page can verify the
* response matches a request this browser actually started.
*
* A request carrying a loopback port came from a CLI with a local callback
* listener: the authorization code must return to `127.0.0.1` directly, so
* the hosted callback page never sees it. Clerk enforces its registered
* redirect URI allowlist either way.
*/
export function buildConnectCliClerkAuthorizeUrl(request: ConnectAuthorizeRequest): string | null {
const { clerkPublishableKey } = resolveCloudPublicConfig();
@@ -44,7 +50,10 @@ export function buildConnectCliClerkAuthorizeUrl(request: ConnectAuthorizeReques
return buildConnectClerkAuthorizeUrl({
authorizationEndpoint: `${clerkFrontendApiUrlFromPublishableKey(clerkPublishableKey)}/oauth/authorize`,
clientId,
redirectUri: connectCallbackUrl(configuredHostedAppUrl()),
redirectUri:
request.loopbackPort === undefined
? connectCallbackUrl(configuredHostedAppUrl())
: connectLoopbackRedirectUri(request.loopbackPort),
scopes: CONNECT_OAUTH_SCOPES,
state: request.state,
challenge: request.challenge,
+22
View File
@@ -1,14 +1,20 @@
import { useAtomValue } from "@effect/atom-react";
import {
createManagedRelayQueryManager,
deregisterManagedRelayEnvironment,
ManagedRelay,
managedRelaySessionAtom,
readManagedRelaySnapshotState,
} from "@t3tools/client-runtime/relay";
import {
createAtomCommandScheduler,
createRuntimeCommand,
} from "@t3tools/client-runtime/state/runtime";
import type {
RelayClientDeviceRecord,
RelayClientEnvironmentRecord,
} from "@t3tools/contracts/relay";
import type { EnvironmentId } from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -29,6 +35,22 @@ const managedRelayAtomRuntime = Atom.runtime(
export const managedRelayQueryManager = createManagedRelayQueryManager(managedRelayAtomRuntime);
const managedRelayMutationScheduler = createAtomCommandScheduler();
export const deregisterManagedRelayEnvironmentCommand = createRuntimeCommand(
managedRelayAtomRuntime,
{
label: "web:managed-relay:deregister-environment",
scheduler: managedRelayMutationScheduler,
concurrency: {
mode: "serial",
key: (input: { readonly accountId: string; readonly environmentId: EnvironmentId }) =>
input.accountId,
},
execute: (input, registry) => deregisterManagedRelayEnvironment(registry, input),
},
);
const EMPTY_ENVIRONMENTS_ATOM = Atom.make(
AsyncResult.success<ReadonlyArray<RelayClientEnvironmentRecord>>([]),
).pipe(Atom.keepAlive, Atom.withLabel("managed-relay:web:environments:null"));
+10 -2
View File
@@ -10,7 +10,7 @@ import {
import { useLocation, useNavigate } from "@tanstack/react-router";
import { isElectron } from "../env";
import { getLocalStorageItem } from "../hooks/useLocalStorage";
import { getLocalStorageItem, removeLocalStorageItem } from "../hooks/useLocalStorage";
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
import { cn, isMacPlatform } from "../lib/utils";
import { primaryServerKeybindingsAtom } from "../state/server";
@@ -147,6 +147,14 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
// that would otherwise refresh a render-time snapshot.
const viewportWidth = useSyncExternalStore(subscribeToViewportWidth, readViewportWidth);
const sidebarMaximumWidth = resolveThreadSidebarMaximumWidth(viewportWidth);
const resetSidebarWidth = () => {
try {
removeLocalStorageItem(THREAD_SIDEBAR_WIDTH_STORAGE_KEY);
} catch (error) {
console.error("Could not clear persisted thread sidebar width.", error);
}
setSidebarWidth(resolveInitialThreadSidebarWidth(null, viewportWidth));
};
const [isWindowFullscreen, setIsWindowFullscreen] = useState(() => {
const getWindowFullscreenState = window.desktopBridge?.getWindowFullscreenState;
return isMacosDesktop && typeof getWindowFullscreenState === "function"
@@ -225,7 +233,7 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
) : (
<ThreadSidebar />
)}
<SidebarRail />
<SidebarRail onDoubleClick={resetSidebarWidth} />
</Sidebar>
{children}
<SidebarControl />
+2 -1
View File
@@ -1569,13 +1569,14 @@ function ChatMarkdown({
if (href) openChangeRequestLink(event, href);
}}
onContextMenu={(event) => {
if (!canOpenInPreview || !href || !faviconHost) return;
if (!href || !faviconHost) return;
event.preventDefault();
event.stopPropagation();
const api = readLocalApi();
if (!api) return;
void showExternalLinkContextMenu({
href,
canOpenInPreview,
position: { x: event.clientX, y: event.clientY },
showContextMenu: (items, position) => api.contextMenu.show(items, position),
openInPreview: async (target) => {
+36 -11
View File
@@ -123,11 +123,11 @@ import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
import { useMediaQuery } from "../hooks/useMediaQuery";
import { RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY } from "../rightPanelLayout";
import {
pullRequestSurfaceId,
selectActiveRightPanel,
selectActiveRightPanelSurface,
selectThreadRightPanelState,
type RightPanelSurface,
updatePullRequestTabStatus,
useRightPanelStore,
} from "../rightPanelStore";
import {
@@ -144,6 +144,7 @@ import {
selectThreadPreviewMiniPlayer,
usePreviewMiniPlayerStore,
} from "../previewMiniPlayerStore";
import { isThreadOwnPullRequest } from "./pullRequest/pullRequestDetail.logic";
import { PullRequestDetailPanel } from "./pullRequest/PullRequestDetailPanel";
import { PullRequestDetailGhost } from "./pullRequest/PullRequestGhosts";
import { PullRequestsUnavailableState } from "./pullRequest/PullRequestsUnavailableState";
@@ -480,6 +481,14 @@ function shouldTypeToFocusComposer(event: KeyboardEvent): boolean {
if (eventPathContainsSelector(event, TYPE_TO_FOCUS_INTERACTIVE_SELECTOR)) return false;
if (document.querySelector(TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR)) return false;
// The right-panel surface launcher claims its shortcut letters while it is
// visible (data attribute set in RightPanelTabs); those keys open surfaces
// instead of typing into the composer.
const launcherKeys = document
.querySelector("[data-surface-launcher-keys]")
?.getAttribute("data-surface-launcher-keys");
if (launcherKeys && launcherKeys.toLowerCase().includes(event.key.toLowerCase())) return false;
return true;
}
@@ -1592,14 +1601,18 @@ function ChatViewContent(props: ChatViewProps) {
const [pullRequestTabStatuses, setPullRequestTabStatuses] = useState<
Record<string, PullRequestTabStatus>
>({});
const handlePullRequestTabStatusChange = useCallback((status: PullRequestTabStatus) => {
const id = pullRequestSurfaceId(status);
setPullRequestTabStatuses((current) =>
current[id]?.state === status.state && current[id]?.isDraft === status.isDraft
? current
: { ...current, [id]: status },
);
}, []);
// Keyed by the surface the panel is showing rather than by a key rebuilt from the status, so
// the tab is found again whether or not that surface was opened with an environment on it.
const activePullRequestSurfaceId =
activeRightPanelSurface?.kind === "pull-request" ? activeRightPanelSurface.id : undefined;
const handlePullRequestTabStatusChange = useCallback(
(status: PullRequestTabStatus) => {
const id = activePullRequestSurfaceId;
if (id === undefined) return;
setPullRequestTabStatuses((current) => updatePullRequestTabStatus(current, id, status));
},
[activePullRequestSurfaceId],
);
const activeFileSurface =
activeRightPanelSurface?.kind === "file" ? activeRightPanelSurface : null;
const activePreviewState = useThreadPreviewState(activeThreadRef);
@@ -6074,11 +6087,23 @@ function ChatViewContent(props: ChatViewProps) {
number: activeRightPanelSurface.number,
}}
context={
activeThreadPr?.number === activeRightPanelSurface.number &&
threadRepository === activeRightPanelSurface.repository
isThreadOwnPullRequest(
{
projectId: activeProject?.id ?? null,
repository: threadRepository,
number: activeThreadPr?.number ?? null,
},
{
projectId: activeRightPanelSurface.projectId,
repository: activeRightPanelSurface.repository,
number: activeRightPanelSurface.number,
},
)
? "thread"
: "page"
}
chromeVariant="collapse"
composerDraftTarget={composerDraftTarget}
onStateChange={handlePullRequestTabStatusChange}
/>
) : activeRightPanelSurface?.kind === "agents" ? (
@@ -264,6 +264,20 @@ describe("buildThreadActionItems", () => {
expect(item?.description).toBe("T3 Code · #feat/search");
});
it("prefers renderDescription when provided", () => {
const [item] = buildThreadActionItems({
threads: [makeThread({ branch: "feat/search", worktreePath: "/tmp/wt" })],
projectTitleById: new Map([[PROJECT_ID, "T3 Code"]]),
sortOrder: "updated_at",
icon: null,
renderDescription: (thread, { projectTitle }) =>
`${projectTitle}:${thread.branch}:${thread.worktreePath ? "wt" : "local"}`,
runThread: async (_thread) => undefined,
});
expect(item?.description).toBe("T3 Code:feat/search:wt");
});
it("filters archived threads out of thread search items", () => {
const items = buildThreadActionItems({
threads: [
@@ -154,7 +154,16 @@ export function buildProjectActionItems(input: {
export type BuildThreadActionItemsThread = Pick<
SidebarThreadSummary,
"archivedAt" | "branch" | "createdAt" | "environmentId" | "id" | "projectId" | "title"
| "archivedAt"
| "branch"
| "createdAt"
| "environmentId"
| "id"
| "modelSelection"
| "projectId"
| "session"
| "title"
| "worktreePath"
> & {
updatedAt: string;
latestUserMessageAt?: string | null;
@@ -170,6 +179,8 @@ export function buildThreadActionItems<TThread extends BuildThreadActionItemsThr
renderLeadingContent?: (thread: TThread) => ReactNode;
/** Optional content rendered inline after the title text per-thread. */
renderTrailingContent?: (thread: TThread) => ReactNode;
/** Optional rich description (e.g. favicon + workspace icons). Falls back to text. */
renderDescription?: (thread: TThread, meta: { projectTitle: string | undefined }) => ReactNode;
getContentMatch?: (thread: TThread) => CommandPaletteThreadContentMatch | undefined;
runThread: (thread: Pick<SidebarThreadSummary, "environmentId" | "id">) => Promise<void>;
limit?: number;
@@ -198,6 +209,9 @@ export function buildThreadActionItems<TThread extends BuildThreadActionItemsThr
const leadingContent = input.renderLeadingContent?.(thread);
const trailingContent = input.renderTrailingContent?.(thread);
const contentMatch = input.getContentMatch?.(thread);
const description = input.renderDescription
? input.renderDescription(thread, { projectTitle })
: descriptionParts.join(` · `);
return Object.assign(
{
@@ -210,7 +224,7 @@ export function buildThreadActionItems<TThread extends BuildThreadActionItemsThr
contentMatch?.snippet ?? ``,
],
title: thread.title,
description: descriptionParts.join(` · `),
description,
timestamp: formatRelativeTimeLabel(
thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
),
+48 -1
View File
@@ -124,9 +124,14 @@ import { ProjectFavicon } from "./ProjectFavicon";
import { ProjectFilePicker } from "./files/ProjectFilePicker";
import { ProjectContentSearchDialog } from "./search/ProjectContentSearchDialog";
import { toggleThemeEditorForTheme } from "./settings/themeEditorStore";
import { ThreadCommandSubtitle } from "./ThreadCommandSubtitle";
import { ThreadRowLeadingStatus, ThreadRowTrailingStatus } from "./ThreadStatusIndicators";
import { primaryServerKeybindingsAtom, primaryServerProvidersAtom } from "../state/server";
import { resolveDefaultProviderModelSelection } from "../providerInstances";
import {
deriveProviderInstanceEntries,
resolveDefaultProviderModelSelection,
type ProviderInstanceEntry,
} from "../providerInstances";
import { resolveShortcutCommand, threadJumpIndexFromCommand } from "../keybindings";
import { CommandDialog, CommandDialogPopup } from "./ui/command";
import { Button } from "./ui/button";
@@ -584,6 +589,18 @@ function OpenCommandPaletteDialog(props: {
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const { theme, themeHalves, resolvedTheme } = useTheme();
const providers = useAtomValue(primaryServerProvidersAtom);
const providerEntryByEnvironmentAndInstanceId = useMemo(() => {
const map = new Map<string, ProviderInstanceEntry>();
for (const environment of environments) {
const environmentProviders =
environment.serverConfig?.providers ??
(environment.environmentId === primaryEnvironmentId ? providers : []);
for (const entry of deriveProviderInstanceEntries(environmentProviders)) {
map.set(`${environment.environmentId}:${entry.instanceId}`, entry);
}
}
return map;
}, [environments, primaryEnvironmentId, providers]);
const [viewStack, setViewStack] = useState<CommandPaletteView[]>([]);
const currentView = viewStack.at(-1) ?? null;
const environmentIds = useMemo(
@@ -816,6 +833,10 @@ function OpenCommandPaletteDialog(props: {
new Map<ProjectId, string>(projects.map((project) => [project.id, project.workspaceRoot])),
[projects],
);
const projectFaviconPathById = useMemo(
() => new Map(projects.map((project) => [project.id, project.faviconPath ?? null] as const)),
[projects],
);
const projectTitleById = useMemo(
() => new Map<ProjectId, string>(projects.map((project) => [project.id, project.title])),
[projects],
@@ -1000,6 +1021,29 @@ function OpenCommandPaletteDialog(props: {
icon: <MessageSquareIcon className={ITEM_ICON_CLASS} />,
renderLeadingContent: (thread) => <ThreadRowLeadingStatus thread={thread} />,
renderTrailingContent: (thread) => <ThreadRowTrailingStatus thread={thread} />,
renderDescription: (thread, { projectTitle }) => {
const modelInstanceId =
thread.session?.providerInstanceId ?? thread.modelSelection.instanceId;
const providerEntry =
providerEntryByEnvironmentAndInstanceId.get(
`${thread.environmentId}:${modelInstanceId}`,
) ?? null;
return (
<ThreadCommandSubtitle
environmentId={thread.environmentId}
projectCwd={projectCwdById.get(thread.projectId) ?? null}
projectFaviconPath={projectFaviconPathById.get(thread.projectId) ?? null}
projectTitle={projectTitle ?? null}
branch={thread.branch}
worktreePath={thread.worktreePath}
isCurrent={thread.id === activeThreadId}
driverKind={providerEntry?.driverKind ?? null}
providerDisplayName={
thread.session?.providerName ?? providerEntry?.displayName ?? modelInstanceId
}
/>
);
},
getContentMatch: (thread) => {
const match = threadContentMatchByKey.get(
threadSearchMatchKey({
@@ -1026,7 +1070,10 @@ function OpenCommandPaletteDialog(props: {
activeThreadId,
clientSettings.sidebarThreadSortOrder,
navigate,
projectCwdById,
projectFaviconPathById,
projectTitleById,
providerEntryByEnvironmentAndInstanceId,
threadContentMatchByKey,
threadSearchQuery,
threads,
@@ -142,7 +142,7 @@ function DisabledCommandPaletteResultRow(props: {
<ThreadContentMatch match={props.item.threadContentMatch} />
) : null}
{props.item.description ? (
<span className="truncate text-muted-foreground/70 text-xs">
<span className="min-w-0 text-muted-foreground/70 text-xs">
{props.item.description}
</span>
) : null}
@@ -193,7 +193,7 @@ function CommandPaletteResultRow(props: {
<ThreadContentMatch match={props.item.threadContentMatch} />
) : null}
{props.item.description ? (
<span className="truncate text-muted-foreground/70 text-xs">
<span className="min-w-0 text-muted-foreground/70 text-xs">
{props.item.description}
</span>
) : null}
+9 -4
View File
@@ -174,6 +174,7 @@ import {
getSidebarThreadIdsToPrewarm,
resolveAdjacentThreadId,
isContextMenuPointerDown,
isSidebarNestedLinkClick,
isTrailingDoubleClick,
resolveProjectStatusIndicator,
resolveThreadRowClassName,
@@ -567,7 +568,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
[clearSelection, handleMultiSelectContextMenu, handleThreadContextMenu, isSelected, threadRef],
);
const handlePrClick = useCallback(
(event: React.MouseEvent<HTMLButtonElement>) => {
(event: React.MouseEvent<HTMLAnchorElement>) => {
if (!prStatus) return;
const openedInRightPanel = openPrLink(
event,
@@ -694,14 +695,17 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
<a
href={prStatus.url}
target="_blank"
rel="noopener noreferrer"
aria-label={prStatus.tooltip}
className={`inline-flex items-center justify-center ${prStatus.colorClass} cursor-pointer rounded-sm outline-hidden focus-visible:ring-1 focus-visible:ring-ring`}
onPointerDown={(event) => event.stopPropagation()}
onClick={handlePrClick}
>
<ChangeRequestStatusIcon className="size-3" />
</button>
</a>
}
/>
<TooltipPopup side="top">
@@ -1727,6 +1731,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
threadRef: ScopedThreadRef,
orderedProjectThreadKeys: readonly string[],
) => {
if (isSidebarNestedLinkClick(event.target)) return;
const isMac = isMacPlatform(navigator.platform);
const isModClick = isMac ? event.metaKey : event.ctrlKey;
const isShiftClick = event.shiftKey;
+203 -58
View File
@@ -11,6 +11,7 @@ import {
X,
} from "lucide-react";
import {
type KeyboardEvent as ReactKeyboardEvent,
type MouseEvent as ReactMouseEvent,
type ReactElement,
type ReactNode,
@@ -25,6 +26,7 @@ import type { RightPanelSurface } from "~/rightPanelStore";
import { cn } from "~/lib/utils";
import { readLocalApi } from "~/localApi";
import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
import { Kbd } from "~/components/ui/kbd";
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "~/components/ui/menu";
import { ScrollArea } from "~/components/ui/scroll-area";
import { faviconUrlForOrigin } from "~/lib/favicon";
@@ -88,6 +90,28 @@ const SURFACE_DISABLED_REASONS = {
agents: "Agents are only available from a thread.",
} as const;
/** Overlays that must win over the launcher's letter shortcuts. */
const LAUNCHER_SHORTCUT_BLOCKING_LAYERS = [
'[data-slot="dialog-popup"]',
'[data-slot="alert-dialog-popup"]',
'[data-slot="command-dialog-popup"]',
'[data-slot="menu-popup"]',
'[data-slot="select-popup"]',
'[data-slot="popover-popup"]',
'[data-slot="combobox-popup"]',
'[data-slot="autocomplete-popup"]',
].join(",");
/** One-line unavailability hints for the empty-state cards. */
const SURFACE_UNAVAILABLE_HINTS = {
browser: "Only available in the desktop app.",
terminal: "Available when a project is open.",
files: "Available when a project is open.",
diff: "Available for Git repositories.",
pullRequest: "No pull request on this branch yet.",
agents: "Available from a thread.",
} as const;
type TabContextMenuAction = "copy-path" | "close" | "close-others" | "close-to-right" | "close-all";
function DisabledReasonTooltip(props: { reason: string; trigger: ReactElement }) {
@@ -118,6 +142,13 @@ function SurfaceMenuItem(props: {
return <DisabledReasonTooltip reason={props.disabledReason} trigger={item} />;
}
/**
* Card launcher shown when the right panel has no surfaces. Keyboard-first
* without palette chrome: a surface's letter opens it directly from anywhere
* outside a typing context, and arrows plus Enter work while the launcher is
* focused. The highlight only appears on hover or arrow use. Unavailable
* surfaces stay visible with a one-line reason.
*/
function RightPanelEmptyState(props: {
onAddBrowser: () => void;
onAddTerminal: () => void;
@@ -133,13 +164,17 @@ function RightPanelEmptyState(props: {
agentsAvailable: boolean;
liveAgentCount: number;
}) {
// -1 means no highlight: it only appears on hover or arrow use.
const [highlight, setHighlight] = useState(-1);
const actions = [
{
label: "Browser",
description: "Open a local app or URL.",
icon: Globe2,
shortcut: "B",
available: props.browserAvailable,
disabledReason: SURFACE_DISABLED_REASONS.browser,
disabledReason: SURFACE_UNAVAILABLE_HINTS.browser,
onClick: props.onAddBrowser,
badgeCount: 0,
},
@@ -147,8 +182,9 @@ function RightPanelEmptyState(props: {
label: "Terminal",
description: "Start a shell in this workspace.",
icon: TerminalSquare,
shortcut: "T",
available: props.terminalAvailable,
disabledReason: SURFACE_DISABLED_REASONS.terminal,
disabledReason: SURFACE_UNAVAILABLE_HINTS.terminal,
onClick: props.onAddTerminal,
badgeCount: 0,
},
@@ -156,8 +192,9 @@ function RightPanelEmptyState(props: {
label: "Files",
description: "Browse and read workspace files.",
icon: Files,
shortcut: "F",
available: props.filesAvailable,
disabledReason: SURFACE_DISABLED_REASONS.files,
disabledReason: SURFACE_UNAVAILABLE_HINTS.files,
onClick: props.onAddFiles,
badgeCount: 0,
},
@@ -165,91 +202,199 @@ function RightPanelEmptyState(props: {
label: "Diff",
description: "Review changes in this thread.",
icon: FileDiff,
shortcut: "D",
available: props.diffAvailable,
disabledReason: SURFACE_DISABLED_REASONS.diff,
disabledReason: SURFACE_UNAVAILABLE_HINTS.diff,
onClick: props.onAddDiff,
badgeCount: 0,
},
{
label: "Pull request",
description: "Open the pull request for this thread's branch.",
description: "Open this branch's pull request.",
icon: GitPullRequest,
shortcut: "P",
available: props.pullRequestAvailable,
disabledReason: SURFACE_DISABLED_REASONS.pullRequest,
disabledReason: SURFACE_UNAVAILABLE_HINTS.pullRequest,
onClick: props.onAddPullRequest,
badgeCount: 0,
},
{
label: "Agents",
description: "Watch subagents and workflows run.",
description: "Follow subagents and workflows.",
icon: Bot,
shortcut: "A",
available: props.agentsAvailable,
disabledReason: SURFACE_DISABLED_REASONS.agents,
disabledReason: SURFACE_UNAVAILABLE_HINTS.agents,
onClick: props.onAddAgents,
badgeCount: props.liveAgentCount,
},
] as const;
type SurfaceAction = (typeof actions)[number];
const availableActions = actions.filter((action) => action.available);
const highlightIndex =
availableActions.length === 0 ? -1 : Math.min(highlight, availableActions.length - 1);
// Letter shortcuts work while the launcher is visible, not only while it
// is focused; focus moves around too easily (stray clicks) to carry them.
// Capture phase so app-level key handlers cannot swallow the event first;
// typing contexts and already-handled events are left alone.
const shortcutActionsRef = useRef(availableActions);
useEffect(() => {
shortcutActionsRef.current = availableActions;
});
useEffect(() => {
const handler = (event: KeyboardEvent) => {
if (event.defaultPrevented || event.isComposing) return;
if (event.metaKey || event.ctrlKey || event.altKey) return;
if (document.querySelector(LAUNCHER_SHORTCUT_BLOCKING_LAYERS)) return;
const target = event.target;
if (target instanceof HTMLElement) {
if (target.closest("input, textarea, select")) return;
// An empty contenteditable (the chat composer at rest) does not
// count as typing; letters only become text once a draft exists.
const editable = target.isContentEditable ? target : target.closest("[contenteditable]");
if (editable && (editable.textContent ?? "").trim().length > 0) return;
}
const action = shortcutActionsRef.current.find(
(candidate) => candidate.shortcut.toLowerCase() === event.key.toLowerCase(),
);
if (!action) return;
event.preventDefault();
event.stopPropagation();
action.onClick();
};
window.addEventListener("keydown", handler, true);
return () => window.removeEventListener("keydown", handler, true);
}, []);
const handleKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey) return;
if (availableActions.length === 0) return;
if (event.key === "ArrowDown" || event.key === "ArrowRight") {
event.preventDefault();
setHighlight((highlightIndex + 1) % availableActions.length);
return;
}
if (event.key === "ArrowUp" || event.key === "ArrowLeft") {
event.preventDefault();
setHighlight(
highlightIndex === -1
? availableActions.length - 1
: (highlightIndex - 1 + availableActions.length) % availableActions.length,
);
return;
}
if (event.key === "Enter") {
// A focused card button owns its own activation; only open from the
// highlight when the container itself has focus.
if (event.target instanceof HTMLElement && event.target.closest("button")) return;
const action = availableActions[highlightIndex];
if (!action) return;
event.preventDefault();
action.onClick();
}
};
// Stable identity so React only runs this callback ref on mount/unmount;
// an inline arrow would re-attach and re-focus on every render.
const focusOnMount = useCallback((node: HTMLDivElement | null) => {
node?.focus();
}, []);
const isHighlighted = (action: SurfaceAction) =>
highlightIndex !== -1 && availableActions[highlightIndex] === action;
const actionIcon = (action: SurfaceAction, iconClassName = "size-4") => {
const Icon = action.icon;
return (
<span className="relative inline-flex shrink-0">
<Icon className={iconClassName} />
{action.badgeCount > 0 ? (
<span
aria-hidden
className="absolute -top-1.5 -right-2 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-info px-1 text-[9px] font-semibold tabular-nums text-white"
>
{action.badgeCount}
</span>
) : null}
</span>
);
};
const cardShellClass =
"rounded-lg border border-border/80 bg-card dark:border-transparent dark:shadow-none dark:inset-ring-1 dark:inset-ring-white/5";
const highlightedCardClass = "bg-accent/60 dark:inset-ring-white/20";
return (
<div className="flex min-h-0 flex-1 items-center justify-center p-6">
<div className="w-full max-w-xl">
<div className="mb-5 text-center">
<h3 className="text-sm font-medium text-foreground">Open a surface</h3>
<p className="mt-1 text-xs text-muted-foreground">
<div
ref={focusOnMount}
tabIndex={0}
onKeyDown={handleKeyDown}
aria-label="Open a surface"
data-surface-launcher-keys={availableActions.map((action) => action.shortcut).join("")}
className={cn(
"flex min-h-0 flex-1 items-center justify-center overflow-y-auto px-6 pt-6 outline-none",
// The panel topbar sits above this container; matching bottom padding
// keeps the cards centered against the full panel, not the leftover.
"pb-[calc(var(--workspace-topbar-height)+--spacing(6))]",
)}
>
<div className="relative w-full max-w-lg">
<div className="absolute inset-x-0 bottom-full mb-5 text-center">
<h3 className="font-medium text-foreground text-sm">Open a surface</h3>
<p className="mt-1 text-muted-foreground text-xs">
Choose what to show in the right panel.
</p>
</div>
<div className="grid grid-cols-2 gap-2">
{actions.map((action) => {
const Icon = action.icon;
const content = (
<>
<span className="relative mb-3 inline-flex">
<Icon className="size-5" />
{action.badgeCount > 0 ? (
<span
aria-hidden
className="absolute -top-1.5 -right-2 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-info px-1 text-[9px] font-semibold tabular-nums text-white"
>
{action.badgeCount}
</span>
) : null}
{actions.map((action) =>
action.available ? (
<button
key={action.label}
type="button"
onClick={action.onClick}
onMouseEnter={() => setHighlight(availableActions.indexOf(action))}
onMouseLeave={() =>
setHighlight((current) =>
current === availableActions.indexOf(action) ? -1 : current,
)
}
className={cn(
"relative flex w-full cursor-pointer flex-col items-start p-4 text-left transition hover:border-border hover:bg-accent/60",
cardShellClass,
isHighlighted(action) && highlightedCardClass,
)}
>
<Kbd className="absolute top-3 right-3">{action.shortcut}</Kbd>
<span className="flex items-center gap-2 pe-8">
{actionIcon(action)}
<span className="font-medium text-sm">{action.label}</span>
</span>
<span className="text-sm font-medium">{action.label}</span>
<span className="mt-1 text-xs leading-relaxed text-muted-foreground">
<span className="mt-1.5 text-muted-foreground text-xs leading-relaxed">
{action.description}
</span>
</>
);
if (action.available) {
return (
<button
key={action.label}
type="button"
onClick={action.onClick}
className="cursor-pointer flex min-h-28 w-full flex-col items-start rounded-lg border border-border/80 bg-card p-4 text-left transition hover:border-border hover:bg-accent/60 dark:border-transparent dark:shadow-none dark:inset-ring-1 dark:inset-ring-white/5"
>
{content}
</button>
);
}
const disabledCard = (
<button
type="button"
className="flex min-h-28 w-full cursor-not-allowed flex-col items-start rounded-lg border border-border/80 bg-card p-4 text-left opacity-40 dark:border-transparent dark:shadow-none dark:inset-ring-1 dark:inset-ring-white/5"
aria-disabled="true"
>
{content}
</button>
);
return (
<DisabledReasonTooltip
) : (
<div
key={action.label}
reason={action.disabledReason}
trigger={disabledCard}
/>
);
})}
className={cn(
"relative flex w-full flex-col items-start p-4 opacity-40",
cardShellClass,
)}
>
<Kbd className="absolute top-3 right-3">{action.shortcut}</Kbd>
<span className="flex items-center gap-2 pe-8">
{actionIcon(action)}
<span className="font-medium text-sm">{action.label}</span>
</span>
<span className="mt-1.5 text-muted-foreground text-xs leading-relaxed">
{action.disabledReason}
</span>
</div>
),
)}
</div>
</div>
</div>
@@ -12,6 +12,7 @@ import {
getProjectSortTimestamp,
hasUnseenCompletion,
isContextMenuPointerDown,
isSidebarNestedLinkClick,
isTrailingDoubleClick,
orderItemsByPreferredIds,
resolveProjectStatusIndicator,
@@ -411,6 +412,27 @@ describe("isTrailingDoubleClick", () => {
});
});
describe("isSidebarNestedLinkClick", () => {
const linkTarget = {
closest: (selector: string) => (selector === "a[href]" ? ({} as Element) : null),
} as unknown as EventTarget;
it("ignores row clicks that originated on a nested link", () => {
expect(isSidebarNestedLinkClick(linkTarget)).toBe(true);
});
it("walks up from a text node to the enclosing link", () => {
expect(isSidebarNestedLinkClick({ parentElement: linkTarget } as unknown as EventTarget)).toBe(
true,
);
});
it("leaves ordinary row clicks alone", () => {
expect(isSidebarNestedLinkClick({ closest: () => null } as unknown as EventTarget)).toBe(false);
expect(isSidebarNestedLinkClick(null)).toBe(false);
});
});
describe("shouldCreateNewThreadInCurrentProject", () => {
it("creates directly on shift+click in a multi-project setup", () => {
expect(shouldCreateNewThreadInCurrentProject(true, 2)).toBe(true);
+18
View File
@@ -274,6 +274,24 @@ export function isTrailingDoubleClick(detail: number): boolean {
return detail > 1;
}
function nodeClosest(node: object | null, selector: string): unknown {
if (node === null || !("closest" in node) || typeof node.closest !== "function") return null;
return node.closest(selector);
}
/** Clicks on a nested link keep the link's meaning. The row must not treat them as multi-select. */
export function isSidebarNestedLinkClick(target: EventTarget | null): boolean {
if (target == null || typeof target !== "object") return false;
if (nodeClosest(target, "a[href]") !== null) return true;
const parent =
"parentElement" in target &&
target.parentElement !== null &&
typeof target.parentElement === "object"
? target.parentElement
: null;
return nodeClosest(parent, "a[href]") !== null;
}
// Shift+click on the new thread button creates directly in the current
// project, skipping the command palette's project picker. With a single
// project there is nothing to pick, so a plain click already creates
+11 -4
View File
@@ -124,6 +124,7 @@ import {
formatWorkingDurationLabel,
firstValidTimestampMs,
hasUnseenCompletion,
isSidebarNestedLinkClick,
isTrailingDoubleClick,
orderItemsByPreferredIds,
planPinnedReorder,
@@ -1006,7 +1007,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
if (!showSnoozeButton) setSnoozeMenuOpen(false);
}, [showSnoozeButton]);
const handlePrClick = useCallback(
(event: ReactMouseEvent<HTMLElement>) => {
(event: ReactMouseEvent<HTMLAnchorElement>) => {
if (!pr?.url) return;
const openedInRightPanel = openPrLink(
event,
@@ -1083,10 +1084,15 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
</span>
);
// A real link so cmd/ctrl+click and middle-click open the host in the
// browser. A plain click still opens T3's pull request view.
const prBadge =
prStatus && pr ? (
<button
type="button"
<a
href={pr.url}
target="_blank"
rel="noopener noreferrer"
onPointerDown={(event) => event.stopPropagation()}
onClick={handlePrClick}
className={cn(
// Sidebar chrome follows the interface font; tabular digits keep the
@@ -1101,7 +1107,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
aria-label={prStatus.tooltip}
>
#{pr.number}
</button>
</a>
) : null;
const terminalStatusIcon = terminalStatus ? (
<span
@@ -2307,6 +2313,7 @@ export default function Sidebar() {
const handleThreadClick = useCallback(
(event: ReactMouseEvent, threadRef: ScopedThreadRef) => {
if (isSidebarNestedLinkClick(event.target)) return;
const isMac = isMacPlatform(navigator.platform);
const isModClick = isMac ? event.metaKey : event.ctrlKey;
const threadKey = scopedThreadKey(threadRef);
@@ -0,0 +1,112 @@
import type { EnvironmentId, ProviderDriverKind } from "@t3tools/contracts";
import { FolderGit2Icon, FolderIcon, GitBranchIcon } from "lucide-react";
import { ProjectFavicon } from "./ProjectFavicon";
import { ProviderInstanceIcon } from "./chat/ProviderInstanceIcon";
import { cn } from "~/lib/utils";
/**
* Flip this while reviewing command-palette thread subtitles.
* - favicon-workspace-harness: favicon + Folder/FolderGit2 + branch + harness (default)
* - favicon-workspace: same without harness
* - favicon-branch-harness: GitBranch for local, FolderGit2 for worktrees, + harness
*/
export type ThreadCommandSubtitleVariant =
| "favicon-workspace-harness"
| "favicon-workspace"
| "favicon-branch-harness";
export const THREAD_COMMAND_SUBTITLE_VARIANT: ThreadCommandSubtitleVariant =
"favicon-workspace-harness";
const META_ICON_CLASS = "size-3 shrink-0 text-muted-foreground/70";
function Dot() {
return <span className="shrink-0 text-muted-foreground/50">·</span>;
}
function WorkspaceIcon(props: { variant: ThreadCommandSubtitleVariant; isWorktree: boolean }) {
if (props.isWorktree) {
return <FolderGit2Icon className={META_ICON_CLASS} aria-hidden />;
}
if (props.variant === "favicon-branch-harness") {
return <GitBranchIcon className={META_ICON_CLASS} aria-hidden />;
}
return <FolderIcon className={META_ICON_CLASS} aria-hidden />;
}
export function ThreadCommandSubtitle(props: {
environmentId: EnvironmentId;
projectCwd: string | null;
projectFaviconPath?: string | null;
projectTitle: string | null;
branch: string | null;
worktreePath: string | null;
isCurrent: boolean;
driverKind?: ProviderDriverKind | null;
providerDisplayName?: string | null;
variant?: ThreadCommandSubtitleVariant;
className?: string;
}) {
const variant = props.variant ?? THREAD_COMMAND_SUBTITLE_VARIANT;
const isWorktree = props.worktreePath != null && props.worktreePath.trim().length > 0;
const showHarness =
variant !== "favicon-workspace" && props.driverKind != null && props.providerDisplayName;
const projectLabel = props.projectTitle?.trim() || null;
const branchLabel = props.branch?.trim() || null;
if (!projectLabel && !branchLabel && !props.isCurrent && !showHarness) {
return null;
}
return (
<span
className={cn(
"inline-flex min-w-0 max-w-full items-center gap-1 text-xs text-muted-foreground/70",
props.className,
)}
>
{projectLabel ? (
<span className="inline-flex min-w-0 items-center gap-1">
{props.projectCwd ? (
<ProjectFavicon
environmentId={props.environmentId}
cwd={props.projectCwd}
faviconPath={props.projectFaviconPath}
className="size-3 shrink-0"
/>
) : null}
<span className="min-w-0 truncate">{projectLabel}</span>
</span>
) : null}
{branchLabel ? (
<>
{projectLabel ? <Dot /> : null}
<span className="inline-flex min-w-0 items-center gap-1">
<WorkspaceIcon variant={variant} isWorktree={isWorktree} />
<span className="min-w-0 truncate">{branchLabel}</span>
</span>
</>
) : null}
{showHarness && props.driverKind ? (
<>
{projectLabel || branchLabel ? <Dot /> : null}
<ProviderInstanceIcon
driverKind={props.driverKind}
displayName={props.providerDisplayName ?? props.driverKind}
iconClassName="size-3 shrink-0 opacity-70"
/>
</>
) : null}
{props.isCurrent ? (
<>
{projectLabel || branchLabel || showHarness ? <Dot /> : null}
<span className="shrink-0">Current thread</span>
</>
) : null}
</span>
);
}
@@ -23,6 +23,14 @@ describe("ChangedFilesCard", () => {
expect(markup).toContain('data-changed-files-state="expanded"');
expect(markup).toContain('aria-expanded="true"');
expect(markup).toContain("whitespace-nowrap");
expect(markup).toContain(
'class="group flex min-w-0 flex-1 items-center gap-1.5 overflow-hidden',
);
expect(markup).toContain('class="flex shrink-0 items-center gap-1 whitespace-nowrap');
expect(markup).toContain('class="ml-1 hidden min-w-0 flex-1 truncate');
expect(markup).toContain("@[24rem]/changed-files:inline");
expect(markup).not.toContain("sm:inline");
expect(markup).toContain('class="flex shrink-0 items-center gap-1.5"');
expect(markup).toContain("!size-[22px]");
expect(markup).toContain("size-3");
expect(markup).toContain('aria-label="Collapse all folders"');
@@ -56,7 +56,7 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
return (
<div
className="mt-4 rounded-2xl border border-border/70 bg-secondary p-2 dark:border-transparent dark:bg-input/32"
className="@container/changed-files mt-4 rounded-2xl border border-border/70 bg-secondary p-2 dark:border-transparent dark:bg-input/32"
data-changed-files-state={
expanded ? "expanded" : compactPreviewVisible ? "preview" : "collapsed"
}
@@ -73,7 +73,7 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
type="button"
aria-expanded={expanded}
data-scroll-anchor-ignore
className="group flex min-w-0 flex-1 items-center gap-1.5 rounded-lg px-1 py-1.5 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
className="group flex min-w-0 flex-1 items-center gap-1.5 overflow-hidden rounded-lg px-1 py-1.5 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
onClick={() => onExpandedChange(!expanded)}
>
<ChevronRightIcon
@@ -83,7 +83,7 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
expanded && "rotate-90",
)}
/>
<span className="flex min-w-0 items-center gap-1 whitespace-nowrap font-medium text-foreground text-xs leading-4">
<span className="flex shrink-0 items-center gap-1 whitespace-nowrap font-medium text-foreground text-xs leading-4">
<span>
{files.length} changed file{files.length === 1 ? "" : "s"}
</span>
@@ -96,11 +96,11 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
/>
)}
</span>
<span className="ml-1 hidden truncate text-[11px] text-muted-foreground group-hover:text-foreground/80 sm:inline">
<span className="ml-1 hidden min-w-0 flex-1 truncate text-[11px] text-muted-foreground group-hover:text-foreground/80 @[24rem]/changed-files:inline">
{expanded ? "Hide files" : "Show files"}
</span>
</button>
<div className="flex items-center gap-1.5">
<div className="flex shrink-0 items-center gap-1.5">
{expanded ? (
<Tooltip>
<TooltipTrigger
@@ -142,7 +142,7 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
}
>
<FileDiffIcon className="size-3" />
<span className="hidden sm:inline">Open diff</span>
<span className="hidden @[24rem]/changed-files:inline">Open diff</span>
</TooltipTrigger>
<TooltipPopup side="top">Open the full diff</TooltipPopup>
</Tooltip>
@@ -3106,7 +3106,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
showMobilePendingAnswerActions && "hidden sm:flex",
)}
>
<div className="-m-1 flex min-w-0 flex-1 items-center gap-1 overflow-x-auto p-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
<div className="-m-1 -ms-3.5 flex min-w-0 flex-1 items-center gap-1 overflow-x-auto p-1 ps-3.5 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
{noProviderAvailable ? (
<Button
type="button"
@@ -3129,7 +3129,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
instanceEntries={providerInstanceEntries}
keybindings={keybindings}
modelOptionsByInstance={modelOptionsByInstance}
triggerClassName="-ms-px"
triggerClassName="-ms-2.5"
terminalOpen={terminalOpen}
open={isComposerModelPickerOpen}
{...(composerProviderState.modelPickerIconClassName
@@ -41,6 +41,25 @@ describe("external chat link context menu", () => {
expect(harness.copyLink).not.toHaveBeenCalled();
});
it("still offers the link's own actions where the integrated browser cannot be opened", async () => {
const harness = createHarness(null);
await showExternalLinkContextMenu({
href: "https://github.com/pingdotgg/t3code/pull/6169",
canOpenInPreview: false,
position: { x: 4, y: 8 },
...harness,
});
expect(harness.showContextMenu).toHaveBeenCalledWith(
[
{ id: "open-external", label: "Open in system browser" },
{ id: "copy-link", label: "Copy Link" },
],
{ x: 4, y: 8 },
);
});
it("copies the exact destination without opening it", async () => {
const harness = createHarness("copy-link");
const href = "https://example.com/docs?topic=menus#copy";
@@ -20,9 +20,25 @@ const EXTERNAL_LINK_CONTEXT_MENU_ITEMS = [
{ id: "copy-link", label: "Copy Link" },
] as const satisfies readonly ContextMenuItem<ExternalLinkContextMenuAction>[];
/**
* The integrated browser is not always there to offer — it needs a thread to open beside and a
* runtime that can show it — but the other two answers hold wherever a link does. Dropping the
* whole menu with the one item that cannot be honoured is what left a right-click on a link
* showing the platform's cut-and-paste menu instead of a way to copy the link.
*/
export function externalLinkContextMenuItems(options: {
readonly canOpenInPreview: boolean;
}): readonly ContextMenuItem<ExternalLinkContextMenuAction>[] {
return options.canOpenInPreview
? EXTERNAL_LINK_CONTEXT_MENU_ITEMS
: EXTERNAL_LINK_CONTEXT_MENU_ITEMS.filter((item) => item.id !== "open-in-preview");
}
interface ShowExternalLinkContextMenuOptions {
readonly href: string;
readonly position: { readonly x: number; readonly y: number };
/** Absent means yes, which is what every caller before the browser could be missing meant. */
readonly canOpenInPreview?: boolean;
readonly showContextMenu: (
items: readonly ContextMenuItem<ExternalLinkContextMenuAction>[],
position: { readonly x: number; readonly y: number },
@@ -50,6 +66,7 @@ export function resolveExternalWebLinkHost(href: string | undefined): string | n
export async function showExternalLinkContextMenu({
href,
position,
canOpenInPreview = true,
showContextMenu,
openInPreview,
openExternal,
@@ -58,7 +75,7 @@ export async function showExternalLinkContextMenu({
}: ShowExternalLinkContextMenuOptions): Promise<void> {
let action: ExternalLinkContextMenuAction | null;
try {
action = await showContextMenu(EXTERNAL_LINK_CONTEXT_MENU_ITEMS, position);
action = await showContextMenu(externalLinkContextMenuItems({ canOpenInPreview }), position);
} catch (cause) {
reportFailure("show-link-context-menu", cause);
return;
@@ -0,0 +1,86 @@
import { RefreshCwIcon } from "lucide-react";
import type { ReactNode } from "react";
import { cn } from "../../lib/utils";
import { Button } from "../ui/button";
export function ClerkUserProfilePage({
action,
children,
className,
description,
title,
}: {
readonly action?: ReactNode;
readonly children: ReactNode;
readonly className?: string;
readonly description?: ReactNode;
readonly title: ReactNode;
}) {
return (
<div className={cn("w-full min-w-0 text-foreground", className)}>
<header className="flex flex-col gap-3 pb-4 sm:flex-row sm:items-start sm:justify-between sm:gap-4">
<div className="min-w-0">
<h2 className="text-[1.0625rem] leading-6 font-semibold">{title}</h2>
{description ? (
<p className="mt-1 max-w-[34rem] text-[0.8125rem] leading-[1.125rem] text-muted-foreground sm:min-h-9">
{description}
</p>
) : null}
</div>
{action ? <div className="shrink-0">{action}</div> : null}
</header>
{children}
</div>
);
}
export function ClerkUserProfileRefreshButton({
className,
disabled = false,
isPending,
onClick,
}: {
readonly className?: string;
readonly disabled?: boolean;
readonly isPending: boolean;
readonly onClick: () => void;
}) {
return (
<Button
size="sm"
variant="outline"
className={cn("text-[0.8125rem]", className)}
disabled={disabled || isPending}
onClick={onClick}
>
<RefreshCwIcon aria-hidden="true" className={cn("size-3.5", isPending && "animate-spin")} />
Refresh
</Button>
);
}
export function ClerkUserProfileRow({
children,
className,
icon,
}: {
readonly children: ReactNode;
readonly className?: string;
readonly icon: ReactNode;
}) {
return (
<li className={cn("border-t py-4 first:border-t-0", className)}>
<div className="flex items-start gap-3">
<div
aria-hidden="true"
className="flex size-8 shrink-0 items-center justify-center rounded-lg border bg-muted/32 text-muted-foreground"
>
{icon}
</div>
<div className="min-w-0 flex-1">{children}</div>
</div>
</li>
);
}
@@ -1,8 +1,7 @@
import type { RelayClientDeviceRecord } from "@t3tools/contracts/relay";
import { RefreshCwIcon, SmartphoneIcon } from "lucide-react";
import { SmartphoneIcon } from "lucide-react";
import { useManagedRelayDevices } from "../../cloud/managedRelayState";
import { cn } from "../../lib/utils";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "../ui/empty";
@@ -12,6 +11,11 @@ import {
mobileClientPlatformLabel,
mobileClientUpdatedAtLabel,
} from "./MobileClientsUserProfilePage.logic";
import {
ClerkUserProfilePage,
ClerkUserProfileRefreshButton,
ClerkUserProfileRow,
} from "./ClerkUserProfilePage";
const MOBILE_CLIENT_SKELETON_ROWS = ["primary", "secondary"] as const;
@@ -31,53 +35,47 @@ function MobileClientStatusBadge({
function MobileClientRow({ device }: { readonly device: RelayClientDeviceRecord }) {
return (
<li className="rounded-xl border bg-card p-4 text-card-foreground shadow-sm/4">
<div className="flex items-start gap-3">
<div className="flex size-9 shrink-0 items-center justify-center rounded-lg border bg-muted/40 text-muted-foreground">
<SmartphoneIcon className="size-4" />
</div>
<div className="min-w-0 flex-1">
<div className="flex flex-col gap-1 sm:flex-row sm:items-start sm:justify-between sm:gap-3">
<div className="min-w-0">
<h3 className="truncate text-sm font-semibold text-foreground">{device.label}</h3>
<p className="text-xs text-muted-foreground">{mobileClientPlatformLabel(device)}</p>
</div>
<p className="shrink-0 text-[11px] text-muted-foreground/75">
{mobileClientUpdatedAtLabel(device.updatedAt)}
</p>
</div>
<div className="mt-3 flex flex-wrap gap-1.5">
<MobileClientStatusBadge
enabled={device.notifications.enabled}
label="Push notifications"
/>
<MobileClientStatusBadge
enabled={device.liveActivities.enabled}
label="Live Activities"
/>
</div>
<p className="mt-2 text-xs leading-relaxed text-muted-foreground/80">
{mobileClientNotificationDetail(device)}
<ClerkUserProfileRow icon={<SmartphoneIcon className="size-4" />}>
<div className="flex flex-col gap-0.5 sm:flex-row sm:items-start sm:justify-between sm:gap-3">
<div className="min-w-0">
<h3 className="truncate text-[0.8125rem] leading-[1.125rem] font-medium text-foreground">
{device.label}
</h3>
<p className="text-xs leading-[1.125rem] text-muted-foreground">
{mobileClientPlatformLabel(device)}
</p>
</div>
<p className="shrink-0 text-[0.6875rem] leading-4 text-muted-foreground/75">
{mobileClientUpdatedAtLabel(device.updatedAt)}
</p>
</div>
</li>
<div className="mt-2 flex flex-wrap gap-1.5">
<MobileClientStatusBadge
enabled={device.notifications.enabled}
label="Push notifications"
/>
<MobileClientStatusBadge enabled={device.liveActivities.enabled} label="Live Activities" />
</div>
<p className="mt-1.5 text-xs leading-[1.125rem] text-muted-foreground/80">
{mobileClientNotificationDetail(device)}
</p>
</ClerkUserProfileRow>
);
}
function MobileClientsSkeleton() {
return (
<div aria-label="Loading mobile clients" className="space-y-3" role="status">
<div aria-label="Loading mobile clients" className="divide-y border-t" role="status">
{MOBILE_CLIENT_SKELETON_ROWS.map((row) => (
<div key={row} className="rounded-xl border p-4">
<div key={row} className="py-4">
<div className="flex gap-3">
<Skeleton className="size-9 shrink-0 rounded-lg" />
<Skeleton className="size-8 shrink-0 rounded-lg" />
<div className="flex-1 space-y-2">
<Skeleton className="h-4 w-36" />
<Skeleton className="h-3.5 w-36" />
<Skeleton className="h-3 w-28" />
<div className="flex gap-2 pt-1">
<Skeleton className="h-5 w-28" />
<Skeleton className="h-5 w-24" />
<div className="flex gap-2">
<Skeleton className="h-4.5 w-28" />
<Skeleton className="h-4.5 w-24" />
</div>
</div>
</div>
@@ -89,13 +87,13 @@ function MobileClientsSkeleton() {
function EmptyMobileClients() {
return (
<Empty className="min-h-72 rounded-xl border border-dashed bg-muted/15">
<EmptyMedia variant="icon">
<Empty className="min-h-64 gap-4 border-t px-6 py-10 md:p-10">
<EmptyMedia className="mb-0" variant="icon">
<SmartphoneIcon />
</EmptyMedia>
<EmptyHeader>
<EmptyTitle>No mobile clients</EmptyTitle>
<EmptyDescription>
<EmptyTitle className="text-[1.0625rem] leading-6">No mobile clients</EmptyTitle>
<EmptyDescription className="text-[0.8125rem] leading-[1.125rem]">
Sign in to T3 Code on your iPhone to register it for push notifications and Live
Activities.
</EmptyDescription>
@@ -112,29 +110,20 @@ export function MobileClientsUserProfilePage() {
const hasErrorWithoutData = devicesState.error !== null && devicesState.data === null;
return (
<div className="flex min-h-[30rem] w-full flex-col bg-background text-foreground">
<header className="flex flex-col gap-4 border-b px-6 py-5 sm:flex-row sm:items-center sm:justify-between">
<div>
<h2 className="text-base font-semibold tracking-[-0.01em]">Mobile clients</h2>
<p className="mt-1 text-sm text-muted-foreground">
Devices registered to receive T3 Connect activity from your environments.
</p>
</div>
<Button
size="sm"
variant="outline"
disabled={devicesState.isPending}
<ClerkUserProfilePage
title="Mobile clients"
description="Devices registered to receive T3 Connect activity from your environments."
action={
<ClerkUserProfileRefreshButton
isPending={devicesState.isPending}
onClick={devicesState.refresh}
>
<RefreshCwIcon className={cn("size-3.5", devicesState.isPending && "animate-spin")} />
Refresh
</Button>
</header>
<div className="flex-1 p-6">
/>
}
>
<div>
{devicesState.error ? (
<div
className="mb-4 flex flex-col gap-3 rounded-lg border border-destructive/25 bg-destructive/5 p-3 text-sm sm:flex-row sm:items-center sm:justify-between"
className="mb-4 flex flex-col gap-3 border-t border-destructive/35 py-3 text-[0.8125rem] sm:flex-row sm:items-center sm:justify-between"
role="alert"
>
<div>
@@ -152,7 +141,7 @@ export function MobileClientsUserProfilePage() {
{isInitialLoad ? (
<MobileClientsSkeleton />
) : hasErrorWithoutData ? null : devices.length > 0 ? (
<ul className="space-y-3">
<ul className="border-t">
{devices.map((device) => (
<MobileClientRow key={device.deviceId} device={device} />
))}
@@ -161,6 +150,6 @@ export function MobileClientsUserProfilePage() {
<EmptyMobileClients />
)}
</div>
</div>
</ClerkUserProfilePage>
);
}
@@ -1,9 +1,10 @@
import { UserButton, useAuth } from "@clerk/react";
import { LogInIcon, SmartphoneIcon } from "lucide-react";
import { LogInIcon, ServerIcon, SmartphoneIcon } from "lucide-react";
import { hasCloudPublicConfig } from "../../cloud/publicConfig";
import { SidebarMenu, SidebarMenuButton, SidebarMenuItem } from "../ui/sidebar";
import { MobileClientsUserProfilePage } from "./MobileClientsUserProfilePage";
import { T3ConnectUserProfilePage } from "./T3ConnectUserProfilePage";
import { useT3ConnectAuthPrompt } from "./useT3ConnectAuthPrompt";
export function T3ConnectSidebarSignIn() {
@@ -39,6 +40,13 @@ function ConfiguredT3ConnectSidebarAvatar() {
>
<MobileClientsUserProfilePage />
</UserButton.UserProfilePage>
<UserButton.UserProfilePage
label="T3 Connect"
labelIcon={<ServerIcon className="size-4" />}
url="t3-connect"
>
<T3ConnectUserProfilePage />
</UserButton.UserProfilePage>
</UserButton>
);
}
@@ -0,0 +1,63 @@
import type { EnvironmentId } from "@t3tools/contracts";
import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it, vi } from "vite-plus/test";
import { T3ConnectEnvironmentRow } from "./T3ConnectUserProfilePage";
const environment: RelayClientEnvironmentRecord = {
environmentId: "environment-1" as EnvironmentId,
label: "Studio Mac",
endpoint: {
httpBaseUrl: "https://studio.example.com",
wsBaseUrl: "wss://studio.example.com",
providerKind: "cloudflare_tunnel",
},
linkedAt: "2026-08-12T12:00:00.000Z",
};
function renderRow({
confirmationOpen = false,
mutationPending = false,
}: {
readonly confirmationOpen?: boolean;
readonly mutationPending?: boolean;
} = {}) {
return renderToStaticMarkup(
<T3ConnectEnvironmentRow
environment={environment}
confirmationOpen={confirmationOpen}
mutationPending={mutationPending}
onConfirmationChange={vi.fn()}
onDeregister={vi.fn()}
/>,
);
}
describe("T3 Connect environment row", () => {
it("keeps deregistration confirmation inline and collapsed by default", () => {
const markup = renderRow();
expect(markup).toContain("Studio Mac");
expect(markup).toContain("Deregister");
expect(markup).not.toContain("Deregister server");
expect(markup).not.toContain("Confirm deregistration of Studio Mac");
});
it("expands Clerk-style confirmation content beneath the environment row", () => {
const markup = renderRow({ confirmationOpen: true });
expect(markup).toContain("Deregister server");
expect(markup).toContain("“Studio Mac” will be removed from this account.");
expect(markup).toContain("Confirm deregistration of Studio Mac");
expect(markup).toContain("Local connections on your devices are not changed.");
expect(markup).toContain("Cancel");
});
it("locks the confirmation actions while deregistration is pending", () => {
const markup = renderRow({ confirmationOpen: true, mutationPending: true });
expect(markup).toContain("Deregistering…");
expect(markup.match(/ disabled=""/g)).toHaveLength(3);
});
});
@@ -0,0 +1,260 @@
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId } from "@t3tools/contracts";
import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";
import { ServerIcon } from "lucide-react";
import { useRef, useState } from "react";
import {
deregisterManagedRelayEnvironmentCommand,
useManagedRelayEnvironments,
} from "../../cloud/managedRelayState";
import { useAtomCommand } from "../../state/use-atom-command";
import { Button } from "../ui/button";
import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "../ui/empty";
import { toastManager } from "../ui/toast";
import {
ClerkUserProfilePage,
ClerkUserProfileRefreshButton,
ClerkUserProfileRow,
} from "./ClerkUserProfilePage";
const linkedAtFormatter = new Intl.DateTimeFormat(undefined, { dateStyle: "medium" });
function linkedAtLabel(value: string): string {
const linkedAt = new Date(value);
return Number.isNaN(linkedAt.getTime())
? "Link date unavailable"
: `Linked ${linkedAtFormatter.format(linkedAt)}`;
}
function endpointLabel(environment: RelayClientEnvironmentRecord): string {
return environment.endpoint.providerKind === "cloudflare_tunnel"
? "Managed tunnel"
: "Activity publishing only";
}
export function T3ConnectEnvironmentRow(props: {
readonly environment: RelayClientEnvironmentRecord;
readonly confirmationOpen: boolean;
readonly mutationPending: boolean;
readonly onConfirmationChange: (open: boolean) => void;
readonly onDeregister: (environment: RelayClientEnvironmentRecord) => void;
}) {
const { environment } = props;
return (
<ClerkUserProfileRow icon={<ServerIcon className="size-4" />}>
<Collapsible open={props.confirmationOpen} onOpenChange={props.onConfirmationChange}>
<div className="flex items-start gap-4">
<div className="min-w-0 flex-1">
<h3 className="truncate text-[0.8125rem] leading-[1.125rem] font-medium text-foreground">
{environment.label}
</h3>
<p className="mt-1 text-xs leading-[1.125rem] text-muted-foreground">
{linkedAtLabel(environment.linkedAt)} · {endpointLabel(environment)}
</p>
</div>
<CollapsibleTrigger
render={
<Button
size="sm"
variant="destructive-outline"
className="text-[0.8125rem]"
disabled={props.mutationPending}
>
Deregister
</Button>
}
/>
</div>
<CollapsiblePanel>
<div className="pt-3">
<div
className="rounded-lg border border-input bg-muted/32 px-5 py-4 shadow-xs/5"
role="group"
aria-label={`Confirm deregistration of ${environment.label}`}
>
<h4 className="text-[0.8125rem] leading-[1.125rem] font-semibold text-foreground">
Deregister server
</h4>
<p className="mt-1 text-[0.8125rem] leading-[1.125rem] text-muted-foreground">
“{environment.label}” will be removed from this account.
</p>
<p className="mt-4 max-w-xl text-[0.8125rem] leading-[1.125rem] text-muted-foreground">
T3 Connect access will be revoked, any managed tunnel will be removed, and a host
space will become available. Local connections on your devices are not changed.
</p>
<div className="mt-4 flex justify-end gap-2">
<Button
size="sm"
variant="ghost"
className="text-[0.8125rem]"
disabled={props.mutationPending}
onClick={() => props.onConfirmationChange(false)}
>
Cancel
</Button>
<Button
size="sm"
variant="destructive"
className="text-[0.8125rem]"
disabled={props.mutationPending}
onClick={() => props.onDeregister(environment)}
>
{props.mutationPending ? "Deregistering…" : "Deregister"}
</Button>
</div>
</div>
</div>
</CollapsiblePanel>
</Collapsible>
</ClerkUserProfileRow>
);
}
export function T3ConnectUserProfilePage() {
const environmentsState = useManagedRelayEnvironments();
const deregisterEnvironment = useAtomCommand(deregisterManagedRelayEnvironmentCommand, {
reportFailure: false,
});
const [deregisteringEnvironmentId, setDeregisteringEnvironmentId] =
useState<EnvironmentId | null>(null);
const [confirmingEnvironmentId, setConfirmingEnvironmentId] = useState<EnvironmentId | null>(
null,
);
const mutationPendingRef = useRef(false);
const [removedEnvironments, setRemovedEnvironments] = useState<{
readonly accountId: string | null;
readonly linkedAtById: ReadonlyMap<EnvironmentId, string>;
}>({ accountId: null, linkedAtById: new Map() });
const handleDeregister = async (environment: RelayClientEnvironmentRecord) => {
const accountId = environmentsState.accountId;
if (!accountId || mutationPendingRef.current) return;
mutationPendingRef.current = true;
setDeregisteringEnvironmentId(environment.environmentId);
const result = await deregisterEnvironment({
accountId,
environmentId: environment.environmentId,
});
mutationPendingRef.current = false;
setDeregisteringEnvironmentId(null);
if (result._tag === "Success") {
setConfirmingEnvironmentId(null);
setRemovedEnvironments((current) => {
const linkedAtById = new Map(current.accountId === accountId ? current.linkedAtById : []);
linkedAtById.set(environment.environmentId, environment.linkedAt);
return { accountId, linkedAtById };
});
environmentsState.refresh();
toastManager.add({
type: "success",
title: "Server deregistered",
description: "T3 Connect access was revoked and a host space is now available.",
});
return;
}
if (isAtomCommandInterrupted(result)) return;
const cause = squashAtomCommandFailure(result);
const message = cause instanceof Error ? cause.message : "Could not deregister the server.";
const traceId = findErrorTraceId(cause);
console.error("[t3-connect] Could not deregister environment", {
environmentId: environment.environmentId,
message,
traceId,
cause,
});
toastManager.add({
type: "error",
title: "Could not deregister server",
description: message,
data: traceId
? {
secondaryActionProps: {
children: "Copy trace ID",
onClick: () => void navigator.clipboard?.writeText(traceId),
},
}
: undefined,
});
};
const removedEnvironmentLinkedAt =
removedEnvironments.accountId === environmentsState.accountId
? removedEnvironments.linkedAtById
: new Map<EnvironmentId, string>();
const environments = (environmentsState.data ?? []).filter(
(environment) =>
removedEnvironmentLinkedAt.get(environment.environmentId) !== environment.linkedAt,
);
const isInitialLoad =
!environmentsState.accountId || (environmentsState.data === null && !environmentsState.error);
return (
<ClerkUserProfilePage
title="T3 Connect"
description="Environments registered to your account. Connections on this device are managed in Settings."
action={
<ClerkUserProfileRefreshButton
disabled={deregisteringEnvironmentId !== null}
isPending={environmentsState.isPending}
onClick={environmentsState.refresh}
/>
}
>
<div>
{environmentsState.error ? (
<div className="mb-4 border-t border-destructive/35 py-3 text-[0.8125rem]" role="alert">
<p className="font-medium text-destructive-foreground">
Could not load T3 Connect environments
</p>
<p className="mt-1 text-xs text-muted-foreground">{environmentsState.error}</p>
</div>
) : null}
{isInitialLoad ? (
<p className="border-t py-4 text-[0.8125rem] text-muted-foreground" role="status">
Loading environments…
</p>
) : environments.length > 0 ? (
<ul className="border-t">
{environments.map((environment) => (
<T3ConnectEnvironmentRow
key={environment.environmentId}
environment={environment}
confirmationOpen={confirmingEnvironmentId === environment.environmentId}
mutationPending={deregisteringEnvironmentId !== null}
onConfirmationChange={(open) =>
setConfirmingEnvironmentId(open ? environment.environmentId : null)
}
onDeregister={(selected) => void handleDeregister(selected)}
/>
))}
</ul>
) : environmentsState.error ? null : (
<Empty className="min-h-64 gap-4 border-t px-6 py-10 md:p-10">
<EmptyMedia className="mb-0" variant="icon">
<ServerIcon />
</EmptyMedia>
<EmptyHeader>
<EmptyTitle className="text-[1.0625rem] leading-6">
No T3 Connect environments
</EmptyTitle>
<EmptyDescription className="text-[0.8125rem] leading-[1.125rem]">
Link an environment from its local Settings to make it available through T3 Connect.
</EmptyDescription>
</EmptyHeader>
</Empty>
)}
</div>
</ClerkUserProfilePage>
);
}
@@ -0,0 +1,91 @@
import { describe, expect, it } from "vite-plus/test";
import {
EMBER_THEME,
GROVE_THEME,
IRIS_THEME,
OCEAN_THEME,
T3_CHAT_THEME,
themeColorToHex,
type ThemeColors,
} from "../../themePalette";
import { clerkAppearance } from "./clerkAppearance";
function contrastRatio(first: string, second: string): number {
const toRgb = (value: string) => {
const hex = themeColorToHex(value)?.slice(1, 7);
if (!hex) throw new Error(`Expected a theme color, received ${value}`);
return [0, 1, 2].map(
(channel) => Number.parseInt(hex.slice(channel * 2, channel * 2 + 2), 16) / 255,
);
};
const luminance = (value: string) =>
toRgb(value)
.map((channel) => (channel <= 0.03928 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4))
.reduce((sum, channel, index) => sum + channel * [0.2126, 0.7152, 0.0722][index]!, 0);
const lighter = Math.max(luminance(first), luminance(second));
const darker = Math.min(luminance(first), luminance(second));
return (lighter + 0.05) / (darker + 0.05);
}
function mixThemeColors(first: string, second: string, firstWeight: number): string {
const channels = [first, second].map((value) => {
const hex = themeColorToHex(value)?.slice(1, 7);
if (!hex) throw new Error(`Expected a theme color, received ${value}`);
return [0, 1, 2].map((channel) => Number.parseInt(hex.slice(channel * 2, channel * 2 + 2), 16));
});
const mixed = channels[0]!.map((channel, index) =>
Math.round(channel * firstWeight + channels[1]![index]! * (1 - firstWeight)),
);
return `#${mixed.map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
}
const builtInThemeModes = [
T3_CHAT_THEME,
GROVE_THEME,
OCEAN_THEME,
EMBER_THEME,
IRIS_THEME,
].flatMap((theme) =>
[theme.colors, theme.variants?.dark].filter((colors): colors is ThemeColors => !!colors),
);
describe("clerkAppearance", () => {
it("maps theme colors without overriding Clerk's component structure", () => {
expect(clerkAppearance).toEqual({
variables: {
colorPrimary: "var(--update-foreground)",
colorPrimaryForeground: "var(--card)",
colorDanger: "var(--error)",
colorSuccess: "var(--success)",
colorWarning: "var(--warning)",
colorNeutral: "var(--foreground)",
colorForeground: "var(--foreground)",
colorMuted: "color-mix(in srgb, var(--card) 98%, var(--foreground))",
colorMutedForeground: "var(--muted-foreground)",
colorBackground: "var(--card)",
colorInputForeground: "var(--foreground)",
colorInput: "var(--secondary)",
colorRing: "var(--ring)",
},
elements: {
formFieldErrorText: { color: "var(--error-foreground)" },
formFieldWarningText: { color: "var(--warning-foreground)" },
formFieldSuccessText: { color: "var(--success-foreground)" },
otpCodeFieldErrorText: { color: "var(--error-foreground)" },
otpCodeFieldSuccessText: { color: "var(--success-foreground)" },
},
});
});
it.each(builtInThemeModes)("keeps Clerk text readable across a built-in palette", (colors) => {
const mutedSurface = mixThemeColors(colors.surface, colors.text, 0.98);
expect(contrastRatio(colors.text, colors.surface)).toBeGreaterThanOrEqual(4.5);
expect(contrastRatio(colors.mutedForeground, mutedSurface)).toBeGreaterThanOrEqual(4.5);
expect(contrastRatio(colors.text, colors.secondary)).toBeGreaterThanOrEqual(4.5);
expect(contrastRatio(colors.updateForeground, colors.surface)).toBeGreaterThanOrEqual(4.5);
expect(contrastRatio(colors.errorForeground, colors.surface)).toBeGreaterThanOrEqual(4.5);
expect(contrastRatio(colors.warningForeground, colors.surface)).toBeGreaterThanOrEqual(4.5);
});
});
@@ -0,0 +1,34 @@
import type { ClerkProviderProps } from "@clerk/react";
/** Keeps Clerk's stock component structure while binding its color system to
* the live T3 Code palette. CSS variables make theme changes propagate to
* portaled sign-in and profile surfaces without remounting Clerk. */
export const clerkAppearance = {
variables: {
// Clerk reuses its primary color for filled buttons and bare links. The
// app's update foreground is the palette's action hue cast for readable
// text, while the card surface provides the inverse filled-control pair.
colorPrimary: "var(--update-foreground)",
colorPrimaryForeground: "var(--card)",
colorDanger: "var(--error)",
colorSuccess: "var(--success)",
colorWarning: "var(--warning)",
colorNeutral: "var(--foreground)",
colorForeground: "var(--foreground)",
// The stock dark theme's muted token is translucent. Clerk uses this as
// the footer's background, so derive an opaque muted surface from the card.
colorMuted: "color-mix(in srgb, var(--card) 98%, var(--foreground))",
colorMutedForeground: "var(--muted-foreground)",
colorBackground: "var(--card)",
colorInputForeground: "var(--foreground)",
colorInput: "var(--secondary)",
colorRing: "var(--ring)",
},
elements: {
formFieldErrorText: { color: "var(--error-foreground)" },
formFieldWarningText: { color: "var(--warning-foreground)" },
formFieldSuccessText: { color: "var(--success-foreground)" },
otpCodeFieldErrorText: { color: "var(--error-foreground)" },
otpCodeFieldSuccessText: { color: "var(--success-foreground)" },
},
} satisfies NonNullable<ClerkProviderProps["appearance"]>;
@@ -44,8 +44,10 @@ const invalidLinkMessage = {
} as const;
/**
* /connect: the URL a headless CLI prints. Waits for a Clerk session, then
* forwards the CLI's PKCE request to Clerk's authorize endpoint.
* /connect: the URL the CLI prints for both flows. Waits for a Clerk session,
* then forwards the CLI's PKCE request to Clerk's authorize endpoint — with a
* loopback redirect URI when the request carries a port, so the code returns
* straight to the waiting CLI, and the hosted callback page otherwise.
*/
export function ConnectCliAuthorizeSurface() {
const [request] = useState(() => readConnectAuthorizeRequest(new URL(window.location.href)));
@@ -85,7 +87,11 @@ export function ConnectCliAuthorizeSurface() {
return (
<AuthSurfaceShell>
<ConnectCliAuthMessage
eyebrow="Step 1 of 2 · Browser authorization"
eyebrow={
request.loopbackPort === undefined
? "Step 1 of 2 · Browser authorization"
: "Browser authorization"
}
title="Connecting your terminal"
description={
isSignedIn
@@ -18,7 +18,7 @@ function ReleaseNotesLink({
}) {
return (
<button
className="ml-2 inline-flex cursor-pointer items-center gap-1 align-baseline text-muted-foreground underline decoration-dotted underline-offset-4 transition-colors hover:text-foreground"
className="ml-2 inline cursor-pointer text-muted-foreground underline decoration-dotted underline-offset-4 transition-colors hover:text-foreground"
onClick={() => {
void (async () => {
try {
@@ -32,7 +32,11 @@ function ReleaseNotesLink({
type="button"
>
Read more
<ArrowRightIcon aria-hidden className="size-3 -rotate-45" strokeWidth={2.25} />
<ArrowRightIcon
aria-hidden
className="ml-1 inline size-3 -rotate-45 align-[-0.125em]"
strokeWidth={2.25}
/>
</button>
);
}
@@ -269,6 +269,11 @@ type StyledDiffCodeViewProps<LAnnotation> = (
) & {
readonly options?: StyledDiffCodeViewOptions<LAnnotation>;
readonly viewerRef?: Ref<CodeViewHandle<LAnnotation>>;
/**
* Appended to the shared stylesheet inside the viewer's shadow root, for a surface that has
* to restyle chrome the viewer owns — such as replacing its per-file line counts.
*/
readonly unsafeCSSExtra?: string;
};
/** The shared web CodeView surface: app styling and virtualized geometry stay paired here. */
@@ -276,6 +281,7 @@ export function StyledDiffCodeView<LAnnotation = undefined>({
options,
viewerRef,
className,
unsafeCSSExtra,
...props
}: StyledDiffCodeViewProps<LAnnotation>) {
return (
@@ -291,7 +297,9 @@ export function StyledDiffCodeView<LAnnotation = undefined>({
}
options={{
...options,
unsafeCSS: DIFF_VIEW_UNSAFE_CSS,
unsafeCSS: unsafeCSSExtra
? `${DIFF_VIEW_UNSAFE_CSS}\n${unsafeCSSExtra}`
: DIFF_VIEW_UNSAFE_CSS,
itemMetrics: {
diffHeaderHeight: 32,
hunkSeparatorHeight: 24,
@@ -0,0 +1,134 @@
import type {
EnvironmentId,
PullRequestCheck,
PullRequestChecksState,
PullRequestRef,
} from "@t3tools/contracts";
import { readLocalApi } from "~/localApi";
import { cn } from "~/lib/utils";
import { pullRequestEnvironment } from "~/state/pullRequests";
import { useEnvironmentQuery } from "~/state/query";
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
import {
PullRequestCheckStatusIcon,
pullRequestCheckStatusLabel,
pullRequestChecksStatePresentation,
summarizePullRequestChecks,
} from "./pullRequestPresentation";
/**
* The checks behind the rollup, for a row that only carries the rollup. Mounted by the popup, so
* the read starts when somebody opens it rather than once per row of a listing — the detail read
* is a request per pull request, and a page of them at rest would be a hundred.
*/
function LazyChecksBody({
environmentId,
reference,
}: {
environmentId: EnvironmentId;
reference: PullRequestRef;
}) {
const detailQuery = useEnvironmentQuery(
pullRequestEnvironment.detail({ environmentId, input: reference }),
);
if (detailQuery.error !== null) {
return <p className="text-muted-foreground text-xs">{detailQuery.error}</p>;
}
if (detailQuery.data === null) {
return (
<p className="text-muted-foreground text-xs">
{detailQuery.isPending ? "Loading checks…" : "No checks reported"}
</p>
);
}
return <ChecksBody checks={detailQuery.data.checks} />;
}
function ChecksBody({ checks }: { checks: ReadonlyArray<PullRequestCheck> }) {
if (checks.length === 0) {
return <p className="text-muted-foreground text-xs">No checks reported</p>;
}
return (
<ul className="flex flex-col gap-1">
{/* Keyed by position as well as by name: the host is the one that decides how many runs
share a name, and a repeated key is a rendering fault rather than a wrong list. */}
{checks.map((check, index) => (
<li key={`${index}:${check.name}`} className="flex items-center gap-2 text-xs">
<PullRequestCheckStatusIcon status={check.status} />
<span className="min-w-0 flex-1 truncate" title={check.description ?? check.name}>
{check.name}
</span>
<span className="shrink-0 text-muted-foreground">
{pullRequestCheckStatusLabel(check.status)}
</span>
{check.url === null ? null : (
<button
type="button"
className="shrink-0 text-primary hover:underline"
onClick={() => void readLocalApi()?.shell.openExternal(check.url ?? "")}
>
Details
</button>
)}
</li>
))}
</ul>
);
}
/**
* The checks indicator and what it opens, in both places a change request is shown: a listing
* row, which knows only the rollup, and the detail header, which is already holding every check.
*
* `checks` decides between the two. Given them, nothing is read; without them, the popup reads
* the detail itself, which is why the row must also say which environment it came from.
*/
export function PullRequestChecksPopover({
checksState,
checks,
environmentId,
reference,
className,
}: {
checksState: PullRequestChecksState;
/** The checks already in hand, for the detail header. Absent on a listing row. */
checks?: ReadonlyArray<PullRequestCheck>;
environmentId?: EnvironmentId;
reference?: PullRequestRef;
className?: string;
}) {
const presentation = pullRequestChecksStatePresentation(checksState);
// Counts beat the rollup's own wording where they are known, the way GitHub's own header reads.
const summary = checks === undefined ? null : summarizePullRequestChecks(checks);
return (
<Popover>
{/* A listing row is itself a button, so the trigger renders as a span: a nested button is
not valid inside one. The click is stopped here so opening the checks does not also
select the row it sits on. */}
<PopoverTrigger
render={
<span
role="button"
tabIndex={0}
aria-label={`Checks: ${presentation.label}`}
className={cn("inline-flex shrink-0 cursor-pointer items-center", className)}
/>
}
onClick={(event) => event.stopPropagation()}
>
<presentation.Icon aria-hidden className={cn("size-3.5", presentation.toneClassName)} />
</PopoverTrigger>
<PopoverPopup align="start" className="w-80 max-w-full" side="bottom">
<p className="mb-2 font-medium text-sm">{presentation.label}</p>
{summary === null ? null : <p className="mb-2 text-muted-foreground text-xs">{summary}</p>}
{checks !== undefined ? (
<ChecksBody checks={checks} />
) : environmentId !== undefined && reference !== undefined ? (
<LazyChecksBody environmentId={environmentId} reference={reference} />
) : null}
</PopoverPopup>
</Popover>
);
}
@@ -4,6 +4,7 @@ import type {
EnvironmentId,
PullRequestDetailView,
PullRequestDiffSide,
PullRequestOmittedFileStat,
PullRequestRef,
PullRequestReviewThread,
} from "@t3tools/contracts";
@@ -28,6 +29,8 @@ import { useClientSettings } from "~/hooks/useSettings";
import { useTheme } from "~/hooks/useTheme";
import { areAllDiffFilesCollapsed } from "~/lib/diffCollapse";
import { pullRequestFindingKey, type PullRequestFinding } from "./pullRequestDetail.logic";
import { canEditPullRequestComment } from "./pullRequestEditing.logic";
import { orderDiffFiles } from "./pullRequestFileOrder.logic";
import {
buildFileDiffRenderKey,
fnv1a32,
@@ -95,8 +98,20 @@ interface DiffSlice {
readonly patch: string;
readonly truncated: boolean;
readonly nextCursor: string | null;
readonly omittedFileStats: ReadonlyArray<PullRequestOmittedFileStat>;
}
/**
* The viewer's own per-file counts are hidden and drawn from this side of its shadow root
* instead: its counts are hunk sums, and a file whose hunks the host withheld would read as
* an empty change rather than as the counts the host did report.
*/
const REPLACE_FILE_COUNTS_CSS = `
[data-diffs-header] [data-additions-count],
[data-diffs-header] [data-deletions-count] {
display: none !important;
}`;
/** Nothing loaded yet, as one identity, so the memos below do not see a new array every render. */
const NO_SLICES: ReadonlyArray<DiffSlice> = [];
@@ -155,6 +170,7 @@ export function PullRequestCodeTab({
selectedCommitOid,
onSelectedCommitChange,
pendingFinding,
fixFindingLabel = "Fix in a thread",
onFixFinding,
onAskAboutSelection,
onRefresh,
@@ -168,6 +184,7 @@ export function PullRequestCodeTab({
onSelectedCommitChange: (oid: string | null) => void;
/** The hand-off currently preparing, if any, so only the finding it belongs to says so. */
pendingFinding?: string | null;
fixFindingLabel?: string;
onFixFinding?: (finding: PullRequestFinding) => void;
/** Absent where a selection has no agent to go to, which takes the Ask button off the box. */
onAskAboutSelection?: (input: PullRequestAskSelectionInput) => void;
@@ -246,6 +263,7 @@ export function PullRequestCodeTab({
patch: data.patch,
truncated: data.truncated,
nextCursor: data.nextCursor,
omittedFileStats: data.omittedFileStats ?? [],
};
const index = slices.findIndex((slice) => slice.cursor === cursor);
if (index === -1) {
@@ -256,7 +274,17 @@ export function PullRequestCodeTab({
existing !== undefined &&
existing.patch === next.patch &&
existing.truncated === next.truncated &&
existing.nextCursor === next.nextCursor
existing.nextCursor === next.nextCursor &&
existing.omittedFileStats.length === next.omittedFileStats.length &&
existing.omittedFileStats.every((file, index) => {
const refreshed = next.omittedFileStats[index];
return (
refreshed !== undefined &&
refreshed.path === file.path &&
refreshed.additions === file.additions &&
refreshed.deletions === file.deletions
);
})
) {
return previous;
}
@@ -290,6 +318,9 @@ export function PullRequestCodeTab({
const setThreadResolution = useAtomCommand(pullRequestEnvironment.setThreadResolution, {
reportFailure: false,
});
const updateComment = useAtomCommand(pullRequestEnvironment.updateComment, {
reportFailure: false,
});
const getDiffFileContents = useAtomCommand(pullRequestEnvironment.diffFileContents);
const loadDiffFiles = useMemo(
() =>
@@ -337,16 +368,12 @@ export function PullRequestCodeTab({
}),
[loadedSlices, resolvedTheme, scopeKey],
);
// Sorted within a slice rather than across them: sorting the accumulated set would let a late
// Ordered within a slice rather than across them: ordering the accumulated set would let a late
// slice push a file the reader is part way through further down the page.
const files = useMemo(
() =>
parsedSlices.flatMap((parsed) =>
parsed?.kind === "files"
? parsed.files.toSorted((left, right) =>
resolveFileDiffPath(left).localeCompare(resolveFileDiffPath(right)),
)
: [],
parsed?.kind === "files" ? orderDiffFiles(parsed.files) : [],
),
[parsedSlices],
);
@@ -449,7 +476,13 @@ export function PullRequestCodeTab({
}:${thread.comments
.map(
(comment) =>
`${comment.id}:${comment.author?.login ?? ""}:${comment.createdAt}:${comment.body}`,
`${comment.id}:${comment.author?.login ?? ""}:${comment.createdAt}:${comment.body}:${(
comment.reactions ?? []
)
.map(
(r) => `${r.content}:${r.count}:${r.viewerHasReacted ? "v" : ""}`,
)
.join(",")}`,
)
.join(";")}`,
)
@@ -471,6 +504,15 @@ export function PullRequestCodeTab({
],
);
const lineStat = useMemo(() => getDiffLineStat(files), [files]);
const omittedFileStats = useMemo(
() =>
new Map(
loadedSlices.flatMap((slice) =>
slice.omittedFileStats.map((file) => [file.path, file] as const),
),
),
[loadedSlices],
);
const fileKeys = useMemo(() => items.map((item) => item.id), [items]);
const collapsedFileKeys = useMemo(
() => new Set(items.filter((item) => item.collapsed === true).map((item) => item.id)),
@@ -649,6 +691,30 @@ export function PullRequestCodeTab({
[toggleFile],
);
const renderHeaderMetadata = useCallback(
(item: CodeViewItem<ReviewAnnotationGroup>) => {
if (item.type !== "diff") return null;
let additions = 0;
let deletions = 0;
for (const hunk of item.fileDiff.hunks) {
additions += hunk.additionLines;
deletions += hunk.deletionLines;
}
if (additions === 0 && deletions === 0) {
const withheld = omittedFileStats.get(resolveFileDiffPath(item.fileDiff));
if (withheld) ({ additions, deletions } = withheld);
}
return (
<PullRequestDiffStat
additions={additions}
deletions={deletions}
className="font-mono text-[11px]"
/>
);
},
[omittedFileStats],
);
const diffViewOptions = useMemo(
() => ({
diffStyle: diffRenderMode === "split" ? ("split" as const) : ("unified" as const),
@@ -699,13 +765,20 @@ export function PullRequestCodeTab({
const renderThreadCard = useCallback(
(thread: PullRequestReviewThread) => (
<ReviewThreadCard
key={thread.id}
// Named with the pull request too: a thread's id is the host's own, and two pull requests
// can hand out the same one — which would leave one card's open editor standing over the
// other's conversation.
key={`${reference.projectId}#${reference.number}:${thread.id}`}
thread={thread}
workspaceRoot={detail.workspaceRoot}
canReply={review.reply}
canResolve={review.resolve}
canReact={detail.capabilities.reactions === true}
environmentId={environmentId}
reference={reference}
pending={threadPending}
fixPending={pendingFinding === pullRequestFindingKey({ kind: "thread", thread })}
fixLabel={fixFindingLabel}
{...(onFixFinding ? { onFix: () => onFixFinding({ kind: "thread", thread }) } : {})}
onReply={(body) =>
runThreadCommand("Reply could not be posted", () =>
@@ -715,6 +788,18 @@ export function PullRequestCodeTab({
}),
)
}
// A conversation on a line is made of review comments, whatever the host filed them as.
canEditComment={(comment) =>
canEditPullRequestComment(detail, { author: comment.author, kind: "review-comment" })
}
onEditComment={(commentId, body) =>
runThreadCommand("The comment could not be saved", () =>
updateComment({
environmentId,
input: { ...reference, commentId, kind: "review-comment", body },
}),
)
}
onToggleResolved={() =>
void runThreadCommand("The conversation could not be updated", () =>
setThreadResolution({
@@ -723,11 +808,14 @@ export function PullRequestCodeTab({
}),
)
}
onReacted={onRefresh}
/>
),
[
detail.workspaceRoot,
detail,
environmentId,
fixFindingLabel,
onRefresh,
onFixFinding,
pendingFinding,
reference,
@@ -737,12 +825,13 @@ export function PullRequestCodeTab({
runThreadCommand,
setThreadResolution,
threadPending,
updateComment,
],
);
const renderAnnotation = useCallback(
(annotation: ReviewAnnotation) => (
<div className="py-1">
<div className="py-1 font-sans text-foreground">
{annotation.metadata.threads.map(renderThreadCard)}
{annotation.metadata.pending.map((comment) => (
<PendingReviewCommentCard
@@ -1222,7 +1311,9 @@ export function PullRequestCodeTab({
// is running out of diff.
renderCodeViewFooter={renderCodeViewFooter}
renderHeaderPrefix={renderHeaderPrefix}
renderHeaderMetadata={renderHeaderMetadata}
renderAnnotation={renderAnnotation}
unsafeCSSExtra={REPLACE_FILE_COUNTS_CSS}
/>
{reviewOverlay}
</div>
@@ -1,11 +1,13 @@
import { scopeProjectRef } from "@t3tools/client-runtime/environment";
import { scopedThreadKey, scopeProjectRef } from "@t3tools/client-runtime/environment";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import type {
EnvironmentId,
PullRequestAction,
PullRequestMergeMethod,
PullRequestUpdateMethod,
PullRequestRef,
PullRequestState,
ScopedThreadRef,
} from "@t3tools/contracts";
import {
ArrowDownUpIcon,
@@ -28,12 +30,15 @@ import {
LinkIcon,
MoreHorizontalIcon,
PanelRightIcon,
PencilIcon,
RefreshCwIcon,
ServerIcon,
TriangleAlertIcon,
} from "lucide-react";
import {
lazy,
Suspense,
type MouseEvent as ReactMouseEvent,
useCallback,
useEffect,
useLayoutEffect,
@@ -49,6 +54,8 @@ import { usePreparePullRequestThreadAction } from "~/lib/sourceControlActions";
import { cn } from "~/lib/utils";
import { readLocalApi } from "~/localApi";
import type { ReviewCommentContext } from "~/reviewCommentContext";
import { useProjects } from "~/state/entities";
import { useEnvironments } from "~/state/environments";
import { useEnvironmentQuery } from "~/state/query";
import { useLiveRefresh } from "~/hooks/useLiveRefresh";
import { pullRequestEnvironment } from "~/state/pullRequests";
@@ -66,6 +73,7 @@ import {
} from "../ui/alert-dialog";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import {
Menu,
MenuItem,
@@ -75,12 +83,14 @@ import {
MenuSeparator,
MenuTrigger,
} from "../ui/menu";
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
import { toastManager } from "../ui/toast";
import { PullRequestDetailGhost, PullRequestTimelineGhost } from "./PullRequestGhosts";
import { PullRequestActivityUnavailableState } from "./PullRequestActivityUnavailableState";
import { DiffPanelLoadingState } from "../DiffPanelShell";
import { PullRequestsUnavailableState } from "./PullRequestsUnavailableState";
import type { PullRequestAskSelectionInput } from "./PullRequestCodeTab";
import { openOnHostLabel, showPullRequestLinkContextMenu } from "./pullRequestLinkContextMenu";
import { PullRequestSummaryTab } from "./PullRequestSummaryTab";
import { PullRequestTimelineTab } from "./PullRequestTimelineTab";
import {
@@ -92,14 +102,24 @@ import {
buildResolveConflictsPrompt,
handoffPrompt,
handoffReviewComments,
pullRequestActionNeedsHostRefresh,
pullRequestFindingKey,
pullRequestHandoffLabels,
readableFailure,
resolveBaseFreshness,
type PullRequestFinding,
} from "./pullRequestDetail.logic";
import { canEditPullRequestChangeRequest } from "./pullRequestEditing.logic";
import {
resolvePickableEnvironments,
type PickableEnvironment,
} from "./pullRequestProjectAssignment.logic";
import { PullRequestChecksPopover } from "./PullRequestChecksPopover";
import {
PullRequestActorLabel,
PullRequestDiffStat,
PullRequestMetaLine,
pullRequestChecksState,
resolvePullRequestState,
summarizePullRequestChecks,
} from "./pullRequestPresentation";
@@ -112,6 +132,12 @@ const ACTION_SUCCESS_LABELS: Record<PullRequestAction, string> = {
draft: "Converted to draft",
close: "Pull request closed",
reopen: "Pull request reopened",
"update-branch": "Branch updated with the base branch",
// True whichever it did: a pull request that was already mergeable merges the moment this is
// armed, and the client has no way to tell that apart from one still waiting on something.
"enable-auto-merge":
"Auto-merge turned on — merges as soon as this is ready, sooner if it already is",
"disable-auto-merge": "Auto-merge turned off",
};
/** Said as the thing that did not happen, rather than as the operation that returned an error. */
@@ -121,6 +147,9 @@ const ACTION_FAILURE_LABELS: Record<PullRequestAction, string> = {
draft: "Could not convert this to a draft",
close: "Could not close this pull request",
reopen: "Could not reopen this pull request",
"update-branch": "Could not update this branch",
"enable-auto-merge": "Could not turn on auto-merge",
"disable-auto-merge": "Could not turn off auto-merge",
};
/** What to try, for the times the host says only that it refused. */
@@ -132,15 +161,25 @@ const ACTION_FAILURE_HINTS: Record<PullRequestAction, string> = {
close: "The host refused it. Check that you have write access, or that you opened it.",
reopen:
"The host refused it. Check that you have write access, and that the branch still exists.",
// Said for the merge commit, which is what an update is unless a rebase was asked for. The
// rebase has its own reasons to fail and its own sentence below.
"update-branch":
"The host refused it. Check that you have write access to the branch — one from a fork also needs its author to allow edits from maintainers — and that it does not conflict with the base.",
// The one refusal that is usually a repository setting rather than anything about this branch:
// GitHub will not arm an auto-merge at all unless the repository has the feature switched on.
"enable-auto-merge":
"The host refused it. Check that this repository allows auto-merge, that you have write access, and that there is something left for it to wait on.",
"disable-auto-merge":
"The host refused it. Check that you have write access, and that the merge has not already happened.",
};
/** Named for the host rather than "externally": the point is where you will land. */
const OPEN_ON_HOST_LABELS: Partial<Record<string, string>> = {
github: "Open on GitHub",
gitlab: "Open on GitLab",
bitbucket: "Open on Bitbucket",
"azure-devops": "Open on Azure DevOps",
};
/**
* Said instead of the update hint when the reader asked for a rebase: it is the one that fails on
* its own merits, because GitHub replays the commits and stops at the first that does not apply.
* Offering the merge commit only makes sense to somebody who did not already choose it.
*/
const UPDATE_BRANCH_REBASE_FAILURE_HINT =
"The host refused it. A rebase stops at the first commit that does not apply cleanly; updating with a merge commit may still work.";
const TABS: ReadonlyArray<{ value: DetailTab; label: string }> = [
{ value: "summary", label: "Summary" },
@@ -159,7 +198,148 @@ const PullRequestCodeTab = lazy(loadCodeTab);
* is closed by the time the next one opens. It is how a prompt the reader has since edited is told
* apart from the one they were handed: only the sentence still exactly as written may be replaced.
*/
const lastHandoffPromptByDraft = new Map<DraftId, string>();
const lastHandoffPromptByDraft = new Map<string, string>();
const composerTargetKey = (target: ScopedThreadRef | DraftId): string =>
typeof target === "string" ? target : scopedThreadKey(target);
/**
* Which server the checkout and the hand-offs land on, where more than one of them holds this
* repository. The list picked one of them to show the pull request under, so that everything on
* it is read from somewhere; where the reader wants to work is a separate answer, and this is
* where they give it.
*/
function ActOnEnvironmentPicker({
environments,
value,
onChange,
disabled,
}: {
environments: ReadonlyArray<PickableEnvironment>;
value: EnvironmentId;
onChange: (environmentId: EnvironmentId) => void;
disabled: boolean;
}) {
return (
<>
<MenuSeparator />
<MenuRadioGroup
value={value}
onValueChange={(environmentId) => onChange(environmentId as EnvironmentId)}
>
{environments.map((environment) => (
<MenuRadioItem
key={environment.environmentId}
value={environment.environmentId}
disabled={disabled}
>
{/* The radio item lays its children out as one block, so the icon and the label
need their own row to share a line. */}
<span className="flex min-w-0 items-center gap-2">
<ServerIcon className="size-3.5 shrink-0" />
<span className="truncate">{environment.label}</span>
</span>
</MenuRadioItem>
))}
</MenuRadioGroup>
</>
);
}
/** The number is a link in every place the host writes it, so the right-click that copies one
has to answer here too — otherwise the platform's own cut/paste menu opens over it. */
const openNumberContextMenu = (
event: ReactMouseEvent,
detail: { readonly url: string; readonly provider: string },
): void => {
event.preventDefault();
event.stopPropagation();
void showPullRequestLinkContextMenu({
url: detail.url,
openLabel: openOnHostLabel(detail.provider),
position: { x: event.clientX, y: event.clientY },
});
};
/**
* The stale-branch warning, said beside the branch it is about rather than as a bar of its own.
* The banner this replaces held a row of chrome open across the top of every pull request that
* had fallen behind, pushing the reading down to say something that is true of the base branch
* and nothing else; as a mark on the base branch it is where a reader would look for it, and the
* sentence and the way out of it arrive together the moment the mark is pointed at.
*
* A popover rather than a tooltip because what it holds can be pressed: a tooltip's layer takes
* no pointer, and a control nobody can reach is worse than no control.
*/
function PullRequestBaseFreshnessWarning({
baseBranch,
freshness,
pending,
onUpdate,
iconClassName,
}: {
readonly baseBranch: string;
readonly freshness: {
readonly behindBy: number | null;
readonly methods: ReadonlyArray<PullRequestUpdateMethod>;
};
readonly pending: boolean;
readonly onUpdate: (method: PullRequestUpdateMethod) => void;
readonly iconClassName?: string;
}) {
const behind =
freshness.behindBy === null
? ""
: ` by ${freshness.behindBy.toLocaleString()} ${
freshness.behindBy === 1 ? "commit" : "commits"
}`;
const summary = `This branch is out-of-date with ${baseBranch}${behind}.`;
return (
<Popover>
<PopoverTrigger
openOnHover
delay={0}
closeDelay={120}
render={
<button
type="button"
aria-label={summary}
className="inline-flex shrink-0 cursor-help items-center rounded-sm text-amber-600 outline-none focus-visible:ring-2 focus-visible:ring-ring"
/>
}
>
<TriangleAlertIcon aria-hidden className={cn("size-3.5", iconClassName)} />
</PopoverTrigger>
<PopoverPopup
align="start"
side="bottom"
className="max-w-80"
viewportClassName="py-2.5 [--viewport-inline-padding:--spacing(3)]"
>
<p className="text-xs text-foreground">{summary}</p>
<p className="mt-0.5 text-xs text-muted-foreground">Changes can be cleanly merged.</p>
{/* Each way the host offers and this reader may take, as its own button: a split button
would need a menu inside a popover, and two buttons say the same thing in one layer. */}
{freshness.methods.length > 0 ? (
<span className="mt-2 flex flex-wrap items-center gap-1.5">
{freshness.methods.map((method) => (
<Button
key={method}
size="xs"
variant="outline"
disabled={pending}
onClick={() => onUpdate(method)}
>
<GitMergeIcon aria-hidden className="size-3" />
{method === "rebase" ? "Update with rebase" : "Update branch"}
</Button>
))}
</span>
) : null}
</PopoverPopup>
</Popover>
);
}
export function PullRequestDetailPanel({
environmentId,
@@ -170,6 +350,7 @@ export function PullRequestDetailPanel({
onStateChange,
context = "page",
chromeVariant = "full",
composerDraftTarget,
}: {
environmentId: EnvironmentId;
reference: PullRequestRef;
@@ -206,6 +387,11 @@ export function PullRequestDetailPanel({
* top — the chrome spends its height on what is being read.
*/
chromeVariant?: "full" | "collapse";
/**
* The open thread's composer. Beside the thread whose own pull request this is, hand-offs
* land here instead of opening a new thread — the branch is already under the reader's feet.
*/
composerDraftTarget?: ScopedThreadRef | DraftId;
}) {
const pullRequestKey = `${reference.projectId}:${reference.repository}#${reference.number}`;
const [tab, setTab] = useState<DetailTab>("summary");
@@ -267,7 +453,9 @@ export function PullRequestDetailPanel({
if (scroller) scroller.scrollTop = Math.max(0, scroller.scrollTop + delta);
}, [condensed]);
const [mergeMethod, setMergeMethod] = useState<PullRequestMergeMethod>("merge");
const [confirmAction, setConfirmAction] = useState<"merge" | "close" | null>(null);
const [confirmAction, setConfirmAction] = useState<
"merge" | "close" | "enable-auto-merge" | null
>(null);
// Which handoff is preparing, keyed so a per-finding button can say "Preparing..." on itself
// alone. One at a time whatever the key: they all check the same pull request out.
const [handoff, setHandoff] = useState<string | null>(null);
@@ -310,6 +498,7 @@ export function PullRequestDetailPanel({
commentsTruncated: activity?.commentsTruncated ?? false,
reviewThreads: activity?.reviewThreads ?? [],
commits: activity?.commits ?? [],
reactions: activity?.reactions ?? [],
},
[activity, coreDetail],
);
@@ -355,44 +544,157 @@ export function PullRequestDetailPanel({
void refreshFromHost();
}, [forcedRefreshToken, refreshFromHost]);
const runAction = useAtomCommand(pullRequestEnvironment.runAction, { reportFailure: false });
const [actionPending, setActionPending] = useState(false);
// Which action is in flight, not merely that one is: every control here is disabled while any
// of them runs, but only the button that was pressed may say what it is doing.
const [pendingAction, setPendingAction] = useState<PullRequestAction | null>(null);
const actionPending = pendingAction !== null;
const update = useAtomCommand(pullRequestEnvironment.update, { reportFailure: false });
// Scoped to the pull request it was typed against, since this one panel shows a different one
// every time it is opened and a half-written title must not follow it there.
const [titleScope, setTitleScope] = useState<{
readonly pullRequestKey: string;
readonly text: string;
} | null>(null);
const titleDraft = titleScope?.pullRequestKey === pullRequestKey ? titleScope.text : null;
const [titleSaving, setTitleSaving] = useState(false);
const newThread = useNewThreadHandler();
const { environments } = useEnvironments();
const projects = useProjects();
// Beside a thread there is nothing to pick: the hand-offs land in that thread's composer, and
// the thread is already on one server's copy of the branch.
const pickableEnvironments = useMemo(
() =>
context === "page"
? resolvePickableEnvironments(
{ environmentId, projectId: reference.projectId },
projects,
environments,
)
: [],
[context, environmentId, environments, projects, reference.projectId],
);
// Which server the reader chose, and only for the pull request they chose it on: this one panel
// shows a different pull request every time it is opened, and the choice does not follow.
const [actingScope, setActingScope] = useState<{
readonly pullRequestKey: string;
readonly environmentId: EnvironmentId;
} | null>(null);
const chosenEnvironmentId =
actingScope?.pullRequestKey === pullRequestKey ? actingScope.environmentId : environmentId;
// Null wherever there is no choice on offer — one server, or a chosen one that has since gone —
// and then the panel's own server and its own checkout are the answer, as they always were.
const acting =
pickableEnvironments.find((entry) => entry.environmentId === chosenEnvironmentId) ?? null;
const actingEnvironmentId = acting?.environmentId ?? environmentId;
const prepareThread = usePreparePullRequestThreadAction({
environmentId,
cwd: detail?.workspaceRoot ?? null,
environmentId: actingEnvironmentId,
cwd: acting?.workspaceRoot ?? detail?.workspaceRoot ?? null,
});
const perform = async (action: PullRequestAction, method?: PullRequestMergeMethod) => {
if (actionPending) return;
setActionPending(true);
const perform = async (
action: PullRequestAction,
method?: PullRequestMergeMethod,
updateMethod?: PullRequestUpdateMethod,
) => {
if (pendingAction !== null) return;
setPendingAction(action);
const result = await runAction({
environmentId,
input: { ...reference, action, ...(method ? { mergeMethod: method } : {}) },
input: {
...reference,
action,
...(method ? { mergeMethod: method } : {}),
...(updateMethod ? { updateMethod } : {}),
},
});
setActionPending(false);
setPendingAction(null);
if (result._tag === "Failure") {
// The host's own sentence, because it is the only thing that says why. A merge strategy a
// branch policy forbids is refused at completion and nowhere earlier — Azure DevOps
// publishes no per-strategy availability to hide the control with — so "action failed"
// would leave the reader pressing the same button again.
const failure = squashAtomCommandFailure(result);
// The hint stands for what was actually asked for: a reader who pressed Update branch is
// told to check their access, not offered the merge commit they already chose.
const hint =
updateMethod === "rebase"
? UPDATE_BRANCH_REBASE_FAILURE_HINT
: ACTION_FAILURE_HINTS[action];
toastManager.add({
type: "error",
title: ACTION_FAILURE_LABELS[action],
description: readableFailure(failure, ACTION_FAILURE_HINTS[action]),
description: readableFailure(failure, hint),
});
return;
}
toastManager.add({ type: "success", title: ACTION_SUCCESS_LABELS[action] });
refreshDetail();
// A branch update moves the head commit, which leaves the diff atom pointed at a comparison
// that no longer exists — the same staleness the manual refresh button fixes, so it goes
// through that path rather than a second one. Every other action here only changes metadata;
// a merge does move the branch too, but it also closes the pull request, where the diff is
// no longer what anyone is looking at.
if (pullRequestActionNeedsHostRefresh(action)) {
void refreshFromHost();
} else {
refreshDetail();
}
onActed?.();
};
const saveTitle = async (next: string) => {
const title = next.trim();
if (detail === null || titleSaving) return;
if (title.length === 0 || title === detail.title) {
setTitleScope(null);
return;
}
setTitleSaving(true);
const result = await update({ environmentId, input: { ...reference, title } });
setTitleSaving(false);
if (result._tag === "Failure") {
// The draft stays open with the words still in it: retyping a title somebody has just
// rewritten is the one thing a failed save must not cost them.
toastManager.add({
type: "error",
title: "The title could not be saved",
description: readableFailure(
squashAtomCommandFailure(result),
"The host refused the new title.",
),
});
return;
}
setTitleScope(null);
refreshDetail();
};
type ThreadTask = {
prompt: string;
reviewComments?: ReadonlyArray<ReviewCommentContext>;
};
// Beside the thread whose own pull request this is, a task belongs in that thread's composer:
// the branch is already checked out under it, so opening a second thread would only scatter
// the work.
const attachTarget = context === "thread" ? (composerDraftTarget ?? null) : null;
const handoffLabels = pullRequestHandoffLabels(attachTarget !== null);
const writeTaskToComposer = (target: ScopedThreadRef | DraftId, task: ThreadTask) => {
const store = useComposerDraftStore.getState();
const draft = store.getComposerDraft(target);
const key = composerTargetKey(target);
const prompt = handoffPrompt(
{ prompt: draft?.prompt ?? "", lastHandoffPrompt: lastHandoffPromptByDraft.get(key) },
task.prompt,
);
lastHandoffPromptByDraft.set(key, task.prompt);
store.setPrompt(target, prompt);
store.setReviewComments(
target,
handoffReviewComments(draft?.reviewComments ?? [], task.reviewComments ?? []),
);
};
/**
* Opens a thread on this project and leaves the task in its composer for the reader to send.
*
@@ -412,37 +714,32 @@ export function PullRequestDetailPanel({
() => null,
));
if (session === null) return null;
const store = useComposerDraftStore.getState();
if (task === null) return session;
// The latest press is the ask: it takes over what an earlier hand-off left, prompt and chips
// both, rather than stacking a second one under the first. What the reader typed themselves
// survives — the composer they are handed is not always a fresh one, and a prompt they have
// since edited is theirs rather than the hand-off's.
const draft = store.getComposerDraft(session.draftId);
const existingComments = draft?.reviewComments ?? [];
const prompt = handoffPrompt(
{
prompt: draft?.prompt ?? "",
lastHandoffPrompt: lastHandoffPromptByDraft.get(session.draftId),
},
task.prompt,
);
// Remember the hand-off's own contribution, not the merged prompt: only that sentence is
// this session's to take back next time, and the reader's text around it is not.
lastHandoffPromptByDraft.set(session.draftId, task.prompt);
store.setPrompt(session.draftId, prompt);
store.setReviewComments(
session.draftId,
handoffReviewComments(existingComments, task.reviewComments ?? []),
);
writeTaskToComposer(session.draftId, task);
return session;
};
/** A question about the change, which needs a thread and nothing else. */
const startAsk = async (kind: string, task: ThreadTask) => {
if (!detail || handoff !== null) return;
if (attachTarget !== null) {
writeTaskToComposer(attachTarget, task);
toastManager.add({
type: "success",
title: "Added to the composer",
description:
task.prompt.length > 0
? "The question is in the composer — read it over, then send."
: "The pull request is in the composer — type your question, then send.",
});
return;
}
setHandoff(kind);
const projectRef = scopeProjectRef(environmentId, detail.projectId);
const projectRef = scopeProjectRef(actingEnvironmentId, acting?.projectId ?? detail.projectId);
const opened = await openThreadWithTask(projectRef, task);
setHandoff(null);
if (opened === null) {
@@ -477,6 +774,15 @@ export function PullRequestDetailPanel({
mode: "worktree" | "local" = "worktree",
) => {
if (!detail || handoff !== null) return;
if (attachTarget !== null && task !== null) {
writeTaskToComposer(attachTarget, task);
toastManager.add({
type: "success",
title: "Added to the composer",
description: "The task is in the composer — read it over, then send.",
});
return;
}
setHandoff(kind);
// The menu closes on the press and takes its "Preparing..." label with it, so this is the
// only thing answering for the checkout. It carries no timeout of its own: a loading toast
@@ -485,7 +791,9 @@ export function PullRequestDetailPanel({
type: "loading",
title: "Preparing the pull request checkout...",
});
const projectRef = scopeProjectRef(environmentId, detail.projectId);
// Wherever the reader chose to act: the thread, the checkout it is pointed at and the composer
// the task lands in are all one server's, and picking another one moves all three.
const projectRef = scopeProjectRef(actingEnvironmentId, acting?.projectId ?? detail.projectId);
// The thread is opened before the checkout rather than after it, because the project's setup
// script only runs for a checkout that knows which thread it is for — and a worktree with no
// dependencies installed is not something anyone can test.
@@ -688,6 +996,12 @@ export function PullRequestDetailPanel({
? mergeMethod
: (allowedMergeMethods[0] ?? "merge");
const conflicting = detail?.state === "open" && detail.mergeability === "conflicting";
// Only an outright yes arms it. A host that reports nothing has not said the merge is already
// spoken for, and an off switch for something that may not be on says the wrong thing twice.
const autoMergeArmed = detail?.state === "open" && detail.autoMergeEnabled === true;
// Out of date with the base, and still cleanly mergeable — the one pairing an update button
// exists for. Null everywhere else, including hosts that cannot compare at all.
const freshness = detail === null ? null : resolveBaseFreshness(detail);
// A host that cannot produce a patch has no Code tab to open. The tabs themselves stay hidden
// until the detail arrives, so the loading ghost is the panel's only unfinished UI.
const visibleTabs = TABS.filter(
@@ -725,6 +1039,7 @@ export function PullRequestDetailPanel({
? resolvePullRequestState({ state: detail.state, isDraft: detail.isDraft })
: null;
const checksSummary = detail ? summarizePullRequestChecks(detail.checks) : null;
const checksState = detail ? pullRequestChecksState(detail.checks) : null;
return (
<div className="flex h-full min-h-0 w-full flex-col bg-background">
@@ -755,11 +1070,12 @@ export function PullRequestDetailPanel({
<button
type="button"
onClick={() => void readLocalApi()?.shell.openExternal(detail.url)}
onContextMenu={(event) => openNumberContextMenu(event, detail)}
className={cn(
"shrink-0 font-medium underline-offset-2 hover:underline",
statePresentation.toneClassName,
)}
title={OPEN_ON_HOST_LABELS[detail.provider] ?? "Open on host"}
title={openOnHostLabel(detail.provider)}
aria-label={`Open pull request #${detail.number} on host`}
>
#{detail.number}
@@ -783,11 +1099,12 @@ export function PullRequestDetailPanel({
type="button"
tabIndex={condensed ? 0 : -1}
onClick={() => void readLocalApi()?.shell.openExternal(detail.url)}
onContextMenu={(event) => openNumberContextMenu(event, detail)}
className={cn(
"shrink-0 font-medium underline-offset-2 hover:underline",
statePresentation.toneClassName,
)}
title={OPEN_ON_HOST_LABELS[detail.provider] ?? "Open on host"}
title={openOnHostLabel(detail.provider)}
aria-label={`Open pull request #${detail.number} on host`}
>
#{detail.number}
@@ -804,7 +1121,10 @@ export function PullRequestDetailPanel({
Conflicts
</Badge>
) : checksSummary ? (
<span className="shrink-0 text-[10px] text-muted-foreground">
<span className="flex shrink-0 items-center gap-1 text-[10px] text-muted-foreground">
{detail && checksState !== null ? (
<PullRequestChecksPopover checks={detail.checks} checksState={checksState} />
) : null}
{checksSummary}
</span>
) : null}
@@ -832,7 +1152,9 @@ export function PullRequestDetailPanel({
<span className="flex min-w-0 flex-col">
<span>{handoff === "ask" ? "Opening..." : "Ask a question"}</span>
<span className="text-xs text-muted-foreground">
Opens a thread that knows which pull request you mean.
{attachTarget !== null
? "Adds the pull request to this thread's composer."
: "Opens a thread that knows which pull request you mean."}
</span>
</span>
</MenuItem>
@@ -847,8 +1169,16 @@ export function PullRequestDetailPanel({
</MenuItem>
<MenuItem disabled={handoff !== null} onClick={startFixFindings}>
<HammerIcon className="size-3.5" />
{handoff === "findings" ? "Preparing..." : "Fix findings in a thread"}
{handoff === "findings" ? "Preparing..." : handoffLabels.fixFindings}
</MenuItem>
{pickableEnvironments.length > 0 ? (
<ActOnEnvironmentPicker
environments={pickableEnvironments}
value={actingEnvironmentId}
onChange={(next) => setActingScope({ pullRequestKey, environmentId: next })}
disabled={handoff !== null}
/>
) : null}
<MenuSeparator />
{detail.state === "open" ? (
<>
@@ -869,6 +1199,32 @@ export function PullRequestDetailPanel({
{detail.isDraft ? "Ready for review" : "Convert to draft"}
</MenuItem>
) : null}
{/* The same merge, left with the host to carry out once the things it
waits on are done. It is offered beside the merge rather than instead
of it, because the reader who can wait and the reader who cannot are
the same person on different days — and a conflicting branch is neither,
since nothing the host waits for will clear it. */}
{autoMergeArmed && can("disable-auto-merge") ? (
<MenuItem
disabled={actionPending}
onClick={() => void perform("disable-auto-merge")}
>
<GitMergeIcon className="size-3.5" />
Disable auto-merge
</MenuItem>
) : !autoMergeArmed &&
!detail.isDraft &&
!conflicting &&
can("enable-auto-merge") &&
allowedMergeMethods.length > 0 ? (
<MenuItem
disabled={actionPending}
onClick={() => setConfirmAction("enable-auto-merge")}
>
<GitMergeIcon className="size-3.5" />
Enable auto-merge
</MenuItem>
) : null}
{/* A preference for the merge action rather than a second action, so it
is a radio group here instead of a chevron welded to the Merge pill.
Hidden while conflicting: every method would fail. */}
@@ -904,7 +1260,7 @@ export function PullRequestDetailPanel({
) : null}
<MenuItem onClick={() => void readLocalApi()?.shell.openExternal(detail.url)}>
<ArrowUpRightIcon className="size-3.5" />
{OPEN_ON_HOST_LABELS[detail.provider] ?? "Open on host"}
{openOnHostLabel(detail.provider)}
</MenuItem>
<MenuItem onClick={() => void writeTextToClipboard(detail.url)}>
<LinkIcon className="size-3.5" />
@@ -914,7 +1270,7 @@ export function PullRequestDetailPanel({
{conflicting && primaryAction !== "resolve" ? (
<MenuItem disabled={handoff !== null} onClick={startResolveConflicts}>
<GitMergeIcon className="size-3.5" />
{handoff === "conflicts" ? "Preparing..." : "Resolve conflicts in a thread"}
{handoff === "conflicts" ? "Preparing..." : handoffLabels.resolveConflicts}
</MenuItem>
) : null}
{detail.state === "open" && can("close") ? (
@@ -982,9 +1338,29 @@ export function PullRequestDetailPanel({
</span>
</span>
</MenuItem>
{pickableEnvironments.length > 0 ? (
<ActOnEnvironmentPicker
environments={pickableEnvironments}
value={actingEnvironmentId}
onChange={(next) => setActingScope({ pullRequestKey, environmentId: next })}
disabled={handoff !== null}
/>
) : null}
</MenuPopup>
</Menu>
) : null}
{/* Said where the Merge button is, because it is the answer to why nobody has
pressed it: the merge is already asked for, and the host is holding it. */}
{autoMergeArmed ? (
<Badge
variant="info"
className="h-5 shrink-0 gap-1 rounded px-1.5 text-[10px]"
title="The host will merge this on its own once its requirements are met"
>
<GitMergeIcon aria-hidden className="size-3" />
Auto-merge
</Badge>
) : null}
{primaryAction === "ready" ? (
<Button size="xs" disabled={actionPending} onClick={() => void perform("ready")}>
Ready for review
@@ -995,7 +1371,7 @@ export function PullRequestDetailPanel({
disabled={actionPending}
onClick={() => setConfirmAction("merge")}
>
{actionPending ? "Merging..." : "Merge"}
{pendingAction === "merge" ? "Merging..." : "Merge"}
</Button>
) : null}
</>
@@ -1015,7 +1391,16 @@ export function PullRequestDetailPanel({
{/* The condensed chrome's second row: the tabs that the closing fold takes with it,
and compact copies of the branch pair and diff stat so they stay in sight while
the full rows are folded away. Same zero-track mechanism as the fold, inverted. */}
<div className={cn("col-span-2 grid", condensed ? "grid-rows-[1fr]" : "grid-rows-[0fr]")}>
<div
className={cn(
"col-span-2 grid",
// Inverse of the fold's track: closing eases while the fold above eases open,
// so the chrome trades rows in one motion instead of two jumps.
condensed
? "grid-rows-[1fr]"
: "grid-rows-[0fr] transition-[grid-template-rows] duration-200 ease-out motion-reduce:transition-none",
)}
>
<div
ref={condensedRowRef}
className={cn(
@@ -1052,6 +1437,15 @@ export function PullRequestDetailPanel({
title={`${detail.baseBranch} ← ${detail.headBranch}`}
>
<span className="truncate">{detail.baseBranch}</span>
{freshness ? (
<PullRequestBaseFreshnessWarning
baseBranch={detail.baseBranch}
freshness={freshness}
pending={actionPending}
onUpdate={(method) => void perform("update-branch", undefined, method)}
iconClassName="size-3"
/>
) : null}
<ArrowLeftIcon aria-label="receives changes from" className="size-3 shrink-0" />
<span className="truncate">{detail.headBranch}</span>
</span>
@@ -1077,10 +1471,13 @@ export function PullRequestDetailPanel({
<div
className={cn(
"col-span-2 grid",
// Instant in both directions: the scroll compensation keeps the content pinned
// through either flip, and an animated track would fight it frame by frame. The
// top row's crossfade is the transition.
condensed ? "grid-rows-[0fr]" : "grid-rows-[1fr]",
// Collapse is instant: it happens mid-scroll, and the compensation that keeps the
// content pinned would fight an animated track frame by frame. Reopening happens
// at the top with no compensation, so the fold can ease back in instead of
// snapping the content down.
condensed
? "grid-rows-[0fr]"
: "grid-rows-[1fr] transition-[grid-template-rows] duration-200 ease-out motion-reduce:transition-none",
)}
>
<div
@@ -1098,7 +1495,66 @@ export function PullRequestDetailPanel({
>
{detail ? (
<div className="col-span-2 mt-3 min-w-0 px-4 pb-4">
<h1 className="text-base font-semibold leading-snug">{detail.title}</h1>
{titleDraft === null ? (
<div className="group flex min-w-0 items-start gap-1">
<h1 className="min-w-0 flex-1 text-base font-semibold leading-snug">
{detail.title}
</h1>
{canEditPullRequestChangeRequest(detail) ? (
<Button
size="icon-xs"
variant="ghost"
className="shrink-0 text-muted-foreground opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100 focus-visible:opacity-100"
aria-label="Edit title"
onClick={() => setTitleScope({ pullRequestKey, text: detail.title })}
>
<PencilIcon className="size-3" />
</Button>
) : null}
</div>
) : (
// A title is one line of text, not markdown, so it takes an input rather than
// the editor the description and the remarks share.
<div className="space-y-2">
<Input
autoFocus
size="sm"
disabled={titleSaving}
value={titleDraft}
aria-label="Pull request title"
onChange={(event) =>
setTitleScope({ pullRequestKey, text: event.target.value })
}
onKeyDown={(event) => {
if (event.key === "Enter") {
event.preventDefault();
void saveTitle(titleDraft);
} else if (event.key === "Escape") {
event.preventDefault();
setTitleScope(null);
}
}}
/>
<div className="flex justify-end gap-2">
<Button
size="xs"
variant="ghost"
disabled={titleSaving}
onClick={() => setTitleScope(null)}
>
Cancel
</Button>
<Button
size="xs"
variant="outline"
disabled={titleSaving || titleDraft.trim().length === 0}
onClick={() => void saveTitle(titleDraft)}
>
{titleSaving ? "Saving..." : "Save"}
</Button>
</div>
</div>
)}
<PullRequestMetaLine className="mt-2 text-xs text-muted-foreground">
<PullRequestActorLabel actor={detail.author} className="font-medium" />
<span>updated {formatRelativeTimeLabel(detail.updatedAt)}</span>
@@ -1111,6 +1567,14 @@ export function PullRequestDetailPanel({
>
{detail.baseBranch}
</code>
{freshness ? (
<PullRequestBaseFreshnessWarning
baseBranch={detail.baseBranch}
freshness={freshness}
pending={actionPending}
onUpdate={(method) => void perform("update-branch", undefined, method)}
/>
) : null}
<ArrowLeftIcon aria-label="receives changes from" className="size-4 shrink-0" />
<button
type="button"
@@ -1170,7 +1634,7 @@ export function PullRequestDetailPanel({
disabled={handoff !== null}
onClick={startResolveConflicts}
>
{handoff === "conflicts" ? "Preparing..." : "Resolve in a new thread"}
{handoff === "conflicts" ? "Preparing..." : handoffLabels.resolve}
<ArrowUpRightIcon className="size-3.5 text-destructive" />
</Button>
</div>
@@ -1178,7 +1642,7 @@ export function PullRequestDetailPanel({
{detail ? (
<nav
className="col-span-2 flex min-w-0 items-center gap-1 overflow-x-auto border-t border-border/60 px-4 py-2"
className="col-span-2 flex min-w-0 items-center gap-1 overflow-x-auto border-t border-border/60 px-4 py-2 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
aria-label="Pull request tabs"
>
{visibleTabs.map((item) => (
@@ -1202,7 +1666,13 @@ export function PullRequestDetailPanel({
className="ml-auto inline-flex shrink-0 items-center gap-1.5 text-xs text-muted-foreground"
aria-label={checksSummary ? `Checks: ${checksSummary}` : "Checks"}
>
<CircleDotIcon aria-hidden className="size-3.5" />
{/* The rollup icon opens the checks behind the summary; with none reported
there is nothing to open, so the plain glyph stays. */}
{detail && checksState !== null ? (
<PullRequestChecksPopover checks={detail.checks} checksState={checksState} />
) : (
<CircleDotIcon aria-hidden className="size-3.5" />
)}
{checksSummary}
</span>
) : tab === "timeline" ? (
@@ -1290,11 +1760,10 @@ export function PullRequestDetailPanel({
// scrollport actually gains is the difference between the two.
const chromeDelta = foldHeight - (condensedRowRef.current?.scrollHeight ?? 0);
if (previous) {
// The hard top reopens the chrome. The refund puts the reader a fold's height
// from the top, pinned to the same pixels — the metadata is scrolled up to,
// not thrown at them.
// The hard top reopens the chrome with no refund: the reader asked for the top,
// and moving them a fold's height back down would snatch it away — the fold
// slides in above while the content stays where they left it.
if (top < 4 && foldHeight > 0) {
compensationRef.current = chromeDelta;
next = false;
}
} else if (foldHeight > 0 && top > foldHeight + 32) {
@@ -1329,6 +1798,8 @@ export function PullRequestDetailPanel({
activityPending={activityPending}
activityError={activityError}
pendingFinding={handoff}
fixFindingLabel={handoffLabels.fixFinding}
fixCheckLabel={handoffLabels.fixCheck}
onFixFinding={startFixFinding}
onRefresh={refreshDetail}
/>
@@ -1346,8 +1817,11 @@ export function PullRequestDetailPanel({
) : (
<PullRequestTimelineTab
detail={detail}
environmentId={environmentId}
reference={reference}
order={timelineOrder}
onOpenCommit={openCommit}
onRefresh={refreshDetail}
/>
)}
</div>
@@ -1363,6 +1837,7 @@ export function PullRequestDetailPanel({
selectedCommitOid={selectedCodeCommitOid}
onSelectedCommitChange={selectCodeCommit}
pendingFinding={handoff}
fixFindingLabel={handoffLabels.fixFinding}
onFixFinding={startFixFinding}
onRefresh={refreshDetail}
refreshToken={refreshToken}
@@ -1381,12 +1856,21 @@ export function PullRequestDetailPanel({
<AlertDialogPopup>
<AlertDialogHeader>
<AlertDialogTitle>
{confirmAction === "merge" ? "Merge pull request?" : "Close pull request?"}
{confirmAction === "merge"
? "Merge pull request?"
: confirmAction === "enable-auto-merge"
? "Enable auto-merge?"
: "Close pull request?"}
</AlertDialogTitle>
<AlertDialogDescription>
{confirmAction === "merge"
? `This merges #${reference.number} using ${selectedMergeMethod}.`
: `This closes #${reference.number} without merging it.`}
: confirmAction === "enable-auto-merge"
? // The host merges this as soon as it considers the pull request ready, which
// may be immediately — there is no telling from here whether anything is
// still outstanding.
`This merges #${reference.number} using ${selectedMergeMethod} as soon as the host considers it ready, which may be immediately.`
: `This closes #${reference.number} without merging it.`}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
@@ -1401,10 +1885,16 @@ export function PullRequestDetailPanel({
const action = confirmAction;
setConfirmAction(null);
if (action === "merge") void perform("merge", selectedMergeMethod);
if (action === "enable-auto-merge")
void perform("enable-auto-merge", selectedMergeMethod);
if (action === "close") void perform("close");
}}
>
{confirmAction === "merge" ? "Merge" : "Close"}
{confirmAction === "merge"
? "Merge"
: confirmAction === "enable-auto-merge"
? "Enable auto-merge"
: "Close"}
</Button>
</AlertDialogFooter>
</AlertDialogPopup>
@@ -1,4 +1,4 @@
import type { ProjectId } from "@t3tools/contracts";
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
import { CircleIcon } from "lucide-react";
import { Children, isValidElement, type ReactElement, type ReactNode } from "react";
import { describe, expect, it, vi } from "vite-plus/test";
@@ -53,12 +53,17 @@ function menu(overrides: Partial<Parameters<typeof PullRequestFiltersMenu>[0]>)
involvement: "all",
involvementOptions: [{ value: "all", label: "All", Icon: CircleIcon }],
onInvolvement: () => undefined,
filters: {},
onFilters: () => undefined,
host: undefined,
hostOptions: [],
onHost: () => undefined,
environmentId: null,
server: undefined,
serverOptions: [],
onServer: () => undefined,
projects: [],
projectId: undefined,
projectEnvironmentId: undefined,
unavailable: new Map(),
onProject: () => undefined,
...overrides,
@@ -79,21 +84,82 @@ describe("pull request filters menu", () => {
expect(onState).toHaveBeenCalledWith("closed");
});
it("names the chosen narrowing and leaves the others alone", () => {
const onFilters = vi.fn();
const group = findValueChange(
findLabeledGroup(menu({ filters: { review: "approved" }, onFilters }), "Draft"),
);
expect(group).toBeDefined();
group?.props.onValueChange("hide");
expect(onFilters).toHaveBeenCalledWith({ review: "approved", draft: "hide" });
});
it("drops a narrowing chosen back to all rather than sending it as undefined", () => {
const onFilters = vi.fn();
const group = findValueChange(
findLabeledGroup(
menu({ filters: { review: "none", checks: "failing" }, onFilters }),
"Review",
),
);
expect(group).toBeDefined();
group?.props.onValueChange("all");
expect(onFilters).toHaveBeenCalledWith({ checks: "failing" });
});
it("does not emit a change when the selected project is chosen again", () => {
const projectId = "project-1" as ProjectId;
const environmentId = "env-1" as EnvironmentId;
const onProject = vi.fn();
const view = menu({
projects: [{ id: projectId, title: "T3 Code", workspaceRoot: "/work/t3code" }],
projects: [
{
id: projectId,
environmentId,
title: "T3 Code",
workspaceRoot: "/work/t3code",
},
],
projectId,
projectEnvironmentId: environmentId,
onProject,
});
const radioGroup = findValueChange(view);
expect(radioGroup).toBeDefined();
radioGroup?.props.onValueChange(projectId);
radioGroup?.props.onValueChange(`${environmentId} ${projectId}`);
expect(onProject).not.toHaveBeenCalled();
radioGroup?.props.onValueChange("all");
expect(onProject).toHaveBeenCalledWith(undefined);
expect(onProject).toHaveBeenCalledWith(undefined, undefined);
});
it("passes the environment along so a duplicate project id on another server is told apart", () => {
const projectId = "project-1" as ProjectId;
const onProject = vi.fn();
const view = menu({
projects: [
{
id: projectId,
environmentId: "env-1" as EnvironmentId,
title: "T3 Code · one",
workspaceRoot: "/work/t3code-1",
},
{
id: projectId,
environmentId: "env-2" as EnvironmentId,
title: "T3 Code · two",
workspaceRoot: "/work/t3code-2",
},
],
onProject,
});
const radioGroup = findValueChange(view);
expect(radioGroup).toBeDefined();
radioGroup?.props.onValueChange(`env-2 ${projectId}`);
expect(onProject).toHaveBeenCalledWith(projectId, "env-2");
});
});
@@ -2,10 +2,23 @@ import type {
EnvironmentId,
ProjectId,
PullRequestInvolvement,
PullRequestListFilters,
PullRequestListState,
SourceControlProviderKind,
} from "@t3tools/contracts";
import { FolderGit2Icon, LayersIcon, ListFilterIcon, LoaderIcon, SearchIcon } from "lucide-react";
import {
CircleCheckIcon,
CircleDashedIcon,
CircleSlashIcon,
CircleXIcon,
EyeOffIcon,
FolderGit2Icon,
GitPullRequestDraftIcon,
LayersIcon,
ListFilterIcon,
LoaderIcon,
SearchIcon,
} from "lucide-react";
import type { ElementType } from "react";
import { cn } from "~/lib/utils";
@@ -82,7 +95,7 @@ export function PullRequestSearchInput({
type="text"
value={value}
onChange={(event) => onChange(event.currentTarget.value)}
placeholder="Search pull requests"
placeholder="Search pull requests, or label:bug"
aria-label="Search pull requests"
// Tracks the shared input's height at both widths, so it stays level with the icon
// button beside it rather than towering over it on wide screens.
@@ -101,6 +114,38 @@ export function PullRequestSearchInput({
const ALL_PROJECTS_VALUE = "all";
/** MenuRadioGroup wants a string, so "every host" wears the one value no host can be. */
const ALL_HOSTS_VALUE = "";
/** The same trick for the servers, which are named by an id no empty string can collide with. */
const ALL_SERVERS_VALUE = "";
/** The unset value of each narrowing group, which no filter of theirs is named after. */
const UNFILTERED_VALUE = "all";
/**
* A project's own radio value, carrying the server along with the id: the id alone is only
* unique within its own server, so two rows sharing one would otherwise both read as checked.
*/
const projectMenuValue = (project: {
readonly id: ProjectId;
readonly environmentId: EnvironmentId;
}) => `${project.environmentId} ${project.id}`;
const DRAFT_OPTIONS = [
{ value: UNFILTERED_VALUE, label: "All", Icon: LayersIcon },
{ value: "only", label: "Drafts only", Icon: GitPullRequestDraftIcon },
{ value: "hide", label: "Hide drafts", Icon: EyeOffIcon },
] as const satisfies ReadonlyArray<PullRequestFilterOption<string>>;
const REVIEW_OPTIONS = [
{ value: UNFILTERED_VALUE, label: "All", Icon: LayersIcon },
{ value: "approved", label: "Approved", Icon: CircleCheckIcon },
{ value: "changes-requested", label: "Changes requested", Icon: CircleXIcon },
{ value: "review-required", label: "Review required", Icon: CircleDashedIcon },
{ value: "none", label: "No reviews", Icon: CircleSlashIcon },
] as const satisfies ReadonlyArray<PullRequestFilterOption<string>>;
const CHECKS_OPTIONS = [
{ value: UNFILTERED_VALUE, label: "All", Icon: LayersIcon },
{ value: "passing", label: "Passing", Icon: CircleCheckIcon },
{ value: "failing", label: "Failing", Icon: CircleXIcon },
] as const satisfies ReadonlyArray<PullRequestFilterOption<string>>;
function PullRequestFilterRadioGroup<Value extends string>({
label,
@@ -147,12 +192,17 @@ export function PullRequestFiltersMenu({
involvement,
involvementOptions,
onInvolvement,
filters,
onFilters,
host,
hostOptions,
onHost,
environmentId,
server,
serverOptions,
onServer,
projects,
projectId,
projectEnvironmentId,
unavailable,
onProject,
}: {
@@ -162,6 +212,9 @@ export function PullRequestFiltersMenu({
involvement: PullRequestInvolvement;
involvementOptions: ReadonlyArray<PullRequestFilterOption<PullRequestInvolvement>>;
onInvolvement: (involvement: PullRequestInvolvement) => void;
/** The narrowings beyond state and involvement; an absent field is that group unfiltered. */
filters: PullRequestListFilters;
onFilters: (filters: PullRequestListFilters) => void;
host: string | undefined;
/**
* Includes the "all hosts" entry, whose value is the empty string. With fewer than two real
@@ -169,24 +222,52 @@ export function PullRequestFiltersMenu({
*/
hostOptions: ReadonlyArray<PullRequestFilterOption<string>>;
onHost: (host: string | undefined) => void;
/** Where the projects' own favicons are read from; null before the environment is known. */
environmentId: EnvironmentId | null;
server: EnvironmentId | undefined;
/**
* Includes the "all servers" entry, whose value is the empty string. With one server there is
* nothing to switch between, so the whole group stays out of the menu.
*/
serverOptions: ReadonlyArray<PullRequestFilterOption<string>>;
onServer: (server: EnvironmentId | undefined) => void;
/** The projects of every connected environment, each carrying the one its favicon is read from. */
projects: ReadonlyArray<{
readonly id: ProjectId;
readonly environmentId: EnvironmentId;
readonly title: string;
readonly workspaceRoot: string;
}>;
projectId: ProjectId | undefined;
/**
* The server the selected project belongs to. A project id is only unique within its own
* server, so without this two rows sharing an id would both read as checked here.
*/
projectEnvironmentId: EnvironmentId | undefined;
/**
* Projects whose repository could not be read this time round. They are named here, where
* the reader is already choosing between projects, rather than as a count above the list
* that says something is missing without saying which.
*/
unavailable: ReadonlyMap<ProjectId, string>;
onProject: (projectId: ProjectId | undefined) => void;
/** The environment comes with the project id, since picking a row picks a specific server's copy of it. */
onProject: (projectId: ProjectId | undefined, environmentId: EnvironmentId | undefined) => void;
}) {
const filtered =
state !== "open" || involvement !== "all" || host !== undefined || projectId !== undefined;
state !== "open" ||
involvement !== "all" ||
host !== undefined ||
server !== undefined ||
projectId !== undefined ||
Object.keys(filters).length > 0;
/**
* Rebuilt rather than spread so an unfiltered group leaves the record instead of lingering in
* it as an explicit `undefined`, which the listing input does not accept.
*/
const withFilter = (key: keyof PullRequestListFilters, value: string): PullRequestListFilters =>
Object.fromEntries(
Object.entries({ ...filters, [key]: value === UNFILTERED_VALUE ? undefined : value }).filter(
([, held]) => held !== undefined,
),
) as PullRequestListFilters;
return (
<Menu>
<MenuTrigger
@@ -219,6 +300,27 @@ export function PullRequestFiltersMenu({
options={involvementOptions}
onChange={onInvolvement}
/>
<MenuSeparator />
<PullRequestFilterRadioGroup
label="Draft"
value={filters.draft ?? UNFILTERED_VALUE}
options={DRAFT_OPTIONS}
onChange={(next) => onFilters(withFilter("draft", next))}
/>
<MenuSeparator />
<PullRequestFilterRadioGroup
label="Review"
value={filters.review ?? UNFILTERED_VALUE}
options={REVIEW_OPTIONS}
onChange={(next) => onFilters(withFilter("review", next))}
/>
<MenuSeparator />
<PullRequestFilterRadioGroup
label="Checks"
value={filters.checks ?? UNFILTERED_VALUE}
options={CHECKS_OPTIONS}
onChange={(next) => onFilters(withFilter("checks", next))}
/>
{hostOptions.length > 2 ? (
<>
<MenuSeparator />
@@ -230,12 +332,40 @@ export function PullRequestFiltersMenu({
/>
</>
) : null}
{serverOptions.length > 2 ? (
<>
<MenuSeparator />
<PullRequestFilterRadioGroup
label="Server"
value={server ?? ALL_SERVERS_VALUE}
options={serverOptions}
onChange={(next) =>
onServer(next === ALL_SERVERS_VALUE ? undefined : (next as EnvironmentId))
}
/>
</>
) : null}
<MenuSeparator />
<MenuRadioGroup
value={projectId ?? ALL_PROJECTS_VALUE}
value={
projectId === undefined || projectEnvironmentId === undefined
? ALL_PROJECTS_VALUE
: projectMenuValue({ id: projectId, environmentId: projectEnvironmentId })
}
onValueChange={(next) => {
const nextProjectId = next === ALL_PROJECTS_VALUE ? undefined : (next as ProjectId);
if (nextProjectId !== projectId) onProject(nextProjectId);
if (next === ALL_PROJECTS_VALUE) {
if (projectId !== undefined) onProject(undefined, undefined);
return;
}
// The value carries both halves, since the id alone cannot tell two servers' rows
// apart once they share one.
const project = projects.find((candidate) => projectMenuValue(candidate) === next);
if (
project !== undefined &&
(project.id !== projectId || project.environmentId !== projectEnvironmentId)
) {
onProject(project.id, project.environmentId);
}
}}
>
<MenuGroupLabel>Project</MenuGroupLabel>
@@ -255,22 +385,18 @@ export function PullRequestFiltersMenu({
const reason = unavailable.get(project.id);
return (
<MenuRadioItem
key={project.id}
value={project.id}
key={projectMenuValue(project)}
value={projectMenuValue(project)}
disabled={reason !== undefined}
title={reason}
>
<span className="flex min-w-0 flex-1 items-center gap-2">
{environmentId === null ? (
<FolderGit2Icon aria-hidden className="size-3.5 shrink-0" />
) : (
<ProjectFavicon
environmentId={environmentId}
cwd={project.workspaceRoot}
fallbackIcon={FolderGit2Icon}
className="size-3.5 shrink-0"
/>
)}
<ProjectFavicon
environmentId={project.environmentId}
cwd={project.workspaceRoot}
fallbackIcon={FolderGit2Icon}
className="size-3.5 shrink-0"
/>
<span className="min-w-0 flex-1 truncate">{project.title}</span>
{reason === undefined ? null : (
<span className="shrink-0 rounded-full border border-amber-500/40 bg-amber-500/10 px-1.5 py-px text-[10px] font-medium text-amber-600 dark:text-amber-400/90">
@@ -0,0 +1,113 @@
import { useState } from "react";
import { cn } from "~/lib/utils";
import { Button } from "../ui/button";
import { Textarea } from "../ui/textarea";
import { PullRequestMarkdown } from "./PullRequestMarkdown";
/**
* The box a body is rewritten in — a description, or a remark already posted. It owns the draft
* and nothing else: the caller sends the request and says whether it is still in flight, so the
* same box serves every mutation without knowing which one it is.
*
* Preview renders through the same component the saved body will be read through, which is the
* only way to see what a host's markdown will actually become before it is sent.
*/
export function PullRequestMarkdownEditor({
value,
cwd,
placeholder,
label,
saving,
allowEmpty = false,
className,
onSave,
onCancel,
}: {
readonly value: string;
readonly cwd: string;
readonly placeholder?: string | undefined;
readonly label: string;
readonly saving: boolean;
/** A description may be cleared, which is how one is removed; a remark may not be emptied. */
readonly allowEmpty?: boolean;
readonly className?: string | undefined;
readonly onSave: (next: string) => void;
readonly onCancel: () => void;
}) {
const [draft, setDraft] = useState(value);
const [preview, setPreview] = useState(false);
// The words this draft started from. React keeps a component instance wherever the same
// position and key come round again, so an editor opened on one remark can be handed another's
// words without being rebuilt — and saving would then write the first remark's text onto the
// second. Different words mean a different subject, and the draft starts again from them.
const [seed, setSeed] = useState(value);
if (seed !== value) {
setSeed(value);
setDraft(value);
}
const empty = draft.trim().length === 0;
return (
<div
className={cn("space-y-2", className)}
onKeyDown={(event) => {
if (event.key !== "Escape" || saving) return;
event.preventDefault();
onCancel();
}}
>
<div className="flex items-center gap-1">
<Button
size="xs"
variant={preview ? "ghost" : "outline"}
disabled={saving}
onClick={() => setPreview(false)}
>
Write
</Button>
<Button
size="xs"
variant={preview ? "outline" : "ghost"}
disabled={saving}
onClick={() => setPreview(true)}
>
Preview
</Button>
</div>
{preview ? (
<div className="rounded-lg border border-border/60 px-3 py-2">
{empty ? (
<p className="text-xs text-muted-foreground">Nothing to preview.</p>
) : (
<PullRequestMarkdown text={draft} cwd={cwd} />
)}
</div>
) : (
<Textarea
autoFocus
disabled={saving}
value={draft}
rows={6}
placeholder={placeholder}
aria-label={label}
onChange={(event) => setDraft(event.target.value)}
/>
)}
<div className="flex justify-end gap-2">
<Button size="xs" variant="ghost" disabled={saving} onClick={onCancel}>
Cancel
</Button>
<Button
size="xs"
variant="outline"
disabled={saving || (empty && !allowEmpty)}
onClick={() => onSave(draft)}
>
{saving ? "Saving..." : "Save"}
</Button>
</div>
</div>
);
}
@@ -0,0 +1,178 @@
import type {
EnvironmentId,
PullRequestReaction,
PullRequestReactionContent,
PullRequestRef,
} from "@t3tools/contracts";
import { SmilePlusIcon } from "lucide-react";
import { useState } from "react";
import { cn } from "~/lib/utils";
import { pullRequestEnvironment } from "~/state/pullRequests";
import { useAtomCommand } from "~/state/use-atom-command";
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
import { toastManager } from "../ui/toast";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import {
applyPendingPullRequestReactions,
PULL_REQUEST_REACTION_ORDER,
pullRequestReactionEmoji,
pullRequestReactionName,
pullRequestReactionTooltip,
} from "./pullRequestReactions.logic";
const PILL_CLASS =
"inline-flex h-6 shrink-0 items-center gap-1 rounded-full border px-2 text-xs outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring";
const EMPTY_PENDING: ReadonlyMap<PullRequestReactionContent, boolean> = new Map();
/** What the host last said, so a press in flight is forgotten the moment the real counts land. */
function reactionsSignature(reactions: ReadonlyArray<PullRequestReaction>): string {
return reactions
.map((reaction) => `${reaction.content}:${reaction.count}:${reaction.viewerHasReacted ? 1 : 0}`)
.join(" ");
}
/**
* The reaction pills under a remark, and the picker that adds one. The same bar serves the
* description, a conversation comment and a review thread's comments: what differs between them
* is only which subject the host is told about.
*
* The add button is revealed by hovering the remark it belongs to, the way GitHub's is, so the
* parent must carry `group`. It stays put once there is something to press it beside, while the
* picker is open, and whenever it is focused — a control only a mouse can find is no control.
*/
export function PullRequestReactionBar({
reactions,
canReact,
subjectId,
environmentId,
reference,
onRefresh,
className,
}: {
readonly reactions: ReadonlyArray<PullRequestReaction>;
readonly canReact: boolean;
/** Absent reacts to the change request itself, which is where its description's reactions live. */
readonly subjectId?: string | undefined;
readonly environmentId: EnvironmentId;
readonly reference: PullRequestRef;
readonly onRefresh: () => void;
readonly className?: string | undefined;
}) {
const [pickerOpen, setPickerOpen] = useState(false);
const [pending, setPending] = useState<{
readonly signature: string;
readonly values: ReadonlyMap<PullRequestReactionContent, boolean>;
}>({ signature: "", values: EMPTY_PENDING });
const setReaction = useAtomCommand(pullRequestEnvironment.setReaction, { reportFailure: false });
const signature = reactionsSignature(reactions);
const values = pending.signature === signature ? pending.values : EMPTY_PENDING;
const shown = applyPendingPullRequestReactions(reactions, values);
const toggle = async (content: PullRequestReactionContent, reacted: boolean) => {
setPending({ signature, values: new Map([...values, [content, reacted]]) });
const result = await setReaction({
environmentId,
input: {
...reference,
...(subjectId === undefined ? {} : { subjectId }),
content,
reacted,
},
});
if (result._tag === "Failure") {
setPending((current) => {
const next = new Map(current.values);
next.delete(content);
return { signature: current.signature, values: next };
});
toastManager.add({ type: "error", title: "The reaction could not be saved" });
return;
}
onRefresh();
};
if (shown.length === 0 && !canReact) return null;
return (
<div className={cn("flex flex-wrap items-center gap-1", className)}>
{shown.map((reaction) => (
<Tooltip key={reaction.content}>
<TooltipTrigger
render={
<button
type="button"
aria-pressed={reaction.viewerHasReacted}
aria-label={`${pullRequestReactionName(reaction.content)}, ${reaction.count}`}
disabled={!canReact}
className={cn(
PILL_CLASS,
reaction.viewerHasReacted
? "border-primary/60 bg-primary/10 text-foreground"
: "border-border/70 bg-muted/40 text-muted-foreground",
canReact ? "hover:border-primary/60" : "cursor-default",
)}
onClick={() => void toggle(reaction.content, !reaction.viewerHasReacted)}
/>
}
>
<span aria-hidden>{pullRequestReactionEmoji(reaction.content)}</span>
<span className="tabular-nums">{reaction.count}</span>
</TooltipTrigger>
<TooltipPopup side="top">{pullRequestReactionTooltip(reaction)}</TooltipPopup>
</Tooltip>
))}
{canReact ? (
<Popover open={pickerOpen} onOpenChange={setPickerOpen}>
<PopoverTrigger
render={
<button
type="button"
aria-label="Add a reaction"
className={cn(
PILL_CLASS,
"border-border/70 px-1.5 text-muted-foreground hover:border-primary/60 hover:text-foreground",
shown.length === 0 &&
!pickerOpen &&
"opacity-0 group-focus-within:opacity-100 group-hover:opacity-100 focus-visible:opacity-100",
)}
/>
}
>
<SmilePlusIcon aria-hidden className="size-3.5" />
</PopoverTrigger>
<PopoverPopup align="start" className="w-auto" side="top" viewportClassName="py-2">
<div className="flex items-center gap-0.5">
{PULL_REQUEST_REACTION_ORDER.map((content) => {
const reacted =
shown.find((reaction) => reaction.content === content)?.viewerHasReacted ?? false;
return (
<button
key={content}
type="button"
aria-pressed={reacted}
aria-label={pullRequestReactionName(content)}
className={cn(
"flex size-7 items-center justify-center rounded-md text-base outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",
reacted && "bg-primary/10",
)}
onClick={() => {
setPickerOpen(false);
void toggle(content, !reacted);
}}
>
<span aria-hidden>{pullRequestReactionEmoji(content)}</span>
</button>
);
})}
</div>
</PopoverPopup>
</Popover>
) : null}
</div>
);
}
@@ -2,12 +2,18 @@
* Pull-request-specific annotations: conversations already on the host and comments queued for
* the review being written. New comment composition uses the shared diff annotation.
*/
import type { PullRequestReviewThread } from "@t3tools/contracts";
import type {
EnvironmentId,
PullRequestRef,
PullRequestReviewThread,
PullRequestThreadComment,
} from "@t3tools/contracts";
import {
CheckCircle2Icon,
CircleIcon,
HammerIcon,
MessageSquareIcon,
PencilIcon,
Trash2Icon,
} from "lucide-react";
import { useRef, useState } from "react";
@@ -20,6 +26,8 @@ import { Textarea } from "../ui/textarea";
import { isCommentSubmitShortcut } from "../diffs/commentSubmitShortcut";
import { PullRequestActorLabel } from "./pullRequestPresentation";
import { PullRequestMarkdown } from "./PullRequestMarkdown";
import { PullRequestMarkdownEditor } from "./PullRequestMarkdownEditor";
import { PullRequestReactionBar } from "./PullRequestReactions";
import type { PendingReviewComment } from "./pullRequestReviewStore";
const CARD_CLASS =
@@ -82,31 +90,57 @@ export function ReviewThreadCard({
workspaceRoot,
canReply,
canResolve,
canReact,
environmentId,
reference,
pending,
fixPending,
fixLabel = "Fix in a thread",
onFix,
onReply,
canEditComment,
onEditComment,
onToggleResolved,
onReacted,
}: {
thread: PullRequestReviewThread;
workspaceRoot: string;
canReply: boolean;
canResolve: boolean;
canReact: boolean;
environmentId: EnvironmentId;
reference: PullRequestRef;
pending: boolean;
/** True while this thread's own hand-off is preparing, so only its button says so. */
fixPending?: boolean;
fixLabel?: string;
/** Absent where a thread is shown outside the pull request page's reach. */
onFix?: () => void;
/** Resolves to whether the host took it, so a reply that failed keeps the words it was given. */
onReply: (body: string) => Promise<boolean>;
/** Whether this reader wrote this remark, which is what rewriting one takes. */
canEditComment: (comment: PullRequestThreadComment) => boolean;
/** Resolves to whether the host took it, like `onReply`. */
onEditComment: (commentId: string, body: string) => Promise<boolean>;
onToggleResolved: () => void;
onReacted: () => void;
}) {
// A resolved thread is finished work, so it opens collapsed and stays one line until asked for.
const [expanded, setExpanded] = useState(!thread.isResolved);
const [replying, setReplying] = useState(false);
const [reply, setReply] = useState("");
const [editingId, setEditingId] = useState<string | null>(null);
const [savingEdit, setSavingEdit] = useState(false);
const sendingRef = useRef(false);
const saveEdit = async (commentId: string, body: string) => {
if (savingEdit) return;
setSavingEdit(true);
const saved = await onEditComment(commentId, body);
setSavingEdit(false);
if (saved) setEditingId(null);
};
const send = async () => {
const trimmed = reply.trim();
if (trimmed.length === 0 || pending || sendingRef.current) return;
@@ -154,7 +188,7 @@ export function ReviewThreadCard({
onClick={onFix}
>
<HammerIcon className="size-3" />
{fixPending ? "Preparing..." : "Fix in a thread"}
{fixPending ? "Preparing..." : fixLabel}
</Button>
) : null}
{canResolve ? (
@@ -174,15 +208,49 @@ export function ReviewThreadCard({
<>
<div className="mt-2 space-y-3">
{thread.comments.map((comment) => (
<article key={comment.id} className="min-w-0">
<article key={comment.id} className="group min-w-0">
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<PullRequestActorLabel actor={comment.author} className="text-foreground" />
<span>{formatRelativeTimeLabel(comment.createdAt)}</span>
</div>
<PullRequestMarkdown
className="mt-1 text-sm"
text={comment.body}
cwd={workspaceRoot}
{editingId === comment.id ? (
<PullRequestMarkdownEditor
className="mt-1"
value={comment.body}
cwd={workspaceRoot}
label="Edit comment"
saving={savingEdit}
onSave={(body) => void saveEdit(comment.id, body)}
onCancel={() => setEditingId(null)}
/>
) : (
<div className="mt-1 flex items-start gap-1">
<PullRequestMarkdown
className="min-w-0 flex-1 text-sm"
text={comment.body}
cwd={workspaceRoot}
/>
{canEditComment(comment) ? (
<Button
size="icon-xs"
variant="ghost"
className="shrink-0 text-muted-foreground opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100 focus-visible:opacity-100"
aria-label="Edit comment"
onClick={() => setEditingId(comment.id)}
>
<PencilIcon className="size-3" />
</Button>
) : null}
</div>
)}
<PullRequestReactionBar
className="mt-1.5"
reactions={comment.reactions ?? []}
canReact={canReact}
subjectId={comment.id}
environmentId={environmentId}
reference={reference}
onRefresh={onReacted}
/>
</article>
))}
@@ -1,5 +1,3 @@
import type { PullRequestListEntry } from "@t3tools/contracts";
import { memo } from "react";
import { cn } from "~/lib/utils";
@@ -7,6 +5,9 @@ import { getSourceControlPresentationForKind } from "~/sourceControlPresentation
import { formatRelativeTimeLabel } from "~/timestampFormat";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { PullRequestChecksPopover } from "./PullRequestChecksPopover";
import type { EnvironmentPullRequestEntry } from "./pullRequestList.logic";
import { openOnHostLabel, showPullRequestLinkContextMenu } from "./pullRequestLinkContextMenu";
import {
PullRequestActorLabel,
PullRequestDiffStat,
@@ -19,20 +20,23 @@ function PullRequestRowImpl({
selected,
showProjectTitle,
showProvider,
environmentLabel,
matchedElsewhere,
onSelect,
}: {
entry: PullRequestListEntry;
entry: EnvironmentPullRequestEntry;
selected: boolean;
showProjectTitle: boolean;
/** Only when the list spans more than one host, where the repository alone is ambiguous. */
showProvider: boolean;
/** Names the server this row was read from, where the list spans more than one. */
environmentLabel?: string;
/**
* A search found this, but in something the row does not show — a description, a comment, a
* commit message. Saying so is the difference between a result and an apparently random row.
*/
matchedElsewhere?: boolean;
onSelect: (entry: PullRequestListEntry) => void;
onSelect: (entry: EnvironmentPullRequestEntry) => void;
}) {
const { Icon, providerName } = getSourceControlPresentationForKind(entry.provider);
return (
@@ -67,13 +71,52 @@ function PullRequestRowImpl({
<TooltipPopup>{providerName}</TooltipPopup>
</Tooltip>
) : null}
#{entry.number}
{/* The number carries the link, here as much as on the detail: a right-click on it
copies the pull request's own address rather than opening the editing menu. */}
<span
onContextMenu={(event) => {
event.preventDefault();
event.stopPropagation();
void showPullRequestLinkContextMenu({
url: entry.url,
openLabel: openOnHostLabel(entry.provider),
position: { x: event.clientX, y: event.clientY },
});
}}
>
#{entry.number}
</span>
</span>
{showProjectTitle ? <span className="truncate">{entry.repository}</span> : null}
{environmentLabel ? (
<span className="max-w-32 shrink-0 truncate">{environmentLabel}</span>
) : null}
<PullRequestActorLabel actor={entry.author} className="max-w-40 shrink-0" />
<span className="truncate" title={`${entry.headBranch} to ${entry.baseBranch}`}>
{entry.headBranch}
</span>
{/* Only a verdict somebody has actually given: "review required" is the absence of
one, and saying so on every unreviewed row would say nothing. */}
{entry.reviewDecision === "approved" || entry.reviewDecision === "changes-requested" ? (
<span
className={cn(
"shrink-0",
entry.reviewDecision === "approved"
? "text-emerald-600/90 dark:text-emerald-400/80"
: "text-amber-600/90 dark:text-amber-400/80",
)}
>
{entry.reviewDecision === "approved" ? "Approved" : "Changes requested"}
</span>
) : null}
{entry.checksState === undefined ? null : (
<PullRequestChecksPopover
checksState={entry.checksState}
environmentId={entry.environmentId}
reference={{
projectId: entry.projectId,
repository: entry.repository,
number: entry.number,
}}
/>
)}
{matchedElsewhere ? (
<span className="shrink-0 rounded-full border border-border/60 px-1.5 text-[10px]">
matched in the description
@@ -1,13 +1,22 @@
import type { EnvironmentId, PullRequestDetailView, PullRequestRef } from "@t3tools/contracts";
import type {
EnvironmentId,
PullRequestActor,
PullRequestComment,
PullRequestDetailView,
PullRequestRef,
} from "@t3tools/contracts";
import {
ArrowDownUpIcon,
ChevronDownIcon,
ChevronRightIcon,
HammerIcon,
MessageSquareIcon,
PencilIcon,
SendIcon,
TagIcon,
UsersIcon,
} from "lucide-react";
import { useState, type ReactNode } from "react";
import { useRef, useState, type ReactNode } from "react";
import { useAtomCommand } from "~/state/use-atom-command";
import { pullRequestEnvironment } from "~/state/pullRequests";
@@ -21,9 +30,9 @@ import { Textarea } from "../ui/textarea";
import { toastManager } from "../ui/toast";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import {
PullRequestActorAvatar,
PullRequestActorLabel,
PullRequestCheckStatusIcon,
PullRequestMetaLine,
pullRequestCheckStatusLabel,
} from "./pullRequestPresentation";
import { PullRequestReviewerPicker } from "./PullRequestReviewerPicker";
@@ -33,8 +42,149 @@ import {
pullRequestFindingKey,
type PullRequestFinding,
} from "./pullRequestDetail.logic";
import {
canEditPullRequestChangeRequest,
canEditPullRequestComment,
} from "./pullRequestEditing.logic";
import { PullRequestMarkdown } from "./PullRequestMarkdown";
import { PullRequestMarkdownEditor } from "./PullRequestMarkdownEditor";
import { PullRequestReactionBar } from "./PullRequestReactions";
import { PullRequestConversationGhost } from "./PullRequestGhosts";
import { sectionCollapseAnchorScrollTop } from "./pullRequestSummaryScroll.logic";
/** A host colour only when it is one, so a malformed value falls back to the neutral dot. */
function labelDotColor(color: string | null): string | null {
const hex = color?.trim().replace(/^#/, "") ?? "";
return /^[0-9a-fA-F]{6}$/.test(hex) ? `#${hex}` : null;
}
/** The avatar carries the attribution alone; who it is arrives on hover, like the reviewer row. */
function CommentAuthor({ actor }: { actor: PullRequestActor | null }) {
const login = actor?.login ?? "ghost";
return (
<Tooltip>
<TooltipTrigger render={<span className="shrink-0 rounded-full" aria-label={login} />}>
<PullRequestActorAvatar actor={actor} />
</TooltipTrigger>
<TooltipPopup side="bottom">
{actor?.name && actor.name !== login ? `${actor.name} (@${login})` : login}
</TooltipPopup>
</Tooltip>
);
}
/** "CHANGES_REQUESTED" reads as "Changes requested": one capital, the host's underscores gone. */
function reviewStateLabel(state: string): string {
const words = state.toLowerCase().replace(/_/g, " ");
return words.charAt(0).toUpperCase() + words.slice(1);
}
/** What every remark in the conversation needs to be rewritten where it sits. */
interface CommentEditing {
readonly cwd: string;
readonly canEdit: (comment: PullRequestComment) => boolean;
readonly editingId: string | null;
readonly saving: boolean;
readonly onEdit: (comment: PullRequestComment | null) => void;
readonly onSave: (comment: PullRequestComment, body: string) => void;
}
/**
* A remark's words, and the pencil that swaps them for the editor. The pencil is revealed by
* hovering the remark, like the reaction bar's own, so the parent must carry `group`.
*/
function CommentBody({
comment,
editing,
className,
}: {
comment: PullRequestComment;
editing: CommentEditing;
className?: string | undefined;
}) {
if (editing.editingId === comment.id) {
return (
<PullRequestMarkdownEditor
className={className}
value={comment.body}
cwd={editing.cwd}
label="Edit comment"
saving={editing.saving}
onSave={(body) => editing.onSave(comment, body)}
onCancel={() => editing.onEdit(null)}
/>
);
}
return (
<div className={cn("flex items-start gap-1", className)}>
<PullRequestMarkdown className="min-w-0 flex-1" text={comment.body} cwd={editing.cwd} />
{editing.canEdit(comment) ? (
<Button
size="icon-xs"
variant="ghost"
className="shrink-0 text-muted-foreground opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100 focus-visible:opacity-100"
aria-label="Edit comment"
onClick={() => editing.onEdit(comment)}
>
<PencilIcon className="size-3" />
</Button>
) : null}
</div>
);
}
/** Finished work — a resolved conversation or a dismissed approval — opens collapsed. */
function CollapsedComment({
comment,
editing,
label,
reactionBar,
}: {
comment: PullRequestComment;
editing: CommentEditing;
label: string;
reactionBar: ReactNode;
}) {
const [open, setOpen] = useState(false);
return (
<Collapsible open={open} onOpenChange={setOpen}>
<article className="group rounded-lg border border-border/60 [contain-intrinsic-block-size:44px] [content-visibility:auto]">
<CollapsibleTrigger
className={cn(
"flex w-full items-center gap-2 p-3 text-left transition-opacity hover:opacity-100",
open ? "opacity-100" : "opacity-65",
)}
>
<span className="flex min-w-0 flex-1 items-center gap-2 text-xs text-muted-foreground">
<CommentAuthor actor={comment.author} />
<span>{formatRelativeTimeLabel(comment.createdAt)}</span>
<span>{label}</span>
</span>
<ChevronDownIcon
aria-hidden
className={cn(
"size-3.5 shrink-0 text-muted-foreground transition-transform",
open && "rotate-180",
)}
/>
</CollapsibleTrigger>
<CollapsiblePanel>
{open ? (
<div className="px-3 pb-3">
{comment.path ? (
<p className="truncate text-xs text-muted-foreground" title={comment.path}>
{comment.path}
</p>
) : null}
<CommentBody className="mt-2" comment={comment} editing={editing} />
{reactionBar}
</div>
) : null}
</CollapsiblePanel>
</article>
</Collapsible>
);
}
function MetaRow({
icon,
@@ -72,9 +222,39 @@ function Section({
children: ReactNode;
}) {
const [open, setOpen] = useState(defaultOpen);
const headingRef = useRef<HTMLDivElement>(null);
const setOpenWithScrollAnchor = (nextOpen: boolean) => {
if (!nextOpen) {
const heading = headingRef.current;
const section = heading?.closest<HTMLElement>("[data-pull-request-summary-section]");
const scroller = heading?.closest<HTMLElement>("[data-pull-request-summary-scroll]");
if (heading && section && scroller) {
const target = sectionCollapseAnchorScrollTop({
scrollTop: scroller.scrollTop,
viewportTop: scroller.getBoundingClientRect().top,
sectionTop: section.getBoundingClientRect().top,
headingTop: heading.getBoundingClientRect().top,
});
// Synchronous with the press: React commits the collapsed height before the browser
// paints, so the reader sees the heading they pressed stay put rather than a jump first.
if (target !== null) scroller.scrollTop = target;
}
}
setOpen(nextOpen);
};
return (
<Collapsible open={open} onOpenChange={setOpen}>
<div className="flex w-full items-center border-t border-border/60 pr-4">
<Collapsible
open={open}
onOpenChange={setOpenWithScrollAnchor}
data-pull-request-summary-section
>
{/* The heading rides the top of the scroll box the way a diff's file header does, so a
section can be collapsed from wherever its body has been read to rather than only from
where it started. Opaque, because the rows it covers scroll beneath it. */}
<div
ref={headingRef}
className="sticky top-0 z-10 flex w-full items-center border-t border-border/60 bg-background pr-4"
>
{/* Title first, chevron riding to its right, count last: the row reads as a heading
with an affordance rather than a tree node. */}
<CollapsibleTrigger className="flex min-w-0 flex-1 items-center gap-1.5 px-4 py-3 text-left text-sm font-medium">
@@ -174,6 +354,8 @@ export function PullRequestSummaryTab({
activityPending,
activityError,
pendingFinding,
fixFindingLabel = "Fix in a thread",
fixCheckLabel = "Fix",
onFixFinding,
onRefresh,
}: {
@@ -184,6 +366,8 @@ export function PullRequestSummaryTab({
activityError: string | null;
/** The hand-off currently preparing, if any, so only the finding it belongs to says so. */
pendingFinding?: string | null;
fixFindingLabel?: string;
fixCheckLabel?: string;
onFixFinding?: (finding: PullRequestFinding) => void;
onRefresh: () => void;
}) {
@@ -211,8 +395,66 @@ export function PullRequestSummaryTab({
void readLocalApi()?.shell.openExternal(url);
};
const update = useAtomCommand(pullRequestEnvironment.update, { reportFailure: false });
const updateComment = useAtomCommand(pullRequestEnvironment.updateComment, {
reportFailure: false,
});
// Keyed by the pull request, like the comment window above it, so an editor left open never
// reappears over the next pull request's description.
const [bodyScope, setBodyScope] = useState<string | null>(null);
const [bodySaving, setBodySaving] = useState(false);
// The remark being rewritten, named with the pull request it belongs to: a comment id is the
// host's own, and two hosts — or two pull requests on Azure DevOps, which numbers a remark
// inside its thread — hand out the same one. Without the pull request beside it, opening a
// different one would leave its like-numbered remark sitting open in an editor.
const [commentScope, setCommentScope] = useState<{
readonly pullRequest: string;
readonly commentId: string;
} | null>(null);
const [commentSaving, setCommentSaving] = useState(false);
const editingCommentId = commentScope?.pullRequest === detail.url ? commentScope.commentId : null;
const saveBody = async (body: string) => {
if (bodySaving) return;
setBodySaving(true);
const result = await update({ environmentId, input: { ...reference, body } });
setBodySaving(false);
if (result._tag === "Failure") {
toastManager.add({ type: "error", title: "Could not save the description" });
return;
}
setBodyScope(null);
onRefresh();
};
const commentEditing: CommentEditing = {
cwd: detail.workspaceRoot,
canEdit: (comment) => canEditPullRequestComment(detail, comment),
editingId: editingCommentId,
saving: commentSaving,
onEdit: (comment) =>
setCommentScope(comment === null ? null : { pullRequest: detail.url, commentId: comment.id }),
onSave: async (comment, body) => {
// A review's own summary is not a kind any host rewrites, which is why no pencil is ever
// offered on one; the check is here because the comment's own type still allows it.
if (commentSaving || comment.kind === "review") return;
setCommentSaving(true);
const result = await updateComment({
environmentId,
input: { ...reference, commentId: comment.id, kind: comment.kind, body },
});
setCommentSaving(false);
if (result._tag === "Failure") {
toastManager.add({ type: "error", title: "Could not save the comment" });
return;
}
setCommentScope(null);
onRefresh();
},
};
return (
<div className="h-full overflow-y-auto">
<div className="h-full overflow-y-auto" data-pull-request-summary-scroll>
<section className="px-4 py-3">
<div>
<MetaRow icon={<UsersIcon className="size-3.5" />} label="Reviewers">
@@ -261,6 +503,28 @@ export function PullRequestSummaryTab({
) : null}
</span>
</MetaRow>
{detail.labels.length > 0 ? (
<MetaRow icon={<TagIcon className="size-3.5" />} label="Labels">
<span className="flex min-w-0 flex-wrap items-center gap-1">
{detail.labels.map((label) => {
const dot = labelDotColor(label.color);
return (
<span
key={label.name}
className="inline-flex max-w-48 items-center gap-1.5 rounded-full border border-border/70 bg-muted/40 py-0.5 pl-1.5 pr-2 text-xs"
>
<span
aria-hidden
className="size-2 shrink-0 rounded-full bg-muted-foreground"
{...(dot ? { style: { backgroundColor: dot } } : {})}
/>
<span className="truncate">{label.name}</span>
</span>
);
})}
</span>
</MetaRow>
) : null}
<MetaRow icon={<MessageSquareIcon className="size-3.5" />} label="Comments">
{activityPending
? "Loading conversation…"
@@ -274,10 +538,48 @@ export function PullRequestSummaryTab({
</section>
<Section title="Description">
<PullRequestMarkdown
text={detail.body.trim().length > 0 ? detail.body : "_No description provided._"}
cwd={detail.workspaceRoot}
/>
<div className="group">
{bodyScope === detail.url ? (
<PullRequestMarkdownEditor
// Empty is a real answer here: saving nothing is how a description is cleared.
allowEmpty
value={detail.body}
cwd={detail.workspaceRoot}
label="Pull request description"
placeholder="Describe this pull request"
saving={bodySaving}
onSave={(body) => void saveBody(body)}
onCancel={() => setBodyScope(null)}
/>
) : (
<div className="flex items-start gap-1">
<PullRequestMarkdown
className="min-w-0 flex-1"
text={detail.body.trim().length > 0 ? detail.body : "_No description provided._"}
cwd={detail.workspaceRoot}
/>
{canEditPullRequestChangeRequest(detail) ? (
<Button
size="icon-xs"
variant="ghost"
className="shrink-0 text-muted-foreground opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100 focus-visible:opacity-100"
aria-label="Edit description"
onClick={() => setBodyScope(detail.url)}
>
<PencilIcon className="size-3" />
</Button>
) : null}
</div>
)}
<PullRequestReactionBar
className="mt-2"
reactions={detail.reactions ?? []}
canReact={detail.capabilities.reactions === true}
environmentId={environmentId}
reference={reference}
onRefresh={onRefresh}
/>
</div>
</Section>
<Section title="Checks" count={detail.checks.length}>
@@ -285,12 +587,14 @@ export function PullRequestSummaryTab({
<p className="text-xs text-muted-foreground">No checks reported.</p>
) : (
<div className="space-y-0.5">
{detail.checks.map((check) => {
{detail.checks.map((check, index) => {
const finding = { kind: "check", check } as const;
const failing = check.status === "failure" || check.status === "cancelled";
return (
<div
key={`${check.name}:${check.url ?? ""}`}
// Position too: the host decides how many runs share a name, and a repeated
// key would be a rendering fault on top of whatever the list already says.
key={`${index}:${check.name}:${check.url ?? ""}`}
className="group flex items-center gap-1 rounded-md pr-1 hover:bg-accent/60"
>
<button
@@ -319,7 +623,9 @@ export function PullRequestSummaryTab({
onClick={() => onFixFinding(finding)}
>
<HammerIcon className="size-3" />
{pendingFinding === pullRequestFindingKey(finding) ? "Preparing..." : "Fix"}
{pendingFinding === pullRequestFindingKey(finding)
? "Preparing..."
: fixCheckLabel}
</Button>
) : null}
</div>
@@ -385,32 +691,51 @@ export function PullRequestSummaryTab({
) : null}
{visibleComments.map((comment) => {
const thread = threadByCommentId.get(comment.id);
const reviewState = comment.reviewState?.toLowerCase();
if (thread?.isResolved || reviewState === "dismissed") {
return (
<CollapsedComment
key={comment.id}
comment={comment}
editing={commentEditing}
label={thread?.isResolved ? "Resolved" : "Approval dismissed"}
reactionBar={
<PullRequestReactionBar
className="mt-2"
reactions={comment.reactions ?? []}
canReact={detail.capabilities.reactions === true}
subjectId={comment.id}
environmentId={environmentId}
reference={reference}
onRefresh={onRefresh}
/>
}
/>
);
}
// An approval is a verdict, not a finding: there is nothing in it to fix.
const finding: PullRequestFinding | null =
comment.kind !== "review" && comment.kind !== "review-comment"
(comment.kind !== "review" && comment.kind !== "review-comment") ||
reviewState === "approved"
? null
: thread === undefined
? { kind: "comment", comment }
: thread.isResolved
? null
: { kind: "thread", thread };
: { kind: "thread", thread };
return (
<article
key={comment.id}
// Offscreen comments skip style, layout and paint. Bot comments carry pages of
// highlighted code, and the conversation is below the description either way.
className="rounded-lg border border-border/60 p-3 [contain-intrinsic-block-size:120px] [content-visibility:auto]"
className="group rounded-lg border border-border/60 p-3 [contain-intrinsic-block-size:120px] [content-visibility:auto]"
>
<div className="flex items-start gap-2">
<PullRequestMetaLine className="min-w-0 flex-1 text-xs text-muted-foreground">
<PullRequestActorLabel
actor={comment.author}
className="font-medium text-foreground"
/>
<span className="flex min-w-0 flex-1 items-center gap-2 text-xs text-muted-foreground">
<CommentAuthor actor={comment.author} />
<span>{formatRelativeTimeLabel(comment.createdAt)}</span>
{comment.reviewState ? (
<span>{comment.reviewState.toLowerCase()}</span>
<span>{reviewStateLabel(comment.reviewState)}</span>
) : null}
</PullRequestMetaLine>
</span>
{/* Review remarks only. A plain conversation comment is talk, not a finding,
and offering to fix one would promise more than it says. */}
{onFixFinding && finding ? (
@@ -424,7 +749,7 @@ export function PullRequestSummaryTab({
<HammerIcon className="size-3" />
{pendingFinding === pullRequestFindingKey(finding)
? "Preparing..."
: "Fix in a thread"}
: fixFindingLabel}
</Button>
) : null}
</div>
@@ -436,10 +761,15 @@ export function PullRequestSummaryTab({
{comment.path}
</p>
) : null}
<PullRequestMarkdown
<CommentBody className="mt-2" comment={comment} editing={commentEditing} />
<PullRequestReactionBar
className="mt-2"
text={comment.body}
cwd={detail.workspaceRoot}
reactions={comment.reactions ?? []}
canReact={detail.capabilities.reactions === true}
subjectId={comment.id}
environmentId={environmentId}
reference={reference}
onRefresh={onRefresh}
/>
</article>
);
@@ -1,4 +1,10 @@
import type { PullRequestActor, PullRequestDetailView } from "@t3tools/contracts";
import type {
EnvironmentId,
PullRequestActor,
PullRequestComment,
PullRequestDetailView,
PullRequestRef,
} from "@t3tools/contracts";
import {
ChevronDownIcon,
ExternalLinkIcon,
@@ -8,27 +14,42 @@ import {
GitPullRequestClosedIcon,
GitPullRequestIcon,
MessageSquareIcon,
PencilIcon,
} from "lucide-react";
import { useState, type ReactNode } from "react";
import { cn } from "~/lib/utils";
import { readLocalApi } from "~/localApi";
import { pullRequestEnvironment } from "~/state/pullRequests";
import { useAtomCommand } from "~/state/use-atom-command";
import { formatRelativeTimeLabel } from "~/timestampFormat";
import { Button } from "../ui/button";
import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
import { toastManager } from "../ui/toast";
import {
buildPullRequestTimeline,
groupPullRequestTimelineConversations,
type PullRequestTimelineEvent,
} from "./pullRequestDetail.logic";
import { canEditPullRequestComment } from "./pullRequestEditing.logic";
import { PullRequestMarkdown } from "./PullRequestMarkdown";
import { PullRequestMarkdownEditor } from "./PullRequestMarkdownEditor";
import { PullRequestReactionBar } from "./PullRequestReactions";
import {
PullRequestActorAvatar,
PullRequestDiffStat,
PullRequestMetaLine,
} from "./pullRequestPresentation";
/** What every comment on the timeline needs to react; only the subject differs between them. */
interface ReactionSurface {
readonly canReact: boolean;
readonly environmentId: EnvironmentId;
readonly reference: PullRequestRef;
readonly onRefresh: () => void;
}
function TimelineBody({ body, markdown, cwd }: { body: string; markdown: boolean; cwd: string }) {
return (
<div className="mt-3">
@@ -130,15 +151,44 @@ function OpenOnHostButton({ url, onOpen }: { url: string | null; onOpen: (url: s
function ConversationCard({
event,
editable,
cwd,
onOpen,
reactions,
}: {
event: PullRequestTimelineEvent;
/** The remark behind this entry, only where this reader may rewrite it. */
editable: PullRequestComment | null;
cwd: string;
onOpen: (url: string) => void;
reactions: ReactionSurface;
}) {
const [editing, setEditing] = useState(false);
const [saving, setSaving] = useState(false);
const updateComment = useAtomCommand(pullRequestEnvironment.updateComment, {
reportFailure: false,
});
const save = async (body: string) => {
// A review's own summary is not a kind any host rewrites, which is why `editable` is never
// one; the check is here because the comment's own type still allows it.
if (editable === null || saving || editable.kind === "review") return;
setSaving(true);
const result = await updateComment({
environmentId: reactions.environmentId,
input: { ...reactions.reference, commentId: editable.id, kind: editable.kind, body },
});
setSaving(false);
if (result._tag === "Failure") {
toastManager.add({ type: "error", title: "Could not save the comment" });
return;
}
setEditing(false);
reactions.onRefresh();
};
return (
<article className="py-2">
<article className="group py-2">
<div className="px-2">
<div className="flex min-w-0 items-start gap-2">
<div className="min-w-0 flex-1">
@@ -157,14 +207,48 @@ function ConversationCard({
) : null}
</PullRequestMetaLine>
</div>
{editable !== null && !editing ? (
<Button
size="icon-xs"
variant="ghost"
className="-mt-1 shrink-0 text-muted-foreground opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100 focus-visible:opacity-100"
aria-label="Edit comment"
onClick={() => setEditing(true)}
>
<PencilIcon className="size-3" />
</Button>
) : null}
<OpenOnHostButton url={event.url} onOpen={onOpen} />
</div>
</div>
{event.body ? (
{editing && editable !== null ? (
<div className="px-2 pb-2 pt-3">
<PullRequestMarkdownEditor
value={editable.body}
cwd={cwd}
label="Edit comment"
saving={saving}
onSave={(body) => void save(body)}
onCancel={() => setEditing(false)}
/>
</div>
) : event.body ? (
<div className="px-2 pb-2">
<TimelineBody body={event.body} markdown={event.markdown} cwd={cwd} />
</div>
) : null}
{reactions.canReact || event.reactions.length > 0 ? (
<div className="px-2 pb-2">
<PullRequestReactionBar
reactions={event.reactions}
canReact={reactions.canReact}
subjectId={event.id}
environmentId={reactions.environmentId}
reference={reactions.reference}
onRefresh={reactions.onRefresh}
/>
</div>
) : null}
</article>
);
}
@@ -180,12 +264,16 @@ function uniqueConversationActors(events: ReadonlyArray<PullRequestTimelineEvent
function ConversationGroup({
events,
editable,
cwd,
onOpen,
reactions,
}: {
events: ReadonlyArray<PullRequestTimelineEvent>;
editable: ReadonlyMap<string, PullRequestComment>;
cwd: string;
onOpen: (url: string) => void;
reactions: ReactionSurface;
}) {
const [open, setOpen] = useState(false);
const actors = uniqueConversationActors(events);
@@ -229,7 +317,17 @@ function ConversationGroup({
{open ? (
<div className="mt-1 space-y-1">
{events.map((event) => (
<ConversationCard key={event.id} event={event} cwd={cwd} onOpen={onOpen} />
<ConversationCard
// Named with the pull request too: a remark's id is the host's own, and two
// pull requests can hand out the same one — which would leave one card's open
// editor standing over the other's remark.
key={`${reactions.reference.projectId}#${reactions.reference.number}:${event.id}`}
event={event}
editable={editable.get(event.id) ?? null}
cwd={cwd}
onOpen={onOpen}
reactions={reactions}
/>
))}
</div>
) : null}
@@ -315,14 +413,33 @@ function LifecycleEvent({ event }: { event: PullRequestTimelineEvent }) {
export function PullRequestTimelineTab({
detail,
environmentId,
reference,
order,
onOpenCommit,
onRefresh,
}: {
detail: PullRequestDetailView;
environmentId: EnvironmentId;
reference: PullRequestRef;
order: "newest" | "oldest";
onOpenCommit: (oid: string) => void;
onRefresh: () => void;
}) {
const events = buildPullRequestTimeline(detail);
const reactions: ReactionSurface = {
canReact: detail.capabilities.reactions === true,
environmentId,
reference,
onRefresh,
};
// A timeline entry keeps only what it draws, so the remarks this reader may rewrite are looked
// up here by the id the entry carries.
const editable = new Map(
detail.comments
.filter((comment) => canEditPullRequestComment(detail, comment))
.map((comment) => [comment.id, comment] as const),
);
const orderedEvents = order === "newest" ? events : events.toReversed();
const rows = groupPullRequestTimelineConversations(orderedEvents);
const openOnHost = (url: string) => {
@@ -340,8 +457,10 @@ export function PullRequestTimelineTab({
<ConversationGroup
key={`comments:${row.events[0]?.id ?? "empty"}`}
events={row.events}
editable={editable}
cwd={detail.workspaceRoot}
onOpen={openOnHost}
reactions={reactions}
/>
);
}
@@ -0,0 +1,85 @@
import type { EnvironmentId, ProjectId, PullRequestCheck } from "@t3tools/contracts";
import { Children, isValidElement, type ReactNode } from "react";
import { describe, expect, it } from "vite-plus/test";
import { PullRequestChecksPopover } from "./PullRequestChecksPopover";
import type { EnvironmentPullRequestEntry } from "./pullRequestList.logic";
import { PullRequestRow } from "./PullRequestRow";
import { pullRequestChecksState } from "./pullRequestPresentation";
function check(status: PullRequestCheck["status"]): PullRequestCheck {
return { name: `check-${status}`, status, description: null, url: null };
}
describe("pullRequestChecksState", () => {
it("lets a failure outrank a run still going, and reports nothing without checks", () => {
expect(pullRequestChecksState([check("success"), check("pending"), check("failure")])).toBe(
"failing",
);
expect(pullRequestChecksState([check("success"), check("cancelled")])).toBe("failing");
expect(pullRequestChecksState([check("success"), check("pending")])).toBe("pending");
expect(pullRequestChecksState([check("success")])).toBe("passing");
// Skipped and neutral are neither a pass nor a failure, so they are no verdict at all.
expect(pullRequestChecksState([check("skipped"), check("neutral")])).toBe(null);
expect(pullRequestChecksState([])).toBe(null);
});
});
/** Every element of the tree the row returned, so a nested indicator can be looked for. */
function flatten(node: ReactNode): ReadonlyArray<ReturnType<typeof Object>> {
const found: unknown[] = [];
for (const child of Children.toArray(node)) {
if (!isValidElement(child)) continue;
found.push(child);
found.push(...flatten((child.props as { readonly children?: ReactNode }).children));
}
return found as ReadonlyArray<ReturnType<typeof Object>>;
}
function entry(overrides: Partial<EnvironmentPullRequestEntry>): EnvironmentPullRequestEntry {
return {
environmentId: "env-1" as EnvironmentId,
projectId: "project-1" as ProjectId,
provider: "github",
repository: "pingdotgg/t3code",
number: 1,
title: "Add the pull requests page",
url: "https://github.com/pingdotgg/t3code/pull/1",
author: null,
headBranch: "feat/page",
baseBranch: "main",
state: "open",
isDraft: false,
mergeability: "mergeable",
additions: 1,
deletions: 0,
createdAt: "2026-07-01T00:00:00Z",
updatedAt: "2026-07-02T00:00:00Z",
viewerReviewRequested: false,
labels: [],
...overrides,
} as EnvironmentPullRequestEntry;
}
function row(overrides: Partial<EnvironmentPullRequestEntry>): ReactNode {
return PullRequestRow.type({
entry: entry(overrides),
selected: false,
showProjectTitle: false,
showProvider: false,
onSelect: () => {},
});
}
describe("PullRequestRow checks indicator", () => {
function indicators(node: ReactNode): number {
return flatten(node).filter(
(element) => (element as { type?: unknown }).type === PullRequestChecksPopover,
).length;
}
it("shows the indicator only for a row the host reported a rollup for", () => {
expect(indicators(row({ checksState: "failing" }))).toBe(1);
expect(indicators(row({}))).toBe(0);
});
});
@@ -1,8 +1,9 @@
import type {
PullRequestCheck,
PullRequestComment,
PullRequestDetailView,
PullRequestReviewThread,
import {
PullRequestAction,
type PullRequestCheck,
type PullRequestComment,
type PullRequestDetailView,
type PullRequestReviewThread,
} from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
@@ -15,9 +16,13 @@ import {
groupPullRequestTimelineConversations,
handoffPrompt,
handoffReviewComments,
isThreadOwnPullRequest,
orderPullRequestComments,
pullRequestActionNeedsHostRefresh,
pullRequestFindingKey,
pullRequestHandoffLabels,
readableFailure,
resolveBaseFreshness,
buildPullRequestTimeline,
describePullRequestState,
} from "./pullRequestDetail.logic";
@@ -57,6 +62,28 @@ describe("pull request state description", () => {
});
});
describe("pull request handoff labels", () => {
it("names the open thread when actions write to its composer", () => {
expect(pullRequestHandoffLabels(true)).toEqual({
fixFinding: "Fix in this thread",
fixCheck: "Fix in this thread",
fixFindings: "Fix findings in this thread",
resolve: "Resolve in this thread",
resolveConflicts: "Resolve conflicts in this thread",
});
});
it("keeps the standalone pull request page labels", () => {
expect(pullRequestHandoffLabels(false)).toEqual({
fixFinding: "Fix in a thread",
fixCheck: "Fix",
fixFindings: "Fix findings in a thread",
resolve: "Resolve in a new thread",
resolveConflicts: "Resolve conflicts in a thread",
});
});
});
describe("ordering comments", () => {
it("reverses the chronological list for newest first, and leaves oldest first alone", () => {
const comments = [{ createdAt: "a" }, { createdAt: "b" }, { createdAt: "c" }];
@@ -787,3 +814,126 @@ describe("a second ask into the same composer", () => {
]);
});
});
describe("how the branch stands against its base", () => {
const detail = (overrides: Record<string, unknown> = {}) =>
({
state: "open",
mergeability: "mergeable",
baseComparison: "behind",
behindBy: 12,
capabilities: { updateMethods: ["merge", "rebase"] },
viewerPermissions: { updateMethods: ["merge", "rebase"] },
...overrides,
}) as Parameters<typeof resolveBaseFreshness>[0];
it("offers both ways where the host and the reader both allow them", () => {
expect(resolveBaseFreshness(detail())).toEqual({ behindBy: 12, methods: ["merge", "rebase"] });
});
it("says nothing about a branch that is already current", () => {
expect(resolveBaseFreshness(detail({ baseComparison: "up-to-date" }))).toBeNull();
});
it("says nothing where the host could not compare, rather than claiming it is current", () => {
expect(resolveBaseFreshness(detail({ baseComparison: "unknown" }))).toBeNull();
expect(resolveBaseFreshness(detail({ baseComparison: undefined }))).toBeNull();
});
it("leaves a conflicting branch to the conflicts row", () => {
expect(resolveBaseFreshness(detail({ mergeability: "conflicting" }))).toBeNull();
});
it("says nothing where the host has no merge verdict yet", () => {
expect(resolveBaseFreshness(detail({ mergeability: "unknown" }))).toBeNull();
});
it("says nothing about a merged or closed pull request", () => {
expect(resolveBaseFreshness(detail({ state: "merged" }))).toBeNull();
expect(resolveBaseFreshness(detail({ state: "closed" }))).toBeNull();
});
it("narrows to what this reader may actually take", () => {
expect(
resolveBaseFreshness(detail({ viewerPermissions: { updateMethods: ["merge"] } }))?.methods,
).toEqual(["merge"]);
});
it("still reports the news where the reader may take none of it", () => {
// Somebody reading another account's pull request is told why it is blocked without being
// offered a button the host would refuse.
expect(resolveBaseFreshness(detail({ viewerPermissions: {} }))).toEqual({
behindBy: 12,
methods: [],
});
});
it("reports a count only where the host counted", () => {
expect(resolveBaseFreshness(detail({ behindBy: undefined }))?.behindBy).toBeNull();
});
});
describe("whether the panel is showing the thread's own pull request", () => {
const surface = { projectId: "proj-a", repository: "acme/app", number: 7 };
it("matches on project, repository and number together", () => {
expect(
isThreadOwnPullRequest({ projectId: "proj-a", repository: "acme/app", number: 7 }, surface),
).toBe(true);
});
it("rejects a second checkout of the same repository under another project", () => {
expect(
isThreadOwnPullRequest({ projectId: "proj-b", repository: "acme/app", number: 7 }, surface),
).toBe(false);
});
it("rejects another repository or another number", () => {
expect(
isThreadOwnPullRequest({ projectId: "proj-a", repository: "acme/web", number: 7 }, surface),
).toBe(false);
expect(
isThreadOwnPullRequest({ projectId: "proj-a", repository: "acme/app", number: 8 }, surface),
).toBe(false);
});
it("rejects a thread with no project or no pull request of its own", () => {
expect(
isThreadOwnPullRequest({ projectId: null, repository: "acme/app", number: 7 }, surface),
).toBe(false);
expect(
isThreadOwnPullRequest(
{ projectId: "proj-a", repository: "acme/app", number: null },
surface,
),
).toBe(false);
});
});
describe("which actions need the host read again after they run", () => {
it("classifies every action the contract knows about", () => {
// Imported from the contract rather than hand-listed, so a new PullRequestAction fails this
// test until somebody decides which side of the diff it belongs on.
expect(PullRequestAction.literals.map(pullRequestActionNeedsHostRefresh)).toEqual(
PullRequestAction.literals.map((action) => action === "update-branch"),
);
});
it("sends update-branch back to the host, having moved the head commit", () => {
expect(pullRequestActionNeedsHostRefresh("update-branch")).toBe(true);
});
it("leaves every action that only changes metadata to the cheaper detail refresh", () => {
for (const action of [
"ready",
"draft",
"close",
"reopen",
"enable-auto-merge",
"disable-auto-merge",
"merge",
] as const) {
expect(pullRequestActionNeedsHostRefresh(action)).toBe(false);
}
});
});
@@ -1,14 +1,62 @@
import type {
PullRequestAction,
PullRequestActor,
PullRequestBaseComparison,
PullRequestCheck,
PullRequestComment,
PullRequestDetailView,
PullRequestMergeability,
PullRequestReaction,
PullRequestReviewThread,
PullRequestState,
PullRequestUpdateMethod,
} from "@t3tools/contracts";
import { inferReviewCommentFenceLanguage, type ReviewCommentContext } from "~/reviewCommentContext";
/**
* Whether the pull request on a right-panel surface is the thread's own one. Repository and
* number are not enough: one environment can hold two checkouts of the same repository under
* different projects, and the other project's checkout is somebody else's branch.
*/
export function isThreadOwnPullRequest(
thread: {
readonly projectId: string | null;
readonly repository: string | null;
readonly number: number | null;
},
surface: {
readonly projectId: string;
readonly repository: string;
readonly number: number;
},
): boolean {
return (
thread.projectId === surface.projectId &&
thread.repository === surface.repository &&
thread.number === surface.number
);
}
/** Names where a pull-request task will land, without letting each surface guess independently. */
export function pullRequestHandoffLabels(inThisThread: boolean) {
return inThisThread
? {
fixFinding: "Fix in this thread",
fixCheck: "Fix in this thread",
fixFindings: "Fix findings in this thread",
resolve: "Resolve in this thread",
resolveConflicts: "Resolve conflicts in this thread",
}
: {
fixFinding: "Fix in a thread",
fixCheck: "Fix",
fixFindings: "Fix findings in a thread",
resolve: "Resolve in a new thread",
resolveConflicts: "Resolve conflicts in a thread",
};
}
/** Plain-language state, shown beside the author. Conflicts are a merge signal, not a state. */
export function describePullRequestState(state: PullRequestState, isDraft: boolean): string {
if (state === "merged") return "Merged";
@@ -41,6 +89,8 @@ export interface PullRequestTimelineEvent {
readonly deletions: number | null;
readonly path: string | null;
readonly reviewState: string | null;
/** Empty for everything but a comment, which is the only entry a host lets anyone react to. */
readonly reactions: ReadonlyArray<PullRequestReaction>;
}
export type PullRequestTimelineRow =
@@ -111,6 +161,7 @@ export function buildPullRequestTimeline(
deletions: null,
path: null,
reviewState: null,
reactions: [],
},
...detail.commits.map((commit) => ({
id: commit.oid,
@@ -126,6 +177,7 @@ export function buildPullRequestTimeline(
deletions: commit.deletions ?? null,
path: null,
reviewState: null,
reactions: [],
})),
...detail.comments.map((comment) => ({
id: comment.id,
@@ -141,6 +193,7 @@ export function buildPullRequestTimeline(
deletions: null,
path: comment.path,
reviewState: comment.reviewState,
reactions: comment.reactions ?? [],
})),
...(detail.mergedAt
? [
@@ -158,6 +211,7 @@ export function buildPullRequestTimeline(
deletions: null,
path: null,
reviewState: null,
reactions: [],
},
]
: []),
@@ -177,6 +231,7 @@ export function buildPullRequestTimeline(
deletions: null,
path: null,
reviewState: null,
reactions: [],
},
]
: []),
@@ -648,3 +703,62 @@ export function readableFailure(failure: unknown, hint: string): string {
// that contradicts it is worse than no guess at all.
return bounded;
}
/**
* Where the branch stands against its base, said the way GitHub says it: current, out of date but
* still cleanly mergeable, or conflicting. Only the middle one is an offer — the conflicts row
* already speaks for a branch that collides, and a current branch has nothing to report.
*
* Null where there is nothing to show, which is also every host that cannot compare or has not
* said yet: silence is not the same claim as "up to date", and a banner nobody can act on is
* noise. Only a host verdict of "mergeable" earns the clean-merge wording.
*/
export function resolveBaseFreshness(detail: {
readonly state: PullRequestState;
readonly mergeability: PullRequestMergeability;
readonly baseComparison?: PullRequestBaseComparison | undefined;
readonly behindBy?: number | undefined;
readonly capabilities: {
readonly updateMethods?: ReadonlyArray<PullRequestUpdateMethod> | undefined;
};
readonly viewerPermissions: {
readonly updateMethods?: ReadonlyArray<PullRequestUpdateMethod> | undefined;
};
}): {
readonly behindBy: number | null;
/** Empty where the branch is stale but this reader may not move it: news, not an offer. */
readonly methods: ReadonlyArray<PullRequestUpdateMethod>;
} | null {
if (detail.state !== "open" || detail.baseComparison !== "behind") return null;
// A conflicting branch cannot be updated cleanly either, and the conflicts row is already
// saying the more useful half of that. An unknown verdict is not a clean merge in waiting.
if (detail.mergeability !== "mergeable") return null;
const offered = detail.capabilities.updateMethods ?? [];
const allowed = detail.viewerPermissions.updateMethods ?? [];
return {
behindBy: detail.behindBy ?? null,
methods: offered.filter((method) => allowed.includes(method)),
};
}
/**
* Whether a completed action leaves the diff atom pointed at a comparison that no longer exists,
* the same staleness the manual refresh button fixes. Only `update-branch` moves the head commit;
* a merge moves the branch too, but it also closes the pull request, where the diff is no longer
* what anyone is looking at. Written as a `Record` so a new `PullRequestAction` fails to compile
* here until somebody decides which side of the diff it belongs on.
*/
const ACTION_NEEDS_HOST_REFRESH: Record<PullRequestAction, boolean> = {
"update-branch": true,
merge: false,
ready: false,
draft: false,
close: false,
reopen: false,
"enable-auto-merge": false,
"disable-auto-merge": false,
};
export function pullRequestActionNeedsHostRefresh(action: PullRequestAction): boolean {
return ACTION_NEEDS_HOST_REFRESH[action];
}
@@ -0,0 +1,172 @@
import type {
PullRequestActor,
PullRequestCapabilities,
PullRequestComment,
PullRequestDetail,
PullRequestViewerPermissions,
} from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import {
canEditPullRequestChangeRequest,
canEditPullRequestComment,
} from "./pullRequestEditing.logic";
type Subject = Pick<PullRequestDetail, "author" | "capabilities" | "viewer" | "viewerPermissions">;
function actor(login: string): PullRequestActor {
return { login, name: null, avatarUrl: null };
}
function capabilities(edit?: PullRequestCapabilities["edit"]): PullRequestCapabilities {
return {
diff: true,
comment: true,
actions: [],
mergeMethods: [],
search: true,
reactions: true,
review: { inlineComment: true, reply: true, resolve: true, verdicts: [] },
reviewers: { request: true, listCandidates: true },
...(edit === undefined ? {} : { edit }),
};
}
function permissions(
overrides: Partial<PullRequestViewerPermissions> = {},
): PullRequestViewerPermissions {
return {
actions: [],
comment: true,
resolve: true,
verdicts: [],
requestReviewers: true,
...overrides,
};
}
function subject(overrides: Partial<Subject> = {}): Subject {
return {
author: actor("octocat"),
capabilities: capabilities({ changeRequest: true, comment: true }),
viewer: "octocat",
viewerPermissions: permissions(),
...overrides,
};
}
function comment(overrides: Partial<PullRequestComment> = {}): PullRequestComment {
return {
id: "c1",
kind: "issue-comment",
author: actor("octocat"),
body: "words",
createdAt: "2026-01-01T00:00:00.000Z",
url: null,
path: null,
reviewState: null,
...overrides,
};
}
describe("canEditPullRequestChangeRequest", () => {
it("lets the author rewrite their own change request", () => {
expect(canEditPullRequestChangeRequest(subject())).toBe(true);
});
it("matches the author regardless of case", () => {
expect(canEditPullRequestChangeRequest(subject({ viewer: "OctoCat" }))).toBe(true);
});
it("lets somebody who may merge rewrite a change request they did not write", () => {
expect(
canEditPullRequestChangeRequest(
subject({
author: actor("someone-else"),
viewerPermissions: permissions({ actions: ["merge"] }),
}),
),
).toBe(true);
});
it("refuses a reader who neither wrote it nor may merge it", () => {
expect(
canEditPullRequestChangeRequest(
subject({
author: actor("someone-else"),
viewerPermissions: permissions({ actions: ["close"] }),
}),
),
).toBe(false);
});
it("refuses where the host cannot rewrite a change request at all", () => {
expect(
canEditPullRequestChangeRequest(
subject({ capabilities: capabilities({ changeRequest: false, comment: true }) }),
),
).toBe(false);
expect(canEditPullRequestChangeRequest(subject({ capabilities: capabilities() }))).toBe(false);
});
it("refuses where the host did not say who the reader is", () => {
expect(canEditPullRequestChangeRequest(subject({ viewer: undefined }))).toBe(false);
});
it("still allows a merger the host could not name", () => {
expect(
canEditPullRequestChangeRequest(
subject({ viewer: undefined, viewerPermissions: permissions({ actions: ["merge"] }) }),
),
).toBe(true);
});
});
describe("canEditPullRequestComment", () => {
it("lets the reader rewrite their own conversation comment", () => {
expect(canEditPullRequestComment(subject(), comment())).toBe(true);
});
it("lets the reader rewrite their own remark on a line", () => {
expect(canEditPullRequestComment(subject(), comment({ kind: "review-comment" }))).toBe(true);
});
it("matches the author regardless of case", () => {
expect(
canEditPullRequestComment(
subject({ viewer: "OCTOCAT" }),
comment({ author: actor("octocat") }),
),
).toBe(true);
});
it("refuses somebody else's remark", () => {
expect(canEditPullRequestComment(subject(), comment({ author: actor("someone-else") }))).toBe(
false,
);
});
it("refuses a remark the host attributes to nobody", () => {
expect(canEditPullRequestComment(subject(), comment({ author: null }))).toBe(false);
});
it("refuses a review's own summary", () => {
expect(canEditPullRequestComment(subject(), comment({ kind: "review" }))).toBe(false);
});
it("refuses where the host cannot rewrite a remark at all", () => {
expect(
canEditPullRequestComment(
subject({ capabilities: capabilities({ changeRequest: true, comment: false }) }),
comment(),
),
).toBe(false);
expect(canEditPullRequestComment(subject({ capabilities: capabilities() }), comment())).toBe(
false,
);
});
it("refuses where the host did not say who the reader is", () => {
expect(canEditPullRequestComment(subject({ viewer: undefined }), comment())).toBe(false);
});
});
Loaded 100 of 148 files, more files were not shown because too many files have changed in this diff. Show more