🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(chat): link GitHub PRs from message badges (#23309)
Bryane3f5f3f7cd70
diff --git a/apps/server/src/services/fileParse/worker.test.ts b/apps/server/src/services/fileParse/worker.test.tsindex 3630af0173c..c33aec9bad9 100644--- a/apps/server/src/services/fileParse/worker.test.ts+++ b/apps/server/src/services/fileParse/worker.test.ts@@ -16,6 +16,8 @@ import { FileParseError, parseDatasetInWorker, parseFileInWorker } from './index// a worker busy for ~1.5s, which on the request thread would stall every timer for as long.const here = (relative: string) => fileURLToPath(new URL(relative, import.meta.url));const SPARSE_ROWS = 100_000;+// Starting a real worker and walking the sparse range can exceed Vitest's default under CI load.+const SPARSE_PARSE_TEST_TIMEOUT_MS = 20_000;const CORRUPTED_PPTX = here('../../../../../packages/file-loaders/src/loaders/pptx/fixtures/corrupted-slides.pptx',);@@ -75,37 +77,45 @@ const trackTimerProgress = () => {};describe('file parse worker artifact', () => {- it('parses a spreadsheet with a huge declared range without stalling the main thread', async () => {- const stop = trackTimerProgress();- let ticks = 0;-- const document = await parseFileInWorker(SPARSE_XLSX, {- fileId: 'file-sparse',- mode: 'file',- }).finally(() => {- ticks = stop();- });-- expect(document.content).toContain('tail');- // A callback ran while the parse was pending on its worker thread.- expect(ticks).toBeGreaterThan(0);- });-- it('parses an eval dataset spreadsheet in the same bounded worker', async () => {- const content = new Uint8Array(await readFile(SPARSE_XLSX));- const stop = trackTimerProgress();- let ticks = 0;-- const result = await parseDatasetInWorker<{ totalCount: number }>(content, {- filename: 'sparse.xlsx',- preview: 50,- }).finally(() => {- ticks = stop();- });+ it(+ 'parses a spreadsheet with a huge declared range without stalling the main thread',+ async () => {+ const stop = trackTimerProgress();+ let ticks = 0;++ const document = await parseFileInWorker(SPARSE_XLSX, {+ fileId: 'file-sparse',+ mode: 'file',+ }).finally(() => {+ ticks = stop();+ });++ expect(document.content).toContain('tail');+ // A callback ran while the parse was pending on its worker thread.+ expect(ticks).toBeGreaterThan(0);+ },+ SPARSE_PARSE_TEST_TIMEOUT_MS,+ );- expect(ticks).toBeGreaterThan(0);- expect(result.totalCount).toBeGreaterThan(0);- });+ it(+ 'parses an eval dataset spreadsheet in the same bounded worker',+ async () => {+ const content = new Uint8Array(await readFile(SPARSE_XLSX));+ const stop = trackTimerProgress();+ let ticks = 0;++ const result = await parseDatasetInWorker<{ totalCount: number }>(content, {+ filename: 'sparse.xlsx',+ preview: 50,+ }).finally(() => {+ ticks = stop();+ });++ expect(ticks).toBeGreaterThan(0);+ expect(result.totalCount).toBeGreaterThan(0);+ },+ SPARSE_PARSE_TEST_TIMEOUT_MS,+ );it('parses CSV datasets and reports a broken JSON dataset as a parse failure', async () => {await expect(diff --git a/apps/server/src/services/workRegistration/topicPullRequestLinks.ts b/apps/server/src/services/workRegistration/topicPullRequestLinks.tsindex 4db0451f127..c6e99cd95eb 100644--- a/apps/server/src/services/workRegistration/topicPullRequestLinks.ts+++ b/apps/server/src/services/workRegistration/topicPullRequestLinks.ts@@ -9,24 +9,7 @@ const MAX_DISMISSED = 100;/** Concurrent writers each retry against the row they lost to. */const MAX_WRITE_ATTEMPTS = 3;-/** A github.com PR page, also one of its tabs (`/files`) or with a query / anchor. */-const PULL_URL_RE = /^https:\/\/github\.com\/([\w.-]+)\/([\w.-]+)\/pull\/(\d+)(?:[/?#]\S*)?$/i;--/** `owner/repo#number` and the canonical URL of a github.com pull request URL. */-export const parsePullRequestUrl = (- url: string,-): { identifier: string; number: number; repoFullName: string; url: string } | null => {- const match = PULL_URL_RE.exec(url.trim());- if (!match) return null;- const repoFullName = `${match[1]}/${match[2]}`;- const number = Number(match[3]);- return {- identifier: `${repoFullName}#${number}`,- number,- repoFullName,- url: `https://github.com/${repoFullName}/pull/${number}`,- };-};+export { parsePullRequestUrl } from '@lobechat/utils/githubPullRequest';const sameIdentifier = (a: string, b: string) => a.toLowerCase() === b.toLowerCase();diff --git a/packages/utils/src/githubPullRequest.ts b/packages/utils/src/githubPullRequest.tsnew file mode 100644index 00000000000..00624e39280--- /dev/null+++ b/packages/utils/src/githubPullRequest.ts@@ -0,0 +1,16 @@+/** A github.com PR page, including its tabs, query parameters and fragment. */+const PULL_REQUEST_URL = /^https:\/\/github\.com\/([\w.-]+)\/([\w.-]+)\/pull\/(\d+)(?:[/?#]\S*)?$/i;++export const parsePullRequestUrl = (url: string) => {+ const match = PULL_REQUEST_URL.exec(url.trim());+ if (!match) return null;++ const repoFullName = `${match[1]}/${match[2]}`;+ const number = Number(match[3]);+ return {+ identifier: `${repoFullName}#${number}`,+ number,+ repoFullName,+ url: `https://github.com/${repoFullName}/pull/${number}`,+ };+};diff --git a/src/features/Conversation/Markdown/plugins/Link/PullRequestLinkToolbar.tsx b/src/features/Conversation/Markdown/plugins/Link/PullRequestLinkToolbar.tsxnew file mode 100644index 00000000000..54a2b2111fe--- /dev/null+++ b/src/features/Conversation/Markdown/plugins/Link/PullRequestLinkToolbar.tsx@@ -0,0 +1,74 @@+import { Button, Popover } from '@lobehub/ui';+import { Link2 } from 'lucide-react';+import { type ReactNode, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useUserStore } from '@/store/user';+import { labPreferSelectors } from '@/store/user/selectors';++import { useConversationStore } from '../../../store';+import { usePullRequestLink } from './usePullRequestLink';++interface PullRequestLinkToolbarProps {+ children: ReactNode;+ identifier: string;+ url: string;+}++const Toolbar = ({+ children,+ identifier,+ topicId,+ url,+}: PullRequestLinkToolbarProps & { topicId: string }) => {+ const { t } = useTranslation('chat');+ const { canLink, link, linking } = usePullRequestLink(topicId, identifier, url);+ const [open, setOpen] = useState(false);++ return (+ <Popover+ open={canLink && open}+ placement={'topLeft'}+ popupProps={{ initialFocus: false }}+ styles={{ content: { padding: 4 } }}+ trigger={'hover'}+ triggerProps={{ role: undefined, tabIndex: undefined }}+ content={+ canLink ? (+ <Button+ icon={Link2}+ loading={linking}+ size={'small'}+ type={'text'}+ onClick={(event) => {+ event.stopPropagation();+ void link();+ }}+ >+ {t('workingPanel.overview.pr.linkAction')}+ </Button>+ ) : null+ }+ onOpenChange={setOpen}+ >+ <span+ onFocus={(event) => {+ if (canLink && event.target.matches(':focus-visible')) setOpen(true);+ }}+ >+ {children}+ </span>+ </Popover>+ );+};++export const PullRequestLinkToolbar = (props: PullRequestLinkToolbarProps) => {+ const enabled = useUserStore(labPreferSelectors.enableBetterCodingExperience);+ const topicId = useConversationStore(({ context, skipFetch }) =>+ skipFetch || context.topicShareId || context.agentShareId ? undefined : context.topicId,+ );++ if (!enabled || !topicId) return props.children;++ return <Toolbar key={`${topicId}:${props.identifier}`} {...props} topicId={topicId} />;+};diff --git a/src/features/Conversation/Markdown/plugins/Link/Render.tsx b/src/features/Conversation/Markdown/plugins/Link/Render.tsxnew file mode 100644index 00000000000..36fc8485e3c--- /dev/null+++ b/src/features/Conversation/Markdown/plugins/Link/Render.tsx@@ -0,0 +1,20 @@+import { parsePullRequestUrl } from '@lobechat/utils/githubPullRequest';++import { EntityLinkElement } from '@/features/EntityLink';+import type { EntityLinkElementProps } from '@/features/EntityLink/types';++import { PullRequestLinkToolbar } from './PullRequestLinkToolbar';++export const ConversationLink = (props: EntityLinkElementProps) => {+ const { linkHref, linkKind } = props.node?.properties ?? {};+ const pullRequest = linkKind === 'github' && linkHref ? parsePullRequestUrl(linkHref) : null;+ const link = <EntityLinkElement.Component {...props} />;++ return pullRequest ? (+ <PullRequestLinkToolbar identifier={pullRequest.identifier} url={pullRequest.url}>+ {link}+ </PullRequestLinkToolbar>+ ) : (+ link+ );+};diff --git a/src/features/Conversation/Markdown/plugins/Link/index.ts b/src/features/Conversation/Markdown/plugins/Link/index.tsindex 15c42dcefbb..7a35d04fa5a 100644--- a/src/features/Conversation/Markdown/plugins/Link/index.ts+++ b/src/features/Conversation/Markdown/plugins/Link/index.ts@@ -1,19 +1,16 @@-import { type FC } from 'react';-import { EntityLinkElement } from '@/features/EntityLink';-import { type MarkdownElement, type MarkdownElementProps } from '../type';+import { type MarkdownElement } from '../type';+import { ConversationLink } from './Render';/*** Binds the host-agnostic entity-link capability to the conversation markdown* plugin registry.*- * The parsing, rendering and click behaviour live in `@/features/EntityLink`:- * the conversation is one host among several, and reading surfaces mount the- * same element through `useEntityMarkdown()`.+ * Conversation messages add topic actions to the shared entity-link renderer.*/const LinkElement: MarkdownElement = {- Component: EntityLinkElement.Component as FC<MarkdownElementProps>,+ Component: ConversationLink,rehypePlugin: EntityLinkElement.rehypePlugin,scope: 'all',tag: EntityLinkElement.tag,diff --git a/src/features/Conversation/Markdown/plugins/Link/usePullRequestLink.test.ts b/src/features/Conversation/Markdown/plugins/Link/usePullRequestLink.test.tsnew file mode 100644index 00000000000..da468aaf962--- /dev/null+++ b/src/features/Conversation/Markdown/plugins/Link/usePullRequestLink.test.ts@@ -0,0 +1,92 @@+// @vitest-environment happy-dom+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { usePullRequestLink } from './usePullRequestLink';++const mocks = vi.hoisted(() => ({+ error: vi.fn(),+ items: {} as Record<string, { identifier: string }[]>,+ link: vi.fn(),+ refresh: vi.fn(),+ success: vi.fn(),+}));++vi.mock('@lobehub/ui', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ toast: { error: mocks.error, success: mocks.success },+}));++vi.mock('@/services/work', () => ({+ workService: { linkTopicPullRequest: mocks.link, refreshTopicPullRequests: mocks.refresh },+}));++vi.mock('@/store/work', () => ({+ useWorkStore: (select: (state: typeof mocks.items) => unknown) => select(mocks.items),+ workActions: { useFetchTopicPullRequests: vi.fn() },+ workSelectors: {+ topicPullRequests: (topicId: string) => (state: typeof mocks.items) => state[topicId],+ },+}));++const TOPIC = 'tpc_test';+const PR = 'LobeHub/lobehub#42';+const URL = 'https://github.com/LobeHub/lobehub/pull/42';+const useTestPullRequest = () => usePullRequestLink(TOPIC, PR, URL);++describe('usePullRequestLink', () => {+ beforeEach(() => {+ vi.resetAllMocks();+ mocks.items = { [TOPIC]: [] };+ });++ it('waits for the current topic list and treats an existing PR as linked regardless of casing', () => {+ mocks.items = { tpc_other: [{ identifier: PR }] };+ const { result, rerender } = renderHook(useTestPullRequest);+ expect(result.current.canLink).toBe(false);++ mocks.items[TOPIC] = [{ identifier: 'lobehub/other#42' }];+ rerender();+ expect(result.current.canLink).toBe(true);++ mocks.items[TOPIC] = [{ identifier: PR.toLowerCase() }];+ rerender();+ expect(result.current.canLink).toBe(false);+ });++ it('writes once for repeated clicks and notices the link when the shared list refreshes', async () => {+ mocks.link.mockResolvedValue({ identifier: PR, linked: true });+ mocks.refresh.mockImplementation(async () => {+ mocks.items[TOPIC] = [{ identifier: PR }];+ });+ const { result, rerender } = renderHook(useTestPullRequest);++ await act(async () => {+ await Promise.all([result.current.link(), result.current.link()]);+ });++ expect(mocks.link).toHaveBeenCalledExactlyOnceWith({+ source: 'manual',+ topicId: TOPIC,+ url: URL,+ });+ expect(mocks.refresh).toHaveBeenCalledExactlyOnceWith(TOPIC);+ rerender();+ expect(result.current.canLink).toBe(false);+ expect(mocks.success).toHaveBeenCalledOnce();+ });++ it('keeps a failed link available for retry', async () => {+ mocks.link.mockResolvedValue({ identifier: PR, linked: false });+ const { result } = renderHook(useTestPullRequest);++ await act(async () => {+ await result.current.link();+ });++ expect(result.current.canLink).toBe(true);+ expect(result.current.linking).toBe(false);+ expect(mocks.refresh).not.toHaveBeenCalled();+ expect(mocks.error).toHaveBeenCalledOnce();+ });+});diff --git a/src/features/Conversation/Markdown/plugins/Link/usePullRequestLink.ts b/src/features/Conversation/Markdown/plugins/Link/usePullRequestLink.tsnew file mode 100644index 00000000000..429a1719877--- /dev/null+++ b/src/features/Conversation/Markdown/plugins/Link/usePullRequestLink.ts@@ -0,0 +1,37 @@+import { toast } from '@lobehub/ui';+import { useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { linkManualPullRequest } from '@/features/TopicPullRequests/linkManualPullRequest';+import { useWorkStore, workActions, workSelectors } from '@/store/work';++export const usePullRequestLink = (topicId: string, identifier: string, url: string) => {+ const { t } = useTranslation('chat');+ const [linking, setLinking] = useState(false);+ const inFlight = useRef(false);+ const key = identifier.toLowerCase();++ workActions.useFetchTopicPullRequests({ topicId });+ const canLink = useWorkStore((state) => {+ const items = workSelectors.topicPullRequests(topicId)(state);+ return !!items && !items.some((item) => item.identifier.toLowerCase() === key);+ });++ const link = async () => {+ if (!canLink || inFlight.current) return;+ inFlight.current = true;+ setLinking(true);++ try {+ const name = await linkManualPullRequest(topicId, url);+ toast.success(t('workingPanel.overview.pr.linked', { name }));+ } catch {+ toast.error(t('workingPanel.overview.pr.linkFailed'));+ } finally {+ inFlight.current = false;+ setLinking(false);+ }+ };++ return { canLink, link, linking };+};diff --git a/src/features/Conversation/WorkingSidebar/Overview/index.tsx b/src/features/Conversation/WorkingSidebar/Overview/index.tsxindex 546148578c9..408160b5213 100644--- a/src/features/Conversation/WorkingSidebar/Overview/index.tsx+++ b/src/features/Conversation/WorkingSidebar/Overview/index.tsx@@ -294,7 +294,7 @@ const Overview = memo<OverviewProps>(// Better Coding Experience PRs are server records: they stay listed with// their last known state even when the working directory cannot be read.- const pullRequestRows = pullRequests ? (+ const topicPullRequestRows = pullRequests && (<>{pullRequests.map((view) => (<PullRequestRow@@ -321,8 +321,6 @@ const Overview = memo<OverviewProps>())}{onLinkPullRequest && <LinkPullRequestRow onLink={onLinkPullRequest} />}</>- ) : (- pullRequest && <PullRequestRow pullRequest={pullRequest} onClick={() => onOpenTab('pr')} />);const gitRows = (@@ -435,7 +433,9 @@ const Overview = memo<OverviewProps>(onClick={() => onOpenTab('review')}/>- {pullRequestRows}+ {!pullRequests && pullRequest && (+ <PullRequestRow pullRequest={pullRequest} onClick={() => onOpenTab('pr')} />+ )}</>);@@ -445,24 +445,21 @@ const Overview = memo<OverviewProps>(<Skeleton.Text rows={3} /></div>) : gitError ? (- <>- <OverviewRow- danger- icon={TriangleAlertIcon}- iconColor={cssVar.colorError}- value={t('workingPanel.overview.environmentError')}- trailing={- <Button- icon={<Icon icon={RefreshCwIcon} size={12} />}- size={'small'}- onClick={() => void refreshGit()}- >- {tCommon('retry')}- </Button>- }- />- {pullRequests && pullRequestRows}- </>+ <OverviewRow+ danger+ icon={TriangleAlertIcon}+ iconColor={cssVar.colorError}+ value={t('workingPanel.overview.environmentError')}+ trailing={+ <Button+ icon={<Icon icon={RefreshCwIcon} size={12} />}+ size={'small'}+ onClick={() => void refreshGit()}+ >+ {tCommon('retry')}+ </Button>+ }+ />) : (gitRows)@@ -492,6 +489,7 @@ const Overview = memo<OverviewProps>() : (workspaceSection)}+ {(repoType || !!pullRequests?.length) && topicPullRequestRows}{/* Outside the git rows: a dev server runs in plain folders too. */}{tunnelsEnabled && deviceId && (<PortSwitcher@@ -503,6 +501,9 @@ const Overview = memo<OverviewProps>(</Flexbox></>)}+ {!hasWorkspace && !!pullRequests?.length && (+ <Flexbox {...sectionProps()}>{topicPullRequestRows}</Flexbox>+ )}{/* The bound machine's live state, as its device card shows it. */}{statusDeviceId && <DeviceStatusSection active={active} deviceId={statusDeviceId} />}diff --git a/src/features/Conversation/WorkingSidebar/Overview/useLinkPullRequestField.ts b/src/features/Conversation/WorkingSidebar/Overview/useLinkPullRequestField.tsindex d53b70241da..1d70be458d9 100644--- a/src/features/Conversation/WorkingSidebar/Overview/useLinkPullRequestField.ts+++ b/src/features/Conversation/WorkingSidebar/Overview/useLinkPullRequestField.ts@@ -1,11 +1,9 @@+import { parsePullRequestUrl } from '@lobechat/utils/githubPullRequest';import { toast } from '@lobehub/ui';import { useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';-/** `https://github.com/<owner>/<repo>/pull/<n>`, also with a tab or query after it. */-const PULL_URL_RE = /^https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/\d+(?:[/?#]\S*)?$/i;--export const isPullRequestUrl = (value: string) => PULL_URL_RE.test(value.trim());+export const isPullRequestUrl = (value: string) => !!parsePullRequestUrl(value);/*** State of the "Link a pull request" dialog's field: links on submit, explainsdiff --git a/src/features/Conversation/WorkingSidebar/PullRequest/useSidebarPullRequests.ts b/src/features/Conversation/WorkingSidebar/PullRequest/useSidebarPullRequests.tsindex a6e9af2d575..60b8048fdf8 100644--- a/src/features/Conversation/WorkingSidebar/PullRequest/useSidebarPullRequests.ts+++ b/src/features/Conversation/WorkingSidebar/PullRequest/useSidebarPullRequests.ts@@ -1,6 +1,7 @@import type { DeviceGitLinkedPullRequest } from '@lobechat/types';import { useCallback, useMemo, useState } from 'react';+import { linkManualPullRequest } from '@/features/TopicPullRequests/linkManualPullRequest';import type { TopicPullRequestView } from '@/features/TopicPullRequests/pullRequestView';import { useTopicPullRequests } from '@/features/TopicPullRequests/useTopicPullRequests';import { workService } from '@/services/work';@@ -76,19 +77,8 @@ export const useSidebarPullRequests = (params: {);/** Link a PR by URL; resolves to its `owner/repo#n`, or throws on a bad URL. */const linkPullRequest = useCallback(- async (url: string) => {- if (!topicId) return undefined;- const { identifier, linked } = await workService.linkTopicPullRequest({- source: 'manual',- topicId,- url,- });- // Not saved: reject so the dialog stays open with its error.- if (!linked) throw new Error(`Could not link ${identifier}`);- await refresh();- return identifier;- },- [refresh, topicId],+ async (url: string) => (topicId ? linkManualPullRequest(topicId, url) : undefined),+ [topicId],);if (!linked.enabled) {diff --git a/src/features/TopicPullRequests/linkManualPullRequest.ts b/src/features/TopicPullRequests/linkManualPullRequest.tsnew file mode 100644index 00000000000..7068e831637--- /dev/null+++ b/src/features/TopicPullRequests/linkManualPullRequest.ts@@ -0,0 +1,12 @@+import { workService } from '@/services/work';++export const linkManualPullRequest = async (topicId: string, url: string): Promise<string> => {+ const { identifier, linked } = await workService.linkTopicPullRequest({+ source: 'manual',+ topicId,+ url,+ });+ if (!linked) throw new Error(`Could not link ${identifier}`);+ await workService.refreshTopicPullRequests(topicId);+ return identifier;+};