mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-18 06:01:49 +01:00
feat(connections): show a data-use disclosure in the Google Workspace picker (#21998)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The built-in Google Workspace connection lets agents use Gmail, Drive (with Docs, Sheets and Slides) and Calendar > - Google reviews this connection for restricted scopes. Google requires a disclosure in the product, shown just before the consent request, that says what data the app accesses and how it uses and shares that data. A link to the privacy policy alone is not sufficient > - Before this change, the service picker showed only three service rows and Cancel / Continue. Its only description was text for screen readers > - This pull request adds a visible data-use disclosure to the picker. The disclosure changes with the selected services and access levels > - The benefit is that every user sees what agents can do and where the data goes before Google asks for consent, and the connection meets this review requirement ## Linked Issues or Issue Description Refs #21996 (the code-fix plan, section 1, describes this change). **Is your feature request related to a problem?** Google's restricted-scope review requires an in-product data-use disclosure immediately before the consent request. The Google Workspace service picker has no visible disclosure. It does not say what agents can do with each service, that content goes to the configured AI model provider, how long results stay, or where the privacy policy is. **Describe the solution you'd like** Show a short disclosure between the service rows and the footer. Build it from the current selection. Describe only the selected services, at the selected access level. Explain use, sharing and retention. Link the privacy policy and mention Google's Limited Use requirements. **Describe alternatives you've considered** A privacy-policy link only. Google does not accept this as a disclosure. A separate confirmation step after the picker. This adds a click to every setup and reconnect, and the picker is already the last Paperclip screen before Google consent. ## What Changed - `ui/src/features/connections/googleWorkspaceDisclosure.ts` (new): a pure function `googleWorkspaceDataUseDisclosure(selection)` returns the plain sentences for the selected services and the use/sharing sentences. It also exports the privacy policy URL (`https://paperclip.ing/privacy`). - `ui/src/features/connections/GoogleWorkspaceServices.tsx`: `ServicePicker` shows the disclosure above the footer when one or more services are on. With no services on, it keeps the existing "Select at least one service to continue." message and shows no disclosure. The privacy link opens in a new tab. The dialog now scrolls inside 85% of the viewport height, so the footer stays reachable on a phone. This one picker serves new setup and reconnect, in the Apps flow and in task-hosted setup. - `ui/src/features/connections/GoogleWorkspaceServices.test.tsx`: tests for each service at each access level, picker order, Gmail send wording (read only never mentions sending; read & write only says that Paperclip does not send), the empty selection, the rendered block, the link, and the block's position before the footer. - `ui/src/pages/apps/AppDetail.tsx` and `ui/src/pages/apps/app-detail/AdvancedPanel.tsx`: the app detail page's Reconnect card, "Connect as me", "Connect organization identity" and the dedicated-agent connect started Google sign-in directly. For a Google Workspace connection they now open the same picker first. The picker is filled from the saved request. The chosen services go to the sign-in request (`workspaceServices`, or `scopes` for personal authorization). Other apps start sign-in as before. The gate is `useGoogleWorkspaceServiceGate` in `GoogleWorkspaceServices.tsx`. - `ui/src/pages/apps/AppDetail.test.tsx`: tests for each app-detail path, including Cancel (no sign-in starts). - `ui/storybook/stories/connection-setup/google-workspace-services.stories.tsx`: new `ProductionPickerReadOnly` story (with a play test) and `ProductionPickerMobile` story. Notes on the design (kept here because the change adds no code comments): - Every Google Workspace sign-in must pass through the service picker, so the disclosure always comes just before Google's consent screen. `useGoogleWorkspaceServiceGate` opens the picker for a Google Workspace connection and starts other connections at once. - Gmail read & write only creates drafts. Google's consent screen describes the compose permission as also sending email, so the Gmail line says this and states that Paperclip does not send email. Tests enforce this wording. ### Disclosure copy for sign-off Section heading 1: **What agents can do**. One line for each selected service. Unselected services are not mentioned. | Service | Read only | Read & write | | --- | --- | --- | | Gmail | "Gmail: agents can read and search your email." | "Gmail: agents can read and search your email, and create drafts. Google's permission screen also mentions sending email; Paperclip does not send email." | | Drive | "Drive: agents can read and search your files, Docs, Sheets and Slides." | "Drive: agents can read and search your files, Docs, Sheets and Slides. They can also create files and edit Docs, Sheets and Slides." | | Calendar | "Calendar: agents can see your calendars, events and free/busy times." | "Calendar: agents can see your calendars, events and free/busy times. They can also create, change and delete events, and respond to invitations." | Section heading 2: **How your data is used**. Always shown when one or more services are selected: - "Agents read this content only to do the tasks you give them." - "To do that, the content is sent to the AI model provider configured for your workspace." - "It is not used to train general AI models." - "Results are saved in the task and its run history. They stay there until you delete them, even after you disconnect." Link (opens `https://paperclip.ing/privacy` in a new tab): "Read our privacy policy, including how we meet Google's Limited Use requirements" No services selected: "Select at least one service to continue." (unchanged). No disclosure is shown. ### Screenshots (Storybook, production picker; taken before the Gmail wording change) Desktop, dark:  Desktop, light:  Phone (375 px), top and scrolled to the footer: <img width="300" alt="Picker on a phone, top" src="https://raw.githubusercontent.com/cryppadotta/paperclip-upstream-fork/pr-assets/google-workspace-data-use-disclosure/pr-assets/google-workspace-disclosure/picker-mobile.png"> <img width="300" alt="Picker on a phone, scrolled to the footer" src="https://raw.githubusercontent.com/cryppadotta/paperclip-upstream-fork/pr-assets/google-workspace-data-use-disclosure/pr-assets/google-workspace-disclosure/picker-mobile-bottom.png"> ## Verification - Red first: with a stub helper, 9 new tests failed. The 5 app-detail tests failed before the reconnect fix (sign-in started without the picker). The changed Gmail wording tests failed before the copy change. After the changes: `cd ui && npx vitest run src/features/connections/GoogleWorkspaceServices.test.tsx src/pages/apps/AppDetail.test.tsx src/pages/apps/AppsConnect.test.tsx src/pages/apps/app-detail` passes, 395 tests. - `node scripts/check-token-gates.mjs`: all gates clean. - `cd ui && node ../scripts/run-tsc.mjs -b` passes. - `node scripts/storybook-catalog.mjs` passes. - Headless Playwright against Storybook dev: the `ProductionPicker` story at 1280x900 (dark and light) and the `ProductionPickerMobile` story at 375x812. No horizontal scroll at 375 px. The footer is reachable after scrolling the dialog. The `ProductionPickerReadOnly` play test ran to its end state. - `pnpm verify` exits 2 (a Storybook story is a broad input). Required CI supplies the broad coverage. - Manual: open Apps, start a Google Workspace connection. Turn services on and off and change the access levels. Make sure that the disclosure changes and that unselected services are not mentioned. ## Risks - Low code risk. The change is UI-only. It does not change the selection, scopes, OAuth or saved state. - Wording risk: the copy makes product statements (no training on content, results stay after disconnect). The owner must approve the wording. The published privacy policy must agree with it: today the policy does not yet name AI model providers and describes retention only while a connection is active. Update the policy before or together with this change. - The dialog is taller. On short screens it scrolls inside the dialog. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with tool use (shell, file edits, headless browser). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
12cb18e17d
commit
b124ad0674
7 files changed
+306
-14
No files matched your search
@@ -5,6 +5,7 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { googleWorkspaceSelectedScopes, type ToolConnection } from "@paperclipai/shared";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { GoogleWorkspaceServicesDialog } from "./GoogleWorkspaceServices";
|
||||
import { GOOGLE_WORKSPACE_PRIVACY_POLICY_URL, googleWorkspaceDataUseDisclosure } from "./googleWorkspaceDisclosure";
|
||||
|
||||
const listGrants = vi.hoisted(() => vi.fn());
|
||||
vi.mock("@/api/tools", () => ({ toolsApi: { listConnectionGrants: listGrants } }));
|
||||
@@ -151,3 +152,94 @@ describe("Workspace service consent", () => {
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
const GMAIL_SEND_NOTE = "Google's permission screen also mentions sending email; Paperclip does not send email.";
|
||||
|
||||
describe("Google Workspace data-use disclosure", () => {
|
||||
const use = [
|
||||
"Agents read this content only to do the tasks you give them.",
|
||||
"To do that, the content is sent to the AI model provider configured for your workspace.",
|
||||
"It is not used to train general AI models.",
|
||||
"Results are saved in the task and its run history. They stay there until you delete them, even after you disconnect.",
|
||||
];
|
||||
|
||||
it.each([
|
||||
[{ gmail: "read" }, ["Gmail: agents can read and search your email."]],
|
||||
[{ gmail: "write" }, ["Gmail: agents can read and search your email, and create drafts. Google's permission screen also mentions sending email; Paperclip does not send email."]],
|
||||
[{ drive: "read" }, ["Drive: agents can read and search your files, Docs, Sheets and Slides."]],
|
||||
[{ drive: "write" }, ["Drive: agents can read and search your files, Docs, Sheets and Slides. They can also create files and edit Docs, Sheets and Slides."]],
|
||||
[{ calendar: "read" }, ["Calendar: agents can see your calendars, events and free/busy times."]],
|
||||
[{ calendar: "write" }, ["Calendar: agents can see your calendars, events and free/busy times. They can also create, change and delete events, and respond to invitations."]],
|
||||
] as const)("describes only the selected service (%o)", (selection, access) => {
|
||||
expect(googleWorkspaceDataUseDisclosure(selection)).toEqual({ access, use });
|
||||
});
|
||||
|
||||
it("lists every selected service in picker order and always explains sharing", () => {
|
||||
const disclosure = googleWorkspaceDataUseDisclosure({ calendar: "read", gmail: "write", drive: "read" });
|
||||
expect(disclosure.access.map(line => line.split(":")[0])).toEqual(["Gmail", "Drive", "Calendar"]);
|
||||
expect(disclosure.use).toContain("To do that, the content is sent to the AI model provider configured for your workspace.");
|
||||
});
|
||||
|
||||
it("never claims Gmail can send: read only never mentions sending, read & write only says Paperclip does not send", () => {
|
||||
const text = (gmail: "read" | "write") => {
|
||||
const { access, use } = googleWorkspaceDataUseDisclosure({ gmail });
|
||||
return [...access, ...use].join(" ");
|
||||
};
|
||||
expect(text("read")).not.toMatch(/send/i);
|
||||
expect(text("write")).toContain("Paperclip does not send email.");
|
||||
expect(text("write").replace(GMAIL_SEND_NOTE, "")).not.toMatch(/send/i);
|
||||
});
|
||||
|
||||
it("says nothing with no services selected", () => {
|
||||
expect(googleWorkspaceDataUseDisclosure({})).toEqual({ access: [], use: [] });
|
||||
});
|
||||
});
|
||||
|
||||
describe("Workspace picker disclosure", () => {
|
||||
let root: Root;
|
||||
let container: HTMLDivElement;
|
||||
const flush = async () => { await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); }); };
|
||||
beforeEach(() => {
|
||||
container = document.createElement("div");
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
});
|
||||
afterEach(async () => {
|
||||
await act(async () => { root.unmount(); });
|
||||
container.remove();
|
||||
});
|
||||
async function render(initial?: Record<string, "read" | "write">) {
|
||||
await act(async () => { root.render(<QueryClientProvider client={new QueryClient()}>
|
||||
<GoogleWorkspaceServicesDialog initial={initial} onContinue={vi.fn()} onCancel={vi.fn()} />
|
||||
</QueryClientProvider>); });
|
||||
await flush();
|
||||
}
|
||||
const disclosure = () => document.querySelector('[aria-label="How Paperclip uses your Google data"]');
|
||||
|
||||
it("shows the selected services, sharing and privacy policy before Continue", async () => {
|
||||
await render({ gmail: "write", calendar: "read" });
|
||||
const block = disclosure()!;
|
||||
expect(block.textContent).toContain("Gmail: agents can read and search your email, and create drafts. Google's permission screen also mentions sending email; Paperclip does not send email.");
|
||||
expect(block.textContent).toContain("Calendar: agents can see your calendars, events and free/busy times.");
|
||||
expect(block.textContent).not.toContain("Drive");
|
||||
expect(block.textContent!.replace(GMAIL_SEND_NOTE, "")).not.toMatch(/\bsend/i);
|
||||
expect(block.textContent).toContain("the content is sent to the AI model provider configured for your workspace");
|
||||
const link = block.querySelector("a")!;
|
||||
expect(link.getAttribute("href")).toBe(GOOGLE_WORKSPACE_PRIVACY_POLICY_URL);
|
||||
expect(GOOGLE_WORKSPACE_PRIVACY_POLICY_URL).toBe("https://paperclip.ing/privacy");
|
||||
expect(link.getAttribute("target")).toBe("_blank");
|
||||
expect(link.getAttribute("rel")).toContain("noopener");
|
||||
expect(link.textContent).toContain("Limited Use");
|
||||
const footer = document.querySelector("footer")!;
|
||||
expect(block.compareDocumentPosition(footer) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
});
|
||||
|
||||
it("follows the selection as services are turned off", async () => {
|
||||
await render({ drive: "read" });
|
||||
expect(disclosure()!.textContent).toContain("Drive: agents can read and search your files");
|
||||
const toggle = document.querySelector<HTMLButtonElement>("#workspace-service-drive")!;
|
||||
await act(async () => { toggle.click(); });
|
||||
expect(disclosure()).toBeNull();
|
||||
expect(document.body.textContent).toContain("Select at least one service to continue.");
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useQueryView } from "@/components/QueryView";
|
||||
import { useState } from "react";
|
||||
import { useState, type ReactNode } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { GOOGLE_WORKSPACE_DEFAULT_SELECTION, GOOGLE_WORKSPACE_SERVICE_GROUPS, googleWorkspaceDraftRequestedScopes, googleWorkspaceSelectionForScopes, type GoogleWorkspaceServiceSelection, type ToolConnection } from "@paperclipai/shared";
|
||||
import { toolsApi } from "@/api/tools";
|
||||
@@ -8,6 +8,7 @@ import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } f
|
||||
import { NativeSelect } from "@/components/ui/select";
|
||||
import { ToggleSwitch } from "@/components/ui/toggle-switch";
|
||||
import { AppLogo } from "@/pages/apps/AppLogo";
|
||||
import { GOOGLE_WORKSPACE_PRIVACY_POLICY_URL, googleWorkspaceDataUseDisclosure } from "./googleWorkspaceDisclosure";
|
||||
|
||||
export function GoogleWorkspaceServiceFields({ value, onChange }: {
|
||||
value: GoogleWorkspaceServiceSelection;
|
||||
@@ -36,6 +37,26 @@ export function GoogleWorkspaceServiceFields({ value, onChange }: {
|
||||
</div>;
|
||||
}
|
||||
|
||||
export function isGoogleWorkspaceConnection(connection: Pick<ToolConnection, "config">): boolean {
|
||||
return connection.config?.sourceTemplateKey === "google-workspace";
|
||||
}
|
||||
|
||||
export function useGoogleWorkspaceServiceGate(): {
|
||||
dialog: ReactNode;
|
||||
run: (connection: ToolConnection, start: (selection?: GoogleWorkspaceServiceSelection) => void) => void;
|
||||
} {
|
||||
const [pending, setPending] = useState<{ connection: ToolConnection; start: (selection: GoogleWorkspaceServiceSelection) => void } | null>(null);
|
||||
return {
|
||||
dialog: pending ? <GoogleWorkspaceServicesDialog connection={pending.connection}
|
||||
onCancel={() => setPending(null)}
|
||||
onContinue={selection => { setPending(null); pending.start(selection); }} /> : null,
|
||||
run: (connection, start) => {
|
||||
if (isGoogleWorkspaceConnection(connection)) setPending({ connection, start });
|
||||
else start();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
type DialogProps = {
|
||||
onContinue: (value: GoogleWorkspaceServiceSelection) => void;
|
||||
onCancel: (selection?: GoogleWorkspaceServiceSelection) => void;
|
||||
@@ -77,17 +98,38 @@ export function GoogleWorkspaceServicesDialog(props: DialogProps) {
|
||||
return <ServicePicker {...props} initial={props.initial ?? (pendingScopes ? googleWorkspaceSelectionForScopes(pendingScopes) : existing ? googleWorkspaceSelectionForScopes(savedScopes) : undefined)} />;
|
||||
}
|
||||
|
||||
function DataUseDisclosure({ selection }: { selection: GoogleWorkspaceServiceSelection }) {
|
||||
const { access, use } = googleWorkspaceDataUseDisclosure(selection);
|
||||
return <section aria-label="How Paperclip uses your Google data" className="space-y-3 text-sm">
|
||||
<div className="space-y-1">
|
||||
<h3 className="font-medium">What agents can do</h3>
|
||||
<ul className="list-disc space-y-1 pl-5 text-muted-foreground">{access.map(line => <li key={line}>{line}</li>)}</ul>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<h3 className="font-medium">How your data is used</h3>
|
||||
<ul className="list-disc space-y-1 pl-5 text-muted-foreground">{use.map(line => <li key={line}>{line}</li>)}</ul>
|
||||
</div>
|
||||
<p className="text-muted-foreground">
|
||||
<a href={GOOGLE_WORKSPACE_PRIVACY_POLICY_URL} target="_blank" rel="noopener noreferrer" className="underline">
|
||||
Read our privacy policy, including how we meet Google's Limited Use requirements<span className="sr-only"> (opens in a new tab)</span>
|
||||
</a>
|
||||
</p>
|
||||
</section>;
|
||||
}
|
||||
|
||||
function ServicePicker({ onContinue, onCancel, initial = GOOGLE_WORKSPACE_DEFAULT_SELECTION }: DialogProps) {
|
||||
const [selection, setSelection] = useState(initial);
|
||||
const empty = Object.keys(selection).length === 0;
|
||||
return <Dialog open onOpenChange={open => { if (!open) onCancel(selection); }}>
|
||||
<DialogContent className="sm:max-w-3xl">
|
||||
<DialogContent className="max-h-(--sz-85vh) overflow-y-auto sm:max-w-3xl">
|
||||
<DialogHeader className="text-left">
|
||||
<div className="flex items-center gap-3"><AppLogo name="Google Workspace" brandKey="google" size={40} /><DialogTitle>Connect Google Workspace</DialogTitle></div>
|
||||
<DialogDescription className="sr-only">Choose the Google services to connect.</DialogDescription>
|
||||
</DialogHeader>
|
||||
<GoogleWorkspaceServiceFields value={selection} onChange={setSelection} />
|
||||
{empty && <p role="status" className="text-xs text-muted-foreground">Select at least one service to continue.</p>}
|
||||
{empty
|
||||
? <p role="status" className="text-xs text-muted-foreground">Select at least one service to continue.</p>
|
||||
: <DataUseDisclosure selection={selection} />}
|
||||
<footer className="flex items-center justify-between gap-3 pt-4">
|
||||
<Button variant="ghost" onClick={() => onCancel(selection)}>Cancel</Button>
|
||||
<Button disabled={empty} onClick={() => onContinue(selection)}>Continue</Button>
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { GOOGLE_WORKSPACE_SERVICE_GROUPS, type GoogleWorkspaceServiceSelection } from "@paperclipai/shared";
|
||||
|
||||
export const GOOGLE_WORKSPACE_PRIVACY_POLICY_URL = "https://paperclip.ing/privacy";
|
||||
|
||||
type ServiceId = (typeof GOOGLE_WORKSPACE_SERVICE_GROUPS)[number]["id"];
|
||||
|
||||
const ACCESS: Record<ServiceId, { read: string; write: string }> = {
|
||||
gmail: {
|
||||
read: "Gmail: agents can read and search your email.",
|
||||
write: "Gmail: agents can read and search your email, and create drafts. Google's permission screen also mentions sending email; Paperclip does not send email.",
|
||||
},
|
||||
drive: {
|
||||
read: "Drive: agents can read and search your files, Docs, Sheets and Slides.",
|
||||
write: "Drive: agents can read and search your files, Docs, Sheets and Slides. They can also create files and edit Docs, Sheets and Slides.",
|
||||
},
|
||||
calendar: {
|
||||
read: "Calendar: agents can see your calendars, events and free/busy times.",
|
||||
write: "Calendar: agents can see your calendars, events and free/busy times. They can also create, change and delete events, and respond to invitations.",
|
||||
},
|
||||
};
|
||||
|
||||
const USE = [
|
||||
"Agents read this content only to do the tasks you give them.",
|
||||
"To do that, the content is sent to the AI model provider configured for your workspace.",
|
||||
"It is not used to train general AI models.",
|
||||
"Results are saved in the task and its run history. They stay there until you delete them, even after you disconnect.",
|
||||
];
|
||||
|
||||
export function googleWorkspaceDataUseDisclosure(selection: GoogleWorkspaceServiceSelection): { access: string[]; use: string[] } {
|
||||
const access = GOOGLE_WORKSPACE_SERVICE_GROUPS.flatMap(group => {
|
||||
const level = selection[group.id];
|
||||
return level ? [ACCESS[group.id][level]] : [];
|
||||
});
|
||||
return { access, use: access.length > 0 ? [...USE] : [] };
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import type { ReactNode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { getAppStoreDefinition } from "@paperclipai/shared";
|
||||
import { getAppStoreDefinition, googleWorkspaceSelectedScopes } from "@paperclipai/shared";
|
||||
import type { AggregatorAppSnapshot, AggregatorAppsResponse } from "@paperclipai/shared/aggregator-apps";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
@@ -2115,4 +2115,96 @@ describe("AppDetail", () => {
|
||||
expect(dialogText).toContain("Who can use this identity");
|
||||
expect(dialogText).toContain("Every audience member must be an active company member");
|
||||
});
|
||||
describe("Google Workspace consent always shows the service picker first", () => {
|
||||
const GMAIL_READ = "https://www.googleapis.com/auth/gmail.readonly";
|
||||
function workspaceConnection(overrides: Record<string, unknown> = {}) {
|
||||
return connection({
|
||||
name: "Google Workspace", authKind: "oauth", credentialPolicy: "shared",
|
||||
config: { sourceTemplateKey: "google-workspace", connectionMethodKey: "oauth" },
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
function bodyButton(label: string) {
|
||||
return Array.from(document.body.querySelectorAll("button")).find((button) => button.textContent?.trim() === label);
|
||||
}
|
||||
async function clickBody(label: string) {
|
||||
await act(async () => { bodyButton(label)?.dispatchEvent(new MouseEvent("click", { bubbles: true })); });
|
||||
await flushReact();
|
||||
}
|
||||
const disclosure = () => document.body.querySelector('[aria-label="How Paperclip uses your Google data"]');
|
||||
|
||||
it("reconnects an expired shared account only after the picker, with the saved services", async () => {
|
||||
mockParams.tab = "permissions";
|
||||
getConnectionMock.mockResolvedValue(workspaceConnection({ healthStatus: "failed", healthMessage: "Authorization expired (invalid_grant)." }));
|
||||
listConnectionGrantsMock.mockResolvedValue({ connection: { id: "conn-1" }, capabilities: fullCapabilities(), currentUserId: "user-1", members: [],
|
||||
grants: [organizationGrant({ providerTenant: { oauth: { requestedScopes: [GMAIL_READ] } } })] });
|
||||
|
||||
await renderAppDetail();
|
||||
await clickBody("Reconnect");
|
||||
|
||||
expect(startOAuthMock).not.toHaveBeenCalled();
|
||||
expect(disclosure()?.textContent).toContain("Gmail: agents can read and search your email.");
|
||||
expect(disclosure()?.textContent).not.toContain("Drive");
|
||||
await clickBody("Continue");
|
||||
|
||||
expect(startOAuthMock).toHaveBeenCalledWith("conn-1", { workspaceServices: { gmail: "read" } });
|
||||
expect(popupAssignMock).toHaveBeenCalledWith("https://example.test/oauth");
|
||||
});
|
||||
|
||||
it("reconnects a personal account through the picker as the signed-in user", async () => {
|
||||
mockParams.tab = "permissions";
|
||||
getConnectionMock.mockResolvedValue(workspaceConnection({ credentialPolicy: "per_user", createdByUserId: "user-1", healthStatus: "failed", healthMessage: "Authorization expired (invalid_grant)." }));
|
||||
listConnectionGrantsMock.mockResolvedValue({ connection: { id: "conn-1" }, capabilities: fullCapabilities(), currentUserId: "user-1", members: [],
|
||||
grants: [personalGrant({ providerTenant: { oauth: { requestedScopes: [GMAIL_READ] } } })] });
|
||||
|
||||
await renderAppDetail();
|
||||
await clickBody("Reconnect");
|
||||
expect(startOAuthMock).not.toHaveBeenCalled();
|
||||
expect(disclosure()).not.toBeNull();
|
||||
await clickBody("Continue");
|
||||
|
||||
expect(startOAuthMock).toHaveBeenCalledWith("conn-1", { asCurrentUser: true, workspaceServices: { gmail: "read" } });
|
||||
});
|
||||
|
||||
it("cancelling the picker starts no sign-in", async () => {
|
||||
mockParams.tab = "permissions";
|
||||
getConnectionMock.mockResolvedValue(workspaceConnection({ healthStatus: "failed", healthMessage: "Authorization expired (invalid_grant)." }));
|
||||
await renderAppDetail();
|
||||
await clickBody("Reconnect");
|
||||
await clickBody("Cancel");
|
||||
expect(disclosure()).toBeNull();
|
||||
expect(startOAuthMock).not.toHaveBeenCalled();
|
||||
expect(popupAssignMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("connects the organization identity through the picker", async () => {
|
||||
mockParams.tab = "permissions";
|
||||
getConnectionMock.mockResolvedValue(workspaceConnection());
|
||||
await renderAppDetail();
|
||||
await clickBody("Connect organization identity");
|
||||
expect(startOAuthMock).not.toHaveBeenCalled();
|
||||
await act(async () => { document.body.querySelector<HTMLElement>("#workspace-service-gmail")?.dispatchEvent(new MouseEvent("click", { bubbles: true })); });
|
||||
await flushReact();
|
||||
expect(disclosure()?.textContent).toContain("Gmail: agents can read and search your email, and create drafts. Google's permission screen also mentions sending email; Paperclip does not send email.");
|
||||
await clickBody("Continue");
|
||||
expect(startOAuthMock).toHaveBeenCalledWith("conn-1", { workspaceServices: { gmail: "write" } });
|
||||
});
|
||||
|
||||
it("connects a personal identity through the picker with the chosen services", async () => {
|
||||
mockParams.tab = "permissions";
|
||||
getConnectionMock.mockResolvedValue(workspaceConnection({ credentialPolicy: "per_user" }));
|
||||
startPersonalAuthorizationMock.mockResolvedValue({ url: "https://accounts.example.test/authorize" });
|
||||
await renderAppDetail();
|
||||
await clickBody("Connect as me");
|
||||
expect(startPersonalAuthorizationMock).not.toHaveBeenCalled();
|
||||
await act(async () => { document.body.querySelector<HTMLElement>("#workspace-service-calendar")?.dispatchEvent(new MouseEvent("click", { bubbles: true })); });
|
||||
await flushReact();
|
||||
await clickBody("Continue");
|
||||
expect(startPersonalAuthorizationMock).toHaveBeenCalledWith("company-1", "conn-1", {
|
||||
subjectUserId: "user-1",
|
||||
returnTo: "/apps/conn-1/permissions",
|
||||
scopes: googleWorkspaceSelectedScopes({ calendar: "write" }),
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { AppNotFound, AppReadError } from "./app-detail/AppReadError";
|
||||
import { AiConnectionPoolConnector } from "@/components/ai-connections/AiConnectionPoolConnector";
|
||||
import { aiConnectionRouterPluginKey } from "@paperclipai/shared";
|
||||
import { aiConnectionRouterPluginKey, googleWorkspaceSelectedScopes, type GoogleWorkspaceServiceSelection } from "@paperclipai/shared";
|
||||
import { ConnectionInstructionsSettings } from "@/features/connections/ConnectionInstructions";
|
||||
import { HonchoWorkspaceSettings } from "@/features/connections/HonchoWorkspaceSettings";
|
||||
import { BrowserUseSettingsPanel } from "./app-detail/BrowserUseSettingsPanel";
|
||||
@@ -37,6 +37,7 @@ import { accessApi } from "@/api/access";
|
||||
import { buildCompanyUserProfileMap } from "@/lib/company-members";
|
||||
import { installStateFrom, type InstallState } from "@/lib/tool-installs";
|
||||
import { useAuthorizationWindow } from "@/hooks/useAuthorizationWindow";
|
||||
import { useGoogleWorkspaceServiceGate } from "@/features/connections/GoogleWorkspaceServices";
|
||||
import { QueryErrorState, useQueryView } from "@/components/QueryView";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
@@ -360,8 +361,9 @@ function StandardAppDetail({ renderActions, renderAgentSettings, renderConnectio
|
||||
});
|
||||
|
||||
const authorization = useAuthorizationWindow();
|
||||
const workspaceGate = useGoogleWorkspaceServiceGate();
|
||||
const startOAuth = useMutation({
|
||||
mutationFn: (input?: { asAgentId?: string }) => toolsApi.startOAuth(connectionId, input),
|
||||
mutationFn: (input?: { asAgentId?: string; workspaceServices?: GoogleWorkspaceServiceSelection }) => toolsApi.startOAuth(connectionId, input),
|
||||
onSuccess: async (start) => {
|
||||
try {
|
||||
await authorization.open(start);
|
||||
@@ -394,12 +396,13 @@ function StandardAppDetail({ renderActions, renderAgentSettings, renderConnectio
|
||||
* there is no path here to start consent on a coworker's behalf.
|
||||
*/
|
||||
const startPersonalAuth = useMutation({
|
||||
mutationFn: () => {
|
||||
mutationFn: (scopes?: string[]) => {
|
||||
const subjectUserId = grantsQuery.data?.currentUserId;
|
||||
if (!subjectUserId) throw new Error("Sign in again to connect your own account.");
|
||||
return toolsApi.startPersonalAuthorization(selectedCompanyId!, connectionId, {
|
||||
subjectUserId,
|
||||
returnTo: appTabHref(connectionId, "permissions"),
|
||||
...(scopes ? { scopes } : {}),
|
||||
});
|
||||
},
|
||||
onSuccess: async ({ url, handoff }) => {
|
||||
@@ -590,6 +593,7 @@ function StandardAppDetail({ renderActions, renderAgentSettings, renderConnectio
|
||||
return (
|
||||
<div className="max-w-4xl space-y-10 pb-12">
|
||||
{authorization.fallback}
|
||||
{workspaceGate.dialog}
|
||||
<AppDetailHeader
|
||||
appName={appName}
|
||||
connection={connection}
|
||||
@@ -695,9 +699,9 @@ function StandardAppDetail({ renderActions, renderAgentSettings, renderConnectio
|
||||
setAudienceOpenGrantId(null);
|
||||
setAudienceError(null);
|
||||
}}
|
||||
onConnectAsMe={() => { if (onReconnect) onReconnect(connection); else { authorization.reserve(); startPersonalAuth.mutate(); } }}
|
||||
onConnectOrganization={() => { if (onReconnect) onReconnect(connection); else { authorization.reserve(); startOAuth.mutate(); } }}
|
||||
onConnectAgent={(agentId) => { authorization.reserve(); startOAuth.mutate({ asAgentId: agentId }); }}
|
||||
onConnectAsMe={() => { if (onReconnect) onReconnect(connection); else workspaceGate.run(connection, (services) => { authorization.reserve(); startPersonalAuth.mutate(services ? googleWorkspaceSelectedScopes(services) : undefined); }); }}
|
||||
onConnectOrganization={() => { if (onReconnect) onReconnect(connection); else workspaceGate.run(connection, (services) => { authorization.reserve(); startOAuth.mutate(services ? { workspaceServices: services } : undefined); }); }}
|
||||
onConnectAgent={(agentId) => workspaceGate.run(connection, (services) => { authorization.reserve(); startOAuth.mutate({ asAgentId: agentId, ...(services ? { workspaceServices: services } : {}) }); })}
|
||||
onRefreshAccess={() => refreshGitHubAccess.mutate()}
|
||||
refreshAccessPending={refreshGitHubAccess.isPending}
|
||||
onReplaceAudience={(grant, memberUserIds) =>
|
||||
|
||||
@@ -4,6 +4,7 @@ import { ArrowUpRight, ChevronRight, Loader2, Lock } from "lucide-react";
|
||||
import type {
|
||||
AppDefinition,
|
||||
ConnectionGrant,
|
||||
GoogleWorkspaceServiceSelection,
|
||||
ToolConnection,
|
||||
ToolConnectionCredentialPolicy,
|
||||
} from "@paperclipai/shared";
|
||||
@@ -25,6 +26,7 @@ import { Link } from "@/lib/router";
|
||||
import type { AppDetailSectionProps } from "./types";
|
||||
import { RevokeGrantDialog } from "./IdentitiesSection";
|
||||
import { describeError } from "@/api/errors";
|
||||
import { useGoogleWorkspaceServiceGate } from "@/features/connections/GoogleWorkspaceServices";
|
||||
|
||||
export function AdvancedPanel({
|
||||
connection,
|
||||
@@ -161,13 +163,17 @@ export function ReconnectCard({
|
||||
}) {
|
||||
const { pushToast } = useToast();
|
||||
const authorization = useAuthorizationWindow();
|
||||
const workspaceGate = useGoogleWorkspaceServiceGate();
|
||||
const reconnectOAuth = useMutation({
|
||||
// Reconnect is not a new identity choice. Personal-only connections must
|
||||
// put the replacement token back on the signed-in user's existing grant;
|
||||
// shared and legacy fallback connections keep using the organization slot.
|
||||
mutationFn: () => connection.credentialPolicy === "per_user"
|
||||
? toolsApi.startOAuth(connection.id, { asCurrentUser: true })
|
||||
: toolsApi.startOAuth(connection.id),
|
||||
mutationFn: (workspaceServices?: GoogleWorkspaceServiceSelection) => {
|
||||
const services = workspaceServices ? { workspaceServices } : {};
|
||||
return connection.credentialPolicy === "per_user"
|
||||
? toolsApi.startOAuth(connection.id, { asCurrentUser: true, ...services })
|
||||
: workspaceServices ? toolsApi.startOAuth(connection.id, services) : toolsApi.startOAuth(connection.id);
|
||||
},
|
||||
onSuccess: async (start) => {
|
||||
try {
|
||||
await authorization.open(start);
|
||||
@@ -211,6 +217,7 @@ export function ReconnectCard({
|
||||
return (
|
||||
<div className="flex flex-col gap-4 rounded-lg border border-amber-500/50 bg-amber-500/10 px-4 py-3">
|
||||
{authorization.fallback}
|
||||
{workspaceGate.dialog}
|
||||
<div className="min-w-0">
|
||||
<h2 className="text-sm font-semibold text-amber-900 dark:text-amber-100">
|
||||
{methodUnavailable ? "Connection no longer supported" : oauth ? "Reconnect required" : "This app needs reconnecting"}
|
||||
@@ -258,7 +265,7 @@ export function ReconnectCard({
|
||||
type="button"
|
||||
size="sm"
|
||||
disabled={reconnectOAuth.isPending}
|
||||
onClick={() => { authorization.reserve(); reconnectOAuth.mutate(); }}
|
||||
onClick={() => workspaceGate.run(connection, (services) => { authorization.reserve(); reconnectOAuth.mutate(services); })}
|
||||
>
|
||||
{reconnectOAuth.isPending && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}
|
||||
{reconnectOAuth.isPending ? "Opening sign-in…" : "Reconnect"}
|
||||
|
||||
@@ -19,6 +19,26 @@ export const ProductionPicker: Story = {
|
||||
render: () => <GoogleWorkspaceServicesDialog onContinue={fn()} onCancel={fn()} />,
|
||||
parameters: { docs: { description: { story: "The production picker used by both Apps and task-hosted OAuth setup. Callbacks are mocked in Storybook; no OAuth grant is created." } } },
|
||||
};
|
||||
export const ProductionPickerReadOnly: Story = {
|
||||
render: () => <GoogleWorkspaceServicesDialog initial={{ gmail: "read", calendar: "read" }} onContinue={fn()} onCancel={fn()} />,
|
||||
parameters: { docs: { description: { story: "The data-use disclosure follows the selection: only selected services are described, at their chosen access level." } } },
|
||||
play: async ({ canvasElement }) => {
|
||||
const body = within(canvasElement.ownerDocument.body);
|
||||
const disclosure = body.getByRole("region", { name: "How Paperclip uses your Google data" });
|
||||
await expect(disclosure).toHaveTextContent("Gmail: agents can read and search your email.");
|
||||
await expect(disclosure).not.toHaveTextContent(/Drive|drafts|sending|Paperclip does not send/);
|
||||
await expect(disclosure).toHaveTextContent("the content is sent to the AI model provider configured for your workspace");
|
||||
await expect(within(disclosure).getByRole("link", { name: /Limited Use/ })).toHaveAttribute("href", "https://paperclip.ing/privacy");
|
||||
await userEvent.click(body.getByRole("switch", { name: /^Gmail$/ }));
|
||||
await userEvent.click(body.getByRole("switch", { name: /^Calendar$/ }));
|
||||
await expect(body.queryByRole("region", { name: "How Paperclip uses your Google data" })).not.toBeInTheDocument();
|
||||
await expect(body.getByRole("status")).toHaveTextContent("Select at least one service to continue.");
|
||||
},
|
||||
};
|
||||
export const ProductionPickerMobile: Story = {
|
||||
render: () => <GoogleWorkspaceServicesDialog onContinue={fn()} onCancel={fn()} />,
|
||||
globals: { viewport: { value: "mobile", isRotated: false } },
|
||||
};
|
||||
export const ChooseServices: Story = { args: {} };
|
||||
export const FromApps: Story = { args: { start: "catalog" } };
|
||||
export const GmailOnlyReviewer: Story = { args: { initial: { gmail: "read" }, start: "review" } };
|
||||
|
||||
Reference in new issue
Block a user