From d634335f8eed6fb370b2c8547a98922a4a5fc1d6 Mon Sep 17 00:00:00 2001 From: wSedlacek Date: Wed, 4 Nov 2026 20:23:09 -0800 Subject: [PATCH 1/6] feat(web,mobile): offer to close open PRs when settling Settling a thread with open linked pull requests now asks whether to close them too, so abandoned work can be cleaned up in one step. --- .../home/useThreadListActions.test.ts | 170 +++++++++++++++- .../src/features/home/useThreadListActions.ts | 87 ++++++-- .../useThreadActions.permissions.test.ts | 3 + .../useThreadActions.settleClose.test.ts | 192 ++++++++++++++++++ apps/web/src/hooks/useThreadActions.ts | 61 ++++++ docs/user/thread-sidebar.md | 3 +- .../shared/src/threadPullRequests.test.ts | 69 +++++++ packages/shared/src/threadPullRequests.ts | 13 ++ 8 files changed, 581 insertions(+), 17 deletions(-) create mode 100644 apps/web/src/hooks/useThreadActions.settleClose.test.ts create mode 100644 packages/shared/src/threadPullRequests.test.ts diff --git a/apps/mobile/src/features/home/useThreadListActions.test.ts b/apps/mobile/src/features/home/useThreadListActions.test.ts index 9313aef299881..718ec9269808a 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,31 @@ 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(), })); vi.mock("react", () => ({ @@ -50,7 +70,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) => { @@ -200,6 +246,7 @@ beforeEach(() => { state.dialogs = []; state.alerts = []; state.afterRequest = undefined; + state.closeFailures = new Set(); }); afterEach(() => { @@ -559,3 +606,120 @@ 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("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"); + }); +}); diff --git a/apps/mobile/src/features/home/useThreadListActions.ts b/apps/mobile/src/features/home/useThreadListActions.ts index 248c436905311..0b9d7872411ae 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,7 @@ 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 { composerPullRequests } from "../../state/pull-requests"; import { environmentServerConfigsAtom } from "../../state/server"; import { connectedEnvironmentIdsAtom } from "../../state/presentation"; import { readEnvironmentScope } from "../../state/session"; @@ -210,6 +216,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 }); @@ -276,19 +285,71 @@ 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 askToClose = + 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) => { + Dialog.confirm({ + title: "Close open pull requests?", + message: settleClosePullRequestsMessage(openPullRequests.length), + confirmText: "Close & Settle", + cancelText: "Settle", + destructive: true, + onConfirm: () => { + void performSettle(true).then(resolve); + }, + onCancel: () => { + void performSettle(false).then(resolve); + }, + }); }); - 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/web/src/hooks/useThreadActions.permissions.test.ts b/apps/web/src/hooks/useThreadActions.permissions.test.ts index de5056c4af696..5375c6336e9be 100644 --- a/apps/web/src/hooks/useThreadActions.permissions.test.ts +++ b/apps/web/src/hooks/useThreadActions.permissions.test.ts @@ -99,6 +99,9 @@ vi.mock("../state/threads", () => ({ 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) => 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..e8c809eae7d51 --- /dev/null +++ b/apps/web/src/hooks/useThreadActions.settleClose.test.ts @@ -0,0 +1,192 @@ +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[], +})); + +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: () => false })); +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 = []; +}); + +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 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 904b94ebfc5c5..0661f83be43ff 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, }); @@ -755,6 +763,24 @@ export function useThreadActions() { ); } const resolved = resolveThreadTarget(target); + const openPullRequests = openLinkedThreadPullRequests(resolved?.thread.pullRequests); + let shouldClosePullRequests = false; + const localApi = readLocalApi(); + if ( + 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; @@ -781,6 +807,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 6a3145d17512f..6ff0561743120 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -167,7 +167,8 @@ and prevents automatic settlement until new activity resumes the usual rules. Manually settling an idle thread dismisses unanswered async questions without sending an answer or restarting the agent. Settling also closes the thread's terminals that wait at an idle prompt, and keeps their output. A terminal that -runs a command, such as a dev server, stays open. +runs a command, such as a dev server, stays open. When the thread has open pull +requests and you can write to the host, 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/packages/shared/src/threadPullRequests.test.ts b/packages/shared/src/threadPullRequests.test.ts new file mode 100644 index 0000000000000..7d185d12103ee --- /dev/null +++ b/packages/shared/src/threadPullRequests.test.ts @@ -0,0 +1,69 @@ +import type { ThreadPullRequestLink, ThreadPullRequestSnapshot } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { + openLinkedThreadPullRequests, + settleClosePullRequestsMessage, +} 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([]); + }); +}); + +describe("settleClosePullRequestsMessage", () => { + it("names a single pull request", () => { + expect(settleClosePullRequestsMessage(1)).toBe( + "This thread has 1 open pull request.\n\nClose them when settling?", + ); + }); + + it("pluralizes several pull requests", () => { + expect(settleClosePullRequestsMessage(3)).toBe( + "This thread has 3 open pull requests.\n\nClose them when settling?", + ); + }); +}); 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); From 816355b2a2df98d11e174b4b50a724cd39140b0c Mon Sep 17 00:00:00 2001 From: wSedlacek Date: Thu, 5 Nov 2026 06:21:05 -0800 Subject: [PATCH 2/6] fix(mobile): settle confirms resolve when another dialog replaces them Android dialogs replace the active confirm without a button press, which left settleThread hanging and could stick threadDropBusyAtom. Cancel the replaced dialog and ignore duplicate choices so moveThread can clear busy. --- .../src/components/ui/Dialog.android.test.tsx | 23 ++++++++++ .../src/components/ui/Dialog.android.tsx | 14 ++++++ apps/mobile/src/components/ui/Dialog.tsx | 44 +++++++++++++++++-- .../home/useThreadListActions.test.ts | 11 +++++ .../src/features/home/useThreadListActions.ts | 12 ++++- 5 files changed, 98 insertions(+), 6 deletions(-) diff --git a/apps/mobile/src/components/ui/Dialog.android.test.tsx b/apps/mobile/src/components/ui/Dialog.android.test.tsx index d283cf004c23a..5d2a4928f0ede 100644 --- a/apps/mobile/src/components/ui/Dialog.android.test.tsx +++ b/apps/mobile/src/components/ui/Dialog.android.test.tsx @@ -102,3 +102,26 @@ 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(); +}); diff --git a/apps/mobile/src/components/ui/Dialog.android.tsx b/apps/mobile/src/components/ui/Dialog.android.tsx index af05275b7f270..463b0eeffe2b2 100644 --- a/apps/mobile/src/components/ui/Dialog.android.tsx +++ b/apps/mobile/src/components/ui/Dialog.android.tsx @@ -47,8 +47,22 @@ function setPresented(next: PresentedDialog | null) { for (const listener of listeners) listener(); } +function cancelPresented(dialog: PresentedDialog) { + if (dialog.kind === "alert") dialog.request.options?.onDismiss?.(); + else dialog.request.onCancel?.(); +} + function submitRequest(dialog: DialogRequest) { + const previous = presented; setPresented({ ...dialog, id: ++nextPresentationId }); + // 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. */ diff --git a/apps/mobile/src/components/ui/Dialog.tsx b/apps/mobile/src/components/ui/Dialog.tsx index afef71264cc6d..f15a37e28e419 100644 --- a/apps/mobile/src/components/ui/Dialog.tsx +++ b/apps/mobile/src/components/ui/Dialog.tsx @@ -3,28 +3,64 @@ import type { ConfirmDialogRequest, TextInputDialogRequest } from "./Dialog.type export type { ConfirmDialogRequest, TextInputDialogRequest } from "./Dialog.types"; +type PendingDialogCancel = () => void; + +let pendingDialogCancel: PendingDialogCancel | undefined; + +function replacePendingDialogCancel(next: PendingDialogCancel | undefined) { + const previous = pendingDialogCancel; + pendingDialogCancel = next; + if (previous === undefined) return; + // Defer so a cancel handler that opens another dialog replaces `next` cleanly. + queueMicrotask(() => { + if (pendingDialogCancel === previous) return; + previous(); + }); +} + +/** Tracks cancel for the active confirm/prompt; calling it is idempotent. */ +function beginTrackedDialog(onCancel: (() => void) | undefined) { + let finished = false; + const finish = (action?: () => void) => { + if (finished) return; + finished = true; + if (pendingDialogCancel === cancel) pendingDialogCancel = undefined; + action?.(); + }; + const cancel = () => finish(onCancel); + const complete = (action: () => void) => finish(action); + replacePendingDialogCancel(cancel); + return { cancel, complete }; +} + export function alert(...args: Parameters): void { + replacePendingDialogCancel(undefined); 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 718ec9269808a..458dec2add8ed 100644 --- a/apps/mobile/src/features/home/useThreadListActions.test.ts +++ b/apps/mobile/src/features/home/useThreadListActions.test.ts @@ -722,4 +722,15 @@ describe("settleThread close open pull requests", () => { 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 0b9d7872411ae..072c412424cc9 100644 --- a/apps/mobile/src/features/home/useThreadListActions.ts +++ b/apps/mobile/src/features/home/useThreadListActions.ts @@ -336,6 +336,12 @@ export function useThreadListActions(): { }; 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), @@ -343,10 +349,12 @@ export function useThreadListActions(): { cancelText: "Settle", destructive: true, onConfirm: () => { - void performSettle(true).then(resolve); + choose(true); }, + // Cancel, dismiss, and Android replacement all land here so moveThread + // can clear threadDropBusyAtom even when another dialog takes over. onCancel: () => { - void performSettle(false).then(resolve); + choose(false); }, }); }); From b8a5eada6322f99940c58205d88c22ac80153194 Mon Sep 17 00:00:00 2001 From: wSedlacek Date: Thu, 5 Nov 2026 06:43:38 -0800 Subject: [PATCH 3/6] feat(web,mobile): gate settle PR close behind a Threads setting MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closing open linked pull requests on settle is opt-in via Settings → Threads so settling stays quiet unless the user turns the option on. --- .../home/useThreadListActions.test.ts | 48 +++-- .../src/features/home/useThreadListActions.ts | 5 + .../settings/ThreadSettingsSections.tsx | 18 ++ .../src/features/settings/settings-search.ts | 1 + .../src/persistence/mobile-preferences.ts | 5 + .../components/settings/SettingsPanels.tsx | 198 ++++++++++-------- .../src/components/settings/settingsSearch.ts | 7 + .../useThreadActions.permissions.test.ts | 1 + .../useThreadActions.settleClose.test.ts | 16 +- apps/web/src/hooks/useThreadActions.ts | 4 + docs/user/thread-sidebar.md | 5 +- packages/contracts/src/settings.ts | 3 + 12 files changed, 211 insertions(+), 100 deletions(-) diff --git a/apps/mobile/src/features/home/useThreadListActions.test.ts b/apps/mobile/src/features/home/useThreadListActions.test.ts index 458dec2add8ed..4966a9efeb73c 100644 --- a/apps/mobile/src/features/home/useThreadListActions.test.ts +++ b/apps/mobile/src/features/home/useThreadListActions.test.ts @@ -51,6 +51,7 @@ const state = vi.hoisted(() => ({ }[], afterRequest: undefined as (() => void) | undefined, closeFailures: new Set(), + closePullRequestsOnSettle: true, })); vi.mock("react", () => ({ @@ -113,6 +114,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) => { @@ -127,22 +131,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", () => ({ @@ -247,6 +255,7 @@ beforeEach(() => { state.alerts = []; state.afterRequest = undefined; state.closeFailures = new Set(); + state.closePullRequestsOnSettle = true; }); afterEach(() => { @@ -661,6 +670,17 @@ describe("settleThread close open pull requests", () => { 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)] }), diff --git a/apps/mobile/src/features/home/useThreadListActions.ts b/apps/mobile/src/features/home/useThreadListActions.ts index 072c412424cc9..6a91bd2d6f39b 100644 --- a/apps/mobile/src/features/home/useThreadListActions.ts +++ b/apps/mobile/src/features/home/useThreadListActions.ts @@ -19,6 +19,7 @@ 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"; @@ -286,7 +287,11 @@ export function useThreadListActions(): { }); const settleThread = async (thread: EnvironmentThreadShell) => { 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) => { diff --git a/apps/mobile/src/features/settings/ThreadSettingsSections.tsx b/apps/mobile/src/features/settings/ThreadSettingsSections.tsx index 4952f9a2f20ca..43a6b76c493de 100644 --- a/apps/mobile/src/features/settings/ThreadSettingsSections.tsx +++ b/apps/mobile/src/features/settings/ThreadSettingsSections.tsx @@ -160,6 +160,7 @@ export function AutoSettleSettingsRows(props: { /> ) : null} + {!props.pending && mismatches.length > 0 ? ( @@ -181,6 +182,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 9dcaf7b6bf003..78a5a18091a46 100644 --- a/apps/mobile/src/features/settings/settings-search.ts +++ b/apps/mobile/src/features/settings/settings-search.ts @@ -51,6 +51,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 3760ae10c3026..665850605eb89 100644 --- a/apps/mobile/src/persistence/mobile-preferences.ts +++ b/apps/mobile/src/persistence/mobile-preferences.ts @@ -117,6 +117,7 @@ export interface Preferences { readonly projectGroupingMode?: SidebarProjectGroupingMode; readonly planModeEnabled?: boolean; readonly workingShelfEnabled?: boolean; + readonly closePullRequestsOnSettle?: boolean; readonly useLastProjectForNewThreads?: boolean; readonly lastThreadProject?: typeof ThreadProject.Type; readonly modelFavorites?: ReadonlyArray<{ @@ -199,6 +200,7 @@ function sanitizePreferences(parsed: Preferences): Preferences { projectGroupingMode?: SidebarProjectGroupingMode; planModeEnabled?: boolean; workingShelfEnabled?: boolean; + closePullRequestsOnSettle?: boolean; useLastProjectForNewThreads?: boolean; lastThreadProject?: typeof ThreadProject.Type; modelFavorites?: Preferences["modelFavorites"]; @@ -327,6 +329,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 d408d6c8d5d94..783ee5825c261 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -493,6 +493,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"] : []), @@ -655,6 +658,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, @@ -1658,104 +1662,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" + /> + } + /> + ({ 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 index e8c809eae7d51..e88a86b90e8dd 100644 --- a/apps/web/src/hooks/useThreadActions.settleClose.test.ts +++ b/apps/web/src/hooks/useThreadActions.settleClose.test.ts @@ -22,6 +22,7 @@ const state = vi.hoisted(() => ({ close: vi.fn(), toasts: [] as { type?: string; title?: string; description?: string }[], pullRequests: [] as ThreadPullRequestLink[], + closePullRequestsOnSettle: true, })); vi.mock("react", async (original) => ({ @@ -61,7 +62,10 @@ vi.mock("../components/ui/toast", () => ({ }, }, })); -vi.mock("./useSettings", () => ({ useClientSettings: () => false })); +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() })); @@ -127,6 +131,7 @@ beforeEach(() => { state.close.mockReset().mockResolvedValue(AsyncResult.success(undefined)); state.toasts = []; state.pullRequests = []; + state.closePullRequestsOnSettle = true; }); describe("settleThread close open pull requests", () => { @@ -138,6 +143,15 @@ describe("settleThread close open pull requests", () => { 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)]; diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.ts index 0661f83be43ff..42054cb0bbdca 100644 --- a/apps/web/src/hooks/useThreadActions.ts +++ b/apps/web/src/hooks/useThreadActions.ts @@ -339,6 +339,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, @@ -767,6 +770,7 @@ export function useThreadActions() { let shouldClosePullRequests = false; const localApi = readLocalApi(); if ( + closePullRequestsOnSettle && openPullRequests.length > 0 && localApi && readEnvironmentScope(target.environmentId, AuthSourceControlWriteScope) diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 6ff0561743120..1953dcad29538 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -167,8 +167,9 @@ and prevents automatic settlement until new activity resumes the usual rules. Manually settling an idle thread dismisses unanswered async questions without sending an answer or restarting the agent. Settling also closes the thread's terminals that wait at an idle prompt, and keeps their output. A terminal that -runs a command, such as a dev server, stays open. When the thread has open pull -requests and you can write to the host, settling asks whether to close them too. +runs a command, such as a dev server, stays open. 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/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 798e076495a95..710607bae1478 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -419,6 +419,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))), @@ -1789,6 +1791,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), From 61fda4da0eb31778acd351301970c705ec062842 Mon Sep 17 00:00:00 2001 From: maria-rcks Date: Fri, 6 Nov 2026 10:57:26 +0000 Subject: [PATCH 4/6] fix(web,mobile): close-on-settle setting is findable and always shown --- .../mobile/src/features/settings/ThreadSettingsSections.tsx | 6 +++++- apps/web/src/components/settings/settingsSearch.ts | 1 - 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/apps/mobile/src/features/settings/ThreadSettingsSections.tsx b/apps/mobile/src/features/settings/ThreadSettingsSections.tsx index ceb18847bc4ba..4bd0c1567b714 100644 --- a/apps/mobile/src/features/settings/ThreadSettingsSections.tsx +++ b/apps/mobile/src/features/settings/ThreadSettingsSections.tsx @@ -84,7 +84,11 @@ export function AutoSettleSettingsRows(props: { const referenceSettings = reference?.settings ?? null; if (reference === null || referenceSettings === null) { - return null; + return ( + + + + ); } const writeToAll = ( diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 7854189014760..2ed36ad030312 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -629,7 +629,6 @@ export const SETTINGS_SEARCH_ITEMS = [ id: "close-pull-requests-on-settle", title: "Close open pull requests when settling", to: "/settings/threads", - targetId: "auto-settle", searchTerms: ["close pull request settle linked open ask confirm"], }, { From 846dc8f2affa78eac7cb16648525d6977d7ea1c0 Mon Sep 17 00:00:00 2001 From: wSedlacek Date: Sun, 8 Nov 2026 09:50:27 -0800 Subject: [PATCH 5/6] fix(mobile): complete replaced Android dialogs only once Stale confirm/cancel from a replaced native dialog could still fire alongside the replacement cancel, so track presentation status and ignore late actions after the first completion. --- .../src/components/ui/Dialog.android.test.tsx | 35 ++++++++++ .../src/components/ui/Dialog.android.tsx | 68 ++++++++++++------- knip.jsonc | 2 + 3 files changed, 79 insertions(+), 26 deletions(-) diff --git a/apps/mobile/src/components/ui/Dialog.android.test.tsx b/apps/mobile/src/components/ui/Dialog.android.test.tsx index 5d2a4928f0ede..71af1e0c08fe4 100644 --- a/apps/mobile/src/components/ui/Dialog.android.test.tsx +++ b/apps/mobile/src/components/ui/Dialog.android.test.tsx @@ -125,3 +125,38 @@ it("cancels a confirm that a newer dialog replaced", async () => { 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 1f2ae58fc8095..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,14 +50,24 @@ 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) { const previous = presented; - setPresented({ ...dialog, id: ++nextPresentationId }); + 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) { @@ -101,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 ( @@ -132,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)} /> ); } @@ -150,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/knip.jsonc b/knip.jsonc index ed4bf19129645..06db0569d89db 100644 --- a/knip.jsonc +++ b/knip.jsonc @@ -117,10 +117,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": { From 8fe91b3815ef83629948d2fc83f3d9824e5a21f1 Mon Sep 17 00:00:00 2001 From: maria-rcks Date: Wed, 11 Nov 2026 22:11:15 +0000 Subject: [PATCH 6/6] fix(mobile): keep stacked ios dialogs actionable --- apps/mobile/src/components/ui/Dialog.tsx | 19 ------------------- 1 file changed, 19 deletions(-) diff --git a/apps/mobile/src/components/ui/Dialog.tsx b/apps/mobile/src/components/ui/Dialog.tsx index f15a37e28e419..c6294293f11b9 100644 --- a/apps/mobile/src/components/ui/Dialog.tsx +++ b/apps/mobile/src/components/ui/Dialog.tsx @@ -3,38 +3,19 @@ import type { ConfirmDialogRequest, TextInputDialogRequest } from "./Dialog.type export type { ConfirmDialogRequest, TextInputDialogRequest } from "./Dialog.types"; -type PendingDialogCancel = () => void; - -let pendingDialogCancel: PendingDialogCancel | undefined; - -function replacePendingDialogCancel(next: PendingDialogCancel | undefined) { - const previous = pendingDialogCancel; - pendingDialogCancel = next; - if (previous === undefined) return; - // Defer so a cancel handler that opens another dialog replaces `next` cleanly. - queueMicrotask(() => { - if (pendingDialogCancel === previous) return; - previous(); - }); -} - -/** Tracks cancel for the active confirm/prompt; calling it is idempotent. */ function beginTrackedDialog(onCancel: (() => void) | undefined) { let finished = false; const finish = (action?: () => void) => { if (finished) return; finished = true; - if (pendingDialogCancel === cancel) pendingDialogCancel = undefined; action?.(); }; const cancel = () => finish(onCancel); const complete = (action: () => void) => finish(action); - replacePendingDialogCancel(cancel); return { cancel, complete }; } export function alert(...args: Parameters): void { - replacePendingDialogCancel(undefined); Alert.alert(...args); }