From 371b52d9dad76876f84609a4cd0f80eaa757b69c Mon Sep 17 00:00:00 2001 From: maria Date: Mon, 21 Sep 2026 14:39:40 -0300 Subject: [PATCH 01/60] feat(web): answer pull request actions on the row at once (#12843) Co-authored-by: Claude Fable 5.1 --- .../pullRequest/PullRequestDetailPanel.tsx | 11 +- .../pullRequest/pullRequestList.logic.test.ts | 94 +++++++++++ .../pullRequest/pullRequestList.logic.ts | 126 +++++++++++++++ apps/web/src/routes/_chat.pull-requests.tsx | 151 ++++++++++++++++-- 4 files changed, 367 insertions(+), 15 deletions(-) diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx index f19e41599043c..a02cb52173bd6 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx @@ -458,7 +458,12 @@ export function PullRequestDetailPanel({ * An action changed this pull request on the host, so a list showing it is now out of date. * Told rather than assumed: only the page knows whether it is showing one. */ - onActed?: () => void; + /** + * Each host action as it goes: "sent" the moment it leaves, so a list can answer before the + * host does; "done" or "failed" when the host has spoken. Undefined for one the caller cannot + * name, which is only ever "done". + */ + onActed?: (action?: PullRequestAction, phase?: "sent" | "done" | "failed") => void; /** Page-owned detail columns use this to clear the selected pull request. */ onClose?: () => void; /** @@ -961,6 +966,7 @@ export function PullRequestDetailPanel({ method?: PullRequestMergeMethod, updateMethod?: PullRequestUpdateMethod, ) => { + onActed?.(action, "sent"); const result = await runAction({ environmentId, input: { @@ -988,6 +994,7 @@ export function PullRequestDetailPanel({ title: ACTION_FAILURE_LABELS[action], description: readableFailure(failure, hint), }); + onActed?.(action, "failed"); return false; } toastManager.add({ type: "success", title: ACTION_SUCCESS_LABELS[action] }); @@ -1001,7 +1008,7 @@ export function PullRequestDetailPanel({ } else { refreshDetail(); } - onActed?.(); + onActed?.(action, "done"); return true; }; diff --git a/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts index 9154e38026d2d..357ea20ad76d7 100644 --- a/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts @@ -32,6 +32,10 @@ import { resolveQueryEnvironmentIds, resolveSelectedEnvironmentId, type EnvironmentPullRequestEntry, + applyPullRequestOverrides, + pullRequestOverrideAfterAction, + reusePullRequestEntries, + settlePullRequestOverrides, } from "./pullRequestList.logic"; import { pullRequestListPreferences, @@ -1600,3 +1604,93 @@ describe("the priority groups against a paginated feed", () => { ).toEqual([6123]); }); }); + +describe("pull request list overrides", () => { + const entry = (number: number, state: "open" | "closed" | "merged") => + ({ + host: "github.com", + repository: "pingdotgg/t3code", + number, + state, + isDraft: false, + updatedAt: "2026-07-01T00:00:00Z", + labels: [], + }) as unknown as PullRequestListEntry; + const key = (row: { number: number }) => `#${row.number}`; + + it("maps the actions that change a row's state and nothing else", () => { + const now = new Date("2026-07-02T00:00:00Z"); + expect(pullRequestOverrideAfterAction(entry(1, "open"), "close", now, 7)).toEqual({ + state: "closed", + updatedAt: "2026-07-02T00:00:00.000Z", + token: 7, + at: now.getTime(), + }); + expect(pullRequestOverrideAfterAction(entry(1, "closed"), "reopen", now, 1)?.state).toBe( + "open", + ); + expect(pullRequestOverrideAfterAction(entry(1, "open"), "merge", now, 1)?.state).toBe("merged"); + expect(pullRequestOverrideAfterAction(entry(1, "open"), "draft", now, 1)?.isDraft).toBe(true); + expect(pullRequestOverrideAfterAction(entry(1, "open"), "update-branch", now, 1)).toBeNull(); + }); + + it("writes the override over the row and drops it from a list whose state it left", () => { + const rows = [entry(1, "open"), entry(2, "open")]; + const overrides = new Map([ + ["#1", { state: "closed" as const, updatedAt: "2026-07-03T00:00:00Z", token: 1, at: 0 }], + ]); + expect( + applyPullRequestOverrides(rows, overrides, key, "open").map((row) => row.number), + ).toEqual([2]); + const all = applyPullRequestOverrides(rows, overrides, key, "all"); + expect(all.map((row) => [row.number, row.state])).toEqual([ + [1, "closed"], + [2, "open"], + ]); + expect(applyPullRequestOverrides(rows, new Map(), key, "open")).toBe(rows); + }); + + it("hands back the held object for a row a refresh did not change", () => { + const previous = [entry(1, "open"), entry(2, "open")]; + const next = [{ ...entry(1, "open") }, { ...entry(2, "open"), state: "merged" as const }]; + const reused = reusePullRequestEntries(previous, next, key); + expect(reused[0]).toBe(previous[0]); + expect(reused[1]).toBe(next[1]); + expect( + reusePullRequestEntries(previous, [{ ...entry(1, "open") }, { ...entry(2, "open") }], key), + ).toBe(previous); + }); +}); + +describe("pull request list override settlement", () => { + const entry = (number: number, state: "open" | "closed" | "merged") => + ({ number, state, isDraft: false, labels: [] }) as unknown as PullRequestListEntry; + const key = (row: { number: number }) => `#${row.number}`; + + it("keeps an override until an answer agrees with it", () => { + const at = 1_000_000; + const closed = { state: "closed" as const, updatedAt: "2026-07-03T00:00:00Z", token: 1, at }; + const overrides = new Map([["#1", closed]]); + // A read from before the action still says open: the override stands. + expect(settlePullRequestOverrides(overrides, [entry(1, "open")], key, at + 5_000)).toBe( + overrides, + ); + // Absent from the answer says nothing: the row may live in another group or page. + expect(settlePullRequestOverrides(overrides, [entry(2, "open")], key, at + 5_000).size).toBe(1); + // Present as closed: confirmed. + expect(settlePullRequestOverrides(overrides, [entry(1, "closed")], key, at + 5_000).size).toBe( + 0, + ); + // Present as open a good while later: the host's news, which outranks the note. + expect(settlePullRequestOverrides(overrides, [entry(1, "open")], key, at + 90_000).size).toBe( + 0, + ); + }); + + it("does not hand back the old order when only the order changed", () => { + const previous = [entry(1, "open"), entry(2, "open")]; + const swapped = reusePullRequestEntries(previous, [entry(2, "open"), entry(1, "open")], key); + expect(swapped).not.toBe(previous); + expect(swapped.map((row) => row.number)).toEqual([2, 1]); + }); +}); diff --git a/apps/web/src/components/pullRequest/pullRequestList.logic.ts b/apps/web/src/components/pullRequest/pullRequestList.logic.ts index f001e33829c52..f4cb3a31f46f1 100644 --- a/apps/web/src/components/pullRequest/pullRequestList.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestList.logic.ts @@ -9,6 +9,7 @@ import { } from "@t3tools/contracts"; import type { ProjectId, + PullRequestAction, PullRequestActor, PullRequestDiffStat, PullRequestInvolvement, @@ -16,6 +17,7 @@ import type { PullRequestListCursors, PullRequestListFilters, PullRequestListState, + PullRequestState, } from "@t3tools/contracts"; import { toSortableTimestamp } from "../../lib/threadSort"; @@ -1140,3 +1142,127 @@ export function withDiffStat< const stat = statsByRow.get(pullRequestDiffStatKey(entry)); return stat === undefined ? entry : { ...entry, ...stat }; } + +/** + * What a row should say the moment an action is sent, before any host has answered. The host + * is the record and a later read replaces this, but the reader pressed the button and should + * see the row answer at once: a closed pull request leaves an "open" list on the click, not + * after the reads that follow. + */ +export interface PullRequestListOverride { + readonly state: PullRequestState; + readonly isDraft?: boolean; + readonly updatedAt: string; + /** Which action wrote it, so a failure takes back its own note and not a later one's. */ + readonly token: number; + /** When it was written, in the reader's clock. */ + readonly at: number; +} + +export function pullRequestOverrideAfterAction( + entry: Pick, + action: PullRequestAction, + now: Date, + token: number, +): PullRequestListOverride | null { + const stamp = { updatedAt: now.toISOString(), token, at: now.getTime() }; + switch (action) { + case "close": + return { state: "closed", ...stamp }; + case "reopen": + return { state: "open", ...stamp }; + case "merge": + return { state: "merged", ...stamp }; + case "draft": + return { state: entry.state, isDraft: true, ...stamp }; + case "ready": + return { state: entry.state, isDraft: false, ...stamp }; + default: + return null; + } +} + +/** The rows with their pending answers written over them, and the ones the list's state filter no longer holds dropped. */ +export function applyPullRequestOverrides( + entries: ReadonlyArray, + overrides: ReadonlyMap, + keyOf: (entry: Entry) => string, + state: PullRequestListState, +): ReadonlyArray { + if (overrides.size === 0) return entries; + const out: Entry[] = []; + for (const entry of entries) { + const override = overrides.get(keyOf(entry)); + if (override === undefined) { + out.push(entry); + continue; + } + if (state !== "all" && override.state !== state) continue; + out.push({ ...entry, ...override }); + } + return out; +} + +/** + * A fresh answer with the rows it did not change handed back as the objects already held, so a + * memoized row whose data is the same does not render again. Every refresh otherwise rebuilds + * every entry, and a hundred rows repaint for the one that moved. + */ +export function reusePullRequestEntries( + previous: ReadonlyArray, + next: ReadonlyArray, + keyOf: (entry: Entry) => string, +): ReadonlyArray { + if (previous.length === 0) return next; + const held = new Map(previous.map((entry) => [keyOf(entry), entry])); + let reused = 0; + const out = next.map((entry) => { + const before = held.get(keyOf(entry)); + if (before !== undefined && JSON.stringify(before) === JSON.stringify(entry)) { + reused += 1; + return before; + } + return entry; + }); + return reused === next.length && + previous.length === next.length && + previous.every((entry, index) => keyOf(entry) === keyOf(next[index]!)) + ? previous + : out; +} + +/** How long a read that disagrees is taken for a stale one rather than for news. */ +const PULL_REQUEST_OVERRIDE_TRUST_MS = 60_000; + +/** + * The overrides an answer has confirmed, dropped; the rest kept. A read that started before + * the action can land after it and still say the old thing, so an override is not cleared + * because an answer arrived but because the answer agrees: the row is there in the state the + * override said. A row that is absent says nothing — the authored and reviewing groups are read + * apart from the feed, and a page is only a page — so absence never confirms. A row present in + * another state is taken for a stale read for a minute, and for the host's news after that, + * which is how a pull request reopened elsewhere comes back. + */ +export function settlePullRequestOverrides( + overrides: ReadonlyMap, + answered: ReadonlyArray, + keyOf: (entry: Entry) => string, + now: number, +): ReadonlyMap { + if (overrides.size === 0) return overrides; + const byKey = new Map(answered.map((entry) => [keyOf(entry), entry])); + const kept = new Map(); + for (const [key, override] of overrides) { + const row = byKey.get(key); + if (row === undefined) { + kept.set(key, override); + continue; + } + const agrees = + row.state === override.state && + (override.isDraft === undefined || row.isDraft === override.isDraft); + const outranked = now - override.at > PULL_REQUEST_OVERRIDE_TRUST_MS; + if (!agrees && !outranked) kept.set(key, override); + } + return kept.size === overrides.size ? overrides : kept; +} diff --git a/apps/web/src/routes/_chat.pull-requests.tsx b/apps/web/src/routes/_chat.pull-requests.tsx index 485fa7718e3e8..59368351359d7 100644 --- a/apps/web/src/routes/_chat.pull-requests.tsx +++ b/apps/web/src/routes/_chat.pull-requests.tsx @@ -4,6 +4,7 @@ import { pullRequestHostOf, resolveEnvironmentMachineKind } from "@t3tools/contr import type { EnvironmentId, ProjectId, + PullRequestAction, PullRequestInvolvement, PullRequestListCursors, PullRequestListFilters, @@ -77,6 +78,11 @@ import { type PullRequestStatsPolicy, type PullRequestStatsScope, type PullRequestPartitionsSnapshot, + applyPullRequestOverrides, + type PullRequestListOverride, + pullRequestOverrideAfterAction, + reusePullRequestEntries, + settlePullRequestOverrides, } from "../components/pullRequest/pullRequestList.logic"; import { pullRequestListPreferences, @@ -914,6 +920,36 @@ function PullRequestsRouteView() { key: string; entries: ReadonlyArray; } | null>(null); + // What the reader just did to a row, shown before any host confirms it. A closed pull request + // leaves an "open" list on the click; the reads that follow are slow, and until one lands the + // row says what was asked of it. Cleared when a whole-page answer arrives after the action. + const [overrides, setOverrides] = useState>( + () => new Map(), + ); + const overrideToken = useRef(0); + /** Writes the action's outcome onto the row; the token names this write for a later rollback. */ + const overrideEntry = ( + entry: EnvironmentPullRequestEntry, + action: PullRequestAction, + ): number | null => { + const token = ++overrideToken.current; + const override = pullRequestOverrideAfterAction(entry, action, new Date(), token); + if (override === null) return null; + setOverrides((current) => new Map(current).set(pullRequestEntryKey(entry), override)); + return token; + }; + /** A rollback for one write only: a later action's note over the same row is left alone. */ + const revertOverride = (key: string, token: number | null) => { + if (token === null) return; + setOverrides((current) => { + if (current.get(key)?.token !== token) return current; + const next = new Map(current); + next.delete(key); + return next; + }); + }; + /** The detail panel's own writes, by row, so its failure takes back its own note. */ + const detailOverrideTokens = useRef(new Map()); // A reload recreates the registry the queries live in, so with nothing held the page would // cold-start into skeletons even though almost every row is unchanged. The last answer for // this set of environments is kept across reloads and hydrated here as the carried rows: they @@ -1077,8 +1113,20 @@ function PullRequestsRouteView() { // since the last read at the bottom of the page — below rows a week older — where "the // latest" is exactly what a refresh was for. The host answers in the order the page // reads, so its order stands; a row that moved was updated, and moving is the news. - return { key: filterKey, entries: rankPullRequestMatches(answered.entries, sentParsed.text) }; + return { + key: filterKey, + entries: reusePullRequestEntries( + previous.entries, + rankPullRequestMatches(answered.entries, sentParsed.text), + pullRequestEntryKey, + ), + }; }); + // The host's word outranks the reader's, once it has actually said it: an override is + // cleared by an answer that agrees with it, not by any answer that happens to land. + setOverrides((current) => + settlePullRequestOverrides(current, answered.entries, pullRequestEntryKey, Date.now()), + ); }, [ answered, filterKey, @@ -1455,10 +1503,34 @@ function PullRequestsRouteView() { setStatsByRow((previous) => mergePullRequestDiffStats(previous, stats)); }, [statsQuery.stats]); const displayGroups = useMemo(() => { - const enriched = groups.map((group) => ({ - ...group, - entries: group.entries.map((entry) => withDiffStat(entry, statsByRow)), - })); + // The reader's pending answers go on here, after grouping: the authored and reviewing + // groups are read separately from the feed, and a row closed a moment ago has to leave + // whichever group it was in. + const enriched = groups.map((group) => { + const answered = applyPullRequestOverrides( + group.entries.map((entry) => withDiffStat(entry, statsByRow)), + overrides, + pullRequestEntryKey, + search.state, + ); + // A row whose draft flag just changed has to pass the local filters again: a draft + // filter that let it in may not let the new one in. + return { + ...group, + entries: + hasLocalFilters && overrides.size > 0 + ? answered.filter( + (entry) => + !overrides.has(pullRequestEntryKey(entry)) || + matchesPullRequestFilters( + entry, + localFilters, + pullRequestEntryViewer(entry, viewers), + ), + ) + : answered, + }; + }); // Searching keeps its relevance order and priority groups unless the reader explicitly asks // for another sort. The readiness queue is the default browse order, not a way to bury a // closer text match. @@ -1470,7 +1542,29 @@ function PullRequestsRouteView() { entry.additions + entry.deletions > 0 || statsByRow.has(pullRequestDiffStatKey(entry)), search.involvement, ); - }, [groups, search.involvement, sort, statsByRow, typedParsed.text]); + }, [ + groups, + hasLocalFilters, + localFilters, + overrides, + search.involvement, + search.state, + sort, + statsByRow, + typedParsed.text, + viewers, + ]); + /** What is actually on screen once the reader's pending answers are on the rows. */ + const shownCount = displayGroups.reduce((count, group) => count + group.entries.length, 0); + const heldPullRequestsBySurface = useMemo( + () => + new Map( + groups.flatMap((group) => + group.entries.map((entry) => [pullRequestListEntryId(entry), entry] as const), + ), + ), + [groups], + ); const listedPullRequestsBySurface = useMemo( () => new Map( @@ -1645,7 +1739,7 @@ function PullRequestsRouteView() { // so that case waits with the skeletons rather than answering for the hosts. A search says so // in its own words and is left to. const carriedToNothing = - showingCarried && listQuery.isPending && entries.length === 0 && typedQuery.length === 0; + showingCarried && listQuery.isPending && shownCount === 0 && typedQuery.length === 0; const listBody = ( <> {!capabilityKnown ? ( @@ -1657,7 +1751,7 @@ function PullRequestsRouteView() { /> ) : firstLoad ? ( - ) : listQuery.error && entries.length === 0 ? ( + ) : listQuery.error && shownCount === 0 ? ( ) : carriedToNothing ? ( - ) : entries.length === 0 ? ( + ) : shownCount === 0 ? ( 0} refreshing={refreshing} @@ -1724,7 +1818,7 @@ function PullRequestsRouteView() { )} - {listQuery.error && entries.length > 0 ? ( + {listQuery.error && shownCount > 0 ? (
{listQuery.error} Showing the last pull requests loaded. ); From 2d377bfb1c8c85a61679fa6cdb6e8181cfb13626 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Mon, 21 Sep 2026 17:11:14 -0500 Subject: [PATCH 04/60] fix(web): dismiss selection actions when pressing buttons (#12950) --- apps/web/src/lib/selectionActions.test.ts | 35 +++++++++++++++++++++-- apps/web/src/lib/selectionActions.ts | 4 +++ 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/apps/web/src/lib/selectionActions.test.ts b/apps/web/src/lib/selectionActions.test.ts index 56f51863b6907..d677b28587710 100644 --- a/apps/web/src/lib/selectionActions.test.ts +++ b/apps/web/src/lib/selectionActions.test.ts @@ -24,7 +24,12 @@ function createSelectionSurface({ interactiveActions = false } = {}) { }); const element = Object.assign(new EventTarget(), { ownerDocument: document, - contains: (target: unknown): boolean => target === element, + contains: (target: unknown): boolean => target === element || target === buttonIcon, + closest: () => null, + }); + const button = new EventTarget(); + const buttonIcon = Object.assign(new EventTarget(), { + closest: (selector: string) => (selector === "button, [role=button]" ? button : null), }); const onSelection = vi.fn(); const onDismiss = vi.fn(); @@ -58,7 +63,7 @@ function createSelectionSurface({ interactiveActions = false } = {}) { const press = event("pointerdown", { button, isPrimary }); Object.defineProperty(press, "target", { value: target }); document.dispatchEvent(press); - if (target === element && !consumed) element.dispatchEvent(press); + if (element.contains(target) && !consumed) element.dispatchEvent(press); }; const focus = (target: EventTarget) => { document.activeElement = target; @@ -92,6 +97,7 @@ function createSelectionSurface({ interactiveActions = false } = {}) { view, document, element, + buttonIcon, actionElement, field, onSelection, @@ -177,6 +183,31 @@ describe("selection action gestures", () => { expect(surface.onSelection).not.toHaveBeenCalled(); }); + it.each([1, 2])( + "dismisses selection actions when a button is pressed after %i clicks", + (detail) => { + const surface = createSelectionSurface(); + surface.down(); + surface.up({ detail }); + surface.flush(); + surface.onSelection.mockClear(); + surface.onDismiss.mockClear(); + + surface.down({ target: surface.buttonIcon }); + surface.up(); + surface.change(); + surface.flush(1000); + expect(surface.onDismiss).toHaveBeenCalledWith("interaction"); + expect(surface.onSelection).not.toHaveBeenCalled(); + + surface.down(); + surface.change(); + surface.up(); + surface.flush(); + expect(surface.onSelection).toHaveBeenCalledOnce(); + }, + ); + it("ignores nonprimary pointers and non-left mouseup without ending a left drag", () => { const surface = createSelectionSurface(); surface.down({ isPrimary: false }); diff --git a/apps/web/src/lib/selectionActions.ts b/apps/web/src/lib/selectionActions.ts index 91e6c2e6a10b1..5954a770aa656 100644 --- a/apps/web/src/lib/selectionActions.ts +++ b/apps/web/src/lib/selectionActions.ts @@ -101,6 +101,10 @@ export function observeSelectionActions({ }; const onSelectionStart = (event: PointerEvent) => { if (!event.isPrimary) return; + const target = event.target as Element | null; + // Buttons can preserve an existing text selection while opening a menu. + // Their release must not reopen selection actions beside the button. + if (target?.closest("button, [role=button]")) return; // A surface may consume a press for a link or terminal mouse reporting. gestureActive = event.button === 0 && !event.defaultPrevented; dismissed = !gestureActive; From d2a90b921a5843654a58448d0bc59828e1e3ccc4 Mon Sep 17 00:00:00 2001 From: Alex Southwell Date: Tue, 22 Sep 2026 08:33:28 +1000 Subject: [PATCH 05/60] fix(web): name message copy actions accurately (#12865) --- .../src/components/chat/MessageCopyButton.tsx | 4 +- .../components/chat/MessagesTimeline.test.tsx | 2 +- docs/internals/consistency-action-names.md | 39 +++++++++++++++++++ 3 files changed, 42 insertions(+), 3 deletions(-) create mode 100644 docs/internals/consistency-action-names.md diff --git a/apps/web/src/components/chat/MessageCopyButton.tsx b/apps/web/src/components/chat/MessageCopyButton.tsx index 4a5c3f170d200..aaaa171f10de7 100644 --- a/apps/web/src/components/chat/MessageCopyButton.tsx +++ b/apps/web/src/components/chat/MessageCopyButton.tsx @@ -37,7 +37,7 @@ export const MessageCopyButton = memo(function MessageCopyButton({ copyToClipboard(text)} ref={ref} @@ -51,7 +51,7 @@ export const MessageCopyButton = memo(function MessageCopyButton({ {isCopied ? : } -

Copy to clipboard

+

Copy message

); diff --git a/apps/web/src/components/chat/MessagesTimeline.test.tsx b/apps/web/src/components/chat/MessagesTimeline.test.tsx index dae27ccdba473..016e621be1dd8 100644 --- a/apps/web/src/components/chat/MessagesTimeline.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.test.tsx @@ -1320,7 +1320,7 @@ describe("MessagesTimeline", () => { />, ); - expect(markup).toContain('aria-label="Copy link"'); + expect(markup).toContain('aria-label="Copy message"'); expect(markup).toContain('data-user-message-collapsed="true"'); expect(markup).toContain('data-user-message-footer="true"'); }); diff --git a/docs/internals/consistency-action-names.md b/docs/internals/consistency-action-names.md new file mode 100644 index 0000000000000..7277c1bbf74f7 --- /dev/null +++ b/docs/internals/consistency-action-names.md @@ -0,0 +1,39 @@ +# Action names agree across presentations + +Proposed invariant: a command's visible label, tooltip, menu wording and accessible +name describe the same action on the same object. An icon-only presentation must +retain that meaning. This applies to shared web/Electron controls and corresponding +React Native iOS/Android actions, wherever those actions are available. + +Separate strings can drift while each presentation still looks plausible. A message +copy action called “Copy link” promises a different clipboard payload to someone +using a screen reader. Use wording that identifies the actual target, including +when a message contains links or structured context. Additional clipboard formats +do not turn copying a message into copying a link. + +This proposal draws on Apple's [Writing](https://developer.apple.com/design/human-interface-guidelines/writing) +and [Accessibility](https://developer.apple.com/design/human-interface-guidelines/accessibility) +guidance. It is a product constraint, not a claim of Apple certification or complete +application compliance. + +## Boundaries + +Native menus and assistive technologies may use different wording or omit a tooltip. +Labels need semantic agreement, not identical strings across platforms. A contextual +“Copy” is sufficient when its target is unambiguous; do not globally expand it. +Temporary “Copied” feedback may replace an action label without implying a different +target. Clipboard transport, success timing and error reporting are separate concerns. + +## Observable cases + +- User and assistant message copy controls identify the message, in both tooltip + and accessible name. Collapsing a long message does not change the action's meaning. +- Copying a message with structured context still identifies the message; it does + not promise to copy only a context link. +- Code and plan copy actions retain their own targets. A contextual plan menu can + say “Copy to clipboard”; a code control must not be announced as copying a message. +- An icon, labeled button or native menu for an equivalent command conveys the same + operation. Completed feedback never names a different object. + +Verify visible wording alongside the runtime accessible name and resulting action. +Source inspection and screenshots alone do not establish accessibility-tree behavior. From 80d9c181da41ee3890791c9b65018ce093e7bc9e Mon Sep 17 00:00:00 2001 From: Igor Makowski <56691628+Mnigos@users.noreply.github.com> Date: Tue, 22 Sep 2026 00:33:44 +0200 Subject: [PATCH 06/60] fix(contracts): old message-sent events without turnId no longer stop the server from starting (#12763) --- packages/contracts/src/orchestration.test.ts | 31 ++++++++++++++++++++ packages/contracts/src/orchestration.ts | 3 +- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/packages/contracts/src/orchestration.test.ts b/packages/contracts/src/orchestration.test.ts index d89e1fb2957c5..7c7bade4502e2 100644 --- a/packages/contracts/src/orchestration.test.ts +++ b/packages/contracts/src/orchestration.test.ts @@ -812,6 +812,37 @@ it.effect("decodes thread pull request links with snapshot and stack", () => }), ); +// A stored event that fails to decode stops the event store read, and with it +// server startup, so rows written before `turnId` existed must still load. +it.effect("decodes a legacy message-sent event persisted without turnId", () => + Effect.gen(function* () { + const event = yield* decodeOrchestrationEvent({ + sequence: 539, + eventId: "event-message-legacy-1", + aggregateKind: "thread", + aggregateId: "thread-1", + type: "thread.message-sent", + occurredAt: "2026-01-01T00:00:00.000Z", + commandId: "cmd-message-legacy-1", + causationEventId: null, + correlationId: "cmd-message-legacy-1", + metadata: {}, + payload: { + threadId: "thread-1", + messageId: "message-1", + role: "user", + text: "written before turn ids were recorded", + streaming: false, + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + }, + }); + assert.strictEqual(event.type, "thread.message-sent"); + if (event.type !== "thread.message-sent") return; + assert.strictEqual(event.payload.turnId, null); + }), +); + it.effect("decodes thread archived and unarchived events", () => Effect.gen(function* () { const archived = yield* decodeOrchestrationEvent({ diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index 9a9ed05d4e6d8..3e323e4964d58 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -1893,7 +1893,8 @@ export const ThreadMessageSentPayload = Schema.Struct({ text: Schema.String, attachments: Schema.optional(Schema.Array(ChatAttachment)), context: Schema.optional(OrchestrationMessageContext), - turnId: Schema.NullOr(TurnId), + // Events persisted before the field existed carry no key at all. + turnId: Schema.NullOr(TurnId).pipe(Schema.withDecodingDefault(Effect.succeed(null))), streaming: Schema.Boolean, createdAt: IsoDateTime, updatedAt: IsoDateTime, From e1cbb705273a261d26b489f35a7ddca6567d9663 Mon Sep 17 00:00:00 2001 From: Igor Makowski <56691628+Mnigos@users.noreply.github.com> Date: Tue, 22 Sep 2026 00:34:12 +0200 Subject: [PATCH 07/60] fix(web): the custom snooze calendar starts the week where the locale does (#12745) --- .../web/src/components/CustomSnoozeDialog.tsx | 2 ++ apps/web/src/timestampFormat.test.ts | 26 +++++++++++++++++ apps/web/src/timestampFormat.ts | 29 +++++++++++++++++++ 3 files changed, 57 insertions(+) diff --git a/apps/web/src/components/CustomSnoozeDialog.tsx b/apps/web/src/components/CustomSnoozeDialog.tsx index d80ebf0d36fb9..453efb1cbe536 100644 --- a/apps/web/src/components/CustomSnoozeDialog.tsx +++ b/apps/web/src/components/CustomSnoozeDialog.tsx @@ -10,6 +10,7 @@ import { import { Button } from "./ui/button"; import { CalendarIcon } from "lucide-react"; import { Calendar } from "./ui/calendar"; +import { weekStartsOn } from "../timestampFormat"; import { Popover, PopoverTrigger, PopoverPopup } from "./ui/popover"; import { Input } from "./ui/input"; import { Label } from "./ui/label"; @@ -149,6 +150,7 @@ function CustomSnoozeDialog() { required selected={date} defaultMonth={date} + {...(weekStartsOn === undefined ? {} : { weekStartsOn })} disabled={{ before: new Date(new Date().setHours(0, 0, 0, 0)) }} onSelect={(selected) => { setDate(selected); diff --git a/apps/web/src/timestampFormat.test.ts b/apps/web/src/timestampFormat.test.ts index 8c6287010d8f1..d748853000c5c 100644 --- a/apps/web/src/timestampFormat.test.ts +++ b/apps/web/src/timestampFormat.test.ts @@ -52,6 +52,32 @@ describe("formatShortTimestamp", () => { }); }); +describe("resolveWeekStartsOn", () => { + it.each([ + ["en-US", 0], + ["en-GB", 1], + ["pl-PL", 1], + ["ar-EG", 6], + ])("starts the %s week on weekday %i", async (locale, weekday) => { + const { resolveWeekStartsOn } = await import("./timestampFormat"); + expect(resolveWeekStartsOn(locale)).toBe(weekday); + }); + + it("leaves the default to the caller for a malformed locale", async () => { + const { resolveWeekStartsOn } = await import("./timestampFormat"); + expect(resolveWeekStartsOn("not a locale")).toBeUndefined(); + }); + + it("follows the locale the desktop host reports", async () => { + vi.stubGlobal("window", { desktopBridge: { getSystemLocale: () => "en-GB" } }); + vi.resetModules(); + const { weekStartsOn } = await import("./timestampFormat"); + expect(weekStartsOn).toBe(1); + vi.unstubAllGlobals(); + vi.resetModules(); + }); +}); + describe("formatChatTimestampTooltip", () => { afterEach(() => { vi.restoreAllMocks(); diff --git a/apps/web/src/timestampFormat.ts b/apps/web/src/timestampFormat.ts index 9dd463bb50fa3..5106a00bdf2f4 100644 --- a/apps/web/src/timestampFormat.ts +++ b/apps/web/src/timestampFormat.ts @@ -53,6 +53,35 @@ function readHostSystemLocale(): string | null { const timestampLocale = resolveTimestampLocale(readHostSystemLocale()); +const WEEKDAY_INDEXES = [0, 1, 2, 3, 4, 5, 6] as const; +type WeekdayIndex = (typeof WEEKDAY_INDEXES)[number]; + +type LocaleWithWeekInfo = Intl.Locale & { + readonly weekInfo?: { readonly firstDay: number }; + getWeekInfo?: () => { readonly firstDay: number }; +}; + +/** + * First weekday of a locale as a `Date#getDay` index (0 is Sunday), or + * `undefined` when the runtime has no week data, so callers keep their own + * default. Without a locale it reads the runtime's. + */ +export function resolveWeekStartsOn(locale: string | undefined): WeekdayIndex | undefined { + try { + const resolved: LocaleWithWeekInfo = new Intl.Locale( + locale ?? Intl.DateTimeFormat().resolvedOptions().locale, + ); + // Week info counts Monday as 1 and Sunday as 7. + const firstDay = resolved.getWeekInfo?.().firstDay ?? resolved.weekInfo?.firstDay; + return firstDay === undefined ? undefined : WEEKDAY_INDEXES[firstDay % 7]; + } catch { + return undefined; + } +} + +/** Week start for calendars, from the same locale timestamps are shown in. */ +export const weekStartsOn = resolveWeekStartsOn(timestampLocale); + const timestampFormatterCache = new Map(); function getTimestampFormatter( From 76cc9b08f19d89012f16d18f47478c4f7b9b0a6f Mon Sep 17 00:00:00 2001 From: "t3-code[bot]" <269035359+t3-code[bot]@users.noreply.github.com> Date: Mon, 21 Sep 2026 23:22:36 +0000 Subject: [PATCH 08/60] chore(mobile): bump app version to 1.3.0 Co-authored-by: codex --- apps/mobile/app.config.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts index 11fb377145e35..aef812ce354b5 100644 --- a/apps/mobile/app.config.ts +++ b/apps/mobile/app.config.ts @@ -214,7 +214,7 @@ const config: ExpoConfig = { slug: "t3-code", platforms: ["ios", "android"], scheme: variant.scheme, - version: "1.2.1", + version: "1.3.0", runtimeVersion: { // Development manifests resolve on every launch, so avoid fingerprint's // expensive native-project calculation there. Preview and production stay From 1262d2f3ab2940c1d47ca4f5c4ca42e5c7259765 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 21 Sep 2026 18:15:07 -0700 Subject: [PATCH 09/60] feat(server): let t3.json limit or disable submodule init in new worktrees (#12953) Co-authored-by: Claude Fable 5 --- apps/server/src/vcs/GitVcsDriver.ts | 2 + apps/server/src/vcs/GitVcsDriverCore.test.ts | 78 ++++++++++++++++++++ apps/server/src/vcs/GitVcsDriverCore.ts | 28 ++++++- apps/server/src/ws.ts | 7 ++ docs/user/project-settings.md | 4 + packages/contracts/src/environment.ts | 7 ++ packages/contracts/src/t3ProjectFile.test.ts | 6 ++ packages/contracts/src/t3ProjectFile.ts | 8 +- packages/shared/src/t3ProjectFile.test.ts | 1 + 9 files changed, 137 insertions(+), 4 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index 2aaabeed3d7a4..040862eaf6a8a 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -128,6 +128,8 @@ export interface CreateWorktreeProgress { total: number; }) => Effect.Effect; readonly onSubmodulesStarted?: () => Effect.Effect; + /** Fires when `.gitmodules` exists but t3.json sets `worktreeSubmodules` to `"none"`. */ + readonly onSubmodulesDisabled?: () => Effect.Effect; readonly onSubmoduleLine?: (line: string) => Effect.Effect; readonly onSubmodulesFinished?: (input: { ok: boolean; diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index f798abba74b61..045f6d15cfe64 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -2353,6 +2353,84 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => { }), ); + it.effect("honors the t3.json worktreeSubmodules setting", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const pathService = yield* Path.Path; + + const previousAllowedProtocol = process.env.GIT_ALLOW_PROTOCOL; + process.env.GIT_ALLOW_PROTOCOL = "file"; + yield* Effect.addFinalizer(() => + Effect.sync(() => { + if (previousAllowedProtocol === undefined) { + delete process.env.GIT_ALLOW_PROTOCOL; + } else { + process.env.GIT_ALLOW_PROTOCOL = previousAllowedProtocol; + } + }), + ); + + // inner -> nested, so a recursive init populates nested/NESTED.md and + // a top-level init leaves it empty. + const nestedRepo = yield* makeTmpDir("git-nested-"); + yield* initRepoWithCommit(nestedRepo); + yield* writeTextFile(nestedRepo, "NESTED.md", "# nested\n"); + yield* git(nestedRepo, ["add", "."]); + yield* git(nestedRepo, ["commit", "-m", "nested"]); + const innerRepo = yield* makeTmpDir("git-inner-"); + yield* initRepoWithCommit(innerRepo); + yield* writeTextFile(innerRepo, "INNER.md", "# inner\n"); + yield* git(innerRepo, ["submodule", "add", nestedRepo, "nested"]); + yield* git(innerRepo, ["add", "."]); + yield* git(innerRepo, ["commit", "-m", "inner"]); + + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + yield* git(cwd, ["submodule", "add", innerRepo, "inner"]); + yield* git(cwd, ["commit", "-m", "add submodule"]); + const driver = yield* GitVcsDriver.GitVcsDriver; + const worktreesDir = yield* makeTmpDir("git-worktrees-"); + + const createWithMode = Effect.fn(function* ( + fileMode: "recursive" | "top-level" | "none", + branch: string, + ) { + yield* writeTextFile(cwd, "t3.json", `{ "worktreeSubmodules": "${fileMode}" }`); + yield* git(cwd, ["add", "t3.json"]); + yield* git(cwd, ["commit", "-m", `submodules: ${fileMode}`]); + const worktreePath = pathService.join(worktreesDir, branch); + const disabled = yield* Ref.make(false); + yield* driver.createWorktree( + { cwd, path: worktreePath, refName: initialBranch, newRefName: branch }, + { progress: { onSubmodulesDisabled: () => Ref.set(disabled, true) } }, + ); + return { + disabled: yield* Ref.get(disabled), + inner: yield* fileSystem.exists(pathService.join(worktreePath, "inner", "INNER.md")), + nested: yield* fileSystem.exists( + pathService.join(worktreePath, "inner", "nested", "NESTED.md"), + ), + }; + }); + + assert.deepEqual(yield* createWithMode("recursive", "recursive"), { + disabled: false, + inner: true, + nested: true, + }); + assert.deepEqual(yield* createWithMode("top-level", "top-level"), { + disabled: false, + inner: true, + nested: false, + }); + assert.deepEqual(yield* createWithMode("none", "none"), { + disabled: true, + inner: false, + nested: false, + }); + }), + ); + it.effect("reports checkout progress during parallel worktree creation", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 56cff0cb9a583..18587c9f36ef7 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -20,6 +20,7 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; import { GitCommandError, + T3_PROJECT_FILE_NAME, type ReviewDiffFileContentsInput, type ReviewDiffPreviewInput, type ReviewDiffFileStat, @@ -30,6 +31,7 @@ import { dedupeRemoteBranchesWithLocalMatches, normalizeGitRemoteUrl } from "@t3 import { HostProcessPlatform } from "@t3tools/shared/hostProcess"; import { compactTraceAttributes } from "@t3tools/shared/observability"; import { decodeJsonResult } from "@t3tools/shared/schemaJson"; +import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile"; import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../observability/Metrics.ts"; import * as GitVcsDriver from "./GitVcsDriver.ts"; import { @@ -3092,11 +3094,29 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* // skills, tooling or source in one gets a worktree that is quietly missing // them. Best-effort: the objects are usually already in the parent's // `.git/modules`, but a first-ever clone needs the network, and failing to - // populate a submodule must not roll back the caller's thread. + // populate a submodule must not roll back the caller's thread. Repos with + // hundreds of nested submodules opt out or stop at the top level through + // t3.json, read from the checkout that was just created. const hasSubmodules = yield* fileSystem .exists(path.join(worktreePath, ".gitmodules")) .pipe(Effect.orElseSucceed(() => false)); - if (hasSubmodules) { + const submoduleMode = hasSubmodules + ? yield* fileSystem.readFileString(path.join(worktreePath, T3_PROJECT_FILE_NAME)).pipe( + Effect.flatMap((contents) => { + const file = parseT3ProjectFile(contents); + return file === null + ? Effect.logWarning("t3.json is invalid; initializing submodules recursively", { + worktreePath, + }).pipe(Effect.as("recursive" as const)) + : Effect.succeed(file.worktreeSubmodules ?? "recursive"); + }), + Effect.orElseSucceed(() => "recursive" as const), + ) + : "none"; + if (hasSubmodules && submoduleMode === "none" && progress?.onSubmodulesDisabled) { + yield* progress.onSubmodulesDisabled(); + } + if (submoduleMode !== "none") { if (progress?.onSubmodulesStarted) { yield* progress.onSubmodulesStarted(); } @@ -3104,7 +3124,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* yield* runGit( "GitVcsDriver.createWorktree.updateSubmodules", worktreePath, - ["submodule", "update", "--init", "--recursive"], + submoduleMode === "recursive" + ? ["submodule", "update", "--init", "--recursive"] + : ["submodule", "update", "--init"], onSubmoduleLine ? { env: { LC_ALL: "C" }, diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 90271e00adfba..909216d893497 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -1500,6 +1500,13 @@ const makeWsRpcLayer = ( worktreeSetupTracker.stageStatus(threadId, "submodules", "running"), ), ), + onSubmodulesDisabled: () => + worktreeSetupTracker.stageStatus( + threadId, + "submodules", + "skipped", + "disabled in t3.json", + ), onSubmoduleLine: (line) => { const submodulePath = /Submodule path '([^']+)'/.exec(line)?.[1]; return submodulePath === undefined diff --git a/docs/user/project-settings.md b/docs/user/project-settings.md index 0d5d7e66b1fbe..6144bd960100f 100644 --- a/docs/user/project-settings.md +++ b/docs/user/project-settings.md @@ -52,6 +52,10 @@ on each selected environment, and reset returns to the environment's shared list For workspace mode, a project's `t3.json` preference applies when the project has no override. Browser access changes apply when an agent session next starts. +New worktrees initialize git submodules recursively. If that step is slow because the repository +declares many nested submodules, set `"worktreeSubmodules"` in `t3.json` to `"top-level"` to stop +at the ones the repository declares itself, or `"none"` to leave them for a setup script. + ## Storage cleanup Open **Settings → Storage** to enable automatic cleanup on one machine or all connected diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index 70888f2988e67..b5a3290f63144 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -58,6 +58,13 @@ export const ExecutionEnvironmentPlatform = Schema.Struct({ */ export const ThreadEnvMode = Schema.Literals(["local", "worktree"]); export type ThreadEnvMode = typeof ThreadEnvMode.Type; + +/** + * How a new worktree populates git submodules: every nested level, only the + * ones this repository declares, or not at all. + */ +export const WorktreeSubmodules = Schema.Literals(["recursive", "top-level", "none"]); +export type WorktreeSubmodules = typeof WorktreeSubmodules.Type; export type ExecutionEnvironmentPlatform = typeof ExecutionEnvironmentPlatform.Type; /** How a server can replace itself with another version when asked over RPC. diff --git a/packages/contracts/src/t3ProjectFile.test.ts b/packages/contracts/src/t3ProjectFile.test.ts index 4352449c7adef..64128a4990b0f 100644 --- a/packages/contracts/src/t3ProjectFile.test.ts +++ b/packages/contracts/src/t3ProjectFile.test.ts @@ -60,4 +60,10 @@ describe("T3ProjectFile", () => { expect(decode({ defaultThreadEnvMode: "local" }).defaultThreadEnvMode).toBe("local"); expect(() => decode({ defaultThreadEnvMode: "remote" })).toThrow(); }); + + it("decodes worktreeSubmodules and rejects unknown modes", () => { + expect(decode({ worktreeSubmodules: "none" }).worktreeSubmodules).toBe("none"); + expect(decode({ worktreeSubmodules: "top-level" }).worktreeSubmodules).toBe("top-level"); + expect(() => decode({ worktreeSubmodules: "shallow" })).toThrow(); + }); }); diff --git a/packages/contracts/src/t3ProjectFile.ts b/packages/contracts/src/t3ProjectFile.ts index 6bd4168054d50..2e31e5271f7d7 100644 --- a/packages/contracts/src/t3ProjectFile.ts +++ b/packages/contracts/src/t3ProjectFile.ts @@ -1,7 +1,7 @@ import * as Schema from "effect/Schema"; import * as SchemaTransformation from "effect/SchemaTransformation"; -import { ThreadEnvMode } from "./environment.ts"; +import { ThreadEnvMode, WorktreeSubmodules } from "./environment.ts"; import { ProjectScriptIcon } from "./orchestration.ts"; /** File name of the checked-in T3 project file, resolved at the workspace root. */ @@ -86,6 +86,12 @@ export const T3ProjectFile = Schema.Struct({ 'Where new threads start for this repository: "worktree" for a fresh git worktree, "local" for the current checkout. A per-project setting in T3 Code overrides this; when neither is set, the global default applies.', }), ), + worktreeSubmodules: Schema.optionalKey( + WorktreeSubmodules.annotate({ + description: + 'How new worktrees populate git submodules: "recursive" (the default) initializes nested submodules too, "top-level" initializes only those declared by this repository, and "none" leaves every submodule empty for a setup script to handle.', + }), + ), scripts: Schema.optionalKey( Schema.Array(T3ProjectFileScript) .annotate({ diff --git a/packages/shared/src/t3ProjectFile.test.ts b/packages/shared/src/t3ProjectFile.test.ts index 924a01c4414b5..42045cc4284f1 100644 --- a/packages/shared/src/t3ProjectFile.test.ts +++ b/packages/shared/src/t3ProjectFile.test.ts @@ -36,6 +36,7 @@ describe("buildT3ProjectFileJsonSchema", () => { "defaultThreadEnvMode", "iconPath", "scripts", + "worktreeSubmodules", ]); expect(schema.required).toBeUndefined(); expect(schema.properties.iconPath?.description).toContain("Workspace-relative path"); From 742173a13250bcba880b700aaead34e1b0810dff Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 21 Sep 2026 18:15:07 -0700 Subject: [PATCH 10/60] feat(settings): resolve t3.json inside the project settings resolver (#12954) Co-authored-by: Claude Fable 5 --- .../SettingsServerControlsRouteScreen.tsx | 25 ++++-- .../settings/settings-scoped-server.test.ts | 33 ++++++++ .../settings/settings-scoped-server.ts | 15 +++- .../threads/new-task-flow-provider.tsx | 49 +++++------- .../files/projectFilesQueryState.ts | 7 +- .../settings/ProjectDefaultsSettings.tsx | 45 ++++------- .../settings/SettingInheritance.test.ts | 37 +++++++++ .../settings/SettingInheritance.tsx | 47 +++++++++--- .../settings/SettingsScopeContext.tsx | 62 ++++++++++++++- .../settings/scopedSettings.test.ts | 47 ++++++++++++ .../src/components/settings/scopedSettings.ts | 28 ++++++- .../components/settings/settingsLayout.tsx | 12 +-- apps/web/src/hooks/useHandleNewThread.test.ts | 25 +++--- apps/web/src/hooks/useHandleNewThread.ts | 29 +++---- apps/web/src/lib/t3ProjectFileDefaults.ts | 18 ++--- docs/user/project-settings.md | 4 +- packages/contracts/src/baseSchemas.ts | 25 ++++++ packages/contracts/src/settings.test.ts | 21 +++++ packages/contracts/src/settings.ts | 34 ++++++++- packages/contracts/src/t3ProjectFile.ts | 35 +++++++++ packages/shared/package.json | 4 - packages/shared/src/projectSettings.test.ts | 76 +++++++++++++++++++ packages/shared/src/projectSettings.ts | 72 +++++++++++++++++- packages/shared/src/threadEnvMode.test.ts | 65 ---------------- packages/shared/src/threadEnvMode.ts | 36 --------- 25 files changed, 615 insertions(+), 236 deletions(-) delete mode 100644 packages/shared/src/threadEnvMode.test.ts delete mode 100644 packages/shared/src/threadEnvMode.ts diff --git a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx index 090467a8cd909..94312207714ad 100644 --- a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx @@ -50,10 +50,16 @@ const PAGE_PROJECT_KEYS: Record = [ + // Only offered at environment scope; a project falls back through "Use defaults". + { + mode: null, + label: "Inherit", + description: "Use the repository's t3.json, or the current checkout.", + }, { mode: "local", label: "Current checkout", @@ -126,6 +132,10 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) { const value = reference.settings[key]; return displayTargets.every((entry) => entry.settings[key] === value) ? value : null; }; + // `uniform` folds a real null into "mixed"; nullable keys need the distinction. + const isMixed = (key: keyof ServerSettings) => + reference === null || + displayTargets.some((entry) => entry.settings[key] !== reference.settings[key]); const updateSettings = useAtomCommand(serverEnvironment.updateSettings, { label: "environment settings update", reportFailure: true, @@ -219,17 +229,22 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) { ) : null } > - {WORKSPACE_CHOICES.map((choice, index) => ( + {WORKSPACE_CHOICES.filter( + (choice) => choice.mode !== null || !projectSelected, + ).map((choice, index) => ( 0} disabled={disabledFor("defaultThreadEnvMode")} onPress={() => write({ defaultThreadEnvMode: choice.mode })} diff --git a/apps/mobile/src/features/settings/settings-scoped-server.test.ts b/apps/mobile/src/features/settings/settings-scoped-server.test.ts index dd589cd2038c6..185fb07e602fd 100644 --- a/apps/mobile/src/features/settings/settings-scoped-server.test.ts +++ b/apps/mobile/src/features/settings/settings-scoped-server.test.ts @@ -69,6 +69,39 @@ describe("mobile project settings scope", () => { expect(secondSettings.responseStreamingMode).toBe("token"); }); + it("removes a project override when a picker sends null for a key that cannot store it", () => { + const settings: ServerSettings = { + ...DEFAULT_SERVER_SETTINGS, + projectSettingsOverrides: { + [firstProject]: { defaultThreadEnvMode: "worktree", defaultAutoPull: true }, + }, + }; + const targets = resolveMobileSettingsTargets( + [environment(firstId, settings)], + [{ environmentId: firstId, id: firstProject }], + ); + expect(planMobileScopedSettingsPatch(targets, true, { defaultThreadEnvMode: null })).toEqual([ + { + environmentId: firstId, + patch: { projectSettingsOverrides: { [firstProject]: { defaultAutoPull: true } } }, + }, + ]); + expect(planMobileScopedSettingsPatch(targets, true, { defaultModelSelection: null })).toEqual([ + { + environmentId: firstId, + patch: { + projectSettingsOverrides: { + [firstProject]: { + defaultThreadEnvMode: "worktree", + defaultAutoPull: true, + defaultModelSelection: null, + }, + }, + }, + }, + ]); + }); + it("resets only the selected page's override and rejects environment-wide writes", () => { const settings: ServerSettings = { ...DEFAULT_SERVER_SETTINGS, diff --git a/apps/mobile/src/features/settings/settings-scoped-server.ts b/apps/mobile/src/features/settings/settings-scoped-server.ts index 53cc44a7ee1c9..01020a3eb221c 100644 --- a/apps/mobile/src/features/settings/settings-scoped-server.ts +++ b/apps/mobile/src/features/settings/settings-scoped-server.ts @@ -1,4 +1,5 @@ import { + isNullableProjectSettingsOverride, PROJECT_SCOPED_SERVER_SETTING_KEYS, type EnvironmentId, type ProjectId, @@ -69,7 +70,19 @@ export function planMobileScopedSettingsPatch( continue; const current = target.environment.serverConfig.settings.projectSettingsOverrides[target.projectId] ?? {}; - const next = { ...current, ...patch }; + const next: Record = { ...current }; + for (const [key, value] of Object.entries(patch)) { + // A picker's "Inherit" sends null; for keys whose override cannot + // store null that means remove the override. + if ( + value === null && + !isNullableProjectSettingsOverride(key as ProjectScopedServerSettingKey) + ) { + delete next[key]; + } else { + next[key] = value; + } + } const overrides = writes.get(target.environment.environmentId) ?? {}; overrides[target.projectId] = next; writes.set(target.environment.environmentId, overrides); diff --git a/apps/mobile/src/features/threads/new-task-flow-provider.tsx b/apps/mobile/src/features/threads/new-task-flow-provider.tsx index 4a912f171a556..f2801255b3bcd 100644 --- a/apps/mobile/src/features/threads/new-task-flow-provider.tsx +++ b/apps/mobile/src/features/threads/new-task-flow-provider.tsx @@ -20,10 +20,6 @@ import { } from "@t3tools/contracts"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile"; -import { - isDefaultThreadEnvModeSettled, - resolveDefaultThreadEnvMode, -} from "@t3tools/shared/threadEnvMode"; import * as Arr from "effect/Array"; import { pipe } from "effect/Function"; @@ -431,38 +427,35 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) { : null, ); const t3ProjectFileData = t3ProjectFileQuery.data as ProjectReadFileResult | null; - const t3ProjectFileDefaultMode = useMemo(() => { - if (t3ProjectFileData === null || t3ProjectFileData.truncated) return null; - return parseT3ProjectFile(t3ProjectFileData.contents)?.defaultThreadEnvMode ?? null; - }, [t3ProjectFileData]); - // Environment settings with the project's overrides applied; the - // aggregate's own legacy fields still count until the server folds them. + const t3ProjectFile = useMemo( + () => + t3ProjectFileData === null || t3ProjectFileData.truncated + ? null + : parseT3ProjectFile(t3ProjectFileData.contents), + [t3ProjectFileData], + ); + // Environment settings with the project's overrides and its t3.json + // applied; the aggregate's own legacy fields still count until the server + // folds them. const projectSettings = useMemo( () => resolveProjectSettings( selectedEnvironmentServerConfig?.settings ?? DEFAULT_SERVER_SETTINGS, selectedProject?.id ?? null, selectedProject, + t3ProjectFile, ), - [selectedEnvironmentServerConfig?.settings, selectedProject], + [selectedEnvironmentServerConfig?.settings, selectedProject, t3ProjectFile], ); - const projectThreadEnvMode = - projectSettings.sources.defaultThreadEnvMode === "project" - ? projectSettings.settings.defaultThreadEnvMode - : undefined; - const defaultWorkspaceMode: WorkspaceMode = resolveDefaultThreadEnvMode({ - projectSetting: projectThreadEnvMode, - projectFile: t3ProjectFileDefaultMode, - globalDefault: projectSettings.settings.defaultThreadEnvMode, - }); - // While unsettled the resolved default is provisional. Nothing may write - // it into the draft during that window (the auto-branch effect does), or - // the frozen interim value beats the t3.json default once it loads. - const defaultWorkspaceModeSettled = isDefaultThreadEnvModeSettled({ - explicitMode: selectedProjectDraft.workspaceSelection?.mode, - projectSetting: projectThreadEnvMode, - projectFilePending: t3ProjectFileQuery.isPending, - }); + const defaultWorkspaceMode: WorkspaceMode = projectSettings.settings.defaultThreadEnvMode; + // While the file read is pending and nothing above it decided, the + // resolved default is provisional. Nothing may write it into the draft + // during that window (the auto-branch effect does), or the frozen interim + // value beats the t3.json default once it loads. + const defaultWorkspaceModeSettled = + selectedProjectDraft.workspaceSelection?.mode !== undefined || + projectSettings.sources.defaultThreadEnvMode !== "environment" || + !t3ProjectFileQuery.isPending; const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? defaultWorkspaceMode; const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null; const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null; diff --git a/apps/web/src/components/files/projectFilesQueryState.ts b/apps/web/src/components/files/projectFilesQueryState.ts index b9a8803018317..a6a556231e189 100644 --- a/apps/web/src/components/files/projectFilesQueryState.ts +++ b/apps/web/src/components/files/projectFilesQueryState.ts @@ -20,7 +20,12 @@ const EMPTY_PROJECT_FILE_PATH = ""; const EMPTY_PROJECT_FILE_QUERY_ATOM = Atom.make( AsyncResult.initial(false), ).pipe(Atom.withLabel("project-file-query:empty")); -function optimisticFileAtom(environmentId: EnvironmentId, cwd: string, relativePath: string) { +/** A pending in-app write to the file, overlaying the query until confirmed. */ +export function optimisticFileAtom( + environmentId: EnvironmentId, + cwd: string, + relativePath: string, +) { return projectEnvironment.optimisticFile({ environmentId, cwd, relativePath }); } diff --git a/apps/web/src/components/settings/ProjectDefaultsSettings.tsx b/apps/web/src/components/settings/ProjectDefaultsSettings.tsx index a08b918be4c5f..d49eaa5cbf85d 100644 --- a/apps/web/src/components/settings/ProjectDefaultsSettings.tsx +++ b/apps/web/src/components/settings/ProjectDefaultsSettings.tsx @@ -1,13 +1,12 @@ import { DEFAULT_SERVER_SETTINGS, - EnvironmentId, type ModelSelection, type ProviderInstanceId, } from "@t3tools/contracts"; import { createModelSelection } from "@t3tools/shared/model"; +import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { useNavigate } from "@tanstack/react-router"; -import { useT3ProjectFileState } from "../../hooks/useT3ProjectFileScripts"; import { getCustomModelOptionsByInstance } from "../../modelSelection"; import { applyProviderInstanceSettings, @@ -75,25 +74,16 @@ export function ProjectDefaultsSettings({ category }: { category: ProjectSetting const mixedAutoPull = useScopedSettingsMixed(["defaultAutoPull"]); const mixedMergeMethod = useScopedSettingsMixed(["pullRequestMergeMethod"]); const modelSource = useScopedSettingSource(["defaultModelSelection"]); - const workspaceSource = useScopedSettingSource(["defaultThreadEnvMode"]); const isProjectScope = scope.kind === "project" || scope.kind === "checkout"; const unavailable = connectedEnvironments.length === 0; - - // A checkout's t3.json wins over the environment default when the project - // has no override of its own; show which one "inherit" resolves to. - const checkout = scope.kind === "checkout" ? scope.checkout : null; - // The query is disabled without a checkout, so any id satisfies the hook. - const t3File = useT3ProjectFileState( - checkout?.environmentId ?? EnvironmentId.make("none"), - category === "general" && checkout ? checkout.workspaceRoot : null, - ); - const repositoryEnvMode = t3File.file?.defaultThreadEnvMode ?? null; - const inheritedEnvModeLabel = - workspaceSource === "project" - ? null - : repositoryEnvMode - ? `${resolveEnvModeLabel(repositoryEnvMode)} (t3.json)` - : null; + // File-backed keys show their effective value; the target already carries + // the checkout's t3.json, and a null file here only fills the built-in. + // The reset arrow beside the title clears the tier (SettingsRow handles a + // project override, the environment value is cleared here), so the picker + // has no "inherit" item. + const effective = target + ? resolveProjectSettings(target.settings, null, null, null).settings + : null; function modelDisabledReason(instanceId: ProviderInstanceId, model: string): string | null { const sourceEntry = entries.find((entry) => entry.instanceId === instanceId); @@ -292,27 +282,20 @@ export function ProjectDefaultsSettings({ category }: { category: ProjectSetting title="Workspace" description={ isProjectScope - ? "Where new threads in this project start. A t3.json preference applies when the project has no override." - : "Where new threads start, unless overridden by the project or t3.json." - } - status={ - inheritedEnvModeLabel ? `Repository default: ${inheritedEnvModeLabel}` : undefined + ? "Where new threads in this project start." + : "Where new threads start. Projects and their t3.json can override it." } resetAction={ - settings.defaultThreadEnvMode !== DEFAULT_SERVER_SETTINGS.defaultThreadEnvMode ? ( + !isProjectScope && settings.defaultThreadEnvMode !== null ? ( - updateSettings({ - defaultThreadEnvMode: DEFAULT_SERVER_SETTINGS.defaultThreadEnvMode, - }) - } + onClick={() => updateSettings({ defaultThreadEnvMode: null })} /> ) : null } control={ } /> + updateSettings({ worktreeSubmodules: null })} + /> + ) : null + } + control={ + + } + /> ) : category === "source-control" ? ( <> diff --git a/apps/web/src/components/settings/SettingInheritance.tsx b/apps/web/src/components/settings/SettingInheritance.tsx index 623e830561558..a351fa5fa25b3 100644 --- a/apps/web/src/components/settings/SettingInheritance.tsx +++ b/apps/web/src/components/settings/SettingInheritance.tsx @@ -4,6 +4,7 @@ import { type ProjectFileBackedSettingKey, resolveEnvironmentMachineKind, type ServerSettings, + type WorktreeSubmodules, } from "@t3tools/contracts"; import { CheckIcon, LayersIcon } from "lucide-react"; import * as Equal from "effect/Equal"; @@ -11,7 +12,7 @@ import * as Equal from "effect/Equal"; import { cn } from "../../lib/utils"; import type { EnvironmentPresentation } from "../../state/environments"; import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon"; -import { resolveEnvModeLabel } from "../BranchToolbar.logic"; +import { resolveEnvModeLabel, WORKTREE_SUBMODULES_LABELS } from "../BranchToolbar.logic"; import { PULL_REQUEST_MERGE_METHOD_LABELS } from "../pullRequest/pullRequestDetail.logic"; import { Button, InlineButton } from "../ui/button"; import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover"; @@ -44,7 +45,7 @@ function formatValue(key: keyof ServerSettings, value: unknown): string { ? "Automatic" : key === "sourceControlWriterModelSelection" ? "Text generation model" - : key === "defaultThreadEnvMode" + : key === "defaultThreadEnvMode" || key === "worktreeSubmodules" ? "Inherit" : "Not set"; } @@ -58,6 +59,9 @@ function formatValue(key: keyof ServerSettings, value: unknown): string { if (key === "defaultThreadEnvMode" && (value === "local" || value === "worktree")) { return resolveEnvModeLabel(value); } + if (key === "worktreeSubmodules" && value in WORKTREE_SUBMODULES_LABELS) { + return WORKTREE_SUBMODULES_LABELS[value as WorktreeSubmodules]; + } if (key === "pullRequestMergeMethod" && value in PULL_REQUEST_MERGE_METHOD_LABELS) { return PULL_REQUEST_MERGE_METHOD_LABELS[ value as keyof typeof PULL_REQUEST_MERGE_METHOD_LABELS diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 88f0326ea9e0c..acc9b7eb7dbe6 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -401,6 +401,13 @@ export const SETTINGS_SEARCH_ITEMS = [ scope: "project-defaults", searchTerms: ["default workspace mode draft local worktree"], }, + { + id: "worktree-submodules", + title: "Submodules", + to: "/settings/general", + scope: "project-defaults", + searchTerms: ["git submodule init recursive top-level none worktree t3.json"], + }, { id: "start-from-origin", title: "Start from origin", diff --git a/docs/user/project-settings.md b/docs/user/project-settings.md index 363b2a4583a41..b5ad7c6514d19 100644 --- a/docs/user/project-settings.md +++ b/docs/user/project-settings.md @@ -55,8 +55,11 @@ built-in default. Leave a setting on **Inherit** to let the next tier decide. Browser access changes apply when an agent session next starts. New worktrees initialize git submodules recursively. If that step is slow because the repository -declares many nested submodules, set `"worktreeSubmodules"` in `t3.json` to `"top-level"` to stop -at the ones the repository declares itself, or `"none"` to leave them for a setup script. +declares many nested submodules, set **Submodules** in **Settings → General** (with the project +selected to override it there) to **Top level only** to stop at the ones the repository declares +itself, or **Skip** to leave them for a setup script. It resolves in the same order as the +workspace default: a `"worktreeSubmodules"` value in the `t3.json` of the branch being checked out +applies when the project and environment are both on **Inherit**. ## Storage cleanup diff --git a/packages/contracts/src/settings.test.ts b/packages/contracts/src/settings.test.ts index 007d04505c86c..692edfb18a658 100644 --- a/packages/contracts/src/settings.test.ts +++ b/packages/contracts/src/settings.test.ts @@ -835,6 +835,15 @@ describe("ServerSettings worktree defaults", () => { decodeServerSettingsPatch({ newWorktreesStartFromOrigin: false }).newWorktreesStartFromOrigin, ).toBe(false); }); + + it("defaults worktree submodules to inherit and tolerates unknown modes", () => { + expect(decodeServerSettings({}).worktreeSubmodules).toBeNull(); + expect(decodeServerSettings({ worktreeSubmodules: "top-level" }).worktreeSubmodules).toBe( + "top-level", + ); + expect(decodeServerSettings({ worktreeSubmodules: "shallow" }).worktreeSubmodules).toBeNull(); + expect(decodeServerSettingsPatch({ worktreeSubmodules: null }).worktreeSubmodules).toBeNull(); + }); }); describe("ServerSettings.sourceControlWritingStyle", () => { diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 4a57f6680fb19..504a9423f2a37 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -5,13 +5,14 @@ import * as Schema from "effect/Schema"; import * as SchemaTransformation from "effect/SchemaTransformation"; import { ForwardCompatibleNullable, + ForwardCompatibleOptional, OmittedWhenNull, ProjectId, TrimmedNonEmptyString, TrimmedString, } from "./baseSchemas.ts"; import { UsageLimitSourceId } from "./usageLimitSourceId.ts"; -import { EnvironmentMachineKind, ThreadEnvMode } from "./environment.ts"; +import { EnvironmentMachineKind, ThreadEnvMode, WorktreeSubmodules } from "./environment.ts"; import { KeybindingShortcut } from "./keybindings.ts"; import { CustomModelSetting, @@ -1001,6 +1002,7 @@ export const PROJECT_SCOPED_SERVER_SETTING_KEYS = [ "defaultRuntimeMode", "defaultThreadEnvMode", "newWorktreesStartFromOrigin", + "worktreeSubmodules", "defaultAutoPull", "defaultProjectScripts", "enableAgentBrowserAccess", @@ -1027,6 +1029,7 @@ export const ProjectSettingsOverrides = Schema.Struct({ defaultRuntimeMode: Schema.optionalKey(RuntimeMode), defaultThreadEnvMode: Schema.optionalKey(ThreadEnvMode), newWorktreesStartFromOrigin: Schema.optionalKey(Schema.Boolean), + worktreeSubmodules: ForwardCompatibleOptional(WorktreeSubmodules), defaultAutoPull: Schema.optionalKey(Schema.Boolean), defaultProjectScripts: Schema.optionalKey(Schema.Array(ProjectScript)), enableAgentBrowserAccess: Schema.optionalKey(Schema.Boolean), @@ -1208,6 +1211,14 @@ export const ServerSettings = Schema.Struct({ newWorktreesStartFromOrigin: Schema.Boolean.pipe( Schema.withDecodingDefault(Effect.succeed(true)), ), + /** + * Null defers to the repository's t3.json, then to recursive. A value + * picked on a newer server decodes as null here rather than failing the + * whole settings snapshot for an older client. + */ + worktreeSubmodules: ForwardCompatibleNullable(WorktreeSubmodules).pipe( + Schema.withDecodingDefault(Effect.succeed(null)), + ), addProjectBaseDirectory: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))), textGenerationModelSelection: ModelSelection.pipe( Schema.withDecodingDefault( @@ -1499,6 +1510,7 @@ export const ServerSettingsPatch = Schema.Struct({ environmentIcon: Schema.optionalKey(Schema.NullOr(EnvironmentMachineKind)), defaultThreadEnvMode: Schema.optionalKey(Schema.NullOr(ThreadEnvMode)), newWorktreesStartFromOrigin: Schema.optionalKey(Schema.Boolean), + worktreeSubmodules: Schema.optionalKey(Schema.NullOr(WorktreeSubmodules)), addProjectBaseDirectory: Schema.optionalKey(TrimmedString), textGenerationModelSelection: Schema.optionalKey(ModelSelectionPatch), sourceControlWritingStyle: Schema.optionalKey( diff --git a/packages/contracts/src/t3ProjectFile.ts b/packages/contracts/src/t3ProjectFile.ts index 53294a9759b36..536ac77880aa4 100644 --- a/packages/contracts/src/t3ProjectFile.ts +++ b/packages/contracts/src/t3ProjectFile.ts @@ -90,7 +90,7 @@ export const T3ProjectFile = Schema.Struct({ worktreeSubmodules: Schema.optionalKey( WorktreeSubmodules.annotate({ description: - 'How new worktrees populate git submodules: "recursive" (the default) initializes nested submodules too, "top-level" initializes only those declared by this repository, and "none" leaves every submodule empty for a setup script to handle.', + 'How new worktrees populate git submodules: "recursive" (the default) initializes nested submodules too, "top-level" initializes only those declared by this repository, and "none" leaves every submodule empty for a setup script to handle. A project or environment setting in T3 Code overrides this.', }), ), scripts: Schema.optionalKey( @@ -118,6 +118,7 @@ export type T3ProjectFile = typeof T3ProjectFile.Type; */ export const PROJECT_FILE_BACKED_SETTINGS = { defaultThreadEnvMode: { field: "defaultThreadEnvMode", builtIn: "local" }, + worktreeSubmodules: { field: "worktreeSubmodules", builtIn: "recursive" }, } as const satisfies { readonly [K in ProjectScopedServerSettingKey]?: { readonly field: { diff --git a/packages/shared/src/projectSettings.test.ts b/packages/shared/src/projectSettings.test.ts index c4c02660a311a..f59156530aa5b 100644 --- a/packages/shared/src/projectSettings.test.ts +++ b/packages/shared/src/projectSettings.test.ts @@ -9,6 +9,7 @@ import { createModelSelection } from "./model.ts"; import { clearProjectSettingsOverrides, hasProjectSettingsOverrides, + resolveProjectFileBackedSetting, resolveProjectSettings, resolveWorktreeCleanup, withProjectSettingsOverrides, @@ -187,6 +188,23 @@ describe("resolveProjectSettings with a t3.json", () => { ).toBe("environment"); }); + it("resolves one key from the settings tier, then the file, then the built-in", () => { + expect( + resolveProjectFileBackedSetting("worktreeSubmodules", "none", { + worktreeSubmodules: "top-level", + }), + ).toEqual({ value: "none", source: "environment" }); + expect( + resolveProjectFileBackedSetting("worktreeSubmodules", null, { + worktreeSubmodules: "top-level", + }), + ).toEqual({ value: "top-level", source: "t3.json" }); + expect(resolveProjectFileBackedSetting("worktreeSubmodules", null, null)).toEqual({ + value: "recursive", + source: "environment", + }); + }); + it("leaves settings untouched when no file is passed", () => { expect(resolveProjectSettings(DEFAULT_SERVER_SETTINGS, projectId).settings).toBe( DEFAULT_SERVER_SETTINGS, diff --git a/packages/shared/src/projectSettings.ts b/packages/shared/src/projectSettings.ts index 967f3bc6b0c50..f99dacbbb69df 100644 --- a/packages/shared/src/projectSettings.ts +++ b/packages/shared/src/projectSettings.ts @@ -2,6 +2,7 @@ import { type ModelSelection, PROJECT_FILE_BACKED_SETTINGS, PROJECT_SCOPED_SERVER_SETTING_KEYS, + type ProjectFileBackedSettingKey, type ProjectId, type ProjectScopedServerSettingKey, type ProjectSettingsOverrides, @@ -104,22 +105,42 @@ function applyProjectFile( ): ResolvedProjectSettings { let effective: Record | null = null; let sources: Record | null = null; - for (const [key, { field, builtIn }] of Object.entries(PROJECT_FILE_BACKED_SETTINGS)) { - const settingKey = key as ProjectScopedServerSettingKey; - if (resolved.settings[settingKey] !== null) continue; - const fromFile = projectFile?.[field]; + for (const key of Object.keys(PROJECT_FILE_BACKED_SETTINGS) as ProjectFileBackedSettingKey[]) { + if (resolved.settings[key] !== null) continue; + const { value, source } = resolveProjectFileBackedSetting(key, null, projectFile); effective ??= { ...resolved.settings }; sources ??= { ...resolved.sources }; - effective[settingKey] = fromFile ?? builtIn; + effective[key] = value; // A project override of null defers like an unset one, so the value did // not come from the project either way. - sources[settingKey] = fromFile === undefined ? "environment" : "t3.json"; + sources[key] = source; } return effective === null || sources === null ? resolved : { ...resolved, settings: effective as ServerSettings, sources }; } +/** + * The file and built-in tiers for one key, given the project-over-environment + * value (`null` when neither is set). For callers that hold the settings tier + * but only see the file later, such as the git driver reading the t3.json of + * the checkout it just created. Same chain as `resolveProjectSettings`. + */ +export function resolveProjectFileBackedSetting( + key: K, + setting: ServerSettings[K], + projectFile: T3ProjectFile | null, +): { value: ResolvedServerSettings[K]; source: ProjectSettingSource } { + if (setting !== null) { + return { value: setting as ResolvedServerSettings[K], source: "environment" }; + } + const { field, builtIn } = PROJECT_FILE_BACKED_SETTINGS[key]; + const fromFile = projectFile?.[field] as ResolvedServerSettings[K] | undefined; + return fromFile === undefined + ? { value: builtIn as ResolvedServerSettings[K], source: "environment" } + : { value: fromFile, source: "t3.json" }; +} + function resolveProjectOverrides( settings: ServerSettings, projectId: ProjectId | null, From 9a609a4e444ba739d6fcd607769d68b679b0bcc5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 21 Sep 2026 18:52:08 -0700 Subject: [PATCH 12/60] fix(web): show thread undo notice in the sidebar (#12972) --- apps/web/src/components/ChatView.tsx | 12 -- apps/web/src/components/Sidebar.tsx | 40 +---- .../src/components/sidebar/SidebarChrome.tsx | 2 + .../sidebar/SidebarThreadUndoNotice.tsx | 30 ++++ apps/web/src/components/ui/alert.tsx | 2 + .../src/hooks/showThreadUndoNotice.test.ts | 152 ++++++++++++++++++ apps/web/src/hooks/showThreadUndoNotice.ts | 106 ++++++++++++ apps/web/src/hooks/showUndoToast.test.ts | 127 --------------- apps/web/src/hooks/showUndoToast.ts | 87 ---------- apps/web/src/hooks/threadUndo.ts | 19 ++- apps/web/src/hooks/useThreadActions.ts | 47 ++---- .../src/hooks/useThreadActions.undo.test.ts | 71 ++++---- apps/web/src/routes/_chat.tsx | 14 ++ docs/user/keybindings.md | 9 +- 14 files changed, 378 insertions(+), 340 deletions(-) create mode 100644 apps/web/src/components/sidebar/SidebarThreadUndoNotice.tsx create mode 100644 apps/web/src/hooks/showThreadUndoNotice.test.ts create mode 100644 apps/web/src/hooks/showThreadUndoNotice.ts delete mode 100644 apps/web/src/hooks/showUndoToast.test.ts delete mode 100644 apps/web/src/hooks/showUndoToast.ts diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index c9540e4a0a84a..981f6f2c04af2 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -230,7 +230,6 @@ import { import { BranchToolbar, type BranchToolbarHandle } from "./BranchToolbar"; import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings"; import { isEditableFocused } from "../lib/editableFocus"; -import { undoLatestThreadAction } from "../hooks/showUndoToast"; import ThreadTerminalDrawer from "./ThreadTerminalDrawer"; import { AlarmClockIcon, @@ -6731,17 +6730,6 @@ export default function ChatView(props: ChatViewProps) { return; } - if (command === "thread.undo") { - // Only claim the chord when there is an Undo to run; otherwise the - // page keeps its native behavior for the key. - if (event.repeat) return; - if (undoLatestThreadAction()) { - event.preventDefault(); - event.stopPropagation(); - } - return; - } - if (command === "thread.pin") { event.preventDefault(); event.stopPropagation(); diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 23c55fe8eccea..6341b34b37681 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -3077,9 +3077,7 @@ export default function Sidebar() { settlingThreadKeysRef.current.add(threadKey); try { const navigateAfterSettle = planForwardNavigation(threadKey, opts.coSettlingKeys); - const result = await settleThread(threadRef, { - undoToast: opts.coSettlingKeys === undefined, - }); + const result = await settleThread(threadRef); if (result._tag === "Failure") { // Never navigate away from a thread that did not settle. if (!isAtomCommandInterrupted(result)) { @@ -3731,9 +3729,7 @@ export default function Sidebar() { // Snoozing the open thread moves you forward, same as settle — // both park the thread you're done with for now. const navigateAfterSnooze = planForwardNavigation(threadKey, opts.coSnoozingKeys); - const result = await snoozeThread(threadRef, preset.snoozedUntil, { - undoToast: opts.coSnoozingKeys === undefined, - }); + const result = await snoozeThread(threadRef, preset.snoozedUntil); if (result._tag === "Failure") { // Never navigate away from a thread that did not snooze. return isAtomCommandInterrupted(result) @@ -3887,35 +3883,15 @@ export default function Sidebar() { outcome.status === "failure" ? [outcome.error] : [], ); - if (snoozedThreadRefs.length > 0) { - const snoozedCount = snoozedThreadRefs.length; - const failedCount = failures.length; - toastManager.add( - stackedThreadToast({ - type: failedCount > 0 ? "warning" : "success", - title: - failedCount > 0 - ? `Snoozed ${snoozedCount} of ${selectedThreads.length} threads` - : `Snoozed ${snoozedCount} thread${snoozedCount === 1 ? "" : "s"}`, - description: - failedCount > 0 - ? `${failedCount} thread${failedCount === 1 ? "" : "s"} couldn't be snoozed.` - : undefined, - timeout: 5_000, - actionProps: { - children: "Undo", - onClick: () => { - for (const threadRef of snoozedThreadRefs) attemptUnsnooze(threadRef); - }, - }, - }), - ); - } else if (failures.length > 0) { + if (failures.length > 0) { const firstError = failures[0]; toastManager.add( stackedThreadToast({ type: "error", - title: "Failed to snooze threads", + title: + snoozedThreadRefs.length > 0 + ? `Failed to snooze ${failures.length} thread${failures.length === 1 ? "" : "s"}` + : "Failed to snooze threads", description: firstError instanceof Error ? firstError.message : "An error occurred.", }), @@ -4019,7 +3995,6 @@ export default function Sidebar() { }, [ attemptSettle, - attemptSnooze, attemptUnpin, clearSelection, confirmThreadDelete, @@ -4028,7 +4003,6 @@ export default function Sidebar() { performSnooze, removeFromSelection, serverConfigs, - attemptUnsnooze, updateThreadMetadata, timestampFormat, ], diff --git a/apps/web/src/components/sidebar/SidebarChrome.tsx b/apps/web/src/components/sidebar/SidebarChrome.tsx index 22ebf1831e047..6433a1cba81af 100644 --- a/apps/web/src/components/sidebar/SidebarChrome.tsx +++ b/apps/web/src/components/sidebar/SidebarChrome.tsx @@ -26,6 +26,7 @@ import { } from "../ui/sidebar"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { readPullRequestListPreferences } from "../pullRequest/pullRequestListPreferences"; +import { SidebarThreadUndoNotice } from "./SidebarThreadUndoNotice"; import { SidebarProviderUpdatePill } from "./SidebarProviderUpdatePill"; import { SidebarUpdateArchitectureWarning, SidebarUpdatePill } from "./SidebarUpdatePill"; import { PullRequestGlyph } from "~/components/pullRequest/pullRequestIcons"; @@ -221,6 +222,7 @@ export const SidebarUtilityMenu = memo(function SidebarUtilityMenu() { export const SidebarChromeFooter = memo(function SidebarChromeFooter() { return ( + diff --git a/apps/web/src/components/sidebar/SidebarThreadUndoNotice.tsx b/apps/web/src/components/sidebar/SidebarThreadUndoNotice.tsx new file mode 100644 index 0000000000000..74f767f05d9aa --- /dev/null +++ b/apps/web/src/components/sidebar/SidebarThreadUndoNotice.tsx @@ -0,0 +1,30 @@ +import { useAtomValue } from "@effect/atom-react"; + +import { undoLatestThreadAction, useThreadUndoNotice } from "../../hooks/showThreadUndoNotice"; +import { shortcutLabelForCommand } from "../../keybindings"; +import { primaryServerKeybindingsAtom } from "../../state/server"; +import { Alert, AlertDescription } from "../ui/alert"; +import { InlineButton } from "../ui/button"; + +export function SidebarThreadUndoNotice() { + const notice = useThreadUndoNotice((state) => state.notice); + const keybindings = useAtomValue(primaryServerKeybindingsAtom); + + if (!notice) return null; + const shortcut = shortcutLabelForCommand(keybindings, "thread.undo"); + + return ( + + + {notice.action} {notice.count} thread{notice.count === 1 ? "" : "s"},{" "} + + {shortcut ? `${shortcut} to undo` : "Undo"} + + + + ); +} diff --git a/apps/web/src/components/ui/alert.tsx b/apps/web/src/components/ui/alert.tsx index d071fd2dad53a..e2a08066e6c05 100644 --- a/apps/web/src/components/ui/alert.tsx +++ b/apps/web/src/components/ui/alert.tsx @@ -11,6 +11,8 @@ const alertVariants = cva("relative rounded-xl border px-3.5 py-3 text-card-fore variants: { variant: { default: "bg-transparent dark:bg-input/32 [&_svg]:text-muted-foreground", + sidebar: + "rounded-lg border-sidebar-border bg-sidebar-control-surface px-2 py-1.5 text-[11px] leading-4 [&_[data-slot=alert-description]]:block [&_[data-slot=alert-description]]:text-sidebar-muted-foreground", error: "border-error/32 bg-error-surface text-error-foreground [&_[data-slot=alert-description]]:text-error-foreground/80 [&_svg]:text-error", info: "border-info/32 bg-info/4 [&_svg]:text-info", diff --git a/apps/web/src/hooks/showThreadUndoNotice.test.ts b/apps/web/src/hooks/showThreadUndoNotice.test.ts new file mode 100644 index 0000000000000..aceb70c21d9c2 --- /dev/null +++ b/apps/web/src/hooks/showThreadUndoNotice.test.ts @@ -0,0 +1,152 @@ +import { AsyncResult } from "effect/unstable/reactivity"; +import * as Cause from "effect/Cause"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; + +import { toastManager } from "../components/ui/toast"; +import { + showThreadUndoNotice, + undoLatestThreadAction, + useThreadUndoNotice, +} from "./showThreadUndoNotice"; +import * as ThreadUndo from "./threadUndo"; + +beforeEach(() => vi.useFakeTimers()); +afterEach(() => { + vi.runAllTimers(); + vi.useRealTimers(); + vi.restoreAllMocks(); +}); + +function setup() { + const add = vi.spyOn(toastManager, "add").mockReturnValue("error-toast"); + const undo = vi.fn(async () => AsyncResult.success(undefined)); + const claim = ThreadUndo.begin("pin", "env/thread"); + const options = { action: "Unpinned" as const, failureTitle: "Restore failed", undo, claim }; + return { add, undo, claim, options }; +} + +function notice() { + const value = useThreadUndoNotice.getState().notice; + if (!value) throw new Error("Undo notice is missing"); + return value; +} + +describe("thread undo notice", () => { + it("aggregates consecutive actions without success toasts and restores the group once", async () => { + const { add, undo, options } = setup(); + showThreadUndoNotice({ + ...options, + action: "Settled", + claim: ThreadUndo.begin("settle", "env/a"), + }); + showThreadUndoNotice({ + ...options, + action: "Settled", + claim: ThreadUndo.begin("settle", "env/b"), + }); + expect(notice()).toMatchObject({ action: "Settled", count: 2 }); + expect(add).not.toHaveBeenCalled(); + const group = notice(); + await group.undo(); + await group.undo(); + expect(undo).toHaveBeenCalledTimes(2); + expect(undoLatestThreadAction()).toBe(false); + }); + + it("drops invalidated claims immediately and rejects a captured stale undo", async () => { + const { undo, options } = setup(); + showThreadUndoNotice(options); + const stale = notice(); + ThreadUndo.invalidate("pin", "env/thread"); + expect(useThreadUndoNotice.getState().notice).toBeNull(); + showThreadUndoNotice({ ...options, claim: ThreadUndo.begin("pin", "env/thread") }); + await stale.undo(); + expect(undo).not.toHaveBeenCalled(); + await notice().undo(); + expect(undo).toHaveBeenCalledOnce(); + }); + + it("does not show a notice for a late completion after a newer action", () => { + const { add, options } = setup(); + ThreadUndo.invalidate("pin", "env/thread"); + showThreadUndoNotice(options); + expect(useThreadUndoNotice.getState().notice).toBeNull(); + expect(add).not.toHaveBeenCalled(); + }); + + it("keeps the group available until five seconds after the latest action", async () => { + const { undo, claim, options } = setup(); + showThreadUndoNotice(options); + vi.advanceTimersByTime(4_000); + const second = ThreadUndo.begin("pin", "env/second"); + showThreadUndoNotice({ ...options, claim: second }); + const group = notice(); + vi.advanceTimersByTime(4_999); + expect(notice().count).toBe(2); + vi.advanceTimersByTime(1); + expect(useThreadUndoNotice.getState().notice).toBeNull(); + expect(claim.isCurrent()).toBe(false); + expect(second.isCurrent()).toBe(false); + await group.undo(); + expect(undo).not.toHaveBeenCalled(); + }); + + it("reports a failed restore and releases its claim", async () => { + const { add, claim, options } = setup(); + showThreadUndoNotice({ + ...options, + undo: async () => AsyncResult.failure(Cause.fail(new Error("offline"))), + }); + await notice().undo(); + expect(add).toHaveBeenLastCalledWith( + expect.objectContaining({ type: "error", title: "Restore failed", description: "offline" }), + ); + expect(claim.isCurrent()).toBe(false); + }); + + it("reports a rejected restore promise", async () => { + const { add, options } = setup(); + showThreadUndoNotice({ + ...options, + undo: async () => { + throw new Error("disconnected"); + }, + }); + await notice().undo(); + expect(add).toHaveBeenLastCalledWith( + expect.objectContaining({ type: "error", description: "disconnected" }), + ); + }); + + it("does not report interrupted restores as errors", async () => { + const { add, options } = setup(); + showThreadUndoNotice({ ...options, undo: async () => AsyncResult.failure(Cause.interrupt()) }); + await notice().undo(); + expect(add).not.toHaveBeenCalled(); + }); + + it("undoes the latest kind first, then reveals the preceding group", async () => { + const { options } = setup(); + const older = vi.fn(async () => AsyncResult.success(undefined)); + const newer = vi.fn(async () => AsyncResult.success(undefined)); + showThreadUndoNotice({ + ...options, + action: "Settled", + undo: older, + claim: ThreadUndo.begin("settle", "env/a"), + }); + showThreadUndoNotice({ + ...options, + action: "Snoozed", + undo: newer, + claim: ThreadUndo.begin("snooze", "env/b"), + }); + expect(undoLatestThreadAction()).toBe(true); + expect(newer).toHaveBeenCalledOnce(); + expect(older).not.toHaveBeenCalled(); + expect(notice().action).toBe("Settled"); + await notice().undo(); + expect(older).toHaveBeenCalledOnce(); + expect(undoLatestThreadAction()).toBe(false); + }); +}); diff --git a/apps/web/src/hooks/showThreadUndoNotice.ts b/apps/web/src/hooks/showThreadUndoNotice.ts new file mode 100644 index 0000000000000..ea296219487a4 --- /dev/null +++ b/apps/web/src/hooks/showThreadUndoNotice.ts @@ -0,0 +1,106 @@ +import { + type AtomCommandResult, + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import { create } from "zustand"; + +import { stackedThreadToast, toastManager } from "../components/ui/toast"; +import * as ThreadUndo from "./threadUndo"; + +type UndoOptions = { + action: "Settled" | "Snoozed" | "Unpinned" | "Archived"; + undo: () => Promise>; + failureTitle: string; + claim: ReturnType; +}; + +type UndoNotice = { + action: UndoOptions["action"]; + count: number; + undo: () => Promise; +}; + +export const useThreadUndoNotice = create<{ notice: UndoNotice | null }>(() => ({ notice: null })); + +// Shared across sidebar, header and menu actions. Consecutive actions of the +// same kind share one notice and can be restored together. +let liveUndos: UndoOptions[] = []; +let expiry: ReturnType | undefined; + +function refreshNotice() { + liveUndos = liveUndos.filter(({ claim }) => claim.isCurrent()); + const latest = liveUndos.at(-1); + if (!latest) { + clearTimeout(expiry); + useThreadUndoNotice.setState({ notice: null }); + return; + } + const group: UndoOptions[] = []; + for (let index = liveUndos.length - 1; index >= 0; index--) { + const entry = liveUndos[index]!; + if (entry.action !== latest.action) break; + group.push(entry); + } + useThreadUndoNotice.setState({ + notice: { + action: latest.action, + count: group.length, + undo: async () => { + const current = group.filter( + (entry) => liveUndos.includes(entry) && entry.claim.isCurrent(), + ); + liveUndos = liveUndos.filter((entry) => !group.includes(entry)); + // Consume every claim before awaiting, so repeated clicks or shortcuts + // cannot restore the same group twice. + for (const entry of current) entry.claim.finish(); + refreshNotice(); + await Promise.all( + current.map(async ({ undo, failureTitle }) => { + const reportFailure = (error: unknown) => { + toastManager.add( + stackedThreadToast({ + type: "error", + title: failureTitle, + description: error instanceof Error ? error.message : "An error occurred.", + }), + ); + }; + try { + const result = await undo(); + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + reportFailure(squashAtomCommandFailure(result)); + } + } catch (error) { + reportFailure(error); + } + }), + ); + }, + }, + }); +} + +ThreadUndo.subscribe(refreshNotice); + +/** Runs the group displayed in the sidebar; false when nothing is left to undo. */ +export function undoLatestThreadAction(): boolean { + const notice = useThreadUndoNotice.getState().notice; + if (!notice) return false; + void notice.undo(); + return true; +} + +/** Shows one compact confirmation for the currently undoable thread actions. */ +export function showThreadUndoNotice(options: UndoOptions) { + if (!options.claim.isCurrent()) return; + liveUndos.push(options); + refreshNotice(); + clearTimeout(expiry); + expiry = setTimeout(() => { + const expired = liveUndos; + liveUndos = []; + for (const { claim } of expired) claim.finish(); + refreshNotice(); + }, 5_000); +} diff --git a/apps/web/src/hooks/showUndoToast.test.ts b/apps/web/src/hooks/showUndoToast.test.ts deleted file mode 100644 index ced0b2bc55045..0000000000000 --- a/apps/web/src/hooks/showUndoToast.test.ts +++ /dev/null @@ -1,127 +0,0 @@ -import { AsyncResult } from "effect/unstable/reactivity"; -import * as Cause from "effect/Cause"; -import { afterEach, describe, expect, it, vi } from "vite-plus/test"; - -import { toastManager } from "../components/ui/toast"; -import { showUndoToast, undoLatestThreadAction } from "./showUndoToast"; -import * as ThreadUndo from "./threadUndo"; - -afterEach(() => vi.restoreAllMocks()); - -function setup() { - const add = vi.spyOn(toastManager, "add").mockReturnValue("undo-toast"); - const close = vi.spyOn(toastManager, "close").mockImplementation(() => {}); - const undo = vi.fn(async () => AsyncResult.success(undefined)); - const claim = ThreadUndo.begin("pin", "env/thread"); - const options = { - title: "Thread unpinned", - description: "Thread", - failureTitle: "Restore failed", - undo, - claim, - }; - return { add, close, undo, claim, options }; -} - -function click(add: ReturnType["add"], index = 0) { - const handler = add.mock.calls[index]?.[0].actionProps?.onClick; - if (!handler) throw new Error("Undo action is missing"); - return handler({} as Parameters[0]); -} - -describe("showUndoToast", () => { - it("ignores a stale toast and lets the latest action run only once", async () => { - const { add, close, undo, options } = setup(); - showUndoToast(options); - ThreadUndo.invalidate("pin", "env/thread"); - showUndoToast({ ...options, claim: ThreadUndo.begin("pin", "env/thread") }); - await click(add); - expect(undo).not.toHaveBeenCalled(); - await click(add, 1); - await click(add, 1); - expect(undo).toHaveBeenCalledOnce(); - expect(close).toHaveBeenCalledExactlyOnceWith("undo-toast"); - }); - - it("releases the claim on close and rejects a later click", async () => { - const { add, undo, claim, options } = setup(); - showUndoToast(options); - add.mock.calls[0]?.[0].onClose?.(); - expect(claim.isCurrent()).toBe(false); - await click(add); - expect(undo).not.toHaveBeenCalled(); - }); - - it("does not show a toast for a late completion after a newer action", () => { - const { add, options } = setup(); - ThreadUndo.invalidate("pin", "env/thread"); - showUndoToast(options); - expect(add).not.toHaveBeenCalled(); - }); - - it("reports a failed restore and releases its claim", async () => { - const { add, claim, options } = setup(); - showUndoToast({ - ...options, - undo: async () => AsyncResult.failure(Cause.fail(new Error("offline"))), - }); - await click(add); - expect(add).toHaveBeenLastCalledWith( - expect.objectContaining({ type: "error", title: "Restore failed", description: "offline" }), - ); - expect(claim.isCurrent()).toBe(false); - }); - - it("reports a rejected restore promise", async () => { - const { add, options } = setup(); - showUndoToast({ - ...options, - undo: async () => { - throw new Error("disconnected"); - }, - }); - await click(add); - expect(add).toHaveBeenLastCalledWith( - expect.objectContaining({ type: "error", description: "disconnected" }), - ); - }); - - it("does not report interrupted restores as errors", async () => { - const { add, options } = setup(); - showUndoToast({ ...options, undo: async () => AsyncResult.failure(Cause.interrupt()) }); - await click(add); - expect(add).toHaveBeenCalledOnce(); - }); -}); - -describe("undoLatestThreadAction", () => { - it("runs the newest live Undo once and then reports nothing to undo", () => { - const { options } = setup(); - const older = vi.fn(async () => AsyncResult.success(undefined)); - const newer = vi.fn(async () => AsyncResult.success(undefined)); - showUndoToast({ ...options, undo: older, claim: ThreadUndo.begin("settle", "env/a") }); - showUndoToast({ ...options, undo: newer, claim: ThreadUndo.begin("snooze", "env/b") }); - expect(undoLatestThreadAction()).toBe(true); - expect(newer).toHaveBeenCalledOnce(); - expect(older).not.toHaveBeenCalled(); - expect(undoLatestThreadAction()).toBe(true); - expect(older).toHaveBeenCalledOnce(); - expect(undoLatestThreadAction()).toBe(false); - }); - - it("skips a superseded toast and a closed toast", () => { - const { add, options } = setup(); - const superseded = vi.fn(async () => AsyncResult.success(undefined)); - const closed = vi.fn(async () => AsyncResult.success(undefined)); - const live = vi.fn(async () => AsyncResult.success(undefined)); - showUndoToast({ ...options, undo: live, claim: ThreadUndo.begin("archive", "env/live") }); - showUndoToast({ ...options, undo: closed, claim: ThreadUndo.begin("archive", "env/closed") }); - add.mock.calls[1]?.[0].onClose?.(); - showUndoToast({ ...options, undo: superseded, claim: ThreadUndo.begin("pin", "env/stale") }); - ThreadUndo.invalidate("pin", "env/stale"); - expect(undoLatestThreadAction()).toBe(true); - expect(superseded).not.toHaveBeenCalled(); - expect(closed).not.toHaveBeenCalled(); - expect(live).toHaveBeenCalledOnce(); - }); -}); diff --git a/apps/web/src/hooks/showUndoToast.ts b/apps/web/src/hooks/showUndoToast.ts deleted file mode 100644 index 14d532411e7f0..0000000000000 --- a/apps/web/src/hooks/showUndoToast.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { - type AtomCommandResult, - isAtomCommandInterrupted, - squashAtomCommandFailure, -} from "@t3tools/client-runtime/state/runtime"; - -import { stackedThreadToast, toastManager } from "../components/ui/toast"; -import type * as ThreadUndo from "./threadUndo"; - -// Undo toasts still on screen, oldest first, so the `thread.undo` shortcut -// mirrors the newest toast's button without knowing which action it was. -const liveUndos: Array<() => Promise | null> = []; - -/** Runs the newest Undo whose claim still holds; false when nothing is left to undo. */ -export function undoLatestThreadAction(): boolean { - // A superseded entry drops itself when tried, so keep going until one - // runs or the list is empty. - while (liveUndos.length > 0) { - if (liveUndos[liveUndos.length - 1]?.() !== null) return true; - } - return false; -} - -/** Shows a single-use Undo while its thread action still owns the claim. */ -export function showUndoToast({ - title, - description, - undo, - failureTitle, - claim, -}: { - title: string; - description: string | undefined; - undo: () => Promise>; - failureTitle: string; - claim: ReturnType; -}) { - if (!claim.isCurrent()) return; - let undoStarted = false; - let toastId: string | undefined; - const reportFailure = (error: unknown) => { - toastManager.add( - stackedThreadToast({ - type: "error", - title: failureTitle, - description: error instanceof Error ? error.message : "An error occurred.", - }), - ); - }; - const forget = () => { - const index = liveUndos.indexOf(run); - if (index !== -1) liveUndos.splice(index, 1); - }; - const run = () => { - forget(); - if (undoStarted || !claim.isCurrent()) return null; - undoStarted = true; - claim.finish(); - if (toastId !== undefined) toastManager.close(toastId); - return undo() - .then((result) => { - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { - reportFailure(squashAtomCommandFailure(result)); - } - }) - .catch(reportFailure); - }; - liveUndos.push(run); - toastId = toastManager.add({ - ...stackedThreadToast({ - type: "success", - title, - description, - timeout: 5_000, - actionProps: { - children: "Undo", - onClick: async () => { - await run(); - }, - }, - }), - onClose: () => { - claim.finish(); - forget(); - }, - }); -} diff --git a/apps/web/src/hooks/threadUndo.ts b/apps/web/src/hooks/threadUndo.ts index a9e5c179fc87f..29d05b51efd0f 100644 --- a/apps/web/src/hooks/threadUndo.ts +++ b/apps/web/src/hooks/threadUndo.ts @@ -1,16 +1,32 @@ // Shared across hook instances so sidebar, header and menu actions invalidate each other. const currentActions = new Map(); +const listeners = new Set<() => void>(); + +export function subscribe(listener: () => void) { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; +} + +function notify() { + for (const listener of listeners) listener(); +} /** Claims one kind of thread action; a later claim of that kind expires its Undo. */ export function begin(kind: string, threadKey: string) { const key = JSON.stringify([kind, threadKey]); const token = Symbol(); currentActions.set(key, token); + notify(); const isCurrent = () => currentActions.get(key) === token; return { isCurrent, finish: () => { - if (isCurrent()) currentActions.delete(key); + if (isCurrent()) { + currentActions.delete(key); + notify(); + } }, }; } @@ -18,4 +34,5 @@ export function begin(kind: string, threadKey: string) { /** Expires only this action kind, leaving unrelated thread actions intact. */ export function invalidate(kind: string, threadKey: string) { currentActions.delete(JSON.stringify([kind, threadKey])); + notify(); } diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.ts index 40a06ba9676a0..0e54910992230 100644 --- a/apps/web/src/hooks/useThreadActions.ts +++ b/apps/web/src/hooks/useThreadActions.ts @@ -15,7 +15,6 @@ import { useRouter } from "@tanstack/react-router"; import { useCallback, useMemo, useRef } from "react"; import { getFallbackThreadIdAfterDelete, pinOrderKeyBetween } from "../components/Sidebar.logic"; -import { snoozeWakeDescription } from "../components/Sidebar.snooze"; import { useComposerDraftStore } from "../composerDraftStore"; import { terminalEnvironment } from "../state/terminal"; import { appAtomRegistry } from "../rpc/atomRegistry"; @@ -44,7 +43,7 @@ import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from " import { stackedThreadToast, toastManager } from "../components/ui/toast"; import { useClientSettings } from "./useSettings"; import * as ThreadUndo from "./threadUndo"; -import { showUndoToast } from "./showUndoToast"; +import { showThreadUndoNotice } from "./showThreadUndoNotice"; import { useAtomCommand } from "../state/use-atom-command"; export class ThreadArchiveBlockedError extends Schema.TaggedError()( @@ -223,7 +222,6 @@ export function useThreadActions() { const sidebarThreadSortOrder = useClientSettings((settings) => settings.sidebarThreadSortOrder); const confirmThreadDelete = useClientSettings((settings) => settings.confirmThreadDelete); const confirmThreadUnpin = useClientSettings((settings) => settings.confirmThreadUnpin); - const timestampFormat = useClientSettings((settings) => settings.timestampFormat); const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread); const clearProjectDraftThreadById = useComposerDraftStore( (store) => store.clearProjectDraftThreadById, @@ -313,9 +311,8 @@ export function useThreadActions() { } refreshArchivedThreadsForEnvironment(threadRef.environmentId); opts.onArchived?.(); - showUndoToast({ - title: "Thread archived", - description: thread.title, + showThreadUndoNotice({ + action: "Archived", claim: action, // Undo also brings the reader back when archiving moved them to a draft. undo: () => unarchiveThread(threadRef, { navigate: shouldNavigateToDraft }), @@ -613,9 +610,8 @@ export function useThreadActions() { input: { threadId: target.threadId }, }); if (result._tag === "Success" && action.isCurrent()) { - showUndoToast({ - title: "Thread unpinned", - description: thread?.title, + showThreadUndoNotice({ + action: "Unpinned", claim: action, undo: () => pinThread(target, orderKey === undefined ? {} : { orderKey }), failureTitle: "Failed to undo unpin", @@ -629,11 +625,7 @@ export function useThreadActions() { ); const settleThread = useCallback( - async ( - target: ScopedThreadRef, - // Batch callers settle a selection at once and stay silent as before. - opts: { undoToast?: boolean } = {}, - ) => { + async (target: ScopedThreadRef) => { // Version skew: never send the command to a server that predates it — // the raw protocol rejection would read as a random failure. if (!readEnvironmentSupportsSettlement(target.environmentId)) { @@ -671,13 +663,8 @@ export function useThreadActions() { if (wokeAt !== null) { markThreadVisited(scopedThreadKey(target), wokeAt); } - if (opts.undoToast === false) { - action.finish(); - return result; - } - showUndoToast({ - title: "Thread settled", - description: resolved?.thread.title, + showThreadUndoNotice({ + action: "Settled", claim: action, undo: async () => { const unsettled = await unsettleThread(target); @@ -797,12 +784,7 @@ export function useThreadActions() { ); const snoozeThread = useCallback( - async ( - target: ScopedThreadRef, - snoozedUntil: string, - // Batch callers report one toast for the whole selection instead. - opts: { undoToast?: boolean } = {}, - ) => { + async (target: ScopedThreadRef, snoozedUntil: string) => { // Version skew: never send the command to a server that predates it. if (!readEnvironmentSupportsSnooze(target.environmentId)) { return AsyncResult.failure( @@ -833,21 +815,20 @@ export function useThreadActions() { environmentId: target.environmentId, input: { threadId: target.threadId, snoozedUntil }, }); - if (result._tag !== "Success" || opts.undoToast === false) { + if (result._tag !== "Success") { action.finish(); return result; } - // Snooze hides the row, so the toast is the only confirmation. - showUndoToast({ - title: `Snoozed until ${snoozeWakeDescription(snoozedUntil, new Date(), timestampFormat)}`, - description: resolved?.thread.title, + // Snooze hides the row, so keep its confirmation in the sidebar. + showThreadUndoNotice({ + action: "Snoozed", claim: action, undo: () => unsnoozeThread(target), failureTitle: "Failed to wake thread", }); return result; }, - [resolveThreadTarget, snoozeThreadMutation, timestampFormat, unsnoozeThread], + [resolveThreadTarget, snoozeThreadMutation, unsnoozeThread], ); const confirmAndDeleteThread = useCallback( diff --git a/apps/web/src/hooks/useThreadActions.undo.test.ts b/apps/web/src/hooks/useThreadActions.undo.test.ts index eacffd146e20c..6e61b298be51c 100644 --- a/apps/web/src/hooks/useThreadActions.undo.test.ts +++ b/apps/web/src/hooks/useThreadActions.undo.test.ts @@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test" import { useThreadActions } from "./useThreadActions"; import { threadEnvironment } from "../state/threads"; import { toastManager } from "../components/ui/toast"; +import { useThreadUndoNotice } from "./showThreadUndoNotice"; const commands = vi.hoisted(() => ({ pin: vi.fn(), @@ -78,18 +79,14 @@ const target = { environmentId: EnvironmentId.make("undo-env"), threadId: ThreadId.make("thread"), }; -const event = {} as Parameters["onClick"]>>[0]; - -function undoOf( - add: { mock: { calls: Array<[Parameters[0]]> } }, - index: number, -) { - const onClick = add.mock.calls[index]?.[0].actionProps?.onClick; - expect(onClick).toBeTypeOf("function"); - return () => onClick?.(event); +function currentUndo() { + const notice = useThreadUndoNotice.getState().notice; + expect(notice).not.toBeNull(); + return notice!.undo; } beforeEach(() => { + vi.useFakeTimers(); for (const command of Object.values(commands)) { command.mockReset().mockResolvedValue({ _tag: "Success", value: undefined }); } @@ -98,19 +95,21 @@ beforeEach(() => { threadShell.pinnedAt = null; threadShell.snoozedUntil = null; }); -afterEach(() => vi.restoreAllMocks()); +afterEach(() => { + vi.runAllTimers(); + vi.useRealTimers(); + vi.restoreAllMocks(); +}); describe("unpin Undo", () => { - it("ignores an old toast across hook instances and still restores the latest unpin", async () => { - const add = vi.spyOn(toastManager, "add").mockReturnValue("toast"); - vi.spyOn(toastManager, "close").mockImplementation(() => {}); + it("ignores an old notice across hook instances and still restores the latest unpin", async () => { const sidebar = useThreadActions(); const header = useThreadActions(); await sidebar.unpinThread(target); - const staleUndo = undoOf(add, 0); + const staleUndo = currentUndo(); await header.pinThread(target, { orderKey: "a1" }); await header.unpinThread(target); - const latestUndo = undoOf(add, 1); + const latestUndo = currentUndo(); await staleUndo(); expect(commands.pin).toHaveBeenCalledTimes(1); await latestUndo(); @@ -127,15 +126,15 @@ describe("unpin Undo", () => { describe("archive Undo", () => { it("unarchives and returns to the thread when archiving left it", async () => { const add = vi.spyOn(toastManager, "add").mockReturnValue("toast"); - vi.spyOn(toastManager, "close").mockImplementation(() => {}); router.state.matches[0]!.params = { environmentId: target.environmentId, threadId: target.threadId, }; const actions = useThreadActions(); await actions.archiveThread(target); - expect(add).toHaveBeenCalledWith(expect.objectContaining({ title: "Thread archived" })); - await undoOf(add, 0)(); + expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: "Archived", count: 1 }); + expect(add).not.toHaveBeenCalled(); + await currentUndo()(); expect(commands.unarchive).toHaveBeenCalledExactlyOnceWith({ environmentId: target.environmentId, input: { threadId: target.threadId }, @@ -149,11 +148,9 @@ describe("archive Undo", () => { }); it("stays put when the archived thread was not open", async () => { - const add = vi.spyOn(toastManager, "add").mockReturnValue("toast"); - vi.spyOn(toastManager, "close").mockImplementation(() => {}); const actions = useThreadActions(); await actions.archiveThread(target); - await undoOf(add, 0)(); + await currentUndo()(); expect(commands.unarchive).toHaveBeenCalledOnce(); expect(router.navigate).not.toHaveBeenCalled(); }); @@ -167,27 +164,25 @@ describe("archive Undo", () => { }); describe("settle and snooze Undo", () => { - it("un-settles from the toast and expires the Undo after a manual un-settle", async () => { + it("un-settles from the notice and expires the Undo after a manual un-settle", async () => { const add = vi.spyOn(toastManager, "add").mockReturnValue("toast"); - vi.spyOn(toastManager, "close").mockImplementation(() => {}); const actions = useThreadActions(); await actions.settleThread(target); - expect(add).toHaveBeenCalledWith(expect.objectContaining({ title: "Thread settled" })); - const undo = undoOf(add, 0); + expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: "Settled", count: 1 }); + expect(add).not.toHaveBeenCalled(); + const undo = currentUndo(); await actions.unsettleThread(target); await undo(); expect(commands.unsettle).toHaveBeenCalledOnce(); }); it("re-pins and re-snoozes a thread that settling had cleared", async () => { - const add = vi.spyOn(toastManager, "add").mockReturnValue("toast"); - vi.spyOn(toastManager, "close").mockImplementation(() => {}); const snoozedUntil = "2030-01-01T09:00:00.000Z"; threadShell.pinnedAt = "2026-01-01T00:00:00.000Z"; threadShell.snoozedUntil = snoozedUntil; const actions = useThreadActions(); await actions.settleThread(target); - await undoOf(add, 0)(); + await currentUndo()(); expect(commands.unsettle).toHaveBeenCalledOnce(); expect(commands.pin).toHaveBeenCalledExactlyOnceWith({ environmentId: target.environmentId, @@ -200,31 +195,21 @@ describe("settle and snooze Undo", () => { }); it("expires an older unpin Undo when the thread is settled", async () => { - const add = vi.spyOn(toastManager, "add").mockReturnValue("toast"); - vi.spyOn(toastManager, "close").mockImplementation(() => {}); const actions = useThreadActions(); await actions.unpinThread(target); - const staleUnpinUndo = undoOf(add, 0); + const staleUnpinUndo = currentUndo(); await actions.settleThread(target); await staleUnpinUndo(); expect(commands.pin).not.toHaveBeenCalled(); }); - it("stays silent for batch settles", async () => { + it("wakes the thread from the snooze notice", async () => { const add = vi.spyOn(toastManager, "add").mockReturnValue("toast"); - await useThreadActions().settleThread(target, { undoToast: false }); - expect(add).not.toHaveBeenCalled(); - }); - - it("wakes the thread from the snooze toast", async () => { - const add = vi.spyOn(toastManager, "add").mockReturnValue("toast"); - vi.spyOn(toastManager, "close").mockImplementation(() => {}); const actions = useThreadActions(); await actions.snoozeThread(target, new Date(Date.now() + 60_000).toISOString()); - expect(add).toHaveBeenCalledWith( - expect.objectContaining({ title: expect.stringMatching(/^Snoozed until /) }), - ); - await undoOf(add, 0)(); + expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: "Snoozed", count: 1 }); + expect(add).not.toHaveBeenCalled(); + await currentUndo()(); expect(commands.unsnooze).toHaveBeenCalledExactlyOnceWith({ environmentId: target.environmentId, input: { threadId: target.threadId, reason: "user" }, diff --git a/apps/web/src/routes/_chat.tsx b/apps/web/src/routes/_chat.tsx index 980177004daab..5b5b4888269ba 100644 --- a/apps/web/src/routes/_chat.tsx +++ b/apps/web/src/routes/_chat.tsx @@ -16,6 +16,9 @@ import { useHandleNewThread } from "../hooks/useHandleNewThread"; import { startNewThreadFromContext } from "../lib/chatThreadActions"; import { isPreviewFocused } from "../lib/previewFocus"; import { isTerminalFocused } from "../lib/terminalFocus"; +import { isEditableFocused } from "../lib/editableFocus"; +import { isModelPickerOpen } from "../modelPickerVisibility"; +import { undoLatestThreadAction } from "../hooks/showThreadUndoNotice"; import { resolveShortcutCommand } from "../keybindings"; import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore"; import { isPreviewSupportedInRuntime } from "../previewStateStore"; @@ -66,6 +69,8 @@ function ChatRouteGlobalShortcuts() { terminalOpen, previewFocus: isPreviewFocused(), previewOpen, + editableFocus: isEditableFocused(event.target), + modelPickerOpen: isModelPickerOpen(), }, }); @@ -73,6 +78,15 @@ function ChatRouteGlobalShortcuts() { return; } + if (command === "thread.undo") { + if (event.repeat || isModelPickerOpen()) return; + if (undoLatestThreadAction()) { + event.preventDefault(); + event.stopPropagation(); + } + return; + } + if (event.key === "Escape" && selectedThreadKeysSize > 0) { event.preventDefault(); clearSelection(); diff --git a/docs/user/keybindings.md b/docs/user/keybindings.md index 78c792d298515..548b03fd1a73d 100644 --- a/docs/user/keybindings.md +++ b/docs/user/keybindings.md @@ -111,10 +111,11 @@ a shortcut. `thread.stop` interrupts the running turn in the focused thread. It has no default shortcut; assign one in **Settings → Keybindings**. -`thread.undo` (`mod+z` by default) reverses the most recent thread action that is -still offering **Undo** in a notification, such as an unpin, settle, snooze, or -archive. Its default rule skips text fields and terminals so native undo keeps -working there. +`thread.undo` (`mod+z` by default) reverses the actions shown in the notice at the +bottom of the sidebar, such as unpin, settle, snooze, or archive. Consecutive +actions of the same kind undo together. The notice remains available for five +seconds after the latest action. The default shortcut skips text fields and +terminals so native undo keeps working there. `chat.new` may ask you to choose a project when there is more than one. `chat.newLocal` skips that chooser. Both use your From 5423ba0fd08447240282c08362ee8e382bf16903 Mon Sep 17 00:00:00 2001 From: Bilal Bakr <62337003+Bil0000@users.noreply.github.com> Date: Tue, 22 Sep 2026 05:51:35 +0300 Subject: [PATCH 13/60] feat(web): merge the comment and review buttons into one composer (#12945) Co-authored-by: maria-rcks --- .../pullRequest/PullRequestCodeTab.tsx | 90 +------- .../PullRequestCommentComposer.tsx | 171 --------------- .../pullRequest/PullRequestCommentForm.tsx | 145 +++++++++++++ .../pullRequest/PullRequestComposer.tsx | 195 ++++++++++++++++++ .../pullRequest/PullRequestDetailPanel.tsx | 7 +- ...eviewBar.tsx => PullRequestReviewForm.tsx} | 95 +++++---- apps/web/src/components/ui/popover.tsx | 11 +- 7 files changed, 413 insertions(+), 301 deletions(-) delete mode 100644 apps/web/src/components/pullRequest/PullRequestCommentComposer.tsx create mode 100644 apps/web/src/components/pullRequest/PullRequestCommentForm.tsx create mode 100644 apps/web/src/components/pullRequest/PullRequestComposer.tsx rename apps/web/src/components/pullRequest/{PullRequestReviewBar.tsx => PullRequestReviewForm.tsx} (64%) diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx index 08a46872b6976..131593ab6d225 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx @@ -18,13 +18,11 @@ import { Columns2Icon, FolderTreeIcon, InfoIcon, - MessageSquareIcon, MessageSquareOffIcon, PilcrowIcon, Rows3Icon, TextWrapIcon, TriangleAlertIcon, - XIcon, } from "lucide-react"; import { useAtomRefresh } from "@effect/atom-react"; import * as Schema from "effect/Schema"; @@ -78,7 +76,6 @@ import { toastManager } from "../ui/toast"; import { Toggle, ToggleGroup } from "../ui/toggle-group"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { PendingReviewCommentCard, ReviewThreadCard } from "./PullRequestReviewAnnotation"; -import { PullRequestReviewBar } from "./PullRequestReviewBar"; import { isFileDiffCollapsed, isLineInFileDiff, @@ -247,9 +244,6 @@ function PullRequestCodeTab({ const [draft, setDraft] = useState(null); const [threadPending, setThreadPending] = useState(false); const [orphansOpen, setOrphansOpen] = useState(false); - // Closed by default so the review form does not permanently eat vertical space below the - // diff; opened on demand as a floating overlay instead. - const [reviewOpen, setReviewOpen] = useState(false); // Which pull request the slices belong to travels with them, so a render taken before the // reset below cannot read the previous one's slices — or send its cursor to the host. const [sliceState, setSliceState] = useState<{ @@ -378,7 +372,6 @@ function PullRequestCodeTab({ inlineComment: hostReview.inlineComment && viewer.comment, reply: hostReview.reply && viewer.comment, resolve: hostReview.resolve && viewer.resolve, - verdicts: hostReview.verdicts.filter((verdict) => viewer.verdicts.includes(verdict)), }; }, [detail.capabilities.review, detail.viewerPermissions]); // A comment is posted against the pull request's head diff, so a line number taken from one @@ -1054,70 +1047,6 @@ function PullRequestCodeTab({ ], ); - /** - * The review overlay belongs to the pull request, not to the patch: a change whose diff - * cannot be structured — or read at all — is still one a reviewer can approve or reject, so - * it survives every branch below. It floats over the scroll area rather than sitting in the - * layout flow, so the diff keeps the full height instead of permanently losing a strip to a - * footer most reviews never touch. Hidden entirely where the host offers no verdicts, same as - * the bar it wraps did. - */ - const reviewOverlay = - review.verdicts.length === 0 ? null : ( -
- {reviewOpen ? ( -
- - { - onRefresh(); - setReviewOpen(false); - }} - /> -
- ) : ( - - )} -
- ); // A rebase or a force-push can take the scoped commit out of the change. Its diff may still // be reachable on the host, but it is no longer part of what is being reviewed, so the scope // goes back to the whole change rather than sitting under a name nothing matches. @@ -1392,29 +1321,23 @@ function PullRequestCodeTab({ ); // The toolbar rides above every branch below, not just the one with a patch in it: a commit // whose diff is empty or unreadable still needs the scope dropdown that got the reader there. - const withReviewBar = (body: ReactNode) => ( + const withToolbar = (body: ReactNode) => (
{toolbar} - {/* The overlay is anchored to this wrapper, not the scroller: absolute positioning - inside an overflowing element tracks the content's bottom edge, which would carry - the trigger away with the first scroll. */} -
-
{body}
- {reviewOverlay} -
+
{body}
); // Under the toolbar rather than in place of it, so choosing a commit does not take the // dropdown that was just used off the screen while its diff loads. if (diffQuery.isPending && loadedSlices.length === 0) { - return withReviewBar(); + return withToolbar(); } // A slice that fails once there are files on screen is reported at the end of them instead: // the diff already read is worth more than the error that stopped it growing. if (diffQuery.error && loadedSlices.length === 0) { - return withReviewBar( + return withToolbar(

{diffQuery.error}

, ); } @@ -1428,7 +1351,7 @@ function PullRequestCodeTab({ ? parsedSlices.flatMap((parsed) => (parsed?.kind === "raw" ? [parsed] : [])) : []; if (files.length === 0 && rawSlices.length > 0) { - return withReviewBar( + return withToolbar(
{rawSlices.map((slice) => (
@@ -1441,7 +1364,7 @@ function PullRequestCodeTab({ } if (items.length === 0 && nextCursor === null) { - return withReviewBar( + return withToolbar(

{commit === null ? "This pull request has no file changes." @@ -1595,7 +1518,6 @@ function PullRequestCodeTab({ renderAnnotation={renderAnnotation} unsafeCSSExtra={REPLACE_FILE_COUNTS_CSS} /> - {reviewOverlay}

{fileTreeOpen ? (