From 797038ec5f97ebb585daeb32e0002cfbbd06ed1c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 00:37:54 -0800 Subject: [PATCH 01/39] fix(mobile): Vietnamese letters stay bold in bold text on Android (#40205) --- apps/mobile/app.config.ts | 7 ++++++- apps/mobile/global.css | 1 + apps/mobile/src/native/EnrichedMarkdownText.tsx | 9 ++++++++- 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts index bad4faed441fd..464f7ab9929b0 100644 --- a/apps/mobile/app.config.ts +++ b/apps/mobile/app.config.ts @@ -346,7 +346,12 @@ const config: ExpoConfig = { }, { fontFamily: "DMSans-Bold", - fontDefinitions: [{ path: dmSansFonts.bold, weight: 700 }], + // Android picks fallback glyphs (such as Vietnamese) at the requested weight, so bold text + // asks for 700; the 400 entry lets a relative bold step (Typeface.BOLD) land on 700 too. + fontDefinitions: [ + { path: dmSansFonts.bold, weight: 400 }, + { path: dmSansFonts.bold, weight: 700 }, + ], }, ], }, diff --git a/apps/mobile/global.css b/apps/mobile/global.css index 7a4cd4eff5046..79010054c1492 100644 --- a/apps/mobile/global.css +++ b/apps/mobile/global.css @@ -50,6 +50,7 @@ @utility font-t3-bold { font-family: var(--font-bold); + font-weight: 700; } @utility font-t3-extrabold { diff --git a/apps/mobile/src/native/EnrichedMarkdownText.tsx b/apps/mobile/src/native/EnrichedMarkdownText.tsx index 9c207a3034eb5..4ef351b39873b 100644 --- a/apps/mobile/src/native/EnrichedMarkdownText.tsx +++ b/apps/mobile/src/native/EnrichedMarkdownText.tsx @@ -49,6 +49,8 @@ function enrichedStyle( fontScale: number, ): MarkdownStyle { const monospace = Platform.OS === "ios" ? "Menlo" : "monospace"; + // Android only bolds fallback glyphs when the bold family is asked for at a bold weight (app.config.ts). + const boldFontWeight = Platform.OS === "android" ? "bold" : undefined; // Keep the radius modest: iOS clips square table-cell borders without stroking the corner arcs. const block = { marginTop: 4, @@ -71,6 +73,7 @@ function enrichedStyle( ...body, color: style.strongColor, fontFamily: style.headingFontFamily, + fontWeight: boldFontWeight, fontSize, lineHeight: fontSize * 1.35, marginTop: 8, @@ -93,7 +96,11 @@ function enrichedStyle( h4: heading(4), h5: heading(5), h6: heading(6), - strong: { color: style.strongColor, fontFamily: style.boldFontFamily, fontWeight: "normal" }, + strong: { + color: style.strongColor, + fontFamily: style.boldFontFamily, + fontWeight: boldFontWeight ?? "normal", + }, link: { color: style.linkColor, underline: false }, code: { fontFamily: monospace, From 7ef0558f758882628d4aa5a68796ce7c374f90e1 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 00:39:09 -0800 Subject: [PATCH 02/39] fix(desktop): preview tabs drop a destroyed webview's WebContents (#40177) --- apps/desktop/src/preview/Manager.test.ts | 24 +++++ apps/desktop/src/preview/Manager.ts | 94 +++++++++++-------- .../ElectronBrowserHost.browser.test.tsx | 1 + apps/web/src/browser/HostedBrowserWebview.tsx | 13 ++- 4 files changed, 91 insertions(+), 41 deletions(-) diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.ts index 2a01977302594..9c15a0e0a4a95 100644 --- a/apps/desktop/src/preview/Manager.test.ts +++ b/apps/desktop/src/preview/Manager.test.ts @@ -1680,6 +1680,30 @@ describe("PreviewManager", () => { ), ); + effectIt.effect( + "does not open picture-in-picture against a destroyed webview's WebContents", + () => + withManager((manager) => + Effect.gen(function* () { + const guest = makeAttachingGuest(49); + fromId.mockImplementation((id) => + id === 49 && !guest.wc.isDestroyed() ? guest.wc : null, + ); + yield* manager.prepareWebview(guest.wc); + yield* manager.createTab("tab_destroyed_guest"); + yield* manager.registerWebview("tab_destroyed_guest", 49); + + guest.destroy(); + yield* Effect.yieldNow; + + const pictureInPicture = yield* Effect.flip( + manager.openPictureInPicture("tab_destroyed_guest"), + ).pipe(Effect.orDie); + expect(pictureInPicture._tag).toBe("PreviewWebviewNotInitializedError"); + }), + ), + ); + effectIt.effect("skips a guest destroyed while another guest's session opens", () => withManager((manager) => Effect.gen(function* () { diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts index fbf70e12fd375..531e269a07f11 100644 --- a/apps/desktop/src/preview/Manager.ts +++ b/apps/desktop/src/preview/Manager.ts @@ -2040,6 +2040,51 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function ); }); + // Clears a tab's dead guest so callers see "no webview" until the renderer registers a new one. + const detachDestroyedWebContents = Effect.fn("PreviewManager.detachDestroyedWebContents")( + function* (tabId: string, webContentsId: number) { + const expectedAttachment = (yield* Ref.get(attachedRef)).get(webContentsId); + yield* withTabLifecycleLock( + tabId, + Effect.gen(function* () { + const currentTab = (yield* SynchronizedRef.get(tabsRef)).get(tabId); + const currentAttachment = (yield* Ref.get(attachedRef)).get(webContentsId); + const currentWebContents = webContents.fromId(webContentsId); + if ( + currentTab?.webContentsId !== webContentsId || + currentAttachment !== expectedAttachment || + (currentWebContents && !currentWebContents.isDestroyed()) + ) { + return; + } + yield* Effect.all( + [ + detachControlSession(webContentsId), + detachListeners(webContentsId), + cancelPickElement(tabId), + ], + { concurrency: 3, discard: true }, + ); + const detached = yield* SynchronizedRef.modify(tabsRef, (tabs) => { + const current = tabs.get(tabId); + if (current?.webContentsId !== webContentsId) { + return [Option.none(), tabs] as const; + } + const { favicon: _favicon, ...currentWithoutFavicon } = current; + const next: PreviewTabState = { ...currentWithoutFavicon, webContentsId: null }; + return [ + Option.some(next), + replaceMap(tabs, (copy) => { + copy.set(tabId, next); + }), + ] as const; + }); + if (Option.isSome(detached)) yield* emitIfCurrent(tabId, detached.value); + }), + ); + }, + ); + // URL tabs can paint before registerWebview; set the background at attach time. const prepareWebview = Effect.fn("PreviewManager.prepareWebview")(function* ( wc: Electron.WebContents, @@ -2059,7 +2104,13 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function }); wc.once("destroyed", () => { guestLoadFailures.delete(webContentsId); - runFork(hideDestroyedGuest(webContentsId)); + runFork( + Effect.gen(function* () { + yield* hideDestroyedGuest(webContentsId); + const tabId = yield* tabIdForWebContents(webContentsId); + if (tabId) yield* detachDestroyedWebContents(tabId, webContentsId); + }), + ); runFork(detachControlSession(webContentsId)); }); yield* ensureControlSession(wc).pipe( @@ -2135,45 +2186,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function const webContentsId = pending.webContentsId; const wc = webContents.fromId(webContentsId); if (!wc || wc.isDestroyed()) { - const expectedAttachment = (yield* Ref.get(attachedRef)).get(webContentsId); - yield* withTabLifecycleLock( - tabId, - Effect.gen(function* () { - const currentTab = (yield* SynchronizedRef.get(tabsRef)).get(tabId); - const currentAttachment = (yield* Ref.get(attachedRef)).get(webContentsId); - const currentWebContents = webContents.fromId(webContentsId); - if ( - currentTab?.webContentsId !== webContentsId || - currentAttachment !== expectedAttachment || - (currentWebContents && !currentWebContents.isDestroyed()) - ) { - return; - } - yield* Effect.all( - [ - detachControlSession(webContentsId), - detachListeners(webContentsId), - cancelPickElement(tabId), - ], - { concurrency: 3, discard: true }, - ); - const detached = yield* SynchronizedRef.modify(tabsRef, (tabs) => { - const current = tabs.get(tabId); - if (current?.webContentsId !== webContentsId) { - return [Option.none(), tabs] as const; - } - const { favicon: _favicon, ...currentWithoutFavicon } = current; - const next: PreviewTabState = { ...currentWithoutFavicon, webContentsId: null }; - return [ - Option.some(next), - replaceMap(tabs, (copy) => { - copy.set(tabId, next); - }), - ] as const; - }); - if (Option.isSome(detached)) yield* emitIfCurrent(tabId, detached.value); - }), - ); + yield* detachDestroyedWebContents(tabId, webContentsId); return; } yield* leaveBusyPage(wc); @@ -2248,6 +2261,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function Effect.catchTags({ PreviewTabNotFoundError: () => Effect.void, PreviewWebContentsNotFoundError: () => Effect.void, + PreviewWebviewNotInitializedError: () => Effect.void, }), ); diff --git a/apps/web/src/browser/ElectronBrowserHost.browser.test.tsx b/apps/web/src/browser/ElectronBrowserHost.browser.test.tsx index 29c217e064adc..d561254290427 100644 --- a/apps/web/src/browser/ElectronBrowserHost.browser.test.tsx +++ b/apps/web/src/browser/ElectronBrowserHost.browser.test.tsx @@ -43,6 +43,7 @@ vi.mock(import("~/components/preview/previewBridge"), async (original) => ({ closeTab: mocks.closeTab, registerWebview: mocks.registerWebview, getPreviewConfig: mocks.getPreviewConfig, + onStateChange: () => () => {}, } as never, })); diff --git a/apps/web/src/browser/HostedBrowserWebview.tsx b/apps/web/src/browser/HostedBrowserWebview.tsx index 023fb03c3aa17..b20d737095116 100644 --- a/apps/web/src/browser/HostedBrowserWebview.tsx +++ b/apps/web/src/browser/HostedBrowserWebview.tsx @@ -159,6 +159,7 @@ export function HostedBrowserWebview(props: { if (!clientSettingsHydrated || !webview || !config || !bridge) return; let disposed = false; let recoveryTimeout: ReturnType | null = null; + let registeredWebContentsId: number | null = null; const register = () => { const lease = tabLeaseRef.current; if (!lease) return; @@ -170,6 +171,7 @@ export function HostedBrowserWebview(props: { const webContentsId = webview.getWebContentsId(); if (Number.isInteger(webContentsId) && webContentsId > 0) { await bridge.registerWebview(runtimeTabId, webContentsId); + registeredWebContentsId = webContentsId; withDesktopTab(runtimeTabId, () => bridge.setShown(runtimeTabId, reportedShown())); } } catch {} @@ -198,6 +200,13 @@ export function HostedBrowserWebview(props: { dismissHostPopups(); } }; + // The desktop clears a destroyed guest's id; nothing reattaches this element, so remount it. + const unsubscribeState = bridge.onStateChange((changedTabId, state) => { + if (changedTabId !== runtimeTabId || registeredWebContentsId === null) return; + if (state.webContentsId !== null) return; + registeredWebContentsId = null; + recoverGuest(); + }); webview.addEventListener("did-attach", register); webview.addEventListener("dom-ready", register); webview.addEventListener("render-process-gone", recoverGuest); @@ -207,6 +216,7 @@ export function HostedBrowserWebview(props: { return () => { disposed = true; if (recoveryTimeout !== null) clearTimeout(recoveryTimeout); + unsubscribeState(); webview.removeEventListener("did-attach", register); webview.removeEventListener("dom-ready", register); webview.removeEventListener("render-process-gone", recoverGuest); @@ -374,6 +384,8 @@ export function HostedBrowserWebview(props: { /> ) : null}
Date: Sat, 21 Nov 2026 00:41:26 -0800 Subject: [PATCH 03/39] fix(acp): persist context usage reported after a turn ends (#40220) --- .../Adapters/AcpAdapterV2.test.ts | 91 +++++++++++++++++++ packages/provider-acp/src/server/adapter.ts | 2 + 2 files changed, 93 insertions(+) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index ec56c0c389a69..4946377c94502 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -11680,6 +11680,97 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest), Effect.scoped), ); + it.effect("persists context usage the agent reports after its prompt settles", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const path = yield* Path.Path; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdateHandler: Parameters[0] | undefined; + const promptStarted = yield* Deferred.make(); + const promptGate = yield* Deferred.make(); + const instanceId = ProviderInstanceId.make("acp-test"); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapRuntime: (runtime) => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdateHandler = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + prompt: () => + Deferred.succeed(promptStarted, undefined).pipe( + Effect.andThen(Deferred.await(promptGate)), + ), + }), + }), + }, + }); + const threadId = ThreadId.make("thread-acp-late-usage"); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-late-usage"), + modelSelection, + runtimePolicy, + }); + const events = yield* Queue.unbounded(); + yield* runtime.events.pipe( + Stream.runForEach((event) => Queue.offer(events, event)), + Effect.forkScoped, + ); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + yield* runtime + .startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + }), + ) + .pipe(Effect.forkScoped); + yield* Deferred.await(promptStarted); + const update = (update: EffectAcpSchema.SessionUpdate) => + sessionUpdateHandler!({ sessionId: "mock-session-1", update }); + yield* update({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "OK" }, + }); + yield* Deferred.succeed(promptGate, { stopReason: "end_turn" }); + while ((yield* Queue.take(events)).type !== "turn.terminal"); + + // Kimi Code 2.6.2 sends its usage_update just after answering session/prompt. + yield* update({ sessionUpdate: "usage_update", used: 13101, size: 1048576 }); + let late: ProviderAdapter.ProviderAdapterV2Event; + do late = yield* Queue.take(events); + while (late.type !== "provider_thread.updated"); + assert.deepInclude(late.providerThread.contextUsage, { usedTokens: 13101 }); + // With no run left to receive it, only a session-scoped update reaches the projection. + assert.isTrue(late.sessionScoped); + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); + it.live("durably poisons start and resume when required hard teardown is unavailable", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 144943368c1d9..cf7bb6c0f92fd 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -5734,6 +5734,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( type: "provider_thread.updated", driver, providerThread, + // Agents like Kimi report usage after the prompt settles, when no run receives it. + ...(context === null ? { sessionScoped: true } : {}), }); } return; From 67933a2236c1835e38362b218cd0d1f4918c0a71 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 00:50:47 -0800 Subject: [PATCH 04/39] perf(server): complete Changes preview reuses its tracked-only pass (#40211) --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 34 +++++++- apps/server/src/vcs/GitVcsDriverCore.ts | 82 ++++++++++++++++++-- packages/client-runtime/src/state/review.ts | 6 ++ packages/contracts/src/review.ts | 3 + 4 files changed, 115 insertions(+), 10 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index a5ec6a0d05413..c6f90862380fe 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -916,9 +916,39 @@ it.effect("resolves a branch's base once while its refs and branch config are un // One thread switch: two local status reads and the two diff preview passes. yield* driver.statusDetailsLocal(cwd); yield* driver.statusDetailsLocal(cwd); - yield* driver.getReviewDiffPreview({ cwd, trackedOnly: true }); - yield* driver.getReviewDiffPreview({ cwd }); + const tracked = yield* driver.getReviewDiffPreview({ cwd, trackedOnly: true }); + assert.isDefined(tracked.completionToken); assert.equal(lookups(), 1); + // The complete pass adds only the untracked listing to the tracked pass it follows. + const complete = yield* driver.getReviewDiffPreview({ + cwd, + completionToken: tracked.completionToken!, + }); + assert.deepStrictEqual( + spawnedArgs.map((args) => args.find((arg) => !arg.startsWith("-") && !arg.includes("="))), + ["ls-files"], + ); + assert.isUndefined(complete.incomplete); + assert.deepStrictEqual(complete.sources, tracked.sources); + spawnedArgs.length = 0; + // A token is used once, and untracked files are still diffed when there are some. + yield* writeTextFile(cwd, "untracked.txt", "untracked\n"); + const second = yield* driver.getReviewDiffPreview({ cwd, trackedOnly: true }); + const withUntracked = yield* driver.getReviewDiffPreview({ + cwd, + completionToken: second.completionToken!, + }); + assert.include( + withUntracked.sources.flatMap((source) => source.files?.map((file) => file.path) ?? []), + "untracked.txt", + ); + const reused = yield* driver.getReviewDiffPreview({ + cwd, + completionToken: tracked.completionToken!, + }); + assert.deepStrictEqual(reused.sources, withUntracked.sources); + yield* (yield* FileSystem.FileSystem).remove(`${cwd}/untracked.txt`); + spawnedArgs.length = 0; yield* git(cwd, ["config", "branch.feature/x.t3-merge-base-ref", "refs/heads/main"]); yield* driver.statusDetailsLocal(cwd); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 6e7725833c022..66ab23e9c534e 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -94,6 +94,8 @@ const REVIEW_DIFF_PATCH_MAX_OUTPUT_BYTES = 120_000; const REVIEW_METADATA_MAX_OUTPUT_BYTES = 16 * 1024 * 1024; // Temporary-index git add scales poorly (50k files took ~30 s); report incomplete totals above this cap. const REVIEW_UNTRACKED_MAX_FILES = 5_000; +const REVIEW_TRACKED_PREVIEW_CAPACITY = 16; +const REVIEW_TRACKED_PREVIEW_TTL_MS = 30_000; // git diff reads every untracked byte (~5 ms/MB), so larger untracked input stays out of the review index. const REVIEW_UNTRACKED_MAX_BYTES = 256 * 1024 * 1024; // The listing walks the whole untracked tree before the cap applies, so a folder whose listing @@ -4439,6 +4441,44 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }; }); + type ReviewTrackedDiff = { + readonly stdout: string; + readonly stdoutTruncated: boolean; + readonly files: ReadonlyArray; + }; + // A trackedOnly read, kept by its completionToken so the complete read that follows it adds + // only the untracked files. Taken once, so a later complete read always reads fresh. + const trackedReviewPreviews = new Map< + string, + { + readonly key: string; + readonly expiresAt: number; + readonly repository: { readonly worktreeRoot: string; readonly currentBranch: string | null }; + readonly review: { readonly baseRef: string | null; readonly mergeBase: string | null }; + readonly dirty: ReviewTrackedDiff; + readonly base: ReviewTrackedDiff; + } + >(); + const trackedReviewPreviewKey = (input: ReviewDiffPreviewInput) => + JSON.stringify([ + input.cwd, + input.baseRef ?? null, + input.sourceKind ?? null, + input.ignoreWhitespace === true, + input.metadataOnly === true, + ]); + const takeTrackedReviewPreview = Effect.fn("takeTrackedReviewPreview")(function* ( + input: ReviewDiffPreviewInput, + ) { + if (input.completionToken === undefined || input.trackedOnly) return undefined; + const entry = trackedReviewPreviews.get(input.completionToken); + if (entry === undefined) return undefined; + trackedReviewPreviews.delete(input.completionToken); + if (entry.key !== trackedReviewPreviewKey(input)) return undefined; + if ((yield* Clock.currentTimeMillis) > entry.expiresAt) return undefined; + return entry; + }); + const getReviewDiffPreview = Effect.fn("getReviewDiffPreview")(function* ( input: ReviewDiffPreviewInput, ) { @@ -4467,12 +4507,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* input.commitSha === undefined && input.file?.sourceKind !== "commit" && sourceKind !== "working-tree"; - const repository = yield* resolveReviewRepository(input.cwd, needsCurrentBranch).pipe( - Effect.catchTags({ - GitCommandError: (error) => - isMissingGitCwdError(error) ? Effect.succeed(null) : Effect.fail(error), - }), - ); + const reusesTracked = input.file === undefined && input.commitSha === undefined; + const tracked = reusesTracked ? yield* takeTrackedReviewPreview(input) : undefined; + const repository = + tracked?.repository ?? + (yield* resolveReviewRepository(input.cwd, needsCurrentBranch).pipe( + Effect.catchTags({ + GitCommandError: (error) => + isMissingGitCwdError(error) ? Effect.succeed(null) : Effect.fail(error), + }), + )); if (!repository?.worktreeRoot) { return { cwd: input.cwd, @@ -4546,9 +4590,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const dirtyRef = sourceKind === "branch-range" ? null : "HEAD"; const review = - sourceKind === "working-tree" + tracked?.review ?? + (sourceKind === "working-tree" ? { baseRef: input.baseRef ?? null, mergeBase: null } - : yield* resolveReviewMergeBase(cwd, repository.currentBranch, input.baseRef); + : yield* resolveReviewMergeBase(cwd, repository.currentBranch, input.baseRef)); const diffArgs = [ ...REVIEW_DIFF_ARGS, @@ -4608,6 +4653,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* : yield* prepareUntrackedReviewIndex(cwd, pathArgs, input.file?.path); // Untracked files left out make the file list partial, so the bounded patch is sent instead. const complete = untracked !== null && !untracked.omitted; + // With no untracked files to add, the tracked read already is the complete diff. + if (tracked !== undefined && complete && untracked.env === undefined) { + return [tracked.dirty, tracked.base] as const; + } const metadataOnly = input.metadataOnly === true && !input.file && complete; const [dirty, base] = review.mergeBase === dirtyRef @@ -4626,6 +4675,22 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ref === null ? result : { ...result, files: undefined, stdoutTruncated: true }; return [incomplete(dirtyRef, dirty), incomplete(review.mergeBase, base)] as const; }).pipe(Effect.scoped); + let completionToken: string | undefined; + if (input.trackedOnly && reusesTracked && dirtyTrackedResult.files && baseResult.files) { + completionToken = yield* random.uuidV4(); + trackedReviewPreviews.set(completionToken, { + key: trackedReviewPreviewKey(input), + expiresAt: (yield* Clock.currentTimeMillis) + REVIEW_TRACKED_PREVIEW_TTL_MS, + repository, + review, + dirty: { ...dirtyTrackedResult, files: dirtyTrackedResult.files }, + base: { ...baseResult, files: baseResult.files }, + }); + if (trackedReviewPreviews.size > REVIEW_TRACKED_PREVIEW_CAPACITY) { + const oldestKey = trackedReviewPreviews.keys().next().value; + if (oldestKey !== undefined) trackedReviewPreviews.delete(oldestKey); + } + } const dirtyFiles = dirtyTrackedResult.files; const baseFiles = baseResult.files; const dirtyDiff = dirtyTrackedResult.stdout; @@ -4673,6 +4738,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ? sources.filter((source) => source.kind === input.sourceKind) : sources, ...(input.trackedOnly ? { incomplete: true } : {}), + ...(completionToken === undefined ? {} : { completionToken }), }; }); diff --git a/packages/client-runtime/src/state/review.ts b/packages/client-runtime/src/state/review.ts index a374e51b1df89..a92e213c44608 100644 --- a/packages/client-runtime/src/state/review.ts +++ b/packages/client-runtime/src/state/review.ts @@ -55,6 +55,12 @@ export function createReviewEnvironmentAtoms( // Older servers ignore trackedOnly and already return the complete preview. if (!tracked.incomplete) return tracked; yield* emit(tracked); + if (tracked.completionToken !== undefined) { + return yield* request(WS_METHODS.reviewGetDiffPreview, { + ...input, + completionToken: tracked.completionToken, + }); + } } return yield* request(WS_METHODS.reviewGetDiffPreview, input); }), diff --git a/packages/contracts/src/review.ts b/packages/contracts/src/review.ts index c663e2690056c..f8d8a6133358c 100644 --- a/packages/contracts/src/review.ts +++ b/packages/contracts/src/review.ts @@ -10,6 +10,8 @@ export const ReviewDiffPreviewInput = Schema.Struct({ ignoreWhitespace: Schema.optionalKey(Schema.Boolean), sourceKind: Schema.optionalKey(Schema.Literals(["working-tree", "branch-range"])), trackedOnly: Schema.optionalKey(Schema.Boolean), + /** From a trackedOnly result, so the complete read adds only the untracked files. */ + completionToken: Schema.optionalKey(Schema.String), metadataOnly: Schema.optionalKey(Schema.Boolean), file: Schema.optionalKey( Schema.Struct({ @@ -102,6 +104,7 @@ export const ReviewDiffPreviewResult = Schema.Struct({ generatedAt: Schema.DateTimeUtc, sources: Schema.Array(ReviewDiffPreviewSource), incomplete: Schema.optionalKey(Schema.Boolean), + completionToken: Schema.optionalKey(Schema.String), }); export type ReviewDiffPreviewResult = typeof ReviewDiffPreviewResult.Type; From 511447a9f2a9e8c376c59f5779feb60884d0bb00 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 00:53:50 -0800 Subject: [PATCH 05/39] feat(server): add a TanStack Source forge and issue tracker behind T3CODE_TANSTACK_SOURCE (#40207) Co-authored-by: Claude Opus 5.5 --- .../backend/DesktopBackendConfiguration.ts | 1 + .../src/shell/DesktopShellEnvironment.ts | 2 + apps/mobile/src/i18n/translations/de.json | 1 + apps/mobile/src/i18n/translations/en.json | 1 + apps/mobile/src/i18n/translations/es.json | 1 + apps/mobile/src/i18n/translations/fr.json | 1 + apps/mobile/src/i18n/translations/ja.json | 1 + apps/mobile/src/i18n/translations/ko.json | 1 + apps/mobile/src/i18n/translations/pt-BR.json | 1 + apps/mobile/src/i18n/translations/ru.json | 1 + apps/mobile/src/i18n/translations/sv.json | 1 + apps/mobile/src/i18n/translations/zh.json | 1 + apps/server/package.json | 1 + .../sourceControl/sourceControlDefinitions.ts | 16 +- apps/web/src/i18n/translations/de.json | 1 + apps/web/src/i18n/translations/en.json | 1 + apps/web/src/i18n/translations/es.json | 1 + apps/web/src/i18n/translations/fr.json | 1 + apps/web/src/i18n/translations/ja.json | 1 + apps/web/src/i18n/translations/ko.json | 1 + apps/web/src/i18n/translations/pt-BR.json | 1 + apps/web/src/i18n/translations/ru.json | 1 + apps/web/src/i18n/translations/sv.json | 1 + apps/web/src/i18n/translations/zh.json | 1 + docs/user/source-control.md | 18 + package.json | 2 +- packages/client-runtime/src/contractLabels.ts | 8 + .../src/sourceControlClients.test.ts | 25 + .../source-control-definitions/package.json | 3 +- .../src/registry.ts | 70 +- .../package.json | 31 + .../src/server/TanStackSourceApi.ts | 256 +++++ .../server/TanStackSourceCredentials.test.ts | 132 +++ .../src/server/TanStackSourceCredentials.ts | 249 +++++ .../server/TanStackSourceIssueTracker.test.ts | 192 ++++ .../src/server/TanStackSourceIssueTracker.ts | 430 ++++++++ .../TanStackSourcePullRequestProvider.ts | 957 ++++++++++++++++++ ...anStackSourceSourceControlProvider.test.ts | 132 +++ .../TanStackSourceSourceControlProvider.ts | 610 +++++++++++ .../src/server/driver.ts | 29 + .../server/tanStackSourceAuthStatus.test.ts | 75 ++ .../src/server/tanStackSourceAuthStatus.ts | 65 ++ .../src/server/tanStackSourceEvents.test.ts | 23 + .../src/server/tanStackSourceEvents.ts | 170 ++++ .../src/server/tanStackSourceHosts.ts | 42 + .../src/server/tanStackSourceJson.test.ts | 156 +++ .../src/server/tanStackSourceJson.ts | 494 +++++++++ .../src/server/tanStackSourceListing.test.ts | 110 ++ .../src/server/tanStackSourceListing.ts | 146 +++ .../src/shared/definition.test.ts | 37 + .../src/shared/definition.ts | 142 +++ .../src/shared/icon.ts | 12 + .../tsconfig.json | 7 + pnpm-lock.yaml | 34 + scripts/release-smoke.ts | 1 + 55 files changed, 4663 insertions(+), 35 deletions(-) create mode 100644 packages/source-control-tanstack-source/package.json create mode 100644 packages/source-control-tanstack-source/src/server/TanStackSourceApi.ts create mode 100644 packages/source-control-tanstack-source/src/server/TanStackSourceCredentials.test.ts create mode 100644 packages/source-control-tanstack-source/src/server/TanStackSourceCredentials.ts create mode 100644 packages/source-control-tanstack-source/src/server/TanStackSourceIssueTracker.test.ts create mode 100644 packages/source-control-tanstack-source/src/server/TanStackSourceIssueTracker.ts create mode 100644 packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.ts create mode 100644 packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts create mode 100644 packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts create mode 100644 packages/source-control-tanstack-source/src/server/driver.ts create mode 100644 packages/source-control-tanstack-source/src/server/tanStackSourceAuthStatus.test.ts create mode 100644 packages/source-control-tanstack-source/src/server/tanStackSourceAuthStatus.ts create mode 100644 packages/source-control-tanstack-source/src/server/tanStackSourceEvents.test.ts create mode 100644 packages/source-control-tanstack-source/src/server/tanStackSourceEvents.ts create mode 100644 packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts create mode 100644 packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts create mode 100644 packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts create mode 100644 packages/source-control-tanstack-source/src/server/tanStackSourceListing.test.ts create mode 100644 packages/source-control-tanstack-source/src/server/tanStackSourceListing.ts create mode 100644 packages/source-control-tanstack-source/src/shared/definition.test.ts create mode 100644 packages/source-control-tanstack-source/src/shared/definition.ts create mode 100644 packages/source-control-tanstack-source/src/shared/icon.ts create mode 100644 packages/source-control-tanstack-source/tsconfig.json diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.ts index 983c00a04c3fd..9c12690f31351 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts @@ -90,6 +90,7 @@ const WSL_FORWARDED_ENV_NAMES = [ "ANTHROPIC_API_KEY", "T3CODE_TELEMETRY_ENABLED", "T3CODE_GITHUB_APP_CLIENT_ID", + "T3CODE_TANSTACK_SOURCE", // Otherwise the WSL server keeps exporting to endpoints from the bootstrap. "T3CODE_OTEL_SDK_DISABLED", "OTEL_SDK_DISABLED", diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.ts b/apps/desktop/src/shell/DesktopShellEnvironment.ts index 8d046fc5ca646..3c90d7bfcaff1 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.ts @@ -124,6 +124,7 @@ const LOGIN_SHELL_ENV_NAMES = [ "NODE_EXTRA_CA_CERTS", "T3CODE_TELEMETRY_ENABLED", "T3CODE_GITHUB_APP_CLIENT_ID", + "T3CODE_TANSTACK_SOURCE", "T3CODE_RELEASE_BASE_URL", "__MISE_DIFF", "JAVA_HOME", @@ -553,6 +554,7 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix "PNPM_HOME", "T3CODE_TELEMETRY_ENABLED", "T3CODE_GITHUB_APP_CLIENT_ID", + "T3CODE_TANSTACK_SOURCE", "T3CODE_RELEASE_BASE_URL", ] as const) { if (!config.env[name] && shellEnvironment[name]) { diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 7c61d3f95e40d..8777f08e663ce 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -51,6 +51,7 @@ "d810ecd91e8cf9d0": "Installiere die Origin CLI mit {install} und führe dann {login} aus.", "eb0f60ef4f92ab7d": "Installiere {fj} 0.6 oder neuer von {fjUrl} und führe {fjLogin} aus, oder installiere {tea} 0.16 oder neuer von {teaUrl} und führe {teaLogin} für jeden Forgejo- oder Gitea-Server aus.", "d026a85e2e50e675": "Installiere die GitCafe CLI mit {install} und führe dann {login} aus, speichere ein Token in den Einstellungen oder setze {variable} auf dem Server.", + "22d3c0c48a34b5b3": "Installiere die TanStack Source CLI mit {install} und führe dann {login} aus, speichere ein Token in den Einstellungen oder setze {variable} auf dem Server.", "79d776428f4d0650": "Die Datei konnte nicht geladen werden. Verbinde dich erneut und versuch es noch einmal.", "3ea34cbb1ca5ba9b": "Vorschau abgebrochen.", "7c0af279ecb3da3a": "Streamende Dateivorschauen sind in dieser Laufzeitumgebung nicht verfügbar.", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 53ae1e18e3efa..dfe3a473fe248 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -51,6 +51,7 @@ "d810ecd91e8cf9d0": "Install the Origin CLI with {install}, then run {login}.", "eb0f60ef4f92ab7d": "Install {fj} 0.6 or later from {fjUrl} and run {fjLogin}, or install {tea} 0.16 or later from {teaUrl} and run {teaLogin} for each Forgejo or Gitea server.", "d026a85e2e50e675": "Install the GitCafe CLI with {install}, then run {login}, save a token in Settings, or set {variable} on the server.", + "22d3c0c48a34b5b3": "Install the TanStack Source CLI with {install}, then run {login}, save a token in Settings, or set {variable} on the server.", "79d776428f4d0650": "The file could not be loaded. Reconnect and try again.", "3ea34cbb1ca5ba9b": "Preview cancelled.", "7c0af279ecb3da3a": "Streaming file previews are unavailable in this runtime.", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index e8c92c5285382..05f58a63227d3 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -51,6 +51,7 @@ "d810ecd91e8cf9d0": "Instala la CLI de Origin con {install} y ejecuta {login}.", "eb0f60ef4f92ab7d": "Instala {fj} 0.6 o posterior desde {fjUrl} y ejecuta {fjLogin}, o instala {tea} 0.16 o posterior desde {teaUrl} y ejecuta {teaLogin} para cada servidor de Forgejo o Gitea.", "d026a85e2e50e675": "Instala la CLI de GitCafe con {install} y ejecuta {login}, guarda un token en Ajustes o define {variable} en el servidor.", + "22d3c0c48a34b5b3": "Instala la CLI de TanStack Source con {install} y ejecuta {login}, guarda un token en Ajustes o define {variable} en el servidor.", "79d776428f4d0650": "No se pudo cargar el archivo. Vuelve a conectarte e inténtalo de nuevo.", "3ea34cbb1ca5ba9b": "Vista previa cancelada.", "7c0af279ecb3da3a": "Las vistas previas de archivos en streaming no están disponibles en este entorno de ejecución.", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 9115edfa725dd..f661c315215c0 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -51,6 +51,7 @@ "d810ecd91e8cf9d0": "Installez la CLI Origin avec {install}, puis exécutez {login}.", "eb0f60ef4f92ab7d": "Installez {fj} 0.6 ou version ultérieure depuis {fjUrl} et exécutez {fjLogin}, ou installez {tea} 0.16 ou version ultérieure depuis {teaUrl} et exécutez {teaLogin} pour chaque serveur Forgejo ou Gitea.", "d026a85e2e50e675": "Installez la CLI GitCafe avec {install}, puis exécutez {login}, enregistrez un jeton dans Paramètres ou définissez {variable} sur le serveur.", + "22d3c0c48a34b5b3": "Installez la CLI TanStack Source avec {install}, puis exécutez {login}, enregistrez un jeton dans Paramètres ou définissez {variable} sur le serveur.", "79d776428f4d0650": "Le fichier n’a pas pu être chargé. Reconnectez-vous et réessayez.", "3ea34cbb1ca5ba9b": "Aperçu annulé.", "7c0af279ecb3da3a": "Les aperçus de fichiers en streaming ne sont pas disponibles dans cet environnement d’exécution.", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 3c6e09395d097..56616809052d3 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -51,6 +51,7 @@ "d810ecd91e8cf9d0": "{install} で Origin CLI をインストールしてから、{login} を実行してください。", "eb0f60ef4f92ab7d": "Forgejo または Gitea のサーバーごとに、{fjUrl} から {fj} 0.6 以降をインストールして {fjLogin} を実行するか、{teaUrl} から {tea} 0.16 以降をインストールして {teaLogin} を実行してください。", "d026a85e2e50e675": "{install} で GitCafe CLI をインストールしてから、{login} を実行するか、設定にトークンを保存するか、サーバーで {variable} を設定してください。", + "22d3c0c48a34b5b3": "{install} で TanStack Source CLI をインストールしてから、{login} を実行するか、設定にトークンを保存するか、サーバーで {variable} を設定してください。", "79d776428f4d0650": "ファイルを読み込めませんでした。再接続してもう一度お試しください。", "3ea34cbb1ca5ba9b": "プレビューをキャンセルしました。", "7c0af279ecb3da3a": "このランタイムではファイルのストリーミングプレビューを利用できません。", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 67eaab0392cd9..443285f8664c4 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -51,6 +51,7 @@ "d810ecd91e8cf9d0": "{install}로 Origin CLI를 설치한 후 {login}을(를) 실행하세요.", "eb0f60ef4f92ab7d": "{fjUrl}에서 {fj} 0.6 이상을 설치하고 {fjLogin}을(를) 실행하거나, {teaUrl}에서 {tea} 0.16 이상을 설치하고 Forgejo 또는 Gitea 서버마다 {teaLogin}을(를) 실행하세요.", "d026a85e2e50e675": "{install}로 GitCafe CLI를 설치한 후 {login}을(를) 실행하거나, 설정에 토큰을 저장하거나, 서버에서 {variable}을(를) 설정하세요.", + "22d3c0c48a34b5b3": "{install}로 TanStack Source CLI를 설치한 후 {login}을(를) 실행하거나, 설정에 토큰을 저장하거나, 서버에서 {variable}을(를) 설정하세요.", "79d776428f4d0650": "파일을 불러올 수 없습니다. 다시 연결한 뒤 시도하세요.", "3ea34cbb1ca5ba9b": "미리 보기가 취소되었습니다.", "7c0af279ecb3da3a": "이 런타임에서는 스트리밍 파일 미리 보기를 사용할 수 없습니다.", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 101a01c28c43e..33793cc553d34 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -51,6 +51,7 @@ "d810ecd91e8cf9d0": "Instale a CLI do Origin com {install} e execute {login}.", "eb0f60ef4f92ab7d": "Instale o {fj} 0.6 ou posterior em {fjUrl} e execute {fjLogin}, ou instale o {tea} 0.16 ou posterior em {teaUrl} e execute {teaLogin} para cada servidor Forgejo ou Gitea.", "d026a85e2e50e675": "Instale a CLI do GitCafe com {install} e execute {login}, salve um token nas Configurações ou defina {variable} no servidor.", + "22d3c0c48a34b5b3": "Instale a CLI do TanStack Source com {install} e execute {login}, salve um token nas Configurações ou defina {variable} no servidor.", "79d776428f4d0650": "Não foi possível carregar o arquivo. Reconecte e tente novamente.", "3ea34cbb1ca5ba9b": "Pré-visualização cancelada.", "7c0af279ecb3da3a": "As pré-visualizações de arquivos por streaming não estão disponíveis neste runtime.", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index e1578fe1ade8a..d0e2d9577a9ab 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -51,6 +51,7 @@ "d810ecd91e8cf9d0": "Установите Origin CLI командой {install}, затем выполните {login}.", "eb0f60ef4f92ab7d": "Установите {fj} 0.6 или новее с {fjUrl} и выполните {fjLogin} либо установите {tea} 0.16 или новее с {teaUrl} и выполните {teaLogin} для каждого сервера Forgejo или Gitea.", "d026a85e2e50e675": "Установите GitCafe CLI командой {install}, затем выполните {login}, сохраните токен в настройках или задайте {variable} на сервере.", + "22d3c0c48a34b5b3": "Установите TanStack Source CLI командой {install}, затем выполните {login}, сохраните токен в настройках или задайте {variable} на сервере.", "79d776428f4d0650": "Не удалось загрузить файл. Переподключитесь и попробуйте ещё раз.", "3ea34cbb1ca5ba9b": "Предпросмотр отменён.", "7c0af279ecb3da3a": "Потоковый предпросмотр файлов недоступен в этой среде выполнения.", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 0c1c76802160a..7fd2f945cc033 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -51,6 +51,7 @@ "d810ecd91e8cf9d0": "Installera Origin CLI med {install} och kör sedan {login}.", "eb0f60ef4f92ab7d": "Installera {fj} 0.6 eller senare från {fjUrl} och kör {fjLogin}, eller installera {tea} 0.16 eller senare från {teaUrl} och kör {teaLogin} för varje Forgejo- eller Gitea-server.", "d026a85e2e50e675": "Installera GitCafe CLI med {install} och kör sedan {login}, spara en token i Inställningar eller ange {variable} på servern.", + "22d3c0c48a34b5b3": "Installera TanStack Source CLI med {install} och kör sedan {login}, spara en token i Inställningar eller ange {variable} på servern.", "79d776428f4d0650": "Filen kunde inte läsas in. Återanslut och försök igen.", "3ea34cbb1ca5ba9b": "Förhandsvisningen avbröts.", "7c0af279ecb3da3a": "Strömmande förhandsvisning av filer är inte tillgänglig i den här körmiljön.", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 42127c1ec5d75..54c72efe3b4fb 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -51,6 +51,7 @@ "d810ecd91e8cf9d0": "请使用 {install} 安装 Origin CLI,然后运行 {login}。", "eb0f60ef4f92ab7d": "请从 {fjUrl} 安装 {fj} 0.6 或更高版本并运行 {fjLogin},或从 {teaUrl} 安装 {tea} 0.16 或更高版本,并为每个 Forgejo 或 Gitea 服务器运行 {teaLogin}。", "d026a85e2e50e675": "请使用 {install} 安装 GitCafe CLI,然后运行 {login}、在设置中保存 token,或在服务器上设置 {variable}。", + "22d3c0c48a34b5b3": "请使用 {install} 安装 TanStack Source CLI,然后运行 {login}、在设置中保存 token,或在服务器上设置 {variable}。", "79d776428f4d0650": "无法加载文件。请重新连接后重试。", "3ea34cbb1ca5ba9b": "预览已取消。", "7c0af279ecb3da3a": "此运行时不支持流式文件预览。", diff --git a/apps/server/package.json b/apps/server/package.json index 8ece0aaa8118f..9b9b3c022cacb 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -63,6 +63,7 @@ "@t3tools/source-control-gitcafe": "workspace:*", "@t3tools/source-control-github": "workspace:*", "@t3tools/source-control-gitlab": "workspace:*", + "@t3tools/source-control-tanstack-source": "workspace:*", "character-entities": "2.0.2", "diff": "8.0.3", "effect": "catalog:", diff --git a/apps/server/src/sourceControl/sourceControlDefinitions.ts b/apps/server/src/sourceControl/sourceControlDefinitions.ts index 670047ccae618..c6a770a897f02 100644 --- a/apps/server/src/sourceControl/sourceControlDefinitions.ts +++ b/apps/server/src/sourceControl/sourceControlDefinitions.ts @@ -1,11 +1,18 @@ import * as AzureDevOpsDriver from "@t3tools/source-control-azure-devops/server/driver"; import * as BitbucketDriver from "@t3tools/source-control-bitbucket/server/driver"; import * as CursorOriginDriver from "@t3tools/source-control-cursor-origin/server/driver"; -import { builtInSourceControlDefinitions } from "@t3tools/source-control-definitions/registry"; +import { makeBuiltInSourceControlDefinitions } from "@t3tools/source-control-definitions/registry"; import * as ForgejoDriver from "@t3tools/source-control-forgejo/server/driver"; import * as GitCafeDriver from "@t3tools/source-control-gitcafe/server/driver"; import * as GitHubDriver from "@t3tools/source-control-github/server/driver"; import * as GitLabDriver from "@t3tools/source-control-gitlab/server/driver"; +import * as TanStackSourceDriver from "@t3tools/source-control-tanstack-source/server/driver"; + +/** + * TanStack Source is in private beta, so its forge exists only on a server started with + * `T3CODE_TANSTACK_SOURCE=1`. Read once at load: the registry below is a module constant. + */ +const tanStackSourceEnabled = process.env.T3CODE_TANSTACK_SOURCE?.trim() === "1"; /** In the shared registry's order, which is the order hosts are listed and probed in. */ export const BUILT_IN_SOURCE_CONTROL_DRIVER_LIST = [ @@ -13,12 +20,15 @@ export const BUILT_IN_SOURCE_CONTROL_DRIVER_LIST = [ CursorOriginDriver.driver, GitLabDriver.driver, GitCafeDriver.driver, + ...(tanStackSourceEnabled ? [TanStackSourceDriver.driver] : []), ForgejoDriver.driver, BitbucketDriver.driver, AzureDevOpsDriver.driver, -] as const; +]; -export const sourceControlDefinitions = builtInSourceControlDefinitions; +export const sourceControlDefinitions = makeBuiltInSourceControlDefinitions({ + tanStackSource: tanStackSourceEnabled, +}); /** A host CLI command that merges or closes a change request, such as `gh pr merge`. */ export const isChangeRequestCloseCommand = (command: string) => diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index a792441bc36bb..0e48b30d674da 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -51,6 +51,7 @@ "d810ecd91e8cf9d0": "Installiere die Origin CLI mit {install} und führe dann {login} aus.", "eb0f60ef4f92ab7d": "Installiere {fj} 0.6 oder neuer von {fjUrl} und führe {fjLogin} aus, oder installiere {tea} 0.16 oder neuer von {teaUrl} und führe {teaLogin} für jeden Forgejo- oder Gitea-Server aus.", "d026a85e2e50e675": "Installiere die GitCafe CLI mit {install} und führe dann {login} aus, speichere ein Token in den Einstellungen oder setze {variable} auf dem Server.", + "22d3c0c48a34b5b3": "Installiere die TanStack Source CLI mit {install} und führe dann {login} aus, speichere ein Token in den Einstellungen oder setze {variable} auf dem Server.", "79d776428f4d0650": "Die Datei konnte nicht geladen werden. Verbinde dich erneut und versuch es noch einmal.", "3ea34cbb1ca5ba9b": "Vorschau abgebrochen.", "7c0af279ecb3da3a": "Streamende Dateivorschauen sind in dieser Laufzeitumgebung nicht verfügbar.", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 62f724c4999cc..e5d8d3dc2ed21 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -51,6 +51,7 @@ "d810ecd91e8cf9d0": "Install the Origin CLI with {install}, then run {login}.", "eb0f60ef4f92ab7d": "Install {fj} 0.6 or later from {fjUrl} and run {fjLogin}, or install {tea} 0.16 or later from {teaUrl} and run {teaLogin} for each Forgejo or Gitea server.", "d026a85e2e50e675": "Install the GitCafe CLI with {install}, then run {login}, save a token in Settings, or set {variable} on the server.", + "22d3c0c48a34b5b3": "Install the TanStack Source CLI with {install}, then run {login}, save a token in Settings, or set {variable} on the server.", "79d776428f4d0650": "The file could not be loaded. Reconnect and try again.", "3ea34cbb1ca5ba9b": "Preview cancelled.", "7c0af279ecb3da3a": "Streaming file previews are unavailable in this runtime.", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 911cf253e614e..4a2868a7e97dc 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -51,6 +51,7 @@ "d810ecd91e8cf9d0": "Instala la CLI de Origin con {install} y ejecuta {login}.", "eb0f60ef4f92ab7d": "Instala {fj} 0.6 o posterior desde {fjUrl} y ejecuta {fjLogin}, o instala {tea} 0.16 o posterior desde {teaUrl} y ejecuta {teaLogin} para cada servidor de Forgejo o Gitea.", "d026a85e2e50e675": "Instala la CLI de GitCafe con {install} y ejecuta {login}, guarda un token en Ajustes o define {variable} en el servidor.", + "22d3c0c48a34b5b3": "Instala la CLI de TanStack Source con {install} y ejecuta {login}, guarda un token en Ajustes o define {variable} en el servidor.", "79d776428f4d0650": "No se pudo cargar el archivo. Vuelve a conectarte e inténtalo de nuevo.", "3ea34cbb1ca5ba9b": "Vista previa cancelada.", "7c0af279ecb3da3a": "Las vistas previas de archivos en streaming no están disponibles en este entorno de ejecución.", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index a9a8a1581d5bd..a0962e52bed39 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -51,6 +51,7 @@ "d810ecd91e8cf9d0": "Installez la CLI Origin avec {install}, puis exécutez {login}.", "eb0f60ef4f92ab7d": "Installez {fj} 0.6 ou version ultérieure depuis {fjUrl} et exécutez {fjLogin}, ou installez {tea} 0.16 ou version ultérieure depuis {teaUrl} et exécutez {teaLogin} pour chaque serveur Forgejo ou Gitea.", "d026a85e2e50e675": "Installez la CLI GitCafe avec {install}, puis exécutez {login}, enregistrez un jeton dans Paramètres ou définissez {variable} sur le serveur.", + "22d3c0c48a34b5b3": "Installez la CLI TanStack Source avec {install}, puis exécutez {login}, enregistrez un jeton dans Paramètres ou définissez {variable} sur le serveur.", "79d776428f4d0650": "Le fichier n’a pas pu être chargé. Reconnectez-vous et réessayez.", "3ea34cbb1ca5ba9b": "Aperçu annulé.", "7c0af279ecb3da3a": "Les aperçus de fichiers en streaming ne sont pas disponibles dans cet environnement d’exécution.", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 15378ea0c7f4d..0c149c28fbe91 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -51,6 +51,7 @@ "d810ecd91e8cf9d0": "{install} で Origin CLI をインストールしてから、{login} を実行してください。", "eb0f60ef4f92ab7d": "Forgejo または Gitea のサーバーごとに、{fjUrl} から {fj} 0.6 以降をインストールして {fjLogin} を実行するか、{teaUrl} から {tea} 0.16 以降をインストールして {teaLogin} を実行してください。", "d026a85e2e50e675": "{install} で GitCafe CLI をインストールしてから、{login} を実行するか、設定にトークンを保存するか、サーバーで {variable} を設定してください。", + "22d3c0c48a34b5b3": "{install} で TanStack Source CLI をインストールしてから、{login} を実行するか、設定にトークンを保存するか、サーバーで {variable} を設定してください。", "79d776428f4d0650": "ファイルを読み込めませんでした。再接続してもう一度お試しください。", "3ea34cbb1ca5ba9b": "プレビューをキャンセルしました。", "7c0af279ecb3da3a": "このランタイムではファイルのストリーミングプレビューを利用できません。", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 4466398b827e7..c01191b387b4f 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -51,6 +51,7 @@ "d810ecd91e8cf9d0": "{install}로 Origin CLI를 설치한 후 {login}을(를) 실행하세요.", "eb0f60ef4f92ab7d": "{fjUrl}에서 {fj} 0.6 이상을 설치하고 {fjLogin}을(를) 실행하거나, {teaUrl}에서 {tea} 0.16 이상을 설치하고 Forgejo 또는 Gitea 서버마다 {teaLogin}을(를) 실행하세요.", "d026a85e2e50e675": "{install}로 GitCafe CLI를 설치한 후 {login}을(를) 실행하거나, 설정에 토큰을 저장하거나, 서버에서 {variable}을(를) 설정하세요.", + "22d3c0c48a34b5b3": "{install}로 TanStack Source CLI를 설치한 후 {login}을(를) 실행하거나, 설정에 토큰을 저장하거나, 서버에서 {variable}을(를) 설정하세요.", "79d776428f4d0650": "파일을 불러올 수 없습니다. 다시 연결한 뒤 시도하세요.", "3ea34cbb1ca5ba9b": "미리 보기가 취소되었습니다.", "7c0af279ecb3da3a": "이 런타임에서는 스트리밍 파일 미리 보기를 사용할 수 없습니다.", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index ac79a77f16635..5feb95d75c3da 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -51,6 +51,7 @@ "d810ecd91e8cf9d0": "Instale a CLI do Origin com {install} e execute {login}.", "eb0f60ef4f92ab7d": "Instale o {fj} 0.6 ou posterior em {fjUrl} e execute {fjLogin}, ou instale o {tea} 0.16 ou posterior em {teaUrl} e execute {teaLogin} para cada servidor Forgejo ou Gitea.", "d026a85e2e50e675": "Instale a CLI do GitCafe com {install} e execute {login}, salve um token nas Configurações ou defina {variable} no servidor.", + "22d3c0c48a34b5b3": "Instale a CLI do TanStack Source com {install} e execute {login}, salve um token nas Configurações ou defina {variable} no servidor.", "79d776428f4d0650": "Não foi possível carregar o arquivo. Reconecte e tente novamente.", "3ea34cbb1ca5ba9b": "Pré-visualização cancelada.", "7c0af279ecb3da3a": "As pré-visualizações de arquivos por streaming não estão disponíveis neste runtime.", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 17f514f0b3e0a..65a8eede879fa 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -51,6 +51,7 @@ "d810ecd91e8cf9d0": "Установите Origin CLI командой {install}, затем выполните {login}.", "eb0f60ef4f92ab7d": "Установите {fj} 0.6 или новее с {fjUrl} и выполните {fjLogin} либо установите {tea} 0.16 или новее с {teaUrl} и выполните {teaLogin} для каждого сервера Forgejo или Gitea.", "d026a85e2e50e675": "Установите GitCafe CLI командой {install}, затем выполните {login}, сохраните токен в настройках или задайте {variable} на сервере.", + "22d3c0c48a34b5b3": "Установите TanStack Source CLI командой {install}, затем выполните {login}, сохраните токен в настройках или задайте {variable} на сервере.", "79d776428f4d0650": "Не удалось загрузить файл. Переподключитесь и попробуйте ещё раз.", "3ea34cbb1ca5ba9b": "Предпросмотр отменён.", "7c0af279ecb3da3a": "Потоковый предпросмотр файлов недоступен в этой среде выполнения.", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index da8cb638b7fea..081857c5dae81 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -51,6 +51,7 @@ "d810ecd91e8cf9d0": "Installera Origin CLI med {install} och kör sedan {login}.", "eb0f60ef4f92ab7d": "Installera {fj} 0.6 eller senare från {fjUrl} och kör {fjLogin}, eller installera {tea} 0.16 eller senare från {teaUrl} och kör {teaLogin} för varje Forgejo- eller Gitea-server.", "d026a85e2e50e675": "Installera GitCafe CLI med {install} och kör sedan {login}, spara en token i Inställningar eller ange {variable} på servern.", + "22d3c0c48a34b5b3": "Installera TanStack Source CLI med {install} och kör sedan {login}, spara en token i Inställningar eller ange {variable} på servern.", "79d776428f4d0650": "Filen kunde inte läsas in. Återanslut och försök igen.", "3ea34cbb1ca5ba9b": "Förhandsvisningen avbröts.", "7c0af279ecb3da3a": "Strömmande förhandsvisning av filer är inte tillgänglig i den här körmiljön.", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 2f5ea4af0ddad..17d0dd6a93303 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -51,6 +51,7 @@ "d810ecd91e8cf9d0": "请使用 {install} 安装 Origin CLI,然后运行 {login}。", "eb0f60ef4f92ab7d": "请从 {fjUrl} 安装 {fj} 0.6 或更高版本并运行 {fjLogin},或从 {teaUrl} 安装 {tea} 0.16 或更高版本,并为每个 Forgejo 或 Gitea 服务器运行 {teaLogin}。", "d026a85e2e50e675": "请使用 {install} 安装 GitCafe CLI,然后运行 {login}、在设置中保存 token,或在服务器上设置 {variable}。", + "22d3c0c48a34b5b3": "请使用 {install} 安装 TanStack Source CLI,然后运行 {login}、在设置中保存 token,或在服务器上设置 {variable}。", "79d776428f4d0650": "无法加载文件。请重新连接后重试。", "3ea34cbb1ca5ba9b": "预览已取消。", "7c0af279ecb3da3a": "此运行时不支持流式文件预览。", diff --git a/docs/user/source-control.md b/docs/user/source-control.md index 967f802d5389d..c04060ba831a3 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -144,6 +144,24 @@ sent to `git.cafe`; `CAFE_TOKEN` follows `CAFE_HOST` if you set it. Repositories Line comments are not available for GitCafe pull requests yet. Merging a stack lands it through GitCafe, and updating a branch restacks the layers above it. +### TanStack Source + +TanStack Source is in private beta, so the server shows it only when started with +`T3CODE_TANSTACK_SOURCE=1` in its environment. Install its CLI and sign in: + +```sh +curl -fsSL https://source.tanstack.com/install | sh +src auth login --web +``` + +Alternatively, open **Settings → Source control & issues**, expand **TanStack Source**, and enter a token +from `https://source.tanstack.com/settings/tokens`. A saved token is used before `SRC_TOKEN`, which is +used before the `src` login. With several `src` logins, pick the account there too. + +Pull requests show the runs of TanStack Source CI with their logs, and update live while open. Issues +can be listed, filed, edited, commented on and closed. Reactions and picking reviewers or assignees +from a list are not available yet. + ### Cursor Origin Install the [Origin CLI](https://cursor.com/docs/origin/cli) and sign in. Signing in also sets up Git diff --git a/package.json b/package.json index c3c4aaf49dba3..9f1d2bee11b58 100644 --- a/package.json +++ b/package.json @@ -36,7 +36,7 @@ "knip": "knip --preprocessor ./scripts/knip-schemas.ts", "knip:check": "vp run knip:check:all", "knip:check:files": "knip --include files,dependencies --no-config-hints", - "knip:check:exports": "knip --workspace apps/server --workspace apps/desktop --workspace apps/web --workspace packages/client-runtime --workspace packages/contracts --workspace packages/effect-acp --workspace packages/effect-codex-app-server --workspace packages/shared --workspace packages/ssh --workspace packages/tailscale --workspace packages/provider-core --workspace packages/provider-acp --workspace packages/provider-acp-registry --workspace packages/provider-testing --workspace packages/provider-pi --workspace packages/provider-muse --workspace packages/provider-opencode --workspace packages/provider-cursor --workspace packages/provider-fx --workspace packages/provider-grok --workspace packages/provider-kiro --workspace packages/secret-provider-core --workspace packages/secret-provider-definitions --workspace packages/secret-provider-onepassword --workspace packages/source-control-core --workspace packages/source-control-cursor-origin --workspace packages/source-control-definitions --workspace packages/source-control-azure-devops --workspace packages/source-control-bitbucket --workspace packages/source-control-forgejo --workspace packages/source-control-gitcafe --workspace packages/source-control-github --workspace packages/source-control-gitlab --workspace packages/source-control-testing --exports --preprocessor ./scripts/knip-schemas.ts --no-config-hints", + "knip:check:exports": "knip --workspace apps/server --workspace apps/desktop --workspace apps/web --workspace packages/client-runtime --workspace packages/contracts --workspace packages/effect-acp --workspace packages/effect-codex-app-server --workspace packages/shared --workspace packages/ssh --workspace packages/tailscale --workspace packages/provider-core --workspace packages/provider-acp --workspace packages/provider-acp-registry --workspace packages/provider-testing --workspace packages/provider-pi --workspace packages/provider-muse --workspace packages/provider-opencode --workspace packages/provider-cursor --workspace packages/provider-fx --workspace packages/provider-grok --workspace packages/provider-kiro --workspace packages/secret-provider-core --workspace packages/secret-provider-definitions --workspace packages/secret-provider-onepassword --workspace packages/source-control-core --workspace packages/source-control-cursor-origin --workspace packages/source-control-definitions --workspace packages/source-control-azure-devops --workspace packages/source-control-bitbucket --workspace packages/source-control-forgejo --workspace packages/source-control-gitcafe --workspace packages/source-control-github --workspace packages/source-control-gitlab --workspace packages/source-control-tanstack-source --workspace packages/source-control-testing --exports --preprocessor ./scripts/knip-schemas.ts --no-config-hints", "knip:production": "knip --production --preprocessor ./scripts/knip-schemas.ts", "lint:mobile": "node scripts/mobile-native-static-check.ts", "mobile:install": "node scripts/mobile-native-client.ts ensure", diff --git a/packages/client-runtime/src/contractLabels.ts b/packages/client-runtime/src/contractLabels.ts index bfeb284300b09..ee4e24dfde462 100644 --- a/packages/client-runtime/src/contractLabels.ts +++ b/packages/client-runtime/src/contractLabels.ts @@ -283,6 +283,14 @@ const INSTALL_HINTS = [ variable: "CAFE_TOKEN", }, ), + msg( + "Install the TanStack Source CLI with {install}, then run {login}, save a token in Settings, or set {variable} on the server.", + { + install: "`curl -fsSL https://source.tanstack.com/install | sh`", + login: "`src auth login --web --hostname source.tanstack.com`", + variable: "SRC_TOKEN", + }, + ), ]; /** @public A source-control `installHint`, translated when it is one of the server's fixed hints. */ diff --git a/packages/client-runtime/src/sourceControlClients.test.ts b/packages/client-runtime/src/sourceControlClients.test.ts index acac229e6c1fa..684b26ddf5e36 100644 --- a/packages/client-runtime/src/sourceControlClients.test.ts +++ b/packages/client-runtime/src/sourceControlClients.test.ts @@ -1,4 +1,5 @@ import { ProjectId, SourceControlProviderKind } from "@t3tools/contracts"; +import { makeBuiltInSourceControlDefinitions } from "@t3tools/source-control-definitions/registry"; import { describe, expect, it } from "vite-plus/test"; import { appSignInTargetForRemote, sourceControlClients } from "./sourceControlClients.ts"; @@ -38,6 +39,25 @@ describe("sourceControlClients.parseChangeRequestUrl", () => { }); }); + it("reads a TanStack Source pull request under its @owner path, not as GitHub's /pull/", () => { + const url = "https://source.tanstack.com/@TanStack/router/pull/8882/files"; + expect(parse(url)).toEqual({ + host: "source.tanstack.com", + repository: "tanstack/router", + number: 8882, + }); + expect(kindOf(url)).toBe("tanstack-source"); + expect(sourceControlClients.parseChangeRequestUrl(url)?.link.repositoryUrl).toBe( + "https://source.tanstack.com/@TanStack/router", + ); + // A server without the beta reads no TanStack Source host at all. + const without = makeBuiltInSourceControlDefinitions({ tanStackSource: false }); + expect(without.find(SourceControlProviderKind.make("tanstack-source"))).toBeUndefined(); + expect(without.recognizeRemote("https://source.tanstack.com/@TanStack/router.git")?.kind).toBe( + "unknown", + ); + }); + it("reads a Cursor Origin pull request under Origin's git host, not as GitHub's /pull/", () => { for (const url of [ "https://cursor.com/codebase/Acme.Team/Web-App/pull/42", @@ -276,6 +296,9 @@ describe("sourceControlClients.recognizeRemote", () => { expect(kindOfRemote("https://bitbucket.visualstudio.com/p/_git/r")).toBe("azure-devops"); expect(kindOfRemote("git@git.cafe:pingdotgg/t3code.git")).toBe("gitcafe"); expect(kindOfRemote("https://origin.cursor.com/acme/web.git")).toBe("cursor-origin"); + expect(kindOfRemote("https://source.tanstack.com/@TanStack/router.git")).toBe( + "tanstack-source", + ); }); it("reads a remote no host claims as an unknown host, and a local path as no host", () => { @@ -317,6 +340,8 @@ describe("sourceControlClients repository keys", () => { ["git@ssh.dev.azure.com:v3/o/p", "ssh.dev.azure.com/v3/o/p"], ["ssh.dev.azure.com/v3/o/p/r", "ssh.dev.azure.com/v3/o/p/r"], ["C:/repos/project", "c:/repos/project"], + // The owner's `@` is the web's spelling; the API and every key name it without. + ["https://source.tanstack.com/@TanStack/router.git", "source.tanstack.com/tanstack/router"], ])("keys %s as %s", (remote, key) => { expect(sourceControlClients.repositoryKeyFromRemote(remote)).toBe(key); }); diff --git a/packages/source-control-definitions/package.json b/packages/source-control-definitions/package.json index e42db9e0f617a..35161ff7b8753 100644 --- a/packages/source-control-definitions/package.json +++ b/packages/source-control-definitions/package.json @@ -19,6 +19,7 @@ "@t3tools/source-control-forgejo": "workspace:*", "@t3tools/source-control-gitcafe": "workspace:*", "@t3tools/source-control-github": "workspace:*", - "@t3tools/source-control-gitlab": "workspace:*" + "@t3tools/source-control-gitlab": "workspace:*", + "@t3tools/source-control-tanstack-source": "workspace:*" } } diff --git a/packages/source-control-definitions/src/registry.ts b/packages/source-control-definitions/src/registry.ts index afdb5d424bfdf..46bc9c5b0abd4 100644 --- a/packages/source-control-definitions/src/registry.ts +++ b/packages/source-control-definitions/src/registry.ts @@ -6,39 +6,49 @@ import * as Forgejo from "@t3tools/source-control-forgejo/shared/definition"; import * as GitCafe from "@t3tools/source-control-gitcafe/shared/definition"; import * as GitHub from "@t3tools/source-control-github/shared/definition"; import * as GitLab from "@t3tools/source-control-gitlab/shared/definition"; +import * as TanStackSource from "@t3tools/source-control-tanstack-source/shared/definition"; export { canonicalizePullRequestUrl as canonicalizeGitCafePullRequestUrl } from "@t3tools/source-control-gitcafe/shared/definition"; /** - * GitHub comes first to preserve the client default for repositories with an unknown host. - * GitCafe and Cursor Origin claim URLs first because GitHub and Forgejo accept the same routes on - * any hostname. - * Remote recognition needs its own order because host labels can overlap (`gitea.github.example`). + * GitHub comes first as the client default for unknown hosts. GitCafe, TanStack Source and Origin + * claim URLs first: GitHub and Forgejo accept the same routes on any hostname. TanStack Source is a + * private beta a server may leave out; clients always know it, for a server that has it. */ -export const builtInSourceControlDefinitions = makeSourceControlDefinitionRegistry( - [ - GitHub.definition, - CursorOrigin.definition, - GitLab.definition, - GitCafe.definition, - Forgejo.definition, - Bitbucket.definition, - AzureDevOps.definition, - ], - { - claimChangeRequestUrlsFirst: [ - GitCafe.definition.kind, - CursorOrigin.definition.kind, - AzureDevOps.definition.kind, +export function makeBuiltInSourceControlDefinitions(options: { readonly tanStackSource: boolean }) { + const tanStackSource = options.tanStackSource ? [TanStackSource.definition] : []; + return makeSourceControlDefinitionRegistry( + [ + GitHub.definition, + CursorOrigin.definition, + GitLab.definition, + GitCafe.definition, + ...tanStackSource, + Forgejo.definition, + Bitbucket.definition, + AzureDevOps.definition, ], - recognizeRemotesIn: [ - GitCafe.definition.kind, - CursorOrigin.definition.kind, - Forgejo.definition.kind, - GitHub.definition.kind, - GitLab.definition.kind, - AzureDevOps.definition.kind, - Bitbucket.definition.kind, - ], - }, -); + { + claimChangeRequestUrlsFirst: [ + GitCafe.definition.kind, + ...tanStackSource.map((definition) => definition.kind), + CursorOrigin.definition.kind, + AzureDevOps.definition.kind, + ], + recognizeRemotesIn: [ + GitCafe.definition.kind, + ...tanStackSource.map((definition) => definition.kind), + CursorOrigin.definition.kind, + Forgejo.definition.kind, + GitHub.definition.kind, + GitLab.definition.kind, + AzureDevOps.definition.kind, + Bitbucket.definition.kind, + ], + }, + ); +} + +export const builtInSourceControlDefinitions = makeBuiltInSourceControlDefinitions({ + tanStackSource: true, +}); diff --git a/packages/source-control-tanstack-source/package.json b/packages/source-control-tanstack-source/package.json new file mode 100644 index 0000000000000..e4b2db9d2bad2 --- /dev/null +++ b/packages/source-control-tanstack-source/package.json @@ -0,0 +1,31 @@ +{ + "name": "@t3tools/source-control-tanstack-source", + "private": true, + "type": "module", + "exports": { + "./shared/definition": { + "types": "./src/shared/definition.ts", + "import": "./src/shared/definition.ts" + }, + "./server/driver": { + "types": "./src/server/driver.ts", + "import": "./src/server/driver.ts" + } + }, + "scripts": { + "typecheck": "effect-tsgo tsrs --noEmit", + "test": "vp test run --config ../../vite.config.ts --dir ." + }, + "dependencies": { + "@t3tools/contracts": "workspace:*", + "@t3tools/shared": "workspace:*", + "@t3tools/source-control-core": "workspace:*", + "effect": "catalog:" + }, + "devDependencies": { + "@effect/vitest": "catalog:", + "@t3tools/source-control-testing": "workspace:*", + "@types/node": "catalog:", + "vite-plus": "catalog:" + } +} diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourceApi.ts b/packages/source-control-tanstack-source/src/server/TanStackSourceApi.ts new file mode 100644 index 0000000000000..05bd5baded8d8 --- /dev/null +++ b/packages/source-control-tanstack-source/src/server/TanStackSourceApi.ts @@ -0,0 +1,256 @@ +import * as Clock from "effect/Clock"; +import * as Context from "effect/Context"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Redacted from "effect/Redacted"; +import * as Schema from "effect/Schema"; +import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import * as HttpClient from "effect/http/HttpClient"; +import * as HttpClientRequest from "effect/http/HttpClientRequest"; + +import * as Credentials from "./TanStackSourceCredentials.ts"; +import * as Hosts from "./tanStackSourceHosts.ts"; + +const NO_REDIRECT: RequestInit = { redirect: "manual" }; +const MAX_REDIRECTS = 3; +const TIMEOUT = Duration.seconds(30); + +export const TanStackSourceApiFailure = Schema.Literals([ + "missing-tool", + "unauthenticated", + "forbidden", + "rate-limited", + "not-found", + "failed", +]); + +export class TanStackSourceApiError extends Schema.TaggedError()( + "TanStackSourceApiError", + { + host: Schema.String, + operation: Schema.String, + status: Schema.NullOr(Schema.Int), + reason: TanStackSourceApiFailure, + detail: Schema.String, + retryAt: Schema.optional(Schema.Number), + cause: Schema.optional(Schema.Defect()), + }, +) { + override get message(): string { + return `TanStack Source ${this.operation} failed on ${this.host}: ${this.detail}`; + } +} + +export interface TanStackSourceApiRequest { + readonly host: string; + readonly operation: string; + readonly method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE"; + /** Below `/api/v1`, starting with `/`. */ + readonly path: string; + readonly body?: unknown; + readonly accept?: string; +} + +export interface TanStackSourceApiResponse { + readonly status: number; + readonly headers: Readonly>; + readonly text: string; +} + +export class TanStackSourceApi extends Context.Service< + TanStackSourceApi, + { + readonly request: ( + input: TanStackSourceApiRequest, + ) => Effect.Effect; + /** `request` with the response headers, for routes that answer in them (job logs). */ + readonly response: ( + input: TanStackSourceApiRequest, + ) => Effect.Effect; + } +>()("@t3tools/source-control-tanstack-source/server/TanStackSourceApi") {} + +const decodeProblem = Schema.decodeUnknownOption( + Schema.fromJsonString( + Schema.Struct({ + error: Schema.optional(Schema.String), + message: Schema.optional(Schema.String), + }), + ), +); + +const reasonForStatus = (status: number): typeof TanStackSourceApiFailure.Type => + status === 401 + ? "unauthenticated" + : status === 403 + ? "forbidden" + : status === 429 + ? "rate-limited" + : status === 404 + ? "not-found" + : "failed"; + +const MAX_PROBLEM_TEXT = 300; +const boundedProblemText = (text: string | undefined) => { + const line = text?.replace(/\s+/gu, " ").trim(); + if (!line) return undefined; + return line.length > MAX_PROBLEM_TEXT ? `${line.slice(0, MAX_PROBLEM_TEXT)}…` : line; +}; + +const credentialFailure = ( + error: Credentials.TanStackSourceCredentialUnavailableError, +): typeof TanStackSourceApiFailure.Type => + error._tag === "TanStackSourceCliMissingError" + ? "missing-tool" + : error._tag === "TanStackSourceCliFailedError" || + error._tag === "TanStackSourceCliTimeoutError" + ? "failed" + : "unauthenticated"; + +const REDIRECTS = new Set([301, 302, 303, 307, 308]); +// 307 and 308 keep the method and body; the others only safely repeat a read. +const METHOD_PRESERVING = new Set([307, 308]); + +/** A transferred issue answers 301 with its new place; follow it only within this host's API. */ +const redirectTarget = ( + method: string, + origin: string, + from: string, + response: { readonly status: number; readonly location: string | undefined }, +): string | null => { + if (!REDIRECTS.has(response.status) || response.location === undefined) return null; + if (method !== "GET" && !METHOD_PRESERVING.has(response.status)) return null; + const target = URL.parse(response.location, from); + return target !== null && + target.origin === origin && + target.username === "" && + target.password === "" && + target.pathname.startsWith("/api/v1/") + ? target.href + : null; +}; + +const retryAtFrom = (headers: Readonly>, now: number) => { + const seconds = Number(headers["retry-after"]); + return Number.isFinite(seconds) && seconds >= 0 ? now + seconds * 1_000 : undefined; +}; + +/** @public */ +export const make = Effect.gen(function* () { + const httpClient = yield* HttpClient.HttpClient; + const credentials = yield* Credentials.TanStackSourceCredentials; + + const response = Effect.fn("TanStackSourceApi.request")(function* ( + input: TanStackSourceApiRequest, + ) { + const fail = ( + fields: Pick & { + readonly cause?: unknown; + readonly retryAt?: number | undefined; + }, + ) => + new TanStackSourceApiError({ + host: input.host, + operation: input.operation, + status: fields.status, + reason: fields.reason, + detail: fields.detail, + ...(fields.retryAt === undefined ? {} : { retryAt: fields.retryAt }), + ...(fields.cause === undefined ? {} : { cause: fields.cause }), + }); + // A remote or link may name any host; the token only goes to Source's own. + const host = Hosts.tanStackSourceHost(input.host); + if (host === null) + return yield* fail({ + status: null, + reason: "failed", + detail: `TanStack Source lives on ${Hosts.TANSTACK_SOURCE_HOSTS.join(" and ")}, not ${input.host}.`, + }); + const method = input.method ?? "GET"; + yield* Effect.annotateCurrentSpan({ + "tanstack_source.host": host, + "tanstack_source.operation": input.operation, + "http.request.method": method, + }); + const credential = yield* credentials + .get(host) + .pipe( + Effect.mapError((cause) => + fail({ status: null, reason: credentialFailure(cause), detail: cause.message, cause }), + ), + ); + const origin = `https://${host}`; + const send = (url: string) => { + const base = HttpClientRequest.make(method)(url).pipe( + HttpClientRequest.bearerToken(Redacted.value(credential.token)), + HttpClientRequest.setHeaders({ + accept: input.accept ?? "application/json", + "user-agent": "t3code", + }), + ); + return Effect.gen(function* () { + const reply = yield* httpClient + .execute( + input.body === undefined + ? base + : base.pipe(HttpClientRequest.bodyJsonUnsafe(input.body)), + ) + .pipe( + // Client spans expose query strings carrying branch names. + Effect.provideService(HttpClient.TracerDisabledWhen, () => true), + // fetch would carry the bearer token to any redirect target. + Effect.provideService(FetchHttpClient.RequestInit, NO_REDIRECT), + ); + return { status: reply.status, headers: reply.headers, text: yield* reply.text }; + }).pipe( + Effect.timeout(TIMEOUT), + Effect.mapError((cause) => + fail({ + status: null, + reason: "failed", + detail: "Could not reach TanStack Source.", + cause, + }), + ), + ); + }; + let url = `${origin}/api/v1${input.path}`; + let reply = yield* send(url); + for (let hop = 0; hop < MAX_REDIRECTS; hop++) { + const next = redirectTarget(method, origin, url, { + status: reply.status, + location: reply.headers.location, + }); + if (next === null) break; + url = next; + reply = yield* send(url); + } + yield* Effect.annotateCurrentSpan({ "http.response.status_code": reply.status }); + if (reply.status >= 200 && reply.status < 300) return reply; + // The source may hold a newer token than the one that was refused. + if (reply.status === 401) yield* credentials.invalidate(host); + const problem = Option.getOrUndefined(decodeProblem(reply.text)); + return yield* fail({ + status: reply.status, + reason: reasonForStatus(reply.status), + detail: + boundedProblemText(problem?.error ?? problem?.message) ?? + `TanStack Source answered HTTP ${reply.status}.`, + retryAt: + reply.status === 429 + ? retryAtFrom(reply.headers, yield* Clock.currentTimeMillis) + : undefined, + }); + }); + + return TanStackSourceApi.of({ + response, + request: Effect.fn("TanStackSourceApi.requestText")(function* (input) { + return (yield* response(input)).text; + }), + }); +}); + +export const layer = Layer.effect(TanStackSourceApi, make); diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourceCredentials.test.ts b/packages/source-control-tanstack-source/src/server/TanStackSourceCredentials.test.ts new file mode 100644 index 0000000000000..21f5b7f1ea894 --- /dev/null +++ b/packages/source-control-tanstack-source/src/server/TanStackSourceCredentials.test.ts @@ -0,0 +1,132 @@ +import { assert, describe, it } from "@effect/vitest"; +import { VcsProcessExitError } from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; +import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Redacted from "effect/Redacted"; + +import * as TanStackSourceCredentials from "./TanStackSourceCredentials.ts"; + +const processOutput = TestSourceControlHost.processOutput; +const HOST = "source.tanstack.com"; + +function harness( + run: SourceControlHost.SourceControlHost["Service"]["process"]["run"], + env: NodeJS.ProcessEnv = {}, +) { + const calls: Array = []; + const layer = TanStackSourceCredentials.layer.pipe( + Layer.provideMerge( + TestSourceControlHost.layer({ + process: { + run: (input) => { + calls.push(input); + return run(input); + }, + }, + }), + ), + Layer.provide(Layer.succeed(HostProcess.Environment, env)), + Layer.provide(Layer.succeed(HostProcess.WorkingDirectory, "/server")), + ); + return { layer, calls }; +} + +const notSignedIn = (input: SourceControlHost.SourceControlProcessInput) => + Effect.fail( + new VcsProcessExitError({ + operation: input.operation, + command: input.command, + cwd: input.cwd, + exitCode: 1, + detail: "no oauth token found", + }), + ); + +describe("TanStackSourceCredentials", () => { + it("hands SRC_TOKEN only to the host src itself sends it to", () => { + const token = { SRC_TOKEN: "tsp_env" }; + assert.strictEqual(TanStackSourceCredentials.environmentToken(HOST, token), "tsp_env"); + assert.isNull(TanStackSourceCredentials.environmentToken("github.com", token)); + assert.isNull( + TanStackSourceCredentials.environmentToken(HOST, { ...token, SRC_HOST: "localhost:5173" }), + ); + assert.isNull(TanStackSourceCredentials.environmentToken(HOST, { SRC_TOKEN: " " })); + }); + + it.effect("puts a saved token before SRC_TOKEN, and SRC_TOKEN before the src login", () => { + const { layer, calls } = harness(() => Effect.succeed(processOutput("tsp_cli\n")), { + SRC_TOKEN: "tsp_env", + }); + return Effect.gen(function* () { + const credentials = yield* TanStackSourceCredentials.TanStackSourceCredentials; + const settings = yield* TestSourceControlHost.TestSourceControlHostSettings; + yield* settings.update({ + sourceControlHosts: { "tanstack-source": { tokens: { [HOST]: "tsp_saved" } } }, + }); + const saved = yield* credentials.get(HOST); + assert.strictEqual(Redacted.value(saved.token), "tsp_saved"); + assert.strictEqual(saved.source, "settings"); + + yield* settings.update({ sourceControlHosts: { "tanstack-source": { tokens: {} } } }); + const fromEnv = yield* credentials.get(HOST); + assert.strictEqual(Redacted.value(fromEnv.token), "tsp_env"); + assert.strictEqual(fromEnv.source, "env"); + assert.deepStrictEqual(calls, []); + }).pipe(Effect.provide(layer)); + }); + + it.effect("asks src for the account picked in Settings, then its active login", () => { + const { layer, calls } = harness((input) => + input.args.includes("--user") + ? notSignedIn(input) + : Effect.succeed(processOutput("tsp_active\n")), + ); + return Effect.gen(function* () { + const credentials = yield* TanStackSourceCredentials.TanStackSourceCredentials; + const settings = yield* TestSourceControlHost.TestSourceControlHostSettings; + yield* settings.update({ + sourceControlHosts: { "tanstack-source": { hosts: { [HOST]: { account: "gone" } } } }, + }); + const credential = yield* credentials.get("Source.TanStack.com"); + assert.strictEqual(Redacted.value(credential.token), "tsp_active"); + assert.strictEqual(credential.source, "src"); + assert.deepStrictEqual( + calls.map((call) => [call.command, ...call.args]), + [ + ["src", "auth", "token", "--hostname", HOST, "--user", "gone"], + ["src", "auth", "token", "--hostname", HOST], + ], + ); + // An inherited SRC_TOKEN must not answer for the login asked for. + assert.strictEqual(calls[0]?.env?.SRC_TOKEN, ""); + yield* credentials.get(HOST); + assert.strictEqual(calls.length, 2); + }).pipe(Effect.provide(layer)); + }); + + it.effect("refuses a host turned off in Settings and any host that is not Source's", () => { + const { layer, calls } = harness(() => Effect.succeed(processOutput("tsp_cli\n")), { + SRC_TOKEN: "tsp_env", + }); + return Effect.gen(function* () { + const credentials = yield* TanStackSourceCredentials.TanStackSourceCredentials; + const settings = yield* TestSourceControlHost.TestSourceControlHostSettings; + const foreign = yield* Effect.flip(credentials.get("source.tanstack.com.evil.test")); + assert.strictEqual(foreign._tag, "TanStackSourceNotSignedInError"); + yield* settings.update({ + sourceControlHosts: { + "tanstack-source": { + hosts: { [HOST]: { enabled: false } }, + tokens: { [HOST]: "tsp_saved" }, + }, + }, + }); + const disabled = yield* Effect.flip(credentials.get(HOST)); + assert.strictEqual(disabled._tag, "TanStackSourceHostDisabledError"); + assert.deepStrictEqual(calls, []); + }).pipe(Effect.provide(layer)); + }); +}); diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourceCredentials.ts b/packages/source-control-tanstack-source/src/server/TanStackSourceCredentials.ts new file mode 100644 index 0000000000000..7bd6ea135fd46 --- /dev/null +++ b/packages/source-control-tanstack-source/src/server/TanStackSourceCredentials.ts @@ -0,0 +1,249 @@ +import { + requireSettingsSecretLiteral, + type ServerSettings, + type SettingsSecretUnresolvedError, +} from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { normalizeHost } from "@t3tools/source-control-core/server/pullRequestUtils"; +import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; +import { readSourceControlHostSettings } from "@t3tools/source-control-core/shared/definition"; +import * as Cache from "effect/Cache"; +import * as Context from "effect/Context"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as PlatformError from "effect/PlatformError"; +import * as Redacted from "effect/Redacted"; +import * as Schema from "effect/Schema"; + +import * as TanStackSource from "../shared/definition.ts"; +import * as Hosts from "./tanStackSourceHosts.ts"; + +const TOKEN_TTL = Duration.minutes(5); +const MISSING_TTL = Duration.seconds(10); + +export const TanStackSourceCredentialSource = Schema.Literals(["settings", "env", "src"]); +export type TanStackSourceCredentialSource = typeof TanStackSourceCredentialSource.Type; + +export interface TanStackSourceCredential { + readonly host: string; + readonly token: Redacted.Redacted; + readonly source: TanStackSourceCredentialSource; +} + +export class TanStackSourceCliMissingError extends Schema.TaggedError()( + "TanStackSourceCliMissingError", + { host: Schema.String }, +) { + override get message(): string { + return `No TanStack Source credential for ${this.host}: save a token in Settings, set SRC_TOKEN, or install the src CLI and run \`src auth login --web\`.`; + } +} + +export class TanStackSourceNotSignedInError extends Schema.TaggedError()( + "TanStackSourceNotSignedInError", + { host: Schema.String, account: Schema.optional(Schema.String) }, +) { + override get message(): string { + return this.account === undefined + ? `No TanStack Source credential for ${this.host}: run \`src auth login --web --hostname ${this.host}\`.` + : `No TanStack Source credential for ${this.account} on ${this.host}: run \`src auth login --web --hostname ${this.host}\` for that account or pick another in Settings → Source control & issues.`; + } +} + +export class TanStackSourceHostDisabledError extends Schema.TaggedError()( + "TanStackSourceHostDisabledError", + { host: Schema.String }, +) { + override get message(): string { + return `TanStack Source host ${this.host} is turned off in Settings → Source control & issues.`; + } +} + +export class TanStackSourceCliFailedError extends Schema.TaggedError()( + "TanStackSourceCliFailedError", + { host: Schema.String, cause: Schema.Defect() }, +) { + override get message(): string { + return `The src CLI could not hand over a credential for ${this.host}. Check \`src auth status\` on the server.`; + } +} + +export class TanStackSourceCliTimeoutError extends Schema.TaggedError()( + "TanStackSourceCliTimeoutError", + { host: Schema.String, timeoutMs: Schema.Number, cause: Schema.Defect() }, +) { + override get message(): string { + return `The src CLI did not hand over a credential for ${this.host} within ${this.timeoutMs / 1000} seconds. The server may be overloaded; try again.`; + } +} + +export type TanStackSourceCredentialUnavailableError = + | TanStackSourceCliMissingError + | TanStackSourceNotSignedInError + | TanStackSourceHostDisabledError + | TanStackSourceCliFailedError + | TanStackSourceCliTimeoutError + | SettingsSecretUnresolvedError; + +/** Where requests to a host get their token. The API layer asks; it never reads a source itself. */ +export class TanStackSourceCredentials extends Context.Service< + TanStackSourceCredentials, + { + readonly get: ( + host: string, + ) => Effect.Effect; + readonly invalidate: (host: string) => Effect.Effect; + } +>()("@t3tools/source-control-tanstack-source/server/TanStackSourceCredentials") {} + +/** `src` sends SRC_TOKEN only to SRC_HOST (default source.tanstack.com); so does T3. */ +export function environmentToken( + host: string, + env: Readonly>, +): string | null { + const configured = env.SRC_HOST?.trim().toLowerCase() || TanStackSource.TANSTACK_SOURCE_HOST; + if (configured !== normalizeHost(host)) return null; + return env.SRC_TOKEN?.trim() || null; +} + +/** @public */ +export const make = Effect.gen(function* () { + const sourceControlHost = yield* SourceControlHost.SourceControlHost; + const environment = yield* HostProcess.Environment; + const workingDirectory = yield* HostProcess.WorkingDirectory; + + const fromCli = (host: string, account: string | undefined) => + sourceControlHost.process + .run({ + operation: "TanStackSourceCredentials.get", + command: "src", + args: [ + "auth", + "token", + "--hostname", + host, + ...(account === undefined ? [] : ["--user", account]), + ], + cwd: workingDirectory, + // An inherited SRC_TOKEN would answer in place of the login asked for; it is read above. + env: { SRC_TOKEN: "", SRC_NO_TELEMETRY: "1" }, + timeoutMs: 10_000, + }) + .pipe( + Effect.mapError((error) => + error._tag === "VcsProcessSpawnError" && + error.cause instanceof PlatformError.PlatformError && + error.cause.reason._tag === "NotFound" + ? new TanStackSourceCliMissingError({ host }) + : // src exits 1 with "no oauth token found" when it has no login for the host. + error._tag === "VcsProcessExitError" + ? new TanStackSourceNotSignedInError({ + host, + ...(account === undefined ? {} : { account }), + }) + : error._tag === "VcsProcessTimeoutError" + ? new TanStackSourceCliTimeoutError({ + host, + timeoutMs: error.timeoutMs, + cause: error, + }) + : new TanStackSourceCliFailedError({ host, cause: error }), + ), + Effect.map((output) => output.stdout.trim()), + Effect.filterOrFail( + (token) => token !== "", + () => + new TanStackSourceNotSignedInError({ + host, + ...(account === undefined ? {} : { account }), + }), + ), + ); + + const readSettings = (settings: ServerSettings) => + readSourceControlHostSettings( + TanStackSource.settings, + settings.sourceControlHosts[TanStackSource.definition.kind], + ); + + const hostChoice = (host: string) => + sourceControlHost.settings.get.pipe( + Effect.map((settings) => readSettings(settings).hosts[host]), + Effect.orElseSucceed(() => undefined), + ); + + const savedToken = (host: string) => + sourceControlHost.settings.getWithSecrets(TanStackSource.definition.kind).pipe( + Effect.map((settings) => ({ + token: readSettings(settings).tokens[host], + secretProviders: settings.secretProviders, + })), + Effect.orElseSucceed(() => ({ token: undefined, secretProviders: {} })), + Effect.flatMap(({ token, secretProviders }) => + requireSettingsSecretLiteral(token, secretProviders), + ), + Effect.map((token) => token.trim() || null), + ); + + const cacheKey = (host: string, account: string | undefined) => + account === undefined ? host : `${host}\u0000${account}`; + + const lookup = Effect.fn("TanStackSourceCredentials.lookup")(function* (key: string) { + const [host = key, account] = key.split("\u0000"); + const fromEnv = environmentToken(host, environment); + const token = + fromEnv ?? + (yield* fromCli(host, account).pipe( + Effect.catchTags({ + TanStackSourceNotSignedInError: (error) => + account === undefined ? Effect.fail(error) : fromCli(host, undefined), + }), + )); + return { + host, + token: Redacted.make(token), + source: fromEnv === null ? "src" : "env", + } satisfies TanStackSourceCredential; + }); + + const cache = yield* Cache.makeWith(lookup, { + capacity: 8, + timeToLive: (exit) => + Exit.isSuccess(exit) + ? TOKEN_TTL + : Exit.findErrorOption(exit).pipe( + Option.exists( + (error) => + error._tag === "TanStackSourceCliFailedError" || + error._tag === "TanStackSourceCliTimeoutError", + ), + ) + ? Duration.zero + : MISSING_TTL, + }); + + return TanStackSourceCredentials.of({ + get: Effect.fn("TanStackSourceCredentials.get")(function* (rawHost) { + const host = normalizeHost(rawHost); + // Only Source's own hosts get a token, whatever host a remote or link names. + if (Hosts.tanStackSourceHost(host) === null) + return yield* new TanStackSourceNotSignedInError({ host }); + const choice = yield* hostChoice(host); + if (choice?.enabled === false) return yield* new TanStackSourceHostDisabledError({ host }); + const saved = yield* savedToken(host); + if (saved !== null) return { host, token: Redacted.make(saved), source: "settings" as const }; + return yield* Cache.get(cache, cacheKey(host, choice?.account)); + }), + invalidate: Effect.fn("TanStackSourceCredentials.invalidate")(function (rawHost) { + const host = normalizeHost(rawHost); + return hostChoice(host).pipe( + Effect.flatMap((choice) => Cache.invalidate(cache, cacheKey(host, choice?.account))), + ); + }), + }); +}); + +export const layer = Layer.effect(TanStackSourceCredentials, make); diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourceIssueTracker.test.ts b/packages/source-control-tanstack-source/src/server/TanStackSourceIssueTracker.test.ts new file mode 100644 index 0000000000000..bed0175c9cc22 --- /dev/null +++ b/packages/source-control-tanstack-source/src/server/TanStackSourceIssueTracker.test.ts @@ -0,0 +1,192 @@ +import { assert, describe, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; + +import * as TanStackSourceApi from "./TanStackSourceApi.ts"; +import * as TanStackSourceIssueTracker from "./TanStackSourceIssueTracker.ts"; + +const target = { cwd: "/repo", host: "source.tanstack.com", scope: "TanStack/ai" }; + +function withApi(routes: Readonly>) { + const paths: Array = []; + const writes: Array = []; + const request = (input: TanStackSourceApi.TanStackSourceApiRequest) => { + paths.push(input.path); + if (input.method !== undefined && input.method !== "GET") { + writes.push([input.method, input.path, input.body]); + return Effect.succeed("{}"); + } + const body = routes[input.path]; + return body === undefined + ? Effect.die(`unexpected ${input.path}`) + : Effect.succeed(JSON.stringify(body)); + }; + const api = TanStackSourceApi.TanStackSourceApi.of({ + request, + response: (input) => + request(input).pipe(Effect.map((text) => ({ status: 200, headers: {}, text }))), + }); + return { + paths, + writes, + tracker: TanStackSourceIssueTracker.make.pipe( + Effect.provideService(TanStackSourceApi.TanStackSourceApi, api), + ), + }; +} + +const row = (number: number, state: string, createdAt: number) => ({ + number, + title: `Issue ${number}`, + state, + author: "alice", + labels: ["bug"], + assignees: ["bob"], + comments: 1, + createdAt, +}); + +describe("TanStackSourceIssueTracker", () => { + it.effect("lists open and closed issues together, newest first, under one cursor each", () => { + const { tracker, paths } = withApi({ + "/repos/TanStack/ai/issues?state=open": { items: [row(3, "open", 30)], next: "o2" }, + "/repos/TanStack/ai/issues?state=closed": { items: [row(4, "closed", 40)], next: null }, + "/repos/TanStack/ai/issues?state=open&cursor=o2": { + items: [row(1, "open", 10)], + next: null, + }, + }); + return Effect.gen(function* () { + const issues = yield* tracker; + const first = yield* issues.listIssues({ + ...target, + involvement: "all", + state: "all", + limit: 2, + sort: "created", + }); + assert.deepStrictEqual( + first.items.map((issue) => [issue.key, issue.state.category]), + [ + ["4", "closed"], + ["3", "open"], + ], + ); + assert.strictEqual(first.items[0]?.url, "https://source.tanstack.com/@TanStack/ai/issues/4"); + assert.isNotNull(first.nextCursor); + const second = yield* issues.listIssues({ + ...target, + involvement: "all", + state: "all", + limit: 2, + sort: "created", + cursor: first.nextCursor!, + }); + assert.deepStrictEqual( + second.items.map((issue) => issue.key), + ["1"], + ); + assert.isNull(second.nextCursor); + // The closed listing had ended, so it is not read again. + assert.strictEqual(paths.filter((path) => path.includes("state=closed")).length, 1); + }); + }); + + it.effect("reads comments, events and the pull requests that fix it, hiding held entries", () => { + const { tracker } = withApi({ + "/user": { username: "alice" }, + "/repos/TanStack/ai/issues/2219": { + ...row(2219, "open", 1_000), + // The issue's own count, which a first timeline page may not reach. + comments: 12, + kind: "issue", + body: "Spec changed.", + assignees: [{ username: "bob", note: null }], + timeline: [ + { event: "labeled", actor: "alice", at: 2_000 }, + { event: "linked_from", actor: "bob", at: 3_000 }, + { id: 7, comment: "On it.", author: "bob", at: 4_000, moderation: "visible" }, + { id: 8, comment: null, author: "spam", at: 5_000, moderation: "quarantined" }, + ], + // Older conversation carries on past this first page. + next: "t2", + fixedBy: [{ number: 2221, title: "fix(ai-mcp): follow the spec", state: "open" }], + }, + }); + return Effect.gen(function* () { + const issues = yield* tracker; + const issue = yield* issues.getIssue({ ...target, key: "2219" }); + assert.strictEqual(issue.body, "Spec changed."); + assert.strictEqual(issue.viewer, "alice"); + assert.deepStrictEqual( + issue.assignees.map((actor) => actor.login), + ["bob"], + ); + assert.deepStrictEqual( + issue.events.map((event) => event.kind), + ["labeled", "referenced"], + ); + assert.deepStrictEqual( + issue.comments.map((comment) => [comment.id, comment.body]), + [["7", "On it."]], + ); + assert.strictEqual(issue.updatedAt, "1970-01-01T00:00:05.000Z"); + assert.strictEqual(issue.commentCount, 12); + assert.strictEqual(issue.commentsCursor, "t2"); + assert.deepStrictEqual(issue.linkedPullRequests, [ + { + repository: "TanStack/ai", + number: 2221, + title: "fix(ai-mcp): follow the spec", + url: "https://source.tanstack.com/@TanStack/ai/pull/2221", + state: "open", + isDraft: false, + closesIssue: true, + }, + ]); + }); + }); + + it.effect("keeps an explicit assignee while also requiring the viewer to be assigned", () => { + const { tracker, paths } = withApi({ + "/repos/TanStack/ai/issues?assignee=bob&state=open": { + items: [ + { ...row(2, "open", 20), assignees: ["bob"] }, + { ...row(1, "open", 10), assignees: ["bob", "Alice"] }, + ], + next: null, + }, + }); + return Effect.gen(function* () { + const issues = yield* tracker; + const page = yield* issues.listIssues({ + ...target, + involvement: "assigned", + viewer: "alice", + assignee: "bob", + state: "open", + limit: 50, + sort: "created", + }); + assert.deepStrictEqual( + page.items.map((issue) => issue.key), + ["1"], + ); + assert.deepStrictEqual(paths, ["/repos/TanStack/ai/issues?assignee=bob&state=open"]); + }); + }); + + it.effect("writes each changed field on its own route, clearing labels and assignees", () => { + const { tracker, writes } = withApi({}); + return Effect.gen(function* () { + const issues = yield* tracker; + yield* issues.update!({ ...target, key: "7", title: "New title", labels: [], assignees: [] }); + yield* issues.setState!({ ...target, key: "7", state: "Closed" }); + assert.deepStrictEqual(writes, [ + ["PATCH", "/repos/TanStack/ai/issues/7", { title: "New title" }], + ["PUT", "/repos/TanStack/ai/issues/7/labels", { labels: [] }], + ["PUT", "/repos/TanStack/ai/issues/7/assignees", { assignees: [] }], + ["PATCH", "/repos/TanStack/ai/issues/7", { state: "closed" }], + ]); + }); + }); +}); diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourceIssueTracker.ts b/packages/source-control-tanstack-source/src/server/TanStackSourceIssueTracker.ts new file mode 100644 index 0000000000000..e436ba54375c1 --- /dev/null +++ b/packages/source-control-tanstack-source/src/server/TanStackSourceIssueTracker.ts @@ -0,0 +1,430 @@ +import { + IssueTrackerKind, + type IssueCapabilities, + type IssueComment, + type IssueEvent, + type IssueState, +} from "@t3tools/contracts"; +import { + IssueTrackerError, + type IssueScopeTarget, + type IssueTrackerApi, + type TrackerIssueSummary, +} from "@t3tools/source-control-core/server/IssueTracker"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { definition } from "../shared/definition.ts"; +import * as TanStackSourceApi from "./TanStackSourceApi.ts"; +import * as Hosts from "./tanStackSourceHosts.ts"; +import * as Json from "./tanStackSourceJson.ts"; +import * as Listing from "./tanStackSourceListing.ts"; + +const KIND = IssueTrackerKind.make(definition.kind); + +const CAPABILITIES: IssueCapabilities = { + create: true, + edit: true, + comment: true, + labels: true, + assignees: true, + // Source documents no REST route for reactions. + reactions: false, + templates: false, + linkedPullRequests: true, + events: true, + search: true, +}; + +const OPEN: IssueState = { category: "open", name: "Open" }; +const CLOSED: IssueState = { category: "closed", name: "Closed" }; +const STATES: ReadonlyArray = [OPEN, CLOSED]; + +/** Source keeps no update time; the newest timeline entry stands in where one was read. */ +const EVENT_KINDS: Readonly> = { + closed: "closed", + reopened: "reopened", + labeled: "labeled", + unlabeled: "unlabeled", + assigned: "assigned", + unassigned: "unassigned", + renamed: "renamed", + linked_from: "referenced", + referenced: "referenced", +}; + +const Assignee = Schema.Union([Schema.String, Schema.Struct({ username: Schema.String })]); +const IssueRow = Schema.Struct({ + number: Schema.Int, + title: Schema.String, + state: Schema.String, + author: Schema.NullOr(Schema.String), + labels: Schema.optional(Schema.Array(Schema.String)), + assignees: Schema.optional(Schema.Array(Assignee)), + comments: Schema.optional(Schema.Int), + createdAt: Schema.Finite, + moderation: Schema.optional(Schema.String), +}); +type IssueRow = typeof IssueRow.Type; +const IssueRows = Schema.Struct({ + items: Schema.Array(IssueRow), + next: Schema.NullOr(Schema.String), +}); + +const TimelineEntry = Schema.Struct({ + id: Schema.optional(Schema.Int), + comment: Schema.optional(Schema.NullOr(Schema.String)), + event: Schema.optional(Schema.String), + author: Schema.optional(Schema.NullOr(Schema.String)), + actor: Schema.optional(Schema.NullOr(Schema.String)), + at: Schema.Finite, + moderation: Schema.optional(Schema.String), +}); +const IssueDetail = Schema.Struct({ + ...IssueRow.fields, + kind: Schema.optional(Schema.String), + body: Schema.NullOr(Schema.String), + locked: Schema.optional(Schema.Boolean), + timeline: Schema.Array(TimelineEntry), + next: Schema.NullOr(Schema.String), + fixedBy: Schema.optional( + Schema.Array(Schema.Struct({ number: Schema.Int, title: Schema.String, state: Schema.String })), + ), +}); +type IssueDetail = typeof IssueDetail.Type; +const Created = Schema.Struct({ number: Schema.Int }); +const PAGE_LIMIT = 5; + +const issueUrl = (host: string, scope: string, number: number | string) => + `https://${host}/@${scope}/issues/${number}`; +const assigneeLogin = (assignee: typeof Assignee.Type) => + typeof assignee === "string" ? assignee : assignee.username; +const pullState = (state: string) => + state === "merged" + ? ("merged" as const) + : state === "closed" + ? ("closed" as const) + : ("open" as const); + +export const make = Effect.gen(function* () { + const api = yield* TanStackSourceApi.TanStackSourceApi; + + const failure = (operation: string, detail: string, cause?: unknown) => + new IssueTrackerError({ + tracker: KIND, + operation, + reason: "failed", + detail, + ...(cause === undefined ? {} : { cause }), + }); + + const base = (operation: string, input: IssueScopeTarget) => { + const repository = Hosts.tanStackSourceRepositoryPath(input.scope); + return Hosts.tanStackSourceHost(input.host) !== null && repository !== null + ? Effect.succeed(`/repos/${repository}`) + : Effect.fail(failure(operation, "TanStack Source issues live in owner/name repositories.")); + }; + + const send = ( + operation: string, + input: Pick, + request: Omit, + ) => + api.request({ ...request, host: input.host, operation }).pipe( + Effect.mapError( + (error) => + new IssueTrackerError({ + tracker: KIND, + operation, + // A refused write is the request's, not a reason to switch the tracker off. + reason: error.reason === "forbidden" ? "failed" : error.reason, + detail: error.detail, + ...(error.retryAt === undefined ? {} : { retryAt: error.retryAt }), + cause: error, + }), + ), + ); + + const read = >( + operation: string, + input: Pick, + request: Omit, + schema: S, + ) => + send(operation, input, request).pipe( + Effect.flatMap((raw) => + Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe( + Effect.mapError((cause) => + failure(operation, "TanStack Source returned an unreadable response.", cause), + ), + ), + ), + ); + + const toSummary = ( + issue: IssueRow, + input: IssueScopeTarget, + updatedAt = issue.createdAt, + ): TrackerIssueSummary => { + const created = Json.iso(issue.createdAt); + return { + key: String(issue.number), + displayKey: `#${issue.number}`, + title: issue.title.trim() || `#${issue.number}`, + url: issueUrl(input.host, input.scope, issue.number), + author: Json.toActor(issue.author, input.host), + state: issue.state === "closed" ? CLOSED : OPEN, + createdAt: created, + updatedAt: Json.iso(Math.max(updatedAt, issue.createdAt)), + // Source reports no close time. + closedAt: null, + assignees: (issue.assignees ?? []).flatMap((assignee) => { + const actor = Json.toActor(assigneeLogin(assignee), input.host); + return actor === null ? [] : [actor]; + }), + labels: (issue.labels ?? []).map((name) => ({ name, color: null })), + commentCount: issue.comments ?? 0, + }; + }; + + const toConversation = (detail: IssueDetail, input: IssueScopeTarget & { key: string }) => { + const comments: Array = []; + const events: Array = []; + for (const [index, entry] of detail.timeline.entries()) { + if (entry.moderation !== undefined && entry.moderation !== "visible") continue; + if (entry.event !== undefined) { + const kind = EVENT_KINDS[entry.event]; + if (kind !== undefined) + events.push({ + id: `${input.key}:${entry.at}:${index}`, + kind, + actor: Json.toActor(entry.actor ?? null, input.host), + createdAt: Json.iso(entry.at), + detail: null, + }); + continue; + } + if (entry.id === undefined) continue; + comments.push({ + id: String(entry.id), + author: Json.toActor(entry.author ?? null, input.host), + body: entry.comment ?? "", + createdAt: Json.iso(entry.at), + url: `${issueUrl(input.host, input.scope, input.key)}#comment-${entry.id}`, + }); + } + return { comments, events }; + }; + + const readDetail = Effect.fn("TanStackSourceIssueTracker.readDetail")(function* ( + operation: string, + input: IssueScopeTarget & { readonly key: string }, + ) { + const path = yield* base(operation, input); + if (!/^\d+$/u.test(input.key)) + return yield* failure(operation, "TanStack Source issue keys are numbers."); + return yield* read(operation, input, { path: `${path}/issues/${input.key}` }, IssueDetail); + }); + + const tracker: IssueTrackerApi = { + kind: KIND, + capabilities: CAPABILITIES, + getViewer: (input) => + read("getViewer", input, { path: "/user" }, Json.SourceUser).pipe( + Effect.map((user) => user.username), + ), + + listIssues: Effect.fn("TanStackSourceIssueTracker.listIssues")(function* (input) { + const path = yield* base("listIssues", input); + const query = new URLSearchParams(); + if (input.query?.trim()) query.set("query", input.query.trim()); + // Source narrows by one label; the rest are matched below. + const [label, ...moreLabels] = input.labels ?? []; + if (label !== undefined) query.set("label", label); + // An explicit assignee narrows on Source; being assigned too is checked on the rows. + if (input.assignee !== undefined) query.set("assignee", input.assignee); + else if (input.involvement === "assigned") query.set("assignee", "@me"); + if (input.involvement === "authored") query.set("author", "@me"); + if (input.involvement === "mentioned") query.set("mention", "@me"); + const viewer = input.involvement === "all" ? null : input.viewer.toLowerCase(); + const listing = yield* Listing.readMerged({ + states: input.state === "all" ? ["open", "closed"] : [input.state], + cursor: input.cursor, + limit: Math.max(1, input.limit), + maxPages: PAGE_LIMIT, + readPage: (state, page) => { + const params = new URLSearchParams(query); + params.set("state", state); + if (page !== null) params.set("cursor", page); + return read("listIssues", input, { path: `${path}/issues?${params}` }, IssueRows); + }, + keep: (issue) => + (issue.moderation === undefined || issue.moderation === "visible") && + moreLabels.every((name) => issue.labels?.includes(name) === true) && + (input.involvement !== "assigned" || + input.assignee === undefined || + (issue.assignees ?? []).some( + (assignee) => assigneeLogin(assignee).toLowerCase() === viewer, + )), + }); + return { + items: listing.items.map((issue) => toSummary(issue, input)), + nextCursor: listing.next, + }; + }), + + getIssue: Effect.fn("TanStackSourceIssueTracker.getIssue")(function* (input) { + const [detail, viewer] = yield* Effect.all( + [ + readDetail("getIssue", input), + tracker.getViewer(input).pipe(Effect.orElseSucceed(() => null)), + ], + { concurrency: 2 }, + ); + if (detail.kind === "pull") + return yield* failure("getIssue", `#${input.key} is a pull request, not an issue.`); + const { comments, events } = toConversation(detail, input); + const latest = detail.timeline.reduce((newest, entry) => Math.max(newest, entry.at), 0); + return { + ...toSummary(detail, input, latest), + commentCount: detail.comments ?? comments.length, + body: detail.body ?? "", + viewer, + viewerPermissions: { + setState: viewer !== null, + comment: viewer !== null && detail.locked !== true, + edit: viewer !== null, + labels: viewer !== null, + assignees: viewer !== null, + }, + states: STATES, + comments, + commentsCursor: detail.next, + events, + linkedPullRequests: (detail.fixedBy ?? []).map((pull) => ({ + repository: input.scope, + number: pull.number, + title: pull.title.trim() || `#${pull.number}`, + url: Json.pullUrl(input.host, input.scope, pull.number), + state: pullState(pull.state), + isDraft: false, + closesIssue: true, + })), + }; + }), + + getComments: Effect.fn("TanStackSourceIssueTracker.getComments")(function* (input) { + const path = yield* base("getComments", input); + const detail = yield* read( + "getComments", + input, + { + path: `${path}/issues/${input.key}?${new URLSearchParams({ cursor: input.cursor })}`, + }, + IssueDetail, + ); + return { comments: toConversation(detail, input).comments, nextCursor: detail.next }; + }), + + create: Effect.fn("TanStackSourceIssueTracker.create")(function* (input) { + const path = yield* base("create", input); + const created = yield* read( + "create", + input, + { + method: "POST", + path: `${path}/issues`, + body: { + title: input.title, + ...(input.body.trim() === "" ? {} : { body: input.body }), + }, + }, + Created, + ); + const key = String(created.number); + // Source takes labels and assignees on their own routes. + if (input.labels.length > 0) + yield* send("create", input, { + method: "PUT", + path: `${path}/issues/${key}/labels`, + body: { labels: input.labels }, + }); + if (input.assignees.length > 0) + yield* send("create", input, { + method: "PUT", + path: `${path}/issues/${key}/assignees`, + body: { assignees: input.assignees }, + }); + return { key, displayKey: `#${key}`, url: issueUrl(input.host, input.scope, key) }; + }), + + comment: Effect.fn("TanStackSourceIssueTracker.comment")(function* (input) { + const path = yield* base("comment", input); + yield* send("comment", input, { + method: "POST", + path: `${path}/issues/${input.key}/comments`, + body: { body: input.body }, + }); + }), + + update: Effect.fn("TanStackSourceIssueTracker.update")(function* (input) { + const path = `${yield* base("update", input)}/issues/${input.key}`; + if (input.title !== undefined || input.body !== undefined) + yield* send("update", input, { + method: "PATCH", + path, + body: { + ...(input.title === undefined ? {} : { title: input.title }), + ...(input.body === undefined ? {} : { body: input.body }), + }, + }); + if (input.labels !== undefined) + yield* send("update", input, { + method: "PUT", + path: `${path}/labels`, + body: { labels: input.labels }, + }); + if (input.assignees !== undefined) + yield* send("update", input, { + method: "PUT", + path: `${path}/assignees`, + body: { assignees: input.assignees }, + }); + }), + + setState: Effect.fn("TanStackSourceIssueTracker.setState")(function* (input) { + const state = STATES.find((candidate) => candidate.name === input.state); + if (state === undefined) + return yield* failure("setState", `TanStack Source issues have no "${input.state}" state.`); + const path = yield* base("setState", input); + yield* send("setState", input, { + method: "PATCH", + path: `${path}/issues/${input.key}`, + body: { state: state.category }, + }); + }), + + listCandidates: Effect.fn("TanStackSourceIssueTracker.listCandidates")(function* (input) { + const path = yield* base("listCandidates", input); + const [labels, viewer] = yield* Effect.all( + [ + read("listCandidates", input, { path: `${path}/labels` }, Json.SourceLabels), + tracker.getViewer(input).pipe(Effect.orElseSucceed(() => null)), + ], + { concurrency: 2 }, + ); + const self = Json.toActor(viewer, input.host); + return { + labels: labels.map((label) => ({ + name: label.name, + color: label.color, + description: label.description ?? null, + })), + // Source lists no collaborators, so only the viewer is offered. + assignees: self === null ? [] : [{ ...self, id: self.login }], + truncated: true, + }; + }), + }; + return tracker; +}); diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.ts b/packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.ts new file mode 100644 index 0000000000000..69c30f22deb29 --- /dev/null +++ b/packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.ts @@ -0,0 +1,957 @@ +import { + resolvePullRequestAuthorFilter, + type PullRequestCapabilities, + type PullRequestListState, + type PullRequestViewerPermissions, +} from "@t3tools/contracts"; +import { + PullRequestProviderError, + tailLogLines, + type ProviderChangeRequestDetail, + type ProviderCheckLog, + type ProviderCheckRerun, + type ProviderRepositoryRef, + type PullRequestProviderApi, +} from "@t3tools/source-control-core/server/PullRequestProvider"; +import * as Cache from "effect/Cache"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Schema from "effect/Schema"; + +import { definition } from "../shared/definition.ts"; +import * as TanStackSourceApi from "./TanStackSourceApi.ts"; +import * as Events from "./tanStackSourceEvents.ts"; +import * as Hosts from "./tanStackSourceHosts.ts"; +import * as Json from "./tanStackSourceJson.ts"; +import * as Listing from "./tanStackSourceListing.ts"; + +const KIND = definition.kind; + +const CAPABILITIES: PullRequestCapabilities = { + diff: true, + comment: true, + actions: [...definition.changeRequestActions], + mergeMethods: ["merge", "squash"], + updateMethods: ["merge", "rebase"], + search: true, + stacks: true, + // A merge lands every layer below it on its own; there is no separate stack action. + stackActions: false, + reactions: false, + labels: true, + review: { + inlineComment: true, + rangeComment: true, + reply: true, + resolve: true, + verdicts: ["approve", "request-changes", "comment"], + }, + // Source lists no collaborators to pick from; reviewers are requested by username. + reviewers: { request: true, listCandidates: false }, + edit: { changeRequest: true, comment: true }, +}; + +const PAGE_LIMIT = 5; +const VIEWER_TTL = Duration.minutes(5); +/** Runs of a pull request are listed newest first, a page at a time. */ +const CI_RUNS_LIMIT = 30; +const CI_RUN_PAGES = 3; +/** Runs at one head whose jobs are read, re-runs included. */ +const MAX_CI_RUNS = 12; +/** Strips the terminal colour codes CI logs keep. */ +const ANSI = /\u001b\[[0-9;?]*[ -/]*[@-~]/gu; + +const LogSteps = Schema.Array(Schema.Struct({ lines: Schema.Int })); +const decodeLogSteps = Schema.decodeUnknownOption(Schema.fromJsonString(LogSteps)); + +type PullRef = ProviderRepositoryRef & { readonly number: number }; + +export const make = Effect.gen(function* () { + const api = yield* TanStackSourceApi.TanStackSourceApi; + const events = yield* Events.make; + + const failure = (operation: string, detail: string, cause?: unknown) => + new PullRequestProviderError({ + provider: KIND, + operation, + reason: "failed", + detail, + ...(cause === undefined ? {} : { cause }), + }); + + const repositoryPath = ( + operation: string, + input: ProviderRepositoryRef, + ): Effect.Effect => { + const repository = Hosts.tanStackSourceRepositoryPath(input.repository); + return Hosts.tanStackSourceHost(input.host) !== null && repository !== null + ? Effect.succeed(`/repos/${repository}`) + : Effect.fail( + failure( + operation, + `TanStack Source serves owner/name repositories on ${Hosts.TANSTACK_SOURCE_HOSTS.join(" and ")}.`, + ), + ); + }; + + const toProviderError = + (operation: string) => (error: TanStackSourceApi.TanStackSourceApiError) => + new PullRequestProviderError({ + provider: KIND, + operation, + reason: error.reason, + detail: error.detail, + ...(error.retryAt === undefined ? {} : { retryAt: error.retryAt }), + cause: error, + }); + + const send = ( + operation: string, + input: Pick, + request: Omit, + ) => + api + .request({ ...request, host: input.host, operation }) + .pipe(Effect.mapError(toProviderError(operation))); + + const decode = + >(operation: string, schema: S) => + (raw: string) => + Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe( + Effect.mapError((cause) => + failure(operation, "TanStack Source returned an unreadable response.", cause), + ), + ); + + const read = >( + operation: string, + input: Pick, + request: Omit, + schema: S, + ) => send(operation, input, request).pipe(Effect.flatMap(decode(operation, schema))); + + const pullPath = (operation: string, input: PullRef) => + repositoryPath(operation, input).pipe(Effect.map((base) => `${base}/pulls/${input.number}`)); + + const readPull = (operation: string, input: PullRef) => + pullPath(operation, input).pipe( + Effect.flatMap((path) => read(operation, input, { path }, Json.SourcePullDetail)), + ); + + const viewers = yield* Cache.makeWith( + (host: string) => + read("getViewer", { host }, { path: "/user" }, Json.SourceUser).pipe( + Effect.map((user) => user.username), + ), + { + capacity: 4, + timeToLive: (exit) => (Exit.isSuccess(exit) ? VIEWER_TTL : Duration.zero), + }, + ); + const viewerOf = (host: string) => Cache.get(viewers, host.toLowerCase()); + + const permissionsOf = ( + pull: Json.SourcePullDetail, + viewer: string | null, + ): PullRequestViewerPermissions => { + const open = pull.state === "open"; + const authored = viewer !== null && pull.author?.toLowerCase() === viewer.toLowerCase(); + return { + actions: open + ? [ + pull.draft ? "ready" : "draft", + "close", + ...(pull.draft ? [] : (["merge"] as const)), + "update-branch", + pull.autoMerge == null ? "enable-auto-merge" : "disable-auto-merge", + ] + : pull.state === "closed" + ? ["reopen"] + : [], + comment: pull.locked !== true, + resolve: true, + // Source refuses an author's approval and request for changes, as GitHub does. + verdicts: authored ? ["comment"] : ["approve", "request-changes", "comment"], + requestReviewers: open, + labels: true, + editChangeRequest: true, + updateMethods: open ? ["merge", "rebase"] : [], + }; + }; + + /** + * The Source CI jobs of every run at `headSha`, by job id, so each check links to its run and + * log and a re-run's jobs group with the ones they replace. Runs come newest first. + */ + const readCiJobs = Effect.fn("TanStackSourcePullRequestProvider.readCiJobs")(function* ( + operation: string, + input: PullRef, + headSha: string, + ) { + const base = yield* repositoryPath(operation, input); + const runs: Array = []; + let cursor: string | null = null; + for (let page = 0; page < CI_RUN_PAGES; page++) { + const query = new URLSearchParams({ + pull: String(input.number), + limit: String(CI_RUNS_LIMIT), + }); + if (cursor !== null) query.set("cursor", cursor); + const listed: typeof Json.SourceCiRuns.Type = yield* read( + operation, + input, + { path: `${base}/ci/runs?${query}` }, + Json.SourceCiRuns, + ); + const atHead = listed.items.filter((run) => run.headSha === headSha); + runs.push(...atHead); + // Runs of older heads follow the head's own, so a page past them ends the search. + if (listed.next === null || (atHead.length === 0 && runs.length > 0)) break; + cursor = listed.next; + } + const details = yield* Effect.forEach( + runs.slice(0, MAX_CI_RUNS), + (run) => + read(operation, input, { path: `${base}/ci/runs/${run.id}` }, Json.SourceCiRunDetail).pipe( + Effect.map((detail) => ({ run, detail })), + ), + { concurrency: 4 }, + ); + const jobs = new Map(); + for (const { run, detail } of details) + for (const job of detail.jobs) + if (job.jobId !== null) + jobs.set(job.jobId, { + runId: run.id, + workflow: run.workflow, + key: job.key, + runUrl: run.htmlUrl, + }); + return jobs; + }); + + const readChecks = Effect.fn("TanStackSourcePullRequestProvider.readChecks")(function* ( + operation: string, + input: PullRef, + headSha: string | null, + ) { + if (headSha === null) return { checks: [], merge: null }; + const base = yield* repositoryPath(operation, input); + const path = yield* pullPath(operation, input); + const [runs, jobs, merge] = yield* Effect.all( + [ + read( + operation, + input, + { path: `${base}/check-runs?${new URLSearchParams({ sha: headSha })}` }, + Json.SourceCheckRuns, + ), + // Without its run a job still shows; it just links to no log. + readCiJobs(operation, input, headSha).pipe( + Effect.orElseSucceed(() => new Map()), + ), + read(operation, input, { path: `${path}/checks` }, Json.SourceMergeChecks), + ], + { concurrency: 3 }, + ); + const required = new Set(merge.checks.map((check) => check.name)); + return { checks: Json.toChecks({ runs, jobs, required }), merge }; + }); + + const toSummary = (pull: Json.SourcePullDetail, input: ProviderRepositoryRef) => ({ + ...Json.toChangeRequest(pull, input), + ...(pull.headSha === null ? {} : { headSha: pull.headSha }), + mergedAt: pull.mergedAt === null ? null : Json.iso(pull.mergedAt), + mergeability: + pull.mergeable === true + ? ("mergeable" as const) + : pull.mergeable === false + ? ("conflicting" as const) + : ("unknown" as const), + autoMergeEnabled: pull.autoMerge != null, + ...(pull.autoMerge?.method === "merge" || pull.autoMerge?.method === "squash" + ? { autoMergeMethod: pull.autoMerge.method } + : {}), + }); + + const readStack = Effect.fn("TanStackSourcePullRequestProvider.readStack")(function* ( + operation: string, + input: PullRef, + ) { + const path = yield* pullPath(operation, input); + return yield* read(operation, input, { path: `${path}/stack` }, Json.SourceStack); + }); + + const listState = (state: PullRequestListState) => + // Source lists open or closed rows; closed ones include the merged. + state === "all" + ? (["open", "closed"] as const) + : state === "open" + ? (["open"] as const) + : (["closed"] as const); + + const merge = Effect.fn("TanStackSourcePullRequestProvider.merge")(function* ( + input: Parameters[0], + ) { + const pull = yield* readPull("merge", input); + if (pull.state === "merged") return; + const sha = input.expectedHeadSha ?? pull.headSha; + if (sha === null) + return yield* failure( + "merge", + "TanStack Source has not reported the pull request's head yet.", + ); + const path = yield* pullPath("merge", input); + yield* send("merge", input, { + method: "PUT", + path: `${path}/merge`, + body: { merge_method: input.mergeMethod === "squash" ? "squash" : "merge", sha }, + }); + }); + + const provider: PullRequestProviderApi = { + kind: KIND, + capabilities: CAPABILITIES, + unavailableRequirement: { + missing: + "Install the src CLI and run `src auth login --web`, save a TanStack Source token in Settings, or set SRC_TOKEN on the server.", + unauthenticated: + "TanStack Source refused the server's credential. Run `src auth login --web` again, or replace the token saved in Settings.", + }, + readsPublicHostWithoutCheckout: true, + servesHost: (host) => Hosts.tanStackSourceHost(host) !== null, + getViewer: (input) => viewerOf(input.host ?? definition.publicHost ?? ""), + + listChangeRequests: Effect.fn("TanStackSourcePullRequestProvider.listChangeRequests")( + function* (input) { + const base = yield* repositoryPath("listChangeRequests", input); + const filters = new URLSearchParams(); + if (input.query?.trim()) filters.set("query", input.query.trim()); + if (input.involvement === "authored") filters.set("author", "@me"); + if (input.involvement === "reviewing") filters.set("reviewRequested", "@me"); + if (input.filters?.author !== undefined && input.involvement !== "authored") + filters.set("author", resolvePullRequestAuthorFilter(input.filters.author, input.viewer)); + const label = input.filters?.labels?.[0]; + if (label?.length === 1) filters.set("label", label[0]!); + if (input.filters?.draft !== undefined) + filters.set("draft", input.filters.draft === "only" ? "true" : "false"); + const limit = Math.max(1, input.limit); + const readListing = (cursor: string | undefined) => + Listing.readMerged({ + states: listState(input.state), + cursor, + limit, + maxPages: PAGE_LIMIT, + readPage: (state, page) => { + const query = new URLSearchParams(filters); + query.set("state", state); + if (page !== null) query.set("cursor", page); + return read( + "listChangeRequests", + input, + { path: `${base}/pulls?${query}` }, + Json.SourcePulls, + ); + }, + keep: (pull) => input.state !== "merged" || pull.state === "merged", + }); + // The service ends a listing at a page without rows, so a page a filter emptied reads on. + let listing = yield* readListing(input.cursor?.resumeAfter); + for (let scans = 1; listing.items.length === 0 && listing.next !== null; scans++) { + if (scans >= PAGE_LIMIT) break; + listing = yield* readListing(listing.next); + } + // List rows name no base, which the list shows, so each delivered row is read in full. + const details = yield* Effect.forEach( + listing.items, + (pull) => readPull("listChangeRequests", { ...input, number: pull.number }), + { concurrency: 8 }, + ); + return { + ...(listing.next === null ? {} : { resumeAfter: listing.next }), + items: details.map((pull) => toSummary(pull, input)), + truncated: listing.next !== null, + continues: listing.next !== null, + }; + }, + ), + + getChangeRequestSummary: Effect.fn("TanStackSourcePullRequestProvider.getChangeRequestSummary")( + function* (input) { + const pull = yield* readPull("getChangeRequestSummary", input); + const { checks } = yield* readChecks("getChangeRequestSummary", input, pull.headSha).pipe( + Effect.orElseSucceed(() => ({ checks: [] })), + ); + const { additions: _additions, deletions: _deletions, ...summary } = toSummary(pull, input); + const checksState = Json.checksStateOf(checks); + return { + ...summary, + ...(pull.changedFiles === null ? {} : { changedFiles: pull.changedFiles }), + ...(checksState === null ? {} : { checksState }), + }; + }, + ), + + getChangeRequest: Effect.fn("TanStackSourcePullRequestProvider.getChangeRequest")( + function* (input) { + const operation = "getChangeRequest"; + const pull = yield* readPull(operation, input); + const path = yield* pullPath(operation, input); + const [{ checks, merge: mergeChecks }, files, viewer, stack] = yield* Effect.all( + [ + readChecks(operation, input, pull.headSha), + read(operation, input, { path: `${path}/files` }, Json.SourceFiles).pipe( + Effect.orElseSucceed(() => null), + ), + viewerOf(input.host).pipe(Effect.orElseSucceed(() => null)), + readStack(operation, input).pipe(Effect.orElseSucceed(() => null)), + ], + { concurrency: 4 }, + ); + const counted = files?.files ?? null; + const permissions = permissionsOf(pull, viewer); + const mayMerge = mergeChecks?.mayMerge !== false; + const checksState = Json.checksStateOf(checks); + const index = stack?.members.findIndex((member) => member.number === pull.number) ?? -1; + const detail: ProviderChangeRequestDetail = { + ...toSummary(pull, input), + ...(stack !== null && stack.members.length > 1 && index >= 0 + ? { + stack: { + number: stack.members[0]!.number, + position: index + 1, + size: stack.members.length, + base: stack.members[0]!.baseRef, + }, + } + : {}), + baseBranch: pull.base, + headRepositoryNameWithOwner: pull.headRepo, + reviewRequestLogins: pull.reviewRequests ?? [], + body: pull.body ?? "", + additions: counted?.reduce((total, file) => total + (file.additions ?? 0), 0) ?? 0, + deletions: counted?.reduce((total, file) => total + (file.deletions ?? 0), 0) ?? 0, + changedFiles: pull.changedFiles ?? counted?.length ?? 0, + mergedAt: pull.mergedAt === null ? null : Json.iso(pull.mergedAt), + mergeCommitSha: pull.mergeCommitSha, + mergedBy: Json.toActor(pull.mergedBy, input.host), + closedAt: null, + reviewers: [], + checks, + ...(checksState === null ? {} : { checksState }), + mergeCapabilities: { merge: mayMerge, squash: mayMerge, rebase: false }, + baseComparison: + mergeChecks?.upToDate === true + ? "up-to-date" + : mergeChecks?.upToDate === false + ? "behind" + : "unknown", + viewerPermissions: mayMerge + ? permissions + : { + ...permissions, + actions: permissions.actions.filter((action) => action !== "merge"), + }, + }; + return detail; + }, + ), + + getChangeRequestChecks: Effect.fn("TanStackSourcePullRequestProvider.getChangeRequestChecks")( + function* (input) { + const pull = yield* readPull("getChangeRequestChecks", input); + const { checks } = yield* readChecks("getChangeRequestChecks", input, pull.headSha); + return { checks, state: pull.state }; + }, + ), + + changeRequestEvents: (input) => events(input), + + getChangeRequestStack: Effect.fn("TanStackSourcePullRequestProvider.getChangeRequestStack")( + function* (input) { + const stack = yield* readStack("getChangeRequestStack", input); + if (stack.members.length < 2) return null; + // The stack names no states; a merged layer leaves it, so the rest are open. + return Json.toStack(stack, input, new Map()); + }, + ), + + getChangeRequestActivity: Effect.fn( + "TanStackSourcePullRequestProvider.getChangeRequestActivity", + )(function* (input) { + const operation = "getChangeRequestActivity"; + const base = yield* repositoryPath(operation, input); + const path = yield* pullPath(operation, input); + const [timeline, threads, commits] = yield* Effect.all( + [ + read(operation, input, { path: `${base}/issues/${input.number}` }, Json.SourceTimeline), + read(operation, input, { path: `${path}/comments` }, Json.SourceThreads), + read(operation, input, { path: `${path}/commits` }, Json.SourceCommits).pipe( + Effect.orElseSucceed(() => ({ + baseSha: null, + headSha: null, + mergeBaseSha: null, + available: false, + commitsTruncated: null, + commits: null, + })), + ), + ], + { concurrency: 3 }, + ); + return Json.toActivity({ + timeline, + threads, + commits, + host: input.host, + repository: input.repository, + number: input.number, + }); + }), + + getViewerPermissions: Effect.fn("TanStackSourcePullRequestProvider.getViewerPermissions")( + function* (input) { + const [pull, viewer] = yield* Effect.all( + [readPull("getViewerPermissions", input), viewerOf(input.host)], + { concurrency: 2 }, + ); + return permissionsOf(pull, viewer); + }, + ), + + getDiff: Effect.fn("TanStackSourcePullRequestProvider.getDiff")(function* (input) { + if (input.commit !== undefined) + return yield* failure("getDiff", "TanStack Source cannot show one commit's diff here yet."); + const path = yield* pullPath("getDiff", input); + const [diff, files] = yield* Effect.all( + [ + read("getDiff", input, { path: `${path}/diff` }, Json.SourceDiff), + read("getDiff", input, { path: `${path}/files` }, Json.SourceFiles).pipe( + Effect.orElseSucceed(() => null), + ), + ], + { concurrency: 2 }, + ); + if (!diff.available || diff.patch === null) + return yield* failure( + "getDiff", + "TanStack Source has no diff for this pull request right now.", + ); + const sections = Json.patchSections(diff.patch); + // Files the cut-off patch leaves out still show, as counts. + const omittedFileStats = (files?.files ?? []) + .filter((file) => !sections.has(file.path)) + .map((file) => ({ + path: file.path, + additions: file.additions ?? 0, + deletions: file.deletions ?? 0, + })); + if (input.path !== undefined) { + const section = sections.get(input.path); + return { + patch: section ?? "", + truncated: section === undefined && diff.truncated === true, + nextCursor: null, + }; + } + return { + patch: diff.patch, + truncated: diff.truncated === true || omittedFileStats.length > 0, + nextCursor: null, + ...(omittedFileStats.length === 0 ? {} : { omittedFileStats }), + }; + }), + + getDiffFilePaths: Effect.fn("TanStackSourcePullRequestProvider.getDiffFilePaths")( + function* (input) { + if (input.commit !== undefined) + return yield* failure( + "getDiffFilePaths", + "TanStack Source cannot list one commit's files here yet.", + ); + const path = yield* pullPath("getDiffFilePaths", input); + const files = yield* read( + "getDiffFilePaths", + input, + { path: `${path}/files` }, + Json.SourceFiles, + ); + return { + files: (files.files ?? []).map((file) => ({ + oldPath: file.oldPath ?? file.path, + newPath: file.path, + })), + nextCursor: null, + }; + }, + ), + + getFileStats: Effect.fn("TanStackSourcePullRequestProvider.getFileStats")(function* (input) { + const path = yield* pullPath("getFileStats", input); + const files = yield* read("getFileStats", input, { path: `${path}/files` }, Json.SourceFiles); + return { + files: (files.files ?? []).map((file) => ({ + path: file.path, + additions: file.additions ?? 0, + deletions: file.deletions ?? 0, + })), + truncated: files.truncated === true, + }; + }), + + getDiffFileContents: Effect.fn("TanStackSourcePullRequestProvider.getDiffFileContents")( + function* (input) { + const operation = "getDiffFileContents"; + if (input.commit !== undefined) + return yield* failure( + operation, + "TanStack Source cannot read one commit's files here yet.", + ); + const path = yield* pullPath(operation, input); + const [pull, files] = yield* Effect.all( + [ + readPull(operation, input), + read(operation, input, { path: `${path}/files` }, Json.SourceFiles), + ], + { concurrency: 2 }, + ); + const oldRevision = files.mergeBaseSha; + const newRevision = files.headSha; + if (oldRevision === null || newRevision === null) + return yield* failure(operation, "TanStack Source has not reported the diff's commits."); + const readFile = (repository: string, revision: string, filePath: string) => + repositoryPath(operation, { ...input, repository }).pipe( + Effect.flatMap((base) => + read( + operation, + input, + { + path: `${base}/contents/${filePath.split("/").map(encodeURIComponent).join("/")}?${new URLSearchParams({ ref: revision })}`, + }, + Json.SourceContents, + ), + ), + Effect.flatMap((file) => + file.binary || file.truncated || file.content === null + ? Effect.fail(failure(operation, `${filePath} is too large or binary to show.`)) + : Effect.succeed(file.content), + ), + ); + const [oldContents, newContents] = yield* Effect.all( + [ + input.changeType === "new" + ? Effect.succeed("") + : readFile(input.repository, oldRevision, input.oldPath), + input.changeType === "deleted" + ? Effect.succeed("") + : readFile(pull.headRepo ?? input.repository, newRevision, input.newPath), + ], + { concurrency: 2 }, + ); + return { oldContents, newContents }; + }, + ), + + getCheckLogs: Effect.fn("TanStackSourcePullRequestProvider.getCheckLogs")(function* (input) { + const base = yield* repositoryPath("getCheckLogs", input); + return yield* Effect.forEach( + input.checks, + (check): Effect.Effect => { + const job = Json.parseCiJobUrl(check.url, input.host); + if (job === null) + return Effect.succeed({ + ...check, + log: null, + truncated: false, + detail: + "This check did not run on TanStack Source CI, which holds no log for it. Open its url.", + }); + const logs = `${base}/ci/runs/${encodeURIComponent(job.runId)}/jobs/${encodeURIComponent(job.job)}/logs`; + return Effect.gen(function* () { + // The first line's answer names every step's line count, so the tail is one more read. + const head = yield* api + .response({ + host: input.host, + operation: "getCheckLogs", + path: `${logs}?from=1&to=1`, + accept: "text/plain", + }) + .pipe(Effect.mapError(toProviderError("getCheckLogs"))); + const steps = decodeLogSteps(head.headers["x-log-steps"] ?? ""); + const total = + steps._tag === "Some" ? steps.value.reduce((sum, step) => sum + step.lines, 0) : 0; + const from = Math.max(1, total - input.tailLines + 1); + const text = + total <= 1 + ? head.text + : yield* send("getCheckLogs", input, { + path: `${logs}?from=${from}&to=${total}`, + accept: "text/plain", + }); + const tail = tailLogLines(text.replace(ANSI, ""), input.tailLines); + return { ...check, log: tail.log, truncated: tail.truncated || from > 1, detail: null }; + }).pipe( + // Sign-in and rate-limit failures fail the call; the rest are this check's. + Effect.catchIf( + (error) => error.reason !== "unauthenticated" && error.reason !== "rate-limited", + (error) => + Effect.succeed({ ...check, log: null, truncated: false, detail: error.detail }), + ), + ); + }, + { concurrency: 4 }, + ); + }), + + rerunChecks: Effect.fn("TanStackSourcePullRequestProvider.rerunChecks")(function* (input) { + const base = yield* repositoryPath("rerunChecks", input); + const located = input.checks.map((check) => ({ + check, + runId: Json.parseCiJobUrl(check.url, input.host)?.runId ?? null, + })); + const runIds = new Set(located.flatMap(({ runId }) => (runId === null ? [] : [runId]))); + const outcomes = new Map(); + yield* Effect.forEach( + runIds, + (runId) => + send("rerunChecks", input, { + method: "POST", + path: `${base}/ci/runs/${encodeURIComponent(runId)}/rerun`, + body: { failedOnly: true }, + }).pipe( + Effect.as(null), + Effect.catchIf( + (error) => error.reason !== "unauthenticated" && error.reason !== "rate-limited", + (error) => Effect.succeed(error.detail), + ), + Effect.map((detail) => outcomes.set(runId, detail)), + ), + { concurrency: 2, discard: true }, + ); + return located.map(({ check, runId }): ProviderCheckRerun => { + if (runId === null) + return { + name: check.name, + rerun: false, + detail: "This check did not run on TanStack Source CI, so it cannot be re-run here.", + }; + const detail = outcomes.get(runId) ?? null; + return { name: check.name, rerun: detail === null, detail }; + }); + }), + + runAction: Effect.fn("TanStackSourcePullRequestProvider.runAction")(function* (input) { + const path = yield* pullPath(input.action, input); + switch (input.action) { + case "merge": + return yield* merge(input); + case "ready": + case "draft": + yield* send(input.action, input, { + method: input.action === "ready" ? "PUT" : "DELETE", + path: `${path}/ready`, + }); + return; + case "close": + case "reopen": + yield* send(input.action, input, { + method: "PATCH", + path, + body: { state: input.action === "close" ? "closed" : "open" }, + }); + return; + case "update-branch": { + const pull = yield* readPull(input.action, input); + yield* send(input.action, input, { + method: "POST", + path: `${path}/update-branch`, + body: { + rebase: input.updateMethod === "rebase", + ...(pull.headSha === null ? {} : { sha: input.expectedHeadSha ?? pull.headSha }), + }, + }); + return; + } + case "enable-auto-merge": + yield* send(input.action, input, { + method: "PUT", + path: `${path}/auto-merge`, + body: { merge_method: input.mergeMethod === "squash" ? "squash" : "merge" }, + }); + return; + case "disable-auto-merge": + yield* send(input.action, input, { method: "DELETE", path: `${path}/auto-merge` }); + return; + default: + return yield* failure( + input.action, + `TanStack Source cannot ${input.action} from T3 Code.`, + ); + } + }), + + updateChangeRequest: Effect.fn("TanStackSourcePullRequestProvider.updateChangeRequest")( + function* (input) { + const path = yield* pullPath("updateChangeRequest", input); + yield* send("updateChangeRequest", input, { + method: "PATCH", + path, + body: { + ...(input.title === undefined ? {} : { title: input.title }), + ...(input.body === undefined ? {} : { body: input.body }), + }, + }); + }, + ), + + comment: Effect.fn("TanStackSourcePullRequestProvider.comment")(function* (input) { + const base = yield* repositoryPath("comment", input); + yield* send("comment", input, { + method: "POST", + path: `${base}/issues/${input.number}/comments`, + body: { body: input.body }, + }); + }), + + updateComment: Effect.fn("TanStackSourcePullRequestProvider.updateComment")(function* (input) { + if (!/^\d+$/u.test(input.commentId)) + return yield* failure("updateComment", "TanStack Source comment ids are numbers."); + const base = yield* repositoryPath("updateComment", input); + yield* send("updateComment", input, { + method: "PATCH", + path: `${base}/issues/comments/${input.commentId}`, + body: { body: input.body }, + }); + }), + + submitReview: Effect.fn("TanStackSourcePullRequestProvider.submitReview")(function* (input) { + const pull = yield* readPull("submitReview", input); + if (input.comments.length > 0 && pull.headSha === null) + return yield* failure( + "submitReview", + "TanStack Source has not reported the pull request's head, which line comments pin to.", + ); + const path = yield* pullPath("submitReview", input); + yield* send("submitReview", input, { + method: "POST", + path: `${path}/reviews`, + body: { + verdict: + input.verdict === "approve" + ? "approved" + : input.verdict === "request-changes" + ? "changes_requested" + : "commented", + ...(input.body.length === 0 ? {} : { body: input.body }), + ...(input.comments.length === 0 + ? {} + : { + comments: input.comments.map((comment) => + Json.toReviewComment(comment, pull.headSha!), + ), + }), + }, + }); + }), + + listReviewerCandidates: () => Effect.succeed({ candidates: [], truncated: false }), + + setReviewerRequest: Effect.fn("TanStackSourcePullRequestProvider.setReviewerRequest")( + function* (input) { + const path = yield* pullPath("setReviewerRequest", input); + const usernames = input.reviewers.map((reviewer) => reviewer.id); + yield* send("setReviewerRequest", input, { + method: "POST", + path: `${path}/reviewers`, + body: input.requested ? { add: usernames } : { remove: usernames }, + }); + }, + ), + + listLabelCandidates: Effect.fn("TanStackSourcePullRequestProvider.listLabelCandidates")( + function* (input) { + const base = yield* repositoryPath("listLabelCandidates", input); + const [labels, pull] = yield* Effect.all( + [ + read("listLabelCandidates", input, { path: `${base}/labels` }, Json.SourceLabels), + readPull("listLabelCandidates", input), + ], + { concurrency: 2 }, + ); + const applied = new Set(pull.labels ?? []); + return { + candidates: labels.map((label) => ({ + name: label.name, + color: label.color, + description: label.description ?? null, + isApplied: applied.has(label.name), + })), + truncated: false, + }; + }, + ), + + listRepositoryLabels: Effect.fn("TanStackSourcePullRequestProvider.listRepositoryLabels")( + function* (input) { + const base = yield* repositoryPath("listRepositoryLabels", input); + const labels = yield* read( + "listRepositoryLabels", + input, + { path: `${base}/labels` }, + Json.SourceLabels, + ); + return { + items: labels.map((label) => ({ name: label.name, color: label.color })), + truncated: false, + }; + }, + ), + + setLabels: Effect.fn("TanStackSourcePullRequestProvider.setLabels")(function* (input) { + const base = yield* repositoryPath("setLabels", input); + const path = `${base}/issues/${input.number}/labels`; + if (input.applied) { + yield* send("setLabels", input, { method: "POST", path, body: { labels: input.labels } }); + return; + } + yield* Effect.forEach( + input.labels, + (label) => + send("setLabels", input, { + method: "DELETE", + path: `${path}/${encodeURIComponent(label)}`, + }), + { concurrency: 2, discard: true }, + ); + }), + + replyToThread: Effect.fn("TanStackSourcePullRequestProvider.replyToThread")(function* (input) { + if (!/^\d+$/u.test(input.threadId)) + return yield* failure("replyToThread", "TanStack Source thread ids are numbers."); + const path = yield* pullPath("replyToThread", input); + yield* send("replyToThread", input, { + method: "POST", + path: `${path}/comments`, + body: { replyTo: Number(input.threadId), body: input.body }, + }); + }), + + setReaction: () => + Effect.fail(failure("setReaction", "TanStack Source reactions are not supported here yet.")), + + setThreadResolution: Effect.fn("TanStackSourcePullRequestProvider.setThreadResolution")( + function* (input) { + if (!/^\d+$/u.test(input.threadId)) + return yield* failure("setThreadResolution", "TanStack Source thread ids are numbers."); + const path = yield* pullPath("setThreadResolution", input); + yield* send("setThreadResolution", input, { + method: "PUT", + path: `${path}/threads/${input.threadId}`, + body: { resolved: input.resolved }, + }); + }, + ), + }; + return provider; +}); diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts new file mode 100644 index 0000000000000..509e03e1f41f4 --- /dev/null +++ b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts @@ -0,0 +1,132 @@ +import { assert, describe, it } from "@effect/vitest"; +import { GitCommandError } from "@t3tools/contracts"; +import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; + +import * as TanStackSourceApi from "./TanStackSourceApi.ts"; +import * as TanStackSourceSourceControlProvider from "./TanStackSourceSourceControlProvider.ts"; + +const REMOTE = "https://source.tanstack.com/@acme/web.git"; +const OWNER_KEY = "branch.pr-42.t3TanstackSourcePull"; + +/** Pull request #42 of acme/web, opened from a fork, so it checks out as `pr-42`. */ +const PULL = { + number: 42, + title: "Fix the thing", + state: "open", + draft: false, + author: "bob", + head: "fix-thing", + createdAt: 1_000, + body: null, + base: "main", + headRepo: "bob/web", + headSha: "c".repeat(40), + baseSha: "b".repeat(40), + mergeCommitSha: null, + mergedAt: null, + mergedBy: null, + mergeable: null, + changedFiles: null, +}; + +function checkout(options: { + readonly recordedOwner: string | null; + readonly isAncestor: boolean; +}) { + const git: Array = []; + const config = new Map( + options.recordedOwner === null ? [] : [[OWNER_KEY, options.recordedOwner]], + ); + const api = TanStackSourceApi.TanStackSourceApi.of({ + request: (input) => + input.path === "/repos/acme/web/pulls/42" + ? Effect.succeed(JSON.stringify(PULL)) + : Effect.die(`unexpected ${input.path}`), + response: () => Effect.die("unexpected response read"), + }); + const host = TestSourceControlHost.layer({ + git: { + resolvePrimaryRemoteName: () => Effect.succeed("origin"), + ensureRemote: () => Effect.succeed("origin"), + readConfigValue: (_cwd, key) => + Effect.succeed(key === "remote.origin.url" ? REMOTE : (config.get(key) ?? null)), + writeConfigValue: (input) => Effect.sync(() => void config.set(input.key, input.value)), + listLocalBranchNames: () => Effect.succeed(["main", "pr-42"]), + createBranch: (input) => Effect.sync(() => void git.push(`create ${input.branch}`)), + switchRef: (input) => + Effect.sync(() => { + git.push(`switch ${input.refName}`); + return { refName: input.refName }; + }), + execute: (input) => + input.args[0] === "merge-base" && !options.isAncestor + ? Effect.fail( + new GitCommandError({ + operation: input.operation, + command: "git", + cwd: input.cwd, + argumentCount: input.args.length, + exitCode: 1, + detail: "not an ancestor", + }), + ) + : Effect.sync(() => { + git.push(input.args.join(" ")); + return { + exitCode: 0, + stdout: "", + stderr: "", + stdoutTruncated: false, + stderrTruncated: false, + } as never; + }), + }, + }); + const run = TanStackSourceSourceControlProvider.make.pipe( + Effect.flatMap((provider) => provider.checkoutChangeRequest({ cwd: "/repo", reference: "42" })), + Effect.provideService(TanStackSourceApi.TanStackSourceApi, api), + Effect.provide(Layer.merge(host, FileSystem.layerNoop({}))), + ); + return { run, git, config }; +} + +describe("TanStackSourceSourceControlProvider.checkoutChangeRequest", () => { + it.effect( + "refuses a pr- branch T3 did not make for this pull request, and leaves it alone", + () => { + // An unrelated branch at the pull request's base is an ancestor of its head. + const { run, git, config } = checkout({ recordedOwner: null, isAncestor: true }); + return Effect.gen(function* () { + const error = yield* Effect.flip(run); + assert.include(error.detail, "pr-42 was not made for pull request #42"); + assert.isFalse( + git.some((command) => command.startsWith("checkout") || command.startsWith("switch")), + ); + assert.isFalse(config.has(OWNER_KEY)); + }); + }, + ); + + it.effect("moves the branch it made for the pull request up to the new head", () => { + const { run, git } = checkout({ recordedOwner: "acme/web#42", isAncestor: true }); + return Effect.gen(function* () { + yield* run; + assert.deepStrictEqual( + git.filter((command) => /^(checkout|switch|create) /u.test(command)), + ["checkout --no-track -B pr-42 refs/remotes/origin/pull/42 --", "switch pr-42"], + ); + }); + }); + + it.effect("keeps local commits on its own branch rather than moving it", () => { + const { run, git } = checkout({ recordedOwner: "acme/web#42", isAncestor: false }); + return Effect.gen(function* () { + const error = yield* Effect.flip(run); + assert.include(error.detail, "has commits pull request #42 does not"); + assert.isFalse(git.some((command) => command.startsWith("checkout"))); + }); + }); +}); diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts new file mode 100644 index 0000000000000..a1abb376b472d --- /dev/null +++ b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts @@ -0,0 +1,610 @@ +import { + requireSettingsSecretLiteral, + SourceControlProviderError, + type ChangeRequest, + type SourceControlProviderAuth, + type SourceControlProviderDiscoveryItem, +} from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { + isMissingExecutable, + providerAuth, + type SourceControlManagedCliDiscoverySpec, +} from "@t3tools/source-control-core/server/discovery"; +import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; +import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider"; +import { readSourceControlHostSettings } from "@t3tools/source-control-core/shared/definition"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import * as Result from "effect/Result"; +import * as Schema from "effect/Schema"; + +import * as TanStackSource from "../shared/definition.ts"; +import * as TanStackSourceApi from "./TanStackSourceApi.ts"; +import { parseTanStackSourceAuthStatus } from "./tanStackSourceAuthStatus.ts"; +import * as TanStackSourceCredentials from "./TanStackSourceCredentials.ts"; +import * as Hosts from "./tanStackSourceHosts.ts"; +import * as Json from "./tanStackSourceJson.ts"; + +const HOST = TanStackSource.TANSTACK_SOURCE_HOST; +/** Pull requests from one branch name, across forks, read in full when looking one up. */ +const MAX_BRANCH_MATCHES = 20; +const LABEL = "TanStack Source"; +const LOGIN = `src auth login --web --hostname ${HOST}`; + +const INSTALL_HINT = `Install the TanStack Source CLI with \`curl -fsSL https://${HOST}/install | sh\`, then run \`${LOGIN}\`, save a token in Settings, or set SRC_TOKEN on the server.`; + +/** The account a request would use: SRC_TOKEN, else the one picked in Settings, else the active one. */ +export function effectiveAccount( + accounts: ReturnType, + choice: string | undefined, +) { + const usable = accounts.filter((entry) => entry.host === HOST && entry.authenticated); + return ( + usable.find((entry) => entry.environmentVariable !== null) ?? + (choice === undefined ? undefined : usable.find((entry) => entry.account === choice)) ?? + usable.find((entry) => entry.active) ?? + usable[0] + ); +} + +const decodeUser = Schema.decodeEffect(Schema.fromJsonString(Json.SourceUser)); + +const authAccounts = (accounts: ReturnType) => + accounts + .filter((entry) => entry.account !== "") + .map((entry) => ({ + host: entry.host, + account: entry.account, + active: entry.active, + authenticated: entry.authenticated, + ...(entry.error === null ? {} : { error: entry.error }), + ...(entry.environmentVariable === null + ? {} + : { environmentVariable: entry.environmentVariable }), + })); + +/** + * `src` has no version flag, so its sign-in status is the only probe. A saved token or SRC_TOKEN + * is checked against the API, since the CLI knows nothing of the first. + */ +export const makeDiscovery = Effect.gen(function* () { + const sourceControlHost = yield* SourceControlHost.SourceControlHost; + const api = yield* TanStackSourceApi.TanStackSourceApi; + const environment = yield* HostProcess.Environment; + + const viewer = api.request({ host: HOST, operation: "discovery", path: "/user" }).pipe( + Effect.flatMap((raw) => + decodeUser(raw).pipe( + Effect.mapError( + (cause) => + new TanStackSourceApi.TanStackSourceApiError({ + host: HOST, + operation: "discovery", + status: null, + reason: "failed", + detail: "TanStack Source returned an unreadable account.", + cause, + }), + ), + ), + ), + Effect.result, + ); + + const probe = Effect.fn("TanStackSourceSourceControlProvider.discovery")(function* (cwd: string) { + const current = yield* sourceControlHost.settings + .getWithSecrets(TanStackSource.definition.kind) + .pipe(Effect.orElseSucceed(() => undefined)); + const settings = readSourceControlHostSettings( + TanStackSource.settings, + current?.sourceControlHosts[TanStackSource.definition.kind], + ); + const status = yield* sourceControlHost.process + .run({ + operation: "source-control.discovery.auth", + command: "src", + args: ["auth", "status"], + cwd, + env: { SRC_NO_TELEMETRY: "1" }, + allowNonZeroExit: true, + timeoutMs: 5_000, + maxOutputBytes: 8_000, + appendTruncationMarker: true, + }) + .pipe(Effect.result); + const installed = Result.isSuccess(status) || !isMissingExecutable(status.failure); + const accounts = Result.isSuccess(status) + ? parseTanStackSourceAuthStatus(`${status.success.stdout}\n${status.success.stderr}`) + : []; + const item = (fields: { + readonly auth: SourceControlProviderAuth; + readonly available: boolean; + }): SourceControlProviderDiscoveryItem => ({ + kind: TanStackSource.definition.kind, + label: LABEL, + executable: "src", + status: fields.available ? "available" : "missing", + version: Option.none(), + installHint: INSTALL_HINT, + detail: Option.none(), + auth: + accounts.length === 0 ? fields.auth : { ...fields.auth, accounts: authAccounts(accounts) }, + }); + + if (settings.hosts[HOST]?.enabled === false) + return item({ + available: installed, + auth: providerAuth({ + status: "unauthenticated", + host: HOST, + detail: `${HOST} is turned off in Settings → Source control & issues.`, + }), + }); + + const saved = yield* Effect.result( + requireSettingsSecretLiteral(settings.tokens[HOST], current?.secretProviders ?? {}), + ); + if (Result.isFailure(saved)) + return item({ + available: true, + auth: providerAuth({ + status: "unauthenticated", + host: HOST, + detail: saved.failure.message, + }), + }); + const savedToken = saved.success.trim() !== ""; + const envToken = TanStackSourceCredentials.environmentToken(HOST, environment) !== null; + if (savedToken || envToken) { + const tokenSource = savedToken ? "the token saved in Settings" : "SRC_TOKEN"; + const answer = yield* viewer; + return item({ + available: true, + auth: Result.isSuccess(answer) + ? providerAuth({ + status: "authenticated", + host: HOST, + account: answer.success.username, + detail: savedToken + ? "Using the token saved in Settings; it overrides SRC_TOKEN and the src login." + : "Using SRC_TOKEN from the server environment; it overrides the account chosen in Settings.", + }) + : answer.failure.reason === "unauthenticated" + ? providerAuth({ + status: "unauthenticated", + host: HOST, + detail: savedToken + ? "TanStack Source refused the token saved in Settings. Replace or remove it in Settings → Source control & issues." + : "TanStack Source refused the token in SRC_TOKEN. Replace it, or unset it to use `src auth login`.", + }) + : providerAuth({ + status: "unknown", + host: HOST, + detail: `Could not check ${tokenSource}: ${answer.failure.detail}`, + }), + }); + } + + if (!installed) + return item({ + available: false, + auth: providerAuth({ status: "unknown", detail: INSTALL_HINT }), + }); + const chosen = effectiveAccount(accounts, settings.hosts[HOST]?.account); + if (chosen !== undefined) + return item({ + available: true, + auth: providerAuth({ status: "authenticated", host: HOST, account: chosen.account }), + }); + const failed = accounts.find((entry) => entry.host === HOST); + return item({ + available: true, + auth: providerAuth({ + status: Result.isSuccess(status) ? "unauthenticated" : "unknown", + host: HOST, + detail: failed?.error ?? `Run \`${LOGIN}\` to sign the src CLI in.`, + }), + }); + }); + + return { + type: "managed-cli", + kind: TanStackSource.definition.kind, + label: LABEL, + installHint: INSTALL_HINT, + probe, + // Source's remotes are recognized by host alone, so an unknown remote is never one. + refineUnknownRemote: () => Effect.succeed(null), + } satisfies SourceControlManagedCliDiscoverySpec; +}); + +const Repository = Schema.Struct({ + owner: Schema.String, + name: Schema.String, + defaultBranch: Schema.NullOr(Schema.String), + cloneUrl: Schema.String, +}); + +interface Target { + readonly host: Hosts.TanStackSourceHost; + readonly repository: string; +} + +const cloneUrls = (target: Target, cloneUrl?: string) => { + const url = cloneUrl ?? `${Hosts.webRepositoryUrl(target.host, target.repository)}.git`; + // Source serves git over HTTPS only. + return { nameWithOwner: target.repository, url, sshUrl: url }; +}; + +export const make = Effect.gen(function* () { + const api = yield* TanStackSourceApi.TanStackSourceApi; + const host = yield* SourceControlHost.SourceControlHost; + const fileSystem = yield* FileSystem.FileSystem; + + const error = (operation: string, cwd: string, detail: string, cause?: unknown) => + new SourceControlProviderError({ + provider: TanStackSource.definition.kind, + operation, + cwd, + detail, + ...(cause === undefined ? {} : { cause }), + }); + const read = >( + operation: string, + cwd: string, + request: Omit, + schema: S, + ) => + api.request({ ...request, operation }).pipe( + Effect.mapError((cause) => error(operation, cwd, cause.detail, cause)), + Effect.flatMap((raw) => + Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe( + Effect.mapError((cause) => + error(operation, cwd, "TanStack Source returned an unreadable response.", cause), + ), + ), + ), + ); + + const resolveTarget = Effect.fn("TanStackSourceSourceControlProvider.resolveTarget")(function* ( + operation: string, + input: { + readonly cwd: string; + readonly context?: SourceControlProvider.SourceControlProviderContext; + readonly repository?: string; + }, + ) { + const named = + input.repository === undefined ? null : Hosts.parseTanStackSourceRemote(input.repository); + if (named) return named; + if (input.repository !== undefined) { + const repository = Hosts.tanStackSourceRepositoryPath(input.repository); + if (repository !== null) return { host: HOST, repository } satisfies Target; + return yield* error( + operation, + input.cwd, + "A TanStack Source repository is named owner/name or by its source.tanstack.com URL.", + ); + } + const remoteUrl = + input.context?.remoteUrl ?? + (yield* host.git.resolvePrimaryRemoteName(input.cwd).pipe( + Effect.flatMap((remote) => host.git.readConfigValue(input.cwd, `remote.${remote}.url`)), + Effect.mapError((cause) => + error(operation, input.cwd, "Could not read the TanStack Source remote.", cause), + ), + )); + const remote = remoteUrl ? Hosts.parseTanStackSourceRemote(remoteUrl) : null; + if (remote) return remote; + return yield* error(operation, input.cwd, "No TanStack Source repository remote was found."); + }); + + const toChangeRequest = (target: Target, pull: Json.SourcePullDetail): ChangeRequest => { + const headRepository = pull.headRepo ?? target.repository; + const headBranch = Json.headBranchName(pull.head); + // A pull request synced from a GitHub fork names its head only by its pull ref. + const crossRepository = + headRepository.toLowerCase() !== target.repository.toLowerCase() || + headBranch.startsWith("refs/"); + const updatedAt = pull.mergedAt ?? pull.createdAt; + return { + provider: TanStackSource.definition.kind, + number: pull.number, + title: pull.title, + url: Json.pullUrl(target.host, target.repository, pull.number), + baseRefName: pull.base, + headRefName: headBranch, + ...(pull.headSha ? { headSha: pull.headSha } : {}), + state: pull.state, + ...(pull.draft ? { isDraft: true } : {}), + mergedAt: pull.mergedAt === null ? null : Json.iso(pull.mergedAt), + updatedAt: Option.some(DateTime.makeUnsafe(updatedAt)), + isCrossRepository: crossRepository, + headRepositoryNameWithOwner: headRepository, + headRepositoryOwnerLogin: headRepository.split("/")[0] ?? null, + }; + }; + + const readPull = (operation: string, cwd: string, target: Target, number: number) => + read( + operation, + cwd, + { host: target.host, path: `/repos/${target.repository}/pulls/${number}` }, + Json.SourcePullDetail, + ).pipe(Effect.map((pull) => toChangeRequest(target, pull))); + + const getPull = Effect.fn("TanStackSourceSourceControlProvider.getPull")(function* (input: { + readonly cwd: string; + readonly context?: SourceControlProvider.SourceControlProviderContext; + readonly reference: string; + }) { + const link = TanStackSource.parsePullRequestUrl(input.reference.trim()); + const target: Target = link + ? { host: HOST, repository: link.repository } + : yield* resolveTarget("getChangeRequest", input); + const number = link ? link.number : Number(/^#?([1-9]\d*)$/u.exec(input.reference.trim())?.[1]); + if (!Number.isSafeInteger(number) || number < 1) + return yield* error( + "getChangeRequest", + input.cwd, + "A TanStack Source pull request is a number or a source.tanstack.com pull request URL.", + ); + return yield* readPull("getChangeRequest", input.cwd, target, number); + }); + + return SourceControlProvider.SourceControlProvider.of({ + kind: TanStackSource.definition.kind, + repositoryNameFromRemoteUrl: (url) => Hosts.parseTanStackSourceRemote(url)?.repository ?? null, + getChangeRequest: getPull, + listChangeRequests: Effect.fn("TanStackSourceSourceControlProvider.listChangeRequests")( + function* (input) { + const target = yield* resolveTarget("listChangeRequests", input); + const source = SourceControlProvider.sourceControlRefFromInput(input); + const branch = SourceControlProvider.sourceBranch(input); + const limit = input.limit ?? 20; + const query = new URLSearchParams({ head: branch }); + if (input.state !== "all") query.set("state", input.state); + const page = yield* read( + "listChangeRequests", + input.cwd, + { host: target.host, path: `/repos/${target.repository}/pulls?${query}` }, + Json.SourcePulls, + ); + // List rows name neither the base nor the head's repository, so matches are read in full + // and the limit counts only those whose head is the one asked for. + const matches = page.items + .filter((pull) => Json.headBranchName(pull.head) === branch) + .slice(0, MAX_BRANCH_MATCHES); + const details = yield* Effect.forEach( + matches, + (pull) => readPull("listChangeRequests", input.cwd, target, pull.number), + { concurrency: 4 }, + ); + const owned = details.filter( + (detail) => + (!source?.repository || + detail.headRepositoryNameWithOwner?.toLowerCase() === + source.repository.toLowerCase()) && + (!source?.owner || + detail.headRepositoryOwnerLogin?.toLowerCase() === source.owner.toLowerCase()), + ); + return owned.slice(0, limit); + }, + ), + createsDraftChangeRequests: true, + createChangeRequest: Effect.fn("TanStackSourceSourceControlProvider.createChangeRequest")( + function* (input) { + const target = yield* resolveTarget("createChangeRequest", { + ...input, + ...(input.target?.repository ? { repository: input.target.repository } : {}), + }); + const source = SourceControlProvider.sourceControlRefFromInput(input); + if ( + (source?.repository && + source.repository.toLowerCase() !== target.repository.toLowerCase()) || + (source?.owner && + source.owner.toLowerCase() !== target.repository.split("/")[0]?.toLowerCase()) + ) + return yield* error( + "createChangeRequest", + input.cwd, + "TanStack Source opens pull requests from a branch of the same repository. Push the branch there first.", + ); + const body = yield* fileSystem + .readFileString(input.bodyFile) + .pipe( + Effect.mapError((cause) => + error( + "createChangeRequest", + input.cwd, + "Could not read the pull request description.", + cause, + ), + ), + ); + yield* api + .request({ + host: target.host, + operation: "createChangeRequest", + method: "POST", + path: `/repos/${target.repository}/pulls`, + body: { + title: input.title, + head: SourceControlProvider.sourceBranch(input), + base: input.target?.refName ?? input.baseRefName, + ...(body.trim().length === 0 ? {} : { body }), + ...(input.draft === true ? { draft: true } : {}), + }, + }) + .pipe( + Effect.mapError((cause) => + error("createChangeRequest", input.cwd, cause.detail, cause), + ), + ); + }, + ), + getRepositoryCloneUrls: Effect.fn("TanStackSourceSourceControlProvider.getRepositoryCloneUrls")( + function* (input) { + const target = yield* resolveTarget("getRepositoryCloneUrls", input); + const repository = yield* read( + "getRepositoryCloneUrls", + input.cwd, + { host: target.host, path: `/repos/${target.repository}` }, + Repository, + ); + return cloneUrls( + { host: target.host, repository: `${repository.owner}/${repository.name}` }, + repository.cloneUrl, + ); + }, + ), + createRepository: Effect.fn("TanStackSourceSourceControlProvider.createRepository")( + function* (input) { + const target = yield* resolveTarget("createRepository", input); + const [owner, name] = target.repository.split("/"); + const created = yield* read( + "createRepository", + input.cwd, + { + host: target.host, + method: "POST", + path: "/repos", + body: { name, owner, visibility: input.visibility }, + }, + Repository, + ); + return cloneUrls( + { host: target.host, repository: `${created.owner}/${created.name}` }, + created.cloneUrl, + ); + }, + ), + getDefaultBranch: Effect.fn("TanStackSourceSourceControlProvider.getDefaultBranch")( + function* (input) { + const target = yield* resolveTarget("getDefaultBranch", input); + const repository = yield* read( + "getDefaultBranch", + input.cwd, + { host: target.host, path: `/repos/${target.repository}` }, + Repository, + ); + return repository.defaultBranch; + }, + ), + // Every pull request's head is published as `refs/pull//head`, forks and GitHub sync too. + checkoutChangeRequest: Effect.fn("TanStackSourceSourceControlProvider.checkoutChangeRequest")( + function* (input) { + const pull = yield* getPull(input); + const target = yield* resolveTarget("checkoutChangeRequest", input).pipe( + Effect.orElseSucceed(() => null), + ); + const pullRepository = Hosts.tanStackSourceRepositoryPath( + new URL(pull.url).pathname.split("/pull/")[0] ?? "", + ); + const git = host.git; + yield* Effect.gen(function* () { + const remoteName = + input.context && + target !== null && + pullRepository !== null && + target.repository.toLowerCase() === pullRepository.toLowerCase() + ? input.context.remoteName + : yield* git.ensureRemote({ + cwd: input.cwd, + preferredName: "source", + url: `${Hosts.webRepositoryUrl(HOST, pullRepository ?? "")}.git`, + }); + const operation = "TanStackSourceSourceControlProvider.checkoutChangeRequest"; + const branches = yield* git.listLocalBranchNames(input.cwd); + if (!pull.isCrossRepository) { + const localBranch = pull.headRefName; + const remoteBranch = { cwd: input.cwd, remoteName, remoteBranch: localBranch }; + if (input.force !== true && !branches.includes(localBranch)) + yield* git.fetchRemoteBranch({ ...remoteBranch, localBranch }); + else yield* git.fetchRemoteTrackingBranch(remoteBranch); + if (input.force === true) + yield* git.execute({ + operation, + cwd: input.cwd, + // The upstream is recorded next, through the host's serialized config write. + args: [ + "checkout", + "--no-track", + "-B", + localBranch, + `refs/remotes/${remoteName}/${localBranch}`, + "--", + ], + }); + yield* git.setBranchUpstream({ ...remoteBranch, branch: localBranch }); + yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch })); + return; + } + // A fork's head, or one synced from GitHub, is only reachable through its pull ref. + const localBranch = `pr-${pull.number}`; + const tracking = `refs/remotes/${remoteName}/pull/${pull.number}`; + yield* git.execute({ + operation, + cwd: input.cwd, + args: ["fetch", "--no-tags", remoteName, `+refs/pull/${pull.number}/head:${tracking}`], + }); + const exists = branches.includes(localBranch); + // T3 records which pull request it made `pr-` for, and reuses only that branch, and + // only while it holds nothing the pull request lacks: an unrelated branch of the name, + // or local commits, are never switched to, moved or lost. + const ownerKey = `branch.${localBranch}.t3TanstackSourcePull`; + const owner = `${pullRepository ?? ""}#${pull.number}`; + if (exists && input.force !== true) { + const recorded = yield* git + .readConfigValue(input.cwd, ownerKey) + .pipe(Effect.orElseSucceed(() => null)); + const behind = + recorded === owner && + (yield* git + .execute({ + operation, + cwd: input.cwd, + args: ["merge-base", "--is-ancestor", `refs/heads/${localBranch}`, tracking], + }) + .pipe( + Effect.as(true), + Effect.orElseSucceed(() => false), + )); + if (!behind) + return yield* error( + "checkoutChangeRequest", + input.cwd, + recorded === owner + ? `Local branch ${localBranch} has commits pull request #${pull.number} does not. Rename it, or check out with force to replace it.` + : `Local branch ${localBranch} was not made for pull request #${pull.number}. Rename it, or check out with force to replace it.`, + ); + } + if (exists) + yield* git.execute({ + operation, + cwd: input.cwd, + args: ["checkout", "--no-track", "-B", localBranch, tracking, "--"], + }); + else + yield* git.createBranch({ cwd: input.cwd, branch: localBranch, startPoint: tracking }); + yield* git.writeConfigValue({ cwd: input.cwd, key: ownerKey, value: owner }); + yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch })); + }).pipe( + Effect.mapError((cause) => + cause._tag === "SourceControlProviderError" + ? cause + : error( + "checkoutChangeRequest", + input.cwd, + "Could not check out the TanStack Source pull request.", + cause, + ), + ), + ); + }, + ), + }); +}); diff --git a/packages/source-control-tanstack-source/src/server/driver.ts b/packages/source-control-tanstack-source/src/server/driver.ts new file mode 100644 index 0000000000000..d8a25334f7297 --- /dev/null +++ b/packages/source-control-tanstack-source/src/server/driver.ts @@ -0,0 +1,29 @@ +import { + defineSourceControlDriver, + withOwnServices, +} from "@t3tools/source-control-core/server/driver"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import { definition } from "../shared/definition.ts"; + +import * as TanStackSourceApi from "./TanStackSourceApi.ts"; +import * as TanStackSourceCredentials from "./TanStackSourceCredentials.ts"; +import * as TanStackSourceIssueTracker from "./TanStackSourceIssueTracker.ts"; +import * as TanStackSourcePullRequestProvider from "./TanStackSourcePullRequestProvider.ts"; +import * as TanStackSourceSourceControlProvider from "./TanStackSourceSourceControlProvider.ts"; + +const services = TanStackSourceApi.layer.pipe(Layer.provideMerge(TanStackSourceCredentials.layer)); + +const makeInstance = Effect.all({ + sourceControl: TanStackSourceSourceControlProvider.make, + discovery: TanStackSourceSourceControlProvider.makeDiscovery, + pullRequests: TanStackSourcePullRequestProvider.make, + issues: TanStackSourceIssueTracker.make, +}); + +export const driver = defineSourceControlDriver({ + kind: definition.kind, + definition, + make: withOwnServices(makeInstance, services), +}); diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceAuthStatus.test.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceAuthStatus.test.ts new file mode 100644 index 0000000000000..7a9bfafa852ee --- /dev/null +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceAuthStatus.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { parseTanStackSourceAuthStatus } from "./tanStackSourceAuthStatus.ts"; +import { effectiveAccount } from "./TanStackSourceSourceControlProvider.ts"; + +// Captured from src 0.6.2. +const SIGNED_IN = `source.tanstack.com + ✓ Logged in to source.tanstack.com account alice (/home/alice/.config/src/hosts.json) + - Active account: true + - Git operations protocol: https + - Token: tsp_**************************************** + ✓ Logged in to source.tanstack.com account bob (/home/alice/.config/src/hosts.json) + - Active account: false + - Git operations protocol: https + - Token: tsp_**************************************** +`; + +const REFUSED_ENV_TOKEN = `source.tanstack.com + X Failed to log in to source.tanstack.com using token (SRC_TOKEN) + - Active account: true + - The token in SRC_TOKEN is invalid. + + ✓ Logged in to source.tanstack.com account alice (/home/alice/.config/src/hosts.json) + - Active account: false + - Git operations protocol: https + - Token: tsp_**************************************** +`; + +describe("parseTanStackSourceAuthStatus", () => { + it("reads every login with its active flag, and never a token line", () => { + const accounts = parseTanStackSourceAuthStatus(SIGNED_IN); + expect(accounts).toEqual([ + { + host: "source.tanstack.com", + account: "alice", + authenticated: true, + active: true, + error: null, + environmentVariable: null, + }, + { + host: "source.tanstack.com", + account: "bob", + authenticated: true, + active: false, + error: null, + environmentVariable: null, + }, + ]); + expect(effectiveAccount(accounts, undefined)?.account).toBe("alice"); + expect(effectiveAccount(accounts, "bob")?.account).toBe("bob"); + expect(effectiveAccount(accounts, "carol")?.account).toBe("alice"); + }); + + it("keeps a refused SRC_TOKEN's reason and falls back to the saved login", () => { + const accounts = parseTanStackSourceAuthStatus(REFUSED_ENV_TOKEN); + expect(accounts[0]).toEqual({ + host: "source.tanstack.com", + account: "", + authenticated: false, + active: true, + error: "The token in SRC_TOKEN is invalid.", + environmentVariable: "SRC_TOKEN", + }); + expect(effectiveAccount(accounts, undefined)?.account).toBe("alice"); + }); + + it("reads no login from a signed-out CLI", () => { + expect( + parseTanStackSourceAuthStatus( + "You are not logged into any TanStack Source hosts. To log in, run: src auth login\n", + ), + ).toEqual([]); + }); +}); diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceAuthStatus.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceAuthStatus.ts new file mode 100644 index 0000000000000..484d3cc1c83dc --- /dev/null +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceAuthStatus.ts @@ -0,0 +1,65 @@ +export interface TanStackSourceAuthAccount { + readonly host: string; + readonly account: string; + readonly authenticated: boolean; + readonly active: boolean; + readonly error: string | null; + /** Set when the login is `SRC_TOKEN`, which `src` puts before every saved login. */ + readonly environmentVariable: string | null; +} + +const HOST_LINE = /^([a-z0-9][a-z0-9.-]*(?::\d+)?)$/iu; +const ACCOUNT_LINE = + /^\s*(?:✓|X)\s+(Logged in|Failed to log in) to (\S+) (?:account (\S+)(?: \(([A-Z][A-Z0-9_]*)\))?|using token \(([A-Z][A-Z0-9_]*)\))/u; +const ACTIVE_LINE = /^\s*-\s+Active account:\s+(true|false)\s*$/u; +const DETAIL_LINE = /^\s*-\s+(.+)$/u; +const SAFE_DETAIL = /^(?!Token:|Git operations protocol:)/u; + +/** + * `src auth status` speaks `gh auth status`'s text (it has no `--json`): a host line, then per + * login a `✓`/`X` line and indented `- key: value` lines, the last of a failed one its reason. + */ +export function parseTanStackSourceAuthStatus( + text: string, +): ReadonlyArray { + const accounts: Array = []; + let current: { + host: string; + account: string; + authenticated: boolean; + active: boolean; + error: string | null; + environmentVariable: string | null; + } | null = null; + for (const line of text.split(/\r?\n/u)) { + if (HOST_LINE.test(line.trim()) && !line.startsWith(" ")) { + current = null; + continue; + } + const login = ACCOUNT_LINE.exec(line); + if (login !== null) { + const variable = login[4] ?? login[5] ?? null; + current = { + host: login[2]!.toLowerCase(), + // A refused SRC_TOKEN names no account; it is reported, but is no login to pick. + account: login[3] ?? "", + authenticated: login[1] === "Logged in", + active: false, + error: null, + environmentVariable: variable, + }; + accounts.push(current); + continue; + } + if (current === null) continue; + const active = ACTIVE_LINE.exec(line); + if (active !== null) { + current.active = active[1] === "true"; + continue; + } + const detail = DETAIL_LINE.exec(line)?.[1]?.trim(); + if (!current.authenticated && detail !== undefined && SAFE_DETAIL.test(detail)) + current.error = detail; + } + return accounts; +} diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceEvents.test.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceEvents.test.ts new file mode 100644 index 0000000000000..4838ac862e9f5 --- /dev/null +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceEvents.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { frameReader } from "./tanStackSourceEvents.ts"; + +describe("frameReader", () => { + it("records the id-only frames Source opens with and reports only frames with an event", () => { + const cursor = { lastEventId: undefined as string | undefined }; + const read = frameReader(cursor); + // Captured from `GET /repos/{owner}/{repo}/events?scope=pr&number=4`, then one change. + const lines = [ + ": ok", + "", + "id: 135", + "", + "id: 136", + "event: item", + 'data: {"type":"item"}', + "", + ]; + expect(lines.map(read)).toEqual([false, false, false, false, false, false, false, true]); + expect(cursor.lastEventId).toBe("136"); + }); +}); diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceEvents.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceEvents.ts new file mode 100644 index 0000000000000..a84d70fd275b5 --- /dev/null +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceEvents.ts @@ -0,0 +1,170 @@ +import * as Clock from "effect/Clock"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Random from "effect/Random"; +import * as Redacted from "effect/Redacted"; +import * as Stream from "effect/Stream"; +import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import * as HttpClient from "effect/http/HttpClient"; +import * as HttpClientRequest from "effect/http/HttpClientRequest"; + +import * as Credentials from "./TanStackSourceCredentials.ts"; +import * as Hosts from "./tanStackSourceHosts.ts"; + +/** Source sends `: ok` every 15 seconds and ends each stream after 60. */ +const SILENCE_LIMIT = Duration.seconds(45); +/** A stream that stayed open this long was healthy however it ended; Source closes at 60s. */ +const HEALTHY_AFTER = Duration.seconds(30); +const MAX_FAILURES = 6; +const MAX_BACKOFF_MS = 60_000; +const NO_REDIRECT: RequestInit = { redirect: "manual" }; + +export interface PullRequestEventsInput { + readonly host: string; + readonly repository: string; + readonly number: number; +} + +/** + * Reads Source's stream a line at a time; true where a frame that reports a change ends. Source + * also sends frames with an id alone, which only move the cursor, and `: ok` keep-alives; a + * generic SSE decoder drops the former without recording their id. + */ +export function frameReader(cursor: { lastEventId: string | undefined }) { + let reports = false; + return (line: string): boolean => { + if (line === "") { + const ended = reports; + reports = false; + return ended; + } + if (line.startsWith(":")) return false; + const colon = line.indexOf(":"); + const field = colon < 0 ? line : line.slice(0, colon); + const value = colon < 0 ? "" : line.slice(colon + 1).replace(/^ /u, ""); + if (field === "id") cursor.lastEventId = value; + else if (field === "event" || field === "data") reports = true; + return false; + }; +} + +/** How one connection ended: Source closes every stream after a minute, which is `reconnect`. */ +type Ending = { readonly _tag: "reconnect"; readonly healthy: boolean } | { readonly _tag: "stop" }; + +/** + * Follows the pull request's live event stream: once when it first connects, so a reader catches + * up, then once per change Source reports. Reconnects resume from the last event, so nothing in + * between is lost. Ends quietly when Source refuses it; readers then poll. + */ +export const make = Effect.gen(function* () { + const httpClient = yield* HttpClient.HttpClient; + const credentials = yield* Credentials.TanStackSourceCredentials; + + const connection = ( + input: PullRequestEventsInput, + cursor: { lastEventId: string | undefined }, + ): Stream.Stream<"changed" | Ending> => + Stream.unwrap( + Effect.gen(function* () { + const credential = yield* credentials.get(input.host); + const query = new URLSearchParams({ scope: "pr", number: String(input.number) }); + const response = yield* httpClient + .execute( + HttpClientRequest.get( + `https://${input.host}/api/v1/repos/${input.repository}/events?${query}`, + ).pipe( + HttpClientRequest.setHeaders({ + accept: "text/event-stream", + "user-agent": "t3code", + authorization: `Bearer ${Redacted.value(credential.token)}`, + ...(cursor.lastEventId === undefined + ? {} + : { "last-event-id": cursor.lastEventId }), + }), + ), + ) + .pipe( + Effect.provideService(HttpClient.TracerDisabledWhen, () => true), + Effect.provideService(FetchHttpClient.RequestInit, NO_REDIRECT), + ); + if (response.status === 401 || response.status === 403 || response.status === 404) + return Stream.succeed({ _tag: "stop" }); + if (response.status !== 200) + return Stream.succeed({ _tag: "reconnect", healthy: false }); + const openedAt = yield* Clock.currentTimeMillis; + // A stream with nothing to resume from is a catch-up point; one sent `Last-Event-ID` + // resumes where the last left off, so it misses nothing and needs no refresh of its own. + const opening = cursor.lastEventId === undefined ? (["changed"] as const) : []; + const readLine = frameReader(cursor); + let events = 0; + return response.stream.pipe( + Stream.timeoutOrElse({ duration: SILENCE_LIMIT, orElse: () => Stream.fail("silent") }), + Stream.decodeText, + Stream.splitLines, + Stream.filter(readLine), + Stream.map((): "changed" => { + events += 1; + return "changed"; + }), + Stream.prepend(opening), + Stream.concat( + Stream.fromEffect( + Clock.currentTimeMillis.pipe( + Effect.map((closedAt): Ending => ({ + _tag: "reconnect", + // An event, or a stream that ran most of its minute, proves it worked. + healthy: events > 0 || closedAt - openedAt >= Duration.toMillis(HEALTHY_AFTER), + })), + ), + ), + ), + ); + }), + ).pipe( + Stream.catchCause((cause) => + Stream.fromEffect( + Effect.logDebug("TanStack Source event stream failed", { cause }).pipe( + Effect.as({ _tag: "reconnect", healthy: false }), + ), + ), + ), + ); + + const backoff = Effect.fn("TanStackSourceEvents.backoff")(function* (failures: number) { + const jitter = yield* Random.next; + yield* Effect.sleep( + Duration.millis(Math.min(MAX_BACKOFF_MS, 1_000 * 2 ** failures) * (0.5 + jitter / 2)), + ); + }); + + return (input: PullRequestEventsInput): Stream.Stream => { + const host = Hosts.tanStackSourceHost(input.host); + const repository = Hosts.tanStackSourceRepositoryPath(input.repository); + if (host === null || repository === null) return Stream.empty; + const target = { host, repository, number: input.number }; + const cursor = { lastEventId: undefined as string | undefined }; + + const follow = (failures: number): Stream.Stream => { + let ending: Ending = { _tag: "stop" }; + return connection(target, cursor).pipe( + Stream.flatMap((element) => { + if (element === "changed") return Stream.succeed(undefined); + ending = element; + return Stream.empty; + }), + Stream.concat( + Stream.suspend(() => { + if (ending._tag === "stop") return Stream.empty; + const next = ending.healthy ? 0 : failures + 1; + if (next > MAX_FAILURES) return Stream.empty; + return next === 0 + ? follow(0) + : Stream.fromEffectDrain(backoff(next)).pipe(Stream.concat(follow(next))); + }), + ), + ); + }; + + return follow(0); + }; +}); diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts new file mode 100644 index 0000000000000..22923264629bf --- /dev/null +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts @@ -0,0 +1,42 @@ +import { TANSTACK_SOURCE_HOST } from "../shared/definition.ts"; + +export const TANSTACK_SOURCE_HOSTS = [TANSTACK_SOURCE_HOST] as const; +export type TanStackSourceHost = (typeof TANSTACK_SOURCE_HOSTS)[number]; + +export function tanStackSourceHost(host: string): TanStackSourceHost | null { + const normalized = host.trim().toLowerCase(); + return TANSTACK_SOURCE_HOSTS.find((candidate) => candidate === normalized) ?? null; +} + +const SEGMENT = /^[A-Za-z0-9_.-]+$/u; + +/** `owner/name` from the API spelling or the web spelling `@owner/name`, `.git` dropped. */ +export function tanStackSourceRepositoryPath(path: string): string | null { + const [owner, name, ...rest] = path + .trim() + .replace(/^\/+|\/+$/gu, "") + .replace(/\.git$/u, "") + .replace(/^@/u, "") + .split("/"); + return rest.length === 0 && + owner !== undefined && + name !== undefined && + [owner, name].every((segment) => SEGMENT.test(segment) && segment !== "." && segment !== "..") + ? `${owner}/${name}` + : null; +} + +/** Source serves git over HTTPS only, at `https:///@/.git`. */ +export function parseTanStackSourceRemote( + url: string, +): { readonly host: TanStackSourceHost; readonly repository: string } | null { + const parsed = URL.parse(url.trim()); + if (parsed === null || (parsed.protocol !== "https:" && parsed.protocol !== "http:")) return null; + const host = tanStackSourceHost(parsed.hostname); + if (host === null || !parsed.pathname.startsWith("/@")) return null; + const repository = tanStackSourceRepositoryPath(parsed.pathname); + return repository === null ? null : { host, repository }; +} + +export const webRepositoryUrl = (host: string, repository: string) => + `https://${host}/@${repository}`; diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts new file mode 100644 index 0000000000000..4d698fb881dfb --- /dev/null +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts @@ -0,0 +1,156 @@ +import { describe, expect, it } from "vite-plus/test"; + +import * as Json from "./tanStackSourceJson.ts"; + +const HOST = "source.tanstack.com"; +const run = (fields: Partial & { readonly name: string }) => ({ + view: "full", + status: "completed", + conclusion: "success", + startedAt: 1, + completedAt: 2, + summary: null, + ...fields, +}); + +describe("toChecks", () => { + // Shapes from `GET /check-runs?sha=` on TanStack/ai: Source CI jobs carry a job id, checks + // synced from GitHub a url and a source. + const job: Json.SourceCiJob = { + runId: "b524c952-431d-885f-255c-bf2fbf8addb2", + workflow: "pr", + key: "test (shard: 1)", + runUrl: `https://${HOST}/@TanStack/ai/ci/b524c952-431d-885f-255c-bf2fbf8addb2`, + }; + + it("names Source CI jobs by workflow, links their log, and keeps a re-run's newest result", () => { + const checks = Json.toChecks({ + runs: [ + run({ jobId: "old", name: "test (shard: 1)", conclusion: "failure", startedAt: 1 }), + // A job Source CI has not reported a run for yet still shows, under its own name. + run({ jobId: "unread", name: "lint", conclusion: "failure", startedAt: 0 }), + run({ jobId: "new", name: "test (shard: 1)", startedAt: 5, summary: "### Passed\nmore" }), + run({ + jobId: "", + name: "CodeRabbit", + status: "in_progress", + conclusion: null, + url: "https://coderabbit.ai", + source: "github", + }), + ], + jobs: new Map([ + ["old", job], + ["new", job], + ]), + required: new Set(["pr/test (shard: 1)"]), + }); + expect(checks).toEqual( + expect.arrayContaining([ + { + name: "pr/test (shard: 1)", + status: "success", + description: "Passed", + url: `${job.runUrl}?job=test+%28shard%3A+1%29`, + required: true, + }, + { name: "CodeRabbit", status: "pending", description: null, url: "https://coderabbit.ai" }, + { name: "lint", status: "failure", description: null, url: null }, + ]), + ); + expect(checks).toHaveLength(3); + expect(Json.checksStateOf(checks)).toBe("failing"); + expect(Json.parseCiJobUrl(checks.find((check) => check.required)!.url, HOST)).toEqual({ + runId: job.runId, + job: job.key, + }); + expect(Json.parseCiJobUrl("https://coderabbit.ai", HOST)).toBeNull(); + }); +}); + +describe("toReviewComment", () => { + it("anchors added and right-side lines on new, deleted and left-side lines on old", () => { + const draft = (position: Parameters[0]["position"]) => + Json.toReviewComment({ path: "a.ts", position, body: "x" }, "sha"); + expect(draft({ kind: "added", newLine: 4 })).toMatchObject({ side: "new", line: 4 }); + expect(draft({ kind: "deleted", oldLine: 3 })).toMatchObject({ side: "old", line: 3 }); + expect(draft({ kind: "context", oldLine: 3, newLine: 5, side: "left" })).toMatchObject({ + side: "old", + line: 3, + }); + expect( + Json.toReviewComment( + { + path: "a.ts", + startPosition: { kind: "added", newLine: 2 }, + position: { kind: "added", newLine: 4 }, + body: "x", + }, + "sha", + ), + ).toEqual({ path: "a.ts", side: "new", line: 4, startLine: 2, commitId: "sha", body: "x" }); + }); +}); + +describe("patchSections", () => { + it("splits a unified patch by the path each section changes", () => { + const patch = + "diff --git a/a.ts b/a.ts\n--- a/a.ts\n+++ b/a.ts\n@@ -1 +1 @@\n-a\n+b\n" + + "diff --git a/old.ts b/new.ts\nsimilarity index 100%\n"; + const sections = Json.patchSections(patch); + expect([...sections.keys()]).toEqual(["a.ts", "new.ts"]); + expect(sections.get("new.ts")).toBe("diff --git a/old.ts b/new.ts\nsimilarity index 100%\n"); + }); +}); + +describe("toActivity", () => { + it("tells conversation comments, line comments and reviews apart, and hides held ones", () => { + const activity = Json.toActivity({ + timeline: { + timeline: [ + { id: 1, comment: "hi", author: "alice", at: 1_000, moderation: "visible" }, + { id: 2, comment: null, author: "spam", at: 2_000, moderation: "quarantined" }, + { id: 3, comment: "LGTM", author: "bob", at: 3_000, review: "approved" }, + { id: 4, comment: "nit", author: "bob", at: 3_000, path: "a.ts", reviewId: 3 }, + ], + next: null, + }, + threads: [ + { + id: 4, + path: "a.ts", + side: "old", + line: 2, + outdated: false, + resolved: true, + comments: [{ id: 4, comment: "nit", author: "bob", at: 3_000 }], + }, + ], + commits: { + baseSha: null, + headSha: null, + mergeBaseSha: null, + available: true, + commitsTruncated: false, + commits: [{ sha: "abc", title: "fix", author: { name: "Bob", timestamp: 3 } }], + }, + host: HOST, + repository: "TanStack/ai", + number: 9, + }); + expect( + activity.comments.map((comment) => [comment.id, comment.kind, comment.reviewState]), + ).toEqual([ + ["1", "issue-comment", null], + ["3", "review", "approved"], + ["4", "review-comment", null], + ]); + expect(activity.comments[0]?.url).toBe(`https://${HOST}/@TanStack/ai/pull/9#comment-1`); + expect(activity.reviewThreads).toMatchObject([ + { id: "4", path: "a.ts", line: 2, side: "left", isResolved: true }, + ]); + expect(activity.commits).toEqual([ + { oid: "abc", messageHeadline: "fix", committedDate: "1970-01-01T00:00:03.000Z" }, + ]); + }); +}); diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts new file mode 100644 index 0000000000000..acf3c4158f95c --- /dev/null +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts @@ -0,0 +1,494 @@ +import { + type PullRequestActor, + type PullRequestCheck, + type PullRequestChecksState, + type PullRequestComment, + type PullRequestReviewCommentDraft, + type PullRequestReviewThread, + type PullRequestState, +} from "@t3tools/contracts"; +import { sortChecks } from "@t3tools/source-control-core/server/pullRequestChecks"; +import type { + ProviderChangeRequest, + ProviderChangeRequestActivity, + ProviderChangeRequestStack, +} from "@t3tools/source-control-core/server/PullRequestProvider"; +import * as DateTime from "effect/DateTime"; +import * as Schema from "effect/Schema"; + +/** Source sends times as epoch milliseconds. */ +const EpochMillis = Schema.Finite; +const Login = Schema.String; + +export const SourcePull = Schema.Struct({ + number: Schema.Int, + title: Schema.String, + state: Schema.Literals(["open", "closed", "merged"]), + draft: Schema.Boolean, + author: Schema.NullOr(Login), + labels: Schema.optional(Schema.Array(Schema.String)), + head: Schema.String, + createdAt: EpochMillis, +}); +export type SourcePull = typeof SourcePull.Type; + +export const SourcePulls = Schema.Struct({ + items: Schema.Array(SourcePull), + next: Schema.NullOr(Schema.String), +}); + +const AutoMerge = Schema.Struct({ method: Schema.optional(Schema.String) }); + +export const SourcePullDetail = Schema.Struct({ + ...SourcePull.fields, + body: Schema.NullOr(Schema.String), + base: Schema.String, + headRepo: Schema.NullOr(Schema.String), + headSha: Schema.NullOr(Schema.String), + baseSha: Schema.NullOr(Schema.String), + mergeCommitSha: Schema.NullOr(Schema.String), + mergedAt: Schema.NullOr(EpochMillis), + mergedBy: Schema.NullOr(Login), + mergeable: Schema.NullOr(Schema.Boolean), + changedFiles: Schema.NullOr(Schema.Int), + changedLines: Schema.optional(Schema.NullOr(Schema.Unknown)), + reviewRequests: Schema.optional(Schema.Array(Login)), + autoMerge: Schema.optional(Schema.NullOr(AutoMerge)), + locked: Schema.optional(Schema.Boolean), + htmlUrl: Schema.optional(Schema.String), +}); +export type SourcePullDetail = typeof SourcePullDetail.Type; + +/** `GET /pulls/{n}/checks`: the required checks of the base branch and whether it may merge. */ +export const SourceMergeChecks = Schema.Struct({ + headSha: Schema.optional(Schema.NullOr(Schema.String)), + checks: Schema.Array( + Schema.Struct({ + name: Schema.String, + state: Schema.String, + reason: Schema.optional(Schema.NullOr(Schema.String)), + }), + ), + upToDate: Schema.optional(Schema.NullOr(Schema.Boolean)), + mayMerge: Schema.Boolean, + refusal: Schema.optional(Schema.NullOr(Schema.String)), +}); +export type SourceMergeChecks = typeof SourceMergeChecks.Type; + +/** `GET /check-runs?sha=`: Source CI jobs (with a job id) and checks synced from GitHub (url). */ +export const SourceCheckRun = Schema.Struct({ + jobId: Schema.optional(Schema.String), + name: Schema.String, + view: Schema.optional(Schema.String), + status: Schema.String, + conclusion: Schema.NullOr(Schema.String), + startedAt: Schema.optional(Schema.NullOr(EpochMillis)), + completedAt: Schema.optional(Schema.NullOr(EpochMillis)), + summary: Schema.optional(Schema.NullOr(Schema.String)), + url: Schema.optional(Schema.NullOr(Schema.String)), + source: Schema.optional(Schema.NullOr(Schema.String)), +}); +export type SourceCheckRun = typeof SourceCheckRun.Type; +export const SourceCheckRuns = Schema.Array(SourceCheckRun); + +export const SourceCiRuns = Schema.Struct({ + items: Schema.Array( + Schema.Struct({ + id: Schema.String, + workflow: Schema.String, + headSha: Schema.String, + createdAt: EpochMillis, + htmlUrl: Schema.String, + }), + ), + next: Schema.NullOr(Schema.String), +}); +export type SourceCiRun = (typeof SourceCiRuns.Type)["items"][number]; + +export const SourceCiRunDetail = Schema.Struct({ + id: Schema.String, + jobs: Schema.Array( + Schema.Struct({ key: Schema.String, name: Schema.String, jobId: Schema.NullOr(Schema.String) }), + ), +}); + +/** The job of a run a check came from, which its log and re-run are addressed by. */ +export interface SourceCiJob { + readonly runId: string; + readonly workflow: string; + readonly key: string; + readonly runUrl: string; +} + +const TimelineEntry = Schema.Struct({ + id: Schema.Int, + comment: Schema.NullOr(Schema.String), + author: Schema.NullOr(Login), + at: EpochMillis, + updatedAt: Schema.optional(Schema.NullOr(EpochMillis)), + moderation: Schema.optional(Schema.String), + review: Schema.optional(Schema.NullOr(Schema.String)), + path: Schema.optional(Schema.NullOr(Schema.String)), + replyTo: Schema.optional(Schema.NullOr(Schema.Int)), + reviewId: Schema.optional(Schema.NullOr(Schema.Int)), +}); +type TimelineEntry = typeof TimelineEntry.Type; + +export const SourceTimeline = Schema.Struct({ + timeline: Schema.Array(TimelineEntry), + next: Schema.NullOr(Schema.String), +}); + +const ThreadComment = Schema.Struct({ + id: Schema.Int, + comment: Schema.NullOr(Schema.String), + author: Schema.NullOr(Login), + at: EpochMillis, + updatedAt: Schema.optional(Schema.NullOr(EpochMillis)), +}); + +export const SourceThreads = Schema.Array( + Schema.Struct({ + id: Schema.Int, + htmlUrl: Schema.optional(Schema.NullOr(Schema.String)), + path: Schema.String, + side: Schema.Literals(["old", "new"]), + line: Schema.NullOr(Schema.Int), + outdated: Schema.Boolean, + resolved: Schema.Boolean, + comments: Schema.Array(ThreadComment), + }), +); + +const CommitDetails = { + baseSha: Schema.NullOr(Schema.String), + headSha: Schema.NullOr(Schema.String), + mergeBaseSha: Schema.NullOr(Schema.String), + available: Schema.Boolean, + unavailable: Schema.optional(Schema.NullOr(Schema.Unknown)), + tooLarge: Schema.optional(Schema.NullOr(Schema.Unknown)), +}; + +export const SourceCommits = Schema.Struct({ + ...CommitDetails, + commitsTruncated: Schema.NullOr(Schema.Boolean), + commits: Schema.NullOr( + Schema.Array( + Schema.Struct({ + sha: Schema.String, + title: Schema.String, + author: Schema.Struct({ name: Schema.String, timestamp: Schema.Finite }), + }), + ), + ), +}); + +export const SourceFiles = Schema.Struct({ + ...CommitDetails, + truncated: Schema.NullOr(Schema.Boolean), + files: Schema.NullOr( + Schema.Array( + Schema.Struct({ + path: Schema.String, + oldPath: Schema.optional(Schema.NullOr(Schema.String)), + status: Schema.String, + binary: Schema.optional(Schema.Boolean), + additions: Schema.optional(Schema.Int), + deletions: Schema.optional(Schema.Int), + }), + ), + ), +}); +export type SourceFiles = typeof SourceFiles.Type; + +export const SourceDiff = Schema.Struct({ + ...CommitDetails, + truncated: Schema.NullOr(Schema.Boolean), + patch: Schema.NullOr(Schema.String), +}); + +export const SourceContents = Schema.Struct({ + binary: Schema.Boolean, + truncated: Schema.Boolean, + content: Schema.NullOr(Schema.String), +}); + +export const SourceStack = Schema.Struct({ + members: Schema.Array( + Schema.Struct({ + number: Schema.Int, + title: Schema.String, + headRef: Schema.String, + baseRef: Schema.String, + draft: Schema.Boolean, + }), + ), +}); +export type SourceStack = typeof SourceStack.Type; + +export const SourceLabels = Schema.Array( + Schema.Struct({ + name: Schema.String, + color: Schema.NullOr(Schema.String), + description: Schema.optional(Schema.NullOr(Schema.String)), + }), +); + +export const SourceUser = Schema.Struct({ username: Schema.String }); + +export const iso = (millis: number) => DateTime.formatIso(DateTime.makeUnsafe(millis)); + +export const pullUrl = (host: string, repository: string, number: number) => + `https://${host}/@${repository}/pull/${number}`; + +/** A GitHub-synced pull request from a fork names its head only by its pull ref. */ +export const headBranchName = (head: string) => head.replace(/^refs\/heads\//u, ""); + +export function toActor(login: string | null, host: string): PullRequestActor | null { + if (login === null || login.trim() === "") return null; + return { + login, + name: null, + avatarUrl: `https://${host}/avatars/${encodeURIComponent(login)}`, + ...(login.endsWith("[bot]") ? { isBot: true } : {}), + }; +} + +const toLabels = (labels: ReadonlyArray | undefined) => + (labels ?? []).map((name) => ({ name, color: null })); + +interface RepositoryOnHost { + readonly repository: string; + readonly host: string; +} + +/** List rows name no base; the caller fills it from the detail read or the stack. */ +export function toChangeRequest( + pull: SourcePull & { + readonly base?: string | undefined; + readonly reviewRequests?: ReadonlyArray | undefined; + }, + target: RepositoryOnHost, +): ProviderChangeRequest { + const createdAt = iso(pull.createdAt); + return { + number: pull.number, + title: pull.title, + url: pullUrl(target.host, target.repository, pull.number), + author: toActor(pull.author, target.host), + headBranch: headBranchName(pull.head), + baseBranch: pull.base ?? "", + state: pull.state, + isDraft: pull.draft, + mergeability: "unknown", + additions: 0, + deletions: 0, + createdAt, + // Source reports no update time; creation is the latest it can vouch for. + updatedAt: createdAt, + reviewRequestLogins: pull.reviewRequests ?? [], + labels: toLabels(pull.labels), + }; +} + +const COMPLETED_STATUS: Readonly> = { + success: "success", + neutral: "neutral", + skipped: "skipped", + cancelled: "cancelled", + action_required: "action-required", + stale: "neutral", +}; + +function checkStatus(run: SourceCheckRun): PullRequestCheck["status"] { + if (run.status !== "completed") return run.status === "waiting" ? "action-required" : "pending"; + return COMPLETED_STATUS[run.conclusion ?? ""] ?? "failure"; +} + +/** A Source CI job's page: its run, scrolled to the job. Also how its log is found again. */ +const ciJobUrl = (job: SourceCiJob) => `${job.runUrl}?${new URLSearchParams({ job: job.key })}`; + +/** The run and job a Source CI check's URL names. */ +export function parseCiJobUrl( + url: string | null, + host: string, +): { readonly runId: string; readonly job: string } | null { + const parsed = url === null ? null : URL.parse(url); + if (parsed === null || parsed.hostname !== host) return null; + const runId = /^\/@[^/]+\/[^/]+\/ci\/([0-9a-f-]{8,})\/?$/iu.exec(parsed.pathname)?.[1]; + const job = parsed.searchParams.get("job"); + return runId === undefined || job === null || job === "" ? null : { runId, job }; +} + +/** + * Source lists every run of a commit's checks, so a re-run arrives beside the run it replaced. + * The newest run of a name is the check's state; an older failure is history. + */ +export function toChecks(input: { + readonly runs: ReadonlyArray; + readonly jobs: ReadonlyMap; + readonly required: ReadonlySet; +}): ReadonlyArray { + const newest = new Map(); + for (const run of input.runs) { + if (run.view === "superseded") continue; + const job = run.jobId ? input.jobs.get(run.jobId) : undefined; + const name = job === undefined ? run.name : `${job.workflow}/${run.name}`; + const at = run.startedAt ?? run.completedAt ?? 0; + const held = newest.get(name); + if (held === undefined || at > held.at) newest.set(name, { run, at }); + } + return sortChecks( + [...newest.entries()].map(([name, { run }]) => { + const job = run.jobId ? input.jobs.get(run.jobId) : undefined; + return { + name, + status: checkStatus(run), + description: run.summary?.split("\n", 1)[0]?.replace(/^#+\s*/u, "") || null, + url: job === undefined ? (run.url ?? null) : ciJobUrl(job), + ...(input.required.has(name) ? { required: true } : {}), + }; + }), + ); +} + +export function checksStateOf( + checks: ReadonlyArray, +): PullRequestChecksState | null { + const statuses = new Set(checks.map((check) => check.status)); + if (statuses.has("failure") || statuses.has("cancelled")) return "failing"; + if (statuses.has("pending") || statuses.has("action-required")) return "pending"; + return statuses.has("success") ? "passing" : null; +} + +const REVIEW_STATES: Readonly> = { + approved: "approved", + changes_requested: "changes_requested", + commented: "commented", +}; + +const visible = (entry: { readonly moderation?: string | undefined }) => + entry.moderation === undefined || entry.moderation === "visible"; + +export function toActivity(input: { + readonly timeline: typeof SourceTimeline.Type; + readonly threads: typeof SourceThreads.Type; + readonly commits: typeof SourceCommits.Type; + readonly host: string; + readonly repository: string; + readonly number: number; +}): ProviderChangeRequestActivity { + const { host } = input; + const page = pullUrl(host, input.repository, input.number); + const entries = input.timeline.timeline.filter(visible); + const comments: Array = entries.map((entry: TimelineEntry) => ({ + id: String(entry.id), + kind: + entry.review != null + ? ("review" as const) + : entry.path != null + ? ("review-comment" as const) + : ("issue-comment" as const), + author: toActor(entry.author, host), + body: entry.comment ?? "", + createdAt: iso(entry.at), + ...(entry.updatedAt != null && entry.updatedAt > entry.at + ? { editedAt: iso(entry.updatedAt) } + : {}), + url: `${page}#comment-${entry.id}`, + path: entry.path ?? null, + reviewState: entry.review == null ? null : (REVIEW_STATES[entry.review] ?? entry.review), + })); + const reviewThreads = input.threads.flatMap((thread): ReadonlyArray => { + if (thread.path.trim() === "" || thread.comments.length === 0) return []; + return [ + { + id: String(thread.id), + path: thread.path, + line: thread.line !== null && thread.line > 0 ? thread.line : null, + side: thread.side === "old" ? "left" : "right", + isResolved: thread.resolved, + isOutdated: thread.outdated, + comments: thread.comments.map((comment) => ({ + id: String(comment.id), + author: toActor(comment.author, host), + body: comment.comment ?? "", + createdAt: iso(comment.at), + ...(comment.updatedAt != null && comment.updatedAt > comment.at + ? { editedAt: iso(comment.updatedAt) } + : {}), + url: `${page}#comment-${comment.id}`, + })), + }, + ]; + }); + return { + comments, + commentCount: comments.length, + commentsTruncated: input.timeline.next !== null, + reviewThreads, + commits: (input.commits.commits ?? []).map((commit) => ({ + oid: commit.sha, + messageHeadline: commit.title, + committedDate: iso(commit.author.timestamp * 1_000), + })), + }; +} + +export function toStack( + stack: SourceStack, + target: RepositoryOnHost, + states: ReadonlyMap, +): ProviderChangeRequestStack | null { + const bottom = stack.members[0]; + if (bottom === undefined || stack.members.length < 2) return null; + return { + id: `${target.repository}#${bottom.number}`, + number: bottom.number, + url: pullUrl(target.host, target.repository, bottom.number), + base: bottom.baseRef, + layers: stack.members.map((member) => ({ + number: member.number, + title: member.title, + headBranch: headBranchName(member.headRef), + state: states.get(member.number) ?? "open", + isDraft: member.draft, + })), + }; +} + +/** The line comment a review draft names, as Source's review takes it. */ +export function toReviewComment(draft: PullRequestReviewCommentDraft, commitId: string) { + const line = (position: PullRequestReviewCommentDraft["position"]) => + position.kind === "added" + ? { side: "new" as const, line: position.newLine } + : position.kind === "deleted" + ? { side: "old" as const, line: position.oldLine } + : position.side === "left" + ? { side: "old" as const, line: position.oldLine } + : { side: "new" as const, line: position.newLine }; + const end = line(draft.position); + const start = draft.startPosition === undefined ? undefined : line(draft.startPosition); + return { + path: draft.path, + side: end.side, + line: end.line, + ...(start !== undefined && start.side === end.side && start.line < end.line + ? { startLine: start.line } + : {}), + commitId, + body: draft.body, + }; +} + +/** The sections of a unified patch, by the path each one changes. */ +export function patchSections(patch: string): ReadonlyMap { + const sections = new Map(); + const starts = [...patch.matchAll(/^diff --git a\/(.*) b\/(.*)$/gmu)]; + for (const [index, match] of starts.entries()) { + const end = starts[index + 1]?.index ?? patch.length; + const section = patch.slice(match.index, end); + sections.set(match[2]!, section.endsWith("\n") ? section : `${section}\n`); + } + return sections; +} diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceListing.test.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceListing.test.ts new file mode 100644 index 0000000000000..88d7695f0c82b --- /dev/null +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceListing.test.ts @@ -0,0 +1,110 @@ +import { assert, describe, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; + +import { decodeCursor, encodeCursor, readMerged } from "./tanStackSourceListing.ts"; + +type Row = { readonly createdAt: number; readonly number: number }; +const row = (createdAt: number): Row => ({ createdAt, number: createdAt }); + +/** Source pages by state, each keyed by the cursor that reads it ("" for the first). */ +function source( + pages: Readonly>>>, +) { + const reads: Array = []; + return { + reads, + readPage: (state: string, page: string | null) => { + reads.push(`${state}:${page ?? ""}`); + const [items, next] = pages[state]![page ?? ""]!; + return Effect.succeed({ items, next }); + }, + }; +} + +describe("readMerged", () => { + it.effect("holds back a row until every state with more pages is read past it", () => { + const { readPage, reads } = source({ + open: { "": [[row(100)], "o2"], o2: [[row(90)], null] }, + closed: { "": [[row(40)], null] }, + }); + return Effect.gen(function* () { + const list = (cursor: string | undefined) => + readMerged({ states: ["open", "closed"], cursor, limit: 10, maxPages: 1, readPage }); + const first = yield* list(undefined); + assert.deepStrictEqual( + first.items.map((item) => item.createdAt), + [100], + ); + const second = yield* list(first.next!); + assert.deepStrictEqual( + second.items.map((item) => item.createdAt), + [90, 40], + ); + assert.isNull(second.next); + assert.deepStrictEqual(reads, ["open:", "closed:", "open:o2", "closed:"]); + }); + }); + + it.effect("moves past rows a filter drops, so the scan budget never pins it in place", () => { + const { readPage } = source({ + closed: { + "": [[row(50), row(49)], "c2"], + c2: [[row(48)], "c3"], + c3: [[row(47)], null], + }, + }); + return Effect.gen(function* () { + const list = (cursor: string | undefined) => + readMerged({ + states: ["closed"], + cursor, + limit: 1, + maxPages: 1, + readPage, + keep: (item) => item.createdAt === 47, + }); + let page = yield* list(undefined); + const seen: Array = []; + for (let calls = 0; calls < 5 && page.next !== null; calls++) { + seen.push(...page.items.map((item) => item.createdAt)); + page = yield* list(page.next); + } + seen.push(...page.items.map((item) => item.createdAt)); + assert.deepStrictEqual(seen, [47]); + assert.isNull(page.next); + }); + }); + + it.effect("hands over a row seen in two states once", () => { + const { readPage } = source({ + open: { "": [[row(90), row(80)], null] }, + closed: { "": [[row(90)], null] }, + }); + return Effect.gen(function* () { + const page = yield* readMerged({ + states: ["open", "closed"], + cursor: undefined, + limit: 10, + maxPages: 1, + readPage, + }); + assert.deepStrictEqual( + page.items.map((item) => item.number), + [90, 80], + ); + }); + }); + + it("writes cursors the pull request service accepts, and reads them back", () => { + // `resumeAfter`'s alphabet in apps/server PullRequestService's LIST_CURSOR_PATTERN. + const allowed = /^[\w.:~+-]{1,128}$/u; + for (const cursor of [ + { after: { createdAt: 1795239489187, number: 2221 }, pages: { open: "2047", closed: null } }, + { after: null, pages: { open: "", closed: "a/b=c?" } }, + ]) { + const written = encodeCursor(cursor); + assert.match(written, allowed); + assert.deepStrictEqual(decodeCursor(written), cursor); + } + }); +}); diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceListing.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceListing.ts new file mode 100644 index 0000000000000..4306e87d8a3e4 --- /dev/null +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceListing.ts @@ -0,0 +1,146 @@ +import * as Effect from "effect/Effect"; +import * as Base64Url from "effect/encoding/Base64Url"; +import * as Result from "effect/Result"; + +/** A row of a Source listing, which comes newest first by creation within one state. */ +export interface ListedRow { + readonly createdAt: number; + readonly number: number; +} + +/** + * Where a listing carries on: the last row handed over, and per state the Source page to read + * from next. A state's page is re-read from where its first undelivered row was, so nothing + * between pages is skipped; `""` is the first page and `null` means the state has nothing more. + */ +const FIRST_PAGE = ""; + +interface ListCursor { + readonly after: { readonly createdAt: number; readonly number: number } | null; + readonly pages: Readonly>; +} + +/** + * Written in the alphabet pull request list cursors allow (`[\w.:~+-]`, which the service checks) + * as `.` or `_`, then `~:` per state: `-` for ended, `0` for the + * first page, else `p` and the Source page token in base64url. + */ +export function encodeCursor(cursor: ListCursor): string { + const after = cursor.after === null ? "_" : `${cursor.after.createdAt}.${cursor.after.number}`; + const pages = Object.entries(cursor.pages).map( + ([state, page]) => + `~${state}:${page === null ? "-" : page === FIRST_PAGE ? "0" : `p${Base64Url.encode(page)}`}`, + ); + return `${after}${pages.join("")}`; +} + +export function decodeCursor(raw: string): ListCursor | null { + const [head, ...states] = raw.split("~"); + const position = /^(\d+)\.(\d+)$/u.exec(head ?? ""); + if (head !== "_" && position === null) return null; + const pages: Record = {}; + for (const entry of states) { + const match = /^([a-z]+):(-|0|p[\w-]*)$/u.exec(entry); + if (match === null) return null; + const value = match[2]!; + if (value === "-") pages[match[1]!] = null; + else if (value === "0") pages[match[1]!] = FIRST_PAGE; + else { + const decoded = Base64Url.decodeString(value.slice(1)); + if (Result.isFailure(decoded)) return null; + pages[match[1]!] = decoded.success; + } + } + return { + after: + position === null ? null : { createdAt: Number(position[1]), number: Number(position[2]) }, + pages, + }; +} + +const newer = (a: ListedRow, b: ListedRow) => + a.createdAt > b.createdAt || (a.createdAt === b.createdAt && a.number > b.number); + +/** + * Reads `states` (Source lists open and closed apart) and merges them newest first. A row is + * handed over only once every state that has more pages has been read past it, so a later page + * can never hold a row that belonged earlier. The cursor survives rows above it closing. + */ +export const readMerged = Effect.fn("TanStackSourceListing.readMerged")(function* < + A extends ListedRow, + E, +>(input: { + readonly states: ReadonlyArray; + readonly cursor: string | undefined; + readonly limit: number; + readonly maxPages: number; + readonly readPage: ( + state: string, + page: string | null, + ) => Effect.Effect<{ readonly items: ReadonlyArray; readonly next: string | null }, E>; + /** Rows a host-side filter could not exclude. Dropped rows still move the cursor. */ + readonly keep?: (row: A) => boolean; +}) { + const resumed: ListCursor | null = input.cursor === undefined ? null : decodeCursor(input.cursor); + const after = resumed?.after ?? null; + const isNew = (row: A) => after === null || newer(after, row); + const reads = yield* Effect.forEach( + input.states.filter((state) => resumed === null || resumed.pages[state] !== null), + Effect.fnUntraced(function* (state) { + let page: string = resumed?.pages[state] ?? FIRST_PAGE; + const rows: Array<{ readonly row: A; readonly page: string }> = []; + let oldest: A | undefined; + let pages = 0; + let next: string | null = null; + do { + const read: { readonly items: ReadonlyArray; readonly next: string | null } = + yield* input.readPage(state, page === FIRST_PAGE ? null : page); + pages += 1; + for (const row of read.items) if (isNew(row)) rows.push({ row, page }); + oldest = read.items.at(-1) ?? oldest; + next = read.items.length === 0 ? null : read.next; + if (next !== null) page = next; + } while (next !== null && rows.length <= input.limit && pages < input.maxPages); + return { state, rows, next, oldest }; + }), + { concurrency: "unbounded" }, + ); + // Rows older than the oldest one read from a state that has more may yet be beaten by its next + // page, so they wait for a later call. + const unfinished = reads.filter((read) => read.next !== null && read.oldest !== undefined); + const cutoff = unfinished.reduce( + (latest, read) => (latest === undefined || newer(read.oldest!, latest) ? read.oldest : latest), + undefined, + ); + const seen = new Set(); + const merged = reads + .flatMap((read) => read.rows.map((entry) => ({ ...entry, state: read.state }))) + .filter((entry) => cutoff === undefined || !newer(cutoff, entry.row)) + .toSorted((a, b) => (newer(a.row, b.row) ? -1 : newer(b.row, a.row) ? 1 : 0)) + // A row that changed state between the reads of two states is in both; it is one row. + .filter((entry) => !seen.has(entry.row.number) && seen.add(entry.row.number) !== undefined); + const keep = input.keep ?? (() => true); + const delivered: Array<(typeof merged)[number]> = []; + let consumed = 0; + for (const entry of merged) { + if (delivered.length >= input.limit) break; + consumed += 1; + if (keep(entry.row)) delivered.push(entry); + } + const last = merged[consumed - 1]?.row; + const pages: Record = { ...resumed?.pages }; + for (const read of reads) { + const pending = read.rows.find(({ row }) => last === undefined || newer(last, row)); + pages[read.state] = pending !== undefined ? pending.page : read.next; + } + const more = Object.values(pages).some((page) => page !== null) || consumed < merged.length; + return { + items: delivered.map((entry) => entry.row), + next: more + ? encodeCursor({ + after: last === undefined ? after : { createdAt: last.createdAt, number: last.number }, + pages, + }) + : null, + }; +}); diff --git a/packages/source-control-tanstack-source/src/shared/definition.test.ts b/packages/source-control-tanstack-source/src/shared/definition.test.ts new file mode 100644 index 0000000000000..e3ce5c867fa5c --- /dev/null +++ b/packages/source-control-tanstack-source/src/shared/definition.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { definition, parsePullRequestUrl } from "./definition.ts"; + +describe("TanStack Source definition", () => { + it("reads pull requests and commits only on its own host", () => { + expect( + definition.parseCommitUrl?.( + new URL( + "https://source.tanstack.com/@TanStack/router/commit/cebaf84a4fe3776f27359ef1d978f0650d6b0e51", + ), + ), + ).toMatchObject({ repository: "tanstack/router" }); + for (const url of [ + "https://github.com/TanStack/router/pull/1", + "https://source.tanstack.com.evil.test/@TanStack/router/pull/1", + "https://source.tanstack.com/@TanStack/router/pull/0", + ]) + expect(parsePullRequestUrl(url), url).toBeNull(); + // Some clients send the owner's `@` percent-encoded. + expect( + definition.parseIssueUrl?.(new URL("https://source.tanstack.com/%40TanStack/ai/issues/12")), + ).toEqual({ host: "source.tanstack.com", scope: "tanstack/ai", key: "12" }); + }); + + it("builds links with the owner's @ and reads src's checkout command", () => { + expect( + definition.changeRequestUrl({ + host: "source.tanstack.com", + repository: "TanStack/router", + number: 7, + }), + ).toBe("https://source.tanstack.com/@TanStack/router/pull/7"); + expect(definition.checkoutCommandArgument("src pr checkout 7")).toBe("7"); + expect(definition.checkoutCommandArgument("gh pr checkout 7")).toBeNull(); + }); +}); diff --git a/packages/source-control-tanstack-source/src/shared/definition.ts b/packages/source-control-tanstack-source/src/shared/definition.ts new file mode 100644 index 0000000000000..1aee00c968dc6 --- /dev/null +++ b/packages/source-control-tanstack-source/src/shared/definition.ts @@ -0,0 +1,142 @@ +import { makeProviderSettingsSchema, SourceControlProviderKind } from "@t3tools/contracts"; +import { + buildCommitUrl, + changeRequestUrlBelow, + defineSourceControl, + hostCredentialSettingsFields, + isChangeRequestInProjectRepository, + isChangeRequestOnProjectHost, + parseChangeRequestPath, + parseCommitPath, + parseIssuePath, + projectChangeRequestHost, + repositoryUrlFromPagePath, +} from "@t3tools/source-control-core/shared/definition"; + +import { icon } from "./icon.ts"; + +export const TANSTACK_SOURCE_HOST = "source.tanstack.com"; + +/** Every web page and clone URL names the owner with a leading `@`, as `/@TanStack/router`. */ +const CHANGE_REQUEST_PATH = /^\/(?:@|%40)?([^/@%]+\/[^/]+)\/pull\/(\d+)(?:\/|$)/u; +const ISSUE_PATH = /^\/(?:@|%40)?([^/@%]+\/[^/]+)\/issues\/(\d+)(?:\/|$)/u; +const COMMIT_PATH = /^\/(?:@|%40)?([^/@%]+\/[^/]+)\/commit\/([0-9a-f]+)\/?$/iu; +const REPOSITORY_PAGE_PATH = /^\/(@[^/@]+\/[^/]+)\/(?:tree|blob)\/[^/]/u; +const CHECKOUT_COMMAND = /^src\s+pr\s+checkout\s+(.+)$/iu; + +const KIND = SourceControlProviderKind.make("tanstack-source"); + +const isTanStackSourceHost = (hostname: string) => hostname.toLowerCase() === TANSTACK_SOURCE_HOST; + +function parseChangeRequestUrl(url: URL) { + const link = isTanStackSourceHost(url.hostname) + ? parseChangeRequestPath(url, CHANGE_REQUEST_PATH) + : null; + return link === null + ? null + : { ...link, repositoryUrl: `${url.origin}/@${CHANGE_REQUEST_PATH.exec(url.pathname)![1]}` }; +} + +/** Keys drop the owner's `@`, so a project's repository is `owner/name` as the API names it. */ +function repositoryKeyFromRemote(key: string): string | null { + // Remote parsing spells the `@` percent-encoded. + const match = /^source\.tanstack\.com\/(?:@|%40)([^/@%]+\/[^/]+)$/u.exec(key); + return match?.[1] === undefined + ? null + : `${TANSTACK_SOURCE_HOST}/${match[1].replace(/\.git$/u, "")}`; +} + +export const settings = makeProviderSettingsSchema(hostCredentialSettingsFields); +export type TanStackSourceSettings = typeof settings.Type; + +export const definition = defineSourceControl({ + kind: KIND, + label: "TanStack Source", + pickerLabel: "TanStack Source", + icon, + searchKeywords: ["tanstack", "src"], + credentials: { + cliName: "src", + cliLabel: "TanStack Source CLI", + loginCommand: "src auth login --web", + tokenEnvVar: "SRC_TOKEN", + tokenAccess: "read and write access to repositories, issues and pull requests", + newTokenUrl: (host) => `https://${host}/settings/tokens`, + }, + changeRequest: { + shortLabel: "PR", + shortLabelWithArticle: "a PR", + singular: "pull request", + plural: "pull requests", + }, + repositoryPathHint: "owner/repo", + publicHost: TANSTACK_SOURCE_HOST, + publishDescription: TANSTACK_SOURCE_HOST, + publishHost: () => TANSTACK_SOURCE_HOST, + newRepositoryOwner: (account) => ({ owner: account }), + defaultCloneTransport: "https", + changeRequestUrl: ({ host, repository, number, webUrl }) => + !Number.isSafeInteger(number) || number < 1 + ? null + : webUrl + ? changeRequestUrlBelow(webUrl, `pull/${number}`) + : `https://${host}/@${repository.replace(/^@/u, "")}/pull/${number}`, + parseChangeRequestUrl, + commitUrl: (input) => + buildCommitUrl( + input.webUrl + ? input + : { ...input, webUrl: `https://${input.host}/@${input.repository.replace(/^@/u, "")}` }, + "commit", + ), + parseIssueUrl: (url) => + isTanStackSourceHost(url.hostname) ? parseIssuePath(url, ISSUE_PATH) : null, + parseCommitUrl: (url) => + isTanStackSourceHost(url.hostname) ? parseCommitPath(url, COMMIT_PATH) : null, + repositoryUrlFromPage: (url) => + isTanStackSourceHost(url.hostname) + ? repositoryUrlFromPagePath(url, REPOSITORY_PAGE_PATH) + : null, + changeRequestUrlFromReferenceAutolink: () => null, + changeRequestActions: new Set([ + "merge", + "ready", + "draft", + "close", + "reopen", + "update-branch", + "enable-auto-merge", + "disable-auto-merge", + "revert", + ] as const), + checkoutCommand: ({ number }) => `src pr checkout ${number}`, + changeRequestCloseCommand: /\bsrc\s+pr\s+(?:merge|close)\b/u, + changeRequestCreateCommand: /\bsrc\s+pr\s+(?:create|new)\b/u, + authorProfileUrl: (login) => + login.endsWith("[bot]") + ? null + : `https://${TANSTACK_SOURCE_HOST}/@${encodeURIComponent(login)}`, + reviewSummaryRequired: () => false, + checkoutCommandArgument: (input) => CHECKOUT_COMMAND.exec(input)?.[1]?.trim() ?? null, + isChangeRequestReference: (url) => parsePullRequestUrl(url) !== null, + checkoutChangeRequestHost: () => null, + changeRequestHeadRef: (number) => `refs/pull/${number}/head`, + repositoryKeyFromRemote, + recognizeRemote: ({ hostname }) => + isTanStackSourceHost(hostname) + ? { kind: KIND, name: "TanStack Source", baseUrl: `https://${TANSTACK_SOURCE_HOST}` } + : null, + isChangeRequestInRepository: (identity, link) => + isChangeRequestInProjectRepository(projectChangeRequestHost(identity, KIND), identity, link), + canReadChangeRequestOnHost: (identity, link) => + isChangeRequestOnProjectHost(projectChangeRequestHost(identity, KIND), identity, link), + settings, +}); + +export function parsePullRequestUrl(value: string) { + try { + return parseChangeRequestUrl(new URL(value)); + } catch { + return null; + } +} diff --git a/packages/source-control-tanstack-source/src/shared/icon.ts b/packages/source-control-tanstack-source/src/shared/icon.ts new file mode 100644 index 0000000000000..b497142e8b91b --- /dev/null +++ b/packages/source-control-tanstack-source/src/shared/icon.ts @@ -0,0 +1,12 @@ +import type { SourceControlIcon } from "@t3tools/source-control-core/shared/definition"; + +/** The TanStack Source favicon, drawn in the text colour as the site draws it per theme. */ +export const icon: SourceControlIcon = { + viewBox: "-9.9 0 83.84 83.84", + paths: [ + { + d: "M32.02,0c23.15,0,32.02,14.33,32.02,41.92s-8.87,41.92-32.02,41.92S0,69.53,0,41.92C0,14.33,8.87,0,32.02,0ZM42.61,61.08c-3.01,0-4.65.82-5.97,1.48-1.14.57-2.03,1.02-4.01,1.02s-2.87-.45-4.01-1.02c-1.32-.66-2.96-1.48-5.97-1.48s-4.65.82-5.97,1.48c-1.14.57-2.03,1.02-4.01,1.02v4.37c3.01,0,4.65-.82,5.97-1.48,1.14-.57,2.03-1.02,4.01-1.02s2.87.45,4.01,1.02c1.32.66,2.96,1.48,5.97,1.48s4.65-.82,5.97-1.48c1.14-.57,2.03-1.02,4.01-1.02s2.87.45,4.01,1.02c1.32.66,2.96,1.48,5.97,1.48v-4.37c-1.97,0-2.87-.45-4.01-1.02-1.32-.66-2.96-1.48-5.97-1.48ZM44.04,17.29c2.27-2.05,0-5.76-2.84-4.64-1.57.63-3.05,1.53-4.37,2.72-2.06,1.87-3.45,4.22-4.2,6.78-.75-2.56-2.14-4.91-4.2-6.78-1.32-1.18-2.8-2.09-4.37-2.72-2.84-1.12-5.11,2.59-2.84,4.64l8.33,7.52c-2.72-1.84-6-2.93-9.54-2.93-1.93,0-3.78.31-5.52.91-2.92.99-2.11,5.35.96,5.35h11.62c-2.56.49-4.99,1.63-7.03,3.45-1.32,1.18-2.36,2.56-3.14,4.07-1.41,2.71,2.05,5.34,4.32,3.31l9.38-8.45-.7,23.25c0,.28-.16.55-.37.78-.3-.13-.58-.27-.9-.43-1.32-.66-2.96-1.48-5.97-1.48s-4.65.82-5.97,1.48c-1.14.57-2.03,1.02-4.01,1.02v4.37c3.01,0,4.65-.82,5.97-1.48,1.14-.57,2.03-1.02,4.01-1.02s2.87.45,4.01,1.02c1.32.66,2.96,1.48,5.97,1.48s4.65-.82,5.97-1.48c1.14-.57,2.03-1.02,4.01-1.02s2.87.45,4.01,1.02c1.32.66,2.96,1.48,5.97,1.48v-4.37c-1.97,0-2.87-.45-4.01-1.02v-.02c-1.32-.66-2.96-1.48-5.97-1.48s-4.65.82-5.97,1.48c-.34.16-.66.33-.99.46-.25-.22-.4-.51-.42-.81l-.7-23.37,9.51,8.58c2.27,2.05,5.73-.58,4.32-3.31-.78-1.5-1.82-2.89-3.14-4.07-2.03-1.84-4.46-2.96-7.03-3.45h11.62c3.08,0,3.87-4.35.96-5.35-1.73-.58-3.59-.91-5.52-.91-3.53,0-6.8,1.09-9.54,2.93l8.33-7.52Z", + fill: "currentColor", + }, + ], +}; diff --git a/packages/source-control-tanstack-source/tsconfig.json b/packages/source-control-tanstack-source/tsconfig.json new file mode 100644 index 0000000000000..374bac55202dd --- /dev/null +++ b/packages/source-control-tanstack-source/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "types": ["node"] + }, + "include": ["src"] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 33b1c3341677e..62cbee3b4d8f8 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -932,6 +932,9 @@ importers: '@t3tools/source-control-gitlab': specifier: workspace:* version: link:../../packages/source-control-gitlab + '@t3tools/source-control-tanstack-source': + specifier: workspace:* + version: link:../../packages/source-control-tanstack-source character-entities: specifier: 2.0.2 version: 2.0.2 @@ -2365,6 +2368,9 @@ importers: '@t3tools/source-control-gitlab': specifier: workspace:* version: link:../source-control-gitlab + '@t3tools/source-control-tanstack-source': + specifier: workspace:* + version: link:../source-control-tanstack-source packages/source-control-forgejo: dependencies: @@ -2502,6 +2508,34 @@ importers: specifier: 1.4.0 version: 1.4.0(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + packages/source-control-tanstack-source: + dependencies: + '@t3tools/contracts': + specifier: workspace:* + version: link:../contracts + '@t3tools/shared': + specifier: workspace:* + version: link:../shared + '@t3tools/source-control-core': + specifier: workspace:* + version: link:../source-control-core + effect: + specifier: 4.1.5 + version: 4.1.5 + devDependencies: + '@effect/vitest': + specifier: 4.1.5 + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + '@t3tools/source-control-testing': + specifier: workspace:* + version: link:../source-control-testing + '@types/node': + specifier: 24.12.4 + version: 24.12.4 + vite-plus: + specifier: 1.4.0 + version: 1.4.0(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + packages/source-control-testing: dependencies: '@effect/platform-node': diff --git a/scripts/release-smoke.ts b/scripts/release-smoke.ts index b564001c19290..3c58be4cbabbf 100644 --- a/scripts/release-smoke.ts +++ b/scripts/release-smoke.ts @@ -53,6 +53,7 @@ const workspaceFiles = [ "packages/source-control-gitcafe/package.json", "packages/source-control-github/package.json", "packages/source-control-gitlab/package.json", + "packages/source-control-tanstack-source/package.json", "packages/source-control-testing/package.json", "packages/effect-acp/package.json", "packages/effect-codex-app-server/package.json", From 2c01259fb4f64381998b76950fc8960896090507 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 01:01:25 -0800 Subject: [PATCH 06/39] perf(server): remote status polls read HEAD, upstream and remotes once (#40162) --- apps/server/src/vcs/GitVcsDriverCore.ts | 69 ++++++++++++++++--------- 1 file changed, 45 insertions(+), 24 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 66ab23e9c534e..3691a03687bf0 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -1968,25 +1968,31 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* Effect.orElseSucceed(() => null), ); + // Returns the upstream remote name it read, or undefined when it did not read one. const refreshStatusUpstreamIfStale = Effect.fn("refreshStatusUpstreamIfStale")(function* ( cwd: string, + knownHeadRef?: string, ) { - if (Duration.isZero(yield* automaticFetchInterval)) return; - const headRef = yield* runGitStdout( - "GitVcsDriver.refreshStatusUpstreamIfStale.headRef", - cwd, - ["symbolic-ref", "--quiet", "HEAD"], - true, - ).pipe(Effect.map((stdout) => stdout.trim())); - if (headRef.length === 0) return; - const remoteName = yield* runGitStdout( + if (Duration.isZero(yield* automaticFetchInterval)) return undefined; + const headRef = + knownHeadRef ?? + (yield* runGitStdout( + "GitVcsDriver.refreshStatusUpstreamIfStale.headRef", + cwd, + ["symbolic-ref", "--quiet", "HEAD"], + true, + ).pipe(Effect.map((stdout) => stdout.trim()))); + if (headRef.length === 0) return undefined; + const upstreamRemote = yield* executeGit( "GitVcsDriver.refreshStatusUpstreamIfStale.upstreamRemote", cwd, ["for-each-ref", "--format=%(upstream:remotename)", headRef], - true, - ).pipe(Effect.map((stdout) => stdout.trim())); + { allowNonZeroExit: true }, + ); + if (upstreamRemote.exitCode !== 0) return undefined; + const remoteName = upstreamRemote.stdout.trim(); // Empty means no upstream; `.` means the upstream is a local branch. - if (remoteName.length === 0 || remoteName === ".") return; + if (remoteName.length === 0 || remoteName === ".") return remoteName; const gitCommonDir = yield* resolveGitCommonDir(cwd); yield* Cache.get( statusRemoteRefreshCache, @@ -1996,6 +2002,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* // The cache returns after five seconds while the fetch keeps running. const pending = statusFetches.get(`${gitCommonDir}\0${remoteName}`); if (pending) yield* Fiber.await(pending.fiber); + return remoteName; }); const resolveDefaultBranchName = ( @@ -2515,7 +2522,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return Number.isFinite(parsed) ? Math.max(0, parsed) : 0; }); - const readStatusDetailsRemote = Effect.fn("readStatusDetailsRemote")(function* (cwd: string) { + const readStatusDetailsRemote = Effect.fn("readStatusDetailsRemote")(function* ( + cwd: string, + refreshUpstream: boolean, + ) { const branchResult = yield* executeGitWithStableDiagnostics( "GitVcsDriver.statusDetailsRemote.branch", cwd, @@ -2532,6 +2542,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return NON_REPOSITORY_REMOTE_STATUS_DETAILS; } let branch: string | null; + let headRef: string; if (branchResult.exitCode !== 0) { if (isNonRepositoryGitStderr(branchResult.stderr)) { return NON_REPOSITORY_REMOTE_STATUS_DETAILS; @@ -2556,10 +2567,29 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ["symbolic-ref", "--quiet", "HEAD"], ); branch = branchNameFromHeadRef(branchValue); + // An unborn branch has no ref, so for-each-ref below cannot report its upstream. + headRef = ""; } else { branch = branchNameFromHeadRef(branchResult.stdout); + headRef = branchResult.stdout.trim(); + } + let upstreamRemoteName: string | undefined; + if (refreshUpstream) { + // A detached HEAD prints `HEAD`, which has no upstream to refresh. + yield* refreshStatusUpstreamIfStale(cwd, headRef.startsWith("refs/") ? headRef : "").pipe( + Effect.map((remoteName) => { + upstreamRemoteName = remoteName; + }), + Effect.catchTags({ + GitCommandError: (error) => + isMissingGitCwdError(error) ? Effect.void : Effect.fail(error), + }), + Effect.ignoreCause({ log: true }), + ); } - const currentUpstreamRef = yield* readCurrentUpstreamRef(cwd); + // `%(upstream:remotename)` is empty exactly when `@{upstream}` does not resolve. + const currentUpstreamRef = + upstreamRemoteName === "" ? null : yield* readCurrentUpstreamRef(cwd); let upstreamRef = currentUpstreamRef; // Trimming a remote that starts with Unicode whitespace can leave a leading slash. if (currentUpstreamRef?.startsWith("/")) { @@ -2966,16 +2996,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const statusDetailsRemote: GitVcsDriver.GitVcsDriver["Service"]["statusDetailsRemote"] = Effect.fn("statusDetailsRemote")(function* (cwd, options) { - if (options?.refreshUpstream !== false) { - yield* refreshStatusUpstreamIfStale(cwd).pipe( - Effect.catchTags({ - GitCommandError: (error) => - isMissingGitCwdError(error) ? Effect.void : Effect.fail(error), - }), - Effect.ignoreCause({ log: true }), - ); - } - return yield* readStatusDetailsRemote(cwd); + return yield* readStatusDetailsRemote(cwd, options?.refreshUpstream !== false); }); const status: GitVcsDriver.GitVcsDriver["Service"]["status"] = (input) => From d51d8c4766f6c8760d5db9428596b98c4f81eab1 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 01:02:31 -0800 Subject: [PATCH 07/39] fix(client-runtime): opening the Diff panel reads each file patch once (#40217) --- packages/client-runtime/src/state/review.ts | 51 ++++++++--- .../client-runtime/src/state/runtime.test.ts | 85 +++++++++++++++++++ packages/client-runtime/src/state/runtime.ts | 14 +-- 3 files changed, 135 insertions(+), 15 deletions(-) diff --git a/packages/client-runtime/src/state/review.ts b/packages/client-runtime/src/state/review.ts index a92e213c44608..fa93b3b81e7d5 100644 --- a/packages/client-runtime/src/state/review.ts +++ b/packages/client-runtime/src/state/review.ts @@ -9,7 +9,7 @@ import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Semaphore from "effect/Semaphore"; import { request } from "../rpc/client.ts"; -import { AsyncResult, Atom } from "effect/reactivity"; +import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity"; import { createAtomCommandScheduler, @@ -20,6 +20,14 @@ import { } from "./runtime.ts"; import type { EnvironmentRegistry } from "../connection/registry.ts"; +interface PreviewRevisionState { + readonly key: string | null; + /** When the preview's pending read was first seen; set only while it waits. */ + readonly requestedAt: number | undefined; + /** The revision patches are read under. */ + readonly revision: string | null; +} + export function createReviewEnvironmentAtoms( runtime: Atom.AtomRuntime, options: { @@ -66,19 +74,42 @@ export function createReviewEnvironmentAtoms( }), ...(options.onDiffPreviewAnswer === undefined ? {} : { onAnswer: options.onDiffPreviewAnswer }), }); - // A file patch is a slice of the comparison its preview generated, so a newer preview - // revision makes every patch read under the old one stale. - const previewRevisionFamily = Atom.family((key: string) => { - const target = JSON.parse(key) as Parameters[0]; + // A file patch is a slice of the comparison its preview generated, so a preview revision + // requested after the patch was read makes it stale. A read that overlaps the revision's own + // read, such as the Diff panel's patches requested as it revalidates on show, is as fresh as it. + const previewRevision = ( + target: Parameters[0], + patch: Atom.Atom>, + ) => { + // Held outside the node so a swept and rebuilt node does not report a revision change. + const states = new WeakMap(); return Atom.make((get) => { - // A failed refresh keeps the last revision, so an error does not refresh every patch. // Reading the preview here keeps its query mounted while any of its patches is read. - return Option.match(AsyncResult.value(get(diffPreview(target))), { + const result = get(diffPreview(target)); + // A failed refresh keeps the last revision, so an error does not refresh every patch. + const key = Option.match(AsyncResult.value(result), { onNone: () => null, onSome: (preview) => DateTime.formatIso(preview.generatedAt), }); + const previous = states.get(get.registry); + const requestedAt = result.waiting + ? // @effect-diagnostics-next-line globalDate:off - Compared with `AsyncResult` timestamps, which come from `Date.now`. + (previous?.requestedAt ?? Date.now()) + : undefined; + let revision = key; + if (previous !== undefined && key === previous.key) revision = previous.revision; + else if (previous !== undefined) { + const since = requestedAt ?? previous.requestedAt; + const read = get.once(patch); + const fresh = + since !== undefined && + (read.waiting || (read._tag === "Success" && read.timestamp >= since)); + if (fresh) revision = previous.revision; + } + states.set(get.registry, { key, requestedAt, revision }); + return revision; }); - }); + }; return { branchCommits: createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:review:branch-commits", @@ -89,10 +120,10 @@ export function createReviewEnvironmentAtoms( diffFilePatch: createEnvironmentQueryAtomFamily(runtime, { label: "environment-data:review:diff-file-patch", staleTimeMs: 5 * 60_000, - refreshTrigger: ({ environmentId, input }) => + refreshTrigger: ({ environmentId, input }, patch) => input.preview === undefined ? undefined - : previewRevisionFamily(JSON.stringify({ environmentId, input: input.preview })), + : previewRevision({ environmentId, input: input.preview }, patch), execute: (input: { request: ReviewDiffPreviewInput & { file: NonNullable }; cacheKey: string; diff --git a/packages/client-runtime/src/state/runtime.test.ts b/packages/client-runtime/src/state/runtime.test.ts index 27a1b22c91f41..3b54ce7d32b05 100644 --- a/packages/client-runtime/src/state/runtime.test.ts +++ b/packages/client-runtime/src/state/runtime.test.ts @@ -266,6 +266,91 @@ it.effect("keeps complete review metadata visible while a refresh is held", () = }), ); +it.effect("does not re-read a file patch read while its preview was revalidating", () => + Effect.gen(function* () { + let now = 0; + using _now = vi.spyOn(Date, "now").mockImplementation(() => now); + const previewStarted = yield* Deferred.make(); + const releasePreview = yield* Deferred.make(); + let previewReads = 0; + let patchReads = 0; + const rpcSession = { + client: { + [WS_METHODS.reviewGetDiffPreview]: (input: ReviewDiffPreviewInput) => + Effect.gen(function* () { + if (input.file) patchReads += 1; + else if (++previewReads > 1) { + yield* Deferred.succeed(previewStarted, undefined); + yield* Deferred.await(releasePreview); + } + return { + cwd: input.cwd, + generatedAt: DateTime.makeUnsafe(previewReads), + sources: [ + { + id: "working-tree", + kind: "working-tree" as const, + title: "Uncommitted", + baseRef: "HEAD", + headRef: null, + diff: "", + diffHash: "same", + truncated: false, + patchesDeferred: true, + files: [{ path: "a.ts", previousPath: null, additions: 1, deletions: 0 }], + }, + ], + }; + }), + }, + } as unknown as RpcSession.RpcSession; + const harness = yield* makeEnvironmentQueryHarness(Effect.void, { rpcSession }); + const review = createReviewEnvironmentAtoms(harness.runtime); + const previewInput = { + cwd: "/project", + sourceKind: "working-tree", + metadataOnly: true, + } as const; + const preview = review.diffPreview({ + environmentId: QUERY_ENVIRONMENT.environmentId, + input: previewInput, + }); + const registry = yield* mountEnvironmentQuery(preview); + yield* readEnvironmentQuery(registry, preview); + + // Opening the Diff panel revalidates the preview and reads the visible patches at once. + registry.refresh(preview); + yield* Deferred.await(previewStarted); + const patch = review.diffFilePatch({ + environmentId: QUERY_ENVIRONMENT.environmentId, + input: { + request: { + cwd: "/project", + sourceKind: "working-tree", + file: { sourceKind: "working-tree", path: "a.ts", previousPath: null }, + }, + cacheKey: "a.ts", + preview: previewInput, + }, + }); + registry.mount(patch); + yield* readEnvironmentQuery(registry, patch); + expect(patchReads).toBe(1); + + yield* Deferred.succeed(releasePreview, undefined); + yield* readEnvironmentQuery(registry, preview); + yield* readEnvironmentQuery(registry, patch); + expect(patchReads).toBe(1); + + // A revalidation requested after the patch was read still refreshes it. + now = 1; + registry.refresh(preview); + yield* readEnvironmentQuery(registry, preview); + yield* readEnvironmentQuery(registry, patch); + expect(patchReads).toBe(2); + }), +); + it.effect("keeps manual Issues refresh intent through an overlapping write", () => Effect.gen(function* () { const requests = yield* Queue.unbounded(); diff --git a/packages/client-runtime/src/state/runtime.ts b/packages/client-runtime/src/state/runtime.ts index 7740f126b865d..f96da6e04ed21 100644 --- a/packages/client-runtime/src/state/runtime.ts +++ b/packages/client-runtime/src/state/runtime.ts @@ -102,10 +102,14 @@ interface EnvironmentQueryAtomOptions extends Omit< readonly staleTimeMs?: number; readonly idleTtlMs?: number; readonly refreshIntervalMs?: number; - readonly refreshTrigger?: (target: { - readonly environmentId: EnvironmentIdType; - readonly input: Input; - }) => Atom.Atom | undefined; + /** Each change of the returned signal refreshes the query; `query` is the data it refreshes. */ + readonly refreshTrigger?: ( + target: { + readonly environmentId: EnvironmentIdType; + readonly input: Input; + }, + query: Atom.Atom>, + ) => Atom.Atom | undefined; readonly isFinal?: (value: A) => boolean; /** * Runs where each server answer lands, before readers see it, so derived records (summaries, @@ -905,7 +909,7 @@ export function createEnvironmentQueryAtomFamily( options.refreshIntervalMs === undefined ? queryAtom : queryAtom.pipe(refreshEveryUntilFinal(options.refreshIntervalMs, isFinal)); - const refreshTrigger = options.refreshTrigger?.(target); + const refreshTrigger = options.refreshTrigger?.(target, intervalQuery); return ( refreshTrigger === undefined ? intervalQuery From 28bcb737360410e9849e47ce5afa984f7af6d902 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 01:35:04 -0800 Subject: [PATCH 08/39] fix(web): floating device preview keeps its stream across thread switches (#40240) --- .../ThreadPreviewMiniPlayer.browser.test.tsx | 39 ++++++++++++++++++- .../preview/ThreadPreviewMiniPlayer.tsx | 5 ++- 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/apps/web/src/components/preview/ThreadPreviewMiniPlayer.browser.test.tsx b/apps/web/src/components/preview/ThreadPreviewMiniPlayer.browser.test.tsx index 9bb9e746ea12f..ebf42cc7d563a 100644 --- a/apps/web/src/components/preview/ThreadPreviewMiniPlayer.browser.test.tsx +++ b/apps/web/src/components/preview/ThreadPreviewMiniPlayer.browser.test.tsx @@ -2,7 +2,12 @@ import "~/index.css"; import { RegistryContext } from "@effect/atom-react"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; -import { type DeviceServiceState, type EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { + type DeviceServiceState, + type EnvironmentId, + type ScopedThreadRef, + ThreadId, +} from "@t3tools/contracts"; import { AsyncResult, Atom } from "effect/reactivity"; import { useState } from "react"; import { expect, it, vi } from "vite-plus/test"; @@ -27,6 +32,7 @@ vi.mock(import("../device/DeviceStreamView"), () => ({ })); const threadRef = scopeThreadRef("env-1" as EnvironmentId, ThreadId.make("thread-1")); +const defaultThreadRef = threadRef; const phone: PreviewMiniPlayerSource = { kind: "device", hostId: "local", @@ -35,7 +41,7 @@ const phone: PreviewMiniPlayerSource = { name: "Phone", }; -function Harness() { +function Harness({ threadRef = defaultThreadRef }: { readonly threadRef?: ScopedThreadRef }) { const [store] = useState(createChatCanvasStore); const miniPlayer = usePreviewMiniPlayerStore((state) => selectThreadPreviewMiniPlayer(state.byThreadKey, threadRef), @@ -119,3 +125,32 @@ it("holds its frame through a source change and stops when the gesture is interr await point(handle("west"), "pointermove", landscape.left - 100, landscape.top + 10, 1); expect(rect()).toEqual(landscape); }); + +it("keeps one stream when switching between threads floating the same device", async () => { + using _state = vi + .spyOn(deviceEnvironment, "state") + .mockReturnValue(Atom.make>(AsyncResult.initial())); + const otherThreadRef = scopeThreadRef("env-1" as EnvironmentId, ThreadId.make("thread-2")); + using _store = { + [Symbol.dispose]: () => { + usePreviewMiniPlayerStore.getState().removeThread(threadRef); + usePreviewMiniPlayerStore.getState().removeThread(otherThreadRef); + }, + }; + usePreviewMiniPlayerStore.getState().open(threadRef, phone); + usePreviewMiniPlayerStore.getState().open(otherThreadRef, phone); + const harness = (ref: ScopedThreadRef) => ( + + + + ); + const container = document.createElement("div"); + container.style.cssText = "display:flex;position:fixed;inset:0;width:1200px;height:800px"; + await using screen = await render(harness(threadRef), { container }); + const viewId = () => screen.getByTestId("stream").element().getAttribute("data-view-id"); + const first = viewId(); + + // The stream session is keyed by view, so a new view id reconnects the device. + await screen.rerender(harness(otherThreadRef)); + expect(viewId()).toBe(first); +}); diff --git a/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx b/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx index 378bcdd88408f..989f283ad083b 100644 --- a/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx +++ b/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx @@ -121,12 +121,13 @@ const streamedSourceKey = (threadRef: ScopedThreadRef, sourceKey: string) => `${scopedThreadKey(threadRef)}\u0000${sourceKey}`; // The mini player's device stream view, named so the canvas can read the -// screen size that view reports. +// screen size that view reports. Not per thread: only the active thread's player +// mounts, so switching threads that float the same device keeps its stream. const miniPlayerDeviceViewId = ( threadRef: ScopedThreadRef, source: Extract, ) => - `preview-mini-player\u0000${scopedThreadKey(threadRef)}\u0000${deviceScreenKey(threadRef.environmentId, source.hostId, source.deviceId)}`; + `preview-mini-player\u0000${deviceScreenKey(threadRef.environmentId, source.hostId, source.deviceId)}`; function useBrowserMiniPlayerSource(threadRef: ScopedThreadRef | null, tabId: string | null) { const previewState = useThreadPreviewState(threadRef); From 5aae5578de0ffd3f052e17a397368e2c2f6d1476 Mon Sep 17 00:00:00 2001 From: screen Date: Sat, 21 Nov 2026 01:06:22 +0400 Subject: [PATCH 09/39] fix(web): show the update capsule label in narrower sidebars Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit b32f90ba52d840540506066696766e323055adb0) --- apps/web/src/components/sidebar/SidebarUpdateCapsule.tsx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/apps/web/src/components/sidebar/SidebarUpdateCapsule.tsx b/apps/web/src/components/sidebar/SidebarUpdateCapsule.tsx index 2e6cbe19390cc..4d71b74244b97 100644 --- a/apps/web/src/components/sidebar/SidebarUpdateCapsule.tsx +++ b/apps/web/src/components/sidebar/SidebarUpdateCapsule.tsx @@ -105,7 +105,7 @@ export function SidebarUpdateCapsule({
} /> - + {view.label} {view.slow ? ( {view.slow.elapsed} @@ -130,7 +130,7 @@ export function SidebarUpdateCapsule({ {view.action !== null ? (
diff --git a/apps/web/src/components/files/FileBrowserPanel.tsx b/apps/web/src/components/files/FileBrowserPanel.tsx index 1fee7db238727..cd44d99220939 100644 --- a/apps/web/src/components/files/FileBrowserPanel.tsx +++ b/apps/web/src/components/files/FileBrowserPanel.tsx @@ -27,7 +27,11 @@ import { useWorkspaceMutationRefresh } from "~/hooks/useWorkspaceMutationRefresh import { useFileContextMenu, type FileContextMenuAction } from "~/fileContextMenu"; import { readLocalApi } from "~/localApi"; import { T3_PIERRE_ICONS } from "~/pierre-icons"; -import { PIERRE_TREE_UNSAFE_CSS, pierreTreeStyle } from "~/pierre-tree-theme"; +import { + PIERRE_TREE_UNSAFE_CSS, + pierreTreeStyle, + titleClippedPierreTreeRow, +} from "~/pierre-tree-theme"; import { joinHostPath } from "./filePath"; import { createFileTreeDragMentionController } from "./fileTreeDragMention"; @@ -646,6 +650,7 @@ export default function FileBrowserPanel({ aria-label={gt("{projectName} files", { projectName })} className="min-h-0 flex-1 overflow-hidden" style={pierreTreeStyle(resolvedTheme)} + onPointerOver={titleClippedPierreTreeRow} /> )}
diff --git a/apps/web/src/pierre-tree-theme.ts b/apps/web/src/pierre-tree-theme.ts index ada2a7d1abc7b..7deb41db7dcf0 100644 --- a/apps/web/src/pierre-tree-theme.ts +++ b/apps/web/src/pierre-tree-theme.ts @@ -1,4 +1,4 @@ -import type { CSSProperties } from "react"; +import type { CSSProperties, PointerEvent } from "react"; export const PIERRE_TREE_UNSAFE_CSS = ` :host { @@ -27,3 +27,20 @@ export function pierreTreeStyle(colorScheme: "light" | "dark"): CSSProperties { ["--trees-status-ignored-override" as string]: "var(--contrast-muted-foreground)", }; } + +// Clipped labels are unreadable and the tree cannot scroll sideways, so a clipped row gets its full name as a native tooltip. +export function titleClippedPierreTreeRow(event: PointerEvent) { + const row = event.nativeEvent + .composedPath() + .find( + (node): node is HTMLElement => + node instanceof HTMLElement && node.matches("button[data-type='item']"), + ); + if (!row) return; + const label = row.getAttribute("aria-label"); + const clipped = Array.from( + row.querySelectorAll("[data-truncate-content='visible']"), + ).some((element) => element.scrollWidth > element.clientWidth); + if (label && clipped) row.title = label; + else row.removeAttribute("title"); +} From 66441268e800dc7a73acd71810e34e6fa4b82e32 Mon Sep 17 00:00:00 2001 From: gero3 Date: Sat, 21 Nov 2026 13:39:40 +0100 Subject: [PATCH 24/39] fix(cli): update Windows launchers outside PATH (#40309) Co-authored-by: Julius Marminge --- apps/server/src/cli/update.test.ts | 26 ++++++++++++++++++++++++++ apps/server/src/cli/update.ts | 28 ++++++++++++++++++++++------ 2 files changed, 48 insertions(+), 6 deletions(-) diff --git a/apps/server/src/cli/update.test.ts b/apps/server/src/cli/update.test.ts index b5d3394f23fd2..2de00fc24bf54 100644 --- a/apps/server/src/cli/update.test.ts +++ b/apps/server/src/cli/update.test.ts @@ -229,6 +229,32 @@ it.layer(NodeServices.layer)("t3 update launcher", (it) => { }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")), ); + it.effect("repoints a recorded Windows launcher outside PATH", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped(); + const baseDir = path.join(root, "home"); + const runtimeDir = path.join(baseDir, "runtime"); + const launcher = path.join(root, "custom bin", "t3.cmd"); + const launchedAs = path.join(runtimeDir, "versions", "1.0.0", "t3.exe"); + const targetEntryPath = path.join(runtimeDir, "versions", "2.0.0", "t3.exe"); + yield* fs.makeDirectory(runtimeDir, { recursive: true }); + yield* fs.makeDirectory(path.dirname(launcher), { recursive: true }); + yield* fs.writeFileString(launcher, `@echo off\r\n"${launchedAs}" %*`); + yield* fs.writeFileString(path.join(runtimeDir, "launchers"), `${launcher}\r\n`); + + const repointed = yield* repointLauncher({ launchedAs, baseDir, targetEntryPath }); + + assert.equal(Option.getOrUndefined(repointed), launcher); + assert.equal(yield* fs.readFileString(launcher), `@echo off\r\n"${targetEntryPath}" %*`); + }).pipe( + Effect.scoped, + Effect.provideService(HostProcess.Platform, "win32"), + Effect.provideService(HostProcess.Environment, { PATH: "" }), + ), + ); + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( "finds the script that ran this executable and rewrites it, keeping aliases and arguments", () => diff --git a/apps/server/src/cli/update.ts b/apps/server/src/cli/update.ts index b7b76f2f34223..07f3458fb3b66 100644 --- a/apps/server/src/cli/update.ts +++ b/apps/server/src/cli/update.ts @@ -25,6 +25,7 @@ import * as BootService from "../cloud/bootService.ts"; import { ensurePinnedRuntimeInstalled, findPosixLauncher, + generatedWindowsShimTarget, launcherOwnsVersionsDir, isUnpublishedRelease, pinnedRuntimePaths, @@ -171,7 +172,7 @@ export const repointLauncher = Effect.fn("cli.update.repoint_launcher")(function ); if (platform === "win32") { - const shimPath = yield* findWindowsShim(input.launchedAs); + const shimPath = yield* findWindowsShim(input.launchedAs, versionsDir); if (shimPath === undefined) return Option.none(); const current = yield* fs.readFileString(shimPath).pipe(Effect.option); const quoted = Option.isSome(current) ? windowsShimTarget(current.value) : undefined; @@ -203,9 +204,10 @@ export const repointLauncher = Effect.fn("cli.update.repoint_launcher")(function return Option.some(launcher); }); -/** Windows executables see their own path, so find the installer shim by matching t3.cmd targets on PATH. */ +/** Windows executables see their own path, so locate the installer shim by matching its target. */ export const findWindowsShim = Effect.fn("cli.update.find_windows_shim")(function* ( executablePath: string, + versionsDir?: string, ) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -213,12 +215,26 @@ export const findWindowsShim = Effect.fn("cli.update.find_windows_shim")(functio const candidates = [ ...(environment["T3CODE_INSTALL_BIN_DIR"] ? [environment["T3CODE_INSTALL_BIN_DIR"]] : []), ...(environment["PATH"] ?? environment["Path"] ?? "").split(";"), - ].filter((entry) => entry.trim().length > 0); - for (const directory of candidates) { - const shimPath = path.join(directory, "t3.cmd"); + ] + .filter((entry) => entry.trim().length > 0) + .map((directory) => ({ + shimPath: path.join(directory, "t3.cmd"), + parseTarget: windowsShimTarget, + })); + if (versionsDir !== undefined) { + const recorded = yield* fs + .readFileString(path.join(path.dirname(versionsDir), "launchers")) + .pipe(Effect.orElseSucceed(() => "")); + for (const shimPath of recorded.split(/\r?\n/)) { + if (path.isAbsolute(shimPath) && path.basename(shimPath).toLowerCase() === "t3.cmd") { + candidates.push({ shimPath, parseTarget: generatedWindowsShimTarget }); + } + } + } + for (const { shimPath, parseTarget } of candidates) { const contents = yield* fs.readFileString(shimPath).pipe(Effect.option); if (Option.isNone(contents)) continue; - const target = windowsShimTarget(contents.value); + const target = parseTarget(contents.value); if ( target !== undefined && path.resolve(target).toLowerCase() === path.resolve(executablePath).toLowerCase() From 69228fe179815a9446531eb9cf73d8deaa26db4c Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:16:58 +0530 Subject: [PATCH 25/39] fix(server): typed-message commits stage the worktree once (#40282) Co-authored-by: Julius Marminge --- apps/server/src/git/GitManager.test.ts | 45 +++++++++++++ apps/server/src/git/GitManager.ts | 27 ++++++-- apps/server/src/vcs/GitVcsDriver.ts | 22 +++++- apps/server/src/vcs/GitVcsDriverCore.test.ts | 45 ++++++++++++- apps/server/src/vcs/GitVcsDriverCore.ts | 71 ++++++++++++++++++++ 5 files changed, 201 insertions(+), 9 deletions(-) diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index 0528d08f36c29..9dc3407597a4f 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -3584,6 +3584,51 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }), ); + it.effect("stages the worktree once for a typed commit message", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "typed\n"); + const gitCommands: string[] = []; + const { manager } = yield* makeManager({ gitCommands }); + + const created = yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit", + commitMessage: "Typed subject\n\nTyped body", + }); + + expect(created.commit).toMatchObject({ status: "created", subject: "Typed subject" }); + expect(gitCommands.filter((args) => args.endsWith("add -A"))).toHaveLength(1); + expect((yield* runGit(repoDir, ["log", "-1", "--pretty=%B"])).stdout.trim()).toBe( + "Typed subject\n\nTyped body", + ); + + // Status shows the staged change, but staging the reverted worktree leaves nothing. + NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "staged\n"); + yield* runGit(repoDir, ["add", "README.md"]); + NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "typed\n"); + const head = (yield* runGit(repoDir, ["rev-parse", "HEAD"])).stdout; + + const skipped = yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit", + commitMessage: "Nothing to commit", + }); + + expect(skipped.commit.status).toBe("skipped_no_changes"); + expect((yield* runGit(repoDir, ["rev-parse", "HEAD"])).stdout).toBe(head); + expect((yield* runGit(repoDir, ["show", ":README.md"])).stdout).toBe("staged\n"); + + // A generated message already checked a scratch index, so staging again stays at two. + NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "generated\n"); + gitCommands.length = 0; + const generated = yield* runStackedAction(manager, { cwd: repoDir, action: "commit" }); + expect(generated.commit.status).toBe("created"); + expect(gitCommands.filter((args) => args.endsWith("add -A"))).toHaveLength(2); + }), + ); + it.effect("lowercases a capitalized Conventional Commits description", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index 118e4ffd461ae..9db4fbfc27755 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -2494,7 +2494,13 @@ export const make = Effect.gen(function* () { } as GitActionProgressEvent) : Effect.void; - let suggestion: CommitAndBranchSuggestion | null | undefined = preResolvedSuggestion; + const customCommit = parseCustomCommitMessage(commitMessage ?? ""); + let suggestion: CommitAndBranchSuggestion | null | undefined = + preResolvedSuggestion ?? + (customCommit && { + ...customCommit, + commitMessage: formatCommitMessage(customCommit.subject, customCommit.body), + }); if (!suggestion) { const needsGeneration = !commitMessage?.trim(); if (needsGeneration) { @@ -2566,11 +2572,20 @@ export const make = Effect.gen(function* () { }, } : null; - const { commitSha } = yield* gitCore.commit(cwd, suggestion.subject, suggestion.body, { - timeoutMs: COMMIT_TIMEOUT_MS, - stage: filePaths ? { filePaths } : {}, - ...(commitProgress ? { progress: commitProgress } : {}), - }); + const committed = yield* gitCore + .commit(cwd, suggestion.subject, suggestion.body, { + timeoutMs: COMMIT_TIMEOUT_MS, + stage: { + ...(filePaths ? { filePaths } : {}), + ...(!preResolvedSuggestion && customCommit ? { unverified: true } : {}), + }, + ...(commitProgress ? { progress: commitProgress } : {}), + }) + .pipe(Effect.catchTags({ GitNothingToCommitError: () => Effect.succeed(null) })); + if (!committed) { + return { status: "skipped_no_changes" as const }; + } + const { commitSha } = committed; if (currentHookName !== null) { yield* emit({ kind: "hook_finished", diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index 5164e6f4585c8..700ad3b3571c9 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -10,6 +10,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; import { ChildProcessSpawner } from "effect/process"; import { @@ -76,6 +77,19 @@ export interface ExecuteGitResult { readonly stderrTruncated: boolean; } +export class GitNothingToCommitError extends Schema.TaggedError()( + "GitNothingToCommitError", + { + operation: Schema.String, + cwd: Schema.String, + detail: Schema.String, + }, +) { + override get message(): string { + return `Nothing to commit in ${this.operation} (${this.cwd}): ${this.detail}`; + } +} + export interface GitStatusDetails { isRepo: boolean; sourceControlProvider?: VcsStatusResult["sourceControlProvider"]; @@ -173,7 +187,11 @@ export interface GitCommitProgress { export interface GitCommitOptions { readonly timeoutMs?: number; readonly progress?: GitCommitProgress; - readonly stage?: { readonly filePaths?: readonly string[] }; + readonly stage?: { + readonly filePaths?: readonly string[]; + /** The caller has not run `prepareCommitContext`, so an empty result must keep the index. */ + readonly unverified?: boolean; + }; } export interface GitDeleteLocalBranchInput { @@ -361,7 +379,7 @@ export class GitVcsDriver extends Context.Service< subject: string, body: string, options?: GitCommitOptions, - ) => Effect.Effect<{ commitSha: string }, GitCommandError>; + ) => Effect.Effect<{ commitSha: string }, GitCommandError | GitNothingToCommitError>; readonly pushCurrentBranch: ( cwd: string, fallbackBranch: string | null, diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index e23343ed67165..8789b54d31562 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -8621,6 +8621,17 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { assert.notInclude(context?.stagedSummary ?? "", "b.txt"); assert.equal(yield* git(repository, ["diff", "--cached", "--name-only"]), ""); + // A selected file staged and then reverted stages to nothing, like git commit --only. + const head = yield* git(repository, ["rev-parse", "HEAD"]); + yield* writeTextFile(repository, "README.md", "staged\n"); + yield* git(repository, ["add", "README.md"]); + yield* git(repository, ["restore", "--source=HEAD", "--worktree", "--", "README.md"]); + const empty = yield* driver + .commit(cwd, "Empty", "", { stage: { filePaths: ["README.md"] } }) + .pipe(Effect.flip); + assert.equal(empty._tag, "GitNothingToCommitError"); + assert.equal(yield* git(repository, ["rev-parse", "HEAD"]), head); + const commit = yield* driver.commit(cwd, "Add a", "", { stage: { filePaths: [selected] }, }); @@ -8840,6 +8851,8 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { // A branch named MERGE_HEAD is not a merge in progress. yield* git(cwd, ["branch", "MERGE_HEAD"]); assert.isNull(yield* driver.prepareCommitContext(cwd, undefined, { includePatch: false })); + const empty = yield* driver.commit(cwd, "Empty", "", { stage: {} }).pipe(Effect.flip); + assert.equal(empty._tag, "GitNothingToCommitError"); yield* git(cwd, ["branch", "-D", "MERGE_HEAD"]); yield* git(cwd, ["checkout", "-b", "feature"]); yield* writeTextFile(cwd, "README.md", "feature version\n"); @@ -8859,6 +8872,13 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { assert.isNotNull( yield* driver.prepareCommitContext(cwd, undefined, { includePatch: false }), ); + const mainHead = yield* git(cwd, ["rev-parse", "HEAD"]); + const featureHead = yield* git(cwd, ["rev-parse", "feature"]); + yield* driver.commit(cwd, "Merge feature", "", { stage: {} }); + assert.equal( + yield* git(cwd, ["show", "-s", "--format=%P", "HEAD"]), + `${mainHead} ${featureHead}`, + ); }), ); @@ -9004,6 +9024,9 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { yield* writeTextFile(cwd, "README.md", "stashed version\n"); yield* git(cwd, ["stash"]); yield* writeTextFile(cwd, "README.md", "committed version\n"); + yield* writeTextFile(cwd, "same.txt", "same\n"); + yield* writeTextFile(cwd, "gone.txt", "gone\n"); + yield* git(cwd, ["add", "same.txt", "gone.txt"]); yield* git(cwd, ["commit", "-am", "Change README"]); const pop = yield* driver.execute({ operation: "test.stashPop", @@ -9012,9 +9035,29 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { allowNonZeroExit: true, }); assert.equal(pop.exitCode, 1); + const unmerged = yield* git(cwd, ["ls-files", "--unmerged"]); + + // A selected file staged and then reverted has nothing to commit despite the conflict. + const unchangedHead = yield* git(cwd, ["rev-parse", "HEAD"]); + yield* writeTextFile(cwd, "same.txt", "staged\n"); + yield* git(cwd, ["add", "same.txt"]); + yield* git(cwd, ["restore", "--source=HEAD", "--worktree", "--", "same.txt"]); + const empty = yield* driver + .commit(cwd, "Empty", "", { stage: { filePaths: ["same.txt"] } }) + .pipe(Effect.flip); + assert.equal(empty._tag, "GitNothingToCommitError"); + assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), unchangedHead); + assert.equal(yield* git(cwd, ["ls-files", "--unmerged"]), unmerged); + + yield* (yield* FileSystem.FileSystem).remove((yield* Path.Path).join(cwd, "gone.txt")); + yield* driver.commit(cwd, "Remove gone", "", { stage: { filePaths: ["gone.txt"] } }); + assert.equal( + yield* git(cwd, ["show", "--pretty=", "--name-status", "HEAD"]), + "D\tgone.txt", + ); + yield* writeTextFile(cwd, "other.txt", "other\n"); const head = yield* git(cwd, ["rev-parse", "HEAD"]); - const unmerged = yield* git(cwd, ["ls-files", "--unmerged"]); const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const nested = path.join(cwd, "nested"); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index ab9b10563c690..27927f5dc5c8b 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -3399,10 +3399,81 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* body, options?: GitVcsDriver.GitCommitOptions, ) { + const diffCached = [ + "-c", + "diff.relative=false", + "diff", + "--cached", + "--no-ext-diff", + "--no-textconv", + ]; + if (options?.stage?.unverified) { + const indexMatchesHead = + (yield* executeGit("GitVcsDriver.commit.indexChanges", cwd, [...diffCached, "--quiet"], { + allowNonZeroExit: true, + })).exitCode === 0; + // Staging an empty result would overwrite what is already staged, so check a scratch index. + if ( + !indexMatchesHead && + (yield* prepareCommitContext(cwd, options.stage.filePaths, { includePatch: false })) === + null + ) { + return yield* new GitVcsDriver.GitNothingToCommitError({ + operation: "GitVcsDriver.commit", + cwd, + detail: "Staging found no changes.", + }); + } + } const partialCommitPaths = options?.stage !== undefined ? yield* stageCommitChanges(cwd, options.stage.filePaths) : undefined; + // Preserved unselected conflicts always show as index changes, so only selected paths count. + const selectedPaths = partialCommitPaths && new Set(options?.stage?.filePaths); + const hasStagedChanges = selectedPaths + ? (yield* runGitStdoutWithOptions( + "GitVcsDriver.commit.stagedChanges", + cwd, + [...diffCached, "--no-renames", "--name-only", "-z"], + { maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES }, + )) + .split("\0") + .some((file) => file.length > 0 && selectedPaths.has(file)) + : (yield* executeGit("GitVcsDriver.commit.stagedChanges", cwd, [...diffCached, "--quiet"], { + allowNonZeroExit: true, + })).exitCode !== 0; + if (!hasStagedChanges) { + // Like git commit, a merge resolved to HEAD's tree still records its merge commit. + const mergeHeadPath = yield* runGitStdout("GitVcsDriver.commit.mergeHead", cwd, [ + "rev-parse", + "--git-path", + "MERGE_HEAD", + ]); + const merging = yield* fileSystem.realPath(cwd).pipe( + Effect.orElseSucceed(() => cwd), + Effect.flatMap((physicalCwd) => + fileSystem.exists(path.resolve(physicalCwd, mergeHeadPath.trim())), + ), + Effect.mapError( + (cause) => + new GitCommandError({ + operation: "GitVcsDriver.commit.mergeHead", + command: "git commit", + cwd, + detail: "Could not check whether a merge is in progress.", + cause, + }), + ), + ); + if (!merging) { + return yield* new GitVcsDriver.GitNothingToCommitError({ + operation: "GitVcsDriver.commit", + cwd, + detail: "Staging found no changes.", + }); + } + } const args = ["commit", "-m", subject]; const trimmedBody = body.trim(); if (trimmedBody.length > 0) { From 7ef7ba0e3b1bc0582e44f1379bff1cc5559cf0d2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 04:49:13 -0800 Subject: [PATCH 26/39] perf(server): a tracked file's Diff panel patch skips the untracked-file listing (#40304) --- .../src/features/review/useReviewDiffData.ts | 1 + apps/server/src/vcs/GitVcsDriverCore.test.ts | 54 ++++++++++++++++++- apps/server/src/vcs/GitVcsDriverCore.ts | 26 +++++++-- .../components/diffs/useReviewFilePatches.ts | 1 + packages/contracts/src/review.ts | 20 +++---- 5 files changed, 88 insertions(+), 14 deletions(-) diff --git a/apps/mobile/src/features/review/useReviewDiffData.ts b/apps/mobile/src/features/review/useReviewDiffData.ts index 35cf8f2f14b3c..d530279f8ca25 100644 --- a/apps/mobile/src/features/review/useReviewDiffData.ts +++ b/apps/mobile/src/features/review/useReviewDiffData.ts @@ -219,6 +219,7 @@ export function useReviewDiffData(input: { file: { path: file.path, previousPath: file.previousPath, + ...(file.changeType ? { changeType: file.changeType } : {}), sourceKind: lazySource.kind, }, }, diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 8789b54d31562..e745669fda5c2 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -3463,7 +3463,12 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const scoped = yield* driver.getReviewDiffPreview({ cwd: projectDirectory, baseRef: initialBranch, - file: { path: file.path, previousPath: file.previousPath, sourceKind: source.kind }, + file: { + path: file.path, + previousPath: file.previousPath, + sourceKind: source.kind, + ...(file.changeType ? { changeType: file.changeType } : {}), + }, }); const patch = scoped.sources.find((item) => item.kind === source.kind)!; assert.deepStrictEqual(patch.files, [file]); @@ -3474,6 +3479,53 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect( + "lists untracked files for a file the preview called tracked only when it is not", + () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + yield* writeTextFile(cwd, "tracked.txt", "one\n"); + yield* git(cwd, ["add", "."]); + yield* git(cwd, ["commit", "-m", "tracked"]); + yield* writeTextFile(cwd, "tracked.txt", "two\n"); + yield* writeTextFile(cwd, "README.md", "dirty\n"); + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + let listings = 0; + const spawner = ChildProcessSpawner.make((command) => { + if (ChildProcess.isStandardCommand(command) && command.args.includes("--others")) { + listings++; + } + return delegate.spawn(command); + }); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + const read = (path: string, changeType?: "change") => + driver + .getReviewDiffPreview({ + cwd, + file: { + path, + previousPath: null, + sourceKind: "working-tree", + ...(changeType ? { changeType } : {}), + }, + }) + .pipe(Effect.map((preview) => preview.sources[0]!)); + + const tracked = yield* read("tracked.txt", "change"); + assert.include(tracked.diff, "+two"); + assert.equal(listings, 0); + + // A stale hint: the file left the index after the preview listed it. + yield* git(cwd, ["rm", "--cached", "-q", "README.md"]); + const stale = yield* read("README.md", "change"); + assert.equal(listings, 1); + assert.deepStrictEqual(stale, yield* read("README.md")); + }), + ); + it.effect("rejects a file selector for a different source than the request", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 27927f5dc5c8b..7c4363b1647be 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -4788,13 +4788,30 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* exitCode: result.exitCode, }); }); + // A file the preview did not list as new is stat-ed against the real index first. `git diff` + // lists an indexed path as anything but deleted, and `ls-files --others` never lists one. + const indexedRef = + input.file && !input.trackedOnly && input.file.changeType && input.file.changeType !== "new" + ? (dirtyRef ?? review.mergeBase) + : null; + const indexedStat = indexedRef === null ? undefined : yield* readStats(indexedRef); + const indexed = + indexedStat?.files.some( + (file) => + file.path === input.file?.path && + file.changeType !== undefined && + file.changeType !== "deleted", + ) === true; const readTrackedDiff = Effect.fn("GitVcsDriver.getReviewDiffPreview.tracked")(function* ( ref: string | null, env?: NodeJS.ProcessEnv, metadataOnly = false, ) { if (ref === null) return { stdout: "", stdoutTruncated: false, files: [] }; - const stat = yield* readStats(ref, env); + const stat = + env === undefined && ref === indexedRef && indexedStat !== undefined + ? indexedStat + : yield* readStats(ref, env); if (metadataOnly || stat.files.length === 0) { return { stdout: "", stdoutTruncated: false, files: stat.files }; } @@ -4807,9 +4824,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return { ...patch, files: stat.files }; }); const [dirtyTrackedResult, baseResult] = yield* Effect.gen(function* () { - const untracked = input.trackedOnly - ? { env: undefined, omitted: false } - : yield* prepareUntrackedReviewIndex(cwd, pathArgs, input.file?.path); + const untracked = + input.trackedOnly || indexed + ? { env: undefined, omitted: false } + : yield* prepareUntrackedReviewIndex(cwd, pathArgs, input.file?.path); // Untracked files left out make the file list partial, so the bounded patch is sent instead. const complete = untracked !== null && !untracked.omitted; // With no untracked files to add, the tracked read already is the complete diff. diff --git a/apps/web/src/components/diffs/useReviewFilePatches.ts b/apps/web/src/components/diffs/useReviewFilePatches.ts index 94fee877f0f4b..0c889d501264d 100644 --- a/apps/web/src/components/diffs/useReviewFilePatches.ts +++ b/apps/web/src/components/diffs/useReviewFilePatches.ts @@ -206,6 +206,7 @@ function reviewFileQueries({ file: { path: file.path, previousPath: file.previousPath, + ...(file.changeType ? { changeType: file.changeType } : {}), sourceKind: source.kind, }, }, diff --git a/packages/contracts/src/review.ts b/packages/contracts/src/review.ts index ab5cae42624d4..d43946e217219 100644 --- a/packages/contracts/src/review.ts +++ b/packages/contracts/src/review.ts @@ -8,6 +8,15 @@ const ReviewMergeBase = Schema.String.check( Schema.isPattern(/^(?:[0-9a-f]{40}|[0-9a-f]{64}|HEAD)$/), ); +export const ReviewDiffChangeType = Schema.Literals([ + "change", + "rename-pure", + "rename-changed", + "new", + "deleted", +]); +export type ReviewDiffChangeType = typeof ReviewDiffChangeType.Type; + export const ReviewDiffPreviewInput = Schema.Struct({ cwd: TrimmedNonEmptyString, baseRef: Schema.optional(TrimmedNonEmptyString), @@ -25,6 +34,8 @@ export const ReviewDiffPreviewInput = Schema.Struct({ path: Schema.NonEmptyString, previousPath: Schema.NullOr(Schema.NonEmptyString), sourceKind: Schema.Literals(["working-tree", "branch-range", "commit"]), + // The preview's change type; the server still confirms a tracked path before relying on it. + changeType: Schema.optionalKey(ReviewDiffChangeType), }), ), }); @@ -55,15 +66,6 @@ export const ReviewDiffPreviewSourceKind = Schema.Literals([ ]); export type ReviewDiffPreviewSourceKind = typeof ReviewDiffPreviewSourceKind.Type; -export const ReviewDiffChangeType = Schema.Literals([ - "change", - "rename-pure", - "rename-changed", - "new", - "deleted", -]); -export type ReviewDiffChangeType = typeof ReviewDiffChangeType.Type; - export const ReviewDiffFileStat = Schema.Struct({ path: Schema.String, previousPath: Schema.NullOr(Schema.String), From 0775dc450fcf4a6f85cc7db955f3c5b5f7d4f42a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 04:57:44 -0800 Subject: [PATCH 27/39] fix(mobile): mark the linked line in the native source viewer (#40295) --- .../main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt | 3 ++- apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt index 8b0a84a952caf..e2d5a12d76304 100644 --- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt +++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt @@ -1314,12 +1314,13 @@ private class DiffCanvasView(context: Context) : View(context) { } val selected = selectedRowIds.contains(row.id) if (selected) { + // Source files hide the change bar (width 0); the selection marker still needs to show. fill( canvas, withAlpha(theme.hunkText, 242), 0f, top.toFloat(), - style.changeBarWidthPx, + maxOf(style.changeBarWidthPx, 4f * density), bottom.toFloat() ) } diff --git a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift index 7fe4a068f9bbb..0c65ddf19460a 100644 --- a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift +++ b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift @@ -2661,8 +2661,9 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { return } + // Source files hide the change bar (width 0); the selection marker still needs to show. theme.hunkText.withAlphaComponent(0.95).setFill() - context.fill(CGRect(x: 0, y: rect.minY, width: style.changeBarWidth, height: rect.height)) + context.fill(CGRect(x: 0, y: rect.minY, width: max(style.changeBarWidth, 4), height: rect.height)) } private func drawWordDiffRanges( From c3853775447b466b402f38452ce81bcb1617e491 Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:40:15 +0530 Subject: [PATCH 28/39] fix(server): slash commands sent during a turn wait instead of steering (#40316) Co-authored-by: Julius Marminge --- .../orchestration-v2/CommandPolicy.test.ts | 24 +++ .../src/orchestration-v2/CommandPolicy.ts | 20 +++ .../src/orchestration-v2/Orchestrator.ts | 66 +++++++-- .../SteeringCompletion.integration.test.ts | 138 +++++++++++++++--- .../ThreadLaunchService.test.ts | 2 +- .../src/components/chat/QueuedRunsControl.tsx | 31 ++-- apps/web/src/i18n/translations/de.json | 4 +- apps/web/src/i18n/translations/en.json | 4 +- apps/web/src/i18n/translations/es.json | 4 +- apps/web/src/i18n/translations/fr.json | 4 +- apps/web/src/i18n/translations/ja.json | 4 +- apps/web/src/i18n/translations/ko.json | 4 +- apps/web/src/i18n/translations/pt-BR.json | 4 +- apps/web/src/i18n/translations/ru.json | 4 +- apps/web/src/i18n/translations/sv.json | 4 +- apps/web/src/i18n/translations/zh.json | 4 +- docs/user/composer.md | 9 +- packages/shared/src/composerTrigger.ts | 8 + .../steered-compact-waits-for-turn.e2e.ts | 71 +++++++++ 19 files changed, 353 insertions(+), 56 deletions(-) create mode 100644 scripts/scenarios/steered-compact-waits-for-turn.e2e.ts diff --git a/apps/server/src/orchestration-v2/CommandPolicy.test.ts b/apps/server/src/orchestration-v2/CommandPolicy.test.ts index e9f829524948b..d5b06dbf6c47f 100644 --- a/apps/server/src/orchestration-v2/CommandPolicy.test.ts +++ b/apps/server/src/orchestration-v2/CommandPolicy.test.ts @@ -252,6 +252,30 @@ it("steers a Grok follow-up into its running turn without restarting it", () => assert.isTrue(grok.turns.supportsActiveSteering); }); +// regression: #32606 a slash command steered into a running turn replaced the task +it.each([ + ["/compact", { type: "queue_after_active" }], + ["/context", { type: "queue_after_active" }], + [" /context all\n", { type: "queue_after_active" }], + ["/plugin:review-pr 12", { type: "queue_after_active" }], + ["/home/me/x.ts fails", { type: "steer_active", targetRunId: activeRunId }], + ["/ context", { type: "steer_active", targetRunId: activeRunId }], + ["$skill /context", { type: "steer_active", targetRunId: activeRunId }], +] as const)("steers %j only when it is not a slash command", (text, expected) => { + const projection = dispatchProjection(baseCapabilities); + for (const deliveryIntent of ["auto", "steer"] as const) { + assert.deepEqual( + CommandPolicy.resolveMessageDispatch(projection, { + dispatchMode: { type: "start_immediately" }, + deliveryIntent, + text, + attachments: [], + }), + expected, + ); + } +}); + it.each(["/compact", " /LOGOUT "])("queues a steer sent while %s runs", (text) => { const projection = dispatchProjection(baseCapabilities); const maintenance = { diff --git a/apps/server/src/orchestration-v2/CommandPolicy.ts b/apps/server/src/orchestration-v2/CommandPolicy.ts index 451ca978b9e51..1319083cca030 100644 --- a/apps/server/src/orchestration-v2/CommandPolicy.ts +++ b/apps/server/src/orchestration-v2/CommandPolicy.ts @@ -10,6 +10,7 @@ import { ProviderInstanceId, ThreadId, } from "@t3tools/contracts"; +import { isSlashCommand } from "@t3tools/shared/composerTrigger"; import { latestExecutedRun } from "@t3tools/shared/orchestrationV2ThreadError"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; @@ -101,6 +102,25 @@ export function goalCommandStopsActiveRun( } } +export function resolveMessageDispatch( + projection: OrchestrationV2ThreadProjection, + message: Pick< + Extract, + "dispatchMode" | "deliveryIntent" | "text" | "attachments" + >, +): MessageDispatchMode { + const mode = resolveMessageDispatchIntent( + projection, + message.dispatchMode, + message.deliveryIntent, + ); + // A provider runs a steered command in place of the turn's task, so commands wait. + return mode.type === "steer_active" && isSlashCommand(message) + ? { type: "queue_after_active" } + : mode; +} + +/** How a message joins active work when it is free to steer. */ export function resolveMessageDispatchIntent( projection: OrchestrationV2ThreadProjection, requestedMode: MessageDispatchMode, diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 00939843c13f1..e27fe09d07d1b 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -92,6 +92,7 @@ import { isPlaceholderThreadTitle } from "./placeholderThreadTitle.ts"; import { combinePullRequestWatchWakes, type PullRequestWatchWake } from "./pullRequestWatch.ts"; import { outputRequestProblem } from "./runOutput.ts"; import { recordThreadOpen } from "@t3tools/shared/paletteSearch"; +import { isSlashCommand } from "@t3tools/shared/composerTrigger"; import { backgroundWorkHoldsCompletion, derivePendingBackgroundWork, @@ -126,6 +127,7 @@ import { isNativeMaintenanceCommand, providerSwitchWaitsForTurn, providerTurnCapabilities, + resolveMessageDispatch, resolveMessageDispatchIntent, } from "./CommandPolicy.ts"; import { CommandReceiptStoreV2, type CommandReceiptV2 } from "./CommandReceiptStore.ts"; @@ -6308,6 +6310,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); } yield* ensureSteeringMessage(input.command, input); + // An explicit restart already gives up the turn, so only steering holds commands back. + if (!input.forceRestart && isSlashCommand(input)) { + return yield* new OrchestratorDispatchError({ + commandId: input.command.commandId, + commandType: input.command.type, + cause: + "Commands must run as a separate turn. Queue it or wait for the active turn to finish.", + }); + } const targetMessage = input.projection.messages.find( (message) => message.id === targetRun.userMessageId, ); @@ -7416,11 +7427,18 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio projection = applyToProjection(projection, event); } let modelSelection = command.modelSelection ?? projection.thread.modelSelection; - let dispatchMode = resolveMessageDispatchIntent( - projection, - command.dispatchMode, - command.deliveryIntent, - ); + // Native goal commands must not steer an existing turn. + const parsedGoalCommand = parseGoalCommand(command); + const goalCommand = + parsedGoalCommand === null || + (yield* goalDriverFor(command, modelSelection.instanceId)) === undefined + ? null + : parsedGoalCommand; + // A goal command keeps the run it was sent at; the goal handling below queues it. + let dispatchMode = + goalCommand === null + ? resolveMessageDispatch(projection, command) + : resolveMessageDispatchIntent(projection, command.dispatchMode, command.deliveryIntent); if (dispatchMode.type === "steer_active" || dispatchMode.type === "restart_active") { const targetRunId = dispatchMode.targetRunId; const target = projection.runs.find((run) => run.id === targetRunId); @@ -7515,13 +7533,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ) { dispatchMode = { type: "queue_after_active" }; } - // Native goal commands must not steer an existing turn. - const parsedGoalCommand = parseGoalCommand(command); - const goalCommand = - parsedGoalCommand === null || - (yield* goalDriverFor(command, modelSelection.instanceId)) === undefined - ? null - : parsedGoalCommand; let queuedRunStop: | { readonly runId: RunId; readonly reason: string; readonly skipsHeldQueue?: true } | undefined; @@ -7672,6 +7683,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const commandNotice = noticeKind === "command" && command.creationSource === "server"; if ( !freshContext && + // Steering refuses a command, so a notice that reads like one stays queued. + !isSlashCommand(command) && (delegatedCompletion !== undefined ? delegatedCompletion.taskIds.every( (id) => @@ -11856,8 +11869,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: "A message that asks for a result can't steer the current turn.", }); } - if (goalCommand !== null) { - yield* ensureGoalCommandSupported(command, queuedMessage, modelSelection.instanceId); + // A steered command replaces the turn's task, so promoting one only moves it first. + if (goalCommand !== null || isSlashCommand(queuedMessage)) { + if (goalCommand !== null) { + yield* ensureGoalCommandSupported(command, queuedMessage, modelSelection.instanceId); + } const goal = projection.providerThreads.find( (candidate) => candidate.id === target?.providerThreadId, )?.goal; @@ -11871,6 +11887,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio payload: { ...queuedRun, queuePosition: 1 }, }); const stops = + goalCommand !== null && target !== undefined && isLiveRun(target) && goalCommandStopsActiveRun(goalCommand, goal?.status ?? null) && @@ -12298,6 +12315,25 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }), }); } + // A command cannot steer, so an edit into one keeps it queued where it is. + if ( + queuedRun.steerWhenReadyRunId !== undefined && + isSlashCommand({ + text: command.text, + attachments: command.attachments ?? queuedMessage.attachments, + }) + ) { + const { steerWhenReadyRunId: _, ...queued } = queuedRun; + yield* emitEvent({ + type: "run.updated", + threadId: command.threadId, + runId: queuedRun.id, + ...(queuedRun.rootNodeId === null ? {} : { nodeId: queuedRun.rootNodeId }), + providerInstanceId: queuedRun.providerInstanceId, + occurredAt: now, + payload: queued, + }); + } // Thread deletion only cleans files the thread still references. const keptAttachmentIds = new Set( (command.attachments ?? queuedMessage.attachments).map((attachment) => attachment.id), @@ -14182,7 +14218,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ); - /** Puts a queued goal command first and, given a target, stops the run in its way. */ + /** Puts a queued command first and, given a target, stops the run in its way. */ const stopRunForQueuedCommand = Effect.fn("Orchestrator.stopRunForQueuedCommand")( function* (input: { readonly command: Extract< diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index cc14fde257da8..3ef67192ceb77 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -711,14 +711,15 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function* it.effect.each([ { notice: "delegated task question", goal: null, steers: true }, + { notice: "delegated task question", goal: null, steers: false, summary: "/review is ready" }, { notice: "background command", goal: "active", steers: true }, { notice: "background command", goal: null, steers: false }, ] as const)( "a $notice notice steers into the running turn: $steers (goal $goal)", - ({ notice, goal, steers }) => + ({ notice, goal, steers, ...row }) => Effect.gen(function* () { const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness( - `notice-steer-${notice.replaceAll(" ", "-")}-${goal ?? "none"}`, + `notice-steer-${notice.replaceAll(" ", "-")}-${goal ?? "none"}-${steers}`, ); yield* Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; @@ -762,7 +763,7 @@ it.effect.each([ childThreadId: ThreadId.make("thread:question-child"), }, outcome: "updated" as const, - summary: "Delegated task has a question", + summary: "summary" in row ? row.summary : "Delegated task has a question", } : { source: { kind: "command" as const }, @@ -945,6 +946,7 @@ it.effect.each( const edited = (yield* orchestrator.getThreadProjection(threadId)).runs.find( (candidate) => candidate.userMessageId === MessageId.make("message:edited-steer"), )!; + assert.equal(edited.steerWhenReadyRunId, run.id); yield* orchestrator.dispatch({ type: "queued-run.edit", commandId: CommandId.make("edit-steer-to-compact"), @@ -952,6 +954,11 @@ it.effect.each( runId: edited.id, text: "/compact", }); + const compact = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (candidate) => candidate.id === edited.id, + )!; + assert.isUndefined(compact.steerWhenReadyRunId); + assert.equal(compact.queuePosition, edited.queuePosition); } if (direct) { yield* orchestrator.dispatch({ @@ -998,16 +1005,18 @@ it.effect.each( const maintenance = (yield* orchestrator.getThreadProjection(threadId)).runs.find( (candidate) => candidate.userMessageId === MessageId.make(`message:${text}`), )!; - const error = yield* orchestrator - .dispatch({ - type: "queued-message.promote-to-steer", - commandId: CommandId.make(`promote-${text}`), - threadId, - queuedRunId: maintenance.id, - targetRunId: run.id, - }) - .pipe(Effect.flip); - assert.equal(error._tag, "OrchestratorDispatchError"); + yield* orchestrator.dispatch({ + type: "queued-message.promote-to-steer", + commandId: CommandId.make(`promote-${text}`), + threadId, + queuedRunId: maintenance.id, + targetRunId: run.id, + }); + const promoted = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (candidate) => candidate.id === maintenance.id, + )!; + assert.equal(promoted.status, "queued"); + assert.equal(promoted.queuePosition, 1); } const command = { type: "queued-message.promote-to-steer" as const, @@ -3165,15 +3174,12 @@ it.effect.each([undefined, false, true])( const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; const threadId = yield* startFirstTurn; yield* send("queued", "queued", "queue"); - const sending = send("goal", "/goal all tests pass", "auto"); - if (nativeGoals === false) { - yield* Effect.flip(sending); - } else yield* sending; + yield* send("goal", "/goal all tests pass", "auto"); yield* worker.drain(); assert.deepEqual(steered, []); assert.deepEqual(yield* read(threadId), { - queue: ["queued"], + queue: nativeGoals === false ? ["queued", "/goal all tests pass"] : ["queued"], started: nativeGoals === false ? ["first"] : ["first", "/goal all tests pass"], stopRequested: nativeGoals !== false, }); @@ -3472,6 +3478,70 @@ it.effect("queues a goal clear without stopping work when no goal drives it", () }), ); +it.effect("promoting a queued /context moves it first and does not steer", () => + Effect.gen(function* () { + const { started, steered, layer, startFirstTurn, send, read } = + yield* goalHarness("slash-promote"); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + yield* send("queued", "queued", "queue"); + yield* send("context", "/context", "queue"); + const queuedRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.userMessageId === MessageId.make("message:context"), + )!; + yield* orchestrator.dispatch({ + type: "queued-message.promote-to-steer", + commandId: CommandId.make("promote"), + threadId, + queuedRunId: queuedRun.id, + targetRunId: started[0]!.runId, + }); + yield* worker.drain(); + + assert.deepEqual(steered, []); + assert.deepEqual(yield* read(threadId), { + queue: ["/context", "queued"], + started: ["first"], + stopRequested: false, + }); + }).pipe(Effect.provide(layer)); + }), +); + +it.effect("restarts the turn for a slash command sent as an explicit restart", () => + Effect.gen(function* () { + const { started, steered, interrupted, layer, startFirstTurn } = + yield* nextTurnSelectionHarness("slash-restart", true); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("restart-context"), + threadId, + messageId: MessageId.make("message:restart-context"), + text: "/context", + attachments: [], + modelSelection: runSelection, + dispatchMode: { type: "restart_active", targetRunId: started[0]!.runId }, + createdBy: "user", + creationSource: "web", + }); + yield* worker.drain(); + + assert.deepEqual(steered, []); + assert.lengthOf(interrupted, 1); + assert.deepEqual( + started.map((turn) => turn.message.text), + ["first", "/context"], + ); + }).pipe(Effect.provide(layer)); + }), +); + it.effect("promotes a queued goal by stopping the running turn", () => Effect.gen(function* () { const { started, steered, layer, startFirstTurn, send, read } = @@ -3504,6 +3574,38 @@ it.effect("promotes a queued goal by stopping the running turn", () => }), ); +it.effect("stops the running turn for a goal an agent steers into it", () => + Effect.gen(function* () { + const { started, steered, layer, startFirstTurn, read } = yield* goalHarness("goal-raw-steer"); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + // Agent sends carry a raw steer target and no delivery intent. + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("goal"), + threadId, + messageId: MessageId.make("message:goal"), + text: "/goal ship it", + attachments: [], + modelSelection: runSelection, + dispatchMode: { type: "steer_active", targetRunId: started[0]!.runId }, + createdBy: "agent", + creationSource: "server", + }); + yield* worker.drain(); + + assert.deepEqual(steered, []); + assert.deepEqual(yield* read(threadId), { + queue: [], + started: ["first", "/goal ship it"], + stopRequested: true, + }); + }).pipe(Effect.provide(layer)); + }), +); + // A fresh message skips compaction as its own turn, which steering a running turn would not. it.effect.each(["next", "/goal ship it", "fresh next"])( "promoting %s into a compaction stops it and sends it next", diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index 2a3a8e5510550..73eaabdde2016 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -913,7 +913,7 @@ it.effect("keeps native maintenance commands out of steering and restart message attachments: [], dispatchMode: { type: scenario.mode, targetRunId: targetRun.id }, }); - if (scenario.name.startsWith("steer-")) { + if (scenario.mode === "steer_active") { yield* dispatch; const queued = (yield* threads.getThreadProjection(launched.threadId)).runs[1]; assert.equal(queued?.status, "queued"); diff --git a/apps/web/src/components/chat/QueuedRunsControl.tsx b/apps/web/src/components/chat/QueuedRunsControl.tsx index fb82f9c858d61..d8318b7279e7d 100644 --- a/apps/web/src/components/chat/QueuedRunsControl.tsx +++ b/apps/web/src/components/chat/QueuedRunsControl.tsx @@ -5,16 +5,18 @@ import { } from "@t3tools/client-runtime/state/runtime"; import { deriveThreadQueueWorkflowState } from "@t3tools/client-runtime/state/thread-workflows"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; +import { isSlashCommand } from "@t3tools/shared/composerTrigger"; import { isAttachmentOnlyBootstrapPrompt, replaceComposerContextReferences, } from "@t3tools/shared/composerContextReferences"; -import type { - ChatAttachment as ContractChatAttachment, - EnvironmentId, - MessageId, - RunId, - ThreadId, +import { + parseGoalCommand, + type ChatAttachment as ContractChatAttachment, + type EnvironmentId, + type MessageId, + type RunId, + type ThreadId, } from "@t3tools/contracts"; import { resolveUserMessagePresentation } from "@t3tools/client-runtime/user-message"; import { Link } from "@tanstack/react-router"; @@ -273,6 +275,9 @@ export function QueuedRunsControl({ replaceComposerContextReferences(item.text, (reference) => reference.label), ).trim(); const isEditing = item.runId !== null && item.runId === props.editingRunId; + // The server decides on the agent's text, and a goal command can stop the turn. + const sentText = { text: item.message?.text ?? item.text, attachments: item.attachments }; + const movesCommandFirst = isSlashCommand(sentText) && parseGoalCommand(sentText) === null; return (
  • diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 0e48b30d674da..4f60fef9f6088 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -12458,5 +12458,7 @@ "27d76249d09eb69f": "Review-Leitfaden bereit", "faa3bb26abb39c93": "Review-Leitfaden fehlgeschlagen", "b7df38b7d8792d78": "Leitfaden öffnen", - "9e91e9a77b664e4e": "Review-Leitfaden konnte nicht gestartet werden" + "9e91e9a77b664e4e": "Review-Leitfaden konnte nicht gestartet werden", + "d8aaf932f90429c4": "Diesen Befehl an den Anfang der Warteschlange verschieben ({shortcut})", + "425ab15036aec8a4": "Diesen Befehl an den Anfang der Warteschlange verschieben" } diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index e5d8d3dc2ed21..6453de11f9da0 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -12467,5 +12467,7 @@ "27d76249d09eb69f": "Review guide ready", "faa3bb26abb39c93": "Review guide failed", "b7df38b7d8792d78": "Open guide", - "9e91e9a77b664e4e": "Could not start a review guide" + "9e91e9a77b664e4e": "Could not start a review guide", + "d8aaf932f90429c4": "Move this command to the front of the queue ({shortcut})", + "425ab15036aec8a4": "Move this command to the front of the queue" } diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 4a2868a7e97dc..a73a02ec3bcc9 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -12453,5 +12453,7 @@ "27d76249d09eb69f": "Guía de revisión lista", "faa3bb26abb39c93": "Falló la guía de revisión", "b7df38b7d8792d78": "Abrir guía", - "9e91e9a77b664e4e": "No se pudo iniciar una guía de revisión" + "9e91e9a77b664e4e": "No se pudo iniciar una guía de revisión", + "d8aaf932f90429c4": "Mover este comando al principio de la cola ({shortcut})", + "425ab15036aec8a4": "Mover este comando al principio de la cola" } diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index a0962e52bed39..95ea50d6bf22d 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -12458,5 +12458,7 @@ "27d76249d09eb69f": "Guide de revue prêt", "faa3bb26abb39c93": "Échec du guide de revue", "b7df38b7d8792d78": "Ouvrir le guide", - "9e91e9a77b664e4e": "Impossible de démarrer un guide de revue" + "9e91e9a77b664e4e": "Impossible de démarrer un guide de revue", + "d8aaf932f90429c4": "Placer cette commande en tête de la file d’attente ({shortcut})", + "425ab15036aec8a4": "Placer cette commande en tête de la file d’attente" } diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 0c149c28fbe91..96bf9c7c7bf48 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -12407,5 +12407,7 @@ "27d76249d09eb69f": "レビューガイドの準備ができました", "faa3bb26abb39c93": "レビューガイドの作成に失敗しました", "b7df38b7d8792d78": "ガイドを開く", - "9e91e9a77b664e4e": "レビューガイドを開始できませんでした" + "9e91e9a77b664e4e": "レビューガイドを開始できませんでした", + "d8aaf932f90429c4": "このコマンドをキューの先頭に移動 ({shortcut})", + "425ab15036aec8a4": "このコマンドをキューの先頭に移動" } diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index c01191b387b4f..d7b1a7628ffc6 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -12402,5 +12402,7 @@ "27d76249d09eb69f": "검토 가이드 준비됨", "faa3bb26abb39c93": "검토 가이드 실패", "b7df38b7d8792d78": "가이드 열기", - "9e91e9a77b664e4e": "검토 가이드를 시작할 수 없습니다" + "9e91e9a77b664e4e": "검토 가이드를 시작할 수 없습니다", + "d8aaf932f90429c4": "이 명령을 대기열 맨 앞으로 이동 ({shortcut})", + "425ab15036aec8a4": "이 명령을 대기열 맨 앞으로 이동" } diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 5feb95d75c3da..5097324486fb8 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -12458,5 +12458,7 @@ "27d76249d09eb69f": "Guia de revisão pronto", "faa3bb26abb39c93": "O guia de revisão falhou", "b7df38b7d8792d78": "Abrir guia", - "9e91e9a77b664e4e": "Não foi possível iniciar um guia de revisão" + "9e91e9a77b664e4e": "Não foi possível iniciar um guia de revisão", + "d8aaf932f90429c4": "Mover este comando para o início da fila ({shortcut})", + "425ab15036aec8a4": "Mover este comando para o início da fila" } diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 65a8eede879fa..4c19189200eb5 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -12458,5 +12458,7 @@ "27d76249d09eb69f": "Гид по ревью готов", "faa3bb26abb39c93": "Не удалось создать гид по ревью", "b7df38b7d8792d78": "Открыть гид", - "9e91e9a77b664e4e": "Не удалось запустить гид по ревью" + "9e91e9a77b664e4e": "Не удалось запустить гид по ревью", + "d8aaf932f90429c4": "Переместить эту команду в начало очереди ({shortcut})", + "425ab15036aec8a4": "Переместить эту команду в начало очереди" } diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 081857c5dae81..7add0fa009b1d 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -12465,5 +12465,7 @@ "27d76249d09eb69f": "Granskningsguiden är klar", "faa3bb26abb39c93": "Granskningsguiden misslyckades", "b7df38b7d8792d78": "Öppna guiden", - "9e91e9a77b664e4e": "Kunde inte starta en granskningsguide" + "9e91e9a77b664e4e": "Kunde inte starta en granskningsguide", + "d8aaf932f90429c4": "Flytta det här kommandot först i kön ({shortcut})", + "425ab15036aec8a4": "Flytta det här kommandot först i kön" } diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 17d0dd6a93303..5a5c7160230de 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -12484,5 +12484,7 @@ "27d76249d09eb69f": "审查导览已就绪", "faa3bb26abb39c93": "审查导览生成失败", "b7df38b7d8792d78": "打开导览", - "9e91e9a77b664e4e": "无法开始生成审查导览" + "9e91e9a77b664e4e": "无法开始生成审查导览", + "d8aaf932f90429c4": "将此命令移到队列最前面 ({shortcut})", + "425ab15036aec8a4": "将此命令移到队列最前面" } diff --git a/docs/user/composer.md b/docs/user/composer.md index 94b0219e5ab5a..53017052a2a01 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -69,6 +69,10 @@ are saved on the server and can be edited or removed before they send. When Enter sends, `Cmd+Enter` on macOS or `Ctrl+Enter` on Windows and Linux uses the opposite action: it steers when your default is Queue and queues when your default is Steer. +A slash command such as `/compact` or `/context` waits for the current turn to +finish, because a command steered into a turn would replace the agent's task. +Sending a queued command now moves it to the front of the queue. [Goal](#goals) +commands are the exception: some can stop the current turn. If your **Send shortcut** requires `Cmd+Enter` or `Ctrl+Enter`, that shortcut uses your default follow-up behavior; add **Shift** to use the opposite action. This applies only to multiline messages when you choose the multiline send option. @@ -271,8 +275,9 @@ shortcut described above. On web and desktop, queued messages appear at the end of the thread as dashed messages that have not been sent yet. On mobile they appear above the composer. Each shows its text and any attached -images. **Send now** sends a message right away, into the running turn if there is one. You can -also edit or remove it. +images. **Send now** sends a message right away, into the running turn if there is one. While a +turn runs, a slash command moves to the front of the queue instead. You can also edit or +remove it. If you stop the agent or the server restarts, queued messages keep their order and are held. Press **Resume** in an empty composer to continue. For stopped runs and usage limits, diff --git a/packages/shared/src/composerTrigger.ts b/packages/shared/src/composerTrigger.ts index 96a0a877d14df..2a95d6b34cd0a 100644 --- a/packages/shared/src/composerTrigger.ts +++ b/packages/shared/src/composerTrigger.ts @@ -137,6 +137,14 @@ export function replaceTextRange( return { text: nextText, cursor: safeStart + replacement.length }; } +/** A message that only invokes a slash command, such as `/context all`, not a path like `/src/a.ts`. */ +export function isSlashCommand(message: { + readonly text: string; + readonly attachments: ReadonlyArray; +}): boolean { + return message.attachments.length === 0 && /^\/[\w:-]+(?:\s|$)/u.test(message.text.trim()); +} + /** `/clear` as the whole message arms a fresh session instead of sending. */ export function isClearComposerCommand(text: string): boolean { return /^\/clear\s*$/i.test(text.trim()); diff --git a/scripts/scenarios/steered-compact-waits-for-turn.e2e.ts b/scripts/scenarios/steered-compact-waits-for-turn.e2e.ts new file mode 100644 index 0000000000000..7ed990805fd22 --- /dev/null +++ b/scripts/scenarios/steered-compact-waits-for-turn.e2e.ts @@ -0,0 +1,71 @@ +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; + +import { T3_HOME } from "../e2e.config.ts"; +import { makeState, runPromise, test, WEB } from "./t3.ts"; + +const SettingsJson = Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)); +const decodeSettings = Schema.decodeEffect(SettingsJson); +const encodeSettings = Schema.encodeEffect(SettingsJson); + +const threadRuntimeSettings = Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const settingsPath = (yield* Path.Path).join(T3_HOME, "userdata/settings.json"); + const original = yield* fs.readFileString(settingsPath); + const settings = yield* decodeSettings(original); + return { + supervise: fs.writeFileString( + settingsPath, + yield* encodeSettings({ ...settings, defaultRuntimeMode: "approval-required" }), + ), + restore: fs.writeFileString(settingsPath, original), + }; +}); + +test("/compact sent while the agent works waits for the turn", WEB, async ({ t3, app, screen }) => { + const project = await t3.project("demo"); + // The showcase recording streams for several seconds, long enough to send into its turn. + const thread = await t3.thread({ + project, + title: "Long work", + messages: ["Show me around"], + model: "showcase", + }); + await t3.open(thread); + + const composer = screen.getByRole("textbox"); + await composer.tap(); + await composer.pressSequentially("Show me again"); + await composer.press("Enter"); + await expect(screen.getByRole("button", "Stop generation")).toBeVisible(); + + // The trailing space closes the slash menu so Enter sends instead of picking a command. + await composer.pressSequentially("/compact "); + await composer.press("Enter"); + await app.screenshot("compact-sent"); + await expect(screen.getByRole("button", "Edit queued message")).toBeVisible(); + + const settings = await runPromise(threadRuntimeSettings); + try { + // An approval holds this turn open, so the queued command stays put while Send now is hovered. + await runPromise(settings.supervise); + const waiting = await t3.thread({ + project, + title: "Waiting work", + messages: ["Change the file"], + model: "approval", + }); + await runPromise(makeState(T3_HOME).cli(["thread", "send", waiting.threadId, "/compact"])); + await t3.open(waiting); + await screen.getByRole("button", "Send now").hover(); + await expect( + screen.getByText("Move this command to the front of the queue", { exact: false }), + ).toBeVisible(); + await app.screenshot("send-now-tooltip"); + } finally { + await runPromise(settings.restore); + } +}); From 989d7ec882aa1b7e510cd44f93ab5fe61368058b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 05:17:55 -0800 Subject: [PATCH 29/39] perf(server): push and commit-and-push read the full git status once instead of three times (#40305) --- apps/server/src/git/GitManager.test.ts | 2 +- apps/server/src/git/GitManager.ts | 4 +++- apps/server/src/vcs/GitVcsDriver.ts | 2 ++ apps/server/src/vcs/GitVcsDriverCore.ts | 24 +++++++++++++++++------- 4 files changed, 23 insertions(+), 9 deletions(-) diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index 9dc3407597a4f..064427a3727f5 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -4198,7 +4198,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { ), ); yield* Deferred.await(gate.reached); - NodeFS.writeFileSync(NodePath.join(repoDir, ".git", "index.lock"), ""); + NodeFS.appendFileSync(NodePath.join(repoDir, ".git", "config"), "\n[broken\n"); yield* Deferred.succeed(gate.release, undefined); const result = yield* Fiber.join(action); diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index 9db4fbfc27755..dab6d4d20924e 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -2256,7 +2256,9 @@ export const make = Effect.gen(function* () { const finalStatus = result.action === "commit" ? null - : yield* gitCore.statusDetails(cwd).pipe(Effect.orElseSucceed(() => null)); + : yield* gitCore + .statusDetailsRemote(cwd, { refreshUpstream: false, includeAheadOfDefault: false }) + .pipe(Effect.orElseSucceed(() => null)); if (finalStatus?.branch) { finalBranchContext = { branch: finalStatus.branch, diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index 700ad3b3571c9..f341ebd987a6c 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -337,6 +337,8 @@ export interface GitSetBranchUpstreamInput { export interface GitRemoteStatusOptions { readonly refreshUpstream?: boolean; + /** False skips the base-branch lookup and reports `aheadOfDefaultCount` as 0. */ + readonly includeAheadOfDefault?: boolean; } /** diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 7c4363b1647be..7fe1dab187ac5 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -2540,6 +2540,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const readStatusDetailsRemote = Effect.fn("readStatusDetailsRemote")(function* ( cwd: string, refreshUpstream: boolean, + includeAheadOfDefault = true, ) { const branchResult = yield* executeGitWithStableDiagnostics( "GitVcsDriver.statusDetailsRemote.branch", @@ -2640,7 +2641,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* (branch === defaultBranch || (defaultBranch === null && (branch === "main" || branch === "master"))); const aheadOfDefaultCount = - branch && !isDefaultBranch + branch && !isDefaultBranch && includeAheadOfDefault ? upstreamRef === null ? aheadCount : yield* computeAheadCountAgainstBase(cwd, branch).pipe(Effect.orElseSucceed(() => 0)) @@ -3004,22 +3005,29 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return yield* readStatusDetailsLocal(cwd, options); }); - const statusDetails: GitVcsDriver.GitVcsDriver["Service"]["statusDetails"] = Effect.fn( - "statusDetails", - )(function* (cwd) { - yield* refreshStatusUpstreamIfStale(cwd).pipe( + const refreshStatusUpstream = (cwd: string) => + refreshStatusUpstreamIfStale(cwd).pipe( Effect.catchTags({ GitCommandError: (error) => isMissingGitCwdError(error) ? Effect.void : Effect.fail(error), }), Effect.ignoreCause({ log: true }), ); + + const statusDetails: GitVcsDriver.GitVcsDriver["Service"]["statusDetails"] = Effect.fn( + "statusDetails", + )(function* (cwd) { + yield* refreshStatusUpstream(cwd); return yield* readStatusDetailsLocal(cwd); }); const statusDetailsRemote: GitVcsDriver.GitVcsDriver["Service"]["statusDetailsRemote"] = Effect.fn("statusDetailsRemote")(function* (cwd, options) { - return yield* readStatusDetailsRemote(cwd, options?.refreshUpstream !== false); + return yield* readStatusDetailsRemote( + cwd, + options?.refreshUpstream !== false, + options?.includeAheadOfDefault !== false, + ); }); const status: GitVcsDriver.GitVcsDriver["Service"]["status"] = (input) => @@ -3658,7 +3666,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const pushCurrentBranch: GitVcsDriver.GitVcsDriver["Service"]["pushCurrentBranch"] = Effect.fn( "pushCurrentBranch", )(function* (cwd, fallbackBranch, options) { - const details = yield* statusDetails(cwd); + // Refresh first so the branch, upstream and divergence reads below stay close together. + yield* refreshStatusUpstream(cwd); + const details = yield* readStatusDetailsRemote(cwd, false, false); const branch = details.branch ?? fallbackBranch; if (!branch) { return yield* new GitCommandError({ From 0c921e1fdf6feda7d1bab2be83e3916c6f4509c2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 05:28:23 -0800 Subject: [PATCH 30/39] fix(server): ACP session/load replay no longer pins background work (#40328) --- .../Adapters/AcpAdapterV2.test.ts | 89 +++++++++++ packages/provider-acp/src/server/adapter.ts | 149 ++++++++++-------- 2 files changed, 173 insertions(+), 65 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 4946377c94502..d79257944c8e9 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -9234,6 +9234,95 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect("session/load replay does not leave post-settle background work pending", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + const instanceId = ProviderInstanceId.make("acp-test"); + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdateHandler: Parameters[0] | undefined; + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + enablePostSettleContinuation: true, + normalizeToolCall: normalizeXAiAcpToolCallState, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapRuntime: (runtime) => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdateHandler = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + }), + }), + }, + continuationRequests: { offer: () => Effect.void }, + }); + const threadId = ThreadId.make("thread-acp-load-replay-background"); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-load-replay-background"), + modelSelection, + runtimePolicy, + }); + if (runtime.hasPendingBackgroundWork === undefined) { + return yield* Effect.die("ACP runtime must expose hasPendingBackgroundWork."); + } + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + assert.isFalse(yield* runtime.hasPendingBackgroundWork); + assert.isDefined(sessionUpdateHandler, "session update handler must be wired"); + + // A large session/load replays its tail after the session is active. + yield* sessionUpdateHandler!({ + sessionId: "mock-session-1", + _meta: { isReplay: true }, + update: { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "old reply from history" }, + }, + }); + yield* sessionUpdateHandler!({ + sessionId: "mock-session-1", + _meta: { isReplay: true }, + update: { + sessionUpdate: "tool_call", + toolCallId: "replayed-tool-1", + title: "run_command", + kind: "execute", + status: "completed", + rawInput: { command: "echo old" }, + }, + }); + yield* Effect.yieldNow; + + assert.isFalse( + yield* runtime.hasPendingBackgroundWork, + "replayed history must not pin background work", + ); + const snapshot = yield* runtime.readThreadSnapshot({ providerThread }); + assert.deepEqual( + snapshot.messages.map((message) => message.text), + ["old reply from history"], + ); + }).pipe(Effect.provide(layerTest)), + ); + it.effect("projects completed-root carryover eagerly and drain cannot resurrect it", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index cf7bb6c0f92fd..a712d40629e60 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -87,6 +87,7 @@ import { mergeToolCallState, parsePermissionRequest, parseSessionUpdateEvent, + sessionUpdateIsReplay, toolCallVisibleOutputChanged, withTrackedPermissionToolCall, type AcpPlanUpdate, @@ -5650,6 +5651,80 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ), ); + const recordLoadedHistory = Effect.fnUntraced(function* ( + notification: EffectAcpSchema.SessionNotification, + live: boolean, + ) { + const update = notification.update; + if ( + notification.sessionId !== + ((yield* Ref.get(loadingSessionId)) ?? (yield* Ref.get(activeSessionId))) + ) + return; + if ( + update.sessionUpdate === "user_message_chunk" || + update.sessionUpdate === "agent_message_chunk" || + update.sessionUpdate === "agent_thought_chunk" + ) { + const text = acpContentBlockDisplayText(update.content); + if (text === undefined) return; + const lateBackgroundMutations = + update.content.type === "text" + ? (flavor.extractBackgroundToolMutation?.(text) ?? []) + : []; + if (live) { + for (const lateBackgroundMutation of lateBackgroundMutations) { + yield* applyLateBackgroundMutation(notification.sessionId, lateBackgroundMutation); + } + } + if (lateBackgroundMutations.length === 0 && !acpIsMonitorChatter(text)) { + yield* appendLoadedHistory( + notification, + update.sessionUpdate === "user_message_chunk" + ? "user" + : update.sessionUpdate === "agent_thought_chunk" + ? "thought" + : "assistant", + text, + ); + } + } else if ( + update.sessionUpdate === "user_message" || + update.sessionUpdate === "agent_message" || + update.sessionUpdate === "agent_thought" + ) { + if (update.content === undefined) return; + const text = (update.content ?? []) + .flatMap((content) => { + const display = acpContentBlockDisplayText(content); + return display === undefined ? [] : [display]; + }) + .join("\n"); + yield* appendLoadedHistory( + notification, + update.sessionUpdate === "user_message" + ? "user" + : update.sessionUpdate === "agent_thought" + ? "thought" + : "assistant", + text, + true, + ); + } else if ( + update.sessionUpdate === "tool_call" || + update.sessionUpdate === "tool_call_update" || + update.sessionUpdate === "plan" || + update.sessionUpdate === "plan_update" || + update.sessionUpdate === "plan_removed" + ) { + yield* Ref.update(snapshot, (current) => ({ + ...current, + loadingRole: null, + loadingMessageId: null, + })); + } + }); + const handleSessionUpdate = Effect.fnUntraced(function* ( notification: EffectAcpSchema.SessionNotification, ) { @@ -5898,71 +5973,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (wakeOutcome.stopProcessing) { return; } - if ( - notification.sessionId !== - ((yield* Ref.get(loadingSessionId)) ?? (yield* Ref.get(activeSessionId))) - ) - return; - if ( - update.sessionUpdate === "user_message_chunk" || - update.sessionUpdate === "agent_message_chunk" || - update.sessionUpdate === "agent_thought_chunk" - ) { - const text = acpContentBlockDisplayText(update.content); - if (text === undefined) return; - const lateBackgroundMutations = - update.content.type === "text" - ? (flavor.extractBackgroundToolMutation?.(text) ?? []) - : []; - for (const lateBackgroundMutation of lateBackgroundMutations) { - yield* applyLateBackgroundMutation(notification.sessionId, lateBackgroundMutation); - } - if (lateBackgroundMutations.length === 0 && !acpIsMonitorChatter(text)) { - yield* appendLoadedHistory( - notification, - update.sessionUpdate === "user_message_chunk" - ? "user" - : update.sessionUpdate === "agent_thought_chunk" - ? "thought" - : "assistant", - text, - ); - } - } else if ( - update.sessionUpdate === "user_message" || - update.sessionUpdate === "agent_message" || - update.sessionUpdate === "agent_thought" - ) { - if (update.content === undefined) return; - const text = (update.content ?? []) - .flatMap((content) => { - const display = acpContentBlockDisplayText(content); - return display === undefined ? [] : [display]; - }) - .join("\n"); - yield* appendLoadedHistory( - notification, - update.sessionUpdate === "user_message" - ? "user" - : update.sessionUpdate === "agent_thought" - ? "thought" - : "assistant", - text, - true, - ); - } else if ( - update.sessionUpdate === "tool_call" || - update.sessionUpdate === "tool_call_update" || - update.sessionUpdate === "plan" || - update.sessionUpdate === "plan_update" || - update.sessionUpdate === "plan_removed" - ) { - yield* Ref.update(snapshot, (current) => ({ - ...current, - loadingRole: null, - loadingMessageId: null, - })); - } + yield* recordLoadedHistory(notification, true); return; } if (context.finalized) return; @@ -7016,6 +7027,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( Effect.fnUntraced( function* (rawNotification: EffectAcpSchema.SessionNotification) { if (flavor.ignoreSessionUpdate?.(rawNotification) === true) return; + // Replayed history feeds snapshots only; it must not drive live turn or wake state. + if (sessionUpdateIsReplay(rawNotification)) { + yield* recordLoadedHistory( + flavor.normalizeSessionUpdate?.(rawNotification) ?? rawNotification, + false, + ); + return; + } yield* notePromptProgress(rawNotification); const nativePromptId = flavor.forkFromTurn?.nativeTurnId(rawNotification); if (nativePromptId !== undefined) { From 232f52c8db1998fc566c4bb5940db6a12c898c8d Mon Sep 17 00:00:00 2001 From: Arif Ali <51419655+arifali123@users.noreply.github.com> Date: Sat, 21 Nov 2026 05:28:38 -0800 Subject: [PATCH 31/39] fix(mobile): confirming a push to the default branch no longer opens the thread a second time (#40311) Co-authored-by: Orin Co-authored-by: Julius Marminge --- .../features/threads/git/GitConfirmSheet.tsx | 10 +++-- .../thread-inspector-navigation.test.tsx | 41 ++++++++++++++++++- .../threads/thread-inspector-navigation.ts | 38 +++++++++++++---- 3 files changed, 74 insertions(+), 15 deletions(-) diff --git a/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx b/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx index b916b49697fc5..1da0ec450a572 100644 --- a/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx +++ b/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx @@ -3,7 +3,7 @@ import { sourceControlClients } from "@t3tools/client-runtime/source-control-cli import { resolveAutoFeatureBranchName } from "@t3tools/shared/git"; import * as Arr from "effect/Array"; import * as Result from "effect/Result"; -import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native"; +import { useNavigation, type StaticScreenProps } from "@react-navigation/native"; import { useGT, useMessages } from "gt-react-native"; import { useCallback, useMemo } from "react"; import { View } from "react-native"; @@ -20,6 +20,7 @@ import { type GitRepositoryRouteParams, } from "../../../state/thread-git-target"; import { vcsEnvironment } from "../../../state/vcs"; +import { useReturnToThread } from "../thread-inspector-navigation"; import { SheetActionButton } from "./gitSheetComponents"; type GitConfirmSheetProps = StaticScreenProps< @@ -38,6 +39,7 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) { const gt = useGT(); const messages = useMessages(); const navigation = useNavigation(); + const returnToThread = useReturnToThread(); const repository = gitRepositoryTargetFromRoute(props.route.params); const gitState = useSelectedThreadGitState(repository); const gitActions = useSelectedThreadGitActions(repository); @@ -89,7 +91,7 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) { const continuePendingAction = async () => { if (!canWriteSourceControl || !confirmAction) return; - navigation.dispatch(StackActions.replace("Thread", { environmentId, threadId })); + returnToThread({ environmentId, threadId }); await gitActions.onRunSelectedThreadGitAction({ action: confirmAction, ...(params.commitMessage ? { commitMessage: params.commitMessage } : {}), @@ -99,7 +101,7 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) { const movePendingActionToFeatureBranch = useCallback(async () => { if (!canCreateFeatureBranch || !confirmAction) return; - navigation.dispatch(StackActions.replace("Thread", { environmentId, threadId })); + returnToThread({ environmentId, threadId }); if (includesCommit) { await gitActions.onRunSelectedThreadGitAction({ @@ -131,7 +133,7 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) { gitState.selectedThreadBranches, includesCommit, params, - navigation, + returnToThread, environmentId, threadId, ]); diff --git a/apps/mobile/src/features/threads/thread-inspector-navigation.test.tsx b/apps/mobile/src/features/threads/thread-inspector-navigation.test.tsx index 404d28184d7b8..f2398d6e1fc90 100644 --- a/apps/mobile/src/features/threads/thread-inspector-navigation.test.tsx +++ b/apps/mobile/src/features/threads/thread-inspector-navigation.test.tsx @@ -29,7 +29,7 @@ vi.mock("@react-navigation/native", async () => { }; }); -import { useOpenThreadInspector } from "./thread-inspector-navigation"; +import { useOpenThreadInspector, useReturnToThread } from "./thread-inspector-navigation"; import { useOpenLinkedThread, useOpenLinkedThreadRead } from "./useOpenLinkedThread"; const requireNavigation = NodeModule.createRequire( @@ -45,7 +45,15 @@ function setup(fromAgents: boolean, fullscreen = false, inspectorSupported = tru (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; const router = StackRouter({}); const options = { - routeNames: ["Home", "Thread", "ThreadAgents", "ThreadInspectorFullscreen", "LinkedThread"], + routeNames: [ + "Home", + "Thread", + "ThreadAgents", + "ThreadInspectorFullscreen", + "LinkedThread", + "ThreadReview", + "GitConfirm", + ], routeParamList: {}, routeGetIdList: {}, }; @@ -70,14 +78,17 @@ function setup(fromAgents: boolean, fullscreen = false, inspectorSupported = tru let openInspector: ReturnType; let openLinkedThread: ReturnType; let openLinkedThreadRead: ReturnType; + let returnToThread: ReturnType; function Probe() { const open = useOpenThreadInspector(); const openLinked = useOpenLinkedThread(); const openLinkedRead = useOpenLinkedThreadRead(); + const returnTo = useReturnToThread(); useLayoutEffect(() => { openInspector = open; openLinkedThread = openLinked; openLinkedThreadRead = openLinkedRead; + returnToThread = returnTo; }); return null; } @@ -103,6 +114,9 @@ function setup(fromAgents: boolean, fullscreen = false, inspectorSupported = tru openLinkedRead(...input: Parameters) { act(() => openLinkedThreadRead(...input)); }, + returnTo(thread: Parameters[0]) { + act(() => returnToThread(thread)); + }, [Symbol.dispose]() { act(() => root.unmount()); }, @@ -190,6 +204,29 @@ it.each([ }, ); +it.each([ + { confirmFrom: "parent", routes: ["Home", "Thread"] }, + // A side thread's review, opened from the parent's inspector, sits above the parent's route. + { confirmFrom: "child", routes: ["Home", "Thread", "ThreadReview", "Thread"] }, +])( + "returns from a Git confirmation to the $confirmFrom thread without replacing another", + ({ confirmFrom, routes }) => { + using screen = setup(false); + const inspector = { type: "device", ...screen.source } as const; + screen.open(inspector); + const thread = { ...screen.source, threadId: confirmFrom }; + if (confirmFrom !== "parent") screen.dispatch(StackActions.push("ThreadReview", thread)); + screen.dispatch(StackActions.push("GitConfirm", thread)); + screen.returnTo(thread); + expect(screen.state.routes.map((route) => route.name)).toEqual(routes); + expect(screen.state.routes[1]).toMatchObject({ + key: screen.parentKey, + params: { ...screen.source, prompt: "retained prompt", inspector }, + }); + expect(screen.state.routes.at(-1)?.params).toMatchObject(thread); + }, +); + it("switches between subagents and devices in the same parent route", () => { using screen = setup(false); screen.open({ type: "thread", environmentId: screen.source.environmentId, threadId: "child" }); diff --git a/apps/mobile/src/features/threads/thread-inspector-navigation.ts b/apps/mobile/src/features/threads/thread-inspector-navigation.ts index 966dd1a92a632..04fc59ed636e1 100644 --- a/apps/mobile/src/features/threads/thread-inspector-navigation.ts +++ b/apps/mobile/src/features/threads/thread-inspector-navigation.ts @@ -41,15 +41,7 @@ export function useOpenThreadInspector() { if (presentation === "full-screen") return false; if (openInInspector) openInInspector(target); else { - const parent = navigation.getState()?.routes.findLast((route) => route.name === "Thread"); - if ( - !parent?.params || - !("environmentId" in parent.params) || - parent.params.environmentId !== source.environmentId || - !("threadId" in parent.params) || - parent.params.threadId !== source.threadId - ) - return false; + if (!isNearestThreadRoute(navigation.getState(), source)) return false; navigation.dispatch( StackActions.popTo("Thread", { ...source, inspector: target }, { merge: true }), ); @@ -57,3 +49,31 @@ export function useOpenThreadInspector() { return true; }; } + +/** Closes the screens above `thread`, or opens it when the nearest thread route is another one. */ +export function useReturnToThread() { + const navigation = useNavigation(); + return (thread: { readonly environmentId: string; readonly threadId: string }) => + navigation.dispatch( + isNearestThreadRoute(navigation.getState(), thread) + ? StackActions.popTo("Thread", thread, { merge: true }) + : StackActions.replace("Thread", thread), + ); +} + +// `Thread` has no `getId`, so `popTo("Thread")` lands on the nearest one whatever thread it shows. +function isNearestThreadRoute( + state: + | { readonly routes: ReadonlyArray<{ readonly name: string; readonly params?: object }> } + | undefined, + thread: { readonly environmentId: string; readonly threadId: string }, +) { + const params = state?.routes.findLast((route) => route.name === "Thread")?.params; + return ( + params !== undefined && + "environmentId" in params && + params.environmentId === thread.environmentId && + "threadId" in params && + params.threadId === thread.threadId + ); +} From 9c25b71395e36bba1e86f3f093348f0ad966495e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 05:31:49 -0800 Subject: [PATCH 32/39] =?UTF-8?q?fix(opencode):=20Usage=20=E2=86=92=20Limi?= =?UTF-8?q?ts=20shows=20why=20OpenCode=20could=20not=20read=20usage=20(#40?= =?UTF-8?q?340)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/server/v2/OpenCode2Client.test.ts | 12 ++++++++++++ .../src/server/v2/usageLimits.ts | 19 +++++++++++++++---- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts b/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts index ff77d8ef72a2f..701ad57fe488a 100644 --- a/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts +++ b/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts @@ -467,6 +467,16 @@ describe("OpenCode2Client usage limits", () => { "unsupported", ], [503, {}, "probeFailed"], + [ + 503, + { + _tag: "ServiceUnavailableError", + message: + "OpenCode Console budgets are unavailable: StatusCode: non 2xx status code (401 GET https://opencode.ai/console/api/policies/current-budgets)", + service: "opencode", + }, + "probeFailed", + ], [401, {}, "probeFailed"], [200, { data: { workspace: {} } }, "probeFailed"], ] as const) { @@ -487,6 +497,8 @@ describe("OpenCode2Client usage limits", () => { else assert.strictEqual(result?.unavailable?.reason, reason); if ("data" in body && body.data === null) assert.include(result?.unavailable?.message ?? "", "signed in"); + if ("message" in body) + assert.include(result?.unavailable?.message ?? "", "OpenCode Console budgets"); } }), ); diff --git a/packages/provider-opencode/src/server/v2/usageLimits.ts b/packages/provider-opencode/src/server/v2/usageLimits.ts index dd28770b9c5c4..bdf678e424692 100644 --- a/packages/provider-opencode/src/server/v2/usageLimits.ts +++ b/packages/provider-opencode/src/server/v2/usageLimits.ts @@ -61,6 +61,9 @@ const Providers = Schema.Struct({ ), }); +const ErrorBody = Schema.Struct({ message: Schema.String }); +const probeFailedMessage = "OpenCode could not read workspace usage."; + const resetTime = (ms: number) => DateTime.formatIso(DateTime.makeUnsafe(ms)); const budgetPercent = (spent: number, limit: number) => limit <= 0 ? 100 : clampPercent((spent / limit) * 100); @@ -81,9 +84,17 @@ export const readServerUsageLimits = Effect.fn("OpenCode2Client.usageLimits")(fu response.headers["content-type"]?.split(";")[0]?.trim() === "text/html") ) return undefined; - const body = yield* HttpClientResponse.filterStatusOk(response).pipe( - Effect.flatMap(HttpClientResponse.schemaBodyJson(ResponseBody)), - ); + // OpenCode names the upstream cause, such as an expired Console login, in its error body. + if (response.status < 200 || response.status >= 300) + return makeUnavailableUsageLimits({ + checkedAt, + reason: "probeFailed", + message: yield* HttpClientResponse.schemaBodyJson(ErrorBody)(response).pipe( + Effect.map((error) => error.message.trim() || probeFailedMessage), + Effect.orElseSucceed(() => probeFailedMessage), + ), + }); + const body = yield* HttpClientResponse.schemaBodyJson(ResponseBody)(response); if (body.data === null) return makeUnavailableUsageLimits({ checkedAt, @@ -186,7 +197,7 @@ export const readServerUsageLimits = Effect.fn("OpenCode2Client.usageLimits")(fu makeUnavailableUsageLimits({ checkedAt, reason: "probeFailed", - message: "OpenCode could not read workspace usage.", + message: probeFailedMessage, }), ), ); From d3bb8f810898b939712aea7629e94073ae50c0f8 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 05:56:16 -0800 Subject: [PATCH 33/39] perf(server): deleting a thread's worktree refreshes git status once, not twice (#40337) --- apps/server/src/ws.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index d96b91f30d62a..afa030d4d7e9c 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -3295,7 +3295,8 @@ export const layerWsRpc = ( Effect.flatMap((removed) => removed ? Effect.void : gitWorkflow.removeWorktree(input), ), - Effect.tap(() => refreshGitStatus(input.cwd)), + // No project-root refresh here: the client awaits vcs.refreshStatus right after, and a + // second refresh would queue behind this one and reread an unchanged repository. // Subscribers of the removed checkout learn it is no longer a repository. Effect.tap(() => vcsStatusBroadcaster From ece4964b8ea2ac15cf59658c1a2112d1e2bb95f5 Mon Sep 17 00:00:00 2001 From: Simone Date: Sat, 21 Nov 2026 14:56:29 +0100 Subject: [PATCH 34/39] fix(antigravity): accept null skill manifest lists (#40287) Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../src/provider/Drivers/AntigravitySkills.test.ts | 10 +++++++++- .../src/provider/Drivers/AntigravitySkills.ts | 13 +++++-------- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/apps/server/src/provider/Drivers/AntigravitySkills.test.ts b/apps/server/src/provider/Drivers/AntigravitySkills.test.ts index 96dd2c5dbaa44..0033755bfe706 100644 --- a/apps/server/src/provider/Drivers/AntigravitySkills.test.ts +++ b/apps/server/src/provider/Drivers/AntigravitySkills.test.ts @@ -435,8 +435,16 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { yield* fileSystem.writeFileString( path.join(input.cwd, ".agents", "skills.json"), JSON.stringify({ + entries: null, + inherits: [{ path: "workspace-skills.json", include_only: null }], + }), + ); + yield* fileSystem.writeFileString( + path.join(input.cwd, "workspace-skills.json"), + JSON.stringify({ + inherits: null, entries: [ - { path: "tools/skills/deploy/SKILL.md" }, + { path: "tools/skills/deploy/SKILL.md", exclude: null }, { path: "tools/skills/internal/SKILL.md", exclude: ["internal"] }, ], }), diff --git a/apps/server/src/provider/Drivers/AntigravitySkills.ts b/apps/server/src/provider/Drivers/AntigravitySkills.ts index 51fd5535c8226..f69b3d1c455be 100644 --- a/apps/server/src/provider/Drivers/AntigravitySkills.ts +++ b/apps/server/src/provider/Drivers/AntigravitySkills.ts @@ -48,14 +48,14 @@ const SkillFrontmatter = Schema.Struct({ const decodeSkillFrontmatter = Schema.decodeUnknownSync(SkillFrontmatter); const SkillConfigEntry = Schema.Struct({ path: Schema.String, - include_only: Schema.optional(Schema.Array(Schema.String)), - exclude: Schema.optional(Schema.Array(Schema.String)), + include_only: Schema.optional(Schema.NullOr(Schema.Array(Schema.String))), + exclude: Schema.optional(Schema.NullOr(Schema.Array(Schema.String))), }); const decodeSkillsConfig = Schema.decodeUnknownOption( Schema.fromJsonString( Schema.Struct({ - inherits: Schema.optional(Schema.Array(SkillConfigEntry)), - entries: Schema.optional(Schema.Array(SkillConfigEntry)), + inherits: Schema.optional(Schema.NullOr(Schema.Array(SkillConfigEntry))), + entries: Schema.optional(Schema.NullOr(Schema.Array(SkillConfigEntry))), }), ), ); @@ -289,10 +289,7 @@ function matchesSkillFilter(entry: string, filter: SkillEntryFilter): boolean { function narrowSkillFilter( parent: SkillEntryFilter, - entry: { - readonly include_only?: ReadonlyArray | undefined; - readonly exclude?: ReadonlyArray | undefined; - }, + entry: typeof SkillConfigEntry.Type, ): SkillEntryFilter { const includeGroups = entry.include_only && entry.include_only.length > 0 From e0f3ab9e78a72e86727b6664488f9a19a1e8fe7b Mon Sep 17 00:00:00 2001 From: panol <302941691@qq.com> Date: Sat, 21 Nov 2026 21:57:47 +0800 Subject: [PATCH 35/39] fix(mobile): text selection menu items follow the UI language (#40297) Co-authored-by: Julius Marminge --- apps/mobile/src/i18n/translations/de.json | 6 ++++-- apps/mobile/src/i18n/translations/en.json | 6 ++++-- apps/mobile/src/i18n/translations/es.json | 6 ++++-- apps/mobile/src/i18n/translations/fr.json | 6 ++++-- apps/mobile/src/i18n/translations/ja.json | 6 ++++-- apps/mobile/src/i18n/translations/ko.json | 6 ++++-- apps/mobile/src/i18n/translations/pt-BR.json | 6 ++++-- apps/mobile/src/i18n/translations/ru.json | 6 ++++-- apps/mobile/src/i18n/translations/sv.json | 6 ++++-- apps/mobile/src/i18n/translations/zh.json | 6 ++++-- apps/mobile/src/native/EnrichedMarkdownText.tsx | 17 +++++++++++++++++ 11 files changed, 57 insertions(+), 20 deletions(-) diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 8777f08e663ce..e0eb437599e38 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -1546,6 +1546,10 @@ "8f2e6a13eee27d59": "Überschriften", "29005b7a742cae1e": "Links", "728a49012344e673": "Bilder", + "a034d65164bb39de": "Kopieren", + "0165ef55eb6c8a99": "Als Markdown kopieren", + "439737cb6de2a5b3": "Bild-URL kopieren", + "d3d24474c922eef2": "{count} Bild-URLs kopieren", "f18f6d80b6bd08a0": "Modellreferenz kopieren", "d7a551536aa43f3e": "Modellreferenz teilen", "9f1b29c948772f0f": "Link öffnen", @@ -1553,7 +1557,6 @@ "d7dc565616d13a5c": "Link teilen", "51244cd196696a00": "Zitieren", "6cdca065884f77f2": "Kopieren", - "0165ef55eb6c8a99": "Als Markdown kopieren", "7c1923203049d602": "Code kopieren", "74d986aed0381cb0": "Der Diagramm-Renderer konnte nicht geladen werden.", "9cc6288e83305ca3": "Das Diagramm konnte nicht gerendert werden.", @@ -1862,7 +1865,6 @@ "1d0a7acef4a95536": "Akzeptieren", "255ae21697461ef6": "Übernimm die Steuerung, um zu antworten.", "d2a40ef08ef016ec": "{command} kopieren", - "a034d65164bb39de": "Kopieren", "e0cfab9ded209e81": "Neu verbinden", "b00379f06c304b6a": "Browser öffnen, {title}", "149eba5f977b0549": "Öffnet den Browser-Tab im Vollbild", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index dfe3a473fe248..bca87cee0884f 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -1546,6 +1546,10 @@ "8f2e6a13eee27d59": "Headings", "29005b7a742cae1e": "Links", "728a49012344e673": "Images", + "a034d65164bb39de": "Copy", + "0165ef55eb6c8a99": "Copy as Markdown", + "439737cb6de2a5b3": "Copy Image URL", + "d3d24474c922eef2": "Copy {count} Image URLs", "f18f6d80b6bd08a0": "Copy model reference", "d7a551536aa43f3e": "Share model reference", "9f1b29c948772f0f": "Open link", @@ -1553,7 +1557,6 @@ "d7dc565616d13a5c": "Share link", "51244cd196696a00": "Cite", "6cdca065884f77f2": "Copy", - "0165ef55eb6c8a99": "Copy as Markdown", "7c1923203049d602": "Copy code", "74d986aed0381cb0": "The diagram renderer failed to load.", "9cc6288e83305ca3": "The diagram could not be rendered.", @@ -1862,7 +1865,6 @@ "1d0a7acef4a95536": "Accept", "255ae21697461ef6": "Take control to respond.", "d2a40ef08ef016ec": "Copy {command}", - "a034d65164bb39de": "Copy", "e0cfab9ded209e81": "Reconnect", "b00379f06c304b6a": "Open browser, {title}", "149eba5f977b0549": "Opens the browser tab full screen", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 05f58a63227d3..3f73e995b2521 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -1546,6 +1546,10 @@ "8f2e6a13eee27d59": "Encabezados", "29005b7a742cae1e": "Enlaces", "728a49012344e673": "Imágenes", + "a034d65164bb39de": "Copiar", + "0165ef55eb6c8a99": "Copiar como Markdown", + "439737cb6de2a5b3": "Copiar URL de la imagen", + "d3d24474c922eef2": "Copiar {count} URL de imágenes", "f18f6d80b6bd08a0": "Copiar referencia del modelo", "d7a551536aa43f3e": "Compartir referencia del modelo", "9f1b29c948772f0f": "Abrir enlace", @@ -1553,7 +1557,6 @@ "d7dc565616d13a5c": "Compartir enlace", "51244cd196696a00": "Citar", "6cdca065884f77f2": "Copiar", - "0165ef55eb6c8a99": "Copiar como Markdown", "7c1923203049d602": "Copiar código", "74d986aed0381cb0": "No se pudo cargar el renderizador de diagramas.", "9cc6288e83305ca3": "No se pudo renderizar el diagrama.", @@ -1862,7 +1865,6 @@ "1d0a7acef4a95536": "Aceptar", "255ae21697461ef6": "Toma el control para responder.", "d2a40ef08ef016ec": "Copiar {command}", - "a034d65164bb39de": "Copiar", "e0cfab9ded209e81": "Volver a conectar", "b00379f06c304b6a": "Abrir navegador, {title}", "149eba5f977b0549": "Abre la pestaña del navegador a pantalla completa", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index f661c315215c0..3aff16728eeff 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -1546,6 +1546,10 @@ "8f2e6a13eee27d59": "Titres", "29005b7a742cae1e": "Liens", "728a49012344e673": "Images", + "a034d65164bb39de": "Copier", + "0165ef55eb6c8a99": "Copier en Markdown", + "439737cb6de2a5b3": "Copier l’URL de l’image", + "d3d24474c922eef2": "Copier {count} URL d’images", "f18f6d80b6bd08a0": "Copier la référence du modèle", "d7a551536aa43f3e": "Partager la référence du modèle", "9f1b29c948772f0f": "Ouvrir le lien", @@ -1553,7 +1557,6 @@ "d7dc565616d13a5c": "Partager le lien", "51244cd196696a00": "Citer", "6cdca065884f77f2": "Copier", - "0165ef55eb6c8a99": "Copier en Markdown", "7c1923203049d602": "Copier le code", "74d986aed0381cb0": "Le moteur de rendu des diagrammes n’a pas pu se charger.", "9cc6288e83305ca3": "Impossible d’afficher le diagramme.", @@ -1862,7 +1865,6 @@ "1d0a7acef4a95536": "Accepter", "255ae21697461ef6": "Prenez le contrôle pour répondre.", "d2a40ef08ef016ec": "Copier {command}", - "a034d65164bb39de": "Copier", "e0cfab9ded209e81": "Se reconnecter", "b00379f06c304b6a": "Ouvrir le navigateur, {title}", "149eba5f977b0549": "Ouvre l’onglet du navigateur en plein écran", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 56616809052d3..302318926d092 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -1546,6 +1546,10 @@ "8f2e6a13eee27d59": "見出し", "29005b7a742cae1e": "リンク", "728a49012344e673": "画像", + "a034d65164bb39de": "コピー", + "0165ef55eb6c8a99": "Markdown としてコピー", + "439737cb6de2a5b3": "画像URLをコピー", + "d3d24474c922eef2": "{count}件の画像URLをコピー", "f18f6d80b6bd08a0": "モデルの参照をコピー", "d7a551536aa43f3e": "モデルの参照を共有", "9f1b29c948772f0f": "リンクを開く", @@ -1553,7 +1557,6 @@ "d7dc565616d13a5c": "リンクを共有", "51244cd196696a00": "引用", "6cdca065884f77f2": "コピー", - "0165ef55eb6c8a99": "Markdown としてコピー", "7c1923203049d602": "コードをコピー", "74d986aed0381cb0": "図のレンダラーを読み込めませんでした。", "9cc6288e83305ca3": "図をレンダリングできませんでした。", @@ -1862,7 +1865,6 @@ "1d0a7acef4a95536": "承諾", "255ae21697461ef6": "応答するには操作権を取得してください。", "d2a40ef08ef016ec": "{command} をコピー", - "a034d65164bb39de": "コピー", "e0cfab9ded209e81": "再接続", "b00379f06c304b6a": "ブラウザーを開く、{title}", "149eba5f977b0549": "ブラウザータブを全画面で開きます", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 443285f8664c4..ec0ee0864e6ef 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -1546,6 +1546,10 @@ "8f2e6a13eee27d59": "제목", "29005b7a742cae1e": "링크", "728a49012344e673": "이미지", + "a034d65164bb39de": "복사", + "0165ef55eb6c8a99": "Markdown으로 복사", + "439737cb6de2a5b3": "이미지 URL 복사", + "d3d24474c922eef2": "이미지 URL {count}개 복사", "f18f6d80b6bd08a0": "모델 참조 복사", "d7a551536aa43f3e": "모델 참조 공유", "9f1b29c948772f0f": "링크 열기", @@ -1553,7 +1557,6 @@ "d7dc565616d13a5c": "링크 공유", "51244cd196696a00": "인용하기", "6cdca065884f77f2": "복사", - "0165ef55eb6c8a99": "Markdown으로 복사", "7c1923203049d602": "코드 복사", "74d986aed0381cb0": "다이어그램 렌더러를 불러오지 못했습니다.", "9cc6288e83305ca3": "다이어그램을 렌더링할 수 없습니다.", @@ -1862,7 +1865,6 @@ "1d0a7acef4a95536": "수락", "255ae21697461ef6": "응답하려면 제어하세요.", "d2a40ef08ef016ec": "{command} 복사", - "a034d65164bb39de": "복사", "e0cfab9ded209e81": "다시 연결", "b00379f06c304b6a": "브라우저 열기, {title}", "149eba5f977b0549": "브라우저 탭을 전체 화면으로 엽니다", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 33793cc553d34..56b52f85e6d01 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -1546,6 +1546,10 @@ "8f2e6a13eee27d59": "Títulos", "29005b7a742cae1e": "Links", "728a49012344e673": "Imagens", + "a034d65164bb39de": "Copiar", + "0165ef55eb6c8a99": "Copiar como Markdown", + "439737cb6de2a5b3": "Copiar URL da imagem", + "d3d24474c922eef2": "Copiar {count} URLs de imagens", "f18f6d80b6bd08a0": "Copiar referência do modelo", "d7a551536aa43f3e": "Compartilhar referência do modelo", "9f1b29c948772f0f": "Abrir link", @@ -1553,7 +1557,6 @@ "d7dc565616d13a5c": "Compartilhar link", "51244cd196696a00": "Citar", "6cdca065884f77f2": "Copiar", - "0165ef55eb6c8a99": "Copiar como Markdown", "7c1923203049d602": "Copiar código", "74d986aed0381cb0": "Falha ao carregar o renderizador de diagramas.", "9cc6288e83305ca3": "Não foi possível renderizar o diagrama.", @@ -1862,7 +1865,6 @@ "1d0a7acef4a95536": "Aceitar", "255ae21697461ef6": "Assuma o controle para responder.", "d2a40ef08ef016ec": "Copiar {command}", - "a034d65164bb39de": "Copiar", "e0cfab9ded209e81": "Reconectar", "b00379f06c304b6a": "Abrir navegador, {title}", "149eba5f977b0549": "Abre a aba do navegador em tela cheia", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index d0e2d9577a9ab..9b3b38bcf0234 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -1546,6 +1546,10 @@ "8f2e6a13eee27d59": "Заголовки", "29005b7a742cae1e": "Ссылки", "728a49012344e673": "Изображения", + "a034d65164bb39de": "Копировать", + "0165ef55eb6c8a99": "Копировать как Markdown", + "439737cb6de2a5b3": "Копировать URL изображения", + "d3d24474c922eef2": "Копировать URL изображений: {count}", "f18f6d80b6bd08a0": "Копировать ссылку на модель", "d7a551536aa43f3e": "Поделиться ссылкой на модель", "9f1b29c948772f0f": "Открыть ссылку", @@ -1553,7 +1557,6 @@ "d7dc565616d13a5c": "Поделиться ссылкой", "51244cd196696a00": "Цитировать", "6cdca065884f77f2": "Копировать", - "0165ef55eb6c8a99": "Копировать как Markdown", "7c1923203049d602": "Копировать код", "74d986aed0381cb0": "Не удалось загрузить отрисовщик диаграмм.", "9cc6288e83305ca3": "Не удалось отрисовать диаграмму.", @@ -1862,7 +1865,6 @@ "1d0a7acef4a95536": "Принять", "255ae21697461ef6": "Возьмите управление, чтобы ответить.", "d2a40ef08ef016ec": "Копировать {command}", - "a034d65164bb39de": "Копировать", "e0cfab9ded209e81": "Переподключить", "b00379f06c304b6a": "Открыть браузер, {title}", "149eba5f977b0549": "Открывает вкладку браузера на весь экран", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 7fd2f945cc033..5b94cd6efe6ea 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -1546,6 +1546,10 @@ "8f2e6a13eee27d59": "Rubriker", "29005b7a742cae1e": "Länkar", "728a49012344e673": "Bilder", + "a034d65164bb39de": "Kopiera", + "0165ef55eb6c8a99": "Kopiera som Markdown", + "439737cb6de2a5b3": "Kopiera bild-URL", + "d3d24474c922eef2": "Kopiera {count} bild-URL:er", "f18f6d80b6bd08a0": "Kopiera modellreferens", "d7a551536aa43f3e": "Dela modellreferens", "9f1b29c948772f0f": "Öppna länk", @@ -1553,7 +1557,6 @@ "d7dc565616d13a5c": "Dela länk", "51244cd196696a00": "Citera", "6cdca065884f77f2": "Kopiera", - "0165ef55eb6c8a99": "Kopiera som Markdown", "7c1923203049d602": "Kopiera kod", "74d986aed0381cb0": "Diagramrenderaren kunde inte läsas in.", "9cc6288e83305ca3": "Diagrammet kunde inte renderas.", @@ -1862,7 +1865,6 @@ "1d0a7acef4a95536": "Godkänn", "255ae21697461ef6": "Ta kontrollen för att svara.", "d2a40ef08ef016ec": "Kopiera {command}", - "a034d65164bb39de": "Kopiera", "e0cfab9ded209e81": "Återanslut", "b00379f06c304b6a": "Öppna webbläsaren, {title}", "149eba5f977b0549": "Öppnar webbläsarfliken i helskärm", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 54c72efe3b4fb..0478b5b378409 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -1547,6 +1547,10 @@ "8f2e6a13eee27d59": "标题", "29005b7a742cae1e": "链接", "728a49012344e673": "图片", + "a034d65164bb39de": "复制", + "0165ef55eb6c8a99": "复制为 Markdown", + "439737cb6de2a5b3": "复制图片 URL", + "d3d24474c922eef2": "复制 {count} 个图片 URL", "f18f6d80b6bd08a0": "复制模型引用", "d7a551536aa43f3e": "分享模型引用", "9f1b29c948772f0f": "打开链接", @@ -1554,7 +1558,6 @@ "d7dc565616d13a5c": "分享链接", "51244cd196696a00": "引用", "6cdca065884f77f2": "复制", - "0165ef55eb6c8a99": "复制为 Markdown", "7c1923203049d602": "复制代码", "74d986aed0381cb0": "图表渲染器加载失败。", "9cc6288e83305ca3": "无法渲染图表。", @@ -1863,7 +1866,6 @@ "1d0a7acef4a95536": "接受", "255ae21697461ef6": "接管控制后才能回应。", "d2a40ef08ef016ec": "复制 {command}", - "a034d65164bb39de": "复制", "e0cfab9ded209e81": "重新连接", "b00379f06c304b6a": "打开浏览器,{title}", "149eba5f977b0549": "全屏打开浏览器标签页", diff --git a/apps/mobile/src/native/EnrichedMarkdownText.tsx b/apps/mobile/src/native/EnrichedMarkdownText.tsx index 4ef351b39873b..ff542959413ec 100644 --- a/apps/mobile/src/native/EnrichedMarkdownText.tsx +++ b/apps/mobile/src/native/EnrichedMarkdownText.tsx @@ -22,6 +22,7 @@ import { type MarkdownImageBlock, type MarkdownLinkOccurrence, type MarkdownStyle, + type TextSelectionMenuConfig, } from "react-native-enriched-markdown"; import { codeFenceRenderer } from "./codeBlockMarkdown"; import { HighlightedCodeBlock } from "./HighlightedCodeBlock"; @@ -190,6 +191,7 @@ function codeBlockElement( mathRenderingEnabled: boolean, scheme: HighlightScheme, accessibilityLabels: AccessibilityLabels, + selectionMenuConfig: TextSelectionMenuConfig, ): ReactElement | undefined { const renderer = codeFenceRenderer(block.language, mathRenderingEnabled); if (renderer.kind === "mermaid") { @@ -210,6 +212,7 @@ function codeBlockElement( selectionColor={textStyle.selectionColor} selectionHandleColor={textStyle.selectionHandleColor} accessibilityLabels={accessibilityLabels} + selectionMenuConfig={selectionMenuConfig} /> ) : undefined; } @@ -254,6 +257,18 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) { }), [gt], ); + // The library's built-in selection menu items default to English labels. + const selectionMenuConfig = useMemo( + () => ({ + copy: { label: gt("Copy", { $context: "verb" }) }, + copyAsMarkdown: { label: gt("Copy as Markdown") }, + copyImageUrl: { + label: gt("Copy Image URL"), + pluralLabels: { other: gt("Copy {count} Image URLs", { count: "{count}" }) }, + }, + }), + [gt], + ); const { markdown, fileHrefs } = useMemo(() => { if (!fileEmbedLabel) { return { @@ -415,6 +430,7 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) { mathRenderingEnabled, themeAppearance, accessibilityLabels, + selectionMenuConfig, ), }; const resolveNativeImageSource = useRetryingImageSource(resolveImageSource); @@ -472,6 +488,7 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) { : undefined } selectionClipboard={selectionClipboard} + selectionMenuConfig={selectionMenuConfig} selectionColor={props.textStyle.selectionColor} selectionHandleColor={props.textStyle.selectionHandleColor} md4cFlags={{ From 997575be5f5dde8e5443a26ae4cfd4155fa27d87 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 06:06:28 -0800 Subject: [PATCH 36/39] perf(server): pull no longer scans the working tree twice (#40338) --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 50 ++++++++++++++++++++ apps/server/src/vcs/GitVcsDriverCore.ts | 35 ++++++++++++-- 2 files changed, 80 insertions(+), 5 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index e745669fda5c2..777d46e53d4c9 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -1630,6 +1630,56 @@ describe("pullCurrentBranch", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect("does not scan the working tree to pull", () => + Effect.gen(function* () { + const { cwd, initialBranch, remoteHead } = yield* cloneBehindRemote; + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + const spawnedArgs: Array> = []; + const spawner = ChildProcessSpawner.make((command) => { + if (ChildProcess.isStandardCommand(command)) spawnedArgs.push(command.args.map(String)); + return delegate.spawn(command); + }); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + + const result = yield* driver.pullCurrentBranch(cwd); + + assert.deepEqual(result, { + status: "pulled", + refName: initialBranch, + upstreamRef: `origin/${initialBranch}`, + }); + assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), remoteHead); + // The status broadcast after a pull re-reads the working tree for the UI. + assert.deepEqual( + spawnedArgs.filter((args) => args.includes("status") || args.includes("--numstat")), + [], + ); + }).pipe(Effect.provide(layerTest)), + ); + + it.effect("pulls into an unborn branch that tracks an unfetched upstream", () => + Effect.gen(function* () { + const { remote, initialBranch, remoteHead } = yield* cloneBehindRemote; + const cwd = yield* makeTmpDir(); + yield* git(cwd, ["init", "--initial-branch", initialBranch]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["config", `branch.${initialBranch}.remote`, "origin"]); + yield* git(cwd, ["config", `branch.${initialBranch}.merge`, `refs/heads/${initialBranch}`]); + const driver = yield* makeGitVcsDriverCore(); + + const result = yield* driver.pullCurrentBranch(cwd); + + assert.deepEqual(result, { + status: "pulled", + refName: initialBranch, + upstreamRef: `origin/${initialBranch}`, + }); + assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), remoteHead); + }).pipe(Effect.provide(layerTest)), + ); + it.effect.each([false, true])( "pulls past an unrelated lock with custom fetch mapping=%s", (customMapping) => diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 7fe1dab187ac5..63d8ab594d607 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -3845,8 +3845,34 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const pullCurrentBranch: GitVcsDriver.GitVcsDriver["Service"]["pullCurrentBranch"] = Effect.fn( "pullCurrentBranch", )(function* (cwd) { - const details = yield* readStatusDetailsLocal(cwd); - const refName = details.branch; + const [refName, currentUpstreamRef] = yield* Effect.all( + [ + readCurrentBranch("GitVcsDriver.pullCurrentBranch.branch", cwd), + readCurrentUpstreamRef(cwd), + ], + { concurrency: 2 }, + ); + let upstreamRef = currentUpstreamRef; + // `@{upstream}` needs the tracking ref, which an unborn branch's first pull has not fetched. + if (upstreamRef === null && refName) { + const head = yield* executeGit( + "GitVcsDriver.pullCurrentBranch.head", + cwd, + ["rev-parse", "--verify", "--quiet", "HEAD"], + { allowNonZeroExit: true }, + ); + if (head.exitCode !== 0) { + const [configuredRemote, mergeRef] = yield* Effect.all([ + readConfigValue(cwd, `branch.${refName}.remote`), + readConfigValue(cwd, `branch.${refName}.merge`), + ]); + const mergeBranch = mergeRef?.replace(/^refs\/heads\//, ""); + if (configuredRemote && mergeBranch) { + upstreamRef = + configuredRemote === "." ? mergeBranch : `${configuredRemote}/${mergeBranch}`; + } + } + } if (!refName) { return yield* new GitCommandError({ ...gitCommandContext({ @@ -3857,7 +3883,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* detail: "Cannot pull from detached HEAD.", }); } - if (!details.hasUpstream) { + if (upstreamRef === null) { return yield* new GitCommandError({ ...gitCommandContext({ operation: "GitVcsDriver.pullCurrentBranch", @@ -3973,14 +3999,13 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* true, ).pipe(Effect.map((stdout) => stdout.trim())); - const refreshed = yield* readStatusDetailsLocal(cwd); return { status: beforeSha.length > 0 && beforeSha === afterSha ? ("skipped_up_to_date" as const) : ("pulled" as const), refName, - upstreamRef: refreshed.upstreamRef, + upstreamRef, }; }, Effect.scoped); From 755de001f25c54c9d6435bb23a83ffcd231e06a5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 06:22:17 -0800 Subject: [PATCH 37/39] fix(server): Antigravity Orchestrator usage prices at the base Gemini 4 rate (#40352) --- .../Drivers/antigravityUsageReader.test.ts | 12 ++++++++++++ .../provider/Drivers/antigravityUsageReader.ts | 16 ++++++++++++---- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts b/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts index d0def84f1efe0..88e076d98f208 100644 --- a/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts +++ b/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts @@ -383,6 +383,9 @@ describe("readAntigravityUsage", () => { "gemini-3-flash-agent", "gemini-3-flash", "gemini-default", + "gemini-pro-orchestrator-neon", + "gemini-4-hydrogen-orchestrator", + "gemini-pro-orchestrator-g1-pro", ].entries()) { yield* db.run("INSERT INTO gen_metadata VALUES (?, ?)", [ idx, @@ -393,6 +396,11 @@ describe("readAntigravityUsage", () => { new Uint8Array(protoBytes(9, protoNumber(2, 10 + idx))), ]); } + // Orchestrator (Neon), MODEL_PLACEHOLDER_M537, with no name in the metadata. + yield* db.run("INSERT INTO steps VALUES (?, ?)", [ + 20, + new Uint8Array(protoBytes(9, [...protoNumber(1, 1537), ...protoNumber(2, 30)])), + ]); }), ); const result = yield* readAntigravityUsage(dir, 0); @@ -405,6 +413,10 @@ describe("readAntigravityUsage", () => { ["gemini-3-flash-agent", "gemini-3.5-flash"], ["gemini-3-flash", "gemini-3-flash-preview"], ["gemini-default", undefined], + ["gemini-pro-orchestrator-neon", "gemini-4-neon"], + ["gemini-4-hydrogen-orchestrator", "gemini-4-hydrogen"], + ["gemini-pro-orchestrator-g1-pro", "gemini-4-argon"], + ["gemini-pro-orchestrator-neon", "gemini-4-neon"], ], ); }).pipe(Effect.provide(NodeServices.layer)), diff --git a/apps/server/src/provider/Drivers/antigravityUsageReader.ts b/apps/server/src/provider/Drivers/antigravityUsageReader.ts index 4a71c8ed2b056..5dff65928ad24 100644 --- a/apps/server/src/provider/Drivers/antigravityUsageReader.ts +++ b/apps/server/src/provider/Drivers/antigravityUsageReader.ts @@ -126,18 +126,26 @@ const MODEL_IDS: Record = { 1417: "gemini-4-argon", 1418: "gemini-4-argon", 1419: "gemini-4-argon", + 1537: "gemini-pro-orchestrator-neon", }; // Effort and routing variants share the base model's price. export const antigravityRateModel = (model: string) => { - const base = model.replace(/-(?:extra-low|low|medium|high|tiered|control|thinking|agent)$/, ""); + const base = model.replace( + /-(?:extra-low|low|medium|high|tiered|control|thinking|agent|orchestrator)$/, + "", + ); return /^gemini-3-flash-(?:agent(?:-[ab])?|[ab])$/.test(model) ? "gemini-3.5-flash" : model === "gemini-3.7-flash-safety-le" ? "gemini-3.7-flash" - : base === "gemini-3-flash" - ? "gemini-3-flash-preview" - : base; + : model === "gemini-pro-orchestrator-neon" + ? "gemini-4-neon" + : model === "gemini-pro-orchestrator-g1-pro" + ? "gemini-4-argon" + : base === "gemini-3-flash" + ? "gemini-3-flash-preview" + : base; }; function withRateModel(record: UsageRecord): UsageRecord { From dd941b9c3b581b4a04539255fb85f2b0cbc3fa57 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 06:36:07 -0800 Subject: [PATCH 38/39] fix(server): treat a branch rename as done when Git moved the ref but kept the config locked (#40361) --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 17 +++++++++++++++++ apps/server/src/vcs/GitVcsDriverCore.ts | 17 +++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 777d46e53d4c9..b25e0ff2a8f64 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -7907,6 +7907,23 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("reports a rename as done when Git moved the ref but kept the config locked", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + yield* git(cwd, ["checkout", "-b", "t3/abcd1234"]); + yield* writeTextFile(cwd, ".git/config.lock", ""); + const driver = yield* GitVcsDriver.GitVcsDriver; + + const renamed = yield* TestClock.withLive( + driver.renameBranch({ cwd, oldBranch: "t3/abcd1234", newBranch: "t3/fix-login" }), + ); + + assert.equal(renamed.branch, "t3/fix-login"); + assert.equal(yield* git(cwd, ["branch", "--show-current"]), "t3/fix-login"); + }), + ); + it.effect.each([false, true])( "cleans up links left by successful worktree removal, preserving ordinary files: %s", (keepFile) => diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 63d8ab594d607..4356de894f0b4 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -6661,6 +6661,23 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* timeoutMs: 10_000, fallbackErrorDetail: "git branch rename failed", }, + ).pipe( + // Git exits non-zero after moving the ref when it cannot rewrite the locked config. + Effect.catch((error) => + Effect.all( + [branchExists(input.cwd, input.oldBranch), branchExists(input.cwd, targetBranch)], + { concurrency: "unbounded" }, + ).pipe( + Effect.orElseSucceed(() => [true, false] as const), + Effect.flatMap(([oldExists, newExists]) => + !oldExists && newExists + ? Effect.logWarning( + "GitVcsDriver.renameBranch: renamed the branch but could not move its config entries", + ) + : Effect.fail(error), + ), + ), + ), ); return { branch: targetBranch }; From 8d95f32c539d04806529b4103422842d5fba424e Mon Sep 17 00:00:00 2001 From: amv146 <39172404+amv146@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:34:20 +0000 Subject: [PATCH 39/39] Initial plan