From 4db307d53ceb891365f9481d368eb7322e0445d3 Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Wed, 2 Dec 2026 08:20:16 -0800 Subject: [PATCH] Stop resuming completed Claude sign-ins (#23530) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Agents can use a personal or shared Claude connection. > - Setup checks for an active sign-in before starting another. > - A successful credential write leaves a claim for its caller to collect. > - This pull request limits active sign-in discovery to the three states that still require work. ## Linked Issues or Issue Description **What happened?** After a shared Claude sign-in completed, personal account setup kept finding the saved attempt until expiry. **Expected behavior** A user can sign in to another account as soon as the previous attempt succeeds. **Steps to reproduce** Finish a shared Claude sign-in. Start a personal Claude sign-in before the old deadline. ## What Changed - Use the same active states for the live session lookup and the durable lookup. Keep the saved claim available for completion. - Check active lookup after success, after restart, and when a new active row shares the same owner and provider. ## Verification - Ran the setup-token session, transport binding, and HTTP route Vitest suites. All 120 tests passed. The regression failed before the fix. ## Risks - In-progress sign-ins still resume. Existing completion reads and claim consumption retain their previous behavior. No migration is required. > 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 OpenAI Codex (GPT-6), with repository and test tools. ## 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 - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- doc/connections/AI-CONNECTIONS.md | 3 ++- server/src/routes/agents.ts | 4 ++-- server/src/routes/setup-token-route.test.ts | 4 ++-- server/src/services/setup-token-session.test.ts | 12 +++++++++++- server/src/services/setup-token-session.ts | 16 +++++++++------- .../setup-token-transport-binding.test.ts | 7 ++----- 6 files changed, 28 insertions(+), 18 deletions(-) diff --git a/doc/connections/AI-CONNECTIONS.md b/doc/connections/AI-CONNECTIONS.md index d2ddf557869..b319152be5c 100644 --- a/doc/connections/AI-CONNECTIONS.md +++ b/doc/connections/AI-CONNECTIONS.md @@ -57,7 +57,8 @@ aborted read hides the session ID, a separate owner lookup releases the attempt before a replacement can start. Cleanup checks the abandoned environment and account intent, so a conflicting settings sign-in stays active. Selecting a subscription again starts a fresh attempt. Reloading the page can -still resume a sign-in that was not cancelled. +resume a sign-in that is still in progress. After Claude stores the credential, +you can immediately start sign-in for another account. Storybook's simulated controllers and page annotations do not run in the app. diff --git a/server/src/routes/agents.ts b/server/src/routes/agents.ts index 9c25e9fd240..a89ee6e142a 100644 --- a/server/src/routes/agents.ts +++ b/server/src/routes/agents.ts @@ -228,7 +228,7 @@ import { SetupTokenSessionError, assessConfidentialStartup, evaluateConfidentialTransport, - isTerminalSessionState, + SETUP_TOKEN_ACTIVE_STATES, SETUP_TOKEN_START_FAILED, SETUP_TOKEN_SESSION_NOT_FOUND, SETUP_TOKEN_PROVIDER_UNSUPPORTED, @@ -724,7 +724,7 @@ export function agentRoutes( row.companyId === key.companyId && row.ownerUserId === key.ownerUserId && row.adapterType === key.adapterType && - !isTerminalSessionState(row.state) && + SETUP_TOKEN_ACTIVE_STATES.includes(row.state) && row.deadline > now ) { return { ...row }; diff --git a/server/src/routes/setup-token-route.test.ts b/server/src/routes/setup-token-route.test.ts index 1533fa31c3f..af88976aeda 100644 --- a/server/src/routes/setup-token-route.test.ts +++ b/server/src/routes/setup-token-route.test.ts @@ -24,7 +24,7 @@ import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; import { SETUP_TOKEN_SESSION_NOT_FOUND, SETUP_TOKEN_PROVIDER_UNSUPPORTED, - isTerminalSessionState, + SETUP_TOKEN_ACTIVE_STATES, type SetupTokenCleanupRecord, type SetupTokenCleanupStore, type SetupTokenLeaseManager, @@ -302,7 +302,7 @@ function buildTransport(opts: { onSubmit?: "complete" | "throw" | "pending" } = row.companyId === key.companyId && row.ownerUserId === key.ownerUserId && row.adapterType === key.adapterType && - !isTerminalSessionState(row.state) && + SETUP_TOKEN_ACTIVE_STATES.includes(row.state) && row.deadline > now ) { return { ...row }; diff --git a/server/src/services/setup-token-session.test.ts b/server/src/services/setup-token-session.test.ts index 86956e89f11..d12688a4cf3 100644 --- a/server/src/services/setup-token-session.test.ts +++ b/server/src/services/setup-token-session.test.ts @@ -15,6 +15,7 @@ import { SetupTokenSessionError, assessConfidentialStartup, evaluateConfidentialTransport, + SETUP_TOKEN_ACTIVE_STATES, isTerminalSessionState, toSanitizedLoginUrl, SETUP_TOKEN_SESSION_NOT_FOUND, @@ -239,7 +240,7 @@ class FakeStore implements SetupTokenCleanupStore { row.companyId === key.companyId && row.ownerUserId === key.ownerUserId && row.adapterType === key.adapterType && - !isTerminalSessionState(row.state) && + SETUP_TOKEN_ACTIVE_STATES.includes(row.state) && row.deadline > now ) { return { ...row }; @@ -842,6 +843,10 @@ describe("SetupTokenSessionService.completeSession", () => { // The durable row stays as the stored-session claim, not removed. expect(store.rows.get(sessionId)?.state).toBe("stored"); + expect(await service.findActiveByScope(OWNER_SCOPE)).toBeNull(); + const restarted = buildService({ store }).service; + expect(await restarted.findActiveByScope(OWNER_SCOPE)).toBeNull(); + // The completion returns the non-secret storedSessionId and carries no token. const completion = service.completeSession(sessionId, OWNER_SCOPE); expect(completion.storedSessionId).toBe(sessionId); @@ -1413,6 +1418,11 @@ describeEmbeddedPostgres("durable setup-token cleanup store (embedded postgres)" await insertRecord(identity, "stored", Date.now() + 60_000); const store = createDbSetupTokenCleanupStore(db); + expect(await store.findActiveDurable(identity, Date.now())).toBeNull(); + const next = { ...identity, sessionId: randomUUID() }; + await insertRecord(next, "starting", Date.now() + 60_000); + expect((await store.findActiveDurable(identity, Date.now()))?.sessionId).toBe(next.sessionId); + const first = await store.consumeStoredClaim(identity); expect(first).not.toBeNull(); expect(first?.sessionId).toBe(identity.sessionId); diff --git a/server/src/services/setup-token-session.ts b/server/src/services/setup-token-session.ts index 5cf26c9bf34..bb5d48722f9 100644 --- a/server/src/services/setup-token-session.ts +++ b/server/src/services/setup-token-session.ts @@ -35,7 +35,7 @@ import type { ConnectionManagementContext } from "./connection-management.js"; // testable. import { randomBytes } from "node:crypto"; -import { and, eq, gt, inArray, isNotNull, isNull, lte, notInArray, or, sql } from "drizzle-orm"; +import { and, eq, gt, inArray, isNotNull, isNull, lte, or, sql } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { environmentService } from "./environments.js"; import { adapterAuthSessions } from "@paperclipai/db"; @@ -77,6 +77,9 @@ export type SetupTokenSessionState = | "timed_out" | "cancelled"; +/** Only these states occupy the active login slot. A stored claim no longer needs sign-in. */ +export const SETUP_TOKEN_ACTIVE_STATES: readonly SetupTokenSessionState[] = ["starting", "awaiting_code", "submitting"]; + /** The four terminal states. Cleanup runs once when a session reaches one. */ export const SETUP_TOKEN_TERMINAL_STATES: readonly SetupTokenSessionState[] = [ "completed", @@ -302,9 +305,8 @@ export interface SetupTokenCleanupStore { * fallback source of truth for session discovery: the row survives the * restart even though the live process and the in-memory session do not. It * returns a row only when the company, the owner, and the adapter match, the - * state is not terminal, and the deadline is not yet past. It returns null - * for a missing row, a foreign-scope row, a terminal row, and an expired - * row. + * login is in progress, and its deadline has not passed. Stored claims + * remain available to the caller that completed sign-in. */ findActiveDurable( key: Pick, @@ -1196,7 +1198,7 @@ export class SetupTokenSessionService { * Finds the caller's active session for a scope, with no session id. The * browser rediscovers its own session after a reload with no local state. It * matches the company, the owner, and the adapter, and it returns only a - * non-terminal session, so a caller with no active login and a caller with a + * login still in progress, so a caller with no active login and a caller with a * foreign scope both find nothing. * * It checks the in-memory session first. A server restart drops every @@ -1210,7 +1212,7 @@ export class SetupTokenSessionService { key: Pick, ): Promise { for (const session of this.sessions.values()) { - if (isTerminalSessionState(session.state)) continue; + if (!SETUP_TOKEN_ACTIVE_STATES.includes(session.state)) continue; if ( session.scope.companyId === key.companyId && session.scope.ownerUserId === key.ownerUserId && @@ -1680,7 +1682,7 @@ export function createDbSetupTokenCleanupStore(db: Db): SetupTokenCleanupStore { eq(adapterAuthSessions.companyId, key.companyId), eq(adapterAuthSessions.startedByUserId, key.ownerUserId), eq(adapterAuthSessions.adapterType, key.adapterType as AgentAdapterType), - notInArray(adapterAuthSessions.status, [...SETUP_TOKEN_TERMINAL_STATES]), + inArray(adapterAuthSessions.status, [...SETUP_TOKEN_ACTIVE_STATES]), gt(adapterAuthSessions.expiresAt, new Date(now)), ), ) diff --git a/server/src/services/setup-token-transport-binding.test.ts b/server/src/services/setup-token-transport-binding.test.ts index e78b3dc79df..7481fb0fea0 100644 --- a/server/src/services/setup-token-transport-binding.test.ts +++ b/server/src/services/setup-token-transport-binding.test.ts @@ -10,7 +10,7 @@ import { } from "./setup-token-transport-binding.js"; import { SetupTokenSessionService, - isTerminalSessionState, + SETUP_TOKEN_ACTIVE_STATES, type SetupTokenCleanupIdentity, type SetupTokenCleanupRecord, type SetupTokenCleanupStore, @@ -133,7 +133,7 @@ function createRecordingStore() { row.companyId === key.companyId && row.ownerUserId === key.ownerUserId && row.adapterType === key.adapterType && - !isTerminalSessionState(row.state) && + SETUP_TOKEN_ACTIVE_STATES.includes(row.state) && row.deadline > now ) { return { ...row }; @@ -900,9 +900,6 @@ describe("setup-token production transport binding diagnostics", () => { }); }); -// A compile-time guard: a terminal state helper stays importable for the tests. -void isTerminalSessionState; - // A synthetic token. No real token is present. The tests assert the token never // reaches a log or an error message. const SYNTH_TOKEN = "sk-ant-oat01-SYNTHETICSYNTHETICSYNTHETIC01";