Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1eb582bd63 | ||
|
|
f3fb3cb36a | ||
|
|
fe50cbcb90 | ||
|
|
0631f004b4 | ||
|
|
4a375392ab | ||
|
|
fd5a6b032a | ||
|
|
a0becb39e3 | ||
|
|
db1507e986 | ||
|
|
96bfa67b3d | ||
|
|
5ff3a03ada | ||
|
|
23d45d914e | ||
|
|
bad1143b02 | ||
|
|
92d4a2e996 | ||
|
|
2fab18e289 | ||
|
|
1b16ed663f | ||
|
|
83ad26c3a3 | ||
|
|
fd51561b4e | ||
|
|
9e201941aa | ||
|
|
2ab188f1c0 | ||
|
|
9513e62e24 | ||
|
|
97db94c9bf | ||
|
|
5015d7cf9f | ||
|
|
df19f6cfe3 | ||
|
|
6bc6cb6be4 | ||
|
|
1e59b4c400 | ||
|
|
33f9705926 | ||
|
|
da6253b3dd | ||
|
|
ac1264e2ca | ||
|
|
2eb099fdc8 | ||
|
|
b28f9bf0a1 | ||
|
|
d0b8d6306b | ||
|
|
9666b87516 | ||
|
|
e3a9c2518d | ||
|
|
18918d1c4d | ||
|
|
8d24b5131f | ||
|
|
770946d026 | ||
|
|
8601797233 | ||
|
|
b73232bdd3 | ||
|
|
f131228a59 | ||
|
|
e321667b10 | ||
|
|
849bac8946 | ||
|
|
6fd088af9f | ||
|
|
b54bfc9312 | ||
|
|
e1378a1f4d | ||
|
|
5a84614809 | ||
|
|
63e6faef62 | ||
|
|
d37a9b09b8 | ||
|
|
560d4a4560 | ||
|
|
52e5a75a87 | ||
|
|
c196f422ed | ||
|
|
f0b57ca231 | ||
|
|
2db08457f2 | ||
|
|
083fa4ab24 | ||
|
|
35172010b1 | ||
|
|
57b1052679 | ||
|
|
1e355a2a34 | ||
|
|
44621c345f | ||
|
|
220e573b14 | ||
|
|
6befe42eb0 | ||
|
|
b30a9bc414 | ||
|
|
ac4780f451 |
No files matched your search
@@ -37,3 +37,5 @@ github:shivamhwp
|
||||
github:jappyjan
|
||||
github:justsomelegs
|
||||
github:UtkarshUsername
|
||||
github:SunkenInTime
|
||||
github:bil0000
|
||||
@@ -114,7 +114,6 @@ An empty database is a bad test. Seed your worktree's `.t3` with a copy of real
|
||||
- Never make a PR unless the developer explicitly asks you to do so.
|
||||
- Conventional commit titles, plain language: `fix(web): new threads no longer spike CPU`.
|
||||
- Body: the problem in a sentence or two, then how you fixed it. End with the model and harness that did the work.
|
||||
- **Rebase onto latest main before opening.** Stale branches conflict and burn a review round.
|
||||
- UI changes need before/after images. Motion or timing needs a short video.
|
||||
- One concern per PR. If the description says "also", split it.
|
||||
- When babysitting: poll checks and comments newer than the last push, verify each bot finding against the source, fix real ones, dismiss false positives with a written reason. Stay quiet when nothing is new. Stop when the bots are green on the latest commit.
|
||||
|
||||
@@ -31,7 +31,6 @@ const clientSettings: ClientSettings = {
|
||||
glassOpacity: 80,
|
||||
planModeEnabled: false,
|
||||
providerModelPreferences: {},
|
||||
sidebarAutoSettleAfterDays: 3,
|
||||
sidebarProjectGroupingMode: "repository_path",
|
||||
sidebarProjectGroupingOverrides: {
|
||||
"environment-1:/tmp/project-a": "separate",
|
||||
|
||||
@@ -4,16 +4,13 @@ import type { MarkdownNode } from "react-native-nitro-markdown/headless";
|
||||
|
||||
import { CopyTextButton } from "./CopyTextButton";
|
||||
import { MarkdownTextPrimitive } from "./MarkdownTextPrimitive";
|
||||
import {
|
||||
nativeMarkdownDocumentRuns,
|
||||
nativeMarkdownListItemBlocks,
|
||||
nativeMarkdownTextRuns,
|
||||
} from "./nativeMarkdownText";
|
||||
import { nativeMarkdownDocumentRuns, nativeMarkdownListItemBlocks } from "./nativeMarkdownText";
|
||||
import { NativeMarkdownSelectableText } from "./NativeMarkdownSelectableText.ios";
|
||||
import type {
|
||||
MarkdownCodeHighlighter,
|
||||
MarkdownHighlightedToken,
|
||||
NativeMarkdownTextStyle,
|
||||
SelectableMarkdownSkill,
|
||||
} from "./SelectableMarkdownText.types";
|
||||
|
||||
type HighlightedCode = ReadonlyArray<ReadonlyArray<MarkdownHighlightedToken>>;
|
||||
@@ -48,12 +45,13 @@ function documentFor(node: MarkdownNode): MarkdownNode {
|
||||
|
||||
function SelectableNode(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<NativeMarkdownSelectableText
|
||||
runs={nativeMarkdownDocumentRuns(documentFor(props.node))}
|
||||
runs={nativeMarkdownDocumentRuns(documentFor(props.node), props.skills)}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
@@ -322,6 +320,7 @@ function collectTableRows(node: MarkdownNode): MarkdownNode[] {
|
||||
|
||||
function NativeTable(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
}) {
|
||||
@@ -359,7 +358,7 @@ function NativeTable(props: {
|
||||
}}
|
||||
>
|
||||
<NativeMarkdownSelectableText
|
||||
runs={nativeMarkdownTextRuns(cell).map((run) =>
|
||||
runs={nativeMarkdownDocumentRuns(documentFor(cell), props.skills).map((run) =>
|
||||
rowIndex === 0 || cell.isHeader ? { ...run, bold: true } : run,
|
||||
)}
|
||||
textStyle={props.textStyle}
|
||||
@@ -376,6 +375,7 @@ function NativeTable(props: {
|
||||
|
||||
function NativeMarkdownImage(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
}) {
|
||||
@@ -384,6 +384,7 @@ function NativeMarkdownImage(props: {
|
||||
return (
|
||||
<SelectableNode
|
||||
node={props.node}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
@@ -445,6 +446,7 @@ function inlineGroups(nodes: ReadonlyArray<MarkdownNode>): MarkdownNode[] {
|
||||
|
||||
function NativeMixedParagraph(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
}) {
|
||||
@@ -455,6 +457,7 @@ function NativeMixedParagraph(props: {
|
||||
<NativeMarkdownImage
|
||||
key={nodeKey(child, index)}
|
||||
node={child}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
@@ -462,6 +465,7 @@ function NativeMixedParagraph(props: {
|
||||
<SelectableNode
|
||||
key={nodeKey(child, index)}
|
||||
node={child}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
@@ -473,6 +477,7 @@ function NativeMixedParagraph(props: {
|
||||
|
||||
function NativeList(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly highlightCode: MarkdownCodeHighlighter;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
@@ -534,6 +539,7 @@ function NativeList(props: {
|
||||
<NativeMarkdownBlock
|
||||
key={nodeKey(child, childIndex)}
|
||||
node={child}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
onLinkPress={props.onLinkPress}
|
||||
@@ -551,6 +557,7 @@ function NativeList(props: {
|
||||
|
||||
export function NativeMarkdownBlock(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly highlightCode: MarkdownCodeHighlighter;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
@@ -566,6 +573,7 @@ export function NativeMarkdownBlock(props: {
|
||||
<NativeMarkdownBlock
|
||||
key={nodeKey(child, index)}
|
||||
node={child}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
onLinkPress={props.onLinkPress}
|
||||
@@ -587,6 +595,7 @@ export function NativeMarkdownBlock(props: {
|
||||
return (
|
||||
<NativeTable
|
||||
node={props.node}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
@@ -595,6 +604,7 @@ export function NativeMarkdownBlock(props: {
|
||||
return (
|
||||
<NativeMarkdownImage
|
||||
node={props.node}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
@@ -624,6 +634,7 @@ export function NativeMarkdownBlock(props: {
|
||||
<NativeMarkdownBlock
|
||||
key={nodeKey(child, index)}
|
||||
node={child}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
onLinkPress={props.onLinkPress}
|
||||
@@ -637,6 +648,7 @@ export function NativeMarkdownBlock(props: {
|
||||
return (
|
||||
<NativeList
|
||||
node={props.node}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
onLinkPress={props.onLinkPress}
|
||||
@@ -647,12 +659,14 @@ export function NativeMarkdownBlock(props: {
|
||||
return (props.node.children ?? []).some((child) => child.type === "image") ? (
|
||||
<NativeMixedParagraph
|
||||
node={props.node}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
) : (
|
||||
<SelectableNode
|
||||
node={props.node}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
@@ -673,6 +687,7 @@ export function NativeMarkdownBlock(props: {
|
||||
>
|
||||
<SelectableNode
|
||||
node={props.node}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
@@ -690,6 +705,7 @@ export function NativeMarkdownBlock(props: {
|
||||
<NativeMarkdownBlock
|
||||
key={nodeKey(child, index)}
|
||||
node={child}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
onLinkPress={props.onLinkPress}
|
||||
@@ -703,6 +719,7 @@ export function NativeMarkdownBlock(props: {
|
||||
return (
|
||||
<SelectableNode
|
||||
node={props.node}
|
||||
skills={props.skills}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
|
||||
@@ -69,6 +69,7 @@ export function SelectableMarkdownText({
|
||||
chunk.kind === "rich" ? (
|
||||
<NativeMarkdownBlock
|
||||
node={chunk.node}
|
||||
skills={skills}
|
||||
textStyle={textStyle}
|
||||
highlightCode={highlightCode}
|
||||
onLinkPress={onLinkPress}
|
||||
|
||||
@@ -70,15 +70,22 @@ const EMPTY_CONTEXT: RunContext = {
|
||||
|
||||
const INLINE_HTML_TAG_PATTERN = /<\/?(?:kbd|mark|sub|sup|u)(?:\s[^>]*)?>/gi;
|
||||
|
||||
function decodeCodePoint(codePoint: number, entity: string): string {
|
||||
if (!Number.isInteger(codePoint) || codePoint < 0 || codePoint > 0x10ffff) {
|
||||
return entity;
|
||||
}
|
||||
return String.fromCodePoint(codePoint);
|
||||
}
|
||||
|
||||
function decodeHtmlEntitiesOnce(value: string): string {
|
||||
return value.replace(
|
||||
/&(?:#(\d+)|#x([0-9a-f]+)|amp|apos|gt|lt|nbsp|quot);/gi,
|
||||
(entity, decimal: string | undefined, hexadecimal: string | undefined) => {
|
||||
if (decimal) {
|
||||
return String.fromCodePoint(Number.parseInt(decimal, 10));
|
||||
return decodeCodePoint(Number.parseInt(decimal, 10), entity);
|
||||
}
|
||||
if (hexadecimal) {
|
||||
return String.fromCodePoint(Number.parseInt(hexadecimal, 16));
|
||||
return decodeCodePoint(Number.parseInt(hexadecimal, 16), entity);
|
||||
}
|
||||
switch (entity.toLowerCase()) {
|
||||
case "&":
|
||||
@@ -661,6 +668,7 @@ function appendDocumentBlock(
|
||||
function containsRichBlock(node: MarkdownNode): boolean {
|
||||
if (
|
||||
node.type === "code_block" ||
|
||||
node.type === "blockquote" ||
|
||||
node.type === "table" ||
|
||||
node.type === "image" ||
|
||||
node.type === "horizontal_rule" ||
|
||||
|
||||
-97
@@ -1,97 +0,0 @@
|
||||
package expo.modules.t3nativecontrols
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.Paint
|
||||
import android.view.View
|
||||
import expo.modules.kotlin.AppContext
|
||||
import expo.modules.kotlin.viewevent.EventDispatcher
|
||||
import expo.modules.kotlin.views.ExpoView
|
||||
|
||||
class T3HeaderButtonView(context: Context, appContext: AppContext) : ExpoView(context, appContext) {
|
||||
private val iconView = HeaderIconView(context)
|
||||
private val onTriggered by EventDispatcher()
|
||||
|
||||
init {
|
||||
isClickable = true
|
||||
isFocusable = true
|
||||
setOnClickListener {
|
||||
onTriggered(emptyMap<String, Any>())
|
||||
}
|
||||
addView(iconView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
|
||||
}
|
||||
|
||||
fun setLabel(label: String) {
|
||||
contentDescription = label
|
||||
}
|
||||
|
||||
fun setSystemImage(systemImage: String) {
|
||||
iconView.systemImage = systemImage
|
||||
}
|
||||
}
|
||||
|
||||
private class HeaderIconView(context: Context) : View(context) {
|
||||
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
color = Color.parseColor("#6B7280")
|
||||
strokeCap = Paint.Cap.ROUND
|
||||
strokeJoin = Paint.Join.ROUND
|
||||
strokeWidth = 3f * resources.displayMetrics.density
|
||||
style = Paint.Style.STROKE
|
||||
}
|
||||
|
||||
var systemImage: String = "gearshape"
|
||||
set(value) {
|
||||
field = value
|
||||
invalidate()
|
||||
}
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
super.onDraw(canvas)
|
||||
val cx = width / 2f
|
||||
val cy = height / 2f
|
||||
val size = minOf(width, height).toFloat()
|
||||
if (systemImage == "square.and.pencil") {
|
||||
drawNewTask(canvas, cx, cy, size)
|
||||
} else {
|
||||
drawSettings(canvas, cx, cy, size)
|
||||
}
|
||||
}
|
||||
|
||||
private fun drawSettings(canvas: Canvas, cx: Float, cy: Float, size: Float) {
|
||||
val radius = size * 0.12f
|
||||
canvas.drawCircle(cx, cy, radius, paint)
|
||||
for (index in 0 until 8) {
|
||||
val angle = Math.PI * index / 4.0
|
||||
val inner = size * 0.19f
|
||||
val outer = size * 0.27f
|
||||
val sx = cx + kotlin.math.cos(angle).toFloat() * inner
|
||||
val sy = cy + kotlin.math.sin(angle).toFloat() * inner
|
||||
val ex = cx + kotlin.math.cos(angle).toFloat() * outer
|
||||
val ey = cy + kotlin.math.sin(angle).toFloat() * outer
|
||||
canvas.drawLine(sx, sy, ex, ey, paint)
|
||||
}
|
||||
}
|
||||
|
||||
private fun drawNewTask(canvas: Canvas, cx: Float, cy: Float, size: Float) {
|
||||
val left = cx - size * 0.2f
|
||||
val top = cy - size * 0.16f
|
||||
val right = cx + size * 0.14f
|
||||
val bottom = cy + size * 0.2f
|
||||
canvas.drawRoundRect(left, top, right, bottom, size * 0.04f, size * 0.04f, paint)
|
||||
canvas.drawLine(
|
||||
cx - size * 0.02f,
|
||||
cy + size * 0.13f,
|
||||
cx + size * 0.24f,
|
||||
cy - size * 0.13f,
|
||||
paint
|
||||
)
|
||||
canvas.drawLine(
|
||||
cx + size * 0.17f,
|
||||
cy - size * 0.2f,
|
||||
cx + size * 0.24f,
|
||||
cy - size * 0.13f,
|
||||
paint
|
||||
)
|
||||
}
|
||||
}
|
||||
-11
@@ -32,16 +32,5 @@ class T3NativeControlsModule : Module() {
|
||||
?.resolve("t3-showcase-ready")
|
||||
?.writeText(scene)
|
||||
}
|
||||
|
||||
View(T3HeaderButtonView::class) {
|
||||
Prop("label") { view: T3HeaderButtonView, label: String ->
|
||||
view.setLabel(label)
|
||||
}
|
||||
Prop("systemImage") { view: T3HeaderButtonView, systemImage: String ->
|
||||
view.setSystemImage(systemImage)
|
||||
}
|
||||
|
||||
Events("onTriggered")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
import ExpoModulesCore
|
||||
import UIKit
|
||||
|
||||
public final class T3HeaderButtonView: ExpoView {
|
||||
private static let size: CGFloat = 44
|
||||
private static let symbolSize: CGFloat = 18
|
||||
|
||||
private let button = UIButton(type: .system)
|
||||
private var systemImage = "circle"
|
||||
|
||||
let onTriggered = EventDispatcher()
|
||||
|
||||
public required init(appContext: AppContext? = nil) {
|
||||
super.init(appContext: appContext)
|
||||
|
||||
isAccessibilityElement = false
|
||||
button.frame = bounds
|
||||
button.autoresizingMask = [.flexibleWidth, .flexibleHeight]
|
||||
button.addTarget(self, action: #selector(handlePress), for: .primaryActionTriggered)
|
||||
addSubview(button)
|
||||
applyConfiguration()
|
||||
}
|
||||
|
||||
public override var intrinsicContentSize: CGSize {
|
||||
CGSize(width: Self.size, height: Self.size)
|
||||
}
|
||||
|
||||
public func setLabel(_ label: String) {
|
||||
button.accessibilityLabel = label
|
||||
}
|
||||
|
||||
public func setSystemImage(_ systemImage: String) {
|
||||
guard self.systemImage != systemImage else {
|
||||
return
|
||||
}
|
||||
self.systemImage = systemImage
|
||||
applyConfiguration()
|
||||
}
|
||||
|
||||
private func applyConfiguration() {
|
||||
var configuration: UIButton.Configuration
|
||||
if #available(iOS 26.0, *) {
|
||||
configuration = .glass()
|
||||
configuration.cornerStyle = .capsule
|
||||
} else {
|
||||
configuration = .plain()
|
||||
}
|
||||
|
||||
configuration.baseForegroundColor = .label
|
||||
configuration.contentInsets = .zero
|
||||
configuration.image = UIImage(systemName: systemImage)
|
||||
configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(
|
||||
pointSize: Self.symbolSize,
|
||||
weight: .regular
|
||||
)
|
||||
button.configuration = configuration
|
||||
}
|
||||
|
||||
@objc private func handlePress() {
|
||||
onTriggered()
|
||||
}
|
||||
}
|
||||
@@ -87,16 +87,5 @@ public final class T3NativeControlsModule: Module {
|
||||
let readyPath = NSHomeDirectory() + "/Library/Caches/T3ShowcaseReadyScene"
|
||||
try? scene.write(toFile: readyPath, atomically: true, encoding: .utf8)
|
||||
}
|
||||
|
||||
View(T3HeaderButtonView.self) {
|
||||
Prop("label") { (view: T3HeaderButtonView, label: String) in
|
||||
view.setLabel(label)
|
||||
}
|
||||
Prop("systemImage") { (view: T3HeaderButtonView, systemImage: String) in
|
||||
view.setSystemImage(systemImage)
|
||||
}
|
||||
|
||||
Events("onTriggered")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -278,13 +278,6 @@ export function AndroidAnchoredMenu(props: AndroidAnchoredMenuProps) {
|
||||
<Pressable
|
||||
key={action.id ?? `${index}-${action.title}`}
|
||||
android_ripple={{ color: rippleColor }}
|
||||
accessibilityRole="menuitem"
|
||||
accessibilityState={{
|
||||
disabled,
|
||||
...(action.state === undefined
|
||||
? {}
|
||||
: { selected: action.state === "on" }),
|
||||
}}
|
||||
disabled={disabled}
|
||||
className={cn(
|
||||
"min-h-11 flex-row items-center gap-2.5 px-3.5 py-2.5",
|
||||
|
||||
@@ -45,6 +45,7 @@ export function HomeRouteScreen() {
|
||||
pinThread,
|
||||
unpinThread,
|
||||
movePinnedThread,
|
||||
regenerateThreadTitle,
|
||||
unsettleThread,
|
||||
} = useThreadListActions();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
@@ -186,6 +187,7 @@ export function HomeRouteScreen() {
|
||||
onPinThread={pinThread}
|
||||
onUnpinThread={unpinThread}
|
||||
onMovePinnedThread={movePinnedThread}
|
||||
onRegenerateThreadTitle={regenerateThreadTitle}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onProjectChange={setSelectedProjectKey}
|
||||
onOpenSettings={() =>
|
||||
|
||||
@@ -115,6 +115,7 @@ interface HomeScreenProps {
|
||||
thread: EnvironmentThreadShell,
|
||||
direction: "up" | "down",
|
||||
) => Promise<boolean>;
|
||||
readonly onRegenerateThreadTitle: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onNewThreadInProject: (project: EnvironmentProject) => void;
|
||||
@@ -482,26 +483,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
// Settled threads stay in the live shell stream (settled ≠ archived), so
|
||||
// the partition works directly off live shells — no snapshot merging or
|
||||
// optimistic holds.
|
||||
// PR states stream in per-row (rows own the VCS subscriptions); a merged or
|
||||
// closed PR auto-settles its thread on the next partition (mirrors web).
|
||||
const [changeRequestStateByKey, setChangeRequestStateByKey] = useState<
|
||||
ReadonlyMap<string, "open" | "closed" | "merged">
|
||||
>(() => new Map());
|
||||
const handleChangeRequestState = useCallback(
|
||||
(threadKey: string, state: "open" | "closed" | "merged" | null) => {
|
||||
setChangeRequestStateByKey((current) => {
|
||||
if ((current.get(threadKey) ?? null) === state) return current;
|
||||
const next = new Map(current);
|
||||
if (state === null) {
|
||||
next.delete(threadKey);
|
||||
} else {
|
||||
next.set(threadKey, state);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
},
|
||||
[],
|
||||
);
|
||||
const handleSettleThread = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
void props.onSettleThread(thread);
|
||||
@@ -538,6 +519,12 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
},
|
||||
[props.onUnpinThread],
|
||||
);
|
||||
const handleRegenerateThreadTitle = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
void props.onRegenerateThreadTitle(thread);
|
||||
},
|
||||
[props.onRegenerateThreadTitle],
|
||||
);
|
||||
const handleDeleteThread = props.onDeleteThread;
|
||||
const handleUnsettleThread = props.onUnsettleThread;
|
||||
// The settled tail renders in pages; expansion resets when the filter
|
||||
@@ -559,9 +546,8 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
const toggleSnoozedShelf = useCallback(() => setSnoozedShelfExpanded((value) => !value), []);
|
||||
const [settledShelfExpanded, setSettledShelfExpanded] = useState(true);
|
||||
const toggleSettledShelf = useCallback(() => setSettledShelfExpanded((value) => !value), []);
|
||||
// now is quantized to the minute and ticks so the inactivity auto-settle
|
||||
// boundary is actually crossed while the app stays open (mirrors web);
|
||||
// without a clock dependency the partition memoizes a frozen "now".
|
||||
// The minute tick only refreshes snooze labels and preset choices;
|
||||
// settlement itself is projected server state.
|
||||
const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
|
||||
// Snooze wake times are second-precise; a counter bumped exactly at the
|
||||
// next wake boundary re-runs the partition with a fresh clock so a woken
|
||||
@@ -569,9 +555,8 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
|
||||
useEffect(() => {
|
||||
if (!threadListV2Enabled) return;
|
||||
// Refresh immediately on enable: the mount-time value can be hours old
|
||||
// by the time the beta is switched on, which would misclassify the
|
||||
// inactivity auto-settle boundary until the first tick.
|
||||
// Refresh immediately on enable so snooze labels do not inherit an old
|
||||
// mount-time value.
|
||||
setNowMinute(new Date().toISOString().slice(0, 16));
|
||||
const id = setInterval(() => setNowMinute(new Date().toISOString().slice(0, 16)), 60_000);
|
||||
return () => clearInterval(id);
|
||||
@@ -615,6 +600,15 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const titleRegenerationEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadTitleRegeneration === true) {
|
||||
supported.add(environmentId);
|
||||
}
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
// Canonical arranged pinned order (reorder-capable threads only) for the
|
||||
// Move up/down position flags. Computed from all shells, not the rendered
|
||||
// list, so search/scope filtering never disables or misdirects a move.
|
||||
@@ -648,7 +642,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
projectRefs: v2ScopedProjectGroup === null ? null : v2ScopedProjectGroup.projectRefs,
|
||||
searchQuery: props.searchQuery,
|
||||
matchedThreadKeys,
|
||||
changeRequestStateByKey,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
settledLimit: settledVisibleCount,
|
||||
@@ -659,7 +652,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
selectedThreadKey: null,
|
||||
});
|
||||
}, [
|
||||
changeRequestStateByKey,
|
||||
nowMinute,
|
||||
snoozeWakeTick,
|
||||
snoozedShelfExpanded,
|
||||
@@ -811,6 +803,8 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
onSelectThread={props.onSelectThread}
|
||||
onDeleteThread={handleDeleteThread}
|
||||
onArchiveThread={props.onArchiveThread}
|
||||
onRegenerateThreadTitle={handleRegenerateThreadTitle}
|
||||
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
|
||||
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
|
||||
onSettleThread={handleSettleThread}
|
||||
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
|
||||
@@ -827,7 +821,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
onPinThread={handlePinThread}
|
||||
onUnpinThread={handleUnpinThread}
|
||||
onMovePinnedThread={handleMovePinnedThread}
|
||||
onChangeRequestState={handleChangeRequestState}
|
||||
projectCwd={
|
||||
projectCwdByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
|
||||
}
|
||||
@@ -837,11 +830,11 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
);
|
||||
},
|
||||
[
|
||||
handleChangeRequestState,
|
||||
handleDeleteThread,
|
||||
arrangedPinnedKeys,
|
||||
handleMovePinnedThread,
|
||||
handlePinThread,
|
||||
handleRegenerateThreadTitle,
|
||||
handleSettleThread,
|
||||
handleSnoozeThread,
|
||||
handleUnpinThread,
|
||||
@@ -863,6 +856,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
snoozeEnvironmentIds,
|
||||
threadListV2Items,
|
||||
threadSearchMatchByKey,
|
||||
titleRegenerationEnvironmentIds,
|
||||
toggleSettledShelf,
|
||||
toggleSnoozedShelf,
|
||||
v2ProjectTitleByProjectKey,
|
||||
@@ -967,6 +961,8 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
searchQuery={props.searchQuery}
|
||||
onArchiveThread={props.onArchiveThread}
|
||||
onDeleteThread={props.onDeleteThread}
|
||||
onRegenerateThreadTitle={handleRegenerateThreadTitle}
|
||||
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
|
||||
onSelectThread={props.onSelectThread}
|
||||
onSwipeableClose={handleSwipeableClose}
|
||||
onSwipeableWillOpen={handleSwipeableWillOpen}
|
||||
@@ -988,6 +984,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
[
|
||||
handleSwipeableClose,
|
||||
handleSwipeableWillOpen,
|
||||
handleRegenerateThreadTitle,
|
||||
projectCwdByKey,
|
||||
props.onArchiveThread,
|
||||
props.onDeletePendingTask,
|
||||
@@ -998,6 +995,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
props.searchQuery,
|
||||
props.savedConnectionsById,
|
||||
threadSearchMatchByKey,
|
||||
titleRegenerationEnvironmentIds,
|
||||
updateGroupDisplay,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -48,6 +48,15 @@ function environmentSupportsPinReorder(environmentId: EnvironmentThreadShell["en
|
||||
);
|
||||
}
|
||||
|
||||
function environmentSupportsTitleRegeneration(
|
||||
environmentId: EnvironmentThreadShell["environmentId"],
|
||||
) {
|
||||
return (
|
||||
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
|
||||
.threadTitleRegeneration === true
|
||||
);
|
||||
}
|
||||
|
||||
type ThreadListAction = "archive" | "unarchive" | "delete" | "settle" | "unsettle";
|
||||
|
||||
const ACTION_VERBS: Record<ThreadListAction, string> = {
|
||||
@@ -109,9 +118,8 @@ function useThreadActionExecutor(
|
||||
);
|
||||
return false;
|
||||
}
|
||||
// Settle may only target what effectiveSettled could classify as
|
||||
// settled: not starting/running sessions, not threads waiting on
|
||||
// approvals or user input. Anything else would hide live work.
|
||||
// Mirror the server's explicit-settle guard so obviously blocked
|
||||
// requests fail locally instead of making a round trip.
|
||||
if (action === "settle" && !canSettle(thread, { now: new Date().toISOString() })) {
|
||||
Alert.alert(
|
||||
actionFailureTitle(action),
|
||||
@@ -134,8 +142,8 @@ function useThreadActionExecutor(
|
||||
}
|
||||
const result =
|
||||
action === "unsettle"
|
||||
? // reason "user" pins the thread active: auto-settle stays
|
||||
// suppressed until real activity clears the pin server-side.
|
||||
? // reason "user" holds the thread active: automation stays
|
||||
// suppressed until real activity clears the override.
|
||||
await unsettleMutation({
|
||||
environmentId: thread.environmentId,
|
||||
input: { threadId: thread.id, reason: "user" },
|
||||
@@ -227,13 +235,18 @@ export function useThreadListActions(): {
|
||||
thread: EnvironmentThreadShell,
|
||||
direction: "up" | "down",
|
||||
) => Promise<boolean>;
|
||||
readonly regenerateThreadTitle: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
} {
|
||||
const executeAction = useThreadActionExecutor();
|
||||
const snoozeMutation = useAtomCommand(threadEnvironment.snooze, { reportFailure: false });
|
||||
const unsnoozeMutation = useAtomCommand(threadEnvironment.unsnooze, { reportFailure: false });
|
||||
const pinMutation = useAtomCommand(threadEnvironment.pin, { reportFailure: false });
|
||||
const unpinMutation = useAtomCommand(threadEnvironment.unpin, { reportFailure: false });
|
||||
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const snoozeInFlightThreadKeys = useRef(new Set<string>());
|
||||
const titleRegenerationInFlightThreadKeys = useRef(new Set<string>());
|
||||
|
||||
const archiveThread = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
@@ -405,6 +418,47 @@ export function useThreadListActions(): {
|
||||
},
|
||||
[unpinMutation],
|
||||
);
|
||||
const regenerateThreadTitle = useCallback(
|
||||
async (thread: EnvironmentThreadShell) => {
|
||||
const key = scopedThreadKey(thread.environmentId, thread.id);
|
||||
if (
|
||||
thread.titleRegeneration != null ||
|
||||
titleRegenerationInFlightThreadKeys.current.has(key)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (!environmentSupportsTitleRegeneration(thread.environmentId)) {
|
||||
Alert.alert(
|
||||
"Could not regenerate title",
|
||||
"This environment's server does not support title regeneration yet. Update the server to regenerate thread titles.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
titleRegenerationInFlightThreadKeys.current.add(key);
|
||||
selectionHaptic();
|
||||
try {
|
||||
const result = await updateThreadMetadata({
|
||||
environmentId: thread.environmentId,
|
||||
input: { threadId: thread.id, regenerateTitle: true },
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
const error = Cause.squash(result.cause);
|
||||
Alert.alert(
|
||||
"Could not regenerate title",
|
||||
error instanceof Error && error.message.trim().length > 0
|
||||
? error.message
|
||||
: "The thread title could not be regenerated.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} finally {
|
||||
titleRegenerationInFlightThreadKeys.current.delete(key);
|
||||
}
|
||||
},
|
||||
[updateThreadMetadata],
|
||||
);
|
||||
|
||||
// Move up / Move down for the pinned block. Computed against the CANONICAL
|
||||
// keyed pinned order (not the rendered list), so the move is valid even
|
||||
@@ -497,6 +551,7 @@ export function useThreadListActions(): {
|
||||
pinThread,
|
||||
unpinThread,
|
||||
movePinnedThread,
|
||||
regenerateThreadTitle,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -32,9 +32,12 @@ import { refreshManagedRelayEnvironments } from "../cloud/managedRelayState";
|
||||
import { hasCloudPublicConfig, resolveRelayClerkTokenOptions } from "../cloud/publicConfig";
|
||||
import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";
|
||||
import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
|
||||
import { environmentCatalog } from "../../connection/catalog";
|
||||
import { runtime } from "../../lib/runtime";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
|
||||
import { environmentServerConfigsAtom, serverEnvironment } from "../../state/server";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
|
||||
import {
|
||||
type AppUpdateCheckState,
|
||||
@@ -522,9 +525,46 @@ function ConfiguredSettingsRouteScreen() {
|
||||
}
|
||||
|
||||
function GeneralSettingsSection() {
|
||||
const environmentCatalogState = useAtomValue(environmentCatalog.catalogValueAtom);
|
||||
const serverConfigs = useAtomValue(environmentServerConfigsAtom);
|
||||
const updateServerSettings = useAtomCommand(
|
||||
serverEnvironment.updateSettings,
|
||||
"server settings update",
|
||||
);
|
||||
const environmentIds = useMemo(
|
||||
() => [...environmentCatalogState.entries.keys()],
|
||||
[environmentCatalogState.entries],
|
||||
);
|
||||
const allServerConfigsAvailable =
|
||||
environmentCatalogState.isReady &&
|
||||
environmentIds.length > 0 &&
|
||||
environmentIds.every((environmentId) => serverConfigs.has(environmentId));
|
||||
const autoSettleOnMerge = environmentIds.every(
|
||||
(environmentId) => serverConfigs.get(environmentId)?.settings.threadAutoSettleOnMerge !== false,
|
||||
);
|
||||
const handleAutoSettleOnMergeChange = useCallback(
|
||||
(value: boolean) => {
|
||||
if (!allServerConfigsAvailable) return;
|
||||
for (const environmentId of environmentIds) {
|
||||
void updateServerSettings({
|
||||
environmentId,
|
||||
input: { patch: { threadAutoSettleOnMerge: value } },
|
||||
});
|
||||
}
|
||||
},
|
||||
[allServerConfigsAvailable, environmentIds, updateServerSettings],
|
||||
);
|
||||
|
||||
return (
|
||||
<SettingsSection title="General">
|
||||
<SettingsRow icon="folder" label="Project Grouping" target="SettingsProjectGrouping" />
|
||||
<SettingsSwitchRow
|
||||
icon="arrow.triangle.branch"
|
||||
label="Auto-settle merged threads"
|
||||
disabled={!allServerConfigsAvailable}
|
||||
value={autoSettleOnMerge}
|
||||
onValueChange={handleAutoSettleOnMergeChange}
|
||||
/>
|
||||
<SettingsRow icon="chart.bar.xaxis" label="Usage" target="SettingsUsage" />
|
||||
</SettingsSection>
|
||||
);
|
||||
|
||||
@@ -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 &&
|
||||
|
||||
@@ -211,6 +211,7 @@ function ThreadNavigationSidebarPane(
|
||||
pinThread,
|
||||
unpinThread,
|
||||
movePinnedThread,
|
||||
regenerateThreadTitle,
|
||||
} = useThreadListActions();
|
||||
const threadListV2Enabled = useThreadListV2Enabled();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
@@ -410,26 +411,6 @@ function ThreadNavigationSidebarPane(
|
||||
|
||||
// Thread List v2 (beta) support — same model as the compact Home list
|
||||
// (HomeScreen.tsx): flat creation-order card block + settled recency tail.
|
||||
// PR states stream in per-row; merged/closed PRs auto-settle their thread
|
||||
// on the next partition.
|
||||
const [changeRequestStateByKey, setChangeRequestStateByKey] = useState<
|
||||
ReadonlyMap<string, "open" | "closed" | "merged">
|
||||
>(() => new Map());
|
||||
const handleChangeRequestState = useCallback(
|
||||
(threadKey: string, state: "open" | "closed" | "merged" | null) => {
|
||||
setChangeRequestStateByKey((current) => {
|
||||
if ((current.get(threadKey) ?? null) === state) return current;
|
||||
const next = new Map(current);
|
||||
if (state === null) {
|
||||
next.delete(threadKey);
|
||||
} else {
|
||||
next.set(threadKey, state);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
},
|
||||
[],
|
||||
);
|
||||
// The settled tail renders in pages; expansion resets when the filter
|
||||
// context changes so environment/search flips never inherit a deep page.
|
||||
const [settledVisibleCount, setSettledVisibleCount] = useState(
|
||||
@@ -449,9 +430,8 @@ function ThreadNavigationSidebarPane(
|
||||
const toggleSnoozedShelf = useCallback(() => setSnoozedShelfExpanded((value) => !value), []);
|
||||
const [settledShelfExpanded, setSettledShelfExpanded] = useState(true);
|
||||
const toggleSettledShelf = useCallback(() => setSettledShelfExpanded((value) => !value), []);
|
||||
// now ticks per minute so the inactivity auto-settle boundary is actually
|
||||
// crossed while the pane stays open; without a clock dependency the
|
||||
// partition memoizes a frozen "now".
|
||||
// The minute tick only refreshes snooze labels and preset choices;
|
||||
// settlement itself is projected server state.
|
||||
const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
|
||||
// Snooze wake times are second-precise; a counter bumped exactly at the
|
||||
// next wake boundary re-runs the partition with a fresh clock so a woken
|
||||
@@ -459,9 +439,8 @@ function ThreadNavigationSidebarPane(
|
||||
const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
|
||||
useEffect(() => {
|
||||
if (!threadListV2Enabled) return;
|
||||
// Refresh immediately on enable: the mount-time value can be hours old
|
||||
// by the time the beta is switched on, which would misclassify the
|
||||
// inactivity auto-settle boundary until the first tick.
|
||||
// Refresh immediately on enable so snooze labels do not inherit an old
|
||||
// mount-time value.
|
||||
setNowMinute(new Date().toISOString().slice(0, 16));
|
||||
const id = setInterval(() => setNowMinute(new Date().toISOString().slice(0, 16)), 60_000);
|
||||
return () => clearInterval(id);
|
||||
@@ -505,6 +484,15 @@ function ThreadNavigationSidebarPane(
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const titleRegenerationEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadTitleRegeneration === true) {
|
||||
supported.add(environmentId);
|
||||
}
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
// Canonical arranged pinned order for Move up/down flags — computed from
|
||||
// all shells so search/scope filtering never disables a valid move.
|
||||
const arrangedPinnedKeys = useMemo(() => {
|
||||
@@ -535,7 +523,6 @@ function ThreadNavigationSidebarPane(
|
||||
projectRefs: selectedProjectScope === null ? null : selectedProjectScope.projectRefs,
|
||||
searchQuery: props.searchQuery,
|
||||
matchedThreadKeys,
|
||||
changeRequestStateByKey,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
settledLimit: settledVisibleCount,
|
||||
@@ -546,7 +533,6 @@ function ThreadNavigationSidebarPane(
|
||||
selectedThreadKey: props.selectedThreadKey ?? null,
|
||||
});
|
||||
}, [
|
||||
changeRequestStateByKey,
|
||||
nowMinute,
|
||||
snoozeWakeTick,
|
||||
snoozedShelfExpanded,
|
||||
@@ -950,6 +936,8 @@ function ThreadNavigationSidebarPane(
|
||||
onSelectThread={handleSelectThread}
|
||||
onDeleteThread={confirmDeleteThread}
|
||||
onArchiveThread={archiveThread}
|
||||
onRegenerateThreadTitle={regenerateThreadTitle}
|
||||
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
|
||||
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
|
||||
onSettleThread={settleThread}
|
||||
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
|
||||
@@ -968,7 +956,6 @@ function ThreadNavigationSidebarPane(
|
||||
onPinThread={pinThread}
|
||||
onUnpinThread={unpinThread}
|
||||
onMovePinnedThread={movePinnedThread}
|
||||
onChangeRequestState={handleChangeRequestState}
|
||||
projectCwd={projectCwdByKey.get(scopeKey) ?? null}
|
||||
onSwipeableClose={handleSwipeableClose}
|
||||
onSwipeableWillOpen={handleSwipeableWillOpen}
|
||||
@@ -1067,6 +1054,8 @@ function ThreadNavigationSidebarPane(
|
||||
fullSwipeWidth={props.width - 20}
|
||||
onArchiveThread={archiveThread}
|
||||
onDeleteThread={confirmDeleteThread}
|
||||
onRegenerateThreadTitle={regenerateThreadTitle}
|
||||
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
|
||||
onSelectThread={handleSelectThread}
|
||||
onSwipeableClose={handleSwipeableClose}
|
||||
onSwipeableWillOpen={handleSwipeableWillOpen}
|
||||
@@ -1091,7 +1080,6 @@ function ThreadNavigationSidebarPane(
|
||||
arrangedPinnedKeys,
|
||||
confirmDeletePendingTask,
|
||||
confirmDeleteThread,
|
||||
handleChangeRequestState,
|
||||
handleSelectThread,
|
||||
handleSwipeableClose,
|
||||
handleSwipeableWillOpen,
|
||||
@@ -1103,6 +1091,7 @@ function ThreadNavigationSidebarPane(
|
||||
projectByKey,
|
||||
projectCwdByKey,
|
||||
projectTitleByProjectKey,
|
||||
regenerateThreadTitle,
|
||||
props.onNewThreadInProject,
|
||||
props.searchQuery,
|
||||
props.selectedThreadKey,
|
||||
@@ -1110,6 +1099,7 @@ function ThreadNavigationSidebarPane(
|
||||
savedConnectionsById,
|
||||
serverConfigs,
|
||||
threadSearchMatchByKey,
|
||||
titleRegenerationEnvironmentIds,
|
||||
settleThread,
|
||||
settlementEnvironmentIds,
|
||||
showMoreSettled,
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
import { View } from "react-native";
|
||||
|
||||
import { T3HeaderButton } from "../../native/T3HeaderButton.android";
|
||||
import type { SidebarHeaderActionsProps } from "./sidebar-header-actions";
|
||||
|
||||
export function SidebarHeaderActions(props: SidebarHeaderActionsProps) {
|
||||
return (
|
||||
<View className="h-11 flex-row gap-1">
|
||||
<T3HeaderButton
|
||||
accessibilityLabel="Open settings"
|
||||
icon="gearshape"
|
||||
onPress={props.onOpenSettings}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -22,6 +22,7 @@ import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
import { useThreadPr, type ThreadPr } from "../../state/use-thread-pr";
|
||||
import type { HomeGroupDisplayAction } from "../home/homeListItems";
|
||||
import { ThreadSwipeable } from "../home/thread-swipe-actions";
|
||||
import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
|
||||
import { resolveThreadStatus } from "./threadPresentation";
|
||||
import { ThreadSearchMatchExcerpt } from "./thread-search-match";
|
||||
|
||||
@@ -430,6 +431,8 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
|
||||
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onRegenerateThreadTitle: (thread: EnvironmentThreadShell) => void;
|
||||
readonly titleRegenerationSupported: boolean;
|
||||
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
|
||||
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
|
||||
readonly simultaneousSwipeGesture?: ComponentProps<
|
||||
@@ -451,7 +454,8 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
|
||||
const pressedBackgroundColor = useThemeColor("--color-subtle");
|
||||
const selectedBackgroundColor = useThemeColor("--color-user-bubble");
|
||||
|
||||
const { thread, onSelectThread, onArchiveThread, onDeleteThread } = props;
|
||||
const { thread, onSelectThread, onArchiveThread, onDeleteThread, onRegenerateThreadTitle } =
|
||||
props;
|
||||
const status = resolveThreadStatus(thread);
|
||||
const pr = useThreadPr(thread, props.projectCwd);
|
||||
const timestamp = relativeTime(
|
||||
@@ -471,6 +475,21 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
|
||||
|
||||
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
|
||||
const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]);
|
||||
const handleRegenerateTitle = useCallback(
|
||||
() => onRegenerateThreadTitle(thread),
|
||||
[onRegenerateThreadTitle, thread],
|
||||
);
|
||||
const menuActions = useMemo<MenuAction[]>(
|
||||
() => [
|
||||
THREAD_ROW_MENU_ACTIONS[0]!,
|
||||
...buildThreadTitleRegenerationMenuItems({
|
||||
supported: props.titleRegenerationSupported,
|
||||
isRegenerating: thread.titleRegeneration != null,
|
||||
}),
|
||||
THREAD_ROW_MENU_ACTIONS[1]!,
|
||||
],
|
||||
[props.titleRegenerationSupported, thread.titleRegeneration],
|
||||
);
|
||||
const primaryAction = useMemo(
|
||||
() => ({
|
||||
accessibilityLabel: `Archive ${thread.title}`,
|
||||
@@ -483,9 +502,10 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
|
||||
const handleMenuAction = useCallback(
|
||||
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
|
||||
if (nativeEvent.event === "archive") handleArchive();
|
||||
if (nativeEvent.event === "regenerate-title") handleRegenerateTitle();
|
||||
if (nativeEvent.event === "delete") handleDelete();
|
||||
},
|
||||
[handleArchive, handleDelete],
|
||||
[handleArchive, handleDelete, handleRegenerateTitle],
|
||||
);
|
||||
|
||||
const statusPill = effectiveStatus ? (
|
||||
@@ -674,7 +694,7 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
|
||||
// ControlPillMenu injects onLongPress into the row and anchors the
|
||||
// token-styled dropdown to it; taps and swipes are untouched.
|
||||
<ControlPillMenu
|
||||
actions={THREAD_ROW_MENU_ACTIONS}
|
||||
actions={menuActions}
|
||||
onPressAction={handleMenuAction}
|
||||
shouldOpenOnLongPress
|
||||
>
|
||||
|
||||
@@ -27,6 +27,7 @@ import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
import { useThreadPr } from "../../state/use-thread-pr";
|
||||
import { ThreadSwipeable } from "../home/thread-swipe-actions";
|
||||
import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
|
||||
import {
|
||||
resolveThreadListV2SnoozeMenuSelection,
|
||||
resolveThreadListV2SnoozeGateExpiryMs,
|
||||
@@ -65,8 +66,8 @@ function threadTimeLabel(thread: EnvironmentThreadShell): string {
|
||||
return relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt);
|
||||
}
|
||||
|
||||
// Menus stay lifecycle-focused: settle/un-settle plus delete. Archive keeps
|
||||
// its own surface (thread screen / settings) rather than crowding the row.
|
||||
// Menus keep lifecycle and title regeneration together. Archive keeps its
|
||||
// own surface (thread screen / settings) rather than crowding v2 rows.
|
||||
const CARD_MENU_ACTIONS: MenuAction[] = [
|
||||
{ id: "settle", title: "Settle", image: "checkmark" },
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
@@ -341,6 +342,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
readonly fullSwipeWidth?: number;
|
||||
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onRegenerateThreadTitle: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onSettleThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onSnoozeThread: (thread: EnvironmentThreadShell, snoozedUntil: string) => void;
|
||||
readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => void;
|
||||
@@ -355,6 +357,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
readonly snoozeSupported: boolean;
|
||||
/** False on servers that predate thread.pin/unpin. */
|
||||
readonly pinningSupported: boolean;
|
||||
/** False on servers that predate thread title regeneration. */
|
||||
readonly titleRegenerationSupported: boolean;
|
||||
/** False on servers that predate thread.pin.reorder. Gates the pinned
|
||||
Move up / Move down menu items. */
|
||||
readonly pinReorderSupported?: boolean;
|
||||
@@ -365,12 +369,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
readonly canMovePinnedDown?: boolean;
|
||||
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
|
||||
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
|
||||
/** Reports this row's live PR state up so the partition can auto-settle
|
||||
merged/closed work (mirrors web's onChangeRequestState). */
|
||||
readonly onChangeRequestState?: (
|
||||
threadKey: string,
|
||||
state: "open" | "closed" | "merged" | null,
|
||||
) => void;
|
||||
readonly projectCwd?: string | null;
|
||||
readonly searchMatch?: EnvironmentThreadSearchMatch;
|
||||
readonly searchQuery?: string;
|
||||
@@ -384,6 +382,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
variant,
|
||||
onSelectThread,
|
||||
onDeleteThread,
|
||||
onRegenerateThreadTitle,
|
||||
onSettleThread,
|
||||
onSnoozeThread,
|
||||
onUnsnoozeThread,
|
||||
@@ -392,17 +391,11 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
onPinThread,
|
||||
onUnpinThread,
|
||||
onMovePinnedThread,
|
||||
onChangeRequestState,
|
||||
} = props;
|
||||
const snoozedRow = props.snoozed === true;
|
||||
const pinnedRow = props.pinned === true;
|
||||
|
||||
const pr = useThreadPr(thread, props.projectCwd ?? props.project?.workspaceRoot ?? null);
|
||||
const prState = pr?.state ?? null;
|
||||
const threadKey = `${thread.environmentId}:${thread.id}`;
|
||||
useEffect(() => {
|
||||
onChangeRequestState?.(threadKey, prState);
|
||||
}, [onChangeRequestState, prState, threadKey]);
|
||||
|
||||
const screenColor = useThemeColor("--color-screen");
|
||||
const drawerColor = useThemeColor("--color-drawer");
|
||||
@@ -417,6 +410,10 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
const timeLabel = threadTimeLabel(thread);
|
||||
|
||||
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
|
||||
const handleRegenerateTitle = useCallback(
|
||||
() => onRegenerateThreadTitle(thread),
|
||||
[onRegenerateThreadTitle, thread],
|
||||
);
|
||||
const handleSettle = useCallback(() => onSettleThread(thread), [onSettleThread, thread]);
|
||||
const handleSnooze = useCallback(
|
||||
(snoozedUntil: string) => onSnoozeThread(thread, snoozedUntil),
|
||||
@@ -437,8 +434,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]);
|
||||
|
||||
// Swipe: the v2 primary action is the lifecycle transition. Every settled
|
||||
// row can un-settle — explicit settles clear the override, auto-settled
|
||||
// rows get pinned active until real activity clears the pin.
|
||||
// row can un-settle, suppressing automation until real activity resets it.
|
||||
const canUnsettle = variant === "slim";
|
||||
const [snoozeGateTick, bumpSnoozeGateTick] = useState(0);
|
||||
const snoozeGateExpiryMs = props.snoozeSupported
|
||||
@@ -506,6 +502,14 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
props.pinningSupported,
|
||||
],
|
||||
);
|
||||
const titleRegenerationMenuItems = useMemo<MenuAction[]>(
|
||||
() =>
|
||||
buildThreadTitleRegenerationMenuItems({
|
||||
supported: props.titleRegenerationSupported,
|
||||
isRegenerating: thread.titleRegeneration != null,
|
||||
}),
|
||||
[props.titleRegenerationSupported, thread.titleRegeneration],
|
||||
);
|
||||
const snoozableCardMenuActions = useMemo<MenuAction[]>(
|
||||
() => [
|
||||
{ id: "settle", title: "Settle", image: "checkmark" },
|
||||
@@ -516,13 +520,31 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
subactions: snoozePresetActions,
|
||||
},
|
||||
...pinMenuItem,
|
||||
...titleRegenerationMenuItems,
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
],
|
||||
[pinMenuItem, snoozePresetActions],
|
||||
[pinMenuItem, snoozePresetActions, titleRegenerationMenuItems],
|
||||
);
|
||||
const cardMenuActions = useMemo<MenuAction[]>(
|
||||
() => [CARD_MENU_ACTIONS[0]!, ...pinMenuItem, ...CARD_MENU_ACTIONS.slice(1)],
|
||||
[pinMenuItem],
|
||||
() => [
|
||||
CARD_MENU_ACTIONS[0]!,
|
||||
...pinMenuItem,
|
||||
...titleRegenerationMenuItems,
|
||||
...CARD_MENU_ACTIONS.slice(1),
|
||||
],
|
||||
[pinMenuItem, titleRegenerationMenuItems],
|
||||
);
|
||||
const slimMenuActions = useMemo<MenuAction[]>(
|
||||
() => [SLIM_MENU_ACTIONS[0]!, ...titleRegenerationMenuItems, SLIM_MENU_ACTIONS[1]!],
|
||||
[titleRegenerationMenuItems],
|
||||
);
|
||||
const snoozedMenuActions = useMemo<MenuAction[]>(
|
||||
() => [SNOOZED_MENU_ACTIONS[0]!, ...titleRegenerationMenuItems, SNOOZED_MENU_ACTIONS[1]!],
|
||||
[titleRegenerationMenuItems],
|
||||
);
|
||||
const legacyMenuActions = useMemo<MenuAction[]>(
|
||||
() => [LEGACY_MENU_ACTIONS[0]!, ...titleRegenerationMenuItems, LEGACY_MENU_ACTIONS[1]!],
|
||||
[titleRegenerationMenuItems],
|
||||
);
|
||||
const handleMenuAction = useCallback(
|
||||
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
|
||||
@@ -534,6 +556,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
if (nativeEvent.event === "move-pin-up") handleMovePinnedUp();
|
||||
if (nativeEvent.event === "move-pin-down") handleMovePinnedDown();
|
||||
if (nativeEvent.event === "archive") handleArchive();
|
||||
if (nativeEvent.event === "regenerate-title") handleRegenerateTitle();
|
||||
if (nativeEvent.event === "delete") handleDelete();
|
||||
const snoozeSelection = resolveThreadListV2SnoozeMenuSelection({
|
||||
event: nativeEvent.event,
|
||||
@@ -549,6 +572,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
[
|
||||
handleArchive,
|
||||
handleDelete,
|
||||
handleRegenerateTitle,
|
||||
handleMovePinnedDown,
|
||||
handleMovePinnedUp,
|
||||
handlePin,
|
||||
@@ -890,11 +914,11 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
<ControlPillMenu
|
||||
actions={
|
||||
snoozedRow
|
||||
? SNOOZED_MENU_ACTIONS
|
||||
? snoozedMenuActions
|
||||
: !props.settlementSupported
|
||||
? LEGACY_MENU_ACTIONS
|
||||
? legacyMenuActions
|
||||
: canUnsettle
|
||||
? SLIM_MENU_ACTIONS
|
||||
? slimMenuActions
|
||||
: swipeActions.secondary === "snooze"
|
||||
? snoozableCardMenuActions
|
||||
: cardMenuActions
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
|
||||
|
||||
describe("buildThreadTitleRegenerationMenuItems", () => {
|
||||
it("hides regeneration when the environment does not advertise support", () => {
|
||||
expect(
|
||||
buildThreadTitleRegenerationMenuItems({ supported: false, isRegenerating: false }),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("offers regeneration for a supported environment", () => {
|
||||
expect(
|
||||
buildThreadTitleRegenerationMenuItems({ supported: true, isRegenerating: false }),
|
||||
).toEqual([
|
||||
{
|
||||
id: "regenerate-title",
|
||||
title: "Regenerate title",
|
||||
image: "arrow.clockwise",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("shows and disables the pending state", () => {
|
||||
expect(
|
||||
buildThreadTitleRegenerationMenuItems({ supported: true, isRegenerating: true }),
|
||||
).toEqual([
|
||||
{
|
||||
id: "regenerate-title",
|
||||
title: "Regenerating…",
|
||||
image: "arrow.clockwise",
|
||||
attributes: { disabled: true },
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
|
||||
export function buildThreadTitleRegenerationMenuItems(input: {
|
||||
readonly supported: boolean;
|
||||
readonly isRegenerating: boolean;
|
||||
}): MenuAction[] {
|
||||
if (!input.supported) return [];
|
||||
|
||||
return [
|
||||
{
|
||||
id: "regenerate-title",
|
||||
title: input.isRegenerating ? "Regenerating…" : "Regenerate title",
|
||||
image: "arrow.clockwise",
|
||||
...(input.isRegenerating ? { attributes: { disabled: true } } : {}),
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
@@ -292,7 +291,7 @@ describe("buildThreadListV2Items", () => {
|
||||
expect(layout.snoozedCount).toBe(1);
|
||||
});
|
||||
|
||||
it("renders pinned threads first and exempts them from auto-settle — parity with web", () => {
|
||||
it("renders pinned threads first during a transient pin/settle projection overlap", () => {
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("active"), title: "Active" }),
|
||||
@@ -576,13 +575,28 @@ describe("buildThreadListV2Items", () => {
|
||||
title: "Newer",
|
||||
createdAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("settled-first"),
|
||||
title: "Settled first",
|
||||
settledAt: "2026-06-01T13:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("settled-last"),
|
||||
title: "Settled last",
|
||||
settledAt: "2026-06-01T14:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(items.map((item) => item.thread.id)).toEqual(["newer-created", "older-created"]);
|
||||
expect(items.map((item) => item.thread.id)).toEqual([
|
||||
"newer-created",
|
||||
"older-created",
|
||||
"settled-last",
|
||||
"settled-first",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps settled threads in the tail and filters by search query", () => {
|
||||
@@ -682,18 +696,7 @@ describe("buildThreadListV2Items settled paging", () => {
|
||||
id: ThreadId.make(`settled-${index}`),
|
||||
title: `Settled ${index}`,
|
||||
settledOverride: "settled",
|
||||
settledAt: NOW,
|
||||
latestUserMessageAt: `2026-06-01T0${index}:00:00.000Z`,
|
||||
// A turn adopted the message (same requestedAt): without it the
|
||||
// thread reads as a queued turn start, which never settles.
|
||||
latestTurn: {
|
||||
turnId: TurnId.make(`turn-${index}`),
|
||||
state: "completed",
|
||||
requestedAt: `2026-06-01T0${index}:00:00.000Z`,
|
||||
startedAt: `2026-06-01T0${index}:00:00.000Z`,
|
||||
completedAt: `2026-06-01T0${index}:10:00.000Z`,
|
||||
assistantMessageId: null,
|
||||
},
|
||||
settledAt: `2026-06-01T0${index}:10:00.000Z`,
|
||||
}),
|
||||
),
|
||||
];
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import {
|
||||
effectiveSettled,
|
||||
effectiveSnoozed,
|
||||
hasQueuedTurnStart,
|
||||
QUEUED_TURN_START_GRACE_MS,
|
||||
@@ -147,17 +146,6 @@ function parseTimestampMs(isoDate: string): number {
|
||||
return Number.isNaN(parsed) ? 0 : parsed;
|
||||
}
|
||||
|
||||
/** First VALID timestamp wins: a present-yet-malformed string falls through
|
||||
to the next candidate rather than sinking the row to the epoch. */
|
||||
function firstValidTimestampMs(...candidates: ReadonlyArray<string | null | undefined>): number {
|
||||
for (const candidate of candidates) {
|
||||
if (candidate == null) continue;
|
||||
const parsed = Date.parse(candidate);
|
||||
if (!Number.isNaN(parsed)) return parsed;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* v2 sort: static creation order, newest thread on top. Activity NEVER
|
||||
* reorders the list — a row holds its position from open until settled, so
|
||||
@@ -305,10 +293,8 @@ export function buildThreadListV2ListItems(input: {
|
||||
}
|
||||
|
||||
/**
|
||||
* Partitions visible threads into the active card block (creation order) and
|
||||
* the settled recency tail, matching the web v2 list. `autoSettleAfterDays`
|
||||
* mirrors the web default of 3 — mobile has no client-settings sync yet, so
|
||||
* the default is fixed here rather than user-configurable.
|
||||
* Partitions visible threads into the active card block and the settled
|
||||
* recency tail. Settlement is persisted server state.
|
||||
*/
|
||||
export function buildThreadListV2Items(input: {
|
||||
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
|
||||
@@ -319,8 +305,6 @@ export function buildThreadListV2Items(input: {
|
||||
}> | null;
|
||||
readonly searchQuery: string;
|
||||
readonly matchedThreadKeys?: ReadonlySet<string>;
|
||||
/** Per-row PR state reported up by visible rows ("env:threadId" keys). */
|
||||
readonly changeRequestStateByKey?: ReadonlyMap<string, "open" | "closed" | "merged">;
|
||||
/** Environments whose server supports thread.settle/unsettle. Threads on
|
||||
other environments never classify as settled — the user could neither
|
||||
un-settle nor pin them. Absent = no gating (tests). */
|
||||
@@ -328,7 +312,6 @@ export function buildThreadListV2Items(input: {
|
||||
/** Environments whose server supports thread.snooze/unsnooze. Same
|
||||
contract as settlementEnvironmentIds. */
|
||||
readonly snoozeEnvironmentIds?: ReadonlySet<EnvironmentId>;
|
||||
readonly autoSettleAfterDays?: number;
|
||||
/** Max settled rows to render; the rest are counted, not built. */
|
||||
readonly settledLimit?: number;
|
||||
/** Injectable for tests; defaults to now. */
|
||||
@@ -348,7 +331,6 @@ export function buildThreadListV2Items(input: {
|
||||
}): ThreadListV2Layout {
|
||||
const now = input.now ?? new Date().toISOString();
|
||||
const snoozeNow = input.snoozeNow ?? now;
|
||||
const autoSettleAfterDays = input.autoSettleAfterDays ?? 3;
|
||||
const query = input.searchQuery.trim().toLocaleLowerCase();
|
||||
const projectKeys = input.projectRefs
|
||||
? new Set(input.projectRefs.map((ref) => `${ref.environmentId}:${ref.projectId}`))
|
||||
@@ -360,8 +342,8 @@ export function buildThreadListV2Items(input: {
|
||||
const snoozed: EnvironmentThreadShell[] = [];
|
||||
let nextSnoozeWakeAt: string | null = null;
|
||||
for (const thread of input.threads) {
|
||||
// Callers pass live (unarchived) shells; settled threads are among them
|
||||
// and partition into the tail via effectiveSettled.
|
||||
// Callers pass live (unarchived) shells; settled threads remain among
|
||||
// them and partition into the tail from their projected timestamp.
|
||||
if (input.environmentId !== null && thread.environmentId !== input.environmentId) continue;
|
||||
if (projectKeys !== null && !projectKeys.has(`${thread.environmentId}:${thread.projectId}`)) {
|
||||
continue;
|
||||
@@ -380,8 +362,6 @@ export function buildThreadListV2Items(input: {
|
||||
}
|
||||
const supportsSettlement = input.settlementEnvironmentIds?.has(thread.environmentId) ?? true;
|
||||
const supportsSnooze = input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true;
|
||||
const changeRequestState =
|
||||
input.changeRequestStateByKey?.get(`${thread.environmentId}:${thread.id}`) ?? null;
|
||||
// Visibility parity with web: snooze outranks everything, including a
|
||||
// pin — a snoozed thread leaves the list until it wakes (or raises its
|
||||
// hand). The pin (and its pinOrderKey) survives underneath, so a woken
|
||||
@@ -397,16 +377,13 @@ export function buildThreadListV2Items(input: {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// A pin otherwise overrides the lifecycle: pinned threads render above
|
||||
// the inbox and never auto-settle out of sight.
|
||||
// Server commands clear one side of a pin/settle transition atomically;
|
||||
// pin wins here only while the paired projection event catches up.
|
||||
if (thread.pinnedAt != null) {
|
||||
pinned.push(thread);
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
supportsSettlement &&
|
||||
effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })
|
||||
) {
|
||||
if (supportsSettlement && thread.settledAt !== null) {
|
||||
settled.push(thread);
|
||||
} else {
|
||||
active.push(thread);
|
||||
@@ -427,8 +404,7 @@ export function buildThreadListV2Items(input: {
|
||||
);
|
||||
const orderedSettled = [...settled].sort(
|
||||
(left, right) =>
|
||||
firstValidTimestampMs(right.latestUserMessageAt, right.updatedAt) -
|
||||
firstValidTimestampMs(left.latestUserMessageAt, left.updatedAt),
|
||||
parseTimestampMs(right.settledAt ?? "") - parseTimestampMs(left.settledAt ?? ""),
|
||||
);
|
||||
const settledLimit = input.settledLimit ?? Number.POSITIVE_INFINITY;
|
||||
const pagedSettled =
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import type { DailyTotals, MergedUsage } from "@t3tools/shared/usageMerge";
|
||||
import {
|
||||
enumerateDays,
|
||||
@@ -13,13 +11,12 @@ import {
|
||||
formatUsd,
|
||||
makeWindow,
|
||||
} from "@t3tools/shared/usageFormat";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { Platform, Pressable, RefreshControl, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
|
||||
import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useUsage, type EnvironmentUsageStatus } from "../../state/usage";
|
||||
import { SettingsSection } from "../settings/components/SettingsSection";
|
||||
@@ -44,47 +41,9 @@ export function UsageRouteScreen() {
|
||||
window: makeWindow(30),
|
||||
}));
|
||||
const [metric, setMetric] = useState<UsageChartMetric>("cost");
|
||||
const [environmentFilter, setEnvironmentFilter] = useState<EnvironmentId | null>(null);
|
||||
const { days: windowDays, window } = windowSelection;
|
||||
const isPast24Hours = windowDays === 1;
|
||||
const { merged, options, environments, selectedEnvironmentId, isPending, isPartial, refresh } =
|
||||
useUsage(window, environmentFilter);
|
||||
|
||||
useEffect(() => {
|
||||
if (environmentFilter !== null && selectedEnvironmentId === null) {
|
||||
setEnvironmentFilter(null);
|
||||
}
|
||||
}, [environmentFilter, selectedEnvironmentId]);
|
||||
|
||||
const environmentActions = useMemo<readonly MenuAction[]>(
|
||||
() => [
|
||||
{
|
||||
id: "all",
|
||||
title: "All environments",
|
||||
state: selectedEnvironmentId === null ? "on" : "off",
|
||||
},
|
||||
...options.map((environment) => ({
|
||||
id: `environment:${environment.environmentId}`,
|
||||
title: environment.label,
|
||||
state:
|
||||
environment.environmentId === selectedEnvironmentId ? ("on" as const) : ("off" as const),
|
||||
})),
|
||||
],
|
||||
[options, selectedEnvironmentId],
|
||||
);
|
||||
const selectedEnvironmentLabel =
|
||||
selectedEnvironmentId === null
|
||||
? "All environments"
|
||||
: (options.find((environment) => environment.environmentId === selectedEnvironmentId)
|
||||
?.label ?? "All environments");
|
||||
const selectedEnvironmentControlLabel =
|
||||
selectedEnvironmentLabel.length > 20
|
||||
? `${selectedEnvironmentLabel.slice(0, 19)}…`
|
||||
: selectedEnvironmentLabel;
|
||||
const usableEnvironmentCount = environments.filter(
|
||||
(environment) =>
|
||||
environment.summary !== null && !merged.staleEnvironments.includes(environment.environmentId),
|
||||
).length;
|
||||
const { merged, environments, isPending, isPartial, refresh } = useUsage(window);
|
||||
|
||||
const days = useMemo(
|
||||
() => enumerateDays(window.sinceDay, window.untilDay),
|
||||
@@ -110,11 +69,10 @@ export function UsageRouteScreen() {
|
||||
[isPast24Hours, merged.daily, merged.hourly],
|
||||
);
|
||||
|
||||
// The pull spinner tracks re-scans of connected environments that have
|
||||
// answered before. The initial scan renders its own placeholder.
|
||||
const refreshing = environments.some(
|
||||
(entry) => entry.phase === "connected" && entry.isPending && entry.summary !== null,
|
||||
);
|
||||
// The pull spinner tracks re-scans of environments that have answered
|
||||
// before. The initial scan renders its own placeholder, and an unreachable
|
||||
// environment stays pending forever — neither may pin the spinner on.
|
||||
const refreshing = environments.some((entry) => entry.isPending && entry.summary !== null);
|
||||
const selectWindow = (days: number) => {
|
||||
setWindowSelection({
|
||||
days,
|
||||
@@ -151,52 +109,22 @@ export function UsageRouteScreen() {
|
||||
contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
refreshControl={<RefreshControl refreshing={refreshing} onRefresh={refreshWindow} />}
|
||||
>
|
||||
<View className="gap-3">
|
||||
<SegmentedControl
|
||||
options={WINDOW_OPTIONS.map((option) => ({
|
||||
value: option.days,
|
||||
label: option.label,
|
||||
}))}
|
||||
selected={windowDays}
|
||||
onSelect={selectWindow}
|
||||
/>
|
||||
<View className="max-w-full items-start">
|
||||
<ControlPillMenu
|
||||
title="Filter environments"
|
||||
actions={[...environmentActions]}
|
||||
onPressAction={({ nativeEvent }) => {
|
||||
setEnvironmentFilter(
|
||||
nativeEvent.event === "all"
|
||||
? null
|
||||
: (nativeEvent.event.slice("environment:".length) as EnvironmentId),
|
||||
);
|
||||
}}
|
||||
>
|
||||
<ControlPill
|
||||
variant="pill"
|
||||
label={selectedEnvironmentControlLabel}
|
||||
accessibilityLabel={`Filter environments, ${selectedEnvironmentLabel}`}
|
||||
/>
|
||||
</ControlPillMenu>
|
||||
</View>
|
||||
</View>
|
||||
<SegmentedControl
|
||||
options={WINDOW_OPTIONS.map((option) => ({ value: option.days, label: option.label }))}
|
||||
selected={windowDays}
|
||||
onSelect={selectWindow}
|
||||
/>
|
||||
|
||||
<UsageCoverageNotice environments={environments} merged={merged} isPartial={isPartial} />
|
||||
|
||||
{isPending || (usableEnvironmentCount === 0 && isPartial) ? (
|
||||
{isPending ? (
|
||||
<Text className="py-16 text-center text-base text-foreground-muted">
|
||||
Scanning provider transcripts…
|
||||
</Text>
|
||||
) : options.length === 0 ? (
|
||||
) : environments.length === 0 ? (
|
||||
<Text className="py-16 text-center text-base text-foreground-muted">
|
||||
Connect an environment to see usage.
|
||||
</Text>
|
||||
) : usableEnvironmentCount === 0 ? (
|
||||
<Text className="py-16 text-center text-base text-foreground-muted">
|
||||
{selectedEnvironmentId === null
|
||||
? "No connected environment could report usage."
|
||||
: "This environment is unavailable for usage."}
|
||||
</Text>
|
||||
) : (
|
||||
<>
|
||||
<ChartCard
|
||||
@@ -521,31 +449,21 @@ function ModelsSection(props: { readonly merged: MergedUsage }) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Explains incomplete totals without hiding healthy environment data.
|
||||
* Says plainly when the totals are incomplete: an environment still answering,
|
||||
* one that failed, or one whose transcripts another environment already
|
||||
* reported.
|
||||
*/
|
||||
function UsageCoverageNotice(props: {
|
||||
readonly environments: readonly EnvironmentUsageStatus[];
|
||||
readonly merged: MergedUsage;
|
||||
readonly isPartial: boolean;
|
||||
}) {
|
||||
const settling = props.environments.filter(
|
||||
(environment) => environment.phase === "connecting" || environment.phase === "reconnecting",
|
||||
);
|
||||
const unavailable = props.environments.filter(
|
||||
(environment) =>
|
||||
!environment.isPending &&
|
||||
(environment.phase === "available" ||
|
||||
environment.phase === "offline" ||
|
||||
environment.phase === "error"),
|
||||
);
|
||||
const failed = props.environments.filter((environment) => environment.error !== null);
|
||||
const stale = props.environments.filter((environment) =>
|
||||
props.merged.staleEnvironments.includes(environment.environmentId),
|
||||
);
|
||||
const duplicateSources = props.merged.duplicateSources;
|
||||
if (
|
||||
settling.length === 0 &&
|
||||
unavailable.length === 0 &&
|
||||
failed.length === 0 &&
|
||||
stale.length === 0 &&
|
||||
duplicateSources.length === 0 &&
|
||||
@@ -561,22 +479,6 @@ function UsageCoverageNotice(props: {
|
||||
Some environments are still reporting. Totals are partial.
|
||||
</Text>
|
||||
) : null}
|
||||
{settling.map((environment) => (
|
||||
<Text key={environment.environmentId} className="text-sm text-foreground-muted">
|
||||
{environment.label} is {environment.phase}.
|
||||
</Text>
|
||||
))}
|
||||
{unavailable.map((environment) => (
|
||||
<Text key={environment.environmentId} className="text-sm text-foreground-muted">
|
||||
{environment.label} is{" "}
|
||||
{environment.phase === "available"
|
||||
? "not connected"
|
||||
: environment.phase === "error"
|
||||
? "unavailable"
|
||||
: environment.phase}
|
||||
.
|
||||
</Text>
|
||||
))}
|
||||
{failed.map((environment) => (
|
||||
<Text key={environment.environmentId} className="text-sm text-foreground-muted">
|
||||
{environment.label} could not report usage.
|
||||
|
||||
@@ -126,6 +126,22 @@ describe("nativeMarkdownTextRuns", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["😀", "😀"],
|
||||
["🚀", "🚀"],
|
||||
["�", "�"],
|
||||
["�", "�"],
|
||||
["&#9999999999;", "�"],
|
||||
["&#x110000;", "�"],
|
||||
])("normalizes numeric entity %s without throwing", (content, expected) => {
|
||||
const node: MarkdownNode = {
|
||||
type: "paragraph",
|
||||
children: [{ type: "text", content }],
|
||||
};
|
||||
|
||||
expect(nativeMarkdownTextRuns(node)).toEqual([{ text: expected }]);
|
||||
});
|
||||
|
||||
it("reads inline content from nested text nodes", () => {
|
||||
const node: MarkdownNode = {
|
||||
type: "paragraph",
|
||||
@@ -173,6 +189,25 @@ describe("nativeMarkdownDocumentRuns", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("decorates known skill references inside blockquotes", () => {
|
||||
const node: MarkdownNode = {
|
||||
type: "blockquote",
|
||||
children: [
|
||||
{
|
||||
type: "paragraph",
|
||||
children: [{ type: "text", content: "Use $ui for this." }],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
expect(nativeMarkdownDocumentRuns(node, [{ name: "ui", displayName: "UI" }])).toContainEqual({
|
||||
text: "$ui",
|
||||
role: "body",
|
||||
skillName: "ui",
|
||||
skillLabel: "UI",
|
||||
});
|
||||
});
|
||||
|
||||
it("leaves unknown skill-like text unchanged", () => {
|
||||
const node: MarkdownNode = {
|
||||
type: "document",
|
||||
@@ -328,7 +363,7 @@ describe("nativeMarkdownDocumentRuns", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("includes quotes and fenced code in the same selectable string", () => {
|
||||
it("preserves quotes and fenced code in document runs", () => {
|
||||
const node: MarkdownNode = {
|
||||
type: "document",
|
||||
children: [
|
||||
@@ -414,6 +449,39 @@ describe("nativeMarkdownListItemBlocks", () => {
|
||||
});
|
||||
|
||||
describe("nativeMarkdownDocumentChunks", () => {
|
||||
it("renders plain blockquotes as rich blocks so their marker spans wrapped lines", () => {
|
||||
const blockquote: MarkdownNode = {
|
||||
type: "blockquote",
|
||||
beg: 0,
|
||||
end: 120,
|
||||
children: [
|
||||
{
|
||||
type: "paragraph",
|
||||
children: [
|
||||
{
|
||||
type: "text",
|
||||
content:
|
||||
"Persistent random per-result keys are the strongest design, even when this text wraps.",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
expect(
|
||||
nativeMarkdownDocumentChunks({
|
||||
type: "document",
|
||||
children: [blockquote],
|
||||
}),
|
||||
).toEqual([
|
||||
{
|
||||
kind: "rich",
|
||||
key: "rich:blockquote:0:120",
|
||||
node: blockquote,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps headings and plain lists in one selectable document", () => {
|
||||
const document: MarkdownNode = {
|
||||
type: "document",
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
import { requireNativeView } from "expo";
|
||||
import type { NativeSyntheticEvent, StyleProp, ViewProps, ViewStyle } from "react-native";
|
||||
|
||||
interface NativeHeaderButtonProps extends ViewProps {
|
||||
readonly label: string;
|
||||
readonly systemImage: "gearshape" | "square.and.pencil";
|
||||
readonly onTriggered: (event: NativeSyntheticEvent<Record<string, never>>) => void;
|
||||
}
|
||||
|
||||
const NativeHeaderButton = requireNativeView<NativeHeaderButtonProps>("T3NativeControls");
|
||||
|
||||
export function T3HeaderButton(props: {
|
||||
readonly accessibilityLabel: string;
|
||||
readonly icon: NativeHeaderButtonProps["systemImage"];
|
||||
readonly onPress: () => void;
|
||||
readonly style?: StyleProp<ViewStyle>;
|
||||
}) {
|
||||
return (
|
||||
<NativeHeaderButton
|
||||
label={props.accessibilityLabel}
|
||||
onTriggered={props.onPress}
|
||||
style={[{ width: 44, height: 44 }, props.style]}
|
||||
systemImage={props.icon}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
getEnvironmentUsageLoadingState,
|
||||
resolveEnvironmentUsageScope,
|
||||
type EnvironmentUsageOption,
|
||||
} from "./usageEnvironmentScope";
|
||||
|
||||
const environment = (
|
||||
environmentId: string,
|
||||
phase: EnvironmentConnectionPhase,
|
||||
): EnvironmentUsageOption => ({
|
||||
environmentId: environmentId as EnvironmentId,
|
||||
label: environmentId,
|
||||
phase,
|
||||
});
|
||||
|
||||
describe("mobile usage environment scope", () => {
|
||||
it("does not wait indefinitely for a reconnecting environment", () => {
|
||||
expect(
|
||||
getEnvironmentUsageLoadingState([
|
||||
{ phase: "reconnecting", isPending: false, summary: null, error: null },
|
||||
]),
|
||||
).toEqual({ isPending: false, isPartial: false });
|
||||
});
|
||||
|
||||
it("does not let an offline environment hold healthy totals open", () => {
|
||||
expect(
|
||||
getEnvironmentUsageLoadingState([
|
||||
{ phase: "connected", isPending: false, summary: {}, error: null },
|
||||
{ phase: "offline", isPending: false, summary: null, error: null },
|
||||
]),
|
||||
).toEqual({ isPending: false, isPartial: false });
|
||||
});
|
||||
|
||||
it("waits for an initial available connection state", () => {
|
||||
expect(
|
||||
getEnvironmentUsageLoadingState([
|
||||
{ phase: "available", isPending: true, summary: null, error: null },
|
||||
]),
|
||||
).toEqual({ isPending: true, isPartial: false });
|
||||
});
|
||||
|
||||
it("waits for the first connection attempt", () => {
|
||||
expect(
|
||||
getEnvironmentUsageLoadingState([
|
||||
{ phase: "connecting", isPending: true, summary: null, error: null },
|
||||
]),
|
||||
).toEqual({ isPending: true, isPartial: false });
|
||||
});
|
||||
|
||||
it("isolates a selected environment and falls back when it disappears", () => {
|
||||
const options = [environment("healthy", "connected"), environment("down", "offline")];
|
||||
|
||||
expect(resolveEnvironmentUsageScope(options, "down" as EnvironmentId).environments).toEqual([
|
||||
options[1],
|
||||
]);
|
||||
expect(
|
||||
resolveEnvironmentUsageScope(options.slice(0, 1), "down" as EnvironmentId)
|
||||
.selectedEnvironmentId,
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,11 +1,11 @@
|
||||
/**
|
||||
* Multi-environment usage state.
|
||||
*
|
||||
* Connected environments answer the typed usage query. Connection state
|
||||
* determines whether a waiting query contributes to loading coverage, so one
|
||||
* unreachable machine can never hold the dashboard open.
|
||||
* Every connected environment answers the same typed query; the client merges
|
||||
* the results. Raw transcripts never leave the machine that produced them.
|
||||
*
|
||||
* Mirror of web usage state over mobile's atom registry.
|
||||
* Mirror of `apps/web/src/state/usage.ts` over mobile's atom wiring; the merge
|
||||
* rules themselves live in `@t3tools/shared/usageMerge`.
|
||||
*
|
||||
* @module state/usage
|
||||
*/
|
||||
@@ -16,109 +16,74 @@ import {
|
||||
type UsageSummary,
|
||||
type UsageSummaryInput,
|
||||
} from "@t3tools/contracts";
|
||||
import { mergeUsage, type EnvironmentUsage, type MergedUsage } from "@t3tools/shared/usageMerge";
|
||||
import * as Option from "effect/Option";
|
||||
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
import { useCallback, useMemo } from "react";
|
||||
|
||||
import { mergeUsage, type EnvironmentUsage, type MergedUsage } from "@t3tools/shared/usageMerge";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import { environmentCatalog } from "../connection/catalog";
|
||||
import { environmentPresentations } from "./presentation";
|
||||
import { serverEnvironment } from "./server";
|
||||
import {
|
||||
getEnvironmentUsageLoadingState,
|
||||
resolveEnvironmentUsageScope,
|
||||
type EnvironmentUsageOption,
|
||||
} from "./usageEnvironmentScope";
|
||||
|
||||
export type { EnvironmentUsageOption } from "./usageEnvironmentScope";
|
||||
|
||||
export interface EnvironmentUsageStatus extends EnvironmentUsageOption {
|
||||
export interface EnvironmentUsageStatus {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly label: string;
|
||||
readonly isPending: boolean;
|
||||
/** A connected usage query failed. Connection coverage uses `phase`. */
|
||||
readonly error: string | null;
|
||||
readonly summary: UsageSummary | null;
|
||||
}
|
||||
|
||||
interface UsageAtomValue {
|
||||
readonly isCatalogReady: boolean;
|
||||
readonly options: readonly EnvironmentUsageOption[];
|
||||
readonly environments: readonly EnvironmentUsageStatus[];
|
||||
}
|
||||
|
||||
interface UsageAtomKey {
|
||||
readonly input: UsageSummaryInput;
|
||||
}
|
||||
|
||||
const usageByWindowAtom = Atom.family((key: string) =>
|
||||
Atom.make((get): UsageAtomValue => {
|
||||
const { input } = JSON.parse(key) as UsageAtomKey;
|
||||
const catalog = get(environmentCatalog.catalogValueAtom);
|
||||
/**
|
||||
* Reads every environment's summary for one window.
|
||||
*
|
||||
* Keyed by the serialised window so switching ranges does not thrash the atom
|
||||
* cache, and so each environment's query is shared with any other reader of the
|
||||
* same window.
|
||||
*/
|
||||
const usageByWindowAtom = Atom.family((windowKey: string) =>
|
||||
Atom.make((get): readonly EnvironmentUsageStatus[] => {
|
||||
const input = JSON.parse(windowKey) as UsageSummaryInput;
|
||||
const presentations = get(environmentPresentations.presentationsAtom);
|
||||
const options = Array.from(presentations, ([environmentId, presentation]) => ({
|
||||
environmentId,
|
||||
label: presentation.entry.target.label,
|
||||
phase: presentation.connection.phase,
|
||||
}));
|
||||
|
||||
// Keep every environment subscribed while this time window is mounted. Filtering
|
||||
// only the view avoids evicting sibling usage caches when switching scopes.
|
||||
const environments: EnvironmentUsageStatus[] = [];
|
||||
for (const option of options) {
|
||||
const { environmentId } = option;
|
||||
const connectionResult = get(environmentCatalog.stateAtom(environmentId));
|
||||
// Keep reading the environment-scoped atom while disconnected so a prior
|
||||
// successful value remains visible. Wait through the first connection attempt,
|
||||
// then treat retries as terminal coverage so a down machine cannot block the UI.
|
||||
const statuses: EnvironmentUsageStatus[] = [];
|
||||
for (const [environmentId, presentation] of presentations) {
|
||||
const result = get(serverEnvironment.usageSummary({ environmentId, input }));
|
||||
const failed = option.phase === "connected" && result._tag === "Failure";
|
||||
environments.push({
|
||||
...option,
|
||||
isPending:
|
||||
(option.phase === "available" && connectionResult.waiting) ||
|
||||
option.phase === "connecting" ||
|
||||
(option.phase === "connected" && result.waiting),
|
||||
error: failed ? "This environment could not report usage." : null,
|
||||
statuses.push({
|
||||
environmentId,
|
||||
label: presentation.entry.target.label,
|
||||
isPending: result.waiting,
|
||||
error: result._tag === "Failure" ? "This environment could not report usage." : null,
|
||||
summary: Option.getOrNull(AsyncResult.value(result)),
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
isCatalogReady: catalog.isReady,
|
||||
options,
|
||||
environments,
|
||||
};
|
||||
}).pipe(Atom.withLabel(`mobile-usage:${key}`)),
|
||||
return statuses;
|
||||
}).pipe(Atom.withLabel(`mobile-usage:window:${windowKey}`)),
|
||||
);
|
||||
|
||||
export interface UsageView {
|
||||
readonly merged: MergedUsage;
|
||||
/** All catalog entries, including entries outside the active filter. */
|
||||
readonly options: readonly EnvironmentUsageOption[];
|
||||
/** Coverage entries in the active filter. */
|
||||
readonly environments: readonly EnvironmentUsageStatus[];
|
||||
readonly selectedEnvironmentId: EnvironmentId | null;
|
||||
/** True until at least one connected environment has answered. */
|
||||
/** True until at least one environment has answered. */
|
||||
readonly isPending: boolean;
|
||||
/**
|
||||
* True while environments that have not failed are still answering. Failed
|
||||
* environments are reported through their own error rows: totals will not
|
||||
* improve by waiting on them, so they must not read as "still reporting".
|
||||
*/
|
||||
readonly isPartial: boolean;
|
||||
readonly refresh: () => void;
|
||||
}
|
||||
|
||||
export function useUsage(
|
||||
input: UsageSummaryInput,
|
||||
selectedEnvironmentId: EnvironmentId | null,
|
||||
): UsageView {
|
||||
const key = useMemo(
|
||||
export function useUsage(input: UsageSummaryInput): UsageView {
|
||||
const windowKey = useMemo(
|
||||
() =>
|
||||
JSON.stringify({
|
||||
input: {
|
||||
sinceDay: input.sinceDay,
|
||||
untilDay: input.untilDay,
|
||||
timeZone: input.timeZone,
|
||||
resolution: input.resolution,
|
||||
sinceTime: input.sinceTime,
|
||||
untilTime: input.untilTime,
|
||||
},
|
||||
sinceDay: input.sinceDay,
|
||||
untilDay: input.untilDay,
|
||||
timeZone: input.timeZone,
|
||||
resolution: input.resolution,
|
||||
sinceTime: input.sinceTime,
|
||||
untilTime: input.untilTime,
|
||||
}),
|
||||
[
|
||||
input.sinceDay,
|
||||
@@ -129,25 +94,20 @@ export function useUsage(
|
||||
input.untilTime,
|
||||
],
|
||||
);
|
||||
const atom = usageByWindowAtom(key);
|
||||
const value = useAtomValue(atom);
|
||||
const scope = resolveEnvironmentUsageScope(value.options, selectedEnvironmentId);
|
||||
const environments = useMemo(() => {
|
||||
if (scope.selectedEnvironmentId === null) return value.environments;
|
||||
return value.environments.filter(
|
||||
(environment) => environment.environmentId === scope.selectedEnvironmentId,
|
||||
);
|
||||
}, [scope.selectedEnvironmentId, value.environments]);
|
||||
const atom = usageByWindowAtom(windowKey);
|
||||
const environments = useAtomValue(atom);
|
||||
|
||||
// Refreshing only the derived atom would re-read the per-environment SWR
|
||||
// queries within their stale window and change nothing. Refresh each
|
||||
// environment's query so pull-to-refresh always rescans.
|
||||
const refresh = useCallback(() => {
|
||||
const { input } = JSON.parse(key) as UsageAtomKey;
|
||||
const input = JSON.parse(windowKey) as UsageSummaryInput;
|
||||
for (const environment of environments) {
|
||||
if (environment.phase !== "connected") continue;
|
||||
appAtomRegistry.refresh(
|
||||
serverEnvironment.usageSummary({ environmentId: environment.environmentId, input }),
|
||||
);
|
||||
}
|
||||
}, [environments, key]);
|
||||
}, [environments, windowKey]);
|
||||
|
||||
const merged = useMemo(() => {
|
||||
const answered: EnvironmentUsage[] = environments.flatMap((environment) =>
|
||||
@@ -164,15 +124,16 @@ export function useUsage(
|
||||
return mergeUsage(answered, USAGE_CONTRACT_VERSION);
|
||||
}, [environments]);
|
||||
|
||||
const loadingState = getEnvironmentUsageLoadingState(environments);
|
||||
const answeredCount = environments.filter((environment) => environment.summary !== null).length;
|
||||
const stillReporting = environments.filter(
|
||||
(environment) => environment.summary === null && environment.error === null,
|
||||
).length;
|
||||
|
||||
return {
|
||||
merged,
|
||||
options: value.options,
|
||||
environments,
|
||||
selectedEnvironmentId: scope.selectedEnvironmentId,
|
||||
isPending: !value.isCatalogReady || loadingState.isPending,
|
||||
isPartial: loadingState.isPartial,
|
||||
isPending: answeredCount === 0 && stillReporting > 0,
|
||||
isPartial: answeredCount > 0 && stillReporting > 0,
|
||||
refresh,
|
||||
};
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
|
||||
export interface EnvironmentUsageOption {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly label: string;
|
||||
readonly phase: EnvironmentConnectionPhase;
|
||||
}
|
||||
|
||||
export function resolveEnvironmentUsageScope(
|
||||
options: readonly EnvironmentUsageOption[],
|
||||
selectedEnvironmentId: EnvironmentId | null,
|
||||
): {
|
||||
readonly selectedEnvironmentId: EnvironmentId | null;
|
||||
readonly environments: readonly EnvironmentUsageOption[];
|
||||
} {
|
||||
const effectiveSelection =
|
||||
selectedEnvironmentId !== null &&
|
||||
options.some((environment) => environment.environmentId === selectedEnvironmentId)
|
||||
? selectedEnvironmentId
|
||||
: null;
|
||||
return {
|
||||
selectedEnvironmentId: effectiveSelection,
|
||||
environments:
|
||||
effectiveSelection === null
|
||||
? options
|
||||
: options.filter((environment) => environment.environmentId === effectiveSelection),
|
||||
};
|
||||
}
|
||||
|
||||
interface EnvironmentUsageLoadingEntry {
|
||||
readonly phase: EnvironmentConnectionPhase;
|
||||
readonly isPending: boolean;
|
||||
readonly summary: unknown | null;
|
||||
readonly error: string | null;
|
||||
}
|
||||
|
||||
export function isEnvironmentUsageStillReporting(
|
||||
environment: EnvironmentUsageLoadingEntry,
|
||||
): boolean {
|
||||
return environment.isPending && environment.summary === null && environment.error === null;
|
||||
}
|
||||
|
||||
export function getEnvironmentUsageLoadingState(
|
||||
environments: readonly EnvironmentUsageLoadingEntry[],
|
||||
): { readonly isPending: boolean; readonly isPartial: boolean } {
|
||||
const answeredCount = environments.filter((environment) => environment.summary !== null).length;
|
||||
const stillReporting = environments.filter(isEnvironmentUsageStillReporting).length;
|
||||
|
||||
return {
|
||||
isPending: answeredCount === 0 && stillReporting > 0,
|
||||
isPartial: answeredCount > 0 && stillReporting > 0,
|
||||
};
|
||||
}
|
||||
@@ -63,6 +63,7 @@ import {
|
||||
type OrchestrationEngineShape,
|
||||
} from "../src/orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ThreadDeletionReactor } from "../src/orchestration/Services/ThreadDeletionReactor.ts";
|
||||
import { ThreadSettlementReactor } from "../src/orchestration/ThreadSettlementReactor.ts";
|
||||
import { OrchestrationReactor } from "../src/orchestration/Services/OrchestrationReactor.ts";
|
||||
import { ProjectionSnapshotQuery } from "../src/orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import {
|
||||
@@ -342,6 +343,8 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(VcsStatusBroadcaster, {
|
||||
getStatus: () => Effect.die("getStatus should not be called in this test"),
|
||||
peekStatus: () => Effect.die("peekStatus should not be called in this test"),
|
||||
pollStatus: () => Effect.die("pollStatus should not be called in this test"),
|
||||
refreshLocalStatus: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
@@ -375,6 +378,12 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
drain: Effect.void,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ThreadSettlementReactor, {
|
||||
start: () => Effect.void,
|
||||
drain: Effect.void,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(AgentAwarenessRelay.AgentAwarenessRelay, {
|
||||
publishThread: () => Effect.void,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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");
|
||||
}),
|
||||
|
||||
@@ -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,
|
||||
),
|
||||
|
||||
@@ -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-");
|
||||
|
||||
@@ -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) =>
|
||||
|
||||
@@ -316,6 +316,8 @@ describe("CheckpointReactor", () => {
|
||||
});
|
||||
const vcsStatusBroadcasterLayer = Layer.succeed(VcsStatusBroadcaster, {
|
||||
getStatus: () => Effect.die("getStatus should not be called in this test"),
|
||||
peekStatus: () => Effect.die("peekStatus should not be called in this test"),
|
||||
pollStatus: () => Effect.die("pollStatus should not be called in this test"),
|
||||
refreshLocalStatus: (cwd: string) =>
|
||||
Effect.sync(() => {
|
||||
options?.gitStatusRefreshCalls?.push(cwd);
|
||||
|
||||
@@ -9,6 +9,7 @@ import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
|
||||
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
|
||||
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
|
||||
import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts";
|
||||
import { ThreadSettlementReactor } from "../ThreadSettlementReactor.ts";
|
||||
import { OrchestrationReactor } from "../Services/OrchestrationReactor.ts";
|
||||
import { makeOrchestrationReactor } from "./OrchestrationReactor.ts";
|
||||
import * as AgentAwarenessRelay from "../../relay/AgentAwarenessRelay.ts";
|
||||
@@ -64,6 +65,15 @@ describe("OrchestrationReactor", () => {
|
||||
drain: Effect.void,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ThreadSettlementReactor, {
|
||||
start: () => {
|
||||
started.push("thread-settlement-reactor");
|
||||
return Effect.void;
|
||||
},
|
||||
drain: Effect.void,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(AgentAwarenessRelay.AgentAwarenessRelay, {
|
||||
publishThread: () => Effect.void,
|
||||
@@ -85,6 +95,7 @@ describe("OrchestrationReactor", () => {
|
||||
"provider-command-reactor",
|
||||
"checkpoint-reactor",
|
||||
"thread-deletion-reactor",
|
||||
"thread-settlement-reactor",
|
||||
"agent-awareness-relay",
|
||||
]);
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
|
||||
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
|
||||
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
|
||||
import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts";
|
||||
import { ThreadSettlementReactor } from "../ThreadSettlementReactor.ts";
|
||||
import * as AgentAwarenessRelay from "../../relay/AgentAwarenessRelay.ts";
|
||||
|
||||
export const makeOrchestrationReactor = Effect.gen(function* () {
|
||||
@@ -16,6 +17,7 @@ export const makeOrchestrationReactor = Effect.gen(function* () {
|
||||
const providerCommandReactor = yield* ProviderCommandReactor;
|
||||
const checkpointReactor = yield* CheckpointReactor;
|
||||
const threadDeletionReactor = yield* ThreadDeletionReactor;
|
||||
const threadSettlementReactor = yield* ThreadSettlementReactor;
|
||||
const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
|
||||
|
||||
const start: OrchestrationReactorShape["start"] = Effect.fn("start")(function* () {
|
||||
@@ -23,6 +25,7 @@ export const makeOrchestrationReactor = Effect.gen(function* () {
|
||||
yield* providerCommandReactor.start();
|
||||
yield* checkpointReactor.start();
|
||||
yield* threadDeletionReactor.start();
|
||||
yield* threadSettlementReactor.start();
|
||||
yield* agentAwarenessRelay.start();
|
||||
});
|
||||
|
||||
|
||||
@@ -400,6 +400,8 @@ describe("ProviderCommandReactor", () => {
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(VcsStatusBroadcaster, {
|
||||
getStatus: () => Effect.die("getStatus should not be called in this test"),
|
||||
peekStatus: () => Effect.die("peekStatus should not be called in this test"),
|
||||
pollStatus: () => Effect.die("pollStatus should not be called in this test"),
|
||||
refreshLocalStatus: () =>
|
||||
Effect.die("refreshLocalStatus should not be called in this test"),
|
||||
refreshStatus,
|
||||
|
||||
@@ -0,0 +1,344 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import {
|
||||
GitManagerError,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationCommand,
|
||||
type OrchestrationProjectShell,
|
||||
type OrchestrationShellSnapshot,
|
||||
type OrchestrationThreadShell,
|
||||
type VcsStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import { VcsStatusBroadcaster } from "../vcs/VcsStatusBroadcaster.ts";
|
||||
import {
|
||||
OrchestrationEngineService,
|
||||
type OrchestrationEngineShape,
|
||||
} from "./Services/OrchestrationEngine.ts";
|
||||
import {
|
||||
ProjectionSnapshotQuery,
|
||||
type ProjectionSnapshotQueryShape,
|
||||
} from "./Services/ProjectionSnapshotQuery.ts";
|
||||
import { make } from "./ThreadSettlementReactor.ts";
|
||||
|
||||
const projectId = ProjectId.make("project-1");
|
||||
const project: OrchestrationProjectShell = {
|
||||
id: projectId,
|
||||
title: "Project",
|
||||
workspaceRoot: "/repo",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2020-01-01T00:00:00.000Z",
|
||||
updatedAt: "2020-01-01T00:00:00.000Z",
|
||||
};
|
||||
|
||||
function makeThread(input: {
|
||||
readonly id: string;
|
||||
readonly branch?: string | null;
|
||||
readonly cwd?: string;
|
||||
readonly pinned?: boolean;
|
||||
}): OrchestrationThreadShell {
|
||||
const threadId = ThreadId.make(input.id);
|
||||
return {
|
||||
id: threadId,
|
||||
projectId,
|
||||
title: input.id,
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: input.branch ?? null,
|
||||
worktreePath: input.cwd ?? null,
|
||||
latestTurn: {
|
||||
turnId: TurnId.make(`turn-${input.id}`),
|
||||
state: "completed",
|
||||
// @effect/vitest's test clock starts at the Unix epoch.
|
||||
requestedAt: "1960-01-01T00:00:00.000Z",
|
||||
startedAt: null,
|
||||
completedAt: null,
|
||||
assistantMessageId: null,
|
||||
},
|
||||
createdAt: "2020-01-01T00:00:00.000Z",
|
||||
updatedAt: "2020-01-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
...(input.pinned ? { pinnedAt: "2020-01-02T00:00:00.000Z" } : {}),
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
};
|
||||
}
|
||||
|
||||
function vcsStatus(
|
||||
branch: string,
|
||||
state: "open" | "closed" | "merged" | null,
|
||||
headRef = branch,
|
||||
): VcsStatusResult {
|
||||
return {
|
||||
isRepo: true,
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: branch,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr:
|
||||
state === null
|
||||
? null
|
||||
: {
|
||||
number: 1,
|
||||
title: branch,
|
||||
url: `https://example.test/${branch}`,
|
||||
baseRef: "main",
|
||||
headRef,
|
||||
state,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function makeHarness(input: {
|
||||
readonly threads: ReadonlyArray<OrchestrationThreadShell>;
|
||||
readonly peekStatus?: VcsStatusBroadcaster["Service"]["peekStatus"];
|
||||
readonly pollStatus?: VcsStatusBroadcaster["Service"]["pollStatus"];
|
||||
readonly opportunisticWork?: boolean;
|
||||
readonly autoSettleOnMerge?: boolean;
|
||||
}) {
|
||||
return Effect.gen(function* () {
|
||||
const snapshot = {
|
||||
snapshotSequence: 1,
|
||||
projects: [project],
|
||||
threads: input.threads,
|
||||
updatedAt: "2020-01-02T00:00:00.000Z",
|
||||
} satisfies OrchestrationShellSnapshot;
|
||||
const dispatched = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
|
||||
const dependencies = Layer.mergeAll(
|
||||
Layer.succeed(OrchestrationEngineService, {
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: (command) =>
|
||||
Ref.update(dispatched, (commands) => [...commands, command]).pipe(
|
||||
Effect.as({ sequence: 1 }),
|
||||
),
|
||||
streamDomainEvents: Stream.empty,
|
||||
latestSequence: Effect.succeed(0),
|
||||
} satisfies OrchestrationEngineShape),
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getShellSnapshot: () => Effect.succeed(snapshot),
|
||||
} as unknown as ProjectionSnapshotQueryShape),
|
||||
ServerSettingsService.layerTest({
|
||||
threadAutoSettleOnMerge: input.autoSettleOnMerge ?? true,
|
||||
}),
|
||||
Layer.succeed(VcsStatusBroadcaster, {
|
||||
getStatus: () => Effect.die("getStatus should not be called"),
|
||||
peekStatus: input.peekStatus ?? (() => Effect.succeed(null)),
|
||||
pollStatus: input.pollStatus ?? (() => Effect.die("pollStatus should not be called")),
|
||||
refreshLocalStatus: () => Effect.die("refreshLocalStatus should not be called"),
|
||||
refreshStatus: () => Effect.die("refreshStatus should not be called"),
|
||||
streamStatus: () => Stream.empty,
|
||||
}),
|
||||
Layer.mock(BackgroundPolicy.BackgroundPolicy)({
|
||||
shouldRunOpportunisticWork: Effect.succeed(input.opportunisticWork ?? false),
|
||||
}),
|
||||
NodeServices.layer,
|
||||
);
|
||||
const reactor = yield* make.pipe(Effect.provide(dependencies));
|
||||
return { reactor, dispatched };
|
||||
});
|
||||
}
|
||||
|
||||
it.effect("persists inactivity and merged-PR settlement while leaving other pins alone", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const inactivity = makeThread({ id: "inactivity" });
|
||||
const pinnedClosed = makeThread({
|
||||
id: "pinned-closed",
|
||||
branch: "feature/closed",
|
||||
cwd: "/repo/closed",
|
||||
pinned: true,
|
||||
});
|
||||
const pinnedOpen = makeThread({
|
||||
id: "pinned-open",
|
||||
branch: "feature/open",
|
||||
cwd: "/repo/open",
|
||||
pinned: true,
|
||||
});
|
||||
const pinnedMerged = makeThread({
|
||||
id: "pinned-merged",
|
||||
branch: "feature/merged",
|
||||
cwd: "/repo/merged",
|
||||
pinned: true,
|
||||
});
|
||||
const byCwd = new Map([
|
||||
[pinnedClosed.worktreePath, vcsStatus(pinnedClosed.branch!, "closed")],
|
||||
[pinnedOpen.worktreePath, vcsStatus(pinnedOpen.branch!, "open")],
|
||||
[pinnedMerged.worktreePath, vcsStatus(pinnedMerged.branch!, "merged")],
|
||||
]);
|
||||
const { reactor, dispatched } = yield* makeHarness({
|
||||
threads: [inactivity, pinnedClosed, pinnedOpen, pinnedMerged],
|
||||
peekStatus: ({ cwd }) => Effect.succeed(byCwd.get(cwd) ?? null),
|
||||
pollStatus: (cwd) => Effect.succeed(byCwd.get(cwd)!),
|
||||
opportunisticWork: true,
|
||||
});
|
||||
|
||||
yield* reactor.start();
|
||||
yield* reactor.drain;
|
||||
|
||||
const settledThreadIds = (yield* Ref.get(dispatched))
|
||||
.filter((command) => command.type === "thread.settle")
|
||||
.map((command) => command.threadId)
|
||||
.sort();
|
||||
expect(settledThreadIds).toEqual([inactivity.id, pinnedMerged.id].sort());
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("re-verifies cached PR state and settles a pin only after merge", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const thread = makeThread({
|
||||
id: "pinned-merged-after-cache",
|
||||
branch: "feature/merge-later",
|
||||
cwd: "/repo/merge-later",
|
||||
pinned: true,
|
||||
});
|
||||
const pollCalls = yield* Ref.make(0);
|
||||
const { reactor, dispatched } = yield* makeHarness({
|
||||
threads: [thread],
|
||||
peekStatus: () => Effect.succeed(vcsStatus(thread.branch!, "open")),
|
||||
pollStatus: () =>
|
||||
Ref.update(pollCalls, (count) => count + 1).pipe(
|
||||
Effect.as(vcsStatus(thread.branch!, "merged")),
|
||||
),
|
||||
opportunisticWork: true,
|
||||
});
|
||||
|
||||
yield* reactor.start();
|
||||
yield* reactor.drain;
|
||||
|
||||
expect(yield* Ref.get(pollCalls)).toBe(1);
|
||||
expect(
|
||||
(yield* Ref.get(dispatched)).map((command) =>
|
||||
command.type === "thread.settle" ? command.threadId : null,
|
||||
),
|
||||
).toEqual([thread.id]);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("keeps merged pinned threads active when merge settlement is disabled", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const thread = makeThread({
|
||||
id: "pinned-merged-disabled",
|
||||
branch: "feature/merged-disabled",
|
||||
cwd: "/repo/merged-disabled",
|
||||
pinned: true,
|
||||
});
|
||||
const pollCalls = yield* Ref.make(0);
|
||||
const { reactor, dispatched } = yield* makeHarness({
|
||||
threads: [thread],
|
||||
peekStatus: () => Effect.succeed(vcsStatus(thread.branch!, "open")),
|
||||
pollStatus: () =>
|
||||
Ref.update(pollCalls, (count) => count + 1).pipe(
|
||||
Effect.as(vcsStatus(thread.branch!, "merged")),
|
||||
),
|
||||
opportunisticWork: true,
|
||||
autoSettleOnMerge: false,
|
||||
});
|
||||
|
||||
yield* reactor.start();
|
||||
yield* reactor.drain;
|
||||
|
||||
expect(yield* Ref.get(pollCalls)).toBe(0);
|
||||
expect(yield* Ref.get(dispatched)).toEqual([]);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not settle when PR verification fails or belongs to another branch", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const lookupFailed = makeThread({
|
||||
id: "lookup-failed",
|
||||
branch: "feature/open-pr",
|
||||
cwd: "/repo/lookup-failed",
|
||||
});
|
||||
const mismatchedMerge = makeThread({
|
||||
id: "mismatched-merge",
|
||||
branch: "feature/current",
|
||||
cwd: "/repo/mismatched",
|
||||
});
|
||||
const { reactor, dispatched } = yield* makeHarness({
|
||||
threads: [lookupFailed, mismatchedMerge],
|
||||
peekStatus: ({ cwd }) =>
|
||||
Effect.succeed(
|
||||
cwd === mismatchedMerge.worktreePath
|
||||
? vcsStatus(mismatchedMerge.branch!, "merged", "feature/other")
|
||||
: null,
|
||||
),
|
||||
pollStatus: (cwd) =>
|
||||
cwd === lookupFailed.worktreePath
|
||||
? Effect.fail(
|
||||
new GitManagerError({
|
||||
operation: "ThreadSettlementReactor.test",
|
||||
cwd,
|
||||
detail: "temporary lookup failure",
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(vcsStatus(mismatchedMerge.branch!, "merged", "feature/other")),
|
||||
opportunisticWork: true,
|
||||
});
|
||||
|
||||
yield* reactor.start();
|
||||
yield* reactor.drain;
|
||||
|
||||
expect(yield* Ref.get(dispatched)).toEqual([]);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("bounds live verification and lets cooldown-skipped entries yield the next batch", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const threads = Array.from({ length: 7 }, (_, index) =>
|
||||
makeThread({
|
||||
id: `pinned-${index}`,
|
||||
branch: `feature/${index}`,
|
||||
cwd: `/repo/${index}`,
|
||||
pinned: true,
|
||||
}),
|
||||
);
|
||||
const branchByCwd = new Map(threads.map((thread) => [thread.worktreePath, thread.branch!]));
|
||||
const polledCwds = yield* Ref.make<ReadonlyArray<string>>([]);
|
||||
const { reactor, dispatched } = yield* makeHarness({
|
||||
threads,
|
||||
pollStatus: (cwd) =>
|
||||
Ref.update(polledCwds, (values) => [...values, cwd]).pipe(
|
||||
Effect.as(vcsStatus(branchByCwd.get(cwd)!, "open")),
|
||||
),
|
||||
opportunisticWork: true,
|
||||
});
|
||||
|
||||
yield* reactor.start();
|
||||
yield* reactor.drain;
|
||||
expect(yield* Ref.get(polledCwds)).toHaveLength(5);
|
||||
|
||||
yield* reactor.start();
|
||||
yield* reactor.drain;
|
||||
expect(new Set(yield* Ref.get(polledCwds))).toEqual(new Set(branchByCwd.keys()));
|
||||
expect(yield* Ref.get(dispatched)).toEqual([]);
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -0,0 +1,225 @@
|
||||
import {
|
||||
CommandId,
|
||||
type OrchestrationProjectShell,
|
||||
type OrchestrationThreadShell,
|
||||
type VcsStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Ref from "effect/Ref";
|
||||
import type * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
|
||||
import { resolveThreadWorkspaceCwd } from "../checkpointing/Utils.ts";
|
||||
import { forkParked } from "../serverActivation.ts";
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import { VcsStatusBroadcaster } from "../vcs/VcsStatusBroadcaster.ts";
|
||||
import { OrchestrationEngineService } from "./Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "./Services/ProjectionSnapshotQuery.ts";
|
||||
import {
|
||||
type AutomaticSettlementChangeRequestState,
|
||||
resolveAutomaticSettlementVerdict,
|
||||
} from "./threadSettlement.ts";
|
||||
|
||||
const RECONCILE_INTERVAL = Duration.minutes(1);
|
||||
const PR_VERIFY_COOLDOWN_MS = Duration.toMillis(Duration.minutes(30));
|
||||
const MAX_PR_VERIFICATIONS_PER_RECONCILE = 5;
|
||||
|
||||
export class ThreadSettlementReactor extends Context.Service<
|
||||
ThreadSettlementReactor,
|
||||
{
|
||||
/** Start the persisted inactivity and merged-PR settlement lifecycle. */
|
||||
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
|
||||
|
||||
/** Resolves when all automatic settlement work already queued is complete. */
|
||||
readonly drain: Effect.Effect<void>;
|
||||
}
|
||||
>()("t3/orchestration/ThreadSettlementReactor") {}
|
||||
|
||||
function workspaceCwd(
|
||||
thread: Pick<OrchestrationThreadShell, "projectId" | "worktreePath">,
|
||||
projects: ReadonlyArray<OrchestrationProjectShell>,
|
||||
): string | undefined {
|
||||
return resolveThreadWorkspaceCwd({ thread, projects });
|
||||
}
|
||||
|
||||
function cachedChangeRequestState(
|
||||
thread: Pick<OrchestrationThreadShell, "branch">,
|
||||
status: VcsStatusResult | null,
|
||||
): AutomaticSettlementChangeRequestState {
|
||||
if (thread.branch === null) return null;
|
||||
if (status === null || status.refName !== thread.branch) return "unknown";
|
||||
if (status.pr === null || status.pr.headRef !== thread.branch) return "unknown";
|
||||
if (status.pr.state === "open") return "open-cached";
|
||||
if (status.pr.state === "closed") return "closed-cached";
|
||||
return "merged";
|
||||
}
|
||||
|
||||
function liveChangeRequestState(
|
||||
thread: Pick<OrchestrationThreadShell, "branch">,
|
||||
status: VcsStatusResult,
|
||||
): AutomaticSettlementChangeRequestState {
|
||||
if (thread.branch === null) return null;
|
||||
if (status.refName !== thread.branch || status.pr?.headRef !== thread.branch) return "unknown";
|
||||
return status.pr.state;
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
|
||||
const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
const lastPrVerifyAtByCwd = yield* Ref.make(new Map<string, number>());
|
||||
|
||||
const dispatchSettlement = Effect.fn("ThreadSettlementReactor.dispatchSettlement")(function* (
|
||||
thread: OrchestrationThreadShell,
|
||||
reason: "inactivity" | "pr-merged",
|
||||
) {
|
||||
const commandId = CommandId.make(
|
||||
`server:thread-auto-settle:${reason}:${yield* crypto.randomUUIDv4}`,
|
||||
);
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.settle",
|
||||
commandId,
|
||||
threadId: thread.id,
|
||||
});
|
||||
});
|
||||
|
||||
const dispatchSettlementSafely = (
|
||||
thread: OrchestrationThreadShell,
|
||||
reason: "inactivity" | "pr-merged",
|
||||
) =>
|
||||
dispatchSettlement(thread, reason).pipe(
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) return Effect.failCause(cause);
|
||||
return Effect.logDebug("automatic thread settlement skipped after a raced state change", {
|
||||
threadId: thread.id,
|
||||
reason,
|
||||
cause: Cause.pretty(cause),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const verifyChangeRequestState = Effect.fn("ThreadSettlementReactor.verifyChangeRequestState")(
|
||||
function* (input: {
|
||||
readonly thread: OrchestrationThreadShell;
|
||||
readonly cwd: string;
|
||||
}): Effect.fn.Return<{
|
||||
readonly state: AutomaticSettlementChangeRequestState;
|
||||
readonly verified: boolean;
|
||||
}> {
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
const mayVerify = yield* Ref.modify(lastPrVerifyAtByCwd, (byCwd) => {
|
||||
const lastAt = byCwd.get(input.cwd);
|
||||
if (lastAt !== undefined && now - lastAt < PR_VERIFY_COOLDOWN_MS) {
|
||||
return [false, byCwd] as const;
|
||||
}
|
||||
const next = new Map(byCwd);
|
||||
next.set(input.cwd, now);
|
||||
return [true, next] as const;
|
||||
});
|
||||
if (!mayVerify) return { state: "unknown", verified: false };
|
||||
|
||||
const status = yield* vcsStatusBroadcaster.pollStatus(input.cwd).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logDebug("automatic thread settlement could not verify change request state", {
|
||||
threadId: input.thread.id,
|
||||
cwdLength: input.cwd.length,
|
||||
errorTag: error._tag,
|
||||
}).pipe(Effect.as(null)),
|
||||
),
|
||||
);
|
||||
return status === null
|
||||
? { state: "unknown", verified: true }
|
||||
: { state: liveChangeRequestState(input.thread, status), verified: true };
|
||||
},
|
||||
);
|
||||
|
||||
const reconcile = Effect.fn("ThreadSettlementReactor.reconcile")(function* () {
|
||||
const [snapshot, settings, now, mayVerifyPr] = yield* Effect.all([
|
||||
projectionSnapshotQuery.getShellSnapshot(),
|
||||
serverSettings.getSettings,
|
||||
DateTime.now,
|
||||
backgroundPolicy.shouldRunOpportunisticWork,
|
||||
]);
|
||||
const nowIso = DateTime.formatIso(now);
|
||||
let verifyBudget = MAX_PR_VERIFICATIONS_PER_RECONCILE;
|
||||
|
||||
for (const thread of snapshot.threads) {
|
||||
const cwd = workspaceCwd(thread, snapshot.projects);
|
||||
const changeRequestState =
|
||||
thread.branch === null
|
||||
? null
|
||||
: cwd === undefined
|
||||
? "unknown"
|
||||
: cachedChangeRequestState(thread, yield* vcsStatusBroadcaster.peekStatus({ cwd }));
|
||||
const verdict = resolveAutomaticSettlementVerdict(thread, {
|
||||
now: nowIso,
|
||||
autoSettleAfterDays: settings.threadAutoSettleAfterDays,
|
||||
autoSettleOnMerge: settings.threadAutoSettleOnMerge,
|
||||
changeRequestState,
|
||||
});
|
||||
if (verdict.kind === "skip") continue;
|
||||
if (verdict.kind === "settle") {
|
||||
yield* dispatchSettlementSafely(thread, verdict.reason);
|
||||
continue;
|
||||
}
|
||||
if (!mayVerifyPr || cwd === undefined || verifyBudget <= 0) continue;
|
||||
|
||||
const verification = yield* verifyChangeRequestState({ thread, cwd });
|
||||
if (verification.verified) verifyBudget -= 1;
|
||||
const verifiedVerdict = resolveAutomaticSettlementVerdict(thread, {
|
||||
now: nowIso,
|
||||
autoSettleAfterDays: settings.threadAutoSettleAfterDays,
|
||||
autoSettleOnMerge: settings.threadAutoSettleOnMerge,
|
||||
changeRequestState: verification.state,
|
||||
});
|
||||
if (verifiedVerdict.kind === "settle") {
|
||||
yield* dispatchSettlementSafely(thread, verifiedVerdict.reason);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const reconcileSafely = reconcile().pipe(
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) return Effect.failCause(cause);
|
||||
return Effect.logWarning("thread settlement reactor failed to reconcile", {
|
||||
cause: Cause.pretty(cause),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const worker = yield* makeDrainableWorker((_input: void) => reconcileSafely);
|
||||
|
||||
const start: ThreadSettlementReactor["Service"]["start"] = Effect.fn(
|
||||
"ThreadSettlementReactor.start",
|
||||
)(function* () {
|
||||
yield* forkParked(
|
||||
Stream.runForEach(serverSettings.streamChanges, () => worker.enqueue(undefined)),
|
||||
);
|
||||
yield* worker.enqueue(undefined);
|
||||
yield* forkParked(
|
||||
Effect.sleep(RECONCILE_INTERVAL).pipe(
|
||||
Effect.andThen(worker.enqueue(undefined)),
|
||||
Effect.forever,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
return ThreadSettlementReactor.of({
|
||||
start,
|
||||
drain: worker.drain,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ThreadSettlementReactor, make);
|
||||
@@ -25,8 +25,8 @@ import { projectEvent } from "./projector.ts";
|
||||
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
|
||||
|
||||
// Session adoption takes seconds; a user message still unadopted after this
|
||||
// window is a failed/stale start, not pending work. Mirrors the client's
|
||||
// QUEUED_TURN_START_GRACE_MS in client-runtime threadSettled.ts.
|
||||
// window is a failed/stale start, not pending work. Keep this synchronized
|
||||
// with the automatic settlement policy in threadSettlement.ts.
|
||||
const QUEUED_TURN_START_GRACE_MS = 2 * 60 * 1_000;
|
||||
|
||||
/**
|
||||
@@ -456,9 +456,8 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
// Server-side twin of the client's canSettle session check: a stale
|
||||
// or raced client must not settle a thread whose session is coming
|
||||
// alive or working.
|
||||
// The server owns this invariant: a stale or raced client must not
|
||||
// settle a thread whose session is coming alive or working.
|
||||
if (thread.session?.status === "starting" || thread.session?.status === "running") {
|
||||
return yield* Effect.fail(
|
||||
new OrchestrationCommandInvariantError({
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
import {
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationThreadShell,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
resolveAutomaticSettlementReason,
|
||||
resolveAutomaticSettlementVerdict,
|
||||
shellHasQueuedTurnStart,
|
||||
threadLastActivityAt,
|
||||
} from "./threadSettlement.ts";
|
||||
|
||||
const NOW = "2026-04-10T00:00:00.000Z";
|
||||
const FRESH = "2026-04-09T00:00:00.000Z";
|
||||
const STALE = "2026-04-06T23:59:59.999Z";
|
||||
|
||||
function makeShell(
|
||||
input: Partial<OrchestrationThreadShell> & {
|
||||
readonly activityAt?: string | null;
|
||||
} = {},
|
||||
): OrchestrationThreadShell {
|
||||
const threadId = ThreadId.make("thread-1");
|
||||
const { activityAt = FRESH, ...overrides } = input;
|
||||
return {
|
||||
id: threadId,
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: "feature/settlement",
|
||||
worktreePath: null,
|
||||
latestTurn:
|
||||
activityAt === null
|
||||
? null
|
||||
: {
|
||||
turnId: TurnId.make("turn-1"),
|
||||
state: "completed",
|
||||
requestedAt: activityAt,
|
||||
startedAt: null,
|
||||
completedAt: null,
|
||||
assistantMessageId: null,
|
||||
},
|
||||
createdAt: "2026-04-01T00:00:00.000Z",
|
||||
updatedAt: NOW,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function resolve(
|
||||
shell: OrchestrationThreadShell,
|
||||
options: {
|
||||
readonly changeRequestState?: "open" | "merged" | "closed" | null;
|
||||
readonly autoSettleAfterDays?: 3 | null;
|
||||
readonly autoSettleOnMerge?: boolean;
|
||||
readonly now?: string;
|
||||
} = {},
|
||||
) {
|
||||
return resolveAutomaticSettlementReason(shell, {
|
||||
now: options.now ?? NOW,
|
||||
autoSettleAfterDays:
|
||||
options.autoSettleAfterDays === undefined ? 3 : options.autoSettleAfterDays,
|
||||
autoSettleOnMerge: options.autoSettleOnMerge ?? true,
|
||||
changeRequestState: options.changeRequestState ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
describe("resolveAutomaticSettlementReason", () => {
|
||||
it("settles stale unpinned threads for inactivity", () => {
|
||||
expect(resolve(makeShell({ activityAt: STALE }))).toBe("inactivity");
|
||||
expect(resolve(makeShell({ activityAt: "2026-04-07T00:00:00.000Z" }))).toBeNull();
|
||||
expect(resolve(makeShell({ activityAt: STALE }), { autoSettleAfterDays: null })).toBeNull();
|
||||
});
|
||||
|
||||
it("never timer-settles a pinned thread", () => {
|
||||
const pinned = makeShell({
|
||||
activityAt: STALE,
|
||||
pinnedAt: "2026-04-07T00:00:00.000Z",
|
||||
});
|
||||
|
||||
expect(resolve(pinned)).toBeNull();
|
||||
expect(resolve(pinned, { changeRequestState: "closed" })).toBeNull();
|
||||
});
|
||||
|
||||
it("settles and therefore unpins a pinned thread only when its PR merges", () => {
|
||||
const pinned = makeShell({
|
||||
activityAt: FRESH,
|
||||
pinnedAt: "2026-04-07T00:00:00.000Z",
|
||||
});
|
||||
|
||||
expect(resolve(pinned, { changeRequestState: "open" })).toBeNull();
|
||||
expect(resolve(pinned, { changeRequestState: "closed" })).toBeNull();
|
||||
expect(resolve(pinned, { changeRequestState: "merged" })).toBe("pr-merged");
|
||||
expect(resolve(pinned, { changeRequestState: "merged", autoSettleOnMerge: false })).toBeNull();
|
||||
});
|
||||
|
||||
it("does not treat a closed PR as an immediate settlement signal", () => {
|
||||
expect(
|
||||
resolve(makeShell({ activityAt: FRESH }), {
|
||||
autoSettleAfterDays: null,
|
||||
changeRequestState: "closed",
|
||||
}),
|
||||
).toBeNull();
|
||||
expect(resolve(makeShell({ activityAt: STALE }), { changeRequestState: "closed" })).toBe(
|
||||
"inactivity",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps open-PR threads active regardless of inactivity", () => {
|
||||
expect(resolve(makeShell({ activityAt: STALE }), { changeRequestState: "open" })).toBeNull();
|
||||
});
|
||||
|
||||
it("honors explicit lifecycle state until real activity clears it", () => {
|
||||
for (const settledOverride of ["active", "settled"] as const) {
|
||||
expect(
|
||||
resolve(makeShell({ activityAt: STALE, settledOverride }), {
|
||||
changeRequestState: "merged",
|
||||
}),
|
||||
).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it("never settles live, blocked, or newly queued work", () => {
|
||||
const queued = makeShell({
|
||||
activityAt: null,
|
||||
latestUserMessageAt: "2026-04-09T12:00:00.000Z",
|
||||
});
|
||||
const mergedOptions = {
|
||||
now: "2026-04-09T12:00:30.000Z",
|
||||
changeRequestState: "merged" as const,
|
||||
};
|
||||
|
||||
expect(resolve(queued, mergedOptions)).toBeNull();
|
||||
expect(resolve(makeShell({ hasPendingApprovals: true }), mergedOptions)).toBeNull();
|
||||
expect(resolve(makeShell({ hasPendingUserInput: true }), mergedOptions)).toBeNull();
|
||||
expect(
|
||||
resolve(
|
||||
makeShell({
|
||||
session: {
|
||||
threadId: queued.id,
|
||||
status: "running",
|
||||
providerName: "Codex",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: TurnId.make("turn-active"),
|
||||
lastError: null,
|
||||
updatedAt: NOW,
|
||||
},
|
||||
}),
|
||||
mergedOptions,
|
||||
),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveAutomaticSettlementVerdict", () => {
|
||||
it("re-verifies cached or unknown PR state even for pinned threads", () => {
|
||||
const pinned = makeShell({
|
||||
activityAt: FRESH,
|
||||
pinnedAt: "2026-04-07T00:00:00.000Z",
|
||||
});
|
||||
|
||||
for (const changeRequestState of ["unknown", "open-cached", "closed-cached"] as const) {
|
||||
expect(
|
||||
resolveAutomaticSettlementVerdict(pinned, {
|
||||
now: NOW,
|
||||
autoSettleAfterDays: 3,
|
||||
autoSettleOnMerge: true,
|
||||
changeRequestState,
|
||||
}),
|
||||
).toEqual({ kind: "verify-pr" });
|
||||
}
|
||||
});
|
||||
|
||||
it("does not look up PR state for pins when merge settlement is disabled", () => {
|
||||
const pinned = makeShell({
|
||||
activityAt: FRESH,
|
||||
pinnedAt: "2026-04-07T00:00:00.000Z",
|
||||
});
|
||||
|
||||
expect(
|
||||
resolveAutomaticSettlementVerdict(pinned, {
|
||||
now: NOW,
|
||||
autoSettleAfterDays: 3,
|
||||
autoSettleOnMerge: false,
|
||||
changeRequestState: "open-cached",
|
||||
}),
|
||||
).toEqual({ kind: "skip" });
|
||||
});
|
||||
|
||||
it("does not re-verify terminal live states", () => {
|
||||
const pinned = makeShell({
|
||||
activityAt: STALE,
|
||||
pinnedAt: "2026-04-07T00:00:00.000Z",
|
||||
});
|
||||
|
||||
expect(
|
||||
resolveAutomaticSettlementVerdict(pinned, {
|
||||
now: NOW,
|
||||
autoSettleAfterDays: 3,
|
||||
autoSettleOnMerge: true,
|
||||
changeRequestState: "closed",
|
||||
}),
|
||||
).toEqual({ kind: "skip" });
|
||||
expect(
|
||||
resolveAutomaticSettlementVerdict(pinned, {
|
||||
now: NOW,
|
||||
autoSettleAfterDays: 3,
|
||||
autoSettleOnMerge: true,
|
||||
changeRequestState: "merged",
|
||||
}),
|
||||
).toEqual({ kind: "settle", reason: "pr-merged" });
|
||||
expect(
|
||||
resolveAutomaticSettlementVerdict(pinned, {
|
||||
now: NOW,
|
||||
autoSettleAfterDays: 3,
|
||||
autoSettleOnMerge: false,
|
||||
changeRequestState: "merged",
|
||||
}),
|
||||
).toEqual({ kind: "skip" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("server settlement activity guards", () => {
|
||||
it("uses the latest user or turn activity timestamp", () => {
|
||||
const shell = makeShell({
|
||||
latestUserMessageAt: "2026-04-04T00:00:00.000Z",
|
||||
latestTurn: {
|
||||
turnId: TurnId.make("turn-1"),
|
||||
state: "completed",
|
||||
requestedAt: "2026-04-03T00:00:00.000Z",
|
||||
startedAt: "2026-04-05T00:00:00.000Z",
|
||||
completedAt: "2026-04-06T00:00:00.000Z",
|
||||
assistantMessageId: null,
|
||||
},
|
||||
});
|
||||
|
||||
expect(threadLastActivityAt(shell)).toBe("2026-04-06T00:00:00.000Z");
|
||||
});
|
||||
|
||||
it("bounds the queued-turn guard so failed starts do not block forever", () => {
|
||||
const shell = makeShell({
|
||||
activityAt: null,
|
||||
latestUserMessageAt: "2026-04-09T12:00:00.000Z",
|
||||
});
|
||||
|
||||
expect(shellHasQueuedTurnStart(shell, "2026-04-09T12:00:30.000Z")).toBe(true);
|
||||
expect(shellHasQueuedTurnStart(shell, "2026-04-09T12:03:00.000Z")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,121 @@
|
||||
import type {
|
||||
ChangeRequestState,
|
||||
OrchestrationThreadShell,
|
||||
ThreadAutoSettleAfterDays,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
const DAY_MS = 24 * 60 * 60 * 1_000;
|
||||
|
||||
// Session adoption takes seconds. A newer user message with no adopted turn
|
||||
// is pending work, but old unmatched messages must not block settlement forever.
|
||||
export const QUEUED_TURN_START_GRACE_MS = 2 * 60 * 1_000;
|
||||
|
||||
export type AutomaticSettlementReason = "inactivity" | "pr-merged";
|
||||
export type AutomaticSettlementChangeRequestState =
|
||||
| ChangeRequestState
|
||||
| "open-cached"
|
||||
| "closed-cached"
|
||||
| "unknown"
|
||||
| null;
|
||||
export type AutomaticSettlementVerdict =
|
||||
| { readonly kind: "skip" }
|
||||
| { readonly kind: "verify-pr" }
|
||||
| { readonly kind: "settle"; readonly reason: AutomaticSettlementReason };
|
||||
|
||||
export function threadLastActivityAt(shell: OrchestrationThreadShell): string | null {
|
||||
const candidates = [
|
||||
shell.latestUserMessageAt,
|
||||
shell.latestTurn?.requestedAt,
|
||||
shell.latestTurn?.startedAt,
|
||||
shell.latestTurn?.completedAt,
|
||||
];
|
||||
let latest: string | null = null;
|
||||
let latestTimestamp = Number.NEGATIVE_INFINITY;
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (candidate == null) continue;
|
||||
const timestamp = Date.parse(candidate);
|
||||
if (timestamp > latestTimestamp) {
|
||||
latest = candidate;
|
||||
latestTimestamp = timestamp;
|
||||
}
|
||||
}
|
||||
|
||||
return latest;
|
||||
}
|
||||
|
||||
export function shellHasQueuedTurnStart(
|
||||
shell: Pick<OrchestrationThreadShell, "latestUserMessageAt" | "latestTurn" | "session">,
|
||||
now: string,
|
||||
): boolean {
|
||||
if (shell.latestUserMessageAt == null || shell.session?.status === "error") return false;
|
||||
const messageAt = Date.parse(shell.latestUserMessageAt);
|
||||
const nowMs = Date.parse(now);
|
||||
if (!Number.isFinite(messageAt) || !Number.isFinite(nowMs)) return false;
|
||||
if (Math.abs(nowMs - messageAt) > QUEUED_TURN_START_GRACE_MS) return false;
|
||||
if (shell.latestTurn === null) return true;
|
||||
return [
|
||||
shell.latestTurn.requestedAt,
|
||||
shell.latestTurn.startedAt,
|
||||
shell.latestTurn.completedAt,
|
||||
].every((candidate) => candidate == null || Date.parse(candidate) < messageAt);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the server-owned automatic settlement transition. Explicit user
|
||||
* state wins, live or blocked work stays active, and a visible pin suppresses
|
||||
* inactivity only. A merged PR is the one automatic signal allowed to settle
|
||||
* and unpin a pinned thread.
|
||||
*/
|
||||
export function resolveAutomaticSettlementVerdict(
|
||||
shell: OrchestrationThreadShell,
|
||||
options: {
|
||||
readonly now: string;
|
||||
readonly autoSettleAfterDays: ThreadAutoSettleAfterDays | null;
|
||||
readonly autoSettleOnMerge: boolean;
|
||||
readonly changeRequestState: AutomaticSettlementChangeRequestState;
|
||||
},
|
||||
): AutomaticSettlementVerdict {
|
||||
if (shell.settledOverride !== null) return { kind: "skip" };
|
||||
if (shell.hasPendingApprovals || shell.hasPendingUserInput) return { kind: "skip" };
|
||||
if (shell.session?.status === "starting" || shell.session?.status === "running") {
|
||||
return { kind: "skip" };
|
||||
}
|
||||
if (shellHasQueuedTurnStart(shell, options.now)) return { kind: "skip" };
|
||||
|
||||
if (shell.pinnedAt != null && !options.autoSettleOnMerge) return { kind: "skip" };
|
||||
if (options.changeRequestState === "merged" && options.autoSettleOnMerge) {
|
||||
return { kind: "settle", reason: "pr-merged" };
|
||||
}
|
||||
// Cached non-terminal states can hide a later merge. Re-verify them on the
|
||||
// reactor's bounded cooldown even for fresh or pinned threads.
|
||||
if (
|
||||
options.changeRequestState === "unknown" ||
|
||||
options.changeRequestState === "open-cached" ||
|
||||
options.changeRequestState === "closed-cached"
|
||||
) {
|
||||
return { kind: "verify-pr" };
|
||||
}
|
||||
if (shell.pinnedAt != null) return { kind: "skip" };
|
||||
if (options.changeRequestState === "open") return { kind: "skip" };
|
||||
if (options.autoSettleAfterDays === null) return { kind: "skip" };
|
||||
|
||||
const lastActivityAt = threadLastActivityAt(shell);
|
||||
if (lastActivityAt === null) return { kind: "skip" };
|
||||
return Date.parse(lastActivityAt) < Date.parse(options.now) - options.autoSettleAfterDays * DAY_MS
|
||||
? { kind: "settle", reason: "inactivity" }
|
||||
: { kind: "skip" };
|
||||
}
|
||||
|
||||
export function resolveAutomaticSettlementReason(
|
||||
shell: OrchestrationThreadShell,
|
||||
options: {
|
||||
readonly now: string;
|
||||
readonly autoSettleAfterDays: ThreadAutoSettleAfterDays | null;
|
||||
readonly autoSettleOnMerge: boolean;
|
||||
readonly changeRequestState: ChangeRequestState | null;
|
||||
},
|
||||
): AutomaticSettlementReason | null {
|
||||
const verdict = resolveAutomaticSettlementVerdict(shell, options);
|
||||
return verdict.kind === "settle" ? verdict.reason : null;
|
||||
}
|
||||
@@ -120,7 +120,7 @@ Example:
|
||||
plan content
|
||||
</proposed_plan>
|
||||
|
||||
plan content should be human and agent digestible. The final plan must be plan-only and include:
|
||||
plan content should be human and agent digestible. The final plan must be plan-only, concise by default, and include:
|
||||
|
||||
* A clear title
|
||||
* A brief summary section
|
||||
@@ -128,9 +128,17 @@ plan content should be human and agent digestible. The final plan must be plan-o
|
||||
* Test cases and scenarios
|
||||
* Explicit assumptions and defaults chosen where needed
|
||||
|
||||
When possible, prefer a compact structure with 3-5 short sections, usually: Summary, Key Changes or Implementation Changes, Test Plan, and Assumptions. Do not include a separate Scope section unless scope boundaries are genuinely important to avoid mistakes.
|
||||
|
||||
Prefer grouped implementation bullets by subsystem or behavior over file-by-file inventories. Mention files only when needed to disambiguate a non-obvious change, and avoid naming more than 3 paths unless extra specificity is necessary to prevent mistakes. Prefer behavior-level descriptions over symbol-by-symbol removal lists. For v1 feature-addition plans, do not invent detailed schema, validation, precedence, fallback, or wire-shape policy unless the request establishes it or it is needed to prevent a concrete implementation mistake; prefer the intended capability and minimum interface/behavior changes.
|
||||
|
||||
Keep bullets short and avoid explanatory sub-bullets unless they are needed to prevent ambiguity. Prefer the minimum detail needed for implementation safety, not exhaustive coverage. Within each section, compress related changes into a few high-signal bullets and omit branch-by-branch logic, repeated invariants, and long lists of unaffected behavior unless they are necessary to prevent a likely implementation mistake. Avoid repeated repo facts and irrelevant edge-case or rollout detail. For straightforward refactors, keep the plan to a compact summary, key edits, tests, and assumptions. If the user asks for more detail, then expand.
|
||||
|
||||
Do not ask "should I proceed?" in the final output. The user can easily switch out of Plan mode and request implementation if you have included a \`<proposed_plan>\` block in your response. Alternatively, they can decide to stay in Plan mode and continue refining the plan.
|
||||
|
||||
Only produce at most one \`<proposed_plan>\` block per turn, and only when you are presenting a complete spec.
|
||||
|
||||
If the user stays in Plan mode and asks for revisions after a prior \`<proposed_plan>\`, any new \`<proposed_plan>\` must be a complete replacement. If the user indicates that the prior plan is not acceptable but does not provide enough information to produce a complete replacement, address the concern and continue planning without producing a \`<proposed_plan>\` block. If the follow-up neither requires changes nor calls the plan into question (e.g. clarifying question), answer it before the block, then reproduce the prior \`<proposed_plan>\` unchanged.
|
||||
${T3_CODE_BROWSER_TOOL_INSTRUCTIONS}
|
||||
</collaboration_mode>`;
|
||||
|
||||
@@ -142,7 +150,7 @@ Your active mode changes only when new developer instructions with a different \
|
||||
|
||||
## request_user_input availability
|
||||
|
||||
The \`request_user_input\` tool is unavailable in Default mode. If you call it while in Default mode, it will return an error.
|
||||
Use the \`request_user_input\` tool only when it is listed in the available tools for this turn.
|
||||
|
||||
In Default mode, strongly prefer making reasonable assumptions and executing the user's request rather than stopping to ask questions. If you absolutely must ask a question because the answer cannot be discovered from local context and a reasonable assumption would be risky, ask the user directly with a concise plain-text question. Never write a multiple choice question as a textual assistant message.
|
||||
${T3_CODE_BROWSER_TOOL_INSTRUCTIONS}
|
||||
|
||||
@@ -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
@@ -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;
|
||||
});
|
||||
}
|
||||
@@ -58,6 +58,7 @@ import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRun
|
||||
import { ProviderCommandReactorLive } from "./orchestration/Layers/ProviderCommandReactor.ts";
|
||||
import { CheckpointReactorLive } from "./orchestration/Layers/CheckpointReactor.ts";
|
||||
import { ThreadDeletionReactorLive } from "./orchestration/Layers/ThreadDeletionReactor.ts";
|
||||
import * as ThreadSettlementReactor from "./orchestration/ThreadSettlementReactor.ts";
|
||||
import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts";
|
||||
import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
|
||||
import { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry.ts";
|
||||
@@ -242,6 +243,7 @@ const ReactorLayerLive = Layer.empty.pipe(
|
||||
Layer.provideMerge(ProviderCommandReactorLive),
|
||||
Layer.provideMerge(CheckpointReactorLive),
|
||||
Layer.provideMerge(ThreadDeletionReactorLive),
|
||||
Layer.provideMerge(ThreadSettlementReactor.layer),
|
||||
Layer.provideMerge(AgentAwarenessRelay.layer.pipe(Layer.provide(ServerSecretStore.layer))),
|
||||
Layer.provideMerge(RuntimeReceiptBusLive),
|
||||
);
|
||||
|
||||
@@ -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 });
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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") ||
|
||||
|
||||
@@ -7,6 +7,7 @@ import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Option from "effect/Option";
|
||||
@@ -74,7 +75,10 @@ function makeTestLayer(state: {
|
||||
remoteStatusCalls: number;
|
||||
localInvalidationCalls: number;
|
||||
remoteInvalidationCalls: number;
|
||||
fullInvalidationCalls?: number;
|
||||
remoteStatusRefreshUpstreamValues?: Array<boolean | undefined>;
|
||||
localStatusEffect?: (call: number) => Effect.Effect<VcsStatusLocalResult>;
|
||||
remoteStatusEffect?: (call: number) => Effect.Effect<VcsStatusRemoteResult | null>;
|
||||
}) {
|
||||
return VcsStatusBroadcaster.layer.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
@@ -82,15 +86,21 @@ function makeTestLayer(state: {
|
||||
Layer.provide(
|
||||
Layer.mock(GitWorkflowService.GitWorkflowService)({
|
||||
localStatus: () =>
|
||||
Effect.sync(() => {
|
||||
Effect.suspend(() => {
|
||||
state.localStatusCalls += 1;
|
||||
return state.currentLocalStatus;
|
||||
return (
|
||||
state.localStatusEffect?.(state.localStatusCalls) ??
|
||||
Effect.succeed(state.currentLocalStatus)
|
||||
);
|
||||
}),
|
||||
remoteStatus: (_input, options) =>
|
||||
Effect.sync(() => {
|
||||
Effect.suspend(() => {
|
||||
state.remoteStatusCalls += 1;
|
||||
state.remoteStatusRefreshUpstreamValues?.push(options?.refreshUpstream);
|
||||
return state.currentRemoteStatus;
|
||||
return (
|
||||
state.remoteStatusEffect?.(state.remoteStatusCalls) ??
|
||||
Effect.succeed(state.currentRemoteStatus)
|
||||
);
|
||||
}),
|
||||
invalidateLocalStatus: () =>
|
||||
Effect.sync(() => {
|
||||
@@ -104,6 +114,9 @@ function makeTestLayer(state: {
|
||||
Effect.sync(() => {
|
||||
state.localInvalidationCalls += 1;
|
||||
state.remoteInvalidationCalls += 1;
|
||||
if (state.fullInvalidationCalls !== undefined) {
|
||||
state.fullInvalidationCalls += 1;
|
||||
}
|
||||
}),
|
||||
}),
|
||||
),
|
||||
@@ -167,6 +180,84 @@ describe("VcsStatusBroadcaster", () => {
|
||||
}).pipe(Effect.provide(makeTestLayer(state)));
|
||||
});
|
||||
|
||||
it.effect("peeks without loading and polls without invalidating the PR cache", () => {
|
||||
const state = {
|
||||
currentLocalStatus: baseLocalStatus,
|
||||
currentRemoteStatus: baseRemoteStatus,
|
||||
localStatusCalls: 0,
|
||||
remoteStatusCalls: 0,
|
||||
localInvalidationCalls: 0,
|
||||
remoteInvalidationCalls: 0,
|
||||
fullInvalidationCalls: 0,
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
|
||||
|
||||
assert.equal(yield* broadcaster.peekStatus({ cwd: "/repo" }), null);
|
||||
assert.equal(state.localStatusCalls, 0);
|
||||
assert.equal(state.remoteStatusCalls, 0);
|
||||
|
||||
yield* broadcaster.getStatus({ cwd: "/repo" });
|
||||
assert.deepStrictEqual(yield* broadcaster.peekStatus({ cwd: "/repo" }), baseStatus);
|
||||
assert.equal(state.localStatusCalls, 1);
|
||||
assert.equal(state.remoteStatusCalls, 1);
|
||||
|
||||
state.currentRemoteStatus = { ...baseRemoteStatus, aheadCount: 2 };
|
||||
assert.deepStrictEqual(yield* broadcaster.pollStatus("/repo"), {
|
||||
...baseLocalStatus,
|
||||
...state.currentRemoteStatus,
|
||||
});
|
||||
assert.equal(state.localInvalidationCalls, 1);
|
||||
assert.equal(state.remoteInvalidationCalls, 1);
|
||||
assert.equal(state.fullInvalidationCalls, 0);
|
||||
}).pipe(Effect.provide(makeTestLayer(state)));
|
||||
});
|
||||
|
||||
it.effect("serializes full polling with explicit local refreshes", () =>
|
||||
Effect.gen(function* () {
|
||||
const pollReadStarted = yield* Deferred.make<void>();
|
||||
const releasePollRead = yield* Deferred.make<void>();
|
||||
const refreshedLocalStatus = {
|
||||
...baseLocalStatus,
|
||||
refName: "feature/refreshed-after-poll",
|
||||
};
|
||||
const state = {
|
||||
currentLocalStatus: baseLocalStatus,
|
||||
currentRemoteStatus: baseRemoteStatus,
|
||||
localStatusCalls: 0,
|
||||
remoteStatusCalls: 0,
|
||||
localInvalidationCalls: 0,
|
||||
remoteInvalidationCalls: 0,
|
||||
localStatusEffect: (call: number) =>
|
||||
call === 1
|
||||
? Deferred.succeed(pollReadStarted, undefined).pipe(
|
||||
Effect.andThen(Deferred.await(releasePollRead)),
|
||||
Effect.as(baseLocalStatus),
|
||||
)
|
||||
: Effect.succeed(refreshedLocalStatus),
|
||||
};
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
|
||||
const pollFiber = yield* broadcaster.pollStatus("/repo").pipe(Effect.forkChild);
|
||||
yield* Deferred.await(pollReadStarted);
|
||||
const refreshFiber = yield* broadcaster.refreshLocalStatus("/repo").pipe(Effect.forkChild);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
assert.equal(state.localStatusCalls, 1);
|
||||
yield* Deferred.succeed(releasePollRead, undefined);
|
||||
yield* Fiber.join(pollFiber);
|
||||
yield* Fiber.join(refreshFiber);
|
||||
|
||||
assert.deepStrictEqual(yield* broadcaster.peekStatus({ cwd: "/repo" }), {
|
||||
...refreshedLocalStatus,
|
||||
...baseRemoteStatus,
|
||||
});
|
||||
}).pipe(Effect.provide(makeTestLayer(state)));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("refreshes the cached snapshot after explicit invalidation", () => {
|
||||
const state = {
|
||||
currentLocalStatus: baseLocalStatus,
|
||||
|
||||
@@ -10,6 +10,7 @@ import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
import type {
|
||||
@@ -159,6 +160,10 @@ export class VcsStatusBroadcaster extends Context.Service<
|
||||
readonly getStatus: (
|
||||
input: VcsStatusInput,
|
||||
) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
|
||||
/** Read the merged cached status without touching git or a forge. */
|
||||
readonly peekStatus: (input: VcsStatusInput) => Effect.Effect<VcsStatusResult | null>;
|
||||
/** Refresh local and remote status while preserving the slower PR lookup cache. */
|
||||
readonly pollStatus: (cwd: string) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
|
||||
readonly refreshLocalStatus: (
|
||||
cwd: string,
|
||||
) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
|
||||
@@ -193,6 +198,22 @@ export const make = Effect.gen(function* () {
|
||||
);
|
||||
const cacheRef = yield* Ref.make(new Map<string, CachedVcsStatus>());
|
||||
const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
|
||||
const refreshLocksRef = yield* SynchronizedRef.make(new Map<string, Semaphore.Semaphore>());
|
||||
|
||||
const getRefreshLock = (cwd: string) =>
|
||||
SynchronizedRef.modifyEffect(refreshLocksRef, (current) => {
|
||||
const existing = current.get(cwd);
|
||||
if (existing !== undefined) return Effect.succeed([existing, current] as const);
|
||||
return Semaphore.make(1).pipe(
|
||||
Effect.map((lock) => [lock, new Map(current).set(cwd, lock)] as const),
|
||||
);
|
||||
});
|
||||
|
||||
const withRefreshLock = <A, E, R>(
|
||||
cwd: string,
|
||||
effect: Effect.Effect<A, E, R>,
|
||||
): Effect.Effect<A, E, R> =>
|
||||
Effect.flatMap(getRefreshLock(cwd), (lock) => lock.withPermits(1)(effect));
|
||||
|
||||
const getCachedStatus = Effect.fn("VcsStatusBroadcaster.getCachedStatus")(function* (
|
||||
cwd: string,
|
||||
@@ -329,14 +350,54 @@ export const make = Effect.gen(function* () {
|
||||
if (cached?.local && cached.remote) {
|
||||
return mergeGitStatusParts(cached.local.value, cached.remote.value);
|
||||
}
|
||||
const [local, remote] = yield* Effect.all(
|
||||
[
|
||||
cached?.local ? Effect.succeed(cached.local.value) : workflow.localStatus({ cwd }),
|
||||
cached?.remote ? Effect.succeed(cached.remote.value) : workflow.remoteStatus({ cwd }),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
return yield* withRefreshLock(
|
||||
cwd,
|
||||
Effect.gen(function* () {
|
||||
const latest = yield* getCachedStatus(cwd);
|
||||
if (latest?.local && latest.remote) {
|
||||
return mergeGitStatusParts(latest.local.value, latest.remote.value);
|
||||
}
|
||||
const [local, remote] = yield* Effect.all(
|
||||
[
|
||||
latest?.local ? Effect.succeed(latest.local.value) : workflow.localStatus({ cwd }),
|
||||
latest?.remote ? Effect.succeed(latest.remote.value) : workflow.remoteStatus({ cwd }),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
return yield* updateCachedStatus(cwd, local, remote);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const peekStatus: VcsStatusBroadcaster["Service"]["peekStatus"] = Effect.fn(
|
||||
"VcsStatusBroadcaster.peekStatus",
|
||||
)(function* (input) {
|
||||
const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
|
||||
const cached = yield* getCachedStatus(cwd);
|
||||
if (!cached?.local || !cached.remote) return null;
|
||||
return mergeGitStatusParts(cached.local.value, cached.remote.value);
|
||||
});
|
||||
|
||||
const pollStatus: VcsStatusBroadcaster["Service"]["pollStatus"] = Effect.fn(
|
||||
"VcsStatusBroadcaster.pollStatus",
|
||||
)(function* (rawCwd) {
|
||||
const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
|
||||
return yield* withRefreshLock(
|
||||
cwd,
|
||||
Effect.gen(function* () {
|
||||
// Automatic polling refreshes the one-second status caches but deliberately
|
||||
// leaves GitManager's slower PR cache and failure backoff intact.
|
||||
yield* Effect.all(
|
||||
[workflow.invalidateLocalStatus(cwd), workflow.invalidateRemoteStatus(cwd)],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
const [local, remote] = yield* Effect.all(
|
||||
[workflow.localStatus({ cwd }), workflow.remoteStatus({ cwd })],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
return yield* updateCachedStatus(cwd, local, remote, { publish: true });
|
||||
}),
|
||||
);
|
||||
return yield* updateCachedStatus(cwd, local, remote);
|
||||
});
|
||||
|
||||
const refreshLocalStatusCore = Effect.fn("VcsStatusBroadcaster.refreshLocalStatusCore")(
|
||||
@@ -351,32 +412,42 @@ export const make = Effect.gen(function* () {
|
||||
"VcsStatusBroadcaster.refreshLocalStatus",
|
||||
)(function* (rawCwd) {
|
||||
const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
|
||||
return yield* refreshLocalStatusCore(cwd);
|
||||
return yield* withRefreshLock(cwd, refreshLocalStatusCore(cwd));
|
||||
});
|
||||
|
||||
const refreshRemoteStatus = Effect.fn("VcsStatusBroadcaster.refreshRemoteStatus")(function* (
|
||||
cwd: string,
|
||||
options?: { readonly refreshUpstream?: boolean },
|
||||
) {
|
||||
if (options?.refreshUpstream !== false) {
|
||||
yield* workflow.invalidateRemoteStatus(cwd);
|
||||
}
|
||||
const remote = yield* workflow.remoteStatus({ cwd }, options);
|
||||
return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
|
||||
return yield* withRefreshLock(
|
||||
cwd,
|
||||
Effect.gen(function* () {
|
||||
if (options?.refreshUpstream !== false) {
|
||||
yield* workflow.invalidateRemoteStatus(cwd);
|
||||
}
|
||||
const remote = yield* workflow.remoteStatus({ cwd }, options);
|
||||
return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const refreshStatus: VcsStatusBroadcaster["Service"]["refreshStatus"] = Effect.fn(
|
||||
"VcsStatusBroadcaster.refreshStatus",
|
||||
)(function* (rawCwd) {
|
||||
const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
|
||||
// invalidateStatus (not the two partial invalidations) so an explicit
|
||||
// refresh also bypasses GitManager's slow PR-lookup cache.
|
||||
yield* workflow.invalidateStatus(cwd);
|
||||
const [local, remote] = yield* Effect.all(
|
||||
[workflow.localStatus({ cwd }), workflow.remoteStatus({ cwd })],
|
||||
{ concurrency: "unbounded" },
|
||||
return yield* withRefreshLock(
|
||||
cwd,
|
||||
Effect.gen(function* () {
|
||||
// invalidateStatus (not the two partial invalidations) so an explicit
|
||||
// refresh also bypasses GitManager's slow PR-lookup cache.
|
||||
yield* workflow.invalidateStatus(cwd);
|
||||
const [local, remote] = yield* Effect.all(
|
||||
[workflow.localStatus({ cwd }), workflow.remoteStatus({ cwd })],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
return yield* updateCachedStatus(cwd, local, remote, { publish: true });
|
||||
}),
|
||||
);
|
||||
return yield* updateCachedStatus(cwd, local, remote, { publish: true });
|
||||
});
|
||||
|
||||
const makeRemoteRefreshLoop = (
|
||||
@@ -587,6 +658,8 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
return VcsStatusBroadcaster.of({
|
||||
getStatus,
|
||||
peekStatus,
|
||||
pollStatus,
|
||||
refreshLocalStatus,
|
||||
refreshStatus,
|
||||
streamStatus,
|
||||
|
||||
@@ -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",
|
||||
|
||||
+72
-55
@@ -35,16 +35,16 @@
|
||||
// app colors before React mounts.
|
||||
const DEFAULT_THEME_PALETTES = {
|
||||
light: {
|
||||
background: "#fdf7fd",
|
||||
foreground: "#501854",
|
||||
accent: "#db2777",
|
||||
chrome: "#fdf7fd",
|
||||
background: "oklch(0.982446 0.010114 325.653)",
|
||||
foreground: "oklch(0.325698 0.116116 325.037)",
|
||||
accent: "oklch(0.591646 0.217985 0.584)",
|
||||
chrome: "oklch(0.982446 0.010114 325.653)",
|
||||
},
|
||||
dark: {
|
||||
background: "#1f1a24",
|
||||
foreground: "#f9f8fb",
|
||||
accent: "#a3004c",
|
||||
chrome: "#1f1a24",
|
||||
background: "oklch(0.22813 0.020366 307.469)",
|
||||
foreground: "oklch(0.980735 0.004092 301.426)",
|
||||
accent: "oklch(0.460685 0.185347 4.099)",
|
||||
chrome: "oklch(0.22813 0.020366 307.469)",
|
||||
},
|
||||
};
|
||||
// Keep this small boot-time copy in sync with the built-in palettes so
|
||||
@@ -52,72 +52,72 @@
|
||||
const BUILT_IN_THEME_PALETTES = {
|
||||
"t3-chat": {
|
||||
light: {
|
||||
background: "#fdf7fd",
|
||||
foreground: "#501854",
|
||||
accent: "#db2777",
|
||||
chrome: "#fdf7fd",
|
||||
background: "oklch(0.982446 0.010114 325.653)",
|
||||
foreground: "oklch(0.325698 0.116116 325.037)",
|
||||
accent: "oklch(0.591646 0.217985 0.584)",
|
||||
chrome: "oklch(0.982446 0.010114 325.653)",
|
||||
},
|
||||
dark: {
|
||||
background: "#1f1a24",
|
||||
foreground: "#f9f8fb",
|
||||
accent: "#a3004c",
|
||||
chrome: "#1f1a24",
|
||||
background: "oklch(0.22813 0.020366 307.469)",
|
||||
foreground: "oklch(0.980735 0.004092 301.426)",
|
||||
accent: "oklch(0.460685 0.185347 4.099)",
|
||||
chrome: "oklch(0.22813 0.020366 307.469)",
|
||||
},
|
||||
},
|
||||
grove: {
|
||||
light: {
|
||||
background: "#f3f7f4",
|
||||
foreground: "#241523",
|
||||
accent: "#1b7d50",
|
||||
chrome: "#f3f7f4",
|
||||
background: "oklch(0.972369 0.005497 157.15)",
|
||||
foreground: "oklch(0.222003 0.03479 328.979)",
|
||||
accent: "oklch(0.523295 0.112292 158.089)",
|
||||
chrome: "oklch(0.972369 0.005497 157.15)",
|
||||
},
|
||||
dark: {
|
||||
background: "#1b2821",
|
||||
foreground: "#fffaff",
|
||||
accent: "#69d69a",
|
||||
chrome: "#1b2821",
|
||||
background: "oklch(0.260865 0.02152 162.75)",
|
||||
foreground: "oklch(0.990339 0.008411 325.64)",
|
||||
accent: "oklch(0.796228 0.133058 157.319)",
|
||||
chrome: "oklch(0.260865 0.02152 162.75)",
|
||||
},
|
||||
},
|
||||
ocean: {
|
||||
light: {
|
||||
background: "#f5f7f8",
|
||||
foreground: "#241523",
|
||||
accent: "#2672af",
|
||||
chrome: "#f5f7f8",
|
||||
background: "oklch(0.974199 0.002856 241.597)",
|
||||
foreground: "oklch(0.222003 0.03479 328.979)",
|
||||
accent: "oklch(0.536684 0.120219 247.01)",
|
||||
chrome: "oklch(0.974199 0.002856 241.597)",
|
||||
},
|
||||
dark: {
|
||||
background: "#17212b",
|
||||
foreground: "#fffaff",
|
||||
accent: "#70b9ee",
|
||||
chrome: "#17212b",
|
||||
background: "oklch(0.242641 0.024125 250.573)",
|
||||
foreground: "oklch(0.990339 0.008411 325.64)",
|
||||
accent: "oklch(0.758933 0.105833 241.548)",
|
||||
chrome: "oklch(0.242641 0.024125 250.573)",
|
||||
},
|
||||
},
|
||||
ember: {
|
||||
light: {
|
||||
background: "#f9f7f5",
|
||||
foreground: "#241523",
|
||||
accent: "#ae552a",
|
||||
chrome: "#f9f7f5",
|
||||
background: "oklch(0.976527 0.002685 60.725)",
|
||||
foreground: "oklch(0.222003 0.03479 328.979)",
|
||||
accent: "oklch(0.552831 0.129438 44.656)",
|
||||
chrome: "oklch(0.976527 0.002685 60.725)",
|
||||
},
|
||||
dark: {
|
||||
background: "#291e1a",
|
||||
foreground: "#fffaff",
|
||||
accent: "#f09a64",
|
||||
chrome: "#291e1a",
|
||||
background: "oklch(0.245899 0.019144 42.044)",
|
||||
foreground: "oklch(0.990339 0.008411 325.64)",
|
||||
accent: "oklch(0.762174 0.124117 52.082)",
|
||||
chrome: "oklch(0.245899 0.019144 42.044)",
|
||||
},
|
||||
},
|
||||
iris: {
|
||||
light: {
|
||||
background: "#f8f7f9",
|
||||
foreground: "#241523",
|
||||
accent: "#7253b9",
|
||||
chrome: "#f8f7f9",
|
||||
background: "oklch(0.976531 0.003855 303.226)",
|
||||
foreground: "oklch(0.222003 0.03479 328.979)",
|
||||
accent: "oklch(0.525348 0.15373 294.176)",
|
||||
chrome: "oklch(0.976531 0.003855 303.226)",
|
||||
},
|
||||
dark: {
|
||||
background: "#1d1929",
|
||||
foreground: "#fffaff",
|
||||
accent: "#9d7df2",
|
||||
chrome: "#1d1929",
|
||||
background: "oklch(0.225975 0.031062 293.741)",
|
||||
foreground: "oklch(0.990339 0.008411 325.64)",
|
||||
accent: "oklch(0.671712 0.169136 293.929)",
|
||||
chrome: "oklch(0.225975 0.031062 293.741)",
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -152,9 +152,26 @@
|
||||
}
|
||||
};
|
||||
|
||||
const isHexColor = (value) =>
|
||||
typeof value === "string" &&
|
||||
/^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(value);
|
||||
// The runtime decodes the same literal CSS formats into OKLCH. Keep
|
||||
// contextual colors out: they cannot be resolved from stored data.
|
||||
const SYSTEM_COLOR_KEYWORD =
|
||||
/^(?:accentcolor(?:text)?|active(?:border|caption|text)|appworkspace|background|button(?:border|face|highlight|shadow|text)|canvas(?:text)?|captiontext|field(?:text)?|graytext|highlight(?:text)?|inactive(?:border|caption(?:text)?)|info(?:background|text)|linktext|mark(?:text)?|menu(?:text)?|scrollbar|selecteditem(?:text)?|threed(?:darkshadow|face|highlight|lightshadow|shadow)|visitedtext|window(?:frame|text)?)$/i;
|
||||
const isThemeColor = (value) => {
|
||||
if (typeof value !== "string" || typeof CSS === "undefined") return false;
|
||||
const color = value.trim();
|
||||
if (
|
||||
/^(?:currentcolor|inherit|initial|revert|revert-layer|unset)$/i.test(color) ||
|
||||
SYSTEM_COLOR_KEYWORD.test(color) ||
|
||||
/\bfrom\b|(?:var|env|attr|calc|min|max|clamp)\(/i.test(color)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const isLiteralColor =
|
||||
/^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(color) ||
|
||||
/^[a-z]+$/i.test(color) ||
|
||||
/^(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)\(/i.test(color);
|
||||
return isLiteralColor && CSS.supports("color", color);
|
||||
};
|
||||
const isRecord = (value) =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
const isThemeId = (value) =>
|
||||
@@ -322,13 +339,13 @@
|
||||
const fallbackSplash = isDark ? SPLASH_COLORS.dark : SPLASH_COLORS.light;
|
||||
const customSplash = customColors
|
||||
? {
|
||||
background: isHexColor(customColors.canvas)
|
||||
background: isThemeColor(customColors.canvas)
|
||||
? customColors.canvas
|
||||
: (customDefaults?.background ?? fallbackSplash.background),
|
||||
foreground: isHexColor(customColors.text)
|
||||
foreground: isThemeColor(customColors.text)
|
||||
? customColors.text
|
||||
: (customDefaults?.foreground ?? fallbackSplash.foreground),
|
||||
accent: isHexColor(customColors.accent)
|
||||
accent: isThemeColor(customColors.accent)
|
||||
? customColors.accent
|
||||
: (customDefaults?.accent ?? fallbackSplash.accent),
|
||||
}
|
||||
@@ -350,7 +367,7 @@
|
||||
}
|
||||
document.documentElement.classList.toggle("dark", isDark);
|
||||
const chromeColor = customColors
|
||||
? isHexColor(customColors.chrome)
|
||||
? isThemeColor(customColors.chrome)
|
||||
? customColors.chrome
|
||||
: (customDefaults?.chrome ?? fallbackSplash.background)
|
||||
: builtInSplash
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
"@formkit/auto-animate": "^0.9.0",
|
||||
"@legendapp/list": "catalog:",
|
||||
"@lexical/react": "^0.41.0",
|
||||
"@noble/hashes": "catalog:",
|
||||
"@pierre/diffs": "catalog:",
|
||||
"@pierre/trees": "1.0.0-beta.4",
|
||||
"@t3tools/client-runtime": "workspace:*",
|
||||
@@ -31,8 +32,11 @@
|
||||
"@tanstack/react-pacer": "^0.19.4",
|
||||
"@tanstack/react-router": "^1.160.2",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"culori": "^4.0.2",
|
||||
"effect": "catalog:",
|
||||
"jose": "catalog:",
|
||||
"jsonc-parser": "3.3.1",
|
||||
"jszip": "3.10.1",
|
||||
"lexical": "^0.41.0",
|
||||
"lucide-react": "^0.564.0",
|
||||
"react": "19.2.6",
|
||||
@@ -53,6 +57,7 @@
|
||||
"@tanstack/router-plugin": "^1.161.0",
|
||||
"@types/babel__core": "^7.20.5",
|
||||
"@types/compression": "^1.8.1",
|
||||
"@types/culori": "^4.0.1",
|
||||
"@types/react": "~19.2.14",
|
||||
"@types/react-dom": "~19.2.3",
|
||||
"@vercel/config": "^0.3.0",
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
type PreviewViewportSetting,
|
||||
} from "@t3tools/contracts";
|
||||
import { PREVIEW_VIEWPORT_PRESETS, resolvePreviewViewport } from "@t3tools/shared/previewViewport";
|
||||
import { Link2, X } from "lucide-react";
|
||||
import { Link2, Unlink2, X } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
|
||||
import { Button } from "~/components/ui/button";
|
||||
@@ -310,7 +310,11 @@ export function BrowserDeviceToolbar({
|
||||
onPointerDown={(event) => event.preventDefault()}
|
||||
onClick={toggleAspectRatio}
|
||||
>
|
||||
<Link2 className={cn(aspectRatio !== null && "text-foreground")} />
|
||||
{aspectRatio === null ? (
|
||||
<Unlink2 className={cn(aspectRatio !== null && "text-foreground")} />
|
||||
) : (
|
||||
<Link2 className={cn(aspectRatio !== null && "text-foreground")} />
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,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";
|
||||
@@ -19,7 +19,10 @@ import LegacyThreadSidebar from "./LegacySidebar";
|
||||
import ThreadSidebar from "./Sidebar";
|
||||
import { SettingsSidebarNav } from "./settings/SettingsSidebarNav";
|
||||
import { SidebarChromeHeader } from "./sidebar/SidebarChrome";
|
||||
import { useSidebarStageBackdropVariant } from "./SidebarStageBackdrop";
|
||||
import {
|
||||
resolveSidebarStageFocusRingOffsetClass,
|
||||
useSidebarStageBackdropVariant,
|
||||
} from "./SidebarStageBackdrop";
|
||||
import { useProjects } from "../state/entities";
|
||||
import {
|
||||
resolveInitialThreadSidebarWidth,
|
||||
@@ -105,7 +108,10 @@ function SidebarControl() {
|
||||
"pointer-events-auto",
|
||||
isSidebarVisible &&
|
||||
stageBackdropVariant &&
|
||||
"[:hover,[data-pressed]]:bg-white/15 focus-visible:ring-white/90 focus-visible:ring-offset-blue-700 [&_svg]:stroke-white/90! [&_svg]:opacity-100! [&_svg]:hover:stroke-white!",
|
||||
"focus-visible:ring-white/90 [&_svg]:stroke-white/90! [&_svg]:opacity-100! [&_svg]:hover:stroke-white! [:hover,[data-pressed]]:bg-white/15",
|
||||
isSidebarVisible &&
|
||||
stageBackdropVariant &&
|
||||
resolveSidebarStageFocusRingOffsetClass(stageBackdropVariant),
|
||||
)}
|
||||
aria-label="Toggle main sidebar"
|
||||
/>
|
||||
@@ -141,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"
|
||||
@@ -219,7 +233,7 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
|
||||
) : (
|
||||
<ThreadSidebar />
|
||||
)}
|
||||
<SidebarRail />
|
||||
<SidebarRail onDoubleClick={resetSidebarWidth} />
|
||||
</Sidebar>
|
||||
{children}
|
||||
<SidebarControl />
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
HistoryIcon,
|
||||
MonitorIcon,
|
||||
} from "lucide-react";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
|
||||
import { useProject, useThread, useThreadShellsForProjectRefs } from "../state/entities";
|
||||
@@ -218,16 +218,20 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
|
||||
/**
|
||||
* Collapse the strip's labels to icons only when the text no longer fits.
|
||||
*
|
||||
* Hidden labels stay measurable (they collapse to invisible absolute boxes,
|
||||
* which keep their natural width), so the required width can be recomputed in
|
||||
* either state on every pass - no remembered widths that could go stale or
|
||||
* latch the strip compact. A small hysteresis keeps the boundary from
|
||||
* flapping between states.
|
||||
* Hidden labels stay measurable because their inner text keeps its natural
|
||||
* width while the outer layout box collapses. This lets every pass recompute
|
||||
* the expanded width without remembered values that could go stale or latch
|
||||
* the strip compact. A small hysteresis keeps the boundary from flapping.
|
||||
*/
|
||||
const COMPACT_EXPAND_HYSTERESIS_PX = 16;
|
||||
const COMPOSER_CONTEXT_MOTION_DURATION_MS = 180;
|
||||
const COMPOSER_CONTEXT_MOTION_EASING = "cubic-bezier(0.32, 0.72, 0, 1)";
|
||||
const COMPOSER_CONTEXT_CONTROL_SELECTOR = "[data-composer-context-control]";
|
||||
|
||||
function useLabelsOverflow(element: HTMLDivElement | null): boolean {
|
||||
const [overflows, setOverflows] = useState(false);
|
||||
const pendingControlRectsRef = useRef<Map<HTMLElement, DOMRect> | null>(null);
|
||||
const controlAnimationsRef = useRef(new Map<HTMLElement, Animation>());
|
||||
// A render-synced mirror instead of useEffectEvent: the compiler memoizes
|
||||
// the event callback, which left observers reading the first render's null
|
||||
// element forever.
|
||||
@@ -241,7 +245,7 @@ function useLabelsOverflow(element: HTMLDivElement | null): boolean {
|
||||
if (available === 0) return;
|
||||
// flex-1 stretches the groups to fill the strip, so their own boxes always
|
||||
// measure "full". Sum the laid-out content instead, skipping hidden form
|
||||
// artifacts and absolutely-positioned nodes (the compact-hidden labels).
|
||||
// artifacts and other out-of-flow nodes.
|
||||
const contentWidth = (parent: Element): number => {
|
||||
const gap = Number.parseFloat(getComputedStyle(parent).columnGap) || 0;
|
||||
let width = 0;
|
||||
@@ -283,9 +287,71 @@ function useLabelsOverflow(element: HTMLDivElement | null): boolean {
|
||||
needed += Math.max(0, textWidth - label.clientWidth);
|
||||
}
|
||||
}
|
||||
setOverflows(compact ? needed > available - COMPACT_EXPAND_HYSTERESIS_PX : needed > available);
|
||||
const nextOverflows = compact
|
||||
? needed > available - COMPACT_EXPAND_HYSTERESIS_PX
|
||||
: needed > available;
|
||||
if (nextOverflows !== compact) {
|
||||
pendingControlRectsRef.current = new Map(
|
||||
Array.from(current.querySelectorAll<HTMLElement>(COMPOSER_CONTEXT_CONTROL_SELECTOR)).map(
|
||||
(control) => [control, control.getBoundingClientRect()],
|
||||
),
|
||||
);
|
||||
}
|
||||
setOverflows(nextOverflows);
|
||||
}, []);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const previousRects = pendingControlRectsRef.current;
|
||||
if (!previousRects) return;
|
||||
pendingControlRectsRef.current = null;
|
||||
|
||||
for (const animation of controlAnimationsRef.current.values()) {
|
||||
animation.cancel();
|
||||
}
|
||||
controlAnimationsRef.current.clear();
|
||||
|
||||
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
|
||||
|
||||
for (const [control, previousRect] of previousRects) {
|
||||
if (!control.isConnected) continue;
|
||||
const nextRect = control.getBoundingClientRect();
|
||||
const deltaX = previousRect.left - nextRect.left;
|
||||
const deltaY = previousRect.top - nextRect.top;
|
||||
if (Math.abs(deltaX) < 0.5 && Math.abs(deltaY) < 0.5) continue;
|
||||
|
||||
const animation = control.animate(
|
||||
[
|
||||
{ transform: `translate3d(${deltaX}px, ${deltaY}px, 0)` },
|
||||
{ transform: "translate3d(0, 0, 0)" },
|
||||
],
|
||||
{
|
||||
duration: COMPOSER_CONTEXT_MOTION_DURATION_MS,
|
||||
easing: COMPOSER_CONTEXT_MOTION_EASING,
|
||||
fill: "backwards",
|
||||
},
|
||||
);
|
||||
controlAnimationsRef.current.set(control, animation);
|
||||
animation.addEventListener(
|
||||
"finish",
|
||||
() => {
|
||||
if (controlAnimationsRef.current.get(control) === animation) {
|
||||
controlAnimationsRef.current.delete(control);
|
||||
}
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
}
|
||||
}, [overflows]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
for (const animation of controlAnimationsRef.current.values()) {
|
||||
animation.cancel();
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
// Label widths can change without the strip box moving (font family or
|
||||
// size preferences), so re-measure on every render as well as on resize
|
||||
// and font loads.
|
||||
@@ -403,7 +469,7 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
<div
|
||||
ref={setStripElement}
|
||||
data-compact={labelsOverflow ? "" : undefined}
|
||||
className="chat-composer-context-strip group/composer-context -mt-4 mx-auto flex w-[calc(100%-2.75rem)] max-w-[calc(48rem-2.75rem)] items-center gap-2 ps-1 pe-2 pt-5 pb-1"
|
||||
className="chat-composer-context-strip group/composer-context -mt-4 mx-auto flex w-[calc(100%-2.75rem)] max-w-[calc(48rem-2.75rem)] items-center gap-2 overflow-x-clip overflow-y-visible ps-1 pe-2 pt-5 pb-1"
|
||||
>
|
||||
{isMobile && showGitControls ? (
|
||||
<MobileRunContextSelector
|
||||
@@ -431,7 +497,11 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
{...(showEnvironmentPicker && onEnvironmentChange ? { onEnvironmentChange } : {})}
|
||||
/>
|
||||
{showGitControls ? (
|
||||
<Separator orientation="vertical" className="mx-0.5 h-3.5!" />
|
||||
<Separator
|
||||
orientation="vertical"
|
||||
className="mx-0.5 h-3.5!"
|
||||
data-composer-context-control
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -714,7 +714,10 @@ export function BranchToolbarBranchSelector({
|
||||
open={isBranchMenuOpen}
|
||||
value={resolvedActiveBranch}
|
||||
>
|
||||
<div className={cn("flex min-w-0 items-center gap-1", className)}>
|
||||
<div
|
||||
className={cn("flex min-w-0 items-center gap-1", className)}
|
||||
data-composer-context-control
|
||||
>
|
||||
{branchPr && branchPrStatus ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
@@ -751,9 +754,14 @@ export function BranchToolbarBranchSelector({
|
||||
<GitBranchIcon className="size-3 shrink-0 opacity-70" />
|
||||
<span
|
||||
data-composer-label
|
||||
className="min-w-0 max-w-[240px] truncate transition-[max-width,opacity] duration-300 ease-out group-data-[compact]/composer-context:max-w-0 group-data-[compact]/composer-context:opacity-0"
|
||||
className="min-w-0 max-w-[240px] group-data-[compact]/composer-context:max-w-0"
|
||||
>
|
||||
{triggerLabel}
|
||||
<span
|
||||
data-composer-label-motion
|
||||
className="block w-full min-w-0 max-w-[240px] origin-left truncate transition-[opacity,transform] duration-180 ease-[cubic-bezier(0.32,0.72,0,1)] group-data-[compact]/composer-context:[transform:translateX(-0.25rem)_scaleX(0.95)] group-data-[compact]/composer-context:opacity-0 motion-reduce:transform-none motion-reduce:transition-opacity"
|
||||
>
|
||||
{triggerLabel}
|
||||
</span>
|
||||
</span>
|
||||
<ChevronDownIcon className="size-3 shrink-0 opacity-50" />
|
||||
</ComboboxTrigger>
|
||||
|
||||
@@ -50,7 +50,10 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
|
||||
|
||||
if (envLocked) {
|
||||
return (
|
||||
<span className="inline-flex h-7 shrink-0 items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:h-6 sm:text-xs">
|
||||
<span
|
||||
className="inline-flex h-7 shrink-0 items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:h-6 sm:text-xs"
|
||||
data-composer-context-control
|
||||
>
|
||||
{activeWorktreePath ? (
|
||||
<>
|
||||
<FolderGitIcon className="size-3" />
|
||||
@@ -84,6 +87,7 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
|
||||
size="xs"
|
||||
className="min-w-0 shrink font-medium"
|
||||
aria-label="Workspace"
|
||||
data-composer-context-control
|
||||
>
|
||||
{effectiveEnvMode === "worktree" ? (
|
||||
<FolderGit2Icon className="size-3" />
|
||||
@@ -94,9 +98,14 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
|
||||
)}
|
||||
<span
|
||||
data-composer-label
|
||||
className="min-w-0 max-w-[240px] truncate transition-[max-width,opacity] duration-300 ease-out group-data-[compact]/composer-context:max-w-0 group-data-[compact]/composer-context:opacity-0"
|
||||
className="min-w-0 max-w-[240px] group-data-[compact]/composer-context:max-w-0"
|
||||
>
|
||||
<SelectValue />
|
||||
<span
|
||||
data-composer-label-motion
|
||||
className="block w-full min-w-0 max-w-[240px] origin-left truncate transition-[opacity,transform] duration-180 ease-[cubic-bezier(0.32,0.72,0,1)] group-data-[compact]/composer-context:[transform:translateX(-0.25rem)_scaleX(0.95)] group-data-[compact]/composer-context:opacity-0 motion-reduce:transform-none motion-reduce:transition-opacity"
|
||||
>
|
||||
<SelectValue />
|
||||
</span>
|
||||
</span>
|
||||
</SelectTrigger>
|
||||
<SelectPopup>
|
||||
|
||||
@@ -48,7 +48,10 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
|
||||
// only thing in the strip.
|
||||
if (envLocked || onEnvironmentChange === undefined) {
|
||||
return (
|
||||
<span className="inline-flex h-7 min-w-0 max-w-full items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:h-6 sm:text-xs">
|
||||
<span
|
||||
className="inline-flex h-7 min-w-0 max-w-full items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:h-6 sm:text-xs"
|
||||
data-composer-context-control
|
||||
>
|
||||
{activeEnvironment?.isPrimary ? (
|
||||
<MonitorIcon className="size-3 shrink-0" />
|
||||
) : (
|
||||
@@ -56,9 +59,14 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
|
||||
)}
|
||||
<span
|
||||
data-composer-label
|
||||
className="min-w-0 max-w-[240px] truncate transition-[max-width,opacity] duration-300 ease-out group-data-[compact]/composer-context:max-w-0 group-data-[compact]/composer-context:opacity-0"
|
||||
className="min-w-0 max-w-[240px] group-data-[compact]/composer-context:max-w-0"
|
||||
>
|
||||
{activeEnvironment?.label ?? "Run on"}
|
||||
<span
|
||||
data-composer-label-motion
|
||||
className="block w-full min-w-0 max-w-[240px] origin-left truncate transition-[opacity,transform] duration-180 ease-[cubic-bezier(0.32,0.72,0,1)] group-data-[compact]/composer-context:[transform:translateX(-0.25rem)_scaleX(0.95)] group-data-[compact]/composer-context:opacity-0 motion-reduce:transform-none motion-reduce:transition-opacity"
|
||||
>
|
||||
{activeEnvironment?.label ?? "Run on"}
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
@@ -76,6 +84,7 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
|
||||
size="xs"
|
||||
className="min-w-0 max-w-full font-medium"
|
||||
aria-label="Run on"
|
||||
data-composer-context-control
|
||||
>
|
||||
{activeEnvironment?.isPrimary ? (
|
||||
<MonitorIcon className="size-3 shrink-0" />
|
||||
@@ -84,9 +93,14 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
|
||||
)}
|
||||
<span
|
||||
data-composer-label
|
||||
className="min-w-0 max-w-[240px] truncate transition-[max-width,opacity] duration-300 ease-out group-data-[compact]/composer-context:max-w-0 group-data-[compact]/composer-context:opacity-0"
|
||||
className="min-w-0 max-w-[240px] group-data-[compact]/composer-context:max-w-0"
|
||||
>
|
||||
<SelectValue />
|
||||
<span
|
||||
data-composer-label-motion
|
||||
className="block w-full min-w-0 max-w-[240px] origin-left truncate transition-[opacity,transform] duration-180 ease-[cubic-bezier(0.32,0.72,0,1)] group-data-[compact]/composer-context:[transform:translateX(-0.25rem)_scaleX(0.95)] group-data-[compact]/composer-context:opacity-0 motion-reduce:transform-none motion-reduce:transition-opacity"
|
||||
>
|
||||
<SelectValue />
|
||||
</span>
|
||||
</span>
|
||||
</SelectTrigger>
|
||||
<SelectPopup>
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -26,11 +26,7 @@ import {
|
||||
connectionStatusTitle,
|
||||
type EnvironmentConnectionPresentation,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import {
|
||||
effectiveSettled,
|
||||
effectiveSnoozed,
|
||||
threadWokeAt,
|
||||
} from "@t3tools/client-runtime/state/thread-settled";
|
||||
import { effectiveSnoozed, threadWokeAt } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import {
|
||||
parseScopedThreadKey,
|
||||
scopedThreadKey,
|
||||
@@ -123,11 +119,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 +140,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";
|
||||
@@ -184,7 +181,6 @@ import {
|
||||
useClientSettingsHydrated,
|
||||
useEnvironmentSettings,
|
||||
} from "../hooks/useSettings";
|
||||
import { useNowMinute } from "../hooks/useNowMinute";
|
||||
import { useNewThreadHandler } from "../hooks/useHandleNewThread";
|
||||
import { resolveAppModelSelectionForInstance } from "../modelSelection";
|
||||
import { getTerminalFocusOwner } from "../lib/terminalFocus";
|
||||
@@ -264,7 +260,13 @@ import {
|
||||
ProviderStatusBanner,
|
||||
shouldShowProviderStatusBanner,
|
||||
} from "./chat/ProviderStatusBanner";
|
||||
import { ThreadErrorBanner } from "./chat/ThreadErrorBanner";
|
||||
import {
|
||||
dismissThreadErrorBannerForSession,
|
||||
getThreadErrorBannerKey,
|
||||
isThreadErrorBannerDismissedForSession,
|
||||
shouldShowThreadErrorBanner,
|
||||
ThreadErrorBanner,
|
||||
} from "./chat/ThreadErrorBanner";
|
||||
import { resolveThreadPr } from "./ThreadStatusIndicators";
|
||||
import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack";
|
||||
import { ThreadSyncStatusPill } from "./chat/ThreadSyncStatusPill";
|
||||
@@ -474,6 +476,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;
|
||||
}
|
||||
|
||||
@@ -1493,6 +1503,24 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
const threadError = isServerThread
|
||||
? (localServerError ?? activeServerThread?.session?.lastError ?? null)
|
||||
: localDraftError;
|
||||
// Dismissals can only mask the shown error, never clear it: a server thread
|
||||
// keeps its error in session.lastError, so clearing the local shadow would
|
||||
// just fall through to the persisted one. Mask the current error until a
|
||||
// different error arrives, mirroring the provider status banner.
|
||||
const threadErrorBannerKey = getThreadErrorBannerKey(routeThreadKey, threadError);
|
||||
const visibleThreadError = shouldShowThreadErrorBanner(
|
||||
routeThreadKey,
|
||||
threadError,
|
||||
isThreadErrorBannerDismissedForSession(threadErrorBannerKey),
|
||||
)
|
||||
? threadError
|
||||
: null;
|
||||
// Dismissing only mutates the session-scoped mask set, which does not
|
||||
// trigger a render on its own; setThreadError(null) can also bail when the
|
||||
// local shadow is already empty and the banner is driven purely by
|
||||
// session.lastError. Bump a tick so the banner hides immediately. Mirrors
|
||||
// the branch mismatch banner.
|
||||
const [, setThreadErrorBannerDismissTick] = useState(0);
|
||||
const runtimeMode = composerRuntimeMode ?? activeThread?.runtimeMode ?? DEFAULT_RUNTIME_MODE;
|
||||
// Plan mode is legacy (Settings → Beta). With the flag off the effective
|
||||
// mode is forced to "default" — even for threads with a stored plan mode —
|
||||
@@ -1568,14 +1596,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);
|
||||
@@ -2618,7 +2650,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
)
|
||||
? activeProviderStatus
|
||||
: null;
|
||||
const hasTimelineTopBanner = Boolean(threadError) || visibleProviderStatus !== null;
|
||||
const hasTimelineTopBanner = Boolean(visibleThreadError) || visibleProviderStatus !== null;
|
||||
const activeProjectCwd = activeProject?.workspaceRoot ?? null;
|
||||
const activeThreadWorktreePath = activeThread?.worktreePath ?? null;
|
||||
const activeWorkspaceRoot = activeThreadWorktreePath ?? activeProjectCwd ?? undefined;
|
||||
@@ -4059,11 +4091,9 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
: null,
|
||||
[activeThreadBranch, activeWorktreePath, envMode, gitStatusQuery.data?.refName, isServerThread],
|
||||
);
|
||||
// Settled state of the open thread, resolved exactly like the sidebar
|
||||
// partition (same shell, same capability gate, same PR auto-settle input)
|
||||
// so the banner and the sidebar row never disagree.
|
||||
// Settlement is projected server state. The open-thread banner and every
|
||||
// navigation surface read the same persisted timestamp.
|
||||
const activeThreadShell = useThreadShell(isServerThread ? activeThreadRef : null);
|
||||
const autoSettleAfterDays = useClientSettings((settings) => settings.sidebarAutoSettleAfterDays);
|
||||
const activeThreadPr = resolveThreadPr({
|
||||
threadBranch: activeThread?.branch ?? null,
|
||||
gitStatus: gitStatusQuery.data ?? null,
|
||||
@@ -4078,7 +4108,6 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
supportsPullRequests && activeThreadPr !== null && threadRepository !== null;
|
||||
const supportsSettlement = serverConfig?.environment.capabilities.threadSettlement === true;
|
||||
const supportsSnooze = serverConfig?.environment.capabilities.threadSnooze === true;
|
||||
const nowMinute = useNowMinute();
|
||||
const snoozeNow = new Date().toISOString();
|
||||
const activeThreadSnoozed =
|
||||
activeThreadShell !== null &&
|
||||
@@ -4104,15 +4133,14 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
if (activeThreadRef === null || activeThreadWokeAt === null) return;
|
||||
markThreadVisited(scopedThreadKey(activeThreadRef), activeThreadWokeAt);
|
||||
}, [activeThreadRef, activeThreadWokeAt, markThreadVisited]);
|
||||
// Mirror of the sidebar's Woke pill for the open thread: same visit
|
||||
// comparison, same merged/closed-PR suppression (finished work needs no
|
||||
// wake-up call). Drives the dismissible composer banner below.
|
||||
// Mirror of the sidebar's Woke pill for the open thread. It uses the same
|
||||
// visit comparison and change request settle rule.
|
||||
const activeThreadLastVisitedAt = useUiStateStore((store) =>
|
||||
activeThreadKey === null ? undefined : store.threadLastVisitedAtById[activeThreadKey],
|
||||
);
|
||||
const activeThreadWokeVisible = useMemo(() => {
|
||||
if (activeThreadWokeAt === null) return false;
|
||||
if (activeThreadPr?.state === "merged" || activeThreadPr?.state === "closed") return false;
|
||||
if (activeThreadShell?.settledAt != null) return false;
|
||||
const wokeAtMs = Date.parse(activeThreadWokeAt);
|
||||
if (Number.isNaN(wokeAtMs)) return false;
|
||||
// Having the thread open counts as a visit at completedAt (the effect
|
||||
@@ -4132,23 +4160,11 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}, [
|
||||
activeLatestTurn?.completedAt,
|
||||
activeThreadLastVisitedAt,
|
||||
activeThreadPr?.state,
|
||||
activeThreadShell?.settledAt,
|
||||
activeThreadWokeAt,
|
||||
]);
|
||||
const activeThreadSettled = useMemo(() => {
|
||||
if (activeThreadShell === null || !supportsSettlement) return false;
|
||||
return effectiveSettled(activeThreadShell, {
|
||||
now: `${nowMinute}:00.000Z`,
|
||||
autoSettleAfterDays,
|
||||
changeRequestState: activeThreadPr?.state ?? null,
|
||||
});
|
||||
}, [
|
||||
activeThreadPr?.state,
|
||||
activeThreadShell,
|
||||
autoSettleAfterDays,
|
||||
nowMinute,
|
||||
supportsSettlement,
|
||||
]);
|
||||
const activeThreadSettled =
|
||||
activeThreadShell !== null && supportsSettlement && activeThreadShell.settledAt !== null;
|
||||
const unsettleThreadMutation = useAtomCommand(threadEnvironment.unsettle, {
|
||||
reportFailure: false,
|
||||
});
|
||||
@@ -6050,11 +6066,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" ? (
|
||||
@@ -6124,7 +6152,6 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
{...(routeKind === "draft" && draftId ? { draftId } : {})}
|
||||
activeThreadTitle={activeThread.title}
|
||||
isServerThread={isServerThread}
|
||||
changeRequestState={activeThreadPr?.state ?? null}
|
||||
activeProjectName={activeProject?.title}
|
||||
activeProjectCwd={activeProject?.workspaceRoot ?? null}
|
||||
activeProjectFaviconPath={activeProject?.faviconPath ?? null}
|
||||
@@ -6146,8 +6173,12 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
</header>
|
||||
|
||||
<ThreadErrorBanner
|
||||
error={threadError}
|
||||
onDismiss={() => setThreadError(activeThread.id, null)}
|
||||
error={visibleThreadError}
|
||||
onDismiss={() => {
|
||||
setThreadError(activeThread.id, null);
|
||||
dismissThreadErrorBannerForSession(threadErrorBannerKey);
|
||||
setThreadErrorBannerDismissTick((tick) => tick + 1);
|
||||
}}
|
||||
/>
|
||||
{/* Main content area with optional plan sidebar */}
|
||||
<div className="flex min-h-0 min-w-0 flex-1">
|
||||
|
||||
Loaded 100 of 246 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user