From f829c05943e53e2d2ce07c234f50c50031d21ad8 Mon Sep 17 00:00:00 2001 From: Antony <97451137+TonybynMp4@users.noreply.github.com> Date: Fri, 6 Nov 2026 02:40:10 +0100 Subject: [PATCH 001/181] feat(gitlab): reviews can request changes (#30549) Co-authored-by: Claude Opus 5.5 Co-authored-by: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> --- .../src/server/GitLabPullRequestCli.test.ts | 44 ++++++++++ .../src/server/GitLabPullRequestCli.ts | 81 +++++++++++++++++-- .../server/GitLabPullRequestProvider.test.ts | 4 +- .../src/server/GitLabPullRequestProvider.ts | 3 +- .../src/server/gitLabMergeRequestJson.ts | 22 +++++ 5 files changed, 145 insertions(+), 9 deletions(-) diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts index d51d952f3109e..8e19295cdbde8 100644 --- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts @@ -1421,6 +1421,50 @@ layer("GitLabPullRequestCli.layer", (it) => { }), ); + it.effect("requests changes as a reviewer and reports what GitLab refused", () => + Effect.gen(function* () { + mockedExecute + .mockReturnValueOnce(Effect.succeed(output(JSON.stringify({ username: "bilal" })))) + .mockReturnValueOnce( + Effect.succeed( + output(JSON.stringify({ data: { mergeRequestSetReviewers: { errors: [] } } })), + ), + ) + .mockReturnValueOnce( + Effect.succeed( + output( + JSON.stringify({ + data: { mergeRequestRequestChanges: { errors: ["Merge request is locked"] } }, + }), + ), + ), + ); + const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli; + + const error = yield* Effect.flip( + cli.submitReview({ + cwd: "/w", + repository: "acme/web", + number: 7, + verdict: "request-changes", + body: "Needs work", + comments: [{ path: "src/a.ts", position: { kind: "added", newLine: 4 }, body: "nit" }], + }), + ); + + expect(mockedExecute).toHaveBeenCalledTimes(3); + const target = { projectPath: "acme/web", iid: "7" }; + const setReviewers = JSON.parse(callAt(1).stdin ?? ""); + expect(setReviewers.query).toContain("operationMode: APPEND"); + expect(setReviewers.variables).toEqual({ ...target, reviewers: ["bilal"] }); + const requestChanges = JSON.parse(callAt(2).stdin ?? ""); + expect(requestChanges.query).toContain("mergeRequestRequestChanges"); + expect(requestChanges.variables).toEqual(target); + assert.strictEqual(error._tag, "GitLabMutationRefusedError"); + expect(error.detail).toBe("GitLab refused it: Merge request is locked"); + }), + ); + it.effect("removes an award by listing them and deleting the reader's own id", () => Effect.gen(function* () { mockedExecute.mockReturnValueOnce( diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts index 2572fcd025327..43f54b1651cd3 100644 --- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts +++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts @@ -51,6 +51,7 @@ import { decodeMergeRequestListJson, decodeMergeRequestFileStatsJson, decodeMergeRequestStatsJson, + decodeMutationErrorsJson, decodeNotesJson, decodeOwnAwardIdJson, decodePipelineStageChecksJson, @@ -204,6 +205,34 @@ export class GitLabDiffFileContentsUnavailableError extends Schema.TaggedError()( + "GitLabMutationRefusedError", + { + command: Schema.Literal("glab"), + cwd: Schema.String, + operation: Schema.String, + reasons: Schema.Array(Schema.String), + }, +) { + get detail(): string { + return `GitLab refused it: ${this.reasons.join("; ")}`; + } + + override get message(): string { + return `GitLab CLI failed in ${this.operation}: ${this.detail}`; + } +} + +const SET_SELF_AS_REVIEWER_MUTATION = `mutation($projectPath: ID!, $iid: String!, $reviewers: [String!]!) { + mergeRequestSetReviewers( + input: { projectPath: $projectPath, iid: $iid, reviewerUsernames: $reviewers, operationMode: APPEND } + ) { errors } +}`; + +const REQUEST_CHANGES_MUTATION = `mutation($projectPath: ID!, $iid: String!) { + mergeRequestRequestChanges(input: { projectPath: $projectPath, iid: $iid }) { errors } +}`; + export class GitLabBranchDeletionRefusedError extends Schema.TaggedError()( "GitLabBranchDeletionRefusedError", { @@ -266,7 +295,8 @@ export type GitLabPullRequestCliError = | GitLabDiffCommitParentUnavailableError | GitLabDiffFileContentsUnavailableError | GitLabDiffRefsUnavailableError - | GitLabViewerUnavailableError; + | GitLabViewerUnavailableError + | GitLabMutationRefusedError; /** GitLab's `per_page` limit. */ const MAX_PAGE_SIZE = 100; @@ -1454,6 +1484,28 @@ export const make = Effect.gen(function* () { }), ); + const graphqlMutation = (input: { + readonly cwd: string; + readonly host?: string | undefined; + readonly operation: string; + readonly query: string; + readonly variables: Record; + }) => + graphqlRead({ ...input, decode: decodeMutationErrorsJson }).pipe( + Effect.flatMap((reasons) => + reasons.length === 0 + ? Effect.void + : Effect.fail( + new GitLabMutationRefusedError({ + command: "glab", + cwd: input.cwd, + operation: input.operation, + reasons, + }), + ), + ), + ); + const graphqlListPage = (input: { readonly cwd: string; readonly host?: string | undefined; @@ -2337,10 +2389,29 @@ export const make = Effect.gen(function* () { submitReview: Effect.fn("GitLabPullRequestCli.submitReview")(function* (input) { const project = projectPath(input.repository); const mergeRequest = `projects/${project}/merge_requests/${input.number}`; - // GitLab has no pending review to attach comments to, so a review is replayed as the - // requests it is made of: the line comments, then the summary, then the verdict. A - // failure part-way therefore leaves what was already posted in place, which is why - // the verdict goes last — a half-sent review is never an approval. + // GitLab has no pending review, so a review is replayed as separate requests and a failure + // leaves earlier ones posted. Requesting changes (GitLab 18.9+) goes first so an older + // server fails before any comment lands; approval goes last so a half-sent review never + // approves. + if (input.verdict === "request-changes") { + // GitLab keeps the verdict on the reviewer, so the viewer joins the reviewers first. + const viewer = yield* viewerUsername(input); + const target = { projectPath: input.repository, iid: String(input.number) }; + yield* graphqlMutation({ + cwd: input.cwd, + host: input.host, + operation: "submitReview", + query: SET_SELF_AS_REVIEWER_MUTATION, + variables: { ...target, reviewers: [viewer] }, + }); + yield* graphqlMutation({ + cwd: input.cwd, + host: input.host, + operation: "submitReview", + query: REQUEST_CHANGES_MUTATION, + variables: target, + }); + } if (input.comments.length > 0) { const refs = yield* getDiffRefs(input); yield* Effect.forEach( diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts index d5e5793c68b8b..e2adb243b9703 100644 --- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts @@ -143,7 +143,7 @@ describe("gitLabViewerPermissions", () => { ], comment: true, resolve: true, - verdicts: ["comment", "approve"], + verdicts: ["comment", "approve", "request-changes"], requestReviewers: true, labels: true, updateMethods: ["rebase"], @@ -155,7 +155,7 @@ describe("gitLabViewerPermissions", () => { actions: ["ready", "draft", "close", "reopen"], comment: true, resolve: true, - verdicts: ["comment", "approve"], + verdicts: ["comment", "approve", "request-changes"], requestReviewers: true, labels: false, }); diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts index 6839e7febd0a9..c7a38794ee6fa 100644 --- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts +++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts @@ -39,8 +39,7 @@ const CAPABILITIES: PullRequestCapabilities = { inlineComment: true, reply: true, resolve: true, - // GitLab has no requested-changes verdict. - verdicts: ["comment", "approve"], + verdicts: ["comment", "approve", "request-changes"], }, reviewers: { request: true, listCandidates: true }, labels: true, diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts index 770712c2397d0..18366b536786f 100644 --- a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts +++ b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts @@ -1712,6 +1712,28 @@ export function decodeGraphqlListSupportJson(raw: string): Result.Result 17 || (major === 17 && minor >= 9)); } +const decodeMutationPayloads = decodeJsonResult( + Schema.Struct({ + data: Schema.Record( + Schema.String, + Schema.NullOr( + Schema.Struct({ errors: Schema.optional(Schema.NullOr(Schema.Array(Schema.String))) }), + ), + ), + }), +); + +/** GitLab answers a refused mutation with HTTP 200 and the reasons in each payload's `errors`. */ +export function decodeMutationErrorsJson( + raw: string, +): Result.Result, DecodeFailure> { + const decoded = decodeMutationPayloads(raw); + if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure); + return Result.succeed( + Object.values(decoded.success.data).flatMap((payload) => payload?.errors ?? []), + ); +} + /** * Line counts for merge requests of one project. The REST listing carries no line counts, and * reading each diff to count them would cost a request per row, so GraphQL's per-merge-request From e4ff5da0d344909de1d80eff73803d9924cd7aaa Mon Sep 17 00:00:00 2001 From: Antony <97451137+TonybynMp4@users.noreply.github.com> Date: Fri, 6 Nov 2026 02:41:01 +0100 Subject: [PATCH 002/181] feat(pull-requests): PR composers complete #123 and GitLab !123 references (#30857) Co-authored-by: Claude Opus 5.5 Co-authored-by: maria-rcks Co-authored-by: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> --- .../PullRequestCompletionSuggestions.tsx | 105 +++++++++ .../PullRequestDiscussionScreen.tsx | 16 +- .../pull-requests/PullRequestEditScreen.tsx | 16 +- .../PullRequestInlineCommentScreen.tsx | 16 +- .../PullRequestMentionSuggestions.tsx | 65 ------ .../pull-requests/PullRequestReviewSheet.tsx | 16 +- .../usePullRequestCompletions.ts | 82 +++++++ .../pull-requests/usePullRequestMentions.ts | 73 ------- .../pullRequest/PullRequestService.test.ts | 44 ++++ .../src/pullRequest/PullRequestService.ts | 31 ++- .../diffs/DiffCommentAnnotation.tsx | 8 +- .../pullRequest/PullRequestCodeTab.tsx | 8 +- .../pullRequest/PullRequestCommentForm.tsx | 4 +- .../pullRequest/PullRequestComposer.tsx | 4 +- .../pullRequest/PullRequestDetailPanel.tsx | 4 +- .../PullRequestGuideTab.browser.test.tsx | 2 +- .../pullRequest/PullRequestGuideTab.tsx | 8 +- ...PullRequestMarkdownEditor.browser.test.tsx | 23 +- .../pullRequest/PullRequestMarkdownEditor.tsx | 8 +- .../PullRequestMarkdownTextarea.tsx | 200 ++++++++++++------ .../PullRequestReviewAnnotation.tsx | 10 +- .../PullRequestReviewForm.browser.test.tsx | 2 +- .../pullRequest/PullRequestReviewForm.tsx | 8 +- .../pullRequest/PullRequestSummaryTab.tsx | 14 +- .../pullRequest/PullRequestTimelineTab.tsx | 10 +- .../pullRequest/guide/GuideExcerpt.tsx | 6 +- apps/web/src/state/pullRequests.ts | 1 + packages/contracts/src/pullRequest.ts | 24 ++- .../src/pullRequestComposerTrigger.test.ts | 88 ++++++-- .../shared/src/pullRequestComposerTrigger.ts | 125 +++++++++-- .../server/AzureDevOpsPullRequestProvider.ts | 1 + .../server/BitbucketPullRequestProvider.ts | 1 + .../src/server/PullRequestProvider.ts | 16 ++ .../src/server/ForgejoPullRequestProvider.ts | 1 + .../src/server/GitCafePullRequestProvider.ts | 1 + .../schema/github.graphql.ts | 11 + .../src/server/GitHubPullRequestApi.test.ts | 37 ++++ .../src/server/GitHubPullRequestApi.ts | 48 ++++- .../src/server/GitHubPullRequestProvider.ts | 6 + .../src/server/gitHubPullRequestJson.test.ts | 36 ++++ .../src/server/gitHubPullRequestJson.ts | 61 ++++++ .../src/server/pullRequestReads.graphql | 37 ++++ .../src/server/pullRequestReads.graphql.ts | 111 +++++++++- .../src/server/GitLabPullRequestCli.test.ts | 49 +++++ .../src/server/GitLabPullRequestCli.ts | 128 ++++++++++- .../src/server/GitLabPullRequestProvider.ts | 12 ++ .../src/server/gitLabMergeRequestJson.test.ts | 23 ++ .../src/server/gitLabMergeRequestJson.ts | 35 +++ 48 files changed, 1308 insertions(+), 327 deletions(-) create mode 100644 apps/mobile/src/features/pull-requests/PullRequestCompletionSuggestions.tsx delete mode 100644 apps/mobile/src/features/pull-requests/PullRequestMentionSuggestions.tsx create mode 100644 apps/mobile/src/features/pull-requests/usePullRequestCompletions.ts delete mode 100644 apps/mobile/src/features/pull-requests/usePullRequestMentions.ts diff --git a/apps/mobile/src/features/pull-requests/PullRequestCompletionSuggestions.tsx b/apps/mobile/src/features/pull-requests/PullRequestCompletionSuggestions.tsx new file mode 100644 index 0000000000000..2d403d68727d7 --- /dev/null +++ b/apps/mobile/src/features/pull-requests/PullRequestCompletionSuggestions.tsx @@ -0,0 +1,105 @@ +import { Pressable, ScrollView, StyleSheet, View } from "react-native"; + +import { AppText as Text } from "../../components/ui/AppText"; +import { GlassSurface } from "../../components/ui/GlassSurface"; +import { PullRequestAvatar } from "./PullRequestPresentation"; +import type { PullRequestCompletion } from "@t3tools/shared/pullRequestComposerTrigger"; +import type { usePullRequestCompletions } from "./usePullRequestCompletions"; + +const COPY = { + mention: { + label: "Mention a user", + pending: "Searching users...", + failed: "Couldn't search users on the host", + none: "No matching users", + }, + reference: { + label: "Reference an issue or change request", + pending: "Searching...", + failed: "Couldn't search the host", + none: "No matching issues or change requests", + }, +} as const; + +const STATE_LABEL = { open: "Open", closed: "Closed", merged: "Merged" } as const; + +function CompletionRow({ completion }: { readonly completion: PullRequestCompletion }) { + if (completion.kind === "mention") { + const { actor } = completion; + return ( + <> + + + {actor.login} + + {actor.name && actor.name !== actor.login ? ( + + {actor.name} + + ) : null} + + ); + } + const { candidate } = completion; + return ( + <> + + {candidate.reference} + + + {candidate.title} + + + {STATE_LABEL[candidate.state]} + + + ); +} + +/** The `@`, `#` and `!` suggestions for a pull request text input, rendered just above it. */ +export function PullRequestCompletionSuggestions({ + completions, +}: { + readonly completions: ReturnType; +}) { + if (completions.kind === null) return null; + const copy = COPY[completions.kind]; + return ( + + {completions.candidates.length > 0 ? ( + + {completions.candidates.map((completion, index) => ( + completions.select(completion)} + className="flex-row items-center gap-2.5 border-border px-3.5 py-2.5 active:opacity-60" + style={{ + borderBottomWidth: + index === completions.candidates.length - 1 ? 0 : StyleSheet.hairlineWidth, + }} + > + + + ))} + + ) : ( + + + {copy[completions.isLoading ? "pending" : completions.failed ? "failed" : "none"]} + + + )} + + ); +} diff --git a/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx index e3ed028b592e5..9e4231ad65dd2 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx @@ -26,8 +26,8 @@ import { PullRequestCommentFooter } from "./PullRequestReactions"; import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff"; import { usePullRequestPermissions } from "./usePullRequestPermissions"; import { pullRequestReviewKey } from "./pullRequestReviewDrafts"; -import { PullRequestMentionSuggestions } from "./PullRequestMentionSuggestions"; -import { usePullRequestMentions } from "./usePullRequestMentions"; +import { PullRequestCompletionSuggestions } from "./PullRequestCompletionSuggestions"; +import { usePullRequestCompletions } from "./usePullRequestCompletions"; export function PullRequestDiscussionScreen({ route, @@ -57,12 +57,12 @@ function Discussion({ params }: { params: PullRequestParams & { readonly discuss const loadMore = useAtomCommand(composerPullRequests.threadComments, { reportFailure: false }); const thread = activity.data?.reviewThreads.find((thread) => thread.id === params.discussionId); const [body, setBody] = useState(""); - const mentions = usePullRequestMentions({ + const completions = usePullRequestCompletions({ environmentId: params.environmentId, projectId: params.projectId, value: body, onChangeValue: setBody, - enabled: detail.data?.capabilities.mentions === true, + support: detail.data?.capabilities ?? null, }); const [extra, setExtra] = useState([]); const [cursor, setCursor] = useState(); @@ -235,7 +235,7 @@ function Discussion({ params }: { params: PullRequestParams & { readonly discuss className="absolute inset-x-4 bottom-0 gap-2" style={{ paddingBottom: bottomInset }} > - + setComposerHeight(event.nativeEvent.layout.height)} @@ -243,9 +243,9 @@ function Discussion({ params }: { params: PullRequestParams & { readonly discuss > (null); const value = draft ?? original ?? ""; - const mentions = usePullRequestMentions({ + const completions = usePullRequestCompletions({ environmentId: params.environmentId, projectId: params.projectId, value: value, onChangeValue: setDraft, - enabled: params.field !== "title" && pr?.capabilities.mentions === true, + support: params.field === "title" ? null : (pr?.capabilities ?? null), }); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); @@ -140,12 +140,12 @@ export function PullRequestEditScreen({ route }: StaticScreenProps } > - + - + ; -}) { - if (!mentions.open) return null; - return ( - - {mentions.candidates.length > 0 ? ( - - {mentions.candidates.map((actor, index) => ( - mentions.select(actor)} - className="flex-row items-center gap-2.5 border-border px-3.5 py-2.5 active:opacity-60" - style={{ - borderBottomWidth: - index === mentions.candidates.length - 1 ? 0 : StyleSheet.hairlineWidth, - }} - > - - - {actor.login} - - {actor.name && actor.name !== actor.login ? ( - - {actor.name} - - ) : null} - - ))} - - ) : ( - - - {mentions.isLoading - ? "Searching users..." - : mentions.failed - ? "Couldn't search users on the host" - : "No matching users"} - - - )} - - ); -} diff --git a/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx b/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx index 3b5fa30d181da..ab121d0c41e7d 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx @@ -19,8 +19,8 @@ import { useAtomCommand } from "../../state/use-atom-command"; import { PullRequestSheetContent as SheetContent } from "./PullRequestSheetContent"; import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff"; import { usePullRequestPermissions } from "./usePullRequestPermissions"; -import { PullRequestMentionSuggestions } from "./PullRequestMentionSuggestions"; -import { usePullRequestMentions } from "./usePullRequestMentions"; +import { PullRequestCompletionSuggestions } from "./PullRequestCompletionSuggestions"; +import { usePullRequestCompletions } from "./usePullRequestCompletions"; function useActionSubmission(params: PullRequestParams) { const navigation = useNavigation(); @@ -83,12 +83,12 @@ export function PullRequestReviewSheet({ ...draft, ...(params.mode === "review" ? { summary: body } : { comment: body }), })); - const mentions = usePullRequestMentions({ + const completions = usePullRequestCompletions({ environmentId: params.environmentId, projectId: params.projectId, value: body, onChangeValue: setBody, - enabled: result.data?.capabilities.mentions === true, + support: result.data?.capabilities ?? null, }); const stale = store.draft.comments.some((comment) => comment.headSha !== result.data?.headSha); const [requestedVerdict, setRequestedVerdict] = useState("comment"); @@ -178,12 +178,12 @@ export function PullRequestReviewSheet({ {reviewing ? "Summary" : "Comment"} - + void; + /** What the pull request's host completes (its `capabilities`); null where the field takes none. */ + readonly support: PullRequestCompletionSupport | null; +}) { + const [selection, setSelection] = useState<{ start: number; end: number } | null>(null); + // Set only right after an insertion, so the native input keeps its own caret otherwise. + const [placed, setPlaced] = useState<{ start: number; end: number } | null>(null); + const trigger = + input.support === null || selection === null || selection.start !== selection.end + ? null + : detectPullRequestComposerTrigger(input.value, selection.start, input.support); + const key = pullRequestCompletionKey(trigger); + const sentKey = useDebouncedValue(key, 250); + const sent = + trigger === null ? undefined : debouncedPullRequestCompletionSearch(trigger, sentKey); + const hosted = useEnvironmentQuery( + trigger === null + ? null + : composerPullRequests.filterOptions({ + environmentId: EnvironmentId.make(input.environmentId), + input: + trigger.kind === "mention" + ? { + kind: "authors", + projectId: ProjectId.make(input.projectId), + ...(sent ? { query: sent } : {}), + } + : { + kind: "references", + projectId: ProjectId.make(input.projectId), + sigil: trigger.sigil, + ...(sent ? { query: sent } : {}), + }, + }), + ); + // Older answers stay useful while the debounced search catches up, narrowed to what is typed now. + const candidates = pullRequestCompletions(trigger, hosted.data, COMPLETION_SUGGESTION_LIMIT); + + return { + kind: trigger?.kind ?? null, + candidates, + isLoading: hosted.isPending || sentKey !== key, + failed: hosted.error !== null, + selection: placed ?? undefined, + onSelectionChange: (event: TextInputSelectionChangeEvent) => { + setSelection(event.nativeEvent.selection); + setPlaced(null); + }, + onBlur: () => setSelection(null), + select: (completion: PullRequestCompletion) => { + if (trigger === null) return; + const next = insertPullRequestCompletion(input.value, trigger, completion.token); + input.onChangeValue(next.text); + setSelection({ start: next.cursor, end: next.cursor }); + setPlaced({ start: next.cursor, end: next.cursor }); + }, + }; +} diff --git a/apps/mobile/src/features/pull-requests/usePullRequestMentions.ts b/apps/mobile/src/features/pull-requests/usePullRequestMentions.ts deleted file mode 100644 index 8c2a759bef812..0000000000000 --- a/apps/mobile/src/features/pull-requests/usePullRequestMentions.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { EnvironmentId, ProjectId, type PullRequestActor } from "@t3tools/contracts"; -import { - detectPullRequestMention, - insertPullRequestMention, - narrowPullRequestMentions, -} from "@t3tools/shared/pullRequestComposerTrigger"; -import { useState } from "react"; -import type { TextInputSelectionChangeEvent } from "react-native"; - -import { composerPullRequests } from "../../state/pull-requests"; -import { useEnvironmentQuery } from "../../state/query"; -import { useDebouncedValue } from "../../state/queries"; - -const MENTION_SUGGESTION_LIMIT = 6; - -/** Completes `@login` in a pull request text input from the repository's users. */ -export function usePullRequestMentions(input: { - readonly environmentId: string; - readonly projectId: string; - readonly value: string; - readonly onChangeValue: (value: string) => void; - /** The pull request's host completes mentions (`capabilities.mentions`), and the field takes them. */ - readonly enabled: boolean; -}) { - const [selection, setSelection] = useState<{ start: number; end: number } | null>(null); - // Set only right after an insertion, so the native input keeps its own caret otherwise. - const [placed, setPlaced] = useState<{ start: number; end: number } | null>(null); - const trigger = - !input.enabled || selection === null || selection.start !== selection.end - ? null - : detectPullRequestMention(input.value, selection.start); - const typed = trigger?.query ?? ""; - const search = typed === "" ? undefined : typed.slice(0, 100); - const sent = useDebouncedValue(search, 250); - const hosted = useEnvironmentQuery( - trigger === null - ? null - : composerPullRequests.filterOptions({ - environmentId: EnvironmentId.make(input.environmentId), - input: { - kind: "authors", - projectId: ProjectId.make(input.projectId), - ...(sent ? { query: sent } : {}), - }, - }), - ); - // Older answers stay useful while the debounced search catches up, narrowed to what is typed now. - const candidates = narrowPullRequestMentions( - hosted.data?.authors ?? [], - typed, - MENTION_SUGGESTION_LIMIT, - ); - - return { - open: trigger !== null, - candidates, - isLoading: hosted.isPending || sent !== search, - failed: hosted.error !== null, - selection: placed ?? undefined, - onSelectionChange: (event: TextInputSelectionChangeEvent) => { - setSelection(event.nativeEvent.selection); - setPlaced(null); - }, - onBlur: () => setSelection(null), - select: (actor: PullRequestActor) => { - if (trigger === null) return; - const next = insertPullRequestMention(input.value, trigger, actor.login); - input.onChangeValue(next.text); - setSelection({ start: next.cursor, end: next.cursor }); - setPlaced({ start: next.cursor, end: next.cursor }); - }, - }; -} diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts index 7a43394c2a2b7..e559bc84dd978 100644 --- a/apps/server/src/pullRequest/PullRequestService.test.ts +++ b/apps/server/src/pullRequest/PullRequestService.test.ts @@ -1067,6 +1067,50 @@ it.effect("puts the author a query names exactly ahead of those it only begins", }), ); +it.effect("ranks references by number, keeping the host's recent-first order", () => + Effect.gen(function* () { + const service = yield* makeService({ + projects: [ + project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }), + project({ id: "p2", title: "tree", workspaceRoot: "/b", repository: "pingdotgg/t3code" }), + ], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + searchRepositoryReferences: () => + Effect.succeed({ + items: [ + { reference: "#129", kind: "issue", number: 129, title: "Newest", state: "open" }, + { + reference: "#7", + kind: "issue", + number: 7, + title: "Fix #12 again", + state: "open", + }, + { + reference: "#12", + kind: "change-request", + number: 12, + title: "Exact", + state: "merged", + }, + { reference: "#120", kind: "issue", number: 120, title: "Older", state: "closed" }, + ], + truncated: false, + }), + }), + ], + }); + + const result = yield* service.filterOptions({ kind: "references", query: "12" }); + + assert.deepStrictEqual( + result.references.map((candidate) => candidate.reference), + ["#12", "#129", "#120", "#7"], + ); + }), +); + it.effect("tries another workspace on the same host for the viewer", () => Effect.gen(function* () { const service = yield* makeService({ diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index 6600f6810bce7..80d6d101336eb 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -47,6 +47,7 @@ import { type PullRequestFilterOptions, type PullRequestFilterOptionsInput, type PullRequestActor, + type PullRequestReferenceCandidate, type PullRequestLabel, type PullRequestListStatsResult, type PullRequestProviderSummary, @@ -622,6 +623,14 @@ function withRateLimitBackoff( api.searchRepositoryAuthors, ), }), + ...(api.searchRepositoryReferences === undefined + ? {} + : { + searchRepositoryReferences: interactive( + "searchRepositoryReferences", + api.searchRepositoryReferences, + ), + }), replyToThread: interactive("replyToThread", api.replyToThread), setReaction: interactive("setReaction", api.setReaction), setThreadResolution: interactive("setThreadResolution", api.setThreadResolution), @@ -643,6 +652,8 @@ function rankFilterOptions( readonly query: string | undefined; readonly keyOf: (item: A) => string; readonly textsOf: (item: A) => ReadonlyArray; + /** Ties keep the hosts' order instead of sorting by key. */ + readonly hostOrder?: boolean; }, ): { readonly items: ReadonlyArray; readonly truncated: boolean } { const query = input.query?.trim().toLowerCase() ?? ""; @@ -669,7 +680,9 @@ function rankFilterOptions( .toSorted( (left, right) => left.score - right.score || - left.key.localeCompare(right.key, undefined, { sensitivity: "base" }), + (input.hostOrder === true + ? 0 + : left.key.localeCompare(right.key, undefined, { sensitivity: "base" })), ); return { items: ranked.slice(0, FILTER_OPTIONS_LIMIT).map(({ item }) => item), @@ -2578,7 +2591,19 @@ export const make = Effect.gen(function* () { keyOf: (label) => label.name, textsOf: (label) => [label.name], }); - return { labels: items, authors: [], truncated }; + return { labels: items, authors: [], references: [], truncated }; + } + if (input.kind === "references") { + const pages = yield* gather((project) => + project.api.searchRepositoryReferences?.({ ...refOf(project), sigil: input.sigil }), + ); + const { items, truncated } = rankFilterOptions(pages, { + query: input.query, + keyOf: (candidate) => candidate.reference, + textsOf: (candidate) => [String(candidate.number), candidate.title], + hostOrder: true, + }); + return { labels: [], authors: [], references: items, truncated }; } const pages = yield* gather((project) => project.api.searchRepositoryAuthors?.(refOf(project)), @@ -2588,7 +2613,7 @@ export const make = Effect.gen(function* () { keyOf: (author) => author.login, textsOf: (author) => [author.login, author.name], }); - return { labels: [], authors: items, truncated }; + return { labels: [], authors: items, references: [], truncated }; }); const labelCandidates: PullRequestService["Service"]["labelCandidates"] = (input) => diff --git a/apps/web/src/components/diffs/DiffCommentAnnotation.tsx b/apps/web/src/components/diffs/DiffCommentAnnotation.tsx index f012daf098d11..1c7b6eb5273ca 100644 --- a/apps/web/src/components/diffs/DiffCommentAnnotation.tsx +++ b/apps/web/src/components/diffs/DiffCommentAnnotation.tsx @@ -5,7 +5,7 @@ import { useLayoutEffect, useRef, useState, type ReactNode } from "react"; import { Button } from "~/components/ui/button"; import { PullRequestMarkdownTextarea, - type PullRequestMentionScope, + type PullRequestCompletionScope, } from "~/components/pullRequest/PullRequestMarkdownTextarea"; import { SpeechTextField, @@ -41,7 +41,7 @@ interface DiffCommentAnnotationProps { secondaryAction?: DiffCommentSecondaryAction; focusOnMount?: boolean; /** Set only for pull request comments, where `@` completes the repository's users. */ - mentionScope?: PullRequestMentionScope | null; + completionScope?: PullRequestCompletionScope | null; } export function DiffCommentAnnotation({ @@ -60,7 +60,7 @@ export function DiffCommentAnnotation({ pending = false, secondaryAction, focusOnMount = true, - mentionScope = null, + completionScope = null, }: DiffCommentAnnotationProps) { const [localDraftText, setLocalDraftText] = useState(""); const displayedText = kind === "draft" && !onTextChange ? localDraftText : text; @@ -129,7 +129,7 @@ export function DiffCommentAnnotation({ > addSelectionToAgent({ comment, request }, { keepGuide: true }) } diff --git a/apps/web/src/components/pullRequest/PullRequestGuideTab.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestGuideTab.browser.test.tsx index d1a1a249d7833..127e4b4cc9ca8 100644 --- a/apps/web/src/components/pullRequest/PullRequestGuideTab.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestGuideTab.browser.test.tsx @@ -55,7 +55,7 @@ it("keeps Try again inside a short panel when a failed guide has long diagnostic active canComment={false} rangeComments={false} - mentionScope={null} + completionScope={null} onAskAboutLines={null} onAskAboutStop={null} onFinishReview={null} diff --git a/apps/web/src/components/pullRequest/PullRequestGuideTab.tsx b/apps/web/src/components/pullRequest/PullRequestGuideTab.tsx index 8952c785a9657..fda10783728c6 100644 --- a/apps/web/src/components/pullRequest/PullRequestGuideTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestGuideTab.tsx @@ -17,7 +17,7 @@ import { usePendingReviewComments, usePullRequestReviewStore, } from "./pullRequestReviewStore"; -import type { PullRequestMentionScope } from "./PullRequestMarkdownTextarea"; +import type { PullRequestCompletionScope } from "./PullRequestMarkdownTextarea"; export function PullRequestGuideTab({ environmentId, @@ -27,7 +27,7 @@ export function PullRequestGuideTab({ active, canComment, rangeComments, - mentionScope, + completionScope, onAskAboutLines, onAskAboutStop, onFinishReview, @@ -41,7 +41,7 @@ export function PullRequestGuideTab({ active: boolean; canComment: boolean; rangeComments: boolean; - mentionScope: PullRequestMentionScope | null; + completionScope: PullRequestCompletionScope | null; onAskAboutLines: ((comment: ReviewCommentContext, request: string) => void) | null; onAskAboutStop: | ((stop: PullRequestReviewGuideStop, index: number, question: string) => void) @@ -65,7 +65,7 @@ export function PullRequestGuideTab({ : { canComment, rangeComments, - mentionScope, + completionScope, pending, onComment: ({ path, oldPath, position, startPosition, body }) => addComment(reviewKey, { diff --git a/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.browser.test.tsx index 31dfb68338de6..1f946c684f6b1 100644 --- a/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.browser.test.tsx @@ -37,6 +37,13 @@ vi.mock(import("~/state/pullRequests"), async (original) => ({ { login: "julius", name: "Julius", avatarUrl: null }, { login: "theo", name: "Theo", avatarUrl: null }, ], + references: + targets.length === 0 + ? [] + : [ + { reference: "#12", kind: "issue", number: 12, title: "Crash", state: "open" }, + { reference: "!12", kind: "change-request", number: 12, title: "Fix", state: "open" }, + ], error: null, isPending: false, }), @@ -61,7 +68,11 @@ async function openEditor(options?: { value?: string; allowEmpty?: boolean }) { value={options?.value ?? "Original description"} cwd="/repo" environmentId={secondary} - mentionScope={{ environmentId: secondary, projectId: ProjectId.make("project") }} + completionScope={{ + environmentId: secondary, + projectId: ProjectId.make("project"), + support: { mentions: true, referenceSigils: ["#", "!"] }, + }} label="Pull request description" saving={false} allowEmpty={options?.allowEmpty ?? false} @@ -106,7 +117,7 @@ it("keeps an edited draft through revocation and saves it after access returns w expect(onSave).toHaveBeenCalledExactlyOnceWith("Keep these unsaved edits"); }); -it("completes an @mention on Enter and closes the list on Escape until the next keystroke", async () => { +it("completes @mentions and !references on Enter, and Escape closes the list until the next keystroke", async () => { setup(); permissions.allowed.add(secondary); await using screen = await openEditor({ value: "" }); @@ -122,9 +133,13 @@ it("completes an @mention on Enter and closes the list on Escape until the next await expect.element(page.getByRole("option", { name: /theo/ })).toBeVisible(); await userEvent.keyboard("{Escape}"); await expect.element(page.getByRole("listbox")).not.toBeInTheDocument(); - expect(onCancel).not.toHaveBeenCalled(); - await userEvent.type(textarea, "t"); await expect.element(page.getByRole("option", { name: /theo/ })).toBeVisible(); + + await userEvent.type(textarea, " fixes !1"); + await expect.element(page.getByRole("option", { name: /Fix/ })).toBeVisible(); + await userEvent.keyboard("{Enter}"); + expect(textarea.value).toBe("Thanks @julius and @t fixes !12 "); + expect(onCancel).not.toHaveBeenCalled(); expect(onSave).not.toHaveBeenCalled(); }); diff --git a/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.tsx b/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.tsx index aeb834ae31251..2ff293f95717f 100644 --- a/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.tsx +++ b/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.tsx @@ -13,14 +13,14 @@ import { Toggle, ToggleGroup } from "../ui/toggle-group"; import { PullRequestMarkdown } from "./PullRequestMarkdown"; import { PullRequestMarkdownTextarea, - type PullRequestMentionScope, + type PullRequestCompletionScope, } from "./PullRequestMarkdownTextarea"; export function PullRequestMarkdownEditor({ value, cwd, environmentId, - mentionScope, + completionScope, threadRef = null, placeholder, label, @@ -33,7 +33,7 @@ export function PullRequestMarkdownEditor({ readonly value: string; readonly cwd: string; readonly environmentId: EnvironmentId; - readonly mentionScope: PullRequestMentionScope | null; + readonly completionScope: PullRequestCompletionScope | null; readonly threadRef?: ScopedThreadRef | null; readonly placeholder?: string | undefined; readonly label: string; @@ -110,7 +110,7 @@ export function PullRequestMarkdownEditor({ , environmentId: EnvironmentId, reference: PullRequestRef, -): PullRequestMentionScope | null { - return detail.capabilities.mentions === true - ? { environmentId, projectId: reference.projectId } +): PullRequestCompletionScope | null { + const { mentions, referenceSigils } = detail.capabilities; + return mentions === true || (referenceSigils?.length ?? 0) > 0 + ? { environmentId, projectId: reference.projectId, support: { mentions, referenceSigils } } : null; } - -const MENTION_SEARCH_DEBOUNCE_MS = 200; -const MENTION_SUGGESTION_LIMIT = 8; // About a full list of suggestions. The popup fits itself to the space it opens into, so it never // flips once results grow it; the side is picked up front from the room a full list needs. const SUGGESTION_LIST_HEIGHT = 320; @@ -50,43 +56,117 @@ function suggestionSide(target: HTMLTextAreaElement): "top" | "bottom" { return below < SUGGESTION_LIST_HEIGHT && rect.top > below ? "top" : "bottom"; } -function useMentionCandidates(scope: PullRequestMentionScope | null, query: string | null) { - const typed = query ?? ""; - const search = typed === "" ? undefined : typed.slice(0, 100); - const sent = useDebouncedValue(search, MENTION_SEARCH_DEBOUNCE_MS); +const COMPLETION_SEARCH_DEBOUNCE_MS = 200; +const COMPLETION_SUGGESTION_LIMIT = 8; + +function useCompletions( + scope: PullRequestCompletionScope | null, + trigger: PullRequestComposerTrigger | null, +) { + const key = pullRequestCompletionKey(trigger); + const sentKey = useDebouncedValue(key, COMPLETION_SEARCH_DEBOUNCE_MS); + const sent = + trigger === null ? undefined : debouncedPullRequestCompletionSearch(trigger, sentKey); const hosted = usePullRequestFilterOptions( - scope === null || query === null + scope === null || trigger === null ? [] : [ { environmentId: scope.environmentId, - input: { - kind: "authors", - projectId: scope.projectId, - ...(sent ? { query: sent } : {}), - }, + input: + trigger.kind === "mention" + ? { kind: "authors", projectId: scope.projectId, ...(sent ? { query: sent } : {}) } + : { + kind: "references", + projectId: scope.projectId, + sigil: trigger.sigil, + ...(sent ? { query: sent } : {}), + }, }, ], ); // Older answers stay useful while the debounced search catches up, narrowed to what is typed now. + const completions = pullRequestCompletions(trigger, hosted, COMPLETION_SUGGESTION_LIMIT); return { - candidates: narrowPullRequestMentions(hosted.authors, typed, MENTION_SUGGESTION_LIMIT), - isPending: hosted.isPending || sent !== search, + completions, + isPending: hosted.isPending || sentKey !== key, failed: hosted.error !== null, }; } +function ReferenceStateIcon({ candidate }: { candidate: PullRequestReferenceCandidate }) { + const presentation = + candidate.kind === "change-request" + ? resolvePullRequestState({ state: candidate.state, isDraft: false }) + : candidate.state === "open" + ? { + label: "Open issue", + Icon: CircleDotIcon, + toneClassName: PULL_REQUEST_STATE_PRESENTATION.open.toneClassName, + } + : { + label: "Closed issue", + Icon: CircleCheckIcon, + toneClassName: PULL_REQUEST_STATE_PRESENTATION.merged.toneClassName, + }; + return ( + + ); +} + +function CompletionRow({ completion }: { completion: PullRequestCompletion }) { + if (completion.kind === "mention") { + const { actor } = completion; + return ( + <> + + {actor.login} + {actor.name && actor.name !== actor.login ? ( + {actor.name} + ) : null} + + ); + } + const { candidate } = completion; + return ( + <> + + {candidate.reference} + {candidate.title} + + ); +} + +const EMPTY_STATE = { + mention: { + label: "Mention a user", + pending: "Searching users...", + failed: "Couldn't search users on the host", + none: "No matching users", + }, + reference: { + label: "Reference an issue or change request", + pending: "Searching...", + failed: "Couldn't search the host", + none: "No matching issues or change requests", + }, +} as const; + function assignRef(ref: Ref | undefined, value: T | null) { if (typeof ref === "function") ref(value); else if (ref) ref.current = value; } -/** A markdown textarea for pull request text that completes `@login` from the repository's users. */ +/** A markdown textarea for pull request text that completes `@login`, `#123` and GitLab `!123`. */ export function PullRequestMarkdownTextarea({ ref, value, onValueChange, - mentionScope, + completionScope, onKeyDown, onSelect, onFocus, @@ -95,7 +175,7 @@ export function PullRequestMarkdownTextarea({ }: Omit & { readonly value: string; readonly onValueChange: (value: string) => void; - readonly mentionScope: PullRequestMentionScope | null; + readonly completionScope: PullRequestCompletionScope | null; }) { const listId = useId(); const [element, setElement] = useState(null); @@ -105,29 +185,30 @@ export function PullRequestMarkdownTextarea({ const [highlight, setHighlight] = useState({ query: "", index: 0 }); const trigger = - mentionScope === null || caret === null || props.readOnly + completionScope === null || caret === null || props.readOnly ? null - : detectPullRequestMention(value, caret); + : detectPullRequestComposerTrigger(value, caret, completionScope.support); const open = trigger !== null && trigger.rangeStart !== dismissedAt; - const { candidates, isPending, failed } = useMentionCandidates( - mentionScope, - open ? trigger.query : null, - ); + const { + completions: candidates, + isPending, + failed, + } = useCompletions(completionScope, open ? trigger : null); const activeIndex = trigger !== null && highlight.query === trigger.query ? Math.min(highlight.index, Math.max(0, candidates.length - 1)) : 0; const active = open ? candidates[activeIndex] : undefined; - const optionId = (login: string) => `${listId}-${login}`; + const optionId = (token: string) => `${listId}-${token}`; const syncCaret = (target: HTMLTextAreaElement) => { setSide(suggestionSide(target)); setCaret(target.selectionStart === target.selectionEnd ? target.selectionStart : null); }; - const select = (actor: PullRequestActor) => { + const select = (completion: PullRequestCompletion) => { if (trigger === null || element === null) return; - const next = insertPullRequestMention(value, trigger, actor.login); + const next = insertPullRequestCompletion(value, trigger, completion.token); flushSync(() => onValueChange(next.text)); element.setSelectionRange(next.cursor, next.cursor); setCaret(next.cursor); @@ -142,11 +223,11 @@ export function PullRequestMarkdownTextarea({ assignRef(ref, node); }} value={value} - role={mentionScope === null ? undefined : "combobox"} - aria-autocomplete={mentionScope === null ? undefined : "list"} - aria-expanded={mentionScope === null ? undefined : open} + role={completionScope === null ? undefined : "combobox"} + aria-autocomplete={completionScope === null ? undefined : "list"} + aria-expanded={completionScope === null ? undefined : open} aria-controls={open && candidates.length > 0 ? listId : undefined} - aria-activedescendant={active ? optionId(active.login) : undefined} + aria-activedescendant={active ? optionId(active.token) : undefined} onChange={(event) => { onValueChange(event.target.value); syncCaret(event.target); @@ -210,16 +291,21 @@ export function PullRequestMarkdownTextarea({ side={side} align="start" padding="compact" - width="sm" + width={trigger?.kind === "reference" ? "md" : "sm"} initialFocus={false} finalFocus={false} > {candidates.length > 0 ? ( -
- {candidates.map((actor, index) => ( +
+ {candidates.map((completion, index) => (
event.preventDefault()} - onClick={() => select(actor)} + onClick={() => select(completion)} > - - {actor.login} - {actor.name && actor.name !== actor.login ? ( - {actor.name} - ) : null} +
))}
) : (

- {isPending - ? "Searching users..." - : failed - ? "Couldn't search users on the host" - : "No matching users"} + { + EMPTY_STATE[trigger?.kind ?? "mention"][ + isPending ? "pending" : failed ? "failed" : "none" + ] + }

)} diff --git a/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx b/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx index 2fe3f96431b44..d2ae440fde9e8 100644 --- a/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx +++ b/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx @@ -32,7 +32,7 @@ import { PullRequestReactionBar } from "./PullRequestReactions"; import type { PendingReviewComment } from "./pullRequestReviewStore"; import { PullRequestMarkdownTextarea, - type PullRequestMentionScope, + type PullRequestCompletionScope, } from "./PullRequestMarkdownTextarea"; const CARD_CLASS = @@ -117,7 +117,7 @@ export function ReviewThreadCard({ canReact, environmentId, reference, - mentionScope, + completionScope, pending, fixPending, fixLabel = "Fix in a thread", @@ -137,7 +137,7 @@ export function ReviewThreadCard({ canReact: boolean; environmentId: EnvironmentId; reference: PullRequestRef; - mentionScope: PullRequestMentionScope | null; + completionScope: PullRequestCompletionScope | null; pending: boolean; fixPending?: boolean; fixLabel?: string; @@ -310,7 +310,7 @@ export function ReviewThreadCard({ value={comment.body} cwd={workspaceRoot} environmentId={environmentId} - mentionScope={mentionScope} + completionScope={completionScope} label="Edit comment" saving={savingEdit} onSave={(body) => void saveEdit(comment.id, body)} @@ -366,7 +366,7 @@ export function ReviewThreadCard({ readOnly={speech.freezesEditor} autoFocus size="sm" - mentionScope={mentionScope} + completionScope={completionScope} value={reply} placeholder="Reply" aria-label="Reply to this conversation" diff --git a/apps/web/src/components/pullRequest/PullRequestReviewForm.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestReviewForm.browser.test.tsx index 23c82d5c38dc9..eae69143d31ea 100644 --- a/apps/web/src/components/pullRequest/PullRequestReviewForm.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestReviewForm.browser.test.tsx @@ -37,7 +37,7 @@ it("submits only the line comments still in the draft when dictation finishes", active environmentId={EnvironmentId.make("test")} reference={reference} - mentionScope={null} + completionScope={null} term="pull request" verdicts={["comment"]} requestChangesSummaryRequired={false} diff --git a/apps/web/src/components/pullRequest/PullRequestReviewForm.tsx b/apps/web/src/components/pullRequest/PullRequestReviewForm.tsx index edf718d8489a3..5308c63208986 100644 --- a/apps/web/src/components/pullRequest/PullRequestReviewForm.tsx +++ b/apps/web/src/components/pullRequest/PullRequestReviewForm.tsx @@ -20,7 +20,7 @@ import { } from "./pullRequestReviewStore"; import { PullRequestMarkdownTextarea, - type PullRequestMentionScope, + type PullRequestCompletionScope, } from "./PullRequestMarkdownTextarea"; const VERDICTS: ReadonlyArray<{ @@ -53,7 +53,7 @@ export function PullRequestReviewForm({ environmentId, active, reference, - mentionScope, + completionScope, term, verdicts, requestChangesSummaryRequired, @@ -66,7 +66,7 @@ export function PullRequestReviewForm({ /** False while the form stays mounted but hidden; dictation is cancelled then. */ active: boolean; reference: PullRequestRef; - mentionScope: PullRequestMentionScope | null; + completionScope: PullRequestCompletionScope | null; /** The host's word for a change request, as in "pull request". */ term: string; verdicts: ReadonlyArray; @@ -157,7 +157,7 @@ export function PullRequestReviewForm({ <> boolean; readonly editingId: string | null; @@ -194,7 +194,7 @@ function CommentBody({ value={comment.body} cwd={editing.cwd} environmentId={editing.environmentId} - mentionScope={editing.mentionScope} + completionScope={editing.completionScope} threadRef={editing.threadRef} label="Edit comment" saving={editing.saving} @@ -584,11 +584,11 @@ export function PullRequestSummaryTab({ if (body !== description) void saveDescription(body); }; - const mentionScope = pullRequestMentionScope(detail, environmentId, reference); + const completionScope = pullRequestCompletionScope(detail, environmentId, reference); const commentEditing: CommentEditing = { cwd: detail.workspaceRoot, environmentId, - mentionScope, + completionScope, threadRef, canEdit: (comment) => canEditPullRequestComment(detail, comment), editingId: editingCommentId, @@ -845,7 +845,7 @@ export function PullRequestSummaryTab({ value={bodyScope.body} cwd={detail.workspaceRoot} environmentId={environmentId} - mentionScope={mentionScope} + completionScope={completionScope} threadRef={threadRef} label={`${capitalizeTerm(terminology.singular)} description`} placeholder={`Describe this ${terminology.singular}`} diff --git a/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx b/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx index 60357c75712a9..36dca98e23179 100644 --- a/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx @@ -60,8 +60,8 @@ import { } from "./pullRequestPresentation"; import { PullRequestGlyph } from "./pullRequestIcons"; import { - type PullRequestMentionScope, - pullRequestMentionScope, + type PullRequestCompletionScope, + pullRequestCompletionScope, } from "./PullRequestMarkdownTextarea"; import { LegendList, type LegendListRef } from "@legendapp/list/react"; @@ -72,7 +72,7 @@ interface ReactionSurface { readonly environmentId: EnvironmentId; readonly threadRef: ScopedThreadRef | null; readonly reference: PullRequestRef; - readonly mentionScope: PullRequestMentionScope | null; + readonly completionScope: PullRequestCompletionScope | null; readonly onRefresh: () => void; } @@ -306,7 +306,7 @@ function ConversationCard({ value={editable.body} cwd={cwd} environmentId={reactions.environmentId} - mentionScope={reactions.mentionScope} + completionScope={reactions.completionScope} threadRef={reactions.threadRef} label="Edit comment" saving={saving} @@ -704,7 +704,7 @@ export function PullRequestTimelineTab({ environmentId, threadRef, reference, - mentionScope: pullRequestMentionScope(detail, environmentId, reference), + completionScope: pullRequestCompletionScope(detail, environmentId, reference), onRefresh, }; const editable = new Map( diff --git a/apps/web/src/components/pullRequest/guide/GuideExcerpt.tsx b/apps/web/src/components/pullRequest/guide/GuideExcerpt.tsx index e419a16500232..cf1c248a3c50c 100644 --- a/apps/web/src/components/pullRequest/guide/GuideExcerpt.tsx +++ b/apps/web/src/components/pullRequest/guide/GuideExcerpt.tsx @@ -37,7 +37,7 @@ import { fileDiffRows, rowsToPatch, } from "@t3tools/client-runtime/review-guide-tour"; -import type { PullRequestMentionScope } from "../PullRequestMarkdownTextarea"; +import type { PullRequestCompletionScope } from "../PullRequestMarkdownTextarea"; import { GuideNoteMarker } from "./GuideNotes"; import { GuideProse } from "./GuideProse"; @@ -56,7 +56,7 @@ export interface ExcerptCommenting { readonly canComment: boolean; /** The host anchors a comment to a range of lines rather than to its last one. */ readonly rangeComments: boolean; - readonly mentionScope: PullRequestMentionScope | null; + readonly completionScope: PullRequestCompletionScope | null; readonly pending: ReadonlyArray; readonly onComment: (comment: { readonly path: string; @@ -325,7 +325,7 @@ function ExcerptDiff({ kind="draft" rangeLabel={`${excerpt.path}:${getReviewPositionAnchor(draft.position).line}`} text="" - mentionScope={commenting.canComment ? commenting.mentionScope : null} + completionScope={commenting.canComment ? commenting.completionScope : null} placeholder={ commenting.canComment ? "Add a comment…" : "Ask the agent about these lines…" } diff --git a/apps/web/src/state/pullRequests.ts b/apps/web/src/state/pullRequests.ts index c8ac23ced0584..914b6e6c72056 100644 --- a/apps/web/src/state/pullRequests.ts +++ b/apps/web/src/state/pullRequests.ts @@ -647,6 +647,7 @@ export function usePullRequestFilterOptions( return { labels: query.values.flatMap(([, options]) => options.labels), authors: query.values.flatMap(([, options]) => options.authors), + references: query.values.flatMap(([, options]) => options.references), error: query.error, isPending: query.isPending, }; diff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.ts index e96d1f3dfdb06..5dbec3e2dd3a7 100644 --- a/packages/contracts/src/pullRequest.ts +++ b/packages/contracts/src/pullRequest.ts @@ -257,6 +257,10 @@ export type PullRequestReviewerCapabilities = typeof PullRequestReviewerCapabili export const PullRequestViewedFilesStore = Schema.Literals(["host", "environment"]); export type PullRequestViewedFilesStore = typeof PullRequestViewedFilesStore.Type; +/** `#` references issues (and GitHub pull requests); `!` references GitLab merge requests. */ +export const PullRequestReferenceSigil = Schema.Literals(["#", "!"]); +export type PullRequestReferenceSigil = typeof PullRequestReferenceSigil.Type; + export const PullRequestCapabilities = Schema.Struct({ diff: Schema.Boolean, comment: Schema.Boolean, @@ -279,6 +283,8 @@ export const PullRequestCapabilities = Schema.Struct({ labels: Schema.optional(Schema.Boolean), /** The host searches the repository's users, so composers can complete `@login`. */ mentions: Schema.optional(Schema.Boolean), + /** The sigils whose issue and change request references composers can complete. */ + referenceSigils: Schema.optional(ForwardCompatibleArray(PullRequestReferenceSigil)), /** * Every head gets at least one check, so a head that has gone a while without any means none * reported rather than that the repository runs none. Absent means an empty list says nothing. @@ -523,7 +529,7 @@ export const PullRequestListStatsResult = Schema.Struct({ }); export type PullRequestListStatsResult = typeof PullRequestListStatsResult.Type; -export const PullRequestFilterOptionKind = Schema.Literals(["labels", "authors"]); +export const PullRequestFilterOptionKind = Schema.Literals(["labels", "authors", "references"]); export type PullRequestFilterOptionKind = typeof PullRequestFilterOptionKind.Type; /** Scoped like `PullRequestListInput`, so the options come from the repositories it lists. */ @@ -533,12 +539,28 @@ export const PullRequestFilterOptionsInput = Schema.Struct({ projectIds: Schema.optional(Schema.Array(ProjectId).check(Schema.isMaxLength(100))), host: Schema.optional(TrimmedNonEmptyString), query: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(100))), + /** For `references`, the sigil typed, so a host can search only what it links. */ + sigil: Schema.optional(PullRequestReferenceSigil), }); export type PullRequestFilterOptionsInput = typeof PullRequestFilterOptionsInput.Type; +/** An issue or change request a composer can reference, with the text the host links. */ +export const PullRequestReferenceCandidate = Schema.Struct({ + reference: TrimmedNonEmptyString, + kind: Schema.Literals(["issue", "change-request"]), + number: PositiveInt, + title: Schema.String, + state: Schema.Literals(["open", "closed", "merged"]), +}); +export type PullRequestReferenceCandidate = typeof PullRequestReferenceCandidate.Type; + export const PullRequestFilterOptions = Schema.Struct({ labels: Schema.Array(PullRequestLabel), authors: Schema.Array(PullRequestActor), + // Servers from before reference completion send no key. + references: Schema.Array(PullRequestReferenceCandidate).pipe( + Schema.withDecodingDefault(Effect.succeed([])), + ), truncated: Schema.Boolean, }); export type PullRequestFilterOptions = typeof PullRequestFilterOptions.Type; diff --git a/packages/shared/src/pullRequestComposerTrigger.test.ts b/packages/shared/src/pullRequestComposerTrigger.test.ts index 0aa786a581a86..c17beab3a1275 100644 --- a/packages/shared/src/pullRequestComposerTrigger.test.ts +++ b/packages/shared/src/pullRequestComposerTrigger.test.ts @@ -1,20 +1,30 @@ import { describe, expect, it } from "vite-plus/test"; import { - detectPullRequestMention, - insertPullRequestMention, + debouncedPullRequestCompletionSearch, + detectPullRequestComposerTrigger, + insertPullRequestCompletion, narrowPullRequestMentions, + narrowPullRequestReferences, } from "./pullRequestComposerTrigger.ts"; -describe("detectPullRequestMention", () => { +const GITLAB = { mentions: true, referenceSigils: ["#", "!"] } as const; + +describe("detectPullRequestComposerTrigger", () => { it.each([ - ["@", 0, ""], - ["cc @ju", 3, "ju"], - ["line one\n@first.last", 9, "first.last"], - ["@jane-doe more", 0, "jane-doe"], - ])("finds the mention in %j", (text, rangeStart, query) => { + ["@", 0, "@", ""], + ["cc @ju", 3, "@", "ju"], + ["line one\n@first.last", 9, "@", "first.last"], + ["@jane-doe more", 0, "@", "jane-doe"], + ["fixes #", 6, "#", ""], + ["see #12", 4, "#", "12"], + ["after !5", 6, "!", "5"], + ["#crash", 0, "#", "crash"], + ])("finds the trigger in %j", (text, rangeStart, sigil, query) => { const cursor = rangeStart + 1 + query.length; - expect(detectPullRequestMention(text, cursor)).toEqual({ + expect(detectPullRequestComposerTrigger(text, cursor, GITLAB)).toEqual({ + kind: sigil === "@" ? "mention" : "reference", + sigil, query, rangeStart, rangeEnd: cursor, @@ -27,18 +37,30 @@ describe("detectPullRequestMention", () => { ["@-jane", "@-jane".length], ["`@decorator`", "`@decorator".length], ["@jane", 3], + ["C#", 2], + ["![image", "![image".length], + ["## Heading", 2], ])("ignores %j", (text, cursor) => { - expect(detectPullRequestMention(text, cursor)).toBeNull(); + expect(detectPullRequestComposerTrigger(text, cursor, GITLAB)).toBeNull(); + }); + + it.each([ + ["@ju", {}], + ["#12", { mentions: true }], + ["!important", { mentions: true, referenceSigils: ["#"] }], + ["#12", { mentions: true, referenceSigils: [] }], + ] as const)("ignores %j on a host that cannot complete it", (text, support) => { + expect(detectPullRequestComposerTrigger(text, text.length, support)).toBeNull(); }); }); -describe("insertPullRequestMention", () => { +describe("insertPullRequestCompletion", () => { it.each(["", "\nnext line", "\r\nnext line"])( - "replaces the partial login and adds a space before %j", + "replaces the partial token and adds a space before %j", (suffix) => { const text = `thanks @ju${suffix}`; - const trigger = detectPullRequestMention(text, "thanks @ju".length)!; - expect(insertPullRequestMention(text, trigger, "julius")).toEqual({ + const trigger = detectPullRequestComposerTrigger(text, "thanks @ju".length, GITLAB)!; + expect(insertPullRequestCompletion(text, trigger, "@julius")).toEqual({ text: `thanks @julius ${suffix}`, cursor: "thanks @julius ".length, }); @@ -46,11 +68,23 @@ describe("insertPullRequestMention", () => { ); it("reuses the space that already follows and moves past it", () => { - const text = "@ju please look"; - const trigger = detectPullRequestMention(text, 3)!; - const inserted = insertPullRequestMention(text, trigger, "julius"); - expect(inserted).toEqual({ text: "@julius please look", cursor: "@julius ".length }); - expect(detectPullRequestMention(inserted.text, inserted.cursor)).toBeNull(); + const text = "#1 please look"; + const trigger = detectPullRequestComposerTrigger(text, 2, GITLAB)!; + const inserted = insertPullRequestCompletion(text, trigger, "#123"); + expect(inserted).toEqual({ text: "#123 please look", cursor: "#123 ".length }); + expect(detectPullRequestComposerTrigger(inserted.text, inserted.cursor, GITLAB)).toBeNull(); + }); +}); + +describe("debouncedPullRequestCompletionSearch", () => { + it.each([ + ["a settled search", { sigil: "#" }, "#crash", "crash"], + ["a settled bare sigil", { sigil: "@" }, "@", undefined], + ["a lagging search", { sigil: "#" }, "#cra", "cra"], + ["the other sigil's key", { sigil: "!" }, "#12", undefined], + ["no key yet", { sigil: "#" }, null, undefined], + ] as const)("sends %s as the host search", (_, trigger, key, sent) => { + expect(debouncedPullRequestCompletionSearch(trigger, key)).toBe(sent); }); }); @@ -68,3 +102,19 @@ describe("narrowPullRequestMentions", () => { expect(narrowPullRequestMentions(users, "", 2)).toHaveLength(2); }); }); + +describe("narrowPullRequestReferences", () => { + it("keeps the sigil's kind and matches a number prefix or the title", () => { + const candidates = [ + { reference: "#12", number: 12, title: "Crash on start" }, + { reference: "!12", number: 12, title: "Fix the crash" }, + { reference: "#3", number: 3, title: "Issue 12 follow-up" }, + { reference: "#120", number: 120, title: "Docs" }, + ]; + const narrowed = (sigil: "#" | "!", query: string) => + narrowPullRequestReferences(candidates, { sigil, query }, 5).map((c) => c.reference); + expect(narrowed("#", "12")).toEqual(["#12", "#3", "#120"]); + expect(narrowed("!", "CRASH")).toEqual(["!12"]); + expect(narrowed("#", "")).toEqual(["#12", "#3", "#120"]); + }); +}); diff --git a/packages/shared/src/pullRequestComposerTrigger.ts b/packages/shared/src/pullRequestComposerTrigger.ts index a2e64f924c964..6a14f0fcc8260 100644 --- a/packages/shared/src/pullRequestComposerTrigger.ts +++ b/packages/shared/src/pullRequestComposerTrigger.ts @@ -1,42 +1,92 @@ +import type { + PullRequestActor, + PullRequestCapabilities, + PullRequestFilterOptions, + PullRequestReferenceCandidate, + PullRequestReferenceSigil, +} from "@t3tools/contracts"; + import { replaceTextRange } from "./composerTrigger.ts"; -export interface PullRequestMentionTrigger { +export type PullRequestComposerTrigger = { readonly query: string; readonly rangeStart: number; readonly rangeEnd: number; -} +} & ( + | { readonly kind: "mention"; readonly sigil: "@" } + | { readonly kind: "reference"; readonly sigil: PullRequestReferenceSigil } +); + +// Mentions cover GitHub logins (letters, digits, hyphens) and GitLab usernames (also `_` and `.`). +const TOKEN = /^(?:@([A-Za-z0-9_][A-Za-z0-9_.-]*)?|([#!])([\p{L}\p{N}_-]*))$/u; -// Covers GitHub logins (letters, digits, hyphens) and GitLab usernames (also `_` and `.`). -const MENTION_TOKEN = /^@([A-Za-z0-9_][A-Za-z0-9_.-]*)?$/; +/** What a pull request's host can complete; absent fields complete nothing. */ +export type PullRequestCompletionSupport = Pick< + PullRequestCapabilities, + "mentions" | "referenceSigils" +>; -/** The `@login` being typed at the caret, when the caret sits at its end. */ -export function detectPullRequestMention( +/** + * The `@login`, `#123` or `!123` being typed at the caret, when the caret sits at its end and the + * host completes that sigil. + */ +export function detectPullRequestComposerTrigger( text: string, cursor: number, -): PullRequestMentionTrigger | null { + support: PullRequestCompletionSupport, +): PullRequestComposerTrigger | null { const end = Math.max(0, Math.min(text.length, cursor)); const next = text[end]; if (next !== undefined && !/\s/.test(next)) return null; let start = end; while (start > 0 && !/\s/.test(text[start - 1] ?? "")) start -= 1; - const match = MENTION_TOKEN.exec(text.slice(start, end)); + const match = TOKEN.exec(text.slice(start, end)); if (!match) return null; - return { query: match[1] ?? "", rangeStart: start, rangeEnd: end }; + const sigil = match[2]; + if (sigil === "#" || sigil === "!") { + return support.referenceSigils?.includes(sigil) + ? { kind: "reference", sigil, query: match[3] ?? "", rangeStart: start, rangeEnd: end } + : null; + } + return support.mentions === true + ? { kind: "mention", sigil: "@", query: match[1] ?? "", rangeStart: start, rangeEnd: end } + : null; } -export function insertPullRequestMention( +/** Replaces the trigger with `token` and leaves the caret past the space after it. */ +export function insertPullRequestCompletion( text: string, - trigger: PullRequestMentionTrigger, - login: string, + trigger: PullRequestComposerTrigger, + token: string, ): { text: string; cursor: number } { const followedBySpace = /[ \t]/.test(text[trigger.rangeEnd] ?? ""); if (!followedBySpace) { - return replaceTextRange(text, trigger.rangeStart, trigger.rangeEnd, `@${login} `); + return replaceTextRange(text, trigger.rangeStart, trigger.rangeEnd, `${token} `); } - const inserted = replaceTextRange(text, trigger.rangeStart, trigger.rangeEnd, `@${login}`); + const inserted = replaceTextRange(text, trigger.rangeStart, trigger.rangeEnd, token); return { ...inserted, cursor: inserted.cursor + 1 }; } +/** The key a debounce delays: the trigger's sigil and its host search, or `null` with no trigger. */ +export function pullRequestCompletionKey( + trigger: Pick | null, +): string | null { + return trigger === null ? null : `${trigger.sigil}${trigger.query.slice(0, 100)}`; +} + +/** + * The search to send for `trigger` given a debounced key. Until a key for this sigil settles, the + * host is asked for its unsearched list, which narrows locally, so a burst of typing sends one query. + */ +export function debouncedPullRequestCompletionSearch( + trigger: Pick, + debouncedKey: string | null, +): string | undefined { + return debouncedKey?.startsWith(trigger.sigil) + ? debouncedKey.slice(trigger.sigil.length) || undefined + : undefined; +} + export function narrowPullRequestMentions
( users: ReadonlyArray, typed: string, @@ -51,3 +101,50 @@ export function narrowPullRequestMentions( + candidates: ReadonlyArray, + trigger: Pick, + limit: number, +): A[] { + const needle = trigger.query.toLowerCase(); + return candidates + .filter( + (candidate) => + candidate.reference.startsWith(trigger.sigil) && + (String(candidate.number).startsWith(needle) || + candidate.title.toLowerCase().includes(needle)), + ) + .slice(0, limit); +} + +export type PullRequestCompletion = + | { readonly kind: "mention"; readonly token: string; readonly actor: PullRequestActor } + | { + readonly kind: "reference"; + readonly token: string; + readonly candidate: PullRequestReferenceCandidate; + }; + +/** The host's options for `trigger`, narrowed to what is typed now. */ +export function pullRequestCompletions( + trigger: PullRequestComposerTrigger | null, + options: Pick | null, + limit: number, +): ReadonlyArray { + if (trigger === null) return []; + return trigger.kind === "mention" + ? narrowPullRequestMentions(options?.authors ?? [], trigger.query, limit).map((actor) => ({ + kind: "mention", + token: `@${actor.login}`, + actor, + })) + : narrowPullRequestReferences(options?.references ?? [], trigger, limit).map((candidate) => ({ + kind: "reference", + token: candidate.reference, + candidate, + })); +} diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts index 7f3aa0561fc5b..061a5d0f931ee 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts @@ -53,6 +53,7 @@ const CAPABILITIES: PullRequestCapabilities = { search: false, reactions: false, mentions: false, + referenceSigils: [], review: { inlineComment: false, reply: false, resolve: false, verdicts: [] }, // Reviewer candidates require separate identity/graph APIs and permissions. reviewers: { request: true, listCandidates: false }, diff --git a/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts b/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts index 9123f34c7ef9f..1f7729ee2a58b 100644 --- a/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts +++ b/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts @@ -24,6 +24,7 @@ const CAPABILITIES: PullRequestCapabilities = { search: true, reactions: false, mentions: false, + referenceSigils: [], review: { inlineComment: true, reply: true, diff --git a/packages/source-control-core/src/server/PullRequestProvider.ts b/packages/source-control-core/src/server/PullRequestProvider.ts index 9769bc6634705..549210e382781 100644 --- a/packages/source-control-core/src/server/PullRequestProvider.ts +++ b/packages/source-control-core/src/server/PullRequestProvider.ts @@ -5,6 +5,8 @@ import type { PullRequestAction, PullRequestStackHead, PullRequestActor, + PullRequestReferenceCandidate, + PullRequestReferenceSigil, PullRequestBaseComparison, PullRequestCapabilities, PullRequestChecksState, @@ -555,6 +557,20 @@ export interface PullRequestProviderApi { input: ProviderRepositoryRef & { readonly query?: string | undefined }, ) => Effect.Effect, PullRequestProviderError>; + /** + * Issues and change requests a composer can reference, recently updated first. A numeric + * `query` also finds that number exactly; other text matches titles as far as the host can. + */ + readonly searchRepositoryReferences?: ( + input: ProviderRepositoryRef & { + readonly query?: string | undefined; + readonly sigil?: PullRequestReferenceSigil | undefined; + }, + ) => Effect.Effect< + ProviderFilterOptionPage, + PullRequestProviderError + >; + readonly setLabels?: ( input: ProviderRepositoryRef & { readonly number: number; diff --git a/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts b/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts index f41dbe0d0d846..cd2047664a31a 100644 --- a/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts +++ b/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts @@ -49,6 +49,7 @@ const CAPABILITIES: PullRequestCapabilities = { search: false, reactions: true, mentions: true, + referenceSigils: [], labels: true, // Forgejo's public API has no thread replies/resolution or draft conversion endpoint. review: { diff --git a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts index f465da71a4143..565f0b76722b6 100644 --- a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts +++ b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts @@ -35,6 +35,7 @@ const CAPABILITIES: PullRequestCapabilities = { stackActions: true, reactions: true, mentions: true, + referenceSigils: [], labels: true, // Line comments go through GitCafe's review drafts, which arrive with revision fencing. review: { diff --git a/packages/source-control-github/schema/github.graphql.ts b/packages/source-control-github/schema/github.graphql.ts index 9ac930c9ffe29..332060b960ff8 100644 --- a/packages/source-control-github/schema/github.graphql.ts +++ b/packages/source-control-github/schema/github.graphql.ts @@ -86,6 +86,15 @@ export type DiffSide = typeof DiffSide.Type export const FileViewedState = Schema.Literals(["DISMISSED", "UNVIEWED", "VIEWED"]) export type FileViewedState = typeof FileViewedState.Type +/** + * The possible states of an issue. + * + * - `CLOSED`: An issue that has been closed + * - `OPEN`: An issue that is still open + */ +export const IssueState = Schema.Literals(["CLOSED", "OPEN"]) +export type IssueState = typeof IssueState.Type + /** * Detailed status information about a pull request merge. * @@ -291,6 +300,8 @@ export declare namespace Typename { export type Actor = "Bot" | "EnterpriseUserAccount" | "Mannequin" | "Organization" | "User" /** Every possible `__typename` of interface `GitObject`. */ export type GitObject = "Blob" | "Commit" | "Tag" | "Tree" + /** Every possible `__typename` of union `IssueOrPullRequest`. */ + export type IssueOrPullRequest = "Issue" | "PullRequest" /** Every possible `__typename` of interface `Node`. */ export type Node = | "AddedToMergeQueueEvent" | "AddedToProjectEvent" | "AddedToProjectV2Event" | "AddedToStackEvent" | "App" diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts index 4ba8dceeee562..14b50258d71d6 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts @@ -731,6 +731,43 @@ it.effect( ); layer("GitHubPullRequestApi.layer", (it) => { + it.effect("keeps recent references when the typed number does not exist", () => + Effect.gen(function* () { + const search = { + pageInfo: { hasNextPage: false }, + nodes: [{ __typename: "Issue", number: 7, title: "Seven", issueState: "OPEN" }], + }; + mockedExecute.mockImplementation((call) => + Effect.succeed( + output( + encodeJson( + call.kind === "graphql" && call.variables?.["exact"] === true + ? { + data: { search, repository: { issueOrPullRequest: null } }, + errors: [ + { + type: "NOT_FOUND", + path: ["repository", "issueOrPullRequest"], + message: "Could not resolve to an issue or pull request.", + }, + ], + } + : { data: { search } }, + ), + ), + ), + ); + const api = yield* GitHubPullRequestApi.GitHubPullRequestApi; + const result = yield* api.searchRepositoryReferences({ + cwd: "/w", + repository: "acme/web", + host: "github.com", + query: "99", + }); + expect(result.items.map((item) => item.reference)).toEqual(["#7"]); + }), + ); + it.effect("turns maintainer edits off without rewriting the pull request's text", () => Effect.gen(function* () { mockedExecute.mockImplementation((call) => diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.ts index cb3c3d994b419..372e0a838204f 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestApi.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestApi.ts @@ -24,6 +24,7 @@ import { type PullRequestAction, type PullRequestStackHead, type PullRequestActor, + type PullRequestReferenceCandidate, type PullRequestComment, type PullRequestCommit, type PullRequestFileViewed, @@ -74,6 +75,9 @@ import { pullRequestLookup, toLabelCandidates, toRepositoryAuthors, + toRepositoryReferences, + referenceSearchQuery, + searchPhrase, toRepositoryLabels, toPullRequestActivityPage, toPullRequestActionSummary, @@ -642,6 +646,19 @@ export class GitHubPullRequestApi extends Context.Service< GitHubPullRequestApiError >; + readonly searchRepositoryReferences: (input: { + readonly cwd: string; + readonly repository: string; + readonly host: string; + readonly query?: string | undefined; + }) => Effect.Effect< + { + readonly items: ReadonlyArray; + readonly truncated: boolean; + }, + GitHubPullRequestApiError + >; + readonly setLabels: (input: { readonly cwd: string; readonly repository: string; @@ -743,11 +760,6 @@ function diffCursorPage(cursor: string): number | null { return /^[1-9][0-9]{0,6}$/.test(cursor) ? Number(cursor) : null; } -/** Quote user text so GitHub cannot interpret it as qualifiers that widen the listing. */ -function searchPhrase(query: string): string { - return `"${query.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`; -} - const REVIEW_QUALIFIERS = { approved: "approved", "changes-requested": "changes_requested", @@ -2373,6 +2385,32 @@ export const make = Effect.gen(function* () { }, ), + searchRepositoryReferences: Effect.fn("GitHubPullRequestApi.searchRepositoryReferences")( + function (input) { + const { owner, name } = parseRepositorySelector(input.repository); + const parsed = /^\d+$/.test(input.query ?? "") ? Number(input.query) : 0; + // GraphQL validates `$number: Int!` even when `@include` skips the lookup. + const exact = parsed > 0 && parsed <= 2_147_483_647; + const search = (lookup: boolean) => + client.RepositoryReferences({ + owner, + name, + q: referenceSearchQuery(input.repository, input.query), + number: lookup ? parsed : 0, + exact: lookup, + }); + return search(exact).pipe( + // A missing number fails the whole query, which would discard the search results. + Effect.catchIf( + (error) => exact && isNotFoundOnly(error), + () => search(false), + ), + graphql({ ...input, operation: "searchRepositoryReferences", allowReserve: true }), + Effect.map(toRepositoryReferences), + ); + }, + ), + setLabels: Effect.fn("GitHubPullRequestApi.setLabels")(function (input) { const { owner, name } = parseRepositorySelector(input.repository); const issue = `repos/${owner}/${name}/issues/${input.number}/labels`; diff --git a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts index 6e0f0af0cad38..d281b90f30acc 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts @@ -42,6 +42,7 @@ const CAPABILITIES: PullRequestCapabilities = { search: true, reactions: true, mentions: true, + referenceSigils: ["#"], viewedFiles: "host", review: { inlineComment: true, @@ -657,6 +658,11 @@ export const make = Effect.gen(function* () { searchRepositoryAuthors: (input) => cli.searchRepositoryAuthors(input).pipe(Effect.mapError(fail("searchRepositoryAuthors"))), + searchRepositoryReferences: (input) => + cli + .searchRepositoryReferences(input) + .pipe(Effect.mapError(fail("searchRepositoryReferences"))), + setLabels: (input) => cli .setLabels({ diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts index 58b7969277c09..f06c847471d0e 100644 --- a/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts +++ b/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts @@ -6,6 +6,8 @@ import { buildReviewSubmission, buildReviewerRequest, pullRequestLookup, + referenceSearchQuery, + toRepositoryReferences, toPullRequestWatchFingerprint, decodePullRequestFilesJson, decodePullRequestStacksJson, @@ -1629,6 +1631,40 @@ const decodeWatchedResult = Schema.decodeUnknownSync(PullRequestWatchFingerprint const decodeWatched = (pullRequest: object) => decodeWatchedResult({ repository: { pullRequest } }).repository!.pullRequest!; +describe("repository references", () => { + it.each([ + [undefined, "repo:o/r sort:updated-desc"], + ["12", "repo:o/r sort:updated-desc"], + ['say "hi"', 'repo:o/r in:title "say \\"hi\\"" sort:updated-desc'], + ])("searches %j as %j", (query, q) => { + expect(referenceSearchQuery("o/r", query)).toBe(q); + }); + + it("puts the exact number first and maps issue and pull request states", () => { + const result = toRepositoryReferences({ + search: { + pageInfo: { hasNextPage: true }, + nodes: [ + { __typename: "PullRequest", number: 3, title: "Merged", pullRequestState: "MERGED" }, + { __typename: "Issue", number: 2, title: "Closed", issueState: "CLOSED" }, + null, + ], + }, + repository: { + issueOrPullRequest: { __typename: "Issue", number: 1, title: "Exact", issueState: "OPEN" }, + }, + }); + expect(result).toEqual({ + items: [ + { reference: "#1", kind: "issue", number: 1, title: "Exact", state: "open" }, + { reference: "#3", kind: "change-request", number: 3, title: "Merged", state: "merged" }, + { reference: "#2", kind: "issue", number: 2, title: "Closed", state: "closed" }, + ], + truncated: true, + }); + }); +}); + describe("pull request lookups", () => { it("refuses what GitHub cannot name, so one bad row cannot fail a whole batch", () => { expect(pullRequestLookup({ repository: "acme/web", number: 7 })).toEqual({ diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.ts index 76c101766b326..5c6fce4a0f338 100644 --- a/packages/source-control-github/src/server/gitHubPullRequestJson.ts +++ b/packages/source-control-github/src/server/gitHubPullRequestJson.ts @@ -7,6 +7,7 @@ import { GraphQL } from "effect/graphql"; import type { PullRequestStackMembership, PullRequestActor, + PullRequestReferenceCandidate, PullRequestPreview, PullRequestCheck, PullRequestCheckStatus, @@ -65,6 +66,8 @@ import type { PullRequestSubject, RepositoryAuthors, RepositoryLabels, + RepositoryReferences, + ReferenceCandidate, ReviewerCandidates, ViewerPermissions, } from "./pullRequestReads.graphql.ts"; @@ -1576,6 +1579,64 @@ export function toRepositoryAuthors( }; } +/** The `search` string for {@link toRepositoryReferences}; a numeric query searches recent items. */ +export function referenceSearchQuery(repository: string, query: string | undefined): string { + const text = query?.trim() ?? ""; + const titled = text.length === 0 || /^\d+$/.test(text) ? [] : [`in:title ${searchPhrase(text)}`]; + return [`repo:${repository}`, ...titled, "sort:updated-desc"].join(" "); +} + +/** Quote user text so GitHub cannot interpret it as qualifiers that widen the listing. */ +export function searchPhrase(query: string): string { + return `"${query.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`; +} + +type ReferenceNode = + | ReferenceCandidate + | NonNullable[number]>; + +function toReferenceCandidate(node: ReferenceNode): PullRequestReferenceCandidate | null { + if (node.__typename === "Issue") { + return { + reference: `#${node.number}`, + kind: "issue", + number: node.number, + title: node.title, + state: node.issueState === "OPEN" ? "open" : "closed", + }; + } + if (node.__typename === "PullRequest") { + return { + reference: `#${node.number}`, + kind: "change-request", + number: node.number, + title: node.title, + state: + node.pullRequestState === "OPEN" + ? "open" + : node.pullRequestState === "MERGED" + ? "merged" + : "closed", + }; + } + return null; +} + +export function toRepositoryReferences(result: RepositoryReferences.Result): { + readonly items: ReadonlyArray; + readonly truncated: boolean; +} { + const exact = result.repository?.issueOrPullRequest; + const nodes = [...(exact == null ? [] : [exact]), ...nodesOf(result.search)]; + return { + items: nodes.flatMap((node) => { + const candidate = toReferenceCandidate(node); + return candidate === null ? [] : [candidate]; + }), + truncated: result.search.pageInfo.hasNextPage, + }; +} + export function buildLabelRequest(labels: ReadonlyArray): { readonly labels: ReadonlyArray; } { diff --git a/packages/source-control-github/src/server/pullRequestReads.graphql b/packages/source-control-github/src/server/pullRequestReads.graphql index f317ae0f5ea2e..61f77a289a766 100644 --- a/packages/source-control-github/src/server/pullRequestReads.graphql +++ b/packages/source-control-github/src/server/pullRequestReads.graphql @@ -487,6 +487,43 @@ query RepositoryLabels($owner: String!, $name: String!, $query: String) { } } +fragment ReferenceCandidate on IssueOrPullRequest { + __typename + ... on Issue { + number + title + issueState: state + } + ... on PullRequest { + number + title + pullRequestState: state + } +} + +# `search` cannot match a number, so a numeric query also looks the number up directly. +query RepositoryReferences( + $owner: String! + $name: String! + $q: String! + $number: Int! + $exact: Boolean! +) { + search(query: $q, type: ISSUE, first: 20) { + pageInfo { + hasNextPage + } + nodes { + ...ReferenceCandidate + } + } + repository(owner: $owner, name: $name) @include(if: $exact) { + issueOrPullRequest(number: $number) { + ...ReferenceCandidate + } + } +} + # Mentionable rather than assignable users: a pull request from a fork is opened by someone with # no access to the repository, and a listing is still narrowed by them. query RepositoryAuthors($owner: String!, $name: String!, $query: String) { diff --git a/packages/source-control-github/src/server/pullRequestReads.graphql.ts b/packages/source-control-github/src/server/pullRequestReads.graphql.ts index ff19cfd0f6a35..fca2349bcfcde 100644 --- a/packages/source-control-github/src/server/pullRequestReads.graphql.ts +++ b/packages/source-control-github/src/server/pullRequestReads.graphql.ts @@ -82,6 +82,48 @@ export const CheckContext = Schema.Union([ ]) export type CheckContext = typeof CheckContext.Type +/** An Issue is a place to discuss ideas, enhancements, tasks, and bugs for a project. */ +export const Issue = Schema.Struct({ + __typename: Schema.Literal("Issue"), + /** Identifies the issue number. */ + number: Shared.Int, + /** Identifies the issue title. */ + title: Schema.String, + /** Identifies the state of the issue. */ + issueState: GraphQL.enumLiterals(Shared.IssueState.literals) +}) +export interface Issue extends Schema.Struct.Type {} + +/** A repository pull request. */ +export const ReferenceCandidatePullRequest = Schema.Struct({ + __typename: Schema.Literal("PullRequest"), + /** Identifies the pull request number. */ + number: Shared.Int, + /** Identifies the pull request title. */ + title: Schema.String, + /** Identifies the state of the pull request. */ + pullRequestState: GraphQL.enumLiterals(Shared.PullRequestState.literals) +}) +export interface ReferenceCandidatePullRequest extends Schema.Struct.Type {} + +/** Used for return value of Repository.issueOrPullRequest. */ +export const IssueOrPullRequestOther = Schema.Struct({ + __typename: GraphQL.otherTypename()(["Issue", "PullRequest"]) +}) +export interface IssueOrPullRequestOther extends Schema.Struct.Type {} + +/** + * `fragment ReferenceCandidate on IssueOrPullRequest` + * + * Used for return value of Repository.issueOrPullRequest. + */ +export const ReferenceCandidate = Schema.Union([ + Issue, + ReferenceCandidatePullRequest, + IssueOrPullRequestOther +]) +export type ReferenceCandidate = typeof ReferenceCandidate.Type + /** A user is an individual's account on GitHub that owns repositories and can make new content. */ export const ViewerUser = Schema.Struct({ /** Identifies the primary key from the database. */ @@ -1301,6 +1343,73 @@ export declare namespace RepositoryLabels { export type Result = typeof RepositoryLabels.result.Type } +/** The results of a search. */ +export const SearchResultItemOther = Schema.Struct({ + __typename: GraphQL.otherTypename()(["Issue", "PullRequest"]) +}) +export interface SearchResultItemOther extends Schema.Struct.Type {} + +/** + * A list of results that matched against a search query. Regardless of the number + * of matches, a maximum of 1,000 results will be available across all types, + * potentially split across many pages. + */ +export const SearchResultItemConnection = Schema.Struct({ + /** Information to aid in pagination. */ + pageInfo: AssignableUsersPageInfoPageInfo, + /** A list of nodes. */ + nodes: Schema.NullOr(Schema.Array(Schema.NullOr(Schema.Union([ + Issue, + ReferenceCandidatePullRequest, + SearchResultItemOther + ])))) +}) +export interface SearchResultItemConnection extends Schema.Struct.Type {} + +/** A repository contains the content for a project. */ +export const RepositoryReferencesRepositoryRepository = Schema.Struct({ + /** Returns a single issue-like object from the current repository by number. */ + issueOrPullRequest: Schema.NullOr(ReferenceCandidate) +}) +export interface RepositoryReferencesRepositoryRepository extends Schema.Struct.Type {} + +/** `query RepositoryReferences` */ +export const RepositoryReferences = GraphQL.query("RepositoryReferences", { + document: { + variables: [ + { name: "owner", body: "String!" }, + { name: "name", body: "String!" }, + { name: "q", body: "String!" }, + { name: "number", body: "Int!" }, + { name: "exact", body: "Boolean!" } + ], + selections: [ + { name: "search", body: ["(query:$", "q", " type:ISSUE first:20){pageInfo{hasNextPage}nodes{__typename...ReferenceCandidate}}"] }, + { name: "repository", body: ["(owner:$", "owner", " name:$", "name", ")@include(if:$", "exact", "){issueOrPullRequest(number:$", "number", "){__typename...ReferenceCandidate}}"] } + ], + fragments: [ + { name: "ReferenceCandidate", body: ["on IssueOrPullRequest{__typename...on Issue{number title issueState:state}...on PullRequest{number title pullRequestState:state}}"] } + ] + }, + variables: { + owner: Schema.String, + name: Schema.String, + q: Schema.String, + number: Shared.Int, + exact: Schema.Boolean + }, + result: Schema.Struct({ + /** Perform a search across resources, returning a maximum of 1,000 results. */ + search: SearchResultItemConnection, + /** Lookup a given repository by the owner and repository name. */ + repository: Schema.optionalKey(Schema.NullOr(RepositoryReferencesRepositoryRepository)) + }) +}) +export declare namespace RepositoryReferences { + export type Variables = typeof RepositoryReferences.variables.Type + export type Result = typeof RepositoryReferences.result.Type +} + /** A repository contains the content for a project. */ export const RepositoryAuthorsRepositoryRepository = Schema.Struct({ /** A list of Users that can be mentioned in the context of the repository. */ @@ -1687,4 +1796,4 @@ export declare namespace PullRequestSourceBranch { } /** Every operation in pullRequestReads.graphql. */ -export const PullRequestReadsGraphQLGroup = GraphQLGroup.make(RoutingIdentityViewer, ActorAvatars, PullRequestCore, PullRequestCheckContexts, PullRequestPreview, PullRequestActivity, PullRequestCommitStats, PullRequestHeads, PullRequestNodeId, PullRequestSubject, ViewerPermissions, ReviewerCandidates, LabelCandidates, RepositoryLabels, RepositoryAuthors, PullRequestFilesViewed, PullRequestFileStats, PullRequestMergeMessage, PullRequestActionState, PullRequestBranchToDelete, PullRequestSourceBranch) +export const PullRequestReadsGraphQLGroup = GraphQLGroup.make(RoutingIdentityViewer, ActorAvatars, PullRequestCore, PullRequestCheckContexts, PullRequestPreview, PullRequestActivity, PullRequestCommitStats, PullRequestHeads, PullRequestNodeId, PullRequestSubject, ViewerPermissions, ReviewerCandidates, LabelCandidates, RepositoryLabels, RepositoryReferences, RepositoryAuthors, PullRequestFilesViewed, PullRequestFileStats, PullRequestMergeMessage, PullRequestActionState, PullRequestBranchToDelete, PullRequestSourceBranch) diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts index 8e19295cdbde8..1641ff79dc1b7 100644 --- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts @@ -2211,6 +2211,27 @@ layer("GitLabPullRequestCli.layer", (it) => { expect(result).toMatchObject({ _tag: "Failure", failure: error }); }), ); + + it.effect("keeps merge request references when the issue search fails", () => + Effect.gen(function* () { + mockedExecute.mockImplementation((input) => + JSON.stringify(input).includes("/issues?") + ? Effect.fail( + new GitLabCli.GitLabCliCommandError({ + operation: "execute", + command: "glab", + cwd: "/w", + cause: null, + }), + ) + : Effect.succeed(output(JSON.stringify([{ iid: 5, title: "Ship it", state: "opened" }]))), + ); + const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli; + const page = yield* cli.searchProjectReferences({ cwd: "/w", repository: "acme/web" }); + expect(page.items.map((item) => item.reference)).toEqual(["!5"]); + }), + ); + describe("the head pipeline's stages", () => { const pipeline = { id: 9, @@ -2379,3 +2400,31 @@ layer("GitLabPullRequestCli.layer", (it) => { ); }); }); + +it("asks for a numeric reference's iid besides the recent issues and merge requests", () => { + const recent = [ + ["order_by", "updated_at"], + ["sort", "desc"], + ]; + expect(GitLabPullRequestCli.referenceSearches("12")).toEqual([ + { kind: "issue", params: [["iids[]", "12"]] }, + { kind: "change-request", params: [["iids[]", "12"]] }, + { kind: "issue", params: recent }, + { kind: "change-request", params: recent }, + ]); + expect(GitLabPullRequestCli.referenceSearches("crash")).toEqual([ + { kind: "issue", params: [...recent, ["search", "crash"], ["in", "title"]] }, + { kind: "change-request", params: [...recent, ["search", "crash"], ["in", "title"]] }, + ]); + expect(GitLabPullRequestCli.referenceSearches("cr")).toEqual([ + { kind: "issue", params: recent }, + { kind: "change-request", params: recent }, + ]); + expect(GitLabPullRequestCli.referenceSearches("12", "!")).toEqual([ + { kind: "change-request", params: [["iids[]", "12"]] }, + { kind: "change-request", params: recent }, + ]); + expect(GitLabPullRequestCli.referenceSearches(undefined, "#")).toEqual([ + { kind: "issue", params: recent }, + ]); +}); diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts index 43f54b1651cd3..7eda058ceb4c4 100644 --- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts +++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts @@ -11,6 +11,8 @@ import { resolvePullRequestAuthorFilter, VcsProcessExitError } from "@t3tools/co import type { PullRequestAction, PullRequestActor, + PullRequestReferenceCandidate, + PullRequestReferenceSigil, PullRequestCheck, PullRequestComment, PullRequestCommit, @@ -58,6 +60,7 @@ import { decodeProjectMergeCapabilitiesJson, decodeProjectLabelsJson, decodeProjectUsersJson, + decodeReferenceCandidatesJson, decodeRepositoryBlobsJson, decodeListStatesJson, decodeSourceBranchJson, @@ -512,6 +515,20 @@ export class GitLabPullRequestCli extends Context.Service< GitLabPullRequestCliError >; + readonly searchProjectReferences: (input: { + readonly cwd: string; + readonly host?: string | undefined; + readonly repository: string; + readonly search?: string | undefined; + readonly sigil?: PullRequestReferenceSigil | undefined; + }) => Effect.Effect< + { + readonly items: ReadonlyArray; + readonly truncated: boolean; + }, + GitLabPullRequestCliError + >; + readonly setReviewerRequest: (input: { readonly cwd: string; readonly host?: string | undefined; @@ -791,6 +808,58 @@ function searchParams(search: string | undefined): ReadonlyArray { + return (search?.trim().length ?? 0) >= 3 ? searchParams(search) : []; +} + +const REFERENCE_PAGE_SIZE = 20; + +/** + * Recently updated issues and merge requests, by title for text. Issue and MR search cannot match + * a number, so a numeric query also asks for that iid of each. + */ +export function referenceSearches( + search: string | undefined, + sigil?: PullRequestReferenceSigil | undefined, +): ReadonlyArray<{ + readonly kind: PullRequestReferenceCandidate["kind"]; + readonly params: ReadonlyArray; +}> { + const text = search?.trim() ?? ""; + const numeric = /^\d+$/.test(text); + const recent: ReadonlyArray = [ + ["order_by", "updated_at"], + ["sort", "desc"], + ...(numeric || hostSearchParams(text).length === 0 + ? [] + : ([...hostSearchParams(text), ["in", "title"]] as const)), + ]; + const kinds = + sigil === "#" + ? (["issue"] as const) + : sigil === "!" + ? (["change-request"] as const) + : (["issue", "change-request"] as const); + return [ + ...(numeric ? kinds.map((kind) => ({ kind, params: [["iids[]", text]] as const })) : []), + ...kinds.map((kind) => ({ kind, params: recent })), + ]; +} + +function mergeReferencePages( + pages: ReadonlyArray<{ + readonly items: ReadonlyArray; + readonly rawCount: number; + }>, +) { + return { + items: pages.flatMap((page) => page.items), + truncated: pages.some((page) => page.rawCount >= REFERENCE_PAGE_SIZE), + }; +} + function query(params: ReadonlyArray): string { return params.map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join("&"); } @@ -1317,9 +1386,7 @@ export const make = Effect.gen(function* () { host: input.host, path: `projects/${projectPath(input.repository)}/users?${query([ ["per_page", String(MAX_PAGE_SIZE)], - // GitLab answers nothing for a user search under three characters; callers narrow the - // unsearched page instead. - ...((input.search?.trim().length ?? 0) >= 3 ? searchParams(input.search) : []), + ...hostSearchParams(input.search), ])}`, }).pipe( Effect.flatMap((result) => { @@ -1337,6 +1404,35 @@ export const make = Effect.gen(function* () { }), ); + const projectReferences = (input: { + readonly cwd: string; + readonly host?: string | undefined; + readonly repository: string; + readonly kind: PullRequestReferenceCandidate["kind"]; + readonly params: ReadonlyArray; + }) => + api({ + cwd: input.cwd, + host: input.host, + path: `projects/${projectPath(input.repository)}/${ + input.kind === "issue" ? "issues" : "merge_requests" + }?${query([...input.params, ["per_page", String(REFERENCE_PAGE_SIZE)]])}`, + }).pipe( + Effect.flatMap((result) => { + const decoded = decodeReferenceCandidatesJson(result.stdout.trim(), input.kind); + return Result.isSuccess(decoded) + ? Effect.succeed(decoded.success) + : Effect.fail( + new GitLabMergeRequestReadError({ + command: "glab", + cwd: input.cwd, + operation: "searchProjectReferences", + cause: decoded.failure, + }), + ); + }), + ); + const awardSubjectPath = (input: { readonly repository: string; readonly number: number; @@ -2222,6 +2318,32 @@ export const make = Effect.gen(function* () { ); }), + searchProjectReferences: Effect.fn("GitLabPullRequestCli.searchProjectReferences")( + function (input) { + return Effect.forEach( + referenceSearches(input.search, input.sigil), + ({ kind, params }) => + projectReferences({ ...input, kind, params }).pipe( + // A project with issues turned off answers 403 for issues; its merge requests still + // complete. An unusable CLI or account still reaches the caller. + Effect.catchIf( + (cause) => + cause._tag !== "GitLabCliUnavailableError" && + cause._tag !== "GitLabCliAuthenticationError" && + cause._tag !== "GitLabCliRateLimitError", + (cause) => + Effect.logWarning("GitLab reference search failed", { + repository: input.repository, + kind, + reason: cause._tag, + }).pipe(Effect.as({ items: [], rawCount: 0 })), + ), + ), + { concurrency: "unbounded" }, + ).pipe(Effect.map(mergeReferencePages)); + }, + ), + listReviewerCandidates: Effect.fn("GitLabPullRequestCli.listReviewerCandidates")( function (input) { return Effect.all([mergeRequestDetail(input), projectUsers(input)], { diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts index c7a38794ee6fa..4247008c273d1 100644 --- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts +++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts @@ -33,6 +33,7 @@ const CAPABILITIES: PullRequestCapabilities = { search: true, reactions: true, mentions: true, + referenceSigils: ["#", "!"], // GitLab's viewed marks live in browser-local storage. viewedFiles: "environment", review: { @@ -534,6 +535,17 @@ export const make = Effect.gen(function* () { }) .pipe(Effect.mapError(fail("searchRepositoryAuthors"))), + searchRepositoryReferences: (input) => + cli + .searchProjectReferences({ + cwd: input.cwd, + host: input.host, + repository: input.repository, + search: input.query, + sigil: input.sigil, + }) + .pipe(Effect.mapError(fail("searchRepositoryReferences"))), + setReviewerRequest: writing((input) => cli .setReviewerRequest({ diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts index f755f185adcde..181b73a44b730 100644 --- a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts +++ b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts @@ -13,6 +13,7 @@ import { decodeMergeRequestListJson, decodeMergeRequestFileStatsJson, decodeMergeRequestStatsJson, + decodeReferenceCandidatesJson, decodeNotesJson, decodeOwnAwardIdJson, decodeListStatesJson, @@ -1052,6 +1053,28 @@ describe("decodeListStatesJson", () => { }); }); +describe("decodeReferenceCandidatesJson", () => { + it("prefixes merge requests with ! and skips malformed entries", () => { + const raw = JSON.stringify([ + { iid: 5, title: "Ship it", state: "merged" }, + { iid: 6, title: "Draft", state: "opened" }, + { iid: 7, title: "Locked", state: "locked" }, + { title: "No iid", state: "opened" }, + ]); + const decoded = decodeReferenceCandidatesJson(raw, "change-request"); + expect(Result.isSuccess(decoded) && decoded.success).toEqual({ + items: [ + { reference: "!5", kind: "change-request", number: 5, title: "Ship it", state: "merged" }, + { reference: "!6", kind: "change-request", number: 6, title: "Draft", state: "open" }, + { reference: "!7", kind: "change-request", number: 7, title: "Locked", state: "closed" }, + ], + rawCount: 4, + }); + const issues = decodeReferenceCandidatesJson(raw, "issue"); + expect(Result.isSuccess(issues) && issues.success.items[0]?.reference).toBe("#5"); + }); +}); + describe("decodeMergeRequestStatsJson", () => { it("keys the counts by merge request number", () => { const stats = expectSuccess( diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts index 18366b536786f..602d5971f0995 100644 --- a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts +++ b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts @@ -16,6 +16,7 @@ import type { PullRequestMergeMethod, PullRequestReaction, PullRequestReactionContent, + PullRequestReferenceCandidate, PullRequestReviewDecision, PullRequestReviewThread, PullRequestReviewerCandidate, @@ -655,6 +656,40 @@ export function decodeProjectUsersJson( return Result.succeed({ candidates, rawCount: decoded.success.length }); } +const RawReferenceSchema = Schema.Struct({ + iid: Schema.Number, + title: Schema.String, + state: Schema.String, +}); +const decodeReferenceEntry = Schema.decodeUnknownExit(RawReferenceSchema); + +/** A list of issues (`#`) or merge requests (`!`), as composers reference them. */ +export function decodeReferenceCandidatesJson( + raw: string, + kind: PullRequestReferenceCandidate["kind"], +): Result.Result< + { readonly items: ReadonlyArray; readonly rawCount: number }, + DecodeFailure +> { + const decoded = decodeUnknownList(raw); + if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure); + const items: PullRequestReferenceCandidate[] = []; + for (const entry of decoded.success) { + const reference = decodeReferenceEntry(entry); + if (Exit.isFailure(reference) || !Number.isInteger(reference.value.iid)) continue; + if (reference.value.iid < 1) continue; + const { iid, title, state } = reference.value; + items.push({ + reference: `${kind === "issue" ? "#" : "!"}${iid}`, + kind, + number: iid, + title, + state: state === "merged" ? "merged" : state === "opened" ? "open" : "closed", + }); + } + return Result.succeed({ items, rawCount: decoded.success.length }); +} + const RawLabelSchema = Schema.Struct({ name: Schema.String, color: Schema.optional(Schema.NullOr(Schema.String)), From 508f869cb3d3ac07a6d81963da5054e1af0d8f51 Mon Sep 17 00:00:00 2001 From: Antony <97451137+TonybynMp4@users.noreply.github.com> Date: Fri, 6 Nov 2026 02:45:13 +0100 Subject: [PATCH 003/181] feat(gitlab): merge requests from forks can toggle maintainer edits (#30518) Co-authored-by: Claude Opus 5.5 Co-authored-by: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> --- .../src/server/GitLabPullRequestCli.test.ts | 191 +++++++++++++++--- .../src/server/GitLabPullRequestCli.ts | 85 ++++---- .../server/GitLabPullRequestProvider.test.ts | 11 +- .../src/server/GitLabPullRequestProvider.ts | 16 +- .../src/server/gitLabMergeRequestJson.ts | 73 +++++++ 5 files changed, 312 insertions(+), 64 deletions(-) diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts index 1641ff79dc1b7..e70941f156861 100644 --- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts @@ -1643,33 +1643,39 @@ layer("GitLabPullRequestCli.layer", (it) => { expected: true, }, { answer: JSON.stringify({ errors: [{ message: "Field unknown" }] }), expected: false }, - ])("reads merge and label permissions without reading the trigger jobs", ({ answer, expected }) => - Effect.gen(function* () { - mockedExecute.mockImplementation(({ args }) => - Effect.succeed( - output( - args[1] === "graphql" - ? answer - : mergeRequestJson({ - head_pipeline: { id: 31, project_id: 12, status: "success" }, - user: { can_merge: false }, - }), + ])( + "reads merge and label permissions without reading the trigger jobs or fork settings", + ({ answer, expected }) => + Effect.gen(function* () { + mockedExecute.mockImplementation(({ args }) => + Effect.succeed( + output( + args[1] === "graphql" + ? answer + : mergeRequestJson({ + head_pipeline: { id: 31, project_id: 12, status: "success" }, + user: { can_merge: false }, + source_project_id: 12, + target_project_id: 12, + allow_collaboration: null, + }), + ), ), - ), - ); - const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli; + ); + const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli; - const detail = yield* cli.getMergeRequestDetail({ - cwd: "/w", - repository: "acme/web", - number: 7, - downstreamChecks: false, - }); + const detail = yield* cli.getMergeRequestDetail({ + cwd: "/w", + repository: "acme/web", + number: 7, + downstreamChecks: false, + }); - expect(detail.viewerCanMerge).toBe(false); - expect(detail.viewerCanEditLabels).toBe(expected); - expect(mockedExecute).toHaveBeenCalledTimes(2); - }), + expect(detail.viewerCanMerge).toBe(false); + expect(detail.maintainerCanModify).toBeUndefined(); + expect(detail.viewerCanEditLabels).toBe(expected); + expect(mockedExecute).toHaveBeenCalledTimes(2); + }), ); it.effect( @@ -1888,6 +1894,143 @@ layer("GitLabPullRequestCli.layer", (it) => { }), ); + it.effect.each([ + { viewer: "the author who can push to the fork", username: "bilal", allowed: true }, + { + viewer: "the author who turned them off", + username: "bilal", + allowCollaboration: false, + allowed: true, + }, + { viewer: "a target maintainer the fork lets push", username: "octocat", allowed: false }, + { + viewer: "the author without push access", + username: "bilal", + pushToSourceBranch: false, + allowed: false, + }, + { + viewer: "a viewer on a host that rejects the permission read", + username: "bilal", + rejected: true, + allowed: false, + }, + { + viewer: "the author of a protected source branch", + username: "bilal", + sourceBranchProtected: true, + allowed: false, + }, + { + viewer: "the author of a private fork", + username: "bilal", + sourceVisibility: "private", + allowed: false, + }, + { + viewer: "the author targeting a private project", + username: "bilal", + targetVisibility: "private", + allowed: false, + }, + ])("reads a fork's maintainer edits and lets $viewer change them", (row) => + Effect.gen(function* () { + const allowCollaboration = row.allowCollaboration ?? true; + mockedExecute.mockImplementation(({ args }) => + Effect.succeed( + output( + args[1] === "graphql" + ? JSON.stringify( + row.rejected === true + ? { errors: [{ message: "Field 'pushToSourceBranch' doesn't exist" }] } + : { + data: { + currentUser: { username: row.username }, + project: { + visibility: row.targetVisibility ?? "public", + mergeRequest: { + author: { username: "bilal" }, + userPermissions: { + pushToSourceBranch: row.pushToSourceBranch ?? true, + }, + sourceBranchProtected: row.sourceBranchProtected ?? false, + sourceProject: { visibility: row.sourceVisibility ?? "public" }, + }, + }, + }, + }, + ) + : mergeRequestJson({ + author, + source_project_id: 40, + target_project_id: 12, + allow_collaboration: allowCollaboration, + }), + ), + ), + ); + const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli; + + const detail = yield* cli.getMergeRequestDetail({ + cwd: "/w", + repository: "acme/web", + number: 7, + downstreamChecks: false, + }); + + expect(detail.maintainerCanModify).toBe(allowCollaboration); + expect(detail.viewerCanEditMaintainerEdits).toBe(row.allowed); + }), + ); + + it.effect("skips a fork's maintainer edits permission read when the caller opts out", () => + Effect.gen(function* () { + mockedExecute + .mockReturnValueOnce( + Effect.succeed( + output( + mergeRequestJson({ + source_project_id: 40, + target_project_id: 12, + allow_collaboration: true, + }), + ), + ), + ) + .mockReturnValueOnce(Effect.succeed(labelPermission)); + const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli; + + const detail = yield* cli.getMergeRequestDetail({ + cwd: "/w", + repository: "acme/web", + number: 7, + downstreamChecks: false, + maintainerEdits: false, + }); + + expect(detail.maintainerCanModify).toBe(true); + expect(detail.viewerCanEditMaintainerEdits).toBeUndefined(); + expect(mockedExecute).toHaveBeenCalledTimes(2); + }), + ); + + it.effect("sends maintainer edits as allow_collaboration", () => + Effect.gen(function* () { + mockedExecute.mockReturnValueOnce(Effect.succeed(output("{}"))); + const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli; + + yield* cli.updateMergeRequest({ + cwd: "/w", + repository: "acme/web", + number: 7, + allowCollaboration: false, + }); + + expect(argsOfCall(0)).toContain("PUT"); + expect(JSON.parse(callAt(0).stdin ?? "")).toEqual({ allow_collaboration: false }); + }), + ); + it.effect.each([ ["th", "projects/acme%2Fweb/users?per_page=100"], ["tho", "projects/acme%2Fweb/users?per_page=100&search=tho"], diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts index 7eda058ceb4c4..f8a52e9f33ff6 100644 --- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts +++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts @@ -42,6 +42,7 @@ import { decodeCommitsJson, decodeDiffRefsJson, decodeDiscussionsJson, + decodeMaintainerEditsPermissionJson, decodeLabelNameJson, decodeLabelPermissionJson, decodeMergeMessagesJson, @@ -67,6 +68,7 @@ import { decodeTriggerJobChecksJson, decodeViewerJson, gitLabAwardName, + MAINTAINER_EDITS_PERMISSION_GRAPHQL_QUERY, LABEL_PERMISSION_GRAPHQL_QUERY, MERGE_MESSAGES_GRAPHQL_QUERY, MERGE_REQUEST_FILE_STATS_GRAPHQL_QUERY, @@ -380,6 +382,8 @@ export class GitLabPullRequestCli extends Context.Service< readonly number: number; /** `false` skips the stage and trigger job reads, as write permission checks do. */ readonly downstreamChecks?: boolean; + /** `false` skips a fork's maintainer edits permission read, for views that never show it. */ + readonly maintainerEdits?: boolean; }) => Effect.Effect; /** Approval and head pipeline state, read in one GraphQL request per 100 merge requests. */ @@ -555,6 +559,7 @@ export class GitLabPullRequestCli extends Context.Service< readonly number: number; readonly title?: string | undefined; readonly description?: string | undefined; + readonly allowCollaboration?: boolean | undefined; }) => Effect.Effect; readonly commentOnMergeRequest: (input: { @@ -1580,6 +1585,19 @@ export const make = Effect.gen(function* () { }), ); + // A read GitLab could not answer (an older host, a field it rejects) is not worth failing the + // surrounding operation for. An unusable CLI or account still reaches the caller. + const isOptionalReadFailure = (cause: GitLabPullRequestCliError) => + cause._tag !== "GitLabCliUnavailableError" && + cause._tag !== "GitLabCliAuthenticationError" && + cause._tag !== "GitLabCliRateLimitError"; + + const orWhenUnanswered = ( + read: Effect.Effect, + fallback: A, + ): Effect.Effect => + read.pipe(Effect.catchIf(isOptionalReadFailure, () => Effect.succeed(fallback))); + const graphqlMutation = (input: { readonly cwd: string; readonly host?: string | undefined; @@ -1675,16 +1693,7 @@ export const make = Effect.gen(function* () { query: LABEL_PERMISSION_GRAPHQL_QUERY, variables: { fullPath: input.repository, iid: String(input.number) }, decode: decodeLabelPermissionJson, - }).pipe( - // The answer gates one optional control; an unusable CLI or account still surfaces. - Effect.catchIf( - (cause) => - cause._tag !== "GitLabCliUnavailableError" && - cause._tag !== "GitLabCliAuthenticationError" && - cause._tag !== "GitLabCliRateLimitError", - () => Effect.succeed(false), - ), - ); + }).pipe(Effect.catchIf(isOptionalReadFailure, () => Effect.succeed(false))); const sourceBranch = (input: { readonly cwd: string; @@ -1812,18 +1821,12 @@ export const make = Effect.gen(function* () { return stat === undefined ? [] : [{ repository: read.repository, number, ...stat }]; }), ), - // One read GitLab could not answer costs its own rows their counts, not every other - // read's on the same page. An unusable CLI or account still reaches the caller. - Effect.catchIf( - (cause) => - cause._tag !== "GitLabCliUnavailableError" && - cause._tag !== "GitLabCliAuthenticationError" && - cause._tag !== "GitLabCliRateLimitError", - (cause) => - Effect.logWarning("GitLab merge request line count read failed", { - repository: read.repository, - reason: cause._tag, - }).pipe(Effect.as([])), + // One failed read costs its own rows their counts, not every other read's on the page. + Effect.catchIf(isOptionalReadFailure, (cause) => + Effect.logWarning("GitLab merge request line count read failed", { + repository: read.repository, + reason: cause._tag, + }).pipe(Effect.as([])), ), ), { concurrency: STAT_REQUEST_CONCURRENCY }, @@ -1998,24 +2001,33 @@ export const make = Effect.gen(function* () { [mergeRequestDetail(input), labelPermission(input)], { concurrency: 2 }, ); - // Only a closed or merged merge request offers its branch for deletion, so an open one, - // the page most often read, skips the extra query. + // Only a closed or merged merge request offers its branch for deletion, and only an open + // fork's has maintainer edits to change, so each extra read is skipped elsewhere. const detail = read.state === "open" - ? { ...read, viewerCanEditLabels } + ? input.maintainerEdits === false || read.maintainerCanModify === undefined + ? { ...read, viewerCanEditLabels } + : { + ...read, + viewerCanEditLabels, + viewerCanEditMaintainerEdits: yield* orWhenUnanswered( + graphqlRead({ + cwd: input.cwd, + host: input.host, + operation: "getMaintainerEditsPermission", + query: MAINTAINER_EDITS_PERMISSION_GRAPHQL_QUERY, + variables: { fullPath: input.repository, iid: String(input.number) }, + decode: decodeMaintainerEditsPermissionJson, + }), + false, + ), + } : { ...read, viewerCanEditLabels, - viewerCanDeleteBranch: yield* sourceBranch(input).pipe( - Effect.map((source) => source?.canDelete === true), - // The answer gates one optional action; an unusable CLI or account still surfaces. - Effect.catchIf( - (cause) => - cause._tag !== "GitLabCliUnavailableError" && - cause._tag !== "GitLabCliAuthenticationError" && - cause._tag !== "GitLabCliRateLimitError", - () => Effect.succeed(false), - ), + viewerCanDeleteBranch: yield* orWhenUnanswered( + sourceBranch(input).pipe(Effect.map((source) => source?.canDelete === true)), + false, ), }; if (input.downstreamChecks === false || detail.headPipeline === undefined) return detail; @@ -2469,6 +2481,9 @@ export const make = Effect.gen(function* () { stdin: JSON.stringify({ ...(input.title === undefined ? {} : { title: input.title }), ...(input.description === undefined ? {} : { description: input.description }), + ...(input.allowCollaboration === undefined + ? {} + : { allow_collaboration: input.allowCollaboration }), }), }).pipe(Effect.asVoid); }), diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts index e2adb243b9703..926e793297a8e 100644 --- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts @@ -145,6 +145,7 @@ describe("gitLabViewerPermissions", () => { resolve: true, verdicts: ["comment", "approve", "request-changes"], requestReviewers: true, + maintainerEdits: false, labels: true, updateMethods: ["rebase"], }); @@ -157,6 +158,7 @@ describe("gitLabViewerPermissions", () => { resolve: true, verdicts: ["comment", "approve", "request-changes"], requestReviewers: true, + maintainerEdits: false, labels: false, }); }); @@ -190,13 +192,17 @@ describe("getChangeRequest base freshness", () => { }; it.effect.each(["getChangeRequestPreview", "getChangeRequestSummary"] as const)( - "%s preserves merge request fields without fetching project settings", + "%s preserves merge request fields without fetching project settings or fork permissions", (operation) => Effect.gen(function* () { + const detailInputs: Array<{ readonly maintainerEdits?: boolean }> = []; const provider = yield* make.pipe( Effect.provide( Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({ - getMergeRequestDetail: () => Effect.succeed(detail), + getMergeRequestDetail: (input) => { + detailInputs.push(input); + return Effect.succeed(detail); + }, getListStates: () => Effect.succeed(new Map()), listMergeRequestStats: () => Effect.succeed([]), @@ -208,6 +214,7 @@ describe("getChangeRequest base freshness", () => { expect( yield* read({ cwd: "/w", repository: "acme/web", host: "gitlab.com", number: 7 }), ).toEqual(detail); + expect(detailInputs.map((input) => input.maintainerEdits)).toEqual([false]); }), ); diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts index 4247008c273d1..ca0e9ffde5a96 100644 --- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts +++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts @@ -44,7 +44,7 @@ const CAPABILITIES: PullRequestCapabilities = { }, reviewers: { request: true, listCandidates: true }, labels: true, - edit: { changeRequest: true, comment: true }, + edit: { changeRequest: true, comment: true, maintainerEdits: true }, }; const UNAVAILABLE_REQUIREMENT = { @@ -68,6 +68,7 @@ const MERGE_ACTIONS: ReadonlySet = new Set([ /** Authors may close/reopen/change draft state regardless of role; REST omits authorship. */ export function gitLabViewerPermissions(input: { readonly viewerCanMerge: boolean; + readonly viewerCanEditMaintainerEdits?: boolean | undefined; readonly viewerCanDeleteBranch?: boolean; readonly viewerCanEditLabels?: boolean | undefined; }): PullRequestViewerPermissions { @@ -81,6 +82,7 @@ export function gitLabViewerPermissions(input: { resolve: true, verdicts: CAPABILITIES.review.verdicts, requestReviewers: true, + maintainerEdits: input.viewerCanEditMaintainerEdits === true, labels: input.viewerCanEditLabels === true, ...(input.viewerCanMerge ? { updateMethods: CAPABILITIES.updateMethods } : {}), }; @@ -321,12 +323,17 @@ export const make = Effect.gen(function* () { // Merge settings only affect the detail panel's actions. getChangeRequestPreview: (input) => - cli.getMergeRequestDetail(input).pipe(Effect.mapError(fail("getChangeRequestPreview"))), + cli + .getMergeRequestDetail({ ...input, maintainerEdits: false }) + .pipe(Effect.mapError(fail("getChangeRequestPreview"))), getChangeRequestSummary: (input) => Effect.all( [ - mergeRequestWithStats(input), + mergeRequestWithStats( + input, + cli.getMergeRequestDetail({ ...input, maintainerEdits: false }), + ), listStates({ cwd: input.cwd, host: input.host, @@ -582,6 +589,9 @@ export const make = Effect.gen(function* () { number: input.number, ...(input.title === undefined ? {} : { title: input.title }), ...(input.body === undefined ? {} : { description: input.body }), + ...(input.maintainerCanModify === undefined + ? {} + : { allowCollaboration: input.maintainerCanModify }), }) .pipe(Effect.mapError(fail("updateChangeRequest"))), ), diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts index 602d5971f0995..e1115cd660363 100644 --- a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts +++ b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts @@ -92,6 +92,10 @@ const RawMergeRequestSchema = Schema.Struct({ squash: Schema.optional(Schema.NullOr(Schema.Boolean)), /** Only detail reads with include_diverged_commits_count return this expensive count. */ diverged_commits_count: Schema.optional(Schema.NullOr(Schema.Int)), + source_project_id: Schema.optional(Schema.NullOr(Schema.Int)), + target_project_id: Schema.optional(Schema.NullOr(Schema.Int)), + /** Null on merge requests from the same project, where it means nothing. */ + allow_collaboration: Schema.optional(Schema.NullOr(Schema.Boolean)), diff_refs: Schema.optional(Schema.NullOr(RawMergeRequestDiffRefs)), }); @@ -224,6 +228,9 @@ export interface GitLabMergeRequestDetail extends GitLabMergeRequestListItem { readonly diffRefs?: GitLabDiffRefs; /** On a fork the pipeline often belongs to the source project, not the target. */ readonly headPipeline?: { readonly id: number; readonly projectId: number }; + /** Whether target maintainers may push to the source branch. Only set on merge requests from forks. */ + readonly maintainerCanModify?: boolean; + readonly viewerCanEditMaintainerEdits?: boolean; } function toActor(raw: Schema.Schema.Type | null | undefined) { @@ -524,6 +531,11 @@ function toDetail(raw: Schema.Schema.Type): GitLab ...(raw.head_pipeline?.id == null || raw.head_pipeline.project_id == null ? {} : { headPipeline: { id: raw.head_pipeline.id, projectId: raw.head_pipeline.project_id } }), + ...(raw.source_project_id != null && + raw.target_project_id != null && + raw.source_project_id !== raw.target_project_id + ? { maintainerCanModify: raw.allow_collaboration === true } + : {}), }; } @@ -1864,6 +1876,67 @@ export function decodeLabelPermissionJson(raw: string): Result.Result { + const decoded = decodeMaintainerEditsPermission(raw); + if (Result.isFailure(decoded)) return Result.fail(decoded.failure); + const { currentUser, project } = decoded.success.data; + const mergeRequest = project?.mergeRequest; + const isPublicOrInternal = (visibility: string | null | undefined) => + visibility === "public" || visibility === "internal"; + return Result.succeed( + currentUser !== null && + mergeRequest?.author?.username === currentUser.username && + mergeRequest.userPermissions.pushToSourceBranch && + !mergeRequest.sourceBranchProtected && + isPublicOrInternal(project?.visibility) && + isPublicOrInternal(mergeRequest.sourceProject?.visibility), + ); +} + /** Per-file line counts for one merge request, which the code/tests/generated breakdown sorts. */ export const MERGE_REQUEST_FILE_STATS_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!) { project(fullPath: $fullPath) { From c52df24d285a072ad9c3f7ab5b3656c0be1cb0f5 Mon Sep 17 00:00:00 2001 From: Antony <97451137+TonybynMp4@users.noreply.github.com> Date: Fri, 6 Nov 2026 02:54:01 +0100 Subject: [PATCH 004/181] fix(prs): reviewer menu searches past the first page and keeps GitLab's requested reviewers (#22489) Co-authored-by: Claude Opus 5.5 Co-authored-by: maria-rcks Co-authored-by: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> --- .../PullRequestReviewersScreen.tsx | 69 ++++++--- .../src/pullRequest/PullRequestService.ts | 4 +- .../pullRequest/PullRequestReviewerPicker.tsx | 62 +++++++-- .../pullRequest/PullRequestSummaryTab.tsx | 1 + packages/client-runtime/package.json | 4 + .../src/pullRequestReviewers.test.ts | 131 ++++++++++++++++++ .../src/pullRequestReviewers.ts | 101 ++++++++++++++ .../client-runtime/src/state/pullRequests.ts | 28 +++- packages/contracts/src/pullRequest.ts | 12 ++ packages/contracts/src/rpc.ts | 3 +- .../server/AzureDevOpsPullRequestProvider.ts | 2 +- .../server/BitbucketPullRequestProvider.ts | 2 +- .../src/server/PullRequestProvider.ts | 6 +- .../src/server/ForgejoPullRequestProvider.ts | 2 +- .../src/server/GitCafePullRequestProvider.ts | 2 +- .../src/server/GitHubPullRequestApi.test.ts | 48 +++++++ .../src/server/GitHubPullRequestApi.ts | 5 +- .../src/server/GitHubPullRequestProvider.ts | 2 +- .../src/server/gitHubPullRequestJson.ts | 7 +- .../src/server/pullRequestReads.graphql | 4 +- .../src/server/pullRequestReads.graphql.ts | 8 +- .../src/server/GitLabPullRequestCli.test.ts | 97 +++++++++++++ .../src/server/GitLabPullRequestCli.ts | 44 ++++-- .../server/GitLabPullRequestProvider.test.ts | 4 + .../src/server/GitLabPullRequestProvider.ts | 3 +- .../src/server/gitLabMergeRequestJson.ts | 7 + 26 files changed, 593 insertions(+), 65 deletions(-) create mode 100644 packages/client-runtime/src/pullRequestReviewers.test.ts create mode 100644 packages/client-runtime/src/pullRequestReviewers.ts diff --git a/apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsx index dad9ba1c1aaa8..e4a698dee5ea3 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsx @@ -6,6 +6,11 @@ import { useAtomValue } from "@effect/atom-react"; import { useNavigation, type StaticScreenProps } from "@react-navigation/native"; import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; +import { + hostReviewerQuery, + reviewerCandidateView, + type ReviewerTruncation, +} from "@t3tools/client-runtime/pull-request-reviewers"; import type { PullRequestReviewerCandidate } from "@t3tools/contracts"; import { useRef, useState } from "react"; import { FlatList, Pressable, ScrollView, View } from "react-native"; @@ -17,10 +22,21 @@ import { Button } from "../../components/ui/Button"; import { SymbolView } from "../../components/ui/AppSymbol"; import { composerPullRequests } from "../../state/pull-requests"; import { useEnvironmentQuery } from "../../state/query"; +import { useDebouncedValue } from "../../state/queries"; import { useAtomCommand } from "../../state/use-atom-command"; import { PullRequestAvatar } from "./PullRequestPresentation"; import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff"; +const TRUNCATED_LABELS: Record string> = { + unsearchable: () => + "The provider has more reviewers than it returned. Find additional reviewers on the provider.", + searchable: () => "The provider has more reviewers than are listed here. Search to find them.", + "search-failed": (error) => + `Only listed reviewers are matched: the provider search failed. ${error ?? ""}`, + "search-truncated": () => + "More reviewers match than the provider returned. Keep typing to narrow it down.", +}; + export function PullRequestReviewersScreen({ route }: StaticScreenProps) { const navigation = useNavigation(); const contentTopInset = useContentTopInset(); @@ -51,16 +67,30 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps(null); const [error, setError] = useState(null); const inFlight = useRef(false); - const candidates = (() => { - const needle = query.trim().toLowerCase(); - return [...(result.data?.candidates ?? [])] - .filter((candidate) => - `${candidate.login} ${candidate.name ?? ""}`.toLowerCase().includes(needle), - ) - .sort( - (a, b) => Number(b.isRequested) - Number(a.isRequested) || a.login.localeCompare(b.login), - ); - })(); + const debouncedQuery = useDebouncedValue(query.trim(), 250); + const searchInput = { + loaded: result.data, + searchable: pr?.capabilities.reviewers.searchCandidates === true, + query, + debouncedQuery, + }; + const hostQuery = hostReviewerQuery(searchInput); + const searchResult = useEnvironmentQuery( + hostQuery !== null + ? composerPullRequests.reviewerSearch({ + ...target, + input: { ...target.input, query: hostQuery }, + }) + : null, + ); + const view = reviewerCandidateView({ + ...searchInput, + search: searchResult, + }); + const candidates = [...view.candidates].sort( + (a, b) => Number(b.isRequested) - Number(a.isRequested) || a.login.localeCompare(b.login), + ); + const queryError = result.error ?? view.searchError; // A new search shows its best matches from the top. const search = (next: string) => { setQuery(next); @@ -93,6 +123,7 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps ) : ( - {result.error ?
+ } + /> + ); +} + /** Signed out of T3 Connect, the row offers to sign in instead of its switch. */ function GuestLinksRowWithSignIn() { const { isSignedIn } = useAuth(); diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index f7156f33bb333..4c890c05aa4e9 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -468,6 +468,14 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/labs", searchTerms: ["beta boring sidebar folder rows multiline branch pull request details"], }, + { + id: "tool-call-visibility", + title: "Tool calls in chat", + to: "/settings/labs", + searchTerms: [ + "beta hide tool calls commands edits searches work log activity quiet chat zen final answers only", + ], + }, { id: "guest-links", title: "Guest links", diff --git a/docs/user/activity-log.md b/docs/user/activity-log.md index 0aad505e0faed..221e58e006c2f 100644 --- a/docs/user/activity-log.md +++ b/docs/user/activity-log.md @@ -17,3 +17,14 @@ Failed calls do not count as successful messages or creations. Waiting on a thre it finished, and an interrupt or cancellation request does not mean the thread stopped. When tool details are unavailable, summaries use a broader description instead of guessing how many threads were affected. + +## Hide tool calls + +**Settings → Labs → Tool calls in chat** hides commands, file edits, searches, and MCP tool calls +from the conversation. **Hide successful** shows a call while it runs and keeps +it only if it fails. **Hide all** hides every call and shows **Thinking** while the agent works. +**Zen** also hides the agent's in-between messages, so each turn shows your message +and the agent's last reply, which appears when the turn ends. If you steer while the agent is +answering, the answer it finished before reading your steer stays too. On web and desktop, Find +shows the in-between messages while it is open. Approvals, questions, and errors always show. The +setting applies to this browser or device only. diff --git a/packages/client-runtime/src/work-log/presentation.ts b/packages/client-runtime/src/work-log/presentation.ts index 9fa515e793947..fd0dca831e06d 100644 --- a/packages/client-runtime/src/work-log/presentation.ts +++ b/packages/client-runtime/src/work-log/presentation.ts @@ -9,6 +9,7 @@ import { type OrchestrationV2TurnItem, type ThreadId, } from "@t3tools/contracts"; +import type { ToolCallVisibility } from "@t3tools/contracts/settings"; import { resolveT3McpSummaryAction, resolveT3McpToolDefinition, @@ -318,6 +319,23 @@ export function workEntryDisplayIndicatesToolFailure(entry: WorkLogPresentationE )); } +const HIDEABLE_TOOL_CALL_ITEM_TYPES: ReadonlySet = new Set([ + "command_execution", + "file_change", + "file_search", + "web_search", + "dynamic_tool", +]); + +export function workEntryHiddenByToolCallVisibility( + entry: WorkLogPresentationEntry, + visibility: ToolCallVisibility, +): boolean { + if (visibility === "showAll" || !HIDEABLE_TOOL_CALL_ITEM_TYPES.has(entry.itemType)) return false; + if (visibility !== "hideSuccessful") return true; + return entry.toolLifecycleStatus === "completed" && !workEntryDisplayIndicatesToolFailure(entry); +} + function workLogEntryIsLocalCodeSearch(entry: WorkLogPresentationEntry): boolean { return ( entry.itemType === "file_search" || diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index c35193aa6f8cc..8a4b25589121c 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -342,6 +342,9 @@ export type ChatWidth = typeof ChatWidth.Type; export const EffortDisplay = Schema.Literals(["label", "bars"]); export type EffortDisplay = typeof EffortDisplay.Type; +export const ToolCallVisibility = Schema.Literals(["showAll", "hideSuccessful", "hideAll", "zen"]); +export type ToolCallVisibility = typeof ToolCallVisibility.Type; + export const ModelFavorite = Schema.Struct({ provider: ProviderInstanceId, model: TrimmedNonEmptyString, @@ -499,6 +502,9 @@ export const ClientSettingsSchema = Schema.Struct({ boringSidebarMultilineRows: Schema.Boolean.pipe( Schema.withDecodingDefault(Effect.succeed(false)), ), + toolCallVisibility: ToolCallVisibility.pipe( + Schema.withDecodingDefault(Effect.succeed("showAll" as const)), + ), // Retired Labs toggle. Still read as the default for the Usage item in threadDetailsItems. threadDetailsUsageEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), // Sparse show/hide overrides for thread details card items. Missing ids use the client's @@ -1877,6 +1883,7 @@ export const ClientSettingsPatch = Schema.Struct({ showSkillsInSlashMenu: Schema.optionalKey(Schema.Boolean), boringSidebarEnabled: Schema.optionalKey(Schema.Boolean), boringSidebarMultilineRows: Schema.optionalKey(Schema.Boolean), + toolCallVisibility: Schema.optionalKey(ToolCallVisibility), threadDetailsUsageEnabled: Schema.optionalKey(Schema.Boolean), threadDetailsItems: Schema.optionalKey(Schema.Record(Schema.String, Schema.Boolean)), legacySidebarEnabled: Schema.optionalKey(Schema.Boolean), From 4a087861d0764654c0e9f450f40015aea03d50a7 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Thu, 5 Nov 2026 20:07:47 -0800 Subject: [PATCH 007/181] feat(scheduled-tasks): tasks link to their thread (#31764) Co-authored-by: Claude Opus 5.5 --- .../SettingsScheduledTasksRouteScreen.tsx | 14 ++++++++++ .../settings/ScheduledTasksSettings.tsx | 27 ++++++++++++++++++- 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx index 34dd75e7500e8..6e90e449359ca 100644 --- a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx @@ -18,7 +18,9 @@ import { MAX_WEBHOOK_DELIVERY_AGE_MINUTES, MAX_WEBHOOK_FILTERS, resolveEnvironmentMachineKind, + scheduledTaskThreadMode, } from "@t3tools/contracts"; +import { useSelectWorkspaceDetail } from "../layout/workspace/useSelectWorkspaceDetail"; import type { MenuAction } from "@react-native-menu/menu"; import { DateTimePicker } from "@expo/ui/community/datetime-picker"; import { @@ -1412,6 +1414,7 @@ function EnvironmentTasks({ label: "scheduled task delete", reportFailure: false, }); + const selectDetail = useSelectWorkspaceDetail(); const failure = (title: string, result: AtomCommandResult) => { if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { Dialog.alert(title, String(squashAtomCommandFailure(result))); @@ -1493,6 +1496,9 @@ function EnvironmentTasks({ {task.lastRunStatus} ) : null} + {task.threadId !== null && scheduledTaskThreadMode(task) !== "new_thread" ? ( + + ) : null} {task.lastRunError ? {task.lastRunError} : null} } @@ -847,6 +852,26 @@ function ScheduledTaskRow({ ); } +function ScheduledTaskThreadLink({ + environmentId, + threadId, +}: { + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; +}) { + const ref = scopeThreadRef(environmentId, threadId); + const title = useQuietThreadShell(ref)?.title.trim(); + return ( + + {title || "Open thread"} + + ); +} + function WebhookDeliveriesDialog({ environmentId, task, From 260d84387fbfbf97c0b7391e3f95e9d10429cdd2 Mon Sep 17 00:00:00 2001 From: maco Date: Fri, 6 Nov 2026 05:20:50 +0100 Subject: [PATCH 008/181] fix(shared): recognize numeric bare-repository config (#27500) Co-authored-by: maria-rcks --- packages/shared/src/git.test.ts | 41 +++++++++++++++++++++++++++++++++ packages/shared/src/git.ts | 17 +++++++++++++- 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/packages/shared/src/git.test.ts b/packages/shared/src/git.test.ts index a788abb1d1d7e..a21a52cb70e7c 100644 --- a/packages/shared/src/git.test.ts +++ b/packages/shared/src/git.test.ts @@ -66,6 +66,47 @@ describe("normalizeGitRemoteUrl", () => { }); describe("isBareGitConfig", () => { + it("reads Git's numeric booleans without accepting invalid or overflowing values", () => { + for (const value of [ + "true", + "yes", + "on", + "1", + "2", + "-1", + "+1", + "01", + "0x10", + "1k", + "1m", + "1g", + "2147483647", + "-2147483648", + ]) { + expect(isBareGitConfig(`[core]\nbare = ${value}\n`), value).toBe(true); + } + for (const value of [ + "false", + "no", + "off", + "0", + "-0", + "00", + "0x0", + "0k", + "08", + "1.5", + "2no", + "2g", + "2147483648", + "-2147483649", + ]) { + expect(isBareGitConfig(`[core]\nbare = ${value}\n`), value).toBe(false); + } + expect(isBareGitConfig("[core]\nbare = 2\nbare = 0\n")).toBe(false); + expect(isBareGitConfig("[core]\nbare = false\nbare = -2\n")).toBe(true); + }); + it("reads continued bare values after comments and at end of input", () => { const config = ["[core] bare = false # ignored backslash \\", 'bare = "tr\\', 'ue"'].join("\n"); diff --git a/packages/shared/src/git.ts b/packages/shared/src/git.ts index ba7c9f0a97b70..9f7c6c3227ef5 100644 --- a/packages/shared/src/git.ts +++ b/packages/shared/src/git.ts @@ -213,6 +213,21 @@ function parseGitConfigValue(raw: string): string { return out.trim(); } +function isTrueGitConfigValue(value: string): boolean { + if (value === "true" || value === "yes" || value === "on") return true; + const numeric = /^([+-]?)(0x[0-9a-f]+|0[0-7]*|[1-9][0-9]*)([kmg]?)$/.exec(value); + if (numeric === null) return false; + const digits = numeric[2]!; + const magnitude = digits.startsWith("0x") + ? Number.parseInt(digits.slice(2), 16) + : Number.parseInt(digits, digits.startsWith("0") ? 8 : 10); + const scale = + numeric[3] === "k" ? 1024 : numeric[3] === "m" ? 1024 ** 2 : numeric[3] === "g" ? 1024 ** 3 : 1; + const number = magnitude * scale * (numeric[1] === "-" ? -1 : 1); + // Git's boolean parser accepts integers only within its signed 32-bit range. + return number !== 0 && number >= -2147483648 && number <= 2147483647; +} + export function isBareGitConfig(configText: string): boolean { let inCore = false; let bare = false; @@ -228,7 +243,7 @@ export function isBareGitConfig(configText: string): boolean { const match = /^bare\s*(?:=(.*)|[#;].*)?$/i.exec(line); if (match === null) continue; const value = match[1] === undefined ? "true" : parseGitConfigValue(match[1]).toLowerCase(); - bare = value === "true" || value === "yes" || value === "on" || value === "1"; + bare = isTrueGitConfigValue(value); } return bare; } From a530cab2bdcec09360fb69ec730bc9a1dca5821d Mon Sep 17 00:00:00 2001 From: Alex Southwell Date: Fri, 6 Nov 2026 04:21:08 +0000 Subject: [PATCH 009/181] fix(server): a command id reused for two threads at once no longer succeeds for both (#18385) Co-authored-by: SAPHID Co-authored-by: Claude Opus 5.5 Co-authored-by: maria-rcks --- .../Orchestrator.receipt-race.test.ts | 168 ++++++++++++++++++ .../src/orchestration-v2/Orchestrator.ts | 118 +++++++----- 2 files changed, 241 insertions(+), 45 deletions(-) create mode 100644 apps/server/src/orchestration-v2/Orchestrator.receipt-race.test.ts diff --git a/apps/server/src/orchestration-v2/Orchestrator.receipt-race.test.ts b/apps/server/src/orchestration-v2/Orchestrator.receipt-race.test.ts new file mode 100644 index 0000000000000..3e6fdd19eb9dc --- /dev/null +++ b/apps/server/src/orchestration-v2/Orchestrator.receipt-race.test.ts @@ -0,0 +1,168 @@ +import { vi } from "vite-plus/test"; +import { assert, it } from "@effect/vitest"; +import { + CommandId, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Layer from "effect/Layer"; +import * as Ref from "effect/Ref"; +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; +import * as Orchestrator from "./Orchestrator.ts"; +import * as ProjectionStore from "./ProjectionStore.ts"; +import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; +import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts"; +import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; + +const instanceId = ProviderInstanceId.make("codex"); +const modelSelection = { instanceId, model: "gpt-5.1-codex" }; +// Holds model-selection planning until both racing commands have read no receipt. +let capabilityGate: Effect.Effect | undefined; +const adapter = { + instanceId, + driver: ProviderDriverKind.make("codex"), + getCapabilities: () => + (capabilityGate ?? Effect.void).pipe(Effect.as(CodexProviderCapabilitiesV2)), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }), + openSession: () => Effect.die("No provider process needed for metadata controls"), +} as ProviderAdapter.ProviderAdapterV2["Service"]; +const layerDatabase = SqlitePersistence.layerMemory; +const layerTest = Layer.mergeAll( + layerDatabase, + ProjectionStore.layer.pipe(Layer.provide(layerDatabase)), + ProviderReplayHarness.layerWithRegistry( + { name: "receipt-race" }, + ProviderAdapterRegistry.layerFromAdapters([adapter]), + { databaseLayer: layerDatabase, runEffectWorker: false }, + ), +); + +it.effect("a command id reused concurrently for two threads succeeds for only one", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const threadIds = [ThreadId.make("thread:race-a"), ThreadId.make("thread:race-b")]; + for (const threadId of threadIds) { + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make(`create:${threadId}`), + threadId, + projectId: ProjectId.make("project:receipt-race"), + title: threadId, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdBy: "user", + creationSource: "web", + }); + } + + const arrived = yield* Ref.make(0); + const bothArrived = yield* Deferred.make(); + capabilityGate = Effect.gen(function* () { + if ((yield* Ref.updateAndGet(arrived, (count) => count + 1)) === 2) { + yield* Deferred.succeed(bothArrived, undefined); + } + yield* Deferred.await(bothArrived); + }); + const setModel = (threadId: ThreadId) => + orchestrator.dispatch({ + type: "thread.model-selection.set", + commandId: CommandId.make("command:shared"), + threadId, + modelSelection: { ...modelSelection, model: "gpt-6" }, + }); + const exits = yield* Effect.forEach(threadIds, (threadId) => Effect.exit(setModel(threadId)), { + concurrency: "unbounded", + }).pipe(Effect.ensuring(Effect.sync(() => (capabilityGate = undefined)))); + + const winner = exits.findIndex(Exit.isSuccess); + const loser = exits.findIndex(Exit.isFailure); + assert.isAtLeast(winner, 0); + assert.isAtLeast(loser, 0); + const winnerExit = exits[winner]!; + const loserExit = exits[loser]!; + assert.isTrue(Exit.isSuccess(winnerExit) && Exit.isFailure(loserExit)); + if (Exit.isFailure(loserExit)) { + const error = Cause.findErrorOption(loserExit.cause); + assert.isTrue(error._tag === "Some"); + if (error._tag === "Some") { + assert.equal(error.value._tag, "OrchestratorCommandIdConflictError"); + if (error.value._tag === "OrchestratorCommandIdConflictError") { + assert.equal(error.value.receiptThreadId, threadIds[winner]); + assert.equal(error.value.commandThreadId, threadIds[loser]); + } + } + } + + const models = yield* Effect.forEach(threadIds, (threadId) => + projections.getThreadShell(threadId).pipe(Effect.map((shell) => shell?.modelSelection.model)), + ); + assert.equal(models[winner], "gpt-6"); + assert.equal(models[loser], "gpt-5.1-codex"); + + const noOpArrived = yield* Ref.make(0); + const bothNoOpsArrived = yield* Deferred.make(); + const getThreadRecords = projections.getThreadRecords; + using _records = vi.spyOn(projections, "getThreadRecords").mockImplementation((...args) => + Effect.gen(function* () { + if ((yield* Ref.updateAndGet(noOpArrived, (count) => count + 1)) === 2) { + yield* Deferred.succeed(bothNoOpsArrived, undefined); + } + yield* Deferred.await(bothNoOpsArrived); + return yield* getThreadRecords(...args); + }), + ); + const closeShare = (threadId: ThreadId) => + orchestrator.dispatch({ + type: "thread.guest-share.close", + commandId: CommandId.make("command:shared-noop"), + threadId, + }); + const noOpExits = yield* Effect.forEach( + threadIds, + (threadId) => Effect.exit(closeShare(threadId)), + { + concurrency: "unbounded", + }, + ); + const noOpWinner = noOpExits.findIndex(Exit.isSuccess); + const noOpLoser = noOpExits.findIndex(Exit.isFailure); + assert.isAtLeast(noOpWinner, 0); + assert.isAtLeast(noOpLoser, 0); + const noOpFailure = noOpExits[noOpLoser]!; + if (Exit.isFailure(noOpFailure)) { + const error = Cause.findErrorOption(noOpFailure.cause); + assert.isTrue(error._tag === "Some"); + if (error._tag === "Some") { + assert.equal(error.value._tag, "OrchestratorCommandIdConflictError"); + } + } + const noOpReplay = yield* closeShare(threadIds[noOpWinner]!); + const noOpSuccess = noOpExits[noOpWinner]!; + if (Exit.isSuccess(noOpSuccess)) { + assert.equal(noOpReplay.sequence, noOpSuccess.value.sequence); + assert.deepEqual(noOpReplay.storedEvents, []); + } + + // The winner's own thread still replays its receipt. + const replay = yield* setModel(threadIds[winner]!); + if (Exit.isSuccess(winnerExit)) { + assert.equal(replay.sequence, winnerExit.value.sequence); + assert.isAbove(replay.storedEvents.length, 0); + assert.deepEqual( + replay.storedEvents.map((stored) => stored.sequence), + winnerExit.value.storedEvents.map((stored) => stored.sequence), + ); + } + }).pipe(Effect.provide(layerTest)), +); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index d40ca624a11d2..8bf0c20de98eb 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -110,7 +110,7 @@ import { isNativeMaintenanceCommand, resolveMessageDispatchIntent, } from "./CommandPolicy.ts"; -import { CommandReceiptStoreV2 } from "./CommandReceiptStore.ts"; +import { CommandReceiptStoreV2, type CommandReceiptV2 } from "./CommandReceiptStore.ts"; import { ContextHandoffServiceV2, readForkHistoryItems, @@ -13741,6 +13741,54 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }; }); + const replayCommandReceipt = Effect.fn("orchestrationV2.dispatch.replayReceipt")(function* ( + command: OrchestrationV2ServerCommand, + receipt: CommandReceiptV2, + ) { + if (receipt.status === "rejected") { + return yield* new OrchestratorCommandPreviouslyRejectedError({ + commandId: command.commandId, + commandType: command.type, + detail: receipt.error ?? "Previously rejected.", + }); + } + const dispatchThreadId = commandThreadId(command); + // Receipts only prove execution for the thread they were recorded against. + if (receipt.threadId !== dispatchThreadId) { + return yield* new OrchestratorCommandIdConflictError({ + commandId: command.commandId, + commandType: command.type, + receiptThreadId: receipt.threadId, + commandThreadId: dispatchThreadId, + }); + } + const storedEvents = yield* eventSink.readByCommandId({ commandId: command.commandId }).pipe( + Stream.runCollect, + Effect.map((events): ReadonlyArray => Array.from(events)), + Effect.mapError( + (cause) => + new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause, + }), + ), + ); + if (command.type === "queue.resume" || command.type === "queued-run.start") { + yield* mapDispatchError(command)( + startNextQueuedRun( + command.threadId, + command.type === "queued-run.start" ? { queuedRunId: command.runId } : undefined, + ), + ); + } + return { + sequence: receipt.resultSequence, + storedEvents, + replayed: true, + } satisfies OrchestratorV2DispatchResult; + }); + /** `sideChatIds` are the live side chats a `thread.delete` cascades to, read under their locks. */ const dispatchWithReceiptEffect = Effect.fn("orchestrationV2.dispatch.withReceipt")(function* ( command: OrchestrationV2ServerCommand, @@ -13764,49 +13812,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ); if (Option.isSome(existingReceipt)) { - const receipt = existingReceipt.value; - if (receipt.status === "rejected") { - return yield* new OrchestratorCommandPreviouslyRejectedError({ - commandId: command.commandId, - commandType: command.type, - detail: receipt.error ?? "Previously rejected.", - }); - } - const dispatchThreadId = commandThreadId(command); - // Receipts only prove execution for the thread they were recorded against. - if (receipt.threadId !== dispatchThreadId) { - return yield* new OrchestratorCommandIdConflictError({ - commandId: command.commandId, - commandType: command.type, - receiptThreadId: receipt.threadId, - commandThreadId: dispatchThreadId, - }); - } - const storedEvents = yield* eventSink.readByCommandId({ commandId: command.commandId }).pipe( - Stream.runCollect, - Effect.map((events): ReadonlyArray => Array.from(events)), - Effect.mapError( - (cause) => - new OrchestratorDispatchError({ - commandId: command.commandId, - commandType: command.type, - cause, - }), - ), - ); - if (command.type === "queue.resume" || command.type === "queued-run.start") { - yield* mapDispatchError(command)( - startNextQueuedRun( - command.threadId, - command.type === "queued-run.start" ? { queuedRunId: command.runId } : undefined, - ), - ); - } - return { - sequence: receipt.resultSequence, - storedEvents, - replayed: true, - } satisfies OrchestratorV2DispatchResult; + return yield* replayCommandReceipt(command, existingReceipt.value); } // Recheck under the lock; the user may have raised modes since sender preflight. @@ -13921,10 +13927,22 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }), ), ); + if (!inserted) { + const receipt = yield* mapDispatchError(command)( + commandReceipts.getByCommandId(command.commandId), + ); + if (Option.isNone(receipt)) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: "Conflicting receipt is not a thread command receipt.", + }); + } + return yield* replayCommandReceipt(command, receipt.value); + } return { sequence: resultSequence, storedEvents: [], - ...(inserted ? {} : { replayed: true as const }), } satisfies OrchestratorV2DispatchResult; } const acceptedAt = plan.events.at(-1)?.occurredAt ?? (yield* DateTime.now); @@ -13961,6 +13979,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio detail: committed.receipt.error ?? "Previously rejected.", }); } + // A concurrent command with this id for another thread can commit first, + // under that thread's lock; its receipt is not this command's result. + if (committed.receipt.threadId !== commandThreadId(command)) { + return yield* new OrchestratorCommandIdConflictError({ + commandId: command.commandId, + commandType: command.type, + receiptThreadId: committed.receipt.threadId, + commandThreadId: commandThreadId(command), + }); + } if ( command.type === "queue.resume" || command.type === "queued-run.start" || From 693ac5f5df23a8fd8432ce73c356d05edc40bd0a Mon Sep 17 00:00:00 2001 From: Alyx Buckmann <57874862+snarkyalyx@users.noreply.github.com> Date: Fri, 6 Nov 2026 05:21:26 +0100 Subject: [PATCH 010/181] fix(server): coalesce tool output before it fills the live buffer (#16317) Co-authored-by: maria-rcks --- .../orchestration-v2/LiveStreamBudget.test.ts | 57 +++++++++++++++++ .../ThreadLiveEventCoalescer.test.ts | 63 ++++++++++++++++++- .../ThreadLiveEventCoalescer.ts | 50 ++++++++++----- 3 files changed, 151 insertions(+), 19 deletions(-) diff --git a/apps/server/src/orchestration-v2/LiveStreamBudget.test.ts b/apps/server/src/orchestration-v2/LiveStreamBudget.test.ts index 39f31bfedc7db..44e66412fcd52 100644 --- a/apps/server/src/orchestration-v2/LiveStreamBudget.test.ts +++ b/apps/server/src/orchestration-v2/LiveStreamBudget.test.ts @@ -87,6 +87,63 @@ describe("bufferLatestLiveStream", () => { }); describe("replayAndBufferProjectedLiveEvents", () => { + it.effect.each(["items", "bytes"] as const)( + "replays the undelivered tail after a %s overflow without losing or duplicating events", + (limit) => + Effect.scoped( + Effect.gen(function* () { + const pubsub = yield* PubSub.unbounded(); + const subscribed = yield* Deferred.make>(); + const events = [ + { sequence: 1, text: "one" }, + { sequence: 2, text: "two" }, + { sequence: 3, text: "three" }, + ]; + const limits = limit === "items" ? { maxItems: 1 } : { maxSerializedBytes: 40 }; + const pull = yield* Stream.toPull( + replayAndBufferProjectedLiveEvents( + { + project: (event: Event) => event, + subscribe: PubSub.subscribe(pubsub).pipe( + Effect.tap((subscription) => Deferred.succeed(subscribed, subscription)), + ), + latestSequence: Effect.succeed(1), + replay: () => Stream.succeed(events[0]!), + }, + limits, + ), + ); + const received = [...(yield* pull)]; + // Hold the ACK while more durable events arrive. + yield* PubSub.publishAll(pubsub, events.slice(1)); + yield* (yield* Deferred.await(subscribed)).shutdownHook.await; + const overflow = yield* pull.pipe(Effect.result); + expect(overflow._tag).toBe("Failure"); + if (overflow._tag === "Failure") + expect(overflow.failure._tag).toBe("LiveStreamBufferError"); + + const afterSequence = received.at(-1)!.sequence; + const resumed = yield* replayAndBufferProjectedLiveEvents( + { + project: (event: Event) => event, + subscribe: PubSub.subscribe(pubsub), + afterSequence, + latestSequence: Effect.succeed(3), + replay: (throughSequence) => + Stream.fromIterable( + events.filter( + (event) => event.sequence > afterSequence && event.sequence <= throughSequence, + ), + ), + }, + limits, + ).pipe(Stream.take(2), Stream.runCollect); + expect([...received, ...resumed]).toEqual(events); + expect(yield* PubSub.size(pubsub)).toBe(0); + }), + ), + ); + it.effect.each(["high-water", "replay"] as const)( "unsubscribes and cancels a blocked %s read on live overflow", (phase) => diff --git a/apps/server/src/orchestration-v2/ThreadLiveEventCoalescer.test.ts b/apps/server/src/orchestration-v2/ThreadLiveEventCoalescer.test.ts index 294ed0622d62e..7b91e479b98ef 100644 --- a/apps/server/src/orchestration-v2/ThreadLiveEventCoalescer.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLiveEventCoalescer.test.ts @@ -36,6 +36,7 @@ function makeToolActivity( readonly kind?: "tool.updated" | "tool.completed"; readonly toolCallId?: string; readonly turnId?: RunId; + readonly output?: string; } = {}, ): ThreadEvent { const itemRunId = options.turnId ?? runId; @@ -66,7 +67,7 @@ function makeToolActivity( completedAt: status === "completed" ? now : null, updatedAt: now, input: "echo app.ts", - output: `output-${sequence}`, + output: options.output ?? `output-${sequence}`, }, }, }; @@ -155,6 +156,62 @@ function makeTextItem( } describe("ThreadLiveEventCoalescer", () => { + it.effect.each(["items", "bytes"] as const)( + "replaces superseded tool output before charging the %s budget", + (limit) => + Effect.scoped( + Effect.gen(function* () { + const updates = Array.from({ length: 1_100 }, (_, index) => makeToolActivity(index + 1)); + const latest = updates.at(-1)!; + const coalescer = yield* makeThreadLiveEventCoalescer( + limit === "items" + ? { maxItems: 1 } + : { maxSerializedBytes: Buffer.byteLength(encodeEvent(latest)) }, + ); + yield* coalescer.offerAll(updates); + expect(yield* coalescer.usage).toEqual({ + retainedItems: 1, + retainedSerializedBytes: Buffer.byteLength(encodeEvent(latest)), + }); + yield* coalescer.end; + expect(yield* coalescer.stream.pipe(Stream.runCollect)).toEqual([latest]); + expect(yield* coalescer.usage).toEqual({ retainedItems: 0, retainedSerializedBytes: 0 }); + }), + ), + ); + + it.effect("handles a tool output burst larger than the default 8 MiB buffer", () => + Effect.scoped( + Effect.gen(function* () { + const coalescer = yield* makeThreadLiveEventCoalescer(); + const updates = Array.from({ length: 150 }, (_, index) => + makeToolActivity(index + 1, { output: "x".repeat(64 * 1024) }), + ); + yield* coalescer.offerAll(updates); + yield* coalescer.end; + expect(yield* coalescer.stream.pipe(Stream.runCollect)).toEqual([updates.at(-1)]); + }), + ), + ); + + it.effect("still fails when a single replacement exceeds the byte budget", () => + Effect.scoped( + Effect.gen(function* () { + const first = makeToolActivity(1); + const coalescer = yield* makeThreadLiveEventCoalescer({ + maxSerializedBytes: Buffer.byteLength(encodeEvent(first)), + }); + yield* coalescer.offer(first); + const overflow = yield* coalescer + .offer(makeToolActivity(2, { output: "x".repeat(2_000) })) + .pipe(Effect.result); + expect(overflow._tag).toBe("Failure"); + yield* coalescer.closed; + expect(yield* coalescer.usage).toEqual({ retainedItems: 0, retainedSerializedBytes: 0 }); + }), + ), + ); + it("preserves tool-call identity switches as insertion-order boundaries", () => { const events = [ makeToolActivity(1, { toolCallId: "call-a" }), @@ -399,8 +456,8 @@ describe("ThreadLiveEventCoalescer", () => { yield* TestClock.adjust("40 millis"); yield* coalescer.offerAll(latest); expect(yield* coalescer.usage).toEqual({ - retainedItems: 4, - retainedSerializedBytes: serializedBytes([...first, ...latest]), + retainedItems: 2, + retainedSerializedBytes: serializedBytes(latest), }); yield* TestClock.adjust("10 millis"); const expectedUsage = { diff --git a/apps/server/src/orchestration-v2/ThreadLiveEventCoalescer.ts b/apps/server/src/orchestration-v2/ThreadLiveEventCoalescer.ts index 00adbb0cb5445..33c82dfe4ef4c 100644 --- a/apps/server/src/orchestration-v2/ThreadLiveEventCoalescer.ts +++ b/apps/server/src/orchestration-v2/ThreadLiveEventCoalescer.ts @@ -90,7 +90,9 @@ export const makeThreadLiveEventCoalescer = Effect.fn( E | LiveStreamBufferError | Cause.Done >(); const mutex = yield* Semaphore.make(1); - let pendingUpdates: Array> = []; + const pendingUpdates = new Set>(); + const latestUpdates = new Map>(); + const pendingKeys = new Map(); let windowGeneration = 0; let windowFiber: Fiber.Fiber | null = null; let closed = false; @@ -106,14 +108,13 @@ export const makeThreadLiveEventCoalescer = Effect.fn( }); const flushPending = Effect.fnUntraced(function* () { - if (pendingUpdates.length === 0) { + if (pendingUpdates.size === 0) { return; } - const items = yield* budget.replace( - pendingUpdates, - coalesceLiveUpdatedEvents(pendingUpdates.map((item) => item.value)), - ); - pendingUpdates = []; + const items = Array.from(pendingUpdates); + pendingUpdates.clear(); + latestUpdates.clear(); + pendingKeys.clear(); yield* Queue.offerAll(output, items); }, Effect.uninterruptible); @@ -131,7 +132,6 @@ export const makeThreadLiveEventCoalescer = Effect.fn( } }), ), - Effect.catchTags({ LiveStreamBufferError: () => Effect.void }), ); // Keep each source batch together so a synchronization marker cannot pass @@ -143,18 +143,28 @@ export const makeThreadLiveEventCoalescer = Effect.fn( (input) => Effect.gen(function* () { yield* budget.check; - if (input.kind === "event") { - yield* budget.retain(input).pipe( - Effect.tap((item) => Effect.sync(() => pendingUpdates.push(item))), + const startsWindow = pendingUpdates.size === 0; + const key = input.kind === "event" ? coalescibleUpdateKey(input) : null; + if (input.kind === "event" && key !== null) { + const pendingKey = pendingKeys.get(input.event.type); + if (pendingKey !== undefined && pendingKey !== key) latestUpdates.clear(); + pendingKeys.set(input.event.type, key); + const previous = latestUpdates.get(key); + yield* budget.replace(previous ? [previous] : [], [input]).pipe( + Effect.tap(([item]) => + Effect.sync(() => { + if (previous) pendingUpdates.delete(previous); + pendingUpdates.add(item!); + latestUpdates.set(key, item!); + }), + ), Effect.uninterruptible, ); - } - if (input.kind === "event" && coalescibleUpdateKey(input) !== null) { - if (pendingUpdates.length === 1) { + if (startsWindow) { const generation = ++windowGeneration; windowFiber = yield* Effect.forkIn(flushWindow(generation), coalescerScope); } - if (pendingUpdates.length >= MAX_PENDING_UPDATES) { + if (pendingUpdates.size >= MAX_PENDING_UPDATES) { yield* cancelWindow(); windowGeneration += 1; yield* flushPending(); @@ -162,6 +172,12 @@ export const makeThreadLiveEventCoalescer = Effect.fn( return; } + if (input.kind === "event") { + yield* budget.retain(input).pipe( + Effect.tap((item) => Effect.sync(() => pendingUpdates.add(item))), + Effect.uninterruptible, + ); + } yield* cancelWindow(); windowGeneration += 1; yield* flushPending(); @@ -187,7 +203,9 @@ export const makeThreadLiveEventCoalescer = Effect.fn( windowGeneration += 1; yield* cancelWindow(); budget.release(pendingUpdates); - pendingUpdates = []; + pendingUpdates.clear(); + latestUpdates.clear(); + pendingKeys.clear(); budget.release(yield* Queue.clear(output).pipe(Effect.orElseSucceed(() => []))); if (cause) { yield* Queue.failCause(output, cause); From cedaa0de48e6ab2b6fc5d18ee115df2e262b797a Mon Sep 17 00:00:00 2001 From: Kayzel Date: Fri, 6 Nov 2026 05:21:44 +0100 Subject: [PATCH 011/181] perf(server): Windows git reads no longer start a console host (#19288) --- apps/server/src/vcs/GitVcsDriverCore.ts | 5 +++- packages/shared/src/shell.test.ts | 31 +++++++++++++++++++ packages/shared/src/shell.ts | 40 +++++++++++++++++++++++++ 3 files changed, 75 insertions(+), 1 deletion(-) diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 94404b488b136..d1199f39c6542 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -36,7 +36,7 @@ import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { compactTraceAttributes } from "@t3tools/shared/observability"; import { decodeJsonResult } from "@t3tools/shared/schemaJson"; -import { resolveSpawnCommand } from "@t3tools/shared/shell"; +import { resolveSpawnCommand, runsGitWithoutConsole } from "@t3tools/shared/shell"; import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile"; import { resolveProjectFileBackedSetting } from "@t3tools/shared/projectSettings"; import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../observability/Metrics.ts"; @@ -993,6 +993,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd: commandInput.cwd, env: spawnEnv, forceKillAfter: input.forceKillAfterMs, + ...(runsGitWithoutConsole(hostPlatform, executable, commandInput.args) + ? { detached: true, windowsHide: true } + : {}), }), ) .pipe( diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index 5f268ffa507ea..16dc69ab14c05 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -32,6 +32,7 @@ import { resolveCommandPath, resolveSpawnCommand, resolveWindowsEnvironment, + runsGitWithoutConsole, SpawnExecutableResolution, WindowsShellEnvironment, withPathDirectoryListings, @@ -561,6 +562,36 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { ); }); +describe("runsGitWithoutConsole", () => { + const git = "C:\\Program Files\\Git\\ucrt64\\bin\\git.exe"; + + it.each([ + [["rev-parse", "--git-path", "index"], true], + [["--git-dir", "C:\\repo\\.git", "symbolic-ref", "refs/remotes/origin/HEAD"], true], + [["remote", "get-url", "--", "origin"], true], + [["config", "--get", "branch.main.pushRemote"], true], + [["symbolic-ref", "--quiet", "HEAD"], true], + [["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"], true], + [["rev-parse", "HEAD"], false], + [["symbolic-ref", "HEAD", "refs/heads/x"], false], + [["symbolic-ref", "-qd", "refs/remotes/origin/HEAD"], false], + [["config", "--get", "--edit"], false], + [["-c", "core.pager=x", "config", "--get", "user.name"], false], + ])("Git for Windows %j without a console: %s", (args, expected) => { + expect(runsGitWithoutConsole("win32", git, args)).toBe(expected); + }); + + it.each([ + ["win32", "C:\\Program Files\\Git\\cmd\\git.exe"], + ["win32", "C:\\Users\\x\\scoop\\shims\\git.exe"], + ["linux", git], + ] as const)("keeps the console on %s for %s", (platform, executable) => { + expect(runsGitWithoutConsole(platform, executable, ["rev-parse", "--show-toplevel"])).toBe( + false, + ); + }); +}); + describe("preferGitForWindowsBinary", () => { const files = (...paths: Array) => diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index 28b666ce05531..ad30c152a07c0 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -827,6 +827,46 @@ export interface SpawnCommandOptions extends CommandAvailabilityOptions { readonly bypassNpmShim?: boolean; } +// `*` is one argument that is not an option. These forms read refs or config +// only, so git starts no hook, helper, pager, editor or lazy fetch for them. +const CONSOLE_FREE_GIT_READS = [ + "rev-parse --git-path index", + "rev-parse --git-common-dir", + "rev-parse --show-toplevel", + "rev-parse --symbolic-full-name HEAD", + "rev-parse --abbrev-ref --symbolic-full-name @{upstream}", + "symbolic-ref --quiet HEAD", + "symbolic-ref *", + "remote", + "remote get-url *", + "remote get-url -- *", + "config --get *", +].map((form) => form.split(" ")); + +export function runsGitWithoutConsole( + platform: NodeJS.Platform, + executable: string, + args: ReadonlyArray, +): boolean { + if (platform !== "win32") return false; + const { basename, dirname } = NodePath.win32; + const bin = dirname(executable); + const build = basename(dirname(bin)).toLowerCase(); + if (basename(executable).toLowerCase() !== "git.exe" || basename(bin).toLowerCase() !== "bin") { + return false; + } + if (!GIT_FOR_WINDOWS_BUILDS.some((candidate) => candidate === build)) return false; + const rest = + args[0] === "--git-dir" && args[1] !== undefined && !args[1].startsWith("-") + ? args.slice(2) + : args; + return CONSOLE_FREE_GIT_READS.some( + (form) => + form.length === rest.length && + form.every((part, i) => part === rest[i] || (part === "*" && !rest[i]!.startsWith("-"))), + ); +} + export const resolveSpawnCommand = Effect.fnUntraced(function* ( command: string, args: ReadonlyArray, From 37f9134bea549a18c6bf798678aabcb87d9cffd4 Mon Sep 17 00:00:00 2001 From: Alex Southwell Date: Fri, 6 Nov 2026 04:22:03 +0000 Subject: [PATCH 012/181] fix(server): a publish whose first push fails still shows the new remote (#29688) Co-authored-by: Claude Opus 5.5 Co-authored-by: maria-rcks <254055478+maria-rcks@users.noreply.github.com> --- apps/server/src/ws.test.ts | 92 ++++++++++++++++++++++++++++++++++++++ apps/server/src/ws.ts | 8 +++- 2 files changed, 98 insertions(+), 2 deletions(-) diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index bf2298427e411..855e59440ace4 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -4,12 +4,15 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import { AuthSessionId, + AuthSourceControlWriteScope, EnvironmentId, ProjectId, ThreadId, ProviderDriverKind, ProviderInstanceId, + SourceControlRepositoryError, WS_METHODS, + WsRpcGroup, WsServerRefreshProvidersRpc, WsSubscribeServerConfigRpc, type OrchestrationV2StoredEvent, @@ -63,6 +66,7 @@ import * as ModelManifest from "./provider/ModelManifest.ts"; import * as Orchestrator from "./orchestration-v2/Orchestrator.ts"; import * as OtlpEndpointCheck from "./observability/OtlpEndpointCheck.ts"; import * as PairingGrantStore from "./auth/PairingGrantStore.ts"; +import * as RpcAuthorization from "./auth/RpcAuthorization.ts"; import * as PeerLinkRequests from "./peer/PeerLinkRequests.ts"; import * as PeerLinks from "./peer/PeerLinks.ts"; import * as PortScanner from "./preview/PortScanner.ts"; @@ -1240,6 +1244,94 @@ it.effect("on-demand clients get provider config without workspace snapshots", ( ), ); +it.effect("a publish whose push fails still refreshes the new remote", () => + Effect.gen(function* () { + const refreshes = yield* Queue.unbounded(); + const exits = yield* Queue.unbounded(); + const services = Layer.mergeAll( + layerUnusedConfigRpcServices, + Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({ + publishRepository: (input) => + Effect.fail( + new SourceControlRepositoryError({ + provider: input.provider, + operation: "publishRepository", + detail: 'Created owner/repo and added it as remote "origin", but the push failed.', + }), + ), + }), + Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({ + resolve: (cwd, options) => + Queue.offer(refreshes, `identity ${cwd} refresh=${options?.refresh === true}`).pipe( + Effect.as(null), + ), + }), + Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({ + refreshStatus: (cwd) => + Queue.offer(refreshes, `status ${cwd}`).pipe(Effect.andThen(Effect.die("unused"))), + }), + Layer.mock(ExternalLauncher.ExternalLauncher)({}), + Layer.mock(ProviderRegistry.ProviderRegistry)({}), + Layer.mock(UsageLimitSources.UsageLimitSources)({}), + Layer.mock(RemoteOpenTargets.RemoteOpenTargets)({}), + Layer.mock(DirectEndpoints.DirectEndpoints)({}), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/unused" }), + Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}), + Layer.mock(ServerEnvironment.ServerEnvironment)({}), + Layer.mock(EnvironmentAuth.EnvironmentAuth)({}), + ); + const server = yield* RpcServer.makeNoSerialization(WsRpcGroup, { + ...WS_RPC_SERVER_OPTIONS, + onFromServer: (response) => + response._tag === "Exit" ? Queue.offer(exits, response.exit._tag) : Effect.void, + }).pipe( + Effect.provide( + layerWsRpc( + { + sessionId: AuthSessionId.make("publish-test"), + subject: "publish-test", + method: "browser-session-cookie", + scopes: [AuthSourceControlWriteScope], + }, + {}, + yield* ServerBrowser.ServerBrowser, + () => Effect.void, + { secretReferences: true }, + ).pipe( + Layer.provide(services), + Layer.merge(RpcAuthorization.layer([AuthSourceControlWriteScope])), + ), + ), + ); + yield* server.write(0, { + _tag: "Request", + id: RpcMessage.RequestId("publish"), + tag: WS_METHODS.sourceControlPublishRepository, + payload: { + cwd: "/repo", + provider: "github", + repository: "owner/repo", + visibility: "private", + }, + headers: Headers.empty, + }); + assert.equal(yield* Queue.take(exits), "Failure"); + assert.deepEqual( + [yield* Queue.take(refreshes), yield* Queue.take(refreshes)], + ["identity /repo refresh=true", "status /repo"], + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + Layer.fresh(layerConfigSources), + Layer.mock(PreviewAutomationBroker.PreviewAutomationBroker)({}), + Layer.mock(ServerBrowser.ServerBrowser)({}), + ), + ), + Effect.scoped, + ), +); + // Pruned history cannot be replayed: a cursor below the boundary must resync from a snapshot. it.effect.each(["thread", "shell"] as const)( "%s resume from a cursor below the pruned boundary loads a snapshot", diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index e3c7fdaa47476..079adfb19ce44 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -2921,8 +2921,12 @@ export const layerWsRpc = ( [WS_METHODS.subscribeProjectClones]: () => projectCloneTracker.stream, [WS_METHODS.sourceControlPublishRepository]: (input) => sourceControlRepositories.publishRepository(input).pipe( - Effect.tap(() => repositoryIdentityResolver.resolve(input.cwd, { refresh: true })), - Effect.tap(() => refreshGitStatus(input.cwd)), + // A failed push still leaves the new remote added. + Effect.ensuring( + repositoryIdentityResolver + .resolve(input.cwd, { refresh: true }) + .pipe(Effect.andThen(refreshGitStatus(input.cwd))), + ), ), [WS_METHODS.projectsSearchEntries]: (input) => workspaceEntries.search(input).pipe( From 68d5f7ab6c0a3103f5d0de582e81189c2397609e Mon Sep 17 00:00:00 2001 From: Alex Southwell Date: Fri, 6 Nov 2026 04:22:20 +0000 Subject: [PATCH 013/181] fix(server): reverting files removes what a new .gitignore from the turn was hiding (#29795) Co-authored-by: Claude Opus 5.5 Co-authored-by: maria-rcks --- apps/server/src/vcs/GitVcsDriver.test.ts | 40 ++++++++++++++++++ apps/server/src/vcs/GitVcsDriver.ts | 54 +++++++++++++++++++----- 2 files changed, 84 insertions(+), 10 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriver.test.ts b/apps/server/src/vcs/GitVcsDriver.test.ts index b79f93c192d4e..ec8809d895f6d 100644 --- a/apps/server/src/vcs/GitVcsDriver.test.ts +++ b/apps/server/src/vcs/GitVcsDriver.test.ts @@ -193,6 +193,7 @@ it.effect("checkpoint capture skips untracked nested repositories without a comm `160000 commit ${nestedHead}\tcommitted\n`, ); assert.deepEqual(yield* fileSystem.readFile(path.join(cwd, ".git", "index")), originalIndex); + assert.isTrue(yield* driver.checkpoints.restoreCheckpoint({ cwd, checkpointRef })); assert.strictEqual( yield* fileSystem.readFileString(path.join(cwd, nested, "private.txt")), "nested\n", @@ -1126,6 +1127,8 @@ it.effect("restores empty checkpoints without changing paths outside the workspa yield* fileSystem.writeFileString(path.join(cwd, "ignored.txt"), "keep\n"); yield* fileSystem.makeDirectory(path.join(cwd, "untracked")); yield* fileSystem.writeFileString(path.join(cwd, "untracked", "file.txt"), "remove\n"); + yield* fileSystem.writeFileString(path.join(cwd, "untracked", ".gitignore"), "hidden.txt\n"); + yield* fileSystem.writeFileString(path.join(cwd, "untracked", "hidden.txt"), "remove\n"); assert.isTrue( yield* driver.checkpoints.restoreCheckpoint({ cwd, checkpointRef, fallbackToHead: false }), ); @@ -1143,6 +1146,43 @@ it.effect("restores empty checkpoints without changing paths outside the workspa }); assert.strictEqual(staged.stdout.trim(), "outside.txt"); } + yield* fileSystem.writeFileString(path.join(cwd, "checkpoint.txt"), "checkpoint\n"); + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); + yield* fileSystem.writeFileString(path.join(cwd, "checkpoint.txt"), "later\n"); + let deepest = cwd; + for (let depth = 0; depth < 4; depth++) { + yield* fileSystem.writeFileString(path.join(deepest, ".gitignore"), "d/.gitignore\n"); + deepest = path.join(deepest, "d"); + yield* fileSystem.makeDirectory(deepest); + } + yield* fileSystem.writeFileString(path.join(deepest, ".gitignore"), "hidden.txt\n"); + yield* fileSystem.writeFileString(path.join(deepest, "hidden.txt"), "remove\n"); + const incomplete = yield* driver.checkpoints + .restoreCheckpoint({ cwd, checkpointRef, fallbackToHead: false }) + .pipe(Effect.flip); + assert.strictEqual(incomplete._tag, "VcsProcessExitError"); + assert.strictEqual( + yield* fileSystem.readFileString(path.join(cwd, "checkpoint.txt")), + "checkpoint\n", + ); + assert.strictEqual( + (yield* driver.execute({ + operation: "test", + cwd, + args: ["diff", "--cached", "--name-only", "--", "."], + })).stdout, + "", + ); + if (nested) { + assert.strictEqual( + (yield* driver.execute({ + operation: "test", + cwd: root, + args: ["diff", "--cached", "--name-only"], + })).stdout.trim(), + "outside.txt", + ); + } } }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index a2cd548bcc0b9..d120605d6961f 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -1343,13 +1343,52 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( }), ), ); + const resetIndex = Effect.gen(function* () { + // On Windows clean can remove './' and exit 0. + yield* recreateWorkspace; + yield* execute({ + operation, + cwd: input.cwd, + args: [...longPaths, "reset", "--quiet", "--", "."], + }); + }); yield* recreateWorkspace; - const cleaned = yield* execute({ + const clean = execute({ operation, cwd: input.cwd, args: [...longPaths, "clean", "-fd", "--", "."], + env: { LC_ALL: "C" }, allowNonZeroExit: true, }); + let cleaned = yield* clean; + // Removing a new .gitignore exposes the files it hid; clean again until nothing is left. + for ( + let pass = 1; + pass < 4 && cleaned.exitCode === 0 && /^Removing /m.test(cleaned.stdout); + pass++ + ) { + yield* recreateWorkspace; + cleaned = yield* clean; + } + if (cleaned.exitCode === 0 && /^Removing /m.test(cleaned.stdout)) { + yield* recreateWorkspace; + const remaining = yield* execute({ + operation, + cwd: input.cwd, + args: [...longPaths, "clean", "-dn", "--", "."], + env: { LC_ALL: "C" }, + }); + if (/^Would remove /m.test(remaining.stdout)) { + yield* resetIndex; + return yield* new VcsProcessExitError({ + operation, + command: "git clean", + cwd: input.cwd, + exitCode: 0, + detail: "Could not clean the checkpoint workspace: untracked files remain.", + }); + } + } if (cleaned.exitCode !== 0) { // Git can remove every child, then fail trying to remove './' itself. const emptiedWorkspace = @@ -1359,7 +1398,8 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( Effect.map((entries) => entries.length === 0), Effect.orElseSucceed(() => false), )); - if (!emptiedWorkspace) + if (!emptiedWorkspace) { + yield* resetIndex; return yield* new VcsProcessExitError({ operation, command: "git clean", @@ -1367,15 +1407,9 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( exitCode: cleaned.exitCode, detail: cleaned.stderr.trim() || "Could not clean the checkpoint workspace.", }); + } } - // On Windows the same clean can remove './' and exit 0. - yield* recreateWorkspace; - - yield* execute({ - operation, - cwd: input.cwd, - args: [...longPaths, "reset", "--quiet", "--", "."], - }); + yield* resetIndex; return true; }), From fba1997db4438ff2cd3fea72751af07be35f8b51 Mon Sep 17 00:00:00 2001 From: Muzammil Hussain <58479501+Muzammil-Bit@users.noreply.github.com> Date: Fri, 6 Nov 2026 09:22:38 +0500 Subject: [PATCH 014/181] fix(server): Codex titles no longer fail on ChatGPT accounts without gpt-6-luna (#30078) Co-authored-by: Claude Opus 5.5 --- .../CodexTextGeneration.test.ts | 93 +++++++++++++++++-- .../src/textGeneration/CodexTextGeneration.ts | 31 +++++-- 2 files changed, 109 insertions(+), 15 deletions(-) diff --git a/apps/server/src/textGeneration/CodexTextGeneration.test.ts b/apps/server/src/textGeneration/CodexTextGeneration.test.ts index 9dc4f176e3078..926f17053fb11 100644 --- a/apps/server/src/textGeneration/CodexTextGeneration.test.ts +++ b/apps/server/src/textGeneration/CodexTextGeneration.test.ts @@ -163,6 +163,8 @@ function withFakeCodexEnv( launchArgs?: string; environment?: NodeJS.ProcessEnv; models?: ReadonlyArray; + defaultModel?: string; + customModels?: ReadonlyArray; managedRuntime?: boolean; }, effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect, @@ -171,7 +173,11 @@ function withFakeCodexEnv( const fs = yield* FileSystem.FileSystem; const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" }); const codexPath = yield* makeFakeCodexBinary(tempDir, input); - const config = decodeCodexSettings({ binaryPath: codexPath, launchArgs: input.launchArgs }); + const config = decodeCodexSettings({ + binaryPath: codexPath, + launchArgs: input.launchArgs, + customModels: input.customModels, + }); const textGeneration = yield* makeCodexTextGeneration( config, input.environment === undefined ? undefined : { ...process.env, ...input.environment }, @@ -180,6 +186,7 @@ function withFakeCodexEnv( slug, name: slug, isCustom: false, + ...(slug === input.defaultModel ? { isDefault: true } : {}), capabilities: null, })), ), @@ -224,15 +231,40 @@ it.layer(layerCodexTextGenerationTest)("CodexTextGeneration", (it) => { }), ); - it.effect.each(["gpt-5.6-luna", "openai.gpt-5.6-luna"])( - "dispatches the qualified live model for %s", - (selectedModel) => + it.effect.each([ + { + selectedModel: "gpt-5.6-luna", + models: ["openai.gpt-5.6-luna"], + expected: "openai.gpt-5.6-luna", + }, + { + selectedModel: "openai.gpt-5.6-luna", + models: ["openai.gpt-5.6-luna"], + expected: "openai.gpt-5.6-luna", + }, + { + selectedModel: "openai.gpt-5.6-luna", + models: ["gpt-6-astra", "gpt-5.6-luna"], + defaultModel: "gpt-6-astra", + expected: "gpt-5.6-luna", + }, + { + selectedModel: "gpt-6-luna", + models: ["gpt-5.6-luna", "gpt-6-astra"], + defaultModel: "gpt-6-astra", + expected: "gpt-6-astra", + }, + { selectedModel: "gpt-6-luna", models: ["gpt-5.6-luna"], expected: "gpt-5.6-luna" }, + { selectedModel: "gpt-6-luna", models: [], expected: "gpt-6-luna" }, + ])( + "dispatches $expected for $selectedModel from $models", + ({ selectedModel, models, defaultModel, expected }) => withFakeCodexEnv( { - output: JSON.stringify({ title: "Bedrock title" }), - models: ["openai.gpt-5.6-luna"], - requireArg: "--model openai.gpt-5.6-luna", - forbidArg: "--model gpt-5.6-luna", + output: JSON.stringify({ title: "Live title" }), + models, + ...(defaultModel ? { defaultModel } : {}), + requireArg: `--model ${expected}`, }, (textGeneration) => Effect.gen(function* () { @@ -241,11 +273,54 @@ it.layer(layerCodexTextGenerationTest)("CodexTextGeneration", (it) => { message: "Describe this change", modelSelection: createModelSelection(ProviderInstanceId.make("codex"), selectedModel), }); - expect(result.title).toBe("Bedrock title"); + expect(result.title).toBe("Live title"); }), ), ); + it.effect("drops the requested model's options when falling back to another model", () => + withFakeCodexEnv( + { + output: JSON.stringify({ title: "Live title" }), + models: ["gpt-6-astra"], + requireArg: '--model gpt-6-astra --config model_reasoning_effort="low"', + forbidArg: 'service_tier="priority"', + }, + (textGeneration) => + textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Describe this change", + modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-6-luna", [ + { id: "reasoningEffort", value: "none" }, + { id: "serviceTier", value: "priority" }, + ]), + }), + ), + ); + + it.effect("sends a configured custom model the managed snapshot leaves out", () => + withFakeCodexEnv( + { + output: JSON.stringify({ title: "Live title" }), + models: ["gpt-6-astra", "gpt-5.6-luna"], + defaultModel: "gpt-6-astra", + customModels: ["gpt-5.6-luna-preview"], + managedRuntime: true, + requireArg: '--model gpt-5.6-luna-preview --config model_reasoning_effort="high"', + }, + (textGeneration) => + textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Describe this change", + modelSelection: createModelSelection( + ProviderInstanceId.make("codex"), + "gpt-5.6-luna-preview", + [{ id: "reasoningEffort", value: "high" }], + ), + }), + ), + ); + it.effect("omits a persisted service tier for managed ChatGPT text generation", () => withFakeCodexEnv( { diff --git a/apps/server/src/textGeneration/CodexTextGeneration.ts b/apps/server/src/textGeneration/CodexTextGeneration.ts index e17fa4c4c00e7..cbf095b303abc 100644 --- a/apps/server/src/textGeneration/CodexTextGeneration.ts +++ b/apps/server/src/textGeneration/CodexTextGeneration.ts @@ -24,7 +24,11 @@ import { normalizeCliError, toJsonSchemaObject, } from "@t3tools/provider-core/server/textGenerationUtils"; -import { codexModelFamily, getModelSelectionStringOptionValue } from "@t3tools/shared/model"; +import { + codexModelFamily, + getModelSelectionStringOptionValue, + readCustomModelEntries, +} from "@t3tools/shared/model"; import { getCodexServiceTierOptionValue } from "../codexModelOptions.ts"; import * as HostProcess from "@t3tools/shared/HostProcess"; @@ -245,17 +249,32 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func const effectiveEnvironment = resolved?.environment ?? resolvedEnvironment; const models = yield* getModels; const requestedModel = modelSelection.model; - const model = + const listed = models.filter((candidate) => !candidate.isCustom); + // An unlisted slug is one this account can't run, e.g. gpt-6-luna on a ChatGPT login. + const requestedFamily = codexModelFamily(requestedModel); + const matchedModel = models.find((candidate) => candidate.slug === requestedModel)?.slug ?? - models.find( - (candidate) => !candidate.isCustom && codexModelFamily(candidate.slug) === requestedModel, + // Managed snapshots omit configured custom models; send those as requested. + readCustomModelEntries(codexConfig.customModels).find( + (entry) => entry.slug === requestedModel, )?.slug ?? + listed.find((candidate) => codexModelFamily(candidate.slug) === requestedFamily)?.slug; + const model = + matchedModel ?? + listed.find((candidate) => candidate.isDefault)?.slug ?? + listed.find((candidate) => !candidate.isLegacy)?.slug ?? + listed[0]?.slug ?? requestedModel; + // The selection's options were chosen for the requested model and may not fit a fallback. + const fellBack = matchedModel === undefined && model !== requestedModel; const launchArgs = resolveCodexLaunchArgs(effectiveConfig.launchArgs, effectiveEnvironment); const reasoningEffort = - getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ?? + (fellBack + ? undefined + : getModelSelectionStringOptionValue(modelSelection, "reasoningEffort")) ?? DEFAULT_TEXT_GENERATION_REASONING_EFFORT; - const serviceTier = resolved ? undefined : getCodexServiceTierOptionValue(modelSelection); + const serviceTier = + resolved || fellBack ? undefined : getCodexServiceTierOptionValue(modelSelection); const binary = effectiveConfig.binaryPath || "codex"; const env = { ...effectiveEnvironment, From 69726aac2f6f194c3e3582c134bfabcb44e6ca8c Mon Sep 17 00:00:00 2001 From: Alex Southwell Date: Fri, 6 Nov 2026 04:22:56 +0000 Subject: [PATCH 015/181] fix(desktop): quit no longer orphans a backend that is slow to stop (#22572) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 Co-authored-by: SAPHID Co-authored-by: maria-rcks --- apps/desktop/src/app/DesktopApp.ts | 4 +- .../src/backend/DesktopBackendManager.test.ts | 54 +++++++++++++++++++ .../src/backend/DesktopBackendManager.ts | 6 +++ apps/desktop/src/updates/DesktopUpdates.ts | 4 +- 4 files changed, 65 insertions(+), 3 deletions(-) diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.ts index 151c227e47ff4..5d877206d0e7d 100644 --- a/apps/desktop/src/app/DesktopApp.ts +++ b/apps/desktop/src/app/DesktopApp.ts @@ -1,6 +1,5 @@ import * as Cause from "effect/Cause"; import * as Config from "effect/Config"; -import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; @@ -19,6 +18,7 @@ import * as DesktopClerk from "./DesktopClerk.ts"; import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts"; import * as DesktopWindow from "../window/DesktopWindow.ts"; import * as PreviewPasskeys from "../preview/Passkeys.ts"; +import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts"; import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts"; import * as DesktopEnvironment from "./DesktopEnvironment.ts"; import * as DesktopLegacyLocalStorage from "./DesktopLegacyLocalStorage.ts"; @@ -160,7 +160,7 @@ const stopAllPoolInstances = Effect.fn("desktop.app.stopAllPoolInstances")( const instances = yield* pool.list; yield* Effect.forEach( instances, - (instance) => instance.stop({ timeout: Duration.seconds(5) }), + (instance) => instance.stop({ timeout: DesktopBackendManager.BACKEND_QUIT_STOP_TIMEOUT }), { concurrency: "unbounded" }, ); }, diff --git a/apps/desktop/src/backend/DesktopBackendManager.test.ts b/apps/desktop/src/backend/DesktopBackendManager.test.ts index e4714673777d9..2741daa1ddd07 100644 --- a/apps/desktop/src/backend/DesktopBackendManager.test.ts +++ b/apps/desktop/src/backend/DesktopBackendManager.test.ts @@ -720,4 +720,58 @@ describe("DesktopBackendManager", () => { }).pipe(Effect.provide(TestClock.layer())), ), ); + + it.effect("the quit stop deadline waits for a backend that only exits at the force kill", () => + Effect.scoped( + Effect.gen(function* () { + const spawned = yield* Deferred.make(); + const teardownStarted = yield* Deferred.make(); + const teardownFinished = yield* Deferred.make(); + // The real spawner sends SIGTERM, waits the grace, then SIGKILLs. A backend that + // ignores SIGTERM therefore finishes tearing down just after the grace. + const instance = yield* makeTestInstance({ + spawnerLayer: Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Effect.gen(function* () { + const scope = yield* Scope.Scope; + yield* Deferred.succeed(spawned, undefined); + yield* Scope.addFinalizer( + scope, + Deferred.succeed(teardownStarted, undefined).pipe( + Effect.andThen(Effect.sleep(Duration.seconds(6))), + Effect.andThen(Deferred.succeed(teardownFinished, undefined)), + Effect.asVoid, + ), + ); + return makeProcess({ + exitCode: Deferred.await(teardownFinished).pipe( + Effect.as(ChildProcessSpawner.ExitCode(0)), + ), + }); + }), + ), + ), + httpClientLayer: layerHttpClient(() => Effect.never), + }); + yield* instance.start; + yield* Deferred.await(spawned); + + // App quit and the updater stop every backend with this deadline. + const quitDone = yield* Deferred.make(); + const quitFiber = yield* instance + .stop({ timeout: DesktopBackendManager.BACKEND_QUIT_STOP_TIMEOUT }) + .pipe(Effect.andThen(Deferred.succeed(quitDone, undefined)), Effect.forkChild); + + yield* Deferred.await(teardownStarted); + // Past the SIGTERM grace but before the force kill lands: quit must still be waiting. + yield* TestClock.adjust(Duration.millis(5_500)); + assert.isFalse(yield* Deferred.isDone(quitDone)); + + yield* TestClock.adjust(Duration.millis(500)); + yield* Fiber.join(quitFiber); + assert.isTrue(yield* Deferred.isDone(teardownFinished)); + }).pipe(Effect.provide(TestClock.layer())), + ), + ); }); diff --git a/apps/desktop/src/backend/DesktopBackendManager.ts b/apps/desktop/src/backend/DesktopBackendManager.ts index 2f5b57c4e3c95..6e356a7c856bd 100644 --- a/apps/desktop/src/backend/DesktopBackendManager.ts +++ b/apps/desktop/src/backend/DesktopBackendManager.ts @@ -41,6 +41,12 @@ const DEFAULT_BACKEND_READINESS_INTERVAL = Duration.millis(100); const DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT = Duration.seconds(1); // Match the service launcher's grace period so backends can stop provider sessions. const DEFAULT_BACKEND_TERMINATE_GRACE = Duration.seconds(5); +// Allow SIGKILL and the spawner exit wait after the SIGTERM grace so quit cannot +// orphan a backend whose shutdown hangs. +export const BACKEND_QUIT_STOP_TIMEOUT = Duration.sum( + DEFAULT_BACKEND_TERMINATE_GRACE, + Duration.seconds(2), +); const DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT = Duration.seconds(5); const BACKEND_READINESS_PATH = "/.well-known/t3/environment"; // Three restarts without readiness is about 2 s of backoff: past a blip, early enough to help. diff --git a/apps/desktop/src/updates/DesktopUpdates.ts b/apps/desktop/src/updates/DesktopUpdates.ts index 6279e8b6141a8..14688e5258067 100644 --- a/apps/desktop/src/updates/DesktopUpdates.ts +++ b/apps/desktop/src/updates/DesktopUpdates.ts @@ -25,6 +25,7 @@ import * as Scope from "effect/Scope"; import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; +import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts"; import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts"; import * as DesktopConfig from "../app/DesktopConfig.ts"; import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; @@ -819,7 +820,8 @@ export const make = Effect.gen(function* () { yield* Ref.set(installRunningBackendsRef, runningInstances); yield* Effect.forEach( instances, - (instance) => instance.stop({ timeout: Duration.seconds(5) }), + (instance) => + instance.stop({ timeout: DesktopBackendManager.BACKEND_QUIT_STOP_TIMEOUT }), { concurrency: "unbounded" }, ); yield* electronUpdater.quitAndInstall({ From 596752cffe9fa1cce1c27159bfabe777fa45046f Mon Sep 17 00:00:00 2001 From: Andrei <108398860+Yuruzuu@users.noreply.github.com> Date: Fri, 6 Nov 2026 12:23:15 +0800 Subject: [PATCH 016/181] =?UTF-8?q?perf(server):=20GitHub=20activity=20rea?= =?UTF-8?q?ds=20skip=20PR-wide=20fields=20on=20later=20review-thread=20pag?= =?UTF-8?q?es=20(8.9=20s=20=E2=86=92=206.8=20s=20median)=20(#30294)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Claude Opus 5.5 Co-authored-by: maria-rcks --- .../src/server/GitHubPullRequestApi.test.ts | 130 +++++++++--------- .../src/server/GitHubPullRequestApi.ts | 70 +++++----- .../src/server/gitHubPullRequestJson.ts | 64 ++++++--- .../src/server/pullRequestReviews.graphql | 89 +++++++----- .../src/server/pullRequestReviews.graphql.ts | 88 +++++++++--- 5 files changed, 265 insertions(+), 176 deletions(-) diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts index 705a25b13e85f..f46c91fd69570 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts @@ -338,13 +338,14 @@ function threadComments( ids: ReadonlyArray, endCursor: string | null, totalCount = ids.length, + author: Readonly> | null = null, ) { return { totalCount, pageInfo: { hasNextPage: endCursor !== null, endCursor }, nodes: ids.map((id) => ({ id, - author: null, + author, body: id, createdAt: "2026-07-01T00:00:00Z", lastEditedAt: null, @@ -3455,67 +3456,31 @@ layer("GitHubPullRequestApi.layer", (it) => { }), ); - it.effect.each([false, true])( - "keeps thread cursors and reviewers after a refusal (later page: %s)", - (later) => - Effect.gen(function* () { - if (later) - mockedExecute.mockReturnValueOnce( - Effect.succeed( - output( - reviewThreadsPage([thread("T1", "c1")], "next", [ - { - __typename: "User", - login: "prior", - name: null, - avatarUrl: "https://avatars/prior", - }, - ]), - ), - ), - ); - mockedExecute.mockReturnValueOnce(refusedReviewerResponse()); - mockedExecute.mockReturnValueOnce( - Effect.succeed(output(reviewThreadsPage([thread("T2", "c2")], "last"))), - ); - mockedExecute.mockReturnValueOnce( - Effect.succeed(output(reviewThreadsPage([thread("T3", "c3")], null))), - ); - const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi; - const read = cli.listReviewThreadComments({ - ...pullRequestInput, - repository: `acme/refused-threads-${later}`, - }); - const conversation = yield* read; - expect( - variablesOf("ReviewThreads").map((v) => [v["after"], v["requestedReviewers"]]), - ).toEqual( - later - ? [ - [null, 50], - ["next", 50], - ["next", 0], - ["last", 0], - ] - : [ - [null, 50], - [null, 0], - ["last", 0], - ], - ); - expect(conversation.comments.map((c) => c.id)).toEqual( - later ? ["c1", "c2", "c3"] : ["c2", "c3"], - ); - expect(conversation.reviewers.map((r) => r.login)).toEqual(later ? ["prior"] : []); - expect(conversation.truncated).toBe(false); - - mockedExecute.mockReturnValueOnce(Effect.succeed(output(reviewThreadsPage([], null)))); - yield* read; - expect(variablesOf("ReviewThreads").at(-1)).toMatchObject({ - after: null, - requestedReviewers: 0, - }); - }), + it.effect("keeps thread cursors after a reviewer refusal", () => + Effect.gen(function* () { + mockedExecute.mockReturnValueOnce(refusedReviewerResponse()); + mockedExecute.mockReturnValueOnce( + Effect.succeed(output(reviewThreadsPage([thread("T2", "c2")], "last"))), + ); + mockedExecute.mockReturnValueOnce( + Effect.succeed(output(reviewThreadsPage([thread("T3", "c3")], null))), + ); + const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi; + const read = cli.listReviewThreadComments({ + ...pullRequestInput, + repository: "acme/refused-threads", + }); + const conversation = yield* read; + expect(variablesOf("ReviewThreads").map((v) => v["requestedReviewers"])).toEqual([50, 0]); + expect(variablesOf("ReviewThreadPages").map((v) => v["after"])).toEqual(["last"]); + expect(conversation.comments.map((c) => c.id)).toEqual(["c2", "c3"]); + expect(conversation.reviewers).toEqual([]); + expect(conversation.truncated).toBe(false); + + mockedExecute.mockReturnValueOnce(Effect.succeed(output(reviewThreadsPage([], null)))); + yield* read; + expect(variablesOf("ReviewThreads").at(-1)).toMatchObject({ requestedReviewers: 0 }); + }), ); it.effect("decodes reviewers, labels and workflow checks without another detail read", () => @@ -3767,10 +3732,32 @@ layer("GitHubPullRequestApi.layer", (it) => { it.effect("follows the cursor to the review threads the first page left behind", () => Effect.gen(function* () { mockedExecute.mockReturnValueOnce( - Effect.succeed(output(reviewThreadsPage([thread("PRRT_1", "c1")], "Y3Vyc29yOjE"))), + Effect.succeed( + output( + reviewThreadsPage([thread("PRRT_1", "c1")], "Y3Vyc29yOjE", [ + { __typename: "User", login: "prior", name: null, avatarUrl: "https://avatars/p" }, + ]), + ), + ), ); mockedExecute.mockReturnValueOnce( - Effect.succeed(output(reviewThreadsPage([thread("PRRT_2", "c2")], null))), + Effect.succeed( + output( + reviewThreadsPage( + [ + { + ...thread("PRRT_2", "c2"), + comments: threadComments(["c2"], null, 1, { + __typename: "Bot", + login: "later-bot", + avatarUrl: "https://avatars/later-bot", + }), + }, + ], + null, + ), + ), + ), ); const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi; @@ -3781,9 +3768,20 @@ layer("GitHubPullRequestApi.layer", (it) => { number: 7, }); - expect(varsAt(0)["after"]).toBeNull(); - expect(varsAt(1)["after"]).toBe("Y3Vyc29yOjE"); + expect(callAt(0)).toMatchObject({ operationName: "ReviewThreads" }); + // Later pages ask for the threads alone and keep the first page's PR-wide fields. + const later = callAt(1); + assert(later.kind === "graphql"); + expect(later).toMatchObject({ + operationName: "ReviewThreadPages", + variables: { after: "Y3Vyc29yOjE" }, + }); + for (const field of ["reviewRequests", "commits(", "reviewDismissals", "latestReviews"]) + expect(later.query).not.toContain(field); expect(conversation.comments.map((comment) => comment.id)).toEqual(["c1", "c2"]); + expect(conversation.reviewers.map((reviewer) => reviewer.login)).toEqual(["prior"]); + expect(conversation.avatarsByLogin.get("later-bot")).toBe("https://avatars/later-bot"); + expect(conversation.botLogins.has("later-bot")).toBe(true); assert.isFalse(conversation.truncated); }), ); diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.ts index c4fbbfcd9f64e..ce38cc726a249 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestApi.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestApi.ts @@ -33,7 +33,6 @@ import { type PullRequestListState, type PullRequestMergeMethod, type PullRequestOmittedFileStat, - type PullRequestReaction, type PullRequestReactionContent, type PullRequestReviewCommentDraft, type PullRequestReviewVerdict, @@ -95,6 +94,7 @@ import { toReviewDismissalsPage, toReviewerCandidates, toReviewThreadCommentsPage, + toLaterReviewThreadPage, toReviewThreadPage, toStackMembership, toViewerPermissions, @@ -2216,45 +2216,39 @@ export const make = Effect.gen(function* () { function* (input) { const { owner, name } = parseRepositorySelector(input.repository); const target = { ...input, operation: "listReviewThreadComments" }; - const threadPage = ( - after: string | null, - ): Effect.Effect => - readRequestedReviewers(input, 50, (requestedReviewers) => - client.ReviewThreads({ owner, name, number: input.number, after, requestedReviewers }), - ).pipe(graphql(target), Effect.map(toReviewThreadPage), Effect.flatMap(found(target))); - const entries: GitHubReviewThreadEntry[] = []; - const avatarsByLogin = new Map(); - const botLogins = new Set(); - let reviewers: ReadonlyArray = []; - let reactions: GitHubReviewThreadPage["reactions"] = []; - const reactionsById = new Map>(); - const editedAtById = new Map(); - let commits: GitHubReviewThreadPage["commits"] = []; - let viewer: GitHubReviewThreadPage["viewer"] = { canUpdate: true, didAuthor: false }; - const dismissalsByReviewId = new Map(); - let dismissalCursor: string | null = null; - let cursor: string | null = null; - let page = 0; - do { - const read: GitHubReviewThreadPage = yield* threadPage(cursor); - entries.push(...read.threads); - for (const login of read.botLogins) botLogins.add(login); - for (const [login, avatarUrl] of read.avatarsByLogin) + const first: GitHubReviewThreadPage = yield* readRequestedReviewers( + input, + 50, + (requestedReviewers) => + client.ReviewThreads({ owner, name, number: input.number, requestedReviewers }), + ).pipe(graphql(target), Effect.map(toReviewThreadPage), Effect.flatMap(found(target))); + const entries: GitHubReviewThreadEntry[] = [...first.threads]; + const avatarsByLogin = new Map(first.avatarsByLogin); + const botLogins = new Set(first.botLogins); + const { reviewers, reactions, reactionsById, editedAtById, commits, viewer } = first; + const dismissalsByReviewId = new Map(first.dismissalsByReviewId); + const dismissalCursor = first.nextDismissalCursor; + let cursor = first.nextCursor; + let page = 1; + // Later pages carry the threads alone; the PR-wide fields above come from the first. + while (cursor !== null && page < REVIEW_THREAD_PAGES) { + const later: Pick< + GitHubReviewThreadPage, + "threads" | "nextCursor" | "avatarsByLogin" | "botLogins" + > = yield* client + .ReviewThreadPages({ owner, name, number: input.number, after: cursor }) + .pipe( + graphql(target), + Effect.map(toLaterReviewThreadPage), + Effect.flatMap(found(target)), + ); + entries.push(...later.threads); + for (const login of later.botLogins) botLogins.add(login); + for (const [login, avatarUrl] of later.avatarsByLogin) avatarsByLogin.set(login, avatarUrl); - if (page === 0) { - reviewers = read.reviewers; - reactions = read.reactions; - for (const [id, entry] of read.reactionsById) reactionsById.set(id, entry); - for (const [id, editedAt] of read.editedAtById) editedAtById.set(id, editedAt); - commits = read.commits; - viewer = read.viewer; - for (const [id, message] of read.dismissalsByReviewId) - dismissalsByReviewId.set(id, message); - dismissalCursor = read.nextDismissalCursor; - } - cursor = read.nextCursor; + cursor = later.nextCursor; page += 1; - } while (cursor !== null && page < REVIEW_THREAD_PAGES); + } if (dismissalCursor !== null) { let after: string | null = dismissalCursor; diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.ts index 98a95a363e31d..a4c509e944488 100644 --- a/packages/source-control-github/src/server/gitHubPullRequestJson.ts +++ b/packages/source-control-github/src/server/gitHubPullRequestJson.ts @@ -75,6 +75,8 @@ import type { ReactionGroup, ReviewDismissals, ReviewThreadComments, + ReviewThreadPage, + ReviewThreadPages, ReviewThreads, ThreadComment, } from "./pullRequestReviews.graphql.ts"; @@ -1313,11 +1315,8 @@ type ReviewThreadsPullRequest = NonNullable< NonNullable["pullRequest"] >; -export function toReviewThreadPage(result: ReviewThreads.Result): GitHubReviewThreadPage | null { - const pullRequest = result.repository?.pullRequest; - if (pullRequest == null) return null; - const viewer = trimmed(result.viewer.login); - const threads = pullRequest.reviewThreads; +/** A page of threads and the people commenting on them, whichever query carried it. */ +function toReviewThreadEntries(threads: ReviewThreadPage, viewer: string | null) { const threadNodes = nodesOf(threads); const entries = threadNodes.flatMap((thread): ReadonlyArray => { const path = trimmed(thread.path); @@ -1341,27 +1340,58 @@ export function toReviewThreadPage(result: ReviewThreads.Result): GitHubReviewTh }, ]; }); + return { + entries, + nextCursor: nextCursorOf(threads.pageInfo), + authors: threadNodes.flatMap((thread) => + nodesOf(thread.comments).map((comment) => comment.author), + ), + }; +} + +function collectActors(raws: ReadonlyArray) { + const avatarsByLogin = new Map(); + const botLogins = new Set(); + for (const raw of raws) { + const login = trimmed(raw?.login); + const avatarUrl = trimmed(raw?.avatarUrl); + if (login !== null && avatarUrl !== null) avatarsByLogin.set(login, avatarUrl); + if (login !== null && toActor(raw)?.isBot) botLogins.add(login); + } + return { avatarsByLogin, botLogins }; +} + +export function toLaterReviewThreadPage( + result: ReviewThreadPages.Result, +): Pick | null { + const threads = result.repository?.pullRequest?.reviewThreads; + if (threads === undefined) return null; + const { entries, nextCursor, authors } = toReviewThreadEntries( + threads, + trimmed(result.viewer.login), + ); + return { threads: entries, nextCursor, ...collectActors(authors) }; +} + +export function toReviewThreadPage(result: ReviewThreads.Result): GitHubReviewThreadPage | null { + const pullRequest = result.repository?.pullRequest; + if (pullRequest == null) return null; + const viewer = trimmed(result.viewer.login); + const page = toReviewThreadEntries(pullRequest.reviewThreads, viewer); const requestedReviewers = nodesOf(pullRequest.reviewRequests).map( (node): ActorFields | null => node.requestedReviewer, ); const latestReviews = nodesOf(pullRequest.latestReviews); const comments = nodesOf(pullRequest.comments); const reviews = nodesOf(pullRequest.reviews); - const avatarsByLogin = new Map(); - const botLogins = new Set(); - for (const raw of [ + const { avatarsByLogin, botLogins } = collectActors([ pullRequest.author, ...comments.map((node) => node.author), ...reviews.map((node) => node.author), ...requestedReviewers, ...latestReviews.map((node) => node.author), - ...threadNodes.flatMap((thread) => nodesOf(thread.comments).map((comment) => comment.author)), - ]) { - const login = trimmed(raw?.login); - const avatarUrl = trimmed(raw?.avatarUrl); - if (login !== null && avatarUrl !== null) avatarsByLogin.set(login, avatarUrl); - if (login !== null && toActor(raw)?.isBot) botLogins.add(login); - } + ...page.authors, + ]); const reviewers = new Map(); for (const raw of [...requestedReviewers, ...latestReviews.map((node) => node.author)]) { const actor = toActor(raw) ?? toRequestedTeam(raw); @@ -1391,8 +1421,8 @@ export function toReviewThreadPage(result: ReviewThreads.Result): GitHubReviewTh if (reactions.length > 0) reactionsById.set(id, reactions); } return { - threads: entries, - nextCursor: nextCursorOf(threads.pageInfo), + threads: page.entries, + nextCursor: page.nextCursor, reactions: toReactions(pullRequest.reactionGroups, viewer), reactionsById, editedAtById, diff --git a/packages/source-control-github/src/server/pullRequestReviews.graphql b/packages/source-control-github/src/server/pullRequestReviews.graphql index 96c35783dc1b6..94646874d803d 100644 --- a/packages/source-control-github/src/server/pullRequestReviews.graphql +++ b/packages/source-control-github/src/server/pullRequestReviews.graphql @@ -40,9 +40,39 @@ fragment ThreadComment on PullRequestReviewComment { ...Reactions } -# One page of review threads with their comments, and the people on the review. `$after` is null -# for the first page and the last page's `endCursor` after that, so a pull request with more -# threads than one page holds is walked rather than cut off. +# One page of review threads. Only ten comments ride with each thread. A hundred threads times a +# hundred comments made GitHub reserve 10,000 nested rows and charge 104 points; unfinished threads +# are paged from their own cursor by `ReviewThreadComments`. +fragment ReviewThreadPage on PullRequestReviewThreadConnection { + totalCount + pageInfo { + hasNextPage + endCursor + } + nodes { + id + isResolved + isOutdated + path + # Null once the thread's line has left the diff, which `isOutdated` reports. + line + diffSide + comments(first: 10) { + totalCount + pageInfo { + hasNextPage + endCursor + } + nodes { + ...ThreadComment + } + } + } +} + +# The first page of review threads with their comments, and the people on the review. Later pages +# come from `ReviewThreadPages`, so a pull request with more threads than one page holds is walked +# rather than cut off. # # `viewer` rides along: GitHub names who reacted but never says whether that is the reader, so the # comparison is made locally rather than paid for with a request of its own. @@ -53,46 +83,14 @@ fragment ThreadComment on PullRequestReviewComment { # # `viewerCanUpdate` and `viewerDidAuthor` belong to the pull request this query is already # standing on, so what the reader may do with it arrives with the conversation. -query ReviewThreads( - $owner: String! - $name: String! - $number: Int! - $after: String - $requestedReviewers: Int! -) { +query ReviewThreads($owner: String!, $name: String!, $number: Int!, $requestedReviewers: Int!) { viewer { login } repository(owner: $owner, name: $name) { pullRequest(number: $number) { - reviewThreads(first: 100, after: $after) { - totalCount - pageInfo { - hasNextPage - endCursor - } - nodes { - id - isResolved - isOutdated - path - # Null once the thread's line has left the diff, which `isOutdated` reports. - line - diffSide - # Only ten comments ride with each thread. A hundred threads times a hundred comments - # made GitHub reserve 10,000 nested rows and charge 104 points; unfinished threads are - # paged from their own cursor by `ReviewThreadComments`. - comments(first: 10) { - totalCount - pageInfo { - hasNextPage - endCursor - } - nodes { - ...ThreadComment - } - } - } + reviewThreads(first: 100) { + ...ReviewThreadPage } viewerCanUpdate viewerDidAuthor @@ -198,6 +196,21 @@ query ReviewThreads( } } +# The review threads past the first page. Everything else `ReviewThreads` asks for describes the +# whole pull request and arrived with that page, so later pages carry the threads alone. +query ReviewThreadPages($owner: String!, $name: String!, $number: Int!, $after: String!) { + viewer { + login + } + repository(owner: $owner, name: $name) { + pullRequest(number: $number) { + reviewThreads(first: 100, after: $after) { + ...ReviewThreadPage + } + } + } +} + # The rest of one thread's conversation. GraphQL pages a connection nested inside another only # from the inner node itself, so a thread longer than a page is followed on its own: a request # GitHub makes necessary, and one no ordinary pull request ever provokes. diff --git a/packages/source-control-github/src/server/pullRequestReviews.graphql.ts b/packages/source-control-github/src/server/pullRequestReviews.graphql.ts index 0711ed9ebcfa5..9a1351f8cd138 100644 --- a/packages/source-control-github/src/server/pullRequestReviews.graphql.ts +++ b/packages/source-control-github/src/server/pullRequestReviews.graphql.ts @@ -112,13 +112,6 @@ export const ThreadComment = Schema.Struct({ }) export interface ThreadComment extends Schema.Struct.Type {} -/** A user is an individual's account on GitHub that owns repositories and can make new content. */ -export const ViewerUser = Schema.Struct({ - /** The username used to login. */ - login: Schema.String -}) -export interface ViewerUser extends Schema.Struct.Type {} - /** Information about pagination in a connection. */ export const PageInfo = Schema.Struct({ /** When paginating forwards, are there more items? */ @@ -158,8 +151,12 @@ export const NodesPullRequestReviewThread = Schema.Struct({ }) export interface NodesPullRequestReviewThread extends Schema.Struct.Type {} -/** Review comment threads for a pull request review. */ -export const PullRequestReviewThreadConnection = Schema.Struct({ +/** + * `fragment ReviewThreadPage on PullRequestReviewThreadConnection` + * + * Review comment threads for a pull request review. + */ +export const ReviewThreadPage = Schema.Struct({ /** Identifies the total count of items in the connection. */ totalCount: Shared.Int, /** Information to aid in pagination. */ @@ -167,7 +164,14 @@ export const PullRequestReviewThreadConnection = Schema.Struct({ /** A list of nodes. */ nodes: Schema.NullOr(Schema.Array(Schema.NullOr(NodesPullRequestReviewThread))) }) -export interface PullRequestReviewThreadConnection extends Schema.Struct.Type {} +export interface ReviewThreadPage extends Schema.Struct.Type {} + +/** A user is an individual's account on GitHub that owns repositories and can make new content. */ +export const ViewerUser = Schema.Struct({ + /** The username used to login. */ + login: Schema.String +}) +export interface ViewerUser extends Schema.Struct.Type {} /** Represents a comment on an Issue. */ export const IssueComment = Schema.Struct({ @@ -370,7 +374,7 @@ export interface PullRequestCommitConnection extends Schema.Struct.Type {} + +/** A repository contains the content for a project. */ +export const ReviewThreadPagesRepositoryRepository = Schema.Struct({ + /** Returns a single pull request from the current repository by number. */ + pullRequest: Schema.NullOr(ReviewThreadPagesRepositoryPullRequestPullRequest) +}) +export interface ReviewThreadPagesRepositoryRepository extends Schema.Struct.Type {} + +/** `query ReviewThreadPages` */ +export const ReviewThreadPages = GraphQL.query("ReviewThreadPages", { + document: { + variables: [ + { name: "owner", body: "String!" }, + { name: "name", body: "String!" }, + { name: "number", body: "Int!" }, + { name: "after", body: "String!" } + ], + selections: [ + { name: "viewer", body: ["{login}"] }, + { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){pullRequest(number:$", "number", "){reviewThreads(first:100 after:$", "after", "){...ReviewThreadPage}}}"] } + ], + fragments: [ + { name: "ReviewThreadPage", body: ["on PullRequestReviewThreadConnection{totalCount pageInfo{hasNextPage endCursor}nodes{id isResolved isOutdated path line diffSide comments(first:10){totalCount pageInfo{hasNextPage endCursor}nodes{...ThreadComment}}}}"] }, + { name: "ThreadComment", body: ["on PullRequestReviewComment{id author{__typename login avatarUrl}body createdAt lastEditedAt url...Reactions}"] }, + { name: "Reactions", body: ["on Reactable{__typename reactionGroups{content viewerHasReacted reactors(first:10){totalCount nodes{__typename...on User{login}...on Bot{login}...on Organization{login}...on Mannequin{login}}}}}"] } + ] + }, + variables: { + owner: Schema.String, + name: Schema.String, + number: Shared.Int, + after: Schema.String + }, + result: Schema.Struct({ + /** The currently authenticated user. */ + viewer: ViewerUser, + /** Lookup a given repository by the owner and repository name. */ + repository: Schema.NullOr(ReviewThreadPagesRepositoryRepository) + }) +}) +export declare namespace ReviewThreadPages { + export type Variables = typeof ReviewThreadPages.variables.Type + export type Result = typeof ReviewThreadPages.result.Type +} + /** A repository pull request. */ export const ReviewThreadCommentsRepositoryPullRequestPullRequest = Schema.Struct({ /** The Node ID of the PullRequest object */ @@ -567,4 +621,4 @@ export declare namespace ReviewDismissals { } /** Every operation in pullRequestReviews.graphql. */ -export const PullRequestReviewsGraphQLGroup = GraphQLGroup.make(ReviewThreads, ReviewThreadComments, ReviewDismissals) +export const PullRequestReviewsGraphQLGroup = GraphQLGroup.make(ReviewThreads, ReviewThreadPages, ReviewThreadComments, ReviewDismissals) From 93dbf53db31387e18866ac64bf4488e8994ad86d Mon Sep 17 00:00:00 2001 From: Andrei <108398860+Yuruzuu@users.noreply.github.com> Date: Fri, 6 Nov 2026 12:23:32 +0800 Subject: [PATCH 017/181] =?UTF-8?q?perf(server):=20the=20headless=20browse?= =?UTF-8?q?r=20closes=20after=20five=20idle=20minutes=20(517=20MiB=20?= =?UTF-8?q?=E2=86=92=201.6=20MiB=20median)=20(#30306)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Claude Opus 5.5 --- apps/server/src/preview/ServerBrowser.ts | 1 + .../src/preview/ServerBrowserContexts.test.ts | 42 ++++++++++++++++-- .../src/preview/ServerBrowserContexts.ts | 43 +++++++++++++++++-- 3 files changed, 78 insertions(+), 8 deletions(-) diff --git a/apps/server/src/preview/ServerBrowser.ts b/apps/server/src/preview/ServerBrowser.ts index 6b92e33ce960f..264a875bf6fdf 100644 --- a/apps/server/src/preview/ServerBrowser.ts +++ b/apps/server/src/preview/ServerBrowser.ts @@ -501,6 +501,7 @@ const make = Effect.gen(function* () { const contexts = new ServerBrowserContexts({ profilesDir: NodePath.join(config.stateDir, "server-browser", "profiles"), + idleBrowserMs: 5 * 60_000, executable: () => runPromise(previewBrowser.executable), // An agent scope keeps Chrome out of the server's memory protection and OOM score. launcher: async (executable) => { diff --git a/apps/server/src/preview/ServerBrowserContexts.test.ts b/apps/server/src/preview/ServerBrowserContexts.test.ts index 522df30fb66c8..99504e86cb1b2 100644 --- a/apps/server/src/preview/ServerBrowserContexts.test.ts +++ b/apps/server/src/preview/ServerBrowserContexts.test.ts @@ -22,6 +22,8 @@ const makeContext = () => { return { on: vi.fn((event: string, listener: () => void) => events.on(event, listener)), pages: vi.fn(() => []), + newPage: vi.fn(async () => ({ once: vi.fn() })), + isClosed: () => closed, close: vi.fn(async () => { if (!closed) { closed = true; @@ -35,7 +37,8 @@ const makeBrowser = () => { const events = new NodeEvents.EventEmitter(); const contexts: ReturnType[] = []; return { - contexts, + created: contexts, + contexts: () => contexts.filter((context) => !context.isClosed()), on: vi.fn((event: string, listener: () => void) => events.on(event, listener)), newContext: vi.fn(async () => { const context = makeContext(); @@ -74,6 +77,37 @@ beforeEach(() => { }); describe("ServerBrowserContexts", () => { + it("closes the shared browser only after it holds no context for the idle period", async () => { + vi.useFakeTimers(); + try { + const first = makeBrowser(); + const second = makeBrowser(); + launches.launch + .mockResolvedValueOnce(first as unknown as Browser) + .mockResolvedValueOnce(second as unknown as Browser); + const pool = new ServerBrowserContexts({ ...options(), idleBrowserMs: 10 }); + const agent = await pool.contextFor("default", "agent"); + await pool.scratchPage(); + await agent.close(); + await vi.advanceTimersByTimeAsync(10); + expect(first.close).not.toHaveBeenCalled(); + await first.created[1]!.close(); + await vi.advanceTimersByTimeAsync(9); + const next = await pool.contextFor("default", "next"); + await vi.advanceTimersByTimeAsync(10); + expect(first.close).not.toHaveBeenCalled(); + await next.close(); + await vi.advanceTimersByTimeAsync(10); + expect(first.close).toHaveBeenCalledOnce(); + await pool.contextFor("default", "later"); + expect(launches.launch).toHaveBeenCalledTimes(2); + expect(second.newContext).toHaveBeenCalledOnce(); + await pool.close(); + } finally { + vi.useRealTimers(); + } + }); + it("lazily shares one browser across concurrent isolated sessions and reuses each context", async () => { const browser = makeBrowser(); const launch = Promise.withResolvers(); @@ -107,7 +141,7 @@ describe("ServerBrowserContexts", () => { }); await pool.close(); expect(browser.close).toHaveBeenCalledTimes(1); - for (const context of browser.contexts) expect(context.close).toHaveBeenCalled(); + for (const context of browser.created) expect(context.close).toHaveBeenCalled(); }); it("keeps human profiles persistent without sharing their storage with agents", async () => { @@ -172,7 +206,7 @@ describe("ServerBrowserContexts", () => { force: true, }); expect(await pool.contextFor("work/team", "agent")).toBe(agent); - expect(browser.contexts[0]?.close).not.toHaveBeenCalled(); + expect(browser.created[0]?.close).not.toHaveBeenCalled(); launches.persistent.mockResolvedValue(makeContext() as unknown as BrowserContext); expect(await pool.contextFor("work/team")).not.toBe(persistent); await pool.clearProfile("never-opened"); @@ -291,6 +325,6 @@ describe("ServerBrowserContexts", () => { await expect(pool.contextFor("default", "agent")).rejects.toThrow("closed"); await pool.close(); expect(browser.close).toHaveBeenCalledTimes(1); - expect(browser.contexts[0]?.close).toHaveBeenCalled(); + expect(browser.created[0]?.close).toHaveBeenCalled(); }); }); diff --git a/apps/server/src/preview/ServerBrowserContexts.ts b/apps/server/src/preview/ServerBrowserContexts.ts index 2a7c342d30d81..365add7565c69 100644 --- a/apps/server/src/preview/ServerBrowserContexts.ts +++ b/apps/server/src/preview/ServerBrowserContexts.ts @@ -1,4 +1,4 @@ -// @effect-diagnostics nodeBuiltinImport:off - Owns Playwright resources outside the Effect runtime. +// @effect-diagnostics nodeBuiltinImport:off globalTimers:off -- Owns Playwright resources and their idle timer outside the Effect runtime. import { INCOGNITO_BROWSER_PROFILE_ID } from "@t3tools/contracts"; import { constVoid } from "effect/Function"; import * as NodeFSP from "node:fs/promises"; @@ -26,6 +26,8 @@ interface Options { ) => Promise<{ readonly path: string; readonly release: () => Promise } | undefined>; readonly diagnose?: (executable: string, cause: unknown) => Promise; readonly env?: NodeJS.ProcessEnv; + /** Closes the shared browser once it has held no context for this long. */ + readonly idleBrowserMs?: number; readonly onContextClose?: (context: BrowserContext) => void; } @@ -80,6 +82,8 @@ export class ServerBrowserContexts { private readonly clearing = new Map>(); private browser: Promise | undefined; private closing: Promise | undefined; + private idleTimer: ReturnType | undefined; + private pendingSharedContexts = 0; constructor(options: Options) { this.options = options; @@ -136,6 +140,37 @@ export class ServerBrowserContexts { return this.browser; } + private async sharedContext(options?: Parameters[0]) { + clearTimeout(this.idleTimer); + this.pendingSharedContexts++; + const launched = this.sharedBrowser(); + try { + const context = await (await launched).newContext(options); + context.on("close", () => this.retireWhenIdle(launched)); + return context; + } finally { + this.pendingSharedContexts--; + this.retireWhenIdle(launched); + } + } + + private retireWhenIdle(launched: Promise) { + const delay = this.options.idleBrowserMs; + if (delay === undefined || this.closing || this.pendingSharedContexts > 0) return; + clearTimeout(this.idleTimer); + this.idleTimer = setTimeout(() => void this.retire(launched), delay); + this.idleTimer.unref(); + } + + private async retire(launched: Promise) { + const browser = await launched.catch(() => undefined); + if (!browser || this.browser !== launched || this.pendingSharedContexts > 0) return; + if (browser.contexts().length > 0) return; + // Cleared first, so a request during the close launches a fresh browser. + this.browser = undefined; + await browser.close().catch(constVoid); + } + contextFor(profileId: string, isolationKey?: string): Promise { if (this.closing) return Promise.reject(new Error("The preview browser is closed.")); const key = JSON.stringify([profileId, isolationKey ?? null]); @@ -166,8 +201,7 @@ export class ServerBrowserContexts { private async createContext(profileId: string, isolationKey?: string) { const contextOptions = { viewport: { width: 1280, height: 800 }, deviceScaleFactor: 2 }; if (isolationKey !== undefined || profileId === INCOGNITO_BROWSER_PROFILE_ID) { - const browser = await this.sharedBrowser(); - return browser.newContext(contextOptions); + return this.sharedContext(contextOptions); } const directory = this.profileDirectory(profileId); await NodeFSP.mkdir(directory, { recursive: true }); @@ -192,7 +226,7 @@ export class ServerBrowserContexts { async scratchPage() { if (this.closing) throw new Error("The preview browser is closed."); - const context = await (await this.sharedBrowser()).newContext(); + const context = await this.sharedContext(); const page = await context.newPage(); page.once("close", () => void context.close().catch(constVoid)); return page; @@ -237,6 +271,7 @@ export class ServerBrowserContexts { } private async dispose() { + clearTimeout(this.idleTimer); await Promise.allSettled( [...this.contexts.values()].map(async (pending) => (await pending).close()), ); From b15f772ebee6bab65950cb2b3404736d480eec0d Mon Sep 17 00:00:00 2001 From: Nico Date: Fri, 6 Nov 2026 05:23:51 +0100 Subject: [PATCH 018/181] fix(provider-acp-registry): surface agent error message on sign-in failure (#30295) --- .../src/server/auth.test.ts | 138 +++++++++++++++++- .../provider-acp-registry/src/server/auth.ts | 30 +++- 2 files changed, 165 insertions(+), 3 deletions(-) diff --git a/packages/provider-acp-registry/src/server/auth.test.ts b/packages/provider-acp-registry/src/server/auth.test.ts index b81e2e3fba73e..4bb647bd94069 100644 --- a/packages/provider-acp-registry/src/server/auth.test.ts +++ b/packages/provider-acp-registry/src/server/auth.test.ts @@ -5,6 +5,7 @@ import { assert, it } from "@effect/vitest"; import { ProviderInstanceId, type ProviderAuthState } from "@t3tools/contracts"; import { AcpRegistrySettings } from "../settings.ts"; import * as Deferred from "effect/Deferred"; +import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; @@ -13,7 +14,7 @@ import type * as AcpSchema from "effect-acp/compat"; import { AcpRequestError } from "effect-acp/errors"; import * as PtyAdapter from "@t3tools/shared/PtyAdapter"; -import { makeAcpRegistryAuth } from "./auth.ts"; +import { formatFailureDetail, makeAcpRegistryAuth } from "./auth.ts"; import * as AcpRegistrySupport from "./AcpRegistrySupport.ts"; import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; @@ -61,6 +62,7 @@ const makeHarness = ( failVerification = false, settings = decodeSettings({ agentId: "test-agent" }), providerInstanceId = instanceId, + authenticateError?: AcpRequestError, ) => Effect.gen(function* () { const verify = yield* Deferred.make(); @@ -111,6 +113,9 @@ const makeHarness = ( authenticate: (methodId) => Effect.gen(function* () { authenticated.push(methodId); + if (authenticateError !== undefined) { + return yield* authenticateError; + } if (elicitation) yield* elicitation( { @@ -342,8 +347,137 @@ it.effect("does not report authentication when post-login verification fails", ( h.exit(0); yield* h.phase("verifying"); yield* Deferred.succeed(h.verify, undefined); - yield* h.phase("failed"); + const failed = yield* h.phase("failed"); assert.deepEqual(h.changed, []); assert.isTrue(h.killed()); + assert.strictEqual( + failed.message, + "The provider could not create a session after terminal sign-in. Authentication required", + ); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), +); + +it.effect("surfaces the agent error message when authenticate fails with AcpRequestError", () => + Effect.gen(function* () { + const error = new AcpRequestError({ + method: "authenticate", + code: -32000, + errorMessage: "Connect to the VPN, then sign in again.", + }); + const h = yield* makeHarness( + browserMethod, + false, + decodeSettings({ agentId: "test-agent" }), + instanceId, + error, + ); + yield* h.controller.start("owner", Effect.void, "browser"); + const failed = yield* h.phase("failed"); + assert.strictEqual( + failed.message, + "The ACP agent could not complete sign-in. Connect to the VPN, then sign in again.", + ); + assert.deepEqual(h.changed, []); }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); + +it.effect( + "surfaces the agent error message when post-sign-in verification fails for agent auth", + () => + Effect.gen(function* () { + const h = yield* makeHarness(browserMethod, true); + const flow = yield* h.controller.start("owner", Effect.void, "browser"); + yield* h.phase("waiting"); + yield* h.controller.respond!("owner", { + instanceId, + flowId: flow.flowId!, + interactionId: "consent", + response: { type: "browser", action: "accept" }, + }); + yield* h.phase("verifying"); + yield* Deferred.succeed(h.verify, undefined); + const failed = yield* h.phase("failed"); + assert.strictEqual( + failed.message, + "The provider could not create a session after sign-in. Authentication required", + ); + assert.deepEqual(h.changed, []); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), +); + +it("formatFailureDetail handles all cause types and formatting edge cases cleanly", () => { + const baseWithPeriod = "The ACP agent could not complete sign-in."; + const baseWithoutPeriod = "The ACP agent could not complete sign-in"; + + // 1. undefined or null cause + assert.strictEqual(formatFailureDetail(baseWithPeriod, undefined), baseWithPeriod); + assert.strictEqual(formatFailureDetail(baseWithPeriod, null), baseWithPeriod); + + // 2. plain Error object, string, number, or object defect + assert.strictEqual( + formatFailureDetail(baseWithPeriod, new Error("Something broke")), + baseWithPeriod, + ); + assert.strictEqual(formatFailureDetail(baseWithPeriod, "string error"), baseWithPeriod); + assert.strictEqual(formatFailureDetail(baseWithPeriod, { foo: "bar" }), baseWithPeriod); + + // 3. AcpRequestError with empty or whitespace-only errorMessage + const emptyError = new AcpRequestError({ + method: "authenticate", + code: -32000, + errorMessage: "", + }); + const whitespaceError = new AcpRequestError({ + method: "authenticate", + code: -32000, + errorMessage: " \t\n ", + }); + assert.strictEqual(formatFailureDetail(baseWithPeriod, emptyError), baseWithPeriod); + assert.strictEqual(formatFailureDetail(baseWithPeriod, whitespaceError), baseWithPeriod); + + // 4. AcpRequestError with valid message: ensure no double periods, clean separation + const validError = new AcpRequestError({ + method: "authenticate", + code: -32000, + errorMessage: "Connect to the VPN, then sign in again.", + }); + assert.strictEqual( + formatFailureDetail(baseWithPeriod, validError), + "The ACP agent could not complete sign-in. Connect to the VPN, then sign in again.", + ); + assert.strictEqual( + formatFailureDetail(baseWithoutPeriod, validError), + "The ACP agent could not complete sign-in. Connect to the VPN, then sign in again.", + ); + + // 5. AcpRequestError with trimmed message and message without ending period + const unpunctError = new AcpRequestError({ + method: "authenticate", + code: -32000, + errorMessage: " Invalid credentials ", + }); + assert.strictEqual( + formatFailureDetail(baseWithPeriod, unpunctError), + "The ACP agent could not complete sign-in. Invalid credentials", + ); + + // 6. Nested Cause (e.g. Cause.fail or Cause.die wrapping AcpRequestError) + assert.strictEqual( + formatFailureDetail(baseWithPeriod, Cause.fail(validError)), + "The ACP agent could not complete sign-in. Connect to the VPN, then sign in again.", + ); + assert.strictEqual( + formatFailureDetail(baseWithPeriod, Cause.die(validError)), + "The ACP agent could not complete sign-in. Connect to the VPN, then sign in again.", + ); + + // 7. Extremely long error message: truncates to 500 characters with ellipsis + const longText = "A".repeat(600); + const longError = new AcpRequestError({ + method: "authenticate", + code: -32000, + errorMessage: longText, + }); + const expectedLong = `The ACP agent could not complete sign-in. ${"A".repeat(500)}…`; + assert.strictEqual(formatFailureDetail(baseWithPeriod, longError), expectedLong); +}); diff --git a/packages/provider-acp-registry/src/server/auth.ts b/packages/provider-acp-registry/src/server/auth.ts index 240bca67cea57..9f8d36880f27b 100644 --- a/packages/provider-acp-registry/src/server/auth.ts +++ b/packages/provider-acp-registry/src/server/auth.ts @@ -5,6 +5,7 @@ import { } from "@t3tools/contracts"; import type { AcpRegistrySettings } from "../settings.ts"; import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Cause from "effect/Cause"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; @@ -13,7 +14,9 @@ import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; import * as Scope from "effect/Scope"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; +import * as Schema from "effect/Schema"; import type * as AcpSchema from "effect-acp/compat"; +import * as EffectAcpErrors from "effect-acp/errors"; import * as PtyAdapter from "@t3tools/shared/PtyAdapter"; import * as ProviderAuthFlow from "@t3tools/provider-core/server/providerAuthFlow"; @@ -22,6 +25,26 @@ import * as AcpRegistrySupport from "./AcpRegistrySupport.ts"; import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts"; import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; +const isAcpRequestError = Schema.is(EffectAcpErrors.AcpRequestError); + +const MAX_ERROR_MESSAGE_LENGTH = 500; + +export const formatFailureDetail = (detail: string, cause?: unknown): string => { + const unwrapped = Cause.isCause(cause) ? Cause.squash(cause) : cause; + if (isAcpRequestError(unwrapped)) { + let message = unwrapped.errorMessage.trim(); + if (message.length > MAX_ERROR_MESSAGE_LENGTH) { + message = `${message.slice(0, MAX_ERROR_MESSAGE_LENGTH).trimEnd()}…`; + } + if (message.length > 0) { + const trimmed = detail.trimEnd(); + const prefix = trimmed.endsWith(".") ? `${trimmed} ` : `${trimmed}. `; + return `${prefix}${message}`; + } + } + return detail; +}; + type Runtime = Pick< AcpSessionRuntime.AcpSessionRuntime["Service"], "initialize" | "authenticate" | "start" | "handleElicitation" | "logout" @@ -47,7 +70,12 @@ export const makeAcpRegistryAuth = Effect.fn("makeAcpRegistryAuth")(function* (o const agentKey = options.settings.source === "local" ? `local:${options.instanceId}` : options.settings.agentId; const failure = (operation: string, detail: string, cause?: unknown) => - new ProviderSetupError({ instanceId: options.instanceId, operation, detail, cause }); + new ProviderSetupError({ + instanceId: options.instanceId, + operation, + detail: formatFailureDetail(detail, cause), + cause, + }); const resolve = catalog .resolve(options.settings, options.cwd, options.environment) .pipe( From 56a85428d5b46b81e1706e5644ad0a459edf3318 Mon Sep 17 00:00:00 2001 From: Andrei <108398860+Yuruzuu@users.noreply.github.com> Date: Fri, 6 Nov 2026 12:24:14 +0800 Subject: [PATCH 019/181] =?UTF-8?q?perf(server):=20a=20slow=20host=20no=20?= =?UTF-8?q?longer=20delays=20other=20watched=20PRs'=20wakes=20(935=20ms=20?= =?UTF-8?q?=E2=86=92=2065=20ms=20median)=20(#30291)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Claude Opus 5.5 --- .../PullRequestWatchReactor.ts | 35 +++++---- .../src/orchestration-v2/runtimeLayer.test.ts | 77 +++++++++++++++++++ 2 files changed, 98 insertions(+), 14 deletions(-) diff --git a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts index 2b588b1d2e23e..369bead0ec428 100644 --- a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts +++ b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts @@ -24,6 +24,7 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; +import * as Semaphore from "effect/Semaphore"; import type * as Scope from "effect/Scope"; import { @@ -43,6 +44,8 @@ import { /** Checks take minutes; faster sweeps waste the account's shared host quota. */ const SWEEP_MINUTES = 2; const READ_FAILURE_LIMIT = 8; +/** Group reads in flight at once, inside the host's own request limit. */ +const GROUP_READS = 4; /** Without fingerprints, reread quiet PRs on snapshot changes or this interval to catch edits. */ const QUIET_REREAD_MS = 10 * 60_000; /** Reread despite unchanged fingerprints; they miss review-thread comment edits. */ @@ -626,22 +629,26 @@ export const make = Effect.gen(function* () { ), { discard: true }, ); - const fingerprints = yield* Effect.forEach(groups, fingerprintOf, { - concurrency: "unbounded", - }); + // Every fingerprint is asked for at once so the host can batch them, and each group reads + // as soon as its own answer lands rather than waiting on the slowest host. + const reads = yield* Semaphore.make(GROUP_READS); yield* Effect.forEach( groups, - (group, index) => { - const fingerprint = fingerprints[index]!; - return fingerprint === "paused" - ? Effect.void - : readGroup(group, fingerprint).pipe( - Effect.catchCause( - logFailure("pull request watch check failed", { pullRequest: group.key }), - ), - ); - }, - { concurrency: 4, discard: true }, + (group) => + fingerprintOf(group).pipe( + Effect.flatMap((fingerprint) => + fingerprint === "paused" + ? Effect.void + : reads.withPermit( + readGroup(group, fingerprint).pipe( + Effect.catchCause( + logFailure("pull request watch check failed", { pullRequest: group.key }), + ), + ), + ), + ), + ), + { concurrency: "unbounded", discard: true }, ); }).pipe( Effect.catchCause(logFailure("pull request watch sweep failed", {})), diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 83f77d0073001..af95d71e6121b 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -4334,6 +4334,83 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }), ); + it.effect("reads each watched PR as soon as its own fingerprint lands", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projectId = ProjectId.make("pr-watch-pipeline-project"); + yield* seedProject({ + projectId, + title: "Watch pipeline", + workspaceRoot: "/workspace/watch-pipeline", + defaultModelSelection: null, + createdAt: "2026-10-01T00:00:00.000Z", + }); + for (const number of [21, 22]) { + const threadId = ThreadId.make(`runtime-pull-request-watch-pipeline-${number}`); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`pr-watch-pipeline-create-${number}`), + threadId, + projectId, + title: "Watch pipeline", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }); + yield* orchestrator.dispatch({ + type: "thread.pull-request.watch", + commandId: CommandId.make(`pr-watch-pipeline-start-${number}`), + threadId, + host: "github.com", + repository: "pingdotgg/t3code", + number, + watching: true, + link: { url: `https://github.com/pingdotgg/t3code/pull/${number}`, source: "agent" }, + }); + } + const at = "2026-10-02T12:00:00.000Z"; + const texts = (number: number) => + orchestrator + .getThreadRecords(ThreadId.make(`runtime-pull-request-watch-pipeline-${number}`), [ + "messages", + ]) + .pipe(Effect.map(({ messages }) => messages.map((message) => message.text).join("\n"))); + // #21's host answers only after #22 has been read, so waiting on every fingerprint first + // never finishes. + const read22 = yield* Deferred.make(); + const host = Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + Layer.mock(PullRequestService.PullRequestService)({ + watchFingerprint: (input) => + input.number === 21 + ? Deferred.await(read22).pipe(Effect.as(null)) + : Effect.succeed(null), + detail: (input) => + (input.number === 22 ? Deferred.succeed(read22, undefined) : Effect.void).pipe( + Effect.as(watchedPullRequestDetail({ projectId, number: input.number, at })), + ), + activity: () => + Effect.succeed({ + comments: [], + commentCount: 0, + commentsTruncated: false, + reviewThreads: [], + commits: [], + }), + }), + ); + const reactor = yield* PullRequestWatchReactor.make.pipe(Effect.provide(host)); + yield* reactor.sweep; + assert.include(yield* texts(21), "#21"); + assert.include(yield* texts(22), "#22"); + }), + ); + it.effect("persists rejected command receipts across retries", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; From 8dbf2621fa1b2a201086d6b9535b385d7c3990a8 Mon Sep 17 00:00:00 2001 From: Andrei <108398860+Yuruzuu@users.noreply.github.com> Date: Fri, 6 Nov 2026 12:24:32 +0800 Subject: [PATCH 020/181] =?UTF-8?q?perf(server):=20PR=20cache=20invalidati?= =?UTF-8?q?on=20no=20longer=20waits=20on=20other=20projects'=20reads=20(1,?= =?UTF-8?q?163=20ms=20=E2=86=92=200.12=20ms=20median)=20(#30293)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Claude Opus 5.5 --- .../src/pullRequest/PullRequestReadCache.test.ts | 3 +++ .../src/pullRequest/PullRequestReadCache.ts | 16 +++++++++++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/apps/server/src/pullRequest/PullRequestReadCache.test.ts b/apps/server/src/pullRequest/PullRequestReadCache.test.ts index b73774700fcf8..071f1d4978a7d 100644 --- a/apps/server/src/pullRequest/PullRequestReadCache.test.ts +++ b/apps/server/src/pullRequest/PullRequestReadCache.test.ts @@ -44,6 +44,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("PR filesystem ca const invalidate = yield* cache .invalidate("pr") .pipe(Effect.forkChild({ startImmediately: true })); + // Another PR's invalidation does not wait on this read; this one's does. + yield* cache.invalidate("other-pr"); + assert.isUndefined(invalidate.pollUnsafe()); yield* Deferred.succeed(release, undefined); yield* Fiber.join(read); yield* Fiber.join(invalidate); diff --git a/apps/server/src/pullRequest/PullRequestReadCache.ts b/apps/server/src/pullRequest/PullRequestReadCache.ts index f3ec665ca9786..7f03beef3a245 100644 --- a/apps/server/src/pullRequest/PullRequestReadCache.ts +++ b/apps/server/src/pullRequest/PullRequestReadCache.ts @@ -26,6 +26,8 @@ import { detachStackFrame } from "../git/detachStackFrame.ts"; import { forkParked } from "../serverActivation.ts"; const CONCURRENT_READS = 512; +/** Invalidation excludes only reads whose scopes share its stripe, not every PR read. */ +const SCOPE_STRIPES = 64; // Entry filenames are the URI-encoded `:`; the scope revisions file has // no store id. Effect before 4.1 wrote ``, still pruned here. const STORE_ID = "pr-v2"; @@ -87,6 +89,11 @@ export const make = Effect.gen(function* () { const clock = yield* Clock.Clock; let enabled = true; const lock = yield* Semaphore.make(CONCURRENT_READS); + const stripes = yield* Effect.forEach(Array.from({ length: SCOPE_STRIPES }), () => + Semaphore.make(CONCURRENT_READS), + ); + const stripeOf = (scope: string) => (Hash.string(scope) >>> 0) % SCOPE_STRIPES; + const revisionWrites = yield* Semaphore.make(1); const digest = (key: string) => digester.digest(Digest.sha256, new TextEncoder().encode(key)).pipe(Effect.map(Hex.encode)); const revisions = yield* Cache.makeWith( @@ -162,6 +169,12 @@ export const make = Effect.gen(function* () { PersistenceError: () => read, SchemaError: () => read, }), + // A read stores its result under the revisions it started with, so an invalidation of + // one of its scopes must wait for it; reads of other scopes run on. + (effect) => + [...new Set(scopes.map(stripeOf))] + .toSorted((left, right) => left - right) + .reduceRight((inner, stripe) => stripes[stripe]!.withPermits(1)(inner), effect), lock.withPermits(1), ); }, detachStackFrame), @@ -182,7 +195,8 @@ export const make = Effect.gen(function* () { return Effect.logWarning("PR cache disabled after clearing failed"); }), Effect.uninterruptible, - lock.withPermits(CONCURRENT_READS), + revisionWrites.withPermits(1), + (effect, scope) => stripes[stripeOf(scope)]!.withPermits(CONCURRENT_READS)(effect), detachStackFrame, ), }); From 43dfdcc84eb2f0bddeca9e4e1659c6c35e8fcf03 Mon Sep 17 00:00:00 2001 From: Alex Southwell Date: Fri, 6 Nov 2026 04:24:50 +0000 Subject: [PATCH 021/181] fix(opencode): tools stopped mid-run show as interrupted, not failed (#29762) Co-authored-by: Claude Opus 5.5 Co-authored-by: maria-rcks --- .../src/server/adapter.test.ts | 66 +++++++++++++++++-- .../provider-opencode/src/server/adapter.ts | 16 ++--- 2 files changed, 67 insertions(+), 15 deletions(-) diff --git a/packages/provider-opencode/src/server/adapter.test.ts b/packages/provider-opencode/src/server/adapter.test.ts index 6fb5263b6e3bc..70462070cff51 100644 --- a/packages/provider-opencode/src/server/adapter.test.ts +++ b/packages/provider-opencode/src/server/adapter.test.ts @@ -784,19 +784,35 @@ describe("OpenCodeAdapterV2", () => { error: "Command failed", time: { start: 3, end: 4 }, }, + { + status: "error", + input: { command: "sleep 60" }, + error: "Interrupted", + metadata: { interrupted: true }, + time: { start: 5, end: 6 }, + }, + // OpenCode 1.3 reports a stopped tool only through this message. + { + status: "error", + input: { command: "sleep 90" }, + error: "Tool execution aborted", + time: { start: 6, end: 7 }, + }, ] satisfies ReadonlyArray; for (const state of states) { + const callID = + state.status === "error" ? `call-ended-${state.time.start}` : "call-working"; yield* Effect.promise(() => nativeEvents.push({ type: "message.part.updated", properties: { sessionID: nativeSessionId, part: { - id: state.status === "error" ? "part-failed" : "part-working", + id: `part-${callID}`, sessionID: nativeSessionId, messageID: "late-assistant", type: "tool", - callID: state.status === "error" ? "call-failed" : "call-working", + callID, tool: "bash", state, }, @@ -804,6 +820,34 @@ describe("OpenCodeAdapterV2", () => { }), ); } + for (const error of ["Task cancelled", "Task failed"]) { + yield* Effect.promise(() => + nativeEvents.push({ + type: "message.part.updated", + properties: { + sessionID: nativeSessionId, + part: { + id: `part-${error}`, + sessionID: nativeSessionId, + messageID: "late-assistant", + type: "tool", + callID: `call-${error}`, + tool: "task", + state: { + status: "error", + input: { + description: "Sleep task", + prompt: "sleep 120", + subagent_type: "general", + }, + error, + time: { start: 7, end: 8 }, + }, + }, + }, + }), + ); + } yield* Effect.promise(() => nativeEvents.push({ type: "message.part.updated", @@ -902,21 +946,31 @@ describe("OpenCodeAdapterV2", () => { const commands = items.filter((item) => item.type === "command_execution"); assert.deepEqual( commands.map((item) => item.status), - ["pending", "running", "completed", "failed", "failed"], + ["pending", "running", "completed", "failed", "interrupted", "interrupted", "failed"], ); assert.deepEqual( commands.map((item) => item.input), - ["pwd", "pwd", "pwd", "pwd", "vp test"], + ["pwd", "pwd", "pwd", "pwd", "sleep 60", "sleep 90", "vp test"], ); assert.equal(commands[2]?.output, "/repo\n"); assert.equal(commands[3]?.output, "Command failed"); - assert.equal(commands[4]?.exitCode, 1); + assert.equal(commands[6]?.exitCode, 1); assert.equal( events .flatMap((event) => (event.type === "node.updated" ? [event.node] : [])) - .findLast((node) => node.id === commands[4]?.nodeId)?.status, + .findLast((node) => node.id === commands[6]?.nodeId)?.status, "failed", ); + assert.deepEqual( + items.filter((item) => item.type === "subagent").map((item) => item.status), + ["interrupted", "failed"], + ); + assert.deepEqual( + events.flatMap((event) => + event.type === "subagent.updated" ? [event.subagent.status] : [], + ), + ["interrupted", "failed"], + ); assert.isTrue( events.some( (event) => diff --git a/packages/provider-opencode/src/server/adapter.ts b/packages/provider-opencode/src/server/adapter.ts index 1daf5ec1f4f57..4c72c5f6ef09f 100644 --- a/packages/provider-opencode/src/server/adapter.ts +++ b/packages/provider-opencode/src/server/adapter.ts @@ -747,7 +747,12 @@ function toolStatus(part: ToolPart): { ? { node: "failed", item: "failed" } : { node: "completed", item: "completed" }; case "error": - return { node: "failed", item: "failed" }; + // Stop marks in-flight tools this way; OpenCode's own UI shows them as cancelled. + return part.state.metadata?.["interrupted"] === true || + part.state.error === "Tool execution aborted" || + (part.tool === "task" && part.state.error === "Task cancelled") + ? { node: "interrupted", item: "interrupted" } + : { node: "failed", item: "failed" }; } } @@ -1439,14 +1444,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function if (part.state.status === "completed" && output !== undefined) context.result = output; const status = toolStatus(part); const completedAt = toolCompletedAt(part, now); - const subagentStatus: OrchestrationV2Subagent["status"] = - status.item === "failed" - ? "failed" - : status.item === "completed" - ? "completed" - : status.item === "pending" - ? "pending" - : "running"; + const subagentStatus: OrchestrationV2Subagent["status"] = status.item; const subagent: OrchestrationV2Subagent = { id: nodeId, threadId: turn.threadId, From 4821696509d268eac35a8c3fa04cb4211d68a504 Mon Sep 17 00:00:00 2001 From: MarcoDotIO Date: Thu, 5 Nov 2026 23:25:08 -0500 Subject: [PATCH 022/181] fix(client-runtime): pull request bodies with CRLF line endings keep their code blocks whole (#30352) Co-authored-by: Claude Opus 5.5 Co-authored-by: maria-rcks <254055478+maria-rcks@users.noreply.github.com> --- .../src/pullRequestMarkdown.test.ts | 21 +++++++++++++++++++ .../client-runtime/src/pullRequestMarkdown.ts | 3 ++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/packages/client-runtime/src/pullRequestMarkdown.test.ts b/packages/client-runtime/src/pullRequestMarkdown.test.ts index 8fab1fdd3b632..a5508e8197421 100644 --- a/packages/client-runtime/src/pullRequestMarkdown.test.ts +++ b/packages/client-runtime/src/pullRequestMarkdown.test.ts @@ -80,6 +80,27 @@ describe("pull request body segmentation", () => { ]); }); + // GitHub keeps CRLF in a body written in its web editor. + it("recognizes fences in a body with CRLF line endings", () => { + const body = "```\r\nhttps://example.com/demo.mp4\r\n```"; + expect(splitPullRequestBody(body)).toEqual([ + { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, + ]); + }); + + it("closes a CRLF fence, so a video after it still lifts out", () => { + const code = '```html\r\n\r\n```'; + expect(splitPullRequestBody(`${code}\r\n\r\nhttps://example.com/demo.mp4\r\n`)).toEqual([ + { id: "markdown:0", kind: "markdown", text: code, sourceOffset: 0 }, + { + id: "attachment:1", + kind: "attachment", + url: "https://example.com/demo.mp4", + media: "video", + }, + ]); + }); + it("does not let a different fence marker close an open fence", () => { const body = "```\n~~~\nhttps://example.com/demo.mp4\n```"; expect(splitPullRequestBody(body)).toEqual([ diff --git a/packages/client-runtime/src/pullRequestMarkdown.ts b/packages/client-runtime/src/pullRequestMarkdown.ts index 9524f3e660e04..92c7d6de70cf6 100644 --- a/packages/client-runtime/src/pullRequestMarkdown.ts +++ b/packages/client-runtime/src/pullRequestMarkdown.ts @@ -16,7 +16,8 @@ export type PullRequestBodySegment = readonly media: "video" | "image" | "unknown"; }; -const FENCE_PATTERN = /^\s{0,3}((?:`{3,})|(?:~{3,}))(.*)$/u; +// `.` stops at the `\r` of a CRLF body, which is how GitHub stores one written in its web editor. +const FENCE_PATTERN = /^\s{0,3}((?:`{3,})|(?:~{3,}))(.*)\r?$/u; /** * How far a `(value: A): A => { + if (typeof value === "object" && value !== null && !DateTime.isDateTime(value)) { + for (const child of Object.values(value)) freeze(child); + Object.freeze(value); + } + return value; + }; + const live: ReadonlyArray = freeze([ + { + sequence: 1, + commandId: null, + event: { + id: EventId.make("event:shared-live:message"), + type: "message.updated", + threadId, + occurredAt: at, + payload: { + ...owner, + id: messageId, + role: "assistant", + text: "Done", + attachments: [], + streaming: false, + createdBy: "agent", + creationSource: "provider", + }, + }, + }, + { + sequence: 2, + commandId: null, + event: { + id: EventId.make("event:shared-live:reply"), + type: "turn-item.updated", + threadId, + occurredAt: at, + payload: { + ...owner, + id: TurnItemId.make("item:shared-live:reply"), + type: "assistant_message", + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 1, + title: null, + status: "completed", + messageId, + text: "Done", + streaming: false, + startedAt: at, + completedAt: at, + }, + }, + }, + ] as ReadonlyArray); + const stringify = yield* Effect.acquireRelease( + Effect.sync(() => vi.spyOn(JSON, "stringify")), + (spy) => Effect.sync(() => spy.mockRestore()), + ); + // The EventSink hands every subscriber the same projected objects. + const subscribe = (acceptDedupedBodies: boolean) => + subscribeOrchestrationV2Thread({ threadId, afterSequence: 0, acceptDedupedBodies }).pipe( + Effect.flatMap(Stream.runCollect), + Effect.map((items) => Array.from(items)), + Effect.provideService(ThreadManagement.ThreadManagementService, { + ensureLegacyTranscript: () => Effect.void, + streamStoredEventsFrom: () => Stream.fromIterable(live), + } as unknown as ThreadManagement.ThreadManagementService["Service"]), + ); + const [deduped, first, second] = yield* Effect.forEach([true, false, false], subscribe); + + assert.lengthOf(first!, live.length); + first!.forEach((item, index) => { + assert.strictEqual(item, second![index]); + assert.strictEqual(item.kind === "event" && item.event, live[index]!.event); + }); + assert.strictEqual(deduped![0], first![0]); + const reply = deduped![1]; + assert.deepInclude(reply?.kind === "event" ? reply.event.payload : undefined, { + text: "", + textOmitted: true, + }); + // The live buffer sizes each shared item once, not once per subscriber. + assert.lengthOf( + stringify.mock.calls.filter(([value]) => value?.kind === "event"), + live.length, + ); + }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)), +); + it.effect("shell snapshots omit idle children and older settled threads only on request", () => Effect.gen(function* () { const shell = ( diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 079adfb19ce44..035f8b1688d44 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -165,6 +165,7 @@ import { makeLiveBodyDeduper, projectDomainEventForWire, projectThreadProjectionForWire, + threadStreamEventItem, } from "./orchestration-v2/WireProjection.ts"; import { dedupeSnapshotBodies } from "@t3tools/shared/orchestrationV2DedupedBodies"; import * as ProjectStore from "./orchestration-v2/ProjectStore.ts"; @@ -917,11 +918,7 @@ export const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subs afterSequence, }) .pipe( - Stream.map((stored) => ({ - kind: "event" as const, - sequence: stored.sequence, - event: stored.event, - })), + Stream.map(threadStreamEventItem), coalesceThreadLiveStream, Stream.mapError( (cause) => From 9a5c197c07ef208a2849f5452ccca7b89ec20ef3 Mon Sep 17 00:00:00 2001 From: Roger V <12006627+rgrvlsk@users.noreply.github.com> Date: Fri, 6 Nov 2026 05:41:07 +0100 Subject: [PATCH 074/181] fix(server): request_secret asks for one value per card (#30805) Co-authored-by: Claude Opus 5.5 Co-authored-by: maria-rcks --- .../src/mcp/toolkits/orchestrator/tools.ts | 2 +- .../src/provider/agentContextBudget.json | 2 +- evals/mcp-tool-use/cases/pull-requests.ndjson | 1 + evals/mcp-tool-use/run.test.ts | 56 +++++++++++++++++++ evals/mcp-tool-use/run.ts | 13 +++++ 5 files changed, 72 insertions(+), 2 deletions(-) diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts index 150962e232a13..f0affbf6dec8c 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -197,7 +197,7 @@ const DeleteScheduledTaskTool = Tool.make("delete_scheduled_task", { const RequestSecretTool = Tool.make("request_secret", { description: - 'Ask for a secret in a private card and wait; open it, don\'t offer it. Returns a one-use `secretRef`, or with `delivery: "file"` a file to read only in its command, e.g. `adb pair "$(cat )"`. Asked how to give one: call now. Pasted secret for child or script: `value`. Not one from an old thread.', + 'Ask for one secret per single-line card; never combine values. Open it, don\'t offer it. Returns one-use `secretRef`, or `delivery: "file"` a file read only in its command, e.g. `adb pair "$(cat )"`. Asked how: call now. Pasted secret for child/script: `value`. Never from an old thread.', parameters: OrchestratorMcpRequestSecretInput, success: OrchestratorMcpRequestSecretResult, failure: OrchestratorMcpFailure, diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 0a03b931fcc08..b71053bf272a8 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 5133, "codexAdditionalContextBytes": 6863, - "mcpToolListJsonBytes": 47818 + "mcpToolListJsonBytes": 47809 } diff --git a/evals/mcp-tool-use/cases/pull-requests.ndjson b/evals/mcp-tool-use/cases/pull-requests.ndjson index e0c7144220030..2e14e45f7f250 100644 --- a/evals/mcp-tool-use/cases/pull-requests.ndjson +++ b/evals/mcp-tool-use/cases/pull-requests.ndjson @@ -14,6 +14,7 @@ {"id": "wake-required-passed-rearm-or-shell-wait", "area": "pull-requests", "kind": "bad", "pattern": "on a watch wake: re-arm watch, list PRs, or wait in the shell", "experience": "On a 'required checks passed' wake with a non-required job still running, agents re-called watch_pull_request and listed PRs, or unwatched and started gh run watch.", "rule": "when asked to monitor, watch, or babysit a PR and watch_pull_request is available, call it and end your turn ... do not poll or run your own watcher", "privacy": "commit-safe", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "File PR. Babysit. Merge when you are confident it's good to go."}, {"role": "assistant", "text": "Opened [#124](https://github.com/acme/app/pull/124). T3 Code is watching it; I will merge once checks pass and review findings are clear.", "toolCalls": [{"tool": "Bash", "input": {"command": "git push -u origin fix/socket-retry"}, "result": "To github.com:acme/app.git\n * [new branch] fix/socket-retry -> fix/socket-retry\nbranch 'fix/socket-retry' set up to track 'origin/fix/socket-retry'."}, {"tool": "Bash", "input": {"command": "gh pr create --base main --title \"fix(web): retry the socket once before showing an error\" --fill"}, "result": "https://github.com/acme/app/pull/124"}, {"tool": "link_pull_request", "input": {"url": "https://github.com/acme/app/pull/124"}, "result": {"host": "github.com", "repository": "acme/app", "number": 124, "url": "https://github.com/acme/app/pull/124", "alreadyLinked": false}}, {"tool": "watch_pull_request", "input": {"url": "https://github.com/acme/app/pull/124"}, "result": {"host": "github.com", "repository": "acme/app", "number": 124, "url": "https://github.com/acme/app/pull/124", "watching": true, "wasWatching": false}}]}], "mocks": {"watch_pull_request": "default", "list_thread_pull_requests": "default", "link_pull_request": "default", "unwatch_pull_request": "default"}, "world": {"branch": "fix/socket-retry", "commits": [{"sha": "abc1234", "subject": "fix(web): retry the socket once before showing an error"}], "diff": "diff --git a/apps/web/src/socket.ts b/apps/web/src/socket.ts\n--- a/apps/web/src/socket.ts\n+++ b/apps/web/src/socket.ts\n@@ -10,1 +10,2 @@\n- if (error) return showError(error);\n+ if (error && !retried) return reconnect({ retried: true });\n+ if (error) return showError(error);\n", "prs": [{"number": 124, "title": "fix(web): retry the socket once before showing an error", "headRefName": "fix/socket-retry", "checks": [{"name": "Check", "state": "pass"}, {"name": "Lint", "state": "pass"}, {"name": "Typecheck", "state": "pass"}, {"name": "Test Web", "state": "pending"}], "mergeStateStatus": "UNSTABLE"}]}}, "prompt": "Update on pull request #124 (https://github.com/acme/app/pull/124), which T3 Code is watching for you:\n- All 9 required checks passed on abc1234.\n\nLook into each item and act on it as your task requires. This PR stays linked and watched, so do not link, watch, or list it again. End your turn when you are done, and T3 Code wakes you on the next change. When you hand the work back to the user, call unwatch_pull_request first so the thread returns to their inbox.", "expect": {"notCalls": ["watch_pull_request", "list_thread_pull_requests", "link_pull_request", "link_pull_requests", "Monitor", "ScheduleWakeup"], "shellMustNot": ["\\bsleep \\d", "gh pr checks[^\\n]*--watch", "gh run watch", "\\buntil\\b[^\\n]*\\bgh (pr|run|api)\\b", "\\bfor \\w+ in [^\\n]*;\\s*do[^\\n]*\\bgh pr checks\\b", "pr-wait"]}, "notes": "Merges two real failures on the same wake: Claude unwatch + gh run watch, and Codex re-arming watch + list on each wake (see source.also). Wake text is copied from pullRequestWatch.ts. Merging now or ending the turn to wait for the next wake both pass."} {"id": "secret-webhook-how-to-send", "area": "pull-requests", "kind": "bad", "pattern": "secret asked in chat, or request_secret promised but not called", "experience": "Agents told the user to paste secrets in chat, or said 'give me a token through request_secret' and never called it. request_secret has 0 real calls.", "rule": "When you need a secret from the user ... call request_secret so they enter it privately ... Never ask for a secret in chat", "privacy": "commit-safe", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "Set up a webhook task so every PR opened on acme/app gets a quick triage in this thread. Have GitHub sign the requests."}, {"role": "assistant", "text": "I can set that up. I need the webhook secret so T3 Code can check GitHub's signature. Create a secret for the webhook in the repo's webhook settings first."}], "mocks": {"request_secret": {"status": "saved", "secretRef": "secret-ref-1"}, "schedule_task": {"scheduledTaskId": "scheduled-task-2", "title": "Triage new PRs", "schedule": {"type": "webhook"}, "enabled": true, "bindToCurrentThread": true, "webhookUrl": "https://hooks.example.test/t3/abc"}}}, "prompt": "Ok, I made the secret in GitHub. How do I get it to you?", "expect": {"calls": [{"tool": "request_secret"}, {"tool": "schedule_task", "args": {"schedule.type": "webhook", "schedule.signature.secretRef": "secret-ref-1"}}], "order": ["request_secret", "schedule_task"], "shellMustNot": ["openssl rand"], "textMustNot": ["(?=2026-10-23\" --limit 500 --json number --jq length"}, "result": "290"}, {"tool": "delegate_task", "input": {"title": "Haiku PR audit", "mode": "wait", "target": {"providerInstanceId": "claudeAgent", "model": "claude-haiku-5-5"}, "task": "Audit the 290 PRs with activity in the last 24 hours for mergeability, value, and novelty. Flag the ones that look mergeable."}, "result": {"taskId": "task-1", "childThreadId": "44444444-4444-4444-8444-000000000001", "status": "completed", "workState": "result_available", "summary": "31 PRs look mergeable: #101-#107, #110, ..."}}, {"tool": "delegate_task", "input": {"title": "Opus verify", "mode": "wait", "target": {"providerInstanceId": "claudeAgent", "model": "claude-opus-5-5"}, "task": "Verify the 31 flagged PRs. Say MERGE, TAKEOVER, or SKIP for each."}, "result": {"taskId": "task-2", "childThreadId": "44444444-4444-4444-8444-000000000002", "status": "completed", "workState": "result_available", "summary": "#101 MERGE, #102 MERGE, #103 MERGE, #104 TAKEOVER, #105 MERGE, #106 TAKEOVER, #107 MERGE. #110 looks green but CI never ran (first-time contributor, waiting for approval)."}}, {"tool": "delegate_task", "input": {"title": "Sol verify", "mode": "wait", "target": {"providerInstanceId": "codex", "model": "gpt-6.1-sol"}, "task": "Verify the 31 flagged PRs. Say MERGE, TAKEOVER, or SKIP for each."}, "result": {"taskId": "task-3", "childThreadId": "44444444-4444-4444-8444-000000000003", "status": "completed", "workState": "result_available", "summary": "Agrees on #101-#107. SKIP the rest."}}]}], "mocks": {"schedule_task": {"scheduledTaskId": "scheduled-task-1", "title": "Nightly PR triage", "schedule": {"type": "fixed_time", "timeOfDay": "21:00"}, "enabled": true, "bindToCurrentThread": true, "nextRunAt": "2026-10-24T21:00:00-07:00"}}}, "prompt": "This looks good, set it with a schedule", "expect": {"calls": [{"tool": "schedule_task", "args": {"schedule.type": "fixed_time", "schedule.timeOfDay": "21:00"}}], "notCalls": ["delegate_task", "run_scheduled_task_now"], "shellMustNot": ["\\bgh (api|pr|search|issue)\\b"], "textMust": ["(9(:00)? ?[Pp]\\.?[Mm]|21:00)"]}, "notes": "Correction theme H. The only schedule correction in the data."} {"id": "scheduled-run-lists-tasks", "area": "pull-requests", "kind": "bad", "pattern": "list_scheduled_tasks on every scheduled wake", "experience": "Each 4-minute scheduled run called list_scheduled_tasks and got the same single task back (9 times in 33 minutes).", "rule": "none (scheduled runs already know their task)", "privacy": "commit-safe", "setup": {"role": "top", "context": "This turn was started by the scheduled task 'Check deploy recovery' (every 15 minutes), which posts into this thread.", "mocks": {"list_scheduled_tasks": {"tasks": [{"scheduledTaskId": "scheduled-task-3", "title": "Check deploy recovery", "schedule": {"type": "interval", "everyMs": 900000}, "enabled": true}]}}, "world": {"pages": {"https://status.example.test": "

Status

Deployments: paused for all plans. Next update in 30 minutes.

"}}}, "prompt": "Check https://status.example.test for an explicit announcement that deployments resumed. Do not count green component tiles as recovery. If deployments are still paused, reply in one line and change nothing.", "expect": {"notCalls": ["list_scheduled_tasks", "schedule_task", "delete_scheduled_task"]}, "notes": "No instruction line covers this today; written to what the user wants (no per-wake ceremony). The agent may use WebFetch instead of curl."} {"id": "creator-links-own-pr", "area": "pull-requests", "kind": "guard", "pattern": "created PR ends up linked, with no watch or list", "experience": "Must keep working: an opened PR ends up linked to the thread, and the agent does not watch or list when no babysit was asked.", "rule": "Call link_pull_request with the full PR URL immediately after creating a PR", "privacy": "commit-safe", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "Can we pre-bundle the hot startup paths on shared dev servers? First load takes over a minute."}, {"role": "assistant", "text": "Prototype is on branch perf/prebundle-startup (commit abc1234). First page load on a shared dev server drops from about 64 s to 21 s. Want a PR?", "toolCalls": [{"tool": "Bash", "input": {"command": "git checkout -b perf/prebundle-startup"}, "result": "Switched to a new branch 'perf/prebundle-startup'"}, {"tool": "Write", "input": {"file_path": "/home/user/.t3/worktrees/t3code/t3-f8cdd940/scripts/hotStartupDeps.ts", "content": "// Measured with scripts/bench-first-load.mjs on a shared dev server.\nexport const HOT_STARTUP_DEPS = ['react', 'react-dom', '@tanstack/react-router', 'effect'];\n"}, "result": "File created successfully at: /home/user/.t3/worktrees/t3code/t3-f8cdd940/scripts/hotStartupDeps.ts"}, {"tool": "Write", "input": {"file_path": "/home/user/.t3/worktrees/t3code/t3-f8cdd940/vite.config.ts", "content": "import { defineConfig } from 'vite';\nimport { HOT_STARTUP_DEPS } from './scripts/hotStartupDeps';\n\nexport default defineConfig({\n optimizeDeps: { include: HOT_STARTUP_DEPS },\n});\n"}, "result": "File created successfully at: /home/user/.t3/worktrees/t3code/t3-f8cdd940/vite.config.ts"}, {"tool": "Bash", "input": {"command": "node scripts/bench-first-load.mjs --runs 3"}, "result": "baseline 64.2s 63.8s 65.0s\nprebundled 21.3s 20.9s 21.6s"}, {"tool": "Bash", "input": {"command": "git add -A && git commit -m \"perf(dev): pre-bundle hot startup paths on shared dev servers\""}, "result": "[perf/prebundle-startup abc1234] perf(dev): pre-bundle hot startup paths on shared dev servers\n 2 files changed"}]}], "mocks": {"link_pull_request": "default"}, "world": {"branch": "perf/prebundle-startup", "commits": [{"sha": "abc1234", "subject": "perf(dev): pre-bundle hot startup paths on shared dev servers"}], "diff": "diff --git a/vite.config.ts b/vite.config.ts\n--- a/vite.config.ts\n+++ b/vite.config.ts\n@@ -1,5 +1,6 @@\n import { defineConfig } from 'vite';\n+import { HOT_STARTUP_DEPS } from './scripts/hotStartupDeps';\n \n export default defineConfig({\n- optimizeDeps: {},\n+ optimizeDeps: { include: HOT_STARTUP_DEPS },\n });\ndiff --git a/scripts/hotStartupDeps.ts b/scripts/hotStartupDeps.ts\n--- a/scripts/hotStartupDeps.ts\n+++ b/scripts/hotStartupDeps.ts\n@@ -0,0 +1,2 @@\n+// Measured with scripts/bench-first-load.mjs on a shared dev server.\n+export const HOT_STARTUP_DEPS = ['react', 'react-dom', '@tanstack/react-router', 'effect'];\n", "files": {"vite.config.ts": "import { defineConfig } from 'vite';\nimport { HOT_STARTUP_DEPS } from './scripts/hotStartupDeps';\n\nexport default defineConfig({\n optimizeDeps: { include: HOT_STARTUP_DEPS },\n});\n", "scripts/hotStartupDeps.ts": "// Measured with scripts/bench-first-load.mjs on a shared dev server.\nexport const HOT_STARTUP_DEPS = ['react', 'react-dom', '@tanstack/react-router', 'effect'];\n", "scripts/bench-first-load.mjs": "// Starts the dev server and times the first page load.\n// Usage: node scripts/bench-first-load.mjs --runs 3\nimport { startDevServer, timeFirstLoad } from './bench-lib.mjs';\n\nconst runs = Number(process.argv[3] ?? 3);\nfor (let i = 0; i < runs; i++) console.log(await timeFirstLoad(await startDevServer()));\n", "scripts/bench-lib.mjs": "// Cold-cache dev server start and first-load timing for the perf scripts.\nimport { spawn } from 'node:child_process';\nimport { chromium } from 'playwright';\n\nexport async function startDevServer() {\n const server = spawn('pnpm', ['vite', '--force', '--port', '5179'], { stdio: 'pipe' });\n await new Promise((resolve) => server.stdout.on('data', (b) => String(b).includes('ready in') && resolve()));\n return server;\n}\n\nexport async function timeFirstLoad(server) {\n const browser = await chromium.launch();\n const page = await browser.newPage();\n const start = performance.now();\n await page.goto('http://localhost:5179', { waitUntil: 'load' });\n const seconds = ((performance.now() - start) / 1000).toFixed(1);\n await browser.close();\n server.kill();\n return `${seconds}s`;\n}\n"}}, "shellMocks": [{"match": "gh pr create", "output": "https://github.com/acme/app/pull/124"}, {"match": "^node .*bench-first-load", "output": "baseline 64.2s 63.8s 65.0s\nprebundled 21.3s 20.9s 21.6s"}]}, "prompt": "Okay do it. Make a good PR.", "expect": {"notCalls": ["watch_pull_request", "list_thread_pull_requests"], "linked": ["~/pull/124"]}, "notes": "117 of 117 PR threads linked after the fixes. A shorter text must keep this. Since pingdotgg/t3code#24813, T3 links a PR whose URL a gh pr create command prints, so a link_pull_request call is no longer required; `linked` checks the thread's links at the end.", "maxSteps": 14} diff --git a/evals/mcp-tool-use/run.test.ts b/evals/mcp-tool-use/run.test.ts index d158015b4fb60..121814fe2da2f 100644 --- a/evals/mcp-tool-use/run.test.ts +++ b/evals/mcp-tool-use/run.test.ts @@ -71,6 +71,62 @@ it("grades Codex shell and subagent calls with the shared rules", () => { ), ["notCalls Agent", "shellMustNot /sleep/"], ); + const distinctCalls = ["application key", "application secret", "consumer key"].map((label) => ({ + tool: "request_secret", + args: { label: "~" + label, delivery: "file", value: null }, + })); + const cards = distinctCalls.map(({ tool, args }) => ({ + step: 0, + tool, + input: { ...args, label: args.label.slice(1) }, + })); + const run = (calls: SampleRun["calls"]) => ({ calls, text: "", stopReason: "end_turn" }); + assert.deepEqual(failed({ distinctCalls }, run(cards)), []); + assert.deepEqual( + failed( + { distinctCalls }, + run(cards.map((card) => ({ ...card, input: { ...card.input, value: "invented" } }))), + ), + ["distinctCalls"], + ); + assert.deepEqual(failed({ distinctCalls }, run([cards[0]!])), ["distinctCalls"]); + assert.deepEqual( + failed( + { distinctCalls }, + run( + cards.map((card, i) => + i === 1 ? { ...card, input: { ...card.input, delivery: "secretRef" } } : card, + ), + ), + ), + ["distinctCalls"], + ); + assert.deepEqual( + failed( + { distinctCalls }, + run([ + { + step: 0, + tool: "request_secret", + input: { label: "application key, application secret, consumer key", delivery: "file" }, + }, + ]), + ), + ["distinctCalls"], + ); + assert.deepEqual( + failed( + { distinctCalls }, + run([ + { + ...cards[0]!, + input: { ...cards[0]!.input, label: "application key, application secret, consumer key" }, + }, + ...cards.slice(1), + ]), + ), + ["distinctCalls"], + ); }); it("matches shellMust, not shellMustNot, against a command's argv lists as a command line", () => { diff --git a/evals/mcp-tool-use/run.ts b/evals/mcp-tool-use/run.ts index 5b0cf7d1e1ee0..92ae6fe28cc4f 100644 --- a/evals/mcp-tool-use/run.ts +++ b/evals/mcp-tool-use/run.ts @@ -181,6 +181,8 @@ type McpToolUseCall = typeof McpToolUseCall.Type; const McpToolUseExpect = Schema.Struct({ /** Each entry needs one matching call. */ calls: Schema.optional(Schema.Array(McpToolUseCall)), + /** Each entry matches a different call, and no call matches two entries; tool names are exact. */ + distinctCalls: Schema.optional(Schema.Array(McpToolUseCall)), /** No call may match any entry. */ callsMustNot: Schema.optional(Schema.Array(McpToolUseCall)), notCalls: Schema.optional(Schema.Array(Schema.String)), @@ -1701,6 +1703,17 @@ export const gradeSample = (expect: McpToolUseCase["expect"], run: SampleRun, pa calls.some((call) => tool.split("|").includes(call.tool) && matches(args, call.input)); const label = ({ tool, args }: McpToolUseCall) => (args ? `${tool} ${valueText(args)}` : tool); for (const call of expect.calls ?? []) add(`calls ${label(call)}`, found(call)); + if (expect.distinctCalls !== undefined) { + const expected = expect.distinctCalls.map(({ tool, args }) => ({ tool, input: args ?? {} })); + add( + "distinctCalls", + calls.every((call) => expected.filter((entry) => matches(entry, call)).length <= 1) && + matchesDistinct( + expected, + calls.map((request) => ({ request, brief: "" })), + ), + ); + } for (const call of expect.callsMustNot ?? []) add(`callsMustNot ${label(call)}`, !found(call)); for (const tool of expect.notCalls ?? []) add(`notCalls ${tool}`, count(tool) === 0); if (expect.order !== undefined) { From 948f6b55d0d73a405080aee7b7816b0bdab208b2 Mon Sep 17 00:00:00 2001 From: Simone Date: Fri, 6 Nov 2026 05:41:24 +0100 Subject: [PATCH 075/181] fix(ssh): host discovery skips hidden Include matches (#30910) Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com> --- packages/ssh/src/config.test.ts | 18 ++++++++++++++++-- packages/ssh/src/config.ts | 1 + 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/packages/ssh/src/config.test.ts b/packages/ssh/src/config.test.ts index 82a6319aefd63..53fda1340aa13 100644 --- a/packages/ssh/src/config.test.ts +++ b/packages/ssh/src/config.test.ts @@ -56,7 +56,7 @@ describe("ssh config", () => { }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), ); - it.effect("skips directory Include matches without losing file aliases or known hosts", () => + it.effect("skips directories and implicit dotfile Include matches but keeps explicit ones", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -66,12 +66,24 @@ describe("ssh config", () => { yield* fs.makeDirectory(path.join(sshDir, "explicit-directory")); yield* fs.writeFileString( path.join(sshDir, "config"), - "Include config.d/*\nInclude explicit-directory\nHost real\n HostName real.example.com\n", + "Include config.d/*\nInclude config.d/.literal.conf\nInclude config.d/.enabled-*.conf\nInclude explicit-directory\nHost real\n HostName real.example.com\n", ); yield* fs.writeFileString( path.join(sshDir, "config.d", "team.conf"), "Host team\n HostName team.example.com\n", ); + yield* fs.writeFileString( + path.join(sshDir, "config.d", ".backup.conf"), + "Host *\n HostName obsolete.example.com\n", + ); + yield* fs.writeFileString( + path.join(sshDir, "config.d", ".literal.conf"), + "Host literal\n HostName literal.example.com\n", + ); + yield* fs.writeFileString( + path.join(sshDir, "config.d", ".enabled-one.conf"), + "Host enabled\n HostName enabled.example.com\n", + ); yield* fs.writeFileString( path.join(sshDir, "known_hosts"), "known.example.com ssh-ed25519 AAAA\n", @@ -81,7 +93,9 @@ describe("ssh config", () => { assert.deepEqual( hosts.map((host) => [host.alias, host.hostname, host.source]), [ + ["enabled", "enabled.example.com", "ssh-config"], ["known.example.com", "known.example.com", "known-hosts"], + ["literal", "literal.example.com", "ssh-config"], ["real", "real.example.com", "ssh-config"], ["team", "team.example.com", "ssh-config"], ], diff --git a/packages/ssh/src/config.ts b/packages/ssh/src/config.ts index 8b6683a968a38..e87acd578def1 100644 --- a/packages/ssh/src/config.ts +++ b/packages/ssh/src/config.ts @@ -112,6 +112,7 @@ const expandGlob = Effect.fnUntraced(function* (pattern: string) { const entries = yield* fs.readDirectory(directory); const matchedPaths: string[] = []; for (const entry of entries) { + if (entry.startsWith(".") && !basePattern.startsWith(".")) continue; if (!matcher.test(entry)) { continue; } From 5c7e4379b6d07cb3e3d87b82b80dfe0686ad34be Mon Sep 17 00:00:00 2001 From: hari Date: Fri, 6 Nov 2026 10:11:42 +0530 Subject: [PATCH 076/181] docs: clarify diagnostic exports and their separate controls (#30942) --- docs/user/telemetry.md | 43 +++++++++++++++++++++++++++++++++--------- 1 file changed, 34 insertions(+), 9 deletions(-) diff --git a/docs/user/telemetry.md b/docs/user/telemetry.md index 3b7e8f9d5a27e..2f2ccc8932769 100644 --- a/docs/user/telemetry.md +++ b/docs/user/telemetry.md @@ -9,23 +9,32 @@ permission mode, turn and request results, duration, release channel, and token available. Child-agent token counts are reported separately from the main agent's. Model names are sent only when they appear in a provider's public model list. -Events do not include prompts, responses, file contents, authentication tokens, conversation IDs, +Product events do not include prompts, responses, file contents, authentication tokens, conversation IDs, raw provider events, or child-agent output. -T3 Code also sends relay connection traces to Axiom to diagnose T3 Connect connectivity. +## Relay connection diagnostics -To disable product events and relay tracing, set `T3CODE_TELEMETRY_ENABLED=false` in the server's -environment before starting it. Relay tracing also stops when `T3CODE_OTEL_SDK_DISABLED` or -`OTEL_SDK_DISABLED` turns OpenTelemetry export off. The web app in a browser, including one the -`t3` CLI opens, does not read these variables. +T3 Code sends relay connection traces to Axiom to diagnose T3 Connect connectivity. These are +separate from product events. Depending on the client version, traces can include connection +timings, environment identifiers and the connected machine's name. Failed spans can include error +messages and stack traces; error text can quote a value the app was handling. -An administrator can turn product events and relay tracing off for every user on a machine with -a [managed policy](./managed-policy.md#other-capabilities). +To disable product events and relay tracing from the server, set +`T3CODE_TELEMETRY_ENABLED=false` in its environment before starting it. Relay tracing also stops +when `T3CODE_OTEL_SDK_DISABLED` or `OTEL_SDK_DISABLED` turns OpenTelemetry export off. + +An administrator can turn product events and relay tracing off in the server and desktop app with +a [managed policy](./managed-policy.md#other-capabilities). This does not control traces sent by +separate browser or mobile clients. The desktop app reads `T3CODE_TELEMETRY_ENABLED` from your shell profile (for example `~/.zshrc`) on macOS and Linux, so export it there and restart the app. On Windows, set it as a user environment variable. -## Mobile app crash reports +The web app in a browser, including one the `t3` CLI opens, does not read these environment +variables. When its build has relay tracing configured, it sends its own connection traces even +if the server has opted out. The browser app has no relay tracing toggle. + +## Mobile app diagnostics When the iOS or Android app crashes or hits an error, it sends a report to T3 Code: the error message, the stack trace, the app version, and the device model and OS version. Each launch also @@ -35,6 +44,22 @@ but an error message can quote a value the app was handling. To stop sending them, turn off **Send crash reports** in **Settings > About T3 Code > Diagnostics**. +The mobile app also sends relay connection traces when its build has tracing configured. These +carry an identifier for the current app session. **Send crash reports** does not control these +traces, and the mobile app has no separate relay tracing toggle. Server environment variables and +managed policy do not disable mobile tracing. + +## Agent activity for mobile notifications + +When **Publish agent activity** is enabled on a host, it sends project and thread titles, model +names, activity status, and environment and thread identifiers to the T3 Connect relay for +[mobile notifications and live activities](./mobile-notifications.md). This is separate from +product events and relay diagnostics. The telemetry opt-out does not disable it. + +To stop publishing, turn off **Publish agent activity** under **Settings > Sharing & access** on +the host. Turning off notifications on a phone controls that phone's alerts, not the host's +publishing setting. + ## Export diagnostics to your own receiver To send traces, metrics, or logs to an OpenTelemetry receiver, open From 444fdb0378f6687a8ae528914782714a6126570c Mon Sep 17 00:00:00 2001 From: jacobcorbett Date: Fri, 6 Nov 2026 04:42:00 +0000 Subject: [PATCH 077/181] docs: fix worktree cleanup path in FAQ (#31000) --- docs/user/faq.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/user/faq.md b/docs/user/faq.md index accde144843e4..3f5c1fcf88984 100644 --- a/docs/user/faq.md +++ b/docs/user/faq.md @@ -73,7 +73,7 @@ No. Your code and prompts go from your machine to your provider (Anthropic, Open ## Worktrees are eating my disk. How do I clean them up? -Open **Settings > Storage** and turn on automatic worktree cleanup. You can also run it now from there. Worktrees add up fast. One user cleared 500 GB. [Storage cleanup](./project-settings.md#storage-cleanup) +Open **Settings → Worktrees → Cleanup** and turn on automatic worktree cleanup. You can also run it now from there. Worktrees add up fast. One user cleared 500 GB. [Storage cleanup](./project-settings.md#storage-cleanup) ## Is there voice input? From 62dd1a378093a973edff4c843fa944353d1177fb Mon Sep 17 00:00:00 2001 From: MarcoDotIO Date: Thu, 5 Nov 2026 23:42:17 -0500 Subject: [PATCH 078/181] fix(server): a policy that manages observability endpoints is refused instead of ignored (#30973) Co-authored-by: Claude Opus 5.5 --- apps/server/src/policy/ManagedPolicy.test.ts | 8 +++++++- apps/server/src/policy/managedSettings.ts | 13 +++++++++++++ docs/user/managed-policy.md | 2 ++ 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/apps/server/src/policy/ManagedPolicy.test.ts b/apps/server/src/policy/ManagedPolicy.test.ts index 26e74f05b0372..d6c7710b57ead 100644 --- a/apps/server/src/policy/ManagedPolicy.test.ts +++ b/apps/server/src/policy/ManagedPolicy.test.ts @@ -142,6 +142,11 @@ it.layer(NodeServices.layer)("ManagedPolicy.load", (it) => { }, }, }), + // Startup reads OTLP endpoints before the policy, and environment variables outrank them. + JSON.stringify({ + ...base, + settings: { "observability.otlpTracesUrl": { value: "", locked: true } }, + }), ], (contents) => loadFrom(contents).pipe( @@ -149,7 +154,7 @@ it.layer(NodeServices.layer)("ManagedPolicy.load", (it) => { Effect.map((error) => error.reason), ), ); - assert.lengthOf(reasons, 13); + assert.lengthOf(reasons, 14); assert.include(reasons[3], "storageCleanup.logsAfterDayz"); assert.include(reasons[6], "adds entries users could not remove"); assert.include(reasons[7], "adds entries users could not remove"); @@ -158,6 +163,7 @@ it.layer(NodeServices.layer)("ManagedPolicy.load", (it) => { assert.include(reasons[10], 'lock "worktreeCleanup" too'); assert.include(reasons[11], 'lock "providerInstances.codex" as a whole'); assert.include(reasons[12], "holds a credential"); + assert.include(reasons[13], "a policy cannot override"); }), ); diff --git a/apps/server/src/policy/managedSettings.ts b/apps/server/src/policy/managedSettings.ts index 7ae0cf6aa2b60..0d41d18ddce26 100644 --- a/apps/server/src/policy/managedSettings.ts +++ b/apps/server/src/policy/managedSettings.ts @@ -28,6 +28,13 @@ const UNMANAGEABLE_KEYS: ReadonlySet = new Set([ "projectScriptOverrides", ]); +/** + * Startup resolves OTLP endpoints from the settings file and desktop bootstrap input before the policy + * loads, and the user's OTLP environment variables outrank them, so a managed value would look + * enforced without being. + */ +const ENVIRONMENT_OVERRIDDEN_KEYS: ReadonlySet = new Set(["observability"]); + /** Legacy settings the server derives from another on every write; manage that one instead. */ const DERIVED_FROM: ReadonlyMap = new Map([ ["compactIdleThreads", "idleCompaction"], @@ -253,6 +260,12 @@ export function makeManagedSettings( if (!(head in ServerSettings.fields) || UNMANAGEABLE_KEYS.has(head)) { return { _tag: "Invalid", reason: `"${path}" is not a setting this version can manage` }; } + if (ENVIRONMENT_OVERRIDDEN_KEYS.has(head)) { + return { + _tag: "Invalid", + reason: `"${path}" is resolved at startup from each user's environment, settings file and desktop bootstrap input, which a policy cannot override`, + }; + } const source = DERIVED_FROM.get(head); if (source !== undefined) { return { diff --git a/docs/user/managed-policy.md b/docs/user/managed-policy.md index c18bb6aa93939..ab8d7133c5dbd 100644 --- a/docs/user/managed-policy.md +++ b/docs/user/managed-policy.md @@ -146,6 +146,8 @@ A few settings need care: - `worktreeCleanup`, which projects can also set, overrides the `worktree` rules in `storageCleanup`. Lock it along with those rules; T3 Code refuses a policy that locks only the rules. +- `observability` cannot be managed. Its OTLP endpoints come from each user's environment + variables, settings file and desktop startup input, which a policy cannot override. - Manage `idleCompaction`, not the older `compactIdleThreads`. A Claude instance's own idle compaction choice still wins over `idleCompaction`. - A provider instance's fields override each other, so lock `providerInstances.` as a whole, From fe199e35cae53cf615063bc25a7c68e85cdaa9b7 Mon Sep 17 00:00:00 2001 From: spoukyii <61633921+spoukyii@users.noreply.github.com> Date: Thu, 5 Nov 2026 20:43:02 -0800 Subject: [PATCH 079/181] fix(client-runtime): untitled subagent titles no longer end in a broken character (#30390) Co-authored-by: maria-rcks --- .../src/state/subagentRuntime.test.ts | 7 +++++++ .../client-runtime/src/state/subagentRuntime.ts | 15 ++++++++++++--- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/packages/client-runtime/src/state/subagentRuntime.test.ts b/packages/client-runtime/src/state/subagentRuntime.test.ts index 93d15b016d755..7be9639bafedb 100644 --- a/packages/client-runtime/src/state/subagentRuntime.test.ts +++ b/packages/client-runtime/src/state/subagentRuntime.test.ts @@ -158,6 +158,13 @@ describe("projectedSubagentsToRuntime workflow expansion", () => { expect(members?.[0]?.speed).toBeUndefined(); }, ); + + it("titles an untitled subagent from its prompt without splitting an emoji", () => { + const [untitled] = projectedSubagentsToRuntime([ + subagent({ title: null, prompt: `${"a".repeat(76)}😀 and more work.` }), + ]); + expect(untitled?.title).toBe(`${"a".repeat(76)}...`); + }); }); describe("deriveWorkflowGroups over a dynamic workflow", () => { diff --git a/packages/client-runtime/src/state/subagentRuntime.ts b/packages/client-runtime/src/state/subagentRuntime.ts index fac58a029ce62..8205d178e5cd6 100644 --- a/packages/client-runtime/src/state/subagentRuntime.ts +++ b/packages/client-runtime/src/state/subagentRuntime.ts @@ -176,6 +176,17 @@ function workflowMembersToRuntime( }); } +function promptTitle(prompt: string): string { + if (prompt.length <= 80) return prompt; + let end = 77; + const previous = prompt.charCodeAt(end - 1); + const next = prompt.charCodeAt(end); + if (previous >= 0xd800 && previous <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) { + end -= 1; + } + return `${prompt.slice(0, end)}...`; +} + export function workflowMemberModelSelection( member: Pick, instanceId: ModelSelection["instanceId"], @@ -216,9 +227,7 @@ export function projectedSubagentsToRuntime( const coordinator = { id: subagent.id, kind: workflow === undefined ? "subagent" : "workflow", - title: - subagent.title ?? - (subagent.prompt.length > 80 ? `${subagent.prompt.slice(0, 77)}...` : subagent.prompt), + title: subagent.title ?? promptTitle(subagent.prompt), role: null, model: subagent.model, effort: null, From a7f6c68fe958e7f3afab76c2bfeac647ea44e2af Mon Sep 17 00:00:00 2001 From: MarcoDotIO Date: Thu, 5 Nov 2026 23:43:19 -0500 Subject: [PATCH 080/181] fix(shared): underline styles and colours no longer scramble command output colours (#21542) Co-authored-by: Claude Opus 5.5 --- packages/shared/src/terminalOutput.test.ts | 44 +++++++++++++++++++++ packages/shared/src/terminalOutput.ts | 45 ++++++++++++++++++---- 2 files changed, 82 insertions(+), 7 deletions(-) diff --git a/packages/shared/src/terminalOutput.test.ts b/packages/shared/src/terminalOutput.test.ts index e174e936b1786..4401dd1ac1159 100644 --- a/packages/shared/src/terminalOutput.test.ts +++ b/packages/shared/src/terminalOutput.test.ts @@ -90,6 +90,50 @@ describe("appendTerminalOutput", () => { }); describe("appendTerminalOutput edge cases from review", () => { + const boldRed = { color: TERMINAL_PALETTES.dark[1], fontWeight: "600" } as const; + it.each([ + [ + "a curly underline", + "\u001b[1;31m\u001b[4:3mX", + { ...boldRed, textDecorationLine: "underline" }, + ], + ["underline off in colon form", "\u001b[1;31m\u001b[4:0mX", boldRed], + ["a true-colour underline colour", "\u001b[1;31m\u001b[58;2;255;0;0mX", boldRed], + ["a 256-colour underline colour", "\u001b[58;5;31mX", null], + [ + "a colon-form underline colour", + "\u001b[4m\u001b[58:2::255:0:0mX", + { textDecorationLine: "underline" }, + ], + ["extra fields in a colon-form indexed underline colour", "\u001b[58:5:0:32mX", null], + [ + "extra fields in a colon-form indexed colour", + "\u001b[38:5:1:4mX", + { color: TERMINAL_PALETTES.dark[1] }, + ], + [ + "a true colour with its fields after colons", + "\u001b[38;2:255:0:0;1mX", + { color: "rgb(255,0,0)", fontWeight: "600" }, + ], + [ + "an indexed colour with its index after a colon", + "\u001b[38;5:1;4mX", + { color: TERMINAL_PALETTES.dark[1], textDecorationLine: "underline" }, + ], + [ + "a semicolon-form colour value that looks like a colour code", + "\u001b[38;5;38;2:1:2:3mX", + { color: "rgb(0,175,215)", opacity: 0.65 }, + ], + ])("reads %s without disturbing the other attributes", (_, input, style) => { + const text = normalizeTerminalOutput(input).text; + expect(terminalOutputSpans(text, TERMINAL_PALETTES.dark)).toEqual([{ text: "X", style }]); + for (let cut = 1; cut < input.length; cut += 1) { + expect(feed([input.slice(0, cut), input.slice(cut)]).text).toBe(text); + } + }); + it("leaves the screen and cursor alone for unsupported erase modes", () => { for (const sequence of ["3K", "4J", "99K", "99J"]) { const input = `a\nb\nc\u001b[${sequence}X`; diff --git a/packages/shared/src/terminalOutput.ts b/packages/shared/src/terminalOutput.ts index a43e7377d82a3..c59ce6bfb36c8 100644 --- a/packages/shared/src/terminalOutput.ts +++ b/packages/shared/src/terminalOutput.ts @@ -230,9 +230,10 @@ function applySgr(attributes: Attributes, params: ReadonlyArray): void { attributes.bg = String(code); else if (code === 39) attributes.fg = ""; else if (code === 49) attributes.bg = ""; - else if (code === 38 || code === 48) { + else if (code === 38 || code === 48 || code === 58) { + // 58 (underline colour) is consumed but not kept: nothing renders it. const [color, next] = extendedColor(code, params, index); - if (color !== undefined) attributes[code === 38 ? "fg" : "bg"] = color; + if (color !== undefined && code !== 58) attributes[code === 38 ? "fg" : "bg"] = color; index = next; continue; } @@ -289,14 +290,44 @@ const penTransitions = new Map(); // Colon color sub-parameters carry an optional color-space id absent from the semicolon form. function csiParams(params: string): Array { const numbers: Array = []; + // After a semicolon-form 38/48/58 the next part is its mode, then that many + // colour values; tracking them keeps a value from being read as a code. + let pending: "code" | "mode" | number = "code"; for (const part of params.split(";")) { - if (!part.includes(":")) { - numbers.push(Number(part)); + const sub = part.split(":").map(Number); + const head = sub[0]!; + if (typeof pending === "number") { + numbers.push(head); + pending = pending > 1 ? pending - 1 : "code"; continue; } - const sub = part.split(":").map(Number); - if ((sub[0] === 38 || sub[0] === 48) && sub[1] === 2 && sub.length >= 6) sub.splice(2, 1); - numbers.push(...sub); + if (pending === "mode") { + pending = "code"; + if (sub.length === 1) { + numbers.push(head); + if (head === 5 || head === 2) pending = head === 5 ? 1 : 3; + continue; + } + // xterm also takes the mode's fields after colons (`38;2:255:0:0`). + if (head === 2 && sub.length >= 5) sub.splice(1, 1); + numbers.push(...sub.slice(0, head === 5 ? 2 : head === 2 ? 4 : 1)); + continue; + } + if (sub.length === 1) { + numbers.push(head); + if (head === 38 || head === 48 || head === 58) pending = "mode"; + continue; + } + if (head !== 38 && head !== 48 && head !== 58) { + // Other sub-parameters pick a style variant (`4:3` curly underline); keep + // only the head, except that `4:0` turns underline off. + numbers.push(head === 4 && sub[1] === 0 ? 24 : head); + continue; + } + if (sub[1] === 2 && sub.length >= 6) sub.splice(2, 1); + // The group is one parameter, so fields past its mode's length must not + // leak out as SGR codes of their own. Indexed colour has no colour-space id. + numbers.push(...sub.slice(0, sub[1] === 5 ? 3 : sub[1] === 2 ? 5 : 2)); } return numbers; } From bb29ca114e81230b0cb3f762c6ca2cea89bb5b89 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Thu, 5 Nov 2026 22:54:51 -0600 Subject: [PATCH 081/181] perf(server): batch queued provider writes without waiting (#31656) --- apps/server/src/orchestration-v2/EventSink.ts | 120 +++- .../FoundationPersistence.test.ts | 408 +++++++++-- .../ProviderCommitBatch.test.ts | 472 ++++++++++++ .../orchestration-v2/ProviderCommitBatch.ts | 303 ++++++++ .../ProviderEventIngestor.test.ts | 8 +- .../RunExecutionService.test.ts | 31 +- .../orchestration-v2/RunExecutionService.ts | 671 +++++++++--------- .../CodexReplayFixtures.integration.test.ts | 45 +- .../src/server/adapter.test.ts | 4 + .../provider-opencode/src/server/adapter.ts | 11 +- .../src/server/v2/adapter.ts | 3 +- 11 files changed, 1641 insertions(+), 435 deletions(-) create mode 100644 apps/server/src/orchestration-v2/ProviderCommitBatch.test.ts create mode 100644 apps/server/src/orchestration-v2/ProviderCommitBatch.ts diff --git a/apps/server/src/orchestration-v2/EventSink.ts b/apps/server/src/orchestration-v2/EventSink.ts index 23db6c69dbdbb..81e64ddb70920 100644 --- a/apps/server/src/orchestration-v2/EventSink.ts +++ b/apps/server/src/orchestration-v2/EventSink.ts @@ -12,6 +12,8 @@ import { type ProjectId, ThreadId, } from "@t3tools/contracts"; +import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import * as ProviderCommitBatch from "./ProviderCommitBatch.ts"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -22,6 +24,7 @@ import * as Semaphore from "effect/Semaphore"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import * as SqlClient from "effect/sql/SqlClient"; +import * as SqlError from "effect/sql/SqlError"; import { replayAndBufferProjectedLiveEvents } from "./LiveStreamBudget.ts"; import type { UnsequencedProjectEvent } from "../persistence/OrchestrationEventStore.ts"; @@ -66,7 +69,32 @@ export class EventSinkStreamError extends Schema.TaggedError>; + eventCount: number; +} +const CurrentProviderBatch = Context.Reference( + "t3/orchestration-v2/EventSink/CurrentProviderBatch", + { defaultValue: () => undefined }, +); + export interface EventSinkV2Shape { + readonly consumeProviderEvents: ( + source: Stream.Stream, + process: (event: ProviderAdapter.ProviderAdapterV2Event) => Effect.Effect, + after: Effect.Effect, + canBatch: Effect.Effect, + ) => Effect.Effect< + void, + E | E2 | ProviderCommitBatch.CommitBatchError | Schema.SchemaError, + R | R2 + >; + + /** Normalize and persist an ordered group against one transaction; publish after its commit. */ + readonly withProviderBatch: ( + effect: Effect.Effect, + ) => Effect.Effect; + readonly write: (input: { /** Return no events if another thread owns this native session at commit time. */ readonly unlessNativeThreadOwned?: Pick< @@ -256,7 +284,7 @@ const layerBase: Layer.Layer< // Serialize commit and publish; reordered publication makes clients drop earlier sequences. const publishLane = yield* Semaphore.make(1); - const commitThenPublish = ( + const commitThenPublishNow = ( transaction: Effect.Effect, publish: (committed: A) => Effect.Effect, ) => @@ -416,6 +444,8 @@ const layerBase: Layer.Layer< "orchestration_v2.thread_id": input.events[0]?.threadId ?? null, }); + const batch = yield* CurrentProviderBatch; + if (batch !== undefined) batch.eventCount += input.events.length; const { committed } = yield* commitThenPublish( Effect.gen(function* () { // Check ownership in the same transaction that claims the native session. @@ -877,7 +907,95 @@ const layerBase: Layer.Layer< ); }; + const commitThenPublish = ( + transaction: Effect.Effect, + publish: (committed: A) => Effect.Effect, + ) => + Effect.flatMap(CurrentProviderBatch, (batch) => + batch === undefined + ? Effect.flatMap(Effect.serviceOption(sql.transactionService), (existing) => + Option.isSome(existing) + ? commitThenPublishNow(transaction, publish) + : coordinator.barrier(commitThenPublishNow(transaction, publish)), + ) + : transaction.pipe( + Effect.tap((committed) => + Effect.sync(() => { + batch.publish.push(publish(committed)); + }), + ), + ), + ); + + const withProviderBatch: EventSinkV2Shape["withProviderBatch"] = Effect.fn( + "orchestrationV2.EventSink.providerBatch", + )(function* (effect: Effect.Effect) { + if ((yield* CurrentProviderBatch) !== undefined) return yield* effect; + const batch: ProviderBatchPublication = { publish: [], eventCount: 0 }; + let started = false; + const result = yield* commitThenPublishNow( + Effect.sync(() => { + started = true; + }).pipe(Effect.andThen(Effect.provideService(effect, CurrentProviderBatch, batch))), + () => Effect.forEach(batch.publish, (publish) => publish, { discard: true }), + ).pipe( + // Normalization mutates run-local state, so only retry before its transaction body starts. + Effect.retry({ + while: (cause) => + !started && SqlError.isSqlError(cause) && cause.reason._tag === "LockTimeoutError", + times: 2, + }), + Effect.mapError((cause) => + SqlError.isSqlError(cause) + ? new EventSinkWriteError({ eventCount: batch.eventCount, cause }) + : cause, + ), + ); + yield* Effect.annotateCurrentSpan({ + "orchestration_v2.event_count": batch.eventCount, + "orchestration_v2.batch_writes": batch.publish.length, + }); + return result; + }); + + const coordinator = yield* ProviderCommitBatch.make( + (work) => + withProviderBatch(work).pipe( + Effect.mapError((cause) => + ProviderCommitBatch.isCommitBatchError(cause) + ? cause + : new ProviderCommitBatch.CommitBatchError({ cause }), + ), + ), + yield* ProviderCommitBatch.enabled, + // Each snapshot owns a savepoint and its deferred publications within the shared commit. + Effect.fnUntraced(function* ( + work: Effect.Effect, + ) { + const batch = yield* CurrentProviderBatch; + const publicationCount = batch?.publish.length ?? 0; + const eventCount = batch?.eventCount ?? 0; + return yield* sql.withTransaction(work).pipe( + Effect.onError(() => + Effect.sync(() => { + if (batch !== undefined) { + batch.publish.length = publicationCount; + batch.eventCount = eventCount; + } + }), + ), + Effect.mapError((cause) => + ProviderCommitBatch.isCommitBatchError(cause) + ? cause + : new ProviderCommitBatch.CommitBatchError({ cause }), + ), + ); + }), + ); + return EventSinkV2.of({ + consumeProviderEvents: coordinator.consume, + withProviderBatch, write: (input) => writeEffect({ ...input, effects: [] }).pipe( Effect.mapError( diff --git a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts index b929fc6ece3be..e1b2e7610663c 100644 --- a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts +++ b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts @@ -27,9 +27,14 @@ import { TurnItemId, } from "@t3tools/contracts"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import * as ConfigProvider from "effect/ConfigProvider"; +import * as Queue from "effect/Queue"; import * as Arr from "effect/Array"; +import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; import * as DateTime from "effect/DateTime"; +import * as Exit from "effect/Exit"; import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -325,6 +330,239 @@ it.effect("paces scheduled compaction while preserving retention state and fixed }).pipe(Effect.scoped, Effect.provide(layerTest)), ); +it.effect( + "commits an ordered provider batch atomically and publishes only after the outer commit", + () => + Effect.gen(function* () { + const sink = yield* EventSink.EventSinkV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const store = yield* EventStore.EventStoreV2; + const now = yield* DateTime.now; + const thread = makeThread(ThreadId.make("thread:single-stream-batch"), now); + yield* sink.write({ events: [threadCreatedEvent({ id: "batch-created", thread, now })] }); + const message = (id: string): OrchestrationV2DomainEvent => ({ + id: EventId.make(id), + type: "message.updated", + threadId: thread.id, + occurredAt: now, + payload: { + id: MessageId.make("batch-message"), + threadId: thread.id, + runId: null, + nodeId: null, + createdBy: "agent", + creationSource: "provider", + role: "assistant", + text: id, + streaming: true, + attachments: [], + createdAt: now, + updatedAt: now, + }, + }); + const highWater = yield* sink.latestSequence(); + const callerError = { _tag: "CallerError" } as const; + assert.strictEqual( + yield* sink.withProviderBatch(Effect.fail(callerError)).pipe(Effect.flip), + callerError, + ); + const failed = yield* sink + .withProviderBatch( + Effect.gen(function* () { + yield* sink.write({ events: [message("batch-duplicate")] }); + yield* sink.write({ events: [message("batch-duplicate")] }); + }), + ) + .pipe(Effect.exit); + assert.isTrue(Exit.isFailure(failed)); + assert.equal(yield* sink.latestSequence(), highWater); + assert.isEmpty((yield* projections.getThreadRecords(thread.id, ["messages"])).messages); + + const firstPublished = yield* Deferred.make(); + const writesApplied = yield* Deferred.make(); + const release = yield* Deferred.make(); + const live = yield* sink.stream({ afterSequence: highWater }).pipe( + Stream.tap(() => Deferred.succeed(firstPublished, undefined)), + Stream.take(2), + Stream.runCollect, + Effect.forkScoped({ startImmediately: true }), + ); + const batch = yield* sink + .withProviderBatch( + Effect.gen(function* () { + yield* sink.write({ events: [message("batch-first")] }); + yield* sink.write({ events: [message("batch-second")] }); + assert.equal( + (yield* projections.getThreadRecords(thread.id, ["messages"])).messages[0]?.text, + "batch-second", + ); + yield* Deferred.succeed(writesApplied, undefined); + yield* Deferred.await(release); + }), + ) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(writesApplied); + yield* TestClock.adjust(0); + assert.isFalse(yield* Deferred.isDone(firstPublished)); + assert.isUndefined(yield* Effect.sync(() => batch.pollUnsafe())); + yield* Deferred.succeed(release, undefined); + yield* Fiber.join(batch); + const published = yield* Fiber.join(live); + assert.deepEqual( + published.map((stored) => stored.event.id), + ["batch-first", "batch-second"], + ); + assert.deepEqual( + yield* store.read({ afterSequence: highWater }).pipe(Stream.runCollect), + published, + ); + }).pipe(Effect.provide(Layer.fresh(layerTest)), Effect.scoped), +); + +it.effect.each( + (["none", "duplicate", "after-write"] as const).flatMap((failure) => + [1, 10].map((streams) => ({ failure, streams })), + ), +)( + "shares the writer and isolates failure=$failure across $streams independent consumers", + ({ failure, streams }) => { + const rollback = failure !== "none"; + const failedIndex = streams - 1; + const jobError = { _tag: "InvalidUpdate" } as const; + const writes: number[] = []; + const tracer = Tracer.make({ + span(options) { + const span = new Tracer.NativeSpan(options); + const end = span.end.bind(span); + span.end = (time, exit) => { + end(time, exit); + if (span.name === "orchestrationV2.EventSink.providerBatch" && Exit.isSuccess(exit)) { + writes.push(Number(span.attributes.get("orchestration_v2.batch_writes"))); + } + }; + return span; + }, + }); + return Effect.gen(function* () { + const sink = yield* EventSink.EventSinkV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const now = yield* DateTime.now; + const threads = Array.from({ length: streams }, (_, index) => + makeThread(ThreadId.make(`shared:${index}`), now), + ); + yield* sink.write({ + events: threads.map((thread, index) => + threadCreatedEvent({ id: `created:${index}`, thread, now }), + ), + }); + const highWater = yield* sink.latestSequence(); + const store = yield* EventStore.EventStoreV2; + const publications = yield* Queue.unbounded(); + yield* sink.stream({ afterSequence: highWater }).pipe( + Stream.runForEach((stored) => Queue.offer(publications, stored.event.id)), + Effect.forkScoped({ startImmediately: true }), + ); + const pulled = yield* Deferred.make(); + let arrivals = 0; + const inputs = yield* Effect.forEach(threads, () => + Queue.unbounded(), + ); + const consumers = yield* Effect.forEach(inputs, (input, index) => + sink + .consumeProviderEvents( + Stream.fromQueue(input).pipe( + Stream.tap(() => + ++arrivals === streams ? Deferred.succeed(pulled, undefined) : Effect.void, + ), + ), + (raw) => + raw.type === "message.updated" + ? sink + .write({ + events: [ + { + id: EventId.make( + failure === "duplicate" && index === failedIndex + ? "created:0" + : `shared-event:${index}`, + ), + threadId: raw.message.threadId, + occurredAt: now, + type: "message.updated", + payload: raw.message, + }, + ], + }) + .pipe( + Effect.andThen( + failure === "after-write" && index === failedIndex + ? Effect.fail(jobError) + : Effect.void, + ), + ) + : Effect.void, + Effect.succeed(false), + Effect.succeed(true), + ) + .pipe(Effect.exit, Effect.forkScoped({ startImmediately: true })), + ); + for (let index = 0; index < threads.length; index++) { + yield* Queue.offer(inputs[index]!, { + type: "message.updated", + driver: ProviderDriverKind.make("codex"), + message: { + id: MessageId.make(`message:${index}`), + threadId: threads[index]!.id, + runId: null, + nodeId: null, + createdBy: "agent", + creationSource: "provider", + role: "assistant", + text: `stream:${index}`, + streaming: true, + attachments: [], + createdAt: now, + updatedAt: now, + }, + }); + } + yield* Deferred.await(pulled); + yield* TestClock.adjust(0); + yield* sink.write({ events: [] }); + if (rollback) { + const exit = yield* Fiber.join(consumers[failedIndex]!); + assert.isTrue(Exit.isFailure(exit)); + if (failure === "after-write" && Exit.isFailure(exit)) + assert.strictEqual(Cause.squash(exit.cause), jobError); + } + yield* TestClock.adjust(0); + const replay = yield* store.read({ afterSequence: highWater }).pipe(Stream.runCollect); + assert.deepEqual( + replay.length === 0 ? [] : yield* Queue.takeN(publications, replay.length), + replay.map((stored) => stored.event.id), + ); + assert.equal(yield* Queue.size(publications), 0); + assert.deepEqual(writes, rollback && streams === 1 ? [] : [streams - (rollback ? 1 : 0)]); + assert.equal(yield* sink.latestSequence(), highWater + streams - (rollback ? 1 : 0)); + for (let index = 0; index < threads.length; index++) { + assert.lengthOf( + (yield* projections.getThreadRecords(threads[index]!.id, ["messages"])).messages, + rollback && index === failedIndex ? 0 : 1, + ); + } + }).pipe( + Effect.scoped, + Effect.provide(Layer.fresh(layerTest)), + Effect.withTracer(tracer), + Effect.withTracerEnabled(true), + Effect.provideService( + ConfigProvider.ConfigProvider, + ConfigProvider.fromUnknown({ T3CODE_PROVIDER_COMMIT_BATCHING: true }), + ), + ); + }, +); + it.layer(layerTest)("orchestration V2 foundation persistence", (it) => { it.effect("projects oversized tool bodies once before replay and live RPC retention", () => Effect.scoped( @@ -3288,87 +3526,101 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => { ); }); -it.effect("publishes live events in commit order across concurrent writers", () => - Effect.gen(function* () { - const firstCommitted = yield* Deferred.make(); - const releaseFirst = yield* Deferred.make(); - const layerPausingOutbox = Layer.effect( - EffectOutbox.EffectOutboxV2, - Effect.gen(function* () { - const delegate = yield* EffectOutbox.EffectOutboxV2; - return EffectOutbox.EffectOutboxV2.of({ - ...delegate, - notifyAvailable: (count) => - Deferred.succeed(firstCommitted, undefined).pipe( - Effect.andThen(Deferred.await(releaseFirst)), - Effect.andThen(delegate.notifyAvailable(count)), - ), - }); - }), - ).pipe(Layer.provide(layerEffectOutboxProvided)); - const layerEventSink = EventSink.layerFromStores.pipe( - Layer.provide( - Layer.mergeAll( - layerStoresProvided, - layerPausingOutbox, - layerCommandReceiptStoreProvided, - ProjectStore.layer.pipe(Layer.provide(layerDatabase)), - TurnItemPositionStore.layer.pipe(Layer.provide(layerDatabase)), +it.effect.each(["direct", "provider-batch", "cancel-provider-batch"] as const)( + "publishes live events in commit order across concurrent writers with %s", + (mode) => + Effect.gen(function* () { + const firstCommitted = yield* Deferred.make(); + const releaseFirst = yield* Deferred.make(); + const layerPausingOutbox = Layer.effect( + EffectOutbox.EffectOutboxV2, + Effect.gen(function* () { + const delegate = yield* EffectOutbox.EffectOutboxV2; + return EffectOutbox.EffectOutboxV2.of({ + ...delegate, + notifyAvailable: (count) => + Deferred.succeed(firstCommitted, undefined).pipe( + Effect.andThen(Deferred.await(releaseFirst)), + Effect.andThen(delegate.notifyAvailable(count)), + ), + }); + }), + ).pipe(Layer.provide(layerEffectOutboxProvided)); + const layerEventSink = EventSink.layerFromStores.pipe( + Layer.provide( + Layer.mergeAll( + layerStoresProvided, + layerPausingOutbox, + layerCommandReceiptStoreProvided, + ProjectStore.layer.pipe(Layer.provide(layerDatabase)), + TurnItemPositionStore.layer.pipe(Layer.provide(layerDatabase)), + ), ), - ), - ); + ); - yield* Effect.gen(function* () { - const eventSink = yield* EventSink.EventSinkV2; - const now = yield* DateTime.now; - const first = makeThread(ThreadId.make("thread:foundation-publish-order:first"), now); - const second = makeThread(ThreadId.make("thread:foundation-publish-order:second"), now); - const published = yield* eventSink - .stream({ afterSequence: yield* eventSink.latestSequence() }) - .pipe(Stream.take(2), Stream.runCollect, Effect.forkScoped({ startImmediately: true })); - - const firstWrite = yield* eventSink - .writeWithEffects({ - events: [ - threadCreatedEvent({ id: "event:foundation-publish-order:first", thread: first, now }), - ], - effects: [ - { - id: "effect:foundation-publish-order:first", - commandId: CommandId.make("command:foundation-publish-order:first"), - threadId: first.id, - request: { type: "terminal.cleanup" }, - }, - ], - }) - .pipe(Effect.forkScoped); - yield* Deferred.await(firstCommitted); - const secondWrite = yield* eventSink - .write({ - events: [ - threadCreatedEvent({ - id: "event:foundation-publish-order:second", - thread: second, - now, - }), - ], - }) - .pipe( - Effect.provideService(Scheduler.MaxOpsBeforeYield, Number.POSITIVE_INFINITY), - Effect.forkScoped, - ); - yield* Effect.yieldNow; - yield* Deferred.succeed(releaseFirst, undefined); - yield* Fiber.join(firstWrite); - yield* Fiber.join(secondWrite); + yield* Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const now = yield* DateTime.now; + const first = makeThread(ThreadId.make("thread:foundation-publish-order:first"), now); + const second = makeThread(ThreadId.make("thread:foundation-publish-order:second"), now); + const published = yield* eventSink + .stream({ afterSequence: yield* eventSink.latestSequence() }) + .pipe(Stream.take(2), Stream.runCollect, Effect.forkScoped({ startImmediately: true })); - const sequences = Array.from(yield* Fiber.join(published), (stored) => stored.sequence); - assert.deepEqual( - sequences, - [...sequences].sort((left, right) => left - right), - ); - }).pipe(Effect.provide(layerEventSink)); - }).pipe(Effect.provide(layerDatabase)), + const firstWrite = yield* eventSink + .writeWithEffects({ + events: [ + threadCreatedEvent({ + id: "event:foundation-publish-order:first", + thread: first, + now, + }), + ], + effects: [ + { + id: "effect:foundation-publish-order:first", + commandId: CommandId.make("command:foundation-publish-order:first"), + threadId: first.id, + request: { type: "terminal.cleanup" }, + }, + ], + }) + .pipe( + (write) => (mode === "direct" ? write : eventSink.withProviderBatch(write)), + Effect.forkScoped, + ); + yield* Deferred.await(firstCommitted); + const secondWrite = yield* eventSink + .write({ + events: [ + threadCreatedEvent({ + id: "event:foundation-publish-order:second", + thread: second, + now, + }), + ], + }) + .pipe( + Effect.provideService(Scheduler.MaxOpsBeforeYield, Number.POSITIVE_INFINITY), + Effect.forkScoped, + ); + yield* Effect.yieldNow; + const interrupted = + mode === "cancel-provider-batch" + ? yield* Fiber.interrupt(firstWrite).pipe(Effect.forkScoped({ startImmediately: true })) + : undefined; + yield* Deferred.succeed(releaseFirst, undefined); + if (interrupted !== undefined) yield* Fiber.join(interrupted); + else yield* Fiber.join(firstWrite); + yield* Fiber.join(secondWrite); + + const sequences = Array.from(yield* Fiber.join(published), (stored) => stored.sequence); + assert.deepEqual( + sequences, + [...sequences].sort((left, right) => left - right), + ); + }).pipe(Effect.provide(layerEventSink)); + }).pipe(Effect.provide(layerDatabase)), ); it.effect.each(["events", "receipts"] as const)( diff --git a/apps/server/src/orchestration-v2/ProviderCommitBatch.test.ts b/apps/server/src/orchestration-v2/ProviderCommitBatch.test.ts new file mode 100644 index 0000000000000..6655d1554533f --- /dev/null +++ b/apps/server/src/orchestration-v2/ProviderCommitBatch.test.ts @@ -0,0 +1,472 @@ +import { assert, it } from "@effect/vitest"; +import { MessageId, ProviderDriverKind, ProviderTurnId, ThreadId } from "@t3tools/contracts"; +import * as KeyedLock from "@t3tools/shared/KeyedLock"; +import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import * as Cause from "effect/Cause"; +import * as DateTime from "effect/DateTime"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Fiber from "effect/Fiber"; +import * as Queue from "effect/Queue"; +import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; +import * as ProviderCommitBatch from "./ProviderCommitBatch.ts"; + +const driver = ProviderDriverKind.make("codex"); +function event(index: number, text = `delta:${index}`): ProviderAdapter.ProviderAdapterV2Event { + const threadId = ThreadId.make("single-thread"); + const now = DateTime.makeUnsafe("2026-11-03T00:00:00Z"); + return { + type: "message.updated", + driver, + message: { + id: MessageId.make("single-message"), + threadId, + runId: null, + nodeId: null, + createdBy: "agent", + creationSource: "provider", + role: "assistant", + text, + attachments: [], + streaming: true, + createdAt: now, + updatedAt: now, + }, + }; +} +const control: ProviderAdapter.ProviderAdapterV2Event = { + type: "background_work.updated", + driver, + providerTurnId: ProviderTurnId.make("turn"), + pending: false, +}; + +const recordBatches = Effect.fn("test.recordProviderBatches")(function* ( + beforeCommit: Effect.Effect = Effect.void, +) { + const output = yield* Queue.unbounded>(); + let current: ProviderAdapter.ProviderAdapterV2Event[] = []; + const coordinator = yield* ProviderCommitBatch.make( + (work) => + Effect.gen(function* () { + yield* beforeCommit; + current = []; + yield* work; + if (current.length > 0) yield* Queue.offer(output, current); + }), + true, + ); + const process = (raw: ProviderAdapter.ProviderAdapterV2Event) => + raw.type === "background_work.updated" + ? Queue.offer(output, [raw]).pipe(Effect.asVoid) + : Effect.sync(() => { + current.push(raw); + }); + return { ...coordinator, process, output }; +}); + +it.effect("publishes preceding snapshots before a control", () => + Effect.gen(function* () { + const recorder = yield* recordBatches(); + const input = yield* Queue.unbounded(); + const consumer = yield* recorder + .consume(Stream.fromQueue(input), recorder.process, Effect.succeed(true)) + .pipe(Effect.forkScoped); + yield* Queue.offer(input, event(1)); + assert.deepEqual(yield* Queue.take(recorder.output), [event(1)]); + yield* Queue.offer(input, event(2)); + yield* Queue.offer(input, control); + assert.deepEqual(yield* Queue.take(recorder.output), [event(2)]); + assert.deepEqual(yield* Queue.take(recorder.output), [control]); + yield* Fiber.join(consumer); + }).pipe(Effect.scoped), +); + +it.effect("publishes isolated snapshots without advancing the clock", () => + Effect.gen(function* () { + const recorder = yield* recordBatches(); + const input = yield* Queue.unbounded(); + const pulled = yield* Queue.unbounded(); + yield* recorder + .consume( + Stream.fromQueue(input).pipe(Stream.tap((raw) => Queue.offer(pulled, raw))), + recorder.process, + Effect.succeed(false), + ) + .pipe(Effect.forkScoped); + for (const raw of [event(1), event(2)]) { + yield* Queue.offer(input, raw); + yield* Queue.take(pulled); + yield* TestClock.adjust(0); + const published = yield* Queue.poll(recorder.output); + assert.equal(published._tag, "Some"); + if (published._tag === "Some") assert.deepEqual(published.value, [raw]); + } + }).pipe(Effect.scoped), +); + +it.effect("bounds transactions by count and bytes, including the final partial group", () => + Effect.gen(function* () { + const workloads = [ + { events: Array.from({ length: 129 }, (_, index) => event(index)) }, + { events: [event(0), event(1, "x".repeat(1024 * 1024)), event(2)] }, + { + events: [event(0, "x".repeat(600_000)), event(1, "y".repeat(600_000)), event(2)], + }, + ]; + for (const { events } of workloads) { + const recorder = yield* recordBatches(); + const pulled = yield* Deferred.make(); + let arrivals = 0; + const consumer = yield* recorder + .consume( + Stream.fromArray(events).pipe( + Stream.tap(() => + ++arrivals === events.length ? Deferred.succeed(pulled, undefined) : Effect.void, + ), + ), + recorder.process, + Effect.succeed(false), + ) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(pulled); + yield* TestClock.adjust(0); + yield* recorder.barrier(Effect.void); + yield* Fiber.join(consumer); + const batches = yield* Queue.takeAll(recorder.output); + assert.isTrue(batches.every((batch) => batch.length <= 64)); + if (events.length === 129) assert.isTrue(batches.some((batch) => batch.length > 1)); + assert.isTrue( + batches.every( + (batch) => + batch.length === 1 || + batch.reduce((bytes, raw) => bytes + Buffer.byteLength(JSON.stringify(raw)), 0) <= + 1024 * 1024, + ), + ); + assert.deepEqual(batches.flat(), events); + } + }).pipe(Effect.scoped), +); + +it.effect("keeps updates immediate and ordered when batching is disabled", () => + Effect.gen(function* () { + const seen: ProviderAdapter.ProviderAdapterV2Event[] = []; + const coordinator = yield* ProviderCommitBatch.make(() => Effect.die("must not batch"), false); + yield* coordinator.consume( + Stream.make(event(1), control, event(2)), + (raw) => + Effect.sync(() => { + seen.push(raw); + }), + Effect.succeed(false), + ); + assert.deepEqual(seen, [event(1), control, event(2)]); + }).pipe(Effect.scoped), +); + +it.effect.each([ + { streams: 1, updates: 10 }, + { streams: 10, updates: 1 }, + { streams: 10, updates: 10 }, +])( + "shares bounded transactions across $streams streams with $updates updates each", + ({ streams, updates }) => + Effect.gen(function* () { + const coordinator = yield* recordBatches(); + const inputs = yield* Effect.forEach(Array.from({ length: streams }), () => + Queue.unbounded(), + ); + const pulled = yield* Deferred.make(); + let arrivals = 0; + const consumers = yield* Effect.forEach(inputs, (input) => + coordinator + .consume( + Stream.fromQueue(input).pipe( + Stream.tap(() => { + arrivals++; + return arrivals === streams * updates + ? Deferred.succeed(pulled, undefined) + : Effect.void; + }), + ), + coordinator.process, + Effect.succeed(true), + ) + .pipe(Effect.forkScoped({ startImmediately: true })), + ); + for (let n = 0; n < updates; n++) { + for (let stream = 0; stream < streams; stream++) + yield* Queue.offer(inputs[stream]!, event(stream * updates + n)); + } + yield* Deferred.await(pulled); + yield* TestClock.adjust(0); + + yield* coordinator.barrier(Effect.void); + const batches: Array> = []; + let count = 0; + while (count < streams * updates) { + const batch = yield* Queue.take(coordinator.output); + batches.push(batch); + count += batch.length; + } + assert.deepEqual( + batches.map((batch) => batch.length), + streams * updates > 64 ? [64, 36] : [10], + ); + assert.equal( + new Set( + batches + .flat() + .flatMap((raw) => (raw.type === "message.updated" ? [raw.message.text] : [])), + ).size, + streams * updates, + ); + for (const input of inputs) yield* Queue.offer(input, control); + yield* Effect.forEach(consumers, Fiber.join); + }).pipe(Effect.scoped), +); + +it.effect("does not hold the shared worker while one consumer checks background work", () => + Effect.gen(function* () { + const checking = yield* Deferred.make(); + const release = yield* Deferred.make(); + const coordinator = yield* ProviderCommitBatch.make((work) => work, true); + const consumer = yield* coordinator + .consume( + Stream.make(control), + () => Effect.void, + Deferred.succeed(checking, undefined).pipe( + Effect.andThen(Deferred.await(release)), + Effect.as(true), + ), + ) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(checking); + assert.equal( + yield* coordinator.barrier(Effect.succeed("another run can commit")), + "another run can commit", + ); + yield* Deferred.succeed(release, undefined); + yield* Fiber.join(consumer); + }).pipe(Effect.scoped), +); + +it.effect.each(["job", "commit"] as const)( + "isolates a %s failure at its transaction boundary", + (mode) => + Effect.gen(function* () { + const coordinator = yield* ProviderCommitBatch.make( + (work) => + mode === "commit" + ? work.pipe( + Effect.andThen( + Effect.fail(new ProviderCommitBatch.CommitBatchError({ cause: "COMMIT failed" })), + ), + ) + : work, + true, + ); + const inputs = yield* Effect.forEach([0, 1], () => + Queue.unbounded(), + ); + const consumers = yield* Effect.forEach(inputs, (input, index) => + coordinator + .consume( + Stream.fromQueue(input), + () => (mode === "job" && index === 1 ? Effect.fail("invalid update") : Effect.void), + Effect.succeed(true), + ) + .pipe(Effect.exit, Effect.forkScoped({ startImmediately: true })), + ); + for (const input of inputs) yield* Queue.offer(input, event(0)); + yield* TestClock.adjust(0); + yield* coordinator.barrier(Effect.void); + assert.isTrue(Exit.isFailure(yield* Fiber.join(consumers[1]!))); + if (mode === "commit") assert.isTrue(Exit.isFailure(yield* Fiber.join(consumers[0]!))); + else { + assert.isUndefined(consumers[0]!.pollUnsafe()); + yield* Queue.offer(inputs[0]!, control); + assert.isTrue(Exit.isSuccess(yield* Fiber.join(consumers[0]!))); + } + assert.equal(yield* coordinator.barrier(Effect.succeed("recovered")), "recovered"); + assert.deepEqual( + yield* coordinator.barrier(Effect.fail("original error")).pipe(Effect.exit), + Exit.fail("original error"), + ); + }).pipe(Effect.scoped), +); + +it.effect("keeps a transaction failure when rolling back one failed snapshot", () => + Effect.gen(function* () { + const transactionError = new ProviderCommitBatch.CommitBatchError({ cause: "ROLLBACK failed" }); + const coordinator = yield* ProviderCommitBatch.make( + (work) => work.pipe(Effect.mapError(() => transactionError)), + true, + ); + const exit = yield* coordinator + .consume( + Stream.concat(Stream.make(event(1)), Stream.never), + () => Effect.fail("invalid snapshot"), + Effect.succeed(false), + ) + .pipe(Effect.exit); + assert.isTrue(Exit.isFailure(exit)); + if (Exit.isFailure(exit)) assert.strictEqual(Cause.squash(exit.cause), transactionError); + }).pipe(Effect.scoped), +); + +it.effect( + "allows a command holding the thread lock to commit while a provider control waits for it", + () => + Effect.gen(function* () { + const coordinator = yield* ProviderCommitBatch.make((work) => work, true); + const locks = yield* KeyedLock.make(); + const threadId = ThreadId.make("locked-thread"); + const held = yield* Deferred.make(); + const waiting = yield* Deferred.make(); + const committed = yield* Deferred.make(); + const command = yield* locks + .withLock( + threadId, + Deferred.succeed(held, undefined).pipe( + Effect.andThen(Deferred.await(waiting)), + Effect.andThen(coordinator.barrier(Deferred.succeed(committed, undefined))), + ), + ) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(held); + const consumer = yield* coordinator + .consume( + Stream.make(control), + () => + Deferred.succeed(waiting, undefined).pipe( + Effect.andThen(locks.withLock(threadId, Effect.void)), + ), + Effect.succeed(true), + ) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(waiting); + yield* TestClock.adjust(0); + assert.isTrue(yield* Deferred.isDone(committed)); + yield* Fiber.join(command); + yield* Fiber.join(consumer); + }).pipe(Effect.scoped), +); + +it.effect.each([false, true])( + "batches work accumulated behind a busy writer with cancellation=%s", + (cancel) => + Effect.gen(function* () { + const started = yield* Deferred.make(); + const release = yield* Deferred.make(); + let first = true; + const recorder = yield* recordBatches( + Effect.gen(function* () { + if (!first) return; + first = false; + yield* Deferred.succeed(started, undefined); + yield* Deferred.await(release); + }), + ); + const leading = yield* recorder + .consume(Stream.make(event(-1)), recorder.process, Effect.succeed(false)) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(started); + const pulled = yield* Deferred.make(); + let arrivals = 0; + const consumers = yield* Effect.forEach(Array.from({ length: 10 }), (_, index) => + recorder + .consume( + Stream.make(event(index)).pipe( + Stream.tap(() => + ++arrivals === 10 ? Deferred.succeed(pulled, undefined) : Effect.void, + ), + ), + recorder.process, + Effect.succeed(false), + ) + .pipe(Effect.forkScoped({ startImmediately: true })), + ); + yield* Deferred.await(pulled); + yield* TestClock.adjust(0); + if (cancel) yield* Fiber.interrupt(consumers[0]!); + assert.equal(yield* Queue.size(recorder.output), 0); + yield* Deferred.succeed(release, undefined); + yield* Fiber.join(leading); + yield* Effect.forEach(consumers.slice(cancel ? 1 : 0), Fiber.join); + assert.deepEqual(yield* Queue.takeAll(recorder.output), [ + [event(-1)], + Array.from({ length: cancel ? 9 : 10 }, (_, index) => event(index + (cancel ? 1 : 0))), + ]); + }).pipe(Effect.scoped), +); + +it.effect.each(["failure", "stop"] as const)( + "flushes the prefix and respects a source %s barrier", + (mode) => + Effect.gen(function* () { + const seen: ProviderAdapter.ProviderAdapterV2Event[] = []; + const coordinator = yield* ProviderCommitBatch.make((work) => work, true); + const source = + mode === "failure" + ? Stream.concat(Stream.make(event(1), event(2)), Stream.fail("provider failed")) + : Stream.make(event(1), control, event(2)); + const exit = yield* coordinator + .consume( + source, + (raw) => + Effect.sync(() => { + seen.push(raw); + }), + Effect.succeed(mode === "stop"), + ) + .pipe(Effect.exit); + assert.deepEqual(seen, mode === "failure" ? [event(1), event(2)] : [event(1), control]); + assert.equal(Exit.isFailure(exit), mode === "failure"); + assert.equal( + yield* coordinator.barrier(Effect.succeed("still available")), + "still available", + ); + }).pipe(Effect.scoped), +); + +it.effect("does not force a separate commit for every consumer that ends", () => + Effect.gen(function* () { + const pulled = yield* Deferred.make(); + let arrivals = 0; + const coordinator = yield* recordBatches(); + for (let index = 0; index < 10; index++) { + yield* coordinator + .consume( + Stream.make(event(index)).pipe( + Stream.tap(() => + ++arrivals === 10 ? Deferred.succeed(pulled, undefined) : Effect.void, + ), + ), + coordinator.process, + Effect.succeed(false), + ) + .pipe(Effect.forkScoped({ startImmediately: true })); + } + yield* Deferred.await(pulled); + yield* TestClock.adjust(0); + yield* coordinator.barrier(Effect.void); + assert.deepEqual( + (yield* Queue.takeAll(coordinator.output)).map((batch) => batch.length), + [10], + ); + }).pipe(Effect.scoped), +); + +it.effect("settles calls made after the coordinator's scope closes", () => + Effect.gen(function* () { + const coordinator = yield* ProviderCommitBatch.make((work) => work, true).pipe(Effect.scoped); + const exit = yield* coordinator + .barrier(Effect.die("must not execute after shutdown")) + .pipe(Effect.exit); + assert.isTrue(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)); + }), +); diff --git a/apps/server/src/orchestration-v2/ProviderCommitBatch.ts b/apps/server/src/orchestration-v2/ProviderCommitBatch.ts new file mode 100644 index 0000000000000..60cee2b632f66 --- /dev/null +++ b/apps/server/src/orchestration-v2/ProviderCommitBatch.ts @@ -0,0 +1,303 @@ +import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import * as Cause from "effect/Cause"; +import * as Clock from "effect/Clock"; +import * as Config from "effect/Config"; +import * as Effect from "effect/Effect"; +import * as Context from "effect/Context"; +import * as Deferred from "effect/Deferred"; +import * as Exit from "effect/Exit"; +import * as Queue from "effect/Queue"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; + +const MAX_EVENTS = 64; +const MAX_BYTES = 1024 * 1024; +const encodeQueue = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); + +export const enabled = Config.Boolean("T3CODE_PROVIDER_COMMIT_BATCHING").pipe( + Config.withDefault(true), + Effect.orDie, +); + +type Event = ProviderAdapter.ProviderAdapterV2Event; +const isSnapshot = (event: Event) => + event.type === "node.updated" || + event.type === "message.updated" || + event.type === "turn_item.updated" || + event.type === "plan.updated"; + +export class CommitBatchError extends Schema.TaggedError()("CommitBatchError", { + cause: Schema.Defect(), +}) {} +export const isCommitBatchError = Schema.is(CommitBatchError); + +interface Job { + readonly owner: { active: boolean }; + readonly queuedAt: number; + readonly snapshot: boolean; + readonly bytes: number; + readonly execute: Effect.Effect; + readonly settle: ( + exit: Exit.Exit, + preserveFailure: boolean, + ) => Effect.Effect; + readonly cancel: Effect.Effect; +} +interface Batch { + readonly events: ReadonlyArray; + readonly bytes: number; + readonly reason: "ready" | "limit" | "control"; +} + +function collect(queue: Queue.Queue) { + return Stream.fromEffectRepeat(Queue.takeBetween(queue, 1, MAX_EVENTS)).pipe( + Stream.flatMap((ready) => { + const batches: Array = []; + let events: Array = []; + let bytes = 0; + const flush = (reason: Batch["reason"]) => { + if (events.length > 0) batches.push({ events, bytes, reason }); + events = []; + bytes = 0; + }; + for (const job of ready) { + if (!job.snapshot) { + flush("control"); + batches.push({ events: [job], bytes: 0, reason: "control" }); + } else { + if (events.length > 0 && bytes + job.bytes > MAX_BYTES) flush("limit"); + events.push(job); + bytes += job.bytes; + if (events.length >= MAX_EVENTS || bytes >= MAX_BYTES) flush("limit"); + } + } + flush("ready"); + return Stream.fromArray(batches); + }), + ); +} + +const CurrentWorker = Context.Reference( + "t3/ProviderCommitBatch/CurrentWorker", + { + defaultValue: () => undefined, + }, +); + +export const make = Effect.fn("ProviderCommitBatch.make")(function* ( + commit: (work: Effect.Effect) => Effect.Effect, + enabled: boolean, + isolate: ( + work: Effect.Effect, + ) => Effect.Effect = (work) => work, +) { + const queue = yield* Queue.bounded(MAX_EVENTS); + const pending = new Set(); + let closed = false; + const shutdown = Effect.gen(function* () { + closed = true; + yield* Queue.shutdown(queue); + for (const job of pending) yield* job.cancel; + }); + yield* Effect.addFinalizer(() => shutdown); + // These helpers run once per raw event; the shared transaction owns the tracing span. + const enqueue = Effect.fnUntraced(function* ( + effect: Effect.Effect, + token: { active: boolean }, + snapshot: boolean, + bytes: number, + ) { + const caller = yield* Effect.context(); + const reply = yield* Deferred.make(); + let ownFailure: Cause.Cause | undefined; + let result: A; + const job: Job = { + owner: token, + queuedAt: yield* Clock.currentTimeMillis, + snapshot, + bytes, + execute: effect.pipe( + Effect.tapCause((cause) => + Effect.sync(() => { + ownFailure = cause; + }), + ), + Effect.mapError((cause) => new CommitBatchError({ cause })), + Effect.provideContext(caller), + Effect.tap((value) => + Effect.sync(() => { + result = value; + }), + ), + Effect.asVoid, + ), + settle: Effect.fnUntraced(function* ( + exit: Exit.Exit, + preserveFailure: boolean, + ) { + pending.delete(job); + if (Exit.isFailure(exit)) { + token.active = false; + yield* Deferred.failCause( + reply, + preserveFailure && ownFailure !== undefined ? ownFailure : exit.cause, + ); + } else yield* Deferred.succeed(reply, result); + }), + cancel: Effect.gen(function* () { + pending.delete(job); + yield* Deferred.interrupt(reply); + }), + }; + yield* Effect.uninterruptibleMask((restore) => + Effect.gen(function* () { + pending.add(job); + const accepted = yield* restore(Queue.offer(queue, job)).pipe( + Effect.onError(() => job.cancel), + ); + if (!accepted) yield* job.cancel; + }), + ); + return Deferred.await(reply); + }); + if (enabled) { + yield* collect(queue).pipe( + Stream.runForEach((batch) => + Effect.uninterruptibleMask((restore) => + Effect.gen(function* () { + const jobs = batch.events.filter((job) => job.owner.active); + for (const job of batch.events) if (!job.owner.active) yield* job.cancel; + if (jobs.length === 0) return; + yield* Effect.annotateCurrentSpan({ + "orchestration_v2.work_item_count": jobs.length, + "orchestration_v2.consumer_count": new Set(jobs.map((job) => job.owner)).size, + "orchestration_v2.raw_json_bytes": batch.bytes, + "orchestration_v2.batch_flush_reason": batch.reason, + "orchestration_v2.backlog_batching": true, + "orchestration_v2.batch_wait_ms": + (yield* Clock.currentTimeMillis) - Math.min(...jobs.map((job) => job.queuedAt)), + }); + const outcomes = new Map>(); + const work = Effect.forEach( + jobs, + (job) => + Effect.gen(function* () { + if (!job.owner.active) return yield* job.cancel; + const outcome = yield* ( + jobs.length > 1 && job.bytes > 0 ? isolate(job.execute) : job.execute + ).pipe(Effect.exit); + outcomes.set(job, outcome); + if (Exit.isFailure(outcome)) { + job.owner.active = false; + if (jobs.length === 1) return yield* Effect.failCause(outcome.cause); + } + }), + { discard: true }, + ); + const exit = yield* restore( + (jobs.every((job) => job.bytes === 0) ? work : commit(work)).pipe( + Effect.provideService(CurrentWorker, yield* Effect.fiberId), + ), + ).pipe(Effect.exit); + for (const job of jobs) { + const outcome = outcomes.get(job) ?? Exit.void; + yield* job.settle( + Exit.isSuccess(exit) ? outcome : exit, + Exit.isSuccess(exit) || + (Exit.isFailure(exit) && + Exit.isFailure(outcome) && + Cause.squash(exit.cause) === Cause.squash(outcome.cause)), + ); + } + }), + ).pipe(Effect.withSpan("orchestrationV2.ProviderCommitBatch.flush")), + ), + Effect.ensuring(shutdown), + Effect.forkScoped, + ); + } + const barrier = Effect.fnUntraced(function* (effect: Effect.Effect) { + if (closed) return yield* Effect.interrupt; + if (!enabled || pending.size === 0 || (yield* CurrentWorker) === (yield* Effect.fiberId)) + return yield* effect; + const token = { active: true }; + return yield* enqueue(Effect.exit(effect), token, false, 0).pipe( + Effect.flatten, + Effect.orDie, + Effect.flatten, + Effect.ensuring( + Effect.sync(() => { + token.active = false; + }), + ), + ); + }); + const consume = Effect.fnUntraced(function* ( + source: Stream.Stream, + process: (event: Event) => Effect.Effect, + after: Effect.Effect, + canBatch: Effect.Effect = Effect.succeed(true), + ) { + if (!enabled) + return yield* source.pipe( + Stream.mapEffect((event) => process(event).pipe(Effect.andThen(after))), + Stream.takeUntil(Boolean), + Stream.runDrain, + ); + const token = { active: true }; + const signals = source.pipe( + Stream.map((event) => ({ _tag: "Event" as const, event })), + Stream.catchCause((cause) => Stream.succeed({ _tag: "Failure" as const, cause })), + Stream.concat(Stream.succeed({ _tag: "End" as const })), + ); + let resume: Effect.Effect = Effect.void; + yield* signals.pipe( + Stream.mapEffect((signal) => + Effect.gen(function* () { + yield* resume; + const processed = yield* Deferred.make(); + const event = signal._tag === "Event" ? signal.event : undefined; + // EOF only acknowledges prior work; it can share a commit with other consumers. + const snapshot = + signal._tag === "End" || + (event !== undefined && isSnapshot(event) && (yield* canBatch)); + const bytes = + snapshot && event !== undefined ? Buffer.byteLength(yield* encodeQueue(event)) : 0; + const work: Effect.Effect = + signal._tag === "Failure" + ? Effect.failCause(signal.cause) + : event === undefined + ? Effect.succeed(true) + : process(event).pipe(Effect.as(false)); + const reply = snapshot + ? yield* enqueue(work, token, true, bytes) + : (yield* enqueue(Effect.void, token, false, 0)).pipe(Effect.andThen(work)); + if (!snapshot) resume = Deferred.await(processed); + return { reply, processed, check: !snapshot }; + }), + ), + Stream.buffer({ capacity: MAX_EVENTS }), + Stream.mapEffect(({ reply, processed, check }) => + reply.pipe( + Effect.flatMap((end) => + end ? Effect.succeed(true) : check ? after : Effect.succeed(false), + ), + Effect.tap((stop) => + Effect.sync(() => { + if (stop) token.active = false; + }), + ), + Effect.ensuring(Deferred.succeed(processed, undefined)), + ), + ), + Stream.takeUntil(Boolean), + Stream.runDrain, + Effect.ensuring( + Effect.sync(() => { + token.active = false; + }), + ), + ); + }); + return { barrier, consume }; +}); diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts index d35771ac3d0c7..b6adf6371fb60 100644 --- a/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts +++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts @@ -546,8 +546,12 @@ layer("ProviderEventIngestorV2", (it) => { event: { type: "node.updated", driver: CODEX_DRIVER, node: sent }, }); - assert.lengthOf(yield* ingestNode(node), 1); - assert.isEmpty(yield* ingestNode({ ...node })); + yield* eventSink.withProviderBatch( + Effect.gen(function* () { + assert.lengthOf(yield* ingestNode(node), 1); + assert.isEmpty(yield* ingestNode({ ...node })); + }), + ); yield* eventSink.write({ events: [ { diff --git a/apps/server/src/orchestration-v2/RunExecutionService.test.ts b/apps/server/src/orchestration-v2/RunExecutionService.test.ts index f3f1542146c66..5bfb4fe34dc6a 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.test.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.test.ts @@ -55,6 +55,17 @@ import * as RunExecutionService from "./RunExecutionService.ts"; import * as RunFinalizationService from "./RunFinalizationService.ts"; import * as TurnItemPositionStore from "./TurnItemPositionStore.ts"; +const mockEventSink = (implementation: Partial) => + Layer.mock(EventSink.EventSinkV2)({ + consumeProviderEvents: (source, process, after) => + source.pipe( + Stream.mapEffect((event) => process(event).pipe(Effect.andThen(after))), + Stream.takeUntil(Boolean), + Stream.runDrain, + ), + ...implementation, + }); + const driver = ProviderDriverKind.make("codex"); const rootAppThread = (id: ThreadId) => ({ @@ -73,7 +84,7 @@ const layerRunExecutionTest = RunExecutionService.layer.pipe( PreviewAgentActivity.layer, Layer.mock(CheckpointService.CheckpointServiceV2)({ captureBaseline: () => Effect.void }), layerTurnItemPositionsTest, - Layer.mock(EventSink.EventSinkV2)({}), + mockEventSink({}), IdAllocator.layer, Layer.mock(ProviderEventIngestor.ProviderEventIngestorV2)({ ingestNormalized: () => Effect.succeed([]), @@ -900,7 +911,7 @@ it.effect("passes the thread's MCP app context to the provider under a safe key" captureBaseline: () => Effect.void, }), layerTurnItemPositionsTest, - Layer.mock(EventSink.EventSinkV2)({}), + mockEventSink({}), IdAllocator.layer, Layer.mock(ProviderEventIngestor.ProviderEventIngestorV2)({ ingestNormalized: () => Effect.succeed([]), @@ -929,7 +940,7 @@ it.effect("fails the run when its ownership check cannot be read before calling PreviewAgentActivity.layer, Layer.mock(CheckpointService.CheckpointServiceV2)({ captureBaseline: () => Effect.void }), layerTurnItemPositionsTest, - Layer.mock(EventSink.EventSinkV2)({ + mockEventSink({ writeIfRunCurrent: (input) => Ref.update(writes, (current) => [...current, ...input.events]).pipe( Effect.as({ committed: true, storedEvents: [] }), @@ -1140,7 +1151,7 @@ it.effect("starts the provider when checkpoint baseline capture fails", () => ), }), layerTurnItemPositionsTest, - Layer.mock(EventSink.EventSinkV2)({ + mockEventSink({ writeWithEffects: (input) => Ref.update(writes, (current) => [ ...current, @@ -1254,7 +1265,7 @@ it.effect.each(["failure", "interruption", "stale-attempt", "start-guard"] as co scenario === "start-guard" ? Effect.void : Effect.die("not reached"), }), layerTurnItemPositionsTest, - Layer.mock(EventSink.EventSinkV2)({ + mockEventSink({ writeIfRunCurrent: (input) => Effect.gen(function* () { assert.equal(input.threadId, threadId); @@ -1434,7 +1445,7 @@ it.effect("ingests new member threads of an owned child after the root turn term PreviewAgentActivity.layer, Layer.mock(CheckpointService.CheckpointServiceV2)({ captureBaseline: () => Effect.void }), layerTurnItemPositionsTest, - Layer.mock(EventSink.EventSinkV2)({ + mockEventSink({ write: () => Effect.succeed([]), writeWithEffects: (input) => Effect.gen(function* () { @@ -1694,7 +1705,7 @@ it.effect("ends a nested native subagent and its thread when the root run is int PreviewAgentActivity.layer, Layer.mock(CheckpointService.CheckpointServiceV2)({ captureBaseline: () => Effect.void }), layerTurnItemPositionsTest, - Layer.mock(EventSink.EventSinkV2)({ + mockEventSink({ write: () => Effect.succeed([]), writeWithEffects: (input) => Effect.as( @@ -2107,7 +2118,7 @@ it.effect( captureBaseline: () => Effect.void, }), layerTurnItemPositionsTest, - Layer.mock(EventSink.EventSinkV2)({ + mockEventSink({ write: () => Effect.succeed([]), writeWithEffects: (input) => Effect.gen(function* () { @@ -3193,7 +3204,7 @@ function captureRootRunTermination(input: { }), Layer.mock(CheckpointService.CheckpointServiceV2)({ captureBaseline: () => Effect.void }), layerTurnItemPositionsTest, - Layer.mock(EventSink.EventSinkV2)({ + mockEventSink({ write: (payload) => Effect.gen(function* () { for (const event of payload.events) { @@ -3715,7 +3726,7 @@ function runBackgroundItemScenario( Layer.succeed(PreviewAgentActivity.PreviewAgentActivity, previewActivity), Layer.mock(CheckpointService.CheckpointServiceV2)({ captureBaseline: () => Effect.void }), layerTurnItemPositionsTest, - Layer.mock(EventSink.EventSinkV2)({ + mockEventSink({ write: () => Effect.succeed([]), writeWithEffects: (input) => Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index 6a52fac447926..304eeaba43421 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -35,7 +35,6 @@ import * as Layer from "effect/Layer"; import * as Ref from "effect/Ref"; import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; -import * as Stream from "effect/Stream"; import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts"; import * as McpAppModelContext from "../mcpApps/McpAppModelContext.ts"; @@ -1322,350 +1321,350 @@ export const layer: Layer.Layer< // Ends once the root turn and the children it drives settle. Background commands such // as a dev server keep this consumer alive afterwards and must not pin preview focus. const endPreviewActivity = yield* previewAgentActivity.begin(input.run.threadId); - const providerEventFiber = yield* eventSubscription.events.pipe( - Stream.mapEffect((event) => - Effect.gen(function* () { - const previous = yield* Ref.get(eventRouting); - const [accepted, routing] = routeProviderEvent(event, routeIdentity, previous); - yield* Ref.set(eventRouting, routing); - if ( - event.type === "subagent.updated" && - event.subagent.childThreadId !== null && - previous.ownedThreadIds.has(event.subagent.childThreadId) && - !routing.ownedThreadIds.has(event.subagent.childThreadId) - ) { - const moved = event.subagent; - const detached = yield* Ref.modify(openRunOwnedSubagents, (current) => { - const subagentIds = new Set([moved.id]); - for (const subagent of current.subagents.values()) { - if (subagent.threadId === moved.childThreadId) subagentIds.add(subagent.id); - } - const childTurnItems = new Map( - [...current.childTurnItems].filter( - ([, item]) => item.threadId !== moved.childThreadId, - ), - ); - const turnItems = new Map(current.turnItems); - turnItems.delete(moved.id); - const detachedItems = new Set( - [...current.childTurnItems.values(), ...current.turnItems.values()] - .filter( - (item) => item.threadId === moved.childThreadId || item.nodeId === moved.id, - ) - .map((item) => item.id), - ); - return [ - { itemIds: detachedItems, subagentIds }, - { - subagents: new Map( - [...current.subagents].filter(([id]) => !subagentIds.has(id)), - ), - turnItems, - childTurnItems, - nodes: new Map( - [...current.nodes].filter( - ([id, node]) => id !== moved.id && node.threadId !== moved.childThreadId, - ), - ), - linkedChildThreadIds: new Set( - [...current.linkedChildThreadIds].filter( - (id) => id !== moved.childThreadId, - ), - ), - }, - ]; - }); - yield* Ref.update( - activeChildSubagents, - (current) => - new Map( - [...current].filter( - ([id, threadId]) => - !detached.subagentIds.has(id) && threadId !== moved.childThreadId, - ), - ), - ); - yield* Ref.update( - activeChildProviderTurns, - (current) => - new Set([...current].filter((id) => routing.ownedProviderTurns.has(id))), - ); - for (const id of pendingBackgroundProviderTurns) { - if (!routing.ownedProviderTurns.has(id)) { - pendingBackgroundProviderTurns.delete(id); - } - } - yield* Ref.update( - activeBackgroundTurnItems, - (current) => new Set([...current].filter((id) => !detached.itemIds.has(id))), - ); - } - return { event, accepted }; - }), - ), - Stream.tap(({ event, accepted }) => - Effect.gen(function* () { - if (!accepted) return; - if ( - event.type === "provider_turn.updated" && - event.providerTurn.runAttemptId === input.attempt.id && - event.providerTurn.providerThreadId === input.providerThread.id - ) { - yield* Ref.set(latestRootProviderTurn, event.providerTurn); + // Per-event routing and lifecycle bookkeeping share the run's tracing boundary. + const routeEvent = Effect.fnUntraced(function* ( + event: ProviderAdapter.ProviderAdapterV2Event, + ) { + const previous = yield* Ref.get(eventRouting); + const [accepted, routing] = routeProviderEvent(event, routeIdentity, previous); + yield* Ref.set(eventRouting, routing); + if ( + event.type === "subagent.updated" && + event.subagent.childThreadId !== null && + previous.ownedThreadIds.has(event.subagent.childThreadId) && + !routing.ownedThreadIds.has(event.subagent.childThreadId) + ) { + const moved = event.subagent; + const detached = yield* Ref.modify(openRunOwnedSubagents, (current) => { + const subagentIds = new Set([moved.id]); + for (const subagent of current.subagents.values()) { + if (subagent.threadId === moved.childThreadId) subagentIds.add(subagent.id); } - let storedEventCount = 0; - const deliveredEvent = filterAssistantEvent( - event, - DateTime.toEpochMillis(yield* DateTime.now), + const childTurnItems = new Map( + [...current.childTurnItems].filter( + ([, item]) => item.threadId !== moved.childThreadId, + ), ); - if (deliveredEvent) { - const rootTerminalAlreadySeen = yield* Ref.get(rootTerminalSeen); - const isRootProviderThreadUpdate = - event.type === "provider_thread.updated" && - event.providerThread.id === input.providerThread.id; - const nativeChildTurn = - event.type === "provider_turn.updated" && - event.providerTurn.providerThreadId !== input.providerThread.id; - if (event.type === "provider_turn.updated" && !nativeChildTurn) { - firstRootProviderTurnId ??= event.providerTurn.id; - } - const storedEvents = yield* providerEventIngestor.ingestNormalized({ - analyticsContext: nativeChildTurn - ? { - ...analyticsContext, - origin: NATIVE_SUBAGENT_TURN_ORIGIN, - segment: "native_child", - } - : { - ...analyticsContext, - segment: - event.type === "provider_turn.updated" && - event.providerTurn.id !== firstRootProviderTurnId - ? "continuation" - : input.attempt.reason, - }, - providerSessionId: input.providerSessionId, - providerInstanceId: input.run.providerInstanceId, - threadId: input.run.threadId, - runId: input.run.id, - nodeId: input.rootNode.id, - event: deliveredEvent, - ...(isRootProviderThreadUpdate - ? rootTerminalAlreadySeen - ? { - writeIfProviderThreadOwner: { - providerThreadId: input.providerThread.id, - runId: input.run.id, - activeAttemptId: input.attempt.id, - expectedLastRunOrdinal: input.run.ordinal, - }, - } - : { - writeIfRunCurrent: { - runId: input.run.id, - activeAttemptId: input.attempt.id, - expectedStatus: "running" as const, - }, - } - : {}), - }); - storedEventCount = storedEvents.length; - if ( - isRootProviderThreadUpdate && - rootTerminalAlreadySeen && - storedEventCount === 0 - ) { - yield* Ref.set(providerThreadOwnerLost, true); - } - } else if ( - event.type === "turn_item.updated" && - (event.turnItem.type === "assistant_message" || - event.turnItem.type === "reasoning") && - event.turnItem.streaming && - !reservedHeldTurnItemIds.has(event.turnItem.id) - ) { - yield* turnItemPositions.allocate({ - threadId: event.turnItem.threadId, - turnItemId: event.turnItem.id, - runId: event.turnItem.runId, - }); - reservedHeldTurnItemIds.add(event.turnItem.id); - } - if (event.type === "provider_thread.updated") { - if (event.providerThread.id === input.providerThread.id && storedEventCount > 0) { - yield* Ref.set(latestProviderThread, event.providerThread); - } - } - if ( - event.type === "turn_item.updated" && - event.turnItem.providerTurnId === (yield* Ref.get(eventRouting)).rootProviderTurnId - ) { - yield* Ref.update(latestTurnItemOrdinal, (current) => - Math.max(current, event.turnItem.ordinal), - ); - } - if (event.type === "turn.terminal") { - yield* Ref.set(terminalEvent, event); - yield* Ref.set(rootTerminalSeen, true); - yield* finalizeRootRun(event); - } - if (event.type === "background_work.updated") { - if (event.pending) { - pendingBackgroundProviderTurns.add(event.providerTurnId); - } else { - pendingBackgroundProviderTurns.delete(event.providerTurnId); - } + const turnItems = new Map(current.turnItems); + turnItems.delete(moved.id); + const detachedItems = new Set( + [...current.childTurnItems.values(), ...current.turnItems.values()] + .filter( + (item) => item.threadId === moved.childThreadId || item.nodeId === moved.id, + ) + .map((item) => item.id), + ); + return [ + { itemIds: detachedItems, subagentIds }, + { + subagents: new Map([...current.subagents].filter(([id]) => !subagentIds.has(id))), + turnItems, + childTurnItems, + nodes: new Map( + [...current.nodes].filter( + ([id, node]) => id !== moved.id && node.threadId !== moved.childThreadId, + ), + ), + linkedChildThreadIds: new Set( + [...current.linkedChildThreadIds].filter((id) => id !== moved.childThreadId), + ), + }, + ]; + }); + yield* Ref.update( + activeChildSubagents, + (current) => + new Map( + [...current].filter( + ([id, threadId]) => + !detached.subagentIds.has(id) && threadId !== moved.childThreadId, + ), + ), + ); + yield* Ref.update( + activeChildProviderTurns, + (current) => new Set([...current].filter((id) => routing.ownedProviderTurns.has(id))), + ); + for (const id of pendingBackgroundProviderTurns) { + if (!routing.ownedProviderTurns.has(id)) { + pendingBackgroundProviderTurns.delete(id); } - yield* trackChildLifecycle(event, deliveredEvent !== null); - }), - ), - // Also after events this run does not accept, such as a child handed to another run. - Stream.tap(() => + } + yield* Ref.update( + activeBackgroundTurnItems, + (current) => new Set([...current].filter((id) => !detached.itemIds.has(id))), + ); + } + return { event, accepted }; + }); + const ingestEvent = Effect.fnUntraced(function* ({ + event, + accepted, + }: { + event: ProviderAdapter.ProviderAdapterV2Event; + accepted: boolean; + }) { + if (!accepted) return; + if ( + event.type === "provider_turn.updated" && + event.providerTurn.runAttemptId === input.attempt.id && + event.providerTurn.providerThreadId === input.providerThread.id + ) { + yield* Ref.set(latestRootProviderTurn, event.providerTurn); + } + let storedEventCount = 0; + const deliveredEvent = filterAssistantEvent( + event, + DateTime.toEpochMillis(yield* DateTime.now), + ); + if (deliveredEvent) { + const rootTerminalAlreadySeen = yield* Ref.get(rootTerminalSeen); + const isRootProviderThreadUpdate = + event.type === "provider_thread.updated" && + event.providerThread.id === input.providerThread.id; + const nativeChildTurn = + event.type === "provider_turn.updated" && + event.providerTurn.providerThreadId !== input.providerThread.id; + if (event.type === "provider_turn.updated" && !nativeChildTurn) { + firstRootProviderTurnId ??= event.providerTurn.id; + } + const storedEvents = yield* providerEventIngestor.ingestNormalized({ + analyticsContext: nativeChildTurn + ? { + ...analyticsContext, + origin: NATIVE_SUBAGENT_TURN_ORIGIN, + segment: "native_child", + } + : { + ...analyticsContext, + segment: + event.type === "provider_turn.updated" && + event.providerTurn.id !== firstRootProviderTurnId + ? "continuation" + : input.attempt.reason, + }, + providerSessionId: input.providerSessionId, + providerInstanceId: input.run.providerInstanceId, + threadId: input.run.threadId, + runId: input.run.id, + nodeId: input.rootNode.id, + event: deliveredEvent, + ...(isRootProviderThreadUpdate + ? rootTerminalAlreadySeen + ? { + writeIfProviderThreadOwner: { + providerThreadId: input.providerThread.id, + runId: input.run.id, + activeAttemptId: input.attempt.id, + expectedLastRunOrdinal: input.run.ordinal, + }, + } + : { + writeIfRunCurrent: { + runId: input.run.id, + activeAttemptId: input.attempt.id, + expectedStatus: "running" as const, + }, + } + : {}), + }); + storedEventCount = storedEvents.length; + if (isRootProviderThreadUpdate && rootTerminalAlreadySeen && storedEventCount === 0) { + yield* Ref.set(providerThreadOwnerLost, true); + } + } else if ( + event.type === "turn_item.updated" && + (event.turnItem.type === "assistant_message" || event.turnItem.type === "reasoning") && + event.turnItem.streaming && + !reservedHeldTurnItemIds.has(event.turnItem.id) + ) { + yield* turnItemPositions.allocate({ + threadId: event.turnItem.threadId, + turnItemId: event.turnItem.id, + runId: event.turnItem.runId, + }); + reservedHeldTurnItemIds.add(event.turnItem.id); + } + if (event.type === "provider_thread.updated") { + if (event.providerThread.id === input.providerThread.id && storedEventCount > 0) { + yield* Ref.set(latestProviderThread, event.providerThread); + } + } + if ( + event.type === "turn_item.updated" && + event.turnItem.providerTurnId === (yield* Ref.get(eventRouting)).rootProviderTurnId + ) { + yield* Ref.update(latestTurnItemOrdinal, (current) => + Math.max(current, event.turnItem.ordinal), + ); + } + if (event.type === "turn.terminal") { + yield* Ref.set(terminalEvent, event); + yield* Ref.set(rootTerminalSeen, true); + yield* finalizeRootRun(event); + } + if (event.type === "background_work.updated") { + if (event.pending) { + pendingBackgroundProviderTurns.add(event.providerTurnId); + } else { + pendingBackgroundProviderTurns.delete(event.providerTurnId); + } + } + yield* trackChildLifecycle(event, deliveredEvent !== null); + }); + const providerEventFiber = yield* eventSink + .consumeProviderEvents( + eventSubscription.events, + (event) => + Effect.gen(function* () { + yield* ingestEvent(yield* routeEvent(event)); + }), Effect.gen(function* () { if (yield* agentTurnsSettled) yield* endPreviewActivity; + return yield* shouldStopProviderEventIngestion; }), - ), - Stream.takeUntilEffect(() => shouldStopProviderEventIngestion), - Stream.runDrain, - Effect.mapError((cause) => new RunExecutionIngestError({ runId: input.run.id, cause })), - Effect.flatMap(() => - Effect.gen(function* () { - const terminal = yield* Ref.get(terminalEvent); - if (terminal === null) { - // A session release interrupts or fails the stream; a clean - // end without a terminal means the run would never settle. - return yield* new RunExecutionIngestError({ - runId: input.run.id, - cause: new ProviderAdapter.ProviderAdapterEventStreamError({ - driver: input.providerThread.driver, - providerSessionId: input.providerSessionId, - cause: "Provider event stream ended without a root terminal.", - }), - }); - } - yield* finalizeRootRun(terminal); - }), - ), - // Server shutdown interrupts the subscription and leaves the run to - // restart recovery; every other failure fails the run. - Effect.catchCauseIf( - (cause) => !Cause.hasInterruptsOnly(cause), - (cause) => + Ref.get(rootTerminalSeen).pipe(Effect.map((seen) => !seen)), + ) + .pipe( + Effect.mapError((cause) => new RunExecutionIngestError({ runId: input.run.id, cause })), + Effect.flatMap(() => Effect.gen(function* () { - const completedAt = yield* DateTime.now; - yield* Effect.logWarning("orchestration V2 provider event ingestion failed", { - runId: input.run.id, - cause, - }); - if (yield* Ref.get(rootRunFinalized)) return; - const providerThread = yield* Ref.get(latestProviderThread); - const routing = yield* Ref.get(eventRouting); - const rootProviderTurn = yield* Ref.get(latestRootProviderTurn); - // Stop background work too; the failed consumer cannot persist terminal events. - const abandonedProviderTurn = - routing.rootProviderTurnId !== null && !routing.rootTurnEnded - ? yield* input.session - .interruptTurn({ - providerThread, - providerTurnId: routing.rootProviderTurnId, - requestRuntimeRestart: true, - }) - .pipe( - Effect.as(true), - Effect.catchCauseIf( - (interruptCause) => !Cause.hasInterruptsOnly(interruptCause), - (interruptCause) => - Effect.logWarning( - "orchestration V2 failed to interrupt turn after ingestion failure", - { runId: input.run.id, cause: interruptCause }, - ).pipe(Effect.as(false)), - ), - // A failed interrupt leaves the stored turn running so the next start - // retries it. The snapshot is cached before it is published, so it may - // not be stored: replay a terminal one as-is. - Effect.map((interrupted) => - !interrupted || rootProviderTurn === null - ? null - : isTerminalProviderTurnStatus(rootProviderTurn.status) - ? rootProviderTurn - : { - ...rootProviderTurn, - status: "interrupted" as const, - completedAt, - }, - ), - ) - : null; - const latestItemOrdinal = yield* Ref.get(latestTurnItemOrdinal); - const openSubagents = yield* Ref.get(openRunOwnedSubagents); - const squashed = Cause.squash(cause); - let nextRetryWarningAt = completedAt; - yield* writeFinalRunEvents({ - run: input.run, - rootNode: input.rootNode, - checkpointScope: input.checkpointScope, - providerThread, - attempt: input.attempt, - writeIfRunCurrent: { - activeAttemptId: input.attempt.id, - expectedStatus: "running", - }, - openRunOwnedSubagents: openSubagents, - ...(abandonedProviderTurn === null ? {} : { abandonedProviderTurn }), - completedAt, - terminal: makeFailedTerminalEvent( - makeProviderFailure({ - cause: squashed, - message: - knownProviderFailureMessage(squashed) ?? - userFacingDatabaseErrorMessage(squashed), - class: "unknown", - }), - latestItemOrdinal + 1, - ), - failureItemPersisted: false, - refreshAfterTurn, - }).pipe( - // Storage failures can be defects; retry both failure channels. - Effect.catchCause((writeCause) => - Effect.gen(function* () { - if (Cause.hasInterruptsOnly(writeCause)) { - return yield* Effect.failCause(writeCause); - } - const now = yield* DateTime.now; - if (DateTime.isGreaterThanOrEqualTo(now, nextRetryWarningAt)) { - yield* Effect.logWarning( - "orchestration V2 run failure finalization retry", - { - runId: input.run.id, - attemptId: input.attempt.id, - cause: writeCause, - }, - ); - // Persistent storage failures must not flood the same disk. - nextRetryWarningAt = DateTime.add(now, { minutes: 10 }); - } - return yield* Effect.fail(writeCause); + const terminal = yield* Ref.get(terminalEvent); + if (terminal === null) { + // A session release interrupts or fails the stream; a clean + // end without a terminal means the run would never settle. + return yield* new RunExecutionIngestError({ + runId: input.run.id, + cause: new ProviderAdapter.ProviderAdapterEventStreamError({ + driver: input.providerThread.driver, + providerSessionId: input.providerSessionId, + cause: "Provider event stream ended without a root terminal.", }), - ), - Effect.retry({ - schedule: Schedule.exponential("1 second").pipe( - Schedule.modifyDelay(({ duration }) => - Effect.succeed(Duration.min(duration, Duration.seconds(30))), - ), - ), - }), - // Startup may cancel the consumer and fail its own terminal - // write. Only service shutdown or the atomic gate ends recovery. - Effect.forkIn(scope), - Effect.flatMap(Fiber.join), - ); + }); + } + yield* finalizeRootRun(terminal); }), - ), - Effect.ensuring(endPreviewActivity), - Effect.ensuring(eventSubscription.close), - Effect.forkDetach, - ); + ), + // Server shutdown interrupts the subscription and leaves the run to + // restart recovery; every other failure fails the run. + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + (cause) => + Effect.gen(function* () { + const completedAt = yield* DateTime.now; + yield* Effect.logWarning("orchestration V2 provider event ingestion failed", { + runId: input.run.id, + cause, + }); + if (yield* Ref.get(rootRunFinalized)) return; + const providerThread = yield* Ref.get(latestProviderThread); + const routing = yield* Ref.get(eventRouting); + const rootProviderTurn = yield* Ref.get(latestRootProviderTurn); + // Stop background work too; the failed consumer cannot persist terminal events. + const abandonedProviderTurn = + routing.rootProviderTurnId !== null && !routing.rootTurnEnded + ? yield* input.session + .interruptTurn({ + providerThread, + providerTurnId: routing.rootProviderTurnId, + requestRuntimeRestart: true, + }) + .pipe( + Effect.as(true), + Effect.catchCauseIf( + (interruptCause) => !Cause.hasInterruptsOnly(interruptCause), + (interruptCause) => + Effect.logWarning( + "orchestration V2 failed to interrupt turn after ingestion failure", + { runId: input.run.id, cause: interruptCause }, + ).pipe(Effect.as(false)), + ), + // A failed interrupt leaves the stored turn running so the next start + // retries it. The snapshot is cached before it is published, so it may + // not be stored: replay a terminal one as-is. + Effect.map((interrupted) => + !interrupted || rootProviderTurn === null + ? null + : isTerminalProviderTurnStatus(rootProviderTurn.status) + ? rootProviderTurn + : { + ...rootProviderTurn, + status: "interrupted" as const, + completedAt, + }, + ), + ) + : null; + const latestItemOrdinal = yield* Ref.get(latestTurnItemOrdinal); + const openSubagents = yield* Ref.get(openRunOwnedSubagents); + const squashed = Cause.squash(cause); + let nextRetryWarningAt = completedAt; + yield* writeFinalRunEvents({ + run: input.run, + rootNode: input.rootNode, + checkpointScope: input.checkpointScope, + providerThread, + attempt: input.attempt, + writeIfRunCurrent: { + activeAttemptId: input.attempt.id, + expectedStatus: "running", + }, + openRunOwnedSubagents: openSubagents, + ...(abandonedProviderTurn === null ? {} : { abandonedProviderTurn }), + completedAt, + terminal: makeFailedTerminalEvent( + makeProviderFailure({ + cause: squashed, + message: + knownProviderFailureMessage(squashed) ?? + userFacingDatabaseErrorMessage(squashed), + class: "unknown", + }), + latestItemOrdinal + 1, + ), + failureItemPersisted: false, + refreshAfterTurn, + }).pipe( + // Storage failures can be defects; retry both failure channels. + Effect.catchCause((writeCause) => + Effect.gen(function* () { + if (Cause.hasInterruptsOnly(writeCause)) { + return yield* Effect.failCause(writeCause); + } + const now = yield* DateTime.now; + if (DateTime.isGreaterThanOrEqualTo(now, nextRetryWarningAt)) { + yield* Effect.logWarning( + "orchestration V2 run failure finalization retry", + { + runId: input.run.id, + attemptId: input.attempt.id, + cause: writeCause, + }, + ); + // Persistent storage failures must not flood the same disk. + nextRetryWarningAt = DateTime.add(now, { minutes: 10 }); + } + return yield* Effect.fail(writeCause); + }), + ), + Effect.retry({ + schedule: Schedule.exponential("1 second").pipe( + Schedule.modifyDelay(({ duration }) => + Effect.succeed(Duration.min(duration, Duration.seconds(30))), + ), + ), + }), + // Startup may cancel the consumer and fail its own terminal + // write. Only service shutdown or the atomic gate ends recovery. + Effect.forkIn(scope), + Effect.flatMap(Fiber.join), + ); + }), + ), + Effect.ensuring(endPreviewActivity), + Effect.ensuring(eventSubscription.close), + Effect.forkDetach, + ); // A provider turn is a sign that the session is still alive. Keep // its already-issued MCP credential valid even when the agent goes diff --git a/apps/server/src/orchestration-v2/testkit/CodexReplayFixtures.integration.test.ts b/apps/server/src/orchestration-v2/testkit/CodexReplayFixtures.integration.test.ts index c0593351f20d7..1274c9eaee2e9 100644 --- a/apps/server/src/orchestration-v2/testkit/CodexReplayFixtures.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/CodexReplayFixtures.integration.test.ts @@ -1,9 +1,14 @@ -import { describe } from "@effect/vitest"; +import { assert, describe, it } from "@effect/vitest"; +import * as Tracer from "effect/Tracer"; import * as Effect from "effect/Effect"; import { materializeReplayTranscriptWorkspace } from "@t3tools/provider-testing/replayTranscript"; import { CodexOrchestratorReplayHarness } from "../Adapters/CodexAdapterV2.testkit.ts"; -import { itRunsReplayFixtures, runReplayFixture } from "./ProviderReplayFixtures.ts"; +import { + findReplayFixture, + itRunsReplayFixtures, + runReplayFixture, +} from "./ProviderReplayFixtures.ts"; describe("Codex replay fixtures", () => { itRunsReplayFixtures("codex", (input) => @@ -15,3 +20,39 @@ describe("Codex replay fixtures", () => { }), ); }); + +it.effect( + "persists recorded Codex snapshots through provider transactions in the real run consumer", + () => + Effect.gen(function* () { + const fixture = findReplayFixture("multi_turn")!; + const driver = fixture.providers.find((provider) => provider.driver === "codex")!; + const writes: number[] = []; + const tracer = Tracer.make({ + span(options) { + const span = new Tracer.NativeSpan(options); + const end = span.end.bind(span); + span.end = (time, exit) => { + end(time, exit); + if (span.name === "orchestrationV2.EventSink.providerBatch") { + writes.push(Number(span.attributes.get("orchestration_v2.batch_writes"))); + } + }; + return span; + }, + }); + yield* runReplayFixture({ + fixtureName: fixture.name, + buildInput: fixture.buildInput, + driver, + harness: CodexOrchestratorReplayHarness, + materializeWorkspace: (transcript, workspace) => + Effect.succeed(materializeReplayTranscriptWorkspace(transcript, workspace)), + }).pipe(Effect.withTracer(tracer), Effect.withTracerEnabled(true)); + assert.equal( + writes.reduce((total, count) => total + count, 0), + 6, + ); + assert.isTrue(writes.every((count) => count <= 3)); + }), +); diff --git a/packages/provider-opencode/src/server/adapter.test.ts b/packages/provider-opencode/src/server/adapter.test.ts index 70462070cff51..769d3a81e63d0 100644 --- a/packages/provider-opencode/src/server/adapter.test.ts +++ b/packages/provider-opencode/src/server/adapter.test.ts @@ -712,6 +712,10 @@ describe("OpenCodeAdapterV2", () => { }), ); const events = yield* Fiber.join(received); + assert.deepEqual( + events.map((event) => event.type), + ["turn_item.updated", "runtime_request.updated"], + ); const item = events.find((event) => event.type === "turn_item.updated"); const request = events.find((event) => event.type === "runtime_request.updated"); assert.equal(item?.type, "turn_item.updated"); diff --git a/packages/provider-opencode/src/server/adapter.ts b/packages/provider-opencode/src/server/adapter.ts index 4c72c5f6ef09f..94bdb56eb29ab 100644 --- a/packages/provider-opencode/src/server/adapter.ts +++ b/packages/provider-opencode/src/server/adapter.ts @@ -1899,15 +1899,16 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function }, }); yield* emitProviderEvent({ - type: "runtime_request.updated", + type: "turn_item.updated", driver: OPENCODE_PROVIDER, - threadId: turn.threadId, - runtimeRequest, + turnItem: runtimeRequestTurnItem(pending, "waiting", null, now), }); + // A response can commit as soon as the actionable request is published. yield* emitProviderEvent({ - type: "turn_item.updated", + type: "runtime_request.updated", driver: OPENCODE_PROVIDER, - turnItem: runtimeRequestTurnItem(pending, "waiting", null, now), + threadId: turn.threadId, + runtimeRequest, }); yield* updateProviderSession("waiting", null); }); diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index ddca16ed8fed3..3cbd4d893b6f1 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -1888,13 +1888,14 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr native, }); yield* emit({ type: "node.updated", driver, node }); + yield* emit({ type: "turn_item.updated", driver, turnItem: item }); + // A response can commit as soon as the actionable request is published. yield* emit({ type: "runtime_request.updated", driver, threadId: turn.input.threadId, runtimeRequest: request, }); - yield* emit({ type: "turn_item.updated", driver, turnItem: item }); yield* setSessionStatus("waiting", null); }); From 620a37b988a5a0a270ea7f70c0458ba658e9d072 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Thu, 5 Nov 2026 22:57:21 -0600 Subject: [PATCH 082/181] fix(server): prepare restart continuations faster on shutdown (#31807) --- .../ProjectionRecovery.test.ts | 22 ++++++ .../src/orchestration-v2/ProjectionStore.ts | 39 ++++++++- .../ProviderRuntimeRecoveryService.ts | 79 +++++++++++-------- .../ProviderSessionManager.test.ts | 29 ++++++- .../ProviderSessionManager.ts | 20 +++-- .../RestartContinuation.test.ts | 64 +++++++++++++++ apps/server/src/serverRuntimeStartup.ts | 1 + 7 files changed, 216 insertions(+), 38 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts b/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts index 0868b3b694878..e6351eb5f0097 100644 --- a/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts @@ -836,6 +836,28 @@ it.effect("includes shared sessions and provider-owned background rosters in rec new Set(yield* projections.getRecoveryThreadIds("runtime")), new Set([first, second, roster, prepared]), ); + assert.deepEqual( + new Set(yield* projections.getRecoveryThreadIds("restart-continuations")), + new Set([first, second, prepared]), + ); + assert.deepEqual( + yield* projections.getRecoveryThreadIds("restart-continuations", { include: [] }), + [], + ); + assert.deepEqual( + yield* projections.getRecoveryThreadIds("restart-continuations", { + exclude: ["project:recovery"], + }), + [], + ); + assert.deepEqual( + new Set( + yield* projections.getRecoveryThreadIds("restart-continuations", { + include: ["project:recovery"], + }), + ), + new Set([first, second, prepared]), + ); const preparedState = yield* projections.getRuntimeRecoveryProjection(prepared); assert.deepEqual( preparedState.providerSessions.map((session) => session.id), diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 22f5743c10352..b901ea6b0a49d 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -168,6 +168,7 @@ export type ProjectionStoreV2Error = typeof ProjectionStoreV2Error.Type; export type ProjectionRecoveryKind = | "queued-runs" | "runtime" + | "restart-continuations" | "subagent-results" | "delegated-completions"; @@ -353,6 +354,7 @@ export interface ProjectionRecordFilter { readonly subagentIds?: ReadonlyArray; readonly subagentRunIds?: ReadonlyArray; readonly nodeIds?: ReadonlyArray; + readonly turnItemRequestIds?: ReadonlyArray; readonly turnItemTypes?: ReadonlyArray; readonly turnItemStatuses?: ReadonlyArray; readonly omitSettledLeafNodes?: boolean; @@ -678,6 +680,10 @@ export interface ProjectionStoreV2Shape { ) => Effect.Effect, ProjectionStoreV2Error>; readonly getRecoveryThreadIds: ( kind: ProjectionRecoveryKind, + projects?: { + readonly include?: ReadonlyArray; + readonly exclude?: ReadonlyArray; + }, ) => Effect.Effect, ProjectionStoreV2Error>; readonly getUnreadableThreadIds: () => Effect.Effect< ReadonlyArray, @@ -3129,6 +3135,7 @@ export const layer: Layer.Layer = (fields !== undefined && !fields.includes("turnItems")) || (window === undefined && matchesNothing( + filter?.turnItemRequestIds, filter?.turnItemTypes, filter?.turnItemStatuses, filter?.turnItemRunIds, @@ -3140,6 +3147,7 @@ export const layer: Layer.Layer = SELECT payload_json FROM orchestration_v2_projection_turn_items WHERE thread_id = ${threadId} + ${filter?.turnItemRequestIds === undefined ? sql`` : sql`AND json_extract(payload_json, '$.requestId') IN (SELECT value FROM json_each(${encodeIdList(filter.turnItemRequestIds)}))`} ${filter?.turnItemTypes === undefined ? sql`` : sql`AND type IN (SELECT value FROM json_each(${encodeIdList(filter.turnItemTypes)}))`} ${filter?.turnItemStatuses === undefined ? sql`` : sql`AND status IN (SELECT value FROM json_each(${encodeIdList(filter.turnItemStatuses)}))`} ${filter?.turnItemRunId === undefined ? sql`` : sql`AND run_id = ${filter.turnItemRunId}`} @@ -4120,7 +4128,13 @@ export const layer: Layer.Layer = ); const getRecoveryThreadIds = Effect.fn("ProjectionStore.getRecoveryThreadIds")( - function* (kind: ProjectionRecoveryKind) { + function* ( + kind: ProjectionRecoveryKind, + projects?: { + readonly include?: ReadonlyArray; + readonly exclude?: ReadonlyArray; + }, + ) { const candidates = (() => { switch (kind) { case "queued-runs": @@ -4171,6 +4185,27 @@ export const layer: Layer.Layer = AND type = 'subagent_result' ))) `; + case "restart-continuations": + return sql` + SELECT bindings.thread_id + FROM orchestration_v2_projection_provider_sessions AS sessions + JOIN orchestration_v2_projection_provider_session_bindings AS bindings + ON bindings.provider_session_id = sessions.provider_session_id + WHERE sessions.status NOT IN ('stopped', 'error') + UNION + SELECT thread_id FROM orchestration_v2_projection_provider_sessions AS sessions + WHERE status NOT IN ('stopped', 'error') AND thread_id IS NOT NULL + AND NOT EXISTS ( + SELECT 1 FROM orchestration_v2_projection_provider_session_bindings AS bindings + WHERE bindings.provider_session_id = sessions.provider_session_id + ) + UNION + SELECT thread_id FROM orchestration_v2_projection_runs + WHERE status = 'starting' + AND CASE WHEN json_valid(payload_json) + THEN json_extract(payload_json, '$.restartContinuationOfRunId') IS NOT NULL + ELSE 0 END + `; case "runtime": return sql` WITH pending_provider_threads AS MATERIALIZED ( @@ -4257,6 +4292,8 @@ export const layer: Layer.Layer = SELECT thread_id FROM orchestration_v2_projection_threads WHERE deleted_at IS NULL AND thread_id IN (${candidates}) + ${projects?.include === undefined ? sql`` : sql`AND project_id IN (SELECT value FROM json_each(${encodeIdList(projects.include)}))`} + ${projects?.exclude === undefined ? sql`` : sql`AND project_id NOT IN (SELECT value FROM json_each(${encodeIdList(projects.exclude)}))`} ${kind === "queued-runs" ? sql`AND archived_at IS NULL` : sql``} ORDER BY updated_at ASC, thread_id ASC `; diff --git a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts index a20b5cbfc29c3..c374db2abfb97 100644 --- a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts +++ b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts @@ -875,39 +875,56 @@ export const make = Effect.gen(function* () { const prepareForShutdown = Effect.gen(function* () { const enabled = yield* settings.getSettings.pipe(Effect.orElseSucceed(() => null)); if (!enabled) return; - const threadIds = yield* projections.getRecoveryThreadIds("runtime"); - for (const threadId of threadIds) { - yield* Effect.gen(function* () { - const projection = yield* projections.getRuntimeRecoveryProjection(threadId); - if ( - !resolveProjectSettings(enabled, projection.thread.projectId).settings - .continueThreadsAfterServerUpdate - ) - return; - const run = restartContinuationRun(projection, yield* DateTime.now); - if (!run) return; - const commandId = CommandId.make(`command:restart-prepare:${run.id}`); - yield* eventSink.writeWithEffects({ - commandId, - events: [], - effects: [ - { - id: `effect:restart-continuation:${run.id}`, - commandId, - threadId, - request: { type: "provider-runtime.continue", sourceRunId: run.id }, - }, - ], - }); - }).pipe( - Effect.catchCauseIf( - (cause) => !Cause.hasInterruptsOnly(cause), - (cause) => - Effect.logWarning("Failed to prepare a restart continuation", { threadId, cause }), + const enabledProjects = Object.entries(enabled.projectSettingsOverrides) + .filter(([, overrides]) => overrides.continueThreadsAfterServerUpdate === true) + .map(([id]) => id); + if (!enabled.continueThreadsAfterServerUpdate && enabledProjects.length === 0) return; + const disabledProjects = Object.entries(enabled.projectSettingsOverrides) + .filter(([, overrides]) => overrides.continueThreadsAfterServerUpdate === false) + .map(([id]) => id); + const threadIds = yield* projections.getRecoveryThreadIds( + "restart-continuations", + enabled.continueThreadsAfterServerUpdate + ? { exclude: disabledProjects } + : { include: enabledProjects }, + ); + yield* Effect.forEach( + threadIds, + (threadId) => + Effect.gen(function* () { + const projection = yield* projections.getRuntimeRecoveryProjection(threadId); + if ( + !resolveProjectSettings(enabled, projection.thread.projectId).settings + .continueThreadsAfterServerUpdate + ) + return; + const run = restartContinuationRun(projection, yield* DateTime.now); + if (!run) return; + const commandId = CommandId.make(`command:restart-prepare:${run.id}`); + yield* eventSink.writeWithEffects({ + commandId, + events: [], + effects: [ + { + id: `effect:restart-continuation:${run.id}`, + commandId, + threadId, + request: { type: "provider-runtime.continue", sourceRunId: run.id }, + }, + ], + }); + }).pipe( + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + (cause) => + Effect.logWarning("Failed to prepare a restart continuation", { threadId, cause }), + ), ), - ); - } + // Leave room in the four-reader pool for other shutdown reads. + { concurrency: 2, discard: true }, + ); }).pipe( + Effect.withSpan("ProviderRuntimeRecoveryService.prepareForShutdown"), Effect.mapError((cause) => new ProviderRuntimeRecoveryError({ operation: "reconcile", cause })), ); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index da6774ae23540..896de803a38f6 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -3113,6 +3113,27 @@ it.effect("ProviderSessionManagerV2 marks pending runtime requests non-live on r now, }); yield* eventSink.write({ events: pendingRequest.events }); + const historical = yield* makePendingRuntimeRequestEvents({ + idAllocator, + threadId, + providerSessionId, + providerThread, + now, + }); + yield* eventSink.write({ + events: historical.events.map((event) => + event.type === "runtime-request.updated" + ? { ...event, payload: { ...event.payload, status: "resolved", resolvedAt: now } } + : event, + ), + }); + assert.deepEqual( + (yield* projectionStore.getThreadRecords(threadId, ["nodes", "turnItems"], { + nodeIds: [pendingRequest.nodeId], + turnItemRequestIds: [pendingRequest.requestId], + })).turnItems.map((item) => item.id), + [pendingRequest.events.find((event) => event.type === "turn-item.updated")!.payload.id], + ); yield* manager.open({ threadId, providerSessionId, @@ -3126,7 +3147,13 @@ it.effect("ProviderSessionManagerV2 marks pending runtime requests non-live on r }); const projection = yield* projectionStore.getThreadProjection(threadId); - const request = projection.runtimeRequests.at(-1); + const request = projection.runtimeRequests.find( + (request) => request.id === pendingRequest.requestId, + ); + assert.equal( + projection.runtimeRequests.find((request) => request.id === historical.requestId)?.status, + "resolved", + ); const requestNode = projection.nodes.find((node) => node.id === request?.nodeId); const requestTurnItem = projection.turnItems.find( (item) => item.type === "approval_request" && item.requestId === request?.id, diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 3b01de25bc197..39f383666bae1 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -655,8 +655,8 @@ export const layerWithOptions = ( for (const threadId of input.entry.attachedThreadIds) { const projection = yield* projectionStore.getThreadRecords( threadId, - ["runtimeRequests", "nodes", "turnItems"], - { turnItemTypes: ["approval_request", "user_input_request"] }, + ["runtimeRequests"], + { runtimeRequestStatuses: ["pending"] }, ); const releasedRequests = projection.runtimeRequests.filter( (request) => @@ -668,6 +668,16 @@ export const layerWithOptions = ( !(input.reason === "server_shutdown" && request.kind === "user_input"), ); + if (releasedRequests.length === 0) continue; + const records = yield* projectionStore.getThreadRecords( + threadId, + ["nodes", "turnItems"], + { + nodeIds: releasedRequests.map((request) => request.nodeId), + turnItemRequestIds: releasedRequests.map((request) => request.id), + turnItemTypes: ["approval_request", "user_input_request"], + }, + ); for (const request of releasedRequests) { events.push({ id: yield* idAllocator.allocate.event({ @@ -690,7 +700,7 @@ export const layerWithOptions = ( }, }); - const requestNode = projection.nodes.find((node) => node.id === request.nodeId); + const requestNode = records.nodes.find((node) => node.id === request.nodeId); if (requestNode !== undefined) { events.push({ id: yield* idAllocator.allocate.event({ @@ -711,7 +721,7 @@ export const layerWithOptions = ( }); } - const turnItem = projection.turnItems.find( + const turnItem = records.turnItems.find( (item) => (item.type === "approval_request" || item.type === "user_input_request") && item.requestId === request.id, @@ -2120,7 +2130,7 @@ export const layerWithOptions = ( ), { concurrency: "unbounded", discard: true }, ); - }); + }).pipe(Effect.withSpan("ProviderSessionManager.shutdown")); yield* Effect.addFinalizer(() => shutdown.pipe( Effect.ensuring(closeScopeWithin(sessionScopes, { reason: "server_shutdown" })), diff --git a/apps/server/src/orchestration-v2/RestartContinuation.test.ts b/apps/server/src/orchestration-v2/RestartContinuation.test.ts index a318130500b3b..d2f21a772ac99 100644 --- a/apps/server/src/orchestration-v2/RestartContinuation.test.ts +++ b/apps/server/src/orchestration-v2/RestartContinuation.test.ts @@ -17,6 +17,8 @@ import { } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import * as Deferred from "effect/Deferred"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as ServerSettings from "../serverSettings.ts"; import { restartContinuationRun, continueRestartedRun } from "./RestartContinuation.ts"; @@ -1262,3 +1264,65 @@ it.effect.each(["completed", "failed", "interrupted"] as const)( ); }), ); + +it.effect("prepares independent continuations together and waits for durable writes", () => + Effect.gen(function* () { + const bothReading = yield* Deferred.make(); + const bothWriting = yield* Deferred.make(); + const committed = yield* Deferred.make(); + let reads = 0; + let writes = 0; + const recovery = yield* ProviderRuntimeRecovery.make.pipe( + Effect.provide( + Layer.mergeAll( + ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }), + Layer.mock(ProjectionStore.ProjectionStoreV2)({ + getRecoveryThreadIds: () => Effect.succeed([threadId, ThreadId.make("thread:second")]), + getRuntimeRecoveryProjection: () => + Effect.gen(function* () { + if (++reads === 2) yield* Deferred.succeed(bothReading, undefined); + yield* Deferred.await(bothReading); + return makeProjection(); + }), + }), + Layer.mock(EventSink.EventSinkV2)({ + writeWithEffects: () => + Effect.gen(function* () { + if (++writes === 2) yield* Deferred.succeed(bothWriting, undefined); + yield* Deferred.await(committed); + return []; + }), + }), + IdAllocator.layer, + Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({}), + Layer.mock(EffectOutbox.EffectOutboxV2)({}), + ), + ), + ); + const fiber = yield* recovery.prepareForShutdown.pipe(Effect.forkChild); + yield* Deferred.await(bothWriting); + assert.equal(writes, 2); + assert.isUndefined(fiber.pollUnsafe()); + yield* Deferred.succeed(committed, undefined); + yield* Fiber.join(fiber); + }), +); + +it.effect("skips restart discovery when no project enables continuation", () => + Effect.gen(function* () { + const recovery = yield* ProviderRuntimeRecovery.make.pipe( + Effect.provide( + Layer.mergeAll( + ServerSettings.layerTest({ continueThreadsAfterServerUpdate: false }), + Layer.mock(ProjectionStore.ProjectionStoreV2)({}), + Layer.mock(EventSink.EventSinkV2)({}), + IdAllocator.layer, + Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({}), + Layer.mock(EffectOutbox.EffectOutboxV2)({}), + ), + ), + ); + yield* recovery.prepareForShutdown; + yield* recovery.prepareForShutdown; + }), +); diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.ts index e37f3078548ce..26f91f59affc9 100644 --- a/apps/server/src/serverRuntimeStartup.ts +++ b/apps/server/src/serverRuntimeStartup.ts @@ -478,6 +478,7 @@ const make = Effect.fn("serverRuntimeStartup.make")(function* (options?: Startup const reconciliation = yield* providerRuntimeRecovery.reconcile("shutdown"); yield* Effect.logInfo("V2 orchestration shutdown reconciliation completed", reconciliation); }).pipe( + Effect.withSpan("server.shutdown"), Effect.catchCause((cause) => Effect.logWarning("V2 orchestration shutdown reconciliation failed", { cause: Cause.pretty(cause), From 0aae72244e4238bf1e6e800a35def7adab3cc778 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Thu, 5 Nov 2026 23:04:32 -0600 Subject: [PATCH 083/181] fix(web): keep change totals aligned beside the label (#31814) --- apps/web/src/components/GitActionsControl.tsx | 60 ++++++++++--------- 1 file changed, 33 insertions(+), 27 deletions(-) diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx index d9662910ff683..4d46bb075f236 100644 --- a/apps/web/src/components/GitActionsControl.tsx +++ b/apps/web/src/components/GitActionsControl.tsx @@ -1639,35 +1639,41 @@ export default function GitActionsControl({ onClick={onOpenChanges} > - Changes - {changesBaseLabel ? ( - - + + Changes + {changesBaseLabel ? ( + + + } + > + {changesBaseLabel} + + + {changesBaseLabel} + + + ) : null} + + - {changesBaseLabel} - - - {changesBaseLabel} - - - ) : null} - - - +{formatDiffCount(changesTotals.insertions)} - - - -{formatDiffCount(changesTotals.deletions)} + +{formatDiffCount(changesTotals.insertions)} + + + -{formatDiffCount(changesTotals.deletions)} + From e9233b01bbbc1a3c0cc87085773336c9c0bdfa2e Mon Sep 17 00:00:00 2001 From: Dharmesh Date: Fri, 6 Nov 2026 10:52:24 +0530 Subject: [PATCH 084/181] fix(web): rank usage provider summaries by the selected metric (#15632) Co-authored-by: Julius Marminge Co-authored-by: Yash Singh --- apps/web/src/components/usage/UsagePage.tsx | 14 +++++++--- .../components/usage/usageProviders.test.ts | 28 +++++++++++++++++++ .../src/components/usage/usageProviders.ts | 17 +++++++++++ 3 files changed, 55 insertions(+), 4 deletions(-) create mode 100644 apps/web/src/components/usage/usageProviders.test.ts diff --git a/apps/web/src/components/usage/UsagePage.tsx b/apps/web/src/components/usage/UsagePage.tsx index b4ec17a8940cf..2e7a4bd014395 100644 --- a/apps/web/src/components/usage/UsagePage.tsx +++ b/apps/web/src/components/usage/UsagePage.tsx @@ -100,7 +100,12 @@ import { resolveUsageShortcut, type UsageMetric, } from "./usageShortcuts"; -import { PROVIDER_ORDER, PROVIDER_PRESENTATION, providersWithUsage } from "./usageProviders"; +import { + PROVIDER_ORDER, + PROVIDER_PRESENTATION, + providersWithUsage, + rankProvidersByMetric, +} from "./usageProviders"; import { readUsagePagePreferences, saveUsagePagePreferences, @@ -670,17 +675,18 @@ function UsageOverview({ (peak, model) => Math.max(peak, metric === "tokens" ? model.totalTokens : model.costUsd), 0, ); + const rankedProviders = rankProvidersByMetric(activeProviders, merged.providers, metric); const cursorInsertAt = - Math.max(activeProviders.indexOf("codex"), activeProviders.indexOf("claude")) + 1; + Math.max(rankedProviders.indexOf("codex"), rankedProviders.indexOf("claude")) + 1; const summaryRows: ReadonlyArray< | { readonly kind: "usage"; readonly provider: UsageProviderKind } | { readonly kind: "enable"; readonly environment: EnvironmentUsageStatus } > = [ - ...activeProviders + ...rankedProviders .slice(0, cursorInsertAt) .map((provider) => ({ kind: "usage" as const, provider })), ...cursorAccessEnvironments.map((environment) => ({ kind: "enable" as const, environment })), - ...activeProviders + ...rankedProviders .slice(cursorInsertAt) .map((provider) => ({ kind: "usage" as const, provider })), ]; diff --git a/apps/web/src/components/usage/usageProviders.test.ts b/apps/web/src/components/usage/usageProviders.test.ts new file mode 100644 index 0000000000000..48e4545e8050f --- /dev/null +++ b/apps/web/src/components/usage/usageProviders.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { rankProvidersByMetric } from "./usageProviders"; + +describe("rankProvidersByMetric", () => { + it("ranks by the selected metric, highest first", () => { + const totals = [ + { provider: "codex" as const, totalTokens: 100, costUsd: 20 }, + { provider: "claude" as const, totalTokens: 200, costUsd: 10 }, + ]; + const providers = ["codex", "claude"] as const; + + expect(rankProvidersByMetric(providers, totals, "tokens")).toEqual(["claude", "codex"]); + expect(rankProvidersByMetric(providers, totals, "cost")).toEqual(["codex", "claude"]); + }); + + it("keeps ties in input order without reordering the shared provider list", () => { + const totals = [ + { provider: "codex" as const, totalTokens: 10, costUsd: 1 }, + { provider: "claude" as const, totalTokens: 10, costUsd: 1 }, + { provider: "grok" as const, totalTokens: 20, costUsd: 2 }, + ]; + const providers = ["claude", "codex", "grok"] as const; + + expect(rankProvidersByMetric(providers, totals, "tokens")).toEqual(["grok", "claude", "codex"]); + expect(providers).toEqual(["claude", "codex", "grok"]); + }); +}); diff --git a/apps/web/src/components/usage/usageProviders.ts b/apps/web/src/components/usage/usageProviders.ts index 408327f3cc203..ba86171e87a4c 100644 --- a/apps/web/src/components/usage/usageProviders.ts +++ b/apps/web/src/components/usage/usageProviders.ts @@ -2,6 +2,8 @@ import type { UsageProviderKind } from "@t3tools/contracts"; import { ProviderDriverKind } from "@t3tools/contracts"; +import type { UsageMetric } from "./usageShortcuts"; + type UsageProviderPresentation = { readonly label: string; readonly color: string; @@ -63,3 +65,18 @@ export function providersWithUsage( ); return PROVIDER_ORDER.filter((provider) => active.has(provider)); } + +export function rankProvidersByMetric( + providers: readonly UsageProviderKind[], + totals: readonly { + readonly provider: UsageProviderKind; + readonly costUsd: number; + readonly totalTokens: number; + }[], + metric: UsageMetric, +): readonly UsageProviderKind[] { + const field = metric === "cost" ? "costUsd" : "totalTokens"; + const value = (provider: UsageProviderKind) => + totals.find((entry) => entry.provider === provider)?.[field] ?? 0; + return providers.toSorted((left, right) => value(right) - value(left)); +} From 6f54322e4a57e38c01fabf4e5da0d51fe3a24270 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Thu, 5 Nov 2026 23:30:19 -0600 Subject: [PATCH 085/181] fix(server): wait for automatic follow-ups before settling threads (#31815) Keep deferred settlement requests through automatic follow-up turns and retry from persisted run events, including replayed rejected commands. Preserve failed follow-ups and new user input, and guard settlement against newer runs. Validated with 173 focused tests through check:changed, all CI checks on e1a41f6, and resolved agentic reviews. Model: GPT 6.1 Sol. Harness: Codex in T3 Code. --- .../src/orchestration-v2/Orchestrator.ts | 13 ++ .../ThreadManagementService.test.ts | 132 ++++++++++++++++-- .../ThreadManagementService.ts | 75 +++++++++- .../src/orchestration-v2/runtimeLayer.test.ts | 18 +++ packages/contracts/src/orchestrationV2.ts | 1 + 5 files changed, 219 insertions(+), 20 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index e199decf35260..bcec0a13cf20a 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -3454,6 +3454,19 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } if (command.type === "thread.settle") { const projection = yield* loadProjectionForCommand(command, ["runs", "runtimeRequests"]); + if ( + command.expectedLatestRunId !== undefined && + projection.runs.reduce( + (latest, run) => (latest === undefined || run.ordinal > latest.ordinal ? run : latest), + undefined, + )?.id !== command.expectedLatestRunId + ) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: "The thread received another run before settlement.", + }); + } const queuedMessages = yield* projectionStore .getMessagesById( command.threadId, diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts index 9285f72d46f56..742616f27bd3e 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts @@ -559,28 +559,108 @@ it.effect.each(["live", "no-session", "unsupported-runtime"] as const)( ); it.effect.each([ - { status: "completed" as const, settles: true }, - { status: "failed" as const, settles: false }, - { status: "interrupted" as const, settles: false }, -])("settleAfterRun settles only when the run $status", ({ status, settles }) => + { status: "completed" as const, followUp: "none", settles: true }, + { status: "failed" as const, followUp: "none", settles: false }, + { status: "interrupted" as const, followUp: "none", settles: false }, + { status: "completed" as const, followUp: "notification", settles: true }, + { status: "completed" as const, followUp: "replayed-notification", settles: true }, + { status: "completed" as const, followUp: "delegated", settles: true }, + { status: "completed" as const, followUp: "failed-notification", settles: false }, + { status: "completed" as const, followUp: "held-notification", settles: true }, + { status: "completed" as const, followUp: "user", settles: false }, + { status: "completed" as const, followUp: "steered-notification", settles: false }, +])("settleAfterRun handles $status with $followUp follow-up", ({ status, followUp, settles }) => Effect.gen(function* () { const projectId = ProjectId.make("project:thread-management:settle-after-run"); const threadId = ThreadId.make("thread:thread-management:settle-after-run"); const runId = RunId.make("run:thread-management:settle-after-run"); + const followUpId = RunId.make(`${runId}:follow-up`); + const subscribed = yield* Deferred.make(); + const events = yield* Queue.unbounded(); + const replayRejected = yield* Deferred.make(); + let sequence = 0; + let sequenceReads = 0; + let rejectedCommandId: CommandId | undefined; + const runs = [{ id: runId, ordinal: 1, status, userMessageId: MessageId.make("original") }]; + const nextRun = { + id: followUpId, + ordinal: 2, + status: "running" as OrchestrationV2Run["status"], + userMessageId: MessageId.make("follow-up"), + }; const dispatched: Array = []; + // The notification starts after the completed run was observed, before settlement commits. + let raced = false; const layerTest = ThreadManagementService.layer.pipe( Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})), Layer.provide( Layer.mock(Orchestrator.OrchestratorV2)({ - getThreadEventSequence: () => Effect.succeed(0), + getThreadEventSequence: () => + Effect.sync(() => { + if (followUp === "replayed-notification" && sequenceReads++ === 2) sequence = 1; + return sequence; + }), restartContinuationPending: () => Effect.succeed(false), - getThreadRecords: () => - Effect.succeed({ - thread: { id: threadId, projectId, deletedAt: null }, - runs: [{ id: runId, status }], - } as unknown as OrchestrationV2ThreadProjection), + streamStoredEventsFrom: () => + Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe( + Stream.drain, + Stream.concat(Stream.fromQueue(events)), + ), + getThreadRecords: (_threadId, _fields, filter) => + Effect.sync( + () => + ({ + thread: { id: threadId, projectId, deletedAt: null }, + runs: raced ? [...runs, nextRun] : runs, + messages: [ + { id: MessageId.make("original"), runId, role: "user" as const }, + { + id: nextRun.userMessageId, + runId: followUpId, + role: "user" as const, + ...(followUp.endsWith("notification") ? { notification: {} } : {}), + ...(followUp === "delegated" ? { delegatedCompletion: {} } : {}), + }, + { id: MessageId.make("reply"), runId: followUpId, role: "assistant" as const }, + ...(followUp === "steered-notification" + ? [ + { + id: MessageId.make("user-steer"), + runId: followUpId, + role: "user" as const, + }, + ] + : []), + ].filter( + (message) => + (filter?.messageIds === undefined || + filter.messageIds.includes(message.id)) && + (filter?.messageRunIds === undefined || + filter.messageRunIds.includes(message.runId)) && + (filter?.messageRoles === undefined || + filter.messageRoles.includes(message.role)), + ), + }) as unknown as OrchestrationV2ThreadProjection, + ), dispatch: (command) => - Effect.sync(() => { + Effect.gen(function* () { + if (followUp !== "none" && !raced) { + raced = true; + rejectedCommandId = command.commandId; + return yield* new Orchestrator.OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: "Thread is still running", + }); + } + if (followUp === "replayed-notification" && command.commandId === rejectedCommandId) { + yield* Deferred.succeed(replayRejected, undefined); + return yield* new Orchestrator.OrchestratorCommandPreviouslyRejectedError({ + commandId: command.commandId, + commandType: command.type, + detail: "Thread is still running", + }); + } dispatched.push(command.type); return { sequence: 1, storedEvents: [] } as never; }), @@ -592,9 +672,33 @@ it.effect.each([ const service = yield* ThreadManagementService.ThreadManagementService.pipe( Effect.provide(layerTest), ); - - yield* service.settleAfterRun({ projectId, threadId, runId }); - + const fiber = yield* service + .settleAfterRun({ projectId, threadId, runId }) + .pipe(Effect.forkChild); + if (followUp !== "none") { + yield* Deferred.await(subscribed); + expect(dispatched).toEqual([]); + nextRun.status = + followUp === "failed-notification" + ? "failed" + : followUp === "held-notification" + ? "queued" + : "completed"; + yield* Queue.offer(events, { + sequence: 1, + event: { type: "run.updated", threadId, payload: nextRun }, + } as unknown as OrchestrationV2StoredEvent); + } + if (followUp === "replayed-notification") { + yield* Deferred.await(replayRejected); + expect(dispatched).toEqual([]); + sequence = 2; + yield* Queue.offer(events, { + sequence, + event: { type: "run.updated", threadId, payload: nextRun }, + } as unknown as OrchestrationV2StoredEvent); + } + yield* Fiber.join(fiber); expect(dispatched).toEqual(settles ? ["thread.settle"] : []); }), ); diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index b6c1e27120ae8..46ea454310554 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -446,8 +446,8 @@ export interface ThreadManagementServiceShape { readonly waitForThread: ( input: ThreadManagementWaitInput, ) => Effect.Effect; - /** Waits for the agent's run to end before settling its thread and stopping the session. - * Other endings or settle refusals leave the thread active. */ + /** Waits for the agent's run and automatic follow-ups before settling. + * A new user turn or an unsuccessful ending leaves the thread active. */ readonly settleAfterRun: (input: { readonly projectId: ProjectId; readonly threadId: ThreadId; @@ -1044,11 +1044,74 @@ const make = Effect.gen(function* () { )(function* (input) { const { run } = yield* waitForThread({ ...input, timeoutMs: SETTLE_AFTER_RUN_WAIT_MS }); if (run?.status !== "completed") return; - yield* dispatch({ - type: "thread.settle", - commandId: CommandId.make(`server:settle-after-run:${input.runId}`), - threadId: input.threadId, + const afterSequence = yield* orchestrator.getThreadEventSequence(input.threadId); + const trySettle = Effect.gen(function* () { + const sequence = yield* orchestrator.getThreadEventSequence(input.threadId); + const records = yield* getProjectThreadRecords(input, ["runs"]); + const following = records.runs.filter((candidate) => candidate.ordinal > run.ordinal); + if (following.length > 0) { + const { messages } = yield* getProjectThreadRecords(input, ["messages"], { + messageRunIds: following.map((candidate) => candidate.id), + messageRoles: ["user"], + }); + const automaticMessageIds = new Set( + messages + .filter( + (message) => + message.role === "user" && + (message.notification !== undefined || message.delegatedCompletion !== undefined), + ) + .map((message) => message.id), + ); + if ( + messages.some((message) => !automaticMessageIds.has(message.id)) || + following.some((candidate) => !automaticMessageIds.has(candidate.userMessageId)) + ) { + return true; + } + if ( + following.some( + (candidate) => candidate.status !== "queued" && !isTerminalRunStatus(candidate.status), + ) + ) + return false; + if ( + following.some( + (candidate) => candidate.status !== "queued" && candidate.status !== "completed", + ) + ) + return true; + } + const latest = latestRun(records); + if (latest === undefined) return true; + return yield* dispatch({ + type: "thread.settle", + commandId: CommandId.make(`server:settle-after-run:${input.runId}:${sequence}`), + threadId: input.threadId, + expectedLatestRunId: latest.id, + }).pipe( + Effect.as(true), + // A notification can start between the projection read and the guarded dispatch. + Effect.catchTags({ + OrchestratorDispatchError: () => Effect.succeed(false), + OrchestratorCommandPreviouslyRejectedError: () => Effect.succeed(false), + }), + ); }); + yield* Stream.fromEffect(trySettle).pipe( + Stream.concat( + orchestrator + .streamStoredEventsFrom({ + threadId: input.threadId, + afterSequence, + eventType: "run.updated", + }) + .pipe(Stream.mapEffect(() => trySettle)), + ), + Stream.filter((done) => done), + Stream.runHead, + Effect.timeoutOption(Duration.millis(SETTLE_AFTER_RUN_WAIT_MS)), + ); }); const settleThread: ThreadManagementServiceShape["settleThread"] = Effect.fn( diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index af95d71e6121b..b90f491dfa94e 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -4859,11 +4859,29 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }); }); yield* holdQueueAfterRestart("settle-automatic-restart"); + const beforeSettle = yield* orchestrator.getThreadProjection(threadId); + const oldestRun = beforeSettle.runs.reduce((oldest, run) => + run.ordinal < oldest.ordinal ? run : oldest, + ); + const latestRun = beforeSettle.runs.reduce((latest, run) => + run.ordinal > latest.ordinal ? run : latest, + ); + const staleSettle = yield* orchestrator + .dispatch({ + type: "thread.settle", + commandId: CommandId.make("settle-automatic-stale"), + threadId, + expectedLatestRunId: oldestRun.id, + }) + .pipe(Effect.flip); + assert.equal(staleSettle._tag, "OrchestratorDispatchError"); + assert.isNull((yield* orchestrator.getThreadProjection(threadId)).thread.settledAt); yield* orchestrator.dispatch({ type: "thread.settle", commandId: CommandId.make("settle-automatic-settle"), threadId, + expectedLatestRunId: latestRun.id, }); const settled = yield* orchestrator.getThreadProjection(threadId); assert.isNotNull(settled.thread.settledAt); diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 8234864349504..461ec5e4b3f3e 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -2975,6 +2975,7 @@ export const OrchestrationV2Command = Schema.Union([ type: Schema.Literal("thread.settle"), commandId: CommandId, threadId: ThreadId, + expectedLatestRunId: Schema.optional(RunId), settledAt: Schema.optional(Schema.DateTimeUtc), }), /** Rejects changes since snapshotAt or any explicit settled override to preserve user actions. */ From 2e39f1d7dec44c98a4cabdaf99d3d99209f770c0 Mon Sep 17 00:00:00 2001 From: oliver <97427849+flamboh@users.noreply.github.com> Date: Thu, 5 Nov 2026 21:46:49 -0800 Subject: [PATCH 086/181] fix(web): settings descriptions use the full row and stay two lines (#31826) Co-authored-by: Claude Opus 5.5 --- .../settings/ThreadSettingsSections.tsx | 7 +-- .../components/DatabaseStorageNotice.tsx | 2 +- .../settings/DatabaseStorageNotice.tsx | 2 +- .../components/settings/LabsSettingsPanel.tsx | 10 +-- .../settings/VoiceSettingsPanel.tsx | 2 +- .../components/settings/settingsLayout.tsx | 6 +- oxlint-plugin-t3code/index.ts | 2 + .../max-settings-description-length.test.ts | 43 +++++++++++++ .../rules/max-settings-description-length.ts | 63 +++++++++++++++++++ vite.config.ts | 4 ++ 10 files changed, 126 insertions(+), 15 deletions(-) create mode 100644 oxlint-plugin-t3code/rules/max-settings-description-length.test.ts create mode 100644 oxlint-plugin-t3code/rules/max-settings-description-length.ts diff --git a/apps/mobile/src/features/settings/ThreadSettingsSections.tsx b/apps/mobile/src/features/settings/ThreadSettingsSections.tsx index 8aaae71673a0e..df463bd1f664c 100644 --- a/apps/mobile/src/features/settings/ThreadSettingsSections.tsx +++ b/apps/mobile/src/features/settings/ThreadSettingsSections.tsx @@ -268,7 +268,7 @@ function BetaSettingsSection() { Let agents on a machine work on your other machines, and theirs on it. Turn it on for each - machine. While it is off, nothing new starts over a link; tasks already running finish. + machine. While off, nothing new starts over a link; running tasks finish. ); @@ -306,9 +306,8 @@ function ToolCallVisibilitySection() { ))} - Hide the commands, edits, and searches agents run, so a thread reads like a conversation. - Hide successful keeps calls that fail. Zen also hides the agent's in-between messages - and shows only final answers. Approvals, questions, and errors always show. + Hide the commands, edits, and searches agents run. Hide successful keeps failures. Zen shows + only final answers. Approvals, questions, and errors always show. ); diff --git a/apps/mobile/src/features/settings/components/DatabaseStorageNotice.tsx b/apps/mobile/src/features/settings/components/DatabaseStorageNotice.tsx index f492574db4339..963a94f607ae0 100644 --- a/apps/mobile/src/features/settings/components/DatabaseStorageNotice.tsx +++ b/apps/mobile/src/features/settings/components/DatabaseStorageNotice.tsx @@ -31,7 +31,7 @@ export function DatabaseStorageNotice({ return ( {visible.map(({ environmentId, status }) => ( {visible.map(({ environmentId, status }) => ( onChange({ ...preset, minutes })} /> ) : ( - <> +
at - +
)} ); @@ -410,7 +410,7 @@ function DurationFields(props: { minutes: number; onChange: (minutes: number) => setDraft(amount); } return ( - <> +
))} - +
); } diff --git a/apps/web/src/components/settings/TypographySettings.tsx b/apps/web/src/components/settings/TypographySettings.tsx index 9e3c58aea1c60..b782c61674823 100644 --- a/apps/web/src/components/settings/TypographySettings.tsx +++ b/apps/web/src/components/settings/TypographySettings.tsx @@ -493,8 +493,8 @@ function FontFamilySettingsRow({ /> ); const control = ( -
-
{familyControl}
+
+
{familyControl}