Skip to content

Automate browser based workflows with AI

feat(SKY-12137): queued-warmup bubble footer + Confirm chip for copilot QA turns (#7372)

Celal Zamanoğlu216713775b8e
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.composerControls.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.composerControls.test.tsx
index 488ddcfbe..29c1bcf48 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.composerControls.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.composerControls.test.tsx
@@ -291,11 +291,15 @@ describe("WorkflowCopilotChat — S4 composer, copilot_ux_v1 on", () => {
});
await submit("build me a workflow");
- // No turn started yet — queued purely on the live-browser gate.
+ // No turn started yet — queued purely on the live-browser gate. The
+ // status now lives on the queued bubble's footer, not the composer
+ // chip (that's reserved for the working-reason queue) — getByText
+ // throws on a duplicate match, so this also proves there's only one.
expect(postStreaming).not.toHaveBeenCalled();
expect(
screen.getByText("Prompt queued. Waiting for live browser..."),
).toBeTruthy();
+ expect(screen.queryByText("Queued")).toBeNull();
const button = screen.getByRole("button", {
name: "Send disabled — waiting for live browser",
@@ -309,5 +313,32 @@ describe("WorkflowCopilotChat — S4 composer, copilot_ux_v1 on", () => {
fireEvent.click(cancel);
});
expect(screen.queryByText("Queued")).toBeNull();
+ expect(
+ screen.queryByText("Prompt queued. Waiting for live browser..."),
+ ).toBeNull();
+ });
+});
+
+describe("WorkflowCopilotChat — S4 composer, copilot_ux_v1 off (parity)", () => {
+ it("keeps the legacy plain status line for a live-browser queue, with no bubble footer or chip", async () => {
+ mockCopilotUxV1Enabled.mockReturnValue(false);
+ await renderChat({
+ copilotV2: true,
+ codeBlockMode: true,
+ requiresLiveBrowser: true,
+ isLiveBrowserReady: false,
+ });
+ await submit("build me a workflow");
+
+ expect(postStreaming).not.toHaveBeenCalled();
+ // Same wording, but via the legacy aria-live status line — the S4
+ // chip and the new bubble footer are both flag-gated on uxV1.
+ expect(
+ screen.getByText("Prompt queued. Waiting for live browser..."),
+ ).toBeTruthy();
+ expect(screen.queryByText("Queued")).toBeNull();
+ expect(
+ screen.queryByRole("button", { name: "Cancel queued message" }),
+ ).toBeNull();
});
});
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.confirmCard.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.confirmCard.test.tsx
new file mode 100644
index 000000000..e177d0480
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.confirmCard.test.tsx
@@ -0,0 +1,284 @@
+import {
+ act,
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import {
+ FeatureFlagContext,
+ FeatureFlagValueContext,
+} from "@/hooks/useFeatureFlag";
+
+type StreamBody = {
+ message: string;
+ mode: string | null;
+ code_block: boolean | null;
+};
+type StreamCall = {
+ body: StreamBody;
+ onMessage: (payload: unknown) => boolean;
+ resolve: () => void;
+ reject: (error: unknown) => void;
+};
+
+const { mockCopilotUxV1Enabled } = vi.hoisted(() => ({
+ mockCopilotUxV1Enabled: vi.fn(() => true),
+}));
+
+vi.mock("posthog-js/react", () => ({
+ useFeatureFlagEnabled: () => mockCopilotUxV1Enabled(),
+}));
+
+const { streamCalls, postStreaming, cancelPost, historyResponse } = vi.hoisted(
+ () => {
+ const calls: StreamCall[] = [];
+ const post = vi.fn().mockResolvedValue({});
+ const streaming = vi.fn(
+ (
+ _path: string,
+ body: StreamBody,
+ onMessage: (payload: unknown) => boolean,
+ ) =>
+ new Promise<void>((resolve, reject) => {
+ calls.push({ body, onMessage, resolve, reject });
+ }),
+ );
+ const history = {
+ data: {
+ workflow_copilot_chat_id: null as string | null,
+ chat_history: [] as unknown[],
+ proposed_workflow: null as Record<string, unknown> | null,
+ auto_accept: false,
+ },
+ };
+ return {
+ streamCalls: calls,
+ postStreaming: streaming,
+ cancelPost: post,
+ historyResponse: history,
+ };
+ },
+);
+
+vi.mock("@/api/sse", () => ({
+ getSseClient: vi.fn().mockResolvedValue({ postStreaming }),
+}));
+
+vi.mock("@/api/AxiosClient", () => ({
+ getClient: vi.fn().mockResolvedValue({
+ get: vi.fn().mockImplementation(() => Promise.resolve(historyResponse)),
+ post: cancelPost,
+ }),
+}));
+
+vi.mock("@/hooks/useCredentialGetter", () => ({
+ useCredentialGetter: () => null,
+}));
+
+vi.mock("@/components/ui/use-toast", () => ({ toast: vi.fn() }));
+
+vi.mock("react-router-dom", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("react-router-dom")>();
+ return {
+ ...actual,
+ useParams: () => ({
+ workflowPermanentId: "wpid_1",
+ workflowRunId: undefined,
+ }),
+ useSearchParams: () => [new URLSearchParams(), vi.fn()],
+ };
+});
+
+const saveData = {
+ title: "Test WF",
+ workflow: {
+ workflow_id: "wf_1",
+ workflow_permanent_id: "wpid_1",
+ description: "",
+ totp_verification_url: null,
+ is_saved_task: false,
+ status: "published",
+ },
+ settings: {
+ proxyLocation: null,
+ webhookCallbackUrl: null,
+ persistBrowserSession: false,
+ pinSavedSessionIp: false,
+ browserProfileId: null,
+ browserProfileKey: null,
+ model: null,
+ maxScreenshotScrolls: null,
+ extraHttpHeaders: null,
+ runWith: "agent",
+ scriptCacheKey: "",
+ aiFallback: true,
+ codeVersion: 2,
+ runSequentially: false,
+ sequentialKey: null,
+ },
+ parameters: [],
+ blocks: [],
+ workflowDefinitionVersion: 1,
+};
+
+vi.mock("@/store/WorkflowHasChangesStore", () => ({
+ useWorkflowHasChangesStore: () => ({ getSaveData: () => saveData }),
+}));
+
+vi.mock("@/routes/workflows/hooks/useWorkflowRunQuery", () => ({
+ useWorkflowRunQuery: () => ({ data: undefined }),
+}));
+
+import { WorkflowCopilotChat } from "./WorkflowCopilotChat";
+
+async function renderChat() {
+ const view = render(
+ <FeatureFlagContext.Provider value={() => false}>
+ <FeatureFlagValueContext.Provider value={() => undefined}>
+ <WorkflowCopilotChat />
+ </FeatureFlagValueContext.Provider>
+ </FeatureFlagContext.Provider>,
+ );
+ await waitFor(() => expect(screen.getByRole("textbox")).toBeTruthy());
+ return view;
+}
+
+function textarea(): HTMLTextAreaElement {
+ return screen.getByRole("textbox") as HTMLTextAreaElement;
+}
+
+async function submit(value: string) {
+ fireEvent.change(textarea(), { target: { value } });
+ await act(async () => {
+ fireEvent.keyDown(textarea(), { key: "Enter" });
+ });
+}
+
+const CONFIRM_NOTE =
+ "(Note: Diagnosing a failed run doesn't edit the workflow on its own — confirm and I'll apply the change.)";
+
+const terminalResponse = (message: string) => ({
+ type: "response" as const,
+ workflow_copilot_chat_id: "chat-1",
+ message,
+ updated_workflow: null,
+ response_time: "2026-05-25T00:00:05Z",
+ proposal_disposition: "no_proposal" as const,
+});
+
+function diagnoseNarrativePayload(message: string) {
+ return {
+ turnId: "turn-1",
+ turnIndex: 0,
+ mode: "diagnose",
+ designStarted: false,
+ designEnded: true,
+ draft: null,
+ blocks: [],
+ terminal: "response" as const,
+ terminalMessage: message,
+ narrativeSummary: message,
+ priorBlockCount: null,
+ designActivity: [],
+ startedAt: null,
+ endedAt: null,
+ };
+}
+
+beforeEach(() => {
+ HTMLElement.prototype.scrollIntoView = vi.fn();
+ HTMLElement.prototype.scrollTo = vi.fn();
+ mockCopilotUxV1Enabled.mockReset();
+ mockCopilotUxV1Enabled.mockReturnValue(true);
+ streamCalls.length = 0;
+ postStreaming.mockClear();
+ cancelPost.mockClear();
+ historyResponse.data = {
+ workflow_copilot_chat_id: null,
+ chat_history: [],
+ proposed_workflow: null,
+ auto_accept: false,
+ };
+});
+
+afterEach(() => {
+ cleanup();
+});
+
+async function sendConfirmNote() {
+ await submit("fix the failed run");
+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
+ await act(async () => {
+ streamCalls[0]!.onMessage({
+ ...terminalResponse(CONFIRM_NOTE),
+ narrative_payload: diagnoseNarrativePayload(CONFIRM_NOTE),
+ });
+ streamCalls[0]!.resolve();
+ });
+}
+
+describe("WorkflowCopilotChat — Confirm chip (SKY-12137)", () => {
+ it("renders Confirm + Tell it what to change instead when the turn asks for a typed confirmation", async () => {
+ await renderChat();
+ await sendConfirmNote();
+
+ expect(screen.getByRole("button", { name: "Confirm" })).toBeTruthy();
+ expect(
+ screen.getByRole("button", { name: "Tell it what to change instead" }),
+ ).toBeTruthy();
+ });
+
+ it("sends 'Confirmed.' as a real turn when Confirm is clicked", async () => {
+ await renderChat();
+ await sendConfirmNote();
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: "Confirm" }));
+ });
+
+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(2));
+ expect(streamCalls[1]?.body.message).toBe("Confirmed.");
+ });
+
+ it("focuses the composer instead of sending when 'Tell it what to change instead' is clicked", async () => {
+ await renderChat();
+ await sendConfirmNote();
+
+ await act(async () => {
+ fireEvent.click(
+ screen.getByRole("button", { name: "Tell it what to change instead" }),
+ );
+ });
+
+ expect(postStreaming).toHaveBeenCalledTimes(1);
+ expect(document.activeElement).toBe(textarea());
+ });
+
+ it("does not render for an ordinary QA turn with no confirm-request phrasing", async () => {
+ await renderChat();
+ await submit("what does this workflow do?");
+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
+ const plainAnswer = "It scrapes Hacker News for the top stories.";
+ await act(async () => {
+ streamCalls[0]!.onMessage({
+ ...terminalResponse(plainAnswer),
+ narrative_payload: diagnoseNarrativePayload(plainAnswer),
+ });
+ streamCalls[0]!.resolve();
+ });
+
+ expect(screen.queryByRole("button", { name: "Confirm" })).toBeNull();
+ });
+
+ it("does not render when the flag is off", async () => {
+ mockCopilotUxV1Enabled.mockReturnValue(false);
+ await renderChat();
+ await sendConfirmNote();
+
+ expect(screen.queryByRole("button", { name: "Confirm" })).toBeNull();
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
index 4a3e9b4ce..a05769f79 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
@@ -67,6 +67,7 @@ import { shouldAutoApplyWorkflowResponse } from "./proposalDisposition";
import { shouldArmDraftingGapTimer } from "./copilotPhases";
import { NarrativeView } from "./NarrativeView";
import { useRunLifecycleAnnouncements } from "./useRunLifecycleAnnouncements";
+import { ConfirmCard, shouldShowConfirmCard } from "./cards/ConfirmCard";
import { DiffCard, shouldShowDiffCard } from "./cards/DiffCard";
import { FixCard, shouldShowFixCard } from "./cards/FixCard";
import { ReviewGateCard, getReviewGateVerdict } from "./cards/ReviewGateCard";
@@ -392,34 +393,55 @@ const formatChatTimestamp = (value: string) => {
interface MessageItemProps {
message: ChatMessage;
footer?: React.ReactNode;
+ // Replaces the timestamp with a spinner + cancel affordance while this
+ // message is the currently-queued (not yet sent) prompt.
+ queuedStatus?: { text: string; onCancel: () => void } | null;
}
-const MessageItem = memo(({ message, footer }: MessageItemProps) => {
- if (message.sender === "user") {
- return (
- <div className="flex justify-end">
- <div className="relative max-w-[85%] rounded-xl border border-white/5 bg-slate-elevation4 px-3.5 py-2.5 text-[13.5px] leading-[1.5] text-foreground">
- <p className="whitespace-pre-wrap pr-12">{message.content}</p>
- {message.timestamp ? (
- <span className="pointer-events-none absolute bottom-2 right-2 rounded bg-slate-elevation1/70 px-1.5 py-0.5 text-[10px] text-muted-foreground">
- {formatChatTimestamp(message.timestamp)}
- </span>
- ) : null}
+const MessageItem = memo(
+ ({ message, footer, queuedStatus }: MessageItemProps) => {
+ if (message.sender === "user") {
+ return (
+ <div className="flex justify-end">
+ <div className="relative max-w-[85%] rounded-xl border border-white/5 bg-slate-elevation4 px-3.5 py-2.5 text-[13.5px] leading-[1.5] text-foreground">
+ <p className="whitespace-pre-wrap pr-12">{message.content}</p>
+ {queuedStatus ? (
+ <div className="mt-2 flex items-center gap-1.5 border-t border-white/10 pt-2 text-[11.5px] text-slate-400">
+ <ReloadIcon className="h-3 w-3 shrink-0 animate-spin" />
+ <span className="min-w-0 flex-1 truncate">
+ {queuedStatus.text}
+ </span>
+ <button
+ type="button"
+ onClick={queuedStatus.onCancel}
+ title="Cancel queued message"
+ aria-label="Cancel queued message"
+ className="shrink-0 rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-accent-foreground"
+ >
+ <Cross2Icon className="h-3 w-3" />
+ </button>
+ </div>
+ ) : message.timestamp ? (
+ <span className="pointer-events-none absolute bottom-2 right-2 rounded bg-slate-elevation1/70 px-1.5 py-0.5 text-[10px] text-muted-foreground">
+ {formatChatTimestamp(message.timestamp)}
+ </span>
+ ) : null}
+ </div>
</div>
+ );
+ }
+ return (
+ <div className="flex flex-col gap-2">
+ <p className="whitespace-pre-wrap pl-1 text-[13px] leading-[1.55] text-slate-200">
+ {message.content}
+ </p>
+ {footer ? (
+ <div className="flex flex-wrap gap-2 pl-1">{footer}</div>
+ ) : null}
</div>
);
- }
- return (
- <div className="flex flex-col gap-2">
- <p className="whitespace-pre-wrap pl-1 text-[13px] leading-[1.55] text-slate-200">
- {message.content}
- </p>
- {footer ? (
- <div className="flex flex-wrap gap-2 pl-1">{footer}</div>
- ) : null}
- </div>
- );
-});
+ },
+);
// Studio-only run status line, distinct from ai prose: no bubble, no footer.
function RunLifecycleLine({ content }: { content: string }) {
@@ -2438,8 +2460,9 @@ export function WorkflowCopilotChat({
queuedPrompt?.reason === "working"
? "Queued — sends when this turn finishes."
: "Prompt queued. Waiting for live browser...";
- // S4's Queued chip already surfaces queuedPromptWaitingStatus; don't
- // duplicate it as a second status line above the composer.
+ // queuedPromptWaitingStatus already surfaces via the composer chip
+ // (working reason) or the queued bubble's footer (live_browser reason);
+ // don't duplicate it as a second status line above the composer.
const browserStatusText = queuedPrompt
? copilotUxV1Enabled && copilotV2Enabled
? null
@@ -2781,6 +2804,17 @@ export function WorkflowCopilotChat({
) : null}
</>
) : null}
+ {copilotUxV1Enabled &&
+ isLastMessage &&
+ shouldShowConfirmCard(message.narrative) ? (
+ <ConfirmCard
+ onConfirm={() => handleSend("Confirmed.")}
+ onChangeInstead={() => {
+ textareaRef.current?.focus();
+ adjustTextareaHeight();
+ }}
+ />
+ ) : null}
{docked &&
isLastMessage &&
shouldShowFixCard(message.narrative) ? (
@@ -2803,6 +2837,17 @@ export function WorkflowCopilotChat({
<MessageItem
key={message.id}
message={message}
+ queuedStatus={
+ copilotUxV1Enabled &&
+ copilotV2Enabled &&
+ queuedPrompt?.reason === "live_browser" &&
+ queuedPrompt.id === message.id
+ ? {
+ text: queuedPromptWaitingStatus,
+ onCancel: cancelQueuedPrompt,
+ }
+ : null
+ }
footer={
copilotUxV1Enabled && isGateOwnerOrLast ? (
<ReviewGateCard
@@ -2961,7 +3006,10 @@ export function WorkflowCopilotChat({
pending · Review
</button>
) : null}
- {copilotUxV1Enabled && copilotV2Enabled && queuedPrompt ? (
+ {copilotUxV1Enabled &&
+ copilotV2Enabled &&
+ queuedPrompt &&
+ queuedPrompt.reason === "working" ? (
<div className="mb-2 flex items-center gap-2 rounded-lg border border-border bg-slate-elevation2 px-2.5 py-1.5 text-xs text-muted-foreground">
<ReloadIcon className="h-3 w-3 shrink-0 animate-spin" />
<span className="shrink-0 font-medium text-foreground">Queued</span>
diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/ConfirmCard.test.ts b/skyvern-frontend/src/routes/workflows/copilot/cards/ConfirmCard.test.ts
new file mode 100644
index 000000000..72a05e1e8
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/ConfirmCard.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it } from "vitest";
+
+import { EMPTY_NARRATIVE, type TurnNarrativeState } from "../narrativeState";
+import { shouldShowConfirmCard } from "./ConfirmCard";
+
+const turn = (
+ overrides: Partial<TurnNarrativeState> = {},
+): TurnNarrativeState => ({
+ ...EMPTY_NARRATIVE,
+ turnId: "turn-1",
+ turnIndex: 0,
+ mode: "diagnose",
+ terminal: "response",
+ ...overrides,
+});
+
+describe("shouldShowConfirmCard", () => {
+ it("matches the real backend confirm-request note (agent.py _with_inline_reject_note)", () => {
+ expect(
+ shouldShowConfirmCard(
+ turn({
+ terminalMessage:
+ "(Note: Diagnosing a failed run doesn't edit the workflow on its own — confirm and I'll apply the change.)",
+ }),
+ ),
+ ).toBe(true);
+ });
+
+ it("is case-insensitive and tolerant of curly apostrophes", () => {
+ expect(
+ shouldShowConfirmCard(
+ turn({ terminalMessage: "CONFIRM AND I’LL APPLY it now." }),
+ ),
+ ).toBe(true);
+ });
+
+ it("checks narrativeSummary too", () => {
+ expect(
+ shouldShowConfirmCard(
+ turn({ narrativeSummary: "please confirm and I'll apply the fix" }),
+ ),
+ ).toBe(true);
+ });
+
+ it("does not fire on unrelated QA prose", () => {
+ expect(
+ shouldShowConfirmCard(
+ turn({
+ terminalMessage:
+ "I found two saved credentials — which one should I use?",
+ }),
+ ),
+ ).toBe(false);
+ });
+
+ it("does not fire while the turn is still in flight", () => {
+ expect(
+ shouldShowConfirmCard(
+ turn({
+ terminal: null,
+ terminalMessage: "confirm and I'll apply the change",
+ }),
+ ),
+ ).toBe(false);
+ });
+
+ it("does not fire on an error terminal even if the text happens to match", () => {
+ expect(
+ shouldShowConfirmCard(
+ turn({
+ terminal: "error",
+ terminalMessage: "confirm and I'll apply the change",
+ }),
+ ),
+ ).toBe(false);
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/ConfirmCard.tsx b/skyvern-frontend/src/routes/workflows/copilot/cards/ConfirmCard.tsx
new file mode 100644
index 000000000..e0d36bc10
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/ConfirmCard.tsx
@@ -0,0 +1,46 @@
+import { TurnNarrativeState } from "../narrativeState";
+
+// Backend source: skyvern/forge/sdk/copilot/agent.py's _with_inline_reject_note
+// append when a DIAGNOSE-authority turn's inline REPLACE_WORKFLOW is downgraded
+// to a REPLY ("...confirm and I'll apply the change."). This is the only place
+// that phrase family is emitted server-side today — no typed signal exists yet,
+// so this is a conservative text match, not a structural one. If the backend
+// wording changes, grep for this constant.
+export const CONFIRM_REQUEST_PATTERN = /confirm and i(?:'|’)ll apply/i;
+
+// eslint-disable-next-line react-refresh/only-export-components
+export function shouldShowConfirmCard(turn: TurnNarrativeState): boolean {
+ // The note is only ever appended on the REPLY path (terminal "response"),
+ // never "error" — no reason for an error terminal to earn this affordance.
+ if (turn.terminal !== "response") {
+ return false;
+ }
+ const text = `${turn.terminalMessage ?? ""} ${turn.narrativeSummary ?? ""}`;
+ return CONFIRM_REQUEST_PATTERN.test(text);
+}
+
+type ConfirmCardProps = {
+ onConfirm: () => void;
+ onChangeInstead: () => void;
+};
+
+export function ConfirmCard({ onConfirm, onChangeInstead }: ConfirmCardProps) {
+ return (
+ <div className="flex flex-wrap gap-2 pl-1">
+ <button
+ type="button"
+ onClick={onConfirm}
+ className="rounded-md bg-success px-3 py-1.5 text-xs font-semibold text-success-foreground hover:opacity-90"
+ >
+ Confirm
+ </button>
+ <button
+ type="button"
+ onClick={onChangeInstead}
+ className="rounded-md px-3 py-1.5 text-xs text-slate-400 hover:bg-slate-elevation4 hover:text-slate-200"
+ >
+ Tell it what to change instead
+ </button>
+ </div>
+ );
+}
diff --git a/skyvern/forge/sdk/services/google_drive_service.py b/skyvern/forge/sdk/services/google_drive_service.py
index c56562f41..9e9b841a1 100644
--- a/skyvern/forge/sdk/services/google_drive_service.py
+++ b/skyvern/forge/sdk/services/google_drive_service.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import asyncio
import json
import uuid
+from collections.abc import AsyncIterator, Mapping
from dataclasses import dataclass
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
@@ -11,12 +12,16 @@ from pathlib import Path
from typing import Any
from urllib.parse import urlencode, urlparse
+import aiofiles
import httpx
from skyvern.config import settings
DRIVE_UPLOAD_API_BASE = "https://www.googleapis.com/upload/drive/v3"
DRIVE_MULTIPART_UPLOAD_MAX_BYTES = 5 * 1024 * 1024
+# Reserve headroom for JSON metadata and MIME boundaries below the 5 MiB multipart request cap.
+DRIVE_MULTIPART_FILE_MAX_BYTES = DRIVE_MULTIPART_UPLOAD_MAX_BYTES - 10 * 1024
+DRIVE_RESUMABLE_UPLOAD_CHUNK_BYTES = 8 * 1024 * 1024
_DEFAULT_BACKOFF_SECONDS = 1.0
@@ -42,6 +47,20 @@ class GoogleDriveMultipartUploadRequest:
content: bytes
+@dataclass(frozen=True)
+class GoogleDriveResumableInitiateRequest:
+ target_url: str
+ headers: dict[str, str]
+ content: bytes
+
+
+@dataclass(frozen=True)
+class GoogleDriveResumableUploadRequest:
+ target_url: str
+ headers: dict[str, str]
+ file_path: str
+
+
def _compute_backoff(attempt: int, retry_after: str | None) -> float:
if retry_after:
value = retry_after.strip()
@@ -110,18 +129,14 @@ def _assert_multipart_upload_size(file_path: str, body_size: int | None = None)
raise GoogleDriveAPIError(
status=413,
code="file_too_large",
- message=(
- "Google Drive multipart uploads are limited to 5 MB. "
- "Use a smaller file or wait for resumable Drive upload support."
- ),
+ message="Google Drive multipart uploads are limited to 5 MB; larger files use resumable upload.",
)
if body_size is not None and body_size > DRIVE_MULTIPART_UPLOAD_MAX_BYTES:
raise GoogleDriveAPIError(
status=413,
code="multipart_body_too_large",
message=(
- "Google Drive multipart uploads are limited to 5 MB including metadata. "
- "Use a smaller file or wait for resumable Drive upload support."
+ "Google Drive multipart uploads are limited to 5 MB including metadata; larger files use resumable upload."
),
)
@@ -180,6 +195,76 @@ def build_multipart_upload_request(
)
+def should_use_resumable_upload(file_path: str) -> bool:
+ return Path(file_path).stat().st_size > DRIVE_MULTIPART_FILE_MAX_BYTES
+
+
+def build_resumable_initiate_request(
+ *,
+ access_token: str,
+ file_path: str,
+ folder_id: str,
+) -> GoogleDriveResumableInitiateRequest:
+ path = Path(file_path)
+ file_size = path.stat().st_size
+ content_type = guess_type(file_path)[0] or "application/octet-stream"
+ metadata = {"name": path.name, "parents": [folder_id]}
+ query = urlencode({"uploadType": "resumable", "fields": "id,name,webViewLink", "supportsAllDrives": "true"})
+ return GoogleDriveResumableInitiateRequest(
+ target_url=f"{DRIVE_UPLOAD_API_BASE}/files?{query}",
+ headers={
+ "Authorization": f"Bearer {access_token}",
+ "Content-Type": "application/json; charset=UTF-8",
+ "X-Upload-Content-Type": content_type,
+ "X-Upload-Content-Length": str(file_size),
+ },
+ content=json.dumps(metadata, separators=(",", ":")).encode("utf-8"),
+ )
+
+
+def extract_resumable_session_uri(headers: Mapping[str, str]) -> str:
+ for name, value in headers.items():
+ if name.lower() == "location" and value.strip():
+ session_uri = value.strip()
+ parsed = urlparse(session_uri)
+ hostname = parsed.hostname or ""
+ try:
+ port = parsed.port
+ except ValueError:
+ port = -1
+ if (
+ parsed.scheme != "https"
+ or parsed.username is not None
+ or parsed.password is not None
+ or port not in {None, 443}
+ or not (hostname == "googleapis.com" or hostname.endswith(".googleapis.com"))
+ ):
+ raise GoogleDriveAPIError(
+ status=502,
+ code="invalid_resumable_session",
+ message="Google Drive resumable session URI is not a googleapis.com https URL",
+ )
+ return session_uri
+ raise GoogleDriveAPIError(
+ status=502,
+ code="missing_resumable_session",
+ message="Google Drive resumable upload did not return a session URI",
+ )
+
+
+def build_resumable_upload_request(*, file_path: str, session_uri: str) -> GoogleDriveResumableUploadRequest:
+ file_size = Path(file_path).stat().st_size
+ content_type = guess_type(file_path)[0] or "application/octet-stream"
+ return GoogleDriveResumableUploadRequest(
+ target_url=session_uri,
+ headers={
+ "Content-Type": content_type,
+ "Content-Length": str(file_size),
+ },
+ file_path=file_path,
+ )
+
+
def uploaded_file_from_payload(payload: Any) -> UploadedDriveFile:
if not isinstance(payload, dict):
raise GoogleDriveAPIError(status=500, code="malformed_response", message="Malformed Drive upload response")
@@ -231,12 +316,103 @@ async def _post_multipart_with_retry(
raise AssertionError("Drive upload retry loop exited without a response")
+async def _post_resumable_initiate_with_retry(
+ client: httpx.AsyncClient,
+ request: GoogleDriveResumableInitiateRequest,
+) -> httpx.Response:
+ max_attempts = max(1, settings.GOOGLE_DRIVE_API_MAX_RETRIES)
+ for attempt in range(1, max_attempts + 1):
+ try:
+ return await client.post(
+ request.target_url,
+ headers=request.headers,
+ content=request.content,
+ )
+ except (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout) as exc:
+ if attempt == max_attempts:
+ raise GoogleDriveAPIError(
+ status=503,
+ code="upstream_unavailable",
+ message=f"Google Drive resumable upload connection failure: {exc}",
+ ) from exc
+ await asyncio.sleep(_compute_backoff(attempt, None))
+ continue
+ except (httpx.TransportError, httpx.TimeoutException) as exc:
+ raise GoogleDriveAPIError(
+ status=503,
+ code="ambiguous_upload_status",
+ message="Google Drive resumable upload initiation status is unknown after a transport failure.",
+ ) from exc
+ raise AssertionError("Drive resumable upload retry loop exited without a response")
+
+
+async def _iter_file_chunks(file_path: str) -> AsyncIterator[bytes]:
+ async with aiofiles.open(file_path, "rb") as file:
+ while chunk := await file.read(DRIVE_RESUMABLE_UPLOAD_CHUNK_BYTES):
+ yield chunk
+
+
+async def _upload_file_resumable(
+ *,
+ access_token: str,
+ file_path: str,
+ folder_id: str,
+) -> UploadedDriveFile:
+ initiate_request = build_resumable_initiate_request(
+ access_token=access_token,
+ file_path=file_path,
+ folder_id=folder_id,
+ )
+
+ async with httpx.AsyncClient(timeout=settings.GOOGLE_DRIVE_API_TIMEOUT_SECONDS) as client:
+ initiate_response = await _post_resumable_initiate_with_retry(client, initiate_request)
+ _raise_for_error(initiate_response)
+ session_uri = extract_resumable_session_uri(initiate_response.headers)
+ upload_request = build_resumable_upload_request(file_path=file_path, session_uri=session_uri)
+ try:
+ upload_response = await client.put(
+ upload_request.target_url,
+ headers=upload_request.headers,
+ content=_iter_file_chunks(upload_request.file_path),
+ )
+ except (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout) as exc:
+ raise GoogleDriveAPIError(
+ status=503,
+ code="upstream_unavailable",
+ message=f"Google Drive resumable upload connection failure: {exc}",
+ ) from exc
+ except (httpx.TransportError, httpx.TimeoutException) as exc:
+ raise GoogleDriveAPIError(
+ status=503,
+ code="ambiguous_upload_status",
+ message="Google Drive upload status is unknown after a transport failure.",
+ ) from exc
+
+ _raise_for_error(upload_response)
+ try:
+ payload = upload_response.json() or {}
+ except ValueError as exc:
+ raise GoogleDriveAPIError(
+ status=500,
+ code="malformed_response",
+ message="Drive response was not valid JSON",
+ ) from exc
+ return uploaded_file_from_payload(payload)
+
+
async def upload_file(
*,
access_token: str,
file_path: str,
folder_id: str,
) -> UploadedDriveFile:
+ if should_use_resumable_upload(file_path):
+ return await _upload_file_resumable(
+ access_token=access_token,
+ file_path=file_path,
+ folder_id=folder_id,
+ )
+
request = build_multipart_upload_request(
access_token=access_token,
file_path=file_path,
diff --git a/tests/unit/google/test_google_oauth.py b/tests/unit/google/test_google_oauth.py
index 0e7e8b3da..3c1eaaed8 100644
--- a/tests/unit/google/test_google_oauth.py
+++ b/tests/unit/google/test_google_oauth.py
@@ -10,6 +10,7 @@ from fastapi import HTTPException
from pydantic import ValidationError
from sqlalchemy.sql.elements import BindParameter
+from skyvern.forge.agent_functions import AgentFunction
from skyvern.forge.sdk.db.enums import OrganizationAuthTokenType
from skyvern.forge.sdk.encrypt.base import EncryptMethod
from skyvern.forge.sdk.routes import google_oauth as google_oauth_routes
@@ -21,6 +22,7 @@ from skyvern.forge.sdk.schemas.google_oauth import (
UpdateGoogleOAuthCredentialRequest,
)
from skyvern.forge.sdk.services import google_drive_service, google_oauth_service
+from skyvern.schemas.workflows import FileStorageType, FileUploadDestination
def _unwrap_bind(value: Any) -> Any:
@@ -148,6 +150,75 @@ async def test_google_drive_uploads_multipart(
assert b'"name":"report.txt"' in body
+async def test_google_drive_uploads_zero_byte_file_as_multipart(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path,
+) -> None:
+ source = tmp_path / "empty"
+ source.write_bytes(b"")
+ requests: list[str] = []
+
+ async def handler(request: httpx.Request) -> httpx.Response:
+ requests.append(request.url.params["uploadType"])
+ assert request.method == "POST"
+ assert await request.aread()
+ return httpx.Response(200, json={"id": "file_empty"})
+
+ _install_google_drive_transport(monkeypatch, handler)
+
+ uploaded = await google_drive_service.upload_file(
+ access_token="at-1",
+ file_path=str(source),
+ folder_id="folder_123",
+ )
+
+ assert uploaded.id == "file_empty"
+ assert requests == ["multipart"]
+
+
+ ("file_size", "expected_mode"),
+ [
+ (google_drive_service.DRIVE_MULTIPART_FILE_MAX_BYTES, "multipart"),
+ (google_drive_service.DRIVE_MULTIPART_FILE_MAX_BYTES + 1, "resumable"),
+ (google_drive_service.DRIVE_MULTIPART_UPLOAD_MAX_BYTES, "resumable"),
+ ],
+)
+async def test_google_drive_upload_boundary_selects_expected_mode(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path,
+ file_size: int,
+ expected_mode: str,
+) -> None:
+ source = tmp_path / "boundary.bin"
+ source.write_bytes(b"x" * file_size)
+ session_uri = "https://www.googleapis.com/upload/session"
+ requests: list[tuple[str, str]] = []
+
+ async def handler(request: httpx.Request) -> httpx.Response:
+ upload_type = request.url.params.get("uploadType", "session")
+ requests.append((request.method, upload_type))
+ if upload_type == "resumable":
+ return httpx.Response(200, headers={"Location": session_uri})
+ return httpx.Response(200, json={"id": "file_boundary"})
+
+ _install_google_drive_transport(monkeypatch, handler)
+
+ uploaded = await google_drive_service.upload_file(
+ access_token="at-1",
+ file_path=str(source),
+ folder_id="folder_123",
+ )
+
+ assert uploaded.id == "file_boundary"
+ if expected_mode == "multipart":
+ assert requests == [("POST", "multipart")]
+ else:
+ assert requests == [("POST", "resumable"), ("PUT", "session")]
+
+
@pytest.mark.asyncio
async def test_google_drive_upload_does_not_retry_retryable_create_response(
monkeypatch: pytest.MonkeyPatch,
@@ -244,13 +315,12 @@ async def test_google_drive_upload_does_not_retry_ambiguous_transport_failure(
sleep_mock.assert_not_awaited()
-async def test_google_drive_upload_rejects_multipart_files_over_google_limit(tmp_path) -> None:
+def test_google_drive_multipart_builder_rejects_files_over_google_limit(tmp_path) -> None:
source = tmp_path / "large.bin"
source.write_bytes(b"x" * (google_drive_service.DRIVE_MULTIPART_UPLOAD_MAX_BYTES + 1))
with pytest.raises(google_drive_service.GoogleDriveAPIError) as exc_info:
- await google_drive_service.upload_file(
+ google_drive_service.build_multipart_upload_request(
access_token="at-1",
file_path=str(source),
folder_id="folder_123",
@@ -260,6 +330,430 @@ async def test_google_drive_upload_rejects_multipart_files_over_google_limit(tmp
assert exc_info.value.code == "file_too_large"
+def test_google_drive_should_use_resumable_upload(monkeypatch: pytest.MonkeyPatch, tmp_path) -> None:
+ monkeypatch.setattr(google_drive_service, "DRIVE_MULTIPART_FILE_MAX_BYTES", 4)
+ threshold_file = tmp_path / "threshold.bin"
+ threshold_file.write_bytes(b"1234")
+ large_file = tmp_path / "large.bin"
+ large_file.write_bytes(b"12345")
+
+ assert google_drive_service.should_use_resumable_upload(str(threshold_file)) is False
+ assert google_drive_service.should_use_resumable_upload(str(large_file)) is True
+
+
+def test_google_drive_file_near_multipart_cap_uses_resumable(tmp_path) -> None:
+ boundary_file = tmp_path / "boundary.bin"
+ boundary_file.write_bytes(b"x" * google_drive_service.DRIVE_MULTIPART_UPLOAD_MAX_BYTES)
+ small_file = tmp_path / "small.bin"
+ small_file.write_bytes(b"hello-drive")
+
+ assert google_drive_service.should_use_resumable_upload(str(boundary_file)) is True
+ assert google_drive_service.should_use_resumable_upload(str(small_file)) is False
+
+
+async def test_google_drive_uploads_resumable_for_large_files(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setattr(google_drive_service, "DRIVE_MULTIPART_FILE_MAX_BYTES", 4)
+ source = tmp_path / "report.txt"
+ file_bytes = b"hello-drive"
+ source.write_bytes(file_bytes)
+ session_uri = "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&upload_id=sess_1"
+ requests: list[tuple[str, str]] = []
+
+ async def handler(request: httpx.Request) -> httpx.Response:
+ url = str(request.url)
+ requests.append((request.method, url))
+ if request.method == "POST":
+ assert "uploadType=resumable" in url
+ assert request.url.params["fields"] == "id,name,webViewLink"
+ assert request.url.params["supportsAllDrives"] == "true"
+ assert request.headers["Authorization"] == "Bearer at-1"
+ assert request.headers["Content-Type"] == "application/json; charset=UTF-8"
+ assert request.headers["X-Upload-Content-Type"] == "text/plain"
+ assert request.headers["X-Upload-Content-Length"] == str(len(file_bytes))
+ assert await request.aread() == b'{"name":"report.txt","parents":["folder_123"]}'
+ return httpx.Response(200, headers={"Location": session_uri})
+
+ assert request.method == "PUT"
+ assert url == session_uri
+ assert request.headers["Content-Type"] == "text/plain"
+ assert request.headers["Content-Length"] == str(len(file_bytes))
+ assert "Transfer-Encoding" not in request.headers
+ assert "Authorization" not in request.headers
+ assert await request.aread() == file_bytes
+ return httpx.Response(
+ 200,
+ json={
+ "id": "file_789",
+ "name": "report.txt",
+ "webViewLink": "https://drive.google.com/file/d/file_789/view",
+ },
+ )
+
+ _install_google_drive_transport(monkeypatch, handler)
+
+ uploaded = await google_drive_service.upload_file(
+ access_token="at-1",
+ file_path=str(source),
+ folder_id="folder_123",
+ )
+
+ assert uploaded.id == "file_789"
+ assert [method for method, _url in requests] == ["POST", "PUT"]
+ assert requests[1][1] == session_uri
+
+
+async def test_google_drive_resumable_initiation_accepts_201_and_streams_multiple_chunks(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setattr(google_drive_service, "DRIVE_MULTIPART_FILE_MAX_BYTES", 1)
+ monkeypatch.setattr(google_drive_service, "DRIVE_RESUMABLE_UPLOAD_CHUNK_BYTES", 3)
+ source = tmp_path / "payload"
+ file_bytes = b"0123456789"
+ source.write_bytes(file_bytes)
+ session_uri = "https://www.googleapis.com/upload/session"
+ received_body: bytes | None = None
+
+ async def handler(request: httpx.Request) -> httpx.Response:
+ nonlocal received_body
+ if request.method == "POST":
+ assert request.headers["X-Upload-Content-Type"] == "application/octet-stream"
+ return httpx.Response(201, headers={"Location": session_uri})
+ assert request.headers["Content-Type"] == "application/octet-stream"
+ received_body = await request.aread()
+ return httpx.Response(200, json={"id": "file_chunked"})
+
+ _install_google_drive_transport(monkeypatch, handler)
+
+ uploaded = await google_drive_service.upload_file(
+ access_token="at-1",
+ file_path=str(source),
+ folder_id="folder_123",
+ )
+
+ assert uploaded.id == "file_chunked"
+ assert received_body == file_bytes
+
+
+async def test_google_drive_resumable_204_without_location_raises(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setattr(google_drive_service, "DRIVE_MULTIPART_FILE_MAX_BYTES", 1)
+ source = tmp_path / "payload.bin"
+ source.write_bytes(b"large")
+ requests: list[str] = []
+
+ async def handler(request: httpx.Request) -> httpx.Response:
+ requests.append(request.method)
+ return httpx.Response(204)
+
+ _install_google_drive_transport(monkeypatch, handler)
+
+ with pytest.raises(google_drive_service.GoogleDriveAPIError) as exc_info:
+ await google_drive_service.upload_file(
+ access_token="at-1",
+ file_path=str(source),
+ folder_id="folder_123",
+ )
+
+ assert exc_info.value.code == "missing_resumable_session"
+ assert requests == ["POST"]
+
+
+async def test_google_drive_resumable_initiation_rejects_redirect(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setattr(google_drive_service, "DRIVE_MULTIPART_FILE_MAX_BYTES", 1)
+ source = tmp_path / "payload.bin"
+ source.write_bytes(b"large")
+ session_uri = "https://www.googleapis.com/upload/session"
+ requests: list[str] = []
+
+ async def handler(request: httpx.Request) -> httpx.Response:
+ requests.append(request.method)
+ return httpx.Response(302, headers={"Location": session_uri})
+
+ _install_google_drive_transport(monkeypatch, handler)
+
+ with pytest.raises(google_drive_service.GoogleDriveAPIError) as exc_info:
+ await google_drive_service.upload_file(
+ access_token="at-1",
+ file_path=str(source),
+ folder_id="folder_123",
+ )
+
+ assert exc_info.value.status == 302
+ assert requests == ["POST"]
+
+
+async def test_google_drive_resumable_final_response_missing_id_raises(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setattr(google_drive_service, "DRIVE_MULTIPART_FILE_MAX_BYTES", 1)
+ source = tmp_path / "payload.bin"
+ source.write_bytes(b"large")
+ session_uri = "https://www.googleapis.com/upload/session"
+
+ async def handler(request: httpx.Request) -> httpx.Response:
+ if request.method == "POST":
+ return httpx.Response(200, headers={"Location": session_uri})
+ return httpx.Response(200, json={"name": "payload.bin"})
+
+ _install_google_drive_transport(monkeypatch, handler)
+
+ with pytest.raises(google_drive_service.GoogleDriveAPIError) as exc_info:
+ await google_drive_service.upload_file(
+ access_token="at-1",
+ file_path=str(source),
+ folder_id="folder_123",
+ )
+
+ assert exc_info.value.code == "malformed_response"
+
+
+async def test_google_drive_resumable_missing_web_view_link_uses_fallback(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setattr(google_drive_service, "DRIVE_MULTIPART_FILE_MAX_BYTES", 1)
+ source = tmp_path / "payload.bin"
+ source.write_bytes(b"large")
+ session_uri = "https://www.googleapis.com/upload/session"
+
+ async def handler(request: httpx.Request) -> httpx.Response:
+ if request.method == "POST":
+ return httpx.Response(200, headers={"Location": session_uri})
+ return httpx.Response(200, json={"id": "file_without_link"})
+
+ _install_google_drive_transport(monkeypatch, handler)
+ destination = FileUploadDestination(
+ storage_type=FileStorageType.GOOGLE_DRIVE,
+ customer_uri="https://drive.google.com/drive/folders/folder_123",
+ sdk_uri="https://drive.google.com/drive/folders/folder_123",
+ google_access_token="at-1",
+ google_drive_folder_id="folder_123",
+ )
+
+ result = await AgentFunction().upload_file_to_customer_storage(
+ file_path=str(source),
+ destination=destination,
+ )
+
+ assert result == "https://drive.google.com/file/d/file_without_link/view"
+
+
+async def test_google_drive_resumable_initiation_retries_connect_error(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setattr(google_drive_service, "DRIVE_MULTIPART_FILE_MAX_BYTES", 1)
+ source = tmp_path / "payload.bin"
+ source.write_bytes(b"large")
+ session_uri = "https://www.googleapis.com/upload/session"
+ post_calls = 0
+ put_calls = 0
+
+ async def handler(request: httpx.Request) -> httpx.Response:
+ nonlocal post_calls, put_calls
+ if request.method == "POST":
+ post_calls += 1
+ if post_calls == 1:
+ raise httpx.ConnectError("connect failed", request=request)
+ return httpx.Response(200, headers={"Location": session_uri})
+ put_calls += 1
+ return httpx.Response(200, json={"id": "file_retry"})
+
+ _install_google_drive_transport(monkeypatch, handler)
+ sleep_mock = AsyncMock()
+ monkeypatch.setattr(google_drive_service.asyncio, "sleep", sleep_mock)
+
+ uploaded = await google_drive_service.upload_file(
+ access_token="at-1",
+ file_path=str(source),
+ folder_id="folder_123",
+ )
+
+ assert uploaded.id == "file_retry"
+ assert post_calls == 2
+ assert put_calls == 1
+ sleep_mock.assert_awaited_once_with(1.0)
+
+
+async def test_google_drive_resumable_initiation_does_not_retry_read_timeout(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setattr(google_drive_service, "DRIVE_MULTIPART_FILE_MAX_BYTES", 1)
+ source = tmp_path / "payload.bin"
+ source.write_bytes(b"large")
+ calls = 0
+
+ async def handler(request: httpx.Request) -> httpx.Response:
+ nonlocal calls
+ calls += 1
+ raise httpx.ReadTimeout("read timed out", request=request)
+
+ _install_google_drive_transport(monkeypatch, handler)
+ sleep_mock = AsyncMock()
+ monkeypatch.setattr(google_drive_service.asyncio, "sleep", sleep_mock)
+
+ with pytest.raises(google_drive_service.GoogleDriveAPIError) as exc_info:
+ await google_drive_service.upload_file(
+ access_token="at-1",
+ file_path=str(source),
+ folder_id="folder_123",
+ )
+
+ assert exc_info.value.code == "ambiguous_upload_status"
+ assert calls == 1
+ sleep_mock.assert_not_awaited()
+
+
+async def test_google_drive_resumable_put_does_not_retry_read_timeout(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setattr(google_drive_service, "DRIVE_MULTIPART_FILE_MAX_BYTES", 1)
+ source = tmp_path / "payload.bin"
+ source.write_bytes(b"large")
+ session_uri = "https://www.googleapis.com/upload/session"
+ post_calls = 0
+ put_calls = 0
+
+ async def handler(request: httpx.Request) -> httpx.Response:
+ nonlocal post_calls, put_calls
+ if request.method == "POST":
+ post_calls += 1
+ return httpx.Response(200, headers={"Location": session_uri})
+ put_calls += 1
+ raise httpx.ReadTimeout("read timed out", request=request)
+
+ _install_google_drive_transport(monkeypatch, handler)
+
+ with pytest.raises(google_drive_service.GoogleDriveAPIError) as exc_info:
+ await google_drive_service.upload_file(
+ access_token="at-1",
+ file_path=str(source),
+ folder_id="folder_123",
+ )
+
+ assert exc_info.value.code == "ambiguous_upload_status"
+ assert post_calls == 1
+ assert put_calls == 1
+
+
+async def test_google_drive_resumable_missing_location_raises(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setattr(google_drive_service, "DRIVE_MULTIPART_FILE_MAX_BYTES", 4)
+ source = tmp_path / "report.txt"
+ source.write_text("hello-drive")
+
+ async def handler(request: httpx.Request) -> httpx.Response:
+ assert request.method == "POST"
+ return httpx.Response(200)
+
+ _install_google_drive_transport(monkeypatch, handler)
+
+ with pytest.raises(google_drive_service.GoogleDriveAPIError) as exc_info:
+ await google_drive_service.upload_file(
+ access_token="at-1",
+ file_path=str(source),
+ folder_id="folder_123",
+ )
+
+ assert exc_info.value.status == 502
+ assert exc_info.value.code == "missing_resumable_session"
+
+
+async def test_google_drive_resumable_malformed_final_response_raises(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setattr(google_drive_service, "DRIVE_MULTIPART_FILE_MAX_BYTES", 4)
+ source = tmp_path / "report.txt"
+ source.write_text("hello-drive")
+ session_uri = "https://www.googleapis.com/upload/session"
+
+ async def handler(request: httpx.Request) -> httpx.Response:
+ if request.method == "POST":
+ return httpx.Response(200, headers={"Location": session_uri})
+ assert request.method == "PUT"
+ return httpx.Response(200, content=b"not json")
+
+ _install_google_drive_transport(monkeypatch, handler)
+
+ with pytest.raises(google_drive_service.GoogleDriveAPIError) as exc_info:
+ await google_drive_service.upload_file(
+ access_token="at-1",
+ file_path=str(source),
+ folder_id="folder_123",
+ )
+
+ assert exc_info.value.code == "malformed_response"
+
+
+def test_google_drive_extracts_resumable_session_uri_case_insensitively() -> None:
+ assert (
+ google_drive_service.extract_resumable_session_uri({"location": "https://www.googleapis.com/upload/session"})
+ == "https://www.googleapis.com/upload/session"
+ )
+
+
+def test_google_drive_resumable_session_uri_accepts_googleapis_subdomain() -> None:
+ session_uri = "https://storage.googleapis.com/upload/session"
+
+ assert google_drive_service.extract_resumable_session_uri({"Location": session_uri}) == session_uri
+
+
+ "session_uri",
+ [
+ "https://googleapis.com.evil.com/upload",
+ "https://[email protected]/upload",
+ "https://[email protected]/upload",
+ "https://www.googleapis.com:444/upload",
+ ],
+)
+def test_google_drive_resumable_session_uri_rejects_ssrf_variants(session_uri: str) -> None:
+ with pytest.raises(google_drive_service.GoogleDriveAPIError) as exc_info:
+ google_drive_service.extract_resumable_session_uri({"Location": session_uri})
+
+ assert exc_info.value.code == "invalid_resumable_session"
+
+
+def test_google_drive_resumable_session_uri_rejects_non_google_host() -> None:
+ with pytest.raises(google_drive_service.GoogleDriveAPIError) as exc_info:
+ google_drive_service.extract_resumable_session_uri({"location": "https://evil.example.com/upload"})
+
+ assert exc_info.value.code == "invalid_resumable_session"
+
+
+def test_google_drive_resumable_session_uri_rejects_http() -> None:
+ with pytest.raises(google_drive_service.GoogleDriveAPIError) as exc_info:
+ google_drive_service.extract_resumable_session_uri({"location": "http://www.googleapis.com/upload"})
+
+ assert exc_info.value.code == "invalid_resumable_session"
+
+
def test_google_drive_maps_insufficient_scope_to_reconnect() -> None:
response = httpx.Response(
403,