Files
PaperClipAI/doc/connections/GOOGLE-WORKSPACE.md
T
DottaandPaperclip 100b364264 Preserve selected Google services when setup resumes (#18048)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Connections control which external services an agent can use.
> - Google Workspace setup lets a person choose services and read or
write access.
> - A draft lost that choice after a declined or expired OAuth handoff.
> - Finish setup could then show all services with write access instead
of the saved narrow choice.
> - This pull request saves the exact draft choice without treating it
as granted access.
> - The benefit is safe setup recovery that preserves the person's
choice and existing account limits.

## Linked Issues or Issue Description

Refs #15545. The duplicate search found no open PR for Workspace draft
consent recovery. Related #18000 concerns satisfied gateway access
requests, not saved OAuth setup intent.

**What happened?**

A cold Workspace draft resumed with the new-account service defaults.
The selected request lived only in short-lived OAuth state. Denial
consumed that state. The picker ignored draft connections.

**Expected behavior**

Finish setup restores the same person's saved service choice. It does
not use another person's choice, a broad profile hint, or a credential
grant as draft intent. An old draft with no reliable choice asks the
person to choose services.

**Steps to reproduce**

1. Start a new Google Workspace connection. Select Gmail read-only. Turn
off Drive and Calendar.
2. Continue to Google, then decline authorization.
3. Close the setup page. Return through Finish setup.
4. Open the service picker. Before this fix, all three services can be
enabled with write access.

**Paperclip version or commit**

Reproduced in tests on master
`820c458465fa40137c81fe510f3e6dc573b4f895`.

**Deployment mode**

Authenticated and local source builds. The source regression uses real
PostgreSQL fixtures and the production React setup components. Live
provider acceptance of this repair is still pending deployment.

## What Changed

- Save validated, non-secret draft intent before managed or
customer-owned OAuth. Bind it to company, connection, actor, grant kind,
and subject.
- Restore that intent after denial, state expiry, and cold Finish setup.
Keep active reconnect bound to its saved grant. Do not change
new-account defaults.
- Preserve agent-to-human setup handoffs. Consume only the addressed
person's reviewed proposal. Keep other people's proposals.
- Lock and merge the current draft before saving intent. Return 409 if
its credential identity or method changed during setup.
- Preserve the latest saved choice across overlapping customer-owned
starts. Merge both current configuration records under short locks.
Reject stale client-binding changes. Keep each OAuth state's own
requested scopes.
- Add shared, service, handoff, picker, and cold-page regression tests.
Update the connector contract and existing feature plan.

- Route the default ungrouped test/release paths through six sequential
exact-cover chat partitions. Preserve remaining server/native coverage,
explicit grouped CI, selection-first execution and shared-database
paths.
- Correct the retention test driver so pending owned real I/O does not
advance logical deadlines. Pump zero-duration connection timers and add
a held-I/O regression; keep production scheduling and original timing
assertions unchanged.

The shared helper is needed by the server and picker to validate the
same narrow binding. It does not resolve credentials or grant access. No
production schema migration, new route, provider scope or deployment
configuration is added. The test-harness changes do not change
production timers.

## Verification

### Current candidate: source qualification passed; live acceptance
pending

- Current published candidate:
`82d13d4d698a5579378b5d506cb7a1f9cb64b5c8`, tree
`78d6a821ce53f481fe3e9991edce56f0acffb22f`. It combines the Workspace
repair with launcher commit `bf29c9` and retention-test commit `e25987`,
then integrates master `493e229d93ba7798e80152f4549e2e9177ce50ae`. The
integration brings 40 upstream commits across 713 files. One launcher
conflict keeps upstream validated CI selection and its selection-first
path, then applies six default chat partitions only without a selection.
The authored PR diff has 16 files, 833 additions and 100 deletions; it
adds no authored lockfile or `.github` changes. The public head is
confirmed at this revision. Fresh CI and review passed as recorded
below. Source qualification is complete using exact-tree full CI and the
local results below. The separate local whole command was interrupted by
host disk protection and is not called a pass. Live repaired-draft
acceptance remains pending deployment.
- Exact clean `82d13d4` passed one Node 24.19.0 builtin-only run: 41/41
cases (37 launcher and four CI-workflow cases), zero failures/skips.
HEAD, tree and relevant file hashes stayed unchanged and clean before,
at start and after. This proves launcher fixtures, not real chat
execution, current typecheck/build, the dependency-backed selection
graph, or full feature acceptance.
- The new default ungrouped whole command uses six sequential
exact-cover chat partitions, then the remaining server suites,
workspaces and serialized suites: 28 expected invocations. It preserves
all native suites, including upstream usage coverage. The plain
ungrouped release launch path also changes. Explicit grouped CI,
validated selection and shared-database execution stay unchanged.
Launcher hard RED had three expected body failures and two unchanged
passes; the repaired focused five and final 37 passed. A later 41-case
staged-merge pass is retained separately; the clean 82 run above is the
frozen proof.
- Fresh [CI run
41153113944](https://github.com/paperclipai/paperclip/actions/runs/41153113944)
completed successfully on October 31 at 01:14:53 UTC. Current head has
52 successful check runs, four conditional skips and no pending/failing
checks; legacy Snyk also passed. The skips are test-file selection, the
optional paired benchmark and two Storybook checks. The full
server/chat/workspace/serialized matrix, all eight e2e shards, normal
build, build-gap typecheck, Runner checks and final aggregate gates
passed. Build and all three chat job logs identify checkout
`e5e831fd3a8534d0d0f1e892118c0f8fbe12dd92`, merging this head into
`493e229d93`. Its Git tree is exactly
`78d6a821ce53f481fe3e9991edce56f0acffb22f`, identical to the clean
candidate. The six real chat partitions passed 314, 358, 273, 239, 321
and 311 cases: 1,816 total. Other cases shown as skipped in each
partition were selection exclusions, not extra passed cases. This is
current tree-equivalent CI proof, not a pass of the separate default
ungrouped local whole command.
- Fresh [Greptile
summary](https://github.com/paperclipai/paperclip/pull/18048#issuecomment-6473856992),
edited October 31 at 01:05:04 UTC, explicitly reviews exact head
`82d13d4` at 5/5 with no actionable code issue. Its exact-head check
passed. The prior overlapping-start discussion is resolved. This review
is source-only, not provider or live acceptance.
- Exact clean `82d13d4` passed full recursive typecheck and normal `pnpm
build` on the independent darwin/arm64 snapshot. Typecheck finished on
October 31 at 01:27:33 UTC; build finished at 01:28:33 UTC. Both exited
0. Normal native preparation and code signing passed. Source HEAD, tree
and tracked/untracked state stayed unchanged and clean. `pnpm
check:token-gates` also passed all token, palette and ClipLab checks on
this candidate. The earlier forced-clone `ENOSYS` preflight remains
recorded as setup failure, not an assertion result.
- The unchanged default `pnpm test:run` started at 01:51:33.796 UTC on
clean exact `82d13d4`. All six real chat partitions passed: 358, 314,
273, 239, 311 and 321 cases, or 1,816 actual cases. The original FIFO
and ambiguous-retry cases both passed under their unchanged 15-second
limits. General-server then reported 37 completed file rows with 5,438
passed cases and five default remote-continuity skips, including all 498
tool-access service cases and all 83 connection-route cases. At 02:39:44
UTC, the unchanged 5-GiB host-disk guard terminated the owned run. The
child ended with SIGTERM and the container/harness exited 143, with no
OOM or recorded assertion failure. Only seven of 28 RUN invocations
started. Retention had no completed local row. Later invocations did not
run. This whole local command is interrupted/incomplete, not passed.
- A coverage check found no default suite missing from current full PR
CI. The maintained launcher tests prove exact coverage for all 12 PR
server shards, chat and five native suites; all configured workspace
projects; and all nine serialized shards. The final Runner CI shard
executes the five native server suites. The 41 local launcher/workflow
cases cover six sequential chat children, per-child isolation, native
retention, fail-fast propagation and unchanged explicit
selection/shared-database paths. The actual six-chat run above exercises
that changed default path. The remaining unqualified local difference is
uninterrupted sequential whole-command composition and resource
accumulation, not omitted test selection. Current exact-tree full CI
supplies broad source-test qualification; no local whole-pass claim or
provider acceptance is inferred.
- A task-owned remote runner was considered to complete that separate
composition check. Its provider rejected the requested allocation with
per-sandbox limits of 8 GiB RAM and 10 GiB disk. No sandbox was admitted
and no remote tests ran. No tests, timeouts, assertions, database
synchronization, source or provider settings were changed to avoid the
capacity limit. Historical a0 failures remain below. No deployment or
live repaired-draft acceptance has run.

### Bounded follow-up on the prior source

- On a0, one finite phase-traced chat diagnostic executed exactly the
two failed cases. Both passed (1,374 and 1,767 ms); 1,814 other cases
were filtered, not passed. This did not reproduce a blocked await or
establish the original monolithic timeout cause. No assertion or
15-second limit changed.
- The retention diagnosis preserved an initial zero-body selector
failure, then corrected only the selector: one original case passed in
783 ms, with 42 filtered. Trace showed the old settling helper advancing
logical time while real I/O was active. A new held-I/O regression then
failed hard because the old helper advanced 1,000 ms. This proves a
test-driver defect, not the precise cause of the old 5,340 ms full-run
gap.
- The first manual-clock repair failed the complete 44-case file: 43
passed, one body hit 15 seconds and cleanup hit 30 seconds. Its planned
mutant did not run. Source then identified a fresh PostgreSQL
connection's zero-duration timer. The corrected driver pumps
zero-duration timers while initial readiness or tracked I/O is pending,
without advancing logical Date. That pre-integration file passed 44/44
with no skips. A separate scratch-only 5,000 ms normal-continuation
mutant failed the original hard `5000 < 3000` assertion; its expected
failure is not a test pass. The original page-count, fairness, expiry
and quiet assertions stayed intact. The authored repair does not change
the production worker. The merged master changes an older retention case
and dependencies; these pre-integration results are not a complete 82
retention or whole-suite pass.

### Historical qualification: SHA-bound, not 82 acceptance

- Historical a0 candidate: `a0f9089fc1ff466bf4e1eeddc5b1a910d09e380b`,
tree `b9d73713319dcd52b9eaa6053008b5190e43fdf1`. It adds the
overlapping-start repair to parent `6c18`, which already merged pinned
master `1511c92965325249ed6b52dd5be52eb6d736fbfa`. That candidate
changed 12 files. Its CI and review passed; its local full qualification
remained failed/incomplete.
- Greptile's previous `6c18` review found P1 [Latest service choice gets
lost](https://github.com/paperclipai/paperclip/pull/18048#discussion_r4425965828),
confidence 4/5. Two hard-assert regressions reproduced it on untouched
`6c18`: the already-bound path overwrote the later choice, and real
first-use client stamping also restored the old choice. Existing OAuth
states/grants were not widened, but a later setup could restore an older
request. The new repair covers both write boundaries without holding
locks over external work or copying another attempt's scopes.
- The complete affected service file passed 498 tests with no failures
or skips. All 31 required controls ran, including both unchanged RED
cases, 14 new client-drift cases, seven earlier identity guards,
reconnect/cold-resume cases and upstream transaction tests. The tested
three-file patch is byte-identical to this commit; the connector
contract update is separate. Independent scoped review found no
additional actionable issue. Fresh Greptile reviewed exact `a0f` at 5/5
with no actionable findings. The previous P1 thread is resolved.
- On exact `a0f`, the five shared/UI files passed 312 tests. An initial
complete connection-management run then failed: 74 passed, eight timed
out at the unchanged 15-second limit, and one AI-account verification
returned 422 instead of 201. The Google addressed-user handoff passed.
The container exited 1 without OOM and stopped before chat/token/whole
tests. This material failure remains retained and its cause
unclassified; the later controlled recovery below is not a causal
explanation.
- One diagnostic executed the first failed gateway case and the two AI
cases with temporary phase-only tracing. All three passed at 8.516,
5.511 and 3.523 seconds; 80 other cases were filtered. Original hard
assertions and timeouts stayed unchanged. No timeout or suspected late
provider cleanup reproduced, so the complete-file failure remains
unresolved. Vitest exited 0; the harness exited 1 because its trace
parser missed ANSI prefixes. All 203 events were recovered from retained
logs without rerunning tests. Instrumentation was removed. This is not
acceptance.
- Historical a0 CI
[41097596364](https://github.com/paperclipai/paperclip/actions/runs/41097596364)
completed successfully: 52 successful checks, two expected Storybook
skips and no failed/pending checks. Legacy Snyk passed. All 48 CI jobs
passed, including all 1,816 chat cases and explicit passing lines for
the original 20 local failures. [Server
11/12](https://github.com/paperclipai/paperclip/actions/runs/41097596364/job/124207469276)
explicitly passed the complete 83-case connection file in 129.49
seconds, including all nine local failure titles. The actual checkout
was synthetic merge `06851da6eb969d63e1c7dc9f7c95f08d09fa4ff1`,
combining `a0f` with `aa58fa107389e8b9ae5949f7ad815943dfd94292`. This is
not standalone local `a0f` qualification and does not erase the nine
local route failures.
- Linux admission uses Node 24.22.2, pnpm 9.15.4 and Rust 1.97.1. Frozen
offline install, exact native hashes and real migrated PostgreSQL 18.1
passed. Native/protocol/build/lock inputs are identical between `6c18`
and `a0f`; validated cache reuse retains the actual `6c18` native-build
provenance. The selected packaged release binary is not called a fresh
`a0f` build. Database synchronization settings stayed on. This admission
alone does not explain the route failures.
- A fresh Mac snapshot of exact `a0f` passed frozen install, workspace
prerequisites, full sequential recursive typecheck and normal `pnpm
build`, both on their first attempt. Typecheck completed at 17:43:05
UTC, build at 17:44:43 UTC; both exited 0 with clean tracked/untracked
source. Pinned Node 24.19, pnpm 9.15.4, Rust 1.97.1, package concurrency
one, Cargo jobs one and a 12 GiB V8 heap ceiling were retained.
Largest-process maximum RSS was 7,668,154,368 bytes for typecheck and
10,038,837,248 bytes for build, not aggregate tree peaks. The first
build correctly withheld its freshness stamp because 125 ignored, pinned
Copilot assets appeared during preparation; exact path/hash analysis
explained this. The normal build then recorded a genuine stamp and
reused Cargo outputs in 1.18 seconds. No manual stamp, source workaround
or gate retry. This is darwin/arm64 static/build proof, not Linux
packaging/runtime or full tests.
- The historical a0 candidate's token checker passed all four gates
across 1,410 files, run directly with pinned Node 24 against the script
behind `pnpm check:token-gates`.
- The single controlled complete-file comparison passed: baseline `6c18`
83/83 in 287.07 seconds, then candidate `a0f` 83/83 in 293.03 seconds,
with zero skips. All nine earlier failure titles passed on both. Both
child/container exits were 0, no OOM/interruption; source and
native/resolver/PostgreSQL guards matched. This ran only after all owned
Mac compilation ended, with fresh processes/databases and identical
four-CPU-quota/6-GiB/overlay inputs. No filtering, instrumentation,
assertion/timeout/source changes or retry loop. This establishes
standalone complete-file recovery, not the cause of the earlier eight
timeouts/AI 422.
- The first unchanged full `pnpm test:run` on exact clean `a0f` ran from
October 30 at 18:01:43 UTC to 21:06:19 UTC. It failed naturally with
test and container exit 1, without OOM. General-server reported 1,257
passed, one failed and seven skipped files; 28,633 passed, one failed
and 103 skipped tests. Only the first of 22 invocations ran. The later
four groups and 21 invocations did not run. The sole failure was the
unchanged chat-shard CLI meta-test: its nested projectless pnpm lookup
hit the offline network guard. This was a failed full gate, not Google
provider acceptance.
- A finite environment pair reproduced that one meta-test failure, then
passed the same unchanged case after supported `corepack prepare
pnpm@9.15.4 --activate` as the existing non-root node user. The cached
pnpm payload was identical. Only the missing node-user last-known-good
record changed. Core source, dependencies, lockfile, fixtures,
assertions, timers and offline guards stayed unchanged. This isolates
the nested collection defect; it does not explain the earlier route
failures or complete the full gate.
- The corrected unchanged full command ran from October 30 at
21:29:03.500 UTC to October 31 at 00:02:44.207 UTC on the same exact
clean `a0f`. It failed naturally with exit 1, signal null and no OOM.
Source stayed clean before, at start and after. It retained two visible
CPUs/quota, 6 GiB, private IPC, normal overlay, matching native inputs,
synchronized real PostgreSQL 18.1, and the default five groups/22
invocations. Only the first general-server invocation ran; the other 21
did not run. General-server reported 1,265 files: 1,256 passed, two
failed and seven skipped. It reported 28,737 tests: 28,631 passed, three
failed and 103 skipped. The two chat cases emitted `Test timed out in
15000ms` at `chat-channels.integration.test.ts:77310` and `:81790`, with
durations of 15,045 and 15,058 ms. These were the durable pre-run FIFO
notice and ambiguous GitHub text restart/retry cases. The retention case
emitted `expected 5340 to be less than 3000` at
`skill-version-retention.test.ts:593`. Its real duration was 1,727 ms;
5,340 ms was the recorded fake-time directory-page gap, not a deadline
timeout. The timeout stacks do not identify the blocked internal await.
The cause of these failures remains unclassified. Inside this same
failed run, the complete 83-case connection file and 498-case service
file passed. The former Corepack meta-case also passed in 6,396 ms.
These component passes do not waive the failed/incomplete full gate. No
rerun, cancellation, timeout/assertion change or full-pass claim. A
later fresh two-case phase trace passed both chat cases; it did not
reproduce or establish the original timeout cause. At that checkpoint,
the PR stayed draft.
- Prior `6c18` targeted checks passed 930 tests across eight files and
token gates. Its selected queue group passed all 53 cases, including the
original 20 failures and 12 new named controls. Backlog cases took 10.49
and 8.45 seconds under the unchanged 15-second limit. Another 1,763 chat
cases were intentionally filtered. This is historical targeted recovery,
not a full pass or proof of the new repair. No timeout or assertion was
relaxed.
- Prior `6c18` full local qualification failed during serial typecheck:
server TypeScript was killed with code 137. Docker confirmed OOM in the
6 GiB container; full tests and build never started. The failure is
retained. The new Mac resource plan avoids repeating that undersized run
and does not change the shared Docker VM.
- Prior CI
[41089793558](https://github.com/paperclipai/paperclip/actions/runs/41089793558)
completed successfully for synthetic merge
`a73bffcfa3ede051961bcabcfa576c703d10c932` (`6c18` plus
`abc270ee4c03e13b4d6eaad156a41b4ebed4bb0a`). All 48 CI jobs passed; all
1,816 chat cases passed, including explicit log lines for the original
20. Check runs were 51 success, two expected skips and one Greptile
failure; legacy Snyk passed. These results do not qualify `a0f` or erase
its local route failures.
- Red proof on the unmodified master baseline: cold picker and Finish
setup restore broad defaults; managed and customer-owned drafts lack
saved intent. The stale setup tests also fail before the lock guard.
- Live staging baseline `b25f3e2af8e77d882cd22d36ca55640e6468e46f` also
reproduces the ordinary failure: select Gmail read-only only, cancel at
Google, reload the connector catalog, then Finish setup. All three
groups return enabled at read/write. Authorization was declined; no new
Google access was granted. This is baseline failure evidence, not a
deployed-fix pass.
- Historical affected suites: 800 tests passed before the final lock
guard. The final focused service and handoff cases passed 126 tests
after that guard. These are not results for the integrated candidate.
- Historical `pnpm -r typecheck` and final lock-guard server typecheck
passed. The historical a0 candidate passed the full recursive gate
separately, as recorded above.
- `pnpm build`: passed again on the final lock-guard source in commit
`1c31cde0ed199fbf4e41b7649590554f7886dfc2`.
- Historical `pnpm check:token-gates` passed; the historical a0
candidate's direct checker pass is recorded above.
- `pnpm test:run` on macOS failed on the frozen commit. It exited 1
after 9,432.41 seconds. General server results: 1,195 files passed, 10
failed, eight skipped; 26,706 tests passed, one timed out, 157 skipped.
Nine setup hooks timed out while starting embedded PostgreSQL. The
retained log records host-wide semaphore exhaustion (`semget`), not disk
exhaustion. One unchanged publication-text performance case also timed
out. Its cause is not established. Later workspace and serialized groups
did not run. This is a failed and incomplete local gate.
- The independent full-source Linux run also failed and was incomplete
on the same frozen commit. Native and real-database admission passed.
Chat integration reported 20 failures in 1,593 tests. Tool-access passed
all 479 tests. Native-session-executor passed all 965 tests. Docker
interrupted the run after about 48 minutes on October 29. The container
exited 143 and was not OOM-killed. The run produced no final group
totals or detailed assertion summary. Shell trap metadata reports zero,
but this is not a valid test-pass result. Source and evidence remain
unchanged. The focused diagnosis below retains those failures; their
cause is not assumed from the interruption. Neither historical local
full run passed.
- A fresh focused replay on the frozen source then executed exactly
those 20 case bodies. All 20 failed; this was not a setup-hook failure.
The two backlog cases reached the unchanged 15-second timeout. The 18
FIFO cases failed on missing notices or receipt rows. All 18 FIFO cases
passed when run alone in a fresh process and database. This supports an
order interaction, not a complete cause or baseline conclusion. A
separate two-backlog control used RAM-backed temporary storage and real
PostgreSQL with synchronization settings on. One backlog case passed in
10.65 seconds; the other still timed out at 15 seconds. No source,
assertion or timeout was changed. The full local gate remains open.
- Earlier mixed-revision run: it began before the final guard and
imported older source before collecting later regression cases. It
failed those new cases with that older cached module. This run is
retained, not counted as candidate acceptance. The fresh focused run
passed all seven stale-setup cases. No case was skipped to hide a
failure.
- Historical remote gates for `1c31` were terminal and clean: 53
successful contexts and two expected Storybook skips. Main CI
[40720536514](https://github.com/paperclipai/paperclip/actions/runs/40720536514)
passed. Greptile reviewed exact head
`1c31cde0ed199fbf4e41b7649590554f7886dfc2` at 5/5 with no actionable
findings; the separate review job also passed, and there were no inline
review comments. These results do not qualify `6c18`.
- CI source qualification: the chat jobs checked out synthetic merge
`ef36746b3d2ec52ba5727dcbe4da265a03421fe4`, which merges the PR into
`7d75ae0569e41786640cf09647ae8849411d2f22`. All 20 locally failing case
names have explicit passing CI log lines. These passes do not establish
standalone local acceptance of `1c31`. The merge adds two upstream Teams
tests, so it collects 1,595 chat cases instead of 1,593. Neither
backlog/FIFO assertions nor their timeouts changed.
- Independent source review found an earlier credential-identity race.
The guard and seven deterministic cases resolve that finding. A later
integration review missed the separate overlapping-start race. Both RED
failures and that review miss are retained. The narrow follow-up repair
passed 498 service cases, independent source review and fresh remote
CI/5-of-5 review; full local qualification remains incomplete.
- Source qualification is ready for merge. Live repaired-draft recovery,
delivery and Google approval are not established by these results. The
local whole command remains explicitly incomplete.

## Risks

- Historical drafts without a matching intent now need an explicit
service choice. This is deliberate and prevents silent broadening.
- A concurrent credential or method edit now returns 409. Reloading lets
the person review the changed setup.
- Overlapping starts keep separate requested scope sets. Updating draft
intent does not relabel an earlier OAuth state's consent request.
- Saved intent is not consent. Provider-reported scopes and current
action policies still control discovery and dispatch.
- No migration is needed. No existing token or grant is rewritten by
saving draft intent.

- Default ungrouped launch paths now execute six chat children in
sequence and 28 whole-command invocations. Exact coverage, local
launcher contracts and all six real default chat partitions passed. A
complete uninterrupted local whole-command run remains unqualified
because of host capacity.
- The retention test-clock repair depends on owned-I/O and zero-duration
connection-timer progress. The controlled regression, sensitivity mutant
and current exact-tree CI protect the original assertion. It did not
reach a completed row in the interrupted local whole run.

## Model Used

OpenAI Codex, described by the runtime as GPT-5 based. The exact runtime
model ID and context-window size are not exposed to this task. Used
reasoning, code execution, browser verification, and independent
delegated review.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used, including the runtime metadata
limit
- [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 described the issue in-PR following the bug report template
- [x] I have not referenced internal or instance-local Paperclip issues
or links
- [x] My branch name describes the change and contains no internal
ticket or instance identifier
- [x] I have run tests locally and they pass — exact clean 82 passed 41
launcher/workflow cases and all 1,816 real default chat cases, full
recursive typecheck, normal build and token gates. Full exact-tree PR CI
passed. The separate local whole `pnpm test:run` was interrupted by disk
protection and remains incomplete; it is not claimed as a local whole
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 risks above
- [x] All Paperclip CI gates are green — current exact-head checks
passed; the verified CI checkout tree equals clean 82. The separate
interrupted local whole command is disclosed above.
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups —
fresh exact-82 summary and check passed; the earlier finding is
resolved. This is source review, not acceptance.
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-10-30 22:02:58 -05:00

18 KiB

Google Workspace connections

New Google Workspace setup uses one google-workspace connection and the workspace.all OAuth profile. Paperclip first offers Gmail, Drive (including Docs, Sheets, and Slides), and Calendar. All three start enabled with read and write access. Users can disable a group or choose read-only access. New setup does not offer Chat, Contacts/directory, or cross-service Search.

The combined connection has one credential grant, capability catalog, policy profile, audit trail and reconnect lifecycle. It requests only the selected groups' scopes (nine scopes for the default selection), not the legacy full union. Google's consent screen also lets users decline permissions; discovery skips services without grants and excludes unsupported actions. The gateway checks actual grant scopes again before each call, including after refresh. Requested scopes alone never authorize an action.

Before managed or customer-owned OAuth opens, Paperclip saves the validated service choice as non-secret setup intent on the draft. It is bound to the company, connection, initiating actor, grant kind, and credential subject. Declined or expired authorization and a cold Finish setup return restore that choice, not the new-account write defaults. Historical drafts without a matching saved intent require an explicit choice. Reconnecting an established account without a new choice keeps its exact grant request.

Overlapping customer-owned starts preserve the latest saved draft choice through client binding and authorization metadata updates. Each OAuth state and consent URL keeps that attempt's own requested scopes. These updates preserve unrelated current settings and other users' pending proposals in both configuration records.

An agent can hand setup to its responsible human without choosing services or creating provider OAuth state. If the agent proposes services, the human can review and change them in the picker. Saving the human's choice consumes only that person's pending proposal, so an old proposal cannot replace their choice after a declined sign-in. Neither draft intent nor a proposal is consent.

Discovery isolates service outages. Healthy services remain usable while the connection's health message identifies unavailable services and recommends a catalog refresh. Failed services' cached actions are disabled until rediscovered; an outage affecting every requested service still fails the refresh. Loss of the shared OAuth grant never degrades into a successful partial discovery. Because the catalog is shared, actions skipped because of narrower consent are preserved when another active grant supports them. Failed services and tools removed from a successful discovery are still disabled. Each caller's listing and dispatch use only their selected grant, without combining permissions from different identities. Individual call failures are reported and audited without marking unrelated Google services unhealthy; they do not trigger automatic write retries.

Existing individual product connections and their direct setup routes remain supported. They are not automatically merged, upgraded or reauthorized. The Sheets robot-account method remains separate because it uses explicitly shared files, not the user's Google OAuth identity.

Google's hosted Workspace MCP servers are Developer Preview services. The app endpoints remain separate. Paperclip namespaces actions by service and routes them to a closed endpoint registry using the combined grant. It does not create child connections or send provider tokens through Paperclip ID.

The catalog reuses the existing reviewed Google mark (google-people.svg), registered under its own google-workspace brand identity. No new artwork is downloaded or substituted for a product logo.

Combined profile deployment and verification

Deploy the companion Cloud broker registry before enabling workspace.all in CLOUD_HARNESS_CONNECTOR_GOOGLE_ENABLED_PROFILES. It uses the existing WORKSPACE client pair; that client's Cloud project must have every applicable MCP API and preview enrollment. Do not remove legacy enabled profiles while their grants are in use. This code change does not enable the broker profile or deploy any stack.

The signed request and envelope authentication bind the exact selected request; the legacy 21-scope profile remains supported for old clients. The encrypted credential payload preserves Google's actual nonempty subset. Missing scope evidence and scopes outside that reviewed union fail closed on authorization and refresh. Individual legacy profiles retain exact matching. For the new google/workspace.all profile only, HKDF info is SHA-256(AAD) to remain below Node's 1024-byte limit. AES-GCM still authenticates the complete AAD; legacy envelope key derivation is unchanged.

Managed OAuth: browser → Cloud /v1/connector/sessions → Google https://accounts.google.com/o/oauth2/v2/auth → Cloud /v1/connector/oauth/google/callback → instance /api/tools/oauth/cloud-connector/callback. Cloud exchanges codes and refreshes at https://oauth2.googleapis.com/token; provider tool calls go directly from the instance to the fixed endpoints below. Customer OAuth uses the instance's existing /api/tools/oauth/callback instead. Register that exact HTTPS or loopback callback on the customer-owned client.

Removal is local for managed grants: Google's project-wide revocation can break other connections. Before rollout, verify full and partial consent with an enrolled test account, allowed reads/writes, reconnect, refresh and removal. Deterministic tests are not real-provider proof. Combining profiles simplifies onboarding, not Google's per-scope demonstration, justification or security-assessment obligations.

Sources: granular consent, Workspace MCP setup.

Connections catalog and rollout

The Connections page offers one Google Workspace card for new accounts. Saved individual-service accounts stay visible and retain their management routes. This replaces the earlier display-only Google visibility hold. Showing the card does not enable managed OAuth: signed instance-specific broker availability still controls it. A customer-owned OAuth app remains a separate setup method.

Do not upgrade or unpin existing verification instances as an implementation step. Qualify the selected-scope flow on an isolated reviewer staging app first. See service consent for the app/broker deployment order and live verification gates.

Developer Preview enrollment

Google grants preview access to the specific Workspace email addresses and Google Cloud project numbers registered with the program. Submitting the form is not the approval signal:

  1. Google first sends a Google Group membership notification after verifying the Workspace account.
  2. Google then sends a final confirmation after registering the Cloud project, usually within a couple of days. This final email is the signal that MCP testing can begin.
  3. If no final confirmation arrives within a week, check spam and contact the Developer Preview program team from the program page.

Enrollment does not authorize every user of an OAuth client. Additional tester emails and Cloud projects must be added through Google's member request forms. Google's preview terms also prohibit making a pre-GA integration available to end users outside the enrolled company or domain unless Google grants explicit permission. Consequently, Paperclip-managed Google OAuth is limited to registered internal testers during preview. Other companies must enroll their own Workspace testers and Cloud project and use a customer-owned OAuth app until Google makes Workspace MCP generally available.

Service endpoints and legacy capability choices

App card MCP endpoint Capability choices
Gmail https://gmailmcp.googleapis.com/mcp/v1 Read only; read and create drafts
Google Drive https://drivemcp.googleapis.com/mcp/v1 Read only; read and create files
Google Docs https://docsmcp.googleapis.com/mcp/v1 Read only; read and edit
Google Sheets https://sheetsmcp.googleapis.com/mcp/v1 Read only; read and edit; share selected sheets with the robot account
Google Slides https://slidesmcp.googleapis.com/mcp/v1 Read only; read and edit
Google Calendar https://calendarmcp.googleapis.com/mcp/v1 Read only; read and manage events
Google Chat https://chatmcp.googleapis.com/mcp/v1 Read only; read and send messages
Google People https://people.googleapis.com/mcp/v1 Read contacts
Google Workspace Search https://workspacemcp.googleapis.com/mcp/v1 Search Workspace

Legacy product setup exposes capability choices under Change. The combined Workspace setup has one capability and asks for service groups before Google consent. The endpoint table also documents legacy connections; it is not the new-account service list. When the managed method is available, it uses Paperclip by default. A small Use your own Google OAuth app link reveals the custom client fields; Use Paperclip instead returns to the managed method. The available authentication methods are:

  • Connect with Paperclip uses the Paperclip Cloud broker when that exact profile is returned for this enrolled instance by the signed POST https://my.paperclip.app/v1/connector/instance-status request. The anonymous capabilities document is global discovery only and never enables an internal-pilot method locally.
  • Use your own Google OAuth app uses customer-supplied OAuth credentials and the app definition's exact reviewed scopes.
  • Use the Paperclip robot account remains an additional Google Sheets-only option for explicitly shared spreadsheets.

Before Google consent, the setup flow shows the credential's human and agent access and lets the user change it. A personal choice stores the tokens only on that user's grant. A company choice stores them on the default organization grant, while still recording which signed-in Google principal completed consent so refresh and reconnect stay bound to that principal.

Catalog discovery and connection creation use the same signed, instance-specific profile availability. Local enrollment files and Cloud-delivered environment identities follow this same path; neither enables managed methods globally in the static app definitions. Saved connections remain recognizable for OAuth callback, refresh, and revoke, while the broker enforces current profile access. Switching capability or authentication methods preserves the selected credential owner when the new method supports that owner.

Legacy product-specific broker profiles

The Paperclip-managed method signs every broker request with one explicit profile. The broker binds that profile into sessions, one-time claims, sealed token envelopes, and refresh. Per-profile removal is local-only for managed Google grants. Google's revocation endpoint can invalidate all grants for the same user and managed client, so Paperclip does not call it while removing one Workspace profile.

App Read profile Write profile
Gmail gmail.read gmail.draft
Drive drive.read drive.write
Docs docs.read docs.write
Sheets sheets.read sheets.write
Slides slides.read slides.write
Calendar calendar.read calendar.write
Chat chat.read chat.write
People people.read —
Workspace Search workspace-search.read —

Every new signed request includes a profile. The Cloud broker rejects a request whose provider, profile, or exact scope set does not match its closed registry.

Instance configuration

All Paperclip-managed Google methods use the existing enrolled-instance keys:

PAPERCLIP_CLOUD_CONNECTOR_BASE_URL=https://my.paperclip.app
PAPERCLIP_CLOUD_CONNECTOR_ENVIRONMENT=production
PAPERCLIP_CLOUD_CONNECTOR_INSTANCE_ID=inst_example
PAPERCLIP_CLOUD_CONNECTOR_SIGN_PRIVATE_KEY=...
PAPERCLIP_CLOUD_CONNECTOR_SEAL_PRIVATE_KEY=...

No per-app client secret is stored on the Paperclip instance for the managed path. For customer-owned OAuth, the setup flow collects that customer's Google OAuth client ID and secret and stores them through the normal instance-vault path.

Cloud-hosted stacks receive these values through the existing per-stack secret delivery path. A self-hosted instance creates its keys during enrollment and stores them with owner-only permissions in the instance's ignored secret directory. The setup page supplies its authenticated same-origin HTTPS address to enrollment, so a normal Tailscale-hosted self-hoster does not need to edit config.json or set PAPERCLIP_PUBLIC_URL; the enrolled origin becomes the durable callback binding. The former PAPERCLIP_ID_CONNECTOR_* values use an incompatible Paperclip ID protocol and are not read aliases. Enroll with Paperclip Cloud and reconnect legacy grants before their old access tokens expire.

The gallery requests the broker capability document with a short cache. A Paperclip-managed method is omitted unless its exact profile is enabled at the broker; the independent app card and customer-owned OAuth method remain available. This supports profile-by-profile rollout and rollback without collapsing the nine cards into one app.

See Gmail connection for the detailed enrollment, signing, encryption, environment-isolation, and security review runbook inherited by all profiles.

Safety boundary

Every Google profile has an explicit MCP tool allowlist. Unknown Developer Preview tools default to disabled. Read profiles expose only reviewed read operations. Write profiles add only the reviewed write operations for their app; destructive or unreviewed tools do not become available merely because Google adds them upstream.

Service-specific minimum scopes (2026-09-30)

Docs, Sheets, and Slides request only their service's read-only scope in the read profile and its read/write scope in the write profile. They do not also request drive.readonly or drive.file: those are authorization alternatives, not additional requirements. Drive and Workspace Search retain their separate Drive permissions. Calendar write requests calendar.calendarlist.readonly and calendar.events; the latter also authorizes suggest_time. Calendar read retains calendar.events.freebusy alongside list/event read-only access.

References: Google's Docs read and update, Sheets read and update, Slides read and update, and Calendar suggest_time.

The write scopes support editing existing accessible files by ID. drive.file is a valid narrower alternative for app-authorized files, but would require a different per-file authorization workflow. Read-only profiles remain separate; the project-wide union is not the scope set requested by every connection.

Deploy with the matching Cloud broker registry and test fresh grants in staging before production. Signed authorization and refresh requests use exact scope sets, so mixed versions fail closed. The broker rejects old broader grants and refresh responses without explicit scope evidence for these reduced profiles. Reconnect affected connections; do not relabel or globally revoke existing tokens. Customer-owned methods request the same reduced sets on new consent; previously issued grants are not retroactively narrowed. The 21-scope integration union is unchanged by these profile-level reductions. Console must still keep Drive/free-busy entries required by other profiles and separately used identity scopes. Fresh provider proof is a release requirement, not implied by unit tests.

Google Chat scope reduction (2026-09-22)

chat.read requests only chat.spaces.readonly and chat.messages.readonly. chat.write adds chat.messages.create. The same sets apply to both managed and customer-owned OAuth methods. Neither requests chat.memberships.readonly nor chat.users.readstate.readonly.

Conversation lookup, message history, ordinary message search, and the write profile's message sending remain supported. Membership listing and marking messages read/unread remain outside the tool allowlist. search_messages cannot filter by read state: the app hides isUnread from its agent and Test schemas and rejects any explicit isUnread/is_unread argument, including false or null, before dispatch. It never silently drops the filter. The guard also applies to cached catalogs and existing broader grants.

References: Google's Chat MCP setup and message-search parameters.

Roll out the app and Cloud broker scope registries together in staging and production: their signed requests and sealed credentials use exact scope sets. During a mixed-version rollout, Chat authorization/refresh can fail closed. Existing Google tokens are not retroactively narrowed or revoked by this code change. A refresh response still containing removed scopes, or omitting the scope set needed to verify the grant, is rejected by the broker; reconnect affected Chat grants for new consent. Do not revoke the shared Google client to migrate one profile, because that can break other Workspace connections. After deployment, verify fresh reduced-scope consent, ordinary Chat search/history and sending, then reconcile Google Console and the verification evidence with the deployed scope set.