diff --git a/apps/mobile/src/components/ui/Dialog.android.test.tsx b/apps/mobile/src/components/ui/Dialog.android.test.tsx index d283cf004c23a..71af1e0c08fe4 100644 --- a/apps/mobile/src/components/ui/Dialog.android.test.tsx +++ b/apps/mobile/src/components/ui/Dialog.android.test.tsx @@ -102,3 +102,61 @@ it("ignores a late action from a dialog that a newer one replaced", () => { expect(olderAction).toHaveBeenCalledOnce(); expect(container.textContent).toContain("Newer"); }); + +it("cancels a confirm that a newer dialog replaced", async () => { + mountHost(); + const onCancel = vi.fn(); + const onConfirm = vi.fn(); + act(() => + Dialog.confirm({ + title: "Close open pull requests?", + confirmText: "Close & Settle", + cancelText: "Settle", + onConfirm, + onCancel, + }), + ); + act(() => Dialog.alert("Newer", undefined, [{ text: "OK" }])); + + await act(async () => { + await Promise.resolve(); + }); + + expect(onCancel).toHaveBeenCalledOnce(); + expect(onConfirm).not.toHaveBeenCalled(); +}); + +it("ignores stale confirm and cancel before and after replacement cancellation", async () => { + mountHost(); + const onCancel = vi.fn(); + const onConfirm = vi.fn(); + act(() => + Dialog.confirm({ + title: "Remove project", + confirmText: "Remove project", + cancelText: "Cancel", + onConfirm, + onCancel, + }), + ); + const staleCancel = renderedClicks.at(-2)!; + const staleConfirm = renderedClicks.at(-1)!; + + act(() => Dialog.alert("Newer", undefined, [{ text: "OK" }])); + act(() => { + staleConfirm(); + staleCancel(); + }); + + await act(async () => { + await Promise.resolve(); + }); + + act(() => { + staleConfirm(); + staleCancel(); + }); + + expect(onCancel).toHaveBeenCalledOnce(); + expect(onConfirm).not.toHaveBeenCalled(); +}); diff --git a/apps/mobile/src/components/ui/Dialog.android.tsx b/apps/mobile/src/components/ui/Dialog.android.tsx index 89871fd99a8ab..dcebb0a6cd2b1 100644 --- a/apps/mobile/src/components/ui/Dialog.android.tsx +++ b/apps/mobile/src/components/ui/Dialog.android.tsx @@ -35,12 +35,14 @@ type DialogRequest = | { readonly kind: "text-input"; readonly request: TextInputDialogRequest }; type PresentedDialog = DialogRequest & { readonly id: number }; +type PresentationStatus = "active" | "replaced" | "completed"; // App services raise dialogs before the root mounts, so the request lives in // the module and the Host renders whatever is current. One dialog shows at a // time: a new request replaces the presented one. let presented: PresentedDialog | null = null; let nextPresentationId = 0; +const presentationStatus = new Map(); const listeners = new Set<() => void>(); function setPresented(next: PresentedDialog | null) { @@ -48,8 +50,32 @@ function setPresented(next: PresentedDialog | null) { for (const listener of listeners) listener(); } +function statusOf(id: number): PresentationStatus | undefined { + return presentationStatus.get(id); +} + +function cancelPresented(dialog: PresentedDialog) { + if (statusOf(dialog.id) === "completed") return; + presentationStatus.set(dialog.id, "completed"); + dismiss(dialog.id); + if (dialog.kind === "alert") dialog.request.options?.onDismiss?.(); + else dialog.request.onCancel?.(); +} + function submitRequest(dialog: DialogRequest) { - setPresented({ ...dialog, id: ++nextPresentationId }); + const previous = presented; + if (previous) presentationStatus.set(previous.id, "replaced"); + const id = ++nextPresentationId; + presentationStatus.set(id, "active"); + setPresented({ ...dialog, id }); + // A newer dialog replaces the current one without a button press; cancel the + // previous so awaiters (settle confirms, busy flags) do not hang. + if (previous !== null) { + queueMicrotask(() => { + if (presented?.id === previous.id) return; + cancelPresented(previous); + }); + } } /** Closes the dialog only if it is still the one the action came from. */ @@ -87,25 +113,32 @@ export function prompt(request: TextInputDialogRequest): void { submitRequest({ kind: "text-input", request }); } -export function Host() { - const presented = useSyncExternalStore(subscribe, getPresented, getPresented); +function handleCancelFor(dialog: PresentedDialog) { + if (statusOf(dialog.id) !== "active") return; + cancelPresented(dialog); +} - const handleCancel = () => { - if (!presented) return; - dismiss(presented.id); - if (presented.kind === "alert") presented.request.options?.onDismiss?.(); - else presented.request.onCancel?.(); - }; +function handleConfirmFor(dialog: PresentedDialog, nativeInputValue?: string) { + if (statusOf(dialog.id) !== "active") return; + presentationStatus.set(dialog.id, "completed"); + dismiss(dialog.id); + if (dialog.kind === "confirm") { + dialog.request.onConfirm(); + } else if (dialog.kind === "text-input") { + dialog.request.onConfirm(nativeInputValue ?? dialog.request.initialValue); + } +} - const handleConfirm = (nativeInputValue?: string) => { - if (!presented) return; - dismiss(presented.id); - if (presented.kind === "confirm") { - presented.request.onConfirm(); - } else if (presented.kind === "text-input") { - presented.request.onConfirm(nativeInputValue ?? presented.request.initialValue); - } - }; +function handleAlertActionFor(dialog: PresentedDialog, action: AlertButton) { + // Stale native alert presses still run their action; only the active + // presentation can clear the store entry. + if (statusOf(dialog.id) === "active") presentationStatus.set(dialog.id, "completed"); + dismiss(dialog.id); + action.onPress?.(); +} + +export function Host() { + const presented = useSyncExternalStore(subscribe, getPresented, getPresented); if (presented?.kind === "alert") { return ( @@ -118,12 +151,9 @@ export function Host() { }} alertActions={presented.request.buttons ?? [{ text: "OK" }]} dismissable={presented.request.options?.cancelable ?? false} - onAlertAction={(action) => { - dismiss(presented.id); - action.onPress?.(); - }} - onCancel={handleCancel} - onConfirm={handleConfirm} + onAlertAction={(action) => handleAlertActionFor(presented, action)} + onCancel={() => handleCancelFor(presented)} + onConfirm={(value) => handleConfirmFor(presented, value)} /> ); } @@ -136,8 +166,8 @@ export function Host() { presented.kind === "text-input" ? presented.request.initialValue : undefined } inputPlaceholder={presented.kind === "text-input" ? presented.request.placeholder : undefined} - onCancel={handleCancel} - onConfirm={handleConfirm} + onCancel={() => handleCancelFor(presented)} + onConfirm={(value) => handleConfirmFor(presented, value)} /> ) : null; } diff --git a/apps/mobile/src/components/ui/Dialog.tsx b/apps/mobile/src/components/ui/Dialog.tsx index afef71264cc6d..c6294293f11b9 100644 --- a/apps/mobile/src/components/ui/Dialog.tsx +++ b/apps/mobile/src/components/ui/Dialog.tsx @@ -3,28 +3,45 @@ import type { ConfirmDialogRequest, TextInputDialogRequest } from "./Dialog.type export type { ConfirmDialogRequest, TextInputDialogRequest } from "./Dialog.types"; +function beginTrackedDialog(onCancel: (() => void) | undefined) { + let finished = false; + const finish = (action?: () => void) => { + if (finished) return; + finished = true; + action?.(); + }; + const cancel = () => finish(onCancel); + const complete = (action: () => void) => finish(action); + return { cancel, complete }; +} + export function alert(...args: Parameters): void { Alert.alert(...args); } export function confirm(request: ConfirmDialogRequest): void { + const { cancel, complete } = beginTrackedDialog(request.onCancel); Alert.alert(request.title, request.message, [ - { text: request.cancelText ?? "Cancel", style: "cancel", onPress: request.onCancel }, + { text: request.cancelText ?? "Cancel", style: "cancel", onPress: cancel }, { text: request.confirmText, style: request.destructive ? "destructive" : "default", - onPress: request.onConfirm, + onPress: () => complete(request.onConfirm), }, ]); } export function prompt(request: TextInputDialogRequest): void { + const { cancel, complete } = beginTrackedDialog(request.onCancel); Alert.prompt( request.title, request.message, [ - { text: request.cancelText ?? "Cancel", style: "cancel", onPress: request.onCancel }, - { text: request.confirmText, onPress: (value) => request.onConfirm(value ?? "") }, + { text: request.cancelText ?? "Cancel", style: "cancel", onPress: cancel }, + { + text: request.confirmText, + onPress: (value) => complete(() => request.onConfirm(value ?? "")), + }, ], "plain-text", request.initialValue, diff --git a/apps/mobile/src/features/home/useThreadListActions.test.ts b/apps/mobile/src/features/home/useThreadListActions.test.ts index 18cd5363d3c0a..2b52e92699188 100644 --- a/apps/mobile/src/features/home/useThreadListActions.test.ts +++ b/apps/mobile/src/features/home/useThreadListActions.test.ts @@ -2,11 +2,14 @@ import { makeThreadShellFixture } from "../../test-fixtures"; import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; import { AuthOrchestrationOperateScope, + AuthSourceControlWriteScope, EnvironmentId, ProjectId, ProviderInstanceId, RunId, ThreadId, + type ThreadPullRequestLink, + type ThreadPullRequestSnapshot, } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; import { AsyncResult } from "effect/reactivity"; @@ -23,14 +26,32 @@ const state = vi.hoisted(() => ({ requests: [] as { action: string; environmentId: string; - input: { threadId: string; orderKey?: string; snoozedUntil?: string; reason?: string }; + input: { + threadId?: string; + orderKey?: string; + snoozedUntil?: string; + reason?: string; + action?: string; + number?: number; + repository?: string; + host?: string; + projectId?: string; + }; + }[], + dialogs: [] as { + title?: string; + confirmText?: string; + cancelText?: string; + onConfirm: () => void; + onCancel?: () => void; }[], - dialogs: [] as { onConfirm: () => void }[], alerts: [] as { title: string; buttons?: { text: string; onPress?: () => void }[]; }[], afterRequest: undefined as (() => void) | undefined, + closeFailures: new Set(), + closePullRequestsOnSettle: true, heldActions: new Map>(), })); @@ -51,7 +72,33 @@ vi.mock("expo-haptics", () => ({ vi.mock("../../components/ui/Dialog", () => ({ alert: (title: string, _message: string, buttons?: { text: string; onPress?: () => void }[]) => state.alerts.push({ title, buttons }), - confirm: (dialog: { onConfirm: () => void }) => state.dialogs.push(dialog), + confirm: (dialog: { + title?: string; + confirmText?: string; + cancelText?: string; + onConfirm: () => void; + onCancel?: () => void; + }) => state.dialogs.push(dialog), +})); +vi.mock("../../state/pull-requests", () => ({ + composerPullRequests: { + runAction: async (request: { + environmentId: string; + input: { + projectId: string; + host: string; + repository: string; + number: number; + action: string; + }; + }) => { + state.requests.push({ action: "closePullRequest", ...request }); + if (state.closeFailures.has(request.input.number)) { + return AsyncResult.failure(Cause.fail(new Error("Host refused close"))); + } + return AsyncResult.success(undefined); + }, + }, })); vi.mock("../archive/useArchivedThreadSnapshots", () => ({ refreshArchivedThreadsForEnvironment: (environmentId: string) => { @@ -68,6 +115,9 @@ vi.mock("../../state/presentation", () => ({ vi.mock("../../state/server", () => ({ environmentServerConfigsAtom: "server-configs", })); +vi.mock("../../state/preferences", () => ({ + mobilePreferencesAtom: "mobile-preferences", +})); vi.mock("../../state/atom-registry", () => ({ appAtomRegistry: { set: (_atom: string, value: boolean) => { @@ -82,22 +132,26 @@ vi.mock("../../state/atom-registry", () => ({ ? state.shells : atom === "queued-thread-keys" ? new Set() - : new Map( - [...state.scopes.keys()].map((environmentId) => [ - environmentId, - { - environment: { - capabilities: { - threadSettlement: true, - threadSnooze: true, - threadPinning: true, - threadPinReorder: true, - threadTitleRegeneration: true, + : atom === "mobile-preferences" + ? AsyncResult.success({ + closePullRequestsOnSettle: state.closePullRequestsOnSettle, + }) + : new Map( + [...state.scopes.keys()].map((environmentId) => [ + environmentId, + { + environment: { + capabilities: { + threadSettlement: true, + threadSnooze: true, + threadPinning: true, + threadPinReorder: true, + threadTitleRegeneration: true, + }, }, }, - }, - ]), - ), + ]), + ), }, })); vi.mock("../../state/use-atom-command", () => ({ @@ -202,6 +256,8 @@ beforeEach(() => { state.dialogs = []; state.alerts = []; state.afterRequest = undefined; + state.closeFailures = new Set(); + state.closePullRequestsOnSettle = true; state.heldActions = new Map(); }); @@ -572,3 +628,142 @@ describe("thread archive guard", () => { expect(state.alerts.at(-1)?.title).toBe("Could not archive thread"); }); }); + +function pullRequestSnapshot( + input: Partial = {}, +): ThreadPullRequestSnapshot { + return { + state: "open", + title: "Change", + headBranch: "feature", + baseBranch: "main", + isDraft: false, + updatedAt: "2026-01-01T00:00:00.000Z", + syncedAt: "2026-01-01T00:00:00.000Z", + ...input, + }; +} + +function openPullRequestLink( + number: number, + input: Partial> = {}, +): ThreadPullRequestLink { + return { + host: "github.com", + repository: "pingdotgg/t3code", + number, + url: `https://github.com/pingdotgg/t3code/pull/${number}`, + source: "manual", + linkedAt: "2026-01-01T00:00:00.000Z", + snapshot: pullRequestSnapshot(), + stack: null, + ...input, + }; +} + +describe("settleThread close open pull requests", () => { + beforeEach(() => { + state.scopes.set( + primaryEnvironmentId, + new Set([AuthOrchestrationOperateScope, AuthSourceControlWriteScope]), + ); + }); + + it("settles without asking when there are no open pull requests", async () => { + expect( + await useThreadListActions().settleThread( + makeThread({ + pullRequests: [ + openPullRequestLink(1, { snapshot: pullRequestSnapshot({ state: "merged" }) }), + ], + }), + ), + ).toBe(true); + expect(state.dialogs).toEqual([]); + expect(state.requests.map(({ action }) => action)).toEqual(["settle"]); + }); + + it("settles without asking when the setting is off", async () => { + state.closePullRequestsOnSettle = false; + expect( + await useThreadListActions().settleThread( + makeThread({ pullRequests: [openPullRequestLink(2)] }), + ), + ).toBe(true); + expect(state.dialogs).toEqual([]); + expect(state.requests.map(({ action }) => action)).toEqual(["settle"]); + }); + + it("closes open pull requests after confirming Close & Settle", async () => { + const settling = useThreadListActions().settleThread( + makeThread({ pullRequests: [openPullRequestLink(4), openPullRequestLink(5)] }), + ); + expect(state.dialogs[0]).toMatchObject({ + title: "Close open pull requests?", + confirmText: "Close & Settle", + cancelText: "Settle", + }); + state.dialogs[0]!.onConfirm(); + expect(await settling).toBe(true); + expect(state.requests.map(({ action }) => action)).toEqual([ + "settle", + "closePullRequest", + "closePullRequest", + ]); + expect(state.requests.slice(1)).toEqual([ + { + action: "closePullRequest", + environmentId: primaryEnvironmentId, + input: { + projectId: ProjectId.make("project"), + host: "github.com", + repository: "pingdotgg/t3code", + number: 4, + action: "close", + }, + }, + { + action: "closePullRequest", + environmentId: primaryEnvironmentId, + input: { + projectId: ProjectId.make("project"), + host: "github.com", + repository: "pingdotgg/t3code", + number: 5, + action: "close", + }, + }, + ]); + }); + + it("settles without closing when Settle is chosen", async () => { + const settling = useThreadListActions().settleThread( + makeThread({ pullRequests: [openPullRequestLink(6)] }), + ); + state.dialogs[0]!.onCancel?.(); + expect(await settling).toBe(true); + expect(state.requests.map(({ action }) => action)).toEqual(["settle"]); + }); + + it("keeps the settle when a close fails", async () => { + state.closeFailures.add(7); + const settling = useThreadListActions().settleThread( + makeThread({ pullRequests: [openPullRequestLink(7)] }), + ); + state.dialogs[0]!.onConfirm(); + expect(await settling).toBe(true); + expect(state.requests.map(({ action }) => action)).toEqual(["settle", "closePullRequest"]); + expect(state.alerts.at(-1)?.title).toBe("Closed 0 of 1 pull requests"); + }); + + it("resolves when cancel runs twice after a replaced confirm", async () => { + const settling = useThreadListActions().settleThread( + makeThread({ pullRequests: [openPullRequestLink(8)] }), + ); + const dialog = state.dialogs[0]!; + dialog.onCancel?.(); + dialog.onCancel?.(); + expect(await settling).toBe(true); + expect(state.requests.map(({ action }) => action)).toEqual(["settle"]); + }); +}); diff --git a/apps/mobile/src/features/home/useThreadListActions.ts b/apps/mobile/src/features/home/useThreadListActions.ts index 9d44d971c1f03..d9b8f67887564 100644 --- a/apps/mobile/src/features/home/useThreadListActions.ts +++ b/apps/mobile/src/features/home/useThreadListActions.ts @@ -3,8 +3,13 @@ import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell import * as ThreadUndo from "@t3tools/client-runtime/state/thread-undo"; import { showThreadUndoNotice } from "./thread-undo-notice"; import { canSnooze } from "@t3tools/client-runtime/state/thread-settled"; -import { AuthOrchestrationOperateScope } from "@t3tools/contracts"; +import { AuthOrchestrationOperateScope, AuthSourceControlWriteScope } from "@t3tools/contracts"; +import { + openLinkedThreadPullRequests, + settleClosePullRequestsMessage, +} from "@t3tools/shared/threadPullRequests"; import * as Cause from "effect/Cause"; +import { AsyncResult } from "effect/reactivity"; import * as Haptics from "expo-haptics"; import { useRef } from "react"; @@ -14,6 +19,8 @@ import { scopedThreadKey } from "../../lib/scopedEntities"; import { refreshArchivedThreadsForEnvironment } from "../archive/useArchivedThreadSnapshots"; import { pinOrderKeyBetween } from "@t3tools/client-runtime/state/thread-sort"; import { appAtomRegistry } from "../../state/atom-registry"; +import { mobilePreferencesAtom } from "../../state/preferences"; +import { composerPullRequests } from "../../state/pull-requests"; import { environmentServerConfigsAtom } from "../../state/server"; import { connectedEnvironmentIdsAtom } from "../../state/presentation"; import { readEnvironmentScope } from "../../state/session"; @@ -212,6 +219,9 @@ export function useThreadListActions(): { readonly regenerateThreadTitle: (thread: EnvironmentThreadShell) => Promise; } { const executeAction = useThreadActionExecutor(); + const closePullRequestMutation = useAtomCommand(composerPullRequests.runAction, { + reportFailure: false, + }); const snoozeMutation = useAtomCommand(threadEnvironment.snooze, { reportFailure: false }); const unsnoozeMutation = useAtomCommand(threadEnvironment.unsnooze, { reportFailure: false }); const pinMutation = useAtomCommand(threadEnvironment.pin, { reportFailure: false }); @@ -278,19 +288,83 @@ export function useThreadListActions(): { }, }); const settleThread = async (thread: EnvironmentThreadShell) => { - const key = scopedThreadKey(thread.environmentId, thread.id); - const plan = ThreadUndo.planThreadUndo("settle", thread); - let claim: ReturnType | undefined; - const succeeded = await executeAction("settle", thread, () => { - ThreadUndo.invalidate("pin", key); - ThreadUndo.invalidate("snooze", key); - claim = ThreadUndo.begin("settle", key); + const openPullRequests = openLinkedThreadPullRequests(thread.pullRequests); + const preferences = appAtomRegistry.get(mobilePreferencesAtom); + const closePullRequestsOnSettle = + AsyncResult.isSuccess(preferences) && preferences.value.closePullRequestsOnSettle === true; + const askToClose = + closePullRequestsOnSettle && + openPullRequests.length > 0 && + readEnvironmentScope(thread.environmentId, AuthSourceControlWriteScope); + const performSettle = async (shouldClosePullRequests: boolean) => { + const key = scopedThreadKey(thread.environmentId, thread.id); + const plan = ThreadUndo.planThreadUndo("settle", thread); + let claim: ReturnType | undefined; + const succeeded = await executeAction("settle", thread, () => { + ThreadUndo.invalidate("pin", key); + ThreadUndo.invalidate("snooze", key); + claim = ThreadUndo.begin("settle", key); + }); + if (claim) { + if (succeeded) offerUndo(thread, "Settled", claim, plan); + else claim.finish(); + } + if (succeeded && shouldClosePullRequests) { + const failures: string[] = []; + let closed = 0; + for (const pullRequest of openPullRequests) { + const closeResult = await closePullRequestMutation({ + environmentId: thread.environmentId, + input: { + projectId: thread.projectId, + host: pullRequest.host, + repository: pullRequest.repository, + number: pullRequest.number, + action: "close", + }, + }); + if (AsyncResult.isFailure(closeResult)) { + const error = Cause.squash(closeResult.cause); + failures.push( + `#${pullRequest.number}: ${error instanceof Error ? error.message : "Could not close this pull request."}`, + ); + continue; + } + closed += 1; + } + if (failures.length > 0) { + Dialog.alert( + `Closed ${closed} of ${openPullRequests.length} pull requests`, + failures.slice(0, 3).join("\n"), + ); + } + } + return succeeded; + }; + if (!askToClose) return performSettle(false); + return await new Promise((resolve) => { + let started = false; + const choose = (shouldClosePullRequests: boolean) => { + if (started) return; + started = true; + void performSettle(shouldClosePullRequests).then(resolve); + }; + Dialog.confirm({ + title: "Close open pull requests?", + message: settleClosePullRequestsMessage(openPullRequests.length), + confirmText: "Close & Settle", + cancelText: "Settle", + destructive: true, + onConfirm: () => { + choose(true); + }, + // Cancel, dismiss, and Android replacement all land here so moveThread + // can clear threadDropBusyAtom even when another dialog takes over. + onCancel: () => { + choose(false); + }, + }); }); - if (claim) { - if (succeeded) offerUndo(thread, "Settled", claim, plan); - else claim.finish(); - } - return succeeded; }; const snoozeThread = async (thread: EnvironmentThreadShell, snoozedUntil: string) => { if (!checkThreadOperationPermission(thread, "Could not snooze thread")) return false; diff --git a/apps/mobile/src/features/settings/ThreadSettingsSections.tsx b/apps/mobile/src/features/settings/ThreadSettingsSections.tsx index 41600619b3a47..58cdc372c3eea 100644 --- a/apps/mobile/src/features/settings/ThreadSettingsSections.tsx +++ b/apps/mobile/src/features/settings/ThreadSettingsSections.tsx @@ -94,7 +94,11 @@ export function AutoSettleSettingsRows(props: { const referenceSettings = reference?.settings ?? null; if (reference === null || referenceSettings === null) { - return null; + return ( + + + + ); } const writeToAll = ( @@ -173,6 +177,7 @@ export function AutoSettleSettingsRows(props: { /> ) : null} + {!props.pending && mismatches.length > 0 ? ( @@ -194,6 +199,23 @@ export function AutoSettleSettingsRows(props: { ); } +function ClosePullRequestsOnSettleRow() { + const savePreferences = useAtomSet(updateMobilePreferencesAtom); + const preferences = useAtomValue(mobilePreferencesAtom); + const closePullRequestsOnSettle = + AsyncResult.isSuccess(preferences) && preferences.value.closePullRequestsOnSettle === true; + + return ( + savePreferences({ closePullRequestsOnSettle: value })} + /> + ); +} + export function WorkingSectionSettings() { const savePreferences = useAtomSet(updateMobilePreferencesAtom); const preferences = useAtomValue(mobilePreferencesAtom); diff --git a/apps/mobile/src/features/settings/settings-search.ts b/apps/mobile/src/features/settings/settings-search.ts index 4d02bd9789b1d..89c0c4c27d025 100644 --- a/apps/mobile/src/features/settings/settings-search.ts +++ b/apps/mobile/src/features/settings/settings-search.ts @@ -70,6 +70,7 @@ const SETTINGS_SEARCH_TERMS = { "browser access", "auto-settle", "settle", + "close open pull requests", "snooze", "usage limits", "auto-resume", diff --git a/apps/mobile/src/persistence/mobile-preferences.ts b/apps/mobile/src/persistence/mobile-preferences.ts index ed2d0b063c767..a15f67047b55f 100644 --- a/apps/mobile/src/persistence/mobile-preferences.ts +++ b/apps/mobile/src/persistence/mobile-preferences.ts @@ -118,6 +118,7 @@ export interface Preferences { readonly projectGroupingMode?: SidebarProjectGroupingMode; readonly toolCallVisibility?: ToolCallVisibility; readonly workingShelfEnabled?: boolean; + readonly closePullRequestsOnSettle?: boolean; readonly useLastProjectForNewThreads?: boolean; readonly lastThreadProject?: typeof ThreadProject.Type; readonly modelFavorites?: ReadonlyArray<{ @@ -202,6 +203,7 @@ function sanitizePreferences(parsed: Preferences): Preferences { projectGroupingMode?: SidebarProjectGroupingMode; toolCallVisibility?: ToolCallVisibility; workingShelfEnabled?: boolean; + closePullRequestsOnSettle?: boolean; useLastProjectForNewThreads?: boolean; lastThreadProject?: typeof ThreadProject.Type; modelFavorites?: Preferences["modelFavorites"]; @@ -330,6 +332,9 @@ function sanitizePreferences(parsed: Preferences): Preferences { if (typeof parsed.workingShelfEnabled === "boolean") { preferences.workingShelfEnabled = parsed.workingShelfEnabled; } + if (typeof parsed.closePullRequestsOnSettle === "boolean") { + preferences.closePullRequestsOnSettle = parsed.closePullRequestsOnSettle; + } if (typeof parsed.useLastProjectForNewThreads === "boolean") { preferences.useLastProjectForNewThreads = parsed.useLastProjectForNewThreads; } diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index dcaca88e6c7f7..a0ac5a437979d 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -503,6 +503,9 @@ export function useSettingsRestore(onRestored?: () => void) { ...(settings.sidebarAutoSettleOnMerge !== DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleOnMerge ? ["Auto-settle merged threads"] : []), + ...(settings.closePullRequestsOnSettle !== DEFAULT_UNIFIED_SETTINGS.closePullRequestsOnSettle + ? ["Close open pull requests when settling"] + : []), ...(settings.autoResumeLimitedThreads !== DEFAULT_UNIFIED_SETTINGS.autoResumeLimitedThreads ? ["Resume after usage limits"] : []), @@ -669,6 +672,7 @@ export function useSettingsRestore(onRestored?: () => void) { sidebarAutoSettleAfterDays: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays, sidebarAutoSettleKeepPullRequests: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleKeepPullRequests, sidebarAutoSettleOnMerge: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleOnMerge, + closePullRequestsOnSettle: DEFAULT_UNIFIED_SETTINGS.closePullRequestsOnSettle, autoResumeLimitedThreads: DEFAULT_UNIFIED_SETTINGS.autoResumeLimitedThreads, snoozeLimitedThreads: DEFAULT_UNIFIED_SETTINGS.snoozeLimitedThreads, snoozePresets: DEFAULT_UNIFIED_SETTINGS.snoozePresets, @@ -1750,104 +1754,132 @@ export function ThreadsSettingsPanel() { /> - {hasServerTargets ? ( - - - updateSettings({ - sidebarAutoSettleOnMerge: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleOnMerge, - }) - } - /> - ) : null - } - control={ - - updateSettings({ sidebarAutoSettleOnMerge: Boolean(checked) }) - } - aria-label="Auto-settle merged threads" - /> - } - /> - - - updateSettings({ - sidebarAutoSettleAfterDays: - DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays, - }) - } - /> - ) : null - } - control={ - - updateSettings({ - sidebarAutoSettleAfterDays: checked ? AUTO_SETTLE_DEFAULT_DAYS : null, - }) - } - aria-label="Auto-settle inactive threads" - /> - } - /> - {settings.sidebarAutoSettleAfterDays !== null ? ( + + {hasServerTargets ? ( + <> + updateSettings({ + sidebarAutoSettleOnMerge: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleOnMerge, + }) + } + /> + ) : null + } control={ - updateSettings({ sidebarAutoSettleAfterDays: days })} + + updateSettings({ sidebarAutoSettleOnMerge: Boolean(checked) }) + } + aria-label="Auto-settle merged threads" /> } /> - ) : null} - {settings.sidebarAutoSettleAfterDays !== null && supportsAutoSettlementScope ? ( + + updateSettings({ + sidebarAutoSettleAfterDays: + DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays, + }) + } + /> + ) : null + } control={ - updateSettings({ sidebarAutoSettleKeepPullRequests: checked }) + updateSettings({ + sidebarAutoSettleAfterDays: checked ? AUTO_SETTLE_DEFAULT_DAYS : null, + }) } - aria-label="Keep threads with a PR" + aria-label="Auto-settle inactive threads" /> } /> - ) : null} - - ) : null} + {settings.sidebarAutoSettleAfterDays !== null ? ( + updateSettings({ sidebarAutoSettleAfterDays: days })} + /> + } + /> + ) : null} + {settings.sidebarAutoSettleAfterDays !== null && supportsAutoSettlementScope ? ( + + updateSettings({ sidebarAutoSettleKeepPullRequests: checked }) + } + aria-label="Keep threads with a PR" + /> + } + /> + ) : null} + + ) : null} + + updateSettings({ + closePullRequestsOnSettle: DEFAULT_UNIFIED_SETTINGS.closePullRequestsOnSettle, + }) + } + /> + ) : null + } + control={ + + updateSettings({ closePullRequestsOnSettle: Boolean(checked) }) + } + aria-label="Close open pull requests when settling" + /> + } + /> + ({ vi.mock("../state/vcs", () => ({ vcsEnvironment: { removeWorktree: "removeWorktree", refreshStatus: "refreshStatus" }, })); +vi.mock("../state/pullRequests", () => ({ + pullRequestEnvironment: { runAction: "closePullRequest" }, +})); vi.mock("../state/entities", () => ({ readEnvironmentServerConfigLoaded: () => true, readThreadShell: (ref: ScopedThreadRef) => @@ -187,6 +190,7 @@ vi.mock("./useSettings", () => ({ sidebarThreadSortOrder: "createdAt", confirmThreadDelete: true, confirmThreadUnpin: true, + closePullRequestsOnSettle: false, }), })); diff --git a/apps/web/src/hooks/useThreadActions.settleClose.test.ts b/apps/web/src/hooks/useThreadActions.settleClose.test.ts new file mode 100644 index 0000000000000..e88a86b90e8dd --- /dev/null +++ b/apps/web/src/hooks/useThreadActions.settleClose.test.ts @@ -0,0 +1,206 @@ +import { + AuthOrchestrationOperateScope, + AuthSourceControlWriteScope, + EnvironmentId, + ProjectId, + ThreadId, + type ThreadPullRequestLink, + type ThreadPullRequestSnapshot, +} from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; +import { AsyncResult } from "effect/reactivity"; +import { beforeEach, describe, expect, it, vi } from "vite-plus/test"; + +import { pullRequestEnvironment } from "../state/pullRequests"; +import { threadEnvironment } from "../state/threads"; +import { useThreadActions } from "./useThreadActions"; + +const state = vi.hoisted(() => ({ + scopes: new Set(), + confirm: vi.fn<(message: string) => Promise>(), + settle: vi.fn(), + close: vi.fn(), + toasts: [] as { type?: string; title?: string; description?: string }[], + pullRequests: [] as ThreadPullRequestLink[], + closePullRequestsOnSettle: true, +})); + +vi.mock("react", async (original) => ({ + ...(await original()), + useCallback: (callback: unknown) => callback, + useMemo: (create: () => unknown) => create(), + useRef: (value: unknown) => ({ current: value }), +})); +vi.mock("@tanstack/react-router", () => ({ + useRouter: () => ({ state: { location: { href: "/" }, matches: [] }, navigate: async () => {} }), +})); +vi.mock("../state/session", async (original) => ({ + ...(await original()), + readEnvironmentScope: (_environmentId: string, scope: string) => state.scopes.has(scope), +})); +vi.mock("../state/entities", async (original) => ({ + ...(await original()), + readEnvironmentServerConfigLoaded: () => true, + readThreadShell: () => ({ + title: "Thread", + projectId: ProjectId.make("project"), + environmentId: "settle-close-env", + pullRequests: state.pullRequests, + pinnedAt: null, + snoozedUntil: null, + session: null, + }), +})); +vi.mock("../localApi", () => ({ + readLocalApi: () => ({ dialogs: { confirm: state.confirm } }), +})); +vi.mock("../components/ui/toast", () => ({ + stackedThreadToast: (toast: unknown) => toast, + toastManager: { + add: (toast: { type?: string; title?: string; description?: string }) => { + state.toasts.push(toast); + }, + }, +})); +vi.mock("./useSettings", () => ({ + useClientSettings: (select: (settings: { closePullRequestsOnSettle: boolean }) => unknown) => + select({ closePullRequestsOnSettle: state.closePullRequestsOnSettle }), +})); +vi.mock("./useHandleNewThread", () => ({ useNewThreadHandler: () => async () => {} })); +vi.mock("../composerDraftStore", () => ({ useComposerDraftStore: () => vi.fn() })); +vi.mock("../lib/composerDraftUploads", () => ({ releaseComposerDraftUploads: vi.fn() })); +vi.mock("../terminalUiStateStore", () => ({ useTerminalUiStateStore: () => vi.fn() })); +vi.mock("../uiStateStore", () => ({ + useUiStateStore: (select: (store: { markThreadVisited: () => void }) => unknown) => + select({ markThreadVisited: () => {} }), +})); +vi.mock("../lib/archivedThreadsState", () => ({ refreshArchivedThreadsForEnvironment: vi.fn() })); +vi.mock("../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => vi.fn() })); +vi.mock("../state/use-atom-command", () => ({ + useAtomCommand: (command: unknown) => { + if (command === pullRequestEnvironment.runAction) return state.close; + return vi.fn(); + }, +})); +vi.mock("../state/use-orchestration-command", () => ({ + useOrchestrationCommand: (command: unknown) => { + if (command === threadEnvironment.settle) return state.settle; + return vi.fn().mockResolvedValue(AsyncResult.success(undefined)); + }, +})); + +const target = { + environmentId: EnvironmentId.make("settle-close-env"), + threadId: ThreadId.make("thread"), +}; + +function snapshot(input: Partial = {}): ThreadPullRequestSnapshot { + return { + state: "open", + title: "Change", + headBranch: "feature", + baseBranch: "main", + isDraft: false, + updatedAt: "2026-01-01T00:00:00.000Z", + syncedAt: "2026-01-01T00:00:00.000Z", + ...input, + }; +} + +function link( + number: number, + input: Partial> = {}, +): ThreadPullRequestLink { + return { + host: "github.com", + repository: "pingdotgg/t3code", + number, + url: `https://github.com/pingdotgg/t3code/pull/${number}`, + source: "manual", + linkedAt: "2026-01-01T00:00:00.000Z", + snapshot: snapshot(), + stack: null, + ...input, + }; +} + +beforeEach(() => { + state.scopes = new Set([AuthOrchestrationOperateScope, AuthSourceControlWriteScope]); + state.confirm.mockReset().mockResolvedValue(false); + state.settle.mockReset().mockResolvedValue(AsyncResult.success(undefined)); + state.close.mockReset().mockResolvedValue(AsyncResult.success(undefined)); + state.toasts = []; + state.pullRequests = []; + state.closePullRequestsOnSettle = true; +}); + +describe("settleThread close open pull requests", () => { + it("settles without asking when there are no open pull requests", async () => { + state.pullRequests = [link(1, { snapshot: snapshot({ state: "merged" }) })]; + await useThreadActions().settleThread(target); + expect(state.confirm).not.toHaveBeenCalled(); + expect(state.settle).toHaveBeenCalledOnce(); + expect(state.close).not.toHaveBeenCalled(); + }); + + it("settles without asking when the setting is off", async () => { + state.closePullRequestsOnSettle = false; + state.pullRequests = [link(1)]; + await useThreadActions().settleThread(target); + expect(state.confirm).not.toHaveBeenCalled(); + expect(state.settle).toHaveBeenCalledOnce(); + expect(state.close).not.toHaveBeenCalled(); + }); + + it("settles without asking when source-control write is unavailable", async () => { + state.scopes = new Set([AuthOrchestrationOperateScope]); + state.pullRequests = [link(1)]; + await useThreadActions().settleThread(target); + expect(state.confirm).not.toHaveBeenCalled(); + expect(state.settle).toHaveBeenCalledOnce(); + expect(state.close).not.toHaveBeenCalled(); + }); + + it("closes open pull requests after settle when confirmed", async () => { + state.pullRequests = [link(7), link(8, { snapshot: snapshot({ state: "closed" }) })]; + state.confirm.mockResolvedValue(true); + await useThreadActions().settleThread(target); + expect(state.confirm).toHaveBeenCalledOnce(); + expect(state.settle).toHaveBeenCalledOnce(); + expect(state.close).toHaveBeenCalledExactlyOnceWith({ + environmentId: target.environmentId, + input: { + projectId: ProjectId.make("project"), + host: "github.com", + repository: "pingdotgg/t3code", + number: 7, + action: "close", + }, + }); + expect(state.toasts).toEqual([{ type: "success", title: "Closed 1 pull request" }]); + }); + + it("settles without closing when the confirm is declined", async () => { + state.pullRequests = [link(3)]; + state.confirm.mockResolvedValue(false); + await useThreadActions().settleThread(target); + expect(state.settle).toHaveBeenCalledOnce(); + expect(state.close).not.toHaveBeenCalled(); + expect(state.toasts).toEqual([]); + }); + + it("keeps the settle when a close fails", async () => { + state.pullRequests = [link(9)]; + state.confirm.mockResolvedValue(true); + state.close.mockResolvedValue(AsyncResult.failure(Cause.fail(new Error("denied")))); + const result = await useThreadActions().settleThread(target); + expect(result._tag).toBe("Success"); + expect(state.toasts).toEqual([ + { + type: "error", + title: "Closed 0 of 1 pull requests", + description: "#9: denied", + }, + ]); + }); +}); diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.ts index e91f170689a56..ea2ced036aba2 100644 --- a/apps/web/src/hooks/useThreadActions.ts +++ b/apps/web/src/hooks/useThreadActions.ts @@ -17,6 +17,10 @@ import { sessionGrantsScope, } from "@t3tools/contracts"; import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings"; +import { + openLinkedThreadPullRequests, + settleClosePullRequestsMessage, +} from "@t3tools/shared/threadPullRequests"; import * as Cause from "effect/Cause"; import * as Schema from "effect/Schema"; import { AsyncResult } from "effect/reactivity"; @@ -30,6 +34,7 @@ import { environmentServerConfigsAtom } from "../state/server"; import { isScratchProject } from "@t3tools/client-runtime/state/projects"; import { orchestrationEnvironment } from "../state/orchestration"; import { projectEnvironment } from "../state/projects"; +import { pullRequestEnvironment } from "../state/pullRequests"; import { threadEnvironment } from "../state/threads"; import { vcsEnvironment } from "../state/vcs"; import { useNewThreadHandler } from "./useHandleNewThread"; @@ -286,6 +291,9 @@ export function useThreadActions() { const settleThreadMutation = useOrchestrationCommand(threadEnvironment.settle, { reportFailure: false, }); + const closePullRequestMutation = useAtomCommand(pullRequestEnvironment.runAction, { + reportFailure: false, + }); const unsettleThreadMutation = useOrchestrationCommand(threadEnvironment.unsettle, { reportFailure: false, }); @@ -335,6 +343,9 @@ export function useThreadActions() { const sidebarThreadSortOrder = useClientSettings((settings) => settings.sidebarThreadSortOrder); const confirmThreadDelete = useClientSettings((settings) => settings.confirmThreadDelete); const confirmThreadUnpin = useClientSettings((settings) => settings.confirmThreadUnpin); + const closePullRequestsOnSettle = useClientSettings( + (settings) => settings.closePullRequestsOnSettle, + ); const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread); const clearProjectDraftThreadById = useComposerDraftStore( (store) => store.clearProjectDraftThreadById, @@ -795,6 +806,25 @@ export function useThreadActions() { ); } const resolved = resolveThreadTarget(target); + const openPullRequests = openLinkedThreadPullRequests(resolved?.thread.pullRequests); + let shouldClosePullRequests = false; + const localApi = readLocalApi(); + if ( + closePullRequestsOnSettle && + openPullRequests.length > 0 && + localApi && + readEnvironmentScope(target.environmentId, AuthSourceControlWriteScope) + ) { + const confirmationResult = await settlePromise(() => + localApi.dialogs.confirm(settleClosePullRequestsMessage(openPullRequests.length), { + variant: "destructive", + }), + ); + if (confirmationResult._tag === "Failure") { + return confirmationResult; + } + shouldClosePullRequests = confirmationResult.value; + } // oxlint-disable-next-line react/purity -- runs in an event handler (oxc#27309) const nowIso = new Date().toISOString(); const wokeAt = resolved ? threadWokeAt(resolved.thread, { now: nowIso }) : null; @@ -821,6 +851,41 @@ export function useThreadActions() { undo: () => runUndoPlan(target, undoPlan), failureTitle: "Failed to undo settle", }); + if (shouldClosePullRequests && resolved) { + const projectId = resolved.thread.projectId; + const failures: string[] = []; + const outcomes = await Promise.all( + openPullRequests.map(async (pullRequest) => { + const closeResult = await closePullRequestMutation({ + environmentId: target.environmentId, + input: { + projectId, + host: pullRequest.host, + repository: pullRequest.repository, + number: pullRequest.number, + action: "close", + }, + }); + if (closeResult._tag === "Failure") { + const error = squashAtomCommandFailure(closeResult); + failures.push( + `#${pullRequest.number}: ${error instanceof Error ? error.message : "Could not close this pull request."}`, + ); + return; + } + return true; + }), + ); + const closed = outcomes.filter(Boolean).length; + toastManager.add({ + type: failures.length > 0 ? "error" : "success", + title: + failures.length > 0 + ? `Closed ${closed} of ${openPullRequests.length} pull requests` + : `Closed ${closed} pull request${closed === 1 ? "" : "s"}`, + ...(failures.length > 0 ? { description: failures.slice(0, 3).join("\n") } : {}), + }); + } return result; }; diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 09ce63e2a3e65..a37767f638fc0 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -172,6 +172,9 @@ when the thread settles** enabled in Settings > Projects > Actions. You can also `"stopOnSettle": true` on a `t3.json` action and import it there. Start the command through that action so T3 can stop its terminal and child processes. Commands started through an agent's own shell tools are managed by the provider. +When **Close open pull requests when settling** is on in **Settings → Threads** and the +thread has open linked pull requests you can write to, settling asks whether to close them +too. To reclaim disk space from settled work, turn on **Run in the thread's worktree when the thread settles** for one of the project's actions, or set `"runOnSettle": true` on a diff --git a/knip.jsonc b/knip.jsonc index 068c8cf84ab69..b3b85dbcd3a80 100644 --- a/knip.jsonc +++ b/knip.jsonc @@ -121,10 +121,12 @@ "src/features/browser/preview-stream.browser.ts!", ], // Fonts are configured as asset paths; Expo autolinks the native packages. + // `generate:nitro` runs `nitrogen` after `cd`, which knip does not attribute. "ignoreDependencies": [ "@expo-google-fonts/dm-sans", "@t3tools/mobile-review-diff-native", "@t3tools/mobile-terminal-native", + "nitrogen", ], }, "apps/mobile/modules/t3-highlights": { diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 346213992e4b2..e978e43423d98 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -459,6 +459,8 @@ export const ClientSettingsSchema = Schema.Struct({ confirmThreadArchive: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), confirmThreadDelete: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), confirmThreadUnpin: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), + /** When settling, ask to close the thread's open linked pull requests. */ + closePullRequestsOnSettle: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), diffFilesCollapsed: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), diffIgnoreWhitespace: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), diffLayout: DiffLayout.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_DIFF_LAYOUT))), @@ -2006,6 +2008,7 @@ export const ClientSettingsPatch = Schema.Struct({ confirmThreadArchive: Schema.optionalKey(Schema.Boolean), confirmThreadDelete: Schema.optionalKey(Schema.Boolean), confirmThreadUnpin: Schema.optionalKey(Schema.Boolean), + closePullRequestsOnSettle: Schema.optionalKey(Schema.Boolean), diffFilesCollapsed: Schema.optionalKey(Schema.Boolean), diffIgnoreWhitespace: Schema.optionalKey(Schema.Boolean), diffLayout: Schema.optionalKey(DiffLayout), diff --git a/packages/shared/src/threadPullRequests.test.ts b/packages/shared/src/threadPullRequests.test.ts new file mode 100644 index 0000000000000..009c15c8d995e --- /dev/null +++ b/packages/shared/src/threadPullRequests.test.ts @@ -0,0 +1,52 @@ +import type { ThreadPullRequestLink, ThreadPullRequestSnapshot } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { openLinkedThreadPullRequests } from "./threadPullRequests.ts"; + +function snapshot(input: Partial = {}): ThreadPullRequestSnapshot { + return { + state: "open", + title: "Change", + headBranch: "feature", + baseBranch: "main", + isDraft: false, + updatedAt: "2026-01-01T00:00:00.000Z", + syncedAt: "2026-01-01T00:00:00.000Z", + ...input, + }; +} + +function link( + number: number, + input: Partial> = {}, +): ThreadPullRequestLink { + return { + host: "github.com", + repository: "pingdotgg/t3code", + number, + url: `https://github.com/pingdotgg/t3code/pull/${number}`, + source: "manual", + linkedAt: "2026-01-01T00:00:00.000Z", + snapshot: snapshot(), + stack: null, + ...input, + }; +} + +describe("openLinkedThreadPullRequests", () => { + it("keeps only visible links whose snapshot is open", () => { + expect( + openLinkedThreadPullRequests([ + link(1), + link(2, { snapshot: snapshot({ state: "closed" }) }), + link(3, { snapshot: snapshot({ state: "merged" }) }), + link(4, { snapshot: null }), + link(5, { source: "stack-dismissed" }), + ]).map((entry) => entry.number), + ).toEqual([1]); + }); + + it("treats a missing list as empty", () => { + expect(openLinkedThreadPullRequests(undefined)).toEqual([]); + }); +}); diff --git a/packages/shared/src/threadPullRequests.ts b/packages/shared/src/threadPullRequests.ts index 0ff12bc3c3f1b..c1865d0a50b52 100644 --- a/packages/shared/src/threadPullRequests.ts +++ b/packages/shared/src/threadPullRequests.ts @@ -7,6 +7,19 @@ export function visibleThreadPullRequests( return links.filter((link) => link.source !== "stack-dismissed"); } +/** Linked pull requests known to be open; unknown snapshots are left alone. */ +export function openLinkedThreadPullRequests( + links: ReadonlyArray | undefined, +): ReadonlyArray { + return visibleThreadPullRequests(links ?? []).filter((link) => link.snapshot?.state === "open"); +} + +/** Confirm-dialog copy when manually settling a thread that still has open pull requests. */ +export function settleClosePullRequestsMessage(count: number): string { + const noun = count === 1 ? "pull request" : "pull requests"; + return [`This thread has ${count} open ${noun}.`, "", "Close them when settling?"].join("\n"); +} + function latestUpdatedAt(link: ThreadPullRequestLink): number { const value = link.snapshot?.updatedAt ?? link.linkedAt; const ms = Date.parse(value);