From 7966f202ef99afee2fa877fce2886b9876e8373a Mon Sep 17 00:00:00 2001 From: Charles Bine <8898759+charlesbine@users.noreply.github.com> Date: Sun, 22 Nov 2026 03:17:39 -0400 Subject: [PATCH 01/17] fix(antigravity): pre-approve T3 MCP tools in Auto and Auto-accept edits (#39822) Co-authored-by: Julius Marminge Co-authored-by: charlesbine --- .../acp/AntigravityAcpSupport.test.ts | 41 +++++++++++++++++++ .../src/provider/acp/AntigravityAcpSupport.ts | 31 +++++++++++++- 2 files changed, 71 insertions(+), 1 deletion(-) diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts index 05f12ec278fd9..7201d1edc0ba0 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts @@ -133,6 +133,47 @@ describe("Antigravity Auto", () => { ).toBe("deny"); }, ); + + it.each(["auto", "auto-accept-edits"] as const)( + "runs only server-qualified T3 MCP calls unasked in %s", + (runtimeMode) => { + const policy = { runtimeMode, cwd: "/workspace" }; + const request = ( + title: string, + rawInput?: Record, + ): EffectAcpSchema.RequestPermissionRequest => ({ + sessionId: "session-1", + toolCall: { toolCallId: "call-1", title, kind: "execute", rawInput }, + options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }], + }); + for (const t3Call of [ + request("Run mcp_t3-code_t3_thread_list?"), + request("MCP Tool delegate_task", { ServerName: "t3-code", ToolName: "delegate_task" }), + ]) { + expect(antigravityPermissionDisposition(policy, t3Call)).toBe("allow"); + expect( + antigravityPermissionDisposition({ ...policy, approvalPolicy: "on-request" }, t3Call), + ).toBe("ask"); + expect( + antigravityPermissionDisposition( + { ...policy, sandboxPolicy: { type: "readOnly" } }, + t3Call, + ), + ).toBe("deny"); + } + for (const otherCall of [ + // Names no server, so another MCP server's tool of the same name looks identical. + request("Running preview_status"), + request("Run mcp_github_create_issue"), + request("MCP Tool preview_status", { ServerName: "other", ToolName: "preview_status" }), + request("Run mcp_t3-code_preview_status", { + CommandLine: "Run mcp_t3-code_preview_status", + }), + ]) { + expect(antigravityPermissionDisposition(policy, otherCall)).toBe("ask"); + } + }, + ); }); describe("applyAntigravityAcpModelSelection", () => { diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index 7434e23b5eda9..4d57305f7e0ec 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -25,9 +25,11 @@ import { import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; import { acpPermissionDisposition, + unknownRecord, type AcpRuntimePolicy, } from "@t3tools/provider-acp/server/clientPolicy"; import type { AcpSessionModeState } from "@t3tools/provider-acp/server/runtimeModel"; +import { T3_MCP_TOOL_NAMES } from "@t3tools/shared/t3McpToolPresentation"; import packageJson from "../../../package.json" with { type: "json" }; import { normalizeAntigravitySessionUpdate } from "./AntigravityProtocol.ts"; @@ -181,13 +183,40 @@ export function antigravitySessionMode( return modeId === "yolo" || modeId === "auto_edit" ? "default" : modeId; } +// Only calls that name T3's server: before agy 1.5.8 "Running " names no server, so another +// MCP server's tool of the same name would pass. +const ANTIGRAVITY_T3_MCP_TITLE = /^Run mcp_t3-code_(?[A-Za-z0-9_]+)\??$/; + +function isAntigravityT3McpRequest(request: EffectAcpSchema.RequestPermissionRequest): boolean { + const rawInput = unknownRecord(request.toolCall.rawInput); + if (rawInput?.ServerName !== undefined) { + return ( + rawInput.ServerName === "t3-code" && + typeof rawInput.ToolName === "string" && + T3_MCP_TOOL_NAMES.has(rawInput.ToolName) + ); + } + if (typeof rawInput?.CommandLine === "string") return false; + const tool = ANTIGRAVITY_T3_MCP_TITLE.exec(request.toolCall.title?.trim() ?? "")?.groups?.tool; + return tool !== undefined && T3_MCP_TOOL_NAMES.has(tool); +} + export function antigravityPermissionDisposition( policy: AcpRuntimePolicy, request: EffectAcpSchema.RequestPermissionRequest, ) { const disposition = acpPermissionDisposition(policy, request); + if (disposition === "deny") return "deny"; + // T3 authorizes its own MCP server, so Auto and Auto-accept edits run it unasked, as Claude does. + if ( + (policy.runtimeMode === "auto" || policy.runtimeMode === "auto-accept-edits") && + (policy.approvalPolicy === undefined || policy.approvalPolicy === "never") && + isAntigravityT3McpRequest(request) + ) { + return "allow"; + } // agy's Auto has already reviewed what it sends; the user decides unless the sandbox forbids it. - return policy.runtimeMode === "auto" && disposition !== "deny" ? "ask" : disposition; + return policy.runtimeMode === "auto" ? "ask" : disposition; } /** The runtime mode an Antigravity session mode grants; the inverse of `antigravityPermissionMode`. */ From ad1b1f9ca4219babe21f0beee73df253d052f994 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 23:18:42 -0800 Subject: [PATCH 02/17] fix(server): Antigravity keeps Auto in the mode picker after a restart (#40154) Co-authored-by: Claude Opus 5.5 --- .../src/provider/AntigravityProvider.test.ts | 27 +++++++ .../src/provider/AntigravityProvider.ts | 70 +++++++++++-------- .../src/provider/Drivers/AntigravityDriver.ts | 30 ++++++++ 3 files changed, 99 insertions(+), 28 deletions(-) diff --git a/apps/server/src/provider/AntigravityProvider.test.ts b/apps/server/src/provider/AntigravityProvider.test.ts index 522be29a8b187..88589d1c9a773 100644 --- a/apps/server/src/provider/AntigravityProvider.test.ts +++ b/apps/server/src/provider/AntigravityProvider.test.ts @@ -7,6 +7,7 @@ import { ProviderDriverKind, ProviderInstanceId, ProviderSetupError, + type RuntimeMode, type ServerProviderUsageLimits, } from "@t3tools/contracts"; import * as Deferred from "effect/Deferred"; @@ -138,8 +139,10 @@ const makeHarness = Effect.fn("makeAntigravityProviderHarness")(function* ( readonly enabled?: boolean; readonly safe?: boolean; readonly probeUsage?: Effect.Effect; + readonly rememberedRuntimeModes?: ReadonlyArray; } = {}, ) { + const savedRuntimeModes = yield* Ref.make>>([]); const initialProbe = yield* Deferred.make(); const probeCalls = yield* Ref.make(0); const safetyCalls = yield* Ref.make(0); @@ -153,6 +156,10 @@ const makeHarness = Effect.fn("makeAntigravityProviderHarness")(function* ( stampIdentity: (snapshot) => Effect.succeed({ ...snapshot, instanceId, driver }), ...(options.auth ? { auth: options.auth } : {}), ...(options.probeUsage ? { probeUsage: options.probeUsage } : {}), + ...(options.rememberedRuntimeModes + ? { rememberedRuntimeModes: options.rememberedRuntimeModes } + : {}), + rememberRuntimeModes: (modes) => Ref.update(savedRuntimeModes, (saved) => [...saved, modes]), probe: Ref.update(probeCalls, (count) => count + 1).pipe( Effect.andThen(Ref.get(probe)), Effect.flatten, @@ -187,6 +194,7 @@ const makeHarness = Effect.fn("makeAntigravityProviderHarness")(function* ( initialUpdate, initialize, nextPublish, + savedRuntimeModes, }; }); @@ -381,6 +389,25 @@ it.layer(layerTest)("Antigravity provider snapshots", (it) => { yield* harness.provider.onSessionStarted(startedWithAuto); yield* harness.provider.onSignedOut; expect(yield* supportedModes).toEqual(withoutAuto); + const withAuto: ReadonlyArray = [ + "approval-required", + "auto-accept-edits", + "auto", + "full-access", + ]; + expect(yield* Ref.get(harness.savedRuntimeModes)).toEqual([ + withAuto, + withoutAuto, + withAuto, + withoutAuto, + ]); + + // A restart offers what the last session advertised before any session starts. + const restarted = yield* makeHarness({ rememberedRuntimeModes: withAuto }); + yield* restarted.initialize; + expect(yield* restarted.provider.snapshot.getSnapshot).toMatchObject({ + supportedRuntimeModes: withAuto, + }); }), ); diff --git a/apps/server/src/provider/AntigravityProvider.ts b/apps/server/src/provider/AntigravityProvider.ts index b3b68d46e8ba8..f5e18f6bece9d 100644 --- a/apps/server/src/provider/AntigravityProvider.ts +++ b/apps/server/src/provider/AntigravityProvider.ts @@ -172,6 +172,9 @@ interface AntigravityProviderOptions { readonly clearUsage?: Effect.Effect; readonly maintenanceCapabilities?: ProviderMaintenanceCapabilities; readonly auth?: { readonly type: string; readonly label: string }; + /** Modes the last session advertised, saved because initialize alone does not report them. */ + readonly rememberedRuntimeModes?: ReadonlyArray; + readonly rememberRuntimeModes?: (modes: ReadonlyArray) => Effect.Effect; } const RUNTIME_MODES_WITHOUT_AUTO = [ @@ -209,7 +212,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func presentation: { displayName: "Antigravity", showInteractionModeToggle: false, - supportedRuntimeModes: RUNTIME_MODES_WITHOUT_AUTO, + supportedRuntimeModes: options.rememberedRuntimeModes ?? RUNTIME_MODES_WITHOUT_AUTO, }, enabled: settings.enabled, checkedAt, @@ -246,6 +249,14 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func thinkingLevels.set(model.currentValue, antigravityThinkingConfig(configOptions) ?? null); } }; + const rememberRuntimeModes = Effect.fn("AntigravityProvider.rememberRuntimeModes")(function* ( + previous: ReadonlyArray | undefined, + next: ReadonlyArray, + ) { + if (options.rememberRuntimeModes && previous?.join() !== next.join()) { + yield* options.rememberRuntimeModes(next); + } + }); const getSnapshot = SubscriptionRef.get(metadata).pipe( Effect.flatMap((state) => options.stampIdentity(state.draft)), ); @@ -400,17 +411,18 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func const before = yield* SubscriptionRef.get(metadata); const supportsTextGeneration = yield* options.supportsTextGeneration; const updatedAt = DateTime.formatIso(yield* DateTime.now); - yield* SubscriptionRef.update(metadata, (state) => { + const supportedRuntimeModes = antigravityRuntimeModes(started.sessionSetupResult); + const previousModes = yield* SubscriptionRef.modify(metadata, (state) => { if ( state.authRevision !== before.authRevision && state.draft.auth.status === "unauthenticated" ) { - return state; + return [supportedRuntimeModes, state] as const; } const { message: _previousMessage, ...draft } = state.draft; const workspaces = draft.workspaceSnapshots ?? []; const workspace = cwd ? workspaces.find((entry) => entry.cwd === cwd) : undefined; - return { + const next = { authRevision: state.authRevision + 1, draft: { ...draft, @@ -424,7 +436,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func }, checkedAt: updatedAt, models: buildAntigravityModelsFromSession(started.sessionSetupResult, thinkingLevels), - supportedRuntimeModes: antigravityRuntimeModes(started.sessionSetupResult), + supportedRuntimeModes, supportsTextGeneration, ...(cwd ? { @@ -441,7 +453,9 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func : {}), }, } satisfies AntigravityProviderState; + return [draft.supportedRuntimeModes, next] as const; }); + yield* rememberRuntimeModes(previousModes, supportedRuntimeModes); if (!before.draft.usageLimits || before.draft.usageLimits.unavailable) yield* refreshUsage(); }); @@ -495,30 +509,30 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func yield* resetUsage; if (!settings.enabled) return; const updatedAt = DateTime.formatIso(yield* DateTime.now); - yield* SubscriptionRef.update( - metadata, - (state) => - ({ - authRevision: state.authRevision + 1, - draft: { - ...state.draft, - auth: { - status: "unauthenticated", - ...(usesCredentials ? options.auth : {}), - }, - status: "warning", - message: signInMessage, - checkedAt: updatedAt, - models: [], - slashCommands: [], - skills: [], - workspaceSnapshots: [], - supportedRuntimeModes: RUNTIME_MODES_WITHOUT_AUTO, - supportsTextGeneration: false, - usageLimits: undefined, + const previousModes = yield* SubscriptionRef.modify(metadata, (state) => [ + state.draft.supportedRuntimeModes, + { + authRevision: state.authRevision + 1, + draft: { + ...state.draft, + auth: { + status: "unauthenticated", + ...(usesCredentials ? options.auth : {}), }, - }) satisfies AntigravityProviderState, - ); + status: "warning", + message: signInMessage, + checkedAt: updatedAt, + models: [], + slashCommands: [], + skills: [], + workspaceSnapshots: [], + supportedRuntimeModes: RUNTIME_MODES_WITHOUT_AUTO, + supportsTextGeneration: false, + usageLimits: undefined, + }, + } satisfies AntigravityProviderState, + ]); + yield* rememberRuntimeModes(previousModes, RUNTIME_MODES_WITHOUT_AUTO); discoveredSkills.clear(); thinkingLevels.clear(); }); diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.ts b/apps/server/src/provider/Drivers/AntigravityDriver.ts index 3d426785813c3..b0d11b453dc61 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.ts @@ -3,8 +3,10 @@ import { AntigravitySettings, ProviderDriverKind, ProviderSetupError, + RuntimeMode, settingsSecretLiteral, } from "@t3tools/contracts"; +import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime"; import { @@ -17,6 +19,7 @@ import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; +import * as Option from "effect/Option"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; @@ -86,6 +89,11 @@ const isNodeRuntimeUnavailableError = Schema.is(NodeRuntimeUnavailableError); const isAcpRequestError = Schema.is(AcpErrors.AcpRequestError); const isProviderSetupError = Schema.is(ProviderSetupError); const isAcpErrorDetails = Schema.is(Schema.Struct({ details: Schema.String })); +const RememberedRuntimeModes = Schema.fromJsonString( + Schema.Struct({ authMethod: Schema.String, modes: Schema.Array(RuntimeMode) }), +); +const decodeRememberedRuntimeModes = Schema.decodeUnknownOption(RememberedRuntimeModes); +const encodeRememberedRuntimeModes = Schema.encodeSync(RememberedRuntimeModes); const REFRESH_FAILED = "Could not refresh Antigravity models. The previous model list is unchanged."; const PYTHON_SOCKS_REQUIRED = "python-socks is required to use a SOCKS proxy"; @@ -178,6 +186,18 @@ export const AntigravityDriver: ProviderDriver< ), ); const profileDirectory = directories.profile; + // Only a session reports whether agy offers Auto, so keep the last answer across restarts. + const runtimeModesPath = path.join(profileDirectory, "t3-runtime-modes.json"); + const rememberedRuntimeModes = yield* fileSystem.readFileString(runtimeModesPath).pipe( + Effect.map((contents) => + decodeRememberedRuntimeModes(contents).pipe( + Option.filter((saved) => saved.authMethod === auth.authMethod), + Option.map((saved) => saved.modes), + Option.getOrUndefined, + ), + ), + Effect.orElseSucceed(() => undefined), + ); for (const directory of [ directories.runtimeTemp, path.join(profileDirectory, "antigravity-acp", "tmp"), @@ -572,6 +592,16 @@ export const AntigravityDriver: ProviderDriver< probeUsage: usage.probe, clearUsage: usage.clear, auth: { type: auth.authMethod, label: antigravityAuthLabel(auth.authMethod) }, + ...(rememberedRuntimeModes ? { rememberedRuntimeModes } : {}), + rememberRuntimeModes: (modes) => + writeFileStringAtomically({ + filePath: runtimeModesPath, + contents: encodeRememberedRuntimeModes({ authMethod: auth.authMethod, modes }), + }).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + Effect.catch(() => Effect.logWarning("Could not save Antigravity permission modes.")), + ), supportsTextGeneration: isAntigravityTextGenerationAvailable(profileDirectory).pipe( Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.provideService(Path.Path, path), From 11224f63d2a3d444ca1fd1f67cd3ff21c1f5f8a1 Mon Sep 17 00:00:00 2001 From: Tgoh Date: Sun, 22 Nov 2026 17:31:26 +1000 Subject: [PATCH 03/17] fix(client-runtime): a new thread's first message and a queued send-now or steer survive a dropped socket (#40703) Co-authored-by: Julius Marminge --- .../src/components/ChatView.browser.test.tsx | 14 ++- .../src/operations/commands.test.ts | 119 ++++++++++++++++++ .../client-runtime/src/operations/commands.ts | 91 ++++++++------ 3 files changed, 181 insertions(+), 43 deletions(-) diff --git a/apps/web/src/components/ChatView.browser.test.tsx b/apps/web/src/components/ChatView.browser.test.tsx index cfd06a8864e0d..60c3c24ce5c2d 100644 --- a/apps/web/src/components/ChatView.browser.test.tsx +++ b/apps/web/src/components/ChatView.browser.test.tsx @@ -17,6 +17,7 @@ import { mergeWithDefaultKeybindings, } from "@t3tools/shared/keybindings"; import type * as Context from "effect/Context"; +import * as Schema from "effect/Schema"; import * as Effect from "effect/Effect"; import { expect, it, vi } from "vite-plus/test"; import { cdp, page, userEvent } from "vite-plus/test/browser"; @@ -89,6 +90,8 @@ function acceptAttachmentUploads(): Disposable { const insertText = (text: string) => cdp().send("Input.insertText", { text }); /** Holds every call to `method` until `release`, then ends it with `end`, until disposed. */ +class LaunchRefused extends Schema.TaggedError()("LaunchRefused", {}) {} + function holdRpc(method: string, end: Effect.Effect) { let release = () => {}; const held = new Promise((resolve) => { @@ -406,7 +409,7 @@ it("a new draft does not load its reserved thread before the server lists it", a expect(threadRequests).toEqual([]); }); -it("an interrupted image-only first send of a new thread says it may not have been sent", async () => { +it("a failed image-only first send of a new thread keeps the new draft", async () => { using _environment = installFakeEnvironment([]); __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, @@ -418,8 +421,11 @@ it("an interrupted image-only first send of a new thread says it may not have be .setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, { threadId: ThreadId.make("thread-image-only-interrupted"), }); - // A dropped connection interrupts a new thread's launch, which is not resent. - using launch = holdRpc(ORCHESTRATION_V2_WS_METHODS.launchThread, Effect.interrupt); + // A refusal fails at once; an interrupted launch would wait for a reconnect and be resent. + using launch = holdRpc( + ORCHESTRATION_V2_WS_METHODS.launchThread, + Effect.fail(new LaunchRefused()), + ); const router = getRouter(createMemoryHistory({ initialEntries: [`/draft/${draftId}`] })); await router.load(); await using _app = await render(, { @@ -445,7 +451,7 @@ it("an interrupted image-only first send of a new thread says it may not have be await expect.element(editor).toHaveTextContent("next draft"); launch.release(); - await expect.element(page.getByText("Message may not have been sent")).toBeVisible(); + await expect.element(page.getByText("Message not sent")).toBeVisible(); await expect.element(editor).toHaveTextContent("next draft"); // With no text there is nothing to copy. expect(page.getByText("Copy message", { exact: true }).query()).toBeNull(); diff --git a/packages/client-runtime/src/operations/commands.test.ts b/packages/client-runtime/src/operations/commands.test.ts index b2535a81123e1..941fdcd9b389e 100644 --- a/packages/client-runtime/src/operations/commands.test.ts +++ b/packages/client-runtime/src/operations/commands.test.ts @@ -28,6 +28,7 @@ import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; import * as SubscriptionRef from "effect/SubscriptionRef"; import * as TestClock from "effect/testing/TestClock"; import { RpcClientError } from "effect/rpc"; @@ -45,6 +46,7 @@ import { v2Now, v2Projection, v2ThreadId } from "../state/orchestrationV2TestFix import { archiveThread, interruptThreadTurn, + promoteQueuedRun, revertThreadCheckpoint, resumeThreadQueue, startThreadTurn, @@ -55,6 +57,8 @@ const layerTestRandom = Layer.succeed( SecureRandom.make((size) => new Uint8Array(size)), ); +class Refused extends Schema.TaggedError()("Refused", {}) {} + const TARGET = new PrimaryConnectionTarget({ environmentId: EnvironmentId.make("environment-1"), label: "Test environment", @@ -634,6 +638,121 @@ describe("V2 environment commands", () => { }).pipe(Effect.provide(layerTestRandom)), ); + const turnSends = [ + { + name: "new thread's first message", + method: ORCHESTRATION_V2_WS_METHODS.launchThread, + send: (commandId: CommandId) => + startThreadTurn({ + commandId, + threadId: v2ThreadId, + message: { + messageId: MessageId.make(commandId), + role: "user", + text: "hi", + attachments: [], + }, + runtimeMode: "full-access", + interactionMode: "default", + bootstrap: { + createThread: { + projectId: ProjectId.make("project-1"), + title: "Thread", + modelSelection: v2Projection.thread.modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdAt: "2026-06-20T00:00:00.000Z", + }, + }, + }), + }, + { + name: "queued message sent now", + method: ORCHESTRATION_V2_WS_METHODS.dispatchCommand, + send: (commandId: CommandId) => + resumeThreadQueue({ commandId, threadId: v2ThreadId, runId: RunId.make("queued") }), + }, + { + name: "queued message steered", + method: ORCHESTRATION_V2_WS_METHODS.dispatchCommand, + send: (commandId: CommandId) => + promoteQueuedRun({ + commandId, + threadId: v2ThreadId, + queuedRunId: RunId.make("queued"), + targetRunId: RunId.make("running"), + }), + }, + ] as const; + + const sendFailingFirstAttempt = Effect.fn("TestEnvironmentCommands.sendFailingFirstAttempt")( + function* (turnSend: (typeof turnSends)[number], failure: Effect.Effect) { + const supervisor = yield* makeSupervisor({ commands: [], projects: [], launches: [] }); + const healthySession = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session)); + const attempts: string[] = []; + const firstAttemptFailed = yield* Deferred.make(); + const healthyMethod = ( + healthySession.client as unknown as Record< + string, + (input: unknown) => Effect.Effect + > + )[turnSend.method]!; + const failingClient = { + ...healthySession.client, + [turnSend.method]: (input: { readonly commandId: CommandId }) => + Effect.gen(function* () { + attempts.push(input.commandId); + if (attempts.length > 1) return yield* healthyMethod(input); + yield* SubscriptionRef.set(supervisor.session, Option.none()); + yield* Deferred.succeed(firstAttemptFailed, undefined); + return yield* failure; + }), + } as unknown as WsRpcProtocolClient; + yield* SubscriptionRef.set( + supervisor.session, + Option.some({ ...healthySession, client: failingClient }), + ); + const sendFiber = yield* turnSend + .send(CommandId.make("command-turn-send")) + .pipe( + Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor), + Effect.forkChild, + ); + yield* Deferred.await(firstAttemptFailed); + yield* SubscriptionRef.set( + supervisor.session, + Option.some({ ...healthySession, client: failingClient }), + ); + return { exit: yield* Fiber.await(sendFiber), attempts }; + }, + ); + + it.effect.each(turnSends)("resends a $name lost to a session close", (turnSend) => + Effect.gen(function* () { + const { exit, attempts } = yield* sendFailingFirstAttempt( + turnSend, + Effect.failCause(Cause.interrupt()), + ); + + expect(attempts).toEqual(["command-turn-send", "command-turn-send"]); + expect(Exit.isSuccess(exit)).toBe(true); + }).pipe(Effect.provide(layerTestRandom)), + ); + + it.effect("doesn't resend a new thread's first message the server refused", () => + Effect.gen(function* () { + const { exit, attempts } = yield* sendFailingFirstAttempt( + turnSends[0], + Effect.fail(new Refused()), + ); + + expect(attempts).toEqual(["command-turn-send"]); + expect(Exit.isFailure(exit)).toBe(true); + }).pipe(Effect.provide(layerTestRandom)), + ); + it.effect("Stop with no run left ends the thread's pull request watches", () => Effect.gen(function* () { const link = { diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index ee17123e8839f..50e1449e3d5fc 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -315,28 +315,12 @@ const MAX_LOST_TRANSPORT_RESENDS = 2; // alone would leave the send pending forever. const MESSAGE_DISPATCH_TIMEOUT = "60 seconds"; -const dispatchMessage = Effect.fn("EnvironmentCommands.dispatchMessage")(function* ( - command: Extract, - resendAfterSocketLoss: boolean, -) { +const resendAfterSocketLoss = Effect.fn("EnvironmentCommands.resendAfterSocketLoss")(function* < + A, + E, + R, +>(attempt: Effect.Effect) { const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor; - const attempt = dispatch(command).pipe( - Effect.timeoutOrElse({ - duration: MESSAGE_DISPATCH_TIMEOUT, - orElse: () => - Effect.fail( - new EnvironmentRpcUnavailableError({ - environmentId: supervisor.target.environmentId, - ...translatableMessage( - msg("{host} did not confirm the message within 60 seconds.", { - host: supervisor.target.label, - }), - ), - }), - ), - }), - ); - if (!resendAfterSocketLoss) return yield* attempt; for (let resends = 0; ; resends += 1) { const attemptSession = yield* SubscriptionRef.get(supervisor.session); const exit = yield* Effect.exit(attempt); @@ -365,6 +349,30 @@ const dispatchMessage = Effect.fn("EnvironmentCommands.dispatchMessage")(functio } }); +const dispatchMessage = Effect.fn("EnvironmentCommands.dispatchMessage")(function* ( + command: Extract, + resend: boolean, +) { + const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor; + const attempt = dispatch(command).pipe( + Effect.timeoutOrElse({ + duration: MESSAGE_DISPATCH_TIMEOUT, + orElse: () => + Effect.fail( + new EnvironmentRpcUnavailableError({ + environmentId: supervisor.target.environmentId, + ...translatableMessage( + msg("{host} did not confirm the message within 60 seconds.", { + host: supervisor.target.label, + }), + ), + }), + ), + }), + ); + return yield* resend ? resendAfterSocketLoss(attempt) : attempt; +}); + const getProjection = (threadId: ThreadId) => request(ORCHESTRATION_V2_WS_METHODS.getThreadProjection, { threadId }); @@ -784,6 +792,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( input.message.attachments, attachments, ); + const resend = input.resendAfterSocketLoss ?? true; const bootstrap = input.bootstrap?.createThread; const prepareWorktree = input.bootstrap?.prepareWorktree; if (bootstrap !== undefined || prepareWorktree !== undefined) { @@ -815,7 +824,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( ? {} : { branch: bootstrap.branch }), }; - return yield* request(ORCHESTRATION_V2_WS_METHODS.launchThread, { + const launch = request(ORCHESTRATION_V2_WS_METHODS.launchThread, { commandId, creationSource: input.creationSource ?? "web", threadId: input.threadId, @@ -834,10 +843,10 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( attachments, }, }); + return yield* resend ? resendAfterSocketLoss(launch) : launch; } const requestedMode = input.dispatchMode ?? "auto"; - const resendAfterSocketLoss = input.resendAfterSocketLoss ?? true; if (requestedMode === "start") { return yield* dispatchMessage( { @@ -868,7 +877,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( ...(input.freshContext ? { freshContext: true } : {}), dispatchMode: { type: "start_immediately" }, }, - resendAfterSocketLoss, + resend, ); } @@ -899,7 +908,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( ...(requestedMode !== "queue" ? { deliveryIntent: requestedMode } : {}), dispatchMode, }, - resendAfterSocketLoss, + resend, ); }); @@ -1156,25 +1165,29 @@ export const mergeThreadBack = Effect.fn("EnvironmentCommands.mergeThreadBack")( export const resumeThreadQueue = Effect.fn("EnvironmentCommands.resumeThreadQueue")(function* ( input: ResumeThreadQueueInput, ) { - return yield* dispatch({ - ...(input.runId === undefined - ? { type: "queue.resume" as const } - : { type: "queued-run.start" as const, runId: input.runId }), - commandId: yield* allocateCommandId(input), - threadId: input.threadId, - }); + return yield* resendAfterSocketLoss( + dispatch({ + ...(input.runId === undefined + ? { type: "queue.resume" as const } + : { type: "queued-run.start" as const, runId: input.runId }), + commandId: yield* allocateCommandId(input), + threadId: input.threadId, + }), + ); }); export const promoteQueuedRun = Effect.fn("EnvironmentCommands.promoteQueuedRun")(function* ( input: PromoteQueuedRunInput, ) { - return yield* dispatch({ - type: "queued-message.promote-to-steer", - commandId: yield* allocateCommandId(input), - threadId: input.threadId, - queuedRunId: input.queuedRunId, - targetRunId: input.targetRunId, - }); + return yield* resendAfterSocketLoss( + dispatch({ + type: "queued-message.promote-to-steer", + commandId: yield* allocateCommandId(input), + threadId: input.threadId, + queuedRunId: input.queuedRunId, + targetRunId: input.targetRunId, + }), + ); }); export const cancelQueuedRun = Effect.fn("EnvironmentCommands.cancelQueuedRun")(function* ( From 02ea261f09d11a613c252c949c62627e56986fce Mon Sep 17 00:00:00 2001 From: tiliakoos <73005126+tiliakoos@users.noreply.github.com> Date: Sun, 22 Nov 2026 09:13:40 +0100 Subject: [PATCH 04/17] fix(server): long webhook prompts in the delivery log no longer end in a broken character (#40726) Co-authored-by: MarcoDotIO <20867620+MarcoDotIO@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../scheduledTasks/ScheduledTaskService.ts | 12 ++- .../ScheduledTaskService.webhook.test.ts | 22 ++++++ .../webhook-log-keeps-whole-emoji.e2e.ts | 75 +++++++++++++++++++ 3 files changed, 107 insertions(+), 2 deletions(-) create mode 100644 scripts/scenarios/webhook-log-keeps-whole-emoji.e2e.ts diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.ts index 68c95748d0ce8..3db6f783f649a 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts @@ -35,6 +35,7 @@ import * as Mac from "effect/crypto/Mac"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; import * as Exit from "effect/Exit"; import * as Duration from "effect/Duration"; @@ -90,6 +91,13 @@ const WEBHOOK_DEDUPE_LOG_PER_MINUTE = 10; const WEBHOOK_FILTERED_LOG_PER_MINUTE = 10; const WEBHOOK_DELIVERY_LOG_BODY_LIMIT = 64 * 1024; const WEBHOOK_DELIVERY_LOG_PROMPT_LIMIT = 64 * 1024; +const loggedWebhookPrompt = (prompt: string) => + prompt.slice( + 0, + splitsSurrogatePair(prompt, WEBHOOK_DELIVERY_LOG_PROMPT_LIMIT) + ? WEBHOOK_DELIVERY_LOG_PROMPT_LIMIT - 1 + : WEBHOOK_DELIVERY_LOG_PROMPT_LIMIT, + ); const WEBHOOK_MAX_QUEUED_PER_TASK = 20; // Enforce the relay's per-task/minute limit here too; tunnel hostnames are public. const WEBHOOK_RATE_LIMIT_PER_MINUTE = 60; @@ -1947,7 +1955,7 @@ export const layer = Layer.effect( ${loggedBody}, ${input.request.body.byteLength}, ${truncated ? 1 : 0}, ${input.outcome}, ${input.signatureVerified ? 1 : 0}, ${encodeMissingFieldsJson(input.missing)}, - ${input.renderedPrompt?.slice(0, WEBHOOK_DELIVERY_LOG_PROMPT_LIMIT) ?? null}, + ${input.renderedPrompt === null ? null : loggedWebhookPrompt(input.renderedPrompt)}, ${input.error ?? null} WHERE EXISTS (SELECT 1 FROM scheduled_tasks WHERE task_id = ${input.taskId}) -- A held request retried after a rate limit reuses its relay @@ -2636,7 +2644,7 @@ export const layer = Layer.effect( } else { if (taskJson !== null) yield* sql`UPDATE scheduled_task_webhook_pending SET task_json = ${taskJson} WHERE delivery_id = ${entry.delivery_id}`; - yield* sql`UPDATE scheduled_task_webhook_deliveries SET outcome = 'accepted', error = NULL, rendered_prompt = ${rendered.prompt.slice(0, WEBHOOK_DELIVERY_LOG_PROMPT_LIMIT)}, missing_fields_json = ${encodeMissingFieldsJson(rendered.missing)} WHERE delivery_id = ${entry.delivery_id}`; + yield* sql`UPDATE scheduled_task_webhook_deliveries SET outcome = 'accepted', error = NULL, rendered_prompt = ${loggedWebhookPrompt(rendered.prompt)}, missing_fields_json = ${encodeMissingFieldsJson(rendered.missing)} WHERE delivery_id = ${entry.delivery_id}`; if (!(yield* runWebhookDelivery(task, entry.delivery_id, rendered.prompt))) return; } yield* remove; diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts index e06ed817ac4f4..82db6f5e16407 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts @@ -571,6 +571,28 @@ it.effect("drops a character split by the delivery log's body limit", () => ), ); +it.effect("drops an emoji split by the delivery log's prompt limit", () => + withService(({ service }) => + Effect.gen(function* () { + const { task } = yield* service.upsert(yield* webhookTaskInput({ prompt: "{{body.text}}" })); + const limit = 64 * 1024; + const frameOpen = "".length; + // The emoji's high surrogate is the last code unit the log keeps. + const bodyText = JSON.stringify({ text: `${"a".repeat(limit - 1 - frameOpen)}😀 tail` }); + yield* service.triggerWebhook( + requestFor(task, { bodyText, body: new TextEncoder().encode(bodyText) }), + ); + const [summary] = (yield* service.listWebhookDeliveries({ id: task.id })).deliveries; + const { delivery } = yield* service.getWebhookDelivery({ + id: task.id, + deliveryId: summary!.id, + }); + assert.equal(delivery.renderedPrompt!.slice(-3), "aaa"); + assert.equal(delivery.renderedPrompt!.length, limit - 1); + }), + ), +); + const queuedDeliveryCases = [ { change: "paused", diff --git a/scripts/scenarios/webhook-log-keeps-whole-emoji.e2e.ts b/scripts/scenarios/webhook-log-keeps-whole-emoji.e2e.ts new file mode 100644 index 0000000000000..acd9096465978 --- /dev/null +++ b/scripts/scenarios/webhook-log-keeps-whole-emoji.e2e.ts @@ -0,0 +1,75 @@ +import { ProjectSnapshot, ProviderInstanceId } from "@t3tools/contracts"; +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; + +import { T3_HOME } from "../e2e.config.ts"; +import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts"; + +const PROMPT_LOG_LIMIT = 64 * 1024; +const FRAME_OPEN = "".length; + +const deliverStraddlingEmoji = Effect.fn("scenario.deliverStraddlingEmoji")( + function* (origin: string) { + const issued = yield* makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]); + const { projects } = yield* HttpClient.execute( + HttpClientRequest.get(`${origin}/api/projects`).pipe( + HttpClientRequest.bearerToken(issued.stdout.trim()), + ), + ).pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.flatMap(HttpClientResponse.schemaBodyJson(ProjectSnapshot)), + ); + const client = yield* rpcClient(T3_HOME, origin); + const { task } = yield* client["scheduledTasks.upsert"]({ + title: "Webhook log", + prompt: "{{body.text}}", + enabled: true, + schedule: { type: "webhook" }, + projectId: projects.find((project) => project.title === "webhook-log")!.id, + workspaceStrategy: { type: "root" }, + modelSelection: { instanceId: ProviderInstanceId.make("devReplay"), model: "showcase" }, + runtimeMode: "full-access", + interactionMode: "default", + }); + // The emoji's high surrogate is the last code unit the delivery log keeps. + const text = `${"a".repeat(PROMPT_LOG_LIMIT - 1 - FRAME_OPEN)}😀 tail`; + yield* HttpClient.execute( + HttpClientRequest.post(`${origin}${task.webhook!.path}`).pipe( + HttpClientRequest.bodyJsonUnsafe({ text }), + ), + ).pipe(Effect.flatMap(HttpClientResponse.filterStatusOk)); + }, + Effect.scoped, + Effect.provide(FetchHttpClient.layer), +); + +test( + "A long webhook prompt in the delivery log does not end in a broken character", + WEB, + async ({ t3, app, browser, screen }) => { + await t3.project("webhook-log"); + await runPromise(deliverStraddlingEmoji(app.baseUrl ?? "")); + + await t3.open("/settings/scheduled-tasks"); + await screen.getByRole("button", "Actions for Webhook log").tap(); + await screen.getByRole("menuitem", "Deliveries").tap(); + const dialog = screen.getByRole("dialog"); + await dialog.getByRole("button", /POST/).tap(); + const prompt = dialog.getByText(/^ { + const block = [...document.querySelectorAll("pre")].find((pre) => + pre.textContent?.startsWith(" Date: Sun, 22 Nov 2026 00:20:29 -0800 Subject: [PATCH 05/17] fix(server): a released ACP session no longer leaves its run stuck running (#40734) --- .../RunExecutionService.test.ts | 42 +++++++++++++++++++ .../orchestration-v2/RunExecutionService.ts | 14 +++---- 2 files changed, 49 insertions(+), 7 deletions(-) diff --git a/apps/server/src/orchestration-v2/RunExecutionService.test.ts b/apps/server/src/orchestration-v2/RunExecutionService.test.ts index 1d13620b75623..3667867904ec9 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.test.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.test.ts @@ -3596,6 +3596,48 @@ it.effect("ends a running root command when the provider stream fails mid-turn", }), ); +it.effect("fails the run when a released session's interrupt exits interrupted", () => + Effect.gen(function* () { + const now = yield* DateTime.now; + const key = "released-session-interrupted-interrupt"; + const { observed, finalEvents } = yield* captureRootRunTermination({ + key, + shouldFinalizeRun: () => Effect.succeed(true), + events: (ids) => + Stream.make({ + type: "provider_turn.updated" as const, + driver, + providerTurn: { + id: ids.rootProviderTurnId, + providerThreadId: ids.providerThreadId, + nodeId: ids.rootNodeId, + runAttemptId: ids.attemptId, + nativeTurnRef: null, + ordinal: 1, + status: "running" as const, + startedAt: now, + completedAt: null, + }, + }).pipe( + Stream.concat( + Stream.fail( + new ProviderAdapter.ProviderAdapterEventStreamError({ + driver, + providerSessionId: ProviderSessionId.make(`session:${key}`), + raisedByT3: true, + cause: "Provider sign-in changed.", + }), + ), + ), + ), + // An ACP session whose scope is already closing interrupts the join. + interruptTurn: () => Effect.interrupt, + }); + assert.deepEqual(observed, ["run:failed", "pull-requests-refreshed"]); + assert.isTrue(finalEvents.some((event) => event.type === "run.updated")); + }), +); + it.effect("keeps a running root command open when a write fails under a live provider", () => Effect.gen(function* () { const key = "write-error-running-command"; diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index 34cc31f98fa09..1e301e12fa8fe 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -2135,13 +2135,13 @@ export const layer: Layer.Layer< }) .pipe( Effect.as(true), - Effect.catchCauseIf( - (interruptCause) => !Cause.hasInterruptsOnly(interruptCause), - (interruptCause) => - Effect.logWarning( - "orchestration V2 failed to interrupt turn after ingestion failure", - { runId: input.run.id, cause: interruptCause }, - ).pipe(Effect.as(false)), + // An adapter whose session scope is closing exits interrupted. That is + // its fiber, not this one: Effect never hands a fiber its own interrupt. + Effect.catchCause((interruptCause) => + Effect.logWarning( + "orchestration V2 failed to interrupt turn after ingestion failure", + { runId: input.run.id, cause: interruptCause }, + ).pipe(Effect.as(false)), ), // A failed interrupt leaves the stored turn running so the next start // retries it. The snapshot is cached before it is published, so it may From cd3a57ac7221b4151fb7c64a132d9ba59d98beaa Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 00:26:39 -0800 Subject: [PATCH 06/17] feat(web): sidebar thread rows show the environment instead of the branch (#40736) Co-authored-by: Claude Opus 5.5 --- apps/web/src/components/Sidebar.tsx | 16 -------- .../src/components/ThreadStatusIndicators.tsx | 38 +---------------- .../components/sidebar/SidebarThreadRow.tsx | 41 +++++++------------ apps/web/src/i18n/translations/de.json | 2 - apps/web/src/i18n/translations/en.json | 2 - apps/web/src/i18n/translations/es.json | 2 - apps/web/src/i18n/translations/fr.json | 2 - apps/web/src/i18n/translations/ja.json | 2 - apps/web/src/i18n/translations/ko.json | 2 - apps/web/src/i18n/translations/pt-BR.json | 2 - apps/web/src/i18n/translations/ru.json | 2 - apps/web/src/i18n/translations/sv.json | 2 - apps/web/src/i18n/translations/zh.json | 2 - 13 files changed, 15 insertions(+), 100 deletions(-) diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 45e00246e2c6d..98ed2224169cd 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -171,7 +171,6 @@ import { resolveThreadRouteTarget, } from "../threadRoutes"; import type { SidebarThreadSummary } from "../types"; -import { isScratchProject } from "@t3tools/client-runtime/state/projects"; import { cn } from "~/lib/utils"; import { ProjectEnvironmentBadge } from "./ProjectEnvironmentBadge"; import { ProjectRowActions } from "./ProjectComboboxRow"; @@ -1162,19 +1161,6 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }, [clearSelection, revealWidensScope, setPersistedProjectScopeKeys]); const revealActiveRow = useActiveRowReveal(routeReveal, routeRowThreadKey, routeKeyInPlace); const showProjectEnvironments = projectGroupsSpanEnvironments(projectGroups); - const scratchMachineLabelFor = ( - thread: Pick, - ) => { - if (!showProjectEnvironments) return null; - const project = projectByKey.get(`${thread.environmentId}:${thread.projectId}`); - if ( - !project || - !isScratchProject(project, serverConfigs.get(thread.environmentId)?.scratchWorkspaceRoot) - ) { - return null; - } - return environmentLabelById.get(thread.environmentId) ?? null; - }; // Pinning from a row keeps rows in place while the menu is open. const projectScopeItems = useOrderWhileOpen( lookupProjectScopeItems, @@ -3523,14 +3509,12 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve jumpLabel={ showJumpHints ? (jumpLabelByKey.get(threadKey) ?? null) : null } - currentEnvironmentId={primaryEnvironmentId} environmentLabel={ environmentLabelById.get(thread.environmentId) ?? null } environmentMachine={ environmentMachineById.get(thread.environmentId) ?? "server" } - scratchMachineLabel={scratchMachineLabelFor(thread)} project={ projectByKey.get(`${thread.environmentId}:${thread.projectId}`) ?? null diff --git a/apps/web/src/components/ThreadStatusIndicators.tsx b/apps/web/src/components/ThreadStatusIndicators.tsx index 9c5e7fa3d830d..905d9cb2131fe 100644 --- a/apps/web/src/components/ThreadStatusIndicators.tsx +++ b/apps/web/src/components/ThreadStatusIndicators.tsx @@ -19,7 +19,7 @@ import { type VcsStatusResult, } from "@t3tools/contracts"; import { msg, T, useGT, useMessages } from "gt-react"; -import { FolderGit2Icon, TerminalIcon } from "lucide-react"; +import { TerminalIcon } from "lucide-react"; import { m, type MessageResolver } from "../i18n/messages"; import { useEnvironment, usePrimaryEnvironmentId } from "../state/environments"; import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon"; @@ -53,7 +53,6 @@ import { } from "./Sidebar.logic"; import type { SidebarThreadSummary } from "../types"; -import { formatWorktreePathForDisplay } from "../worktreeCleanup"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { PULL_REQUEST_STATE_PRESENTATION, @@ -770,41 +769,6 @@ export function ThreadTerminalStatusButton({ ); } -export function ThreadWorktreeIndicator({ - thread, -}: { - thread: Pick; -}) { - const gt = useGT(); - const worktreePath = thread.worktreePath?.trim(); - if (!worktreePath) { - return null; - } - - const displayPath = formatWorktreePathForDisplay(worktreePath); - const tooltip = thread.branch - ? gt("Worktree: {path} ({branch})", { path: displayPath, branch: thread.branch }) - : gt("Worktree: {path}", { path: displayPath }); - - return ( - - - } - > - - - {tooltip} - - ); -} - function ThreadStatusLabel({ status, compact = false, diff --git a/apps/web/src/components/sidebar/SidebarThreadRow.tsx b/apps/web/src/components/sidebar/SidebarThreadRow.tsx index 878cbc894bb88..2aa9be4c244a6 100644 --- a/apps/web/src/components/sidebar/SidebarThreadRow.tsx +++ b/apps/web/src/components/sidebar/SidebarThreadRow.tsx @@ -3,6 +3,7 @@ import { asLaunchingThread } from "@t3tools/client-runtime/state/thread-inbox"; import { ThreadHoverCard, ThreadHoverCardPopup } from "../ThreadHoverCard"; import { ThreadTerminalStatusButton } from "../ThreadStatusIndicators"; import { discardComposerDraft } from "../../lib/discardComposerDraft"; +import { formatWorktreePathForDisplay } from "../../worktreeCleanup"; import { contextMenuSourceOf } from "../../contextMenuSource"; import { requestCustomSnooze } from "../CustomSnoozeDialog"; import { useSupportsMultiplePullRequests } from "~/hooks/useSupportsMultiplePullRequests"; @@ -47,6 +48,7 @@ import { CircleDashedIcon, CircleDotDashedIcon, ClockIcon, + FolderGit2Icon, GitBranchIcon, MessageCircleQuestionIcon, PinIcon, @@ -105,7 +107,6 @@ import { resolveLocalCheckoutBranchMismatch } from "../BranchToolbar.logic"; import { ThreadPullRequestBadgeControl, ThreadPullRequestsMiniList, - ThreadWorktreeIndicator, prStatusIndicator, resolveThreadPullRequestBadge, terminalStatusFromRunningIds, @@ -285,6 +286,7 @@ function SidebarThreadTooltip({ terminalProcessCount: number; }) { const driverKind = providerEntry?.driverKind ?? null; + const worktreePath = thread.worktreePath?.trim(); const previousProviderNames = thread.providerInstanceHistory .filter((instanceId) => instanceId !== modelInstanceId) .map((instanceId) => providerEntryByInstanceId.get(instanceId)?.displayName ?? instanceId); @@ -324,6 +326,12 @@ function SidebarThreadTooltip({ ) : null} + {worktreePath ? ( +
+ + +
+ ) : null} {branchMismatch ? (
@@ -575,7 +583,7 @@ function TopStatusIcon(props: { icon: keyof typeof TOP_STATUS_ICONS; className: type SidebarThreadRowProps = { thread: SidebarThreadSummary; // "folder" is a one-line row inside a boring sidebar project folder; - // "folder-multiline" adds the card's branch and PR line under it. + // "folder-multiline" adds the card's environment and PR line under it. variant: "card" | "slim" | "folder" | "folder-multiline"; navigationParent?: string | undefined; variantAction: SidebarSweepAction; @@ -598,10 +606,8 @@ type SidebarThreadRowProps = { // Read at click time; a prop would re-render every row on entering or leaving a thread route. readOpensPullRequestsInRightPanel: () => boolean; jumpLabel: string | null; - currentEnvironmentId: string | null; environmentLabel: string | null; environmentMachine: EnvironmentMachineKind; - scratchMachineLabel: string | null; project: EnvironmentProject | null; projectDisplayName: string | null; providerEntryByInstanceId: ReadonlyMap; @@ -863,9 +869,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP ? getTriggerDisplayModelName(selectedModel, providerEntry?.driverKind) : thread.modelSelection.model; - const isRemote = thread.environmentId !== props.currentEnvironmentId; - const showsScratchMachine = !checkoutThread.branch && props.scratchMachineLabel !== null; - const detailsTooltip = ( - - - ) : null; const diff = latestRunDiff(thread); // Only the trailing icons would remain, so the row moves them to the title line instead. const metaLineEmpty = - !checkoutThread.branch && - !showsScratchMachine && + props.environmentLabel === null && prBadge === null && issueBadge === null && diff === null && runningTerminalIds.length === 0; const metaLine = metaLineEmpty ? null : (
- {checkoutThread.branch ? ( - <> - - - - - - ) : showsScratchMachine ? ( + {props.environmentLabel !== null ? ( <> - {props.scratchMachineLabel} + {props.environmentLabel} ) : ( @@ -1305,7 +1294,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP aria-hidden className="pointer-events-none ml-auto inline-flex shrink-0 items-center gap-1" > - {remoteMachineIcon} - {remoteMachineIcon} Date: Sun, 22 Nov 2026 00:52:35 -0800 Subject: [PATCH 07/17] fix: a failed checkpoint capture keeps Edit from here for conversation rewind (#40745) --- .../CheckpointCaptureService.test.ts | 17 ++++++++++ .../CheckpointRollbackService.test.ts | 31 ++++++++++++++++--- .../CheckpointRollbackService.ts | 4 ++- .../src/orchestration-v2/Orchestrator.ts | 3 +- .../src/orchestration-v2/ProjectionStore.ts | 4 +-- .../src/orchestration-v2/runtimeLayer.test.ts | 22 +++++++++++++ apps/web/src/session-logic.test.ts | 10 +++++- apps/web/src/session-logic.ts | 6 ++-- .../client-runtime/src/operations/commands.ts | 4 +-- 9 files changed, 86 insertions(+), 15 deletions(-) diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts index aa85cd675dc1a..2110bc3eca027 100644 --- a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts @@ -956,6 +956,23 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { scopeId: cancelledScopeId, }); assert.deepEqual(afterRewind.preservedCheckpointOrdinals, [0]); + + // A failed capture still records which run ended there; the next capture must keep that link. + yield* projectionStore.apply({ + id: EventId.make("event:checkpoint-capture-cancelled:captured-error"), + type: "checkpoint.captured", + threadId: cancelledThreadId, + runId: cancelledRunId, + nodeId: cancelledRootNodeId, + providerInstanceId, + occurredAt: cancelledAt, + payload: { ...captured, status: "error" }, + }); + const afterFailedCapture = yield* projectionStore.getCheckpointCaptureContext( + cancelledThreadId, + { runId: cancelledRunId, scopeId: cancelledScopeId }, + ); + assert.deepEqual([...afterFailedCapture.preservedCheckpointOrdinals].toSorted(), [0, 1]); }), ); diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts index 2f41a9a379306..ff368dccb64d9 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts @@ -401,9 +401,14 @@ it.effect.each([ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); -it.effect.each([{ restoreFiles: true }, { restoreFiles: false }])( - "holds turn starts inside the worktree during rollback with restoreFiles $restoreFiles", - ({ restoreFiles }) => +it.effect.each([ + { restoreFiles: true, status: "ready" }, + { restoreFiles: false, status: "ready" }, + // A failed capture still pins the conversation. + { restoreFiles: false, status: "error" }, +])( + "holds turn starts inside the worktree during rollback with restoreFiles $restoreFiles to a $status checkpoint", + ({ restoreFiles, status }) => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -438,7 +443,7 @@ it.effect.each([{ restoreFiles: true }, { restoreFiles: false }])( providerInstanceId, }, providerSession: undefined, - checkpoint: { id: checkpointId, scopeId, status: "ready", appRunOrdinal: 0 }, + checkpoint: { id: checkpointId, scopeId, status, appRunOrdinal: 0 }, scope: { id: scopeId, cwd: worktreePath }, runsToRollback: [], targetAttempt: undefined, @@ -840,7 +845,7 @@ const seedRollbackHistory = Effect.gen(function* () { ), ), ); - const rollback = (ordinal: number) => + const rollback = (ordinal: number, restoreFiles?: boolean) => Effect.gen(function* () { const service = yield* CheckpointRollbackService.CheckpointRollbackServiceV2; yield* service.execute({ @@ -848,6 +853,7 @@ const seedRollbackHistory = Effect.gen(function* () { providerThreadId, scopeId, checkpointId: checkpointId(ordinal), + ...(restoreFiles === undefined ? {} : { restoreFiles }), }); }).pipe(Effect.provide(serviceLayer)); @@ -943,6 +949,21 @@ it.layer(ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMe }), ); + it.effect("rewinds the conversation to a run whose snapshot capture failed", () => + Effect.gen(function* () { + const history = yield* seedRollbackHistory; + const sql = yield* SqlClient.SqlClient; + yield* sql`UPDATE orchestration_v2_projection_checkpoints + SET status = 'error', payload_json = json_set(payload_json, '$.status', 'error') + WHERE checkpoint_id = ${history.checkpointId(2)}`; + + yield* history.rollback(2, false); + + assert.deepEqual(history.rollbackCounts, [4]); + assert.deepEqual(history.restored, []); + }), + ); + it.effect( "rewinds stopped runs repeatedly without counting discarded provider turns again", () => diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts index 6f9fe79cfde3b..8d6fd1c09441d 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts @@ -178,8 +178,10 @@ export const layer: Layer.Layer< // A repository's checkpoints follow the thread's; they are not a place to rewind to. typeof scope.repositoryPath === "string" || checkpoint.scopeId !== scope.id || - // Missing snapshots support conversation rewind, and restoring a task folder's repositories. + // Missing or failed snapshots support conversation rewind; missing ones also restoring a + // task folder's repositories. (checkpoint.status !== "ready" && + !(checkpoint.status === "error" && !restoreFiles) && !(checkpoint.status === "missing" && (!restoreFiles || linkedProjectFolder))) ) { return yield* invalidTarget(); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 995ff63b25747..61f5027793569 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -14534,9 +14534,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio targetCheckpoint.appRunOrdinal ?? 0, ) !== null, ); - // Missing snapshots otherwise support conversation rewind only. + // Missing or failed snapshots otherwise support conversation rewind only. if ( targetCheckpoint.status !== "ready" && + !(targetCheckpoint.status === "error" && command.restoreFiles === false) && !( targetCheckpoint.status === "missing" && (command.restoreFiles === false || restoresRepositories) diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 6c8308706b651..a42679d304765 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -6379,7 +6379,7 @@ export const layer: Layer.Layer = runRows[0] === undefined ? undefined : yield* decodeRunPayload(runRows[0].payload_json); - const preservedCheckpoint = sql`(status = 'ready' OR (status = 'missing' AND run_id IS NOT NULL))`; + const preservedCheckpoint = sql`(status = 'ready' OR (status IN ('missing', 'error') AND run_id IS NOT NULL))`; const [ nodeRows, scopeRows, @@ -6491,7 +6491,7 @@ export const layer: Layer.Layer = checkpoint === undefined || scope === undefined || checkpoint.scopeId !== scope.id || - (checkpoint.status !== "ready" && checkpoint.status !== "missing") || + checkpoint.status === "stale" || providerThread.id !== thread.activeProviderThreadId || providerThread.providerInstanceId !== thread.modelSelection.instanceId ) diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index b5072355659ef..843e51da40423 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -1878,6 +1878,28 @@ it.layer(layerTest)("OrchestrationV2LayerLive", (it) => { [], ); assert.deepEqual(yield* outbox.listByCommandId(commandId), []); + if (status === "error") { + // A failed capture still pins the conversation. + const conversationCommandId = CommandId.make("runtime-rollback-error-conversation"); + const conversationOnly = yield* orchestrator.dispatch({ + type: "checkpoint.rollback", + commandId: conversationCommandId, + threadId, + checkpointId, + scopeId: scope.id, + restoreFiles: false, + }); + assert.deepEqual( + conversationOnly.storedEvents.map((stored) => stored.event.type), + ["thread.metadata-updated", "checkpoint.rollback-requested"], + ); + assert.deepEqual( + (yield* outbox.listByCommandId(conversationCommandId)).map( + (effect) => effect.request.type, + ), + ["provider-thread.rollback"], + ); + } } } }).pipe(Effect.provide(Layer.fresh(layerTest))), diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.ts index f4670665add6c..2155fedaa83c1 100644 --- a/apps/web/src/session-logic.test.ts +++ b/apps/web/src/session-logic.test.ts @@ -290,7 +290,10 @@ describe("V2 session presentation", () => { }, }; }); - const checkpoint = (ordinal: number, status: "ready" | "missing" | "stale" = "ready") => ({ + const checkpoint = ( + ordinal: number, + status: "ready" | "missing" | "stale" | "error" = "ready", + ) => ({ runId: runId(ordinal), checkpointTurnCount: ordinal, checkpointRef: `checkpoint-${ordinal}` as never, @@ -326,6 +329,11 @@ describe("V2 session presentation", () => { "user-1": 0, "user-2": 1, }); + // A failed snapshot capture still pins the conversation; only file restore needs one. + expect(targets([1, 2], [checkpoint(1, "error")])).toEqual({ + "user-1": 0, + "user-2": 1, + }); }); it("preserves a notification-only wake run while ignoring inherited and unrelated work", () => { diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts index 1122c3122aca0..5196ee43458d8 100644 --- a/apps/web/src/session-logic.ts +++ b/apps/web/src/session-logic.ts @@ -1153,10 +1153,10 @@ export function deriveRevertTurnCountByUserMessageId(input: { return byUserMessageId; } -// A missing snapshot (no git, or a side chat) still pins a conversation position; only -// restoring files needs a ready one. +// A missing or failed snapshot (no git, a side chat, a capture error) still pins a +// conversation position; only restoring files needs a ready one. function isRewindableCheckpoint(checkpoint: Pick) { - return checkpoint.status === "ready" || checkpoint.status === "missing"; + return checkpoint.status !== "stale"; } export function findRevertCheckpoint( diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index 50e1449e3d5fc..0ea95420460a7 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -1074,9 +1074,9 @@ export const revertThreadCheckpoint = Effect.fn("EnvironmentCommands.revertThrea ); if ( checkpoint === undefined || - // Missing snapshots support conversation rewind only. + // Missing or failed snapshots support conversation rewind only. (checkpoint.status !== "ready" && - !(input.restoreFiles === false && checkpoint.status === "missing")) + !(input.restoreFiles === false && checkpoint.status !== "stale")) ) { const target = input.checkpointId === undefined From 15a3daa32a745bc56be9d7dbb346d80661e6b7bd Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 01:00:28 -0800 Subject: [PATCH 08/17] docs(claude): mobile shows the compact chip too (#40755) --- docs/user/providers-claude.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/user/providers-claude.md b/docs/user/providers-claude.md index 84c13d30c4c84..00b27e02ae23d 100644 --- a/docs/user/providers-claude.md +++ b/docs/user/providers-claude.md @@ -63,8 +63,8 @@ When you return to a large thread after Claude's prompt cache expires, a **Compact** chip with the thread's token count shows next to the send button. While it is on, Enter summarizes the history first, then sends your message. Click the chip to switch it to **Keep** and keep the full -history for that message. The mobile app shows no chip: an eligible message sent -from it summarizes first. The cache lasts about an hour on a Claude +history for that message. The mobile app shows the same chip, labelled with the +token count: tap it to keep the full history for that message. The cache lasts about an hour on a Claude subscription and 5 minutes with an API key, Bedrock, or Vertex. See [commands and skills](./composer.md#commands-and-skills) for using composer commands. From e3f9db2447fcfd82e76f7782ca5254e2c7ad80a6 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 01:08:22 -0800 Subject: [PATCH 09/17] fix(server): TanStack Source pull requests open from every client, and private ones work end to end (#40741) --- .../pull-requests/PullRequestListRow.tsx | 12 ++ .../pull-requests/PullRequestRouteScreen.tsx | 11 ++ .../pull-requests/pullRequestGlyphs.ts | 1 + .../features/pull-requests/pullRequestList.ts | 1 + 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/src/git/GitManager.test.ts | 133 ++++++++++++++++ apps/server/src/git/GitManager.ts | 144 +++++++++++++++++- .../toolkits/pullRequests/handlers.test.ts | 15 +- .../src/mcp/toolkits/pullRequests/handlers.ts | 2 + .../src/mcp/toolkits/pullRequests/tools.ts | 8 + .../src/provider/agentContextBudget.json | 2 +- .../src/pullRequest/PullRequestService.ts | 4 + .../SourceControlProviderRegistry.ts | 9 ++ .../pullRequest/PullRequestDetailLayout.tsx | 29 +++- .../pullRequest/PullRequestDetailPanel.tsx | 2 + .../components/pullRequest/PullRequestRow.tsx | 4 + docs/user/source-control.md | 4 +- packages/contracts/src/pullRequest.ts | 8 + .../src/server/PullRequestProvider.ts | 3 + .../src/server/SourceControlProvider.ts | 14 ++ .../TanStackSourcePullRequestProvider.test.ts | 138 +++++++++++++++++ ...anStackSourceSourceControlProvider.test.ts | 107 ++++++++++++- .../TanStackSourceSourceControlProvider.ts | 46 +++++- .../src/server/tanStackSourceHosts.test.ts | 19 +++ .../src/server/tanStackSourceHosts.ts | 16 +- .../src/server/tanStackSourceJson.test.ts | 1 + .../src/server/tanStackSourceJson.ts | 27 +++- .../src/shared/definition.test.ts | 16 ++ .../src/shared/definition.ts | 19 ++- 38 files changed, 774 insertions(+), 31 deletions(-) create mode 100644 packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.test.ts create mode 100644 packages/source-control-tanstack-source/src/server/tanStackSourceHosts.test.ts diff --git a/apps/mobile/src/features/pull-requests/PullRequestListRow.tsx b/apps/mobile/src/features/pull-requests/PullRequestListRow.tsx index 5daf5ef20565b..7b904c8e33105 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestListRow.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestListRow.tsx @@ -122,6 +122,7 @@ export const PullRequestListRow = memo( ), item.title, status.label, + item.visibility === "private" ? gt("Private") : null, conflict ? conflict.label.toLowerCase() : null, gt("by {author}", { author: item.author?.login ?? gt("unknown author") }), review ? review.accessibleLabel : null, @@ -178,6 +179,17 @@ export const PullRequestListRow = memo( {item.repository} #{item.number} + {item.visibility === "private" ? ( + + + + ) : null} {item.stack ? ( {status.label} )} + {"visibility" in pr && pr.visibility === "private" ? ( + + + {gt("Private")} + + ) : null} {"changedFiles" in pr && pr.changedFiles !== undefined ? ( diff --git a/apps/mobile/src/features/pull-requests/pullRequestGlyphs.ts b/apps/mobile/src/features/pull-requests/pullRequestGlyphs.ts index fa79d882cc23d..16b84c596d627 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestGlyphs.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestGlyphs.ts @@ -7,4 +7,5 @@ export const PullRequestGlyph = { merged: "arrow.triangle.merge", stack: "square.3.layers.3d", conflicting: "exclamationmark.triangle", + private: { ios: "lock.fill", android: "lock" }, } as const satisfies Record; diff --git a/apps/mobile/src/features/pull-requests/pullRequestList.ts b/apps/mobile/src/features/pull-requests/pullRequestList.ts index e7c2f5de769c4..3b30c11d65e64 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestList.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestList.ts @@ -190,6 +190,7 @@ export function pullRequestListRowsAreEqual( previous.title === next.title && previous.url === next.url && previous.state === next.state && + previous.visibility === next.visibility && previous.isDraft === next.isDraft && previous.mergeability === next.mergeability && previous.baseBranch === next.baseBranch && diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index f538b87920412..039e1ddadd0bf 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -2851,6 +2851,7 @@ "f9d3c8aa453829ce": "Tippe auf eine Person, um ein Review anzufordern. Tippe auf einen angefragten Reviewer, um die Anfrage zu entfernen. Änderungen werden beim Schließen dieses Fensters gesendet.", "8d3770f150f0bcb4": "Angefragt", "fff1c3d17603f394": "Dieser Anbieter akzeptiert eine Reviewer-ID, kann aber keine Kandidaten auflisten.", + "bbb7d40a7ad7ab71": "Privat", "85ae9979ad3b0c1e": "Basis-Branch {branch} kopieren", "06a684782801e8f7": "Head-Branch {branch} kopieren", "8e4f3c862193b8a5": "Bearbeiten", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 745201ad99094..91170171c1621 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -2851,6 +2851,7 @@ "f9d3c8aa453829ce": "Tap someone to request a review. Tap a requested reviewer to remove the request. Changes are sent when you close this sheet.", "8d3770f150f0bcb4": "Requested", "fff1c3d17603f394": "This provider accepts a reviewer ID but cannot list candidates.", + "bbb7d40a7ad7ab71": "Private", "85ae9979ad3b0c1e": "Copy base branch {branch}", "06a684782801e8f7": "Copy head branch {branch}", "8e4f3c862193b8a5": "Edit", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index fb134339cd3c4..398c20ce17f1f 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -2847,6 +2847,7 @@ "f9d3c8aa453829ce": "Toca a alguien para solicitarle una revisión. Toca a un revisor solicitado para quitar la solicitud. Los cambios se envían al cerrar esta hoja.", "8d3770f150f0bcb4": "Solicitado", "fff1c3d17603f394": "Este proveedor acepta un ID de revisor, pero no puede listar candidatos.", + "bbb7d40a7ad7ab71": "Privado", "85ae9979ad3b0c1e": "Copiar la rama base {branch}", "06a684782801e8f7": "Copiar la rama head {branch}", "8e4f3c862193b8a5": "Editar", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index d6aef220df3a2..1734d91934a04 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -2847,6 +2847,7 @@ "f9d3c8aa453829ce": "Touchez une personne pour lui demander une revue. Touchez un relecteur sollicité pour retirer la demande. Les modifications sont envoyées à la fermeture de ce panneau.", "8d3770f150f0bcb4": "Sollicité", "fff1c3d17603f394": "Ce fournisseur accepte un ID de relecteur mais ne peut pas lister les candidats.", + "bbb7d40a7ad7ab71": "Privé", "85ae9979ad3b0c1e": "Copier la branche de base {branch}", "06a684782801e8f7": "Copier la branche de tête {branch}", "8e4f3c862193b8a5": "Modifier", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 8cd9fba5c8332..113ada551f17d 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -2844,6 +2844,7 @@ "f9d3c8aa453829ce": "ユーザーをタップするとレビューをリクエストします。リクエスト済みのレビュアーをタップするとリクエストを削除します。変更はこのシートを閉じたときに送信されます。", "8d3770f150f0bcb4": "リクエスト済み", "fff1c3d17603f394": "このプロバイダーはレビュアー ID を受け付けますが、候補を一覧表示できません。", + "bbb7d40a7ad7ab71": "プライベート", "85ae9979ad3b0c1e": "ベースブランチ {branch} をコピー", "06a684782801e8f7": "ヘッドブランチ {branch} をコピー", "8e4f3c862193b8a5": "編集", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 731eaeecaec22..7768bd410d434 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -2848,6 +2848,7 @@ "f9d3c8aa453829ce": "검토를 요청하려면 사람을 탭하세요. 요청을 제거하려면 요청된 검토자를 탭하세요. 변경 사항은 이 시트를 닫을 때 전송됩니다.", "8d3770f150f0bcb4": "요청됨", "fff1c3d17603f394": "이 제공자는 검토자 ID를 받지만 후보를 나열할 수 없습니다.", + "bbb7d40a7ad7ab71": "비공개", "85ae9979ad3b0c1e": "기준 브랜치 {branch} 복사", "06a684782801e8f7": "헤드 브랜치 {branch} 복사", "8e4f3c862193b8a5": "편집", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 2c4ee1bc64fc4..88dbb8da5cd87 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -2847,6 +2847,7 @@ "f9d3c8aa453829ce": "Toque em alguém para solicitar uma revisão. Toque em um revisor solicitado para remover a solicitação. As alterações são enviadas quando você fecha esta folha.", "8d3770f150f0bcb4": "Solicitado", "fff1c3d17603f394": "Este provedor aceita um ID de revisor, mas não consegue listar candidatos.", + "bbb7d40a7ad7ab71": "Privado", "85ae9979ad3b0c1e": "Copiar branch base {branch}", "06a684782801e8f7": "Copiar branch head {branch}", "8e4f3c862193b8a5": "Editar", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index c4f78e560083b..2d0fb55302031 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -2899,6 +2899,7 @@ "f9d3c8aa453829ce": "Нажмите на человека, чтобы запросить ревью. Нажмите на запрошенного ревьюера, чтобы отменить запрос. Изменения отправляются при закрытии этой панели.", "8d3770f150f0bcb4": "Запрошен", "fff1c3d17603f394": "Этот провайдер принимает ID ревьюера, но не может показать список кандидатов.", + "bbb7d40a7ad7ab71": "Приватный", "85ae9979ad3b0c1e": "Копировать базовую ветку {branch}", "06a684782801e8f7": "Копировать head-ветку {branch}", "8e4f3c862193b8a5": "Изменить", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index fa3a3dd6d039f..70617afd183ca 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -2851,6 +2851,7 @@ "f9d3c8aa453829ce": "Tryck på någon för att begära en granskning. Tryck på en begärd granskare för att ta bort begäran. Ändringarna skickas när du stänger det här bladet.", "8d3770f150f0bcb4": "Begärd", "fff1c3d17603f394": "Leverantören accepterar ett granskar-id men kan inte lista kandidater.", + "bbb7d40a7ad7ab71": "Privat", "85ae9979ad3b0c1e": "Kopiera basgrenen {branch}", "06a684782801e8f7": "Kopiera huvudgrenen {branch}", "8e4f3c862193b8a5": "Redigera", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index f36e76805c298..485d4206bf054 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -2848,6 +2848,7 @@ "f9d3c8aa453829ce": "轻点某人以请求审查。轻点已请求的审查者以移除请求。关闭此面板时会发送更改。", "8d3770f150f0bcb4": "已请求", "fff1c3d17603f394": "此提供方接受审查者 ID,但无法列出候选人。", + "bbb7d40a7ad7ab71": "私有", "85ae9979ad3b0c1e": "复制基础分支 {branch}", "06a684782801e8f7": "复制头部分支 {branch}", "8e4f3c862193b8a5": "编辑", diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index 94247273e1ca0..1bce13cb0f020 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -86,6 +86,8 @@ interface FakeProviderScenario { kind?: string; /** False for a host that opens every change request ready for review. */ createsDraftChangeRequests?: boolean; + /** The companion repository of a host with private change requests. */ + privateRemote?: { readonly url: string; readonly repository: string }; /** Answers to successive change request listings, whatever their head selector. */ prListSequence?: ReadonlyArray>; prListByHeadSelector?: Record>; @@ -124,6 +126,7 @@ type FakeProviderCall = readonly headSelector: string; readonly title: string; readonly draft: unknown; + readonly private?: boolean; } | { readonly operation: "getChangeRequest"; readonly reference: string } | { @@ -483,6 +486,9 @@ function createFakeSourceControlProvider(scenario: FakeProviderScenario = {}): { service: { kind, createsDraftChangeRequests: scenario.createsDraftChangeRequests ?? true, + ...(scenario.privateRemote === undefined + ? {} + : { privateChangeRequestRemote: () => Effect.succeed(scenario.privateRemote!) }), ...headBranchProbe, listChangeRequests: (input) => record(input.cwd, { @@ -517,6 +523,7 @@ function createFakeSourceControlProvider(scenario: FakeProviderScenario = {}): { headSelector: input.headSelector, title: input.title, draft: "draft" in input ? input.draft : undefined, + ...(input.private === undefined ? {} : { private: input.private }), }), getDefaultBranch: (input) => record(input.cwd, { operation: "getDefaultBranch" }).pipe( @@ -5106,6 +5113,132 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }), ); + it.effect( + "createPullRequest opens a private PR from the companion and never pushes to origin", + () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const originDir = yield* createBareRemote(); + const companionDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", originDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "main"]); + yield* runGit(repoDir, ["checkout", "-b", "sec/fix"]); + NodeFS.writeFileSync(NodePath.join(repoDir, "fix.txt"), "fix\n"); + yield* runGit(repoDir, ["add", "fix.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Fix"]); + const heads = (remote: string) => + runGit(repoDir, ["ls-remote", "--heads", remote]).pipe( + Effect.map((result) => + result.stdout + .split("\n") + .flatMap((line) => (line ? [line.split("\t")[1]] : [])) + .toSorted(), + ), + ); + const createPrivate = (manager: GitManager.GitManager["Service"]) => + manager.createPullRequest({ + cwd: repoDir, + projectId: ProjectId.make("project-1"), + title: "Fix", + body: "Body", + private: true, + }); + + // A host without private pull requests refuses before anything is pushed. + const unsupported = yield* makeManager({ providerScenario: { prListSequence: [[]] } }); + const refused = yield* Effect.flip(createPrivate(unsupported.manager)); + expect(refused.message).toContain("has no private pull requests"); + expect(yield* heads("origin")).toEqual(["refs/heads/main"]); + expect(created(unsupported.providerCalls)).toEqual([]); + + const privateRemote = { url: companionDir, repository: "pingdotgg/codething-mvp.private" }; + const open = { + number: 9, + title: "Fix", + url: "https://source.tanstack.com/@pingdotgg/codething-mvp/pull/9", + baseRefName: "main", + headRefName: "sec/fix", + headRepositoryNameWithOwner: privateRemote.repository, + }; + const supported = yield* makeManager({ + providerScenario: { privateRemote, prListSequence: [[], [open]] }, + }); + expect(yield* createPrivate(supported.manager)).toMatchObject({ + status: "created", + number: 9, + }); + expect(yield* heads(companionDir)).toEqual(["refs/heads/sec/fix"]); + expect(yield* heads("origin")).toEqual(["refs/heads/main"]); + // The branch tracks the companion, which is how status finds its pull request. + expect( + (yield* runGit(repoDir, [ + "rev-parse", + "--abbrev-ref", + "sec/fix@{upstream}", + ])).stdout.trim(), + ).toBe("pingdotgg/sec/fix"); + expect( + (yield* runGit(repoDir, ["config", "--get", "branch.sec/fix.pushRemote"])).stdout.trim(), + ).toBe("pingdotgg"); + expect( + supported.providerCalls.flatMap((call) => + call.operation === "createChangeRequest" ? [call] : [], + ), + ).toMatchObject([{ baseRefName: "main", headSelector: "sec/fix", private: true }]); + + // Later commits follow the recorded push remote. + NodeFS.writeFileSync(NodePath.join(repoDir, "late.txt"), "late\n"); + yield* runGit(repoDir, ["add", "late.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Late"]); + const again = yield* makeManager({ + providerScenario: { privateRemote, prListSequence: [[open]] }, + }); + expect(yield* createPrivate(again.manager)).toMatchObject({ + status: "opened_existing", + number: 9, + }); + const localHead = (yield* runGit(repoDir, ["rev-parse", "HEAD"])).stdout.trim(); + expect( + (yield* runGit(repoDir, ["ls-remote", companionDir, "refs/heads/sec/fix"])).stdout, + ).toContain(localHead); + expect(yield* heads("origin")).toEqual(["refs/heads/main"]); + expect(created(again.providerCalls)).toEqual([]); + + // A lookup answered before the create must not hide the pull request the create returns. + yield* runGit(repoDir, ["checkout", "-b", "sec/two", "main"]); + NodeFS.writeFileSync(NodePath.join(repoDir, "two.txt"), "two\n"); + yield* runGit(repoDir, ["add", "two.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Two"]); + const two = { ...open, number: 10, headRefName: "sec/two" }; + const warmed = yield* makeManager({ + providerScenario: { privateRemote, prListByHeadSelector: { "sec/two": [two] } }, + }); + const lookup = warmed.manager.branchPullRequest({ cwd: repoDir, branch: "sec/two" }); + expect(yield* lookup).toBeNull(); + expect(yield* createPrivate(warmed.manager)).toMatchObject({ status: "opened_existing" }); + expect(yield* lookup).toMatchObject({ number: 10 }); + yield* runGit(repoDir, ["checkout", "sec/fix"]); + + // So does a create that forgets to ask for private: it never publishes the branch. + NodeFS.writeFileSync(NodePath.join(repoDir, "later.txt"), "later\n"); + yield* runGit(repoDir, ["add", "later.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Later"]); + const forgetful = yield* makeManager({ + providerScenario: { privateRemote, prListOtherwise: [open] }, + }); + yield* Effect.exit( + forgetful.manager.createPullRequest({ + cwd: repoDir, + projectId: ProjectId.make("project-1"), + title: "Fix", + body: "Body", + }), + ); + expect(yield* heads("origin")).toEqual(["refs/heads/main"]); + }), + ); + it.effect("createPullRequest pushes to the push remote and never to the base branch", () => 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 db62af1f79b69..dedf2d19f54ed 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -199,6 +199,12 @@ export class GitManager extends Context.Service< readonly body: string; readonly baseBranch?: string | undefined; readonly draft?: boolean | undefined; + /** + * Opens it where only people with write access see it. The branch goes to the host's + * private companion repository and never to the repository itself. Fails on a host + * without private pull requests. + */ + readonly private?: boolean | undefined; }) => Effect.Effect; readonly subscribePullRequestStateChanges: Effect.Effect< Stream.Stream, @@ -2881,9 +2887,131 @@ export const make = Effect.gen(function* () { }), ); - const createPullRequest: GitManager["Service"]["createPullRequest"] = Effect.fn( - "GitManager.createPullRequest", - )(function* (input) { + const openPrivatePullRequest = Effect.fn("GitManager.openPrivatePullRequest")(function* ( + input: Parameters[0], + ) { + const { cwd } = input; + const provider = yield* sourceControlProvider(cwd); + const definition = sourceControlDefinitions.get(provider.kind); + const terms = definition.changeRequest; + const fail = (detail: string, cause?: unknown) => + new GitManagerError({ + operation: "createPullRequest", + cwd, + detail, + ...(cause === undefined ? {} : { cause }), + }); + if (provider.privateChangeRequestRemote === undefined) { + return yield* fail( + `${definition.label} has no private ${terms.plural}. Nothing was pushed. Leave out private to open a public one.`, + ); + } + const status = yield* gitCore.statusDetails(cwd); + const branch = status.branch; + if (!branch) return yield* fail("Cannot create a pull request from detached HEAD."); + const resolved = yield* resolvePrBase(cwd, branch, status.upstreamRef, { + isCrossRepository: false, + remoteName: publishedRemoteName( + yield* readConfigValueNullable(cwd, `branch.${branch}.remote`), + ), + }); + const baseBranch = input.baseBranch ?? resolved.baseBranch; + if (baseBranch === branch) { + return yield* fail( + `${branch} is the base branch. Check out a feature branch to create ${terms.shortLabelWithArticle}.`, + ); + } + const companion = yield* provider.privateChangeRequestRemote({ cwd }); + const remoteName = yield* gitCore.ensureRemote({ + cwd, + preferredName: companion.repository.split("/")[0] || "private", + url: companion.url, + }); + // Recorded before the push, so a later push of this branch, by T3 or by plain `git push`, + // goes to the companion too and never publishes the branch. + yield* gitCore.writeConfigValue({ + cwd, + key: `branch.${branch}.pushRemote`, + value: remoteName, + }); + yield* gitCore + .execute({ + operation: "GitManager.openPrivatePullRequest.push", + cwd, + args: ["push", "--", remoteName, `refs/heads/${branch}:refs/heads/${branch}`], + timeoutMs: null, + }) + .pipe( + Effect.mapError((cause) => + fail(`Could not push ${branch} to ${companion.repository}: ${cause.detail}`, cause), + ), + Effect.tapError(() => invalidateStatus(cwd)), + ); + // The companion branch is the pull request's head, so status finds it through the upstream. + yield* gitCore + .setBranchUpstream({ cwd, branch, remoteName, remoteBranch: branch }) + .pipe(Effect.ensuring(invalidateStatus(cwd))); + const findOpen = provider + .listChangeRequests({ cwd, headSelector: branch, state: "open" }) + .pipe( + Effect.map( + (listed) => + listed.find( + (pr) => + pr.headRefName === branch && + pr.headRepositoryNameWithOwner?.toLowerCase() === + companion.repository.toLowerCase(), + ) ?? null, + ), + ); + const existing = yield* findOpen; + if (existing) { + return { + status: "opened_existing" as const, + url: existing.url, + number: existing.number, + baseBranch: existing.baseRefName, + headBranch: existing.headRefName, + title: existing.title, + }; + } + const bodyFile = path.join( + tempDir, + `t3code-pr-body-${process.pid}-${yield* randomUUIDv4(cwd)}.md`, + ); + yield* fileSystem + .writeFileString(bodyFile, input.body) + .pipe( + Effect.mapError((cause) => fail("Failed to write pull request body temp file.", cause)), + ); + yield* provider + .createChangeRequest({ + cwd, + baseRefName: baseBranch, + headSelector: branch, + title: input.title, + bodyFile, + private: true, + ...(input.draft === true ? { draft: true } : {}), + }) + .pipe( + Effect.ensuring(fileSystem.remove(bodyFile).pipe(Effect.ignore)), + Effect.ensuring(invalidateStatus(cwd)), + ); + // The PR already exists at this point, so a failed lookup only loses its metadata. + const created = yield* findOpen.pipe(Effect.orElseSucceed(() => null)); + return { + status: "created" as const, + ...(created ? { url: created.url, number: created.number } : {}), + baseBranch: created?.baseRefName ?? baseBranch, + headBranch: created?.headRefName ?? branch, + title: created?.title ?? input.title, + }; + }); + + const pushAndOpenPullRequest = Effect.fn("GitManager.pushAndOpenPullRequest")(function* ( + input: Parameters[0], + ) { const status = yield* gitCore.statusDetails(input.cwd); const needsPush = yield* createPrNeedsPush(input.cwd, status); if (needsPush && status.branch) { @@ -2935,6 +3063,16 @@ export const make = Effect.gen(function* () { : Effect.void, ), ); + return result; + }); + + const createPullRequest: GitManager["Service"]["createPullRequest"] = Effect.fn( + "GitManager.createPullRequest", + )(function* (input) { + const result = + input.private === true + ? yield* openPrivatePullRequest(input) + : yield* pushAndOpenPullRequest(input); const openedAsDraft = result.status === "created" && (yield* sourceControlProvider(input.cwd)).createsDraftChangeRequests === true; diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts index b7edff187579d..7caa425d32f2e 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts @@ -837,6 +837,7 @@ describe("source control tools", () => { body: "Adds tools.", state: "open", isDraft: false, + visibility: "private", author: null, headBranch: "tools", baseBranch: "main", @@ -892,6 +893,7 @@ describe("source control tools", () => { }); const compact = yield* harness.call("pull_request_read", {}); expect(compact).toMatchObject({ + visibility: "private", headSha: "abc123", checks: { passed: 2, pending: 1, failed: ["Lint", "E2E"], incomplete: true }, unresolvedThreads: 1, @@ -1178,7 +1180,11 @@ describe("source control tools", () => { it.effect("opens a PR from the thread's worktree and links it even if dismissed", () => Effect.gen(function* () { - const opened: Array<{ readonly cwd: string; readonly draft: boolean | undefined }> = []; + const opened: Array<{ + readonly cwd: string; + readonly draft: boolean | undefined; + readonly private: boolean | undefined; + }> = []; const harness = yield* makeHarness({ thread: { ...makeThread([makeLink(43, { source: "stack-dismissed" })]), @@ -1186,7 +1192,9 @@ describe("source control tools", () => { }, git: { createPullRequest: (input) => - Effect.sync(() => opened.push({ cwd: input.cwd, draft: input.draft })).pipe( + Effect.sync(() => + opened.push({ cwd: input.cwd, draft: input.draft, private: input.private }), + ).pipe( Effect.as({ status: "created" as const, url: "https://github.com/t3tools/t3code/pull/43", @@ -1202,9 +1210,10 @@ describe("source control tools", () => { title: "Add tools", body: "Adds tools.", draft: true, + private: true, }); expect(result).toMatchObject({ number: 43, created: true }); - expect(opened).toEqual([{ cwd: "/workspace/worktree", draft: true }]); + expect(opened).toEqual([{ cwd: "/workspace/worktree", draft: true, private: true }]); expect(yield* Ref.get(harness.commands)).toMatchObject([ { type: "thread.pull-request.link", number: 43, source: "created" }, ]); diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts index f85d8f0abac4a..e422a799f3d9a 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts @@ -617,6 +617,7 @@ const make = Effect.gen(function* () { title: detail.title, state: detail.state, isDraft: detail.isDraft, + ...(detail.visibility === undefined ? {} : { visibility: detail.visibility }), author: detail.author?.login ?? null, headBranch: detail.headBranch, baseBranch: detail.baseBranch, @@ -1052,6 +1053,7 @@ const make = Effect.gen(function* () { body: input.body, baseBranch: input.base, draft: input.draft, + private: input.private, }) .pipe(Effect.mapError(forgeFailure)); if (created.url === undefined) { diff --git a/apps/server/src/mcp/toolkits/pullRequests/tools.ts b/apps/server/src/mcp/toolkits/pullRequests/tools.ts index 71d0a28d4e392..847ae4ef19e7d 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/tools.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/tools.ts @@ -16,6 +16,7 @@ import { PullRequestReviewGuideRun, PullRequestState, PullRequestUnavailableError, + PullRequestVisibility, PullRequestWatchUntil, ThreadPullRequestLinkSource, TrimmedNonEmptyString, @@ -517,6 +518,9 @@ export const ReadPullRequestResult = Schema.Struct({ title: Schema.String, state: PullRequestState, isDraft: Schema.Boolean, + visibility: Schema.optional(PullRequestVisibility).annotate({ + description: "Only on a host with private PRs.", + }), author: Schema.NullOr(Schema.String), headBranch: Schema.String, baseBranch: Schema.String, @@ -675,6 +679,10 @@ const CreatePullRequestTool = Tool.make("pull_request_create", { body: Schema.String, base: Schema.optional(TrimmedNonEmptyString), draft: Schema.optional(Schema.Boolean), + private: Schema.optional(Schema.Boolean).annotate({ + description: + "Visible to writers only; the branch never reaches origin. Fails on a host without private PRs.", + }), }), success: CreatePullRequestResult, failure: PullRequestToolError, diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 139eba175bc8a..9ec6f6509f48c 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6245, "codexAdditionalContextBytes": 7639, - "mcpToolListJsonBytes": 59052 + "mcpToolListJsonBytes": 59192 } diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index e30938735c765..59ece029219df 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -1370,6 +1370,7 @@ export const make = Effect.gen(function* () { ...(input.item.checksState === undefined || input.item.checksState === null ? {} : { checksState: input.item.checksState }), + ...(input.item.visibility === undefined ? {} : { visibility: input.item.visibility }), viewerReviewRequested: input.item.author?.login.toLowerCase() !== viewer && input.item.reviewRequestLogins.some((login) => login.toLowerCase() === viewer), @@ -1993,6 +1994,9 @@ export const make = Effect.gen(function* () { ...(changeRequest.mergeQueueRemoval === undefined ? {} : { mergeQueueRemoval: changeRequest.mergeQueueRemoval }), + ...(changeRequest.visibility === undefined + ? {} + : { visibility: changeRequest.visibility }), })), ), ), diff --git a/apps/server/src/sourceControl/SourceControlProviderRegistry.ts b/apps/server/src/sourceControl/SourceControlProviderRegistry.ts index 06616a914b1e9..98c560cbf4973 100644 --- a/apps/server/src/sourceControl/SourceControlProviderRegistry.ts +++ b/apps/server/src/sourceControl/SourceControlProviderRegistry.ts @@ -222,6 +222,15 @@ function bindProviderContext( context: input.context ?? context, }); }), + ...(provider.privateChangeRequestRemote === undefined + ? {} + : { + privateChangeRequestRemote: (input) => + provider.privateChangeRequestRemote!({ + ...input, + context: input.context ?? context, + }), + }), getRepositoryCloneUrls: Effect.fnUntraced(function* (input) { return yield* provider.getRepositoryCloneUrls({ ...input, diff --git a/apps/web/src/components/pullRequest/PullRequestDetailLayout.tsx b/apps/web/src/components/pullRequest/PullRequestDetailLayout.tsx index a797a7984cbce..250240d2849fa 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailLayout.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailLayout.tsx @@ -1,12 +1,39 @@ import { useGT } from "gt-react"; -import { ArrowLeftIcon, FileDiffIcon } from "lucide-react"; +import { ArrowLeftIcon, FileDiffIcon, LockIcon } from "lucide-react"; import { useEffect, useRef, type ComponentProps, type ReactNode } from "react"; import { cn } from "~/lib/utils"; +import { Badge } from "../ui/badge"; import { Toggle, ToggleGroup } from "../ui/toggle-group"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { PullRequestMetaLine } from "./pullRequestPresentation"; +export function PullRequestPrivateMark({ className }: { className?: string }) { + const gt = useGT(); + const label = gt("Private"); + return ( + + } + /> + {label} + + ); +} + +export function PullRequestPrivateBadge() { + const gt = useGT(); + return ( + + + + {gt("Private")} + + + ); +} + export function PullRequestDetailHeaderBody({ title, author, diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx index cbf9de56dbbb2..1e14ab19d9012 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx @@ -90,6 +90,7 @@ import { MiddleTruncate } from "../ui/middle-truncate"; import { PullRequestChecksStatusLine, PullRequestDetailHeaderBody, + PullRequestPrivateBadge, PullRequestDetailTabBar, } from "./PullRequestDetailLayout"; import { PullRequestDetailGhost, PullRequestTimelineGhost } from "./PullRequestGhosts"; @@ -1578,6 +1579,7 @@ export function PullRequestDetailPanel({
{detail ? ( + {detail.visibility === "private" ? : null} {context === "page" ? ( + {entry.visibility === "private" ? ( + + ) : null} {entry.checksState === undefined ? null : ( ; readonly reviewDecision?: PullRequestReviewDecision | null | undefined; readonly checksState?: PullRequestChecksState | null | undefined; + /** Absent where the host has no private change requests or names no visibility. */ + readonly visibility?: PullRequestVisibility; } export interface ProviderChangeRequestSummary { diff --git a/packages/source-control-core/src/server/SourceControlProvider.ts b/packages/source-control-core/src/server/SourceControlProvider.ts index 4a6e93ab74f45..ccf23f59b2258 100644 --- a/packages/source-control-core/src/server/SourceControlProvider.ts +++ b/packages/source-control-core/src/server/SourceControlProvider.ts @@ -173,6 +173,18 @@ export class SourceControlProvider extends Context.Service< }) => Effect.Effect; /** True when `createChangeRequest` opens the change request as a draft when asked. */ readonly createsDraftChangeRequests?: boolean; + /** + * The private companion of the checkout's repository, made when it has none. The branch of + * a private change request is pushed to `url` and never to the repository itself, which + * everyone can read. Absent on a host without private change requests. + */ + readonly privateChangeRequestRemote?: (input: { + readonly cwd: string; + readonly context?: SourceControlProviderContext; + }) => Effect.Effect< + { readonly url: string; readonly repository: string }, + SourceControlProviderError + >; readonly listChangeRequests: (input: { readonly cwd: string; readonly context?: SourceControlProviderContext; @@ -202,6 +214,8 @@ export class SourceControlProvider extends Context.Service< readonly bodyFile: string; /** Honored only by a provider with `createsDraftChangeRequests`. */ readonly draft?: boolean; + /** Asked only of a provider with `privateChangeRequestRemote`, which holds the head. */ + readonly private?: boolean; }) => Effect.Effect; readonly getRepositoryCloneUrls: (input: { readonly cwd: string; diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.test.ts b/packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.test.ts new file mode 100644 index 0000000000000..838309b037617 --- /dev/null +++ b/packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.test.ts @@ -0,0 +1,138 @@ +import { assert, describe, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as HttpClient from "effect/http/HttpClient"; + +import * as TanStackSourceApi from "./TanStackSourceApi.ts"; +import * as Credentials from "./TanStackSourceCredentials.ts"; +import * as TanStackSourcePullRequestProvider from "./TanStackSourcePullRequestProvider.ts"; + +const HOST = "source.tanstack.com"; + +/** + * Shaped like `GET /pulls/{n}` of a private pull request: its head is `owner:branch` in the + * companion repository, and Source has stored no file or line counts for it. + */ +const PRIVATE_PULL = { + number: 42, + title: "Fix the thing", + state: "open", + visibility: "private", + draft: false, + author: "bob", + head: "acme:fix/thing", + createdAt: 1_000, + body: null, + base: "main", + headRepo: "acme/web.private", + headSha: "c".repeat(40), + baseSha: "b".repeat(40), + mergeCommitSha: null, + mergedAt: null, + mergedBy: null, + mergeable: null, + changedFiles: null, + changedLines: null, +}; + +const FILES = { + baseSha: "b".repeat(40), + headSha: "c".repeat(40), + mergeBaseSha: "b".repeat(40), + available: true, + truncated: false, + files: [ + { path: "a.ts", status: "modified", additions: 3, deletions: 1 }, + { path: "b.ts", status: "added", additions: 4, deletions: 0 }, + ], +}; + +const RESPONSES: Record = { + "/repos/acme/web/pulls/42": PRIVATE_PULL, + "/repos/acme/web/pulls/42/files": FILES, + "/repos/acme/web/pulls/42/checks": { checks: [], upToDate: null, mayMerge: true }, + "/repos/acme/web/pulls/42/stack": { members: [] }, + [`/repos/acme/web/check-runs?sha=${"c".repeat(40)}`]: [], + "/repos/acme/web/ci/runs?pull=42&limit=30": { items: [], next: null }, + "/repos/acme/web/issues/42": { + timeline: [ + { id: 1, comment: "Looks good", author: "alice", at: 2_000 }, + { event: "head_updated", actor: "bob", at: 3_000 }, + ], + next: null, + }, + "/repos/acme/web/pulls/42/comments": [], + "/repos/acme/web/pulls/42/commits": { + baseSha: null, + headSha: null, + mergeBaseSha: null, + available: true, + commits: [], + }, + "/user": { username: "alice" }, +}; + +const api = TanStackSourceApi.TanStackSourceApi.of({ + request: (input) => + input.path in RESPONSES + ? Effect.succeed(JSON.stringify(RESPONSES[input.path])) + : Effect.die(`unexpected ${input.path}`), + response: () => Effect.die("unexpected response read"), +}); + +const provider = TanStackSourcePullRequestProvider.make.pipe( + Effect.provideService(TanStackSourceApi.TanStackSourceApi, api), + Effect.provideService( + Credentials.TanStackSourceCredentials, + Credentials.TanStackSourceCredentials.of({ + get: () => Effect.die("unexpected credential read"), + invalidate: () => Effect.void, + }), + ), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make(() => Effect.die("unexpected http request")), + ), +); + +describe("TanStackSourcePullRequestProvider.getChangeRequest", () => { + // A client without this host's definition percent-encodes the owner's `@`; stored links + // keep the web's own spelling. + it.effect.each(["acme/web", "@acme/web", "%40acme/web"])( + "reads a private pull request of %s", + (repository) => + Effect.gen(function* () { + const detail = yield* (yield* provider).getChangeRequest({ + host: HOST, + repository, + number: 42, + cwd: "/repo", + }); + assert.strictEqual(detail.url, `https://${HOST}/@acme/web/pull/42`); + assert.strictEqual(detail.visibility, "private"); + assert.strictEqual(detail.headBranch, "fix/thing"); + assert.strictEqual(detail.headRepositoryNameWithOwner, "acme/web.private"); + // Source stores no counts for it, so they come from its files. + assert.deepStrictEqual( + [detail.changedFiles, detail.additions, detail.deletions], + [2, 7, 1], + ); + }), + ); +}); + +describe("TanStackSourcePullRequestProvider.getChangeRequestActivity", () => { + it.effect("reads the comments of a timeline that also holds events", () => + Effect.gen(function* () { + const activity = yield* (yield* provider).getChangeRequestActivity({ + host: HOST, + repository: "acme/web", + number: 42, + cwd: "/repo", + }); + assert.deepStrictEqual( + activity.comments.map((comment) => comment.body), + ["Looks good"], + ); + }), + ); +}); diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts index 509e03e1f41f4..0529ce6df17c7 100644 --- a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts +++ b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts @@ -35,6 +35,8 @@ const PULL = { function checkout(options: { readonly recordedOwner: string | null; readonly isAncestor: boolean; + readonly pull?: Partial; + readonly force?: boolean; }) { const git: Array = []; const config = new Map( @@ -43,14 +45,28 @@ function checkout(options: { const api = TanStackSourceApi.TanStackSourceApi.of({ request: (input) => input.path === "/repos/acme/web/pulls/42" - ? Effect.succeed(JSON.stringify(PULL)) + ? Effect.succeed(JSON.stringify({ ...PULL, ...options.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"), + ensureRemote: (input) => + Effect.sync(() => { + git.push(`remote ${input.preferredName} ${input.url}`); + return input.url === REMOTE ? "origin" : input.preferredName; + }), + fetchRemoteBranch: (input) => + Effect.sync( + () => + void git.push(`fetch ${input.remoteName} ${input.remoteBranch}:${input.localBranch}`), + ), + fetchRemoteTrackingBranch: () => Effect.void, + setBranchUpstream: (input) => + Effect.sync( + () => void git.push(`upstream ${input.branch} ${input.remoteName}/${input.remoteBranch}`), + ), 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)), @@ -86,7 +102,13 @@ function checkout(options: { }, }); const run = TanStackSourceSourceControlProvider.make.pipe( - Effect.flatMap((provider) => provider.checkoutChangeRequest({ cwd: "/repo", reference: "42" })), + Effect.flatMap((provider) => + provider.checkoutChangeRequest({ + cwd: "/repo", + reference: "42", + ...(options.force === undefined ? {} : { force: options.force }), + }), + ), Effect.provideService(TanStackSourceApi.TanStackSourceApi, api), Effect.provide(Layer.merge(host, FileSystem.layerNoop({}))), ); @@ -129,4 +151,83 @@ describe("TanStackSourceSourceControlProvider.checkoutChangeRequest", () => { assert.isFalse(git.some((command) => command.startsWith("checkout"))); }); }); + + // Source publishes no `refs/pull//head` for a private pull request, on either repository. + it.effect("takes a private pull request's branch from the companion repository", () => { + const pull = { head: "acme:fix-thing", headRepo: "acme/web.private" }; + const { run, git, config } = checkout({ recordedOwner: null, isAncestor: true, pull }); + const forced = checkout({ recordedOwner: null, isAncestor: true, pull, force: true }); + return Effect.gen(function* () { + yield* forced.run; + assert.include(forced.git, "checkout --no-track -B fix-thing refs/remotes/acme/fix-thing --"); + yield* run; + assert.strictEqual(config.get("branch.fix-thing.pushRemote"), "acme"); + assert.deepStrictEqual(git, [ + `remote source ${REMOTE}`, + "remote acme https://source.tanstack.com/@acme/web.private.git", + "fetch acme fix-thing:fix-thing", + "upstream fix-thing acme/fix-thing", + "switch fix-thing", + ]); + }); + }); +}); + +describe("TanStackSourceSourceControlProvider private pull requests", () => { + it.effect("asks Source for the companion and opens the pull request as private", () => { + const requests: Array<{ method: string; path: string; body: unknown }> = []; + const api = TanStackSourceApi.TanStackSourceApi.of({ + request: (input) => { + requests.push({ method: input.method ?? "GET", path: input.path, body: input.body }); + return Effect.succeed( + JSON.stringify({ + owner: "acme", + name: "web.private", + defaultBranch: null, + cloneUrl: "https://source.tanstack.com/@acme/web.private.git", + }), + ); + }, + response: () => Effect.die("unexpected response read"), + }); + const files = FileSystem.layerNoop({ readFileString: () => Effect.succeed("Body") }); + return Effect.gen(function* () { + const provider = yield* TanStackSourceSourceControlProvider.make; + const companion = provider.privateChangeRequestRemote; + assert.isDefined(companion); + assert.deepStrictEqual(yield* companion({ cwd: "/repo" }), { + url: "https://source.tanstack.com/@acme/web.private.git", + repository: "acme/web.private", + }); + yield* provider.createChangeRequest({ + cwd: "/repo", + baseRefName: "main", + headSelector: "sec/fix", + title: "Fix", + bodyFile: "/tmp/body.md", + private: true, + }); + assert.deepStrictEqual(requests, [ + { method: "POST", path: "/repos/acme/web/private-remote", body: undefined }, + { + method: "POST", + path: "/repos/acme/web/pulls", + body: { title: "Fix", head: "sec/fix", base: "main", body: "Body", private: true }, + }, + ]); + }).pipe( + Effect.provideService(TanStackSourceApi.TanStackSourceApi, api), + Effect.provide( + Layer.merge( + TestSourceControlHost.layer({ + git: { + resolvePrimaryRemoteName: () => Effect.succeed("origin"), + readConfigValue: () => Effect.succeed(REMOTE), + }, + }), + files, + ), + ), + ); + }); }); diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts index a1abb376b472d..f194848611361 100644 --- a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts +++ b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts @@ -395,6 +395,18 @@ export const make = Effect.gen(function* () { }, ), createsDraftChangeRequests: true, + privateChangeRequestRemote: Effect.fn( + "TanStackSourceSourceControlProvider.privateChangeRequestRemote", + )(function* (input) { + const target = yield* resolveTarget("privateChangeRequestRemote", input); + const companion = yield* read( + "privateChangeRequestRemote", + input.cwd, + { host: target.host, method: "POST", path: `/repos/${target.repository}/private-remote` }, + Repository, + ); + return { url: companion.cloneUrl, repository: `${companion.owner}/${companion.name}` }; + }), createChangeRequest: Effect.fn("TanStackSourceSourceControlProvider.createChangeRequest")( function* (input) { const target = yield* resolveTarget("createChangeRequest", { @@ -437,6 +449,7 @@ export const make = Effect.gen(function* () { base: input.target?.refName ?? input.baseRefName, ...(body.trim().length === 0 ? {} : { body }), ...(input.draft === true ? { draft: true } : {}), + ...(input.private === true ? { private: true } : {}), }, }) .pipe( @@ -494,7 +507,8 @@ export const make = Effect.gen(function* () { return repository.defaultBranch; }, ), - // Every pull request's head is published as `refs/pull//head`, forks and GitHub sync too. + // A pull request's head is published as `refs/pull//head`, forks and GitHub sync too. A + // private one has no such ref: its branch is read from the companion repository. checkoutChangeRequest: Effect.fn("TanStackSourceSourceControlProvider.checkoutChangeRequest")( function* (input) { const pull = yield* getPull(input); @@ -519,9 +533,26 @@ export const make = Effect.gen(function* () { }); const operation = "TanStackSourceSourceControlProvider.checkoutChangeRequest"; const branches = yield* git.listLocalBranchNames(input.cwd); - if (!pull.isCrossRepository) { + const companion = + pullRepository !== null && + pull.headRepositoryNameWithOwner?.toLowerCase() === + `${pullRepository}.private`.toLowerCase() + ? pull.headRepositoryNameWithOwner + : null; + if (!pull.isCrossRepository || companion !== null) { const localBranch = pull.headRefName; - const remoteBranch = { cwd: input.cwd, remoteName, remoteBranch: localBranch }; + const remoteBranch = { + cwd: input.cwd, + remoteName: + companion === null + ? remoteName + : yield* git.ensureRemote({ + cwd: input.cwd, + preferredName: companion.split("/")[0] ?? "private", + url: `${Hosts.webRepositoryUrl(HOST, companion)}.git`, + }), + remoteBranch: localBranch, + }; if (input.force !== true && !branches.includes(localBranch)) yield* git.fetchRemoteBranch({ ...remoteBranch, localBranch }); else yield* git.fetchRemoteTrackingBranch(remoteBranch); @@ -535,11 +566,18 @@ export const make = Effect.gen(function* () { "--no-track", "-B", localBranch, - `refs/remotes/${remoteName}/${localBranch}`, + `refs/remotes/${remoteBranch.remoteName}/${localBranch}`, "--", ], }); yield* git.setBranchUpstream({ ...remoteBranch, branch: localBranch }); + // Whatever push defaults say, this branch must not be published to the public remote. + if (companion !== null) + yield* git.writeConfigValue({ + cwd: input.cwd, + key: `branch.${localBranch}.pushRemote`, + value: remoteBranch.remoteName, + }); yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch })); return; } diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.test.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.test.ts new file mode 100644 index 0000000000000..ac43a46ccdcad --- /dev/null +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { tanStackSourceRepositoryPath } from "./tanStackSourceHosts.ts"; + +describe("tanStackSourceRepositoryPath", () => { + it.each([ + ["acme/web", "acme/web"], + ["@acme/web", "acme/web"], + // Clients without this host's definition percent-encode the owner's `@`. + ["%40acme/web", "acme/web"], + ["/@acme/web.git/", "acme/web"], + ["acme/web.private", "acme/web.private"], + ["acme", null], + ["acme/web/extra", null], + ["acme/..", null], + ])("reads %s as %s", (path, repository) => { + expect(tanStackSourceRepositoryPath(path)).toBe(repository); + }); +}); diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts index 22923264629bf..dfa6d4e9031a0 100644 --- a/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts @@ -1,4 +1,4 @@ -import { TANSTACK_SOURCE_HOST } from "../shared/definition.ts"; +import { TANSTACK_SOURCE_HOST, withoutOwnerMark } from "../shared/definition.ts"; export const TANSTACK_SOURCE_HOSTS = [TANSTACK_SOURCE_HOST] as const; export type TanStackSourceHost = (typeof TANSTACK_SOURCE_HOSTS)[number]; @@ -10,14 +10,14 @@ export function tanStackSourceHost(host: string): TanStackSourceHost | null { const SEGMENT = /^[A-Za-z0-9_.-]+$/u; -/** `owner/name` from the API spelling or the web spelling `@owner/name`, `.git` dropped. */ +/** `owner/name` from the API spelling or either web spelling of the owner, `.git` dropped. */ export function tanStackSourceRepositoryPath(path: string): string | null { - const [owner, name, ...rest] = path - .trim() - .replace(/^\/+|\/+$/gu, "") - .replace(/\.git$/u, "") - .replace(/^@/u, "") - .split("/"); + const [owner, name, ...rest] = withoutOwnerMark( + path + .trim() + .replace(/^\/+|\/+$/gu, "") + .replace(/\.git$/u, ""), + ).split("/"); return rest.length === 0 && owner !== undefined && name !== undefined && diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts index 4d698fb881dfb..24c93e6aac83d 100644 --- a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts @@ -146,6 +146,7 @@ describe("toActivity", () => { ["4", "review-comment", null], ]); expect(activity.comments[0]?.url).toBe(`https://${HOST}/@TanStack/ai/pull/9#comment-1`); + expect(Json.pullUrl(HOST, "%40TanStack/ai", 9)).toBe(`https://${HOST}/@TanStack/ai/pull/9`); expect(activity.reviewThreads).toMatchObject([ { id: "4", path: "a.ts", line: 2, side: "left", isResolved: true }, ]); diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts index acf3c4158f95c..51537627ca3e7 100644 --- a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts @@ -16,6 +16,8 @@ import type { import * as DateTime from "effect/DateTime"; import * as Schema from "effect/Schema"; +import { withoutOwnerMark } from "../shared/definition.ts"; + /** Source sends times as epoch milliseconds. */ const EpochMillis = Schema.Finite; const Login = Schema.String; @@ -29,6 +31,7 @@ export const SourcePull = Schema.Struct({ labels: Schema.optional(Schema.Array(Schema.String)), head: Schema.String, createdAt: EpochMillis, + visibility: Schema.optional(Schema.String), }); export type SourcePull = typeof SourcePull.Type; @@ -135,7 +138,8 @@ const TimelineEntry = Schema.Struct({ type TimelineEntry = typeof TimelineEntry.Type; export const SourceTimeline = Schema.Struct({ - timeline: Schema.Array(TimelineEntry), + // Events such as `head_updated` sit between the comments and carry no id. + timeline: Schema.Array(Schema.Union([TimelineEntry, Schema.Struct({ event: Schema.String })])), next: Schema.NullOr(Schema.String), }); @@ -239,10 +243,20 @@ 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}`; + `https://${host}/@${withoutOwnerMark(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, ""); +/** + * A GitHub-synced pull request from a fork names its head only by its pull ref, and a private + * one as `owner:branch`. A branch name holds no colon, so the owner is all that one can precede. + */ +export const headBranchName = (head: string) => + head.replace(/^refs\/heads\//u, "").replace(/^[^/:]+:/u, ""); + +/** Absent when Source names no visibility, so a reader tells unknown from public. */ +const visibilityOf = (pull: Pick) => + pull.visibility === "private" || pull.visibility === "public" + ? { visibility: pull.visibility } + : {}; export function toActor(login: string | null, host: string): PullRequestActor | null { if (login === null || login.trim() === "") return null; @@ -280,6 +294,7 @@ export function toChangeRequest( baseBranch: pull.base ?? "", state: pull.state, isDraft: pull.draft, + ...visibilityOf(pull), mergeability: "unknown", additions: 0, deletions: 0, @@ -380,7 +395,9 @@ export function toActivity(input: { }): ProviderChangeRequestActivity { const { host } = input; const page = pullUrl(host, input.repository, input.number); - const entries = input.timeline.timeline.filter(visible); + const entries = input.timeline.timeline.filter( + (entry): entry is TimelineEntry => "id" in entry && visible(entry), + ); const comments: Array = entries.map((entry: TimelineEntry) => ({ id: String(entry.id), kind: diff --git a/packages/source-control-tanstack-source/src/shared/definition.test.ts b/packages/source-control-tanstack-source/src/shared/definition.test.ts index e3ce5c867fa5c..6e09a89fa2cda 100644 --- a/packages/source-control-tanstack-source/src/shared/definition.test.ts +++ b/packages/source-control-tanstack-source/src/shared/definition.test.ts @@ -31,7 +31,23 @@ describe("TanStack Source definition", () => { number: 7, }), ).toBe("https://source.tanstack.com/@TanStack/router/pull/7"); + // A stored link or an older client may name the repository as the web spells it. + for (const repository of ["@TanStack/router", "%40TanStack/router"]) + expect( + definition.changeRequestUrl({ host: "source.tanstack.com", repository, number: 7 }), + repository, + ).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(); }); + + it.each(["tanstack/router", "@tanstack/router", "%40tanstack/router"])( + "keys %s as the API's owner/name", + (repository) => { + expect(definition.canonicalRepositoryKey?.(`source.tanstack.com/${repository}`)).toBe( + "source.tanstack.com/tanstack/router", + ); + expect(definition.canonicalRepositoryKey?.(`github.com/${repository}`)).toBeNull(); + }, + ); }); diff --git a/packages/source-control-tanstack-source/src/shared/definition.ts b/packages/source-control-tanstack-source/src/shared/definition.ts index 1aee00c968dc6..032adc5a45cdd 100644 --- a/packages/source-control-tanstack-source/src/shared/definition.ts +++ b/packages/source-control-tanstack-source/src/shared/definition.ts @@ -37,6 +37,20 @@ function parseChangeRequestUrl(url: URL) { : { ...link, repositoryUrl: `${url.origin}/@${CHANGE_REQUEST_PATH.exec(url.pathname)![1]}` }; } +/** + * `owner/name` as the API names it. The web spells it `@owner/name`, and a client without this + * definition percent-encodes that as `%40owner/name`. + */ +export const withoutOwnerMark = (repository: string) => repository.replace(/^(?:@|%40)/iu, ""); + +/** Links stored with the web's spelling compare equal to the project's own key. */ +function canonicalRepositoryKey(key: string): string | null { + const slash = key.indexOf("/"); + return slash > 0 && isTanStackSourceHost(key.slice(0, slash)) + ? `${TANSTACK_SOURCE_HOST}/${withoutOwnerMark(key.slice(slash + 1))}` + : null; +} + /** 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. @@ -80,13 +94,13 @@ export const definition = defineSourceControl({ ? null : webUrl ? changeRequestUrlBelow(webUrl, `pull/${number}`) - : `https://${host}/@${repository.replace(/^@/u, "")}/pull/${number}`, + : `https://${host}/@${withoutOwnerMark(repository)}/pull/${number}`, parseChangeRequestUrl, commitUrl: (input) => buildCommitUrl( input.webUrl ? input - : { ...input, webUrl: `https://${input.host}/@${input.repository.replace(/^@/u, "")}` }, + : { ...input, webUrl: `https://${input.host}/@${withoutOwnerMark(input.repository)}` }, "commit", ), parseIssueUrl: (url) => @@ -122,6 +136,7 @@ export const definition = defineSourceControl({ checkoutChangeRequestHost: () => null, changeRequestHeadRef: (number) => `refs/pull/${number}/head`, repositoryKeyFromRemote, + canonicalRepositoryKey, recognizeRemote: ({ hostname }) => isTanStackSourceHost(hostname) ? { kind: KIND, name: "TanStack Source", baseUrl: `https://${TANSTACK_SOURCE_HOST}` } From 976aca331aa15d41f4383def7afeafcfcab5575e Mon Sep 17 00:00:00 2001 From: Wu Shuwen Date: Sun, 22 Nov 2026 17:08:53 +0800 Subject: [PATCH 10/17] fix: include delegated threads in CLI listing (#40738) Co-authored-by: Julius Marminge --- apps/server/src/cli/thread.test.ts | 97 ++++++++++++++++++++++++++++++ apps/server/src/cli/thread.ts | 6 +- 2 files changed, 101 insertions(+), 2 deletions(-) diff --git a/apps/server/src/cli/thread.test.ts b/apps/server/src/cli/thread.test.ts index 7231ea7f2b3e0..49887ee0bb7cc 100644 --- a/apps/server/src/cli/thread.test.ts +++ b/apps/server/src/cli/thread.test.ts @@ -53,6 +53,103 @@ vi.mock("../auth/EnvironmentAuth.ts", async (importOriginal) => { const threadId = ThreadId.make("thread-1"); const runId = RunId.make("run-1"); +it.effect("list includes delegated threads across pages and still leaves out subagents", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-thread-list-" }); + yield* persistServerRuntimeState({ + path: path.join(baseDir, "userdata", "server-runtime.json"), + state: yield* makePersistedServerRuntimeState({ + config: { host: "127.0.0.1", devUrl: undefined }, + port: 3_773, + }), + }); + const projectId = ProjectId.make("project-1"); + const item = (id: string) => ({ + threadId: id, + projectId, + title: id, + createdBy: "user", + creationSource: "web", + status: "idle", + latestRunId: null, + providerInstanceId: "codex", + model: "test", + runtimeMode: "full-access", + interactionMode: "default", + linkedPullRequest: null, + settled: false, + settledAt: null, + snoozed: false, + snoozedUntil: null, + parentThreadId: null, + relationshipToParent: null, + itemCount: 0, + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + }); + const root = item("root"); + const delegated = { + ...item("delegated"), + delegatedFrom: { environmentId: "env-1", threadId: "remote", title: "Remote" }, + }; + const subagent = { ...item("child"), parentThreadId: "root", relationshipToParent: "subagent" }; + using _session = vi.spyOn(McpBridge, "mcpToolSession").mockReturnValue( + Effect.succeed({ + call: (tool, args) => { + if (tool === "t3_project_list") + return Effect.succeed({ + structuredContent: { + projects: [{ id: projectId, title: "Project", workspaceRoot: baseDir }], + nextCursor: null, + }, + }); + if (tool === "t3_thread_list") { + const all = args.includeSubagents ? [root, subagent, delegated] : [root]; + const cursor = Number(args.cursor); + return Effect.succeed({ + structuredContent: { + projectId, + currentThreadId: null, + threads: all.slice(cursor, cursor + 2), + nextCursor: cursor + 2 < all.length ? cursor + 2 : null, + total: all.length, + }, + }); + } + return Effect.die(`unexpected ${tool} call`); + }, + }), + ); + yield* Command.runWith(threadCommand, { version: "0.0.0" })([ + "list", + "--project", + projectId, + "--json", + "--base-dir", + baseDir, + ]); + const listed = JSON.parse(String((yield* TestConsole.logLines).at(-1))) as Array<{ + threadId: string; + }>; + assert.deepStrictEqual( + listed.map((entry) => entry.threadId), + ["root", "delegated"], + ); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + NetService.layer, + ConfigProvider.layer(ConfigProvider.fromEnv({ env: { T3CODE_PORT: "3773" } })), + ), + ), + ), +); + it.effect( "start resolves home-relative project paths while preserving ids and relative paths", () => diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index 8849f10c6a5ec..e63e762237e85 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -850,10 +850,12 @@ const threadListCommand = Command.make("list", { while (cursor !== null) { const page: OrchestratorMcpThreadListResult = yield* tools.call( "t3_thread_list", - { projectId: project.id, includeSubagents: false, limit: 100, cursor }, + { projectId: project.id, includeSubagents: true, limit: 100, cursor }, OrchestratorMcpThreadListResult, ); - threads.push(...page.threads); + threads.push( + ...page.threads.filter((thread) => thread.relationshipToParent !== "subagent"), + ); cursor = page.nextCursor; } if (flags.json) { From bcace0787ee37f4e4dd9a1f68b7be8f871934926 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 01:23:15 -0800 Subject: [PATCH 11/17] fix(pi): turn token usage counts cached tokens as input and stays per turn (#40758) --- .../testkit/fixtures/simple/pi_output.ts | 55 +++++++++------ .../provider-pi/src/server/adapter.test.ts | 56 ++++++++++++++++ packages/provider-pi/src/server/adapter.ts | 67 ++++++++++++------- 3 files changed, 133 insertions(+), 45 deletions(-) diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/simple/pi_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/simple/pi_output.ts index c7579914964ee..bed80f2be65ef 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/simple/pi_output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/simple/pi_output.ts @@ -24,32 +24,45 @@ function lastPiResponseData(transcript: ProviderReplayTranscript, command: strin return field(frame, "data"); } -/** Settled Pi usage uses each recorded get_session_stats response in order, not the last streaming total. */ +/** + * Settled Pi usage takes the context size from each turn's get_session_stats response and the + * input breakdown from the turn's last streamed message usage, since stats tokens are session totals. + */ export function assertPiSettledTokenUsage( result: OrchestratorV2ScenarioResult, transcript: ProviderReplayTranscript, ) { - const stats = transcript.entries.flatMap((entry) => - entry.type === "emit_inbound" && - field(entry.frame, "type") === "response" && - field(entry.frame, "command") === "get_session_stats" - ? [field(entry.frame, "data")] - : [], - ); - const turns = projectionFor(result, transcript.scenario).providerTurns; - assert.lengthOf(turns, stats.length); - for (const [index, turn] of turns.entries()) { - const contextUsage = field(stats[index], "contextUsage"); - const tokens = field(stats[index], "tokens"); - const { updatedAt: _updatedAt, ...tokenUsage } = turn.tokenUsage ?? { updatedAt: "" }; - assert.deepEqual(tokenUsage, { - usedTokens: field(contextUsage, "tokens"), - maxTokens: field(contextUsage, "contextWindow"), - inputTokens: field(tokens, "input"), - cachedInputTokens: field(tokens, "cacheRead"), - outputTokens: field(tokens, "output"), - }); + const expected: Array> = []; + let messageUsage: unknown; + for (const entry of transcript.entries) { + if (entry.type !== "emit_inbound") continue; + const usage = field(entry.frame, "usage"); + if (field(entry.frame, "type") === "message_update" && field(usage, "totalTokens") !== 0) { + messageUsage = usage; + } + if ( + field(entry.frame, "type") === "response" && + field(entry.frame, "command") === "get_session_stats" + ) { + const contextUsage = field(field(entry.frame, "data"), "contextUsage"); + const count = (key: string) => Number(field(messageUsage, key)); + expected.push({ + usedTokens: field(contextUsage, "tokens"), + maxTokens: field(contextUsage, "contextWindow"), + inputTokens: count("input") + count("cacheRead") + count("cacheWrite"), + cachedInputTokens: count("cacheRead"), + outputTokens: count("output"), + }); + } } + const turns = projectionFor(result, transcript.scenario).providerTurns; + assert.deepEqual( + turns.map((turn) => { + const { updatedAt: _updatedAt, ...tokenUsage } = turn.tokenUsage ?? { updatedAt: "" }; + return tokenUsage; + }), + expected, + ); } export function assertPiSimpleOutput( diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index 019af2a98783f..b3e54117f02ee 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -4159,6 +4159,62 @@ describe("PiAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(layerTest)), ); + it.effect("reports cached input as a share of input in live and completed token usage", () => + Effect.gen(function* () { + const fake = yield* makeFakePi; + fake.queueState({ + sessionFile: FAKE_SESSION_FILE, + model: { provider: "anthropic", id: "large", contextWindow: 1_000_000 }, + }); + const { runtime, takeEvent } = yield* openRuntime(fake); + const providerThread = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + yield* startTurn(runtime, providerThread); + yield* fake.takeRequest("prompt"); + // Pi's message usage counts uncached input, cache reads and cache writes separately. + const usage = { input: 6, cacheRead: 40_101, cacheWrite: 10_561, output: 123 }; + // Session stats total every message in the session, not this turn. + fake.queueStats({ + tokens: { + input: 1_206, + cacheRead: 90_202, + cacheWrite: 60_622, + output: 250, + total: 152_280, + }, + contextUsage: { tokens: 50_791, contextWindow: 1_000_000 }, + }); + yield* fake.emit({ type: "response", command: "prompt", success: true }); + yield* fake.emit({ type: "agent_start" }); + yield* fake.emit({ type: "message_start", message: { role: "assistant" } }); + yield* fake.emit({ + type: "message_update", + usage: { ...usage, totalTokens: 50_791 }, + assistantMessageEvent: { type: "text_delta", contentIndex: 0, delta: "ok" }, + }); + const live = yield* takeEvent( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.tokenUsage !== undefined, + ); + assert.deepInclude( + live.type === "provider_turn.updated" ? live.providerTurn.tokenUsage : undefined, + { inputTokens: 50_668, cachedInputTokens: 40_101 }, + ); + yield* fake.emit({ type: "agent_settled" }); + const completed = yield* takeEvent( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.status === "completed", + ); + assert.deepInclude( + completed.type === "provider_turn.updated" ? completed.providerTurn.tokenUsage : undefined, + { inputTokens: 50_668, cachedInputTokens: 40_101 }, + ); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + it.effect.each(["turn window", "full tree"] as const)( "finishes a turn whose %s has a parentId cycle", (cycleIn) => diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index eae7f3eb6c2fa..e7803bbe9c5ee 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -359,6 +359,11 @@ function compactionTitle(status: PiCompactionStatus): string { } } +type PiMessageTokenUsage = Pick< + OrchestrationV2ProviderTurnTokenUsage, + "inputTokens" | "cachedInputTokens" | "outputTokens" +>; + interface ActivePiTurn { readonly turnInput: ProviderAdapter.ProviderAdapterV2TurnInput; readonly providerTurn: OrchestrationV2ProviderTurn; @@ -377,6 +382,7 @@ interface ActivePiTurn { promptMayBeCommandOnly: boolean; latestCompactionAfterTokens: number | null; lastLiveUsedTokens: number | null; + lastMessageUsage: PiMessageTokenUsage | undefined; settleProbeGeneration: number; /** An extension may start compaction immediately after Pi emits agent_settled. */ settleWhenIdle: boolean; @@ -904,6 +910,25 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return value === undefined ? undefined : Math.max(0, Math.trunc(value)); }; + // Pi counts uncached input, cache reads and cache writes separately; input includes all three. + const piMessageTokenUsage = (usage: unknown): PiMessageTokenUsage => { + const uncachedInputTokens = nonNegativeInteger(usage, "input"); + const cachedInputTokens = nonNegativeInteger(usage, "cacheRead"); + const outputTokens = nonNegativeInteger(usage, "output"); + return { + ...(uncachedInputTokens === undefined + ? {} + : { + inputTokens: + uncachedInputTokens + + (cachedInputTokens ?? 0) + + (nonNegativeInteger(usage, "cacheWrite") ?? 0), + }), + ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }), + ...(outputTokens === undefined ? {} : { outputTokens }), + }; + }; + const rememberModelContextWindow = (model: unknown): number | null => { const provider = recordString(model, "provider"); const id = recordString(model, "id"); @@ -994,6 +1019,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( const tokenUsageFromStats = ( stats: unknown, fallbackUsedTokens: number | null, + messageUsage: PiMessageTokenUsage | undefined, updatedAt: DateTime.Utc, ): OrchestrationV2ProviderTurnTokenUsage | undefined => { const contextUsage = recordField(stats, "contextUsage"); @@ -1002,24 +1028,20 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( nonNegativeInteger(contextUsage, "tokens") ?? fallbackUsedTokens ?? undefined; if (usedTokens === undefined || maxTokens === undefined || maxTokens === 0) return undefined; - - const totals = recordField(stats, "tokens"); - const inputTokens = nonNegativeInteger(totals, "input"); - const cachedInputTokens = nonNegativeInteger(totals, "cacheRead"); - const outputTokens = nonNegativeInteger(totals, "output"); - return { - usedTokens, - maxTokens, - ...(inputTokens === undefined ? {} : { inputTokens }), - ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }), - ...(outputTokens === undefined ? {} : { outputTokens }), - updatedAt: DateTime.formatIso(updatedAt), - }; + // Stats `tokens` are whole-session totals; the breakdown comes from the turn's last message. + return { usedTokens, maxTokens, ...messageUsage, updatedAt: DateTime.formatIso(updatedAt) }; }; - const readTokenUsage = (fallbackUsedTokens: number | null, updatedAt: DateTime.Utc) => + const readTokenUsage = (turn: ActivePiTurn, updatedAt: DateTime.Utc) => request({ type: "get_session_stats" }, 2_000).pipe( - Effect.map((stats) => tokenUsageFromStats(stats, fallbackUsedTokens, updatedAt)), + Effect.map((stats) => + tokenUsageFromStats( + stats, + turn.latestCompactionAfterTokens, + turn.lastMessageUsage, + updatedAt, + ), + ), Effect.orElseSucceed(() => undefined), ); @@ -1030,6 +1052,9 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( /* Provider events include streaming deltas; avoid a span for each update. */ Effect.fnUntraced(function* (turn: ActivePiTurn, usage: unknown) { const usedTokens = nonNegativeInteger(usage, "totalTokens"); + if (usedTokens !== undefined && usedTokens > 0) { + turn.lastMessageUsage = piMessageTokenUsage(usage); + } if ( usedTokens === undefined || usedTokens === 0 || @@ -1040,9 +1065,6 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return; } turn.lastLiveUsedTokens = usedTokens; - const inputTokens = nonNegativeInteger(usage, "input"); - const cachedInputTokens = nonNegativeInteger(usage, "cacheRead"); - const outputTokens = nonNegativeInteger(usage, "output"); const updatedAt = yield* DateTime.now; yield* emit({ type: "provider_turn.updated", @@ -1053,9 +1075,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( tokenUsage: { usedTokens, maxTokens: contextWindow, - ...(inputTokens === undefined ? {} : { inputTokens }), - ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }), - ...(outputTokens === undefined ? {} : { outputTokens }), + ...turn.lastMessageUsage, updatedAt: DateTime.formatIso(updatedAt), }, }, @@ -2075,9 +2095,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( } const treeRefs = turn.stopTreeRefs !== undefined ? turn.stopTreeRefs : yield* captureTurnTreeRefs(); - const tokenUsage = readUsage - ? yield* readTokenUsage(turn.latestCompactionAfterTokens, completedAt) - : undefined; + const tokenUsage = readUsage ? yield* readTokenUsage(turn, completedAt) : undefined; const failure = interrupted ? null : (turn.rejectedPromptFailure ?? turn.failure); yield* emit({ type: "provider_turn.updated", @@ -3474,6 +3492,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( compactCommand !== null || (payload?.message.trimStart().startsWith("/") ?? false), latestCompactionAfterTokens: null, lastLiveUsedTokens: null, + lastMessageUsage: undefined, settleProbeGeneration: 0, settleWhenIdle: false, compactionCancelled: false, From 4c3d83ff24c7437582cfd37ebe4565314250630b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 01:25:30 -0800 Subject: [PATCH 12/17] fix(mobile): usage account detail keeps even pace current while open (#40759) --- apps/mobile/src/features/usage/UsageLimitsPooled.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx index 96d8f922340f7..4c290d68ac338 100644 --- a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx +++ b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx @@ -20,6 +20,7 @@ import { import { msg, T, useGT, useMessages, Var } from "gt-react-native"; import { Fragment, type ReactNode, useId, useState } from "react"; import { Pressable, View } from "react-native"; +import { useNowMinuteMs } from "../../lib/clock"; import { tryOpenExternalUrl } from "../../lib/openExternalUrl"; import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView"; import { Defs, Path, Pattern, Rect, Svg } from "react-native-svg"; @@ -201,7 +202,6 @@ function PoolWindowCard({ windowId: pool.id, windowKind: pool.kind, environmentIds, - now, }); const summary = ( <> @@ -590,13 +590,13 @@ type AccountScreenProps = StaticScreenProps<{ windowId: string; windowKind: LimitPoolWindow["kind"]; environmentIds: readonly string[] | null; - now: number; }>; export function UsageLimitAccountScreen({ route }: AccountScreenProps) { const insets = useSafeAreaInsets(); const presentations = useAtomValue(environmentPresentations.presentationsWithProvidersAtom); - const { accountKey, windowId, windowKind, environmentIds, now } = route.params; + const { accountKey, windowId, windowKind, environmentIds } = route.params; + const now = useNowMinuteMs(); const selectedIds = environmentIds === null ? null : new Set(environmentIds.map((id) => EnvironmentId.make(id))); const selected = From 7f125d83d18b2b4e9e65debf8e4d1ae71c45af94 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 01:27:45 -0800 Subject: [PATCH 13/17] fix(server): Resume sends pending context to providers without native resume (#40764) --- .../ProviderTurnStartService.test.ts | 21 +++++++ .../ProviderTurnStartService.ts | 61 +++++++++++++------ 2 files changed, 63 insertions(+), 19 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index 4bf6e71397fe5..89e5a6930bafc 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -2289,6 +2289,27 @@ effectIt.effect("refuses unsupported resume instead of manufacturing a user prom }), ); +effectIt.effect.each([ + { contextRun: "current" }, + { contextRun: "failed", switchedProvider: true }, +] as const)( + "a resume that carries pending context asks a provider without native resume to continue: %j", + (sideChat) => + Effect.gen(function* () { + const harness = makeLocalCommandHarness({ + text: "", + manualContinuation: true, + nativeResumeUnsupported: true, + sideChat, + }); + yield* harness.start; + expect(harness.settledRuns).toEqual([]); + expect(harness.startTurn.mock.calls.map(([turn]) => turn.message.text)).toEqual([ + withInlineContext("SIDE_CHAT_CONTEXT", "Continue where you left off."), + ]); + }), +); + effectIt.effect.each([ { contextRun: "current", runtimeMode: "full-access", context: "SIDE_CHAT_CONTEXT" }, { contextRun: "failed", runtimeMode: "full-access", context: "SIDE_CHAT_CONTEXT" }, diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 8e35271ce5aa9..c3890cab5f71b 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -408,12 +408,22 @@ export const layer: Layer.Layer< return { ...session, startTurn: (input: Parameters[0]) => start(input), - ...(session.resumeTurn === undefined - ? {} - : { - resumeTurn: (input: ProviderAdapter.ProviderAdapterV2ResumeTurnInput) => - start(ProviderAdapter.resumeTurnInput(input)), - }), + // Pending context can prompt a resume, so even a session without native resume takes one. + resumeTurn: (input: ProviderAdapter.ProviderAdapterV2ResumeTurnInput) => + session.resumeTurn === undefined && deliver === undefined + ? Effect.fail( + new ProviderAdapter.ProviderAdapterTurnStartError({ + driver: session.driver, + threadId: input.threadId, + providerThreadId: input.providerThread.id, + runId: input.runId, + cause: new ProviderAdapter.ProviderResumeUnsupportedError({ + driver: session.driver, + providerThreadId: input.providerThread.id, + }), + }), + ) + : start(ProviderAdapter.resumeTurnInput(input)), ...(session.compactThread === undefined ? {} : { @@ -1859,7 +1869,21 @@ export const layer: Layer.Layer< legacyInputRunIds, budget, } = handoffContext; - if (manualResume && unsentResumeMessage === undefined && session.resumeTurn === undefined) { + const retryHandoff = resumedRetryHandoff ?? (yield* prepareRetryHandoff(handoffContext)); + const carriesPendingContext = + effectiveHandoffs.length > 0 || + retryHandoff.handoffs.length > 0 || + retryHandoff.attachments.length > 0 || + sideChatHandoff !== undefined || + restartNote !== "" || + noteContinuation; + // Pending context turns the resume into a prompted turn, which needs no native resume. + if ( + manualResume && + unsentResumeMessage === undefined && + session.resumeTurn === undefined && + !carriesPendingContext + ) { yield* settleStartFailure({ signal: "resume-unsupported", title: "Native resume is unavailable", @@ -1870,7 +1894,6 @@ export const layer: Layer.Layer< }); return; } - const retryHandoff = resumedRetryHandoff ?? (yield* prepareRetryHandoff(handoffContext)); const runningProviderThread: OrchestrationV2ProviderThread = { ...loadedProviderThread, contextUsage: handoffUsage, @@ -2100,8 +2123,14 @@ export const layer: Layer.Layer< turnInput.resume && prompted && userText === "" ? RESUME_PROMPT : userText; const text = goalCommand ? userText : withInlineContext(context, requestText); const operation = - turnInput.resume && !prompted && session.resumeTurn !== undefined - ? session.resumeTurn({ ...resumeInput, messageId: resumeMessage.messageId }) + turnInput.resume && !prompted + ? (session.resumeTurn?.({ ...resumeInput, messageId: resumeMessage.messageId }) ?? + Effect.fail( + new ProviderAdapter.ProviderResumeUnsupportedError({ + driver: session.driver, + providerThreadId: providerThread.id, + }), + )) : start({ ...(prompted ? contextInput : startInput), message: { @@ -2176,15 +2205,9 @@ export const layer: Layer.Layer< }), ), ); - const deliverySession = - effectiveHandoffs.length === 0 && - retryHandoff.handoffs.length === 0 && - retryHandoff.attachments.length === 0 && - sideChatHandoff === undefined && - restartNote === "" && - !noteContinuation - ? session - : makeDeliverySession(session, startWithHandoffs); + const deliverySession = carriesPendingContext + ? makeDeliverySession(session, startWithHandoffs) + : session; return runExecution.startRootRun({ commandId: CommandId.make(`command:effect:provider-turn.start:${run.id}`), appThread: projection.thread, From 90a8ac086435ac3503810f64da2fc3c930ef8ce1 Mon Sep 17 00:00:00 2001 From: Aman Thanvi <22306104+amanthanvi@users.noreply.github.com> Date: Sun, 22 Nov 2026 04:39:13 -0500 Subject: [PATCH 14/17] fix(server): a failed or cancelled clone no longer blocks re-cloning its destination (#40739) Co-authored-by: Julius Marminge --- .../src/project/ProjectCloneTracker.test.ts | 62 +++++++++++++++++++ .../server/src/project/ProjectCloneTracker.ts | 17 +++-- 2 files changed, 74 insertions(+), 5 deletions(-) diff --git a/apps/server/src/project/ProjectCloneTracker.test.ts b/apps/server/src/project/ProjectCloneTracker.test.ts index bdbb47b767c03..3b2e6f1179b86 100644 --- a/apps/server/src/project/ProjectCloneTracker.test.ts +++ b/apps/server/src/project/ProjectCloneTracker.test.ts @@ -312,6 +312,68 @@ describe("ProjectCloneTracker", () => { }).pipe(Effect.provide(harness.layer)); }); + it.effect("a fresh clone into a failed clone's destination supersedes it", () => { + let attempts = 0; + const harness = makeHarness({ + clone: (input) => + Effect.suspend(() => + ++attempts === 1 + ? Effect.fail( + new SourceControlRepositoryError({ + operation: "cloneRepository", + provider: SourceControlProviderKind.make("unknown"), + detail: "fatal: repository not found", + }), + ) + : Effect.succeed({ + cwd: input.destinationPath, + remoteUrl: input.remoteUrl ?? "", + repository: null, + }), + ), + }); + // The failed clone's project still owns the destination. + const conflictingHooks: ProjectCloneTracker.ProjectCloneHooks = { + ...harness.hooks, + createProject: (input) => + Effect.fail( + new ProjectConflictError({ + projectId: input.projectId, + workspaceRoot: input.workspaceRoot, + conflictingProjectId: projectId, + }), + ), + }; + return Effect.gen(function* () { + const tracker = yield* ProjectCloneTracker.ProjectCloneTracker; + yield* tracker.start(startInput, harness.hooks); + yield* Effect.yieldNow; + expect((yield* tracker.get(projectId))?.phase).toBe("failed"); + + const second = ProjectId.make("project-2"); + const result = yield* tracker.start({ ...startInput, projectId: second }, conflictingHooks); + expect(result.projectId).toBe(projectId); + yield* Effect.yieldNow; + expect((yield* tracker.get(projectId))?.phase).toBe("done"); + expect(yield* tracker.get(second)).toBeNull(); + expect(harness.cloned).toEqual([projectId]); + }).pipe(Effect.provide(harness.layer)); + }); + + it.effect("refuses a second clone into a destination that is still cloning", () => { + const harness = makeHarness({ clone: () => Effect.never }); + return Effect.gen(function* () { + const tracker = yield* ProjectCloneTracker.ProjectCloneTracker; + yield* tracker.start(startInput, harness.hooks); + yield* Effect.yieldNow; + const error = yield* Effect.flip( + tracker.start({ ...startInput, projectId: ProjectId.make("project-2") }, harness.hooks), + ); + expect(error.message).toContain("already in progress"); + expect((yield* tracker.get(projectId))?.phase).toBe("running"); + }).pipe(Effect.provide(harness.layer)); + }); + it.effect("does not create a project when the clone cannot be prepared", () => { const harness = makeHarness(); const layer = ProjectCloneTracker.layer.pipe( diff --git a/apps/server/src/project/ProjectCloneTracker.ts b/apps/server/src/project/ProjectCloneTracker.ts index 0a24f11ffd89d..367b839cf2a6b 100644 --- a/apps/server/src/project/ProjectCloneTracker.ts +++ b/apps/server/src/project/ProjectCloneTracker.ts @@ -297,14 +297,19 @@ export const make = Effect.gen(function* () { endedAt: null, sequence: ++sequence, }; - const claimed = yield* Ref.modify(clones, (current) => { - const conflict = Array.from(current.values()).some( + const claim = yield* Ref.modify(clones, (current) => { + const overlapping = Array.from(current.values()).filter( (tracked) => tracked.snapshot.projectId === input.projectId || tracked.input.destinationPath === prepared.destinationPath, ); - if (conflict) return [false, current] as const; + // Only a running clone owns its destination; a failed or cancelled one + // left nothing behind, so a fresh start supersedes it. + if (overlapping.some((tracked) => tracked.snapshot.phase === "running")) { + return [null, current] as const; + } const next = new Map(current); + for (const stale of overlapping) next.delete(stale.snapshot.projectId); next.set(input.projectId, { snapshot, fiber: null, @@ -316,14 +321,16 @@ export const make = Effect.gen(function* () { protocol: input.protocol ?? "auto", }, }); - return [true, next] as const; + return [overlapping.map((stale) => stale.snapshot.projectId), next] as const; }); const alreadyInProgress = new SourceControlRepositoryError({ operation: "cloneRepository", provider: input.provider ?? SourceControlProviderKind.make("unknown"), detail: "A clone into this destination is already in progress.", }); - if (!claimed) return yield* alreadyInProgress; + if (claim === null) return yield* alreadyInProgress; + // A superseded done entry's pending removal would otherwise delete the new claim. + yield* Effect.forEach(claim, clearRetention, { discard: true }); // Finish or release the claim despite disconnects; a claim without a fiber cannot be cancelled or retried. const projectId = yield* Effect.uninterruptible( Effect.gen(function* () { From 70b5e489b91842243655cbc4307c614feb314ff0 Mon Sep 17 00:00:00 2001 From: Wu Shuwen Date: Sun, 22 Nov 2026 17:43:07 +0800 Subject: [PATCH 15/17] fix: retain pull request metadata in thread show (#40744) Co-authored-by: Julius Marminge --- apps/server/src/cli/thread.test.ts | 34 ++++++++++++++++++++++++++++++ apps/server/src/cli/thread.ts | 3 ++- 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/apps/server/src/cli/thread.test.ts b/apps/server/src/cli/thread.test.ts index 49887ee0bb7cc..bb0906a9c6919 100644 --- a/apps/server/src/cli/thread.test.ts +++ b/apps/server/src/cli/thread.test.ts @@ -558,6 +558,40 @@ const timelineTools = (types: ReadonlyArray) => { const tail = (tools: number) => [...Array(tools).fill("tool_call"), "assistant_message"]; +it.effect("show retains pull request metadata when reading a later message window", () => + Effect.gen(function* () { + const link = { + host: "github.com", + repository: "owner/repo", + number: 1, + url: "https://github.com/owner/repo/pull/1", + source: "manual", + state: "open", + watching: false, + watchStartedAt: null, + } as const; + const call = ((_tool: string, input: unknown) => { + const args = input as { afterPosition?: number; limit: number }; + const first = args.afterPosition === undefined && args.limit === 1; + return Effect.succeed({ + thread: { + itemCount: 200, + status: first ? "running" : "completed", + pullRequestCount: 1, + ...(first ? { pullRequests: [link], openPullRequestCount: 1 } : {}), + }, + items: first ? [] : [{ position: 199, itemId: "message", type: "assistant_message" }], + nextPosition: 199, + hasMore: false, + }); + }) as ThreadTools["call"]; + const { thread } = yield* readLatestMessages({ call }, threadId, 1); + assert.strictEqual(thread.status, "completed"); + assert.deepStrictEqual(thread.pullRequests, [link]); + assert.strictEqual(thread.openPullRequestCount, 1); + }), +); + it.effect("show reads the end of a long thread, not its whole history", () => Effect.gen(function* () { const { tools, served, latest } = timelineTools([ diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index e63e762237e85..09ee65c32172b 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -459,7 +459,8 @@ export const readLatestMessages = Effect.fn("cli.thread.readLatestMessages")(fun ); afterPosition = page.nextPosition ?? Number.POSITIVE_INFINITY; } while (page.hasMore && afterPosition < (end ?? Number.POSITIVE_INFINITY) - 1); - thread = page.thread; + // Only the first read carries pull request previews; later pages omit them. + thread = Object.assign({}, thread, page.thread); // A window can hold the whole --messages count, too many to spread as arguments. messages = window.concat(messages); before = start; From c3a330d8342f0825293b56c0fd22b20c6ef3206c Mon Sep 17 00:00:00 2001 From: Jinhui Zheng Date: Sun, 22 Nov 2026 18:03:40 +0800 Subject: [PATCH 16/17] fix(web): show Queue for running sessions that cannot steer (#40767) Co-authored-by: Julius Marminge --- apps/web/src/components/ChatView.tsx | 11 ++---- .../src/state/threadWorkflows.test.ts | 34 ++++++++++++++++- .../src/state/threadWorkflows.ts | 37 ++++++++++++++++--- 3 files changed, 68 insertions(+), 14 deletions(-) diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 254bbd4eb9e42..d17af4f620755 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -106,10 +106,9 @@ import { } from "@t3tools/client-runtime/state/subagentRuntime"; import { getUserQueuedThreadRuns, - threadSteersDuringCompaction, + threadCanSteer, threadSupportsProviderHandoff, } from "@t3tools/client-runtime/state/thread-workflows"; -import { compactionBlocksSteering } from "@t3tools/client-runtime/state/composer-dispatch"; import { resolvePendingHandoff } from "@t3tools/client-runtime/handoff"; import { HandoffRow } from "./chat/V2LifecycleRow"; import { @@ -1545,12 +1544,10 @@ export default function ChatView(props: ChatViewProps) { const isCompacting = (isSendBusy || phase === "connecting" || phase === "running") && (compactionRunning || compactCommandIsActive); - const compactionBlocksSteer = compactionBlocksSteering({ + const canSteer = threadCanSteer(serverProjection, { compactCommandIsActive, compactionRunning, - steersDuringCompaction: threadSteersDuringCompaction(serverProjection), - run: serverProjection?.runs.find((run) => run.id === activeRuntime?.activeRunId), - messages: serverProjection?.messages, + activeRunId: activeRuntime?.activeRunId, }); const isWorking = deriveTimelineWorking({ phase, @@ -3822,7 +3819,7 @@ export default function ChatView(props: ChatViewProps) { isLocalDraftThread && activeProject === null } phase={phase} - canSteer={!compactionBlocksSteer} + canSteer={canSteer} canInterrupt={canInterruptRunningThread} isSendBusy={ (isSendBusy && !sendQueuesBehindSetup) || diff --git a/packages/client-runtime/src/state/threadWorkflows.test.ts b/packages/client-runtime/src/state/threadWorkflows.test.ts index a4049c7169163..fd8092a996a66 100644 --- a/packages/client-runtime/src/state/threadWorkflows.test.ts +++ b/packages/client-runtime/src/state/threadWorkflows.test.ts @@ -6,6 +6,7 @@ import { deriveThreadQueueWorkflowState, getUserQueuedThreadRuns, resolveLatestMergeBackRun, + threadCanSteer, threadSupportsProviderHandoff, } from "./threadWorkflows.ts"; @@ -13,6 +14,7 @@ const capabilities = (input?: { readonly queued?: boolean; readonly steer?: boolean; readonly restartSteer?: boolean; + readonly interrupt?: boolean; readonly nativeFork?: boolean; readonly portableFork?: boolean; }) => @@ -21,6 +23,7 @@ const capabilities = (input?: { supportsQueuedMessages: input?.queued ?? false, supportsActiveSteering: input?.steer ?? false, supportsSteeringByInterruptRestart: input?.restartSteer ?? false, + supportsInterrupt: input?.interrupt ?? false, }, threads: { canForkThread: input?.nativeFork ?? false, @@ -31,6 +34,35 @@ const capabilities = (input?: { }) as never; describe("thread workflows", () => { + it.each([ + ["queue only", { queued: true }, false, false], + ["session still attaching", undefined, false, true], + ["native steering", { steer: true }, false, true], + ["interrupt and restart", { interrupt: true, restartSteer: true }, false, true], + ["restart without interrupt", { restartSteer: true }, false, false], + ["explicit compaction", { steer: true }, true, false], + ] as const)("gates composer steering for %s", (_, turns, compactCommandIsActive, expected) => { + const projection = { + thread: { id: "thread", activeProviderThreadId: "provider-thread" }, + runs: [{ id: "active", status: "running", providerThreadId: "provider-thread" }], + providerThreads: [{ id: "provider-thread", providerSessionId: "session" }], + providerSessions: [ + ...(turns === undefined + ? [] + : [{ id: "session", status: "running", capabilities: capabilities(turns) }]), + { id: "other", status: "ready", capabilities: capabilities({ steer: true }) }, + ], + messages: [], + } as unknown as OrchestrationV2ThreadProjection; + expect( + threadCanSteer(projection, { + compactCommandIsActive, + compactionRunning: false, + activeRunId: projection.runs[0]!.id, + }), + ).toBe(expected); + }); + it("skips message history classification when no runs are queued", () => { let metadataReads = 0; const message = { @@ -139,7 +171,7 @@ describe("thread workflows", () => { { id: "provider-session", status: "running", - capabilities: capabilities({ queued: true, restartSteer: true }), + capabilities: capabilities({ queued: true, interrupt: true, restartSteer: true }), }, ], } as never); diff --git a/packages/client-runtime/src/state/threadWorkflows.ts b/packages/client-runtime/src/state/threadWorkflows.ts index 7dbbcf1e80c57..9e3d1eb4512b2 100644 --- a/packages/client-runtime/src/state/threadWorkflows.ts +++ b/packages/client-runtime/src/state/threadWorkflows.ts @@ -8,6 +8,7 @@ import { copySorted } from "@t3tools/shared/Array"; import { mFallback, msg } from "gt-i18n"; import type { MFunctionType } from "gt-i18n/types"; +import { compactionBlocksSteering } from "./composerDispatch.ts"; import type { ThreadStructure } from "./models.ts"; type Projection = ThreadStructure; @@ -102,6 +103,33 @@ export function threadSteersDuringCompaction(projection: Projection | null | und ); } +function supportsSteering(turns: OrchestrationV2ProviderCapabilities["turns"]): boolean { + return ( + turns.supportsActiveSteering || + (turns.supportsInterrupt && turns.supportsSteeringByInterruptRestart) + ); +} + +export function threadCanSteer( + projection: Projection | null, + input: { + readonly compactCommandIsActive: boolean; + readonly compactionRunning: boolean; + readonly activeRunId: Run["id"] | null | undefined; + }, +): boolean { + const turns = projection && resolveThreadProviderSession(projection)?.capabilities.turns; + // A steer submitted before the session attaches can wait for its provider turn. + if (turns && !supportsSteering(turns)) return false; + return !compactionBlocksSteering({ + compactCommandIsActive: input.compactCommandIsActive, + compactionRunning: input.compactionRunning, + steersDuringCompaction: turns?.activeSteeringDuringCompaction === true, + run: projection?.runs.find((run) => run.id === input.activeRunId), + messages: projection?.messages, + }); +} + export function threadSupportsProviderHandoff(projection: Projection | null | undefined): boolean { if (projection == null) return false; const session = resolveThreadProviderSession(projection); @@ -147,6 +175,7 @@ export function deriveThreadQueueWorkflowState( const activeRun = resolveActiveThreadRun(projection); const session = resolveThreadProviderSession(projection); const capabilities = session?.capabilities.turns; + const canSteer = capabilities !== undefined && supportsSteering(capabilities); const activeMessage = projection.messages.find( (message) => message.id === activeRun?.userMessageId, ); @@ -187,12 +216,8 @@ export function deriveThreadQueueWorkflowState( canPromoteToSteer: promoteSkipsCompaction || ((activeRun?.status === "preparing" || activeRun?.status === "starting") && - (capabilities === undefined || - capabilities.supportsActiveSteering || - capabilities.supportsSteeringByInterruptRestart)) || - (hasSteerableProviderTurn && - (capabilities?.supportsActiveSteering === true || - capabilities?.supportsSteeringByInterruptRestart === true)), + (capabilities === undefined || canSteer)) || + (hasSteerableProviderTurn && canSteer), promoteSkipsCompaction, }; } From c198f73b3766090e02cace1a8b14f439f9fc63b6 Mon Sep 17 00:00:00 2001 From: AymanKhan9 Date: Sun, 22 Nov 2026 15:54:47 +0530 Subject: [PATCH 17/17] fix(web): a click outside the project action editor no longer discards the draft (#40776) --- .../projectScriptEditor.browser.test.tsx | 14 ++++++++++++++ apps/web/src/components/projectScriptEditor.tsx | 2 ++ 2 files changed, 16 insertions(+) diff --git a/apps/web/src/components/projectScriptEditor.browser.test.tsx b/apps/web/src/components/projectScriptEditor.browser.test.tsx index a9ea6f03ad185..0f37c32b23a9e 100644 --- a/apps/web/src/components/projectScriptEditor.browser.test.tsx +++ b/apps/web/src/components/projectScriptEditor.browser.test.tsx @@ -3,6 +3,7 @@ import { EnvironmentId } from "@t3tools/contracts"; import { AsyncResult } from "effect/reactivity"; import { StrictMode } from "react"; import { describe, expect, it, vi } from "vite-plus/test"; +import { page, userEvent } from "vite-plus/test/browser"; vi.mock(import("~/state/session"), async (original) => ({ ...(await original()), @@ -86,3 +87,16 @@ describe("project action editor save lifecycle", () => { expect(onSubmit.mock.calls.map(([scriptId]) => scriptId)).toEqual(["build", "test"]); }); }); + +describe("project action editor dismissal", () => { + it("stays open when the user clicks outside the editor", async () => { + setup(); + await using screen = await render(null); + await open(screen, { scriptId: null, initial: EMPTY_PROJECT_SCRIPT_INPUT }); + await expect.element(page.getByRole("dialog")).toBeVisible(); + + await userEvent.click(document.body, { position: { x: 1, y: 1 } }); + + expect(onClose).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/web/src/components/projectScriptEditor.tsx b/apps/web/src/components/projectScriptEditor.tsx index 504e0afc69ca0..ea9b5ca1f2245 100644 --- a/apps/web/src/components/projectScriptEditor.tsx +++ b/apps/web/src/components/projectScriptEditor.tsx @@ -188,6 +188,8 @@ export function ProjectScriptEditorDialog({ <> { if (!open) onClose(); }}