Skip to content

Retry Relayfile setup after cloud auth refresh - #95

Merged
kjgbot merged 1 commit into
mainfrom
fix/relayfile-auth-refresh-retry
Jun 5, 2026
Merged

kjgbot merged 1 commit into
mainfrom
fix/relayfile-auth-refresh-retry

Conversation

@kjgbot

@kjgbot kjgbot commented Jun 5, 2026 •

Copy link
Copy Markdown
Contributor

User description

Summary

  • expose a forced Cloud auth refresh helper for main-process Relayfile setup
  • retry local integration mounts once after Relayfile join/mount returns Unauthorized
  • retry integration event subscription workspace join once after Unauthorized

This addresses the startup log pattern where Pear has integrations and symlinks, but Relayfile mounts and integration event subscriptions fail with Unauthorized after a Cloud auth token is rejected.

Tests

  • npm test
  • npm run build

CodeAnt-AI Description

Retry Relayfile setup after Cloud auth refresh

What Changed

  • Relayfile mounts now try a Cloud auth refresh and retry once when the first setup call is rejected as unauthorized
  • Integration event workspace joining now does the same, so event delivery can recover after an expired or rejected Cloud token
  • Cloud auth refresh now returns a reusable signed-in auth record for these retries

Impact

✅ Fewer startup failures for integrations
✅ Fewer relaunches after Cloud token rejection
✅ More reliable integration event subscriptions

🔄 Retrigger CodeAnt AI Review

💡 Usage Guide

Checking Your Pull Request

Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.

Talking to CodeAnt AI

Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:

@codeant-ai ask: Your question here

This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.

Example

@codeant-ai ask: Can you suggest a safer alternative to storing this secret?

Preserve Org Learnings with CodeAnt

You can record team preferences so CodeAnt AI applies them in future reviews. Reply directly to the specific CodeAnt AI suggestion (in the same thread) and replace "Your feedback here" with your input:

@codeant-ai: Your feedback here

This helps CodeAnt AI learn and adapt to your team's coding style and standards.

Example

@codeant-ai: Do not flag unused imports.

Retrigger review

Ask CodeAnt AI to review the PR again, by typing:

@codeant-ai: review

Check Your Repository Health

To analyze the health of your code repository, visit our dashboard at https://app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.

@codeant-ai

codeant-ai Bot commented Jun 5, 2026

Copy link
Copy Markdown

CodeAnt AI is reviewing your PR.

@coderabbitai

coderabbitai Bot commented Jun 5, 2026 •

Copy link
Copy Markdown

Review Change Stack

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Free

Run ID: 28d1616e-f34f-4c82-a88d-c6076ed26511

📥 Commits

Reviewing files that changed from the base of the PR and between ae6eacf and cb78e9c.

📒 Files selected for processing (3)
  • src/main/auth.ts
  • src/main/integration-event-bridge.ts
  • src/main/integration-mounts.ts

📝 Walkthrough

Walkthrough

The PR adds token refresh and automatic retry-on-unauthorized functionality. It introduces refreshCloudAuth() in the auth module to refresh Pear-stored tokens, refactors both workspace-join (event bridge) and mount operations to detect authorization failures and retry with refreshed credentials, reducing manual intervention on token expiration.

Changes

Token Refresh and Retry on Authorization Failures

Layer / File(s) Summary
Auth token refresh and CloudAuth normalization
src/main/auth.ts
Introduces cloudAuthFromStored() helper to normalize stored API URLs and derive account keys; refactors resolveCloudAuth() to use the helper; exports new refreshCloudAuth() function to refresh Pear tokens and return updated credentials or null if unavailable or refresh fails.
Event bridge workspace join with auth retry
src/main/integration-event-bridge.ts
Adds isUnauthorizedError() detection for HTTP 401/403 and authorization-related messages; converts auth to a mutable variable; refactors workspace join into joinWorkspace() function with automatic retry logic that calls refreshCloudAuth() and re-joins with refreshed credentials on authorization failures.
Mount reconciliation with auth retry
src/main/integration-mounts.ts
Adds isUnauthorizedError() detection; extracts createSetup() method for RelayfileSetup construction; introduces activeAuth tracking; wraps mount operations in startMount() with try/catch retry logic that refreshes auth via refreshCloudAuth(), recreates setup, and retries mountWorkspace on 401/403 errors.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 A token went stale, the auth would fail,
But now we refresh with a retry tale,
Two paths rejoin with credentials anew,
No more expired attempts breaking through! 🔐


Note

🎁 Summarized by CodeRabbit Free

Your organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login.

Comment @coderabbitai help to get the list of available commands and usage tips.

@codeant-ai codeant-ai Bot added the size:M This PR changes 30-99 lines, ignoring generated files label Jun 5, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces token refreshing logic when encountering unauthorized (401/403) errors during workspace operations. It adds a helper refreshCloudAuth in auth.ts, implements isUnauthorizedError checks, and refactors both IntegrationEventBridge and IntegrationMountManager to catch unauthorized errors, refresh the cloud authentication, and retry the workspace connection or mount. Feedback on the changes highlights a bug in the isUnauthorizedError regular expression where the word boundary \b prevents matching "unauthorized" due to the truncated term "unauthor". It is recommended to update the regex to use "unauthorized" and to handle cases where the error is thrown directly as a string.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +104 to +111
function isUnauthorizedError(error: unknown): boolean {
if (!error || typeof error !== 'object') return false
const status = (error as { httpStatus?: unknown; status?: unknown }).httpStatus ??
(error as { httpStatus?: unknown; status?: unknown }).status
if (status === 401 || status === 403) return true
const message = (error as { message?: unknown }).message
return typeof message === 'string' && /\b(401|403|unauthor|forbidden)\b/i.test(message)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The regular expression /\b(401|403|unauthor|forbidden)\b/i will fail to match the word "unauthorized" because of the trailing word boundary \b. Since "unauthorized" continues with "ized", there is no word boundary after "unauthor", causing the match to fail. Changing "unauthor" to "unauthorized" ensures that the full word is matched correctly. Additionally, handling cases where the error is thrown directly as a string makes this utility more robust.

Suggested change
function isUnauthorizedError(error: unknown): boolean {
if (!error || typeof error !== 'object') return false
const status = (error as { httpStatus?: unknown; status?: unknown }).httpStatus ??
(error as { httpStatus?: unknown; status?: unknown }).status
if (status === 401 || status === 403) return true
const message = (error as { message?: unknown }).message
return typeof message === 'string' && /\b(401|403|unauthor|forbidden)\b/i.test(message)
}
function isUnauthorizedError(error: unknown): boolean {
if (!error) return false;
if (typeof error === 'string') {
return /\b(401|403|unauthorized|forbidden)\b/i.test(error);
}
if (typeof error !== 'object') return false;
const status = (error as { httpStatus?: unknown; status?: unknown }).httpStatus ??
(error as { httpStatus?: unknown; status?: unknown }).status;
if (status === 401 || status === 403) return true;
const message = (error as { message?: unknown }).message;
return typeof message === 'string' && /\b(401|403|unauthorized|forbidden)\b/i.test(message);
}

Comment on lines +32 to +39
function isUnauthorizedError(error: unknown): boolean {
if (!error || typeof error !== 'object') return false
const status = (error as { httpStatus?: unknown; status?: unknown }).httpStatus ??
(error as { httpStatus?: unknown; status?: unknown }).status
if (status === 401 || status === 403) return true
const message = (error as { message?: unknown }).message
return typeof message === 'string' && /\b(401|403|unauthor|forbidden)\b/i.test(message)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The regular expression /\b(401|403|unauthor|forbidden)\b/i will fail to match the word "unauthorized" because of the trailing word boundary \b. Since "unauthorized" continues with "ized", there is no word boundary after "unauthor", causing the match to fail. Changing "unauthor" to "unauthorized" ensures that the full word is matched correctly. Additionally, handling cases where the error is thrown directly as a string makes this utility more robust.

function isUnauthorizedError(error: unknown): boolean {
  if (!error) return false;
  if (typeof error === 'string') {
    return /\b(401|403|unauthorized|forbidden)\b/i.test(error);
  }
  if (typeof error !== 'object') return false;
  const status = (error as { httpStatus?: unknown; status?: unknown }).httpStatus ??
    (error as { httpStatus?: unknown; status?: unknown }).status;
  if (status === 401 || status === 403) return true;
  const message = (error as { message?: unknown }).message;
  return typeof message === 'string' && /\b(401|403|unauthorized|forbidden)\b/i.test(message);
}

@kjgbot
kjgbot merged commit 6d533f4 into main Jun 5, 2026
3 checks passed
@kjgbot
kjgbot deleted the fix/relayfile-auth-refresh-retry branch June 5, 2026 13:15
Comment thread src/main/auth.ts
Comment on lines +652 to +657
export async function refreshCloudAuth(): Promise<CloudAuth | null> {
const pearAuth = loadTokens()
if (!pearAuth) return null
const refreshed = await refreshStoredTokens(pearAuth)
return refreshed ? cloudAuthFromStored(refreshed) : null
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: refreshCloudAuth only tries to refresh Pear-stored tokens and immediately returns null when those tokens are absent, even though resolveCloudAuth also supports Cloud SDK credentials. This makes the new Unauthorized retry path fail for SDK-authenticated setups (env/file auth), because refresh is never attempted from that source. Make refreshCloudAuth fall back to re-resolving Cloud SDK auth so both auth sources are handled consistently. [incomplete implementation]

Severity Level: Major ⚠️
- ❌ Local integration mounts fail to recover after Unauthorized.
- ❌ Integration event subscriptions fail retry under SDK-only auth.
- ⚠️ Env/file-provisioned auth behaves worse than in-app login.
Steps of Reproduction ✅
1. Configure Pear to use only Cloud SDK auth so `loadTokens()` returns null and
`readCloudSdkAuth()` returns valid unexpired credentials (see `loadTokens` at
`src/main/auth.ts:226-235` and `resolveCloudAuth` at `src/main/auth.ts:102-121`).

2. Trigger integration mount reconciliation so
`IntegrationManager.syncLocalIntegrationMount` calls
`integrationMountManager.ensureMounted(...)` (see `src/main/integrations.ts:1718-1725`),
which in turn calls the private `mount()` method and obtains `auth` via
`resolveCloudAuth()` (see `src/main/integration-mounts.ts:224-231`).

3. During `mount()`, `setup.mountWorkspace(...)` is invoked for each mount (see
`startMount` in `src/main/integration-mounts.ts:53-70`); if the Cloud SDK access token is
rejected with 401/403, the error reaches the `catch` block where
`isUnauthorizedError(error)` returns true (see `isUnauthorizedError` at
`src/main/integration-mounts.ts:32-39`).

4. The Unauthorized retry path then calls `refreshCloudAuth()` (see
`src/main/integration-mounts.ts:75-80`), which immediately returns `null` when no
Pear-stored tokens exist (implementation at `src/main/auth.ts:134-139`), causing the code
to rethrow the original error instead of retrying with refreshed or re-resolved Cloud SDK
credentials; the same pattern exists for integration event subscriptions in
`getWorkspaceHandle()` (`src/main/integration-event-bridge.ts:24-67`), so
SDK-authenticated setups never benefit from the new Unauthorized retry behavior.

Fix in Cursor | Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** src/main/auth.ts
**Line:** 652:657
**Comment:**
	*Incomplete Implementation: `refreshCloudAuth` only tries to refresh Pear-stored tokens and immediately returns `null` when those tokens are absent, even though `resolveCloudAuth` also supports Cloud SDK credentials. This makes the new Unauthorized retry path fail for SDK-authenticated setups (env/file auth), because refresh is never attempted from that source. Make `refreshCloudAuth` fall back to re-resolving Cloud SDK auth so both auth sources are handled consistently.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

if (this.deps.getWorkspaceHandle) return this.deps.getWorkspaceHandle()
const { accountWorkspaceReadyRetryOptions, getAccountWorkspaceId, resolveCloudAuth } = await import('./auth.ts')
const auth = await resolveCloudAuth()
const { accountWorkspaceReadyRetryOptions, getAccountWorkspaceId, refreshCloudAuth, resolveCloudAuth } = await import('./auth.ts')

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: The dynamic import uses ./auth.ts while the rest of the code imports the same module via ./auth. In packaged/runtime builds this can break chunk/module resolution or create inconsistent module identity behavior for the same dependency. Use the same module specifier style as the rest of the codebase for this import. [api mismatch]

Severity Level: Critical 🚨
- ❌ Integration event bridge fails to initialize workspace handle.
- ❌ Event subscriptions for integrations never establish in packaged app.
- ⚠️ Inconsistent auth module identity complicates debugging and testing.
Steps of Reproduction ✅
1. Build and run the packaged Electron main process using `npm run build`, which compiles
`src/main/*.ts` (including `auth.ts` and `integration-event-bridge.ts`) to JavaScript
while static imports reference `./auth` without an extension (see usages in
`src/main/proactive-agent.ts:8`, `src/main/integrations.ts:5`,
`src/main/cloud-agent.ts:17`, `src/main/relay-workspace.ts:3`, and
`src/main/ipc-handlers.ts:21`).

2. In the running app, trigger integration event subscription reconciliation so
`IntegrationsManager.syncEventSubscriptions` calls `integrationEventBridge.reconcile(...)`
(see `src/main/integrations.ts:1652-1657`), which internally needs a Relay workspace
handle and calls the private `getWorkspaceHandle()` method (see
`src/main/integration-event-bridge.ts:24-88`).

3. `getWorkspaceHandle()` performs a dynamic import using the specifier `await
import('./auth.ts')` (see `src/main/integration-event-bridge.ts:24-27`), which in the
compiled JavaScript will try to load a module literally named `./auth.ts` even though the
built file is `auth.js` and all other imports target `./auth` without an extension.

4. This dynamic import rejects at runtime due to a failed module resolution or yields a
distinct module identity from the `./auth` import graph, causing `getWorkspaceHandle()` to
throw before resolving credentials, so `syncEventSubscriptions()` logs `[integrations]
Failed to reconcile integration event subscriptions` and returns false (see
`src/main/integrations.ts:13-22`), leaving integration events unsubscribed.

Fix in Cursor | Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** src/main/integration-event-bridge.ts
**Line:** 945:945
**Comment:**
	*Api Mismatch: The dynamic import uses `./auth.ts` while the rest of the code imports the same module via `./auth`. In packaged/runtime builds this can break chunk/module resolution or create inconsistent module identity behavior for the same dependency. Use the same module specifier style as the rest of the codebase for this import.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

@codeant-ai

codeant-ai Bot commented Jun 5, 2026

Copy link
Copy Markdown

CodeAnt AI finished reviewing your PR.

@agent-relay-code

Copy link
Copy Markdown
Contributor

Reviewed and fixed PR #95 locally.

Changes made:

  • Fixed unauthorized detection in integration-event-bridge.ts and integration-mounts.ts so plain "Unauthorized" / "Unauthorised" messages trigger the refresh retry path.
  • Added a mount regression test proving an unauthorized Relayfile mount setup refreshes cloud auth and retries with the refreshed token.
  • Fixed stale integrations.test.ts setup by mocking the current workspace integrations endpoint and waiting for the deferred mount sync path correctly.

Validation run:

  • npm ci
  • npx vitest run passed: 8 files, 81 tests
  • npm test passed: 34 node tests
  • npx tsc --noEmit --pretty false passed

@agent-relay-code

Copy link
Copy Markdown
Contributor

✅ pr-reviewer applied fixes — committed and pushed ce4b708 to this PR. The notes below describe what changed.

Reviewed and fixed PR #95 locally.

Changes made:

  • Fixed unauthorized detection in integration-event-bridge.ts and integration-mounts.ts so plain "Unauthorized" / "Unauthorised" messages trigger the refresh retry path.
  • Added a mount regression test proving an unauthorized Relayfile mount setup refreshes cloud auth and retries with the refreshed token.
  • Fixed stale integrations.test.ts setup by mocking the current workspace integrations endpoint and waiting for the deferred mount sync path correctly.

Validation run:

  • npm ci
  • npx vitest run passed: 8 files, 81 tests
  • npm test passed: 34 node tests
  • npx tsc --noEmit --pretty false passed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:M This PR changes 30-99 lines, ignoring generated files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant