From 74273540e492c5af8ba2a439a48e6705957a954a Mon Sep 17 00:00:00 2001 From: Renfei Zhou Date: Thu, 26 Nov 2026 04:27:04 +0000 Subject: [PATCH] fix(fork): resolve upstream merge 36b9a06f09 (2026-11-25) Resolve the 23 files commit A left conflicted. Each fork change is re-applied on upstream's new structure: shared tooltip triggers, the restructured asset response headers, the thread action menu built in readMenu, the mobile thread body moved inline, the add-surface shortcut block, and the new onSessionStarted session argument. Upstream #43026 stops reading Antigravity usage limits, because calls to Google's internal APIs can get an account flagged. The fork code that only fed those limits goes with it: the agy CLI runtime's limits probe, the Antigravity account e-mail reader and its client-side pooling, and credentialEmail in the usage limits contract. Upstream #42722 hides the "+" menu when no surface can be added. With the whiteboard's right panel menu settings hiding every item, the arranged list is empty, so the menu that points to those settings could no longer open; an empty arranged list now still opens it. agentContextBudget.json takes the measured values of the merged tree. Co-Authored-By: Claude Opus 5.5 --- .../features/threads/ThreadRouteScreen.tsx | 121 +-- .../antigravityAccountEmail.ts | 29 - .../antigravityCliRuntime.test.ts | 106 +-- .../antigravityCliRuntime.ts | 32 - apps/server/src/git/GitManager.ts | 5 +- apps/server/src/http.ts | 45 +- apps/server/src/preview/ServerBrowser.ts | 3 - .../src/provider/Drivers/AntigravityDriver.ts | 20 - .../provider/acp/AntigravityTurnOutcome.ts | 4 - .../src/provider/agentContextBudget.json | 8 +- .../provider/antigravityUsageLimits.test.ts | 804 ------------------ .../src/provider/antigravityUsageLimits.ts | 509 ----------- apps/server/src/usage/cliproxyApi.ts | 18 +- apps/server/src/vcs/GitVcsDriverCore.ts | 6 +- apps/web/src/components/RightPanelTabs.tsx | 87 +- .../components/chat/MarkdownThreadLink.tsx | 62 +- .../components/chat/TimelineAssistantRows.tsx | 38 +- .../components/files/VirtualTablePreview.tsx | 3 - .../allHiddenAddMenu.browser.test.tsx | 77 ++ apps/web/src/hooks/useThreadActionMenu.ts | 46 +- apps/web/src/state/threads.ts | 4 - docs/user/appearance.md | 15 +- docs/user/outside-agents.md | 30 +- docs/user/project-settings.md | 226 +---- docs/user/providers-antigravity.md | 105 +-- docs/user/providers-claude.md | 74 +- packages/contracts/src/providerUsageLimits.ts | 2 - .../src/server/ProviderAdapter.ts | 8 +- .../src/fork/antigravityEmailBindings.test.ts | 251 ------ .../src/fork/antigravityEmailBindings.ts | 38 - packages/shared/src/usageLimits.ts | 12 +- 31 files changed, 145 insertions(+), 2643 deletions(-) delete mode 100644 apps/server/src/fork/antigravityAccountEmail/antigravityAccountEmail.ts delete mode 100644 apps/server/src/provider/antigravityUsageLimits.test.ts delete mode 100644 apps/server/src/provider/antigravityUsageLimits.ts create mode 100644 apps/web/src/fork/rightPanelMenu/allHiddenAddMenu.browser.test.tsx delete mode 100644 packages/shared/src/fork/antigravityEmailBindings.test.ts delete mode 100644 packages/shared/src/fork/antigravityEmailBindings.ts diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx index a15ac37233a4..b73b920649f1 100644 --- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx @@ -1029,126 +1029,6 @@ function ThreadRouteContent( } const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null; -<<<<<<< origin/main - const renderThreadRouteBody = () => ( - <> - dismissGitActionResult(gitActionThreadRef)} - onOpenPullRequest={openPullRequest} - /> - - <> - - ) - } - canOperateThread={canOperateThread} - selectedThread={selectedThreadWithDraftSettings ?? selectedThread} - selectedThreadDetailRef={selectedThreadDetailRef} - contentPresentation={contentPresentation} - screenTone={connectionTone( - routeConnectionState, - routeEnvironmentRuntime?.connectionAwaitingApproval === true, - m, - )} - connectionError={routeConnectionError} - environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null} - feedbackSubmissions={composer.feedbackSubmissions} - onDismissFeedback={composer.dismissFeedback} - selectedThreadFeed={composer.selectedThreadFeed} - fyiRuns={composer.fyiRuns} - pendingHandoff={composer.pendingHandoff} - activityRun={composer.selectedThreadActivityRun} - activeWorkStartedAt={ - creationState?.kind === "preparing" || - (worktreeSetup !== null && setupTurnStartedAt === null) - ? null - : composer.activeWorkStartedAt - } - isCompacting={composer.isCompacting} - compactBeforeSend={composer.compactBeforeSend} - runlessWorkActive={composer.runlessWorkActive} - extensionStatuses={composer.extensionStatuses} - providerSubagentStatus={composer.providerSubagentStatus} - creationState={creationState} - worktreeSetup={ - worktreeSetup - ? { - snapshot: worktreeSetup, - turnStarted: setupTurnStartedAt !== null, - onCancel: handleCancelWorktreeSetup, - onWorkLocally: setupMessage && selectedThreadProject ? handleWorkLocally : null, - } - : null - } - activePendingApproval={requests.activePendingApproval} - activePendingApprovals={requests.activePendingApprovals} - respondingApprovalId={requests.respondingApprovalId} - activePendingUserInput={requests.activePendingUserInput} - activePendingUserInputDrafts={requests.activePendingUserInputDrafts} - activePendingUserInputAnswers={requests.activePendingUserInputAnswers} - respondingUserInputId={requests.respondingUserInputId} - connectionStateLabel={routeConnectionState} - historyControls={historyControls} - activeThreadBusy={composer.activeThreadBusy} - canStopThread={awaitingBootstrapTurn || composer.interruptibleRunId !== null} - queuedRunEdit={composer.queuedRunEdit} - composerDraftKey={composer.composerDraftKey} - followUpBehavior={composer.followUpBehavior} - canSteerActiveTurn={composer.canSteerActiveTurn} - isSavingQueuedEdit={composer.isSavingQueuedEdit} - onCancelQueuedRunEdit={composer.cancelQueuedRunEdit} - onRemoveQueuedEditAttachment={composer.onRemoveQueuedEditAttachment} - environmentId={selectedThread.environmentId} - projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null} - threadCwd={selectedThreadCwd} - selectedThreadQueueCount={composer.selectedThreadQueueCount} - queuedMessages={ - selectedThreadCreation && selectedThreadCreation.outcome?.kind !== "delivered" - ? [selectedThreadCreation.message, ...composer.selectedThreadQueuedMessages] - : composer.selectedThreadQueuedMessages - } - dispatchingMessageId={composer.dispatchingQueuedMessageId} - layoutVariant={layout.variant} - usesAutomaticContentInsets={usesNativeHeaderGlass} - onOpenConnectionEditor={handleOpenConnectionEditor} - onChangeDraftMessage={composer.onChangeDraftMessage} - onPickDraftMedia={composer.onPickDraftMedia} - onPickDraftFiles={composer.onPickDraftFiles} - onNativePasteImages={composer.onNativePasteImages} - onNativePasteText={composer.onNativePasteText} - onRemoveDraftImage={composer.onRemoveDraftImage} - serverConfig={serverConfig} - onStopThread={awaitingBootstrapTurn ? handleCancelWorktreeSetup : handleStopThread} - onResumeQueue={composer.canResume ? handleResumeQueue : null} - onSendMessage={composer.onSendMessage} - offersSideChat={composer.sideChatUnavailableReason === null} - onSendCommand={composer.onSendCommand} - onReconnectEnvironment={handleReconnectEnvironment} - canSwitchThreadProvider={composer.canSwitchThreadProvider} - onRespondToApproval={requests.onRespondToApproval} - onSelectUserInputOption={requests.onSelectUserInputOption} - onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer} - onSubmitUserInput={requests.onSubmitUserInput} - onDismissUserInput={requests.onDismissUserInput} - /> - - - ); - -======= ->>>>>>> upstream/main return ( <> {inspectorHeader} @@ -1196,6 +1076,7 @@ function ThreadRouteContent( feedbackSubmissions={composer.feedbackSubmissions} onDismissFeedback={composer.dismissFeedback} selectedThreadFeed={composer.selectedThreadFeed} + fyiRuns={composer.fyiRuns} pendingHandoff={composer.pendingHandoff} activityRun={composer.selectedThreadActivityRun} activeWorkStartedAt={ diff --git a/apps/server/src/fork/antigravityAccountEmail/antigravityAccountEmail.ts b/apps/server/src/fork/antigravityAccountEmail/antigravityAccountEmail.ts deleted file mode 100644 index 16f856727379..000000000000 --- a/apps/server/src/fork/antigravityAccountEmail/antigravityAccountEmail.ts +++ /dev/null @@ -1,29 +0,0 @@ -import * as Effect from "effect/Effect"; -import * as Option from "effect/Option"; -import * as Schema from "effect/Schema"; - -export interface AntigravityAccountIdentity { - readonly credentialFingerprint: string; - readonly credentialEmail?: string; -} - -/** A fingerprint alone, from a fallback that never saw Google's user info, or with its email. */ -export type AntigravityAccount = string | AntigravityAccountIdentity; - -const decodeUserInfoEmail = Schema.decodeUnknownOption(Schema.Struct({ email: Schema.String })); - -/** Takes the fingerprint function so this module never imports the probe that imports it. */ -export const withAntigravityAccountEmail = - (fingerprintOf: (userInfo: unknown) => Effect.Effect) => - (userInfo: unknown): Effect.Effect => - Effect.map(fingerprintOf(userInfo), (credentialFingerprint) => { - const email = decodeUserInfoEmail(userInfo).pipe( - Option.map(({ email }) => email.trim()), - Option.filter((email) => email.length > 0), - Option.getOrUndefined, - ); - return email ? { credentialFingerprint, credentialEmail: email } : { credentialFingerprint }; - }); - -export const antigravityAccountFields = (account: AntigravityAccount): AntigravityAccountIdentity => - typeof account === "string" ? { credentialFingerprint: account } : account; diff --git a/apps/server/src/fork/antigravityCliRuntime/antigravityCliRuntime.test.ts b/apps/server/src/fork/antigravityCliRuntime/antigravityCliRuntime.test.ts index fc9e253910d1..faf9d68aa1b8 100644 --- a/apps/server/src/fork/antigravityCliRuntime/antigravityCliRuntime.test.ts +++ b/apps/server/src/fork/antigravityCliRuntime/antigravityCliRuntime.test.ts @@ -9,7 +9,6 @@ import { extractMcpToolCallIdentity } from "@t3tools/provider-acp/server/runtime import * as Digest from "effect/crypto/Digest"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; -import { HttpClient, HttpClientResponse } from "effect/http"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; @@ -18,12 +17,7 @@ import type * as EffectAcpSchema from "effect-acp/compat"; import { makeAntigravityAcpAdapterFlavor } from "../../orchestration-v2/Adapters/AntigravityAdapterV2.ts"; import { antigravitySessionMeta } from "../../provider/acp/AntigravityAcpSupport.ts"; -import { - antigravityRuntimeState, - makeAntigravityRuntimeUsageProbe, - profileAntigravityRuntimeState, - withUserAgyState, -} from "./antigravityCliRuntime.ts"; +import { antigravityRuntimeState, withUserAgyState } from "./antigravityCliRuntime.ts"; import { type AntigravityTextGenerationOptions, makeAntigravityTextGeneration, @@ -406,102 +400,4 @@ describe("Antigravity CLI runtime", () => { assert.deepEqual(hooked.helperFiles, [], "no agent started"); }).pipe(Effect.scoped, Effect.provide(layer)), ); - - it.effect("reads limits with the sign-in of the runtime that runs", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const userHome = yield* fileSystem.makeTempDirectoryScoped(); - const profileDirectory = path.join(userHome, "profile"); - // A profile the 1.4.5 runtime used still holds its refreshable login. - const profileApp = path.join(profileDirectory, "antigravity-acp"); - yield* fileSystem.makeDirectory(profileApp, { recursive: true }); - yield* fileSystem.writeFileString( - path.join(profileApp, "acp_token.json"), - JSON.stringify({ - client_id: "client", - client_secret: "profile-secret", - refresh_token: "profile-refresh", - }), - ); - const cliApp = path.join(userHome, ".gemini", "antigravity-cli"); - yield* fileSystem.makeDirectory(cliApp, { recursive: true }); - yield* fileSystem.writeFileString( - path.join(cliApp, "antigravity-oauth-token"), - JSON.stringify({ - token: { - access_token: "cli-access", - refresh_token: "cli-refresh", - expiry: "1970-01-01T01:00:00.123456789Z", - }, - }), - ); - const requests: Array<{ readonly url: string; readonly bearer: string | undefined }> = []; - const http = HttpClient.make((request) => - Effect.sync(() => { - requests.push({ url: request.url, bearer: request.headers.authorization }); - return HttpClientResponse.fromWeb( - request, - request.url.endsWith("/token") - ? Response.json({ access_token: "profile-access", expires_in: 3600 }) - : request.url.endsWith(":retrieveUserQuotaSummary") - ? Response.json({ - buckets: [{ bucketId: "gemini-5h", window: "5h", remainingFraction: 0.75 }], - }) - : Response.json({}, { status: 403 }), - ); - }), - ); - let runtime: "cli" | "managed" = "cli"; - let keyring: string | undefined; - const { probe } = yield* makeAntigravityRuntimeUsageProbe({ - profileDirectory, - userHome, - authMethod: "oauth-personal", - readKeyringSecret: Effect.sync(() => keyring), - runtimeState: Effect.sync(() => - runtime === "cli" - ? antigravityRuntimeState( - { managedVersionDirectory: null }, - { profileDirectory, userHome, path }, - ) - : profileAntigravityRuntimeState(profileDirectory), - ), - }).pipe(Effect.provideService(HttpClient.HttpClient, http)); - - const cli = yield* probe; - assert.isUndefined(cli.unavailable); - assert.deepEqual( - cli.windows.map((window) => [window.id, window.usedPercent]), - [["gemini-5h", 25]], - ); - assert.isFalse( - requests.some((request) => request.url.endsWith("/token")), - "the CLI's own login, not the profile's, with no refresh", - ); - assert.isTrue(requests.some((request) => request.bearer === "Bearer cli-access")); - - runtime = "managed"; - requests.length = 0; - const managed = yield* probe; - assert.isTrue(requests.some((request) => request.url.endsWith("/token"))); - assert.isFalse(requests.some((request) => request.bearer === "Bearer cli-access")); - assert.isUndefined(managed.unavailable); - assert.notMatch( - JSON.stringify([cli, managed]), - /cli-access|cli-refresh|profile-access|profile-refresh|profile-secret/, - ); - - // The user's own CLI may keep its Google sign-in only in the system keyring. - yield* fileSystem.remove(path.join(cliApp, "antigravity-oauth-token")); - keyring = JSON.stringify({ - token: { access_token: "keyring-access", expiry: "1970-01-01T01:00:00.123456789Z" }, - }); - runtime = "cli"; - requests.length = 0; - const fromKeyring = yield* probe; - assert.isUndefined(fromKeyring.unavailable); - assert.isTrue(requests.some((request) => request.bearer === "Bearer keyring-access")); - }).pipe(Effect.scoped, Effect.provide(layer)), - ); }); diff --git a/apps/server/src/fork/antigravityCliRuntime/antigravityCliRuntime.ts b/apps/server/src/fork/antigravityCliRuntime/antigravityCliRuntime.ts index 3cbbb26f4101..6850e1517141 100644 --- a/apps/server/src/fork/antigravityCliRuntime/antigravityCliRuntime.ts +++ b/apps/server/src/fork/antigravityCliRuntime/antigravityCliRuntime.ts @@ -10,7 +10,6 @@ import * as SqlClient from "effect/sql/SqlClient"; import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; import { removeAntigravitySessionFiles } from "../../provider/acp/AntigravitySessionFiles.ts"; -import { makeAntigravityUsageProbe } from "../../provider/antigravityUsageLimits.ts"; import type { AntigravityExecutable } from "../../provider/AntigravityInstallation.ts"; /** @@ -94,37 +93,6 @@ export const antigravityRuntimeStateOf = (options: { const antigravityTokenPath = (state: AntigravityRuntimeState, path: Path.Path) => path.join(state.root, state.appFolder, state.tokenFile); -/** - * Limits read with the sign-in of whichever runtime runs when they are read. The runtime is - * resolved per read, as the binary path may resolve only later; each runtime's folder is fixed. - */ -export const makeAntigravityRuntimeUsageProbe = Effect.fn("makeAntigravityRuntimeUsageProbe")( - function* ( - input: Omit[0], "appDirectory"> & { - readonly userHome: string; - readonly runtimeState: Effect.Effect; - }, - ) { - const path = yield* Path.Path; - const { userHome, runtimeState, ...options } = input; - const cliState = antigravityRuntimeState( - { managedVersionDirectory: null }, - { profileDirectory: options.profileDirectory, userHome, path }, - ); - const managed = yield* makeAntigravityUsageProbe(options); - const cli = yield* makeAntigravityUsageProbe({ - ...options, - appDirectory: path.join(cliState.root, cliState.appFolder), - }); - return { - probe: Effect.flatMap(runtimeState, (state) => - state.runtime === "cli" ? cli.probe : managed.probe, - ), - clear: Effect.andThen(managed.clear, cli.clear), - }; - }, -); - const RefreshToken = Schema.Struct({ refresh_token: Schema.NonEmptyString }); const decodeRefreshToken = Schema.decodeUnknownOption( Schema.fromJsonString(Schema.Union([RefreshToken, Schema.Struct({ token: RefreshToken })])), diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index 41385b65d64d..40a1070d2a7d 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -963,9 +963,6 @@ export const make = Effect.gen(function* () { } return result; }); -<<<<<<< origin/main - const hostPlatform = yield* HostProcess.Platform; -======= /** * Before a push's first side effect: a caller that needs approval learns which hooks to ask * about. The driver reads them again as it starts the push, so this is only the early answer. @@ -1001,7 +998,7 @@ export const make = Effect.gen(function* () { digest: cause.cause.digest, }) : undefined; ->>>>>>> upstream/main + const hostPlatform = yield* HostProcess.Platform; const createPrNeedsPush = Effect.fn("GitManager.createPrNeedsPush")(function* ( cwd: string, status: { diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index 613d7e547196..07bbba505efd 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -129,45 +129,6 @@ export function assetResponseHeaders( readonly htmlPolicy?: "file-page"; }, ): Record { -<<<<<<< origin/main - const lowerPath = filePath.toLowerCase(); - const inlineMimeType = options?.mimeType?.split(";", 1)[0]?.trim(); - const htmlContentSecurityPolicy = - options?.htmlPolicy === "file-page" - ? `${HTML_CONTENT_SECURITY_POLICY}; ${FILE_PAGE_NETWORK_POLICY}` - : HTML_CONTENT_SECURITY_POLICY; - return { - "Cache-Control": "private, max-age=3600", - "X-Content-Type-Options": "nosniff", - ...(options?.download - ? { - "Content-Disposition": downloadContentDisposition(options.fileName), - "Content-Security-Policy": "default-src 'none'; sandbox", - "Content-Type": - options.mimeType !== undefined && isSafeDownloadMimeType(options.mimeType) - ? options.mimeType - : "application/octet-stream", - } - : inlineMimeType !== undefined && isSafeInlineMediaMimeType(inlineMimeType) - ? { "Content-Type": inlineMimeType } - : inlineMimeType !== undefined && isSafeInlineDocumentMimeType(inlineMimeType) - ? { - "Content-Type": - inlineMimeType.toLowerCase() === "text/html" - ? "text/html; charset=utf-8" - : "application/pdf", - ...(inlineMimeType.toLowerCase() === "text/html" - ? { "Content-Security-Policy": htmlContentSecurityPolicy } - : {}), - } - : lowerPath.endsWith(".html") || lowerPath.endsWith(".htm") - ? { - "Content-Type": "text/html; charset=utf-8", - "Content-Security-Policy": htmlContentSecurityPolicy, - } - : {}), - ...(!options?.download && isScriptableXmlPath(lowerPath) -======= const base = { "Cache-Control": "private, max-age=3600", "X-Content-Type-Options": "nosniff" }; if (options?.download) { return { @@ -185,7 +146,10 @@ export function assetResponseHeaders( return { ...base, "Content-Type": "text/html; charset=utf-8", - "Content-Security-Policy": HTML_CONTENT_SECURITY_POLICY, + "Content-Security-Policy": + options?.htmlPolicy === "file-page" + ? `${HTML_CONTENT_SECURITY_POLICY}; ${FILE_PAGE_NETWORK_POLICY}` + : HTML_CONTENT_SECURITY_POLICY, }; } return { @@ -193,7 +157,6 @@ export function assetResponseHeaders( "Content-Type": mimeType, // XML types render as documents, so they get the same policy as SVG. ...(XML_DOCUMENT_MIME_TYPE_PATTERN.test(mimeType) ->>>>>>> upstream/main ? { "Content-Security-Policy": SVG_CONTENT_SECURITY_POLICY } : {}), }; diff --git a/apps/server/src/preview/ServerBrowser.ts b/apps/server/src/preview/ServerBrowser.ts index 559d4bc67e28..b32c4ddabbce 100644 --- a/apps/server/src/preview/ServerBrowser.ts +++ b/apps/server/src/preview/ServerBrowser.ts @@ -3298,17 +3298,14 @@ const make = Effect.gen(function* () { viewer.pressedButtons.set(button, { x: num(message.x), y: num(message.y) }); else if (action === "up") viewer.pressedButtons.delete(button); } -<<<<<<< origin/main if (action === "up") void PreviewPageCopy.forwardPressCopy(tab, viewer, button, CLIPBOARD_WORLD); -======= const press = left && action === "up" ? viewer.selectPress : null; if (press) { viewer.selectPress = null; await offerSelectMenu(session, viewer, press); releaseSelectHandle(viewer, session, press); } ->>>>>>> upstream/main return; } case "wheel": diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.ts b/apps/server/src/provider/Drivers/AntigravityDriver.ts index 27dde84c4d35..a88c08ae9cfb 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.ts @@ -36,7 +36,6 @@ import { } from "../../textGeneration/AntigravityTextGeneration.ts"; import { antigravityRuntimeState, - makeAntigravityRuntimeUsageProbe, profileAntigravityRuntimeState, removeAntigravityRuntimeSessionFiles, withUserAgyState, @@ -578,20 +577,6 @@ export const AntigravityDriver: ProviderDriver< }; }); -<<<<<<< origin/main - const usage = yield* makeAntigravityRuntimeUsageProbe({ - profileDirectory, - userHome, - authMethod: auth.authMethod, - runtimeState, - }).pipe( - Effect.provideService(FileSystem.FileSystem, fileSystem), - Effect.provideService(Path.Path, path), - Effect.provideService(Digest.Digest, digest), - Effect.provideService(HttpClient.HttpClient, httpClient), - ); -======= ->>>>>>> upstream/main const provider = yield* makeAntigravityProvider(settings, { environment: processEnvironment, stampIdentity: classifyModels, @@ -637,16 +622,11 @@ export const AntigravityDriver: ProviderDriver< ), ), profileDirectory, -<<<<<<< origin/main runtimeState, - onSessionStarted: (started, cwd) => - provider.onSessionStarted(started, cwd).pipe(Effect.andThen(authFlow.onSignedInElsewhere)), -======= onSessionStarted: (started, cwd, session) => provider .onSessionStarted(started, cwd, session) .pipe(Effect.andThen(authFlow.onSignedInElsewhere)), ->>>>>>> upstream/main onSessionEvent: (event, cwd) => { if (event._tag === "ConfigOptionsUpdated") { return provider.onConfigOptionsUpdated(event.configOptions); diff --git a/apps/server/src/provider/acp/AntigravityTurnOutcome.ts b/apps/server/src/provider/acp/AntigravityTurnOutcome.ts index b0b7894ef98f..6569601e7816 100644 --- a/apps/server/src/provider/acp/AntigravityTurnOutcome.ts +++ b/apps/server/src/provider/acp/AntigravityTurnOutcome.ts @@ -26,12 +26,9 @@ const MAX_ERROR_PAYLOAD_BYTES = 16_384; const API_ERROR = /Error (\d{3}), Message: ((?:(?!, Status: |Error \d{3}, Message: ).)+), Status: ([A-Z_]+|\d{3}[^,\n]*)/s; // Antigravity 1.5 with a Google account writes "STATUS (code NNN): message". -<<<<<<< origin/main // A protobuf length byte leads it and can be a capital, so only a google.rpc.Code name starts it. const STATUS_ERROR = /(CANCELLED|UNKNOWN|INVALID_ARGUMENT|DEADLINE_EXCEEDED|NOT_FOUND|ALREADY_EXISTS|PERMISSION_DENIED|RESOURCE_EXHAUSTED|FAILED_PRECONDITION|ABORTED|OUT_OF_RANGE|UNIMPLEMENTED|INTERNAL|UNAVAILABLE|DATA_LOSS|UNAUTHENTICATED) \(code (\d{3})\): (\P{Cc}+)/u; -======= -const STATUS_ERROR = /(?>>>>>> upstream/main const QUOTA_EXHAUSTED = /\breason:QUOTA_EXHAUSTED\b/; // Claude rejects a saved thinking block without a valid signature. It sits in the native // history, so every later prompt to that session fails the same way. diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 01847954e1c7..6c516fe6f510 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,11 +1,5 @@ { -<<<<<<< origin/main "claudeSystemAppendBytes": 5945, "codexAdditionalContextBytes": 7339, - "mcpToolListJsonBytes": 67550 -======= - "claudeSystemAppendBytes": 6245, - "codexAdditionalContextBytes": 7639, - "mcpToolListJsonBytes": 62140 ->>>>>>> upstream/main + "mcpToolListJsonBytes": 67776 } diff --git a/apps/server/src/provider/antigravityUsageLimits.test.ts b/apps/server/src/provider/antigravityUsageLimits.test.ts deleted file mode 100644 index 3207501d100e..000000000000 --- a/apps/server/src/provider/antigravityUsageLimits.test.ts +++ /dev/null @@ -1,804 +0,0 @@ -import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; -import * as NodeServices from "@effect/platform-node/NodeServices"; -import * as HostProcess from "@t3tools/shared/HostProcess"; -import * as Layer from "effect/Layer"; -import { describe, expect, it } from "@effect/vitest"; -import * as Context from "effect/Context"; -import * as DateTime from "effect/DateTime"; -import * as Effect from "effect/Effect"; -import * as FileSystem from "effect/FileSystem"; -import * as Path from "effect/Path"; -import * as TestClock from "effect/testing/TestClock"; -import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http"; - -import { - decodeGoKeyringSecret, - makeAntigravityUsageProbe, - readWindowsCliCredential, -} from "./antigravityUsageLimits.ts"; - -const summary = { - groups: [ - { - displayName: "Gemini Models", - buckets: [ - { - bucketId: "gemini-weekly", - window: "weekly", - remainingFraction: 0.96, - resetTime: "2026-10-12T19:41:43Z", - }, - { - bucketId: "gemini-5h", - window: "5h", - remainingFraction: 0.91, - resetTime: "2026-10-09T16:06:01Z", - }, - ], - }, - { - displayName: "Claude and GPT models", - buckets: [ - { - bucketId: "3p-weekly", - window: "weekly", - remainingFraction: 0, - resetTime: "2026-10-10T15:28:22Z", - }, - { - bucketId: "3p-5h", - window: "5h", - remainingFraction: 0.44, - resetTime: "2026-10-09T16:06:30Z", - }, - ], - }, - ], -}; - -const fixture = Effect.fn("AntigravityUsageTest.fixture")(function* ( - options: { - summary?: unknown; - /** Per-host quota summaries; hosts not listed fall back to `summary`. */ - summaryByHost?: Record; - models?: unknown; - summaryStatus?: number; - /** Per-host summary statuses; hosts not listed fall back to `summaryStatus`. */ - summaryStatusByHost?: Record; - tokenStatus?: number; - refreshToken?: string; - userId?: string; - omitUserEmail?: boolean; - userInfoAt?: number; - missingToken?: boolean; - authMethod?: "oauth-personal" | "oauth-business" | "gemini-api-key"; - keyringSecret?: string; - /** Reads the OS keyring instead of `keyringSecret`. */ - nativeKeyring?: boolean; - } = {}, -) { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const profileDirectory = yield* fs.makeTempDirectoryScoped(); - yield* fs.makeDirectory(path.join(profileDirectory, "antigravity-acp")); - const tokenPath = path.join(profileDirectory, "antigravity-acp", "acp_token.json"); - const writeToken = (refreshToken: string) => - fs.writeFileString( - tokenPath, - JSON.stringify({ - client_id: "client-id", - client_secret: "client-secret", - refresh_token: refreshToken, - project_id: "project-id", - }), - ); - if (!options.missingToken) yield* writeToken(options.refreshToken ?? "refresh-a"); - const requests: Array<{ url: string; body: string }> = []; - const http = HttpClient.make((request, url, _signal, fiber) => - Effect.sync(() => { - const init = Context.getOrUndefined(fiber.context, FetchHttpClient.RequestInit); - expect(init?.redirect).toBe("manual"); - const body = - request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : ""; - requests.push({ url: request.url, body }); - if (request.url.endsWith("/token")) { - expect(new URLSearchParams(body).get("grant_type")).toBe("refresh_token"); - return HttpClientResponse.fromWeb( - request, - Response.json( - { access_token: "access-token", expires_in: 3600 }, - { status: options.tokenStatus ?? 200 }, - ), - ); - } - expect(request.headers.authorization).toBe("Bearer access-token"); - if (request.url.endsWith("/userinfo")) { - return HttpClientResponse.fromWeb( - request, - options.userId - ? Response.json({ - id: options.userId, - ...(options.omitUserEmail ? {} : { email: "someone@example.com" }), - }) - : Response.json({}, { status: 403 }), - ); - } - expect(JSON.parse(body)).toEqual(options.missingToken ? {} : { project: "project-id" }); - expect(request.headers["user-agent"]).toMatch(/^antigravity\/hub\/2\.24\.0 /); - return HttpClientResponse.fromWeb( - request, - request.url.endsWith(":retrieveUserQuotaSummary") - ? Response.json(options.summaryByHost?.[url.host] ?? options.summary ?? summary, { - status: options.summaryStatusByHost?.[url.host] ?? options.summaryStatus ?? 200, - }) - : Response.json(options.models ?? { models: {} }), - ); - }).pipe( - Effect.tap(() => - request.url.endsWith("/userinfo") && options.userInfoAt !== undefined - ? TestClock.setTime(options.userInfoAt) - : Effect.void, - ), - ), - ); - const usage = yield* makeAntigravityUsageProbe({ - profileDirectory, - authMethod: options.authMethod ?? "oauth-personal", - ...(options.nativeKeyring ? {} : { readKeyringSecret: Effect.succeed(options.keyringSecret) }), - }).pipe(Effect.provideService(HttpClient.HttpClient, http)); - return { ...usage, requests, writeToken, tokenPath }; -}); - -describe("Antigravity subscription limits", () => { - // Oracle: the 10:16 UTC payload and its narrow Workaround rule. - it.effect("omits rolling resets for untouched summary buckets and keeps used Gemini resets", () => - Effect.gen(function* () { - yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-21T10:16:04Z"))); - const { probe } = yield* fixture({ - summary: { - groups: [ - { - buckets: [ - { - bucketId: "3p-5h", - window: "5h", - remainingFraction: 1, - resetTime: "2026-10-21T15:16:05Z", - }, - { - bucketId: "3p-weekly", - window: "weekly", - remainingFraction: 1, - resetTime: "2026-10-28T10:16:05Z", - }, - { - bucketId: "gemini-5h", - window: "5h", - remainingFraction: 0.848104, - resetTime: "2026-10-21T13:29:53Z", - description: - "You have used some of your 5-hour limit, it will fully refresh in 3 hours, 13 minutes.", - }, - { - bucketId: "gemini-weekly", - window: "weekly", - remainingFraction: 0.9620177, - resetTime: "2026-10-28T08:29:53Z", - description: - "You have used some of your weekly limit, it will fully refresh in 6 days, 22 hours.", - }, - ], - }, - ], - }, - }); - const limits = yield* probe; - const byId = new Map(limits.windows.map((window) => [window.id, window])); - expect(byId.get("3p-5h")).toEqual({ - id: "3p-5h", - label: "Claude & GPT (shared) · 5-hour", - kind: "session", - usedPercent: 0, - windowDurationMins: 300, - }); - expect(byId.get("3p-weekly")).toEqual({ - id: "3p-weekly", - label: "Claude & GPT (shared) · Weekly", - kind: "weekly", - usedPercent: 0, - windowDurationMins: 10080, - }); - expect(byId.get("gemini-5h")?.resetsAt).toBe("2026-10-21T13:29:53.000Z"); - expect(byId.get("gemini-weekly")?.resetsAt).toBe("2026-10-28T08:29:53.000Z"); - }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), - ); - - // Oracle: measure the tolerance from the summary request, after auth. - it.effect("uses summary request time after authentication for the reset tolerance", () => - Effect.gen(function* () { - yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-21T10:16:02Z"))); - const { probe } = yield* fixture({ - userInfoAt: DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-21T10:16:04Z")), - summary: { - buckets: [ - { - bucketId: "3p-5h", - window: "5h", - remainingFraction: 1, - resetTime: "2026-10-21T15:17:03Z", - }, - ], - }, - }); - expect((yield* probe).windows[0]?.resetsAt).toBeUndefined(); - }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), - ); - - // Oracle: keep descriptions, measured resets, and spent buckets. - it.effect("keeps summary resets with a description, a distant reset, or no quota left", () => - Effect.gen(function* () { - yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-21T10:16:04Z"))); - const { probe } = yield* fixture({ - summary: { - buckets: [ - { - bucketId: "described", - window: "5h", - remainingFraction: 1, - description: "Reported reset", - resetTime: "2026-10-21T15:16:04Z", - }, - { - bucketId: "distant", - window: "weekly", - remainingFraction: 1, - resetTime: "2026-10-28T12:16:04Z", - }, - { - bucketId: "spent", - window: "5h", - remainingFraction: 0, - resetTime: "2026-10-21T15:16:04Z", - }, - { - bucketId: "overfull", - window: "5h", - remainingFraction: 1.01, - resetTime: "2026-10-21T15:16:04Z", - }, - { - bucketId: "empty-description", - window: "5h", - remainingFraction: 1, - description: "", - resetTime: "2026-10-21T15:16:04Z", - }, - ], - }, - }); - expect((yield* probe).windows.map(({ id, resetsAt }) => ({ id, resetsAt }))).toEqual([ - { id: "described", resetsAt: "2026-10-21T15:16:04.000Z" }, - { id: "empty-description", resetsAt: "2026-10-21T15:16:04.000Z" }, - { id: "overfull", resetsAt: "2026-10-21T15:16:04.000Z" }, - { id: "spent", resetsAt: "2026-10-21T15:16:04.000Z" }, - { id: "distant", resetsAt: "2026-10-28T12:16:04.000Z" }, - ]); - }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), - ); - - // Oracle: the 60-second tolerance applies to both known window lengths. - it.effect("omits summary resets 59 seconds away but keeps resets 61 seconds away", () => - Effect.gen(function* () { - yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-21T10:16:04Z"))); - const { probe } = yield* fixture({ - summary: { - buckets: [ - { - bucketId: "5h-before", - window: "5h", - remainingFraction: 1, - resetTime: "2026-10-21T15:15:05Z", - }, - { - bucketId: "5h-after", - window: "5h", - remainingFraction: 1, - resetTime: "2026-10-21T15:17:05Z", - }, - { - bucketId: "5h-edge", - window: "5h", - remainingFraction: 1, - resetTime: "2026-10-21T15:17:04Z", - }, - { - bucketId: "weekly-after", - window: "weekly", - remainingFraction: 1, - resetTime: "2026-10-28T10:17:03Z", - }, - { - bucketId: "weekly-before", - window: "weekly", - remainingFraction: 1, - resetTime: "2026-10-28T10:15:03Z", - }, - { - bucketId: "weekly-edge", - window: "weekly", - remainingFraction: 1, - resetTime: "2026-10-28T10:15:04Z", - }, - ], - }, - }); - expect((yield* probe).windows.map(({ id, resetsAt }) => ({ id, resetsAt }))).toEqual([ - { id: "5h-after", resetsAt: "2026-10-21T15:17:05.000Z" }, - { id: "5h-before", resetsAt: undefined }, - { id: "5h-edge", resetsAt: undefined }, - { id: "weekly-after", resetsAt: undefined }, - { id: "weekly-before", resetsAt: "2026-10-28T10:15:03.000Z" }, - { id: "weekly-edge", resetsAt: undefined }, - ]); - }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), - ); - - // Oracle: workspace sign-ins are metered on cloudcode-pa, so its reading wins even when less used. - it.effect("reports a business account's quota from the endpoint it is metered on", () => - Effect.gen(function* () { - yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-21T10:16:04Z"))); - const { probe } = yield* fixture({ - authMethod: "oauth-business", - summaryByHost: { - "daily-cloudcode-pa.googleapis.com": { - buckets: [ - { - bucketId: "3p-5h", - window: "5h", - remainingFraction: 1, - resetTime: "2026-10-21T15:16:04Z", - }, - { - bucketId: "3p-weekly", - window: "weekly", - remainingFraction: 0.5, - resetTime: "2026-10-27T10:16:04Z", - }, - ], - }, - "cloudcode-pa.googleapis.com": { - buckets: [ - { - bucketId: "3p-5h", - window: "5h", - remainingFraction: 0.5, - resetTime: "2026-10-21T13:16:04Z", - }, - { - bucketId: "3p-weekly", - window: "weekly", - remainingFraction: 1, - resetTime: "2026-10-28T10:16:04Z", - }, - ], - }, - }, - }); - expect((yield* probe).windows).toEqual([ - { - id: "3p-5h", - label: "Claude & GPT (shared) · 5-hour", - kind: "session", - usedPercent: 50, - windowDurationMins: 300, - resetsAt: "2026-10-21T13:16:04.000Z", - }, - { - id: "3p-weekly", - label: "Claude & GPT (shared) · Weekly", - kind: "weekly", - usedPercent: 0, - windowDurationMins: 10080, - }, - ]); - }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), - ); - - // Oracle: model quotas have no evidence for the summary-only rule. - it.effect("keeps full model fallback resets even at a full window from the request", () => - Effect.gen(function* () { - yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-21T10:16:04Z"))); - const { probe } = yield* fixture({ - summaryStatus: 404, - models: { - models: { - "gemini-a": { - quotaInfo: { remainingFraction: 1, resetTime: "2026-10-21T15:16:04Z" }, - weeklyQuotaInfo: { remainingFraction: 1, resetTime: "2026-10-28T10:16:04Z" }, - }, - }, - }, - }); - expect( - (yield* probe).windows.map(({ id, resetsAt, windowDurationMins }) => ({ - id, - resetsAt, - windowDurationMins, - })), - ).toEqual([ - { id: "gemini-weekly", resetsAt: "2026-10-28T10:16:04.000Z", windowDurationMins: 10080 }, - { id: "gemini-quota", resetsAt: "2026-10-21T15:16:04.000Z", windowDurationMins: undefined }, - ]); - }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), - ); - - it.effect("reports separate Gemini and shared Claude/GPT five-hour and weekly limits", () => - Effect.gen(function* () { - const { probe, requests } = yield* fixture(); - const limits = yield* probe; - expect(limits.windows).toHaveLength(4); - expect(limits.unavailable).toBeUndefined(); - expect(limits.credentialFingerprint).toMatch(/^[0-9a-f]{64}$/); - const byId = new Map(limits.windows.map((window) => [window.id, window])); - expect(byId.get("gemini-weekly")?.usedPercent).toBeCloseTo(4); - expect(byId.get("gemini-5h")?.usedPercent).toBeCloseTo(9); - expect(byId.get("3p-weekly")).toMatchObject({ - label: "Claude & GPT (shared) · Weekly", - kind: "weekly", - usedPercent: 100, - windowDurationMins: 10080, - resetsAt: "2026-10-10T15:28:22.000Z", - }); - expect(byId.get("3p-5h")).toMatchObject({ kind: "session", windowDurationMins: 300 }); - expect(byId.get("3p-5h")?.usedPercent).toBeCloseTo(56); - yield* probe; - expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(1); - expect( - requests.filter((request) => request.url.endsWith(":retrieveUserQuotaSummary")), - ).toHaveLength(4); - }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), - ); - - it.effect("merges quota groups that only one endpoint reports", () => - Effect.gen(function* () { - const { probe } = yield* fixture({ - summaryByHost: { - // The daily endpoint can omit Gemini while the other endpoint returns all groups. - "daily-cloudcode-pa.googleapis.com": { - groups: [ - { - displayName: "Claude and GPT models", - buckets: [ - { bucketId: "3p-weekly", window: "weekly", remainingFraction: 0.5 }, - { bucketId: "3p-5h", window: "5h", remainingFraction: 0.3 }, - ], - }, - ], - }, - }, - }); - const limits = yield* probe; - expect(limits.windows.map((window) => window.id).toSorted()).toEqual([ - "3p-5h", - "3p-weekly", - "gemini-5h", - "gemini-weekly", - ]); - const byId = new Map(limits.windows.map((window) => [window.id, window])); - expect(byId.get("gemini-weekly")?.label).toBe("Gemini · Weekly"); - expect(byId.get("3p-5h")?.usedPercent).toBeCloseTo(70); - expect(byId.get("3p-weekly")?.usedPercent).toBe(50); - }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), - ); - - // Oracle: reported payloads for a personal sign-in, whose runtime meters on the daily endpoint. - it.effect("reports a personal account's quota from the daily endpoint it is metered on", () => - Effect.gen(function* () { - yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-11-07T12:00:00Z"))); - const argon = (remainingFraction: number, resetTime: string) => ({ - groups: [ - { - displayName: "Gemini 4 Argon", - buckets: [ - { - bucketId: "gemini-argon-wtu-weekly", - window: "weekly", - remainingFraction, - resetTime, - }, - ], - }, - ], - }); - const { probe } = yield* fixture({ - authMethod: "oauth-personal", - summaryByHost: { - "daily-cloudcode-pa.googleapis.com": argon(0.8623059, "2026-11-14T08:41:35Z"), - "cloudcode-pa.googleapis.com": argon(0, "2026-11-08T18:27:14Z"), - }, - }); - expect((yield* probe).windows).toEqual([ - expect.objectContaining({ - id: "gemini-argon-wtu-weekly", - usedPercent: expect.closeTo(13.77, 2), - resetsAt: "2026-11-14T08:41:35.000Z", - }), - ]); - }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), - ); - - it.effect("labels Argon and Carbon quotas apart from the default Gemini quota", () => - Effect.gen(function* () { - const { probe } = yield* fixture({ - summary: { - groups: [ - ...summary.groups, - { - displayName: "Gemini 4 Argon", - buckets: [ - { bucketId: "gemini-argon-wtu-weekly", window: "weekly", remainingFraction: 0.6 }, - ], - }, - { - displayName: "Gemini 4 Carbon", - buckets: [ - { bucketId: "gemini-carbon-wtu-weekly", window: "weekly", remainingFraction: 0.4 }, - ], - }, - { - displayName: " ", - buckets: [{ bucketId: "gemini-carbon-5h", window: "5h", remainingFraction: 0.8 }], - }, - ], - }, - }); - const limits = yield* probe; - const byId = new Map(limits.windows.map((window) => [window.id, window])); - expect(byId.get("gemini-weekly")?.label).toBe("Gemini · Weekly"); - expect(byId.get("gemini-argon-wtu-weekly")?.label).toBe("Gemini 4 Argon · Weekly"); - expect(byId.get("gemini-carbon-wtu-weekly")?.label).toBe("Gemini 4 Carbon · Weekly"); - expect(byId.get("gemini-carbon-5h")?.label).toBe("Gemini Carbon · 5-hour"); - }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), - ); - - it.effect("keeps one endpoint's quotas when the other fails", () => - Effect.gen(function* () { - const { probe } = yield* fixture({ - summaryStatusByHost: { "daily-cloudcode-pa.googleapis.com": 503 }, - }); - const limits = yield* probe; - expect(limits.unavailable).toBeUndefined(); - expect(limits.windows).toHaveLength(4); - }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), - ); - - it.effect("re-reads changed credentials and clears cached access after sign-out", () => - Effect.gen(function* () { - const { probe, clear, requests, writeToken, tokenPath } = yield* fixture(); - const first = yield* probe; - yield* writeToken("refresh-b"); - const second = yield* probe; - expect(second.credentialFingerprint).not.toBe(first.credentialFingerprint); - expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(2); - yield* (yield* FileSystem.FileSystem).remove(tokenPath); - expect((yield* probe).unavailable?.reason).toBe("unsupported"); - yield* writeToken("refresh-b"); - yield* probe; - expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(3); - yield* clear; - yield* probe; - expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(4); - }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), - ); - - it.effect("names one Google account the same way from every sign-in", () => - Effect.gen(function* () { - const read = (refreshToken: string, userId: string) => - fixture({ refreshToken, userId }).pipe(Effect.flatMap((usage) => usage.probe)); - const machineA = yield* read("refresh-a", "google-user-1"); - const machineB = yield* read("refresh-b", "google-user-1"); - const otherAccount = yield* read("refresh-c", "google-user-2"); - expect(machineA.credentialFingerprint).toMatch(/^[0-9a-f]{64}$/); - expect(machineB.credentialFingerprint).toBe(machineA.credentialFingerprint); - expect(otherAccount.credentialFingerprint).not.toBe(machineA.credentialFingerprint); - expect(machineA.credentialEmail).toBe("someone@example.com"); - expect(JSON.stringify(machineA)).not.toMatch(/google-user-1/); - const unidentified = yield* fixture({ refreshToken: "refresh-a" }).pipe( - Effect.flatMap((usage) => usage.probe), - ); - expect(unidentified.credentialFingerprint).not.toBe(machineA.credentialFingerprint); - expect(unidentified.credentialEmail).toBeUndefined(); - const idOnly = yield* fixture({ - refreshToken: "refresh-c", - userId: "google-user-1", - omitUserEmail: true, - }).pipe(Effect.flatMap((usage) => usage.probe)); - expect(idOnly.credentialFingerprint).toBe(machineA.credentialFingerprint); - expect(idOnly.credentialEmail).toBeUndefined(); - }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), - ); - - it.effect("falls back to model quotas without inventing a window duration", () => - Effect.gen(function* () { - const { probe } = yield* fixture({ - summaryStatus: 404, - models: { - models: { - "gemini-a": { - modelProvider: "MODEL_PROVIDER_GOOGLE", - quotaInfo: { remainingFraction: 0.8, resetTime: "2026-10-10T12:00:00Z" }, - }, - "gemini-b": { - modelProvider: "MODEL_PROVIDER_GOOGLE", - quotaInfo: { remainingFraction: 0.6, resetTime: "2026-10-10T12:00:00Z" }, - }, - "claude-a": { quotaInfo: { remainingFraction: 0.2 } }, - }, - }, - }); - const limits = yield* probe; - expect(limits.windows).toHaveLength(2); - expect(limits.windows.find((window) => window.id === "gemini-quota")?.usedPercent).toBe(40); - expect( - limits.windows.every( - (window) => window.kind === "other" && window.windowDurationMins === undefined, - ), - ).toBe(true); - }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), - ); - - it.effect("skips disabled and missing fractions and clamps valid percentages", () => - Effect.gen(function* () { - const { probe } = yield* fixture({ - summary: { - buckets: [ - { bucketId: "disabled", remainingFraction: 0, disabled: true }, - { bucketId: "missing", resetTime: "2026-10-10T12:00:00Z" }, - { bucketId: "gemini-5h", window: "5h", remainingFraction: 2, resetTime: "invalid" }, - ], - }, - }); - expect((yield* probe).windows).toEqual([ - { - id: "gemini-5h", - kind: "session", - label: "Gemini · 5-hour", - usedPercent: 0, - windowDurationMins: 300, - }, - ]); - }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), - ); - - it.effect("returns a safe failure when OAuth refresh fails", () => - Effect.gen(function* () { - const { probe } = yield* fixture({ tokenStatus: 401 }); - const limits = yield* probe; - expect(limits.windows).toEqual([]); - expect(limits.unavailable?.reason).toBe("probeFailed"); - expect(JSON.stringify(limits)).not.toMatch(/client-secret|refresh-a|access-token/); - }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), - ); - - it.effect("reads the native CLI's stored sign-in when acp_token.json is absent", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const { probe, tokenPath } = yield* fixture({ missingToken: true }); - // The 1.5.x CLI never writes acp_token.json; without a keyring it stores this file instead. - yield* fs.writeFileString( - path.join(path.dirname(tokenPath), "antigravity-oauth-token"), - JSON.stringify({ - token: { - access_token: "access-token", - token_type: "Bearer", - refresh_token: "refresh-a", - expiry: "2099-01-01T00:00:00Z", - expires_in: 3600, - }, - auth_method: "consumer", - id_token_email: "someone@example.com", - }), - ); - const limits = yield* probe; - expect(limits.unavailable?.message).not.toBe( - "Sign in with Google to see Antigravity limits.", - ); - expect(limits.unavailable?.reason).not.toBe("unsupported"); - }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), - ); - - it.effect("reads a Gemini Enterprise keyring sign-in and reports when it has expired", () => - Effect.gen(function* () { - yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-09T12:00:00Z"))); - const keyringSecret = (expiry: string) => - JSON.stringify({ token: { access_token: "access-token", refresh_token: "r", expiry } }); - // Google account instances keep their own sign-in; the shared entry belongs to another app. - const personal = yield* fixture({ - missingToken: true, - keyringSecret: keyringSecret("2026-10-09T14:00:00Z"), - }); - expect((yield* personal.probe).unavailable?.message).toBe( - "Sign in with Google to see Antigravity limits.", - ); - expect(personal.requests).toEqual([]); - - const signedIn = yield* fixture({ - authMethod: "oauth-business", - missingToken: true, - userId: "google-user-1", - keyringSecret: keyringSecret("2026-10-09T14:00:00.123456789+01:00"), - }); - const limits = yield* signedIn.probe; - expect(limits.unavailable).toBeUndefined(); - expect(limits.windows).toHaveLength(4); - expect(limits.credentialEmail).toBe("someone@example.com"); - expect(signedIn.requests.some((request) => request.url.endsWith("/token"))).toBe(false); - - const expired = yield* fixture({ - authMethod: "oauth-business", - missingToken: true, - keyringSecret: keyringSecret("2026-10-09T12:00:30Z"), - }); - expect((yield* expired.probe).unavailable?.reason).toBe("probeFailed"); - expect(expired.requests).toEqual([]); - }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), - ); - - it.effect.runIf(HostProcess.Platform.defaultValue() === "win32")( - "reads go-keyring's Windows credential target without changing it", - (ctx) => - Effect.gen(function* () { - // Never overwrite a real sign-in on a developer's machine. - if (readWindowsCliCredential(HostProcess.Architecture.defaultValue())) return ctx.skip(); - yield* TestClock.setTime( - DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-09T12:00:00Z")), - ); - const { AsyncEntry } = yield* Effect.promise(() => import("@napi-rs/keyring")); - // go-keyring writes the UTF-8 JSON at `:`. - const target = AsyncEntry.withTarget("gemini:antigravity", "gemini", "antigravity"); - const stored = new TextEncoder().encode( - JSON.stringify({ - token: { access_token: "access-token", expiry: "2026-10-09T14:00:00Z" }, - }), - ); - yield* Effect.acquireRelease( - Effect.promise(() => target.setSecret(stored)), - () => Effect.promise(() => target.deleteCredential()), - ); - const { probe } = yield* fixture({ - authMethod: "oauth-business", - missingToken: true, - nativeKeyring: true, - }); - const limits = yield* probe; - expect(limits.unavailable).toBeUndefined(); - expect(limits.windows).toHaveLength(4); - expect(readWindowsCliCredential(HostProcess.Architecture.defaultValue())).toEqual( - Buffer.from(stored), - ); - }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), - ); - - it("decodes go-keyring's macOS encodings", () => { - const value = '{"token":{}}'; - const bytes = (text: string) => new TextEncoder().encode(text); - expect(decodeGoKeyringSecret(bytes(value))).toBe(value); - expect( - decodeGoKeyringSecret(bytes(`go-keyring-base64:${Buffer.from(value).toString("base64")}`)), - ).toBe(value); - expect( - decodeGoKeyringSecret(bytes(`go-keyring-encoded:${Buffer.from(value).toString("hex")}`)), - ).toBe(value); - }); - - it.effect("does not make network requests for API keys or missing sign-ins", () => - Effect.gen(function* () { - for (const options of [{ authMethod: "gemini-api-key" as const }, { missingToken: true }]) { - const { probe, requests } = yield* fixture(options); - expect((yield* probe).unavailable?.reason).toBe("unsupported"); - expect(requests).toEqual([]); - } - }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), - ); -}); diff --git a/apps/server/src/provider/antigravityUsageLimits.ts b/apps/server/src/provider/antigravityUsageLimits.ts deleted file mode 100644 index 6c62e9ba2565..000000000000 --- a/apps/server/src/provider/antigravityUsageLimits.ts +++ /dev/null @@ -1,509 +0,0 @@ -import * as NodeModule from "node:module"; - -import type { AntigravitySettings, ServerProviderUsageWindow } from "@t3tools/contracts"; -import * as HostProcess from "@t3tools/shared/HostProcess"; -import * as Clock from "effect/Clock"; -import * as Digest from "effect/crypto/Digest"; -import * as DateTime from "effect/DateTime"; -import * as Effect from "effect/Effect"; -import * as FileSystem from "effect/FileSystem"; -import * as Option from "effect/Option"; -import * as Path from "effect/Path"; -import * as Schema from "effect/Schema"; -import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; - -import { - makeUnavailableUsageLimits, - makeUsageLimits, -} from "@t3tools/provider-core/server/usageLimits"; -import { - type AntigravityAccount, - antigravityAccountFields, - withAntigravityAccountEmail, -} from "../fork/antigravityAccountEmail/antigravityAccountEmail.ts"; - -export function antigravityUserAgent(platform: NodeJS.Platform, architecture: NodeJS.Architecture) { - return `antigravity/hub/2.24.0 (aidev_client; os_type=${platform}; arch=${architecture}; cl=963137146)`; -} - -const DAILY_ENDPOINT = "https://daily-cloudcode-pa.googleapis.com"; -const PROD_ENDPOINT = "https://cloudcode-pa.googleapis.com"; -// The ACP runtime meters consumer tiers on the daily host and GCP-terms tiers on prod. -// The sign-in method stands in for the tier. -const ENDPOINTS = { - "oauth-personal": [DAILY_ENDPOINT, PROD_ENDPOINT], - "oauth-business": [PROD_ENDPOINT, DAILY_ENDPOINT], -}; -const SUMMARY_WINDOW_MINS = new Map([ - ["5h", 5 * 60], - ["weekly", 7 * 24 * 60], -]); -const MANUAL_REDIRECT: RequestInit = { redirect: "manual" }; -const TokenFile = Schema.Struct({ - client_id: Schema.NonEmptyString, - client_secret: Schema.NonEmptyString, - refresh_token: Schema.NonEmptyString, - project_id: Schema.optional(Schema.String), -}); -// The 1.5.x CLI never writes acp_token.json: it keeps its sign-in in the OS keyring, or in -// antigravity-oauth-token without one or when T3 bypasses the keyring. It stores no OAuth client, so T3 cannot refresh it. -const CliToken = Schema.Struct({ - token: Schema.Struct({ - access_token: Schema.NonEmptyString, - refresh_token: Schema.optional(Schema.String), - expiry: Schema.optional(Schema.String), - }), -}); -const TokenResponse = Schema.Struct({ - access_token: Schema.NonEmptyString, - expires_in: Schema.Number.check(Schema.isGreaterThan(0)), -}); -const UserInfo = Schema.Struct({ id: Schema.NonEmptyString }); -const Quota = Schema.Struct({ - remainingFraction: Schema.optional(Schema.Number), - resetTime: Schema.optional(Schema.String), -}); -const Bucket = Schema.Struct({ - ...Quota.fields, - bucketId: Schema.NonEmptyString, - window: Schema.optional(Schema.String), - displayName: Schema.optional(Schema.String), - description: Schema.optional(Schema.String), - disabled: Schema.optional(Schema.Boolean), -}); -const Summary = Schema.Struct({ - groups: Schema.optional( - Schema.Array( - Schema.Struct({ - displayName: Schema.optional(Schema.String), - buckets: Schema.optional(Schema.Array(Bucket)), - }), - ), - ), - buckets: Schema.optional(Schema.Array(Bucket)), -}); -const Models = Schema.Struct({ - models: Schema.Record( - Schema.String, - Schema.Struct({ - modelProvider: Schema.optional(Schema.String), - quotaInfo: Schema.optional(Quota), - weeklyQuotaInfo: Schema.optional(Quota), - }), - ), -}); - -const decodeTokenFile = Schema.decodeEffect(Schema.fromJsonString(TokenFile)); -const decodeCliToken = Schema.decodeEffect(Schema.fromJsonString(CliToken)); -const decodeTokenResponse = Schema.decodeUnknownEffect(TokenResponse); -const decodeUserInfo = Schema.decodeUnknownEffect(UserInfo); -const decodeSummary = Schema.decodeUnknownEffect(Summary); -const decodeModels = Schema.decodeUnknownEffect(Models); - -function iso(value: string | undefined): string | undefined { - const parsed = value ? DateTime.make(value) : Option.none(); - return Option.isSome(parsed) ? DateTime.formatIso(parsed.value) : undefined; -} - -function quotaWindow( - id: string, - label: string, - quota: typeof Quota.Type, - kind: ServerProviderUsageWindow["kind"] = "other", - windowDurationMins?: number, -): ServerProviderUsageWindow | undefined { - if (quota.remainingFraction === undefined || !Number.isFinite(quota.remainingFraction)) { - return undefined; - } - const resetsAt = iso(quota.resetTime); - return { - id, - label, - kind, - usedPercent: (1 - Math.max(0, Math.min(1, quota.remainingFraction))) * 100, - ...(resetsAt ? { resetsAt } : {}), - ...(windowDurationMins === undefined ? {} : { windowDurationMins }), - }; -} - -function summaryResetTime( - bucket: typeof Bucket.Type, - windowDurationMins: number | undefined, - requestedAt: number, -): string | undefined { - // Untouched summary buckets report a rolling full-window reset. - const untouched = - bucket.remainingFraction === 1 && - bucket.description === undefined && - windowDurationMins !== undefined && - Math.abs(Date.parse(bucket.resetTime ?? "") - requestedAt - windowDurationMins * 60_000) <= - 60_000; - return untouched ? undefined : bucket.resetTime; -} - -const sha256 = Effect.fnUntraced(function* (text: string) { - const digest = yield* (yield* Digest.Digest).digest( - Digest.sha256, - new TextEncoder().encode(text), - ); - return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join(""); -}); - -/** go-keyring stores UTF-8, which it prefixes and encodes on macOS. */ -export function decodeGoKeyringSecret(secret: ArrayLike): string { - // The binding resolves a plain number array at runtime despite its Uint8Array type. - const text = new TextDecoder().decode(Uint8Array.from(secret)); - if (text.startsWith("go-keyring-base64:")) { - return Buffer.from(text.slice("go-keyring-base64:".length), "base64").toString("utf8"); - } - if (text.startsWith("go-keyring-encoded:")) { - return Buffer.from(text.slice("go-keyring-encoded:".length), "hex").toString("utf8"); - } - return text; -} - -class AntigravityKeyringError extends Schema.TaggedError()( - "AntigravityKeyringError", - { cause: Schema.Defect() }, -) { - override get message(): string { - return "Could not read the Antigravity sign-in from the system keyring."; - } -} - -// A single-executable server resolves packages on disk only through `require`. -const requireExternal = NodeModule.createRequire(import.meta.url); - -/** - * go-keyring's Windows target is `gemini:antigravity`; @napi-rs/keyring reads `antigravity.gemini`, - * and its `withTarget` overwrites the target with an empty secret before reading. - */ -export function readWindowsCliCredential( - architecture: NodeJS.Architecture, -): Uint8Array | undefined { - // CREDENTIALW offsets and the pointers below are 64-bit. - if (architecture !== "x64" && architecture !== "arm64") { - throw new Error(`no credential access on ${architecture}`); - } - const { DataType, load, open } = requireExternal("ffi-rs") as typeof import("ffi-rs"); - open({ library: "t3-advapi32", path: "advapi32.dll" }); - open({ library: "t3-kernel32", path: "kernel32.dll" }); - const copy = (into: Buffer, from: bigint) => - load({ - library: "t3-kernel32", - funcName: "RtlMoveMemory", - retType: DataType.Void, - paramsType: [DataType.U8Array, DataType.BigInt, DataType.BigInt], - paramsValue: [into, from, BigInt(into.length)], - }); - const out = Buffer.alloc(8); - const read = load({ - library: "t3-advapi32", - funcName: "CredReadW", - retType: DataType.I32, - // CRED_TYPE_GENERIC - paramsType: [DataType.WString, DataType.U32, DataType.U32, DataType.U8Array], - paramsValue: ["gemini:antigravity", 1, 0, out], - errno: true as const, - }); - if (read.value === 0) { - // ERROR_NOT_FOUND - if (read.errnoCode === 1168) return undefined; - throw new Error(`CredReadW failed with Windows error ${read.errnoCode}`); - } - const credential = out.readBigUInt64LE(); - try { - // CredentialBlobSize is a DWORD at 32 and CredentialBlob a pointer at 40. - const header = Buffer.alloc(48); - copy(header, credential); - const size = header.readUInt32LE(32); - if (size === 0) return undefined; - const blob = Buffer.alloc(size); - copy(blob, header.readBigUInt64LE(40)); - return blob; - } finally { - load({ - library: "t3-advapi32", - funcName: "CredFree", - retType: DataType.Void, - paramsType: [DataType.BigInt], - paramsValue: [credential], - }); - } -} - -// Loaded lazily: a native binding that fails to load must not take the provider down. -const readCliKeyringSecret = (platform: NodeJS.Platform, architecture: NodeJS.Architecture) => - Effect.tryPromise({ - try: async () => { - const secret = - platform === "win32" - ? readWindowsCliCredential(architecture) - : await new ( - requireExternal("@napi-rs/keyring") as typeof import("@napi-rs/keyring") - ).AsyncEntry("gemini", "antigravity").getSecret(); - return secret ? decodeGoKeyringSecret(secret) : undefined; - }, - catch: (cause) => new AntigravityKeyringError({ cause }), - }); - -/** Keys an account by its Google ID, which matches across machines and hubs; refresh tokens do not. */ -export const antigravityAccountFingerprint = (userInfo: unknown) => - decodeUserInfo(userInfo).pipe(Effect.flatMap((info) => sha256(`google-account\0${info.id}`))); - -/** Windows from a `retrieveUserQuotaSummary` answer requested at `requestedAt`. */ -export const antigravitySummaryWindows = (response: unknown, requestedAt: number) => - decodeSummary(response).pipe(Effect.map((summary) => summaryWindows(summary, requestedAt))); - -function summaryWindows(summary: typeof Summary.Type, requestedAt: number) { - const windows = new Map(); - const groups = summary.groups?.some((group) => group.buckets?.length) - ? summary.groups - : [{ buckets: summary.buckets }]; - for (const group of groups ?? []) { - for (const bucket of group.buckets ?? []) { - if (bucket.disabled) continue; - // Argon and Carbon are metered separately from the default Gemini buckets. - const family = bucket.bucketId.startsWith("gemini-argon-") - ? group.displayName?.trim() || "Gemini Argon" - : bucket.bucketId.startsWith("gemini-carbon-") - ? group.displayName?.trim() || "Gemini Carbon" - : bucket.bucketId.startsWith("gemini-") - ? "Gemini" - : bucket.bucketId.startsWith("3p-") - ? "Claude & GPT (shared)" - : group.displayName?.trim() || bucket.bucketId; - const weekly = bucket.window === "weekly"; - const session = bucket.window === "5h"; - const windowDurationMins = SUMMARY_WINDOW_MINS.get(bucket.window ?? ""); - const window = quotaWindow( - bucket.bucketId, - `${family} · ${weekly ? "Weekly" : session ? "5-hour" : bucket.displayName?.trim() || "Quota"}`, - { ...bucket, resetTime: summaryResetTime(bucket, windowDurationMins, requestedAt) }, - weekly ? "weekly" : session ? "session" : "other", - windowDurationMins, - ); - if (window) windows.set(window.id, window); - } - } - return [...windows.values()]; -} - -/** Older accounts expose model quotas without a window length. Do not invent a reset cadence. */ -function modelWindows(models: typeof Models.Type) { - const windows = new Map(); - for (const [modelId, model] of Object.entries(models.models)) { - const family = - model.modelProvider === "MODEL_PROVIDER_GOOGLE" || modelId.startsWith("gemini-") - ? "Gemini" - : model.modelProvider === "MODEL_PROVIDER_ANTHROPIC" || modelId.startsWith("claude-") - ? "Claude" - : model.modelProvider === "MODEL_PROVIDER_OPENAI" || modelId.startsWith("gpt-") - ? "GPT" - : undefined; - if (!family) continue; - for (const [suffix, quota] of [ - ["quota", model.quotaInfo], - ["weekly", model.weeklyQuotaInfo], - ] as const) { - if (!quota) continue; - const window = quotaWindow( - `${family.toLowerCase()}-${suffix}`, - `${family} · ${suffix === "weekly" ? "Weekly" : "Reported quota"}`, - quota, - suffix === "weekly" ? "weekly" : "other", - suffix === "weekly" ? 7 * 24 * 60 : undefined, - ); - if (!window) continue; - const previous = windows.get(window.id); - if (!previous || window.usedPercent > previous.usedPercent) windows.set(window.id, window); - } - } - return [...windows.values()]; -} - -export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")(function* (input: { - readonly profileDirectory: string; - readonly authMethod: AntigravitySettings["authMethod"]; - readonly readKeyringSecret?: Effect.Effect; - /** The user's own CLI's app data folder, which holds its sign-in; the profile's when absent. */ - readonly appDirectory?: string; -}) { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const client = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk); - const crypto = yield* Digest.Digest; - const platform = yield* HostProcess.Platform; - const architecture = yield* HostProcess.Architecture; - const appDirectory = input.appDirectory ?? path.join(input.profileDirectory, "antigravity-acp"); - const tokenPath = path.join(appDirectory, "acp_token.json"); - const cliTokenPath = path.join(appDirectory, "antigravity-oauth-token"); - const readKeyringSecret = input.readKeyringSecret ?? readCliKeyringSecret(platform, architecture); - let cached: - | { fingerprint: string; account: AntigravityAccount; accessToken: string; expiresAt: number } - | undefined; - let generation = 0; - - const request = (request: HttpClientRequest.HttpClientRequest) => - client.execute(request).pipe( - Effect.provideService(FetchHttpClient.RequestInit, MANUAL_REDIRECT), - Effect.flatMap(HttpClientResponse.filterStatusOk), - Effect.flatMap((response) => response.json), - Effect.timeout("10 seconds"), - ); - const read = Effect.gen(function* () { - const startedGeneration = generation; - const checkedAt = DateTime.formatIso(yield* DateTime.now); - if (input.authMethod !== "oauth-personal" && input.authMethod !== "oauth-business") { - return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" }); - } - const now = yield* Clock.currentTimeMillis; - let accessToken: string; - let account: AntigravityAccount; - let projectId: string | undefined; - if (!(yield* fs.exists(tokenPath))) { - cached = undefined; - // T3's Google account profiles bypass the keyring, whose one entry every profile shares. - const stored = (yield* fs.exists(cliTokenPath)) - ? yield* fs.readFileString(cliTokenPath) - : input.authMethod === "oauth-business" || input.appDirectory !== undefined - ? yield* readKeyringSecret - : undefined; - if (stored === undefined) { - return makeUnavailableUsageLimits({ - checkedAt, - reason: "unsupported", - message: "Sign in with Google to see Antigravity limits.", - }); - } - const { token } = yield* decodeCliToken(stored); - if (!(Date.parse(token.expiry ?? "") > now + 60_000)) { - return makeUnavailableUsageLimits({ - checkedAt, - reason: "probeFailed", - message: - "Antigravity's saved sign-in has expired. Start an Antigravity turn to renew it, then refresh limits.", - }); - } - accessToken = token.access_token; - account = yield* request( - HttpClientRequest.get("https://www.googleapis.com/oauth2/v2/userinfo").pipe( - HttpClientRequest.setHeaders({ Authorization: `Bearer ${accessToken}` }), - ), - ).pipe( - Effect.flatMap(withAntigravityAccountEmail(antigravityAccountFingerprint)), - Effect.catch(() => sha256(`antigravity-cli\0${token.refresh_token || accessToken}`)), - ); - } else { - const token = yield* fs.readFileString(tokenPath).pipe(Effect.flatMap(decodeTokenFile)); - projectId = token.project_id; - const fingerprint = yield* sha256( - `${token.client_id}\0${token.refresh_token}\0${token.project_id ?? ""}`, - ); - if (cached?.fingerprint !== fingerprint || cached.expiresAt <= now + 60_000) { - cached = undefined; - const refreshed = yield* request( - HttpClientRequest.post("https://oauth2.googleapis.com/token").pipe( - HttpClientRequest.bodyUrlParams({ - client_id: token.client_id, - client_secret: token.client_secret, - refresh_token: token.refresh_token, - grant_type: "refresh_token", - }), - ), - ).pipe(Effect.flatMap(decodeTokenResponse)); - accessToken = refreshed.access_token; - // Use Google account IDs to merge accounts across environments; refresh tokens differ per machine. - account = yield* request( - HttpClientRequest.get("https://www.googleapis.com/oauth2/v2/userinfo").pipe( - HttpClientRequest.setHeaders({ Authorization: `Bearer ${accessToken}` }), - ), - ).pipe( - Effect.flatMap(withAntigravityAccountEmail(antigravityAccountFingerprint)), - Effect.orElseSucceed(() => fingerprint), - ); - if (generation === startedGeneration) { - cached = { - fingerprint, - account, - accessToken, - expiresAt: now + refreshed.expires_in * 1000, - }; - } - } else { - accessToken = cached.accessToken; - account = cached.account; - } - } - const endpoints = ENDPOINTS[input.authMethod]; - // Merge endpoints because quota groups differ; the metered host's reading of a bucket wins. - const fetchWindows = Effect.fn("AntigravityUsageProbe.fetchWindows")(function* ( - operation: string, - parse: ( - response: unknown, - requestedAt: number, - ) => Effect.Effect, - ) { - const responses = yield* Effect.forEach( - endpoints, - (endpoint) => - Effect.gen(function* () { - // Capture each request after auth, so refresh latency does not widen the tolerance. - const requestedAt = yield* Clock.currentTimeMillis; - return yield* request( - HttpClientRequest.post(`${endpoint}/v1internal:${operation}`).pipe( - HttpClientRequest.setHeaders({ - Authorization: `Bearer ${accessToken}`, - "User-Agent": antigravityUserAgent(platform, architecture), - }), - HttpClientRequest.bodyJsonUnsafe(projectId ? { project: projectId } : {}), - ), - ).pipe( - Effect.flatMap((response) => parse(response, requestedAt)), - Effect.orElseSucceed(() => []), - ); - }), - { concurrency: "unbounded" }, - ); - const windows = new Map(); - for (const window of responses.flat()) { - if (!windows.has(window.id)) windows.set(window.id, window); - } - return [...windows.values()]; - }); - const summary = yield* fetchWindows("retrieveUserQuotaSummary", antigravitySummaryWindows); - const windows = summary.length - ? summary - : yield* fetchWindows("fetchAvailableModels", (response) => - decodeModels(response).pipe(Effect.map(modelWindows)), - ); - if (windows.length === 0) { - return makeUnavailableUsageLimits({ - checkedAt, - reason: "probeFailed", - message: "Antigravity did not return usable quota information.", - }); - } - return { ...makeUsageLimits({ checkedAt, windows }), ...antigravityAccountFields(account) }; - }); - const probe = read.pipe( - Effect.provideService(Digest.Digest, crypto), - Effect.timeout("30 seconds"), - Effect.catch(() => - Effect.gen(function* () { - return makeUnavailableUsageLimits({ - checkedAt: DateTime.formatIso(yield* DateTime.now), - reason: "probeFailed", - message: "Could not read Antigravity limits. Refresh provider status to retry.", - }); - }), - ), - ); - return { - probe, - clear: Effect.sync(() => { - cached = undefined; - generation++; - }), - }; -}); diff --git a/apps/server/src/usage/cliproxyApi.ts b/apps/server/src/usage/cliproxyApi.ts index 2007002a5506..0639d00d692d 100644 --- a/apps/server/src/usage/cliproxyApi.ts +++ b/apps/server/src/usage/cliproxyApi.ts @@ -22,21 +22,9 @@ import { import { codexPlanLabel } from "../provider/CodexProvider.ts"; import { codexRateLimitsToLimits } from "../provider/codexUsageLimits.ts"; import { claudeUsageResponseToLimits } from "../provider/claudeUsageLimits.ts"; -<<<<<<< origin/main -import { - antigravityAccountFingerprint, - antigravitySummaryWindows, - antigravityUserAgent, -} from "../provider/antigravityUsageLimits.ts"; -import { - makeUnavailableUsageLimits, - makeUsageLimits, -} from "@t3tools/provider-core/server/usageLimits"; +import { makeUnavailableUsageLimits } from "@t3tools/provider-core/server/usageLimits"; import { withAccountReadAt } from "../fork/usageReadAt/usageReadAt.ts"; import * as ClaudeHub from "../fork/claudeUsageSource/claudeHub.ts"; -======= -import { makeUnavailableUsageLimits } from "@t3tools/provider-core/server/usageLimits"; ->>>>>>> upstream/main /** A hub with its management key already read from wherever the setting keeps it. */ export interface CliproxyHub { @@ -51,11 +39,7 @@ const AuthFile = Schema.Struct({ label: Schema.optional(Schema.String), email: Schema.optional(Schema.String), disabled: Schema.optional(Schema.Boolean), -<<<<<<< origin/main organization_uuid: Schema.optional(Schema.String), - project_id: Schema.optional(Schema.String), -======= ->>>>>>> upstream/main id_token: Schema.optional( Schema.Struct({ chatgpt_account_id: Schema.optional(Schema.String), diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 828768fc272c..360e392ff712 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -1092,11 +1092,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; -<<<<<<< origin/main - const { worktreesDir } = yield* ServerConfig.ServerConfig; -======= - const { stateDir, worktreesDir, worktreeCheckoutCacheDir } = yield* ServerConfig.ServerConfig; ->>>>>>> upstream/main + const { stateDir, worktreesDir } = yield* ServerConfig.ServerConfig; const isServerInternalPath = yield* makeIsServerInternalPath; const digest = yield* Digest.Digest; const random = yield* SecureRandom.SecureRandom; diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsx index 5294e66ab57e..abe54a987a52 100644 --- a/apps/web/src/components/RightPanelTabs.tsx +++ b/apps/web/src/components/RightPanelTabs.tsx @@ -1092,37 +1092,11 @@ function RightPanelTab( }} /> ) : ( -<<<<<<< origin/main - - { - if (surface.kind === "device" && props.canRename) onStartRename(surface.id); - }} - className="cursor-pointer flex min-w-0 items-center" - aria-label={ - sideChatState === null - ? undefined - : gt("{title}, {state}", { - title, - state: messages(SIDE_CHAT_STATE_LABELS[sideChatState]), - }) - } - > - {title} - - } - /> - - {surface.kind === "device" ? ( -======= { if (surface.kind === "device" && props.canRename) onStartRename(surface.id); }} @@ -1135,14 +1109,12 @@ function RightPanelTab( state: messages(SIDE_CHAT_STATE_LABELS[sideChatState]), }) } - onClick={() => onActivate(surface)} > {title} } label={ surface.kind === "device" ? ( ->>>>>>> upstream/main - !addSurfaceMenuOpen && document.querySelector(LAUNCHER_SHORTCUT_BLOCKING_LAYERS) !== null; - const onNewSurfaceKeyDown = useEffectEvent((event: KeyboardEvent) => { - if (event.defaultPrevented || event.isComposing) return; - if ( - resolveShortcutCommand(event, props.keybindings, { - context: { ...props.getShortcutContext(), rightPanelOpen: true }, - }) !== "rightPanel.new" - ) - return; - if (addSurfaceMenuBlocked()) return; - event.preventDefault(); - event.stopPropagation(); - if (!event.repeat) { - addSurfaceTriggerRef.current?.focus(); - setAddSurfaceMenuOpen(true); - } - }); - // Forwarded from a focused browser page. Focusing the trigger here would let ChatView's - // window-focus handler see a plain button and refocus the composer, closing the menu. - const onMenuAction = useEffectEvent((action: string) => { - if (action === "rightPanel.new" && !addSurfaceMenuBlocked()) setAddSurfaceMenuOpen(true); - }); - // Inside ChatView's split view, which owns the shell and the split menu entries. - const pane = useRightPanelPane(); - const takesNewSurfaceShortcut = props.open !== false && pane?.focused !== false; - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes document keydown and the desktop menu action (forwarded from a focused browser page) for the new surface shortcut while the panel is open - useEffect(() => { - if (!takesNewSurfaceShortcut) return; - document.addEventListener("keydown", onNewSurfaceKeyDown, true); - const unsubscribe = window.desktopBridge?.onMenuAction(onMenuAction); - return () => { - document.removeEventListener("keydown", onNewSurfaceKeyDown, true); - unsubscribe?.(); - }; - }, [takesNewSurfaceShortcut]); - -======= ->>>>>>> upstream/main const updateTabScrollState = (viewport: HTMLDivElement) => { const hasOverflow = viewport.scrollWidth - viewport.clientWidth > TAB_SCROLL_EDGE_TOLERANCE; const canScrollLeft = hasOverflow && viewport.scrollLeft > TAB_SCROLL_EDGE_TOLERANCE; @@ -1354,12 +1284,11 @@ export function RightPanelTabs(props: RightPanelTabsProps) { }, ] : []), -<<<<<<< origin/main ...(props.modeSurfaceActions ?? []), ] as const); -======= - ] as const; - const canAddSurface = addSurfaceActions.some((action) => action.available); + // A menu whose items Settings > Right panel all hid still opens, to point there. + const canAddSurface = + addSurfaceActions.length === 0 || addSurfaceActions.some((action) => action.available); if ((props.open === false || !canAddSurface) && addSurfaceMenuOpen) setAddSurfaceMenuOpen(false); @@ -1386,17 +1315,19 @@ export function RightPanelTabs(props: RightPanelTabsProps) { const onMenuAction = useEffectEvent((action: string) => { if (action === "rightPanel.new" && !addSurfaceMenuBlocked()) setAddSurfaceMenuOpen(true); }); + // Inside ChatView's split view, which owns the shell and the split menu entries. + const pane = useRightPanelPane(); + const takesNewSurfaceShortcut = props.open !== false && canAddSurface && pane?.focused !== false; // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes document keydown and the desktop menu action (forwarded from a focused browser page) for the new surface shortcut while the panel is open and can add a surface useEffect(() => { - if (props.open === false || !canAddSurface) return; + if (!takesNewSurfaceShortcut) return; document.addEventListener("keydown", onNewSurfaceKeyDown, true); const unsubscribe = window.desktopBridge?.onMenuAction(onMenuAction); return () => { document.removeEventListener("keydown", onNewSurfaceKeyDown, true); unsubscribe?.(); }; - }, [props.open, canAddSurface]); ->>>>>>> upstream/main + }, [takesNewSurfaceShortcut]); const handleAddSurfaceMenuKeyDown = (event: ReactKeyboardEvent) => { const action = surfaceShortcutActionForKey(addSurfaceActions, event.nativeEvent); diff --git a/apps/web/src/components/chat/MarkdownThreadLink.tsx b/apps/web/src/components/chat/MarkdownThreadLink.tsx index 01ed90a37e39..064bb2668205 100644 --- a/apps/web/src/components/chat/MarkdownThreadLink.tsx +++ b/apps/web/src/components/chat/MarkdownThreadLink.tsx @@ -97,50 +97,6 @@ export function MarkdownThreadLink(props: { title: knownTitle, }; return ( -<<<<<<< origin/main - - - startPanelOnlyDrag( - event, - threadChipPanelLink({ - threadRef: props.threadRef, - target: { kind: "linked", target: linkedTarget }, - }), - ) - } - {...trigger( - (intent) => - openLinkedThreadRead({ - panelRef, - target: linkedTarget, - intent, - navigate, - }), - // Outside a thread there is no panel to read it in. - { panel: panelRef !== null }, - )} - /> - } - aria-label={gt("Thread, {title}", { title })} - > - - {title} - - } - /> - - {gt("Read the thread on {label}", { label: linkedLabel })} - - -======= + startPanelOnlyDrag( + event, + threadChipPanelLink({ + threadRef: props.threadRef, + target: { kind: "linked", target: linkedTarget }, + }), + ) + } {...trigger( (intent) => openLinkedThreadRead({ panelRef, - target: { - viaEnvironmentId: props.environmentId, - ...writtenRef, - label: linkedLabel, - title: knownTitle, - }, + target: linkedTarget, intent, navigate, }), @@ -174,7 +135,6 @@ export function MarkdownThreadLink(props: { } label={gt("Read the thread on {label}", { label: linkedLabel })} /> ->>>>>>> upstream/main ); } if (missing && resolved === null) { diff --git a/apps/web/src/components/chat/TimelineAssistantRows.tsx b/apps/web/src/components/chat/TimelineAssistantRows.tsx index 907ae5c58780..943821b4bbbb 100644 --- a/apps/web/src/components/chat/TimelineAssistantRows.tsx +++ b/apps/web/src/components/chat/TimelineAssistantRows.tsx @@ -23,13 +23,10 @@ import { readThreadTurnItems } from "../../state/entities"; import { useV2ItemSupport } from "../../state/v2ItemSupport"; import { TimelineRowCtx, TimelineRowActivityCtx, type TimelineRow } from "./timelineRowContext"; import { MESSAGE_HEADING_LEVEL, MessageAuthorHeading } from "./TimelineRowParts"; -<<<<<<< origin/main import { SubThreadMetaReply, SubThreadReplyLine } from "../../fork/subThreads/SubThreadReplyLine"; import { AgentMessageDivider } from "../../fork/displayMode/AgentMessageDivider"; import { EditedMark } from "../../fork/displayMode/EditedMark"; -======= import { SharedTooltipTrigger } from "../ui/shared-tooltip"; ->>>>>>> upstream/main export function AssistantTimelineRow({ row }: { row: Extract }) { const ctx = use(TimelineRowCtx); @@ -249,33 +246,22 @@ function AssistantMessageMeta({ ) : null} {!message.streaming && ( -<<<<<<< origin/main - - }> - {formatDayAwareTimestamp( - message.editedAt ?? message.updatedAt, - ctx.timestampFormat, - undefined, - undefined, - m, - )} - - - {formatChatTimestampTooltip( - message.editedAt ?? message.updatedAt, - ctx.timestampFormat, - m, - )} - - -======= } - label={formatChatTimestampTooltip(message.updatedAt, ctx.timestampFormat, m)} + label={formatChatTimestampTooltip( + message.editedAt ?? message.updatedAt, + ctx.timestampFormat, + m, + )} > - {formatDayAwareTimestamp(message.updatedAt, ctx.timestampFormat, undefined, undefined, m)} + {formatDayAwareTimestamp( + message.editedAt ?? message.updatedAt, + ctx.timestampFormat, + undefined, + undefined, + m, + )} ->>>>>>> upstream/main )} diff --git a/apps/web/src/components/files/VirtualTablePreview.tsx b/apps/web/src/components/files/VirtualTablePreview.tsx index ac486006f10a..0967c3a355a3 100644 --- a/apps/web/src/components/files/VirtualTablePreview.tsx +++ b/apps/web/src/components/files/VirtualTablePreview.tsx @@ -3,11 +3,8 @@ import { useEffect, useEffectEvent, useLayoutEffect, useRef, useState } from "re import { useClientSettings } from "~/hooks/useSettings"; import { observeResize } from "~/lib/observeResize"; import { PREVIEW_PAGE_ROWS } from "./largeTextProtocol"; -<<<<<<< origin/main import { announceViewer } from "./fileReadingPlace"; -======= import { SharedTooltipTrigger } from "~/components/ui/shared-tooltip"; ->>>>>>> upstream/main export default function VirtualTablePreview(props: { readonly name: string; diff --git a/apps/web/src/fork/rightPanelMenu/allHiddenAddMenu.browser.test.tsx b/apps/web/src/fork/rightPanelMenu/allHiddenAddMenu.browser.test.tsx new file mode 100644 index 000000000000..e031189fc86f --- /dev/null +++ b/apps/web/src/fork/rightPanelMenu/allHiddenAddMenu.browser.test.tsx @@ -0,0 +1,77 @@ +import "~/index.css"; + +import { EnvironmentId } from "@t3tools/contracts"; +import { describe, expect, it, vi } from "vite-plus/test"; +import { page, userEvent } from "vite-plus/test/browser"; + +import { RightPanelTabs, type RightPanelTabsProps } from "~/components/RightPanelTabs"; +import type { RightPanelSurface } from "~/rightPanelStore"; +import { render } from "../../../test/render"; + +// A board host whose Settings > Right panel hides every item of the "+" menu. +vi.mock("./rightPanelMenu", async (importActual) => ({ + ...(await importActual()), + useArrangedSurfaceActions: () => [], +})); + +const DIFF_SURFACE: RightPanelSurface = { id: "diff", kind: "diff" }; + +function tabs() { + const noop = () => {}; + const props: RightPanelTabsProps = { + mode: "inline", + keybindings: [], + getShortcutContext: () => ({ + terminalFocus: false, + terminalOpen: false, + previewFocus: false, + previewOpen: true, + isWeb: true, + isDesktop: false, + }), + surfaces: [DIFF_SURFACE], + environmentId: EnvironmentId.make("environment-local"), + activeSurfaceId: DIFF_SURFACE.id, + pendingSurfaceIds: new Set(), + previewSessions: {}, + desktopByTabId: {}, + terminalLabelsById: new Map(), + onActivate: noop, + onCloseSurface: noop, + onCloseOtherSurfaces: noop, + onCloseSurfacesToRight: noop, + onCloseAllSurfaces: noop, + onCopyFilePath: noop, + onAddBrowser: noop, + onAddBrowserInProfile: noop, + onAddTerminal: noop, + onAddDiff: noop, + onAddFiles: noop, + onAddPullRequest: noop, + onAddPullRequests: noop, + onAddDevice: noop, + browserAvailable: true, + terminalAvailable: true, + diffAvailable: true, + filesAvailable: true, + pullRequestAvailable: true, + pullRequestsAvailable: true, + deviceAvailable: true, + open: true, + children: null, + }; + return ; +} + +describe("add surface menu with every item hidden", () => { + it("keeps the + button, whose menu points to the settings that hid the items", async () => { + await using screen = await render(tabs()); + const addButton = screen.getByRole("button", { name: "Add panel surface" }); + + await expect.element(addButton).toBeInTheDocument(); + await userEvent.click(addButton); + await expect + .element(page.getByRole("menuitem", { name: /All items are hidden/ })) + .toBeVisible(); + }); +}); diff --git a/apps/web/src/hooks/useThreadActionMenu.ts b/apps/web/src/hooks/useThreadActionMenu.ts index 7777c13cb4c3..f5a8b1856994 100644 --- a/apps/web/src/hooks/useThreadActionMenu.ts +++ b/apps/web/src/hooks/useThreadActionMenu.ts @@ -157,55 +157,11 @@ export function useThreadActionMenu(input: { snoozePresets, canShareWithGuest, canTurnIntoProject: canTurnThreadIntoProject(threadRef), + displayModeItems: displayModeMenuItems(threadRef), }); const run = async (action: ThreadActionMenuId) => { const api = readLocalApi(); if (!api) return; -<<<<<<< origin/main - const thread = readThreadShell(threadRef); - if (!thread) { - failureToast( - m(msg("Thread actions unavailable")), - new Error(m(msg("This thread has not loaded yet."))), - ); - return; - } - const now = new Date(); - const configLoaded = readEnvironmentServerConfigLoaded(threadRef.environmentId); - const supports = { - settlement: configLoaded, - autoSettleOptOut: readEnvironmentSupportsAutoSettleOptOut(threadRef.environmentId), - snooze: configLoaded, - pinning: configLoaded, - titleRegeneration: configLoaded, - }; - const isRegeneratingTitle = thread.titleRegeneration != null; - const snoozePresets = resolveSnoozePresets(now, timestampFormat, threadRef.environmentId); - const items = buildThreadActionMenuItems({ - canOperate: readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope), - canTriage: threadTriagePermitted(threadRef.environmentId), - canFind: onFind !== undefined, - branch: thread.branch ?? null, - projectFilter: null, - isPinned: thread.pinnedAt != null, - isSettled: supports.settlement && thread.settledOverride === "settled", - autoSettleEnabled: thread.autoSettleDisabledAt == null, - isSnoozed: supports.snooze && effectiveSnoozed(thread, { now: now.toISOString() }), - canSnoozeNow: canSnooze(thread, { now: now.toISOString() }), - isRegeneratingTitle, - isRunning: !threadRuntimeCanArchive(thread.runtime), - hasCompletedRun: thread.latestRun?.completedAt != null, - supports, - snoozePresets, - canShareWithGuest, - canTurnIntoProject: canTurnThreadIntoProject(threadRef), - displayModeItems: displayModeMenuItems(threadRef), - }); - const clicked = await settlePromise(() => api.contextMenu.show(items, position, source)); - if (clicked._tag === "Failure" || clicked.value === null) return; - const action: ThreadActionMenuId = clicked.value; -======= ->>>>>>> upstream/main if ( threadActionRequiresOperate(action) && !(isThreadTriageAction(action) diff --git a/apps/web/src/state/threads.ts b/apps/web/src/state/threads.ts index 6b764601a47c..cc6368ecf727 100644 --- a/apps/web/src/state/threads.ts +++ b/apps/web/src/state/threads.ts @@ -35,14 +35,10 @@ export const threadEnvironment = createThreadEnvironmentAtoms( threadFamilies.snapshotAtom, environmentShell.statusAtom, ); -<<<<<<< origin/main const environmentThreads = displayModeThreadStates( createEnvironmentThreadStateAtoms(connectionAtomRuntime), ); -======= -const environmentThreads = createEnvironmentThreadStateAtoms(connectionAtomRuntime); export const environmentThreadStateAtom = environmentThreads.stateAtom; ->>>>>>> upstream/main export const environmentThreadDetails = createEnvironmentThreadDetailAtoms( environmentThreads.stateAtom, ); diff --git a/docs/user/appearance.md b/docs/user/appearance.md index 9d21ff26811c..62df62b2a3cf 100644 --- a/docs/user/appearance.md +++ b/docs/user/appearance.md @@ -16,24 +16,11 @@ Git-backed projects show branch and worktree controls below the composer before ## Math -<<<<<<< origin/main -Messages and Markdown previews typeset LaTeX on web, desktop, and mobile. Math is read from -`$…$`, `$$…$$`, `\(…\)`, and `\[…\]`, outside of code. -Fenced `math` blocks also render. Formulas work in tables, including absolute-value bars. -Dollar amounts such as `$5 and $10` stay text; write `\$` to keep any other dollar sign literal. -Wide formulas scroll horizontally while the surrounding text wraps. Copying a formula or -exporting a table preserves the TeX. - -The composer keeps TeX source editable, including when rich text is enabled. To show the TeX -source instead, turn off **Render math** in **Settings → Appearance**. The preference is saved -separately on each device. -======= -Turn on **Settings → Appearance → Render math** (per device) to render LaTeX in messages and Markdown previews on web, desktop, and mobile. +Messages and Markdown previews render LaTeX by default on web, desktop, and mobile. **Settings → Appearance → Render math** is on by default and saved on each device. Turn it off to show the TeX source instead. - Supports `$…$`, `$$…$$`, `\(…\)`, `\[…\]`, and fenced `math` blocks outside of code. - Currency like `$5 and $10` stays plain text; use `\$` to escape other literal dollar signs. - Copying a formula or exporting a table preserves the raw TeX. The composer keeps TeX source editable. ->>>>>>> upstream/main ## Motion diff --git a/docs/user/outside-agents.md b/docs/user/outside-agents.md index 0d66b26ea4ad..7135ff2aeebd 100644 --- a/docs/user/outside-agents.md +++ b/docs/user/outside-agents.md @@ -52,34 +52,6 @@ t3 thread user-view "$id" --sub-thread 51c0de t3 thread list ``` -<<<<<<< origin/main -`.` means the project that contains the current folder, or a git worktree of -its repository; a project id also works. A new thread uses the project's -default model and permission mode, and runs in the project folder unless you -pass `--worktree `. Its title is the message's first line, or -`--title`; add `--generate-title` to have it named from the message, as threads -started in the app are. `send` never interrupts: a busy thread gets the message -as its next turn. Pass `-` as the message to read it from stdin. - -To choose the model, pass `--provider --model `. Add -`--option id=value` for each model option. For reasoning effort, Codex uses -`--option reasoningEffort=high`, while Claude uses `--option effort=high`. -Option ids and allowed values depend on the provider and model; use those -reported by `orchestrator_capabilities`. `true` and `false` set on/off options. - -`user-view` prints a Chat mode thread word for word as your screen shows it: the latest main-list messages, or -with `--sub-thread`, a sub-thread and the three main-list messages before it. - -`--wait` prints the agent's reply. It exits 1 when the run fails or stops, and -2 when the agent waits for an answer you give in the app. Add `--json` for a -result that always includes the thread id. - -## Remove an agent - -Approved agents appear under **Settings → Sharing & access** like other clients. -Revoke one there to cut off its access immediately. A sign-in lasts 30 days; -after that the agent asks you to approve it again. -======= - Pass `--worktree `, `--title` / `--generate-title`, `--provider --model `, `--option id=value` (e.g. `reasoningEffort=high` for Codex, `effort=high` for Claude), or `-` to read the prompt from stdin. +- `user-view` prints a Chat mode thread word for word as your screen shows it. It prints the latest main-list messages, or with `--sub-thread`, a sub-thread and the three main-list messages before it. - `--wait` prints the reply and exits `1` on failure/stop or `2` when waiting for user input. Add `--json` for structured output including the thread ID. ->>>>>>> upstream/main diff --git a/docs/user/project-settings.md b/docs/user/project-settings.md index 8a047872b086..9ec50130b1f9 100644 --- a/docs/user/project-settings.md +++ b/docs/user/project-settings.md @@ -31,239 +31,21 @@ Configure worktrees in **Settings → Worktrees** (environment default or projec - **Submodules** (under Advanced): Defaults to recursive checkout; set to **Top level only** or **Skip** (or `"worktreeSubmodules"` in `t3.json`) for repos with heavy nested submodules. - **Sparse checkout**: Set `"worktreeSparsePatternsPath"` in `t3.json` to a repo-relative file of Git sparse-checkout patterns (non-cone syntax; requires Git 2.35+; enables `extensions.worktreeConfig`). Set Submodules to **Skip** if you don't want submodules initialized under excluded paths. - **Worktree location** (per machine): Set an absolute path (e.g. `D:\worktrees` or `~/worktrees`) to store new worktrees elsewhere. Existing worktrees stay where they are; cleanup covers both folders. -- **Fast worktree checkout (macOS beta)**: Enable **Settings → Labs → Fast worktree checkout** (Git 2.42+) to clone new worktrees via APFS copy-on-write from a local cache. Falls back to normal checkout for cross-drive paths, sparse checkouts, or Git LFS/filter repos. +- **Fast worktree checkout (macOS beta)**: Enable **Settings → Labs → Fast worktree checkout** (Git 2.42+) to clone new worktrees via APFS copy-on-write from a local cache. Falls back to normal checkout for cross-drive paths, sparse checkouts, Git LFS/filter repos, or a cache folder that is a link to another folder. +- **Reflink worktrees (Linux)**: **Settings → Worktrees → Reflink worktrees** is on by default for each Linux machine. On drives with copy-on-write clones (reflinks, such as Btrfs or XFS formatted with reflink support), T3 Code keeps a few recent checkouts of each repository on that drive and clones new worktrees from them. Worktrees share disk space until their files change. + - **Cache**: Stored in a hidden `.t3-checkout-cache` folder inside the worktree location, or in the `caches` folder of the T3 home when the default location is on the same drive. Changing the location deletes the old location's cache, and turning the setting off deletes the cache. When several T3 homes share a worktree location, each home also deletes another home's cache there once it has not been used for 30 days. + - **Limits and dependencies**: Drives that cannot clone, such as ext4, use Git's normal checkout and keep no cache. The other limits of fast worktree checkout on macOS apply too. Dependencies such as `node_modules` are not cached. A package manager that clones from a store on the same drive, such as pnpm with `package-import-method=clone-or-copy`, shares them the same way. ### Storage cleanup Enable automatic cleanup in **Settings → Worktrees → Cleanup** (off by default; runs on startup, on change, and hourly). Projects can set **Automatic worktree cleanup** to **Inherit**, **Off**, or **Custom**. -<<<<<<< origin/main -Under **Destination**, choose where runs go. **New thread each run** keeps every -run separate. The two one-thread choices start a thread on the first run and post -later runs there: one continues the same conversation, the other starts each run -in a fresh session that doesn't see earlier runs, so the thread stays readable -without the agent's context growing. To move a one-thread task, pick another -thread in its project under **Destination**. Moving such a task to another -project starts a new thread there on its next run. - -Deleting a thread also deletes tasks that post into that thread. Tasks that start -a new thread on each run survive deletion of their previous threads. -An archived thread refuses messages, so a task that posts into one stays on and fails -each run until you unarchive the thread or pick another destination. To set a task's thread -aside without breaking it, settle the thread; see [Settle or archive](thread-sidebar.md#settle-or-archive). - -You can edit, pause, resume, run immediately, or delete a task from the list. -Webhook tasks only run when their URL is called, so they can't be run -immediately. -Leaving an edited form asks before discarding unsaved changes. - -## Webhook automations - -In **Settings → Scheduled tasks**, choose **On webhook** -as a task's schedule to run it whenever another service calls its URL, such as -GitHub on a new pull request or a CI job that failed. A public URL needs a -[T3 Connect](remote-access.md) managed tunnel; after you save the task, copy -its URL from the editor. Without one, the editor shows only the URL's path. -**Rotate** replaces the URL and the old one stops working. - -The prompt decides what the agent sees. Placeholders pull values out of the -request: `{{body.path}}` for a JSON or form field, `{{headers.name}}`, -`{{query.name}}`, `{{body}}` for the raw body, and `{{request}}` for everything. -For example, `Review this PR: {{body.pull_request.html_url}}` sends only the -pull request link. A placeholder with no value is left empty. - -Each value reaches the agent wrapped in `` tags and marked as -untrusted request data. This helps the agent tell it apart from your -instructions, but it doesn't guarantee the agent ignores what the text says. -Inside a value, every `$`, other currency sign and `@`, and a `/` that starts -a lone word, gets an invisible character after it, so mentions like `$skill`, -`@file` and `/command` don't act. Text copied from a value, such as an email -address or a command, carries that character too. Without a signature, anyone -with the URL can start a run with any content. A signature only proves which -service sent the request: a GitHub payload still carries text written by any -GitHub user. - -For GitHub, turn on **Require signature**, keep the header -`x-hub-signature-256`, hex encoding and the `sha256=` prefix, and enter the -same secret in the repository's webhook settings with content type -`application/json`. Requests without a valid signature are rejected. Set this -up on desktop or web; mobile keeps an existing signature check but can't turn -one on. - -To run only for some requests, add **Filters**. Each one tests a value named -like a placeholder, without the braces, such as `headers.x-github-event` equals -`pull_request` or `body.action` is one of `opened, reopened`. A task runs only -when every filter matches; other requests are answered normally, logged as -**Filtered** with the first filter that failed, and start nothing. Values -compare as text, and a value that is an object or a list only passes -**exists**. Separate **is one of** values with commas; a value can't contain -a comma or start or end with a space. - -To suppress repeated deliveries, set a **Duplicate request key** template, such as -`{{headers.delivery-id}}`. The same key is ignored for seven days per task. -To combine a burst, set a **Coalesce key**, such as `{{body.id}}`, and a window -of 10–3600 seconds (120 by default). One run uses the latest body, headers, -and query when the window from the first delivery closes; later requests -do not extend it. Pending windows survive a server restart. Keys must contain -request placeholders; if any placeholder is missing, or the render is empty, -that key's rule is skipped. Clear the templates to turn dedupe off. - -Duplicate and coalesced log entries share a limit of 10 per task per minute. -Additional deliveries are accepted without a log entry, and coalesced deliveries -always replace the persisted payload. Coalesced updates count toward a separate -60-per-minute validation limit; exceeding it receives HTTP 429. - -On desktop and web, pick **Deliveries** from a task's menu to see recent -requests and the prompt each one produced. - -If the environment is offline, the sender gets an error and nothing runs; -redeliver from the sender, such as GitHub's **Recent Deliveries**, once it is -back. To have T3 Connect keep requests instead, turn on **Hold webhooks while -offline** in **Settings → Sharing & access**. T3 Connect then stores requests to a -T3 Connect URL for up to 24 hours and delivers them when the environment -returns. Leave it off if you don't want request bodies stored outside your -machine. To skip requests that waited too long, set **Skip requests older -than** on the task. - -## Defaults and inheritance - -Threads contains the model and workspace for new threads. Browser controls agent browser -access. Source control & issues contains automatic pull, the default pull request merge method and text -generation. The same rows edit environment defaults or project overrides depending on the -project crumb. - -The Projects category, under Code, holds the project's name, icon, actions, -checkouts and removal. Actions belong to a project: editing them creates the project's own list -on each selected environment, and reset returns to the environment's shared list. A project's -`t3.json` actions can be imported there. When a project has several checkouts on one environment, -choose one in the scope line at the top to see or change only that checkout's settings. - -Settings a repository can also declare in `t3.json`, such as the workspace for new threads, -resolve in one order: a project override, then the environment setting, then `t3.json`, then the -built-in default. Leave a setting on **Inherit** to let the next tier decide. -Browser access changes apply when an agent session next starts. - -New worktrees initialize git submodules recursively. If that step is slow because the repository -declares many nested submodules, set **Submodules** in **Settings → Worktrees** under Advanced (with the project -selected to override it there) to **Top level only** to stop at the ones the repository declares -itself, or **Skip** to leave them for a setup script. It resolves in the same order as the -workspace default: a `"worktreeSubmodules"` value in the `t3.json` of the branch being checked out -applies when the project and environment are both on **Inherit**. - -New worktrees check out every file. For a large repository, set `"worktreeSparsePatternsPath"` in -`t3.json` to a repository-relative file of git sparse-checkout patterns in non-cone syntax. New -worktrees then check out only the matching files, before any other file is written. Both files are -read from the branch being checked out, so the patterns can leave out `t3.json` and `.gitmodules`. -If the pattern file is missing, creating the worktree fails instead of checking out everything. -Submodules still follow **Submodules** above, also under excluded paths; set it to **Skip** to leave -them empty. The first sparse worktree turns on Git's `extensions.worktreeConfig` for the repository. -This needs Git 2.35 or newer. - -## Worktree location - -New worktrees go in the `worktrees` folder of the T3 home directory. To put them somewhere else, -such as another drive, set **Settings → Worktrees → Worktree location** to an absolute path like -`D:\worktrees` or `~/worktrees`. The setting is per machine. Existing worktrees stay where they -are, and cleanup covers both the default folder and the custom one. - -## Fast worktree checkout on macOS - -Fast worktree checkout is a beta. Turn it on for each Mac in **Settings → Labs → Fast worktree -checkout**. T3 Code then keeps a few recent checkouts of each repository in the `caches` folder of -the T3 home directory. A new worktree is cloned from one of them with APFS copy-on-write, which is -about twice as fast as writing every file and makes the first `git status` in it fast as well. -Turning it off deletes the cache. - -The first worktree of a repository uses Git's normal checkout and fills the cache. It needs Git 2.42 -or newer. Git's normal checkout is also used for worktrees on a different drive from the T3 home -directory, sparse checkouts, repositories whose attributes use filters such as Git LFS, and -repositories whose checkout settings changed. A cache folder that is a link to another folder is -not used, and worktrees then use Git's normal checkout. - -## Reflink worktrees on Linux - -**Settings → Worktrees → Reflink worktrees** is on by default for each Linux machine. Where the -worktree location's drive supports copy-on-write clones (reflinks, as on Btrfs or XFS formatted with -reflink support), T3 Code keeps a few recent checkouts of each repository on that drive and clones new -worktrees from them. Worktrees then share disk space until their files change. The cache is a -hidden `.t3-checkout-cache` folder inside the worktree location, or the `caches` folder of the T3 -home directory when the default location is on the same drive. Changing the location deletes the -old location's cache, and turning the setting off deletes the cache. When several T3 homes share a -worktree location, each one also deletes another home's cache there once it has not been used for -30 days. - -On drives that cannot clone, such as ext4, worktrees use Git's normal checkout and no cache is kept. -The other limits of fast worktree checkout on macOS apply too. Dependencies such as `node_modules` -are not cached; a package manager that clones from a store on the same drive, such as pnpm with -`package-import-method=clone-or-copy`, shares them in the same way. - -## Storage cleanup - -Open **Settings → Worktrees → Cleanup** to enable automatic cleanup on one machine or all connected -environments. Policies are off by default and run on the server at startup, when changed, and -hourly. Offline machines keep their existing policies. - -Select a project to set **Automatic worktree cleanup** to **Inherit**, **Off**, or **Custom**. -Inherit follows each machine's rules; Off keeps that project's worktrees until you remove them -manually. Custom applies separate worktree rules to the selected project or checkout. Browser -captures and log retention remain machine-wide. - -Worktrees can be removed after a chosen number of inactive days, after a thread settles, after -merging, or when they have no commits beyond the default branch and their thread is settled or -archived. Set settled retention to 0 days to remove a worktree at the next cleanup after -settlement. In repositories without remotes, -unchanged-worktree cleanup compares against the branch checked out in the project workspace; -if that checkout has a detached HEAD, the worktree is kept. Only T3-managed worktrees are eligible. -Active sessions and shared worktrees prevent removal. **Keep worktrees with local changes** defaults -to **Uncommitted changes**, which protects tracked edits and untracked files but deletes ignored -files such as `.env` and build output. **Any local files** also protects ignored files other than -`node_modules`. **Edited tracked files** protects only tracked edits and allows untracked and -ignored files to be deleted. Branches and thread history stay; starting another turn recreates the checkout. -Merge cleanup requires a merged pull request whose commits are included in the remote default -branch. A squash or rebase merge on GitHub also counts when the pull request targeted the default -branch and the worktree is still at the pull request's last commit. - -Enable **Delete worktrees with deleted threads** to remove safe worktrees after their last -thread is deleted, including archived threads and worktrees left by earlier deletions. The -server waits for sessions and terminals to stop and retries skipped worktrees after restart. -Existing prompts for deleting a worktree manually remain available when this policy is off. - -Choose **Delete now** to run the enabled rules immediately. The latest results show which -worktrees were removed or kept and why, plus any failures. -Results also list folders in the worktree folder that no thread uses, with their sizes; cleanup never removes them, so remove them manually if you want. - -The inactive and settled retention periods also apply to the folders of -[threads without a project](./thread-sidebar.md#start-without-a-project). Those folders are not -Git repositories, so their files are deleted with them and cannot be recovered; the thread stays, -and its next turn starts in a new, empty folder. A folder is kept when it has a Git repository -anywhere inside it or when its thread has an enabled scheduled task. Every file in such a folder -counts as untracked, so only **Edited tracked files** removes a folder that holds anything other -than `node_modules`; the other two rules remove only empty folders. Folders that no thread uses -are listed here too. - -Browser captures and rotated logs have separate retention periods. Expired capture links stop -working. Current logs, message attachments, and browser profiles are kept. - -## Project icons - -Select the project and open Project to choose an icon, emoji, monogram, or image. The choice applies to -every checkout in the project group and appears on connected clients. Choose **Automatic** to let -T3 Code detect an icon again. - -Choose **Monogram** in the icon picker to set one or two letters or numbers and a color. - -When no image is found, web and desktop show a two-character monogram with a color -from the icon palette, derived from the saved project name. For example, `Nebula` becomes `NA`, -`Silver Orchard` becomes `SO`, and `M7 Forge` becomes `M7`. A name that starts with a Chinese, -Japanese, or Korean character uses only that character, so `健康顾问` becomes `健`. -======= - **Triggers**: Inactive days, days after settlement (`0` = next cleanup), merged PRs (including GitHub squash/rebase merges into the default branch), or settled/archived threads with no commits beyond the default branch. - **Safety**: Active sessions and shared worktrees are never removed. **Keep worktrees with local changes** defaults to **Uncommitted changes** (protects tracked edits and untracked files; removes ignored files like `.env`/build output). Choose **Any local files** (also protects ignored files except `node_modules`) or **Edited tracked files** (protects tracked edits only). - **Delete with deleted threads**: Enable **Delete worktrees with deleted threads** to automatically clean up safe worktrees once their last thread is deleted. - **Scratch folders**: Inactive and settled rules also apply to [no-project scratch folders](./thread-sidebar.md#start-without-a-project) (skipped if they contain a Git repo or enabled scheduled task). Because scratch files aren't in Git, deleted files cannot be recovered. - **Manual run**: Click **Delete now** to run rules immediately and inspect what was removed, kept, or orphaned (untracked folders are listed but never auto-deleted). - **Captures and logs**: Browser captures and rotated logs have separate machine-wide retention periods. ->>>>>>> upstream/main ## Keep the default branch current diff --git a/docs/user/providers-antigravity.md b/docs/user/providers-antigravity.md index 51c67623dd16..91ee6398455f 100644 --- a/docs/user/providers-antigravity.md +++ b/docs/user/providers-antigravity.md @@ -1,13 +1,6 @@ # Antigravity -<<<<<<< origin/main -T3 Code runs Google's official Antigravity ACP agent on your selected environment. -T3 manages its own CLI installation and sign-in, separate from your terminal or IDE, unless you -[use your own Antigravity CLI](#use-a-manual-installation). Google controls -which models and account access are available through this agent. -======= -T3 Code runs Google's official Antigravity ACP agent on your selected environment, with a T3-managed CLI installation and sign-in separate from your terminal or IDE. ->>>>>>> upstream/main +T3 Code runs Google's official Antigravity ACP agent on your selected environment, with a T3-managed CLI installation and sign-in separate from your terminal or IDE, unless you [use your own Antigravity CLI](#manual-binary). ## Set up Antigravity @@ -16,7 +9,6 @@ T3 Code runs Google's official Antigravity ACP agent on your selected environmen 3. Click **Sign in** and complete browser sign-in. Wait for T3 Code to confirm access and load models. (Once installed, you can also sign in from mobile.) - **Remote sign-in**: Paste the temporary code (or full URL) from Google's completion page into T3 Code's code field. -- **Manual binary**: Install [Antigravity CLI](https://antigravity.google/docs/getting-started) and set **Binary path** to `agy`. Leave blank to use the managed runtime (or `PATH`). - **Updates**: Click **Update Antigravity** in provider settings. T3 Code requires Antigravity **1.5+** (1.5.12+ recommended); running threads finish on their original runtime. ### Sign-in methods @@ -32,99 +24,24 @@ Choose **Sign-in method** in the Antigravity instance settings: API keys are stored outside `settings.json`, and ambient `GEMINI_API_KEY` / Google env vars do not override the instance's configured method. +### Manual binary + +Install [Antigravity CLI](https://antigravity.google/docs/getting-started) and set **Binary path** to `agy` (to find it on `PATH`) or to a full path. Leave **Binary path** blank to use the managed runtime (or `PATH`). + +When **Binary path** names your own `agy` of Antigravity CLI 1.5 or later: + +- **Shared profile and login**: The instance has no private profile. The agent uses the CLI's own Google login, settings, and state folder (`~/.gemini/antigravity-cli`), so sign in with `agy` on the environment first. Every instance that uses it shares that login, and its sessions are stored with the CLI's own. +- **Tool permissions**: The CLI's tool-permission setting decides whether it asks before a tool call. When it asks, T3 Code answers by the thread's [permission mode](./permission-modes.md). When the CLI is set to always proceed, tools run without asking in every mode. +- **Generated text**: T3 Code does not use the CLI for titles, commit messages, or other generated text while `~/.gemini/config` holds hooks or MCP servers, because they would run in those helper sessions too. Select another model for generated text. + ## Models, planning, and goals -<<<<<<< origin/main -| Method | Credentials | -| -------------------------- | -------------------------------------------------------------------------------------------- | -| Google account | Personal Google sign-in in the browser | -| Gemini Enterprise | Browser sign-in, GCP project, and GCP location | -| Gemini API key | API key; choose Connect without a browser | -| Agent Platform / Vertex AI | API key, or GCP project and location with Application Default Credentials on the environment | - -The environment stores the Antigravity API key outside its settings file, and -clients only see whether one is saved. The agent uses the method and credentials selected for this instance; -ambient `GEMINI_API_KEY` and Google credential variables do not override them. -Changing the method stops the instance's sessions. Sign out before replacing an -account. - -## Runtime installation - -Managed installation supports Apple Silicon and Intel macOS, Linux x64 or ARM64 -with glibc or musl, and Windows x64 or ARM64. Allow at least 1.25 GiB of free disk -space for downloading and staging an update. - -### Use a manual installation - -Install [Antigravity CLI](https://antigravity.google/docs/getting-started) on the environment. -Set **Binary path** to its `agy` executable and update it yourself. -Leave the field blank to use the managed runtime, or a compatible executable on -`PATH` if no managed runtime is installed. - -When **Binary path** names your own `agy` of Antigravity CLI 1.5 or later (a full -path, or `agy` to find it on `PATH`), the instance has no private profile. The agent uses the CLI's own Google login, settings, and state -folder (`~/.gemini/antigravity-cli`), so sign in with `agy` on the environment -first. Every instance that uses it shares that login, and its sessions are stored -with the CLI's own. - -The CLI's tool-permission setting decides whether it asks before a tool call. When -it asks, T3 Code answers by the thread's [permission mode](./permission-modes.md). -When the CLI is set to always proceed, tools run without asking in every mode. - -**Usage > Limits** reads with the sign-in the CLI saved, in its state folder or -the system keyring. T3 Code cannot renew it, so after it expires the limits wait -for the CLI's next turn. - -T3 Code does not use the CLI for titles, commit messages, or other generated text -while `~/.gemini/config` holds hooks or MCP servers, because they would run in -those helper sessions too. Select another model for generated text. - -## Update the managed runtime - -In web or desktop provider settings, choose **Update Antigravity** when an update -is available. T3 checks Google's CLI release channel while provider update checks -are enabled. Installing or reinstalling also checks that channel. Updates keep -your profile and existing runtime available if the new release fails validation. - -T3 needs Antigravity 1.5 or newer and recommends 1.5.12 or newer. Sessions do not -start on an older runtime: update the managed runtime here, or update the executable -a custom binary path or `PATH` points at. You may need to sign in again after -updating from a runtime older than 1.5. Threads already running finish with their -original runtime; new sessions use the updated release. Custom binary paths keep -using the executable you selected. - -## Models and threads - -The model list comes from your Antigravity account, including Claude and GPT models -when your plan has them. Pick a thinking level beside the model list in the model picker; it -shows only the levels the selected model supports. A resumed thread keeps its -selected model. If access to that model ends, select another available model -before continuing. - -Antigravity creates empty `.gemini/skills` and `.agents/skills` folders in the -workspace when a session starts. Git does not track empty folders, so they never -appear in commits. - -Use Antigravity's native `/plan` command for planning. Tool approvals follow [Permission modes](./permission-modes.md). -Questions with fixed choices still need one of the offered answers, even in -**Full access**. - -On web and desktop, [Edit from here](./composer.md#edit-an-earlier-prompt) works with -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. - -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. -======= - Models (including Claude and GPT when included in your plan) and thinking levels come from your Antigravity account. - Use `/plan` for planning, `/compact` to summarize (if supported by your runtime), or `/clear` for a fresh session. - **Edit from here** starts a fresh Antigravity session with the kept conversation history. - **Native goals**: Send `/goal ` when supported by your runtime. Use **Stop** to interrupt, then tell Antigravity to stop pursuing it before starting new work (`pause`/`resume`/`clear` are not supported). - **Subagents**: Batched subagent activity is inspectable read-only via **Subagent work** (**Work** on mobile). - Antigravity creates empty `.gemini/skills` and `.agents/skills` directories in workspaces on start (untracked by Git). ->>>>>>> upstream/main ### Skills and attachments diff --git a/docs/user/providers-claude.md b/docs/user/providers-claude.md index f8dde754f576..7cb41842f1cf 100644 --- a/docs/user/providers-claude.md +++ b/docs/user/providers-claude.md @@ -21,9 +21,10 @@ Add a second Claude instance in **Settings → Providers** (or **Add Claude acco - **Auto-compact threshold**: Set **Auto-compact after** (`100000`–`1000000` tokens) in the Claude instance settings to trigger summarization earlier without changing the model's context window. - **Manual compaction**: Send `/compact` in chat. -- **Idle compaction (>200k tokens)**: Configure **Settings → Providers → Advanced → Compact idle threads** (overridable per instance): +- **Idle compaction**: Configure **Settings → Providers → Advanced → Compact idle threads** for large threads (overridable per instance): - **When you return** (default): Shows a **Compact** chip next to Send once Claude's prompt cache expires (~1 hour on subscriptions, 5 min on API/Bedrock/Vertex). Click it to switch to **Keep** if you want full history. - - **Before the cache expires (beta)**: Automatically sends `/compact` shortly before the cache expires while history is still cached (falls back to **When you return** if missed). + - **Before the cache expires (beta)**: Automatically sends `/compact` shortly before the cache expires while history is still cached (falls back to **When you return** if missed). **Cache expiry tokens** under the choice sets the minimum thread size (200,000 by default). + - **Compact when idle**: Does the same as **Before the cache expires (beta)**, and also compacts a thread at 400,000 tokens or more 15 minutes after the last message from you or a bot, or the last answer to a question or approval. Whichever compaction is due first runs, and the idle one can still run after the cache window is missed. A server restart drops a pending wait. If the idle wait ends while the thread is working, it compacts when that turn completes, only if it still has enough tokens and no background work pending. **Idle tokens** and **Idle minutes** under the choice change these values. A Claude provider set to its own mode does not compact when idle. - **Never**: Disables idle compaction prompts. ## Steering, usage limits, and tasks @@ -33,79 +34,10 @@ Add a second Claude instance in **Settings → Providers** (or **Add Claude acco - **Task lists**: Add `CLAUDE_CODE_ENABLE_TODO_TOOLS=1` in the instance's **Environment → Variables** to show Claude's task list progress in web and desktop threads. - **Auto mode**: Uses Claude Code's native auto mode (disabled if `disableAutoMode` is set in Claude's managed, user, or project settings). See [Permission modes](./permission-modes.md). -<<<<<<< origin/main -**Compact idle threads** in **Settings > Providers > Advanced** controls this for large -threads. Each Claude provider's settings can override it: - -- **When you return** shows the **Compact** chip described above. This is the default. -- **Before the cache expires (beta)** tries to compact an idle thread shortly before its - prompt cache expires, while the history is still cached. - The compaction appears in the thread as a `/compact` turn sent by T3 Code. - If the window is missed, such as when you enable this mode after the cache has - expired or the server restarts before compaction runs, it falls back to - **When you return**. Switch the chip to **Keep** to keep the full history for that message. - **Cache expiry tokens** under the choice sets how large a thread must be (200,000 by default). -- **Compact when idle** does the same, and also compacts a thread at 400,000 tokens or more - 15 minutes after the last message from you or a bot, or the last answer to a question or - approval. Whichever compaction is due first runs. The idle one can still run after the cache - window is missed. A server restart drops a pending wait. If the idle wait ends while the - thread is working, it compacts when that turn completes, but only if it still has enough - tokens and no background work pending. **Idle tokens** and **Idle minutes** under the choice - change these values. A Claude provider set to its own mode does not compact when idle. -- **Never** skips idle compaction and Claude's resume prompt. **Auto-compact after** - still applies, and you can still compact by hand. - -## Usage limits - -If your Claude subscription runs out of usage mid-turn, the thread shows which -limit was reached and the remaining wait when Claude provides a reset time. -Claude Code holds the turn until that window reopens, so it can keep showing as -working. Wait for the reset, or stop the turn and continue later. The warning's -timestamp shows when the displayed wait started. - -## Steering - -A steer waits until Claude finishes the tool calls it is running, then Claude reads it -in the same turn. The message shows as unread until then. If Claude drops it before -reading it, the message is sent as the next turn, after any messages queued before it. -If Claude exits or the server restarts first, the message waits in the queue in that -same place until you resume it. If you press Stop, T3 Code shows a notice with the text -of any steer Claude had not read. - -## Skills - -Claude skills come from the config directory's `skills` folder and the project's -`.claude/skills` folder. If both define the same name, the config-directory copy -wins. Skills disabled in Claude's settings do not appear in the composer. - -Use `$` in the composer to select a skill. Enabled installed Claude plugins, -and plugins synced from your claude.ai account, also contribute skills under -names such as `plugin:review`. Skills marked `disable-model-invocation` can -still be started by you. Invoke those one per message: Claude directly runs only -the last named skill and may try to start earlier ones through its Skill tool, -which refuses skills reserved for manual invocation. - -## Task lists - -To show Claude task lists in the web and desktop apps, add -`CLAUDE_CODE_ENABLE_TODO_TOOLS=1` under **Variables** in the Claude instance's -**Environment** section in **Settings > Providers**. Each update shows as a Tasks -row in the thread; open it to see every step. - -## Sign in to an MCP server - -When an MCP server you added to Claude needs you to sign in, the thread shows a notice with -**Sign in**, once per session; on mobile, tap the notice. Approve access on the page it opens. Your -browser then goes to a page that may not load, especially when Claude runs on another machine: -copy that page's address, paste it into T3 Code, and choose **Finish sign-in**. Claude keeps the -sign-in and reconnects the server. Connectors you added on claude.ai are signed in on claude.ai, -so T3 Code doesn't ask about them. Signing in needs permission to manage providers. -======= ## Skills and MCP sign-in - **Skills**: Loaded from `/skills`, the project's `.claude/skills` (config dir wins on name collisions), and enabled Claude plugins (e.g. `plugin:review`). Invoke via `$`. Send `disable-model-invocation` skills one per message. - **MCP OAuth**: When a Claude MCP server needs sign-in, click **Sign in** on the thread notice, approve in your browser, and paste the final redirect URL into T3 Code (**Finish sign-in**). Connectors added on `claude.ai` authenticate there instead. ->>>>>>> upstream/main ## Claude in Chrome diff --git a/packages/contracts/src/providerUsageLimits.ts b/packages/contracts/src/providerUsageLimits.ts index 1a12d4e2b4eb..8a9f0971ea31 100644 --- a/packages/contracts/src/providerUsageLimits.ts +++ b/packages/contracts/src/providerUsageLimits.ts @@ -52,8 +52,6 @@ export const ServerProviderUsageLimits = Schema.Struct({ /** A $0 monthly spend cap has no percentage, so it cannot be a window. */ zeroSpendCap: Schema.optional(Schema.Boolean), credentialFingerprint: Schema.optional(TrimmedNonEmptyString), - /** The account e-mail read in the same identity answer as `credentialFingerprint`. */ - credentialEmail: Schema.optional(TrimmedNonEmptyString), resetCredits: Schema.optional(ServerProviderResetCredits), externalUsage: Schema.optional( Schema.Struct({ diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts index 3f147ea4b049..a0c85df28436 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -604,18 +604,14 @@ export interface ProviderAdapterV2TurnInput { readonly inlineContextLength?: number; readonly modelSelection: ModelSelection; readonly runtimePolicy: ProviderAdapterV2RuntimePolicy; -<<<<<<< origin/main - readonly appContext?: ReadonlyArray<{ readonly key: string; readonly text: string }>; - /** Context for this turn only, beside a slash command that must reach the provider unchanged. Run `delivered` once the agent gets `text`. */ - readonly commandNote?: { readonly text: string; readonly delivered: Effect.Effect }; -======= readonly appContext?: ReadonlyArray<{ readonly key: string; readonly text: string; /** ISO time the note was last set, so a resent note reads as earlier state, not news. */ readonly updatedAt?: string; }>; ->>>>>>> upstream/main + /** Context for this turn only, beside a slash command that must reach the provider unchanged. Run `delivered` once the agent gets `text`. */ + readonly commandNote?: { readonly text: string; readonly delivered: Effect.Effect }; } export type ProviderAdapterV2ResumeTurnInput = Omit< diff --git a/packages/shared/src/fork/antigravityEmailBindings.test.ts b/packages/shared/src/fork/antigravityEmailBindings.test.ts deleted file mode 100644 index 750c5c05ff30..000000000000 --- a/packages/shared/src/fork/antigravityEmailBindings.test.ts +++ /dev/null @@ -1,251 +0,0 @@ -import { - EnvironmentId, - ProviderDriverKind, - ProviderInstanceId, - type ServerProvider, - type UsageLimitSourceAccount, - UsageLimitSourceId, -} from "@t3tools/contracts"; -import { describe, expect, it } from "vite-plus/test"; - -import { collectLimitAccounts } from "../usageLimits.ts"; - -const antigravity = ProviderDriverKind.make("antigravity"); -const checkedAt = "2026-09-03T11:00:00.000Z"; -const window = { - id: "gemini-weekly", - kind: "weekly", - label: "Gemini · Weekly", - usedPercent: 20, - windowDurationMins: 7 * 24 * 60, -} as const; -const limits = (identity: { credentialFingerprint?: string; credentialEmail?: string }) => ({ - checkedAt, - windows: [window], - ...identity, -}); - -type Reader = - | { - readonly kind: "native"; - readonly env: string; - readonly name: string; - readonly fp: string; - readonly email?: string; - } - | { - readonly kind: "hub"; - readonly env: string; - readonly name: string; - readonly fp?: string; - readonly email?: string; - }; - -const paired = (env: string, name: string, fp: string, email: string): Reader => ({ - kind: "native", - env, - name, - fp, - email, -}); -const fingerprintOnly = (env: string, name: string, fp: string): Reader => ({ - kind: "native", - env, - name, - fp, -}); -const answeringHub = (env: string, name: string, fp: string): Reader => ({ - kind: "hub", - env, - name, - fp, -}); -const withholdingHub = (env: string, name: string, email: string): Reader => ({ - kind: "hub", - env, - name, - email, -}); - -function accountsOf(readers: readonly Reader[]) { - const presentations = new Map< - EnvironmentId, - { - entry: { target: { label: string } }; - serverConfig: { - providers: ServerProvider[]; - usageLimitSources: Array<{ - id: UsageLimitSourceId; - kind: "cliproxy"; - label: string; - checkedAt: string; - accounts: UsageLimitSourceAccount[]; - }>; - }; - } - >(); - for (const reader of readers) { - const environmentId = EnvironmentId.make(reader.env); - const presentation = presentations.get(environmentId) ?? { - entry: { target: { label: reader.env } }, - serverConfig: { - providers: [], - usageLimitSources: [ - { - id: UsageLimitSourceId.make("hub"), - kind: "cliproxy", - label: "hub", - checkedAt, - accounts: [], - }, - ], - }, - }; - presentations.set(environmentId, presentation); - if (reader.kind === "native") { - presentation.serverConfig.providers.push({ - instanceId: ProviderInstanceId.make(reader.name), - driver: antigravity, - displayName: reader.name, - enabled: true, - installed: true, - version: null, - status: "ready", - auth: { status: "authenticated" }, - checkedAt, - models: [], - slashCommands: [], - skills: [], - usageLimits: limits({ - credentialFingerprint: reader.fp, - ...(reader.email ? { credentialEmail: reader.email } : {}), - }), - }); - } else { - presentation.serverConfig.usageLimitSources[0]!.accounts.push({ - id: reader.name, - driver: antigravity, - ...(reader.email ? { label: reader.name, email: reader.email } : {}), - usageLimits: limits(reader.fp ? { credentialFingerprint: reader.fp } : {}), - }); - } - } - return collectLimitAccounts(presentations) - .map((account) => `${account.displayName}${account.email ? ` <${account.email}>` : ""}`) - .toSorted(); -} - -describe("Antigravity accounts identified by a Google fingerprint and e-mail pair", () => { - it.each([ - { - name: "a current login and a hub that withholds userinfo", - readers: [ - paired("env-a", "local", "google-x", "x@example.com"), - withholdingHub("env-a", "g1", "X@example.com"), - ], - accounts: ["g1 "], - }, - { - name: "a current login, an older login, an answering hub and a withholding hub", - readers: [ - paired("env-a", "local", "google-x", "x@example.com"), - fingerprintOnly("env-b", "remote", "google-x"), - answeringHub("env-b", "proxy", "google-x"), - withholdingHub("env-a", "g1", "x@example.com"), - ], - accounts: ["g1 "], - }, - { - name: "two Google accounts, each read every way", - readers: [ - paired("env-a", "local-x", "google-x", "x@example.com"), - paired("env-a", "local-y", "google-y", "y@example.com"), - fingerprintOnly("env-b", "remote-x", "google-x"), - fingerprintOnly("env-b", "remote-y", "google-y"), - withholdingHub("env-a", "gx", "x@example.com"), - withholdingHub("env-a", "gy", "y@example.com"), - ], - accounts: ["gx ", "gy "], - }, - { - name: "one Google account whose e-mail changed between two machines", - readers: [ - paired("env-a", "local", "google-x", "old@example.com"), - paired("env-b", "local", "google-x", "new@example.com"), - ], - accounts: ["local"], - }, - { - name: "two fingerprints claiming one e-mail keep apart, and so does the hub listing it", - readers: [ - paired("env-a", "local-x", "google-x", "same@example.com"), - paired("env-b", "remote-y", "google-y", "same@example.com"), - withholdingHub("env-a", "g1", "same@example.com"), - ], - accounts: ["g1 ", "local-x", "remote-y"], - }, - { - name: "an older login and a withholding hub, with no reader that knows both names", - readers: [ - fingerprintOnly("env-a", "local", "google-x"), - withholdingHub("env-a", "g1", "x@example.com"), - ], - accounts: ["g1 ", "local"], - }, - ])("$name", ({ readers, accounts }) => { - expect(accountsOf(readers)).toEqual(accounts); - expect(accountsOf(readers.toReversed())).toEqual(accounts); - }); - - it("leaves other drivers keyed by e-mail first", () => { - const opencode = ProviderDriverKind.make("opencode"); - const accounts = collectLimitAccounts( - new Map([ - [ - EnvironmentId.make("env-a"), - { - entry: { target: { label: "env-a" } }, - serverConfig: { - providers: [ - { - instanceId: ProviderInstanceId.make("opencode"), - driver: opencode, - enabled: true, - installed: true, - version: null, - status: "ready", - auth: { status: "authenticated", email: "same@example.com" }, - checkedAt, - models: [], - slashCommands: [], - skills: [], - usageLimits: limits({ - credentialFingerprint: "key-a", - credentialEmail: "same@example.com", - }), - }, - ], - usageLimitSources: [ - { - id: UsageLimitSourceId.make("hub"), - kind: "cliproxy", - label: "hub", - checkedAt, - accounts: [ - { - id: "go", - driver: opencode, - email: "same@example.com", - usageLimits: limits({}), - }, - ], - }, - ], - }, - }, - ], - ]), - ); - expect(accounts).toHaveLength(1); - }); -}); diff --git a/packages/shared/src/fork/antigravityEmailBindings.ts b/packages/shared/src/fork/antigravityEmailBindings.ts deleted file mode 100644 index decfb36436b8..000000000000 --- a/packages/shared/src/fork/antigravityEmailBindings.ts +++ /dev/null @@ -1,38 +0,0 @@ -import type { ServerProvider, ServerProviderUsageLimits } from "@t3tools/contracts"; - -interface AccountReport { - readonly driver: ServerProvider["driver"]; - readonly email?: string | undefined; - readonly usageLimits?: ServerProviderUsageLimits | undefined; -} - -const normalizedEmail = (email: string | undefined) => email?.trim().toLowerCase() || undefined; - -/** A hub that withholds `userinfo` names an Antigravity account only by its e-mail. */ -export function bindAntigravityEmails( - reports: readonly AccountReport[], -): (report: AccountReport) => AccountReport { - const fingerprints = new Map(); - const claimedTwice = new Set(); - for (const { driver, usageLimits } of reports) { - const email = normalizedEmail(usageLimits?.credentialEmail); - const fingerprint = usageLimits?.credentialFingerprint; - if (driver !== "antigravity" || !email || !fingerprint) continue; - const bound = fingerprints.get(email); - if (bound !== undefined && bound !== fingerprint) claimedTwice.add(email); - fingerprints.set(email, fingerprint); - } - if (fingerprints.size === 0) return (report) => report; - return (report) => { - const email = normalizedEmail(report.email); - if (report.driver !== "antigravity" || !email || !report.usageLimits) return report; - if (report.usageLimits.credentialFingerprint || claimedTwice.has(email)) return report; - const fingerprint = fingerprints.get(email); - return fingerprint - ? { - driver: report.driver, - usageLimits: { ...report.usageLimits, credentialFingerprint: fingerprint }, - } - : report; - }; -} diff --git a/packages/shared/src/usageLimits.ts b/packages/shared/src/usageLimits.ts index cdb81d59dda7..e119e0e8c7f9 100644 --- a/packages/shared/src/usageLimits.ts +++ b/packages/shared/src/usageLimits.ts @@ -21,7 +21,6 @@ import { import * as DateTime from "effect/DateTime"; import { isLocalLoopbackHost, isWildcardHost } from "./hostClassification.ts"; -import { bindAntigravityEmails } from "./fork/antigravityEmailBindings.ts"; const MINUTE = 60_000; @@ -230,21 +229,16 @@ const nativeReport = (provider: ServerProvider): AccountReport => ({ }); // Include every enabled login, even unreadable workspaces. -function accountKeyResolver(reports: readonly AccountReport[]) { - const bind = bindAntigravityEmails(reports); - const keyOf = (report: AccountReport) => { - const { driver, email, usageLimits } = bind(report); - return accountKey(driver, email, usageLimits); - }; +function accountKeyResolver(reports: Iterable) { const workspaces = new Map>(); for (const report of reports) { - const key = keyOf(report); + const key = accountKey(report.driver, report.email, report.usageLimits); if (key && report.workspaceId) { workspaces.set(key, (workspaces.get(key) ?? new Set()).add(report.workspaceId)); } } return (report: AccountReport): string | null => { - const key = keyOf(report); + const key = accountKey(report.driver, report.email, report.usageLimits); if (!key) return null; if (report.workspaceId) return `${key}:${report.workspaceId}`; const known = workspaces.get(key);