From abf072493b6b571fbc1d4c4e860ced59fe676a29 Mon Sep 17 00:00:00 2001 From: SeongHoon Ryu <4997174+ryush00@users.noreply.github.com> Date: Mon, 16 Nov 2026 08:08:16 +0900 Subject: [PATCH 01/21] fix(antigravity): full-access skips agy's own confirmations The agy CLI asks before every tool in its `default` mode, and accounts without `auto` have no mode that stops it. Full-access now starts agy with `--dangerously-skip-permissions`. It is a spawn flag, so a turn that switches to or from full-access restarts the runtime with the new policy. Session modes map to what the CLI or the managed runtime advertises. This patch used to carry a watcher that re-prompted agy after a background command finished. Upstream #38864 and #38916 now continue those replies, so the watcher is gone. Co-Authored-By: Claude Fable 5.2 --- .../Adapters/AntigravityAdapterV2.test.ts | 123 ++++++++++++++++++ .../Adapters/AntigravityAdapterV2.ts | 2 + .../Drivers/AntigravityDriver.test.ts | 3 +- .../src/provider/Drivers/AntigravityDriver.ts | 17 ++- .../acp/AntigravityAcpSupport.test.ts | 35 ++++- .../src/provider/acp/AntigravityAcpSupport.ts | 81 +++++++++++- .../provider/antigravityAuthSupport.test.ts | 25 ++++ .../src/provider/antigravityAuthSupport.ts | 4 + packages/provider-acp/src/server/adapter.ts | 62 ++++++++- 9 files changed, 334 insertions(+), 18 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index b18fa1df947f1..5fc1d2ecba4e8 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -1902,3 +1902,126 @@ describe("AntigravityAdapterV2 session system prompt", () => { }).pipe(Effect.provide(layerSession)), ); }); + +describe("AntigravityAdapterV2 full-access restart", () => { + it.effect("restarts the runtime when a turn switches to full-access", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const crypto = yield* SecureRandom.SecureRandom; + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-ag-restart-ws-" }); + const spawnedRuntimeModes: Array = []; + + const instanceId = ProviderInstanceId.make("antigravity-restart-test"); + const threadId = ThreadId.make("thread-antigravity-restart"); + const adapter = yield* makeAntigravityAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + makeRuntime: (input) => + Effect.sync(() => { + spawnedRuntimeModes.push(input.runtimePolicy?.runtimeMode); + }).pipe( + Effect.andThen( + makeAntigravityAcpRuntime({ + ...input, + childProcessSpawner, + spawn: { + command: process.execPath, + args: [mockAgentPath], + cwd: input.cwd, + env: { T3_ACP_ANTIGRAVITY: "1", T3_ACP_AGENT_VERSION: "1.5.9" }, + }, + }), + ), + Effect.provideService(SecureRandom.SecureRandom, crypto), + Effect.map((runtime): AcpSessionRuntime.AcpSessionRuntime["Service"] => ({ + ...runtime, + prompt: () => Effect.succeed({ stopReason: "end_turn" as const }), + })), + ), + withProcess: (_stop, task) => task, + defaultModel: Effect.undefined, + }); + + const policyFor = (runtimeMode: "approval-required" | "full-access") => + ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode, + interactionMode: "default", + cwd: workspace, + }); + const modelSelection = { instanceId, model: "gemini-test-low" } as const; + const session = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-antigravity-restart"), + modelSelection, + runtimePolicy: policyFor("approval-required"), + }); + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy: policyFor("approval-required"), + }); + const now = yield* DateTime.now; + const runTurn = (ordinal: number, runtimeMode: "approval-required" | "full-access") => + session + .startTurn({ + appThread: { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: ProjectId.make("project-antigravity-restart"), + title: "Antigravity restart", + providerInstanceId: instanceId, + modelSelection, + runtimeMode, + interactionMode: "default", + branch: null, + worktreePath: workspace, + activeProviderThreadId: providerThread.id, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + threadId, + runId: RunId.make(`run-ag-restart-${ordinal}`), + runOrdinal: ordinal, + providerTurnOrdinal: ordinal, + attemptId: RunAttemptId.make(`attempt-ag-restart-${ordinal}`), + rootNodeId: NodeId.make(`node-ag-restart-${ordinal}`), + providerThread, + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make(`msg-ag-restart-${ordinal}`), + text: "continue", + attachments: [], + }, + modelSelection, + runtimePolicy: policyFor(runtimeMode), + }) + .pipe( + Effect.andThen( + session.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ), + ), + ); + + yield* runTurn(1, "approval-required"); + yield* runTurn(2, "full-access"); + // The skip-permissions flag is a spawn argument, so the switch needs a new process. + assert.deepEqual(spawnedRuntimeModes, ["approval-required", "full-access"]); + }).pipe(Effect.provide(layerSession)), + ); +}); diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index 0307c4ba18822..d6ef49f8289d0 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -269,6 +269,8 @@ export function makeAntigravityAcpAdapterFlavor( }); }), sessionModeForPolicy: (policy) => antigravityPermissionMode(policy.runtimeMode), + requiresRuntimeRestartForPolicyChange: (previous, next) => + (previous.runtimeMode === "full-access") !== (next.runtimeMode === "full-access"), runtimeModeForSessionMode: antigravityRuntimeModeForSessionMode, clientFileSystem: { readTextFile: (request, cwd) => diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.test.ts b/apps/server/src/provider/Drivers/AntigravityDriver.test.ts index 2ee99a6fbbfe3..1341c68948c02 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.test.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.test.ts @@ -414,7 +414,7 @@ it.layer(layerTest)("AntigravityDriver", (it) => { }, ]); - // The agy CLI rejects `yolo` and `auto_edit`; it stays in `default` and T3 answers its requests. + // The agy CLI bypasses permissions via CLI flag for full-access and keeps non-advertised modes at `default`. h.controls.selected = { ...(yield* h.makeExecutable("runtime cli", { initialMode: "auto_edit" })), harnessPath: null, @@ -444,6 +444,7 @@ it.layer(layerTest)("AntigravityDriver", (it) => { h.profileDirectory, "--app-data-dir", "antigravity-acp", + ...(runtimeMode === "full-access" ? ["--dangerously-skip-permissions"] : []), ]); expect( (yield* h.readRequests) diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.ts b/apps/server/src/provider/Drivers/AntigravityDriver.ts index 1117fc3b9376c..675f57b56585c 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.ts @@ -44,7 +44,9 @@ import { type AntigravityAuthConfig, } from "../antigravityAuthSupport.ts"; import { + antigravityAdvertisedModeIds, antigravityCliSessionMode, + antigravityManagedSessionMode, antigravityModelOptions, antigravityThinkingConfig, makeAntigravityAcpRuntime, @@ -289,13 +291,22 @@ export const AntigravityDriver: ProviderDriver< baseEnv: spawnEnvironment, auth, runtimeTempDirectory, + skipPermissions: input.runtimePolicy?.runtimeMode === "full-access", }), }).pipe(Effect.provideService(SecureRandom.SecureRandom, random)); return { ...runtime, - ...(executable.harnessPath === null - ? { setMode: (modeId: string) => runtime.setMode(antigravityCliSessionMode(modeId)) } - : {}), + setMode: Effect.fn("AntigravityDriver.setMode")(function* (modeId: string) { + const availableModeIds = antigravityAdvertisedModeIds( + yield* runtime.getModeState, + yield* runtime.getConfigOptions, + ); + const resolved = + executable.harnessPath === null + ? antigravityCliSessionMode(modeId, availableModeIds) + : antigravityManagedSessionMode(modeId, availableModeIds); + return yield* runtime.setMode(resolved); + }), start: () => runtime .start() diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts index dc755d1e7a5a4..65b5e0b5c5f8f 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts @@ -15,9 +15,13 @@ import type * as EffectAcpSchema from "effect-acp/compat"; import { resolveAttachmentPath } from "../../attachmentStore.ts"; import { - applyAntigravityAcpModelSelection, + antigravityCliSessionMode, antigravityClientInfo, + antigravityManagedSessionMode, + antigravityPermissionMode, + antigravityRuntimeModeForSessionMode, antigravitySessionMeta, + applyAntigravityAcpModelSelection, buildAntigravityPrompt, isQualifiedAntigravityRelease, } from "./AntigravityAcpSupport.ts"; @@ -100,6 +104,35 @@ describe("Antigravity release gates", () => { ); }); +describe("Antigravity session mode mapping", () => { + it("maps runtime policies across CLI and managed mode sets", () => { + const cliModes = new Set(["default", "accept-edits", "auto", "plan"]); + const cliWithoutAuto = new Set(["default", "accept-edits", "plan"]); + const managedModes = new Set(["default", "auto_edit", "yolo", "plan"]); + + expect(antigravityPermissionMode("full-access")).toBe("yolo"); + expect(antigravityPermissionMode("auto")).toBe("auto"); + expect(antigravityPermissionMode("auto-accept-edits")).toBe("auto_edit"); + expect(antigravityPermissionMode("approval-required")).toBe("default"); + + expect(antigravityCliSessionMode("yolo", cliModes)).toBe("default"); + expect(antigravityCliSessionMode("auto_edit", cliModes)).toBe("accept-edits"); + expect(antigravityCliSessionMode("auto", cliModes)).toBe("auto"); + expect(antigravityCliSessionMode("auto", cliWithoutAuto)).toBe("default"); + expect(antigravityCliSessionMode("plan", cliModes)).toBe("plan"); + + expect(antigravityManagedSessionMode("yolo", managedModes)).toBe("yolo"); + expect(antigravityManagedSessionMode("accept-edits", managedModes)).toBe("auto_edit"); + expect(antigravityManagedSessionMode("auto", managedModes)).toBe("default"); + + expect(antigravityRuntimeModeForSessionMode("yolo")).toBe("full-access"); + expect(antigravityRuntimeModeForSessionMode("auto")).toBe("auto"); + expect(antigravityRuntimeModeForSessionMode("accept-edits")).toBe("auto-accept-edits"); + expect(antigravityRuntimeModeForSessionMode("auto_edit")).toBe("auto-accept-edits"); + expect(antigravityRuntimeModeForSessionMode("default")).toBe("approval-required"); + }); +}); + describe("applyAntigravityAcpModelSelection", () => { it.effect("restores the saved model instead of the cold-resume default", () => Effect.gen(function* () { diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index 7fd64e2534fa7..bc96bbc3c2453 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -24,6 +24,7 @@ import { makeAntigravityStdoutTransform, } from "../antigravityAuthSupport.ts"; import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; +import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import packageJson from "../../../package.json" with { type: "json" }; import { normalizeAntigravitySessionUpdate } from "./AntigravityProtocol.ts"; @@ -50,6 +51,7 @@ export interface AntigravityAcpRuntimeInput extends Omit< /** Conversational sessions only; helpers and probes leave the system prompt untouched. */ readonly sessionSystemPromptAppend?: string; readonly authMethod?: AntigravityAuthMethod; + readonly runtimePolicy?: ProviderAdapter.ProviderAdapterV2RuntimePolicy; } function parseAntigravityVersion(version: string | null | undefined) { @@ -175,21 +177,62 @@ export function antigravityPermissionMode(runtimeMode: RuntimeMode): string { switch (runtimeMode) { case "full-access": return "yolo"; + case "auto": + return "auto"; case "auto-accept-edits": return "auto_edit"; - case "auto": case "approval-required": return "default"; } } /** - * The agy CLI rejects the managed runtime's `yolo` and `auto_edit`. It stays in `default`, where - * it asks before acting and T3 answers from the live runtime policy, so permission changes apply - * on the next turn without a restart. + * Resolves the session mode to send to the `agy` CLI (`harnessPath === null`). + * `agy` advertises `default`, `accept-edits`, `auto`, and `plan` instead of the managed + * runtime's `yolo` and `auto_edit`; `full-access` uses `--dangerously-skip-permissions` + * at spawn and stays in `default` so accounts without `auto` still auto-approve every tool. */ -export function antigravityCliSessionMode(modeId: string): string { - return modeId === "yolo" || modeId === "auto_edit" ? "default" : modeId; +export function antigravityCliSessionMode( + modeId: string, + availableModeIds?: ReadonlySet, +): string { + const chooseIfAvailable = (candidate: string): string => + availableModeIds === undefined + ? candidate === "accept-edits" || candidate === "auto" + ? "default" + : candidate + : availableModeIds.has(candidate) + ? candidate + : "default"; + switch (modeId) { + case "yolo": + return "default"; + case "auto_edit": + case "accept-edits": + return chooseIfAvailable("accept-edits"); + case "auto": + return chooseIfAvailable("auto"); + case "plan": + return chooseIfAvailable("plan"); + default: + return availableModeIds === undefined || availableModeIds.has(modeId) ? modeId : "default"; + } +} + +/** Managed `agy_acp_server` advertises `yolo`, `auto_edit`, `default`, and `plan`, without `auto`. */ +export function antigravityManagedSessionMode( + modeId: string, + availableModeIds?: ReadonlySet, +): string { + if (modeId === "accept-edits") { + return availableModeIds === undefined || availableModeIds.has("auto_edit") + ? "auto_edit" + : "default"; + } + if (modeId === "auto") { + return availableModeIds?.has("auto") === true ? "auto" : "default"; + } + return availableModeIds === undefined || availableModeIds.has(modeId) ? modeId : "default"; } /** The runtime mode an Antigravity session mode grants; the inverse of `antigravityPermissionMode`. */ @@ -197,7 +240,10 @@ export function antigravityRuntimeModeForSessionMode(modeId: string): RuntimeMod switch (modeId) { case "yolo": return "full-access"; + case "auto": + return "auto"; case "auto_edit": + case "accept-edits": return "auto-accept-edits"; case "default": return "approval-required"; @@ -206,6 +252,29 @@ export function antigravityRuntimeModeForSessionMode(modeId: string): RuntimeMod } } +export function antigravityAdvertisedModeIds( + modeState: { readonly availableModes: ReadonlyArray<{ readonly id: string }> } | undefined, + configOptions: ReadonlyArray, +): ReadonlySet | undefined { + const ids = new Set(); + for (const mode of modeState?.availableModes ?? []) { + ids.add(mode.id); + } + const modeOption = configOptions.find( + (option) => option.id === "mode" || option.category === "mode", + ); + if (modeOption?.type === "select") { + for (const entry of modeOption.options) { + if ("value" in entry) { + ids.add(entry.value); + } else { + for (const choice of entry.options) ids.add(choice.value); + } + } + } + return ids.size > 0 ? ids : undefined; +} + export function antigravityModelOptions( configOptions: ReadonlyArray, ) { diff --git a/apps/server/src/provider/antigravityAuthSupport.test.ts b/apps/server/src/provider/antigravityAuthSupport.test.ts index 4476ccd3a2d1c..70e7bb97512ae 100644 --- a/apps/server/src/provider/antigravityAuthSupport.test.ts +++ b/apps/server/src/provider/antigravityAuthSupport.test.ts @@ -127,6 +127,31 @@ describe("Antigravity process environment", () => { ]); expect(spawn.env).not.toHaveProperty("ANTIGRAVITY_HARNESS_PATH"); expect(spawn.env).toMatchObject({ GEMINI_HOME: profile.geminiHome, PATH: "/usr/bin" }); + + const fullAccessCli = buildAntigravityAcpSpawnInput({ + installation: { executablePath: "/usr/bin/agy", harnessPath: null }, + profile, + cwd: "/project", + baseEnv: { PATH: "/usr/bin" }, + skipPermissions: true, + }); + expect(fullAccessCli.args).toEqual([ + "acp", + "--gemini-dir", + profile.geminiHome, + "--app-data-dir", + "antigravity-acp", + "--dangerously-skip-permissions", + ]); + + const fullAccessManaged = buildAntigravityAcpSpawnInput({ + installation: { executablePath: "/release/acp", harnessPath: "/release/harness" }, + profile, + cwd: "/project", + baseEnv: { PATH: "/usr/bin" }, + skipPermissions: true, + }); + expect(fullAccessManaged.args).toEqual(["--uid=", "--alsologtostderr"]); }); it("passes only the configured method's credential and keeps the GCP pair out of the environment", () => { diff --git a/apps/server/src/provider/antigravityAuthSupport.ts b/apps/server/src/provider/antigravityAuthSupport.ts index 47be6bf31ccae..22aa438c481bb 100644 --- a/apps/server/src/provider/antigravityAuthSupport.ts +++ b/apps/server/src/provider/antigravityAuthSupport.ts @@ -466,6 +466,7 @@ export function buildAntigravityAcpSpawnInput(input: { readonly baseEnv?: NodeJS.ProcessEnv; readonly auth?: AntigravityAuthConfig; readonly runtimeTempDirectory?: string; + readonly skipPermissions?: boolean; }): AcpSessionRuntime.AcpSpawnInput { return { command: input.installation.executablePath, @@ -481,6 +482,9 @@ export function buildAntigravityAcpSpawnInput(input: { "--app-data-dir", // The CLI joins this beneath gemini-dir, including when the value is absolute. "antigravity-acp", + // Background wakeups run while no ACP prompt stream is attached, so full-access + // must also skip native CLI tool confirmations instead of stalling in WAITING. + ...(input.skipPermissions === true ? ["--dangerously-skip-permissions"] : []), ] : [...(input.profile.platform === "linux" ? ["--uid="] : []), "--alsologtostderr"], cwd: input.cwd, diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index e2dc68fc13fdb..56ed03ffb6b0d 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -455,6 +455,14 @@ export interface AcpAdapterV2Flavor { readonly sessionModeForPolicy?: ( policy: ProviderAdapter.ProviderAdapterV2RuntimePolicy, ) => string | undefined; + /** + * True when switching between two runtime policies requires respawning the ACP process + * (for example when CLI startup flags gate full-access bypass). + */ + readonly requiresRuntimeRestartForPolicyChange?: ( + previous: ProviderAdapter.ProviderAdapterV2RuntimePolicy, + next: ProviderAdapter.ProviderAdapterV2RuntimePolicy, + ) => boolean; /** * Native select-option values to apply for a runtime policy (e.g. Kiro's * `autopilot`), set on every session configure. A value the session does @@ -2208,6 +2216,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const configuredRuntimeMode = yield* Ref.make< ProviderAdapter.ProviderAdapterV2RuntimePolicy["runtimeMode"] | null >(null); + const activeRuntimePolicy = + yield* Ref.make(null); const promptInstructionStates = yield* Ref.make(new Map()); const promptRuntimeInstructions = yield* Ref.make(new Map()); // Unique markers keep delayed prompt completions from clearing later compactions. @@ -2710,8 +2720,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( handleRuntimeTerminationAtGeneration(runtimeGeneration), ): AcpAdapterV2RuntimeInput => { return { - cwd: input.runtimePolicy.cwd ?? process.cwd(), - runtimePolicy: input.runtimePolicy, + cwd: latestRuntimePolicy.cwd ?? input.runtimePolicy.cwd ?? process.cwd(), + runtimePolicy: latestRuntimePolicy, mcpServers: mcpContext.servers, acpMcpServers: mcpContext.acpServers, httpMcpServers: mcpContext.httpServers, @@ -7582,6 +7592,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); const restartAcpRuntime = Effect.fnUntraced(function* (threadId: ThreadId | null) { + const previousGeneration = yield* Ref.get(runtimeCallbackGeneration); + yield* runtimeCallbackPermit.withPermit( + quarantineNativeTransportAtGeneration(previousGeneration), + ); + yield* advanceRuntimeCallbackGeneration; yield* spawnAcpRuntime(threadId); yield* wireAcpRuntimeHandlers(runtime, yield* Ref.get(runtimeCallbackGeneration)); }); @@ -7769,6 +7784,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* setActiveSessionSetup(candidate); yield* Ref.set(activeSelection, null); yield* Ref.set(activeInteractionMode, null); + yield* Ref.set(activeRuntimePolicy, null); yield* Ref.set(promptInstructionStates, new Map()); yield* Ref.set(promptRuntimeInstructions, new Map()); yield* Ref.set(compactionMarkers, new Map()); @@ -8176,6 +8192,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ); yield* Ref.set(activeSelection, input.modelSelection); yield* Ref.set(activeInteractionMode, input.runtimePolicy.interactionMode); + yield* Ref.set(activeRuntimePolicy, input.runtimePolicy); const createdAt = yield* DateTime.now; const providerSession: OrchestrationV2ProviderSession = { id: input.providerSessionId, @@ -8786,6 +8803,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(activeSessionSetup, null); yield* Ref.set(activeSelection, null); yield* Ref.set(activeInteractionMode, null); + yield* Ref.set(activeRuntimePolicy, null); // A failed prompt may have been dropped, so the fresh runtime sends T3's notes again. yield* Ref.set(promptInstructionStates, new Map()); yield* Ref.set(promptRuntimeInstructions, new Map()); @@ -8808,7 +8826,17 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } useProviderThreadIdentity(turnInput.providerThread); // load/resume can invoke client methods; install the incoming policy before activation. + const previousRuntimePolicy = yield* Ref.get(activeRuntimePolicy); latestRuntimePolicy = turnInput.runtimePolicy; + if ( + previousRuntimePolicy !== null && + flavor.requiresRuntimeRestartForPolicyChange?.( + previousRuntimePolicy, + turnInput.runtimePolicy, + ) === true + ) { + yield* Ref.set(runtimeRestartRequired, true); + } const requestedSessionId = yield* nativeThreadId(driver, turnInput.providerThread); const restartAfterInterrupt = yield* restartRuntimeAfterTeardownIfRequired( turnInput.threadId, @@ -8823,14 +8851,18 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* configureSession(activated, turnInput.modelSelection, turnInput.runtimePolicy); yield* Ref.set(activeSelection, turnInput.modelSelection); yield* Ref.set(activeInteractionMode, turnInput.runtimePolicy.interactionMode); + yield* Ref.set(activeRuntimePolicy, turnInput.runtimePolicy); } else { const configuredSelection = yield* Ref.get(activeSelection); const configuredInteractionMode = yield* Ref.get(activeInteractionMode); + const configuredRuntimePolicy = yield* Ref.get(activeRuntimePolicy); if ( configuredSelection === null || !modelSelectionsEqual(configuredSelection, turnInput.modelSelection) || configuredInteractionMode !== turnInput.runtimePolicy.interactionMode || - (yield* Ref.get(configuredRuntimeMode)) !== turnInput.runtimePolicy.runtimeMode + (yield* Ref.get(configuredRuntimeMode)) !== turnInput.runtimePolicy.runtimeMode || + configuredRuntimePolicy === null || + configuredRuntimePolicy.maxRuntimeMode !== turnInput.runtimePolicy.maxRuntimeMode ) { const currentSessionSetup = yield* Ref.get(activeSessionSetup); if (currentSessionSetup === null) { @@ -8846,6 +8878,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ); yield* Ref.set(activeSelection, turnInput.modelSelection); yield* Ref.set(activeInteractionMode, turnInput.runtimePolicy.interactionMode); + yield* Ref.set(activeRuntimePolicy, turnInput.runtimePolicy); } } // Checked after activation: a loaded session advertises its own commands. @@ -9551,9 +9584,23 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const restorePreviousItemIdentity = Effect.sync(() => { itemIdentityVersion = previousItemIdentityVersion; }); - const restartAfterInterrupt = yield* restartRuntimeAfterTeardownIfRequired( - threadInput.providerThread.appThreadId, - ).pipe(Effect.tapError(() => restorePreviousItemIdentity)); + const restartAfterInterrupt = yield* Effect.gen(function* () { + const nextRuntimePolicy = threadInput.runtimePolicy ?? latestRuntimePolicy; + const previousRuntimePolicy = yield* Ref.get(activeRuntimePolicy); + latestRuntimePolicy = nextRuntimePolicy; + if ( + previousRuntimePolicy !== null && + flavor.requiresRuntimeRestartForPolicyChange?.( + previousRuntimePolicy, + nextRuntimePolicy, + ) === true + ) { + yield* Ref.set(runtimeRestartRequired, true); + } + return yield* restartRuntimeAfterTeardownIfRequired( + threadInput.providerThread.appThreadId, + ); + }).pipe(Effect.tapError(() => restorePreviousItemIdentity)); if ((yield* Ref.get(activeSessionId)) !== sessionId || restartAfterInterrupt) { yield* Ref.set(snapshot, emptySnapshotState()); const activated = yield* activateSession( @@ -9564,10 +9611,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(loadingSessionId, null); yield* setActiveSessionSetup(activated); const nextSelection = threadInput.modelSelection ?? input.modelSelection; - const nextRuntimePolicy = threadInput.runtimePolicy ?? input.runtimePolicy; + const nextRuntimePolicy = threadInput.runtimePolicy ?? latestRuntimePolicy; yield* configureSession(activated, nextSelection, nextRuntimePolicy); yield* Ref.set(activeSelection, nextSelection); yield* Ref.set(activeInteractionMode, nextRuntimePolicy.interactionMode); + yield* Ref.set(activeRuntimePolicy, nextRuntimePolicy); } const now = yield* DateTime.now; return { From 8c355f60b8df2c6210cae51076fd877c76ba6ea8 Mon Sep 17 00:00:00 2001 From: SeongHoon Ryu <4997174+ryush00@users.noreply.github.com> Date: Mon, 16 Nov 2026 08:08:26 +0900 Subject: [PATCH 02/21] ci(fork): release nightlies, sign macOS builds, and sync with upstream daily Fork-only release and sync infrastructure: a desktop release workflow for macOS and Windows, nightly prereleases with synced upstream commits in the notes, a daily upstream sync, and macOS signing (Developer ID when secrets exist, otherwise ad hoc with a stable requirement) so builds update themselves. --- .agents/skills/fork-sync/SKILL.md | 69 ++++ .github/workflows/fork-release.yml | 393 +++++++++++++++++++++++ .github/workflows/fork-sync-upstream.yml | 122 +++++++ .github/workflows/release-desktop.yml | 22 +- AGENTS.md | 4 + FORK.md | 55 ++++ knip.jsonc | 1 + scripts/build-desktop-artifact.ts | 22 +- scripts/fork-entitlements.mac.plist | 18 ++ scripts/sign-macos-adhoc.ts | 20 ++ 10 files changed, 712 insertions(+), 14 deletions(-) create mode 100644 .agents/skills/fork-sync/SKILL.md create mode 100644 .github/workflows/fork-release.yml create mode 100644 .github/workflows/fork-sync-upstream.yml create mode 100644 FORK.md create mode 100644 scripts/fork-entitlements.mac.plist create mode 100644 scripts/sign-macos-adhoc.ts diff --git a/.agents/skills/fork-sync/SKILL.md b/.agents/skills/fork-sync/SKILL.md new file mode 100644 index 0000000000000..60ff8c5a00956 --- /dev/null +++ b/.agents/skills/fork-sync/SKILL.md @@ -0,0 +1,69 @@ +--- +name: fork-sync +description: Sync this fork (ryush00/t3code) with upstream pingdotgg/t3code - mirror main, rebase the fork branch, resolve conflicts, and publish a fork nightly. Use for "업스트림 동기화", "업스트림 추종", "포크 리베이스", "포크 릴리즈", an "Upstream sync failed" issue, or when adding or dropping a fork patch. +--- + +# 포크 동기화 + +방침과 이유는 [FORK.md](../../../FORK.md)에 있다. 여기는 손으로 할 때의 절차다. 평소에는 `Fork Sync Upstream` 워크플로우가 매일 같은 일을 한다. + +리모트 이름은 체크아웃마다 다르다. 먼저 `git remote -v`로 어느 것이 `pingdotgg/t3code`(아래 `UP`)이고 어느 것이 `ryush00/t3code`(아래 `FK`)인지 확인한다. + +## 1. 동기화 + +```sh +git fetch --no-tags UP main +git fetch FK main fork + +# main은 fast-forward만 한다. 거부되면 main에 누가 커밋한 것이니 멈추고 보고한다. +git push FK UP/main:refs/heads/main + +git switch -C fork-sync FK/fork +git rebase UP/main +``` + +`fork`를 이미 다른 worktree가 잡고 있을 수 있으므로 임시 브랜치 `fork-sync`에서 작업한다. + +## 2. 충돌 해결 + +- 업스트림이 같은 수정을 머지했으면 그 패치는 버린다: `git rebase --skip`. 업스트림 구현이 우리 것과 다르면 업스트림 쪽을 택한다. +- 그 밖에는 업스트림 변경을 살리고 패치를 그 위에 다시 맞춘다. 패치의 의도는 커밋 메시지와 연결된 업스트림 PR에서 확인한다. +- 충돌 표시를 지운 뒤에도 자동 병합된 구간이 옛 이름을 참조할 수 있다. 반드시 테스트로 확인한다. + +## 3. 검증 + +```sh +vp run check:changed +vp test run <패치가 건드린 테스트 파일> +``` + +`vp`가 PATH에 없으면 `node_modules/.bin`을 PATH에 추가한다. + +## 4. 푸시와 릴리즈 + +```sh +git push --force-with-lease=fork:FK/fork FK fork-sync:refs/heads/fork +gh workflow run fork-release.yml -R ryush00/t3code --ref fork +gh run list -R ryush00/t3code --workflow fork-release.yml -L 1 +``` + +`fork` 강제 푸시는 이 절차의 정상 동작이다. `main` 강제 푸시는 아니다. + +릴리즈가 끝나면 프리릴리즈로 올라왔는지, `nightly.yml`과 `nightly-mac.yml`이 자산에 있는지 확인한다. 둘이 없으면 자동 업데이트가 새 빌드를 찾지 못한다. + +## 패치 추가와 제거 + +- 추가: 업스트림 `main`에서 브랜치를 따 업스트림에 PR을 올리고, 같은 커밋을 `fork`에 체리픽한다. +- 제거: `git rebase -i`를 쓸 수 없는 환경이면 `git rebase --onto <커밋>^ <커밋> fork-sync`로 그 커밋만 뺀다. +- 포크 전용 변경은 업스트림에 없는 새 파일에 둔다. + +## 업스트림이 워크플로우를 추가했을 때 + +포크에서는 돌 수 없으므로 끈다. + +```sh +gh workflow list -R ryush00/t3code --all +gh workflow disable <이름 또는 ID> -R ryush00/t3code +``` + +`Fork Desktop Release`, `Fork Sync Upstream`, `Release desktop build`만 켜 둔다. diff --git a/.github/workflows/fork-release.yml b/.github/workflows/fork-release.yml new file mode 100644 index 0000000000000..a01dbe83d6067 --- /dev/null +++ b/.github/workflows/fork-release.yml @@ -0,0 +1,393 @@ +name: Fork Desktop Release + +# Fork-only. Publishes the `fork` branch as a nightly prerelease; see FORK.md. +on: + workflow_dispatch: + +concurrency: + group: fork-release + cancel-in-progress: false + +permissions: + actions: read + contents: read + +jobs: + prepare: + name: Prepare release metadata + if: github.repository != 'pingdotgg/t3code' + runs-on: ubuntu-24.04 + timeout-minutes: 5 + outputs: + version: ${{ steps.meta.outputs.version }} + tag: ${{ steps.meta.outputs.tag }} + release_name: ${{ steps.meta.outputs.release_name }} + release_channel: ${{ steps.meta.outputs.release_channel }} + is_prerelease: ${{ steps.meta.outputs.is_prerelease }} + ref: ${{ steps.meta.outputs.ref }} + clerk_publishable_key: ${{ steps.env_defaults.outputs.clerk_publishable_key }} + clerk_jwt_template: ${{ steps.env_defaults.outputs.clerk_jwt_template }} + clerk_cli_oauth_client_id: ${{ steps.env_defaults.outputs.clerk_cli_oauth_client_id }} + relay_url: ${{ steps.env_defaults.outputs.relay_url }} + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + sparse-checkout: | + /.env.example + /apps/desktop/package.json + sparse-checkout-cone-mode: false + + - id: meta + name: Resolve nightly version and tag + shell: bash + run: | + set -euo pipefail + # Same scheme as upstream nightlies: the next patch of the desktop + # package version, so a build sorts below the stable it previews. + current="$(sed -nE 's/^ "version": "([0-9]+\.[0-9]+\.[0-9]+).*$/\1/p' apps/desktop/package.json | head -n 1)" + if [[ ! "$current" =~ ^([0-9]+)\.([0-9]+)\.([0-9]+)$ ]]; then + echo "Could not read the desktop package version." >&2 + exit 1 + fi + base="${BASH_REMATCH[1]}.${BASH_REMATCH[2]}.$((BASH_REMATCH[3] + 1))" + version="${base}-nightly.$(date -u +%Y%m%d).${GITHUB_RUN_NUMBER}" + echo "version=$version" >> "$GITHUB_OUTPUT" + echo "tag=v$version" >> "$GITHUB_OUTPUT" + echo "release_name=T3 Code Fork Nightly $version (${GITHUB_SHA:0:12})" >> "$GITHUB_OUTPUT" + echo "release_channel=nightly" >> "$GITHUB_OUTPUT" + echo "ref=${GITHUB_SHA}" >> "$GITHUB_OUTPUT" + echo "is_prerelease=true" >> "$GITHUB_OUTPUT" + + - id: env_defaults + name: Read public T3 Connect defaults + shell: bash + run: | + set -euo pipefail + read_var() { + sed -nE "s/^$1=(.+)$/\1/p" .env.example | head -n 1 + } + echo "clerk_publishable_key=$(read_var T3CODE_CLERK_PUBLISHABLE_KEY)" >> "$GITHUB_OUTPUT" + echo "clerk_jwt_template=$(read_var T3CODE_CLERK_JWT_TEMPLATE)" >> "$GITHUB_OUTPUT" + echo "clerk_cli_oauth_client_id=$(read_var T3CODE_CLERK_CLI_OAUTH_CLIENT_ID)" >> "$GITHUB_OUTPUT" + echo "relay_url=$(read_var T3CODE_RELAY_URL)" >> "$GITHUB_OUTPUT" + + build_bundle: + name: Build JS bundle + needs: [prepare] + if: ${{ !cancelled() && needs.prepare.result == 'success' }} + runs-on: ubuntu-24.04 + timeout-minutes: 30 + env: + T3CODE_CLERK_PUBLISHABLE_KEY: ${{ needs.prepare.outputs.clerk_publishable_key }} + T3CODE_CLERK_JWT_TEMPLATE: ${{ needs.prepare.outputs.clerk_jwt_template }} + T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: ${{ needs.prepare.outputs.clerk_cli_oauth_client_id }} + T3CODE_RELAY_URL: ${{ needs.prepare.outputs.relay_url }} + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + ref: ${{ needs.prepare.outputs.ref }} + sparse-checkout: | + /* + !/.repos/ + sparse-checkout-cone-mode: false + + - name: Setup dependencies + uses: ./.github/actions/setup-ci-deps + with: + install-args: --filter=t3... --filter=@t3tools/web... --filter=@t3tools/desktop... --filter=@t3tools/scripts... + env: + pnpm_config_cache_dir: ${{ runner.temp }}/pnpm-metadata + + - name: Align package versions to release version + run: node scripts/update-release-package-versions.ts "${{ needs.prepare.outputs.version }}" + + - name: Build JS bundle + env: + T3CODE_TELEMETRY_CHANNEL: dev + run: vp run build:desktop:bundle + + - name: Upload JS bundle + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: js-bundle + path: | + apps/server/dist + apps/desktop/dist-electron + if-no-files-found: error + retention-days: 1 + + desktop_mac_arm64: + name: Desktop macOS arm64 + needs: [prepare, build_bundle] + if: ${{ !cancelled() && needs.prepare.result == 'success' && needs.build_bundle.result == 'success' }} + uses: ./.github/workflows/release-desktop.yml + secrets: inherit + with: + version: ${{ needs.prepare.outputs.version }} + ref: ${{ needs.prepare.outputs.ref }} + release_channel: ${{ needs.prepare.outputs.release_channel }} + relay_client_tracing: false + clerk_publishable_key: ${{ needs.prepare.outputs.clerk_publishable_key }} + clerk_jwt_template: ${{ needs.prepare.outputs.clerk_jwt_template }} + clerk_cli_oauth_client_id: ${{ needs.prepare.outputs.clerk_cli_oauth_client_id }} + relay_url: ${{ needs.prepare.outputs.relay_url }} + label: macOS arm64 + runner: macos-15 + platform: mac + target: dmg + arch: arm64 + rust_target: aarch64-apple-darwin + resource_key: darwin-arm64 + cli_archive: true + launch_check: true + save_pnpm_store: false + + desktop_mac_x64: + name: Desktop macOS x64 + needs: [prepare, build_bundle] + if: ${{ !cancelled() && needs.prepare.result == 'success' && needs.build_bundle.result == 'success' }} + uses: ./.github/workflows/release-desktop.yml + secrets: inherit + with: + version: ${{ needs.prepare.outputs.version }} + ref: ${{ needs.prepare.outputs.ref }} + release_channel: ${{ needs.prepare.outputs.release_channel }} + relay_client_tracing: false + clerk_publishable_key: ${{ needs.prepare.outputs.clerk_publishable_key }} + clerk_jwt_template: ${{ needs.prepare.outputs.clerk_jwt_template }} + clerk_cli_oauth_client_id: ${{ needs.prepare.outputs.clerk_cli_oauth_client_id }} + relay_url: ${{ needs.prepare.outputs.relay_url }} + label: macOS x64 + runner: macos-15 + platform: mac + target: dmg + arch: x64 + rust_target: x86_64-apple-darwin + resource_key: darwin-x64 + cli_archive: false + + desktop_linux_x64: + name: Desktop Linux x64 + needs: [prepare, build_bundle] + if: ${{ !cancelled() && needs.prepare.result == 'success' && needs.build_bundle.result == 'success' }} + uses: ./.github/workflows/release-desktop.yml + secrets: inherit + with: + version: ${{ needs.prepare.outputs.version }} + ref: ${{ needs.prepare.outputs.ref }} + release_channel: ${{ needs.prepare.outputs.release_channel }} + relay_client_tracing: false + clerk_publishable_key: ${{ needs.prepare.outputs.clerk_publishable_key }} + clerk_jwt_template: ${{ needs.prepare.outputs.clerk_jwt_template }} + clerk_cli_oauth_client_id: ${{ needs.prepare.outputs.clerk_cli_oauth_client_id }} + relay_url: ${{ needs.prepare.outputs.relay_url }} + label: Linux x64 + runner: ubuntu-24.04 + platform: linux + target: AppImage + arch: x64 + rust_target: x86_64-unknown-linux-gnu + resource_key: linux-x64 + cli_archive: true + launch_check: true + + desktop_win_x64: + name: Desktop Windows x64 + needs: [prepare, build_bundle] + if: ${{ !cancelled() && needs.prepare.result == 'success' && needs.build_bundle.result == 'success' }} + uses: ./.github/workflows/release-desktop.yml + secrets: inherit + with: + version: ${{ needs.prepare.outputs.version }} + ref: ${{ needs.prepare.outputs.ref }} + release_channel: ${{ needs.prepare.outputs.release_channel }} + relay_client_tracing: false + clerk_publishable_key: ${{ needs.prepare.outputs.clerk_publishable_key }} + clerk_jwt_template: ${{ needs.prepare.outputs.clerk_jwt_template }} + clerk_cli_oauth_client_id: ${{ needs.prepare.outputs.clerk_cli_oauth_client_id }} + relay_url: ${{ needs.prepare.outputs.relay_url }} + label: Windows x64 + runner: ubuntu-24.04 + verify_runner: windows-2025 + platform: win + target: nsis + arch: x64 + rust_target: x86_64-pc-windows-msvc + resource_key: win32-x64 + cli_archive: true + + publish: + name: Publish GitHub Release + needs: [prepare, desktop_mac_arm64, desktop_mac_x64, desktop_linux_x64, desktop_win_x64] + if: ${{ !failure() && !cancelled() && needs.prepare.result == 'success' && needs.desktop_mac_arm64.result == 'success' && needs.desktop_mac_x64.result == 'success' && needs.desktop_linux_x64.result == 'success' && needs.desktop_win_x64.result == 'success' }} + runs-on: ubuntu-24.04 + timeout-minutes: 20 + permissions: + contents: write + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + ref: ${{ needs.prepare.outputs.ref }} + sparse-checkout: | + /* + !/.repos/ + sparse-checkout-cone-mode: false + + - name: Setup dependencies + uses: ./.github/actions/setup-ci-deps + with: + install-args: --filter=@t3tools/scripts... + + - name: Download all desktop artifacts + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: desktop-* + merge-multiple: true + path: release-assets + + - name: Download all CLI archives + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: cli-* + merge-multiple: true + path: release-assets + + - name: Write CLI archive checksums + shell: bash + run: | + set -euo pipefail + cd release-assets + shopt -s nullglob + archives=(t3-*.tar.gz t3-*.zip) + if [[ ${#archives[@]} -eq 0 ]]; then + echo "No CLI archives were produced." >&2 + exit 1 + fi + sha256sum "${archives[@]}" > SHA256SUMS + cat SHA256SUMS + + - name: Normalize desktop updater manifests + shell: bash + run: | + set -euo pipefail + shopt -s nullglob + rm -f release-assets/builder-debug.yml + for secondary in release-assets/*-mac-x64.yml; do + primary="${secondary%-x64.yml}.yml" + if [[ -f "$primary" ]]; then + node scripts/merge-update-manifests.ts --platform mac "$primary" "$secondary" + rm -f "$secondary" + fi + done + for win_manifest in release-assets/*-win-x64.yml; do + mv "$win_manifest" "${win_manifest%-win-x64.yml}.yml" + done + + - name: Write release notes + shell: bash + env: + GH_TOKEN: ${{ github.token }} + RELEASE_SHA: ${{ needs.prepare.outputs.ref }} + RELEASE_TAG: ${{ needs.prepare.outputs.tag }} + UPSTREAM_REPO: pingdotgg/t3code + run: | + set -euo pipefail + gh api "repos/${GITHUB_REPOSITORY}/compare/main...${RELEASE_SHA}" > "$RUNNER_TEMP/fork-compare.json" + curr_base="$(jq -r '.merge_base_commit.sha' "$RUNNER_TEMP/fork-compare.json")" + + prev_tag="$(gh api "repos/${GITHUB_REPOSITORY}/releases?per_page=20" \ + --jq '[.[] | select(.draft == false and .tag_name != env.RELEASE_TAG and (.tag_name | contains("-nightly.")))][0].tag_name // empty' || true)" + prev_base="" + if [[ -n "$prev_tag" ]]; then + prev_base="$(gh api "repos/${GITHUB_REPOSITORY}/compare/main...${prev_tag}" \ + --jq '.merge_base_commit.sha // empty' 2>/dev/null || true)" + fi + + { + echo "Nightly build of the \`fork\` branch (upstream \`${UPSTREAM_REPO}\` @ \`${curr_base:0:9}\`)." + echo + echo "### Fork patches" + if [[ "$(jq '.commits | length' "$RUNNER_TEMP/fork-compare.json")" -eq 0 ]]; then + echo "- None." + else + jq -r --arg up "$UPSTREAM_REPO" ' + .commits[] + | (.commit.message | split("\n")[0]) as $subject + | (if (.commit.message | contains("https://github.com/" + $up + "/pull/")) + then ($subject | gsub("\\(#(?[0-9]+)\\)"; "(" + $up + "#\(.n))")) + else $subject + end) as $formatted + | "- " + $formatted + " (" + .sha[0:9] + ")" + ' "$RUNNER_TEMP/fork-compare.json" + fi + echo + if [[ -z "$prev_tag" || -z "$prev_base" ]]; then + echo "### Upstream changes" + echo "- Initial upstream base (\`${curr_base:0:9}\`)." + elif [[ "$prev_base" == "$curr_base" ]]; then + echo "### Upstream changes (since ${prev_tag})" + echo "- No new upstream commits (\`${curr_base:0:9}\`)." + else + echo "### Upstream changes (since ${prev_tag})" + if gh api "repos/${GITHUB_REPOSITORY}/compare/${prev_base}...${curr_base}" > "$RUNNER_TEMP/upstream-compare.json" 2>/dev/null \ + && jq -e '.status == "ahead" and (.commits | length) > 0' "$RUNNER_TEMP/upstream-compare.json" >/dev/null; then + jq -r --arg up "$UPSTREAM_REPO" ' + .commits[] + | (.commit.message | split("\n")[0] | gsub("\\(#(?[0-9]+)\\)"; "(" + $up + "#\(.n))")) as $formatted + | "- " + $formatted + " (" + .sha[0:9] + ")" + ' "$RUNNER_TEMP/upstream-compare.json" + total="$(jq -r '.total_commits' "$RUNNER_TEMP/upstream-compare.json")" + shown="$(jq -r '.commits | length' "$RUNNER_TEMP/upstream-compare.json")" + if [[ "$total" -gt "$shown" ]]; then + echo "- ...and $((total - shown)) more commits (https://github.com/${UPSTREAM_REPO}/compare/${prev_base:0:12}...${curr_base:0:12})." + fi + else + echo "- https://github.com/${UPSTREAM_REPO}/compare/${prev_base:0:12}...${curr_base:0:12}" + fi + fi + echo + echo "### Install" + echo "- Installs on the Nightly update channel update themselves." + echo "- If a macOS update fails on a code signature check, the installed build was signed differently; install this \`.dmg\` over it once." + } > release-notes.md + cat release-notes.md + cat release-notes.md >> "$GITHUB_STEP_SUMMARY" + + - name: Verify required Windows and macOS release assets + shell: bash + run: | + set -euo pipefail + shopt -s nullglob + dmgs=(release-assets/*.dmg) + exes=(release-assets/*.exe) + zips=(release-assets/*.zip) + ls -lh release-assets/ + if [[ ${#dmgs[@]} -lt 2 ]]; then + echo "Expected both arm64 and x64 macOS DMGs, found: ${dmgs[*]:-none}" >&2 + exit 1 + fi + if [[ ${#exes[@]} -lt 1 ]]; then + echo "Expected Windows NSIS installer (.exe), found none" >&2 + exit 1 + fi + if [[ ${#zips[@]} -lt 2 || ! -f release-assets/SHA256SUMS ]]; then + echo "Expected macOS/Windows ZIP archives and SHA256SUMS" >&2 + exit 1 + fi + + - name: Publish GitHub Release + uses: softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3.0.4 + with: + tag_name: ${{ needs.prepare.outputs.tag }} + target_commitish: ${{ needs.prepare.outputs.ref }} + name: ${{ needs.prepare.outputs.release_name }} + body_path: release-notes.md + prerelease: ${{ needs.prepare.outputs.is_prerelease }} + draft: false + make_latest: ${{ needs.prepare.outputs.is_prerelease == 'false' }} + files: release-assets/* + fail_on_unmatched_files: true + token: ${{ github.token }} diff --git a/.github/workflows/fork-sync-upstream.yml b/.github/workflows/fork-sync-upstream.yml new file mode 100644 index 0000000000000..04ff3136750ee --- /dev/null +++ b/.github/workflows/fork-sync-upstream.yml @@ -0,0 +1,122 @@ +name: Fork Sync Upstream + +# Fork-only. Keeps `main` a mirror of upstream and rebases `fork` onto it; see FORK.md. +on: + schedule: + - cron: "17 19 * * *" + workflow_dispatch: + inputs: + release: + description: "Publish a nightly when the fork branch moved" + required: false + default: true + type: boolean + +concurrency: + group: fork-sync-upstream + cancel-in-progress: false + +permissions: + contents: read + +env: + UPSTREAM_REPOSITORY: pingdotgg/t3code + +jobs: + sync: + name: Mirror main and rebase fork + if: github.repository != 'pingdotgg/t3code' + runs-on: ubuntu-24.04 + timeout-minutes: 45 + permissions: + actions: write + contents: write + issues: write + steps: + # GITHUB_TOKEN may not push commits that touch .github/workflows, and + # upstream changes those often, so both pushes go through a deploy key. + - name: Require the deploy key + env: + FORK_SYNC_DEPLOY_KEY: ${{ secrets.FORK_SYNC_DEPLOY_KEY }} + run: | + if [[ -z "$FORK_SYNC_DEPLOY_KEY" ]]; then + echo "Set the FORK_SYNC_DEPLOY_KEY secret to a write deploy key. See FORK.md." >&2 + exit 1 + fi + + - name: Checkout fork branch + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + ref: fork + fetch-depth: 0 + ssh-key: ${{ secrets.FORK_SYNC_DEPLOY_KEY }} + + - id: sync + name: Mirror main and rebase fork + shell: bash + run: | + set -euo pipefail + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git remote add upstream "https://github.com/${UPSTREAM_REPOSITORY}.git" + git fetch --no-tags upstream main + git fetch --no-tags origin main + + if ! git merge-base --is-ancestor origin/main upstream/main; then + echo "reason=main has commits that upstream does not. It must stay a pure mirror." >> "$GITHUB_OUTPUT" + exit 1 + fi + git push origin upstream/main:refs/heads/main + + if git merge-base --is-ancestor upstream/main HEAD; then + echo "moved=false" >> "$GITHUB_OUTPUT" + exit 0 + fi + if ! git rebase upstream/main; then + { + echo "reason<> "$GITHUB_OUTPUT" + git rebase --abort + exit 1 + fi + echo "moved=true" >> "$GITHUB_OUTPUT" + + - name: Setup dependencies + if: steps.sync.outputs.moved == 'true' + uses: ./.github/actions/setup-ci-deps + + - name: Typecheck the rebased branch + if: steps.sync.outputs.moved == 'true' + run: vp run typecheck + + - name: Push fork branch + if: steps.sync.outputs.moved == 'true' + run: git push --force-with-lease=fork:origin/fork origin HEAD:refs/heads/fork + + - name: Publish a nightly + if: steps.sync.outputs.moved == 'true' && (github.event_name == 'schedule' || inputs.release) + env: + GH_TOKEN: ${{ github.token }} + run: gh workflow run fork-release.yml --ref fork + + - name: Report a failed sync + if: failure() + env: + GH_TOKEN: ${{ github.token }} + REASON: ${{ steps.sync.outputs.reason }} + run: | + set -euo pipefail + title="Upstream sync failed" + body="$(printf '%s\n\nRun: %s/%s/actions/runs/%s\n\nFollow the fork-sync skill to rebase by hand.' \ + "${REASON:-The sync job failed before or after the rebase; see the run log.}" \ + "$GITHUB_SERVER_URL" "$GITHUB_REPOSITORY" "$GITHUB_RUN_ID")" + existing="$(gh issue list --repo "$GITHUB_REPOSITORY" --state open --search "\"$title\" in:title" --json number --jq '.[0].number // empty')" + if [[ -n "$existing" ]]; then + gh issue comment "$existing" --repo "$GITHUB_REPOSITORY" --body "$body" + else + gh issue create --repo "$GITHUB_REPOSITORY" --title "$title" --body "$body" + fi diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.yml index 4252cb46e7a05..c60fb5364b8a9 100644 --- a/.github/workflows/release-desktop.yml +++ b/.github/workflows/release-desktop.yml @@ -627,20 +627,22 @@ jobs: if [[ "${{ inputs.platform }}" == "mac" ]]; then if has_all "$CSC_LINK" "$CSC_KEY_PASSWORD" "$APPLE_API_KEY" "$APPLE_API_KEY_ID" "$APPLE_API_ISSUER"; then - if ! has_all "$APPLE_TEAM_ID" "$MACOS_PROVISIONING_PROFILE"; then - echo "macOS signing is configured, but APPLE_TEAM_ID or MACOS_PROVISIONING_PROFILE is missing." >&2 - exit 1 - fi - key_path="$RUNNER_TEMP/AuthKey_${APPLE_API_KEY_ID}.p8" printf '%s' "$APPLE_API_KEY" > "$key_path" export APPLE_API_KEY="$key_path" - profile_path="$RUNNER_TEMP/t3code.provisionprofile" - printf '%s' "$MACOS_PROVISIONING_PROFILE" | base64 -D > "$profile_path" - security cms -D -i "$profile_path" >/dev/null - export T3CODE_APPLE_TEAM_ID="$APPLE_TEAM_ID" - export T3CODE_MACOS_PROVISIONING_PROFILE="$profile_path" + # Fork: no profile means signing without in-app browser passkeys. + if [[ -n "$MACOS_PROVISIONING_PROFILE" ]]; then + if [[ -z "$APPLE_TEAM_ID" ]]; then + echo "MACOS_PROVISIONING_PROFILE is set, but APPLE_TEAM_ID is missing." >&2 + exit 1 + fi + profile_path="$RUNNER_TEMP/t3code.provisionprofile" + printf '%s' "$MACOS_PROVISIONING_PROFILE" | base64 -D > "$profile_path" + security cms -D -i "$profile_path" >/dev/null + export T3CODE_APPLE_TEAM_ID="$APPLE_TEAM_ID" + export T3CODE_MACOS_PROVISIONING_PROFILE="$profile_path" + fi echo "macOS signing enabled." args+=(--signed) diff --git a/AGENTS.md b/AGENTS.md index 6d788cd6c9e20..9df999a7350e7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,6 +4,10 @@ T3 Code is a minimal GUI for coding agents. A Node WebSocket server wraps provid You can think of T3 Code as an open source "bring-your-own-subscription" alternative to apps like Claude Desktop, Codex App, Cursor Glass and Conductor. +## This checkout is a fork + +`ryush00/t3code` tracks upstream `pingdotgg/t3code`. `main` is a pure mirror of upstream; never commit to it. Work lands on `fork`, the default branch, as a thin patch stack rebased onto `main`, and ships as nightly prereleases. Read [FORK.md](FORK.md) before touching branches, releases, or workflows, and use the `fork-sync` skill to sync. + ## What makes T3 Code special? We have over 500,000 users who love T3 Code. It's important we maintain the things they love as we continue to iterate on the product. Here's a brief list of the things we can never compromise on. diff --git a/FORK.md b/FORK.md new file mode 100644 index 0000000000000..0db1f66edb8e7 --- /dev/null +++ b/FORK.md @@ -0,0 +1,55 @@ +# 포크 운영 방침 + +이 저장소(`ryush00/t3code`)는 [`pingdotgg/t3code`](https://github.com/pingdotgg/t3code)의 포크이며, **업스트림 `main`을 계속 추종**한다. 자체 기능을 키우는 저장소가 아니라, 업스트림에 아직 머지되지 않은 수정을 먼저 얹어 쓰는 저장소다. + +동기화 절차는 [fork-sync 스킬](.agents/skills/fork-sync/SKILL.md)에 있다. + +## 브랜치 + +| 브랜치 | 역할 | +| ------ | ---------------------------------------------------------------------------------------- | +| `main` | 업스트림 `main`의 순정 미러. fast-forward로만 움직인다. **직접 커밋하지 않는다.** | +| `fork` | 기본 브랜치. 항상 `main` 위에 포크 패치만 리베이스해 얹는다. 리베이스마다 강제 푸시된다. | + +현재 얹혀 있는 패치는 `git log main..fork`가 정답이다. 목록을 문서에 따로 적지 않는다. + +## 패치 규칙 + +- 패치는 업스트림에도 PR로 올린다. 업스트림이 머지하면 다음 리베이스에서 커밋이 비어 자동으로 사라진다. +- 업스트림에 보낼 PR 브랜치는 `fork`가 아니라 `main`에서 딴다. +- 포크에만 필요한 것은 업스트림에 없는 새 파일로 만든다(`fork-` 접두사 워크플로우, 이 문서, 스킬). 업스트림 파일을 고치면 리베이스 충돌이 생긴다. +- 업스트림 파일을 꼭 고쳐야 하면 한 커밋에 모으고 변경 줄 수를 최소로 한다. + +## 릴리즈 + +포크는 **나이틀리 채널로만** 릴리즈한다. 업스트림 `main`을 따라가므로 내용물이 업스트림 나이틀리와 같기 때문이다. + +- 버전은 업스트림과 같은 형식 `X.Y.Z-nightly.YYYYMMDD.N`이다. `X.Y.Z`는 데스크톱 패키지 버전의 다음 패치, `N`은 릴리즈 워크플로우 실행 번호다. +- [fork-release.yml](.github/workflows/fork-release.yml)이 `fork` 브랜치를 빌드해 GitHub 프리릴리즈로 올린다. 태그를 손으로 만들지 않는다. +- 앱 이름은 "T3 Code (Nightly)"지만 앱 ID와 데이터 폴더는 정식 빌드와 같다. 공식 빌드와 동시에 띄우지 않는다. +- 자동 업데이트 피드는 빌드한 저장소(`GITHUB_REPOSITORY`)를 가리키므로 포크 릴리즈만 따라간다. 모든 플랫폼이 Nightly 채널에서 자동 업데이트된다. +- macOS 빌드는 Apple 시크릿(`CSC_LINK`, `CSC_KEY_PASSWORD`, `APPLE_API_KEY`, `APPLE_API_KEY_ID`, `APPLE_API_ISSUER`)이 모두 있으면 포크 소유자의 Developer ID로 서명하고 공증한다. 번들 ID `com.t3tools.t3code`는 업스트림 팀 소유라 프로비저닝 프로파일을 받을 수 없으므로 `MACOS_PROVISIONING_PROFILE` 없이 서명하고, 앱 내 브라우저의 패스키는 빠진다. 이때의 권한은 [fork-entitlements.mac.plist](scripts/fork-entitlements.mac.plist)에 있다. +- 시크릿이 빠지면 임시(ad hoc) 서명으로 떨어진다. 임시 서명의 기본 지정 요구사항은 빌드마다 다른 cdhash라서 Squirrel.Mac이 다음 빌드를 거부하므로, [sign-macos-adhoc.ts](scripts/sign-macos-adhoc.ts)가 요구사항을 번들 ID로 고정한다. 이 빌드는 처음 열 때 `xattr -cr "/Applications/T3 Code (Nightly).app"`이 필요하다. +- 서명 주체가 바뀌면(임시 서명에서 Developer ID로, 또는 인증서 교체) 그 경계의 업데이트는 거부된다. 새 `.dmg`를 한 번 직접 설치한다. +- `t3` CLI의 자체 업데이트는 여전히 업스트림 릴리즈를 본다. + +## 자동 동기화 + +[fork-sync-upstream.yml](.github/workflows/fork-sync-upstream.yml)이 매일 19:17 UTC(한국 04:17)에 돈다. + +1. `main`을 업스트림 `main`으로 fast-forward한다. +2. `fork`를 새 `main` 위로 리베이스하고 타입체크한다. +3. `fork`가 움직였으면 강제 푸시하고 나이틀리 릴리즈를 시작한다. +4. 충돌이나 실패가 나면 아무것도 덮어쓰지 않고 "Upstream sync failed" 이슈를 남긴다. 이때는 스킬 절차대로 손으로 리베이스한다. + +이 워크플로우는 쓰기 권한 deploy key("Fork Sync Upstream workflow")로 푸시하며, 그 개인 키가 `FORK_SYNC_DEPLOY_KEY` 시크릿에 들어 있다. 업스트림이 워크플로우 파일을 자주 바꾸는데, 기본 `GITHUB_TOKEN`은 그런 커밋을 푸시할 수 없다. 키를 바꿀 때는 새 키 쌍을 만들어 deploy key와 시크릿을 함께 교체한다. + +## 저장소 설정 + +- 기본 브랜치는 `fork`다. 예약 워크플로우는 기본 브랜치의 파일로만 돈다. +- 업스트림 워크플로우는 포크에서 모두 꺼 둔다. 전용 러너와 시크릿을 요구해 포크에서는 대기 상태로 남는다. 켜 두는 것은 `Fork Desktop Release`, `Fork Sync Upstream`, 그리고 릴리즈가 호출하는 `Release desktop build`뿐이다. 업스트림이 워크플로우를 새로 추가하면 그것도 끈다. +- Issues를 켜 둔다. 동기화 실패 알림이 이슈로 온다. + +## 로컬 리모트 이름 + +이 체크아웃에서는 `origin`이 업스트림(`pingdotgg/t3code`)이고 `fork`가 이 저장소다. 푸시 전에 `git remote -v`로 확인한다. diff --git a/knip.jsonc b/knip.jsonc index 748d6864e2217..bd6208c6a2a74 100644 --- a/knip.jsonc +++ b/knip.jsonc @@ -38,6 +38,7 @@ "scenarios/*.ts", "setup-worktree.ts", "sign-macos.ts", + "sign-macos-adhoc.ts", "prepare-server-compile-cache.cjs", "smoke-desktop-app.ts", "verify-windows-desktop-artifact.ts", diff --git a/scripts/build-desktop-artifact.ts b/scripts/build-desktop-artifact.ts index 9d34e2412b327..2d60cdb85fd20 100644 --- a/scripts/build-desktop-artifact.ts +++ b/scripts/build-desktop-artifact.ts @@ -2879,13 +2879,23 @@ export const createBuildConfig = Effect.fn("createBuildConfig")(function* ( role: "Viewer", }, ], - ...(signed ? { sign: path.join(repoRoot, "scripts/sign-macos.ts") } : {}), + // An unsigned bundle has no seal, which Gatekeeper reports as "damaged" once quarantined. + // Ad hoc has no team, so the hardened runtime's library validation would refuse Electron. + ...(signed + ? { sign: path.join(repoRoot, "scripts/sign-macos.ts") } + : { + identity: "-", + hardenedRuntime: false, + sign: path.join(repoRoot, "scripts/sign-macos-adhoc.ts"), + }), ...(macPasskeySigning ? { entitlements: macPasskeySigning.entitlementsPath, provisioningProfile: macPasskeySigning.provisioningProfilePath, } - : {}), + : signed + ? { entitlements: path.join(repoRoot, "scripts/fork-entitlements.mac.plist") } + : {}), }; } @@ -3856,10 +3866,14 @@ const buildDesktopArtifactUnlocked = Effect.fn("buildDesktopArtifactUnlocked")(f const stageProdResourcesDir = path.join(stageAppDir, "apps/desktop/prod-resources"); yield* fs.copy(stageResourcesDir, stageProdResourcesDir); + const repoEnv = loadRepoEnv({ repoRoot }); + // A fork cannot get a profile for upstream's bundle ID, so it signs without passkeys. const configuredMacPasskeySigning = - options.platform === "mac" && options.signed + options.platform === "mac" && + options.signed && + repoEnv.T3CODE_MACOS_PROVISIONING_PROFILE?.trim() ? yield* Effect.try({ - try: () => resolveMacPasskeySigningConfiguration(loadRepoEnv({ repoRoot })), + try: () => resolveMacPasskeySigningConfiguration(repoEnv), catch: MacPasskeySigningConfigurationResolutionError.fromCause, }) : undefined; diff --git a/scripts/fork-entitlements.mac.plist b/scripts/fork-entitlements.mac.plist new file mode 100644 index 0000000000000..2344cfb3583ae --- /dev/null +++ b/scripts/fork-entitlements.mac.plist @@ -0,0 +1,18 @@ + + + + + + com.apple.security.cs.allow-jit + + com.apple.security.cs.allow-unsigned-executable-memory + + com.apple.security.cs.disable-library-validation + + com.apple.security.device.camera + + com.apple.security.device.audio-input + + + diff --git a/scripts/sign-macos-adhoc.ts b/scripts/sign-macos-adhoc.ts new file mode 100644 index 0000000000000..b6ef7973ee890 --- /dev/null +++ b/scripts/sign-macos-adhoc.ts @@ -0,0 +1,20 @@ +import { sign as signApplication, type SignOptions } from "@electron/osx-sign"; + +interface Packager { + readonly appInfo: { readonly id: string }; +} + +// An ad hoc signature's default designated requirement is the build's own cdhash, which +// no later build satisfies, so Squirrel.Mac rejects every update. Pin it to the bundle ID. +export default async function sign(options: SignOptions, packager: Packager): Promise { + const requirements = `=designated => identifier "${packager.appInfo.id}"`; + await signApplication({ + ...options, + identity: "-", + identityValidation: false, + optionsForFile: (filePath, context) => ({ + ...options.optionsForFile?.(filePath, context), + ...(filePath === options.app ? { requirements } : {}), + }), + }); +} From 08ed731d7679c95d7ce34e5aefe586fa9fd2b39d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 15 Nov 2026 08:57:24 +0000 Subject: [PATCH 03/21] fix(server): Antigravity ask_question asks each choice once with its free-form answer agy acp names the free-text companion of an ask_question choice qN_other and puts the question in the choice title. The generic elicitation parser only folds OMP's qN__other and reads the question from the description, so every choice became two steps. Add an Antigravity extractElicitationForm, as the OMP, Droid and OpenCode flavors have, that asks qN once with custom input and sends typed text back as qN_other. Co-Authored-By: Claude Opus 5.5 --- .../Adapters/AntigravityAdapterV2.test.ts | 166 ++++++++++++++++++ .../Adapters/AntigravityAdapterV2.ts | 2 + .../src/provider/acp/AntigravityProtocol.ts | 80 ++++++++- 3 files changed, 244 insertions(+), 4 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 5fc1d2ecba4e8..0633123672b1e 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -2025,3 +2025,169 @@ describe("AntigravityAdapterV2 full-access restart", () => { }).pipe(Effect.provide(layerSession)), ); }); + +describe("AntigravityAdapterV2 questions", () => { + it.live("asks each ask_question choice once, with its `_other` field as the custom answer", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const crypto = yield* SecureRandom.SecureRandom; + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + const directory = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-antigravity-ask-question-", + }); + const responseLog = path.join(directory, "responses.jsonl"); + // The form `agy acp` 1.5.9 sends for a two-question ask_question call. + const ask = (question: string, options: ReadonlyArray) => ({ + type: "string", + title: question, + oneOf: options.map((title, index) => ({ const: String(index + 1), title })), + }); + const other = (question: string) => ({ + type: "string", + title: "Other", + description: `Optional free-form answer to: ${question}`, + }); + const research = "Should competitive research run before implementation?"; + const roles = "Which workspace roles may read conversations over MCP?"; + const requestedSchema = { + type: "object", + properties: { + q1: ask(research, ["(Recommended) Skip research", "Run research first"]), + q1_other: other(research), + q2: ask(roles, ["(Recommended) Owner and admin only", "Include support agents"]), + q2_other: other(roles), + }, + }; + const instanceId = ProviderInstanceId.make("antigravity-ask-question-test"); + const threadId = ThreadId.make("thread-antigravity-ask-question"); + const adapter = yield* makeAntigravityAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + makeRuntime: (input) => + makeAntigravityAcpRuntime({ + ...input, + childProcessSpawner, + spawn: { + command: process.execPath, + args: [mockAgentPath], + cwd: input.cwd, + env: { + T3_ACP_ANTIGRAVITY: "1", + T3_ACP_EMIT_ELICITATION: "1", + T3_ACP_ELICITATION_SCHEMA: JSON.stringify(requestedSchema), + T3_ACP_ELICITATION_RESPONSE_LOG_PATH: responseLog, + }, + }, + }).pipe(Effect.provideService(SecureRandom.SecureRandom, crypto)), + withProcess: (_stop, task) => task, + defaultModel: Effect.undefined, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "gemini-test-low" } as const; + const session = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-antigravity-ask-question"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + yield* session.startTurn({ + appThread: { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: ProjectId.make("project-antigravity-ask-question"), + title: "Antigravity ask_question", + providerInstanceId: instanceId, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: process.cwd(), + activeProviderThreadId: providerThread.id, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + threadId, + runId: RunId.make("run-antigravity-ask-question"), + runOrdinal: 1, + providerTurnOrdinal: 1, + attemptId: RunAttemptId.make("attempt-antigravity-ask-question"), + rootNodeId: NodeId.make("node-antigravity-ask-question"), + providerThread, + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make("message-antigravity-ask-question"), + text: "ask me two questions", + attachments: [], + }, + modelSelection, + runtimePolicy, + }); + const request = yield* session.events.pipe( + Stream.filter( + (event) => + event.type === "turn.terminal" || + (event.type === "turn_item.updated" && event.turnItem.type === "user_input_request"), + ), + Stream.runHead, + ); + const item = + request._tag === "Some" && + request.value.type === "turn_item.updated" && + request.value.turnItem.type === "user_input_request" + ? request.value.turnItem + : undefined; + assert(item !== undefined, "the ask_question form reaches the question card"); + + assert.deepEqual( + item.questions.map((question) => [ + question.id, + question.question, + question.allowCustomAnswer !== false, + ]), + [ + ["q1", research, true], + ["q2", roles, true], + ], + ); + + yield* session.respondToRuntimeRequest({ + requestId: item.requestId, + answers: { q1: "1", q2: "Only the support leads" }, + }); + yield* session.events.pipe( + Stream.filter((event) => event.type === "turn.terminal"), + Stream.runHead, + ); + const responses = (yield* fileSystem.readFileString(responseLog)) + .split("\n") + .filter((line) => line.length > 0) + .map((line) => JSON.parse(line)); + assert.deepEqual(responses, [ + { action: "accept", content: { q1: "1", q2_other: "Only the support leads" } }, + ]); + }).pipe(Effect.provide(layerSession)), + ); +}); diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index d6ef49f8289d0..e13acfecee4e3 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -40,6 +40,7 @@ import { antigravityCommandOutlivesPrompt, antigravitySubagentOutput, classifyAntigravitySubagentToolCall, + extractAntigravityElicitationForm, extractAntigravityUserInputQuestion, makeAntigravityReadRepair, makeAntigravityUserInputResponse, @@ -290,6 +291,7 @@ export function makeAntigravityAcpAdapterFlavor( respond: (answers) => makeAntigravityUserInputResponse(request, answers), }; }, + extractElicitationForm: extractAntigravityElicitationForm, normalizeToolCall: normalizeAntigravityToolCall, extractSubagentUpdate: extractAntigravitySubagentUpdate, supportsImagePrompts: true, diff --git a/apps/server/src/provider/acp/AntigravityProtocol.ts b/apps/server/src/provider/acp/AntigravityProtocol.ts index ce4daef806bab..06d2e0e637bed 100644 --- a/apps/server/src/provider/acp/AntigravityProtocol.ts +++ b/apps/server/src/provider/acp/AntigravityProtocol.ts @@ -1,7 +1,9 @@ -import type { - ProviderApprovalOption, - ProviderUserInputAnswers, - UserInputQuestion, +import { + type OrchestrationV2UserInputQuestion, + type ProviderApprovalOption, + type ProviderUserInputAnswers, + TrimmedNonEmptyString, + type UserInputQuestion, } from "@t3tools/contracts"; import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview"; import * as Option from "effect/Option"; @@ -10,6 +12,7 @@ import * as Schema from "effect/Schema"; import type * as EffectAcpSchema from "effect-acp/compat"; import * as AcpWireSchema from "effect-acp/schema-v1"; +import type { AcpAdapterV2Flavor } from "@t3tools/provider-acp/server/adapter"; import type { AcpToolCallState } from "@t3tools/provider-acp/server/runtimeModel"; import { @@ -173,6 +176,75 @@ export function makeAntigravityUserInputResponse( return option ? { outcome: { outcome: "selected", optionId: option.optionId } } : undefined; } +const isElicitationForm = Schema.is( + Schema.Struct({ properties: Schema.Record(Schema.String, Schema.Unknown) }), +); +const isElicitationQuestion = Schema.is( + Schema.Struct({ + type: Schema.Literal("string"), + title: TrimmedNonEmptyString, + oneOf: Schema.NonEmptyArray( + Schema.Struct({ + const: TrimmedNonEmptyString, + title: TrimmedNonEmptyString, + description: Schema.optional(Schema.String), + }), + ), + }), +); +const isElicitationText = Schema.is( + Schema.Struct({ + type: Schema.Literal("string"), + oneOf: Schema.optional(Schema.Undefined), + enum: Schema.optional(Schema.Undefined), + }), +); + +/** ask_question sends each choice as qN titled with the question, plus a qN_other text field. */ +export const extractAntigravityElicitationForm: NonNullable< + AcpAdapterV2Flavor["extractElicitationForm"] +> = (request) => { + if (request.mode !== "form" || !isElicitationForm(request.requestedSchema)) return undefined; + const { properties } = request.requestedSchema; + const questions: OrchestrationV2UserInputQuestion[] = []; + for (const [id, field] of Object.entries(properties)) { + if (!/^q\d+$/.test(id)) continue; + if (!isElicitationQuestion(field) || !isElicitationText(properties[`${id}_other`])) { + return undefined; + } + questions.push({ + id, + header: `Question ${questions.length + 1}`, + question: field.title, + options: field.oneOf.map((option) => ({ + label: option.title, + value: option.const, + description: option.description?.trim() || option.title, + })), + }); + } + // Any other field means a different form; leave it to the generic parser. + if (questions.length === 0 || Object.keys(properties).length !== questions.length * 2) { + return undefined; + } + return { + questions, + respond: (answers) => { + const content: Record = {}; + for (const question of questions) { + const answer = Object.hasOwn(answers, question.id) ? answers[question.id] : undefined; + if (typeof answer !== "string" || !answer.trim()) return { action: "cancel" }; + if (question.options.some((option) => option.value === answer)) { + content[question.id] = answer; + } else { + content[`${question.id}_other`] = answer; + } + } + return { action: "accept", content }; + }, + }; +}; + function boundText(text: string, limit = TOOL_TEXT_LIMIT): string { return text.length <= limit ? text From 1f044c755d5ebdd161414eda3a647c26abb181f6 Mon Sep 17 00:00:00 2001 From: SeongHoon Ryu <4997174+ryush00@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:42:15 +0900 Subject: [PATCH 04/21] fix(antigravity): offer Auto permission mode when agy ACP advertises it Antigravity threads set to Auto ran in Supervised: the provider never offered Auto and mapped it to the agent's default mode. That was right for the legacy 1.4 harness, which has no automatic review, but agy acp 1.5.4+ advertises and enforces an auto session mode. Offer Auto from agy 1.5.4, send the session's auto mode when the session advertises it, and leave the prompts the agent still sends to the user. Sessions without auto (the 1.4 harness, Gemini Enterprise accounts) stay in default and are answered as Supervised. Fixes #37082 Co-Authored-By: Claude Fable 5.2 --- apps/server/scripts/acp-mock-agent.ts | 17 +++-- .../Adapters/AntigravityAdapterV2.test.ts | 55 +++++++++++++++ .../Adapters/AntigravityAdapterV2.ts | 28 +++++--- .../src/provider/AntigravityProvider.test.ts | 55 +++++++++++++-- .../src/provider/AntigravityProvider.ts | 28 ++++++-- .../Drivers/AntigravityDriver.test.ts | 41 +++++++---- .../acp/AntigravityAcpSupport.test.ts | 70 +++++++++++++++++-- .../src/provider/acp/AntigravityAcpSupport.ts | 56 +++++++++++++-- docs/user/permission-modes.md | 8 ++- 9 files changed, 310 insertions(+), 48 deletions(-) diff --git a/apps/server/scripts/acp-mock-agent.ts b/apps/server/scripts/acp-mock-agent.ts index 064b2d2c8d04c..2fe3221b6188a 100644 --- a/apps/server/scripts/acp-mock-agent.ts +++ b/apps/server/scripts/acp-mock-agent.ts @@ -366,11 +366,18 @@ const antigravityModels = [ ] satisfies ReadonlyArray; const availableModes: ReadonlyArray = antigravityProfile - ? [ - { id: "default", name: "Default" }, - { id: "auto_edit", name: "Auto edit" }, - { id: "yolo", name: "YOLO" }, - ] + ? process.env.T3_ACP_ANTIGRAVITY_CLI_MODES === "1" + ? [ + { id: "default", name: "Default" }, + { id: "accept-edits", name: "Accept edits" }, + { id: "auto", name: "Auto" }, + { id: "plan", name: "Plan" }, + ] + : [ + { id: "default", name: "Default" }, + { id: "auto_edit", name: "Auto edit" }, + { id: "yolo", name: "YOLO" }, + ] : copilotModesProfile ? [ { id: copilotModeId("agent"), name: "Agent" }, diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 0633123672b1e..81cd55d8852f6 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -115,6 +115,61 @@ describe("AntigravityAdapterV2 flavor", () => { assert.equal(single?.prompt, "Read README.md"); }); + it.effect("answers Auto as Supervised only in a session that offers no automatic review", () => + Effect.gen(function* () { + const modes = (ids: ReadonlyArray) => ({ + currentModeId: "default", + availableModes: ids.map((id) => ({ id, name: id })), + }); + const sessionModes: Record> = { + personal: modes(["default", "accept-edits", "auto", "plan"]), + enterprise: modes(["default", "accept-edits", "plan"]), + }; + const sessions = makeAntigravityAcpAdapterFlavor({ + instanceId: ProviderInstanceId.make("antigravity-auto-test"), + random: undefined as never, + fileSystem: undefined as never, + path: undefined as never, + host: { paths: { attachmentsDir: "/attachments" } } as never, + selfInvocation: undefined as never, + // The stub names each session after its workspace. + makeRuntime: (input) => + Effect.succeed({ + start: () => + Effect.succeed({ + sessionId: input.cwd, + sessionSetupResult: { modes: sessionModes[input.cwd] }, + }), + } as never), + withProcess: (_stop, task) => task, + defaultModel: Effect.undefined, + }); + const policy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "auto", + interactionMode: "default", + cwd: "/workspace", + }); + const dispositions = (sessionId: string) => + (["read", "execute"] as const).map((kind) => + sessions.permissionDisposition?.(policy, { + sessionId, + options: [], + toolCall: { toolCallId: "tool-1", kind }, + }), + ); + yield* Effect.gen(function* () { + for (const cwd of ["personal", "enterprise"]) { + const runtime = yield* sessions.makeRuntime({ cwd } as never); + yield* runtime.start(); + } + // In `auto` every prompt is a review refusal; without it the agent asks before each action. + assert.deepEqual(dispositions("personal"), ["ask", "ask"]); + assert.deepEqual(dispositions("enterprise"), ["allow", "ask"]); + }).pipe(Effect.scoped); + assert.deepEqual(dispositions("enterprise"), ["ask", "ask"]); + }).pipe(Effect.provide(layerSession)), + ); + it("routes interaction_* permission requests to the question card", () => { const question = flavor.extractPermissionQuestion?.( permissionRequest("interaction_1", [ diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index e13acfecee4e3..1b7125c2d1065 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -21,8 +21,10 @@ import type { AntigravityAuth } from "../../provider/AntigravityAuth.ts"; import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; import { antigravityAppendsSystemPrompt, + antigravityPermissionDisposition, antigravityPermissionMode, antigravityRuntimeModeForSessionMode, + antigravitySessionOffersAutoMode, applyAntigravityAcpModelSelection, buildAntigravityPrompt, type AntigravityAcpRuntimeInput, @@ -146,6 +148,8 @@ export function makeAntigravityAcpAdapterFlavor( const { profileDirectory } = options; const antigravityClientFileRoots = (cwd: string | null) => cwd === null ? [options.host.paths.attachmentsDir] : [cwd, options.host.paths.attachmentsDir]; + // Gemini Enterprise and the 1.4 harness offer no `auto`; those sessions run Auto as Supervised. + const sessionsWithoutAuto = new Set(); const makeRuntime = Effect.fn("AntigravityAdapterV2.makeRuntime")( function* (input: AcpAdapterV2RuntimeInput) { const scope = yield* Scope.fork(yield* Effect.scope); @@ -197,13 +201,17 @@ export function makeAntigravityAcpAdapterFlavor( ); }, start: () => - runtime - .start() - .pipe( - Effect.tap( - (started) => options.onSessionStarted?.(started, input.cwd) ?? Effect.void, - ), - ), + runtime.start().pipe( + Effect.tap((started) => { + if (antigravitySessionOffersAutoMode(started.sessionSetupResult)) return Effect.void; + sessionsWithoutAuto.add(started.sessionId); + return Scope.addFinalizer( + scope, + Effect.sync(() => sessionsWithoutAuto.delete(started.sessionId)), + ); + }), + Effect.tap((started) => options.onSessionStarted?.(started, input.cwd) ?? Effect.void), + ), } satisfies typeof runtime; }, Effect.provideService(SecureRandom.SecureRandom, options.random), @@ -269,7 +277,11 @@ export function makeAntigravityAcpAdapterFlavor( mapError: (cause) => cause, }); }), - sessionModeForPolicy: (policy) => antigravityPermissionMode(policy.runtimeMode), + sessionModeForPolicy: antigravityPermissionMode, + permissionDisposition: (policy, request) => + antigravityPermissionDisposition(policy, request, { + offersAuto: !sessionsWithoutAuto.has(request.sessionId), + }), requiresRuntimeRestartForPolicyChange: (previous, next) => (previous.runtimeMode === "full-access") !== (next.runtimeMode === "full-access"), runtimeModeForSessionMode: antigravityRuntimeModeForSessionMode, diff --git a/apps/server/src/provider/AntigravityProvider.test.ts b/apps/server/src/provider/AntigravityProvider.test.ts index e815fe0e85b9d..b0611915fe90c 100644 --- a/apps/server/src/provider/AntigravityProvider.test.ts +++ b/apps/server/src/provider/AntigravityProvider.test.ts @@ -344,16 +344,57 @@ it.layer(layerTest)("Antigravity provider snapshots", (it) => { }), ); - it.effect("does not offer Auto, so Auto threads fall back to Supervised", () => + it.effect("offers Auto only where the agent has automatic review", () => Effect.gen(function* () { + const modes = (harness: { + readonly provider: { + readonly snapshot: { readonly getSnapshot: Effect.Effect }; + }; + }) => + harness.provider.snapshot.getSnapshot.pipe( + Effect.map((snapshot) => snapshot.supportedRuntimeModes), + ); + const withoutAuto = ["approval-required", "auto-accept-edits", "full-access"]; + const withAuto = ["approval-required", "auto-accept-edits", "auto", "full-access"]; + const startedWithModes = (ids: ReadonlyArray) => ({ + ...started, + sessionSetupResult: { + ...sessionSetupResult, + configOptions: [modelConfig], + modes: { currentModeId: "default", availableModes: ids.map((id) => ({ id, name: id })) }, + }, + }); + + // The 1.4 harness has no automatic review; the shared ACP policy would approve every request. const harness = yield* makeHarness(); yield* harness.initialize; - // Antigravity has no automatic review; the shared ACP policy would approve every request. - expect((yield* harness.provider.snapshot.getSnapshot).supportedRuntimeModes).toEqual([ - "approval-required", - "auto-accept-edits", - "full-access", - ]); + expect(yield* modes(harness)).toEqual(withoutAuto); + yield* harness.provider.onSessionStarted(started); + expect(yield* modes(harness)).toEqual(withoutAuto); + + // The agy CLI offers it from 1.5.4, before any session has reported the account's modes. + const cli = yield* makeHarness(); + yield* Deferred.succeed(cli.initialProbe, { + ...initializeResult, + agentInfo: { ...initializeResult.agentInfo, version: "1.5.6" }, + }); + yield* cli.initialUpdate; + expect(yield* modes(cli)).toEqual(withAuto); + // Gemini Enterprise omits `auto`, and the next health check must not offer it again. + yield* cli.provider.onSessionStarted(startedWithModes(["default", "accept-edits", "plan"])); + expect(yield* modes(cli)).toEqual(withoutAuto); + yield* cli.provider.snapshot.refresh; + expect(yield* modes(cli)).toEqual(withoutAuto); + // Another account may sign in, so the release decides again until its session reports. + yield* cli.provider.onSignedOut; + expect(yield* modes(cli)).toEqual(withAuto); + + const customLauncher = yield* makeHarness(); + yield* customLauncher.initialize; + yield* customLauncher.provider.onSessionStarted( + startedWithModes(["default", "accept-edits", "auto", "plan"]), + ); + expect(yield* modes(customLauncher)).toEqual(withAuto); }), ); diff --git a/apps/server/src/provider/AntigravityProvider.ts b/apps/server/src/provider/AntigravityProvider.ts index 7510106f2c5dc..3f7a95d5eb227 100644 --- a/apps/server/src/provider/AntigravityProvider.ts +++ b/apps/server/src/provider/AntigravityProvider.ts @@ -4,6 +4,7 @@ import { ProviderDriverKind, type AntigravitySettings, type ProviderSetupError, + RuntimeMode, type ServerProvider, type ServerProviderModel, type ServerProviderSlashCommand, @@ -37,7 +38,11 @@ import { } from "@t3tools/provider-core/server/snapshotProbe"; import { resolveUsageLimitsAfterProbe } from "@t3tools/provider-core/server/usageLimits"; -import { antigravityThinkingConfig } from "./acp/AntigravityAcpSupport.ts"; +import { + antigravityReleaseOffersAutoMode, + antigravitySessionOffersAutoMode, + antigravityThinkingConfig, +} from "./acp/AntigravityAcpSupport.ts"; const EMPTY_MODEL_CAPABILITIES = createModelCapabilities({ optionDescriptors: [] }); const MAX_WORKSPACE_SNAPSHOTS = 32; @@ -187,8 +192,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func presentation: { displayName: "Antigravity", showInteractionModeToggle: false, - // No automatic review, so Auto falls back to Supervised instead of approving everything. - supportedRuntimeModes: ["approval-required", "auto-accept-edits", "full-access"], + supportedRuntimeModes: RuntimeMode.literals.filter((mode) => mode !== "auto"), }, enabled: settings.enabled, checkedAt, @@ -225,6 +229,13 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func thinkingLevels.set(model.currentValue, antigravityThinkingConfig(configOptions) ?? null); } }; + // Whether the account's last session offered `auto`; Gemini Enterprise and the 1.4 harness do + // not. Until a session reports, the release decides. Unoffered, Auto falls back to Supervised. + let sessionOffersAuto: boolean | undefined; + const runtimeModes = (version: string | null) => { + const offersAuto = sessionOffersAuto ?? antigravityReleaseOffersAutoMode(version); + return RuntimeMode.literals.filter((mode) => mode !== "auto" || offersAuto); + }; const getSnapshot = SubscriptionRef.get(metadata).pipe( Effect.flatMap((state) => options.stampIdentity(state.draft)), ); @@ -301,6 +312,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func if (state.authRevision !== before.authRevision) return state; const { message: _previousMessage, ...draft } = state.draft; const authenticated = draft.auth.status === "authenticated"; + const resolvedVersion = version === "unknown" ? draft.version : version || draft.version; const message = errorMessage ?? (authenticated @@ -314,7 +326,8 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func ...draft, installed: !missingInstallation, // Lightweight custom-launcher probes lack versions; preserve the real handshake's version. - version: version === "unknown" ? draft.version : version || draft.version, + version: resolvedVersion, + supportedRuntimeModes: runtimeModes(resolvedVersion), status: errorMessage ? "error" : authenticated ? "ready" : "warning", checkedAt: updatedAt, usageLimits: missingInstallation ? undefined : draft.usageLimits, @@ -379,16 +392,19 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func ) { return state; } + sessionOffersAuto = antigravitySessionOffersAutoMode(started.sessionSetupResult); const { message: _previousMessage, ...draft } = state.draft; const workspaces = draft.workspaceSnapshots ?? []; const workspace = cwd ? workspaces.find((entry) => entry.cwd === cwd) : undefined; + const version = started.initializeResult.agentInfo?.version || draft.version; return { authRevision: state.authRevision + 1, draft: { ...draft, installed: true, status: "ready", - version: started.initializeResult.agentInfo?.version || draft.version, + version, + supportedRuntimeModes: runtimeModes(version), auth: { status: "authenticated", type: options.auth?.type ?? "oauth-personal", @@ -466,6 +482,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func yield* resetUsage; if (!settings.enabled) return; const updatedAt = DateTime.formatIso(yield* DateTime.now); + sessionOffersAuto = undefined; yield* SubscriptionRef.update( metadata, (state) => @@ -473,6 +490,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func authRevision: state.authRevision + 1, draft: { ...state.draft, + supportedRuntimeModes: runtimeModes(state.draft.version), auth: { status: "unauthenticated", ...(usesCredentials ? options.auth : {}), diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.test.ts b/apps/server/src/provider/Drivers/AntigravityDriver.test.ts index 1341c68948c02..e44dc79ff50c9 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.test.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.test.ts @@ -88,6 +88,8 @@ const makeHarness = Effect.fn("makeAntigravityDriverHarness")(function* ( /** `data` of the agent's "Internal error" response to `session/new`. */ readonly newSessionErrorData?: unknown; readonly initialMode?: string; + /** Advertise the agy CLI's modes, which include `auto`, instead of the 1.4 harness's. */ + readonly cliModes?: boolean; } = {}, ) { const directory = path.join(root, name); @@ -111,6 +113,7 @@ const makeHarness = Effect.fn("makeAntigravityDriverHarness")(function* ( ...(options.initialMode === undefined ? [] : [`export T3_ACP_INITIAL_MODE=${shellQuote(options.initialMode)}`]), + ...(options.cliModes ? ["export T3_ACP_ANTIGRAVITY_CLI_MODES=1"] : []), `exec ${shellQuote(nodePath)} ${shellQuote(mockAgentPath)} "$@"`, "", ].join("\n"), @@ -419,9 +422,21 @@ it.layer(layerTest)("AntigravityDriver", (it) => { ...(yield* h.makeExecutable("runtime cli", { initialMode: "auto_edit" })), harnessPath: null, }; - for (const runtimeMode of ["full-access", "auto-accept-edits"] as const) { + const cliWithAuto = { + ...(yield* h.makeExecutable("runtime cli auto", { cliModes: true })), + harnessPath: null, + }; + // Auto runs the agent's own review where the session offers it; elsewhere the agent asks. + for (const [runtimeMode, executable, sessionModes] of [ + ["full-access", h.controls.selected, ["default"]], + ["auto-accept-edits", h.controls.selected, ["default"]], + ["auto", h.controls.selected, ["default"]], + ["auto", h.second, []], + ["auto", cliWithAuto, ["auto"]], + ] as const) { + h.controls.selected = executable; const requestsBefore = (yield* h.readRequests).length; - const cliThreadId = ThreadId.make(`thread-antigravity-cli-${runtimeMode}`); + const cliThreadId = ThreadId.make(`thread-antigravity-cli-${requestsBefore}`); const cliPolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ runtimeMode, interactionMode: "default", @@ -429,7 +444,7 @@ it.layer(layerTest)("AntigravityDriver", (it) => { }); const cliSession = yield* h.instance.orchestrationAdapter.openSession({ threadId: cliThreadId, - providerSessionId: ProviderSessionId.make(`provider-session-cli-${runtimeMode}`), + providerSessionId: ProviderSessionId.make(`provider-session-cli-${requestsBefore}`), modelSelection, runtimePolicy: cliPolicy, }); @@ -438,14 +453,16 @@ it.layer(layerTest)("AntigravityDriver", (it) => { modelSelection, runtimePolicy: cliPolicy, }); - expect(h.launches.at(-1)?.args).toEqual([ - "acp", - "--gemini-dir", - h.profileDirectory, - "--app-data-dir", - "antigravity-acp", - ...(runtimeMode === "full-access" ? ["--dangerously-skip-permissions"] : []), - ]); + if (executable.harnessPath === null) { + expect(h.launches.at(-1)?.args).toEqual([ + "acp", + "--gemini-dir", + h.profileDirectory, + "--app-data-dir", + "antigravity-acp", + ...(runtimeMode === "full-access" ? ["--dangerously-skip-permissions"] : []), + ]); + } expect( (yield* h.readRequests) .slice(requestsBefore) @@ -455,7 +472,7 @@ it.layer(layerTest)("AntigravityDriver", (it) => { request.params?.configId === "mode", ) .map((request) => request.params?.value), - ).toEqual(["default"]); + ).toEqual(sessionModes); } }), ); diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts index 65b5e0b5c5f8f..f7da29e0c4839 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts @@ -4,6 +4,7 @@ import { ANTIGRAVITY_DEFAULT_MODEL, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, type ChatAttachment, + type RuntimeMode, } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; @@ -22,6 +23,8 @@ import { antigravityRuntimeModeForSessionMode, antigravitySessionMeta, applyAntigravityAcpModelSelection, + antigravityPermissionDisposition, + antigravityReleaseOffersAutoMode, buildAntigravityPrompt, isQualifiedAntigravityRelease, } from "./AntigravityAcpSupport.ts"; @@ -110,10 +113,10 @@ describe("Antigravity session mode mapping", () => { const cliWithoutAuto = new Set(["default", "accept-edits", "plan"]); const managedModes = new Set(["default", "auto_edit", "yolo", "plan"]); - expect(antigravityPermissionMode("full-access")).toBe("yolo"); - expect(antigravityPermissionMode("auto")).toBe("auto"); - expect(antigravityPermissionMode("auto-accept-edits")).toBe("auto_edit"); - expect(antigravityPermissionMode("approval-required")).toBe("default"); + expect(antigravityPermissionMode({ runtimeMode: "full-access" })).toBe("yolo"); + expect(antigravityPermissionMode({ runtimeMode: "auto" })).toBe("auto"); + expect(antigravityPermissionMode({ runtimeMode: "auto-accept-edits" })).toBe("auto_edit"); + expect(antigravityPermissionMode({ runtimeMode: "approval-required" })).toBe("default"); expect(antigravityCliSessionMode("yolo", cliModes)).toBe("default"); expect(antigravityCliSessionMode("auto_edit", cliModes)).toBe("accept-edits"); @@ -133,6 +136,65 @@ describe("Antigravity session mode mapping", () => { }); }); +describe("Antigravity permission modes", () => { + const policy = ( + runtimeMode: RuntimeMode, + overrides: { readonly approvalPolicy?: unknown; readonly sandboxPolicy?: unknown } = {}, + ) => ({ runtimeMode, cwd: "/workspace", ...overrides }); + const request = (kind: EffectAcpSchema.ToolKind) => + ({ + sessionId: "session-1", + toolCall: { toolCallId: "tool-1", kind }, + options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }], + }) satisfies EffectAcpSchema.RequestPermissionRequest; + + it("expects automatic review from agy 1.5.4, never from the 1.4 harness", () => { + expect( + ["1.5.4", "1.5.6", "1.6.0", "1.5.3", "1.4.5", "agy_acp_server_20260818_01_RC01", null].map( + antigravityReleaseOffersAutoMode, + ), + ).toEqual([true, true, true, false, false, false, false]); + }); + + it("maps Auto to the agent's automatic review", () => { + expect(antigravityPermissionMode(policy("auto"))).toBe("auto"); + expect(antigravityRuntimeModeForSessionMode("auto")).toBe("auto"); + }); + + it("leaves Auto prompts to the user instead of approving them", () => { + const auto = { offersAuto: true }; + const noAuto = { offersAuto: false }; + const disposition = antigravityPermissionDisposition; + // In `auto` a prompt is a review refusal, so even a read reaches the user. + for (const kind of ["read", "edit", "execute"] as const) { + expect(disposition(policy("auto"), request(kind), auto)).toBe("ask"); + } + // A session without `auto` stays in `default` and is answered as Supervised. + expect( + (["read", "edit", "execute"] as const).map((kind) => + disposition(policy("auto"), request(kind), noAuto), + ), + ).toEqual( + (["read", "edit", "execute"] as const).map((kind) => + disposition(policy("approval-required"), request(kind), noAuto), + ), + ); + expect(disposition(policy("auto"), request("read"), noAuto)).toBe("allow"); + // An explicit policy keeps the agent asking and answers for itself. + const readOnly = policy("auto", { + approvalPolicy: "never", + sandboxPolicy: { type: "readOnly" }, + }); + expect(antigravityPermissionMode(readOnly)).toBe("default"); + expect(disposition(readOnly, request("execute"), auto)).toBe("deny"); + // The other modes still answer from the shared ACP policy. + expect(disposition(policy("full-access"), request("execute"), auto)).toBe("allow"); + expect(disposition(policy("auto-accept-edits"), request("edit"), auto)).toBe("allow"); + expect(disposition(policy("auto-accept-edits"), request("execute"), auto)).toBe("ask"); + expect(disposition(policy("approval-required"), request("edit"), auto)).toBe("ask"); + }); +}); + describe("applyAntigravityAcpModelSelection", () => { it.effect("restores the saved model instead of the cold-resume default", () => Effect.gen(function* () { diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index bc96bbc3c2453..1d1569d42d934 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -25,6 +25,12 @@ import { } from "../antigravityAuthSupport.ts"; import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import { + acpPermissionDisposition, + type AcpPermissionDisposition, + type AcpRuntimePolicy, +} from "@t3tools/provider-acp/server/clientPolicy"; +import { parseSessionModeState } from "@t3tools/provider-acp/server/runtimeModel"; import packageJson from "../../../package.json" with { type: "json" }; import { normalizeAntigravitySessionUpdate } from "./AntigravityProtocol.ts"; @@ -173,14 +179,31 @@ export const makeAntigravityAcpRuntime = Effect.fn("makeAntigravityAcpRuntime")( return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(Effect.provide(context)); }); -export function antigravityPermissionMode(runtimeMode: RuntimeMode): string { - switch (runtimeMode) { +// `agy acp` 1.5.4 added `auto`, its automatic safety review; the 1.4 harness has none. +const AUTO_MODE_RELEASE = [1, 5, 4] as const; + +/** Whether a release is expected to offer `auto`, until a session reports its account's modes. */ +export function antigravityReleaseOffersAutoMode(version: string | null | undefined): boolean { + const parsed = parseAntigravityVersion(version); + return parsed !== undefined && compareVersions(parsed, AUTO_MODE_RELEASE) >= 0; +} + +/** + * An explicit approval or sandbox policy must not launch automatic review, which would approve + * actions the policy meant to confine. + */ +export function antigravityPermissionMode( + policy: Pick, +): string { + switch (policy.runtimeMode) { case "full-access": return "yolo"; - case "auto": - return "auto"; case "auto-accept-edits": return "auto_edit"; + case "auto": + return policy.approvalPolicy === undefined && policy.sandboxPolicy === undefined + ? "auto" + : "default"; case "approval-required": return "default"; } @@ -235,6 +258,31 @@ export function antigravityManagedSessionMode( return availableModeIds === undefined || availableModeIds.has(modeId) ? modeId : "default"; } +/** + * In `auto` the agent asks only about what its own review refused, so every prompt reaches the + * user. A session that offers no `auto` stays in `default` and is answered as Supervised. + */ +export function antigravityPermissionDisposition( + policy: AcpRuntimePolicy, + request: EffectAcpSchema.RequestPermissionRequest, + session: { readonly offersAuto: boolean }, +): AcpPermissionDisposition { + if (antigravityPermissionMode(policy) !== "auto") + return acpPermissionDisposition(policy, request); + return session.offersAuto + ? "ask" + : acpPermissionDisposition({ ...policy, runtimeMode: "approval-required" }, request); +} + +export function antigravitySessionOffersAutoMode( + sessionSetupResult: AcpSessionRuntime.AcpSessionRuntimeStartResult["sessionSetupResult"], +): boolean { + return ( + parseSessionModeState(sessionSetupResult)?.availableModes.some((mode) => mode.id === "auto") === + true + ); +} + /** The runtime mode an Antigravity session mode grants; the inverse of `antigravityPermissionMode`. */ export function antigravityRuntimeModeForSessionMode(modeId: string): RuntimeMode | undefined { switch (modeId) { diff --git a/docs/user/permission-modes.md b/docs/user/permission-modes.md index 6a3fa01ab7e75..a10c6ae730ea5 100644 --- a/docs/user/permission-modes.md +++ b/docs/user/permission-modes.md @@ -27,9 +27,9 @@ the parent conversation with the subagent's name, so you can respond without swi ## Provider differences Providers enforce permissions differently. Some read-only actions can proceed in **Supervised**. -**Auto** uses automatic review on Codex, Claude, Cursor, Grok, and fx; providers without an equivalent, -including OpenCode and Antigravity, fall back to asking. On Grok, commands its review blocks come -to you for approval. On fx, prompts it still sends also come to you. +**Auto** uses automatic review on Codex, Claude, Cursor, Grok, fx, and Antigravity; providers +without an equivalent, including OpenCode, fall back to asking. On Grok, commands its review blocks +come to you for approval. On fx and Antigravity, prompts they still send also come to you. Muse Code offers only **Supervised** and **Full access**. A Muse thread already set to another mode runs in **Supervised**. @@ -51,6 +51,8 @@ continues without the removal and tells you what it skipped. While a Claude approval is pending, type a text reply to decline that request and give feedback directly to the agent that asked, including a subagent. Other pending requests stay unanswered. +Antigravity offers **Auto** from version 1.5.4, for accounts that have its automatic review; Gemini +Enterprise accounts do not. Without it, an Antigravity thread set to **Auto** runs in **Supervised**. Antigravity can still send native approval requests in **Full access**. It only offers remembered approvals for actions that support them. From 517968ccfc4a2f71b2fcb62f1f4bd8b557b3c9c4 Mon Sep 17 00:00:00 2001 From: SeongHoon Ryu <4997174+ryush00@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:05:45 +0900 Subject: [PATCH 05/21] fix(acp): follow permission mode changes on an open session An open ACP session was reconfigured only when the model or the interaction mode changed. Antigravity keeps its session across a permission mode change, so switching Auto to Supervised left agy in its auto mode, running edits and commands unasked under a Supervised label, and Supervised to Auto stayed in default. Reconfigure when the turn's policy asks for a different native mode, native config, or ceiling than the session was last configured for, and stop the Plan restore from putting back a mode the policy has replaced. Co-Authored-By: Claude Fable 5.2 --- .../Adapters/AcpAdapterV2.test.ts | 57 ++++++++++++++++--- packages/provider-acp/src/server/adapter.ts | 18 +++++- 2 files changed, 63 insertions(+), 12 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 32956a0d495ff..e785ed7058080 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -2413,12 +2413,19 @@ describe("AcpAdapterV2", () => { ); it.live.each([ - { modeIds: "plain", environment: {}, planModeId: "architect", buildModeId: "ask" }, + { + modeIds: "plain", + environment: {}, + planModeId: "architect", + buildModeId: "ask", + autoModeId: "code", + }, { modeIds: "Copilot URL", environment: { T3_ACP_COPILOT_MODES: "1" }, planModeId: "https://agentclientprotocol.com/protocol/session-modes#plan", buildModeId: "https://agentclientprotocol.com/protocol/session-modes#agent", + autoModeId: "https://agentclientprotocol.com/protocol/session-modes#autopilot", }, { // Without a `mode` category, T3 derives no mode state and only the config option switches. @@ -2426,10 +2433,11 @@ describe("AcpAdapterV2", () => { environment: { T3_ACP_COPILOT_MODES: "1", T3_ACP_MODE_OPTION_CATEGORY: "collaboration_mode" }, planModeId: "https://agentclientprotocol.com/protocol/session-modes#plan", buildModeId: "https://agentclientprotocol.com/protocol/session-modes#agent", + autoModeId: "https://agentclientprotocol.com/protocol/session-modes#autopilot", }, ])( - "refreshes ACP prompt instructions and native mode when the interaction mode changes ($modeIds mode ids)", - ({ environment, planModeId, buildModeId }) => + "refreshes ACP prompt instructions and native mode when the interaction or permission mode changes ($modeIds mode ids)", + ({ environment, planModeId, buildModeId, autoModeId }) => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; const selfInvocation = yield* resolveSelfInvocation(); @@ -2457,12 +2465,22 @@ describe("AcpAdapterV2", () => { protocolEvents, environment, }), + // Full access names no mode, so the agent's advertised default stands. + sessionModeForPolicy: ({ runtimeMode }) => + runtimeMode === "auto" + ? autoModeId + : runtimeMode === "approval-required" + ? buildModeId + : undefined, }, selfInvocation, }); - const policy = (interactionMode: "default" | "plan") => + const policy = ( + interactionMode: "default" | "plan", + runtimeMode: "full-access" | "auto" | "approval-required" = "full-access", + ) => ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", + runtimeMode, interactionMode, cwd: process.cwd(), }); @@ -2566,12 +2584,33 @@ describe("AcpAdapterV2", () => { [buildModeId], "Build should restore the native mode that T3 temporarily replaced for Plan", ); - const switchedModel = yield* runTurn(7, defaultPolicy, "Switch models.", { - instanceId, - model: "composer-2", - }); + const composer = { instanceId, model: "composer-2" } as const; + const switchedModel = yield* runTurn(7, defaultPolicy, "Switch models.", composer); assert.equal(switchedModel.textBlockCount, 2); assert.include(switchedModel.prompt, "as composer-2"); + + // Only the permission mode changes from here; the open session must follow it. + const permissionModeSets = Effect.fnUntraced(function* ( + ordinal: number, + runtimeMode: "auto" | "approval-required", + interactionMode: "default" | "plan" = "default", + ) { + const turn = yield* runTurn( + ordinal, + policy(interactionMode, runtimeMode), + "Continue.", + composer, + ); + assert.notInclude(turn.methods, "session/new"); + return turn.modeSets; + }); + assert.deepEqual(yield* permissionModeSets(8, "auto"), [autoModeId]); + assert.deepEqual(yield* permissionModeSets(9, "auto"), []); + assert.deepEqual(yield* permissionModeSets(10, "approval-required"), [buildModeId]); + assert.deepEqual(yield* permissionModeSets(11, "auto"), [autoModeId]); + assert.deepEqual(yield* permissionModeSets(12, "auto", "plan"), [planModeId]); + // Leaving Plan applies the permission mode of this turn, not the one saved on entering it. + assert.deepEqual(yield* permissionModeSets(13, "approval-required"), [buildModeId]); }).pipe(Effect.provide(layerTest)), ); diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 56ed03ffb6b0d..453ae6692449c 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -2218,6 +2218,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( >(null); const activeRuntimePolicy = yield* Ref.make(null); + // Session mode and config derive from more of the policy than its runtime mode. + const sessionPolicyKey = (policy: ProviderAdapter.ProviderAdapterV2RuntimePolicy) => + JSON.stringify([ + flavor.sessionModeForPolicy?.(policy), + flavor.sessionConfigForPolicy?.(policy), + ]); const promptInstructionStates = yield* Ref.make(new Map()); const promptRuntimeInstructions = yield* Ref.make(new Map()); // Unique markers keep delayed prompt completions from clearing later compactions. @@ -8143,8 +8149,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } else { const nativeBuild = nativeBuildConfigurationBySessionId.get(startResult.sessionId); if (nativeBuild !== undefined) { + // The policy mode applied above already left Plan; a saved mode may predate a policy change. + const policyOwnsMode = policyMode !== undefined; if ( - !modeLocked && + !policyOwnsMode && nativeBuild.modeId !== undefined && effectiveModeState?.currentModeId !== nativeBuild.modeId && effectiveModeState?.availableModes.some( @@ -8160,7 +8168,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if ( option === undefined || option.type !== "select" || - (modeLocked && option.category === "mode") + (policyOwnsMode && (option.category === "mode" || option.id === "mode")) ) continue; const choices = option.options.flatMap((entry) => @@ -8862,7 +8870,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( configuredInteractionMode !== turnInput.runtimePolicy.interactionMode || (yield* Ref.get(configuredRuntimeMode)) !== turnInput.runtimePolicy.runtimeMode || configuredRuntimePolicy === null || - configuredRuntimePolicy.maxRuntimeMode !== turnInput.runtimePolicy.maxRuntimeMode + configuredRuntimePolicy.maxRuntimeMode !== turnInput.runtimePolicy.maxRuntimeMode || + sessionPolicyKey(configuredRuntimePolicy) !== + sessionPolicyKey(turnInput.runtimePolicy) ) { const currentSessionSetup = yield* Ref.get(activeSessionSetup); if (currentSessionSetup === null) { @@ -10136,6 +10146,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* setActiveSessionSetup(activated); yield* Ref.set(activeSelection, null); yield* Ref.set(activeInteractionMode, null); + yield* Ref.set(activeRuntimePolicy, null); } const state = yield* Ref.get(snapshot); const messages = state.order.flatMap((key) => { @@ -10275,6 +10286,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* setActiveSessionSetup(forked); yield* Ref.set(activeSelection, null); yield* Ref.set(activeInteractionMode, null); + yield* Ref.set(activeRuntimePolicy, null); itemIdentityVersion = 2; const now = yield* DateTime.now; const providerThread = makeProviderThread({ From f0d0eb7a702577d9819780279d260e010ab78370 Mon Sep 17 00:00:00 2001 From: youjiaxing Date: Mon, 16 Nov 2026 10:20:37 +0900 Subject: [PATCH 06/21] fix(antigravity): allow compaction when the runtime advertises it (#37020) Upstream PR: https://github.com/pingdotgg/t3code/pull/37020 --- .../Adapters/AntigravityAdapterV2.test.ts | 82 ++++++++++++++++--- .../Adapters/AntigravityAdapterV2.ts | 3 +- docs/user/providers-antigravity.md | 5 +- 3 files changed, 73 insertions(+), 17 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 81cd55d8852f6..93182347e512a 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -372,16 +372,24 @@ describe("AntigravityAdapterV2 harness recovery", () => { }); describe("AntigravityAdapterV2 compaction", () => { - it.live.each([false, true])( - "negotiates native goals (%s) without enabling manual compaction", - (nativeGoals) => + it.live.each([ + { nativeGoals: false, compact: false }, + { nativeGoals: true, compact: false }, + { nativeGoals: false, compact: true }, + { nativeGoals: true, compact: true }, + ])( + "negotiates native goals ($nativeGoals) and advertised compaction ($compact)", + ({ nativeGoals, compact }) => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const crypto = yield* SecureRandom.SecureRandom; const mockAgentPath = yield* path.fromFileUrl( new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), ); + const logs = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-ag-compact-" }); + const requestLog = path.join(logs, "requests.ndjson"); const instanceId = ProviderInstanceId.make("antigravity-compaction-test"); const goalSupport = yield* Ref.make(false); const startupMilestone = yield* Deferred.make(); @@ -401,7 +409,11 @@ describe("AntigravityAdapterV2 compaction", () => { command: process.execPath, args: [mockAgentPath], cwd: input.cwd, - env: { T3_ACP_ANTIGRAVITY: "1" }, + env: { + T3_ACP_ANTIGRAVITY: "1", + T3_ACP_AVAILABLE_COMMANDS: compact ? "compact" : "", + T3_ACP_REQUEST_LOG_PATH: requestLog, + }, }, }).pipe( Effect.provideService(SecureRandom.SecureRandom, crypto), @@ -430,28 +442,72 @@ describe("AntigravityAdapterV2 compaction", () => { ) : Effect.void, }); + const threadId = ThreadId.make("thread-antigravity-compaction"); + const modelSelection = { instanceId, model: "gemini-test-low" } as const; + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); const opening = yield* adapter .openSession({ - threadId: ThreadId.make("thread-antigravity-compaction"), + threadId, providerSessionId: ProviderSessionId.make("provider-session-antigravity-compaction"), - modelSelection: { instanceId, model: "gemini-test-low" }, - runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }), + modelSelection, + runtimePolicy, }) .pipe(Effect.forkScoped); yield* Deferred.await(startupMilestone); yield* Deferred.succeed(consumeStartupCommands, undefined); const session = yield* Fiber.join(opening); assert.deepEqual(yield* Ref.get(workspaceCommands), { - names: ["plan", "logout"], + names: compact ? ["compact"] : ["plan", "logout"], cwd: process.cwd(), }); - assert.isUndefined(session.compactThread); + const compactThread = session.compactThread; + assert.isDefined(compactThread); assert.equal(session.providerSession.capabilities.turns.supportsNativeGoals, nativeGoals); assert.equal((yield* adapter.getCapabilities()).turns.supportsNativeGoals, nativeGoals); + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const turnInput = makeTurnInput({ + threadId, + providerThread, + instanceId, + modelSelection, + runtimePolicy, + now: yield* DateTime.now, + messageText: "Compact the conversation.", + }); + if (compact) { + yield* compactThread!(turnInput); + const events = yield* session.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ); + assert.isTrue( + events.some( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "compaction" && + event.turnItem.status === "completed", + ), + ); + } else { + const error = yield* compactThread!(turnInput).pipe(Effect.flip); + assert.instanceOf(error, ProviderAdapter.ProviderAdapterTurnStartError); + assert.instanceOf(error.cause, ProviderAdapter.ProviderCompactionUnsupportedError); + } + const prompts = (yield* fileSystem.readFileString(requestLog)) + .trim() + .split("\n") + .map((line) => JSON.parse(line) as { method?: string; params?: { prompt?: unknown } }) + .filter((request) => request.method === "session/prompt") + .map((request) => request.params?.prompt); + assert.deepEqual(prompts, compact ? [[{ type: "text", text: "/compact" }]] : []); }).pipe(Effect.provide(layerSession)), ); }); diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index 1b7125c2d1065..acb532161116c 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -307,8 +307,7 @@ export function makeAntigravityAcpAdapterFlavor( normalizeToolCall: normalizeAntigravityToolCall, extractSubagentUpdate: extractAntigravitySubagentUpdate, supportsImagePrompts: true, - // ACP 1.3.0 treats /compact as ordinary model input. - supportsCompaction: false, + compactViaAdvertisedCommand: true, requiresSignIn: isAntigravitySignInRequiredError, // Antigravity can leave a prompt open without updates; long tools and approvals pause this. promptInactivityTimeout: "15 minutes", diff --git a/docs/user/providers-antigravity.md b/docs/user/providers-antigravity.md index c22a20a2ca540..8935439c0a63d 100644 --- a/docs/user/providers-antigravity.md +++ b/docs/user/providers-antigravity.md @@ -98,8 +98,9 @@ Antigravity. Antigravity cannot rewind its own conversation, so the next turn starts a fresh Antigravity session and T3 Code sends it the kept conversation, without the turns you removed. -Manual context compaction is unavailable through Antigravity's ACP runtime, even -though its CLI has `/compact`. Send `/clear` when you need a fresh context. +Use `/compact` to summarize a long conversation when your Antigravity runtime +offers that command. If it is unavailable, update Antigravity in provider settings +or send `/clear` when you need a fresh context. ### Skills and attachments From e3d0c626476bdfe94129db293a445e7cf43b8484 Mon Sep 17 00:00:00 2001 From: Kirat0201 Date: Mon, 16 Nov 2026 10:20:38 +0900 Subject: [PATCH 07/21] fix(server): let Antigravity validate newly discovered models (#36804) Upstream PR: https://github.com/pingdotgg/t3code/pull/36804 --- .../acp/AntigravityAcpSupport.test.ts | 40 ++++++++++--------- .../src/provider/acp/AntigravityAcpSupport.ts | 15 +++---- 2 files changed, 30 insertions(+), 25 deletions(-) diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts index f7da29e0c4839..fe6211416013b 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts @@ -57,6 +57,7 @@ function makeModelRuntime( selections.push( `${configId}=${String(value)}${options?.allowUnlistedValue === true ? " (unlisted)" : ""}`, ); + if (failure) return yield* failure; return { configOptions }; }); return { @@ -250,24 +251,27 @@ describe("applyAntigravityAcpModelSelection", () => { }), ); - it.effect.each(["gemini-removed", "Gemini saved", "gemini-saved[reasoning=high]"])( - "rejects unavailable or non-native model ID %s without selecting a fallback", - (model) => - Effect.gen(function* () { - const { runtime, selections } = makeModelRuntime(); - const error = yield* applyAntigravityAcpModelSelection({ - runtime, - model, - mapError: (cause) => cause, - }).pipe(Effect.flip); - - expect(error).toMatchObject({ - _tag: "AcpRequestError", - code: -32602, - errorMessage: expect.stringContaining(`'${model}' is unavailable`), - }); - expect(selections).toEqual([]); - }), + it.effect("sends an explicit model absent from cached choices to the provider", () => + Effect.gen(function* () { + const { runtime, selections } = makeModelRuntime(); + const model = yield* applyAntigravityAcpModelSelection({ + runtime, + model: "gemini-new", + mapError: (cause) => cause, + }); + expect(model).toBe("gemini-new"); + expect(selections).toEqual(["model=gemini-new (unlisted)"]); + + const failure = EffectAcpErrors.AcpRequestError.invalidParams("Provider rejected it."); + const rejecting = makeModelRuntime([modelConfig], failure); + const error = yield* applyAntigravityAcpModelSelection({ + runtime: rejecting.runtime, + model: "gemini-removed", + mapError: (cause) => ({ cause }), + }).pipe(Effect.flip); + expect(error).toEqual({ cause: failure }); + expect(rejecting.selections).toEqual(["model=gemini-removed (unlisted)"]); + }), ); it.effect("accepts exact model IDs from grouped native options", () => diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index 1d1569d42d934..186948ce78d52 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -390,17 +390,18 @@ export const applyAntigravityAcpModelSelection = Effect.fn("applyAntigravityAcpM }); const explicit = Boolean(input.model) && input.model !== ANTIGRAVITY_DEFAULT_MODEL; if (resolved === undefined || (!explicit && resolved === current)) return current; - const options = antigravityModelOptions(configOptions); - const legacyFamily = options.some((option) => option.value === resolved) - ? undefined - : legacyAntigravityFamily(configOptions, resolved); - if (legacyFamily !== undefined) { + const listed = antigravityModelOptions(configOptions).some( + (option) => option.value === resolved, + ); + const legacyFamily = listed ? undefined : legacyAntigravityFamily(configOptions, resolved); + // A live session's choices go stale when the account gains models; let the agent decide. + if (legacyFamily !== undefined || (explicit && !listed)) { yield* input.runtime .setConfigOption("model", resolved, { allowUnlistedValue: true }) .pipe(Effect.mapError(input.mapError)); - return legacyFamily; + return legacyFamily ?? resolved; } - if (!options.some((option) => option.value === resolved)) { + if (!listed) { return yield* Effect.fail( input.mapError( EffectAcpErrors.AcpRequestError.invalidParams( From 27ae4e7e2822008409be84780f22326b5dcd4e7d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 16 Nov 2026 10:20:38 +0900 Subject: [PATCH 08/21] fix(server): Antigravity subagent view finds auto-approved launches (#31316) Upstream PR: https://github.com/pingdotgg/t3code/pull/31316 --- .../provider/acp/AntigravityChildWork.test.ts | 147 ++++++++++++++++-- .../acp/AntigravityChildWork.testkit.ts | 18 ++- .../src/provider/acp/AntigravityChildWork.ts | 141 ++++++++++------- 3 files changed, 237 insertions(+), 69 deletions(-) diff --git a/apps/server/src/provider/acp/AntigravityChildWork.test.ts b/apps/server/src/provider/acp/AntigravityChildWork.test.ts index e1bfe3aa504e8..b8956cddd9759 100644 --- a/apps/server/src/provider/acp/AntigravityChildWork.test.ts +++ b/apps/server/src/provider/acp/AntigravityChildWork.test.ts @@ -20,6 +20,7 @@ import { invokeStep, LAUNCH, makeProfile, + plannerResponse, plannerStep, ROOT, transcriptLines, @@ -47,7 +48,7 @@ const read = ( }); it.layer(NodeServices.layer)("readAntigravityChildWork", (it) => { - it.effect("follows an auto-approved call id through its planner step to the record", () => + it.effect("follows an auto-approved call id to the record that ran it", () => Effect.gen(function* () { const { profile } = yield* makeProfile({ steps: autoApproved }); const [child, ...rest] = yield* read(profile, `${ROOT}:1`); @@ -68,28 +69,152 @@ it.layer(NodeServices.layer)("readAntigravityChildWork", (it) => { }), ); - it.effect("needs proof that the call id belongs to the parent's record", () => + it.effect("follows each auto-approved launch id to the step that ran it", () => Effect.gen(function* () { + const tester = { role: "Test Runner", prompt: "Run the tests" }; + const empty = new Uint8Array(); + // A 1.4.5 session: USER_INPUT 14, VIEW_FILE 8, SYSTEM_MESSAGE 101, PLANNER_RESPONSE 15. + // Ids number the executing steps, skipping planners with neither text nor thinking: + // the invoke records at idx 8 and 12 arrive as `:6` and `:9`. const { profile } = yield* makeProfile({ steps: (logUri) => [ - ...autoApproved(logUri), - [5, 15, plannerStep(["call-b", "call-c"])], + [0, 14, empty], + [ + 1, + 15, + plannerResponse({ + calls: [ + ["v1", "view_file"], + ["v2", "view_file"], + ], + }), + ], + [2, 8, empty], + [3, 8, empty], + [4, 15, plannerResponse({ text: "Reading more", calls: [["v3", "view_file"]] })], + [5, 8, empty], [ 6, + 15, + plannerResponse({ + calls: [ + ["v4", "view_file"], + ["call-a", "invoke_subagent"], + ], + }), + ], + [7, 8, empty], + [ + 8, + 127, + invokeStep({ callId: "call-a", launches: [LAUNCH], children: [{ id: CHILD, logUri }] }), + ], + [9, 15, plannerResponse({ text: "The reader is done", calls: [] })], + [10, 101, empty], + [11, 15, plannerResponse({ calls: [["call-b", "invoke_subagent"]] })], + [ + 12, 127, - invokeStep({ callId: "call-b", launches: [LAUNCH], children: [{ id: CHILD, logUri }] }), + invokeStep({ callId: "call-b", launches: [tester], children: [{ id: CHILD, logUri }] }), + ], + ], + }); + const first = yield* read(profile, `${ROOT}:6`); + expect(first.map((child) => child.role)).toEqual([LAUNCH.role]); + const second = yield* read(profile, `${ROOT}:9`); + expect(second.map((child) => child.role)).toEqual([tester.role]); + }), + ); + + it.effect("follows a launch id past many earlier launches", () => + Effect.gen(function* () { + const launches = Array.from({ length: 201 }, (_, index) => ({ + role: `Reader ${index + 1}`, + prompt: LAUNCH.prompt, + })); + const { profile } = yield* makeProfile({ + steps: (logUri) => [ + [0, 14, new Uint8Array()], + ...launches.flatMap((launch, index) => [ + [1 + index * 2, 15, plannerStep([`call-${index}`])] as const, + [ + 2 + index * 2, + 127, + invokeStep({ + callId: `call-${index}`, + launches: [launch], + children: [{ id: CHILD, logUri }], + }), + ] as const, + ]), + ], + }); + const children = yield* read(profile, `${ROOT}:201`); + expect(children.map((child) => child.role)).toEqual(["Reader 201"]); + }), + ); + + it.effect("needs proof that the call id belongs to the parent's record", () => + Effect.gen(function* () { + const empty = new Uint8Array(); + // Planners with thinking take an index too: steps 0-2, 4-7 number 0-6. + const { profile } = yield* makeProfile({ + steps: (logUri) => [ + [0, 14, empty], + [1, 15, plannerResponse({ thinking: "Look first", calls: [["v1", "view_file"]] })], + [2, 8, empty], + [3, 15, plannerResponse({ calls: [["v2", "view_file"]] })], + [4, 8, empty], + [ + 5, + 15, + plannerResponse({ + thinking: "Delegate", + calls: [ + ["v3", "view_file"], + ["call-a", "invoke_subagent"], + ], + }), ], + [6, 8, empty], [ 7, 127, - invokeStep({ callId: "call-c", launches: [LAUNCH], children: [{ id: CHILD, logUri }] }), + invokeStep({ callId: "call-a", launches: [LAUNCH], children: [{ id: CHILD, logUri }] }), ], ], }); - // Another session's id, a step that is not the planner call, and parallel calls that share one id. - expect(yield* read(profile, `00000000-0000-4000-8000-000000000000:1`)).toEqual([]); - expect(yield* read(profile, `${ROOT}:2`)).toEqual([]); + expect(yield* read(profile, `${ROOT}:6`)).toHaveLength(1); + // Another session's id, a step that ran another tool, and a step past the end. + expect(yield* read(profile, `00000000-0000-4000-8000-000000000000:6`)).toEqual([]); expect(yield* read(profile, `${ROOT}:5`)).toEqual([]); + expect(yield* read(profile, `${ROOT}:7`)).toEqual([]); + }), + ); + + it.effect("declines an auto-approved id when a planner below it is unreadable", () => + Effect.gen(function* () { + // That planner may or may not take an index, so the record is at `:1` or `:2`. + for (const planner of [Uint8Array.from([0xff, 0xff]), new Uint8Array(1024 * 1024 + 1)]) { + const { profile } = yield* makeProfile({ + steps: (logUri) => [ + [0, 14, new Uint8Array()], + [1, 15, planner], + [2, 15, plannerStep(["call-a"])], + [ + 3, + 127, + invokeStep({ + callId: "call-a", + launches: [LAUNCH], + children: [{ id: CHILD, logUri }], + }), + ], + ], + }); + expect(yield* read(profile, `${ROOT}:1`)).toEqual([]); + expect(yield* read(profile, `${ROOT}:2`)).toEqual([]); + } }), ); @@ -166,14 +291,14 @@ it.layer(NodeServices.layer)("readAntigravityChildWork", (it) => { const launch = describeAntigravitySubagentLaunches([LAUNCH]); const opaque = "35bea692fa95447fbdae6333fec5515f"; expect(yield* read(profile, opaque, launch)).toHaveLength(1); - // An earlier auto-approved batch stored no launch text, but its planner step claims the record. + // An earlier auto-approved batch stored no launch text, but its call id claims the record. const auto = { nativeTaskId: `${ROOT}:1`, title: ANTIGRAVITY_SUBAGENT_BATCH_TITLE, prompt: "", }; expect(yield* read(profile, opaque, launch, [auto])).toEqual([]); - // A sibling that cannot be ruled out refuses the match: its planner step is unreadable, + // A sibling that cannot be ruled out refuses the match: its call id resolves to no record, // or it is a permission batch whose launch text is missing or cut. for (const sibling of [ { ...auto, nativeTaskId: `${ROOT}:99` }, diff --git a/apps/server/src/provider/acp/AntigravityChildWork.testkit.ts b/apps/server/src/provider/acp/AntigravityChildWork.testkit.ts index 82a2befbf6698..2a815149a84ca 100644 --- a/apps/server/src/provider/acp/AntigravityChildWork.testkit.ts +++ b/apps/server/src/provider/acp/AntigravityChildWork.testkit.ts @@ -25,7 +25,7 @@ const field = (number: number, value: string | Uint8Array) => { return [...varint(number * 8 + 2), ...varint(bytes.length), ...bytes]; }; const proto = (...parts: number[][]) => Uint8Array.from(parts.flat()); -const toolCall = (id: string) => proto(field(1, id), field(2, "invoke_subagent")); +const toolCall = (id: string, name = "invoke_subagent") => proto(field(1, id), field(2, name)); export const invokeStep = (input: { readonly callId: string; @@ -49,6 +49,22 @@ export const invokeStep = (input: { ); export const plannerStep = (callIds: ReadonlyArray) => proto(field(20, proto(...callIds.map((id) => field(7, toolCall(id)))))); +/** A planner message with response text (field 1) or thinking (field 3) besides its calls. */ +export const plannerResponse = (input: { + readonly text?: string; + readonly thinking?: string; + readonly calls: ReadonlyArray; +}) => + proto( + field( + 20, + proto( + input.text === undefined ? [] : field(1, input.text), + input.thinking === undefined ? [] : field(3, input.thinking), + ...input.calls.map(([id, name]) => field(7, toolCall(id, name))), + ), + ), + ); export const transcriptLines = [ // Trimmed from 1.4.5: the launch envelope around the prompt the parent record already holds. diff --git a/apps/server/src/provider/acp/AntigravityChildWork.ts b/apps/server/src/provider/acp/AntigravityChildWork.ts index 554e419421f6c..0c5a1c723ef8e 100644 --- a/apps/server/src/provider/acp/AntigravityChildWork.ts +++ b/apps/server/src/provider/acp/AntigravityChildWork.ts @@ -17,19 +17,22 @@ import { antigravityManagedPath, antigravityProfileRoot } from "./AntigravityPro import { boundAntigravityToolText, isCutAntigravityToolText } from "./AntigravityProtocol.ts"; // Field numbers from the runtime's trajectory protos (exa.cortex_pb). -const STEP_METADATA = 5; -const METADATA_TOOL_CALL = 4; const STEP_PLANNER_RESPONSE = 20; -const PLANNER_TOOL_CALLS = 7; +const PLANNER_TEXT = 1; +const PLANNER_THINKING = 3; const STEP_INVOKE_SUBAGENT = 143; const INVOKE_SPECS = 9; const INVOKE_RESULTS = 10; const INVOKE_SUBAGENT_STEP_TYPE = 127; +const PLANNER_RESPONSE_STEP_TYPE = 15; // One open reads at most this much; past any bound the batch view stays as it was. const MAX_STEP_BYTES = 1024 * 1024; const MAX_INVOKE_ROWS = 200; const MAX_SCAN_BYTES = 8 * 1024 * 1024; +// Numbering an auto-approved id reads the planner steps below its record. +const MAX_PLANNER_ROWS = 2_000; +const MAX_PLANNER_BYTES = 32 * 1024 * 1024; const MAX_CHILDREN = 16; const TRANSCRIPT_BYTE_CAP = 256 * 1024; const BATCH_TRANSCRIPT_BYTES = 512 * 1024; @@ -123,7 +126,6 @@ const text = (bytes: Uint8Array | undefined, field: number) => { }; interface InvokeRecord { - readonly toolCallId: string | undefined; readonly launches: ReadonlyArray; readonly children: ReadonlyArray<{ readonly conversationId: string; @@ -153,7 +155,6 @@ const decodeInvokeRecord = safely((payload): InvokeRecord | undefined => { })); if (!children.every((child) => NATIVE_ID.test(child.conversationId))) return undefined; return { - toolCallId: text(message(message(payload, STEP_METADATA), METADATA_TOOL_CALL), 1), launches: messages(invoke, INVOKE_SPECS).map((spec) => ({ role: text(spec, 2) ?? "", prompt: text(spec, 3) ?? "", @@ -162,13 +163,13 @@ const decodeInvokeRecord = safely((payload): InvokeRecord | undefined => { }; }); -const plannerInvokeCallIds = safely((payload): ReadonlyArray => { +/** The runtime gives no step index to a planner response with neither text nor thinking. */ +const plannerTakesIndex = safely((payload): boolean | undefined => { const planner = message(payload, STEP_PLANNER_RESPONSE); - if (planner === undefined) return []; - return messages(planner, PLANNER_TOOL_CALLS).flatMap((call) => { - const id = text(call, 1); - return text(call, 2) === "invoke_subagent" && id !== undefined ? [id] : []; - }); + if (planner === undefined) return undefined; + return [PLANNER_TEXT, PLANNER_THINKING].some( + (field) => (message(planner, field)?.length ?? 0) > 0, + ); }); const payloadOf = (row: unknown) => @@ -184,21 +185,64 @@ interface BatchLaunch { readonly prompt: string; } -const plannerCallIdsAt = (database: NodeSqlite.DatabaseSync, plannerIdx: number) => { - const planner = payloadOf( +/** + * Maps runtime step indexes to the idx of the invoke record that ran there. Steps take indexes in + * idx order, except planner responses with neither text nor thinking; an unreadable planner below + * leaves the numbering unproven, so the result is undefined. + */ +function invokeIdxAtStepIndex( + database: NodeSqlite.DatabaseSync, + stepIndexes: ReadonlySet, +): ReadonlyMap | undefined { + const found = new Map(); + const last = Math.max(...stepIndexes); + let skipped = 0; + let planners = 0; + let plannerBytes = 0; + for (const row of database + .prepare( + // SQLite returns only in-bound planner payloads, so an oversized row never reaches this process. + "SELECT idx, step_type, step_format, length(step_payload) AS size, CASE WHEN step_type = ? AND length(step_payload) <= ? THEN step_payload END AS step_payload FROM steps WHERE step_type IN (?, ?) ORDER BY idx", + ) + .iterate( + PLANNER_RESPONSE_STEP_TYPE, + MAX_STEP_BYTES, + PLANNER_RESPONSE_STEP_TYPE, + INVOKE_SUBAGENT_STEP_TYPE, + )) { + const idx = Number(row.idx); + if (row.step_type === INVOKE_SUBAGENT_STEP_TYPE) { + const stepIndex = idx - skipped; + if (stepIndexes.has(stepIndex)) found.set(stepIndex, idx); + if (stepIndex >= last) break; + continue; + } + planners += 1; + plannerBytes += Number(row.size ?? 0); + if (planners > MAX_PLANNER_ROWS || plannerBytes > MAX_PLANNER_BYTES) return undefined; + const payload = row.step_format === 0 ? payloadOf(row) : undefined; + const takesIndex = payload === undefined ? undefined : plannerTakesIndex(payload); + if (takesIndex === undefined) return undefined; + if (!takesIndex) skipped += 1; + } + return found; +} + +const invokeRecordAt = (database: NodeSqlite.DatabaseSync, idx: number) => { + const payload = payloadOf( database .prepare( - "SELECT step_payload FROM steps WHERE idx = ? AND step_format = 0 AND length(step_payload) <= ?", + "SELECT step_payload FROM steps WHERE idx = ? AND step_type = ? AND step_format = 0 AND length(step_payload) <= ?", ) - .get(plannerIdx, MAX_STEP_BYTES), + .get(idx, INVOKE_SUBAGENT_STEP_TYPE, MAX_STEP_BYTES), ); - return planner === undefined ? undefined : plannerInvokeCallIds(planner); + return payload === undefined ? undefined : decodeInvokeRecord(payload); }; /** - * Auto-approved calls carry `:`; the record with that planner call's id - * is the proof. Permission prompts carry a random id, so the launch text must match one record - * no auto-approved sibling claims, and no sibling may share the text. + * Auto-approved calls carry `:`, the runtime's index of the step that ran the call, + * so the record at that index is the proof. Permission prompts carry a random id, so the launch + * text must match one record no auto-approved sibling claims, and no sibling may share the text. */ function findInvokeRecord( database: NodeSqlite.DatabaseSync, @@ -209,35 +253,16 @@ function findInvokeRecord( readonly siblings: ReadonlyArray; }, ): InvokeRecord | undefined { - const plannerIdxOf = (nativeTaskId: string) => { + const stepIndexOf = (nativeTaskId: string) => { const stepId = /^(.+):(\d+)$/.exec(nativeTaskId); return stepId === null ? undefined : stepId[1] === input.rootSessionId ? Number(stepId[2]) : -1; }; - const plannerIdx = plannerIdxOf(input.nativeTaskId); - if (plannerIdx !== undefined) { - if (plannerIdx < 0) return undefined; - const callIds = plannerCallIdsAt(database, plannerIdx) ?? []; - const [callId] = callIds; - if (callIds.length !== 1) return undefined; - // The record follows the planner step that issued the call. - let rows = 0; - let bytes = 0; - for (const row of database - .prepare( - // SQLite returns only in-bound payloads, so an oversized row never reaches this process. - "SELECT length(step_payload) AS size, CASE WHEN length(step_payload) <= ? THEN step_payload END AS step_payload FROM steps WHERE step_type = ? AND step_format = 0 AND idx > ? ORDER BY idx", - ) - .iterate(MAX_STEP_BYTES, INVOKE_SUBAGENT_STEP_TYPE, plannerIdx)) { - const size = row !== null && typeof row === "object" && "size" in row ? Number(row.size) : 0; - rows += 1; - bytes += size; - if (rows > MAX_INVOKE_ROWS || size > MAX_STEP_BYTES || bytes > MAX_SCAN_BYTES) - return undefined; - const payload = payloadOf(row); - const record = payload === undefined ? undefined : decodeInvokeRecord(payload); - if (record !== undefined && record.toolCallId === callId) return complete(record); - } - return undefined; + const stepIndex = stepIndexOf(input.nativeTaskId); + if (stepIndex !== undefined) { + if (stepIndex < 0) return undefined; + const idx = invokeIdxAtStepIndex(database, new Set([stepIndex]))?.get(stepIndex); + const record = idx === undefined ? undefined : invokeRecordAt(database, idx); + return record === undefined ? undefined : complete(record); } const totals = database .prepare( @@ -257,12 +282,12 @@ function findInvokeRecord( ) { return undefined; } - const claimed = new Set(); + const siblingStepIndexes = new Set(); for (const sibling of input.siblings) { - const idx = plannerIdxOf(sibling.nativeTaskId); - // A sibling whose launch text is missing, or cut under the same roles, or whose planner step - // is unreadable, cannot be ruled out. - if (idx === undefined) { + const siblingStepIndex = stepIndexOf(sibling.nativeTaskId); + // A sibling whose launch text is missing, or cut under the same roles, or whose step does not + // resolve to a record, cannot be ruled out. + if (siblingStepIndex === undefined) { if ( sibling.title === ANTIGRAVITY_SUBAGENT_BATCH_TITLE || (sibling.title !== null && isCutAntigravityToolText(sibling.title)) || @@ -272,20 +297,23 @@ function findInvokeRecord( return undefined; continue; } - if (idx < 0) continue; - const callIds = plannerCallIdsAt(database, idx); - if (callIds === undefined || callIds.length === 0) return undefined; - for (const callId of callIds) claimed.add(callId); + if (siblingStepIndex >= 0) siblingStepIndexes.add(siblingStepIndex); } + const claimedIdx = + siblingStepIndexes.size === 0 + ? new Map() + : invokeIdxAtStepIndex(database, siblingStepIndexes); + if (claimedIdx === undefined || claimedIdx.size !== siblingStepIndexes.size) return undefined; + const claimed = new Set(claimedIdx.values()); const matches: Array = []; for (const row of database - .prepare("SELECT step_payload FROM steps WHERE step_type = ? ORDER BY idx") + .prepare("SELECT idx, step_payload FROM steps WHERE step_type = ? ORDER BY idx") .iterate(INVOKE_SUBAGENT_STEP_TYPE)) { const payload = payloadOf(row); const record = payload === undefined ? undefined : decodeInvokeRecord(payload); // An unreadable record could be an identical launch, so uniqueness is unproven. if (record === undefined) return undefined; - if (record.toolCallId !== undefined && claimed.has(record.toolCallId)) continue; + if (claimed.has(Number(row.idx))) continue; // T3 stored the launch from the bounded tool payload, so bound the record the same way. const described = describeAntigravitySubagentLaunches( record.launches.map((launch) => ({ @@ -630,7 +658,6 @@ async function findDetachedInvokeRecord( : Option.getOrUndefined(decodeArgument(argumentsJson)); const [fromArgs] = antigravitySubagentLaunches(parsedArgs) ?? []; matches.push({ - toolCallId: nativeTaskId, launches: [ fromArgs ?? { role: subagent.subagentDescriptor?.role ?? "", From 739e0a5e4f5a5951fe0423df170499ed22c5caca Mon Sep 17 00:00:00 2001 From: Ajraba04 <143622128+Ajraba04@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:48:33 +0900 Subject: [PATCH 09/21] fix(web,mobile): Usage says when Antigravity subagent calls are left out (#31381) Upstream PR: https://github.com/pingdotgg/t3code/pull/31381 --- apps/mobile/src/features/usage/UsageRouteScreen.tsx | 8 ++++++++ apps/mobile/src/i18n/translations/de.json | 3 ++- apps/mobile/src/i18n/translations/en.json | 3 ++- apps/mobile/src/i18n/translations/es.json | 3 ++- apps/mobile/src/i18n/translations/fr.json | 3 ++- apps/mobile/src/i18n/translations/ja.json | 3 ++- apps/mobile/src/i18n/translations/ko.json | 3 ++- apps/mobile/src/i18n/translations/pt-BR.json | 3 ++- apps/mobile/src/i18n/translations/ru.json | 3 ++- apps/mobile/src/i18n/translations/sv.json | 3 ++- apps/mobile/src/i18n/translations/zh.json | 3 ++- apps/web/src/components/usage/UsagePage.tsx | 6 ++++++ apps/web/src/i18n/translations/de.json | 3 ++- apps/web/src/i18n/translations/en.json | 3 ++- apps/web/src/i18n/translations/es.json | 3 ++- apps/web/src/i18n/translations/fr.json | 3 ++- apps/web/src/i18n/translations/ja.json | 3 ++- apps/web/src/i18n/translations/ko.json | 3 ++- apps/web/src/i18n/translations/pt-BR.json | 3 ++- apps/web/src/i18n/translations/ru.json | 3 ++- apps/web/src/i18n/translations/sv.json | 3 ++- apps/web/src/i18n/translations/zh.json | 3 ++- docs/user/usage.md | 3 ++- 23 files changed, 56 insertions(+), 21 deletions(-) diff --git a/apps/mobile/src/features/usage/UsageRouteScreen.tsx b/apps/mobile/src/features/usage/UsageRouteScreen.tsx index 48215804ee2dc..a2906e8c43265 100644 --- a/apps/mobile/src/features/usage/UsageRouteScreen.tsx +++ b/apps/mobile/src/features/usage/UsageRouteScreen.tsx @@ -707,6 +707,14 @@ function TotalsSection(props: { })} /> + {merged.providers.some( + ({ costUsd, provider, totalTokens }) => + provider === "antigravity" && (totalTokens > 0 || costUsd > 0), + ) ? ( + + Antigravity totals leave out subagent calls recorded only in transcripts. + + ) : null} ); } diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index cabb9a34dbe9a..0ac4bdfdff108 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -5301,5 +5301,6 @@ "ad208e3e32c85029": "Alle ausblenden", "3328503592789bed": "Zen", "856812e7e1fc445e": "Tool-Aufrufe im Chat", - "8d545d54c0a9e950": "Die Befehle, Bearbeitungen und Suchen ausblenden, die Agenten ausführen. „Erfolgreiche ausblenden“ behält Fehler. „Zen“ zeigt nur endgültige Antworten. Genehmigungen, Fragen und Fehler werden immer angezeigt." + "8d545d54c0a9e950": "Die Befehle, Bearbeitungen und Suchen ausblenden, die Agenten ausführen. „Erfolgreiche ausblenden“ behält Fehler. „Zen“ zeigt nur endgültige Antworten. Genehmigungen, Fragen und Fehler werden immer angezeigt.", + "1e4248d235c665e5": "Antigravity-Summen lassen Subagent-Aufrufe aus, die nur in Transkripten erfasst sind." } diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index fa572328fc871..d9e41442afe03 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -5302,5 +5302,6 @@ "ad208e3e32c85029": "Hide all", "3328503592789bed": "Zen", "856812e7e1fc445e": "Tool calls in chat", - "8d545d54c0a9e950": "Hide the commands, edits, and searches agents run. Hide successful keeps failures. Zen shows only final answers. Approvals, questions, and errors always show." + "8d545d54c0a9e950": "Hide the commands, edits, and searches agents run. Hide successful keeps failures. Zen shows only final answers. Approvals, questions, and errors always show.", + "1e4248d235c665e5": "Antigravity totals leave out subagent calls recorded only in transcripts." } diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index aaeb8230bc83e..7c9cd474da858 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -5295,5 +5295,6 @@ "ad208e3e32c85029": "Ocultar todo", "3328503592789bed": "Zen", "856812e7e1fc445e": "Llamadas a herramientas en el chat", - "8d545d54c0a9e950": "Oculta los comandos, ediciones y búsquedas que ejecutan los agentes. Ocultar las correctas mantiene los fallos. Zen solo muestra las respuestas finales. Las aprobaciones, preguntas y errores siempre se muestran." + "8d545d54c0a9e950": "Oculta los comandos, ediciones y búsquedas que ejecutan los agentes. Ocultar las correctas mantiene los fallos. Zen solo muestra las respuestas finales. Las aprobaciones, preguntas y errores siempre se muestran.", + "1e4248d235c665e5": "Los totales de Antigravity omiten las llamadas a subagentes registradas solo en las transcripciones." } diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 371ab3d7532dd..a79259698d293 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -5295,5 +5295,6 @@ "ad208e3e32c85029": "Tout masquer", "3328503592789bed": "Zen", "856812e7e1fc445e": "Appels d’outils dans la discussion", - "8d545d54c0a9e950": "Masque les commandes, modifications et recherches lancées par les agents. Masquer les réussis garde les échecs. Zen n’affiche que les réponses finales. Les approbations, questions et erreurs s’affichent toujours." + "8d545d54c0a9e950": "Masque les commandes, modifications et recherches lancées par les agents. Masquer les réussis garde les échecs. Zen n’affiche que les réponses finales. Les approbations, questions et erreurs s’affichent toujours.", + "1e4248d235c665e5": "Les totaux d'Antigravity omettent les appels de sous-agents enregistrés uniquement dans les transcriptions." } diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 32b5c4d8f9748..b887bf5b0531c 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -5277,5 +5277,6 @@ "ad208e3e32c85029": "すべて非表示", "3328503592789bed": "Zen", "856812e7e1fc445e": "チャット内のツール呼び出し", - "8d545d54c0a9e950": "エージェントが実行するコマンド、編集、検索を非表示にします。「成功したものを非表示」では失敗は表示されます。Zen では最終的な回答だけを表示します。承認、質問、エラーは常に表示されます。" + "8d545d54c0a9e950": "エージェントが実行するコマンド、編集、検索を非表示にします。「成功したものを非表示」では失敗は表示されます。Zen では最終的な回答だけを表示します。承認、質問、エラーは常に表示されます。", + "1e4248d235c665e5": "Antigravity の合計には、トランスクリプトにのみ記録されたサブエージェント呼び出しは含まれません。" } diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 0cd8713696dc5..ffadf99a1dc5e 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -5281,5 +5281,6 @@ "ad208e3e32c85029": "모두 숨기기", "3328503592789bed": "Zen", "856812e7e1fc445e": "채팅의 도구 호출", - "8d545d54c0a9e950": "에이전트가 실행하는 명령, 편집, 검색을 숨깁니다. 성공한 항목 숨기기는 실패를 남겨 둡니다. Zen은 최종 답변만 표시합니다. 승인, 질문, 오류는 항상 표시됩니다." + "8d545d54c0a9e950": "에이전트가 실행하는 명령, 편집, 검색을 숨깁니다. 성공한 항목 숨기기는 실패를 남겨 둡니다. Zen은 최종 답변만 표시합니다. 승인, 질문, 오류는 항상 표시됩니다.", + "1e4248d235c665e5": "Antigravity 합계에는 트랜스크립트에만 기록된 서브에이전트 호출이 빠져 있습니다." } diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index caac483484c2e..d86e9db85c61f 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -5295,5 +5295,6 @@ "ad208e3e32c85029": "Ocultar todas", "3328503592789bed": "Zen", "856812e7e1fc445e": "Chamadas de ferramentas no chat", - "8d545d54c0a9e950": "Oculta os comandos, edições e pesquisas que os agentes executam. \"Ocultar bem-sucedidas\" mantém as falhas. Zen mostra só as respostas finais. Aprovações, perguntas e erros sempre aparecem." + "8d545d54c0a9e950": "Oculta os comandos, edições e pesquisas que os agentes executam. \"Ocultar bem-sucedidas\" mantém as falhas. Zen mostra só as respostas finais. Aprovações, perguntas e erros sempre aparecem.", + "1e4248d235c665e5": "Os totais do Antigravity deixam de fora chamadas de subagentes registradas apenas nas transcrições." } diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index d5439f9698130..8f074d878cca1 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -5375,5 +5375,6 @@ "ad208e3e32c85029": "Скрывать все", "3328503592789bed": "Дзен", "856812e7e1fc445e": "Вызовы инструментов в чате", - "8d545d54c0a9e950": "Скрывать команды, правки и поиски, которые выполняют агенты. «Скрывать успешные» оставляет ошибки. «Дзен» показывает только итоговые ответы. Запросы подтверждения, вопросы и ошибки показываются всегда." + "8d545d54c0a9e950": "Скрывать команды, правки и поиски, которые выполняют агенты. «Скрывать успешные» оставляет ошибки. «Дзен» показывает только итоговые ответы. Запросы подтверждения, вопросы и ошибки показываются всегда.", + "1e4248d235c665e5": "Итоги Antigravity не учитывают вызовы субагентов, записанные только в транскриптах." } diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 7a634bcab134f..cd25396d736f8 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -5301,5 +5301,6 @@ "ad208e3e32c85029": "Dölj alla", "3328503592789bed": "Zen", "856812e7e1fc445e": "Verktygsanrop i chatten", - "8d545d54c0a9e950": "Dölj kommandon, redigeringar och sökningar som agenter kör. Dölj lyckade behåller misslyckanden. Zen visar bara slutliga svar. Godkännanden, frågor och fel visas alltid." + "8d545d54c0a9e950": "Dölj kommandon, redigeringar och sökningar som agenter kör. Dölj lyckade behåller misslyckanden. Zen visar bara slutliga svar. Godkännanden, frågor och fel visas alltid.", + "1e4248d235c665e5": "Antigravitys summor utelämnar subagentanrop som bara finns i transkript." } diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 98b946c76f028..dca8dbde3e8ba 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -5286,5 +5286,6 @@ "ad208e3e32c85029": "全部隐藏", "3328503592789bed": "专注模式", "856812e7e1fc445e": "聊天中的工具调用", - "8d545d54c0a9e950": "隐藏智能体执行的命令、编辑和搜索。“隐藏成功的调用”仍保留失败项;“专注模式”仅显示最终回答。审批、提问和错误始终显示。" + "8d545d54c0a9e950": "隐藏智能体执行的命令、编辑和搜索。“隐藏成功的调用”仍保留失败项;“专注模式”仅显示最终回答。审批、提问和错误始终显示。", + "1e4248d235c665e5": "Antigravity 总计未包含仅记录在对话记录中的子代理调用。" } diff --git a/apps/web/src/components/usage/UsagePage.tsx b/apps/web/src/components/usage/UsagePage.tsx index adb05afb92ebb..191d56cf43dde 100644 --- a/apps/web/src/components/usage/UsagePage.tsx +++ b/apps/web/src/components/usage/UsagePage.tsx @@ -721,6 +721,12 @@ function UsageOverview({

+ {providersWithData.has("antigravity") ? ( +

+ Antigravity totals leave out subagent calls recorded only in transcripts. +

+ ) : null} + {showChatGptSharing ? (
diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 46df7424ab0f2..cb336c26358ff 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -12140,5 +12140,6 @@ "27d76249d09eb69f": "Review-Leitfaden bereit", "faa3bb26abb39c93": "Review-Leitfaden fehlgeschlagen", "b7df38b7d8792d78": "Leitfaden öffnen", - "9e91e9a77b664e4e": "Review-Leitfaden konnte nicht gestartet werden" + "9e91e9a77b664e4e": "Review-Leitfaden konnte nicht gestartet werden", + "1e4248d235c665e5": "Antigravity-Summen lassen Subagent-Aufrufe aus, die nur in Transkripten erfasst sind." } diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index fc971dba6e051..fe7557871bef7 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -12149,5 +12149,6 @@ "27d76249d09eb69f": "Review guide ready", "faa3bb26abb39c93": "Review guide failed", "b7df38b7d8792d78": "Open guide", - "9e91e9a77b664e4e": "Could not start a review guide" + "9e91e9a77b664e4e": "Could not start a review guide", + "1e4248d235c665e5": "Antigravity totals leave out subagent calls recorded only in transcripts." } diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 797888016bd4a..81f3ef513e584 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -12135,5 +12135,6 @@ "27d76249d09eb69f": "Guía de revisión lista", "faa3bb26abb39c93": "Falló la guía de revisión", "b7df38b7d8792d78": "Abrir guía", - "9e91e9a77b664e4e": "No se pudo iniciar una guía de revisión" + "9e91e9a77b664e4e": "No se pudo iniciar una guía de revisión", + "1e4248d235c665e5": "Los totales de Antigravity omiten las llamadas a subagentes registradas solo en las transcripciones." } diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index e06cde54989bd..3d855082c88bd 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -12140,5 +12140,6 @@ "27d76249d09eb69f": "Guide de revue prêt", "faa3bb26abb39c93": "Échec du guide de revue", "b7df38b7d8792d78": "Ouvrir le guide", - "9e91e9a77b664e4e": "Impossible de démarrer un guide de revue" + "9e91e9a77b664e4e": "Impossible de démarrer un guide de revue", + "1e4248d235c665e5": "Les totaux d'Antigravity omettent les appels de sous-agents enregistrés uniquement dans les transcriptions." } diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 4473bff3ddef1..7902a28eac9cf 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -12088,5 +12088,6 @@ "27d76249d09eb69f": "レビューガイドの準備ができました", "faa3bb26abb39c93": "レビューガイドの作成に失敗しました", "b7df38b7d8792d78": "ガイドを開く", - "9e91e9a77b664e4e": "レビューガイドを開始できませんでした" + "9e91e9a77b664e4e": "レビューガイドを開始できませんでした", + "1e4248d235c665e5": "Antigravity の合計には、トランスクリプトにのみ記録されたサブエージェント呼び出しは含まれません。" } diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 68f0b20794362..db0ba747ce173 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -12084,5 +12084,6 @@ "27d76249d09eb69f": "검토 가이드 준비됨", "faa3bb26abb39c93": "검토 가이드 실패", "b7df38b7d8792d78": "가이드 열기", - "9e91e9a77b664e4e": "검토 가이드를 시작할 수 없습니다" + "9e91e9a77b664e4e": "검토 가이드를 시작할 수 없습니다", + "1e4248d235c665e5": "Antigravity 합계에는 트랜스크립트에만 기록된 서브에이전트 호출이 빠져 있습니다." } diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 5a18a359ecb2a..bd779dc4f2402 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -12139,5 +12139,6 @@ "27d76249d09eb69f": "Guia de revisão pronto", "faa3bb26abb39c93": "O guia de revisão falhou", "b7df38b7d8792d78": "Abrir guia", - "9e91e9a77b664e4e": "Não foi possível iniciar um guia de revisão" + "9e91e9a77b664e4e": "Não foi possível iniciar um guia de revisão", + "1e4248d235c665e5": "Os totais do Antigravity deixam de fora chamadas de subagentes registradas apenas nas transcrições." } diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 6c7fa00a15455..02acb10a838f4 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -12139,5 +12139,6 @@ "27d76249d09eb69f": "Гид по ревью готов", "faa3bb26abb39c93": "Не удалось создать гид по ревью", "b7df38b7d8792d78": "Открыть гид", - "9e91e9a77b664e4e": "Не удалось запустить гид по ревью" + "9e91e9a77b664e4e": "Не удалось запустить гид по ревью", + "1e4248d235c665e5": "Итоги Antigravity не учитывают вызовы субагентов, записанные только в транскриптах." } diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index d02de62557d73..bb7967c1a3629 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -12147,5 +12147,6 @@ "27d76249d09eb69f": "Granskningsguiden är klar", "faa3bb26abb39c93": "Granskningsguiden misslyckades", "b7df38b7d8792d78": "Öppna guiden", - "9e91e9a77b664e4e": "Kunde inte starta en granskningsguide" + "9e91e9a77b664e4e": "Kunde inte starta en granskningsguide", + "1e4248d235c665e5": "Antigravitys summor utelämnar subagentanrop som bara finns i transkript." } diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index acf5ce3045376..004cfcb900a66 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -12165,5 +12165,6 @@ "27d76249d09eb69f": "审查导览已就绪", "faa3bb26abb39c93": "审查导览生成失败", "b7df38b7d8792d78": "打开导览", - "9e91e9a77b664e4e": "无法开始生成审查导览" + "9e91e9a77b664e4e": "无法开始生成审查导览", + "1e4248d235c665e5": "Antigravity 总计未包含仅记录在对话记录中的子代理调用。" } diff --git a/docs/user/usage.md b/docs/user/usage.md index 5160becc21567..da940e06715b4 100644 --- a/docs/user/usage.md +++ b/docs/user/usage.md @@ -28,7 +28,8 @@ prunes older history on the next refresh, and raising it again does not bring pr While `settings.json` cannot be read, nothing is pruned. OpenCode reads its SQLite database and older JSON history. Antigravity reads local conversation -databases, including T3-managed profiles. Set `OPENCODE_DATA_DIR` or `ANTIGRAVITY_DATA_DIR` on the +databases, including T3-managed profiles. A subagent recorded only in a transcript, with no +conversation database of its own, is missing from the Antigravity totals. Set `OPENCODE_DATA_DIR` or `ANTIGRAVITY_DATA_DIR` on the server to read a different data directory; comma-separated paths read multiple directories. Cursor reads account usage from Cursor's API for the account you signed in with in T3 or set as From fa19a00f731a7a647888216da63a124ea0e52991 Mon Sep 17 00:00:00 2001 From: Lakshmi Tanmay Date: Mon, 16 Nov 2026 10:50:43 +0900 Subject: [PATCH 10/21] fix(server): load Antigravity project and global rules (#29197) Upstream PR: https://github.com/pingdotgg/t3code/pull/29197 --- .../Adapters/AntigravityAdapterV2.test.ts | 31 +++++++++- .../Adapters/AntigravityAdapterV2.ts | 60 ++++++++++++++++++- .../src/provider/Drivers/AntigravityDriver.ts | 1 + 3 files changed, 88 insertions(+), 4 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 93182347e512a..27307c9bad0aa 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -49,6 +49,7 @@ import { } from "./AntigravityAdapterV2.ts"; const flavor = makeAntigravityAcpAdapterFlavor({ + userHome: process.cwd(), instanceId: ProviderInstanceId.make("antigravity-test"), random: undefined as never, fileSystem: undefined as never, @@ -117,6 +118,9 @@ describe("AntigravityAdapterV2 flavor", () => { it.effect("answers Auto as Supervised only in a session that offers no automatic review", () => Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const userHome = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-ag-auto-home-" }); const modes = (ids: ReadonlyArray) => ({ currentModeId: "default", availableModes: ids.map((id) => ({ id, name: id })), @@ -127,9 +131,10 @@ describe("AntigravityAdapterV2 flavor", () => { }; const sessions = makeAntigravityAcpAdapterFlavor({ instanceId: ProviderInstanceId.make("antigravity-auto-test"), + userHome, random: undefined as never, - fileSystem: undefined as never, - path: undefined as never, + fileSystem, + path, host: { paths: { attachmentsDir: "/attachments" } } as never, selfInvocation: undefined as never, // The stub names each session after its workspace. @@ -243,6 +248,7 @@ describe("AntigravityAdapterV2 harness recovery", () => { const instanceId = ProviderInstanceId.make("antigravity-recovery-test"); const adapter = yield* makeAntigravityAdapterV2({ instanceId, + userHome: process.cwd(), selfInvocation: yield* resolveSelfInvocation(), makeRuntime: (input) => Effect.suspend(() => { @@ -399,6 +405,7 @@ describe("AntigravityAdapterV2 compaction", () => { readonly cwd: string; } | null>(null); const adapter = yield* makeAntigravityAdapterV2({ + userHome: process.cwd(), instanceId, selfInvocation: yield* resolveSelfInvocation(), makeRuntime: (input) => @@ -539,6 +546,7 @@ describe("AntigravityAdapterV2 session open", () => { Effect.gen(function* () { const instanceId = ProviderInstanceId.make("antigravity-sign-in-test"); const adapter = yield* makeAntigravityAdapterV2({ + userHome: process.cwd(), instanceId, selfInvocation: yield* resolveSelfInvocation(), makeRuntime: () => Effect.fail(cause), @@ -587,6 +595,7 @@ describe("AntigravityAdapterV2 client file system", () => { const crypto = yield* SecureRandom.SecureRandom; const instanceId = ProviderInstanceId.make("antigravity-containment-test"); const adapter = yield* makeAntigravityAdapterV2({ + userHome: process.cwd(), instanceId, selfInvocation: yield* resolveSelfInvocation(), makeRuntime: (input) => @@ -739,6 +748,7 @@ describe("AntigravityAdapterV2 workspace changes", () => { let readTextFile: Parameters[0] | undefined; const instanceId = ProviderInstanceId.make("antigravity-workspace-change-test"); const adapter = yield* makeAntigravityAdapterV2({ + userHome: process.cwd(), instanceId, selfInvocation: yield* resolveSelfInvocation(), makeRuntime: (input) => @@ -914,6 +924,7 @@ describe("AntigravityAdapterV2 html_render pages", () => { height: 411, }; const adapter = yield* makeAntigravityAdapterV2({ + userHome: process.cwd(), instanceId, selfInvocation: yield* resolveSelfInvocation(), makeRuntime: (input) => @@ -1221,6 +1232,7 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand") const threadId = ThreadId.make("thread-antigravity-wake"); const adapter = yield* makeAntigravityAdapterV2({ instanceId, + userHome: process.cwd(), selfInvocation: yield* resolveSelfInvocation(), continuationRequests: { offer: (request) => Effect.sync(() => void offers.push(request)) }, makeRuntime: (input) => { @@ -1638,6 +1650,7 @@ describe("AntigravityAdapterV2 subagent reads", () => { const instanceId = ProviderInstanceId.make("antigravity-subagent-reads-test"); const threadId = ThreadId.make("thread-antigravity-subagent-reads"); const adapter = yield* makeAntigravityAdapterV2({ + userHome: process.cwd(), instanceId, selfInvocation: yield* resolveSelfInvocation(), makeRuntime: (input) => @@ -1830,6 +1843,7 @@ describe("AntigravityAdapterV2 runtime mode ceiling", () => { const modesSet: Array = []; const instanceId = ProviderInstanceId.make("antigravity-ceiling-test"); const adapter = yield* makeAntigravityAdapterV2({ + userHome: process.cwd(), instanceId, selfInvocation: yield* resolveSelfInvocation(), makeRuntime: (input) => @@ -1900,8 +1914,10 @@ describe("AntigravityAdapterV2 session system prompt", () => { type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; const promptReceived = yield* Deferred.make[0]>(); const instanceId = ProviderInstanceId.make("antigravity-system-prompt-test"); + const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-ag-home-" }); const adapter = yield* makeAntigravityAdapterV2({ instanceId, + userHome: home, selfInvocation: yield* resolveSelfInvocation(), makeRuntime: (input) => makeAntigravityAcpRuntime({ @@ -1932,6 +1948,10 @@ describe("AntigravityAdapterV2 session system prompt", () => { defaultModel: Effect.undefined, }); const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-ag-sp-" }); + yield* fileSystem.makeDirectory(path.join(home, ".gemini")); + yield* fileSystem.writeFileString(path.join(home, ".gemini", "GEMINI.md"), "GLOBAL_RULE"); + yield* fileSystem.writeFileString(path.join(workspace, "AGENTS.md"), "AGENTS_RULE"); + yield* fileSystem.writeFileString(path.join(workspace, "GEMINI.md"), "GEMINI_RULE"); const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ runtimeMode: "full-access", interactionMode: "default", @@ -2005,10 +2025,15 @@ describe("AntigravityAdapterV2 session system prompt", () => { assert.include(sent, "through the Antigravity harness, as gemini-test-low"); if (agentVersion === "1.4.5") { assert.include(append, "pull_request_linking"); + assert.isBelow(append.indexOf("GLOBAL_RULE"), append.indexOf("AGENTS_RULE")); + assert.isBelow(append.indexOf("AGENTS_RULE"), append.indexOf("GEMINI_RULE")); + assert.notInclude(sent, "AGENTS_RULE"); assert.notInclude(sent, ""); } else { assert.notInclude(append, "systemPrompt"); assert.include(sent, ""); + assert.isBelow(sent.indexOf("GLOBAL_RULE"), sent.indexOf("AGENTS_RULE")); + assert.isBelow(sent.indexOf("AGENTS_RULE"), sent.indexOf("GEMINI_RULE")); } }).pipe(Effect.provide(layerSession)), ); @@ -2031,6 +2056,7 @@ describe("AntigravityAdapterV2 full-access restart", () => { const threadId = ThreadId.make("thread-antigravity-restart"); const adapter = yield* makeAntigravityAdapterV2({ instanceId, + userHome: process.cwd(), selfInvocation: yield* resolveSelfInvocation(), makeRuntime: (input) => Effect.sync(() => { @@ -2177,6 +2203,7 @@ describe("AntigravityAdapterV2 questions", () => { const threadId = ThreadId.make("thread-antigravity-ask-question"); const adapter = yield* makeAntigravityAdapterV2({ instanceId, + userHome: process.cwd(), selfInvocation: yield* resolveSelfInvocation(), makeRuntime: (input) => makeAntigravityAcpRuntime({ diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index acb532161116c..421aa9abeb87b 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -83,6 +83,7 @@ export type AntigravityAdapterV2RuntimeInput = Omit< export interface AntigravityAdapterV2Options { readonly instanceId: ProviderInstanceId; + readonly userHome: string; readonly selfInvocation: SelfInvocation; readonly makeRuntime: ( input: AntigravityAdapterV2RuntimeInput, @@ -135,6 +136,21 @@ const extractAntigravitySubagentUpdate: NonNullable[0]; + +// The ACP adapter resends runtime instructions on a session's first turn, after compaction and on +// change; rules follow them so the agent's history keeps one current copy. +const withTurnRules = (payload: PromptPayload, rules: string): PromptPayload => { + const index = payload.prompt.findIndex( + (block) => block.type === "text" && block.text.startsWith(""), + ); + return index === -1 + ? payload + : { ...payload, prompt: payload.prompt.toSpliced(index, 0, { type: "text", text: rules }) }; +}; + interface AntigravityFlavorServices { readonly random: SecureRandom.SecureRandom["Service"]; readonly fileSystem: FileSystem.FileSystem; @@ -150,8 +166,39 @@ export function makeAntigravityAcpAdapterFlavor( cwd === null ? [options.host.paths.attachmentsDir] : [cwd, options.host.paths.attachmentsDir]; // Gemini Enterprise and the 1.4 harness offer no `auto`; those sessions run Auto as Supervised. const sessionsWithoutAuto = new Set(); + // agy acp loads no rules files itself, so they ride the session system prompt append. + const readRulesFile = (filePath: string) => + options.fileSystem.stat(filePath).pipe( + Effect.flatMap((info) => + info.type === "File" && info.size <= RULES_FILE_MAX_BYTES + ? options.fileSystem.readFileString(filePath) + : Effect.logWarning("Skipping Antigravity rules file", { + filePath, + reason: `not a regular file of at most ${RULES_FILE_MAX_BYTES} bytes`, + }).pipe(Effect.as("")), + ), + Effect.catch((error) => + error.reason._tag === "NotFound" + ? Effect.succeed("") + : Effect.logWarning("Skipping Antigravity rules file", { filePath, error }).pipe( + Effect.as(""), + ), + ), + ); const makeRuntime = Effect.fn("AntigravityAdapterV2.makeRuntime")( function* (input: AcpAdapterV2RuntimeInput) { + const rules: Array = []; + for (const filePath of [ + options.path.join(options.userHome, ".gemini", "GEMINI.md"), + options.path.join(input.cwd, "AGENTS.md"), + options.path.join(input.cwd, "GEMINI.md"), + ]) { + const contents = yield* readRulesFile(filePath); + if (contents.trim()) rules.push(`# ${filePath}\n\n${contents}`); + } + const rulesText = rules.join("\n\n"); + // Set on start: whether this agent drops the system-prompt append, so rules ride the turns. + let rulesInTurns = false; const scope = yield* Scope.fork(yield* Effect.scope); const runtime = yield* options .withProcess( @@ -159,7 +206,7 @@ export function makeAntigravityAcpAdapterFlavor( options.makeRuntime({ ...input, clientFileReads: true, - sessionSystemPromptAppend: PULL_REQUEST_LINKING_INSTRUCTIONS, + sessionSystemPromptAppend: [...rules, PULL_REQUEST_LINKING_INSTRUCTIONS].join("\n\n"), additionalDirectories: [options.host.paths.attachmentsDir], }), ) @@ -193,7 +240,14 @@ export function makeAntigravityAcpAdapterFlavor( ), ), prompt: (payload, promptOptions) => - Effect.sync(reads.reset).pipe(Effect.andThen(runtime.prompt(payload, promptOptions))), + Effect.sync(reads.reset).pipe( + Effect.andThen( + runtime.prompt( + rulesInTurns ? withTurnRules(payload, rulesText) : payload, + promptOptions, + ), + ), + ), handleSessionUpdate: (handler) => { projectUpdate = handler; return runtime.handleSessionUpdate((notification) => @@ -203,6 +257,8 @@ export function makeAntigravityAcpAdapterFlavor( start: () => runtime.start().pipe( Effect.tap((started) => { + rulesInTurns = + rulesText !== "" && !antigravityAppendsSystemPrompt(started.initializeResult); if (antigravitySessionOffersAutoMode(started.sessionSetupResult)) return Effect.void; sessionsWithoutAuto.add(started.sessionId); return Scope.addFinalizer( diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.ts b/apps/server/src/provider/Drivers/AntigravityDriver.ts index 675f57b56585c..75f151926a26a 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.ts @@ -481,6 +481,7 @@ export const AntigravityDriver: ProviderDriver< const defaultModel = currentCatalog.pipe(Effect.map((catalog) => catalog?.defaultChatModel)); const orchestrationAdapter = yield* makeAntigravityAdapterV2({ instanceId, + userHome, selfInvocation, makeRuntime, withProcess: authFlow.withProcess, From 0d5533f9a8cb43ec7a51cddc6bf360dcfb3e4471 Mon Sep 17 00:00:00 2001 From: SeongHoon Ryu <4997174+ryush00@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:52:52 +0900 Subject: [PATCH 11/21] fix(antigravity): Auto no longer asks before every T3 Code tool call Antigravity's automatic review covers shell commands and edits but no MCP call, so in Auto it asked about each one. The adapter passed every Auto prompt to the user, on the assumption that a prompt is a review refusal. In two real Auto threads, 27 of 28 T3 Code tool calls asked, against 6 of 147 shell commands. Auto now answers prompts for T3 Code's own MCP tools itself, the same way Claude pre-approves them: the authenticated MCP endpoint already enforces their scope. Everything else the review refuses still reaches the user, as do other MCP servers' tools. Co-Authored-By: Claude Fable 5.2 --- .../acp/AntigravityAcpSupport.test.ts | 19 +++++++++++++++++ .../src/provider/acp/AntigravityAcpSupport.ts | 21 ++++++++++++++----- 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts index fe6211416013b..a0a0e63cfebe7 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts @@ -170,6 +170,25 @@ describe("Antigravity permission modes", () => { for (const kind of ["read", "edit", "execute"] as const) { expect(disposition(policy("auto"), request(kind), auto)).toBe("ask"); } + // agy reviews no MCP call, so T3's own tools are answered without a prompt. + const mcp = (title: string, kind: EffectAcpSchema.ToolKind = "other") => ({ + ...request(kind), + toolCall: { toolCallId: "tool-1", kind, title }, + }); + expect( + [ + "Run mcp_t3-code_t3_thread_read", + "Run mcp_t3-code_preview_snapshot?", + "Run mcp_t3-code_not_a_real_tool", + "Run mcp_github_t3_thread_read", + "Run mcp_t3-code_t3_thread_read && rm -rf /", + "t3_thread_read", + ].map((title) => disposition(policy("auto"), mcp(title), auto)), + ).toEqual(["allow", "allow", "ask", "ask", "ask", "ask"]); + expect(disposition(policy("auto"), mcp("Run mcp_t3-code_t3_thread_read"), noAuto)).toBe("ask"); + expect( + disposition(policy("approval-required"), mcp("Run mcp_t3-code_t3_thread_read"), auto), + ).toBe("ask"); // A session without `auto` stays in `default` and is answered as Supervised. expect( (["read", "edit", "execute"] as const).map((kind) => diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index 186948ce78d52..7e221d75b9113 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -7,6 +7,7 @@ import { type RuntimeMode, } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { T3_MCP_TOOL_NAMES } from "@t3tools/shared/t3McpToolPresentation"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -258,9 +259,19 @@ export function antigravityManagedSessionMode( return availableModeIds === undefined || availableModeIds.has(modeId) ? modeId : "default"; } +// agy 1.5.8 titles an MCP call "Run mcp__", with "?" on some prompts. +const T3_MCP_PERMISSION_TITLE = /^Run mcp_t3-code_(?[A-Za-z0-9_]+)\??$/; + +function isT3McpPermissionRequest(request: EffectAcpSchema.RequestPermissionRequest): boolean { + const tool = T3_MCP_PERMISSION_TITLE.exec(request.toolCall.title?.trim() ?? "")?.groups?.tool; + return tool !== undefined && T3_MCP_TOOL_NAMES.has(tool); +} + /** - * In `auto` the agent asks only about what its own review refused, so every prompt reaches the - * user. A session that offers no `auto` stays in `default` and is answered as Supervised. + * In `auto` the agent asks about what its own review refused, so those prompts reach the user. + * It reviews no MCP call and asks about each one; T3's own tools are answered here because the + * authenticated MCP endpoint already enforces their scope. A session that offers no `auto` stays + * in `default` and is answered as Supervised. */ export function antigravityPermissionDisposition( policy: AcpRuntimePolicy, @@ -269,9 +280,9 @@ export function antigravityPermissionDisposition( ): AcpPermissionDisposition { if (antigravityPermissionMode(policy) !== "auto") return acpPermissionDisposition(policy, request); - return session.offersAuto - ? "ask" - : acpPermissionDisposition({ ...policy, runtimeMode: "approval-required" }, request); + if (!session.offersAuto) + return acpPermissionDisposition({ ...policy, runtimeMode: "approval-required" }, request); + return isT3McpPermissionRequest(request) ? "allow" : "ask"; } export function antigravitySessionOffersAutoMode( From c45054e23c265cca32fcbe3f229803fcc4319351 Mon Sep 17 00:00:00 2001 From: SeongHoon Ryu <4997174+ryush00@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:57:23 +0900 Subject: [PATCH 12/21] fix(server): PR watches report reruns that fail again and failed runs another GitHub event hides (#32319) --- .../src/orchestration-v2/Orchestrator.ts | 3 + .../PullRequestWatchReactor.ts | 1 + .../orchestration-v2/pullRequestWatch.test.ts | 38 ++++++++++ .../src/orchestration-v2/pullRequestWatch.ts | 18 ++++- packages/contracts/src/threadPullRequest.ts | 2 + .../src/server/pullRequestChecks.test.ts | 15 ++++ .../src/server/pullRequestChecks.ts | 42 +++++++++-- .../src/server/GitHubPullRequestApi.test.ts | 8 ++- .../src/server/gitHubPullRequestJson.test.ts | 72 ++++++++++++++++++- .../src/server/gitHubPullRequestJson.ts | 12 +++- .../src/server/pullRequestReads.graphql | 1 + .../src/server/pullRequestReads.graphql.ts | 6 +- 12 files changed, 206 insertions(+), 12 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index c71addfa57c07..f2e870aa5e95c 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -5245,6 +5245,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio awaitingBaseline: existing.endedWatch ? existing.endedWatch.awaitingBaseline : "all", + ...(existing.endedWatch?.failedRuns !== undefined && { + failedRuns: existing.endedWatch.failedRuns, + }), ...(existing.endedWatch?.owedChecks !== undefined && { owedChecks: existing.endedWatch.owedChecks, }), diff --git a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts index 7590ee3c11b3e..c84cb3d577af6 100644 --- a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts +++ b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts @@ -216,6 +216,7 @@ function watchesEqual(left: ThreadPullRequestWatch, right: ThreadPullRequestWatc left.startedAt === right.startedAt && left.headSha === right.headSha && left.failedChecks.join("\n") === right.failedChecks.join("\n") && + left.failedRuns?.join("\n") === right.failedRuns?.join("\n") && left.passed === right.passed && left.passedChecks.join("\n") === right.passedChecks.join("\n") && (left.owedChecks ?? []).join("\n") === (right.owedChecks ?? []).join("\n") && diff --git a/apps/server/src/orchestration-v2/pullRequestWatch.test.ts b/apps/server/src/orchestration-v2/pullRequestWatch.test.ts index c0ab327d41af4..6b0afc5f3cc6c 100644 --- a/apps/server/src/orchestration-v2/pullRequestWatch.test.ts +++ b/apps/server/src/orchestration-v2/pullRequestWatch.test.ts @@ -481,6 +481,44 @@ describe("evaluatePullRequestWatch", () => { ]); }); + it("reports a rerun that fails again between two reads", () => { + const run = (job: number): PullRequestCheck => ({ + ...check("lint", "failure"), + url: `https://ci.example/lint/job/${job}`, + required: true, + }); + const first = evaluatePullRequestWatch(watch(), detail({ checks: [run(1)] }), noRemarks); + assert.deepEqual(first.changes, [{ kind: "checks-failed", failed: [run(1)] }]); + const again = evaluatePullRequestWatch(first.next, detail({ checks: [run(2)] }), noRemarks); + assert.deepEqual(again.changes, [{ kind: "checks-failed", failed: [run(2)] }]); + // A status can link a build shared with another check; it is that check's run, not lint's. + const shared = { ...check("test", "failure"), url: "https://ci.example/lint/job/3" }; + const both = evaluatePullRequestWatch( + again.next, + detail({ checks: [run(2), shared] }), + noRemarks, + ); + assert.deepEqual( + evaluatePullRequestWatch(both.next, detail({ checks: [run(3), shared] }), noRemarks).changes, + [{ kind: "checks-failed", failed: [run(3)] }], + ); + // Neither the same run nor one told earlier on this head is news again. + for (const job of [2, 1]) { + assert.deepEqual( + evaluatePullRequestWatch(again.next, detail({ checks: [run(job)] }), noRemarks).changes, + [], + ); + } + }); + + it("does not repeat a failure an older watch told by name", () => { + const older = watch({ headSha: "aaaaaaaaaa", failedChecks: ["lint"] }); + const failed = detail({ checks: [check("lint", "failure")] }); + const report = evaluatePullRequestWatch(older, failed, noRemarks); + assert.deepEqual(report.changes, []); + assert.deepEqual(report.next.failedRuns, [JSON.stringify(["lint", "https://ci.example/lint"])]); + }); + it("reports passed once the required checks pass, whatever the others do", () => { const required = (name: string, status: PullRequestCheck["status"]) => ({ ...check(name, status), diff --git a/apps/server/src/orchestration-v2/pullRequestWatch.ts b/apps/server/src/orchestration-v2/pullRequestWatch.ts index eedbe47d1a01f..3ca1661d91727 100644 --- a/apps/server/src/orchestration-v2/pullRequestWatch.ts +++ b/apps/server/src/orchestration-v2/pullRequestWatch.ts @@ -61,6 +61,7 @@ export function evaluatePullRequestWatch( // Hosts can return no checks on read failure; preserve prior state. let failedChecks = headMoved ? [] : watch.failedChecks; + let failedRuns = headMoved ? [] : watch.failedRuns; let passed = headMoved ? false : watch.passed; let passedChecks = headMoved ? [] : watch.passedChecks; let owedChecks = headMoved ? [] : (watch.owedChecks ?? []); @@ -77,7 +78,17 @@ export function evaluatePullRequestWatch( if (checks.length > 0) { // A run awaiting approval waits on a person, like a review, so only running checks count. checksPending = checks.some((check) => check.status === "pending"); - const newlyFailed = failed.filter((check) => !failedChecks.includes(check.name)); + // A new run URL under a failing name is a rerun that failed again between reads. + const toldRuns = failedRuns; + const runOf = (check: PullRequestCheck) => + check.url === null ? null : JSON.stringify([check.name, check.url]); + const newlyFailed = failed.filter((check) => { + const run = runOf(check); + return ( + !failedChecks.includes(check.name) || + (toldRuns !== undefined && run !== null && !toldRuns.includes(run)) + ); + }); if (!checksBaseline && newlyFailed.length > 0) { changes.push({ kind: "checks-failed", failed: newlyFailed }); } @@ -86,6 +97,10 @@ export function evaluatePullRequestWatch( approvalAnnounced = true; } failedChecks = failed.map((check) => check.name); + // Runs told stay told for the head: GitHub can show either event's failed run of one check. + failedRuns = [ + ...new Set([...(toldRuns ?? []), ...failed.flatMap((check) => runOf(check) ?? [])]), + ]; // Approval reads can omit gated runs. Keep each hold until its jobs finish. const awaitingNow = [...new Set(awaiting.map(approvalKey))]; @@ -238,6 +253,7 @@ export function evaluatePullRequestWatch( startedAt: watch.startedAt, headSha, failedChecks, + ...(failedRuns !== undefined && { failedRuns }), passed, passedChecks, owedChecks, diff --git a/packages/contracts/src/threadPullRequest.ts b/packages/contracts/src/threadPullRequest.ts index 252194f48b1f5..1f5c8a3bbb625 100644 --- a/packages/contracts/src/threadPullRequest.ts +++ b/packages/contracts/src/threadPullRequest.ts @@ -84,6 +84,8 @@ export const ThreadPullRequestWatch = Schema.Struct({ startedAt: IsoDateTime, headSha: Schema.NullOr(TrimmedNonEmptyString), failedChecks: Schema.Array(TrimmedNonEmptyString), + /** Name and run URL of each failed run told on this head, so a rerun that fails again is news. */ + failedRuns: Schema.optional(Schema.Array(Schema.String)), passed: Schema.Boolean, passedChecks: Schema.Array(TrimmedNonEmptyString).pipe( Schema.withDecodingDefault(Effect.succeed([])), diff --git a/packages/source-control-core/src/server/pullRequestChecks.test.ts b/packages/source-control-core/src/server/pullRequestChecks.test.ts index 4f6538f833f9a..f083735804653 100644 --- a/packages/source-control-core/src/server/pullRequestChecks.test.ts +++ b/packages/source-control-core/src/server/pullRequestChecks.test.ts @@ -59,6 +59,21 @@ describe("dedupeChecks", () => { expect([forward[0]?.status, reversed[0]?.status]).toEqual(["failure", "failure"]); }); + it("reports the same run for two events' failures finished at once, whichever is listed first", () => { + const failed = (event: string) => ({ + ...entry("lint", "failure", { at: "2026-11-07T00:01:00Z" }), + check: { name: "lint", status: "failure" as const, description: null, url: event }, + event, + }); + + expect( + [ + [failed("push"), failed("pull_request")], + [failed("pull_request"), failed("push")], + ].map((runs) => dedupeChecks(runs)[0]?.url), + ).toEqual(["push", "push"]); + }); + it("takes the higher sequence when instants tie, whichever is listed first", () => { const final = entry("build", "success", { at: "2026-10-12T10:14:29Z", sequence: 15 }); const pending = entry("build", "pending", { at: "2026-10-12T10:14:29Z", sequence: 14 }); diff --git a/packages/source-control-core/src/server/pullRequestChecks.ts b/packages/source-control-core/src/server/pullRequestChecks.ts index c4cea3e162dec..280d58fcdbf80 100644 --- a/packages/source-control-core/src/server/pullRequestChecks.ts +++ b/packages/source-control-core/src/server/pullRequestChecks.ts @@ -59,9 +59,18 @@ export function sortChecks( ); } +// Runs of one check for different events: a failure outranks a run in progress, which outranks a +// pass, which outranks a run cancelled beside it (a concurrency group superseding it). +function eventSeverity(status: PullRequestCheck["status"]): number { + if (status === "failure" || status === "action-required") return 3; + if (status === "pending") return 2; + return status === "success" ? 1 : 0; +} + /** * Rollups repeat checks during reruns or overlapping runs, and checks carry no ids. * Identify checks by workflow plus name because different workflows may share job names. + * Within one event the newest run wins; across events the worse run does. */ export function dedupeChecks( entries: ReadonlyArray<{ @@ -70,12 +79,15 @@ export function dedupeChecks( readonly at: string | null; // Hosts with one-second timestamps can date a final and an earlier status alike. readonly sequence?: number; + /** What triggered the run, where the host says (GitHub's `push` or `pull_request`). */ + readonly event?: string | null; }>, ): ReadonlyArray { - const newestByCheck = new Map(); + type Entry = (typeof entries)[number]; + const newestByRun = new Map(); for (const entry of entries) { - const key = JSON.stringify([entry.workflowName ?? "", entry.check.name]); - const kept = newestByCheck.get(key); + const key = JSON.stringify([entry.workflowName ?? "", entry.check.name, entry.event ?? null]); + const kept = newestByRun.get(key); if (kept !== undefined) { if (!isAtLeastAsNew(entry.at, kept.at)) continue; if ( @@ -86,7 +98,29 @@ export function dedupeChecks( ) continue; } - newestByCheck.set(key, entry); + newestByRun.set(key, entry); + } + const newestByCheck = new Map(); + for (const entry of newestByRun.values()) { + const key = JSON.stringify([entry.workflowName ?? "", entry.check.name]); + const kept = newestByCheck.get(key); + if (kept === undefined) { + newestByCheck.set(key, entry); + continue; + } + const severity = eventSeverity(entry.check.status) - eventSeverity(kept.check.status); + const newer = isAtLeastAsNew(entry.at, kept.at); + // Equal times break on the event, so a reordered rollup cannot flip the run a watch was told. + const tied = newer && isAtLeastAsNew(kept.at, entry.at); + const later = tied ? (entry.event ?? "") > (kept.event ?? "") : newer; + const worse = severity > 0 || (severity === 0 && later); + const chosen = worse ? entry : kept; + newestByCheck.set( + key, + entry.check.required === true || kept.check.required === true + ? { ...chosen, check: { ...chosen.check, required: true } } + : chosen, + ); } const survivors = [...newestByCheck.values()]; const countsByName = new Map(); diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts index aff9f9c627a1a..f19f7b12b8ab0 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts @@ -3926,13 +3926,17 @@ layer("GitHubPullRequestApi.layer", (it) => { name: "build", status: "COMPLETED", conclusion: "SUCCESS", - checkSuite: { workflowRun: { workflow: { name: "linux" } } }, + checkSuite: { + workflowRun: { event: "push", workflow: { name: "linux" } }, + }, }), checkRun({ name: "build", status: "COMPLETED", conclusion: "FAILURE", - checkSuite: { workflowRun: { workflow: { name: "windows" } } }, + checkSuite: { + workflowRun: { event: "push", workflow: { name: "windows" } }, + }, }), ], pageInfo: { hasNextPage: false, endCursor: null }, diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts index 37db822d34386..fb8faba597ed5 100644 --- a/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts +++ b/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts @@ -362,7 +362,7 @@ describe("pull request detail decoding", () => { const inWorkflow = ({ workflowName, ...fields }: Record) => check({ ...fields, - checkSuite: { workflowRun: { workflow: { name: workflowName } } }, + checkSuite: { workflowRun: { event: "pull_request", workflow: { name: workflowName } } }, }); const coreJson = ( @@ -655,6 +655,76 @@ describe("pull request detail decoding", () => { } }); + it("keeps a failed push run failing while the pull_request run of it runs or passes", () => { + const run = (event: string, fields: Record) => + check({ + name: "lint", + checkSuite: { workflowRun: { event, workflow: { name: "CI" } } }, + ...fields, + }); + const pushFailed = run("push", { + status: "COMPLETED", + conclusion: "FAILURE", + startedAt: "2026-10-08T04:06:10Z", + completedAt: "2026-10-08T04:08:00Z", + }); + // Only the losing run says the check is required; the merged check must still say so. + const pullRequestRunning = run("pull_request", { + isRequired: true, + status: "IN_PROGRESS", + conclusion: null, + startedAt: "2026-10-08T04:06:13Z", + completedAt: "0001-01-01T00:00:00Z", + }); + const pullRequestPassed = run("pull_request", { + isRequired: true, + status: "COMPLETED", + conclusion: "SUCCESS", + startedAt: "2026-10-08T04:06:13Z", + completedAt: "2026-10-08T04:12:00Z", + }); + const checksOf = (rollup: ReadonlyArray>) => { + const detail = detailOf(rollup); + return [ + detail.checks.map((check) => [check.name, check.status, check.required]), + detail.checksState, + ]; + }; + + const rollups = [ + [pushFailed, pullRequestRunning], + [pullRequestRunning, pushFailed], + [pushFailed, pullRequestPassed], + [pullRequestPassed, pushFailed], + ]; + expect(rollups.map(checksOf)).toEqual( + rollups.map(() => [[["lint", "failure", true]], "failing"]), + ); + }); + + it("does not fail a check whose run of one event was cancelled beside a passing run", () => { + const run = (event: string, conclusion: string, completedAt: string) => + check({ + name: "lint", + conclusion, + completedAt, + checkSuite: { workflowRun: { event, workflow: { name: "CI" } } }, + }); + const passed = run("push", "SUCCESS", "2026-10-08T04:10:00Z"); + const cancelled = run("pull_request", "CANCELLED", "2026-10-08T04:12:00Z"); + + for (const rollup of [ + [passed, cancelled], + [cancelled, passed], + ]) { + const detail = detailOf(rollup); + expect([detail.checks.map((check) => check.status), detail.checksState]).toEqual([ + ["success"], + "passing", + ]); + } + }); + it("merges reviews with comments in time order and keeps a bodyless approval", () => { const detail = expectSuccess(activity(JSON.parse(detailJson) as Record)); expect(detail.comments.map((comment) => comment.id)).toEqual(["r1", "c1", "r2"]); diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.ts index 7fbe86839d495..34043fb3b383b 100644 --- a/packages/source-control-github/src/server/gitHubPullRequestJson.ts +++ b/packages/source-control-github/src/server/gitHubPullRequestJson.ts @@ -143,6 +143,8 @@ interface CheckFields { readonly targetUrl?: string | null | undefined; /** Empty for app-owned runs; absent for commit statuses. */ readonly workflowName?: string | null | undefined; + /** Absent for commit statuses and `gh` JSON; null for app-owned runs. */ + readonly workflowRun?: { readonly event: string } | null | undefined; readonly startedAt?: string | null | undefined; readonly completedAt?: string | null | undefined; /** Branch protection requires this check; asked for on github.com only. */ @@ -617,11 +619,12 @@ function isNamelessCheck(raw: CheckFields): boolean { return trimmed(raw.name) === null && trimmed(raw.context) === null; } -/** Unfinished runs outrank finished runs of the same check across push/PR workflows. */ +/** Unfinished runs outrank finished runs of the same check, so a rerun replaces its run. */ function toCheckEntries(raw: ReadonlyArray | null | undefined): ReadonlyArray<{ readonly check: PullRequestCheck; readonly workflowName: string | null; readonly at: string | null; + readonly event: string | null; }> { return (raw ?? []).flatMap((check) => { const name = trimmed(check.name) ?? trimmed(check.context); @@ -637,6 +640,7 @@ function toCheckEntries(raw: ReadonlyArray | null | undefined): Rea ...(typeof check.isRequired === "boolean" ? { required: check.isRequired } : {}), }, workflowName: trimmed(check.workflowName), + event: trimmed(check.workflowRun?.event), at: status === "pending" ? STILL_RUNNING @@ -1246,7 +1250,11 @@ export type GitHubCheckContext = CheckFields; function toCheckContexts(nodes: ReadonlyArray): ReadonlyArray { return nodes.map((check) => check.__typename === "CheckRun" - ? { ...check, workflowName: check.checkSuite.workflowRun?.workflow.name ?? null } + ? { + ...check, + workflowName: check.checkSuite.workflowRun?.workflow.name ?? null, + workflowRun: check.checkSuite.workflowRun, + } : check, ); } diff --git a/packages/source-control-github/src/server/pullRequestReads.graphql b/packages/source-control-github/src/server/pullRequestReads.graphql index 2799b67525a27..08ac7bf9fba2e 100644 --- a/packages/source-control-github/src/server/pullRequestReads.graphql +++ b/packages/source-control-github/src/server/pullRequestReads.graphql @@ -42,6 +42,7 @@ fragment CheckContext on StatusCheckRollupContext { isRequired(pullRequestNumber: $number) @include(if: $required) checkSuite { workflowRun { + event workflow { name } diff --git a/packages/source-control-github/src/server/pullRequestReads.graphql.ts b/packages/source-control-github/src/server/pullRequestReads.graphql.ts index ab5e211a4dec2..f5d8e9171cde6 100644 --- a/packages/source-control-github/src/server/pullRequestReads.graphql.ts +++ b/packages/source-control-github/src/server/pullRequestReads.graphql.ts @@ -30,6 +30,8 @@ export interface Workflow extends Schema.Struct.Type {} /** A workflow run. */ export const WorkflowRun = Schema.Struct({ + /** The event that triggered the workflow run */ + event: Schema.String, /** The workflow executed in this workflow run. */ workflow: Workflow }) @@ -565,7 +567,7 @@ export const PullRequestCore = GraphQL.query("PullRequestCore", { { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){mergeCommitAllowed squashMergeAllowed rebaseMergeAllowed autoMergeAllowed viewerPermission pullRequest(number:$", "number", "){number title url body state isDraft mergeable mergeStateStatus reviewDecision additions deletions changedFiles createdAt updatedAt mergedAt mergeCommit{oid}mergedBy{__typename login avatarUrl...on User{name}}closedAt headRefName baseRefName headRefOid isCrossRepository maintainerCanModify headRepositoryOwner{__typename login}headRepository{nameWithOwner viewerPermission}headRef{id}author{__typename login avatarUrl...on User{id name}}autoMergeRequest{mergeMethod}mergeQueueRemovals:timelineItems(last:1 itemTypes:[REMOVED_FROM_MERGE_QUEUE_EVENT])@include(if:$", "mergeQueue", "){nodes{__typename...on RemovedFromMergeQueueEvent{id createdAt reason}}}viewerCanUpdate viewerDidAuthor viewerCanUpdateBranch baseRef{compare(headRef:$", "headRef", "){behindBy}}reviewRequests(first:$", "requestedReviewers", "){nodes{requestedReviewer{__typename...on User{login name}...on Bot{login}...on Team{slug combinedSlug teamName:name teamAvatarUrl:avatarUrl}}}}labels(first:100){nodes{name color description}}commits(last:1){nodes{commit{statusCheckRollup{contexts(first:100){nodes{__typename...", "CheckContext", "}pageInfo{hasNextPage endCursor}}}}}}}}"] } ], fragments: [ - { name: "CheckContext", body: ["on StatusCheckRollupContext{__typename...on StatusContext{context state targetUrl createdAt description isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")}...on CheckRun{name status conclusion startedAt completedAt detailsUrl isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")checkSuite{workflowRun{workflow{name}}}}}"] } + { name: "CheckContext", body: ["on StatusCheckRollupContext{__typename...on StatusContext{context state targetUrl createdAt description isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")}...on CheckRun{name status conclusion startedAt completedAt detailsUrl isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")checkSuite{workflowRun{event workflow{name}}}}}"] } ] }, variables: { @@ -617,7 +619,7 @@ export const PullRequestCheckContexts = GraphQL.query("PullRequestCheckContexts" { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){pullRequest(number:$", "number", "){headRefOid commits(last:1){nodes{commit{statusCheckRollup{contexts(first:100 after:$", "after", "){nodes{__typename...", "CheckContext", "}pageInfo{hasNextPage endCursor}}}}}}}}"] } ], fragments: [ - { name: "CheckContext", body: ["on StatusCheckRollupContext{__typename...on StatusContext{context state targetUrl createdAt description isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")}...on CheckRun{name status conclusion startedAt completedAt detailsUrl isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")checkSuite{workflowRun{workflow{name}}}}}"] } + { name: "CheckContext", body: ["on StatusCheckRollupContext{__typename...on StatusContext{context state targetUrl createdAt description isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")}...on CheckRun{name status conclusion startedAt completedAt detailsUrl isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")checkSuite{workflowRun{event workflow{name}}}}}"] } ] }, variables: { From fa6c2b04d5dc97f3403db9e9c1627ad208c4a106 Mon Sep 17 00:00:00 2001 From: SeongHoon Ryu <4997174+ryush00@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:58:25 +0900 Subject: [PATCH 13/21] fix(gitlab): a watch reports a pipeline retry that fails again (#33671) --- .../orchestration-v2/pullRequestWatch.test.ts | 23 ++++++++++++++++ .../src/orchestration-v2/pullRequestWatch.ts | 9 ++++--- packages/contracts/src/pullRequest.ts | 5 ++++ .../src/server/gitLabMergeRequestJson.test.ts | 26 +++++++++++++++++++ .../src/server/gitLabMergeRequestJson.ts | 7 +++++ 5 files changed, 67 insertions(+), 3 deletions(-) diff --git a/apps/server/src/orchestration-v2/pullRequestWatch.test.ts b/apps/server/src/orchestration-v2/pullRequestWatch.test.ts index 6b0afc5f3cc6c..569bb33e0cae0 100644 --- a/apps/server/src/orchestration-v2/pullRequestWatch.test.ts +++ b/apps/server/src/orchestration-v2/pullRequestWatch.test.ts @@ -511,6 +511,29 @@ describe("evaluatePullRequestWatch", () => { } }); + it("reports a retry that fails again where the run keeps its URL", () => { + // GitLab retries failed jobs inside the same pipeline, so only the run ID moves. + const pipeline = (finishedAt: string): PullRequestCheck => ({ + ...check("Pipeline", "failure"), + url: "https://gitlab.example/o/r/-/pipelines/7", + runId: `7@${finishedAt}`, + }); + const first = pipeline("2026-11-10T00:28:57.000Z"); + const again = pipeline("2026-11-10T00:39:53.000Z"); + const told = evaluatePullRequestWatch(watch(), detail({ checks: [first] }), noRemarks); + assert.deepEqual(told.changes, [{ kind: "checks-failed", failed: [first] }]); + assert.deepEqual( + evaluatePullRequestWatch(told.next, detail({ checks: [first] }), noRemarks).changes, + [], + ); + const retried = evaluatePullRequestWatch(told.next, detail({ checks: [again] }), noRemarks); + assert.deepEqual(retried.changes, [{ kind: "checks-failed", failed: [again] }]); + assert.deepEqual( + evaluatePullRequestWatch(retried.next, detail({ checks: [again] }), noRemarks).changes, + [], + ); + }); + it("does not repeat a failure an older watch told by name", () => { const older = watch({ headSha: "aaaaaaaaaa", failedChecks: ["lint"] }); const failed = detail({ checks: [check("lint", "failure")] }); diff --git a/apps/server/src/orchestration-v2/pullRequestWatch.ts b/apps/server/src/orchestration-v2/pullRequestWatch.ts index 3ca1661d91727..e6efc954140f0 100644 --- a/apps/server/src/orchestration-v2/pullRequestWatch.ts +++ b/apps/server/src/orchestration-v2/pullRequestWatch.ts @@ -78,10 +78,13 @@ export function evaluatePullRequestWatch( if (checks.length > 0) { // A run awaiting approval waits on a person, like a review, so only running checks count. checksPending = checks.some((check) => check.status === "pending"); - // A new run URL under a failing name is a rerun that failed again between reads. + // A new run under a failing name is a rerun that failed again between reads. A run is its + // URL, or the host's run ID where the URL stays the same across reruns. const toldRuns = failedRuns; - const runOf = (check: PullRequestCheck) => - check.url === null ? null : JSON.stringify([check.name, check.url]); + const runOf = (check: PullRequestCheck) => { + const run = check.runId ?? check.url; + return run === null ? null : JSON.stringify([check.name, run]); + }; const newlyFailed = failed.filter((check) => { const run = runOf(check); return ( diff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.ts index 63087b6b253e1..16318bc7f660d 100644 --- a/packages/contracts/src/pullRequest.ts +++ b/packages/contracts/src/pullRequest.ts @@ -121,6 +121,11 @@ export const PullRequestCheck = Schema.Struct({ * approval when that read fails, so nothing waits on it or counts it as passing. */ placeholder: Schema.optional(Schema.Boolean), + /** + * Tells this run of the check apart from earlier ones where its URL does not change on a + * rerun, such as a GitLab pipeline whose failed jobs were retried in place. + */ + runId: Schema.optional(TrimmedNonEmptyString), }); export type PullRequestCheck = typeof PullRequestCheck.Type; diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts index 6b9dfbb6166d6..6c17b9eb84639 100644 --- a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts +++ b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts @@ -196,6 +196,32 @@ describe("decodeMergeRequestDetailJson", () => { ]); }); + it("tells each finish of a pipeline apart, since a job retry keeps its URL", () => { + const pipelineCheck = (pipeline: Record) => + expectSuccess(decodeMergeRequestDetailJson(detailJson({ head_pipeline: pipeline }))) + .checks[0]; + const failed = (finishedAt: string) => + pipelineCheck({ + id: 3047545127, + status: "failed", + web_url: "https://gitlab.com/acme/web/-/pipelines/3047545127", + finished_at: finishedAt, + }); + + const first = failed("2026-11-10T00:28:57.753Z"); + const retried = failed("2026-11-10T00:39:53.753Z"); + expect(first?.url).toBe(retried?.url); + expect(first?.runId).toBe("3047545127@2026-11-10T00:28:57.753Z"); + expect(retried?.runId).toBe("3047545127@2026-11-10T00:39:53.753Z"); + // A running pipeline has no finish time yet, and one without an ID has nothing to key on. + expect(pipelineCheck({ id: 3047545127, status: "running", finished_at: null })?.runId).toBe( + undefined, + ); + expect( + pipelineCheck({ status: "failed", finished_at: "2026-11-10T00:39:53.753Z" })?.runId, + ).toBe(undefined); + }); + it.each(["canceled", "canceling"])("maps a %s pipeline to cancelled", (status) => { const detail = expectSuccess( decodeMergeRequestDetailJson(detailJson({ head_pipeline: { status } })), diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts index c5ed0f2d97193..ecb640a452830 100644 --- a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts +++ b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts @@ -41,6 +41,7 @@ const RawPipelineSchema = Schema.Struct({ status: Schema.optional(Schema.NullOr(Schema.String)), web_url: Schema.optional(Schema.NullOr(Schema.String)), source: Schema.optional(Schema.NullOr(Schema.String)), + finished_at: Schema.optional(Schema.NullOr(Schema.String)), }); const RawTriggerJobSchema = Schema.Struct({ @@ -335,12 +336,18 @@ function toChecks( ): ReadonlyArray { const pipeline = raw.head_pipeline; if (!pipeline) return []; + // Retrying jobs reruns them inside the same pipeline, so its URL stays the same. Each time it + // finishes again, its finish time moves, and that tells a retry that failed again apart. + const finishedAt = trimmed(pipeline.finished_at); return [ { name: "Pipeline", status: toPipelineStatus(pipeline.status), description: trimmed(pipeline.source), url: trimmed(pipeline.web_url), + ...(pipeline.id == null || finishedAt === null + ? {} + : { runId: `${pipeline.id}@${finishedAt}` }), }, ]; } From fc62bdcc994ba001582560f992fe89e8e6b7ef9e Mon Sep 17 00:00:00 2001 From: SeongHoon Ryu <4997174+ryush00@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:01:53 +0900 Subject: [PATCH 14/21] fix(server): PR watches wake when checks finish after an early failure (#28020) --- .../orchestration-v2/pullRequestWatch.test.ts | 130 ++++++++++++++++++ .../src/orchestration-v2/pullRequestWatch.ts | 64 +++++++-- 2 files changed, 180 insertions(+), 14 deletions(-) diff --git a/apps/server/src/orchestration-v2/pullRequestWatch.test.ts b/apps/server/src/orchestration-v2/pullRequestWatch.test.ts index 569bb33e0cae0..dbcbea0a14093 100644 --- a/apps/server/src/orchestration-v2/pullRequestWatch.test.ts +++ b/apps/server/src/orchestration-v2/pullRequestWatch.test.ts @@ -650,6 +650,136 @@ describe("evaluatePullRequestWatch", () => { assert.deepEqual(evaluatePullRequestWatch(final.next, recovered, noRemarks).changes, []); }); + it("wakes once when the other checks finish after one failed where none is required", () => { + const sonar = check("sonar", "cancelled"); + const early = detail({ checks: [sonar, check("unit", "pending"), check("e2e", "pending")] }); + const first = evaluatePullRequestWatch(watch(), early, noRemarks); + assert.deepEqual(first.changes, [{ kind: "checks-failed", failed: [sonar] }]); + + const partway = detail({ checks: [sonar, check("unit", "success"), check("e2e", "pending")] }); + const waiting = evaluatePullRequestWatch(first.next, partway, noRemarks); + assert.deepEqual(waiting.changes, []); + + const done = detail({ checks: [sonar, check("unit", "success"), check("e2e", "success")] }); + const final = evaluatePullRequestWatch(waiting.next, done, noRemarks); + assert.deepEqual(final.changes, [ + { kind: "checks-finished", failing: [sonar], required: false }, + ]); + assert.deepEqual(evaluatePullRequestWatch(final.next, done, noRemarks).changes, []); + + // An owed check stays owed while it runs, even when the failed one turns required. + const gated = detail({ + checks: [{ ...sonar, required: true }, check("unit", "success"), check("e2e", "pending")], + }); + const still = evaluatePullRequestWatch(waiting.next, gated, noRemarks); + assert.deepEqual(still.changes, []); + assert.deepEqual(still.next.owedChecks, ["e2e"]); + + // Another gate failure owes the gate's running checks on top of those still owed. + const lint = { ...check("lint", "failure"), required: true }; + const another = detail({ checks: [...gated.checks, lint] }); + const both = evaluatePullRequestWatch(still.next, another, noRemarks); + assert.deepEqual(both.changes, [{ kind: "checks-failed", failed: [lint] }]); + assert.deepEqual(both.next.owedChecks, ["e2e"]); + + // The last owed check finishing still wakes when an unrelated check fails in the same read. + const bot = check("bot", "failure"); + const finishedWithBot = detail({ + checks: [sonar, check("unit", "success"), check("e2e", "success"), bot], + }); + assert.deepEqual(evaluatePullRequestWatch(waiting.next, finishedWithBot, noRemarks).changes, [ + { kind: "checks-failed", failed: [bot] }, + { kind: "checks-finished", failing: [sonar, bot], required: false }, + ]); + + // A later failure is its own wake and leaves nothing more owed. + const broke = detail({ checks: [sonar, check("unit", "success"), check("e2e", "failure")] }); + const failure = evaluatePullRequestWatch(waiting.next, broke, noRemarks); + assert.deepEqual(failure.changes, [ + { kind: "checks-failed", failed: [check("e2e", "failure")] }, + ]); + assert.deepEqual(evaluatePullRequestWatch(failure.next, broke, noRemarks).changes, []); + + // A failure while another owed check still runs keeps that one owed. + const unitBroke = detail({ + checks: [sonar, check("unit", "failure"), check("e2e", "pending")], + }); + const second = evaluatePullRequestWatch(first.next, unitBroke, noRemarks); + assert.deepEqual(second.changes, [ + { kind: "checks-failed", failed: [check("unit", "failure")] }, + ]); + const settled = detail({ checks: [sonar, check("unit", "failure"), check("e2e", "success")] }); + const last = evaluatePullRequestWatch(second.next, settled, noRemarks); + assert.deepEqual(last.changes, [ + { kind: "checks-finished", failing: [sonar, check("unit", "failure")], required: false }, + ]); + }); + + it("wakes once when the other required checks finish after a required one failed", () => { + const required = (name: string, status: PullRequestCheck["status"]) => ({ + ...check(name, status), + required: true, + }); + const early = detail({ + checks: [ + required("lint", "failure"), + required("unit", "pending"), + check("bot", "failure"), + check("e2e", "pending"), + ], + }); + const first = evaluatePullRequestWatch(watch(), early, noRemarks); + assert.equal(first.changes.length, 1); + assert.deepEqual(first.next.owedChecks, ["unit"]); + + const done = detail({ + checks: [ + required("lint", "failure"), + required("unit", "success"), + check("bot", "failure"), + check("e2e", "pending"), + ], + }); + const final = evaluatePullRequestWatch(first.next, done, noRemarks); + assert.deepEqual(final.changes, [ + { kind: "checks-finished", failing: [required("lint", "failure")], required: true }, + ]); + assert.deepEqual(evaluatePullRequestWatch(final.next, done, noRemarks).changes, []); + const message = pullRequestWatchMessage({ + number: 7, + url: "https://github.com/o/r/pull/7", + baseBranch: "main", + headSha: "aaaaaaaaaa", + report: final, + }); + assert.equal(message.notification.outcome, "failed"); + + // A new advisory failure keeps what was owed rather than owing a required check started since. + const advisory = detail({ + checks: [ + required("lint", "failure"), + required("unit", "pending"), + required("smoke", "pending"), + check("bot", "failure"), + check("e2e", "failure"), + ], + }); + const later = evaluatePullRequestWatch(first.next, advisory, noRemarks); + assert.deepEqual(later.changes, [{ kind: "checks-failed", failed: [check("e2e", "failure")] }]); + assert.deepEqual(later.next.owedChecks, ["unit"]); + + // A rerun of the failed required check is not the gate finishing, even with an advisory failure. + const rerun = detail({ + checks: [ + required("lint", "pending"), + required("unit", "success"), + check("bot", "failure"), + check("e2e", "pending"), + ], + }); + assert.deepEqual(evaluatePullRequestWatch(first.next, rerun, noRemarks).changes, []); + }); + it("clears old-head owed checks when a new head is pushed", () => { const required = { ...check("test", "success"), required: true }; const early = detail({ checks: [required, check("e2e", "pending")] }); diff --git a/apps/server/src/orchestration-v2/pullRequestWatch.ts b/apps/server/src/orchestration-v2/pullRequestWatch.ts index e6efc954140f0..87778292b8734 100644 --- a/apps/server/src/orchestration-v2/pullRequestWatch.ts +++ b/apps/server/src/orchestration-v2/pullRequestWatch.ts @@ -17,6 +17,11 @@ const SNIPPET_LENGTH = 200; export type PullRequestWatchChange = | { readonly kind: "checks-failed"; readonly failed: ReadonlyArray } | { readonly kind: "checks-passed"; readonly count: number; readonly required: boolean } + | { + readonly kind: "checks-finished"; + readonly failing: ReadonlyArray; + readonly required: boolean; + } | { readonly kind: "checks-awaiting-approval"; readonly checks: ReadonlyArray } | { readonly kind: "remarks"; readonly remarks: ReadonlyArray } | { readonly kind: "no-checks"; readonly minutes: number } @@ -65,6 +70,7 @@ export function evaluatePullRequestWatch( let passed = headMoved ? false : watch.passed; let passedChecks = headMoved ? [] : watch.passedChecks; let owedChecks = headMoved ? [] : (watch.owedChecks ?? []); + const owedBefore = owedChecks; let awaitingApproval = headMoved ? [] : (watch.awaitingApproval ?? []); let approvalAnnounced = headMoved ? false : (watch.approvalAnnounced ?? false); // A watch with no answer (saved before the field, or since a push) waits only while the clock @@ -75,23 +81,23 @@ export function evaluatePullRequestWatch( const checks = detail.checks.filter((check) => check.placeholder !== true); const failed = checks.filter(isFailedCheck); const awaiting = checks.filter((check) => check.status === "action-required"); + // A new run under a failing name is a rerun that failed again between reads. A run is its + // URL, or the host's run ID where the URL stays the same across reruns. + const toldRuns = failedRuns; + const runOf = (check: PullRequestCheck) => { + const run = check.runId ?? check.url; + return run === null ? null : JSON.stringify([check.name, run]); + }; + const newlyFailed = failed.filter((check) => { + const run = runOf(check); + return ( + !failedChecks.includes(check.name) || + (toldRuns !== undefined && run !== null && !toldRuns.includes(run)) + ); + }); if (checks.length > 0) { // A run awaiting approval waits on a person, like a review, so only running checks count. checksPending = checks.some((check) => check.status === "pending"); - // A new run under a failing name is a rerun that failed again between reads. A run is its - // URL, or the host's run ID where the URL stays the same across reruns. - const toldRuns = failedRuns; - const runOf = (check: PullRequestCheck) => { - const run = check.runId ?? check.url; - return run === null ? null : JSON.stringify([check.name, run]); - }; - const newlyFailed = failed.filter((check) => { - const run = runOf(check); - return ( - !failedChecks.includes(check.name) || - (toldRuns !== undefined && run !== null && !toldRuns.includes(run)) - ); - }); if (!checksBaseline && newlyFailed.length > 0) { changes.push({ kind: "checks-failed", failed: newlyFailed }); } @@ -172,6 +178,26 @@ export function evaluatePullRequestWatch( } else if (settled && owed.length > 0) { changes.push({ kind: "checks-passed", count: checks.length, required: false }); owedChecks = []; + } else if (gate.some(isFailedCheck)) { + // Gate checks still running when one failed are owed one wake when they finish, since + // the gate can no longer pass and so never sends the checks-passed wake. + const running = checks + .filter((check) => check.status === "pending" || check.status === "action-required") + .map((check) => check.name); + const stillOwed = owedBefore.filter((name) => running.includes(name)); + const gateNewlyFailed = + !checksBaseline && newlyFailed.some((check) => gateNames.includes(check.name)); + owedChecks = gateNewlyFailed + ? [...new Set([...stillOwed, ...running.filter((name) => gateNames.includes(name))])] + : stillOwed; + const owedFailed = newlyFailed.some((check) => owedBefore.includes(check.name)); + if (!owedFailed && owedBefore.length > 0 && owedChecks.length === 0) { + changes.push({ + kind: "checks-finished", + failing: gate.filter(isFailedCheck), + required: owedBefore.every((name) => required.some((check) => check.name === name)), + }); + } } passed = passedNow; passedChecks = passedNow ? gateNames : []; @@ -404,6 +430,14 @@ function changeLines( return ` - ${remark.author?.login ?? "someone"}${where}: ${said}${remark.url ? ` ${remark.url}` : ""}`; }), ]; + case "checks-finished": + return [ + `- The ${change.required ? "required " : ""}checks still running when one failed have finished${context.commit}. Still failing:`, + ...listed( + change.failing, + (check) => ` - ${check.name}${check.url ? ` ${check.url}` : ""}`, + ), + ]; case "no-checks": return [ `- No checks have reported${context.commit} after ${change.minutes} minutes. None may be configured to run on this change.`, @@ -422,6 +456,7 @@ function changeLines( const SUMMARY: Record = { "checks-failed": "checks failed", "checks-passed": "checks passed", + "checks-finished": "checks finished", "checks-awaiting-approval": "checks await approval", remarks: "new comments", "no-checks": "no checks reported", @@ -517,6 +552,7 @@ export function pullRequestWatchMessage(input: { const failed = changes.some( (change) => change.kind === "checks-failed" || + change.kind === "checks-finished" || change.kind === "conflicting" || change.kind === "needs-rebase" || change.kind === "merge-queue-removed", From 02216a4e4dd2245782da7b04a6afc0c8ff565ff9 Mon Sep 17 00:00:00 2001 From: SeongHoon Ryu <4997174+ryush00@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:09:29 +0900 Subject: [PATCH 15/21] fix(server): baseline PR watches at registration so fast check completions still wake (#36463) --- .../PullRequestWatchReactor.ts | 22 ++++ .../src/orchestration-v2/runtimeLayer.test.ts | 120 ++++++++++++++++++ .../pullRequest/PullRequestWatchService.ts | 60 ++++++++- 3 files changed, 197 insertions(+), 5 deletions(-) diff --git a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts index c84cb3d577af6..3d6562ff6342a 100644 --- a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts +++ b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts @@ -809,6 +809,13 @@ export const make = Effect.gen(function* () { for (const cache of [readFailures, lastReads, threadTails]) { for (const key of cache.keys()) if (!byPullRequest.has(key)) cache.delete(key); } + } else { + currentGroups = [ + ...currentGroups.filter( + (group) => threadPullRequestKeyOf(group.targets[0]!.link) !== changed, + ), + ...groups, + ]; } yield* Effect.forEach( ending, @@ -982,6 +989,21 @@ export const make = Effect.gen(function* () { return Effect.forEach(new Set(unread), readOnChange, { discard: true }); }).pipe(Effect.catchCause(logFailure("pull request watch event stream failed", {}))), ); + yield* forkParked( + Stream.runForEach(engine.streamDomainEvents, (event) => { + if (event.type !== "thread.pull-request-synced") return Effect.void; + const added = [ + ...new Set( + visibleThreadPullRequests(event.payload.pullRequests ?? []) + .filter((link) => link.watch?.awaitingBaseline !== undefined) + .map(threadPullRequestKeyOf), + ), + ]; + return added.length === 0 + ? Effect.void + : Effect.forEach(added, readOnChange, { discard: true }).pipe(Effect.andThen(follow)); + }).pipe(Effect.catchCause(logFailure("pull request watch event stream failed", {}))), + ); yield* forkParked( sweep.pipe( Effect.andThen(follow), diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 0fedb489f451a..c78de83c91fd7 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -84,6 +84,7 @@ import * as ProjectionStore from "./ProjectionStore.ts"; import * as PullRequestWatchReactor from "./PullRequestWatchReactor.ts"; import { PULL_REQUEST_WATCH_WAKE_LIMIT } from "./pullRequestWatch.ts"; import * as PullRequestService from "../pullRequest/PullRequestService.ts"; +import * as PullRequestWatchService from "../pullRequest/PullRequestWatchService.ts"; import * as ProjectStore from "./ProjectStore.ts"; import * as ProviderSessionManager from "./ProviderSessionManager.ts"; import * as RuntimeLayer from "./runtimeLayer.ts"; @@ -5334,6 +5335,125 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }), ); + it.effect.each([ + ["success", "#12: checks passed"], + ["failure", "#12: checks failed"], + ] as const)( + "wakes when a pending check settles (%s) between watch registration and the first sweep", + ([outcome, expected]) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = ThreadId.make(`runtime-pull-request-watch-fast-${outcome}`); + const projectId = ProjectId.make(`pr-watch-fast-project-${outcome}`); + yield* seedProject({ + projectId, + title: "Watch fast checks", + workspaceRoot: "/workspace/watch-fast", + defaultModelSelection: null, + createdAt: "2026-10-01T00:00:00.000Z", + }); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`pr-watch-fast-create-${outcome}`), + threadId, + projectId, + title: "Watch fast checks", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }); + + const headSha = "2aaf97e7c8"; + let status: PullRequestCheck["status"] = "pending"; + const host = Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + Layer.mock(ProjectService.ProjectService)({ + getShell: () => Effect.succeedNone, + }), + Layer.mock(PullRequestService.PullRequestService)({ + invalidate: () => Effect.void, + summary: (input) => + Effect.sync(() => ({ + provider: SourceControlProviderKind.make("github"), + projectId: input.projectId, + repository: input.repository, + number: input.number, + title: `PR #${input.number}`, + url: `https://github.com/${input.repository}/pull/${input.number}`, + state: "open" as const, + headBranch: "feature", + baseBranch: "main", + updatedAt: "2026-10-02T12:00:00.000Z", + headSha, + checksState: + status === "pending" + ? ("pending" as const) + : status === "success" + ? ("passing" as const) + : ("failing" as const), + })), + detail: () => + Effect.sync(() => ({ + ...watchedPullRequestDetail({ + projectId, + number: 12, + at: "2026-10-02T12:00:00.000Z", + }), + headSha, + checks: [ + { + name: "test", + status, + description: null, + url: "https://ci.example/test/34258", + required: true, + }, + ], + })), + activity: () => + Effect.succeed({ + comments: [], + commentCount: 0, + commentsTruncated: false, + reviewThreads: [], + commits: [], + }), + }), + ); + + const watches = yield* PullRequestWatchService.PullRequestWatchService.pipe( + Effect.provide(PullRequestWatchService.layer.pipe(Layer.provide(host))), + ); + yield* watches.setWatching({ + threadId, + target: { url: "https://github.com/pingdotgg/t3code/pull/12" }, + watching: true, + }); + + status = outcome; + const reactor = yield* PullRequestWatchReactor.make.pipe(Effect.provide(host)); + yield* reactor.sweep; + yield* worker.drain(); + + const { messages } = yield* orchestrator.getThreadRecords(threadId, ["messages"]); + assert.deepEqual( + messages.flatMap((message) => message.notification?.summary ?? []), + [expected], + ); + yield* watches.setWatching({ + threadId, + target: { url: "https://github.com/pingdotgg/t3code/pull/12" }, + watching: false, + }); + }), + ); + it.effect.each([ ["an idle", false], ["a busy", true], diff --git a/apps/server/src/pullRequest/PullRequestWatchService.ts b/apps/server/src/pullRequest/PullRequestWatchService.ts index c50de1a847f98..e709482b95f9f 100644 --- a/apps/server/src/pullRequest/PullRequestWatchService.ts +++ b/apps/server/src/pullRequest/PullRequestWatchService.ts @@ -14,6 +14,7 @@ import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; +import { evaluatePullRequestWatch } from "../orchestration-v2/pullRequestWatch.ts"; import * as ProjectService from "../project/ProjectService.ts"; import * as PullRequestService from "./PullRequestService.ts"; import { @@ -126,14 +127,17 @@ const make = Effect.gen(function* () { if (watching && before?.snapshot?.state === "merged") { return yield* new PullRequestNotOpenError({ state: "merged" }); } + const reference = { + projectId: thread.projectId, + host: target.host, + repository: target.repository, + number: target.number, + }; if (watching && before?.watch === undefined) { yield* pullRequests .summary( { - projectId: thread.projectId, - host: target.host, - repository: target.repository, - number: target.number, + ...reference, allowStale: false, }, { recoverTransientFailure: false, bypassCache: true }, @@ -150,6 +154,20 @@ const make = Effect.gen(function* () { }), ); } + const initialDetail = + watching && before?.watch === undefined && before?.endedWatch === undefined + ? yield* pullRequests.invalidate({ reference }).pipe( + Effect.andThen(pullRequests.detail({ ...reference, allowStale: false })), + Effect.catchCause((cause) => + Cause.hasInterruptsOnly(cause) + ? Effect.failCause(cause as Cause.Cause) + : Effect.undefined, + ), + ) + : undefined; + if (initialDetail?.state === "merged") { + return yield* new PullRequestNotOpenError({ state: "merged" }); + } const uuid = yield* random.uuidV4().pipe(Effect.orDie); yield* engine .dispatch({ @@ -171,9 +189,41 @@ const make = Effect.gen(function* () { ), ); const after = yield* requireThread(thread.id); + const created = watchedLink(after)?.watch; + if ( + created?.awaitingBaseline !== undefined && + initialDetail !== undefined && + initialDetail.state === "open" + ) { + const baseline = evaluatePullRequestWatch( + created, + initialDetail, + null, + Date.parse(created.startedAt), + ).next; + const syncUuid = yield* random.uuidV4().pipe(Effect.orDie); + yield* engine + .dispatch({ + type: "thread.pull-request-watch.sync", + commandId: CommandId.make(`server:mcp-pr-watch-baseline:${thread.id}:${syncUuid}`), + threadId: thread.id, + host: target.host, + repository: target.repository, + number: target.number, + startedAt: created.startedAt, + watch: baseline, + }) + .pipe( + Effect.catchCause((cause) => + Cause.hasInterruptsOnly(cause) + ? Effect.failCause(cause as Cause.Cause) + : Effect.void, + ), + ); + } return { ...target, - watching: watchedLink(after)?.watch !== undefined, + watching: created !== undefined, wasWatching: before?.watch !== undefined, }; }); From cdc7faf1f0d7e15f4f3145936c7e30b02d481dc9 Mon Sep 17 00:00:00 2001 From: Torben Buck Date: Mon, 16 Nov 2026 13:14:38 +0900 Subject: [PATCH 16/21] fix: GitLab merge request images and videos load in private projects (#23501) Upstream PR: https://github.com/pingdotgg/t3code/pull/23501 --- .../pull-requests/PullRequestMarkdown.tsx | 21 ++-- apps/server/src/assets/AssetAccess.test.ts | 31 +++++ .../src/assets/sourceControlMediaResponse.ts | 3 +- .../pullRequest/pullRequestMarkdown.logic.ts | 17 ++- docs/user/source-control.md | 3 + .../src/pullRequestMarkdown.test.ts | 23 +++- .../client-runtime/src/pullRequestMarkdown.ts | 17 ++- .../source-control-core/src/server/driver.ts | 3 +- .../src/shared/definition.ts | 5 + .../src/server/GitLabCredentials.test.ts | 109 +++++++++++++++++ .../src/server/GitLabCredentials.ts | 112 ++++++++++++++++++ .../GitLabSourceControlProvider.test.ts | 5 +- .../src/server/driver.ts | 8 +- .../src/server/gitLabAuthStatus.ts | 9 +- .../src/server/gitLabMediaFetch.test.ts | 100 ++++++++++++++++ .../src/server/gitLabMediaFetch.ts | 85 +++++++++++++ .../src/shared/definition.ts | 3 + .../src/shared/gitLabMedia.test.ts | 54 +++++++++ .../src/shared/gitLabMedia.ts | 66 +++++++++++ 19 files changed, 649 insertions(+), 25 deletions(-) create mode 100644 packages/source-control-gitlab/src/server/GitLabCredentials.test.ts create mode 100644 packages/source-control-gitlab/src/server/GitLabCredentials.ts create mode 100644 packages/source-control-gitlab/src/server/gitLabMediaFetch.test.ts create mode 100644 packages/source-control-gitlab/src/server/gitLabMediaFetch.ts create mode 100644 packages/source-control-gitlab/src/shared/gitLabMedia.test.ts create mode 100644 packages/source-control-gitlab/src/shared/gitLabMedia.ts diff --git a/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx b/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx index 05fe4b444a6ef..c5eeb36e871b6 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx @@ -43,7 +43,10 @@ const AutolinksContext = createContext<((text: string) => ReadonlyArray(null); +const ChangeRequestContext = createContext<{ + readonly provider: string; + readonly url: string; +} | null>(null); export function PullRequestMarkdownRepository(props: { /** The change request the markdown belongs to, whose host decides what its text links. */ @@ -70,9 +73,11 @@ export function PullRequestMarkdownRepository(props: { return ( - + {props.children} - + ); @@ -120,13 +125,13 @@ export function PullRequestMarkdown(props: { }) => boolean; }) { const mediaContext = useContext(PullRequestMediaContext); - const changeRequestUrl = useContext(ChangeRequestUrlContext); + const changeRequest = useContext(ChangeRequestContext); const segments = useMemo(() => splitPullRequestBody(props.markdown), [props.markdown]); const [undoneTicks, setUndoneTicks] = useState(0); const gallery: FilePreviewItem[] = markdownImageSources( props.imageGroupMarkdown ?? props.markdown, ) - .map((href) => (changeRequestUrl ? resolveChangeRequestMediaUrl(href, changeRequestUrl) : href)) + .map((href) => (changeRequest ? resolveChangeRequestMediaUrl(href, changeRequest) : href)) .filter( (uri) => /^https?:\/\//i.test(uri) && @@ -220,13 +225,13 @@ function PullRequestMarkdownContent(props: { const hostLineBreaks = useContext(LineBreaksContext); const autolinks = useContext(AutolinksContext); const mediaContext = useContext(PullRequestMediaContext); - const changeRequestUrl = useContext(ChangeRequestUrlContext); + const changeRequest = useContext(ChangeRequestContext); const resolveMediaUrl = (href: string) => - changeRequestUrl ? resolveChangeRequestMediaUrl(href, changeRequestUrl) : href; + changeRequest ? resolveChangeRequestMediaUrl(href, changeRequest) : href; const markdown = linkReferenceAutolinks(props.markdown, autolinks); const openPullRequest = useOpenPullRequest(); const openLink = (href: string) => { - void openPullRequest(href); + void openPullRequest(resolveMediaUrl(href)); }; const [preview, setPreview] = useState(null); const renderImage: MarkdownImageRenderer = (image) => ( diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts index be4122e6f559e..1b637432b0e58 100644 --- a/apps/server/src/assets/AssetAccess.test.ts +++ b/apps/server/src/assets/AssetAccess.test.ts @@ -1693,6 +1693,37 @@ describe("AssetAccess", () => { }).pipe(Effect.provide(Layer.mergeAll(layerTest, layerDrivers, layerIdentities))); }); + it.effect("sends the client to media its host's driver will not fetch", () => { + const url = `https://gitlab.example.test/team/app/uploads/${"0".repeat(32)}/demo.mp4`; + const media = sourceControlDefinitions.mediaUrl(url)!; + const layerDrivers = Layer.succeed(BuiltInDrivers.SourceControlDrivers, [ + { + driver: { kind: media.definition.kind, definition: media.definition }, + instance: fakeSourceControlDriverInstance(media.definition.kind, { + pullRequests: null, + fetchMedia: () => Effect.succeed(null), + }), + }, + ]); + return Effect.gen(function* () { + const response = yield* sourceControlMediaResponse( + { url: media.fetchUrl, cwd: "/repo", repository: "team/app", expiresAt: 0 }, + {}, + ); + expect(response.status).toBe(302); + expect(response.headers.location).toBe(url); + }).pipe( + Effect.provide( + Layer.mergeAll( + layerTest, + layerDrivers, + Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({}), + ), + ), + Effect.scoped, + ); + }); + it.effect("refuses media no host keeps behind a credential, without echoing the URL", () => Effect.gen(function* () { const encodeAssetAccessError = Schema.encodeEffect(Schema.fromJsonString(AssetAccessError)); diff --git a/apps/server/src/assets/sourceControlMediaResponse.ts b/apps/server/src/assets/sourceControlMediaResponse.ts index 0cc653bc06189..9a45f810e7718 100644 --- a/apps/server/src/assets/sourceControlMediaResponse.ts +++ b/apps/server/src/assets/sourceControlMediaResponse.ts @@ -66,7 +66,8 @@ export const sourceControlMediaResponse = Effect.fn( headers: forwarded, ...(repository === undefined ? {} : { repository }), }); - if (response === null) return HttpServerResponse.empty({ status: 502, headers }); + // Where the server holds no credential for it, the client loads the URL as it would unproxied. + if (response === null) return HttpServerResponse.redirect(asset.url, { status: 302, headers }); // It carries none of the upstream entity headers: a `content-length` with no body behind it // holds the connection open until the browser gives up on it. if (response.status >= 400) { diff --git a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts index 40dc1473660de..9f23d7cb3545d 100644 --- a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts @@ -68,10 +68,14 @@ export function remarkPullRequestAutolinks(options: { return (tree: MarkdownNode) => visit(tree); } -function remarkChangeRequestMediaUrls(options: { readonly changeRequestUrl: string }) { +const FORGE_RELATIVE_URL_TYPES = new Set(["image", "link", "definition"]); + +function remarkChangeRequestMediaUrls(options: { + readonly changeRequest: { readonly provider: string; readonly url: string }; +}) { const visit = (node: MarkdownNode): void => { - if ((node.type === "image" || node.type === "definition") && node.url !== undefined) { - node.url = resolveChangeRequestMediaUrl(node.url, options.changeRequestUrl); + if (FORGE_RELATIVE_URL_TYPES.has(node.type) && node.url !== undefined) { + node.url = resolveChangeRequestMediaUrl(node.url, options.changeRequest); } node.children?.forEach(visit); }; @@ -96,7 +100,12 @@ export function pullRequestMarkdownPlugins( let plugins = markdownPlugins.get(key); if (plugins === undefined) { const autolinks = changeRequestReferenceAutolinker(changeRequest); - plugins = [[remarkChangeRequestMediaUrls, { changeRequestUrl: repositoryUrl }]]; + plugins = [ + [ + remarkChangeRequestMediaUrls, + { changeRequest: { provider: changeRequest.provider, url: changeRequest.url } }, + ], + ]; if (autolinks) plugins.push([remarkPullRequestAutolinks, { autolinks }]); markdownPlugins.set(key, plugins); } diff --git a/docs/user/source-control.md b/docs/user/source-control.md index ce57f727ff6ae..eee88affa991f 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -72,6 +72,9 @@ Install [GitLab CLI](https://gitlab.com/gitlab-org/cli), then sign in: glab auth login ``` +Images and videos uploaded to a private project's merge requests load through this login on +GitLab 17.4 or later. On older versions they show as unavailable. + ### Bitbucket Open **Settings → Source control & issues**, expand **Bitbucket**, and enter one of: diff --git a/packages/client-runtime/src/pullRequestMarkdown.test.ts b/packages/client-runtime/src/pullRequestMarkdown.test.ts index d4f19173758ec..fc339e1317fc3 100644 --- a/packages/client-runtime/src/pullRequestMarkdown.test.ts +++ b/packages/client-runtime/src/pullRequestMarkdown.test.ts @@ -398,8 +398,25 @@ describe("change request media urls", () => { ["https://example.com/a.png", "https://example.com/a.png"], ["docs/a.png", "docs/a.png"], ])("resolves %s against the forge", (url, expected) => { - expect(resolveChangeRequestMediaUrl(url, "https://git.cafe/pingdotgg/t3code/pulls/31251")).toBe( - expected, - ); + const changeRequest = { + provider: "gitcafe", + url: "https://git.cafe/pingdotgg/t3code/pulls/31251", + }; + expect(resolveChangeRequestMediaUrl(url, changeRequest)).toBe(expected); + }); + + // regression: GitLab's project-relative `/uploads//` resolved against the origin + it.each([ + [ + `/uploads/${"0".repeat(32)}/shot.png`, + `https://gitlab.example.com/group/Sub/app/uploads/${"0".repeat(32)}/shot.png`, + ], + ["/-/project/42/uploads/x/a.png", "https://gitlab.example.com/-/project/42/uploads/x/a.png"], + ])("resolves GitLab's %s against the project", (url, expected) => { + const changeRequest = { + provider: "gitlab", + url: "https://gitlab.example.com/group/Sub/app/-/merge_requests/7", + }; + expect(resolveChangeRequestMediaUrl(url, changeRequest)).toBe(expected); }); }); diff --git a/packages/client-runtime/src/pullRequestMarkdown.ts b/packages/client-runtime/src/pullRequestMarkdown.ts index 8ad710325a50c..ecd3783ee96d2 100644 --- a/packages/client-runtime/src/pullRequestMarkdown.ts +++ b/packages/client-runtime/src/pullRequestMarkdown.ts @@ -359,12 +359,23 @@ export function changeRequestReferenceAutolinker( /** * Forges link uploads root-relative, as GitCafe's `/api/attachments/`. In a change request - * body that always means the forge's origin, never a path on the machine rendering it. + * body that always means the forge, never a path on the machine rendering it: the repository for + * a host that says so, as GitLab's `/uploads//`, otherwise its origin. */ -export function resolveChangeRequestMediaUrl(url: string, changeRequestUrl: string): string { +export function resolveChangeRequestMediaUrl( + url: string, + changeRequest: { readonly provider: string; readonly url: string }, +): string { if (!/^\/(?![/\\])/u.test(url)) return url; + const repositoryUrl = sourceControlClients + .find(changeRequest.provider) + ?.isRepositoryRelativePath?.(url) + ? sourceControlClients.parseChangeRequestUrl(changeRequest.url)?.link.repositoryUrl + : undefined; try { - return new URL(url, changeRequestUrl).href; + return repositoryUrl === undefined + ? new URL(url, changeRequest.url).href + : `${repositoryUrl.replace(/\/+$/u, "")}${url}`; } catch { return url; } diff --git a/packages/source-control-core/src/server/driver.ts b/packages/source-control-core/src/server/driver.ts index 7f86d0fff3b9e..ef2d638513aa6 100644 --- a/packages/source-control-core/src/server/driver.ts +++ b/packages/source-control-core/src/server/driver.ts @@ -58,7 +58,8 @@ export interface SourceControlDriverInstance { readonly issues?: IssueTrackerApi; /** * Fetches media the definition's `mediaUrl` claimed, with the credential the host serves it - * to. Null when the fetch went nowhere a response could come from, such as a redirect loop. + * to. Null when the server cannot fetch it, such as without a credential for its host or on a + * redirect loop; the client is then sent to the URL itself. */ readonly fetchMedia?: ( request: SourceControlMediaRequest, diff --git a/packages/source-control-core/src/shared/definition.ts b/packages/source-control-core/src/shared/definition.ts index d9fe29114a96c..c4b599193fca1 100644 --- a/packages/source-control-core/src/shared/definition.ts +++ b/packages/source-control-core/src/shared/definition.ts @@ -324,6 +324,11 @@ export interface SourceControlDefinition { ) => ReadonlyArray; /** True when the host renders a single newline in change request text as a line break. */ readonly hardLineBreaks?: boolean; + /** + * True for a root-relative path in change request text that the host resolves against the + * repository's web URL rather than its origin. + */ + readonly isRepositoryRelativePath?: (path: string) => boolean; /** Where the host lists a change request's checks. Absent means the change request's own page. */ readonly changeRequestChecksUrl?: (changeRequestUrl: string) => string; /** diff --git a/packages/source-control-gitlab/src/server/GitLabCredentials.test.ts b/packages/source-control-gitlab/src/server/GitLabCredentials.test.ts new file mode 100644 index 0000000000000..25edfdd5484ad --- /dev/null +++ b/packages/source-control-gitlab/src/server/GitLabCredentials.test.ts @@ -0,0 +1,109 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Redacted from "effect/Redacted"; + +import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; +import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost"; +import * as GitLabCredentials from "./GitLabCredentials.ts"; + +/** + * A scripted glab: `config get --host ` reads `config`, `api` refreshes, and + * `auth status` prints `status`. + */ +function harness(config: Record>, refreshed?: string, status = "") { + const runs: Array = []; + const run: SourceControlHost.SourceControlHost["Service"]["process"]["run"] = (input) => + Effect.sync(() => { + runs.push(input); + const host = input.args[input.args.indexOf("--host") + 1] ?? ""; + if (input.args[0] === "auth") + return TestSourceControlHost.processOutput("", { stderr: status }); + if (input.args[0] === "api") { + if (refreshed !== undefined) config[input.args[2]!]!.token = refreshed; + return TestSourceControlHost.processOutput("{}"); + } + return TestSourceControlHost.processOutput(`${config[host]?.[input.args[2]!] ?? ""}\n`); + }); + const layer = GitLabCredentials.layer.pipe( + Layer.provide(TestSourceControlHost.layer({ process: { run } })), + ); + return { layer, runs }; +} + +const token = (host: string) => + GitLabCredentials.GitLabCredentials.pipe( + Effect.flatMap((credentials) => credentials.get(host)), + Effect.map(Option.map(Redacted.value)), + ); + +describe("GitLabCredentials", () => { + it.effect("reads only the token glab stores for the host", () => { + const { layer, runs } = harness({ "gitlab.example.com": { token: "stored" } }); + return Effect.gen(function* () { + expect(yield* token("GitLab.Example.com")).toEqual(Option.some("stored")); + expect(runs.map((input) => input.args)).toEqual([ + ["config", "get", "token", "--host", "gitlab.example.com"], + ["config", "get", "is_oauth2", "--host", "gitlab.example.com"], + ["config", "get", "token", "--host", "gitlab.example.com"], + ]); + // glab would otherwise answer every host with an ambient token. + for (const input of runs) { + expect(input.env).toMatchObject({ GITLAB_TOKEN: "", OAUTH_TOKEN: "", CI_JOB_TOKEN: "" }); + } + // Cached: a second read asks glab nothing. + yield* token("gitlab.example.com"); + expect(runs).toHaveLength(3); + }).pipe(Effect.provide(layer)); + }); + + it.effect("has nothing for a host glab holds no login for", () => { + const { layer } = harness( + { "gitlab.example.com": { token: "stored" } }, + undefined, + "gitlab.example.com\n ✓ REST API Endpoint: https://gitlab.example.com/api/v4/\n", + ); + return Effect.gen(function* () { + expect(yield* token("attacker.example")).toEqual(Option.none()); + }).pipe(Effect.provide(layer)); + }); + + it.effect("reads the login whose api_host is the host", () => { + const { layer } = harness( + { "gitlab-ssh.example.com": { token: "aliased" } }, + undefined, + "gitlab-ssh.example.com\n ✓ REST API Endpoint: https://gitlab.example.com/api/v4/\n", + ); + return Effect.gen(function* () { + expect(yield* token("gitlab.example.com")).toEqual(Option.some("aliased")); + }).pipe(Effect.provide(layer)); + }); + + it.effect("refreshes an OAuth login through an API call before reading it", () => { + const { layer, runs } = harness( + { "gitlab.com": { token: "expired", is_oauth2: "true" } }, + "refreshed", + ); + return Effect.gen(function* () { + expect(yield* token("gitlab.com")).toEqual(Option.some("refreshed")); + expect(runs.map((input) => input.args)).toContainEqual([ + "api", + "--hostname", + "gitlab.com", + "user", + ]); + }).pipe(Effect.provide(layer)); + }); + + it.effect("asks glab again after a refused token is invalidated", () => { + const { layer, runs } = harness({ "gitlab.com": { token: "stored" } }); + return Effect.gen(function* () { + const credentials = yield* GitLabCredentials.GitLabCredentials; + yield* credentials.get("gitlab.com"); + yield* credentials.invalidate("gitlab.com"); + yield* credentials.get("gitlab.com"); + expect(runs).toHaveLength(6); + }).pipe(Effect.provide(layer)); + }); +}); diff --git a/packages/source-control-gitlab/src/server/GitLabCredentials.ts b/packages/source-control-gitlab/src/server/GitLabCredentials.ts new file mode 100644 index 0000000000000..428ae66c439ce --- /dev/null +++ b/packages/source-control-gitlab/src/server/GitLabCredentials.ts @@ -0,0 +1,112 @@ +import * as Cache from "effect/Cache"; +import * as Context from "effect/Context"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Redacted from "effect/Redacted"; + +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; + +import { parseGitLabAuthStatusHosts } from "./gitLabAuthStatus.ts"; + +/** How long a token is reused before `glab` is asked again. */ +const TOKEN_TTL = Duration.minutes(5); +/** A missing login is asked again soon, so a fresh `glab auth login` applies. */ +const MISSING_TTL = Duration.seconds(10); + +/** + * glab hands an environment token to whichever host it is asked about. The host here comes from a + * URL someone wrote into a merge request, so only the token stored for that host may answer. + */ +const STORED_ONLY_ENV = { + GITLAB_TOKEN: "", + GITLAB_ACCESS_TOKEN: "", + OAUTH_TOKEN: "", + CI_JOB_TOKEN: "", + GLAB_ENABLE_CI_AUTOLOGIN: "false", +}; + +/** The token `glab` stores for a GitLab host, used to read what that host serves to the user. */ +export class GitLabCredentials extends Context.Service< + GitLabCredentials, + { + /** None when `glab` holds no login for the host. */ + readonly get: (host: string) => Effect.Effect>>; + /** Drops the held token after GitLab refused it, so the next read asks `glab` again. */ + readonly invalidate: (host: string) => Effect.Effect; + } +>()("@t3tools/source-control-gitlab/server/GitLabCredentials") {} + +/** @public */ +export const make = Effect.gen(function* () { + const { process } = yield* SourceControlHost.SourceControlHost; + const workingDirectory = yield* HostProcess.WorkingDirectory; + + const run = (args: ReadonlyArray, timeoutMs = 10_000) => + process.run({ + operation: "GitLabCredentials.get", + command: "glab", + args, + cwd: workingDirectory, + env: STORED_ONLY_ENV, + allowNonZeroExit: true, + timeoutMs, + maxOutputBytes: 64 * 1024, + }); + const glab = (args: ReadonlyArray) => + run(args).pipe(Effect.map((output) => output.stdout.trim())); + + const storedToken = (host: string) => glab(["config", "get", "token", "--host", host]); + + /** The login whose `api_host` is `host`, as a login stored under an SSH alias has. */ + const aliasFor = Effect.fn("GitLabCredentials.aliasFor")(function* (host: string) { + // glab 1.79+ lists every host only with `--all`; older glab rejects the flag. + for (const args of [ + ["auth", "status", "--all"], + ["auth", "status"], + ]) { + const output = yield* run(args, 30_000); + const hosts = parseGitLabAuthStatusHosts(`${output.stdout}\n${output.stderr}`); + if (hosts.length > 0) return hosts.find((entry) => entry.apiHost === host)?.host; + } + return undefined; + }); + + const login = Effect.fn("GitLabCredentials.login")(function* (host: string) { + if ((yield* storedToken(host)) === "") return Option.none(); + // An OAuth login expires within hours and glab refreshes it only on an API call. + if ((yield* glab(["config", "get", "is_oauth2", "--host", host])) === "true") { + yield* glab(["api", "--hostname", host, "user"]).pipe(Effect.ignore); + } + const token = yield* storedToken(host); + return token === "" ? Option.none() : Option.some(Redacted.make(token)); + }); + + const lookup = Effect.fn("GitLabCredentials.lookup")(function* (host: string) { + const token = yield* login(host); + if (Option.isSome(token)) return token; + const alias = yield* aliasFor(host); + return alias === undefined || alias === host ? Option.none() : yield* login(alias); + }); + + const cache = yield* Cache.makeWith( + (host: string) => lookup(host).pipe(Effect.orElseSucceed(() => Option.none())), + { + capacity: 32, + timeToLive: (exit) => + Exit.isSuccess(exit) && Option.isSome(exit.value) ? TOKEN_TTL : MISSING_TTL, + }, + ); + + return GitLabCredentials.of({ + get: Effect.fn("GitLabCredentials.get")((host) => Cache.get(cache, host.trim().toLowerCase())), + invalidate: Effect.fn("GitLabCredentials.invalidate")((host) => + Cache.invalidate(cache, host.trim().toLowerCase()), + ), + }); +}); + +export const layer = Layer.effect(GitLabCredentials, make); diff --git a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts index 8e5077044c6b3..76b4070459ffd 100644 --- a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts @@ -190,12 +190,13 @@ it("parses authenticated GitLab auth status hosts with ports and single-label na assert.deepStrictEqual( parseGitLabAuthStatusHosts(`localhost:8080 ✓ Logged in to localhost:8080 as local-user + ✓ REST API Endpoint: https://gitlab.localtest/api/v4/ selfhosted ✓ Logged in to selfhosted as single-label-user `), [ - { host: "localhost:8080", account: "local-user" }, - { host: "selfhosted", account: "single-label-user" }, + { host: "localhost:8080", account: "local-user", apiHost: "gitlab.localtest" }, + { host: "selfhosted", account: "single-label-user", apiHost: null }, ], ); }); diff --git a/packages/source-control-gitlab/src/server/driver.ts b/packages/source-control-gitlab/src/server/driver.ts index 2c71e348547f5..8a82e5f7482a3 100644 --- a/packages/source-control-gitlab/src/server/driver.ts +++ b/packages/source-control-gitlab/src/server/driver.ts @@ -8,18 +8,24 @@ import * as Layer from "effect/Layer"; import { definition } from "../shared/definition.ts"; import * as GitLabCli from "./GitLabCli.ts"; +import * as GitLabCredentials from "./GitLabCredentials.ts"; +import * as GitLabMediaFetch from "./gitLabMediaFetch.ts"; import * as GitLabPullRequestCli from "./GitLabPullRequestCli.ts"; import * as GitLabIssueTracker from "./GitLabIssueTracker.ts"; import * as GitLabPullRequestProvider from "./GitLabPullRequestProvider.ts"; import * as GitLabSourceControlProvider from "./GitLabSourceControlProvider.ts"; -const services = GitLabPullRequestCli.layer.pipe(Layer.provideMerge(GitLabCli.layer)); +const services = Layer.merge( + GitLabPullRequestCli.layer.pipe(Layer.provideMerge(GitLabCli.layer)), + GitLabCredentials.layer, +); const makeInstance = Effect.all({ sourceControl: GitLabSourceControlProvider.make, discovery: Effect.succeed(GitLabSourceControlProvider.discovery), pullRequests: GitLabPullRequestProvider.make, issues: GitLabIssueTracker.make, + fetchMedia: GitLabMediaFetch.make, }); export const driver = defineSourceControlDriver({ diff --git a/packages/source-control-gitlab/src/server/gitLabAuthStatus.ts b/packages/source-control-gitlab/src/server/gitLabAuthStatus.ts index f54e300353ad4..4068e1c7abce5 100644 --- a/packages/source-control-gitlab/src/server/gitLabAuthStatus.ts +++ b/packages/source-control-gitlab/src/server/gitLabAuthStatus.ts @@ -1,9 +1,12 @@ const HOST_LINE_PATTERN = /^(?:[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?|\[[a-f0-9:.]+\])(?::\d+)?$/iu; const LOGGED_IN_PATTERN = /Logged in to .+? as\s+([^\s(]+)/iu; +const REST_ENDPOINT_PATTERN = /REST API Endpoint:\s*https?:\/\/([^/\s]+)\//iu; export interface GitLabAuthStatusHost { readonly host: string; readonly account: string | null; + /** The host its API calls go to, which glab's `api_host` can set apart from `host`. */ + readonly apiHost: string | null; } export function parseGitLabAuthStatusHosts(text: string): ReadonlyArray { @@ -14,8 +17,10 @@ export function parseGitLabAuthStatusHosts(text: string): ReadonlyArray { if (currentHost === null) return; - const account = LOGGED_IN_PATTERN.exec(currentLines.join("\n"))?.[1]?.trim() || null; - hosts.push({ host: currentHost, account }); + const lines = currentLines.join("\n"); + const account = LOGGED_IN_PATTERN.exec(lines)?.[1]?.trim() || null; + const apiHost = REST_ENDPOINT_PATTERN.exec(lines)?.[1]?.toLowerCase() ?? null; + hosts.push({ host: currentHost, account, apiHost }); currentHost = null; currentLines = []; }; diff --git a/packages/source-control-gitlab/src/server/gitLabMediaFetch.test.ts b/packages/source-control-gitlab/src/server/gitLabMediaFetch.test.ts new file mode 100644 index 0000000000000..55310e789d305 --- /dev/null +++ b/packages/source-control-gitlab/src/server/gitLabMediaFetch.test.ts @@ -0,0 +1,100 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Redacted from "effect/Redacted"; +import { HttpClient, HttpClientResponse } from "effect/http"; + +import * as GitLabCredentials from "./GitLabCredentials.ts"; +import * as GitLabMediaFetch from "./gitLabMediaFetch.ts"; + +const SECRET = "66dbcd21ec5d24ed6ea225176098d52b"; +const UPLOAD = `https://gitlab.example.com/group/app/uploads/${SECRET}/shot.png`; +const API = `https://gitlab.example.com/api/v4/projects/group%2Fapp/uploads/${SECRET}/shot.png`; + +/** A GitLab that answers `respond`, with `token` as the stored `glab` login. */ +function fetchWith( + token: string | null, + respond: (url: string, authorization: string | undefined) => Response, + url = UPLOAD, +) { + const requests: Array<[string, string | undefined]> = []; + const invalidated: Array = []; + const layer = Layer.merge( + Layer.mock(GitLabCredentials.GitLabCredentials)({ + get: () => Effect.succeed(Option.fromNullishOr(token).pipe(Option.map(Redacted.make))), + invalidate: (host) => Effect.sync(() => void invalidated.push(host)), + }), + Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => { + requests.push([request.url, request.headers.authorization]); + return Effect.succeed( + HttpClientResponse.fromWeb(request, respond(request.url, request.headers.authorization)), + ); + }), + ), + ); + const status = Effect.gen(function* () { + const fetchMedia = yield* GitLabMediaFetch.make; + return (yield* fetchMedia({ url, headers: {} }))?.status; + }).pipe(Effect.provide(layer), Effect.scoped); + return { status, requests, invalidated }; +} + +describe("GitLabMediaFetch", () => { + it.effect("reads the upload through the API with the glab login for its host", () => { + const { status, requests } = fetchWith("stored", () => new Response(null, { status: 200 })); + return Effect.gen(function* () { + expect(yield* status).toBe(200); + expect(requests).toEqual([[API, "Bearer stored"]]); + }); + }); + + it.effect("keeps the token off the object store a redirect hands the upload to", () => { + const { status, requests } = fetchWith("stored", (url) => + url === API + ? new Response(null, { status: 302, headers: { location: "https://objects.example/s" } }) + : new Response(null, { status: 200 }), + ); + return Effect.gen(function* () { + expect(yield* status).toBe(200); + expect(requests).toEqual([ + [API, "Bearer stored"], + ["https://objects.example/s", undefined], + ]); + }); + }); + + it.effect("loads a gitlab.com upload without a login, as a public project serves it", () => { + const upload = `https://gitlab.com/group/app/uploads/${SECRET}/shot.png`; + const { status, requests } = fetchWith(null, () => new Response(null, { status: 200 }), upload); + return Effect.gen(function* () { + expect(yield* status).toBe(200); + expect(requests).toEqual([[upload, undefined]]); + }); + }); + + it.effect("asks no host that glab is not signed in to", () => { + const { status, requests } = fetchWith(null, () => new Response(null, { status: 200 })); + return Effect.gen(function* () { + expect(yield* status).toBeUndefined(); + expect(requests).toEqual([]); + }); + }); + + it.effect("drops a refused token and falls back to the upload itself", () => { + const { status, requests, invalidated } = fetchWith( + "revoked", + (url) => new Response(null, { status: url === API ? 401 : 200 }), + ); + return Effect.gen(function* () { + expect(yield* status).toBe(200); + expect(requests).toEqual([ + [API, "Bearer revoked"], + [UPLOAD, undefined], + ]); + expect(invalidated).toEqual(["gitlab.example.com"]); + }); + }); +}); diff --git a/packages/source-control-gitlab/src/server/gitLabMediaFetch.ts b/packages/source-control-gitlab/src/server/gitLabMediaFetch.ts new file mode 100644 index 0000000000000..3412e98981270 --- /dev/null +++ b/packages/source-control-gitlab/src/server/gitLabMediaFetch.ts @@ -0,0 +1,85 @@ +import type { SourceControlMediaRequest } from "@t3tools/source-control-core/server/driver"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Redacted from "effect/Redacted"; +import { + FetchHttpClient, + HttpClient, + HttpClientRequest, + type HttpClientResponse, +} from "effect/http"; + +import { gitLabUploadApiUrl, parseGitLabUpload } from "../shared/gitLabMedia.ts"; + +import * as GitLabCredentials from "./GitLabCredentials.ts"; + +const PUBLIC_HOST = "gitlab.com"; +const MAX_REDIRECTS = 3; +const MANUAL_REDIRECT: RequestInit = { redirect: "manual" }; + +export const make = Effect.gen(function* () { + const credentials = yield* GitLabCredentials.GitLabCredentials; + const httpClient = HttpClient.withScope(yield* HttpClient.HttpClient); + + /** Follows redirects by hand so `authorization` reaches only `origin`, not object storage. */ + const fetchFollowingRedirects = Effect.fnUntraced(function* ( + url: string, + headers: Readonly>, + credential: { readonly origin: string; readonly authorization: string } | null, + ) { + let target = url; + for (let hop = 0; ; hop += 1) { + const authorization = + credential !== null && new URL(target).origin === credential.origin + ? credential.authorization + : null; + const response: HttpClientResponse.HttpClientResponse = yield* httpClient + .execute( + HttpClientRequest.get(target).pipe( + HttpClientRequest.setHeaders({ + ...headers, + // The bytes are streamed straight through, so never let an encoding layer in. + "accept-encoding": "identity", + ...(authorization === null ? {} : { authorization }), + }), + ), + ) + .pipe( + Effect.provideService(FetchHttpClient.RequestInit, MANUAL_REDIRECT), + // An upload's secret path segment grants access; keep it out of tracing spans. + Effect.provideService(HttpClient.TracerDisabledWhen, () => true), + ); + const location = response.headers.location; + if (response.status < 300 || response.status >= 400) return response; + if (!location || hop >= MAX_REDIRECTS) return null; + const next = URL.parse(location, target); + if (next === null || next.protocol !== "https:" || next.username || next.password) { + return null; + } + target = next.toString(); + } + }); + + /** + * Reads the upload through the API with the `glab` login for its host. Where the API refuses it + * (GitLab before 17.4), or gitlab.com without a login, the upload itself serves a public project. + */ + return Effect.fn("GitLabMediaFetch.fetchMedia")(function* (request: SourceControlMediaRequest) { + const url = new URL(request.url); + const upload = parseGitLabUpload(url); + if (upload === null) return null; + const token = yield* credentials.get(url.host); + // Anyone can write the URL into a body, so only a host `glab` is signed in to, or the public + // GitLab, is ever asked. + if (Option.isNone(token) && url.host !== PUBLIC_HOST) return null; + if (Option.isSome(token)) { + const response = yield* fetchFollowingRedirects(gitLabUploadApiUrl(upload), request.headers, { + origin: upload.origin, + authorization: `Bearer ${Redacted.value(token.value)}`, + }); + if (response !== null && response.status < 400) return response; + if (response?.status === 401) yield* credentials.invalidate(url.host); + } + return yield* fetchFollowingRedirects(request.url, request.headers, null); + }); +}); diff --git a/packages/source-control-gitlab/src/shared/definition.ts b/packages/source-control-gitlab/src/shared/definition.ts index f879329b3f53f..f1b7524520613 100644 --- a/packages/source-control-gitlab/src/shared/definition.ts +++ b/packages/source-control-gitlab/src/shared/definition.ts @@ -12,6 +12,7 @@ import { projectChangeRequestHost, remoteWebOrigin, } from "@t3tools/source-control-core/shared/definition"; +import { gitLabMediaUrl, isGitLabProjectRelativePath } from "./gitLabMedia.ts"; import { icon } from "./icon.ts"; import { gitLabReferenceAutolinks } from "./referenceAutolinks.ts"; @@ -95,4 +96,6 @@ export const definition = defineSourceControl({ isChangeRequestInProjectRepository(projectChangeRequestHost(identity, KIND), identity, link), canReadChangeRequestOnHost: (identity, link) => isChangeRequestOnProjectHost(projectChangeRequestHost(identity, KIND), identity, link), + isRepositoryRelativePath: isGitLabProjectRelativePath, + mediaUrl: gitLabMediaUrl, }); diff --git a/packages/source-control-gitlab/src/shared/gitLabMedia.test.ts b/packages/source-control-gitlab/src/shared/gitLabMedia.test.ts new file mode 100644 index 0000000000000..1d09a74c5951a --- /dev/null +++ b/packages/source-control-gitlab/src/shared/gitLabMedia.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { gitLabMediaUrl, gitLabUploadApiUrl, parseGitLabUpload } from "./gitLabMedia.ts"; + +const SECRET = "66dbcd21ec5d24ed6ea225176098d52b"; + +const media = (url: string) => gitLabMediaUrl(new URL(url)); + +describe("gitLabMedia", () => { + it("maps project-path and project-id upload URLs to the upload API", () => { + const byPath = parseGitLabUpload( + new URL(`https://gitlab.example.com/group/sub/project/uploads/${SECRET}/my%20shot.png`), + ); + expect(byPath && gitLabUploadApiUrl(byPath)).toBe( + `https://gitlab.example.com/api/v4/projects/group%2Fsub%2Fproject/uploads/${SECRET}/my%20shot.png`, + ); + const byId = parseGitLabUpload( + new URL(`https://gitlab.example.com:8443/-/project/42/uploads/${SECRET}/demo.mp4`), + ); + expect(byId && gitLabUploadApiUrl(byId)).toBe( + `https://gitlab.example.com:8443/api/v4/projects/42/uploads/${SECRET}/demo.mp4`, + ); + }); + + it("drops query and fragment from the canonical URL", () => { + expect(media(`https://gitlab.com/team/app/uploads/${SECRET}/demo.mp4?x=1#t=2`)).toEqual({ + fetchUrl: `https://gitlab.com/team/app/uploads/${SECRET}/demo.mp4`, + fileName: "demo.mp4", + immutable: true, + }); + }); + + it("rejects anything that is not a project upload over https", () => { + for (const url of [ + `http://gitlab.com/team/app/uploads/${SECRET}/a.png`, + `https://user:pw@gitlab.com/team/app/uploads/${SECRET}/a.png`, + `https://gitlab.com/uploads/${SECRET}/a.png`, + `https://gitlab.com/team/app/-/uploads/${SECRET}/a.png`, + `https://gitlab.com/uploads/-/system/user/avatar/1/avatar.png`, + `https://gitlab.com/team/app/uploads/not-a-secret/a.png`, + ]) { + expect(media(url), url).toBeNull(); + } + }); + + it("names the file from its decoded last segment", () => { + expect(media(`https://gitlab.com/a/b/uploads/${SECRET}/my%20shot.png`)?.fileName).toBe( + "my shot.png", + ); + expect(media(`https://gitlab.com/a/b/uploads/${SECRET}/%E0%A4%A.png`)?.fileName).toBe( + "%E0%A4%A.png", + ); + }); +}); diff --git a/packages/source-control-gitlab/src/shared/gitLabMedia.ts b/packages/source-control-gitlab/src/shared/gitLabMedia.ts new file mode 100644 index 0000000000000..38deca1fd272d --- /dev/null +++ b/packages/source-control-gitlab/src/shared/gitLabMedia.ts @@ -0,0 +1,66 @@ +import type { SourceControlMediaUrl } from "@t3tools/source-control-core/shared/definition"; + +/** + * GitLab writes uploads into a merge request as project-relative `/uploads//` links, + * and a private project serves them only to a signed-in request. + */ +const UPLOAD_PATH_PATTERN = + /^\/(?:-\/project\/(\d+)|((?:[\w.-]+\/)*[\w.-]+))\/uploads\/([0-9a-f]{32})\/([^/]+)$/iu; +/** GitLab writes uploads into text as `/uploads//`, relative to the project. */ +const PROJECT_RELATIVE_UPLOAD_PATTERN = /^\/uploads\/[0-9a-f]{32}\//iu; + +export interface GitLabUpload { + readonly origin: string; + /** A numeric project id or the full project path, as the API's `:id` accepts either. */ + readonly project: string; + readonly secret: string; + /** The file name segment, still percent-encoded. */ + readonly fileSegment: string; +} + +export function parseGitLabUpload(url: URL): GitLabUpload | null { + if (url.protocol !== "https:" || url.username || url.password) return null; + const match = UPLOAD_PATH_PATTERN.exec(url.pathname); + if (match === null) return null; + const [, projectId, projectPath, secret, fileSegment] = match; + // `-` separates a project path from its routes, so it is never part of one. + if (projectPath?.split("/").includes("-")) return null; + return { + origin: url.origin, + project: projectId ?? projectPath!, + secret: secret!, + fileSegment: fileSegment!, + }; +} + +/** The API route that serves the upload to any project member (GitLab 17.4+). */ +export function gitLabUploadApiUrl(upload: GitLabUpload): string { + return `${upload.origin}/api/v4/projects/${encodeURIComponent(upload.project)}/uploads/${upload.secret}/${upload.fileSegment}`; +} + +function fileName(fileSegment: string): string { + let decoded: string; + try { + decoded = decodeURIComponent(fileSegment); + } catch { + decoded = fileSegment; + } + const name = decoded.replace(/[\p{Cc}\\/]/gu, ""); + return name.length > 0 ? name : "gitlab-upload"; +} + +export function gitLabMediaUrl(url: URL): SourceControlMediaUrl | null { + const upload = parseGitLabUpload(url); + return upload === null + ? null + : { + fetchUrl: `${upload.origin}${url.pathname}`, + fileName: fileName(upload.fileSegment), + // The secret is minted per upload, so a URL never names different bytes. + immutable: true, + }; +} + +export function isGitLabProjectRelativePath(path: string): boolean { + return PROJECT_RELATIVE_UPLOAD_PATTERN.test(path); +} From 513f267b122925f9c520a8a74e5a9509072300fe Mon Sep 17 00:00:00 2001 From: SeongHoon Ryu <4997174+ryush00@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:46:58 +0900 Subject: [PATCH 17/21] feat(source-control): support GitHub PR and GitLab MR file attachments --- .../src/components/ui/AppSymbol.android.tsx | 2 + .../pull-requests/PullRequestAttachButton.tsx | 99 +++++ .../PullRequestDiscussionScreen.tsx | 23 +- .../pull-requests/PullRequestEditScreen.tsx | 24 +- .../PullRequestInlineCommentScreen.tsx | 22 + .../pull-requests/PullRequestReviewSheet.tsx | 27 ++ .../usePullRequestAttachmentUpload.ts | 393 +++++++++++++++++ .../usePullRequestCompletions.ts | 5 + .../usePullRequestPermissions.ts | 5 + apps/mobile/src/i18n/translations/de.json | 9 +- apps/mobile/src/i18n/translations/en.json | 9 +- apps/mobile/src/i18n/translations/es.json | 9 +- apps/mobile/src/i18n/translations/fr.json | 9 +- apps/mobile/src/i18n/translations/ja.json | 9 +- apps/mobile/src/i18n/translations/ko.json | 9 +- apps/mobile/src/i18n/translations/pt-BR.json | 9 +- apps/mobile/src/i18n/translations/ru.json | 9 +- apps/mobile/src/i18n/translations/sv.json | 9 +- apps/mobile/src/i18n/translations/zh.json | 9 +- apps/mobile/src/state/attachments.test.ts | 27 +- apps/mobile/src/state/attachments.ts | 14 +- .../src/assets/AttachmentUpload.test.ts | 25 ++ apps/server/src/assets/AttachmentUpload.ts | 36 +- apps/server/src/auth/RpcAuthorization.test.ts | 85 ++++ apps/server/src/binCli.ts | 2 + apps/server/src/cli/deferredImports.test.ts | 9 +- apps/server/src/cli/pr.ts | 60 +++ apps/server/src/cli/prAttach.test.ts | 49 ++ apps/server/src/cli/prAttach.ts | 237 ++++++++++ .../toolkits/pullRequests/handlers.test.ts | 65 ++- .../src/mcp/toolkits/pullRequests/handlers.ts | 93 +++- .../src/mcp/toolkits/pullRequests/tools.ts | 40 ++ .../src/observability/RpcInstrumentation.ts | 1 + .../src/provider/agentContextBudget.json | 2 +- .../pullRequest/PullRequestService.test.ts | 95 ++++ .../src/pullRequest/PullRequestService.ts | 103 +++++ apps/server/src/ws.ts | 44 +- ...PullRequestMarkdownEditor.browser.test.tsx | 77 +++- .../PullRequestMarkdownTextarea.tsx | 281 +++++++++++- .../uploadPullRequestAttachment.ts | 144 ++++++ apps/web/src/i18n/translations/de.json | 10 +- apps/web/src/i18n/translations/en.json | 10 +- apps/web/src/i18n/translations/es.json | 10 +- apps/web/src/i18n/translations/fr.json | 10 +- apps/web/src/i18n/translations/ja.json | 10 +- apps/web/src/i18n/translations/ko.json | 10 +- apps/web/src/i18n/translations/pt-BR.json | 10 +- apps/web/src/i18n/translations/ru.json | 10 +- apps/web/src/i18n/translations/sv.json | 10 +- apps/web/src/i18n/translations/zh.json | 10 +- docs/user/source-control.md | 8 + packages/client-runtime/package.json | 4 + .../src/pullRequestAttachments.test.ts | 97 ++++ .../src/pullRequestAttachments.ts | 166 +++++++ .../client-runtime/src/state/pullRequests.ts | 5 + packages/contracts/src/assets.ts | 12 + .../contracts/src/clientRpcPermissions.ts | 7 + packages/contracts/src/pullRequest.ts | 21 + packages/contracts/src/rpc.ts | 10 + .../src/server/PullRequestProvider.ts | 14 + .../server/GitHubPullRequestProvider.test.ts | 33 ++ .../src/server/GitHubPullRequestProvider.ts | 30 +- .../src/server/driver.ts | 8 +- .../src/server/gitHubAttachmentUpload.test.ts | 248 +++++++++++ .../src/server/gitHubAttachmentUpload.ts | 417 ++++++++++++++++++ .../src/server/GitLabCredentials.ts | 65 +++ .../src/server/GitLabPullRequestProvider.ts | 1 + .../src/server/driver.ts | 6 +- .../src/server/gitLabAttachmentUpload.test.ts | 192 ++++++++ .../src/server/gitLabAttachmentUpload.ts | 312 +++++++++++++ 70 files changed, 3859 insertions(+), 76 deletions(-) create mode 100644 apps/mobile/src/features/pull-requests/PullRequestAttachButton.tsx create mode 100644 apps/mobile/src/features/pull-requests/usePullRequestAttachmentUpload.ts create mode 100644 apps/server/src/cli/pr.ts create mode 100644 apps/server/src/cli/prAttach.test.ts create mode 100644 apps/server/src/cli/prAttach.ts create mode 100644 apps/web/src/components/pullRequest/uploadPullRequestAttachment.ts create mode 100644 packages/client-runtime/src/pullRequestAttachments.test.ts create mode 100644 packages/client-runtime/src/pullRequestAttachments.ts create mode 100644 packages/source-control-github/src/server/gitHubAttachmentUpload.test.ts create mode 100644 packages/source-control-github/src/server/gitHubAttachmentUpload.ts create mode 100644 packages/source-control-gitlab/src/server/gitLabAttachmentUpload.test.ts create mode 100644 packages/source-control-gitlab/src/server/gitLabAttachmentUpload.ts diff --git a/apps/mobile/src/components/ui/AppSymbol.android.tsx b/apps/mobile/src/components/ui/AppSymbol.android.tsx index 5333af3ea577a..dee3843cf23bd 100644 --- a/apps/mobile/src/components/ui/AppSymbol.android.tsx +++ b/apps/mobile/src/components/ui/AppSymbol.android.tsx @@ -99,6 +99,7 @@ import IconMinus from "@tabler/icons-react-native/IconMinus"; import IconMoon from "@tabler/icons-react-native/IconMoon"; import IconNetwork from "@tabler/icons-react-native/IconNetwork"; import IconPalette from "@tabler/icons-react-native/IconPalette"; +import IconPaperclip from "@tabler/icons-react-native/IconPaperclip"; import IconPencil from "@tabler/icons-react-native/IconPencil"; import IconPlug from "@tabler/icons-react-native/IconPlug"; import IconPhoto from "@tabler/icons-react-native/IconPhoto"; @@ -254,6 +255,7 @@ const ANDROID_ICON_BY_SF_SYMBOL = { "pin.slash": IconPinnedOff, play: IconPlayerPlay, pause: IconPlayerPause, + paperclip: IconPaperclip, plus: IconPlus, minus: IconMinus, "slash.circle": IconBan, diff --git a/apps/mobile/src/features/pull-requests/PullRequestAttachButton.tsx b/apps/mobile/src/features/pull-requests/PullRequestAttachButton.tsx new file mode 100644 index 0000000000000..de70ee88dfba7 --- /dev/null +++ b/apps/mobile/src/features/pull-requests/PullRequestAttachButton.tsx @@ -0,0 +1,99 @@ +import type { MenuAction } from "@react-native-menu/menu"; +import { useGT } from "gt-react-native"; +import { Pressable, View } from "react-native"; + +import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator"; +import { SymbolView } from "../../components/ui/AppSymbol"; +import { AppText as Text } from "../../components/ui/AppText"; +import { Menu } from "../../components/ui/Menu"; +import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing"; + +export function PullRequestAttachButton(props: { + readonly disabled?: boolean; + readonly uploading: boolean; + readonly uploadingCount?: number; + readonly variant?: "row" | "icon"; + readonly onPickMedia: () => Promise; + readonly onPickFiles: () => Promise; +}) { + const gt = useGT(); + const { scale } = useAndroidControlSizing(); + const isDisabled = Boolean(props.disabled); + const label = props.uploading + ? props.uploadingCount && props.uploadingCount > 1 + ? gt("Uploading {count} files…", { count: props.uploadingCount }) + : gt("Uploading file…") + : gt("Attach file"); + const actions: MenuAction[] = [ + { id: "photos", title: gt("Photo Library"), image: "photo" }, + { id: "files", title: gt("Choose Files"), image: "folder" }, + ]; + + const trigger = + props.variant === "icon" ? ( + + {props.uploading ? ( + + ) : ( + + )} + + ) : ( + + + {props.uploading ? ( + + ) : ( + + )} + {label} + + + ); + + if (isDisabled) { + return trigger; + } + + return ( + { + if (nativeEvent.event === "photos") { + void props.onPickMedia(); + } else if (nativeEvent.event === "files") { + void props.onPickFiles(); + } + }} + > + {trigger} + + ); +} diff --git a/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx index f15f2f79e78a8..35ac338dd7d1c 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx @@ -34,6 +34,8 @@ import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff" import { usePullRequestPermissions } from "./usePullRequestPermissions"; import { pullRequestReviewKey } from "./pullRequestReviewDrafts"; import { PullRequestCompletionSuggestions } from "./PullRequestCompletionSuggestions"; +import { PullRequestAttachButton } from "./PullRequestAttachButton"; +import { usePullRequestAttachmentUpload } from "./usePullRequestAttachmentUpload"; import { usePullRequestCompletions } from "./usePullRequestCompletions"; import { m } from "../../i18n/messages"; @@ -79,6 +81,15 @@ function Discussion({ params }: { params: PullRequestParams & { readonly discuss onChangeValue: setBody, support: detail.data?.capabilities ?? null, }); + const attachments = usePullRequestAttachmentUpload({ + environmentId: target.environmentId, + reference: target.input, + provider: detail.data?.provider, + value: body, + updateValue: setBody, + selection: completions.currentSelection, + onPlaceCursor: completions.placeCursor, + }); const [extra, setExtra] = useState([]); const [cursor, setCursor] = useState(); const [busy, setBusy] = useState(false); @@ -310,6 +321,16 @@ function Discussion({ params }: { params: PullRequestParams & { readonly discuss onLayout={(event) => setComposerHeight(event.nativeEvent.layout.height)} className="flex-row items-end gap-1 p-1" > + {permissions.canAttach ? ( + + ) : null} void post()} /> diff --git a/apps/mobile/src/features/pull-requests/PullRequestEditScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestEditScreen.tsx index 0c6483207bd42..e2e1a3702551e 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestEditScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestEditScreen.tsx @@ -17,6 +17,8 @@ import { PullRequestSheetContent } from "./PullRequestSheetContent"; import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff"; import { usePullRequestPermissions } from "./usePullRequestPermissions"; import { PullRequestCompletionSuggestions } from "./PullRequestCompletionSuggestions"; +import { PullRequestAttachButton } from "./PullRequestAttachButton"; +import { usePullRequestAttachmentUpload } from "./usePullRequestAttachmentUpload"; import { usePullRequestCompletions } from "./usePullRequestCompletions"; import { m } from "../../i18n/messages"; @@ -60,6 +62,15 @@ export function PullRequestEditScreen({ route }: StaticScreenProps setDraft((current) => updater(current ?? original ?? "")), + selection: completions.currentSelection, + onPlaceCursor: completions.placeCursor, + }); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const inFlight = useRef(false); @@ -90,7 +101,7 @@ export function PullRequestEditScreen({ route }: StaticScreenProps { - if (!allowed || unchanged || invalid || inFlight.current) return; + if (!allowed || unchanged || invalid || attachments.uploading || inFlight.current) return; inFlight.current = true; setBusy(true); setError(null); @@ -144,7 +155,7 @@ export function PullRequestEditScreen({ route }: StaticScreenProps void save()} /> } @@ -188,6 +199,15 @@ export function PullRequestEditScreen({ route }: StaticScreenProps + {params.field !== "title" && permissions.canAttach && allowed ? ( + + ) : null} {readOnlyReason ? ( {readOnlyReason} ) : null} diff --git a/apps/mobile/src/features/pull-requests/PullRequestInlineCommentScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestInlineCommentScreen.tsx index e9df169649935..de94bbcb3166c 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestInlineCommentScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestInlineCommentScreen.tsx @@ -17,6 +17,8 @@ import { reviewPositionLabel } from "./pullRequestDiffComments"; import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff"; import { usePullRequestPermissions } from "./usePullRequestPermissions"; import { PullRequestCompletionSuggestions } from "./PullRequestCompletionSuggestions"; +import { PullRequestAttachButton } from "./PullRequestAttachButton"; +import { usePullRequestAttachmentUpload } from "./usePullRequestAttachmentUpload"; import { usePullRequestCompletions } from "./usePullRequestCompletions"; export type InlineCommentParams = PullRequestParams & { @@ -45,6 +47,16 @@ export function PullRequestInlineCommentScreen({ route }: StaticScreenProps setBody((current) => updater(current ?? saved?.body ?? "")), + selection: completions.currentSelection, + onPlaceCursor: completions.placeCursor, + }); useFocusEffect(refreshDetail); const permissions = usePullRequestPermissions(params, detail.data); const stale = detail.data && detail.data.headSha !== params.headSha; @@ -98,6 +110,7 @@ export function PullRequestInlineCommentScreen({ route }: StaticScreenProps + {permissions.canAttach && permissions.canInlineComment && !stale ? ( + + ) : null} Saved comments are private until you submit your review. diff --git a/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx b/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx index ec45e5f3a33ca..f980b24681c5c 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx @@ -23,6 +23,8 @@ import { PullRequestSheetContent as SheetContent } from "./PullRequestSheetConte import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff"; import { usePullRequestPermissions } from "./usePullRequestPermissions"; import { PullRequestCompletionSuggestions } from "./PullRequestCompletionSuggestions"; +import { PullRequestAttachButton } from "./PullRequestAttachButton"; +import { usePullRequestAttachmentUpload } from "./usePullRequestAttachmentUpload"; import { usePullRequestCompletions } from "./usePullRequestCompletions"; import { m as resolveMessage } from "../../i18n/messages"; @@ -97,6 +99,21 @@ export function PullRequestReviewSheet({ onChangeValue: setBody, support: result.data?.capabilities ?? null, }); + const attachments = usePullRequestAttachmentUpload({ + environmentId: target.environmentId, + reference: target.input, + provider: result.data?.provider, + value: body, + updateValue: (updater) => + store.update((draft) => ({ + ...draft, + ...(params.mode === "review" + ? { summary: updater(draft.summary) } + : { comment: updater(draft.comment) }), + })), + selection: completions.currentSelection, + onPlaceCursor: completions.placeCursor, + }); const stale = store.draft.comments.some((comment) => comment.headSha !== result.data?.headSha); const [requestedVerdict, setRequestedVerdict] = useState("comment"); const offered = VERDICTS.filter((option) => permissions.verdicts.includes(option.value)); @@ -110,6 +127,7 @@ export function PullRequestReviewSheet({ : false; const canSubmit = store.ready && + !attachments.uploading && (!reviewing || (!stale && canSubmitComments)) && (reviewing ? verdict !== undefined && @@ -213,6 +231,15 @@ export function PullRequestReviewSheet({ className="min-h-36 rounded-[20px] bg-grouped-card p-4 text-base text-foreground" style={{ textAlignVertical: "top" }} /> + {permissions.canAttach ? ( + + ) : null} {reviewing && store.draft.comments.length ? ( diff --git a/apps/mobile/src/features/pull-requests/usePullRequestAttachmentUpload.ts b/apps/mobile/src/features/pull-requests/usePullRequestAttachmentUpload.ts new file mode 100644 index 0000000000000..fe2bedce35e4b --- /dev/null +++ b/apps/mobile/src/features/pull-requests/usePullRequestAttachmentUpload.ts @@ -0,0 +1,393 @@ +import { + insertPullRequestUploadPlaceholders, + makePullRequestUploadPlaceholder, + removePullRequestUploadPlaceholder, + replacePullRequestUploadPlaceholder, + validatePullRequestAttachmentClientFile, +} from "@t3tools/client-runtime/pull-request-attachments"; +import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets"; +import { attachmentUploadError } from "@t3tools/client-runtime/state/attachment-uploads"; +import { + deletePendingAttachmentUpload, + runAttachmentUploadCycle, +} from "@t3tools/client-runtime/state/attachments"; +import { + runAtomCommand, + settlePromise, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import { + AuthOrchestrationOperateScope, + AuthSourceControlWriteScope, + type EnvironmentId, + type PullRequestRef, + type SourceControlProviderKind, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import { msg } from "gt-react-native"; +import * as Option from "effect/Option"; +import { AsyncResult } from "effect/reactivity"; +import { useEffect, useRef, useState } from "react"; + +import { m } from "../../i18n/messages"; + +import * as Dialog from "../../components/ui/Dialog"; +import { beginForegroundHandoff } from "../../lib/foreground-handoff"; +import { appAtomRegistry } from "../../state/atom-registry"; +import { attachmentEnvironment } from "../../state/attachments"; +import { composerPullRequests } from "../../state/pull-requests"; +import { environmentSession, readEnvironmentScope } from "../../state/session"; + +interface PickedMobilePullRequestFile { + readonly uri: string; + readonly name: string; + readonly mimeType: string; + readonly sizeBytes: number; +} + +function inferExtensionForMimeType( + mimeType: string, + assetType?: "image" | "video" | string | null, +): string { + const lower = mimeType.toLowerCase(); + if (lower === "image/png") return ".png"; + if (lower === "image/jpeg") return ".jpg"; + if (lower === "image/gif") return ".gif"; + if (lower === "image/webp") return ".webp"; + if (lower === "image/svg+xml") return ".svg"; + if (lower === "video/mp4") return ".mp4"; + if (lower === "video/quicktime") return ".mov"; + if (lower === "video/webm") return ".webm"; + return assetType === "video" ? ".mp4" : ".jpg"; +} + +function inferMimeTypeFromName(name: string): string { + const ext = name.split(".").pop()?.toLowerCase(); + switch (ext) { + case "png": + return "image/png"; + case "jpg": + case "jpeg": + return "image/jpeg"; + case "gif": + return "image/gif"; + case "webp": + return "image/webp"; + case "svg": + return "image/svg+xml"; + case "mp4": + return "video/mp4"; + case "mov": + return "video/quicktime"; + case "webm": + return "video/webm"; + default: + return "application/octet-stream"; + } +} + +async function resolveAssetSizeBytes( + uri: string, + reported: number | null | undefined, +): Promise { + if (typeof reported === "number" && reported > 0) return reported; + const { File } = await import("expo-file-system"); + const size = new File(uri).size; + return typeof size === "number" ? size : Number(size ?? 0); +} + +async function pickPullRequestMedia(): Promise> { + const imagePicker = await import("expo-image-picker"); + const endHandoff = beginForegroundHandoff(); + let result: Awaited>; + try { + result = await imagePicker.launchImageLibraryAsync({ + mediaTypes: ["images", "videos"], + allowsMultipleSelection: true, + base64: false, + quality: 1, + shouldDownloadFromNetwork: true, + }); + } finally { + endHandoff(); + } + if (result.canceled) return []; + + const picked: PickedMobilePullRequestFile[] = []; + for (const [index, asset] of result.assets.entries()) { + const rawName = asset.fileName?.trim() ?? ""; + const mimeType = + asset.mimeType?.trim() || + (rawName + ? inferMimeTypeFromName(rawName) + : asset.type === "video" + ? "video/mp4" + : "image/jpeg"); + const name = + rawName.length > 0 && rawName.includes(".") + ? rawName + : `${asset.type === "video" ? "video" : "photo"}-${index + 1}${inferExtensionForMimeType(mimeType, asset.type)}`; + const sizeBytes = await resolveAssetSizeBytes(asset.uri, asset.fileSize); + picked.push({ uri: asset.uri, name, mimeType, sizeBytes }); + } + return picked; +} + +async function pickPullRequestDocuments( + provider: SourceControlProviderKind | undefined, +): Promise> { + const { getDocumentAsync } = await import("expo-document-picker"); + const endHandoff = beginForegroundHandoff(); + let result: Awaited>; + try { + result = await getDocumentAsync({ + multiple: true, + copyToCacheDirectory: true, + ...(provider === "github" ? { type: ["image/*", "video/*"] } : {}), + }); + } finally { + endHandoff(); + } + if (result.canceled) return []; + + const picked: PickedMobilePullRequestFile[] = []; + for (const asset of result.assets) { + const name = asset.name.trim() || "attachment"; + const mimeType = asset.mimeType?.trim() || inferMimeTypeFromName(name); + const sizeBytes = await resolveAssetSizeBytes(asset.uri, asset.size); + picked.push({ uri: asset.uri, name, mimeType, sizeBytes }); + } + return picked; +} + +async function uploadNativeFile( + file: PickedMobilePullRequestFile, + url: string, + signal: AbortSignal, +): Promise { + const { File, UploadType } = await import("expo-file-system"); + const result = await new File(file.uri).upload(url, { + httpMethod: "POST", + uploadType: UploadType.BINARY_CONTENT, + headers: { "Content-Type": file.mimeType }, + signal, + }); + if (result.status < 200 || result.status >= 300) { + throw new Error(`Upload failed for '${file.name}' (${result.status}).`); + } +} + +async function uploadMobilePullRequestFile(input: { + readonly environmentId: EnvironmentId; + readonly reference: PullRequestRef; + readonly file: PickedMobilePullRequestFile; + readonly signal: AbortSignal; +}) { + const { environmentId, reference, file, signal } = input; + if (!readEnvironmentScope(environmentId, AuthSourceControlWriteScope)) { + throw new Error("This device isn't allowed to attach files to source control."); + } + + const cycle = await Effect.runPromise( + runAttachmentUploadCycle({ + registry: appAtomRegistry, + createUploadUrl: attachmentEnvironment.createUploadUrl, + remove: attachmentEnvironment.remove, + environmentId, + upload: { + type: "pull-request", + name: file.name, + mimeType: file.mimeType, + sizeBytes: file.sizeBytes, + }, + resolveUploadUrl: (relativeUrl) => { + if (signal.aborted || !readEnvironmentScope(environmentId, AuthSourceControlWriteScope)) { + return null; + } + const connection = appAtomRegistry.get( + environmentSession.preparedConnectionValueAtom(environmentId), + ); + return Option.isNone(connection) + ? null + : resolveAssetUrl(connection.value.httpBaseUrl, relativeUrl); + }, + transport: (url) => + Effect.tryPromise({ + try: (transferSignal) => uploadNativeFile(file, url, transferSignal), + catch: attachmentUploadError, + }), + }), + { signal }, + ).catch(() => { + throw new Error("Upload cancelled."); + }); + + if (cycle.status !== "uploaded") { + if ( + cycle.attachmentId !== null && + readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) + ) { + deletePendingAttachmentUpload({ + registry: appAtomRegistry, + remove: attachmentEnvironment.remove, + environmentId, + attachmentId: cycle.attachmentId, + }); + } + throw cycle.error instanceof Error + ? cycle.error + : new Error(`Could not upload '${file.name}'.`); + } + + const uploaded = await runAtomCommand( + appAtomRegistry, + composerPullRequests.uploadAttachment, + { + environmentId, + input: { + ...reference, + attachmentId: cycle.attachmentId, + fileName: file.name, + mimeType: file.mimeType, + }, + }, + { reportFailure: false }, + ); + + if (uploaded._tag !== "Success") { + if (readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) { + deletePendingAttachmentUpload({ + registry: appAtomRegistry, + remove: attachmentEnvironment.remove, + environmentId, + attachmentId: cycle.attachmentId, + }); + } + const cause = squashAtomCommandFailure(uploaded); + throw cause instanceof Error ? cause : new Error("The provider refused the attachment."); + } + + return uploaded.value; +} + +export function usePullRequestAttachmentUpload(input: { + readonly environmentId: EnvironmentId; + readonly reference: PullRequestRef; + readonly provider?: SourceControlProviderKind | undefined; + readonly value: string; + readonly updateValue: (updater: (current: string) => string) => void; + readonly selection?: { readonly start: number; readonly end: number } | null | undefined; + readonly onPlaceCursor?: ((cursor: number) => void) | undefined; +}) { + const counterRef = useRef(0); + const unmountAbortRef = useRef(null); + const [uploadingCount, setUploadingCount] = useState(0); + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- aborts in-flight native file uploads held until unmount + useEffect( + () => () => { + unmountAbortRef.current?.abort(); + }, + [], + ); + + const attachPickedFiles = async (files: ReadonlyArray) => { + if (files.length === 0) return; + const accepted: Array<{ + readonly file: PickedMobilePullRequestFile; + readonly placeholder: string; + }> = []; + const errors: Array = []; + for (const file of files) { + const problem = validatePullRequestAttachmentClientFile( + { name: file.name, sizeBytes: file.sizeBytes, provider: input.provider }, + m, + ); + if (problem !== null) { + errors.push(problem); + continue; + } + accepted.push({ + file, + placeholder: makePullRequestUploadPlaceholder(file.name, ++counterRef.current), + }); + } + if (errors.length > 0) { + Dialog.alert(m(msg("Could not attach file")), errors.join("\n\n")); + } + if (accepted.length === 0) return; + + const selStart = input.selection?.start ?? input.value.length; + const selEnd = input.selection?.end ?? input.value.length; + const inserted = insertPullRequestUploadPlaceholders( + input.value, + selStart, + selEnd, + accepted.map((entry) => entry.placeholder), + ); + input.updateValue(() => inserted.text); + input.onPlaceCursor?.(inserted.cursor); + + if (unmountAbortRef.current === null || unmountAbortRef.current.signal.aborted) { + unmountAbortRef.current = new AbortController(); + } + const signal = unmountAbortRef.current.signal; + setUploadingCount((count) => count + accepted.length); + + await Promise.all( + accepted.map(async ({ file, placeholder }) => { + const outcome = await settlePromise(() => + uploadMobilePullRequestFile({ + environmentId: input.environmentId, + reference: input.reference, + file, + signal, + }), + ); + if (signal.aborted) return; + if (AsyncResult.isSuccess(outcome)) { + input.updateValue((current) => + replacePullRequestUploadPlaceholder(current, placeholder, outcome.value.markdown), + ); + } else { + input.updateValue((current) => removePullRequestUploadPlaceholder(current, placeholder)); + const cause = squashAtomCommandFailure(outcome); + Dialog.alert( + m(msg("Could not attach file")), + cause instanceof Error ? cause.message : m(msg("Try again.")), + ); + } + setUploadingCount((count) => Math.max(0, count - 1)); + }), + ); + }; + + return { + uploading: uploadingCount > 0, + uploadingCount, + pickMedia: async () => { + const picked = await settlePromise(() => pickPullRequestMedia()); + if (AsyncResult.isFailure(picked)) { + const cause = squashAtomCommandFailure(picked); + Dialog.alert( + m(msg("Could not open photo library")), + cause instanceof Error ? cause.message : m(msg("Try again.")), + ); + return; + } + await attachPickedFiles(picked.value); + }, + pickFiles: async () => { + const picked = await settlePromise(() => pickPullRequestDocuments(input.provider)); + if (AsyncResult.isFailure(picked)) { + const cause = squashAtomCommandFailure(picked); + Dialog.alert( + m(msg("Could not open file picker")), + cause instanceof Error ? cause.message : m(msg("Try again.")), + ); + return; + } + await attachPickedFiles(picked.value); + }, + }; +} diff --git a/apps/mobile/src/features/pull-requests/usePullRequestCompletions.ts b/apps/mobile/src/features/pull-requests/usePullRequestCompletions.ts index 8f03e5c948f2b..2537cc1664468 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestCompletions.ts +++ b/apps/mobile/src/features/pull-requests/usePullRequestCompletions.ts @@ -66,6 +66,11 @@ export function usePullRequestCompletions(input: { isLoading: hosted.isPending || sentKey !== key, failed: hosted.error !== null, selection: placed ?? undefined, + currentSelection: selection, + placeCursor: (cursor: number) => { + setSelection({ start: cursor, end: cursor }); + setPlaced({ start: cursor, end: cursor }); + }, onSelectionChange: (event: TextInputSelectionChangeEvent) => { setSelection(event.nativeEvent.selection); setPlaced(null); diff --git a/apps/mobile/src/features/pull-requests/usePullRequestPermissions.ts b/apps/mobile/src/features/pull-requests/usePullRequestPermissions.ts index 38ba2b74deb24..fe164330f7ab0 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestPermissions.ts +++ b/apps/mobile/src/features/pull-requests/usePullRequestPermissions.ts @@ -1,4 +1,5 @@ import { useAtomValue } from "@effect/atom-react"; +import { canAttachToPullRequest } from "@t3tools/client-runtime/pull-request-attachments"; import { canEditPullRequestChangeRequest, canEditPullRequestComment, @@ -27,8 +28,12 @@ export function usePullRequestPermissions(params: PullRequestParams, pr: PullReq const canSetReaction = useAtomValue( composerPullRequests.setReaction.permissionAtom(environmentId), ); + const canUploadAttachment = useAtomValue( + composerPullRequests.uploadAttachment.permissionAtom(environmentId), + ); return { connected, + canAttach: connected && canUploadAttachment && canAttachToPullRequest(pr), canInlineComment: connected && canReview && diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 0ac4bdfdff108..57cabec7ac76d 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -5302,5 +5302,12 @@ "3328503592789bed": "Zen", "856812e7e1fc445e": "Tool-Aufrufe im Chat", "8d545d54c0a9e950": "Die Befehle, Bearbeitungen und Suchen ausblenden, die Agenten ausführen. „Erfolgreiche ausblenden“ behält Fehler. „Zen“ zeigt nur endgültige Antworten. Genehmigungen, Fragen und Fehler werden immer angezeigt.", - "1e4248d235c665e5": "Antigravity-Summen lassen Subagent-Aufrufe aus, die nur in Transkripten erfasst sind." + "1e4248d235c665e5": "Antigravity-Summen lassen Subagent-Aufrufe aus, die nur in Transkripten erfasst sind.", + "c810e443033ac25a": "''{name}'' ist leer.", + "7ce0e7e30613750d": "''{name}'' wird von GitHub nicht unterstützt. Hänge PNG-, JPEG-, GIF-, WebP-, SVG-, MP4-, MOV- oder WebM-Dateien an.", + "9aa2077538cb3443": "{count} Dateien werden hochgeladen…", + "167ee73b0ebb4806": "Datei wird hochgeladen…", + "5f31c62bdf26a7be": "Datei anhängen", + "48223896dc3bab24": "Fotomediathek konnte nicht geöffnet werden", + "d1aa0d093eca5e03": "Dateiauswahl konnte nicht geöffnet werden" } diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index d9e41442afe03..cd8e4dea4a2fa 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -5303,5 +5303,12 @@ "3328503592789bed": "Zen", "856812e7e1fc445e": "Tool calls in chat", "8d545d54c0a9e950": "Hide the commands, edits, and searches agents run. Hide successful keeps failures. Zen shows only final answers. Approvals, questions, and errors always show.", - "1e4248d235c665e5": "Antigravity totals leave out subagent calls recorded only in transcripts." + "1e4248d235c665e5": "Antigravity totals leave out subagent calls recorded only in transcripts.", + "c810e443033ac25a": "''{name}'' is empty.", + "7ce0e7e30613750d": "''{name}'' is not supported on GitHub. Attach PNG, JPEG, GIF, WebP, SVG, MP4, MOV, or WebM files.", + "9aa2077538cb3443": "Uploading {count} files…", + "167ee73b0ebb4806": "Uploading file…", + "5f31c62bdf26a7be": "Attach file", + "48223896dc3bab24": "Could not open photo library", + "d1aa0d093eca5e03": "Could not open file picker" } diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 7c9cd474da858..f743164ba093b 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -5296,5 +5296,12 @@ "3328503592789bed": "Zen", "856812e7e1fc445e": "Llamadas a herramientas en el chat", "8d545d54c0a9e950": "Oculta los comandos, ediciones y búsquedas que ejecutan los agentes. Ocultar las correctas mantiene los fallos. Zen solo muestra las respuestas finales. Las aprobaciones, preguntas y errores siempre se muestran.", - "1e4248d235c665e5": "Los totales de Antigravity omiten las llamadas a subagentes registradas solo en las transcripciones." + "1e4248d235c665e5": "Los totales de Antigravity omiten las llamadas a subagentes registradas solo en las transcripciones.", + "c810e443033ac25a": "''{name}'' está vacío.", + "7ce0e7e30613750d": "GitHub no admite ''{name}''. Adjunta archivos PNG, JPEG, GIF, WebP, SVG, MP4, MOV o WebM.", + "9aa2077538cb3443": "Subiendo {count} archivos…", + "167ee73b0ebb4806": "Subiendo archivo…", + "5f31c62bdf26a7be": "Adjuntar archivo", + "48223896dc3bab24": "No se pudo abrir la fototeca", + "d1aa0d093eca5e03": "No se pudo abrir el selector de archivos" } diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index a79259698d293..00ef2d7196cb5 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -5296,5 +5296,12 @@ "3328503592789bed": "Zen", "856812e7e1fc445e": "Appels d’outils dans la discussion", "8d545d54c0a9e950": "Masque les commandes, modifications et recherches lancées par les agents. Masquer les réussis garde les échecs. Zen n’affiche que les réponses finales. Les approbations, questions et erreurs s’affichent toujours.", - "1e4248d235c665e5": "Les totaux d'Antigravity omettent les appels de sous-agents enregistrés uniquement dans les transcriptions." + "1e4248d235c665e5": "Les totaux d'Antigravity omettent les appels de sous-agents enregistrés uniquement dans les transcriptions.", + "c810e443033ac25a": "''{name}'' est vide.", + "7ce0e7e30613750d": "''{name}'' n'est pas pris en charge par GitHub. Joignez des fichiers PNG, JPEG, GIF, WebP, SVG, MP4, MOV ou WebM.", + "9aa2077538cb3443": "Envoi de {count} fichiers…", + "167ee73b0ebb4806": "Envoi du fichier…", + "5f31c62bdf26a7be": "Joindre un fichier", + "48223896dc3bab24": "Impossible d'ouvrir la photothèque", + "d1aa0d093eca5e03": "Impossible d'ouvrir le sélecteur de fichiers" } diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index b887bf5b0531c..69e1de8be9ad7 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -5278,5 +5278,12 @@ "3328503592789bed": "Zen", "856812e7e1fc445e": "チャット内のツール呼び出し", "8d545d54c0a9e950": "エージェントが実行するコマンド、編集、検索を非表示にします。「成功したものを非表示」では失敗は表示されます。Zen では最終的な回答だけを表示します。承認、質問、エラーは常に表示されます。", - "1e4248d235c665e5": "Antigravity の合計には、トランスクリプトにのみ記録されたサブエージェント呼び出しは含まれません。" + "1e4248d235c665e5": "Antigravity の合計には、トランスクリプトにのみ記録されたサブエージェント呼び出しは含まれません。", + "c810e443033ac25a": "''{name}'' は空です。", + "7ce0e7e30613750d": "''{name}'' は GitHub でサポートされていません。PNG、JPEG、GIF、WebP、SVG、MP4、MOV、WebM ファイルを添付してください。", + "9aa2077538cb3443": "{count} 件のファイルをアップロード中…", + "167ee73b0ebb4806": "ファイルをアップロード中…", + "5f31c62bdf26a7be": "ファイルを添付", + "48223896dc3bab24": "写真ライブラリを開けませんでした", + "d1aa0d093eca5e03": "ファイル選択画面を開けませんでした" } diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index ffadf99a1dc5e..d5f06cbd159e1 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -5282,5 +5282,12 @@ "3328503592789bed": "Zen", "856812e7e1fc445e": "채팅의 도구 호출", "8d545d54c0a9e950": "에이전트가 실행하는 명령, 편집, 검색을 숨깁니다. 성공한 항목 숨기기는 실패를 남겨 둡니다. Zen은 최종 답변만 표시합니다. 승인, 질문, 오류는 항상 표시됩니다.", - "1e4248d235c665e5": "Antigravity 합계에는 트랜스크립트에만 기록된 서브에이전트 호출이 빠져 있습니다." + "1e4248d235c665e5": "Antigravity 합계에는 트랜스크립트에만 기록된 서브에이전트 호출이 빠져 있습니다.", + "c810e443033ac25a": "''{name}''이(가) 비어 있습니다.", + "7ce0e7e30613750d": "''{name}''은(는) GitHub에서 지원하지 않습니다. PNG, JPEG, GIF, WebP, SVG, MP4, MOV, WebM 파일을 첨부하세요.", + "9aa2077538cb3443": "파일 {count}개 업로드 중…", + "167ee73b0ebb4806": "파일 업로드 중…", + "5f31c62bdf26a7be": "파일 첨부", + "48223896dc3bab24": "사진 보관함을 열 수 없습니다", + "d1aa0d093eca5e03": "파일 선택기를 열 수 없습니다" } diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index d86e9db85c61f..8dade7c03a9d2 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -5296,5 +5296,12 @@ "3328503592789bed": "Zen", "856812e7e1fc445e": "Chamadas de ferramentas no chat", "8d545d54c0a9e950": "Oculta os comandos, edições e pesquisas que os agentes executam. \"Ocultar bem-sucedidas\" mantém as falhas. Zen mostra só as respostas finais. Aprovações, perguntas e erros sempre aparecem.", - "1e4248d235c665e5": "Os totais do Antigravity deixam de fora chamadas de subagentes registradas apenas nas transcrições." + "1e4248d235c665e5": "Os totais do Antigravity deixam de fora chamadas de subagentes registradas apenas nas transcrições.", + "c810e443033ac25a": "''{name}'' está vazio.", + "7ce0e7e30613750d": "O GitHub não aceita ''{name}''. Anexe arquivos PNG, JPEG, GIF, WebP, SVG, MP4, MOV ou WebM.", + "9aa2077538cb3443": "Enviando {count} arquivos…", + "167ee73b0ebb4806": "Enviando arquivo…", + "5f31c62bdf26a7be": "Anexar arquivo", + "48223896dc3bab24": "Não foi possível abrir a fototeca", + "d1aa0d093eca5e03": "Não foi possível abrir o seletor de arquivos" } diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index 8f074d878cca1..582b155fea7b6 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -5376,5 +5376,12 @@ "3328503592789bed": "Дзен", "856812e7e1fc445e": "Вызовы инструментов в чате", "8d545d54c0a9e950": "Скрывать команды, правки и поиски, которые выполняют агенты. «Скрывать успешные» оставляет ошибки. «Дзен» показывает только итоговые ответы. Запросы подтверждения, вопросы и ошибки показываются всегда.", - "1e4248d235c665e5": "Итоги Antigravity не учитывают вызовы субагентов, записанные только в транскриптах." + "1e4248d235c665e5": "Итоги Antigravity не учитывают вызовы субагентов, записанные только в транскриптах.", + "c810e443033ac25a": "''{name}'' пуст.", + "7ce0e7e30613750d": "GitHub не поддерживает ''{name}''. Прикрепите файлы PNG, JPEG, GIF, WebP, SVG, MP4, MOV или WebM.", + "9aa2077538cb3443": "Загрузка файлов: {count}…", + "167ee73b0ebb4806": "Загрузка файла…", + "5f31c62bdf26a7be": "Прикрепить файл", + "48223896dc3bab24": "Не удалось открыть медиатеку", + "d1aa0d093eca5e03": "Не удалось открыть выбор файлов" } diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index cd25396d736f8..86a4af245c6dc 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -5302,5 +5302,12 @@ "3328503592789bed": "Zen", "856812e7e1fc445e": "Verktygsanrop i chatten", "8d545d54c0a9e950": "Dölj kommandon, redigeringar och sökningar som agenter kör. Dölj lyckade behåller misslyckanden. Zen visar bara slutliga svar. Godkännanden, frågor och fel visas alltid.", - "1e4248d235c665e5": "Antigravitys summor utelämnar subagentanrop som bara finns i transkript." + "1e4248d235c665e5": "Antigravitys summor utelämnar subagentanrop som bara finns i transkript.", + "c810e443033ac25a": "''{name}'' är tom.", + "7ce0e7e30613750d": "''{name}'' stöds inte på GitHub. Bifoga PNG-, JPEG-, GIF-, WebP-, SVG-, MP4-, MOV- eller WebM-filer.", + "9aa2077538cb3443": "Laddar upp {count} filer…", + "167ee73b0ebb4806": "Laddar upp fil…", + "5f31c62bdf26a7be": "Bifoga fil", + "48223896dc3bab24": "Det gick inte att öppna bildbiblioteket", + "d1aa0d093eca5e03": "Det gick inte att öppna filväljaren" } diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index dca8dbde3e8ba..f54857b11eea6 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -5287,5 +5287,12 @@ "3328503592789bed": "专注模式", "856812e7e1fc445e": "聊天中的工具调用", "8d545d54c0a9e950": "隐藏智能体执行的命令、编辑和搜索。“隐藏成功的调用”仍保留失败项;“专注模式”仅显示最终回答。审批、提问和错误始终显示。", - "1e4248d235c665e5": "Antigravity 总计未包含仅记录在对话记录中的子代理调用。" + "1e4248d235c665e5": "Antigravity 总计未包含仅记录在对话记录中的子代理调用。", + "c810e443033ac25a": "''{name}'' 为空。", + "7ce0e7e30613750d": "GitHub 不支持 ''{name}''。请附加 PNG、JPEG、GIF、WebP、SVG、MP4、MOV 或 WebM 文件。", + "9aa2077538cb3443": "正在上传 {count} 个文件…", + "167ee73b0ebb4806": "正在上传文件…", + "5f31c62bdf26a7be": "附加文件", + "48223896dc3bab24": "无法打开照片图库", + "d1aa0d093eca5e03": "无法打开文件选择器" } diff --git a/apps/mobile/src/state/attachments.test.ts b/apps/mobile/src/state/attachments.test.ts index 052c5ef045cb1..b76e914ff17c4 100644 --- a/apps/mobile/src/state/attachments.test.ts +++ b/apps/mobile/src/state/attachments.test.ts @@ -1,5 +1,6 @@ import { AuthOrchestrationOperateScope, + AuthSourceControlWriteScope, EnvironmentAuthorizationError, EnvironmentId, } from "@t3tools/contracts"; @@ -13,13 +14,16 @@ import { afterEach, beforeEach, vi } from "vite-plus/test"; const state = vi.hoisted(() => ({ grantedEnvironments: new Set(), + grantedSourceControlEnvironments: new Set(), create: vi.fn(), remove: vi.fn(), })); vi.mock("../connection/runtime", () => ({ connectionAtomRuntime: {} })); vi.mock("./session", () => ({ readEnvironmentScope: (environmentId: string, scope: string) => - scope === AuthOrchestrationOperateScope && state.grantedEnvironments.has(environmentId), + (scope === AuthOrchestrationOperateScope && state.grantedEnvironments.has(environmentId)) || + (scope === AuthSourceControlWriteScope && + state.grantedSourceControlEnvironments.has(environmentId)), })); vi.mock("@t3tools/client-runtime/state/attachments", async (importOriginal) => ({ ...(await importOriginal()), @@ -35,6 +39,7 @@ const environmentId = EnvironmentId.make("secondary"); const registry = AtomRegistry.make(); beforeEach(() => { state.grantedEnvironments = new Set(["primary"]); + state.grantedSourceControlEnvironments = new Set(); state.create.mockReset().mockResolvedValue( AsyncResult.success({ attachmentId: "pending", @@ -104,4 +109,24 @@ describe("attachment mutation grants", () => { expect(state.remove).not.toHaveBeenCalled(); }), ); + + it("checks source-control write permission for pull-request attachment uploads", async () => { + const denied = await attachmentEnvironment.createUploadUrl.run(registry, { + environmentId, + input: { type: "pull-request", name: "demo.mp4", mimeType: "video/mp4", sizeBytes: 128 }, + }); + expect(denied._tag).toBe("Failure"); + if (denied._tag !== "Failure") throw new Error("Expected permission denial"); + expect(Cause.squash(denied.cause)).toMatchObject({ + requiredScope: AuthSourceControlWriteScope, + }); + + state.grantedSourceControlEnvironments.add("secondary"); + const allowed = await attachmentEnvironment.createUploadUrl.run(registry, { + environmentId, + input: { type: "pull-request", name: "demo.mp4", mimeType: "video/mp4", sizeBytes: 128 }, + }); + expect(allowed._tag).toBe("Success"); + expect(state.create).toHaveBeenCalledOnce(); + }); }); diff --git a/apps/mobile/src/state/attachments.ts b/apps/mobile/src/state/attachments.ts index 5406302363f74..56f0aa10fa066 100644 --- a/apps/mobile/src/state/attachments.ts +++ b/apps/mobile/src/state/attachments.ts @@ -1,7 +1,9 @@ import { createAttachmentEnvironmentAtoms } from "@t3tools/client-runtime/state/attachments"; import type { AtomCommand } from "@t3tools/client-runtime/state/runtime"; import { + type AuthEnvironmentScope, AuthOrchestrationOperateScope, + AuthSourceControlWriteScope, EnvironmentAuthorizationError, type EnvironmentId, } from "@t3tools/contracts"; @@ -15,16 +17,18 @@ import { readEnvironmentScope } from "./session"; function requireAttachmentWriteAccess( command: AtomCommand, + resolveScope: (input: W) => AuthEnvironmentScope = () => AuthOrchestrationOperateScope, ): AtomCommand { return { ...command, run: async (registry, input) => { - if (!readEnvironmentScope(input.environmentId, AuthOrchestrationOperateScope)) { + const requiredScope = resolveScope(input); + if (!readEnvironmentScope(input.environmentId, requiredScope)) { return AsyncResult.failure( Cause.fail( new EnvironmentAuthorizationError({ message: m(msg("This connection cannot change attachments.")), - requiredScope: AuthOrchestrationOperateScope, + requiredScope, }), ), ); @@ -36,6 +40,10 @@ function requireAttachmentWriteAccess + call.input.type === "pull-request" + ? AuthSourceControlWriteScope + : AuthOrchestrationOperateScope, + ), remove: requireAttachmentWriteAccess(commands.remove), }; diff --git a/apps/server/src/assets/AttachmentUpload.test.ts b/apps/server/src/assets/AttachmentUpload.test.ts index 9e13ce882ca82..d85b5911bcb49 100644 --- a/apps/server/src/assets/AttachmentUpload.test.ts +++ b/apps/server/src/assets/AttachmentUpload.test.ts @@ -28,6 +28,7 @@ import { ATTACHMENT_UPLOAD_ROUTE_PREFIX, deletePendingAttachment, issueAttachmentUploadUrl, + resolvePendingAttachmentPath, storeAttachmentUpload, validateAttachmentUploadToken, } from "./AttachmentUpload.ts"; @@ -336,4 +337,28 @@ describe("AttachmentUpload", () => { expect(NodeFS.existsSync(claimedPath)).toBe(true); }).pipe(Effect.provide(layerTest)), ); + + it.effect( + "stores binary pull-request uploads without text extraction and resolves their pending path", + () => + Effect.gen(function* () { + const bytes = new Uint8Array([0x00, 0x00, 0x00, 0x18, 0x66, 0x74, 0x79, 0x70]); + const issued = yield* issueAttachmentUploadUrl({ + type: "pull-request", + name: "clip.mp4", + mimeType: "video/mp4", + sizeBytes: bytes.byteLength, + }); + const token = issued.relativeUrl.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length); + const claims = yield* validateAttachmentUploadToken(token); + if (!claims) throw new Error("Expected valid pull-request upload claims."); + expect(claims.type).toBe("pull-request"); + expect(yield* storeAttachmentUpload(claims, bytes)).toEqual({ ok: true }); + const resolvedPath = yield* resolvePendingAttachmentPath(issued.attachmentId); + expect(resolvedPath).not.toBeNull(); + expect(NodeFS.readFileSync(resolvedPath!)).toEqual(Buffer.from(bytes)); + yield* deletePendingAttachment(issued.attachmentId); + expect(yield* resolvePendingAttachmentPath(issued.attachmentId)).toBeNull(); + }).pipe(Effect.provide(layerTest)), + ); }); diff --git a/apps/server/src/assets/AttachmentUpload.ts b/apps/server/src/assets/AttachmentUpload.ts index d2ea0aea145ba..bb0ff09fc1818 100644 --- a/apps/server/src/assets/AttachmentUpload.ts +++ b/apps/server/src/assets/AttachmentUpload.ts @@ -41,7 +41,7 @@ const lastPendingSweepByDirectory = new Map(); const AttachmentUploadClaims = Schema.Struct({ version: Schema.Literal(1), kind: Schema.Literal("attachment-upload"), - type: Schema.Literals(["image", "file"]).pipe( + type: Schema.Literals(["image", "file", "pull-request"]).pipe( Schema.withDecodingDefault(Effect.succeed("image" as const)), ), attachmentId: Schema.String, @@ -85,12 +85,13 @@ export const issueAttachmentUploadUrl = Effect.fn("AttachmentUpload.issueUrl")(f } const attachmentType = input.type ?? "image"; + const isGenericFile = attachmentType === "file" || attachmentType === "pull-request"; const name = - attachmentType === "file" && isSvgAttachment(input) && !/\.svg$/i.test(input.name) + isGenericFile && isSvgAttachment(input) && !/\.svg$/i.test(input.name) ? `${input.name}.svg` : input.name; const attachmentId = createPendingAttachmentId( - attachmentType === "file" ? attachmentFileExtension(name) : undefined, + isGenericFile ? attachmentFileExtension(name) : undefined, ); const expiresAt = nowMs + ATTACHMENT_UPLOAD_URL_TTL_MS; const encodedPayload = base64UrlEncode( @@ -161,7 +162,7 @@ export const storeAttachmentUpload = Effect.fn("AttachmentUpload.store")(functio const config = yield* ServerConfig.ServerConfig; const extension = - claims.type === "file" + claims.type === "file" || claims.type === "pull-request" ? attachmentFileExtension(claims.name) : inferImageExtension({ mimeType: claims.mimeType, fileName: claims.name }); const relativePath = `${claims.attachmentId}${extension}`; @@ -245,8 +246,10 @@ export const storeAttachmentUpload = Effect.fn("AttachmentUpload.store")(functio return { ok: false, status: 409, detail: "Attachment already uploaded." }; } } - const documents = yield* DocumentText.DocumentText; - yield* documents.ensure(finalPath); + if (claims.type !== "pull-request") { + const documents = yield* DocumentText.DocumentText; + yield* documents.ensure(finalPath); + } return { ok: true } satisfies StoreAttachmentUploadResult; }).pipe( Effect.catch((cause) => @@ -267,6 +270,27 @@ export const storeAttachmentUpload = Effect.fn("AttachmentUpload.store")(functio ); }); +export const resolvePendingAttachmentPath = Effect.fn("AttachmentUpload.resolvePendingPath")( + function* (attachmentId: string) { + if (parseThreadSegmentFromAttachmentId(attachmentId) !== PENDING_ATTACHMENT_THREAD_SEGMENT) { + return null; + } + + const config = yield* ServerConfig.ServerConfig; + const attachmentPath = resolveAttachmentPathById({ + attachmentsDir: config.attachmentsDir, + attachmentId, + }); + if (!attachmentPath) { + return null; + } + + const fileSystem = yield* FileSystem.FileSystem; + const exists = yield* fileSystem.exists(attachmentPath).pipe(Effect.orElseSucceed(() => false)); + return exists ? attachmentPath : null; + }, +); + export const deletePendingAttachment = Effect.fn("AttachmentUpload.deletePending")(function* ( attachmentId: string, ) { diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.ts index 8afe47e715a9f..932b19f4da4f9 100644 --- a/apps/server/src/auth/RpcAuthorization.test.ts +++ b/apps/server/src/auth/RpcAuthorization.test.ts @@ -606,3 +606,88 @@ it.effect("denies manual cleanup before the handler without settings permission" expect(handled).toBe(false); }), ); + +it.effect( + "gates pull-request attachment uploads behind source-control write permission while keeping chat uploads behind orchestration operate", + () => + Effect.gen(function* () { + const group = WsRpcGroup.omit( + ...[...WsRpcGroup.requests.keys()].filter( + ( + tag, + ): tag is Exclude< + keyof typeof RPC_REQUIRED_SCOPES, + | typeof WS_METHODS.attachmentsCreateUploadUrl + | typeof WS_METHODS.pullRequestsUploadAttachment + > => + tag !== WS_METHODS.attachmentsCreateUploadUrl && + tag !== WS_METHODS.pullRequestsUploadAttachment, + ), + ); + const handled: Array = []; + const handlers = Layer.mergeAll( + group.toLayerHandler(WS_METHODS.attachmentsCreateUploadUrl, (input) => + Effect.sync(() => { + handled.push(`mint:${input.type}`); + return { + attachmentId: "pending-00000000-0000-4000-8000-000000000001", + relativeUrl: "/api/attachments/upload/token", + expiresAt: 1, + }; + }), + ), + group.toLayerHandler(WS_METHODS.pullRequestsUploadAttachment, () => + Effect.sync(() => { + handled.push("upload"); + return { + url: "https://uploads.github.com/user-attachments/assets/1", + markdown: "![shot](https://uploads.github.com/user-attachments/assets/1)", + name: "shot.png", + mimeType: "image/png", + }; + }), + ), + ); + const scWriterOnly = yield* RpcTest.makeClient(group).pipe( + Effect.provide( + Layer.merge(handlers, RpcAuthorization.layer([AuthSourceControlWriteScope])), + ), + ); + yield* scWriterOnly[WS_METHODS.attachmentsCreateUploadUrl]({ + type: "pull-request", + name: "demo.mp4", + mimeType: "video/mp4", + sizeBytes: 1024, + }); + yield* scWriterOnly[WS_METHODS.pullRequestsUploadAttachment]({ + projectId: "project-1" as never, + repository: "acme/web", + number: 1, + attachmentId: "pending-00000000-0000-4000-8000-000000000001", + fileName: "demo.mp4", + }); + expect( + yield* scWriterOnly[WS_METHODS.attachmentsCreateUploadUrl]({ + type: "file", + name: "notes.txt", + mimeType: "text/plain", + sizeBytes: 12, + }).pipe(Effect.flip), + ).toMatchObject({ requiredPermission: AuthOrchestrationOperateScope }); + + const orchestratorOnly = yield* RpcTest.makeClient(group).pipe( + Effect.provide( + Layer.merge(handlers, RpcAuthorization.layer([AuthOrchestrationOperateScope])), + ), + ); + expect( + yield* orchestratorOnly[WS_METHODS.attachmentsCreateUploadUrl]({ + type: "pull-request", + name: "demo.mp4", + mimeType: "video/mp4", + sizeBytes: 1024, + }).pipe(Effect.flip), + ).toMatchObject({ requiredPermission: AuthSourceControlWriteScope }); + expect(handled).toEqual(["mint:pull-request", "upload"]); + }), +); diff --git a/apps/server/src/binCli.ts b/apps/server/src/binCli.ts index 995b207e7c781..023816e249cb0 100644 --- a/apps/server/src/binCli.ts +++ b/apps/server/src/binCli.ts @@ -19,6 +19,7 @@ import { pairCommand } from "./cli/pair.ts"; import { hasCloudPublicConfig } from "./cloud/publicConfig.ts"; import { extendConnectionAttemptTimeout, keepOutboundFetchOnHttp1 } from "./outboundHttp.ts"; import { sharedServerCommandFlags } from "./cli/config.ts"; +import { prCommand } from "./cli/pr.ts"; import { projectCommand } from "./cli/project.ts"; import { threadCommand } from "./cli/thread.ts"; import { runDefaultServerCommand, serveCommand, startCommand } from "./cli/server.ts"; @@ -89,6 +90,7 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) => authCommand, environmentCommand, browserCommand, + prCommand, projectCommand, threadCommand, upCommand, diff --git a/apps/server/src/cli/deferredImports.test.ts b/apps/server/src/cli/deferredImports.test.ts index 6f4a25507f2fe..1067f412b2a6b 100644 --- a/apps/server/src/cli/deferredImports.test.ts +++ b/apps/server/src/cli/deferredImports.test.ts @@ -50,7 +50,14 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("CLI deferred imp it.effect("runs commands that do not need them without loading them", () => Effect.gen(function* () { hooks.importsAttempted.length = 0; - for (const args of [["--version"], ["--help"], ["project", "--help"], ["thread", "--help"]]) { + for (const args of [ + ["--version"], + ["--help"], + ["pr", "--help"], + ["pr", "attach", "--help"], + ["project", "--help"], + ["thread", "--help"], + ]) { yield* runCli(args); } assert.deepEqual(hooks.importsAttempted, []); diff --git a/apps/server/src/cli/pr.ts b/apps/server/src/cli/pr.ts new file mode 100644 index 0000000000000..b2c3f811bb6a3 --- /dev/null +++ b/apps/server/src/cli/pr.ts @@ -0,0 +1,60 @@ +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import { Argument, Command, Flag } from "effect/cli"; + +import { baseDirFlag } from "./config.ts"; + +const prAttachCommand = Command.make("attach", { + baseDir: baseDirFlag, + cwd: Flag.String("cwd").pipe( + Flag.withDescription("Git repository directory (defaults to the current directory)."), + Flag.optional, + ), + repo: Flag.String("repo").pipe( + Flag.withAlias("R"), + Flag.withDescription( + "Target repository (`owner/name`, `group/project`, or `[HOST/]OWNER/REPO`).", + ), + Flag.optional, + ), + host: Flag.String("host").pipe( + Flag.withDescription("GitHub or GitLab hostname override."), + Flag.optional, + ), + alt: Flag.String("alt").pipe( + Flag.withDescription("Alt text override when attaching a single file."), + Flag.optional, + ), + json: Flag.Boolean("json").pipe( + Flag.withDescription("Print JSON output (`[{ path, url, markdown }]`)."), + Flag.withDefault(false), + ), + files: Argument.String("file").pipe( + Argument.variadic({ min: 1 }), + Argument.withDescription("Local file paths to upload (supports `path#Alt text`)."), + ), +}).pipe( + Command.withDescription( + "Upload local images or videos to GitHub or GitLab and print Markdown to embed in PRs or MRs.", + ), + Command.withHandler((options) => + Effect.promise(() => import("./prAttach.ts")).pipe( + Effect.flatMap((mod) => + mod.runPrAttach({ + baseDir: Option.getOrUndefined(options.baseDir), + cwd: Option.getOrUndefined(options.cwd), + repo: Option.getOrUndefined(options.repo), + host: Option.getOrUndefined(options.host), + alt: Option.getOrUndefined(options.alt), + json: options.json, + files: options.files, + }), + ), + ), + ), +); + +export const prCommand = Command.make("pr").pipe( + Command.withDescription("Pull request and merge request utilities."), + Command.withSubcommands([prAttachCommand]), +); diff --git a/apps/server/src/cli/prAttach.test.ts b/apps/server/src/cli/prAttach.test.ts new file mode 100644 index 0000000000000..911a374e56928 --- /dev/null +++ b/apps/server/src/cli/prAttach.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, it } from "@effect/vitest"; + +import { parseExplicitRepoOption, splitFileAndInlineAlt } from "./prAttach.ts"; + +describe("prAttach option parsing", () => { + it("splits inline #alt suffixes while preserving bare filenames and leading hashes", () => { + expect(splitFileAndInlineAlt("shot.png#Login screen")).toEqual({ + filePart: "shot.png", + inlineAlt: "Login screen", + }); + expect(splitFileAndInlineAlt("shot.png# ")).toEqual({ + filePart: "shot.png", + inlineAlt: undefined, + }); + expect(splitFileAndInlineAlt("#leading.png")).toEqual({ + filePart: "#leading.png", + inlineAlt: undefined, + }); + expect(splitFileAndInlineAlt("dir/demo.mp4")).toEqual({ + filePart: "dir/demo.mp4", + inlineAlt: undefined, + }); + }); + + it("parses owner/repo, [host/]owner/repo, nested GitLab paths, and URLs", () => { + expect(parseExplicitRepoOption("acme/web", undefined)).toEqual({ + host: undefined, + repository: "acme/web", + }); + expect(parseExplicitRepoOption("acme.ghe.com/acme/web", undefined)).toEqual({ + host: "acme.ghe.com", + repository: "acme/web", + }); + expect(parseExplicitRepoOption("group/subgroup/web", undefined)).toEqual({ + host: undefined, + repository: "group/subgroup/web", + }); + expect(parseExplicitRepoOption("group/subgroup/web", "gitlab.internal.test")).toEqual({ + host: "gitlab.internal.test", + repository: "group/subgroup/web", + }); + expect( + parseExplicitRepoOption("https://gitlab.example.com/group/sub/web.git", undefined), + ).toEqual({ + host: "gitlab.example.com", + repository: "group/sub/web", + }); + }); +}); diff --git a/apps/server/src/cli/prAttach.ts b/apps/server/src/cli/prAttach.ts new file mode 100644 index 0000000000000..1b92b4cfa4a74 --- /dev/null +++ b/apps/server/src/cli/prAttach.ts @@ -0,0 +1,237 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { fromJsonStringPretty } from "@t3tools/shared/schemaJson"; +import * as Console from "effect/Console"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import { FetchHttpClient } from "effect/http"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; + +import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; +import * as ServerConfig from "../config.ts"; +import { expandHomePath } from "../os-jank.ts"; +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; +import * as ProcessRunner from "../processRunner.ts"; +import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import * as BuiltInDrivers from "../sourceControl/builtInDrivers.ts"; +import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; +import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; +import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; +import * as VcsProcess from "../vcs/VcsProcess.ts"; +import { resolveCliAuthConfig } from "./config.ts"; + +export class PrAttachCliError extends Schema.TaggedError()("PrAttachCliError", { + detail: Schema.String, + cause: Schema.optional(Schema.Defect()), +}) { + override get message(): string { + return this.detail; + } +} + +const PrAttachUploadedItem = Schema.Struct({ + path: Schema.String, + url: Schema.String, + markdown: Schema.String, +}); +const encodePrAttachJson = Schema.encodeSync( + fromJsonStringPretty(Schema.Array(PrAttachUploadedItem)), +); + +export interface PrAttachOptions { + readonly baseDir?: string | undefined; + readonly cwd?: string | undefined; + readonly repo?: string | undefined; + readonly host?: string | undefined; + readonly alt?: string | undefined; + readonly json: boolean; + readonly files: ReadonlyArray; +} + +export function splitFileAndInlineAlt(raw: string): { + readonly filePart: string; + readonly inlineAlt: string | undefined; +} { + const hashIndex = raw.indexOf("#"); + if (hashIndex <= 0) { + return { filePart: raw, inlineAlt: undefined }; + } + const filePart = raw.slice(0, hashIndex); + const inlineAlt = raw.slice(hashIndex + 1).trim(); + return { filePart, inlineAlt: inlineAlt.length > 0 ? inlineAlt : undefined }; +} + +export function parseExplicitRepoOption( + rawRepo: string, + explicitHost: string | undefined, +): { readonly host: string | undefined; readonly repository: string } { + const trimmed = rawRepo.trim().replace(/\.git$/iu, ""); + if (URL.canParse(trimmed)) { + const parsed = new URL(trimmed); + return { + host: explicitHost?.trim().toLowerCase() ?? parsed.host.toLowerCase(), + repository: parsed.pathname.replace(/^\/+|\/+$/gu, ""), + }; + } + const segments = trimmed.split("/").filter(Boolean); + if (explicitHost === undefined && segments.length >= 3 && segments[0]!.includes(".")) { + return { + host: segments[0]!.toLowerCase(), + repository: segments.slice(1).join("/"), + }; + } + return { + host: explicitHost?.trim().toLowerCase(), + repository: segments.join("/"), + }; +} + +export const runPrAttach = Effect.fn("cli.pr.attach")(function* (options: PrAttachOptions) { + const path = yield* Path.Path; + const fs = yield* FileSystem.FileSystem; + const rawCwd = options.cwd ? yield* expandHomePath(options.cwd) : process.cwd(); + const workingDir = path.resolve(rawCwd); + const config = yield* resolveCliAuthConfig( + { baseDir: Option.fromNullishOr(options.baseDir) }, + Option.none(), + { quietLogs: true }, + ); + + if (options.alt !== undefined && options.files.length > 1) { + return yield* new PrAttachCliError({ + detail: "Pass `--alt` with a single file, or append `#Alt text` per file argument.", + }); + } + + const runtimeLayer = Layer.mergeAll(BuiltInDrivers.layer, RepositoryIdentityResolver.layer).pipe( + Layer.provideMerge( + ServerSettings.layer.pipe( + Layer.provide(Layer.merge(ServerSecretStore.layer, ManagedPolicy.layer)), + ), + ), + Layer.provideMerge(ServerSecretStore.layer), + Layer.provideMerge(SqlitePersistence.layerMemory), + Layer.provideMerge(VcsDriverRegistry.layer), + Layer.provideMerge(GitVcsDriver.layer), + Layer.provideMerge(VcsProcess.layer), + Layer.provideMerge(ProcessRunner.layer), + Layer.provideMerge(Layer.succeed(ServerConfig.ServerConfig, config)), + Layer.provideMerge(FetchHttpClient.layer), + Layer.provideMerge(NodeCrypto.layer), + Layer.provideMerge(NodeServices.layer), + ); + + const results = yield* Effect.gen(function* () { + const drivers = yield* BuiltInDrivers.SourceControlDrivers; + const identityResolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver; + + let host = options.host?.trim().toLowerCase(); + let repository: string | null = null; + let kind: "github" | "gitlab" | undefined; + + if (options.repo !== undefined) { + const parsed = parseExplicitRepoOption(options.repo, host); + host = parsed.host; + repository = parsed.repository; + } + + const identity = yield* identityResolver.resolve(workingDir); + const detectedHost = + identity !== null && identity.provider !== undefined + ? sourceControlDefinitions.changeRequestHost(identity, identity.provider)?.toLowerCase() + : undefined; + if (repository === null && identity !== null) { + repository = sourceControlDefinitions.repositorySelector(identity); + } + if (host === undefined && detectedHost) { + host = detectedHost; + } + if (host === undefined || host === detectedHost) { + if (identity?.provider === "github") kind = "github"; + else if (identity?.provider === "gitlab") kind = "gitlab"; + } + + if (host !== undefined && kind === undefined) { + if (host === "github.com" || host.endsWith(".ghe.com") || host.includes("github")) { + kind = "github"; + } else if (host === "gitlab.com" || host.includes("gitlab")) { + kind = "gitlab"; + } else { + // Probe whether glab has a login for this self-hosted hostname. + const gitlabDriver = drivers.find((entry) => entry.driver.kind === "gitlab")?.instance; + if (gitlabDriver?.pullRequests) { + const viewer = yield* gitlabDriver.pullRequests + .getViewer({ cwd: workingDir, host }) + .pipe(Effect.option); + if (viewer._tag === "Some") kind = "gitlab"; + } + } + } + if (host === undefined && kind !== undefined) { + host = kind === "github" ? "github.com" : "gitlab.com"; + } + if (!repository || !host || !kind) { + return yield* new PrAttachCliError({ + detail: + "Could not determine a GitHub or GitLab repository from this directory. Pass `--repo OWNER/REPO` (and `--host` for self-hosted GitLab).", + }); + } + + const driverEntry = drivers.find((entry) => entry.driver.kind === kind); + const uploader = driverEntry?.instance.pullRequests?.uploadAttachment; + if (!uploader) { + return yield* new PrAttachCliError({ + detail: `Provider ${kind} does not support attachment uploads.`, + }); + } + + const uploadedItems: Array<{ + readonly path: string; + readonly url: string; + readonly markdown: string; + }> = []; + + for (const rawArg of options.files) { + const literalCandidate = path.isAbsolute(rawArg) ? rawArg : path.resolve(workingDir, rawArg); + const literalExists = yield* fs + .exists(literalCandidate) + .pipe(Effect.orElseSucceed(() => false)); + const { filePart, inlineAlt } = literalExists + ? { filePart: rawArg, inlineAlt: undefined } + : splitFileAndInlineAlt(rawArg); + const resolvedPath = path.isAbsolute(filePart) + ? filePart + : path.resolve(workingDir, filePart); + const uploaded = yield* uploader({ + cwd: workingDir, + host, + repository, + filePath: resolvedPath, + fileName: path.basename(resolvedPath), + alt: options.alt ?? inlineAlt, + }).pipe( + Effect.mapError((error) => new PrAttachCliError({ detail: error.detail, cause: error })), + ); + uploadedItems.push({ + path: filePart, + url: uploaded.url, + markdown: uploaded.markdown, + }); + } + + return uploadedItems; + }).pipe(Effect.provide(runtimeLayer), Effect.scoped); + + if (options.json) { + yield* Console.log(encodePrAttachJson(results)); + } else { + for (const item of results) { + yield* Console.log(item.markdown); + } + } +}); diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts index b036392730fa9..dedc260fede1a 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts @@ -23,6 +23,7 @@ import * as Effect from "effect/Effect"; import * as Base64Url from "effect/encoding/Base64Url"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Path from "effect/Path"; import * as Ref from "effect/Ref"; import * as Stream from "effect/Stream"; import type { Tool } from "effect/ai"; @@ -34,9 +35,9 @@ import { v2PullRequestThread, } from "../../../orchestration-v2/testkit/pullRequestFixtures.ts"; import * as ProjectService from "../../../project/ProjectService.ts"; +import * as PullRequestService from "../../../pullRequest/PullRequestService.ts"; import * as PullRequestWatchService from "../../../pullRequest/PullRequestWatchService.ts"; import * as PullRequestReviewGuideService from "../../../pullRequest/PullRequestReviewGuideService.ts"; -import * as PullRequestService from "../../../pullRequest/PullRequestService.ts"; import * as McpInvocationContext from "../../McpInvocationContext.ts"; import * as McpToolAccess from "../../McpToolAccess.ts"; import * as McpToolAccessTestkit from "../../McpToolAccess.testkit.ts"; @@ -164,6 +165,9 @@ const makeHarness = Effect.fn("makePullRequestsToolkitHarness")(function* ( ) { const commands = yield* Ref.make>([]); const guideRequests = yield* Ref.make>([]); + const uploadRequests = yield* Ref.make< + ReadonlyArray + >([]); const thread = options.thread === undefined ? makeThread([]) : options.thread; const project = options.project === undefined ? makeProject() : options.project; const dispatch: Orchestrator.OrchestratorV2Shape["dispatch"] = (command) => @@ -180,6 +184,18 @@ const makeHarness = Effect.fn("makePullRequestsToolkitHarness")(function* ( }); const layerDependencies = Layer.mergeAll( Layer.mock(PullRequestWatchService.PullRequestWatchService)({}), + Layer.mock(PullRequestService.PullRequestService)({ + uploadAttachment: (input) => + Ref.update(uploadRequests, (recorded) => [...recorded, input]).pipe( + Effect.as({ + url: `https://uploads.example.com/${input.fileName}`, + markdown: `![${input.alt ?? input.fileName}](https://uploads.example.com/${input.fileName})`, + name: input.fileName, + mimeType: "image/png", + }), + ), + ...options.pullRequests, + }), Layer.mock(ProjectService.ProjectService)({ getShell: () => Effect.succeed(Option.fromNullishOr(project)), listShells: () => Effect.succeed(options.projects ?? (project ? [project] : [])), @@ -207,8 +223,8 @@ const makeHarness = Effect.fn("makePullRequestsToolkitHarness")(function* ( Effect.succeed(id === thread?.id ? v2PullRequestThread(thread) : null), dispatch, }), - Layer.mock(PullRequestService.PullRequestService)(options.pullRequests ?? {}), Layer.mock(GitManager.GitManager)(options.git ?? {}), + Path.layer, Layer.succeed(SecureRandom.SecureRandom, testCrypto), McpToolAccessTestkit.liveThreadsLayer, ); @@ -233,7 +249,7 @@ const makeHarness = Effect.fn("makePullRequestsToolkitHarness")(function* ( Effect.provideService(McpInvocationContext.McpInvocationContext, invocation(capabilities)), Effect.provide(layerDependencies), ); - return { commands, guideRequests, call }; + return { commands, guideRequests, uploadRequests, call }; }); describe("pull request toolkit handlers", () => { @@ -796,6 +812,49 @@ describe("pull request guide tools", () => { ]); }), ); + + it.effect( + "resolves relative attachment paths against the caller thread worktree and routes to the matching repository project", + () => + Effect.gen(function* () { + const gitlabProject = { + ...makeProject({ + canonicalKey: "gitlab.example.com/group/app", + locator: { + source: "git-remote", + remoteName: "origin", + remoteUrl: "https://gitlab.example.com/group/app.git", + }, + provider: SourceControlProviderKind.make("gitlab"), + displayName: "group/app", + owner: "group", + name: "app", + }), + id: ProjectId.make("project-gitlab"), + }; + const harness = yield* makeHarness({ + thread: { ...makeThread([]), worktreePath: "/workspace/worktree-1" }, + projects: [makeProject(), gitlabProject], + }); + const result = yield* harness.call("upload_pull_request_attachment", { + path: "artifacts/before.png", + alt: "Before fix", + url: "https://gitlab.example.com/group/app/-/merge_requests/42", + }); + expect(result.markdown).toBe("![Before fix](https://uploads.example.com/before.png)"); + expect(yield* Ref.get(harness.uploadRequests)).toEqual([ + { + projectId: "project-gitlab", + repository: "group/app", + host: "gitlab.example.com", + number: 42, + filePath: "/workspace/worktree-1/artifacts/before.png", + fileName: "before.png", + alt: "Before fix", + }, + ]); + }), + ); }); describe("source control tools", () => { diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts index 65eaf22975c68..f9a1ae9e1af54 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts @@ -20,14 +20,15 @@ import * as Effect from "effect/Effect"; import * as Base64Url from "effect/encoding/Base64Url"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; +import * as Path from "effect/Path"; import * as GitManager from "../../../git/GitManager.ts"; import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts"; import * as ProjectService from "../../../project/ProjectService.ts"; +import * as PullRequestService from "../../../pullRequest/PullRequestService.ts"; import * as PullRequestWatchService from "../../../pullRequest/PullRequestWatchService.ts"; import { resolveTarget, type ResolvedTarget } from "../../../pullRequest/pullRequestTarget.ts"; import * as PullRequestReviewGuideService from "../../../pullRequest/PullRequestReviewGuideService.ts"; -import * as PullRequestService from "../../../pullRequest/PullRequestService.ts"; import { reviewPositionInPatch } from "../../../pullRequest/pullRequestReviewPosition.ts"; import { pullRequestSyncKey } from "../../../pullRequest/pullRequestSyncKey.ts"; import { sourceControlDefinitions } from "../../../sourceControl/sourceControlDefinitions.ts"; @@ -59,6 +60,7 @@ import { PullRequestThreadRequiredError, PullRequestGuideFailedError, PullRequestProjectNotFoundError, + PullRequestUploadFailedError, PullRequestsToolkit, type ThreadPullRequestEntry, CHILD_PULL_REQUEST_REPORT_NEXT, @@ -257,10 +259,11 @@ function projectForPullRequest( const make = Effect.gen(function* () { const engine = yield* Orchestrator.OrchestratorV2; + const pullRequests = yield* PullRequestService.PullRequestService; const reviewGuides = yield* PullRequestReviewGuideService.PullRequestReviewGuideService; const watches = yield* PullRequestWatchService.PullRequestWatchService; - const pullRequests = yield* PullRequestService.PullRequestService; const git = yield* GitManager.GitManager; + const path = yield* Path.Path; const projects = yield* ProjectService.ProjectService; const random = yield* SecureRandom.SecureRandom; @@ -1215,6 +1218,92 @@ const make = Effect.gen(function* () { return { ...identityOf(target), checks }; }), ), + upload_pull_request_attachment: writesThread((input) => + Effect.gen(function* () { + const scope = yield* McpInvocationContext.requireMcpCapability("pull-requests"); + const threadId = input.threadId ?? scope.thread?.threadId; + const callerThread = + threadId === undefined + ? undefined + : yield* engine.getThreadShell(threadId).pipe( + Effect.map((shell) => + shell === null || shell.deletedAt !== null ? undefined : shell, + ), + Effect.mapError( + (cause) => + new PullRequestUploadFailedError({ + detail: "Could not read thread context.", + cause, + }), + ), + ); + const known = yield* projects.listShells().pipe( + Effect.mapError( + (cause) => + new PullRequestUploadFailedError({ + detail: "Could not list projects.", + cause, + }), + ), + ); + const callerProject = known.find((project) => project.id === callerThread?.projectId); + + let targetHost = input.host; + let targetRepository = input.repository; + let targetNumber = input.number; + if ( + input.url !== undefined || + (input.repository !== undefined && input.number !== undefined) + ) { + const resolved = yield* resolveTarget(input, callerProject); + targetHost = resolved.host; + targetRepository = resolved.repository; + targetNumber = resolved.number; + } + + const matchedProject = + targetHost !== undefined && targetRepository !== undefined + ? (projectForPullRequest( + known, + { host: targetHost, repository: targetRepository }, + callerProject, + ) ?? callerProject) + : callerProject; + if (matchedProject === undefined) { + if (targetRepository !== undefined) { + return yield* new PullRequestProjectNotFoundError({ repository: targetRepository }); + } + return yield* new PullRequestThreadRequiredError(); + } + + const baseDir = callerThread?.worktreePath ?? matchedProject.workspaceRoot; + const resolvedFilePath = path.isAbsolute(input.path) + ? input.path + : path.resolve(baseDir, input.path); + const fileName = path.basename(resolvedFilePath); + + return yield* pullRequests + .uploadAttachment({ + projectId: matchedProject.id, + repository: targetRepository, + host: targetHost, + number: targetNumber, + filePath: resolvedFilePath, + fileName, + alt: input.alt, + }) + .pipe( + Effect.mapError((error) => + error._tag === "PullRequestUnavailableError" + ? error + : new PullRequestUploadFailedError({ + detail: guideFailureDetail(error), + cause: error, + }), + ), + ); + }), + ), } satisfies McpToolAccess.Handlers; }); diff --git a/apps/server/src/mcp/toolkits/pullRequests/tools.ts b/apps/server/src/mcp/toolkits/pullRequests/tools.ts index 5a4b671a98dea..b925b99b40ef4 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/tools.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/tools.ts @@ -17,10 +17,12 @@ import { PullRequestState, PullRequestUnavailableError, PullRequestWatchUntil, + PullRequestUploadAttachmentResult, ThreadPullRequestLinkSource, TrimmedNonEmptyString, ThreadId, } from "@t3tools/contracts"; +import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import * as McpSchema from "effect/ai/McpSchema"; import * as Tool from "effect/ai/Tool"; @@ -57,6 +59,8 @@ const guideDependencies = [ const watchDependencies = [...dependencies, PullRequestWatchService.PullRequestWatchService]; +const attachmentDependencies = [...forgeDependencies, Path.Path]; + export const PullRequestTargetInput = Schema.Struct({ environmentId: OrchestratorMcpEnvironmentTarget, threadId: Schema.optional( @@ -173,6 +177,15 @@ export class PullRequestNothingToDoError extends Schema.TaggedError()( + "PullRequestUploadFailedError", + { detail: Schema.String, cause: Schema.optional(Schema.Defect()) }, +) { + override get message(): string { + return this.detail; + } +} + export const PullRequestToolError = Schema.Union([ OrchestratorMcpFailure, McpCapabilityUnavailableError, @@ -194,6 +207,7 @@ export const PullRequestToolError = Schema.Union([ PullRequestBranchHasNoneError, PullRequestNothingToDoError, PullRequestCursorInvalidError, + PullRequestUploadFailedError, ]); export type PullRequestToolError = typeof PullRequestToolError.Type; @@ -850,6 +864,31 @@ const RerunChecksTool = Tool.make("ci_rerun", { .annotate(Tool.OpenWorld, true) .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenWithoutForge); +const UploadPullRequestAttachmentTool = Tool.make("upload_pull_request_attachment", { + description: + "Upload a local image or video to a GitHub or GitLab repository and return `{url, markdown}` for PR/MR text.", + parameters: Schema.Struct({ + environmentId: OrchestratorMcpEnvironmentTarget, + path: TrimmedNonEmptyString.annotate({ + description: "Local file path.", + }), + alt: Schema.optional(TrimmedNonEmptyString), + threadId: PullRequestTargetInput.fields.threadId, + url: PullRequestTargetInput.fields.url, + repository: PullRequestTargetInput.fields.repository, + number: PullRequestTargetInput.fields.number, + host: PullRequestTargetInput.fields.host, + }), + success: PullRequestUploadAttachmentResult, + failure: PullRequestToolError, + dependencies: attachmentDependencies, +}) + .annotate(Tool.Title, "Upload pull request attachment") + .annotate(Tool.Readonly, false) + .annotate(Tool.Destructive, false) + .annotate(Tool.Idempotent, false) + .annotate(Tool.OpenWorld, true); + export const PullRequestsToolkit = Toolkit.make( LinkPullRequestTool, LinkPullRequestsTool, @@ -869,4 +908,5 @@ export const PullRequestsToolkit = Toolkit.make( MergePullRequestTool, CheckLogsTool, RerunChecksTool, + UploadPullRequestAttachmentTool, ); diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index a2b698657afcb..00adf4714a7b4 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -158,6 +158,7 @@ const RPC_AGGREGATES = { [WS_METHODS.issueTrackersList]: "issues", [WS_METHODS.issueTrackersConnect]: "issues", [WS_METHODS.issueTrackersBindProject]: "issues", + [WS_METHODS.pullRequestsUploadAttachment]: "pull-requests", [WS_METHODS.sourceControlLookupRepository]: "source-control", [WS_METHODS.sourceControlCloneRepository]: "source-control", [WS_METHODS.sourceControlPublishRepository]: "source-control", diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 5f44bd54c29f8..007b6213722a2 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6245, "codexAdditionalContextBytes": 7639, - "mcpToolListJsonBytes": 57321 + "mcpToolListJsonBytes": 57902 } diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts index 73a7222cf9a01..2d839e6c42c71 100644 --- a/apps/server/src/pullRequest/PullRequestService.test.ts +++ b/apps/server/src/pullRequest/PullRequestService.test.ts @@ -5409,3 +5409,98 @@ it.effect.each(["expiry", "commit expiry", "cache hit", "commit cache hit", "ref assert.strictEqual(diffReads, 2); }), ); + +it.effect( + "uploads pull request attachments through providers that support them and rejects unsupported hosts", + () => + Effect.gen(function* () { + let viewerCanUpload = true; + const baseProvider = fakePullRequestProvider(SourceControlProviderKind.make("github"), { + getViewerPermissions: () => + Effect.succeed({ + actions: ["merge"], + comment: true, + resolve: true, + verdicts: ["comment", "approve", "request-changes"], + requestReviewers: true, + uploadAttachment: viewerCanUpload, + }), + }); + const unsupportedProvider = fakePullRequestProvider( + SourceControlProviderKind.make("bitbucket"), + {}, + ); + const service = yield* makeService({ + projects: [ + project({ id: "p-gh", title: "gh", workspaceRoot: "/gh", repository: "acme/web" }), + project({ + id: "p-bb", + title: "bb", + workspaceRoot: "/bb", + repository: "acme/bb", + provider: "bitbucket", + host: "bitbucket.org", + }), + ], + providers: [ + { + ...baseProvider, + capabilities: { ...baseProvider.capabilities, attachments: true }, + uploadAttachment: (input) => + Effect.succeed({ + url: `https://uploads.github.com/user-attachments/assets/${input.fileName}`, + markdown: `![${input.alt ?? input.fileName}](https://uploads.github.com/user-attachments/assets/${input.fileName})`, + name: input.fileName, + mimeType: input.mimeType ?? "image/png", + }), + }, + unsupportedProvider, + ], + }); + + const uploaded = yield* service.uploadAttachment({ + projectId: "p-gh" as ProjectId, + repository: "acme/web", + number: 1, + filePath: "/tmp/demo.png", + fileName: "demo.png", + alt: "Demo capture", + }); + assert.strictEqual( + uploaded.markdown, + "![Demo capture](https://uploads.github.com/user-attachments/assets/demo.png)", + ); + + viewerCanUpload = false; + yield* service.invalidate({ + reference: { projectId: "p-gh" as ProjectId, repository: "acme/web", number: 1 }, + }); + const denied = yield* service + .uploadAttachment({ + projectId: "p-gh" as ProjectId, + repository: "acme/web", + number: 1, + filePath: "/tmp/demo.png", + fileName: "demo.png", + }) + .pipe(Effect.flip); + assert.strictEqual(denied._tag, "PullRequestOperationError"); + if (denied._tag === "PullRequestOperationError") { + assert.include(denied.detail, "write access"); + } + + const error = yield* service + .uploadAttachment({ + projectId: "p-bb" as ProjectId, + repository: "acme/bb", + number: 1, + filePath: "/tmp/demo.png", + fileName: "demo.png", + }) + .pipe(Effect.flip); + assert.strictEqual(error._tag, "PullRequestOperationError"); + if (error._tag === "PullRequestOperationError") { + assert.strictEqual(error.detail, "This host cannot attach files to change requests."); + } + }), +); diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index eab5d89888d8f..501cb539d9626 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -72,6 +72,8 @@ import { type PullRequestThreadCommentsInput, type PullRequestThreadCommentsResult, type PullRequestUpdateInput, + type PullRequestUploadAttachmentResult, + TrimmedNonEmptyString, type SourceControlProviderInfo, SourceControlProviderKind, type ThreadPullRequestKey, @@ -108,6 +110,17 @@ export interface PullRequestMergeEvent extends PullRequestRef { readonly mergedAt: string; } +export interface PullRequestUploadFileInput { + readonly projectId: ProjectId; + readonly repository?: string | undefined; + readonly host?: string | undefined; + readonly number?: number | undefined; + readonly filePath: string; + readonly fileName: string; + readonly mimeType?: string | undefined; + readonly alt?: string | undefined; +} + type PullRequestReading = Pick< PullRequestSummary, "state" | "isDraft" | "updatedAt" | "observedAt" @@ -316,6 +329,9 @@ export class PullRequestService extends Context.Service< readonly setLabels: ( input: PullRequestLabelChangeInput, ) => Effect.Effect; + readonly uploadAttachment: ( + input: PullRequestUploadFileInput, + ) => Effect.Effect; readonly invalidate: ( input: PullRequestInvalidateInput, options?: { readonly notifyReaders?: boolean }, @@ -682,6 +698,9 @@ function withRateLimitBackoff( replyToThread: interactive("replyToThread", api.replyToThread), setReaction: interactive("setReaction", api.setReaction), setThreadResolution: interactive("setThreadResolution", api.setThreadResolution), + ...(api.uploadAttachment === undefined + ? {} + : { uploadAttachment: interactive("uploadAttachment", api.uploadAttachment) }), }; // Optional provider methods must be forwarded too; returning the interface alone permits omissions. return wrapped satisfies PullRequestProviderApi & @@ -2498,6 +2517,89 @@ export const make = Effect.gen(function* () { }), ); + const uploadAttachment: PullRequestService["Service"]["uploadAttachment"] = (input) => + (input.repository !== undefined && input.repository.trim().length > 0 + ? requireProject({ + projectId: input.projectId, + repository: input.repository, + ...(input.host === undefined ? {} : { host: input.host }), + number: input.number ?? 1, + }) + : listWorkspaceProjects({ projectId: input.projectId }).pipe( + Effect.flatMap(({ supported }): Effect.Effect => { + const own = supported[0]; + if (own === undefined) { + return Effect.fail( + new PullRequestUnavailableError({ reason: "provider-unsupported" }), + ); + } + const requestedHost = input.host?.trim().toLowerCase(); + if (requestedHost !== undefined && requestedHost !== own.host) { + return Effect.fail( + new PullRequestOperationError({ + operation: "uploadAttachment", + detail: "The selected project is not hosted on that server.", + }), + ); + } + return Effect.succeed(own); + }), + ) + ).pipe( + Effect.flatMap( + (project): Effect.Effect => { + const uploader = project.api.uploadAttachment; + if (project.api.capabilities.attachments !== true || uploader === undefined) { + return Effect.fail( + new PullRequestOperationError({ + operation: "uploadAttachment", + detail: "This host cannot attach files to change requests.", + }), + ); + } + const runUpload = uploader({ + cwd: project.project.workspaceRoot, + repository: project.repository, + host: project.host, + filePath: input.filePath, + fileName: input.fileName, + mimeType: input.mimeType, + alt: input.alt, + }).pipe( + Effect.mapError(toPullRequestError("uploadAttachment")), + Effect.map((uploaded) => ({ + url: TrimmedNonEmptyString.make(uploaded.url), + markdown: TrimmedNonEmptyString.make(uploaded.markdown), + })), + ); + if (input.number === undefined) { + return runUpload; + } + return viewerPermissionsOf( + project, + { + projectId: input.projectId, + repository: project.repository, + host: project.host, + number: input.number, + }, + "uploadAttachment", + ).pipe( + Effect.flatMap((viewer) => + viewer.uploadAttachment === false + ? Effect.fail( + new PullRequestOperationError({ + operation: "uploadAttachment", + detail: "You need write access on this repository to attach files.", + }), + ) + : runUpload, + ), + ); + }, + ), + ); + const submitReview: PullRequestService["Service"]["submitReview"] = (input) => requireProject(input).pipe( Effect.flatMap((project): Effect.Effect => { @@ -4165,6 +4267,7 @@ export const make = Effect.gen(function* () { requestReviewers: invalidatedByMutation(requestReviewers), labelCandidates, setLabels: invalidatedByMutation(setLabels), + uploadAttachment, invalidate, }); }); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 63d45c48816e4..8d862627e15ef 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -97,6 +97,7 @@ import { PersistChatAttachmentsError, RpcClientId, EnvironmentAuthorizationError, + PullRequestOperationError, ThreadId, type TerminalMetadataStreamEvent, type PullRequestRef, @@ -206,7 +207,11 @@ import { createDeterministicAttachmentId, } from "./attachmentStore.ts"; import { parseBase64DataUrl } from "./imageMime.ts"; -import { deletePendingAttachment, issueAttachmentUploadUrl } from "./assets/AttachmentUpload.ts"; +import { + deletePendingAttachment, + issueAttachmentUploadUrl, + resolvePendingAttachmentPath, +} from "./assets/AttachmentUpload.ts"; import * as PortScanner from "./preview/PortScanner.ts"; import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts"; import * as KnownWorkspaces from "./workspace/KnownWorkspaces.ts"; @@ -2871,6 +2876,43 @@ export const layerWsRpc = ( withPullRequestViewer(input, pullRequests.labelCandidates(input)), [WS_METHODS.pullRequestsSetLabels]: (input) => withPullRequestViewer(input, pullRequests.setLabels(input)), + [WS_METHODS.pullRequestsUploadAttachment]: (input) => + resolvePendingAttachmentPath(input.attachmentId).pipe( + Effect.flatMap((filePath) => { + if (!filePath) { + return Effect.fail( + new PullRequestOperationError({ + operation: "uploadAttachment", + detail: + "The uploaded file expired before it could be sent to the host. Try attaching it again.", + }), + ); + } + const run = pullRequests.uploadAttachment({ + projectId: input.projectId, + repository: input.repository, + host: input.host, + number: input.number, + filePath, + fileName: input.fileName, + mimeType: input.mimeType, + alt: input.alt, + }); + const scoped = + input.repository !== undefined && input.number !== undefined + ? withPullRequestViewer( + { + projectId: input.projectId, + repository: input.repository, + ...(input.host === undefined ? {} : { host: input.host }), + number: input.number, + }, + run, + ) + : run; + return scoped.pipe(Effect.tap(() => deletePendingAttachment(input.attachmentId))); + }), + ), [WS_METHODS.sourceControlLookupRepository]: (input) => sourceControlRepositories.lookupRepository(input), [WS_METHODS.sourceControlCloneRepository]: (input) => diff --git a/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.browser.test.tsx index 1f946c684f6b1..39b05a5b78f03 100644 --- a/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.browser.test.tsx @@ -1,5 +1,11 @@ import { act, render, type Screen } from "../../../test/render"; -import { AuthSourceControlWriteScope, EnvironmentId, ProjectId } from "@t3tools/contracts"; +import { + AuthSourceControlWriteScope, + EnvironmentId, + ProjectId, + SourceControlProviderKind, + TrimmedNonEmptyString, +} from "@t3tools/contracts"; import { expect, it, vi } from "vite-plus/test"; import { page, userEvent } from "vite-plus/test/browser"; @@ -8,6 +14,14 @@ const permissions = vi.hoisted(() => ({ listeners: new Set<() => void>(), })); +const uploadMock = vi.hoisted(() => ({ + impl: vi.fn(), +})); + +vi.mock(import("./uploadPullRequestAttachment"), () => ({ + uploadPullRequestAttachment: (input: unknown) => uploadMock.impl(input), +})); + vi.mock(import("~/state/session"), async (original) => { const { useSyncExternalStore } = await import("react"); const canWrite = (environmentId: string | null, scope: string) => @@ -60,9 +74,15 @@ function setup() { permissions.listeners.clear(); onSave.mockReset(); onCancel.mockReset(); + uploadMock.impl.mockReset(); } -async function openEditor(options?: { value?: string; allowEmpty?: boolean }) { +async function openEditor(options?: { + value?: string; + allowEmpty?: boolean; + attachable?: boolean; +}) { + const projectId = ProjectId.make("project"); return render( { + setup(); + permissions.allowed.add(secondary); + let resolveUpload!: (result: { url: string; markdown: string }) => void; + uploadMock.impl.mockImplementation( + () => + new Promise((resolve) => { + resolveUpload = resolve; + }), + ); + + await using screen = await openEditor({ value: "Summary:", attachable: true }); + await expect.element(page.getByRole("button", { name: "Attach files" })).toBeVisible(); + const fileInput = screen.container.querySelector('input[type="file"]') as HTMLInputElement; + expect(fileInput).toBeTruthy(); + + const textarea = screen.container.querySelector("textarea")!; + textarea.setSelectionRange(textarea.value.length, textarea.value.length); + + const video = new File([new Uint8Array([1, 2, 3, 4])], "demo.mp4", { type: "video/mp4" }); + await userEvent.upload(fileInput, video); + + expect(textarea.value).toContain('`; +} + +export function insertPullRequestUploadPlaceholders( + text: string, + selectionStart: number, + selectionEnd: number, + placeholders: ReadonlyArray, +): { readonly text: string; readonly cursor: number } { + if (placeholders.length === 0) { + const clamped = Math.max(0, Math.min(selectionEnd, text.length)); + return { text, cursor: clamped }; + } + const start = Math.max(0, Math.min(selectionStart, text.length)); + const end = Math.max(start, Math.min(selectionEnd, text.length)); + const before = text.slice(0, start); + const after = text.slice(end); + const prefix = before.length > 0 && !before.endsWith("\n") ? "\n" : ""; + const suffix = after.length > 0 && !after.startsWith("\n") ? "\n" : ""; + const block = placeholders.join("\n"); + const next = `${before}${prefix}${block}${suffix}${after}`; + const cursor = before.length + prefix.length + block.length; + return { text: next, cursor }; +} + +function isBareAttachmentUrl(markdown: string): boolean { + return /^https?:\/\/\S+$/u.test(markdown.trim()); +} + +export function replacePullRequestUploadPlaceholder( + text: string, + placeholder: string, + markdown: string, +): string { + const trimmedMarkdown = markdown.trim(); + const bareUrl = isBareAttachmentUrl(trimmedMarkdown); + const index = text.indexOf(placeholder); + if (index === -1) { + if (text.length === 0) return trimmedMarkdown; + const separator = bareUrl + ? text.endsWith("\n\n") + ? "" + : text.endsWith("\n") + ? "\n" + : "\n\n" + : text.endsWith("\n") + ? "" + : "\n"; + return `${text}${separator}${trimmedMarkdown}`; + } + const before = text.slice(0, index); + const after = text.slice(index + placeholder.length); + if (!bareUrl) { + return `${before}${trimmedMarkdown}${after}`; + } + const leading = + before.length === 0 || before.endsWith("\n\n") ? "" : before.endsWith("\n") ? "\n" : "\n\n"; + const trailing = + after.length === 0 || after.startsWith("\n\n") ? "" : after.startsWith("\n") ? "\n" : "\n\n"; + return `${before}${leading}${trimmedMarkdown}${trailing}${after}`; +} + +export function removePullRequestUploadPlaceholder(text: string, placeholder: string): string { + const index = text.indexOf(placeholder); + if (index === -1) return text; + const before = text.slice(0, index); + const after = text.slice(index + placeholder.length); + if (before.endsWith("\n") && after.startsWith("\n")) { + return `${before}${after.slice(1)}`; + } + if (before.length === 0 && after.startsWith("\n")) { + return after.slice(1); + } + if (after.length === 0 && before.endsWith("\n")) { + return before.slice(0, -1); + } + return `${before}${after}`; +} diff --git a/packages/client-runtime/src/state/pullRequests.ts b/packages/client-runtime/src/state/pullRequests.ts index a207f69902f7f..883acd4e61808 100644 --- a/packages/client-runtime/src/state/pullRequests.ts +++ b/packages/client-runtime/src/state/pullRequests.ts @@ -1402,6 +1402,11 @@ export function createPullRequestEnvironmentAtoms( scheduler: commandScheduler, concurrency: serialPerEnvironment, }), + uploadAttachment: createEnvironmentRpcCommand(runtime, { + label: "environment-data:pull-requests:upload-attachment", + tag: WS_METHODS.pullRequestsUploadAttachment, + scheduler: commandScheduler, + }), updateComment: createEnvironmentRpcCommand(runtime, { label: "environment-data:pull-requests:update-comment", tag: WS_METHODS.pullRequestsUpdateComment, diff --git a/packages/contracts/src/assets.ts b/packages/contracts/src/assets.ts index 0cae763748d7a..620183afcc8ee 100644 --- a/packages/contracts/src/assets.ts +++ b/packages/contracts/src/assets.ts @@ -105,6 +105,7 @@ export const AssetCreateUrlResult = Schema.Struct({ export type AssetCreateUrlResult = typeof AssetCreateUrlResult.Type; export const ATTACHMENT_UPLOAD_URL_TTL_MS = 10 * 60_000; +export const PULL_REQUEST_ATTACHMENT_MAX_BYTES = 100 * 1024 * 1024; const ImageAttachmentCreateUploadUrlInput = Schema.Struct({ type: Schema.optionalKey(Schema.Literal("image")), @@ -126,9 +127,20 @@ const FileAttachmentCreateUploadUrlInput = Schema.Struct({ ), }); +const PullRequestAttachmentCreateUploadUrlInput = Schema.Struct({ + type: Schema.Literal("pull-request"), + name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)), + mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100)), + sizeBytes: NonNegativeInt.check( + Schema.isGreaterThanOrEqualTo(1), + Schema.isLessThanOrEqualTo(PULL_REQUEST_ATTACHMENT_MAX_BYTES), + ), +}); + export const AttachmentCreateUploadUrlInput = Schema.Union([ ImageAttachmentCreateUploadUrlInput, FileAttachmentCreateUploadUrlInput, + PullRequestAttachmentCreateUploadUrlInput, ]); export type AttachmentCreateUploadUrlInput = typeof AttachmentCreateUploadUrlInput.Type; diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts index 0b6164871a0ad..548aa76381e40 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -1,4 +1,5 @@ import * as Schema from "effect/Schema"; +import { AttachmentCreateUploadUrlInput } from "./assets.ts"; import { GitPreparePullRequestThreadInput, GitRunStackedActionInput } from "./git.ts"; import { AuthAccessWriteScope, @@ -48,6 +49,7 @@ export const CLIENT_GUARDED_RPC_SCOPES = { // A tracker credential and a project's binding are settings, saved under the same grant. [WS_METHODS.issueTrackersConnect]: AuthSettingsWriteScope, [WS_METHODS.issueTrackersBindProject]: AuthSettingsWriteScope, + [WS_METHODS.pullRequestsUploadAttachment]: AuthSourceControlWriteScope, // Writing a guide runs a model on this environment's providers, which reading one does not. [WS_METHODS.pullRequestsGenerateReviewGuide]: AuthOrchestrationOperateScope, [WS_METHODS.projectsCreateFromThread]: AuthOrchestrationOperateScope, @@ -89,6 +91,7 @@ export const CLIENT_GUARDED_RPC_SCOPES = { } as const; export type ClientGuardedRpcTag = keyof typeof CLIENT_GUARDED_RPC_SCOPES; +const decodeAttachmentUpload = Schema.decodeUnknownSync(AttachmentCreateUploadUrlInput); const decodePrepareThread = Schema.decodeUnknownSync(GitPreparePullRequestThreadInput); const decodeStackedAction = Schema.decodeUnknownSync(GitRunStackedActionInput); @@ -96,6 +99,10 @@ export function clientRpcRequiredScopes( method: string, input: unknown, ): readonly AuthEnvironmentScope[] { + if (method === WS_METHODS.attachmentsCreateUploadUrl && input !== undefined) { + const payload = decodeAttachmentUpload(input); + if (payload.type === "pull-request") return [AuthSourceControlWriteScope]; + } if (method === WS_METHODS.gitPreparePullRequestThread && input !== undefined) { const payload = decodePrepareThread(input); if (payload.mode === "worktree" && payload.threadId !== undefined) diff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.ts index 16318bc7f660d..a0f36d2b3eb60 100644 --- a/packages/contracts/src/pullRequest.ts +++ b/packages/contracts/src/pullRequest.ts @@ -326,6 +326,8 @@ export const PullRequestCapabilities = Schema.Struct({ checksAlwaysReport: Schema.optional(Schema.Boolean), /** The diff can read one file the paged diff withheld as too large (`PullRequestDiffInput.path`). */ withheldFileDiff: Schema.optional(Schema.Boolean), + /** The host uploads files to the repository and returns Markdown to embed them. */ + attachments: Schema.optional(Schema.Boolean), }); export type PullRequestCapabilities = typeof PullRequestCapabilities.Type; @@ -341,6 +343,7 @@ export const PullRequestViewerPermissions = Schema.Struct({ labels: Schema.optional(Schema.Boolean), editChangeRequest: Schema.optional(Schema.Boolean), maintainerEdits: Schema.optional(Schema.Boolean), + uploadAttachment: Schema.optional(Schema.Boolean), }); export type PullRequestViewerPermissions = typeof PullRequestViewerPermissions.Type; @@ -977,6 +980,24 @@ export const PullRequestLabelChangeInput = Schema.Struct({ }); export type PullRequestLabelChangeInput = typeof PullRequestLabelChangeInput.Type; +export const PullRequestUploadAttachmentInput = Schema.Struct({ + projectId: ProjectId, + repository: Schema.optional(TrimmedNonEmptyString), + host: Schema.optional(TrimmedNonEmptyString), + number: Schema.optional(PositiveInt), + attachmentId: TrimmedNonEmptyString.check(Schema.isMaxLength(256)), + fileName: TrimmedNonEmptyString.check(Schema.isMaxLength(255)), + mimeType: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(100))), + alt: Schema.optional(Schema.String.check(Schema.isMaxLength(1024))), +}); +export type PullRequestUploadAttachmentInput = typeof PullRequestUploadAttachmentInput.Type; + +export const PullRequestUploadAttachmentResult = Schema.Struct({ + url: TrimmedNonEmptyString, + markdown: TrimmedNonEmptyString, +}); +export type PullRequestUploadAttachmentResult = typeof PullRequestUploadAttachmentResult.Type; + /** * The names keep their `cli-` prefix for wire compatibility; for a host read with a credential * rather than a tool they mean "no credential" and "a refused credential". diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 41733dae56417..688a35842bec1 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -243,6 +243,8 @@ import { PullRequestThreadResolutionInput, PullRequestUnavailableError, PullRequestUpdateInput, + PullRequestUploadAttachmentInput, + PullRequestUploadAttachmentResult, } from "./pullRequest.ts"; import { RelayClientInstallFailedError, @@ -627,6 +629,7 @@ export const WS_METHODS = { pullRequestsRequestReviewers: "pullRequests.requestReviewers", pullRequestsLabelCandidates: "pullRequests.labelCandidates", pullRequestsSetLabels: "pullRequests.setLabels", + pullRequestsUploadAttachment: "pullRequests.uploadAttachment", // Issue tracking methods issuesList: "issues.list", @@ -1240,6 +1243,12 @@ const WsPullRequestsCommentRpc = Rpc.make(WS_METHODS.pullRequestsComment, { error: PullRequestRpcError, }); +const WsPullRequestsUploadAttachmentRpc = Rpc.make(WS_METHODS.pullRequestsUploadAttachment, { + payload: PullRequestUploadAttachmentInput, + success: PullRequestUploadAttachmentResult, + error: PullRequestRpcError, +}); + const WsPullRequestsUpdateCommentRpc = Rpc.make(WS_METHODS.pullRequestsUpdateComment, { payload: PullRequestCommentUpdateInput, success: Schema.Void, @@ -2377,6 +2386,7 @@ export const WsRpcGroup = RpcGroup.make( WsPullRequestsRequestReviewersRpc, WsPullRequestsLabelCandidatesRpc, WsPullRequestsSetLabelsRpc, + WsPullRequestsUploadAttachmentRpc, WsSourceControlLookupRepositoryRpc, WsSourceControlCloneRepositoryRpc, WsSourceControlPublishRepositoryRpc, diff --git a/packages/source-control-core/src/server/PullRequestProvider.ts b/packages/source-control-core/src/server/PullRequestProvider.ts index 4db5f263daba1..4f1e879c85fb2 100644 --- a/packages/source-control-core/src/server/PullRequestProvider.ts +++ b/packages/source-control-core/src/server/PullRequestProvider.ts @@ -342,6 +342,11 @@ export interface ProviderFilterOptionPage { readonly truncated: boolean; } +export interface ProviderUploadedAttachment { + readonly url: string; + readonly markdown: string; +} + export interface ProviderRepositoryRef { readonly cwd: string; readonly repository: string; @@ -702,4 +707,13 @@ export interface PullRequestProviderApi { readonly resolved: boolean; }, ) => Effect.Effect; + + readonly uploadAttachment?: ( + input: ProviderRepositoryRef & { + readonly filePath: string; + readonly fileName: string; + readonly mimeType?: string | undefined; + readonly alt?: string | undefined; + }, + ) => Effect.Effect; } diff --git a/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts b/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts index 5911bd3c3a117..2af3224887ed6 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts @@ -177,12 +177,42 @@ describe("gitHubViewerPermissions", () => { comment: true, resolve: true, stackRebase: true, + uploadAttachment: true, verdicts: ["comment", "approve", "request-changes"], requestReviewers: true, labels: true, }); }); + it("withholds attachment upload on GitHub Enterprise Server even with write access", () => { + expect( + gitHubViewerPermissions( + { + canWrite: true, + canDeleteBranch: true, + canTriage: true, + canUpdate: true, + didAuthor: false, + autoMergeAllowed: true, + }, + "github.example.com", + ).uploadAttachment, + ).toBe(false); + expect( + gitHubViewerPermissions( + { + canWrite: true, + canDeleteBranch: true, + canTriage: true, + canUpdate: true, + didAuthor: false, + autoMergeAllowed: true, + }, + "acme.ghe.com", + ).uploadAttachment, + ).toBe(true); + }); + it("leaves a passer-by on a repository they can only read nothing but the review", () => { expect( gitHubViewerPermissions({ @@ -196,6 +226,7 @@ describe("gitHubViewerPermissions", () => { actions: [], comment: true, resolve: false, + uploadAttachment: false, verdicts: ["comment", "approve", "request-changes"], requestReviewers: false, labels: false, @@ -228,6 +259,7 @@ describe("gitHubViewerPermissions", () => { actions: ["ready", "draft", "close", "reopen"], comment: true, resolve: true, + uploadAttachment: false, verdicts: ["comment"], requestReviewers: false, labels: false, @@ -249,6 +281,7 @@ describe("gitHubViewerPermissions", () => { actions: ["ready", "draft", "close", "reopen"], comment: true, resolve: false, + uploadAttachment: false, verdicts: ["comment", "approve", "request-changes"], requestReviewers: false, labels: false, diff --git a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts index 154cbdb4f3fd7..1bd7fe5c27102 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts @@ -31,10 +31,12 @@ import type { GitHubWorkflowRunApproval, } from "./gitHubPullRequestJson.ts"; import { definition } from "../shared/definition.ts"; +import { isGitHubUploadHost } from "./gitHubAttachmentUpload.ts"; const CAPABILITIES: PullRequestCapabilities = { diff: true, comment: true, + attachments: true, actions: [...definition.changeRequestActions], mergeMethods: ["merge", "squash", "rebase"], deleteBranch: true, @@ -76,9 +78,11 @@ const UNAVAILABLE_REQUIREMENT = { */ export function gitHubViewerPermissions( access: GitHubViewerAccess & Pick, + host = "github.com", ): PullRequestViewerPermissions { return { ...(access.canWrite ? { stackRebase: true } : {}), + uploadAttachment: access.canWrite && isGitHubUploadHost(host), actions: [ ...(access.canDeleteBranch === true ? (["delete-branch"] as const) : []), // Keep disabling available if the repository has since turned auto-merge off. @@ -521,10 +525,13 @@ export const make = Effect.gen(function* () { ], mergeCapabilities: pullRequest.viewerAccess.mergeCapabilities, viewerPermissions: { - ...gitHubViewerPermissions({ - ...pullRequest.viewerAccess, - canUpdateBranch: pullRequest.comparison?.viewerCanUpdate === true, - }), + ...gitHubViewerPermissions( + { + ...pullRequest.viewerAccess, + canUpdateBranch: pullRequest.comparison?.viewerCanUpdate === true, + }, + input.host, + ), maintainerEdits: pullRequest.canEditMaintainerEdits, }, baseComparison: @@ -647,18 +654,21 @@ export const make = Effect.gen(function* () { getViewerPermissions: (input) => { const lightAccess = cli .getViewerAccess({ ...input, allowReserve: true }) - .pipe(Effect.map((access) => gitHubViewerPermissions(access))); + .pipe(Effect.map((access) => gitHubViewerPermissions(access, input.host))); if (input.includeUpdateBranch === false) { return lightAccess.pipe(Effect.mapError(fail("getViewerPermissions"))); } return cli.getPullRequestDetail(input).pipe( Effect.provideService(SourceControlRateLimit.Interactive, true), Effect.map((pullRequest) => - gitHubViewerPermissions({ - ...pullRequest.viewerAccess, - canUpdateBranch: - pullRequest.state === "open" && pullRequest.comparison?.viewerCanUpdate === true, - }), + gitHubViewerPermissions( + { + ...pullRequest.viewerAccess, + canUpdateBranch: + pullRequest.state === "open" && pullRequest.comparison?.viewerCanUpdate === true, + }, + input.host, + ), ), Effect.catchIf( (error) => diff --git a/packages/source-control-github/src/server/driver.ts b/packages/source-control-github/src/server/driver.ts index 05844f6608fe6..dfe6f41146483 100644 --- a/packages/source-control-github/src/server/driver.ts +++ b/packages/source-control-github/src/server/driver.ts @@ -12,6 +12,7 @@ import { definition } from "../shared/definition.ts"; import * as GitHubAppAccess from "./GitHubAppAccess.ts"; import * as GitHubAppSignIn from "./GitHubAppSignIn.ts"; +import * as GitHubAttachmentUpload from "./gitHubAttachmentUpload.ts"; import * as GitHubMediaFetch from "./gitHubMediaFetch.ts"; import * as GitHubPullRequestApi from "./GitHubPullRequestApi.ts"; import * as GitHubPullRequestProvider from "./GitHubPullRequestProvider.ts"; @@ -104,7 +105,12 @@ const makeInstance = Effect.gen(function* () { Effect.all({ sourceControl: GitHubSourceControlProvider.make, discovery: GitHubSourceControlProvider.makeDiscovery, - pullRequests: GitHubPullRequestProvider.make, + pullRequests: Effect.all({ + base: GitHubPullRequestProvider.make, + uploadAttachment: GitHubAttachmentUpload.make.pipe( + Effect.provideService(HttpClient.HttpClient, mediaHttpClient), + ), + }).pipe(Effect.map(({ base, uploadAttachment }) => ({ ...base, uploadAttachment }))), issues: GitHubIssueTracker.make, fetchMedia: GitHubMediaFetch.make.pipe( Effect.provideService(HttpClient.HttpClient, mediaHttpClient), diff --git a/packages/source-control-github/src/server/gitHubAttachmentUpload.test.ts b/packages/source-control-github/src/server/gitHubAttachmentUpload.test.ts new file mode 100644 index 0000000000000..9d5d7fb0d89f0 --- /dev/null +++ b/packages/source-control-github/src/server/gitHubAttachmentUpload.test.ts @@ -0,0 +1,248 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Redacted from "effect/Redacted"; +import * as Stream from "effect/Stream"; +import { HttpBody, HttpClient, HttpClientResponse } from "effect/http"; + +import * as GitHubCredentials from "./GitHubCredentials.ts"; +import * as GitHubAttachmentUpload from "./gitHubAttachmentUpload.ts"; +import * as GitHubRest from "./GitHubRest.ts"; + +function collectBodyBytes(body: HttpBody.HttpBody): Effect.Effect { + if (body._tag === "Uint8Array") return Effect.succeed(body.body); + if (body._tag === "Stream") { + return Stream.runFold( + Stream.orDie(body.stream), + () => [] as number[], + (acc, chunk) => { + for (const byte of chunk) acc.push(byte); + return acc; + }, + ).pipe(Effect.map((bytes) => new Uint8Array(bytes))); + } + return Effect.succeed(new Uint8Array()); +} + +function makeUploadFixture(options: { + readonly fileBytes?: Uint8Array; + readonly repoPermissions?: { + readonly admin?: boolean; + readonly maintain?: boolean; + readonly push?: boolean; + }; + readonly uploadResponse?: (request: { + readonly url: string; + readonly authorization: string | undefined; + readonly contentType: string | undefined; + readonly contentLength: number | undefined; + readonly bytes: Uint8Array; + }) => Response; +}) { + const bytes = options.fileBytes ?? new TextEncoder().encode("png-bytes"); + const uploadCalls: Array<{ + readonly url: string; + readonly authorization: string | undefined; + readonly contentType: string | undefined; + readonly contentLength: number | undefined; + readonly bytes: Uint8Array; + }> = []; + const restCalls: Array = []; + const invalidated: Array = []; + + const fileSystemLayer = FileSystem.layerNoop({ + stat: () => + Effect.succeed({ + type: "File", + size: BigInt(bytes.byteLength) as FileSystem.File.Info["size"], + } as FileSystem.File.Info), + stream: () => Stream.make(bytes), + readFile: () => Effect.succeed(bytes), + }); + + const layer = Layer.mergeAll( + fileSystemLayer, + Layer.mock(GitHubCredentials.GitHubCredentials)({ + get: (host) => + Effect.succeed({ + host, + token: Redacted.make("gho_secret"), + fingerprint: "fp", + source: "gh" as const, + }), + invalidate: (host) => Effect.sync(() => void invalidated.push(host)), + }), + Layer.mock(GitHubRest.GitHubRest)({ + rest: (input) => + Effect.sync(() => { + restCalls.push(`${input.host}:${input.path}`); + return { + status: 200, + headers: {}, + body: JSON.stringify({ + id: 4242, + ...(options.repoPermissions === undefined + ? { permissions: { push: true } } + : { permissions: options.repoPermissions }), + }), + truncated: false, + invalidUtf8: false, + }; + }), + }), + Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.gen(function* () { + const sentBytes = yield* collectBodyBytes(request.body); + // Mirrors fetch: a declared stream length is dropped and the body goes out chunked. + const contentLength = + request.body._tag === "Uint8Array" ? request.body.body.byteLength : undefined; + const contentType = + request.body._tag === "Stream" || request.body._tag === "Uint8Array" + ? request.body.contentType + : undefined; + const entry = { + url: request.url, + authorization: request.headers.authorization, + contentType, + contentLength, + bytes: sentBytes, + }; + uploadCalls.push(entry); + const response = options.uploadResponse + ? options.uploadResponse(entry) + : new Response( + JSON.stringify({ + url: "https://github.com/user-attachments/assets/1a1842fb-6383-492f-873c-57aa0033fa6c", + }), + { status: 201, headers: { "content-type": "application/json" } }, + ); + return HttpClientResponse.fromWeb(request, response); + }), + ), + ), + ); + + return { layer, uploadCalls, restCalls, invalidated, bytes }; +} + +describe("GitHubAttachmentUpload", () => { + it.effect("uploads images to uploads. and escapes markdown alt text", () => { + const fixture = makeUploadFixture({}); + return Effect.gen(function* () { + const upload = yield* GitHubAttachmentUpload.make; + const result = yield* upload({ + cwd: "/repo", + host: "github.com", + repository: "acme/web", + filePath: "/tmp/login.bug.png", + fileName: "login.bug.png", + alt: "Fix [banner](x)", + }); + + expect(result).toEqual({ + url: "https://github.com/user-attachments/assets/1a1842fb-6383-492f-873c-57aa0033fa6c", + markdown: + "![Fix \\[banner\\](x)](https://github.com/user-attachments/assets/1a1842fb-6383-492f-873c-57aa0033fa6c)", + }); + expect(fixture.restCalls).toEqual(["github.com:repos/acme/web"]); + expect(fixture.uploadCalls).toEqual([ + { + url: "https://uploads.github.com/user-attachments/assets?name=login.bug.png&content_type=image%2Fpng&repository_id=4242", + authorization: "Bearer gho_secret", + contentType: "application/octet-stream", + contentLength: fixture.bytes.byteLength, + bytes: fixture.bytes, + }, + ]); + }).pipe(Effect.provide(fixture.layer)); + }); + + it.effect("returns bare URLs for videos and supports data-residency ghe.com tenants", () => { + const fixture = makeUploadFixture({ + uploadResponse: () => + new Response( + JSON.stringify({ + url: "https://acme.ghe.com/user-attachments/assets/clip-uuid", + }), + { status: 201, headers: { "content-type": "application/json" } }, + ), + }); + return Effect.gen(function* () { + const upload = yield* GitHubAttachmentUpload.make; + const result = yield* upload({ + cwd: "/repo", + host: "acme.ghe.com", + repository: "acme/web", + filePath: "/tmp/repro", + fileName: "repro", + mimeType: "video/mp4", + }); + + expect(result).toEqual({ + url: "https://acme.ghe.com/user-attachments/assets/clip-uuid", + markdown: "https://acme.ghe.com/user-attachments/assets/clip-uuid", + }); + expect(fixture.uploadCalls[0]?.url).toBe( + "https://uploads.acme.ghe.com/user-attachments/assets?name=repro.mp4&content_type=video%2Fmp4&repository_id=4242", + ); + }).pipe(Effect.provide(fixture.layer)); + }); + + it.effect("refuses GitHub Enterprise Server and read-only viewers before uploading bytes", () => { + const fixture = makeUploadFixture({ repoPermissions: { push: false } }); + return Effect.gen(function* () { + const upload = yield* GitHubAttachmentUpload.make; + const ghesError = yield* upload({ + cwd: "/repo", + host: "github.example.com", + repository: "acme/web", + filePath: "/tmp/shot.png", + fileName: "shot.png", + }).pipe(Effect.flip); + expect(ghesError.detail).toContain("GitHub Enterprise Server"); + expect(fixture.restCalls).toEqual([]); + + const forbiddenError = yield* upload({ + cwd: "/repo", + host: "github.com", + repository: "acme/web", + filePath: "/tmp/shot.png", + fileName: "shot.png", + }).pipe(Effect.flip); + expect(forbiddenError.reason).toBe("forbidden"); + expect(fixture.uploadCalls).toEqual([]); + }).pipe(Effect.provide(fixture.layer)); + }); + + it.effect("maps 404 upload refusals to forbidden and invalidates credentials on 401", () => { + let status = 404; + const fixture = makeUploadFixture({ + uploadResponse: () => new Response("Not Found", { status }), + }); + return Effect.gen(function* () { + const upload = yield* GitHubAttachmentUpload.make; + const notFoundAsForbidden = yield* upload({ + cwd: "/repo", + host: "github.com", + repository: "acme/web", + filePath: "/tmp/shot.png", + fileName: "shot.png", + }).pipe(Effect.flip); + expect(notFoundAsForbidden.reason).toBe("forbidden"); + + status = 401; + const unauth = yield* upload({ + cwd: "/repo", + host: "github.com", + repository: "acme/web", + filePath: "/tmp/shot.png", + fileName: "shot.png", + }).pipe(Effect.flip); + expect(unauth.reason).toBe("unauthenticated"); + expect(fixture.invalidated).toEqual(["github.com"]); + }).pipe(Effect.provide(fixture.layer)); + }); +}); diff --git a/packages/source-control-github/src/server/gitHubAttachmentUpload.ts b/packages/source-control-github/src/server/gitHubAttachmentUpload.ts new file mode 100644 index 0000000000000..ab8aae3137e87 --- /dev/null +++ b/packages/source-control-github/src/server/gitHubAttachmentUpload.ts @@ -0,0 +1,417 @@ +import { SourceControlProviderKind, TrimmedNonEmptyString } from "@t3tools/contracts"; +import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText"; +import { + PullRequestProviderError, + type PullRequestProviderApi, +} from "@t3tools/source-control-core/server/PullRequestProvider"; +import { normalizeHost } from "@t3tools/source-control-core/server/pullRequestUtils"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import { + FetchHttpClient, + HttpBody, + HttpClient, + HttpClientRequest, + type HttpClientResponse, +} from "effect/http"; +import * as Option from "effect/Option"; +import * as Redacted from "effect/Redacted"; +import * as Result from "effect/Result"; +import * as Schema from "effect/Schema"; + +import * as GitHubCredentials from "./GitHubCredentials.ts"; +import * as GitHubRest from "./GitHubRest.ts"; + +const KIND = SourceControlProviderKind.make("github"); +const MAX_IMAGE_BYTES = 10 * 1024 * 1024; +const MAX_VIDEO_BYTES = 100 * 1024 * 1024; +const MAX_RESPONSE_BYTES = 64 * 1024; +const MAX_REDIRECTS = 3; +const MANUAL_REDIRECT: RequestInit = { redirect: "manual" }; + +const CONTENT_TYPES: ReadonlyArray<{ readonly ext: string; readonly contentType: string }> = [ + { ext: ".png", contentType: "image/png" }, + { ext: ".jpg", contentType: "image/jpeg" }, + { ext: ".jpeg", contentType: "image/jpeg" }, + { ext: ".gif", contentType: "image/gif" }, + { ext: ".webp", contentType: "image/webp" }, + { ext: ".svg", contentType: "image/svg+xml" }, + { ext: ".mp4", contentType: "video/mp4" }, + { ext: ".mov", contentType: "video/quicktime" }, + { ext: ".webm", contentType: "video/webm" }, +]; + +const SUPPORTED_EXTENSIONS = CONTENT_TYPES.map((entry) => entry.ext.slice(1)).join(", "); + +const decodeRepositoryJson = Schema.decodeUnknownResult( + Schema.fromJsonString( + Schema.Struct({ + id: Schema.Int, + permissions: Schema.optional( + Schema.Struct({ + admin: Schema.optional(Schema.Boolean), + maintain: Schema.optional(Schema.Boolean), + push: Schema.optional(Schema.Boolean), + }), + ), + }), + ), +); + +const decodeUploadedAssetJson = Schema.decodeUnknownResult( + Schema.fromJsonString( + Schema.Struct({ + url: TrimmedNonEmptyString, + }), + ), +); + +const decodeErrorMessageJson = Schema.decodeUnknownOption( + Schema.fromJsonString( + Schema.Struct({ + message: Schema.optional(Schema.String), + }), + ), +); + +export function isGitHubUploadHost(host: string): boolean { + const normalized = normalizeHost(host); + return normalized === "github.com" || normalized.endsWith(".ghe.com"); +} + +function sanitizeFileName(raw: string): string { + const leaf = raw.replaceAll("\\", "/").split("/").pop() ?? ""; + const cleaned = leaf.replace(/[\p{Cc}/\\]/gu, "").trim(); + return cleaned.length > 0 ? cleaned : "attachment"; +} + +function extensionOf(fileName: string): string { + const dot = fileName.lastIndexOf("."); + return dot > 0 ? fileName.slice(dot).toLowerCase() : ""; +} + +function resolveGitHubContentType( + fileName: string, + mimeType: string | undefined, +): { readonly uploadName: string; readonly contentType: string; readonly isVideo: boolean } | null { + const baseName = sanitizeFileName(fileName); + const ext = extensionOf(baseName); + const byExt = CONTENT_TYPES.find((entry) => entry.ext === ext); + if (byExt !== undefined) { + return { + uploadName: baseName, + contentType: byExt.contentType, + isVideo: byExt.contentType.startsWith("video/"), + }; + } + const normalizedMime = mimeType?.split(";", 1)[0]?.trim().toLowerCase() ?? ""; + const byMime = CONTENT_TYPES.find((entry) => entry.contentType === normalizedMime); + if (byMime !== undefined) { + const stem = ext.length > 0 ? baseName.slice(0, -ext.length) : baseName; + return { + uploadName: `${stem}${byMime.ext}`, + contentType: byMime.contentType, + isVideo: byMime.contentType.startsWith("video/"), + }; + } + return null; +} + +function escapeMarkdownAlt(value: string): string { + return value + .replaceAll("\\", "\\\\") + .replaceAll("[", "\\[") + .replaceAll("]", "\\]") + .replace(/[\r\n]+/gu, " ") + .trim(); +} + +function defaultImageAlt(uploadName: string): string { + const ext = extensionOf(uploadName); + const stem = ext.length > 0 ? uploadName.slice(0, -ext.length) : uploadName; + const formatted = stem.replaceAll(".", " ").trim(); + return formatted.length > 0 ? formatted : "image"; +} + +function formatBytesLimit(bytes: number): string { + return `${Math.round(bytes / (1024 * 1024))} MB`; +} + +function parseRepositorySegments( + repository: string, +): { readonly owner: string; readonly name: string } | null { + const segments = repository.trim().split("/"); + if ( + segments.length !== 2 || + segments.some((segment) => segment === "" || segment === "." || segment === "..") + ) { + return null; + } + return { owner: segments[0]!, name: segments[1]! }; +} + +function failure( + reason: PullRequestProviderError["reason"], + detail: string, + cause?: unknown, +): PullRequestProviderError { + return new PullRequestProviderError({ + provider: KIND, + operation: "uploadAttachment", + reason, + detail, + ...(cause === undefined ? {} : { cause }), + }); +} + +function mapCredentialOrRestError(error: unknown): PullRequestProviderError { + if (typeof error === "object" && error !== null && "_tag" in error) { + switch (error._tag) { + case "GitHubCliMissingError": + return failure("missing-tool", error instanceof Error ? error.message : "Missing gh CLI."); + case "GitHubNotSignedInError": + case "GitHubHostDisabledError": + case "SettingsSecretUnresolvedError": + case "GitHubApiAuthenticationError": + return failure( + "unauthenticated", + error instanceof Error ? error.message : "GitHub authentication failed.", + error, + ); + case "GitHubApiRateLimitError": + case "SourceControlRateLimitPausedError": + return failure("rate-limited", "GitHub API rate limit exceeded.", error); + case "GitHubApiNotFoundError": + return failure( + "not-found", + "Repository was not found or cannot be accessed with the active GitHub credential.", + error, + ); + case "GitHubApiResponseError": + if ("status" in error && error.status === 403) { + return failure( + "forbidden", + "Attaching files requires write access to the repository.", + error, + ); + } + break; + } + } + return failure( + "failed", + error instanceof Error ? error.message : "Failed to upload attachment to GitHub.", + error, + ); +} + +export const make = Effect.gen(function* () { + const credentials = yield* GitHubCredentials.GitHubCredentials; + const rest = yield* GitHubRest.GitHubRest; + const httpClient = yield* HttpClient.HttpClient; + const fileSystem = yield* FileSystem.FileSystem; + + const upload: NonNullable = Effect.fn( + "GitHubAttachmentUpload.uploadAttachment", + )(function* (input) { + const host = normalizeHost(input.host); + // Check the host first: GitHub Enterprise Server has no user-attachments upload endpoint. + if (!isGitHubUploadHost(host)) { + return yield* failure( + "failed", + "Attaching files is not supported on GitHub Enterprise Server.", + ); + } + + const repoSegments = parseRepositorySegments(input.repository); + if (repoSegments === null) { + return yield* failure("failed", "Repositories on GitHub must be named owner/name."); + } + + const resolvedType = resolveGitHubContentType(input.fileName, input.mimeType); + if (resolvedType === null) { + return yield* failure( + "failed", + `${sanitizeFileName(input.fileName)} is not a supported file type (supported: ${SUPPORTED_EXTENSIONS}).`, + ); + } + + const stat = yield* fileSystem + .stat(input.filePath) + .pipe( + Effect.mapError((cause) => + failure("failed", `Could not read ${sanitizeFileName(input.fileName)}.`, cause), + ), + ); + if (stat.type !== "File") { + return yield* failure("failed", `${sanitizeFileName(input.fileName)} is not a regular file.`); + } + const sizeBytes = Number(stat.size); + if (!Number.isSafeInteger(sizeBytes) || sizeBytes <= 0) { + return yield* failure("failed", `${sanitizeFileName(input.fileName)} is empty.`); + } + const maxBytes = resolvedType.isVideo ? MAX_VIDEO_BYTES : MAX_IMAGE_BYTES; + if (sizeBytes > maxBytes) { + return yield* failure( + "failed", + `${sanitizeFileName(input.fileName)}: ${resolvedType.isVideo ? "videos" : "images"} must be at most ${formatBytesLimit(maxBytes)}.`, + ); + } + + const repoResponse = yield* rest + .rest({ + host, + operation: "uploadAttachment.repository", + path: `repos/${encodeURIComponent(repoSegments.owner)}/${encodeURIComponent(repoSegments.name)}`, + allowReserve: true, + }) + .pipe(Effect.mapError(mapCredentialOrRestError)); + const decodedRepo = decodeRepositoryJson(repoResponse.body); + if (Result.isFailure(decodedRepo) || decodedRepo.success.id <= 0) { + return yield* failure("failed", "Could not determine the target GitHub repository ID."); + } + const permissions = decodedRepo.success.permissions; + // GitHub App installation tokens may omit `permissions`; otherwise refuse before uploading bytes. + if ( + permissions !== undefined && + permissions.admin !== true && + permissions.maintain !== true && + permissions.push !== true + ) { + return yield* failure( + "forbidden", + "Attaching files requires write access to the repository.", + ); + } + + const credential = yield* credentials.get(host).pipe(Effect.mapError(mapCredentialOrRestError)); + // uploads.github.com rejects chunked bodies ("Bad Content-Length"), and fetch drops the + // declared length of a stream body, so send the size-capped file as bytes. + const fileBytes = yield* fileSystem + .readFile(input.filePath) + .pipe( + Effect.mapError((cause) => + failure("failed", `Could not read ${sanitizeFileName(input.fileName)}.`, cause), + ), + ); + const uploadHost = `uploads.${host}`; + const initialUrl = new URL(`https://${uploadHost}/user-attachments/assets`); + initialUrl.searchParams.set("name", resolvedType.uploadName); + initialUrl.searchParams.set("content_type", resolvedType.contentType); + initialUrl.searchParams.set("repository_id", String(decodedRepo.success.id)); + + const executeUpload = Effect.gen(function* () { + let targetUrl = initialUrl.toString(); + let method: "POST" | "GET" = "POST"; + for (let hop = 0; ; hop += 1) { + const parsedTarget = URL.parse(targetUrl); + if (parsedTarget === null || parsedTarget.protocol !== "https:") { + return yield* failure("failed", "GitHub returned an invalid upload redirect."); + } + const sameUploadHost = parsedTarget.hostname.toLowerCase() === uploadHost; + const baseRequest = + method === "POST" + ? HttpClientRequest.post(targetUrl).pipe( + HttpClientRequest.setBody( + HttpBody.uint8Array(fileBytes, "application/octet-stream"), + ), + ) + : HttpClientRequest.get(targetUrl); + const request = baseRequest.pipe( + HttpClientRequest.setHeaders({ + accept: "application/vnd.github+json", + ...(sameUploadHost + ? { authorization: `Bearer ${Redacted.value(credential.token)}` } + : {}), + }), + ); + const response: HttpClientResponse.HttpClientResponse = yield* httpClient + .execute(request) + .pipe( + Effect.provideService(FetchHttpClient.RequestInit, MANUAL_REDIRECT), + Effect.provideService(HttpClient.TracerDisabledWhen, () => true), + Effect.mapError((cause) => + failure("failed", "Failed to send attachment bytes to GitHub.", cause), + ), + ); + const location = response.headers.location; + if (response.status >= 300 && response.status < 400) { + if (!location || hop >= MAX_REDIRECTS) { + return yield* failure( + "failed", + "GitHub redirected the attachment upload too many times.", + ); + } + const next = URL.parse(location, targetUrl); + if (next === null || next.protocol !== "https:" || next.username || next.password) { + return yield* failure("failed", "GitHub returned an invalid upload redirect."); + } + if (response.status === 301 || response.status === 302 || response.status === 303) { + method = "GET"; + } + targetUrl = next.toString(); + continue; + } + const collected = yield* collectUint8StreamText({ + stream: response.stream, + maxBytes: MAX_RESPONSE_BYTES, + }).pipe(Effect.orElseSucceed(() => ({ text: "", truncated: false, invalidUtf8: false }))); + return { status: response.status, body: collected.text }; + } + }); + + const uploadResult = yield* Effect.scoped(executeUpload); + if (uploadResult.status === 401) { + yield* credentials.invalidate(host); + return yield* failure( + "unauthenticated", + `GitHub rejected the credential for ${host}. Run \`gh auth login\` or update your token.`, + ); + } + if (uploadResult.status === 403 || uploadResult.status === 404) { + // GitHub's upload endpoint returns 404 when the token lacks write access to the repository. + return yield* failure( + "forbidden", + "Attaching files requires write access to the repository.", + ); + } + if (uploadResult.status === 429) { + return yield* failure("rate-limited", "GitHub attachment upload rate limit exceeded."); + } + if (uploadResult.status < 200 || uploadResult.status >= 300) { + const apiMessage = Option.getOrUndefined( + decodeErrorMessageJson(uploadResult.body), + )?.message?.trim(); + return yield* failure( + "failed", + apiMessage && apiMessage.length > 0 + ? `Could not upload ${resolvedType.uploadName}: ${apiMessage}` + : `Could not upload ${resolvedType.uploadName} (HTTP ${uploadResult.status}).`, + ); + } + + const decodedAsset = decodeUploadedAssetJson(uploadResult.body); + if (Result.isFailure(decodedAsset)) { + return yield* failure("failed", "GitHub returned no asset URL for the uploaded file."); + } + const parsedAssetUrl = URL.parse(decodedAsset.success.url); + if (parsedAssetUrl === null || parsedAssetUrl.protocol !== "https:") { + return yield* failure("failed", "GitHub returned an invalid asset URL."); + } + + const assetUrl = parsedAssetUrl.toString(); + if (resolvedType.isVideo) { + return { url: assetUrl, markdown: assetUrl }; + } + const rawAlt = input.alt?.trim(); + const escapedAlt = escapeMarkdownAlt( + rawAlt && rawAlt.length > 0 ? rawAlt : defaultImageAlt(resolvedType.uploadName), + ); + return { + url: assetUrl, + markdown: `![${escapedAlt || "image"}](${assetUrl})`, + }; + }); + + return upload; +}); diff --git a/packages/source-control-gitlab/src/server/GitLabCredentials.ts b/packages/source-control-gitlab/src/server/GitLabCredentials.ts index 428ae66c439ce..01297d980a3e7 100644 --- a/packages/source-control-gitlab/src/server/GitLabCredentials.ts +++ b/packages/source-control-gitlab/src/server/GitLabCredentials.ts @@ -29,12 +29,27 @@ const STORED_ONLY_ENV = { GLAB_ENABLE_CI_AUTOLOGIN: "false", }; +export interface GitLabUploadAuth { + readonly apiOrigin: string; + readonly token: Redacted.Redacted; +} + +function normalizeEnvHost(raw: string | undefined): string { + const trimmed = raw?.trim() ?? ""; + if (trimmed === "") return "gitlab.com"; + if (URL.canParse(trimmed)) return new URL(trimmed).host.toLowerCase(); + if (URL.canParse(`https://${trimmed}`)) return new URL(`https://${trimmed}`).host.toLowerCase(); + return trimmed.toLowerCase(); +} + /** The token `glab` stores for a GitLab host, used to read what that host serves to the user. */ export class GitLabCredentials extends Context.Service< GitLabCredentials, { /** None when `glab` holds no login for the host. */ readonly get: (host: string) => Effect.Effect>>; + /** Token and API origin for an explicit project action, allowing matching environment tokens. */ + readonly getUploadAuth: (host: string) => Effect.Effect>; /** Drops the held token after GitLab refused it, so the next read asks `glab` again. */ readonly invalidate: (host: string) => Effect.Effect; } @@ -44,6 +59,7 @@ export class GitLabCredentials extends Context.Service< export const make = Effect.gen(function* () { const { process } = yield* SourceControlHost.SourceControlHost; const workingDirectory = yield* HostProcess.WorkingDirectory; + const environment = yield* HostProcess.Environment; const run = (args: ReadonlyArray, timeoutMs = 10_000) => process.run({ @@ -101,8 +117,57 @@ export const make = Effect.gen(function* () { }, ); + const resolveApiOrigin = Effect.fn("GitLabCredentials.resolveApiOrigin")(function* ( + loginHost: string, + defaultHost: string, + ) { + const configuredHost = (yield* glab(["config", "get", "api_host", "--host", loginHost])) + .trim() + .toLowerCase(); + const configuredProtocol = (yield* glab(["config", "get", "api_protocol", "--host", loginHost])) + .trim() + .toLowerCase(); + const protocol = configuredProtocol === "http" ? "http" : "https"; + const apiHost = configuredHost || defaultHost; + return `${protocol}://${apiHost}`; + }); + + const lookupUploadAuth = Effect.fn("GitLabCredentials.lookupUploadAuth")(function* ( + rawHost: string, + ) { + const host = rawHost.trim().toLowerCase(); + const direct = yield* login(host); + if (Option.isSome(direct)) { + return Option.some({ + apiOrigin: yield* resolveApiOrigin(host, host), + token: direct.value, + }); + } + const alias = yield* aliasFor(host); + if (alias !== undefined && alias !== host) { + const aliased = yield* login(alias); + if (Option.isSome(aliased)) { + return Option.some({ + apiOrigin: yield* resolveApiOrigin(alias, host), + token: aliased.value, + }); + } + } + const envToken = (environment.GITLAB_TOKEN ?? environment.GITLAB_ACCESS_TOKEN)?.trim() ?? ""; + if (envToken !== "" && normalizeEnvHost(environment.GITLAB_HOST) === host) { + return Option.some({ + apiOrigin: `https://${host}`, + token: Redacted.make(envToken), + }); + } + return Option.none(); + }); + return GitLabCredentials.of({ get: Effect.fn("GitLabCredentials.get")((host) => Cache.get(cache, host.trim().toLowerCase())), + getUploadAuth: Effect.fn("GitLabCredentials.getUploadAuth")((host) => + lookupUploadAuth(host).pipe(Effect.orElseSucceed(() => Option.none())), + ), invalidate: Effect.fn("GitLabCredentials.invalidate")((host) => Cache.invalidate(cache, host.trim().toLowerCase()), ), diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts index 81ecb50314bab..57a30563bc91a 100644 --- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts +++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts @@ -26,6 +26,7 @@ import { definition } from "../shared/definition.ts"; const CAPABILITIES: PullRequestCapabilities = { diff: true, comment: true, + attachments: true, actions: [...definition.changeRequestActions], mergeMethods: ["merge", "squash", "rebase"], deleteBranch: true, diff --git a/packages/source-control-gitlab/src/server/driver.ts b/packages/source-control-gitlab/src/server/driver.ts index 8a82e5f7482a3..f7ed3b4c415b2 100644 --- a/packages/source-control-gitlab/src/server/driver.ts +++ b/packages/source-control-gitlab/src/server/driver.ts @@ -8,6 +8,7 @@ import * as Layer from "effect/Layer"; import { definition } from "../shared/definition.ts"; import * as GitLabCli from "./GitLabCli.ts"; +import * as GitLabAttachmentUpload from "./gitLabAttachmentUpload.ts"; import * as GitLabCredentials from "./GitLabCredentials.ts"; import * as GitLabMediaFetch from "./gitLabMediaFetch.ts"; import * as GitLabPullRequestCli from "./GitLabPullRequestCli.ts"; @@ -23,7 +24,10 @@ const services = Layer.merge( const makeInstance = Effect.all({ sourceControl: GitLabSourceControlProvider.make, discovery: Effect.succeed(GitLabSourceControlProvider.discovery), - pullRequests: GitLabPullRequestProvider.make, + pullRequests: Effect.all({ + base: GitLabPullRequestProvider.make, + uploadAttachment: GitLabAttachmentUpload.make, + }).pipe(Effect.map(({ base, uploadAttachment }) => ({ ...base, uploadAttachment }))), issues: GitLabIssueTracker.make, fetchMedia: GitLabMediaFetch.make, }); diff --git a/packages/source-control-gitlab/src/server/gitLabAttachmentUpload.test.ts b/packages/source-control-gitlab/src/server/gitLabAttachmentUpload.test.ts new file mode 100644 index 0000000000000..882fdbd01f28a --- /dev/null +++ b/packages/source-control-gitlab/src/server/gitLabAttachmentUpload.test.ts @@ -0,0 +1,192 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Redacted from "effect/Redacted"; +import * as Stream from "effect/Stream"; +import { HttpBody, HttpClient, HttpClientResponse } from "effect/http"; + +import * as GitLabCredentials from "./GitLabCredentials.ts"; +import * as GitLabAttachmentUpload from "./gitLabAttachmentUpload.ts"; + +function collectBodyText(body: HttpBody.HttpBody): Effect.Effect { + if (body._tag === "Stream") { + return Stream.runFold( + Stream.orDie(body.stream), + () => [] as number[], + (acc, chunk) => { + for (const byte of chunk) acc.push(byte); + return acc; + }, + ).pipe(Effect.map((bytes) => new TextDecoder().decode(new Uint8Array(bytes)))); + } + return Effect.succeed(""); +} + +function makeFixture(options: { + readonly auth?: { readonly apiOrigin: string; readonly token: string } | null; + readonly respond?: (request: { + readonly url: string; + readonly authorization: string | undefined; + readonly contentType: string | undefined; + readonly contentLength: number | undefined; + readonly bodyText: string; + }) => Response; +}) { + const fileBytes = new TextEncoder().encode("gitlab-image-bytes"); + const requests: Array<{ + readonly url: string; + readonly authorization: string | undefined; + readonly contentType: string | undefined; + readonly contentLength: number | undefined; + readonly bodyText: string; + }> = []; + const invalidated: Array = []; + + const layer = Layer.mergeAll( + FileSystem.layerNoop({ + stat: () => + Effect.succeed({ + type: "File", + size: BigInt(fileBytes.byteLength) as FileSystem.File.Info["size"], + } as FileSystem.File.Info), + stream: () => Stream.make(fileBytes), + }), + Layer.mock(GitLabCredentials.GitLabCredentials)({ + getUploadAuth: () => + Effect.succeed( + options.auth === null + ? Option.none() + : Option.some({ + apiOrigin: options.auth?.apiOrigin ?? "https://gitlab.example.com", + token: Redacted.make(options.auth?.token ?? "glpat-secret"), + }), + ), + invalidate: (host) => Effect.sync(() => void invalidated.push(host)), + }), + Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.gen(function* () { + const bodyText = yield* collectBodyText(request.body); + const entry = { + url: request.url, + authorization: request.headers.authorization, + contentType: request.body._tag === "Stream" ? request.body.contentType : undefined, + contentLength: request.body._tag === "Stream" ? request.body.contentLength : undefined, + bodyText, + }; + requests.push(entry); + const response = options.respond + ? options.respond(entry) + : new Response( + JSON.stringify({ + alt: "shot", + url: "/uploads/66dbcd21ec5d24ed6ea225176098d52b/shot.png", + full_path: "/group/sub/app/uploads/66dbcd21ec5d24ed6ea225176098d52b/shot.png", + markdown: "![shot](/uploads/66dbcd21ec5d24ed6ea225176098d52b/shot.png)", + }), + { status: 201, headers: { "content-type": "application/json" } }, + ); + return HttpClientResponse.fromWeb(request, response); + }), + ), + ), + ); + + return { layer, requests, invalidated }; +} + +describe("GitLabAttachmentUpload", () => { + it.effect( + "streams multipart uploads to the project API and preserves GitLab's relative markdown", + () => { + const fixture = makeFixture({}); + return Effect.gen(function* () { + const upload = yield* GitLabAttachmentUpload.make; + const result = yield* upload({ + cwd: "/repo", + host: "gitlab.example.com", + repository: "group/sub/app", + filePath: "/tmp/shot.png", + fileName: "shot.png", + mimeType: "image/png", + }); + + expect(result).toEqual({ + url: "https://gitlab.example.com/group/sub/app/uploads/66dbcd21ec5d24ed6ea225176098d52b/shot.png", + markdown: "![shot](/uploads/66dbcd21ec5d24ed6ea225176098d52b/shot.png)", + }); + expect(fixture.requests).toHaveLength(1); + expect(fixture.requests[0]?.url).toBe( + "https://gitlab.example.com/api/v4/projects/group%2Fsub%2Fapp/uploads", + ); + expect(fixture.requests[0]?.authorization).toBe("Bearer glpat-secret"); + expect(fixture.requests[0]?.contentType).toMatch(/^multipart\/form-data; boundary=/); + expect(fixture.requests[0]?.contentLength).toBe( + new TextEncoder().encode(fixture.requests[0]!.bodyText).byteLength, + ); + expect(fixture.requests[0]?.bodyText).toContain( + 'Content-Disposition: form-data; name="file"; filename="shot.png"', + ); + expect(fixture.requests[0]?.bodyText).toContain("gitlab-image-bytes"); + }).pipe(Effect.provide(fixture.layer)); + }, + ); + + it.effect("applies custom escaped alt text while keeping image vs link syntax", () => { + const fixture = makeFixture({ + respond: () => + new Response( + JSON.stringify({ + url: "/uploads/abc/spec.pdf", + markdown: "[spec.pdf](/uploads/abc/spec.pdf)", + }), + { status: 201 }, + ), + }); + return Effect.gen(function* () { + const upload = yield* GitLabAttachmentUpload.make; + const result = yield* upload({ + cwd: "/repo", + host: "gitlab.com", + repository: "acme/docs", + filePath: "/tmp/spec.pdf", + fileName: "spec.pdf", + alt: "Spec [v2]", + }); + + expect(result.markdown).toBe("[Spec \\[v2\\]](/uploads/abc/spec.pdf)"); + }).pipe(Effect.provide(fixture.layer)); + }); + + it.effect("invalidates credentials on 401 and classifies 403 as forbidden", () => { + let status = 401; + const fixture = makeFixture({ + respond: () => new Response(JSON.stringify({ message: "Unauthorized" }), { status }), + }); + return Effect.gen(function* () { + const upload = yield* GitLabAttachmentUpload.make; + const unauth = yield* upload({ + cwd: "/repo", + host: "gitlab.example.com", + repository: "group/app", + filePath: "/tmp/shot.png", + fileName: "shot.png", + }).pipe(Effect.flip); + expect(unauth.reason).toBe("unauthenticated"); + expect(fixture.invalidated).toEqual(["gitlab.example.com"]); + + status = 403; + const forbidden = yield* upload({ + cwd: "/repo", + host: "gitlab.example.com", + repository: "group/app", + filePath: "/tmp/shot.png", + fileName: "shot.png", + }).pipe(Effect.flip); + expect(forbidden.reason).toBe("forbidden"); + }).pipe(Effect.provide(fixture.layer)); + }); +}); diff --git a/packages/source-control-gitlab/src/server/gitLabAttachmentUpload.ts b/packages/source-control-gitlab/src/server/gitLabAttachmentUpload.ts new file mode 100644 index 0000000000000..35beb5f5f1ea6 --- /dev/null +++ b/packages/source-control-gitlab/src/server/gitLabAttachmentUpload.ts @@ -0,0 +1,312 @@ +import { + PULL_REQUEST_ATTACHMENT_MAX_BYTES, + SourceControlProviderKind, + TrimmedNonEmptyString, +} from "@t3tools/contracts"; +import { + PullRequestProviderError, + type PullRequestProviderApi, +} from "@t3tools/source-control-core/server/PullRequestProvider"; +import { normalizeHost } from "@t3tools/source-control-core/server/pullRequestUtils"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import { + FetchHttpClient, + HttpBody, + HttpClient, + HttpClientRequest, + type HttpClientResponse, +} from "effect/http"; +import * as Option from "effect/Option"; +import * as Redacted from "effect/Redacted"; +import * as Result from "effect/Result"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; + +import * as GitLabCredentials from "./GitLabCredentials.ts"; + +const KIND = SourceControlProviderKind.make("gitlab"); +function createMultipartBoundary(): string { + const bytes = new Uint8Array(16); + globalThis.crypto.getRandomValues(bytes); + return `----t3codeGitLabUpload${Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("")}`; +} + +const MAX_REDIRECTS = 3; +const MANUAL_REDIRECT: RequestInit = { redirect: "manual" }; + +const EXTENSION_BY_MIME: Readonly> = { + "image/png": ".png", + "image/jpeg": ".jpg", + "image/gif": ".gif", + "image/webp": ".webp", + "image/svg+xml": ".svg", + "video/mp4": ".mp4", + "video/quicktime": ".mov", + "video/webm": ".webm", + "application/pdf": ".pdf", +}; + +const MIME_BY_EXTENSION: Readonly> = { + ".png": "image/png", + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + ".gif": "image/gif", + ".webp": "image/webp", + ".svg": "image/svg+xml", + ".mp4": "video/mp4", + ".mov": "video/quicktime", + ".webm": "video/webm", + ".pdf": "application/pdf", + ".txt": "text/plain", + ".log": "text/plain", + ".json": "application/json", + ".zip": "application/zip", +}; + +const decodeGitLabUploadJson = Schema.decodeUnknownResult( + Schema.fromJsonString( + Schema.Struct({ + url: TrimmedNonEmptyString, + full_path: Schema.optional(Schema.NullOr(Schema.String)), + markdown: TrimmedNonEmptyString, + alt: Schema.optional(Schema.NullOr(Schema.String)), + }), + ), +); + +const decodeGitLabErrorJson = Schema.decodeUnknownOption( + Schema.fromJsonString( + Schema.Struct({ + message: Schema.optional(Schema.String), + error: Schema.optional(Schema.String), + }), + ), +); + +function sanitizeFileName(raw: string): string { + const leaf = raw.replaceAll("\\", "/").split("/").pop() ?? ""; + const cleaned = leaf.replace(/[\p{Cc}"/\\]/gu, "").trim(); + return cleaned.length > 0 ? cleaned : "attachment"; +} + +function extensionOf(fileName: string): string { + const dot = fileName.lastIndexOf("."); + return dot > 0 ? fileName.slice(dot).toLowerCase() : ""; +} + +function resolveUploadFileMeta( + fileName: string, + mimeType: string | undefined, +): { readonly uploadName: string; readonly contentType: string } { + const baseName = sanitizeFileName(fileName); + const ext = extensionOf(baseName); + const normalizedMime = mimeType?.split(";", 1)[0]?.trim().toLowerCase() ?? ""; + if (ext.length > 0) { + return { + uploadName: baseName, + contentType: + normalizedMime.length > 0 + ? normalizedMime + : (MIME_BY_EXTENSION[ext] ?? "application/octet-stream"), + }; + } + const inferredExt = EXTENSION_BY_MIME[normalizedMime] ?? ""; + return { + uploadName: `${baseName}${inferredExt}`, + contentType: normalizedMime.length > 0 ? normalizedMime : "application/octet-stream", + }; +} + +function escapeMarkdownAlt(value: string): string { + return value + .replaceAll("\\", "\\\\") + .replaceAll("[", "\\[") + .replaceAll("]", "\\]") + .replace(/[\r\n]+/gu, " ") + .trim(); +} + +function failure( + reason: PullRequestProviderError["reason"], + detail: string, + cause?: unknown, +): PullRequestProviderError { + return new PullRequestProviderError({ + provider: KIND, + operation: "uploadAttachment", + reason, + detail, + ...(cause === undefined ? {} : { cause }), + }); +} + +export const make = Effect.gen(function* () { + const credentials = yield* GitLabCredentials.GitLabCredentials; + const httpClient = yield* HttpClient.HttpClient; + const fileSystem = yield* FileSystem.FileSystem; + + const upload: NonNullable = Effect.fn( + "GitLabAttachmentUpload.uploadAttachment", + )(function* (input) { + const host = normalizeHost(input.host); + const repository = input.repository.trim().replace(/^\/+|\/+$/gu, ""); + if (repository.length === 0 || !repository.includes("/")) { + return yield* failure("failed", "GitLab projects must be named group/project."); + } + + const meta = resolveUploadFileMeta(input.fileName, input.mimeType); + const stat = yield* fileSystem + .stat(input.filePath) + .pipe( + Effect.mapError((cause) => failure("failed", `Could not read ${meta.uploadName}.`, cause)), + ); + if (stat.type !== "File") { + return yield* failure("failed", `${meta.uploadName} is not a regular file.`); + } + const sizeBytes = Number(stat.size); + if (!Number.isSafeInteger(sizeBytes) || sizeBytes <= 0) { + return yield* failure("failed", `${meta.uploadName} is empty.`); + } + if (sizeBytes > PULL_REQUEST_ATTACHMENT_MAX_BYTES) { + return yield* failure( + "failed", + `${meta.uploadName} exceeds the ${Math.round(PULL_REQUEST_ATTACHMENT_MAX_BYTES / (1024 * 1024))} MB upload limit.`, + ); + } + + const auth = yield* credentials.getUploadAuth(host); + if (Option.isNone(auth)) { + return yield* failure( + "unauthenticated", + "GitLab CLI is not authenticated for this host. Run `glab auth login` and retry.", + ); + } + + const { apiOrigin, token } = auth.value; + const boundary = createMultipartBoundary(); + const encoder = new TextEncoder(); + const prefixBytes = encoder.encode( + `--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${meta.uploadName}"\r\nContent-Type: ${meta.contentType}\r\n\r\n`, + ); + const suffixBytes = encoder.encode(`\r\n--${boundary}--\r\n`); + const totalLength = prefixBytes.byteLength + sizeBytes + suffixBytes.byteLength; + const contentTypeHeader = `multipart/form-data; boundary=${boundary}`; + + const makeMultipartStream = () => + Stream.concat( + Stream.concat(Stream.make(prefixBytes), fileSystem.stream(input.filePath)), + Stream.make(suffixBytes), + ); + + const initialUrl = `${apiOrigin}/api/v4/projects/${encodeURIComponent(repository)}/uploads`; + const executeUpload = Effect.gen(function* () { + let targetUrl = initialUrl; + for (let hop = 0; ; hop += 1) { + const parsedTarget = URL.parse(targetUrl); + if (parsedTarget === null || !["https:", "http:"].includes(parsedTarget.protocol)) { + return yield* failure("failed", "GitLab returned an invalid upload URL."); + } + const sameOrigin = parsedTarget.origin === apiOrigin; + const request = HttpClientRequest.post(targetUrl).pipe( + HttpClientRequest.setBody( + HttpBody.stream(makeMultipartStream(), contentTypeHeader, totalLength), + ), + HttpClientRequest.setHeaders({ + accept: "application/json", + ...(sameOrigin ? { authorization: `Bearer ${Redacted.value(token)}` } : {}), + }), + ); + const response: HttpClientResponse.HttpClientResponse = yield* httpClient + .execute(request) + .pipe( + Effect.provideService(FetchHttpClient.RequestInit, MANUAL_REDIRECT), + Effect.provideService(HttpClient.TracerDisabledWhen, () => true), + Effect.mapError((cause) => + failure("failed", "Failed to send attachment bytes to GitLab.", cause), + ), + ); + const location = response.headers.location; + if (response.status === 307 || response.status === 308) { + if (!location || hop >= MAX_REDIRECTS) { + return yield* failure( + "failed", + "GitLab redirected the attachment upload too many times.", + ); + } + const next = URL.parse(location, targetUrl); + if (next === null || next.protocol !== "https:" || next.username || next.password) { + return yield* failure("failed", "GitLab returned an invalid upload redirect."); + } + targetUrl = next.toString(); + continue; + } + const body = yield* response.text.pipe(Effect.orElseSucceed(() => "")); + return { status: response.status, body }; + } + }); + + const uploadResult = yield* Effect.scoped(executeUpload); + if (uploadResult.status === 401) { + yield* credentials.invalidate(host); + return yield* failure( + "unauthenticated", + "GitLab rejected the credential for this host. Run `glab auth login` and retry.", + ); + } + if (uploadResult.status === 403) { + return yield* failure( + "forbidden", + "Attaching files requires at least Reporter access to the GitLab project.", + ); + } + if (uploadResult.status === 404) { + return yield* failure( + "not-found", + `GitLab project ${repository} was not found or cannot accept uploads.`, + ); + } + if (uploadResult.status === 413) { + return yield* failure( + "failed", + `${meta.uploadName} exceeds this GitLab instance's maximum attachment size.`, + ); + } + if (uploadResult.status === 429) { + return yield* failure("rate-limited", "GitLab attachment upload rate limit exceeded."); + } + if (uploadResult.status < 200 || uploadResult.status >= 300) { + const parsedErr = Option.getOrUndefined(decodeGitLabErrorJson(uploadResult.body)); + const detailText = (parsedErr?.message ?? parsedErr?.error)?.trim(); + return yield* failure( + "failed", + detailText && detailText.length > 0 + ? `Could not upload ${meta.uploadName}: ${detailText}` + : `Could not upload ${meta.uploadName} (HTTP ${uploadResult.status}).`, + ); + } + + const decoded = decodeGitLabUploadJson(uploadResult.body); + if (Result.isFailure(decoded)) { + return yield* failure("failed", "GitLab returned an unreadable upload response."); + } + + const uploaded = decoded.success; + const rawAlt = input.alt?.trim(); + const markdown = + rawAlt && rawAlt.length > 0 + ? `${uploaded.markdown.trimStart().startsWith("![") ? "!" : ""}[${escapeMarkdownAlt(rawAlt) || "attachment"}](${uploaded.url})` + : uploaded.markdown; + const fullPath = + uploaded.full_path && uploaded.full_path.startsWith("/") + ? uploaded.full_path + : `/${repository}${uploaded.url.startsWith("/") ? uploaded.url : `/${uploaded.url}`}`; + const resolvedUrl = URL.canParse(uploaded.url) ? uploaded.url : `${apiOrigin}${fullPath}`; + return { + url: resolvedUrl, + markdown, + }; + }); + + return upload; +}); From 061f8537e0f8869b0796641b19f2cfbe5022a5d5 Mon Sep 17 00:00:00 2001 From: SeongHoon Ryu <4997174+ryush00@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:12:02 +0900 Subject: [PATCH 18/21] fix(antigravity): agents stop ending turns to wait on dev servers An Antigravity agent started a dev server, ended its turn with "I'll continue once it's ready", and never resumed: agy wakes an ended turn only when a background command exits, and a dev server never does. The user waited 16 minutes before asking. Tell the agent, in the session system prompt append and in per-turn rules when the append is dropped, to wait for readiness with a command that exits and continue in the same turn. The mcp-tool-use eval has no Antigravity harness or Gemini models, so this was checked with delegated gemini-4-carbon children on a slow-boot server: without the text 2/2 ended their turn before fetching the page; with it 2/2 fetched it in the same turn. Co-Authored-By: Claude Opus 5.5 --- .../orchestration-v2/Adapters/AntigravityAdapterV2.test.ts | 4 ++++ .../src/orchestration-v2/Adapters/AntigravityAdapterV2.ts | 6 ++++++ 2 files changed, 10 insertions(+) diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 27307c9bad0aa..cc98942330425 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -143,6 +143,7 @@ describe("AntigravityAdapterV2 flavor", () => { start: () => Effect.succeed({ sessionId: input.cwd, + initializeResult: { protocolVersion: 1 }, sessionSetupResult: { modes: sessionModes[input.cwd] }, }), } as never), @@ -2027,13 +2028,16 @@ describe("AntigravityAdapterV2 session system prompt", () => { assert.include(append, "pull_request_linking"); assert.isBelow(append.indexOf("GLOBAL_RULE"), append.indexOf("AGENTS_RULE")); assert.isBelow(append.indexOf("AGENTS_RULE"), append.indexOf("GEMINI_RULE")); + assert.include(append, ""); assert.notInclude(sent, "AGENTS_RULE"); + assert.notInclude(sent, ""); assert.notInclude(sent, ""); } else { assert.notInclude(append, "systemPrompt"); assert.include(sent, ""); assert.isBelow(sent.indexOf("GLOBAL_RULE"), sent.indexOf("AGENTS_RULE")); assert.isBelow(sent.indexOf("AGENTS_RULE"), sent.indexOf("GEMINI_RULE")); + assert.include(sent, ""); } }).pipe(Effect.provide(layerSession)), ); diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index 421aa9abeb87b..426092cd8c186 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -138,6 +138,11 @@ const extractAntigravitySubagentUpdate: NonNullable +A dev server, watcher, or other command that keeps running never finishes, so no background completion will wake you while it runs. Never end your turn waiting for one. After you start it, wait for it to be ready with a command that exits, such as \`for i in $(seq 60); do curl -sf http://127.0.0.1:3000 >/dev/null && break; sleep 2; done\`, then continue in the same turn. If it never becomes ready, say so. +`; + type PromptPayload = Parameters[0]; // The ACP adapter resends runtime instructions on a session's first turn, after compaction and on @@ -196,6 +201,7 @@ export function makeAntigravityAcpAdapterFlavor( const contents = yield* readRulesFile(filePath); if (contents.trim()) rules.push(`# ${filePath}\n\n${contents}`); } + rules.push(ANTIGRAVITY_LONG_RUNNING_COMMAND_INSTRUCTIONS); const rulesText = rules.join("\n\n"); // Set on start: whether this agent drops the system-prompt append, so rules ride the turns. let rulesInTurns = false; From 8a73efa78d359dfe1ce047ff7494f08b51c8e490 Mon Sep 17 00:00:00 2001 From: SeongHoon Ryu <4997174+ryush00@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:50:53 +0900 Subject: [PATCH 19/21] fix(server): finished delegates keep their process while the provider reports background work A finished delegate's process was released unless the projection's pendingBackgroundTasks was non-empty. Only the Claude adapter fills that field, so an Antigravity or other ACP child was detached about a second after its turn ended, killing the dev servers and schedule timers it had started and leaving them looking pending. The release now also asks the live runtime, through the same sessionHasBackgroundWork probe that provider switches and fresh sessions already use, and keeps the session when it reports work. Done with Claude Opus 5.5 in Claude Code. Co-Authored-By: Claude Opus 5.5 --- .../DelegatedCompletionDelivery.test.ts | 67 ++++++++++++++++--- .../src/orchestration-v2/Orchestrator.ts | 3 +- 2 files changed, 58 insertions(+), 12 deletions(-) diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts index 23b3deb1184c4..7f110f736c803 100644 --- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts +++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts @@ -49,6 +49,7 @@ import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; import * as EventSink from "./EventSink.ts"; import * as Orchestrator from "./Orchestrator.ts"; import * as ProviderRuntimeRecovery from "./ProviderRuntimeRecoveryService.ts"; +import * as ProviderSessionManager from "./ProviderSessionManager.ts"; import { continueRestartedRun } from "./RestartContinuation.ts"; import * as RuntimeLayer from "./runtimeLayer.ts"; import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts"; @@ -87,12 +88,42 @@ const layerCheckpointStoreTest = CheckpointStore.layer.pipe( ); const driver = ProviderDriverKind.make("codex"); +const perThreadCapabilities = { + ...CodexProviderCapabilitiesV2, + sessions: { + ...CodexProviderCapabilitiesV2.sessions, + supportsMultipleProviderThreadsPerSession: false, + }, +}; const orchestrationAdapter = { instanceId: modelSelection.instanceId, driver, getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }), - openSession: () => Effect.die("sessions are not used by delegated completion tests"), + // Only the live background-work probe is used; ACP providers report work through it alone. + openSession: (input) => + Effect.gen(function* () { + const now = yield* DateTime.now; + return { + instanceId: modelSelection.instanceId, + driver, + providerSessionId: input.providerSessionId, + providerSession: { + id: input.providerSessionId, + driver, + providerInstanceId: modelSelection.instanceId, + status: "ready", + cwd: "/repo", + model: modelSelection.model, + capabilities: perThreadCapabilities, + createdAt: now, + updatedAt: now, + lastError: null, + }, + events: Stream.never, + hasPendingBackgroundWork: Effect.succeed(true), + } as unknown as ProviderAdapter.ProviderAdapterV2SessionRuntime; + }), } as ProviderAdapter.ProviderAdapterV2["Service"]; const providerInstance = { instanceId: modelSelection.instanceId, @@ -4548,16 +4579,24 @@ it.layer(Layer.merge(layerTest, ProviderContinuationRequests.layer))( it.layer(layerTest)("delegated tasks across a server restart", (it) => { it.effect.each([ - { name: "releases", key: "", pendingBackgroundTasks: [], released: true }, + { name: "releases", key: "", pendingBackgroundTasks: [], live: false, released: true }, { name: "keeps while an unawaited background command runs", key: "-background", pendingBackgroundTasks: [{ taskId: "dev-server", kind: "command" as const }], + live: false, + released: false, + }, + { + name: "keeps while the live provider reports background work", + key: "-live-background", + pendingBackgroundTasks: [], + live: true, released: false, }, ])( "queues a child result without creating a provider history handoff and $name its process", - ({ key, pendingBackgroundTasks, released }) => + ({ key, pendingBackgroundTasks, live, released }) => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; const eventSink = yield* EventSink.EventSinkV2; @@ -4591,6 +4630,18 @@ it.layer(layerTest)("delegated tasks across a server restart", (it) => { const providerThreadId = ProviderThreadId.make( `provider-thread:result-message${key}-child`, ); + const providerSessionId = ProviderSessionId.make( + `provider-session:result-message${key}-child`, + ); + if (live) { + const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2; + yield* sessions.open({ + threadId: child.childThreadId, + providerSessionId, + modelSelection, + runtimePolicy: { runtimeMode: "full-access", interactionMode: "default", cwd: null }, + }); + } yield* eventSink.write({ commandId: CommandId.make(`command:result-message${key}-child-provider`), events: [ @@ -4600,19 +4651,13 @@ it.layer(layerTest)("delegated tasks across a server restart", (it) => { threadId: child.childThreadId, occurredAt: now, payload: { - id: ProviderSessionId.make(`provider-session:result-message${key}-child`), + id: providerSessionId, driver, providerInstanceId: modelSelection.instanceId, status: "ready", cwd: "/repo", model: modelSelection.model, - capabilities: { - ...CodexProviderCapabilitiesV2, - sessions: { - ...CodexProviderCapabilitiesV2.sessions, - supportsMultipleProviderThreadsPerSession: false, - }, - }, + capabilities: perThreadCapabilities, createdAt: now, updatedAt: now, lastError: null, diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index f2e870aa5e95c..30b581a8297db 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -14588,7 +14588,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio if ( session.status === "stopped" || session.status === "error" || - session.capabilities.sessions.supportsMultipleProviderThreadsPerSession + session.capabilities.sessions.supportsMultipleProviderThreadsPerSession || + (yield* sessionHasBackgroundWork(session, child.providerThreads)) ) continue; yield* dispatchWithReceiptEffect({ From 4412a1533c589564cb771d1a7de729a1edc86dcc Mon Sep 17 00:00:00 2001 From: SeongHoon Ryu <4997174+ryush00@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:18:39 +0900 Subject: [PATCH 20/21] fix(antigravity): fall back to acp-mcp-call when single T3 tools are missing Antigravity drops large t3-code schemas from its declarations, and the cutoff can move after a resume or compaction. The model then saw most T3 tools, decided the ACP fallback ("if the T3 tools are absent") did not apply, and called Antigravity's generic call_mcp_tool, which refuses t3-code tools ("tool preview_open is not enabled for server t3-code"). The fallback now covers one missing tool and that rejection. Co-Authored-By: Claude Opus 5.5 --- .../provider-core/src/server/orchestrationInstructions.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/provider-core/src/server/orchestrationInstructions.ts b/packages/provider-core/src/server/orchestrationInstructions.ts index 4ce08d71119fe..359dfe71587f7 100644 --- a/packages/provider-core/src/server/orchestrationInstructions.ts +++ b/packages/provider-core/src/server/orchestrationInstructions.ts @@ -55,9 +55,10 @@ export const T3_CODE_DEVICE_TOOL_INSTRUCTIONS_WITH_TOOL_SEARCH = deviceToolInstr ` Load them with ToolSearch \`select:${T3_CODE_DEVICE_TOOLS.map((tool) => `mcp__t3-code__${tool}`).join(",")}\`.`, ); -// ACP only: some ACP agents accept the injected MCP server but never expose -// its tools, so they need the terminal transport other harnesses never use. -const T3_CODE_ACP_MCP_FALLBACK_INSTRUCTIONS = `ACP fallback: if the T3 tools are absent and \`T3_ACP_MCP_NODE\` is present, call them through the terminal: \`ELECTRON_RUN_AS_NODE=1 "$T3_ACP_MCP_NODE" \${T3_ACP_MCP_ENTRYPOINT:+"$T3_ACP_MCP_ENTRYPOINT"} acp-mcp-call orchestrator_capabilities '{}'\` (\`T3_ACP_MCP_ENTRYPOINT\` is unset for a standalone executable). Delegate with \`acp-mcp-call delegate_task '{"task":"...","target":{"providerInstanceId":"...","model":"..."},"mode":"async","clientRequestId":"..."}'\`.`; +// ACP only: some ACP agents accept the injected MCP server but expose none or only +// some of its tools (Antigravity drops large schemas and its generic `call_mcp_tool` +// refuses them), so they need the terminal transport other harnesses never use. +const T3_CODE_ACP_MCP_FALLBACK_INSTRUCTIONS = `ACP fallback: if \`T3_ACP_MCP_NODE\` is present and a T3 tool you need is missing from your tool list, or calling it fails as not enabled or not found (for example through a generic \`call_mcp_tool\`), call that tool through the terminal instead: \`ELECTRON_RUN_AS_NODE=1 "$T3_ACP_MCP_NODE" \${T3_ACP_MCP_ENTRYPOINT:+"$T3_ACP_MCP_ENTRYPOINT"} acp-mcp-call orchestrator_capabilities '{}'\` (\`T3_ACP_MCP_ENTRYPOINT\` is unset for a standalone executable). Delegate with \`acp-mcp-call delegate_task '{"task":"...","target":{"providerInstanceId":"...","model":"..."},"mode":"async","clientRequestId":"..."}'\`.`; const T3_CODE_ACP_DEFAULT_MODE_INSTRUCTIONS = `## T3 Code interaction mode: Default From d5c48cb16e2e40457823371e1d83f9a4eae35da3 Mon Sep 17 00:00:00 2001 From: SeongHoon Ryu <4997174+ryush00@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:54:18 +0900 Subject: [PATCH 21/21] fix(antigravity): threads resume when a timer wakes the agent An Antigravity thread that scheduled a 60 s check sat idle for seven minutes and only showed the agent's two wake replies when the user asked why it had stopped. agy 1.5.9 ends the prompt after `schedule`, runs the wake in its native session, and sends no ACP frames until another prompt reattaches the stream. Upstream's post-settle continuation (#38864, #38916) only reacts to streamed frames, so nothing woke the thread. The fork sync on 2026-11-19 dropped the wake watcher that covered this, assuming upstream had replaced it. Bring the watcher back. After a completed turn it polls the session's native log for a wake step (101) with no reply after it, then queues a message_text continuation whose prompt reattaches the stream. Upstream's buffered continuation still wins when agy does stream, since only one continuation can be requested at a time. Co-Authored-By: Claude Opus 5.5 --- .../Adapters/AntigravityAdapterV2.test.ts | 202 +++++++++++ .../Adapters/AntigravityAdapterV2.ts | 12 + .../acp/AntigravityWakeWatcher.test.ts | 186 ++++++++++ .../provider/acp/AntigravityWakeWatcher.ts | 326 ++++++++++++++++++ packages/provider-acp/src/server/adapter.ts | 56 ++- 5 files changed, 779 insertions(+), 3 deletions(-) create mode 100644 apps/server/src/provider/acp/AntigravityWakeWatcher.test.ts create mode 100644 apps/server/src/provider/acp/AntigravityWakeWatcher.ts diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index cc98942330425..9e38af5cd12b5 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -1,3 +1,5 @@ +import * as NodeSqlite from "node:sqlite"; + import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; @@ -37,6 +39,7 @@ import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost"; import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; import { makeAntigravityAcpRuntime } from "../../provider/acp/AntigravityAcpSupport.ts"; import { normalizeAntigravitySessionUpdate } from "../../provider/acp/AntigravityProtocol.ts"; +import { ANTIGRAVITY_WAKE_CONTINUATION_PROMPT } from "../../provider/acp/AntigravityWakeWatcher.ts"; import { ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE } from "../../provider/antigravityAuthSupport.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; @@ -1592,6 +1595,205 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { }).pipe(Effect.provide(layerSession)), ); + // agy 1.5.9 ends the prompt after `schedule`, then writes the timer's wake (step 101) to its + // session log and sends no ACP frames until a prompt reattaches the stream. + it.effect("re-prompts when a timer wakes the agent without any ACP frames", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const crypto = yield* SecureRandom.SecureRandom; + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + const profileDirectory = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-antigravity-timer-", + }); + const conversations = path.join(profileDirectory, "antigravity-acp", "conversations"); + yield* fileSystem.makeDirectory(conversations, { recursive: true }); + const dbPath = path.join(conversations, "mock-session-1.db"); + const appendSteps = (steps: ReadonlyArray) => + Effect.sync(() => { + const database = new NodeSqlite.DatabaseSync(dbPath); + try { + database.exec( + "CREATE TABLE IF NOT EXISTS steps (idx INTEGER PRIMARY KEY, step_type INTEGER, status INTEGER)", + ); + const insert = database.prepare( + "INSERT INTO steps VALUES ((SELECT coalesce(max(idx), -1) + 1 FROM steps), ?, ?)", + ); + for (const [stepType, status] of steps) insert.run(stepType, status); + } finally { + database.close(); + } + }); + + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdate: Parameters[0] | undefined; + const send = (update: EffectAcpSchema.SessionUpdate) => + sessionUpdate === undefined + ? Effect.die("the adapter must handle session updates") + : sessionUpdate( + normalizeAntigravitySessionUpdate({ sessionId: "mock-session-1", update }), + ); + const prompts: Array = []; + const pollWaiting = yield* Queue.unbounded(); + const offers = + yield* Queue.unbounded(); + const instanceId = ProviderInstanceId.make("antigravity-timer-test"); + const threadId = ThreadId.make("thread-antigravity-timer"); + const adapter = yield* makeAntigravityAdapterV2({ + instanceId, + userHome: process.cwd(), + selfInvocation: yield* resolveSelfInvocation(), + continuationRequests: { + offer: (request) => Queue.offer(offers, request).pipe(Effect.asVoid), + }, + profileDirectory, + wakeWatcherOptions: { + settleGrace: "0 millis", + onPollWait: () => Queue.offer(pollWaiting, undefined).pipe(Effect.asVoid), + }, + makeRuntime: (input) => + makeAntigravityAcpRuntime({ + ...input, + childProcessSpawner, + spawn: { + command: process.execPath, + args: [mockAgentPath], + cwd: input.cwd, + env: { T3_ACP_ANTIGRAVITY: "1" }, + }, + }).pipe( + Effect.provideService(SecureRandom.SecureRandom, crypto), + Effect.map((runtime): RuntimeService => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdate = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + prompt: (request) => + Effect.gen(function* () { + prompts.push(JSON.stringify(request.prompt)); + if (prompts.length === 1) { + yield* appendSteps([[14, 3]]); + yield* send({ + sessionUpdate: "tool_call", + toolCallId: "call_schedule", + kind: "other", + title: "Run schedule", + status: "completed", + rawInput: { DurationSeconds: 60, Prompt: "Check the deploy" }, + }); + yield* send({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "I'll check again in a minute." }, + }); + yield* appendSteps([[15, 3]]); + } else { + yield* send({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "The deploy passed." }, + }); + } + yield* send({ sessionUpdate: "usage_update", used: 9000, size: 1048576 }); + return { stopReason: "end_turn" as const }; + }), + })), + ), + withProcess: (_stop, task) => task, + defaultModel: Effect.undefined, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "gemini-test-low" } as const; + const session = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-antigravity-timer"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const throughTerminal = session.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + Effect.map((events) => Array.from(events)), + ); + const now = yield* DateTime.now; + const startTurn = ( + ordinal: number, + message: { createdBy: "user" | "agent"; creationSource: "web" | "server"; text: string }, + ) => + session.startTurn({ + appThread: { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: ProjectId.make("project-antigravity-timer"), + title: "Antigravity timer", + providerInstanceId: instanceId, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: process.cwd(), + activeProviderThreadId: providerThread.id, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + threadId, + runId: RunId.make(`run-antigravity-timer-${ordinal}`), + runOrdinal: ordinal, + providerTurnOrdinal: ordinal, + attemptId: RunAttemptId.make(`attempt-antigravity-timer-${ordinal}`), + rootNodeId: NodeId.make(`node-antigravity-timer-${ordinal}`), + providerThread, + message: { + ...message, + messageId: MessageId.make(`message-antigravity-timer-${ordinal}`), + attachments: [], + }, + modelSelection, + runtimePolicy, + }); + + yield* startTurn(1, { createdBy: "user", creationSource: "web", text: "watch the deploy" }); + const first = (yield* throughTerminal).at(-1); + assert.equal(first?.type === "turn.terminal" && first.status, "completed"); + + yield* Queue.take(pollWaiting); + yield* appendSteps([[101, 3]]); + yield* TestClock.adjust("400 millis"); + const wake = yield* Queue.take(offers); + assert.equal(wake.delivery, "message_text"); + + yield* startTurn(2, { + createdBy: "agent", + creationSource: "server", + text: "Background task completed.", + }); + const second = yield* throughTerminal; + const secondTerminal = second.at(-1); + assert.equal(secondTerminal?.type === "turn.terminal" && secondTerminal.status, "completed"); + assert.include(prompts[1] ?? "", ANTIGRAVITY_WAKE_CONTINUATION_PROMPT); + assert.include(JSON.stringify(second), "The deploy passed."); + }).pipe(Effect.provide(layerSession)), + ); + it.effect.each([ // session/cancel ends the agent's commands, so only Stop may send it. { ending: "Stop", cancels: 1, status: "interrupted" }, diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index 426092cd8c186..a62cf1fc844b8 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -37,6 +37,11 @@ import { } from "../../provider/acp/AntigravityChildWork.ts"; import { readAntigravityClientTextFile } from "../../provider/acp/AntigravityClientFiles.ts"; import { watchAntigravityPromptOutcome } from "../../provider/acp/AntigravityTurnOutcome.ts"; +import { + makeAntigravityPostSettleWakeWatcher, + rewriteAntigravityUserText, + type AntigravityWakeWatcherOptions, +} from "../../provider/acp/AntigravityWakeWatcher.ts"; import { antigravityApprovalOptions, antigravityCommandOutlivesPrompt, @@ -104,6 +109,7 @@ export interface AntigravityAdapterV2Options { readonly continuationRequests?: Parameters[0]["continuationRequests"]; /** The agent's GEMINI_HOME. Its session logs show turns that ended on an upstream error. */ readonly profileDirectory?: string; + readonly wakeWatcherOptions?: AntigravityWakeWatcherOptions; } /** @@ -347,6 +353,7 @@ export function makeAntigravityAcpAdapterFlavor( requiresRuntimeRestartForPolicyChange: (previous, next) => (previous.runtimeMode === "full-access") !== (next.runtimeMode === "full-access"), runtimeModeForSessionMode: antigravityRuntimeModeForSessionMode, + rewriteUserText: rewriteAntigravityUserText, clientFileSystem: { readTextFile: (request, cwd) => readAntigravityClientTextFile({ @@ -381,6 +388,11 @@ export function makeAntigravityAcpAdapterFlavor( : { watchPromptOutcome: (sessionId: string) => watchAntigravityPromptOutcome(profileDirectory, sessionId), + // agy 1.5.9 records a timer wake in its session log but sends no ACP frames until prompted. + watchPostSettleWake: makeAntigravityPostSettleWakeWatcher( + profileDirectory, + options.wakeWatcherOptions, + ), subagentsOutlivingPrompt: ({ sessionId, nativeTaskIds }) => readAntigravityChildrenAtWork({ profileDirectory, diff --git a/apps/server/src/provider/acp/AntigravityWakeWatcher.test.ts b/apps/server/src/provider/acp/AntigravityWakeWatcher.test.ts new file mode 100644 index 0000000000000..2fe3616cd5f4c --- /dev/null +++ b/apps/server/src/provider/acp/AntigravityWakeWatcher.test.ts @@ -0,0 +1,186 @@ +import * as NodeSqlite from "node:sqlite"; + +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, describe, it } from "@effect/vitest"; +import type { OrchestrationV2Notification } from "@t3tools/contracts"; +import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import * as Queue from "effect/Queue"; +import * as TestClock from "effect/testing/TestClock"; + +import { + ANTIGRAVITY_WAKE_CONTINUATION_PROMPT, + makeAntigravityPostSettleWakeWatcher, + rewriteAntigravityUserText, +} from "./AntigravityWakeWatcher.ts"; + +const USER_INPUT = 14; +const PLANNER_RESPONSE = 15; +const SYSTEM_MESSAGE = 101; + +const DONE_STATUS = 3; +const WAITING_STATUS = 9; + +describe("AntigravityWakeWatcher", () => { + it.effect( + "ignores answered mid-turn wakes, honors settle grace on post-settle wakes, and deduplicates", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const profileDirectory = yield* fs.makeTempDirectoryScoped(); + const sessionId = "e6aba774-5472-4277-b6ee-27b2e05570a7"; + const conversations = path.join(profileDirectory, "antigravity-acp", "conversations"); + yield* fs.makeDirectory(conversations, { recursive: true }); + const dbPath = path.join(conversations, `${sessionId}.db`); + + let nextIndex = 0; + const appendSteps = (steps: ReadonlyArray) => { + const database = new NodeSqlite.DatabaseSync(dbPath); + try { + database.exec( + "CREATE TABLE IF NOT EXISTS steps (idx INTEGER PRIMARY KEY, step_type INTEGER, status INTEGER)", + ); + const insert = database.prepare("INSERT INTO steps VALUES (?, ?, ?)"); + for (const [stepType, status] of steps) { + insert.run(nextIndex++, stepType, status); + } + } finally { + database.close(); + } + }; + + // Turn 1 contained a mid-turn wake that was already answered before `end_turn`. + appendSteps([ + [USER_INPUT, DONE_STATUS], + [SYSTEM_MESSAGE, DONE_STATUS], + [PLANNER_RESPONSE, DONE_STATUS], + ]); + + const pollWaiting = yield* Queue.unbounded(); + const graceWaiting = yield* Queue.unbounded(); + const notifications: Array = []; + const firstWake = yield* Deferred.make(); + + const watch = makeAntigravityPostSettleWakeWatcher(profileDirectory, { + pollInterval: "400 millis", + settleGrace: "150 millis", + onPollWait: () => Queue.offer(pollWaiting, undefined).pipe(Effect.asVoid), + onSettleGraceWait: () => Queue.offer(graceWaiting, undefined).pipe(Effect.asVoid), + }); + + const firstFiber = yield* Effect.forkScoped( + watch({ + sessionId, + offerWake: (options) => + Effect.sync(() => { + notifications.push(options?.notification); + }).pipe( + Effect.andThen(Deferred.succeed(firstWake, options?.notification)), + Effect.as(true), + ), + }), + ); + + yield* Queue.take(pollWaiting); + assert.lengthOf(notifications, 0); + + // Now a detached background command completes after `end_turn` and writes step_type = 101. + appendSteps([[SYSTEM_MESSAGE, DONE_STATUS]]); + yield* TestClock.adjust("400 millis"); + yield* Queue.take(graceWaiting); + assert.lengthOf(notifications, 0); + + yield* TestClock.adjust("150 millis"); + const notification = yield* Deferred.await(firstWake); + yield* Fiber.join(firstFiber); + assert.deepEqual(notification, { + source: { kind: "background_task" }, + outcome: "completed", + summary: "Background task finished", + }); + + // Restarting the watcher after the continuation turn without a newer wake must not re-offer it. + const secondFiber = yield* Effect.forkScoped( + watch({ + sessionId, + offerWake: (options) => + Effect.sync(() => { + notifications.push(options?.notification); + return true; + }), + }), + ); + yield* Queue.take(pollWaiting); + assert.lengthOf(notifications, 1); + yield* Fiber.interrupt(secondFiber); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect("wakes immediately when a boundary wake stalled on tool confirmation (WAITING)", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const profileDirectory = yield* fs.makeTempDirectoryScoped(); + const sessionId = "0d9c2b4e-1111-4222-8333-944455556666"; + const conversations = path.join(profileDirectory, "antigravity-acp", "conversations"); + yield* fs.makeDirectory(conversations, { recursive: true }); + const database = new NodeSqlite.DatabaseSync(path.join(conversations, `${sessionId}.db`)); + try { + database.exec( + "CREATE TABLE steps (idx INTEGER PRIMARY KEY, step_type INTEGER, status INTEGER)", + ); + database.exec( + `INSERT INTO steps VALUES + (0, ${USER_INPUT}, ${DONE_STATUS}), + (1, ${PLANNER_RESPONSE}, ${DONE_STATUS}), + (2, ${SYSTEM_MESSAGE}, ${DONE_STATUS}), + (3, ${PLANNER_RESPONSE}, ${WAITING_STATUS})`, + ); + } finally { + database.close(); + } + + const watch = makeAntigravityPostSettleWakeWatcher(profileDirectory, { + pollInterval: "10 seconds", + settleGrace: "10 seconds", + }); + let offered = 0; + yield* watch({ + sessionId, + offerWake: () => + Effect.sync(() => { + offered += 1; + return true; + }), + }); + assert.equal(offered, 1); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect( + "rewrites only server-authored continuation messages into the non-duplicating prompt", + () => + Effect.gen(function* () { + const serverTurn = { + message: { createdBy: "agent", creationSource: "server" }, + } as ProviderAdapter.ProviderAdapterV2TurnInput; + const userTurn = { + message: { createdBy: "user", creationSource: "web" }, + } as ProviderAdapter.ProviderAdapterV2TurnInput; + + assert.equal( + yield* rewriteAntigravityUserText("Background task completed.", serverTurn), + ANTIGRAVITY_WAKE_CONTINUATION_PROMPT, + ); + assert.equal( + yield* rewriteAntigravityUserText("Background task completed.", userTurn), + "Background task completed.", + ); + }), + ); +}); diff --git a/apps/server/src/provider/acp/AntigravityWakeWatcher.ts b/apps/server/src/provider/acp/AntigravityWakeWatcher.ts new file mode 100644 index 0000000000000..69bf443ba3f9e --- /dev/null +++ b/apps/server/src/provider/acp/AntigravityWakeWatcher.ts @@ -0,0 +1,326 @@ +// @effect-diagnostics nodeBuiltinImport:off -- node:sqlite and stat read the native session log. +import * as NodeFSP from "node:fs/promises"; +import * as NodeSqlite from "node:sqlite"; + +import type { OrchestrationV2Notification } from "@t3tools/contracts"; +import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import { backgroundWorkNotification } from "@t3tools/provider-core/server/notification"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { antigravityManagedPath, antigravityProfileRoot } from "./AntigravityProfilePaths.ts"; + +// Native Cortex trajectory step types and statuses in `.db`. +const USER_INPUT_STEP_TYPE = 14; +const PLANNER_RESPONSE_STEP_TYPE = 15; +const ERROR_STEP_TYPE = 17; +const SYSTEM_MESSAGE_STEP_TYPE = 101; + +const DONE_STEP_STATUS = 3; +const CANCELED_STEP_STATUS = 6; +const ERROR_STEP_STATUS = 7; +const WAITING_STEP_STATUS = 9; +const INTERRUPTED_STEP_STATUS = 12; + +const NATIVE_SESSION_ID = /^[\w-]+$/; +const DEFAULT_POLL_INTERVAL: Duration.Input = "400 millis"; +const DEFAULT_SETTLE_GRACE: Duration.Input = "150 millis"; +const CONTINUATION_MESSAGE_TEXT = "Background task completed."; + +export const ANTIGRAVITY_WAKE_CONTINUATION_PROMPT = + "ACP stream reattached after background wakeup. Continue processing the background notification if you have not finished responding yet; if you already completed your response to it, end your turn immediately without repeating your answer."; + +const DEFAULT_WAKE_NOTIFICATION: OrchestrationV2Notification = backgroundWorkNotification([ + { kind: "background_task", outcome: "completed" }, +]); + +const conversationSegments = ["antigravity-acp", "conversations"]; + +class AntigravityWakeLogError extends Schema.TaggedError()( + "AntigravityWakeLogError", + { cause: Schema.Defect() }, +) { + override get message(): string { + return "Could not read the Antigravity session wake log."; + } +} + +const wakeLogError = (cause: unknown) => new AntigravityWakeLogError({ cause }); + +interface WakeSnapshot { + readonly maxIdx: number; + readonly lastUserInputIdx: number; + readonly latestWakeIdx: number; + readonly hasTerminalResponseAfterWake: boolean; + readonly hasWaitingOrTerminalStepAfterWake: boolean; +} + +interface FileFingerprint { + readonly dbMtimeMs: number; + readonly dbSize: number; + readonly dbChangeCounter: number; + readonly walMtimeMs: number; + readonly walSize: number; + readonly walSalt: string; +} + +async function readHeaderSlice( + path: string, + offset: number, + length: number, +): Promise { + const handle = await NodeFSP.open(path, "r").catch(() => undefined); + if (handle === undefined) return undefined; + try { + const buffer = Buffer.alloc(length); + const { bytesRead } = await handle.read(buffer, 0, length, offset); + return bytesRead === length ? buffer : undefined; + } finally { + await handle.close().catch(() => undefined); + } +} + +async function statFingerprint(dbPath: string): Promise { + const dbStat = await NodeFSP.stat(dbPath).catch(() => undefined); + if (dbStat === undefined) return undefined; + const walPath = `${dbPath}-wal`; + const [dbCounterBytes, walStat, walSaltBytes] = await Promise.all([ + dbStat.size >= 28 ? readHeaderSlice(dbPath, 24, 4) : Promise.resolve(undefined), + NodeFSP.stat(walPath).catch(() => undefined), + readHeaderSlice(walPath, 16, 8), + ]); + return { + dbMtimeMs: dbStat.mtimeMs, + dbSize: dbStat.size, + dbChangeCounter: dbCounterBytes?.readUInt32BE(0) ?? -1, + walMtimeMs: walStat?.mtimeMs ?? -1, + walSize: walStat?.size ?? -1, + walSalt: walSaltBytes?.toString("hex") ?? "", + }; +} + +function sameFingerprint( + left: FileFingerprint | undefined, + right: FileFingerprint | undefined, +): boolean { + return ( + left !== undefined && + right !== undefined && + left.dbMtimeMs === right.dbMtimeMs && + left.dbSize === right.dbSize && + left.dbChangeCounter === right.dbChangeCounter && + left.walMtimeMs === right.walMtimeMs && + left.walSize === right.walSize && + left.walSalt === right.walSalt + ); +} + +const readWakeSnapshot = (file: string, floorIdx: number) => + Effect.try({ + try: (): WakeSnapshot | undefined => { + const database = new NodeSqlite.DatabaseSync(file, { readOnly: true }); + try { + database.exec("PRAGMA busy_timeout = 100"); + const columns = database + .prepare("PRAGMA table_info(steps)") + .all() + .flatMap((row) => (typeof row.name === "string" ? [row.name] : [])); + if (!columns.includes("idx") || !columns.includes("step_type")) { + return undefined; + } + const hasStatus = columns.includes("status"); + const maxRow = database.prepare("SELECT max(idx) AS idx FROM steps").get(); + const maxIdx = typeof maxRow?.idx === "number" ? maxRow.idx : -1; + const userRow = database + .prepare("SELECT max(idx) AS idx FROM steps WHERE step_type = ?") + .get(USER_INPUT_STEP_TYPE); + const lastUserInputIdx = typeof userRow?.idx === "number" ? userRow.idx : -1; + const wakeRow = database + .prepare("SELECT max(idx) AS idx FROM steps WHERE idx > ? AND step_type = ?") + .get(floorIdx, SYSTEM_MESSAGE_STEP_TYPE); + const latestWakeIdx = typeof wakeRow?.idx === "number" ? wakeRow.idx : -1; + if (latestWakeIdx <= floorIdx) { + return { + maxIdx, + lastUserInputIdx, + latestWakeIdx: -1, + hasTerminalResponseAfterWake: false, + hasWaitingOrTerminalStepAfterWake: false, + }; + } + const hasTerminalResponseAfterWake = hasStatus + ? database + .prepare( + `SELECT 1 FROM steps + WHERE idx > ? AND step_type IN (?, ?) AND status IN (?, ?, ?, ?) + LIMIT 1`, + ) + .get( + latestWakeIdx, + PLANNER_RESPONSE_STEP_TYPE, + ERROR_STEP_TYPE, + DONE_STEP_STATUS, + CANCELED_STEP_STATUS, + ERROR_STEP_STATUS, + INTERRUPTED_STEP_STATUS, + ) !== undefined + : database + .prepare( + `SELECT 1 FROM steps + WHERE idx > ? AND step_type IN (?, ?) + LIMIT 1`, + ) + .get(latestWakeIdx, PLANNER_RESPONSE_STEP_TYPE, ERROR_STEP_TYPE) !== undefined; + const hasWaitingOrTerminalStepAfterWake = hasStatus + ? database + .prepare( + `SELECT 1 FROM steps + WHERE idx > ? AND status IN (?, ?, ?, ?, ?) + LIMIT 1`, + ) + .get( + latestWakeIdx, + WAITING_STEP_STATUS, + DONE_STEP_STATUS, + CANCELED_STEP_STATUS, + ERROR_STEP_STATUS, + INTERRUPTED_STEP_STATUS, + ) !== undefined + : hasTerminalResponseAfterWake; + return { + maxIdx, + lastUserInputIdx, + latestWakeIdx, + hasTerminalResponseAfterWake, + hasWaitingOrTerminalStepAfterWake, + }; + } finally { + database.close(); + } + }, + catch: wakeLogError, + }); + +export function rewriteAntigravityUserText( + text: string, + turnInput: ProviderAdapter.ProviderAdapterV2TurnInput, +): Effect.Effect { + if ( + turnInput.message.createdBy === "agent" && + turnInput.message.creationSource === "server" && + text === CONTINUATION_MESSAGE_TEXT + ) { + return Effect.succeed(ANTIGRAVITY_WAKE_CONTINUATION_PROMPT); + } + return Effect.succeed(text); +} + +export interface AntigravityWakeWatcherOptions { + readonly pollInterval?: Duration.Input; + readonly settleGrace?: Duration.Input; + readonly onPollWait?: () => Effect.Effect; + readonly onSettleGraceWait?: () => Effect.Effect; +} + +/** + * `agy acp` 1.5.6+ ends `session/prompt` (`end_turn`) while background commands, timers, and + * subagents continue in the native trajectory, then writes `SYSTEM_MESSAGE` (`step_type = 101`) + * into `.db` on wakeup without emitting any ACP frames unless a prompt reattaches. + */ +export function makeAntigravityPostSettleWakeWatcher( + profileDirectory: string, + options?: AntigravityWakeWatcherOptions, +) { + const pollInterval = options?.pollInterval ?? DEFAULT_POLL_INTERVAL; + const settleGrace = Duration.fromInputUnsafe(options?.settleGrace ?? DEFAULT_SETTLE_GRACE); + const waitSettleGrace = Duration.isZero(settleGrace) + ? Effect.void + : (options?.onSettleGraceWait?.() ?? Effect.void).pipe( + Effect.andThen(Effect.sleep(settleGrace)), + ); + const lastOfferedWakeIndexBySession = new Map(); + + return Effect.fn("AntigravityWakeWatcher.watch")(function* (input: { + readonly sessionId: string; + readonly offerWake: (options?: { + readonly detail?: string | null; + readonly notification?: OrchestrationV2Notification; + }) => Effect.Effect; + }) { + if (!NATIVE_SESSION_ID.test(input.sessionId)) return; + const segments = [...conversationSegments, `${input.sessionId}.db`]; + const resolveManagedDb = Effect.tryPromise({ + try: async () => { + const root = await antigravityProfileRoot(profileDirectory); + if (root === undefined) return undefined; + if ((await antigravityManagedPath(root, conversationSegments, "directory")) === undefined) { + return undefined; + } + return await antigravityManagedPath(root, segments, "file"); + }, + catch: wakeLogError, + }).pipe(Effect.orElseSucceed(() => undefined)); + + const previousOffered = lastOfferedWakeIndexBySession.get(input.sessionId) ?? -1; + let baselineIdx = previousOffered; + let lastFingerprint: FileFingerprint | undefined; + + const initialManaged = yield* resolveManagedDb; + if (initialManaged !== undefined) { + lastFingerprint = yield* Effect.tryPromise({ + try: () => statFingerprint(initialManaged.path), + catch: wakeLogError, + }).pipe(Effect.orElseSucceed(() => undefined)); + const initial = yield* readWakeSnapshot(initialManaged.path, previousOffered).pipe( + Effect.orElseSucceed(() => undefined), + ); + if (initial !== undefined) { + const floorIdx = Math.max(previousOffered, initial.lastUserInputIdx); + if (initial.latestWakeIdx > floorIdx && !initial.hasTerminalResponseAfterWake) { + if (!initial.hasWaitingOrTerminalStepAfterWake) { + yield* waitSettleGrace; + } + lastOfferedWakeIndexBySession.set(input.sessionId, initial.latestWakeIdx); + const offered = yield* input.offerWake({ notification: DEFAULT_WAKE_NOTIFICATION }); + if (offered) return; + baselineIdx = Math.max(floorIdx, initial.latestWakeIdx); + } else { + baselineIdx = Math.max(floorIdx, initial.maxIdx); + } + } + } + + while (true) { + if (options?.onPollWait !== undefined) { + yield* options.onPollWait(); + } + yield* Effect.sleep(pollInterval); + const managed = yield* resolveManagedDb; + if (managed === undefined) continue; + const fingerprint = yield* Effect.tryPromise({ + try: () => statFingerprint(managed.path), + catch: wakeLogError, + }).pipe(Effect.orElseSucceed(() => undefined)); + if (fingerprint === undefined || sameFingerprint(lastFingerprint, fingerprint)) { + continue; + } + lastFingerprint = fingerprint; + const snapshot = yield* readWakeSnapshot(managed.path, baselineIdx).pipe( + Effect.orElseSucceed(() => undefined), + ); + if (snapshot === undefined) continue; + if (snapshot.latestWakeIdx <= baselineIdx) { + baselineIdx = Math.max(baselineIdx, snapshot.maxIdx); + continue; + } + if (!snapshot.hasWaitingOrTerminalStepAfterWake) { + yield* waitSettleGrace; + } + lastOfferedWakeIndexBySession.set(input.sessionId, snapshot.latestWakeIdx); + const offered = yield* input.offerWake({ notification: DEFAULT_WAKE_NOTIFICATION }); + if (offered) return; + baselineIdx = Math.max(baselineIdx, snapshot.latestWakeIdx, snapshot.maxIdx); + } + }); +} diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 453ae6692449c..65179cba8d620 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -5,6 +5,7 @@ import { type ModelSelection, type OrchestrationV2ConversationMessage, type OrchestrationV2ExecutionNode, + type OrchestrationV2Notification, type OrchestrationV2PlanArtifact, type OrchestrationV2PlanStep, type OrchestrationV2ProviderCapabilities, @@ -610,6 +611,17 @@ export interface AcpAdapterV2Flavor { readonly isProviderWakeNotification?: ( notification: EffectAcpSchema.SessionNotification, ) => boolean; + /** + * Watches native session logs after a completed turn, for agents that wake on a timer or + * background command without sending ACP frames until a prompt reattaches the stream. + */ + readonly watchPostSettleWake?: (input: { + readonly sessionId: string; + readonly offerWake: (options?: { + readonly detail?: string | null; + readonly notification?: OrchestrationV2Notification; + }) => Effect.Effect; + }) => Effect.Effect; readonly deferFinalizeForBackgroundWork?: AcpNegotiatedFlag; /** * Every model reply ends with `usage_update`, also the ones the agent starts with no prompt @@ -2224,6 +2236,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( flavor.sessionModeForPolicy?.(policy), flavor.sessionConfigForPolicy?.(policy), ]); + const postSettleWakeFiber = yield* Ref.make | null>(null); + const stopPostSettleWakeWatcher = Ref.getAndSet(postSettleWakeFiber, null).pipe( + Effect.flatMap((fiber) => + fiber === null ? Effect.void : Fiber.interrupt(fiber).pipe(Effect.asVoid), + ), + ); const promptInstructionStates = yield* Ref.make(new Map()); const promptRuntimeInstructions = yield* Ref.make(new Map()); // Unique markers keep delayed prompt completions from clearing later compactions. @@ -5088,7 +5106,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); }); - const offerContinuationRun = Effect.fnUntraced(function* (_sessionId: string) { + const offerContinuationRun = Effect.fnUntraced(function* ( + _sessionId: string, + wakeOptions?: { + readonly delivery?: "adapter_buffered" | "message_text"; + readonly detail?: string | null; + readonly notification?: OrchestrationV2Notification; + }, + ) { if (continuationRequests === undefined) { return false; } @@ -5113,7 +5138,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ); if (Option.isNone(pending)) return false; const { route, generation, reports } = pending.value; - const notification = backgroundWorkNotification([...reports.values()]); + const notification = + wakeOptions?.notification ?? backgroundWorkNotification([...reports.values()]); yield* Effect.logInfo("orchestration-v2.acp-wake-turn-detected", { driver, providerSessionId: input.providerSessionId, @@ -5124,7 +5150,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( threadId: route.threadId, providerThreadId: route.providerThreadId, driver, - detail: null, + detail: wakeOptions?.detail ?? null, + ...(wakeOptions?.delivery === undefined ? {} : { delivery: wakeOptions.delivery }), ...(notification === null ? {} : { notification }), clearIfCurrent: () => continuationPermit.withPermit( @@ -7598,6 +7625,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); const restartAcpRuntime = Effect.fnUntraced(function* (threadId: ThreadId | null) { + yield* stopPostSettleWakeWatcher; const previousGeneration = yield* Ref.get(runtimeCallbackGeneration); yield* runtimeCallbackPermit.withPermit( quarantineNativeTransportAtGeneration(previousGeneration), @@ -7784,6 +7812,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( threadId: ThreadId | null, candidate: AcpSessionRuntime.AcpSessionRuntimeStartResult, ) { + yield* stopPostSettleWakeWatcher; rememberTerminalEnvironment(candidate.sessionId, yield* readMcpContext(threadId)); yield* Ref.set(runtimeRestartRequired, false); yield* Ref.set(activeSessionId, candidate.sessionId); @@ -8313,6 +8342,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ); }); const quarantineStoppedRun = Effect.fnUntraced(function* () { + yield* stopPostSettleWakeWatcher; yield* continuationPermit.withPermit( Effect.gen(function* () { yield* Ref.update(continuationGeneration, (value) => value + 1); @@ -8531,6 +8561,24 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (settledStatus !== "completed") { yield* Ref.set(midTurnUnreportedCompletedTaskIds, new Set()); } + yield* stopPostSettleWakeWatcher; + const wakeSessionId = yield* Ref.get(activeSessionId); + if ( + settledStatus === "completed" && + !directStopQuarantine && + continuationRequests !== undefined && + flavor.watchPostSettleWake !== undefined && + wakeSessionId !== null + ) { + const fiber = yield* flavor + .watchPostSettleWake({ + sessionId: wakeSessionId, + offerWake: (wakeOptions) => + offerContinuationRun(wakeSessionId, { delivery: "message_text", ...wakeOptions }), + }) + .pipe(Effect.forkScoped, Effect.provideService(Scope.Scope, sessionScope)); + yield* Ref.set(postSettleWakeFiber, fiber); + } yield* Deferred.succeed(context.completed, undefined).pipe(Effect.ignore); }); @@ -8832,6 +8880,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( reason: "previous_turn_active", }); } + yield* stopPostSettleWakeWatcher; useProviderThreadIdentity(turnInput.providerThread); // load/resume can invoke client methods; install the incoming policy before activation. const previousRuntimePolicy = yield* Ref.get(activeRuntimePolicy); @@ -9386,6 +9435,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Effect.addFinalizer(() => Effect.gen(function* () { + yield* stopPostSettleWakeWatcher; yield* continuationPermit.withPermit( Effect.gen(function* () { yield* Ref.set(continuationClosed, true);