Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix: distinguish GitHub repository errors from empty results (#21174)

AmAzing-53994223eb52
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index d403cc44a21..4ae77d650bc 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -624,11 +624,13 @@
"environments.form.sourcesHint": "Cloned over HTTPS before anything else runs. Private repositories are not supported yet — a specification holds no credentials.",
"environments.github.connect": "Connect GitHub",
"environments.github.label": "Repository",
+ "environments.github.loadFailed": "Could not load GitHub repositories. Try again.",
"environments.github.noRepositories": "This connection cannot see any repositories yet",
"environments.github.notConnected": "No GitHub connection yet — connect one to build an environment from a repository",
"environments.github.optional": "optional",
"environments.github.organization": "Organization",
"environments.github.organizationPlaceholder": "Search organizations",
+ "environments.github.refreshFailed": "Could not refresh GitHub repositories. Showing the previous list. Try again.",
"environments.github.repository": "Repository",
"environments.github.repositoryPending": "Choose an organization first",
"environments.github.repositoryPlaceholder": "Search repositories",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index 3ed56d99369..b2eb2190028 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -624,11 +624,13 @@
"environments.form.sourcesHint": "在其他步骤之前通过 HTTPS 克隆。暂不支持私有仓库——规格里不存放任何凭据。",
"environments.github.connect": "连接 GitHub",
"environments.github.label": "代码仓库",
+ "environments.github.loadFailed": "无法加载 GitHub 仓库,请重试。",
"environments.github.noRepositories": "这个连接还看不到任何仓库",
"environments.github.notConnected": "还没有连接 GitHub——连接后即可按仓库创建环境",
"environments.github.optional": "可不选",
"environments.github.organization": "组织",
"environments.github.organizationPlaceholder": "搜索组织",
+ "environments.github.refreshFailed": "无法刷新 GitHub 仓库,当前显示上次的列表,请重试。",
"environments.github.repository": "仓库",
"environments.github.repositoryPending": "请先选择组织",
"environments.github.repositoryPlaceholder": "搜索仓库",
diff --git a/packages/connector-data/src/github/client-market.test.ts b/packages/connector-data/src/github/client-market.test.ts
index 0a54a193dea..306e9e68d5e 100644
--- a/packages/connector-data/src/github/client-market.test.ts
+++ b/packages/connector-data/src/github/client-market.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it, vi } from 'vitest';
+import { ConnectorDataError } from '../errors';
import {
createGitHubMarketConnectorClient,
createGitHubMarketTransport,
@@ -124,3 +125,31 @@ describe('createGitHubMarketConnectorClient', () => {
);
});
});
+
+describe('GitHub proxy authorization failures', () => {
+ it('normalizes an expired 401 to authorization unavailable', async () => {
+ const client = createGitHubMarketConnectorClient({
+ market: {
+ proxyOAuthRequest: async () => ({ status: 401, data: {} }),
+ },
+ });
+ const result = client.listAccessibleRepositories();
+ await expect(result).rejects.toBeInstanceOf(ConnectorDataError);
+ await expect(result).rejects.toMatchObject({
+ code: 'github_authorization_unavailable',
+ provider: 'github',
+ retryable: false,
+ });
+ });
+
+ it.each([403, 500, 503])('preserves HTTP %i as a request failure', async (status) => {
+ const client = createGitHubMarketConnectorClient({
+ market: {
+ proxyOAuthRequest: async () => ({ status, data: {} }),
+ },
+ });
+ const result = client.listAccessibleRepositories();
+ await expect(result).rejects.not.toBeInstanceOf(ConnectorDataError);
+ await expect(result).rejects.toMatchObject({ status });
+ });
+});
diff --git a/packages/connector-data/src/github/client-market.ts b/packages/connector-data/src/github/client-market.ts
index 9daeed137bf..78827e30ffa 100644
--- a/packages/connector-data/src/github/client-market.ts
+++ b/packages/connector-data/src/github/client-market.ts
@@ -1,5 +1,6 @@
import { toRecord } from '@lobechat/utils/object';
+import { ConnectorDataError } from '../errors';
import { createRecoverableMemo } from '../memo';
import { createGitHubConnectorClient, type GitHubConnectorClient } from './client';
import type { GitHubConnectorTransport } from './graphql/client';
@@ -54,6 +55,15 @@ const parseProxyResponse = (value: unknown): MarketProxyResponse => {
if (typeof response.status !== 'number' || !Number.isFinite(response.status)) {
throw new Error('GitHub Market proxy status is invalid');
}
+ if (response.status === 401) {
+ throw new ConnectorDataError({
+ cause: { status: response.status },
+ code: 'github_authorization_unavailable',
+ operation: 'proxyRequest',
+ provider: 'github',
+ retryable: false,
+ });
+ }
if (response.status < 200 || response.status >= 300) {
throw Object.assign(new Error('GitHub Market proxy request failed'), {
status: response.status,
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index a2cc86a6526..e25f2dbba90 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -4179,6 +4179,9 @@ When I am ___, I need ___
'environments.upgrade.benefits.instances.title': 'One copy per task',
'environments.upgrade.benefits.instances.desc':
'Parallel conversations each run in their own copy of the environment, so nothing overwrites anything else.',
+ 'environments.github.refreshFailed':
+ 'Could not refresh GitHub repositories. Showing the previous list. Try again.',
+ 'environments.github.loadFailed': 'Could not load GitHub repositories. Try again.',
'environments.github.label': 'Repository',
'environments.github.notConnected':
'No GitHub connection yet — connect one to build an environment from a repository',
diff --git a/src/features/EnvironmentManager/GithubRepositoryPicker.tsx b/src/features/EnvironmentManager/GithubRepositoryPicker.tsx
index 7323a36a529..7b1e9bdc28d 100644
--- a/src/features/EnvironmentManager/GithubRepositoryPicker.tsx
+++ b/src/features/EnvironmentManager/GithubRepositoryPicker.tsx
@@ -5,10 +5,10 @@ import { Button, createStaticStyles, cssVar, Flexbox, Icon, Select, Text } from
import { ArrowRightIcon, LockIcon } from 'lucide-react';
import { memo, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import useSWR from 'swr';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
-import { sandboxStorageService } from '@/services/sandboxStorage';
+
+import { useGithubRepositories } from './useGithubRepositories';
const styles = createStaticStyles(({ css }) => ({
field: css`
@@ -108,9 +108,7 @@ const GithubRepositoryPicker = memo<GithubRepositoryPickerProps>(({ onChange, on
navigate('/settings/credential');
};
- const { data, isLoading } = useSWR('sandbox-github-repositories', () =>
- sandboxStorageService.listGithubRepositories(),
- );
+ const { data, isLoading, isValidating, retry, state } = useGithubRepositories();
// Memoised, not a bare `??` fallback: a fresh `[]` on every render would
// make both lists below recompute every time, which is exactly what they are
@@ -129,35 +127,50 @@ const GithubRepositoryPicker = memo<GithubRepositoryPickerProps>(({ onChange, on
[owner, repositories],
);
- // Both of these are the same kind of answer — "there is nothing to pick from
- // yet, and here is what to do about it" — so they share one shape. An empty
- // list on a live connection usually means the connection cannot see the
- // organization the person is thinking of, which is fixed in the same place.
const guide =
- data?.connected === false
- ? { action: 'connect', text: t('environments.github.notConnected') }
- : !isLoading && repositories.length === 0
- ? { action: 'review', text: t('environments.github.noRepositories') }
- : undefined;
+ state === 'error'
+ ? {
+ action: 'retry',
+ text: t(
+ repositories.length > 0
+ ? 'environments.github.refreshFailed'
+ : 'environments.github.loadFailed',
+ ),
+ }
+ : state === 'disconnected'
+ ? { action: 'connect', text: t('environments.github.notConnected') }
+ : state === 'empty'
+ ? { action: 'review', text: t('environments.github.noRepositories') }
+ : undefined;
+
+ const guideContent = guide && (
+ <div className={styles.guide} role={state === 'error' ? 'alert' : undefined}>
+ <span className={styles.guideText}>{guide.text}</span>
+ <Button
+ loading={guide.action === 'retry' && isValidating}
+ size={'small'}
+ onClick={guide.action === 'retry' ? () => void retry() : connectGithub}
+ >
+ {guide.action === 'retry'
+ ? t('retry', { ns: 'common' })
+ : t(
+ guide.action === 'connect'
+ ? 'environments.github.connect'
+ : 'environments.github.reviewAccess',
+ )}
+ {guide.action !== 'retry' && <Icon icon={ArrowRightIcon} size={12} />}
+ </Button>
+ </div>
+ );
- if (guide)
+ if (guide && (state !== 'error' || repositories.length === 0))
return (
<Flexbox gap={6}>
<Flexbox horizontal align={'center'} gap={6}>
<Github size={13} />
<span className={styles.label}>{t('environments.github.label')}</span>
</Flexbox>
- <div className={styles.guide}>
- <span className={styles.guideText}>{guide.text}</span>
- <Button size={'small'} onClick={connectGithub}>
- {t(
- guide.action === 'connect'
- ? 'environments.github.connect'
- : 'environments.github.reviewAccess',
- )}
- <Icon icon={ArrowRightIcon} size={12} />
- </Button>
- </div>
+ {guideContent}
</Flexbox>
);
@@ -171,6 +184,7 @@ const GithubRepositoryPicker = memo<GithubRepositoryPickerProps>(({ onChange, on
</Text>
</Flexbox>
+ {guideContent}
<Flexbox horizontal gap={8}>
<div className={styles.field}>
<Text fontSize={11} type={'secondary'}>
diff --git a/src/features/EnvironmentManager/useGithubRepositories.test.ts b/src/features/EnvironmentManager/useGithubRepositories.test.ts
new file mode 100644
index 00000000000..3f3364432d8
--- /dev/null
+++ b/src/features/EnvironmentManager/useGithubRepositories.test.ts
@@ -0,0 +1,78 @@
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { createElement, type PropsWithChildren } from 'react';
+import { SWRConfig } from 'swr';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { sandboxStorageService } from '@/services/sandboxStorage';
+
+import { useGithubRepositories } from './useGithubRepositories';
+
+const setup = () => {
+ const cache = new Map();
+ return renderHook(() => useGithubRepositories(), {
+ wrapper: ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ {
+ value: { provider: () => cache, shouldRetryOnError: false, dedupingInterval: 0 },
+ },
+ children,
+ ),
+ });
+};
+
+afterEach(() => vi.restoreAllMocks());
+
+describe('GitHub repository loading', () => {
+ it('reports a rejected request as an error and retries the real SWR fetcher', async () => {
+ const fetcher = vi
+ .spyOn(sandboxStorageService, 'listGithubRepositories')
+ .mockRejectedValueOnce(new Error('HTTP 503'))
+ .mockResolvedValue({ connected: true, repositories: [] });
+ const { result } = setup();
+ await waitFor(() => expect(result.current.state).toBe('error'));
+ await act(async () => {
+ await result.current.retry();
+ });
+ await waitFor(() => expect(result.current.state).toBe('empty'));
+ expect(fetcher).toHaveBeenCalledTimes(2);
+ });
+
+ it('keeps previous repositories when retry fails and recovers without losing them', async () => {
+ const repositories = [{ owner: 'qa', name: 'repo', defaultBranch: 'main', isPrivate: false }];
+ const fetcher = vi
+ .spyOn(sandboxStorageService, 'listGithubRepositories')
+ .mockResolvedValueOnce({ connected: true, repositories })
+ .mockRejectedValueOnce(new Error('HTTP 503'))
+ .mockResolvedValue({ connected: true, repositories });
+ const { result } = setup();
+ await waitFor(() => expect(result.current.state).toBe('ready'));
+ await act(async () => {
+ await result.current.retry();
+ });
+ expect(result.current.state).toBe('error');
+ expect(result.current.data?.repositories).toEqual(repositories);
+ await act(async () => {
+ await result.current.retry();
+ });
+ expect(result.current.state).toBe('ready');
+ expect(fetcher).toHaveBeenCalledTimes(3);
+ });
+
+ it('does not call a pending request empty', () => {
+ vi.spyOn(sandboxStorageService, 'listGithubRepositories').mockReturnValue(
+ new Promise(() => {}),
+ );
+ const { result } = setup();
+ expect(result.current.state).toBe('loading');
+ });
+
+ it('keeps unavailable authorization distinct from a successful empty list', async () => {
+ vi.spyOn(sandboxStorageService, 'listGithubRepositories').mockResolvedValue({
+ connected: false,
+ repositories: [],
+ });
+ const { result } = setup();
+ await waitFor(() => expect(result.current.state).toBe('disconnected'));
+ });
+});
diff --git a/src/features/EnvironmentManager/useGithubRepositories.ts b/src/features/EnvironmentManager/useGithubRepositories.ts
new file mode 100644
index 00000000000..0bfe5a6502a
--- /dev/null
+++ b/src/features/EnvironmentManager/useGithubRepositories.ts
@@ -0,0 +1,26 @@
+import useSWR from 'swr';
+
+import { sandboxStorageService } from '@/services/sandboxStorage';
+
+/** Keeps request failure distinct from a successful empty repository listing. */
+export const useGithubRepositories = () => {
+ const swr = useSWR('sandbox-github-repositories', () =>
+ sandboxStorageService.listGithubRepositories(),
+ );
+ const state = swr.error
+ ? 'error'
+ : !swr.data
+ ? 'loading'
+ : !swr.data.connected
+ ? 'disconnected'
+ : swr.data.repositories.length === 0
+ ? 'empty'
+ : 'ready';
+
+ return {
+ ...swr,
+ state,
+ retry: () =>
+ swr.mutate(undefined, { revalidate: true, populateCache: false, throwOnError: false }),
+ };
+};