🤯 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(cli): look up conversations linked to a GitHub PR (#23313)
Bryanccdcdcf9f63b
diff --git a/apps/cli/src/commands/work.test.ts b/apps/cli/src/commands/work.test.tsnew file mode 100644index 00000000000..f5033b480a8--- /dev/null+++ b/apps/cli/src/commands/work.test.ts@@ -0,0 +1,79 @@+import { Command } from 'commander';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { registerWorkCommand } from './work';++const mocks = vi.hoisted(() => ({ lookup: vi.fn(), workspace: vi.fn() }));+vi.mock('../api/client', () => ({+ getTrpcClient: async () => ({+ work: { lookupPullRequest: { query: mocks.lookup } },+ workspace: { getById: { query: mocks.workspace } },+ }),+}));++const url = 'https://github.com/owner/repo/pull/12/files';+const topics = [+ { agentId: 'agt_a', groupId: null, title: 'Implementation', topicId: 'tpc_a' },+ { agentId: null, groupId: 'grp_b', title: 'Review', topicId: 'tpc_b' },+];++const lookup = async (...args: string[]) => {+ const program = new Command().exitOverride();+ registerWorkCommand(program);+ await program.parseAsync(['work', 'lookup', url, ...args], { from: 'user' });+};++describe('work lookup', () => {+ beforeEach(() => {+ mocks.lookup.mockReset();+ mocks.workspace.mockReset();+ mocks.lookup.mockResolvedValue({ data: topics });+ mocks.workspace.mockResolvedValue({ slug: 'team' });+ vi.stubEnv('LOBEHUB_SERVER', 'https://app.example.com');+ vi.stubEnv('LOBEHUB_WORKSPACE_ID', 'workspace-1');+ });++ afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllEnvs();+ });++ it('outputs all conversations with scoped agent and group URLs in JSON', async () => {+ const out = vi.spyOn(console, 'log').mockImplementation(() => {});+ await lookup('--json');++ expect(mocks.lookup).toHaveBeenCalledWith({ url });+ const [json] = out.mock.calls[0];+ expect(JSON.parse(json)).toEqual([+ { ...topics[0], url: 'https://app.example.com/team/agent/agt_a/tpc_a' },+ { ...topics[1], url: 'https://app.example.com/team/group/grp_b/tpc_b' },+ ]);+ });++ it('prints one row per conversation in the terminal', async () => {+ const out = vi.spyOn(console, 'log').mockImplementation(() => {});+ await lookup();++ expect(out).toHaveBeenCalledTimes(3);+ expect(out.mock.calls[1][0]).toMatch(+ /Implementation +https:\/\/app\.example\.com\/team\/agent\/agt_a\/tpc_a/,+ );+ expect(out.mock.calls[2][0]).toMatch(+ /Review +https:\/\/app\.example\.com\/team\/group\/grp_b\/tpc_b/,+ );+ });++ it('prints a useful empty state and an empty JSON array', async () => {+ const out = vi.spyOn(console, 'log').mockImplementation(() => {});+ mocks.lookup.mockResolvedValue({ data: [] });++ await lookup();+ await lookup('--json');++ expect(out.mock.calls).toEqual([+ ['No linked conversations found in the current workspace.'],+ ['[]'],+ ]);+ expect(mocks.workspace).not.toHaveBeenCalled();+ });+});diff --git a/apps/cli/src/commands/work.ts b/apps/cli/src/commands/work.tsnew file mode 100644index 00000000000..5dd188c5b7a--- /dev/null+++ b/apps/cli/src/commands/work.ts@@ -0,0 +1,46 @@+import type { Command } from 'commander';++import { getTrpcClient } from '../api/client';+import { outputJson, printTable } from '../utils/format';+import { resolveUrlBuilder, resourcePath } from './resourceUrl';++interface LinkedTopic {+ agentId: string | null;+ groupId: string | null;+ title: string | null;+ topicId: string;+}++export function registerWorkCommand(program: Command) {+ const work = program.command('work').description('Look up agent work');++ work+ .command('lookup')+ .argument('<github-pr-url>', 'GitHub pull request URL')+ .description('Find all conversations linked to a GitHub pull request in the current workspace')+ .option('--json', 'Output JSON')+ .action(async (url: string, options: { json?: boolean }) => {+ const client = await getTrpcClient();+ const { data }: { data: LinkedTopic[] } = await client.work.lookupPullRequest.query({ url });++ if (data.length === 0) {+ if (options.json) outputJson([]);+ else console.log('No linked conversations found in the current workspace.');+ return;+ }++ const toUrl = await resolveUrlBuilder(client);+ const topics = data.map((topic) => ({+ ...topic,+ url: toUrl(resourcePath.topic({ ...topic, id: topic.topicId })),+ }));++ if (options.json) outputJson(topics);+ else {+ printTable(+ topics.map((topic) => [topic.title || 'Untitled', topic.url || topic.topicId]),+ ['TITLE', 'CONVERSATION'],+ );+ }+ });+}diff --git a/apps/cli/src/program.ts b/apps/cli/src/program.tsindex 071d09d894b..1189a273ee8 100644--- a/apps/cli/src/program.ts+++ b/apps/cli/src/program.ts@@ -50,6 +50,7 @@ import { registerUpdateCommand } from './commands/update';import { registerUserCommand } from './commands/user';import { registerWebhookCommand } from './commands/webhook';import { registerWidgetCommand } from './commands/widget';+import { registerWorkCommand } from './commands/work';import { registerWorkspaceCommand } from './commands/workspace';import { CLI_DISPLAY_NAME, CLI_PRIMARY_BIN, CLI_PRODUCT_NAME } from './constants/identity';import { cliVersion } from './pkg';@@ -114,6 +115,7 @@ export function createProgram() {registerTaskCommand(program);registerThreadCommand(program);registerTopicCommand(program);+ registerWorkCommand(program);registerTraceCommand(program);registerMessageCommand(program);registerModelCommand(program);diff --git a/apps/server/src/routers/lambda/__tests__/work.topicPullRequests.test.ts b/apps/server/src/routers/lambda/__tests__/work.topicPullRequests.test.tsindex 1a14c5d6f7b..04ef64c6130 100644--- a/apps/server/src/routers/lambda/__tests__/work.topicPullRequests.test.ts+++ b/apps/server/src/routers/lambda/__tests__/work.topicPullRequests.test.ts@@ -1,9 +1,12 @@// @vitest-environment node+import { TRPCError } from '@trpc/server';import { beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({assertCanUseTopicTargets: vi.fn(),+ assertCanViewTopicTargets: vi.fn(),linkTopicPullRequest: vi.fn(async () => true),+ listTopicsByPullRequest: vi.fn(),setTopicPullRequestDismissed: vi.fn(async () => true),}));@@ -18,12 +21,17 @@ vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({}));vi.mock('../_helpers/conversationResourceGuard', () => ({assertCanUseTopicTargets: mocks.assertCanUseTopicTargets,+ assertCanViewTopicTargets: mocks.assertCanViewTopicTargets,}));const Model = vi.fn(function () {return {};});vi.mock('@/database/models/message', () => ({ MessageModel: Model }));-vi.mock('@/database/models/work', () => ({ WorkModel: Model }));+vi.mock('@/database/models/work', () => ({+ WorkModel: vi.fn(function () {+ return { listTopicsByPullRequest: mocks.listTopicsByPullRequest };+ }),+}));vi.mock('@/database/models/topic', () => ({ TopicModel: Model }));vi.mock('@/server/services/workRegistration', async (importOriginal) => ({...(await importOriginal<any>()),@@ -84,4 +92,55 @@ describe('workRouter — topic PR links honour conversation access', () => {}),).toEqual({ updated: true });});++ it('looks up the PR identity and omits conversations the caller cannot view', async () => {+ mocks.listTopicsByPullRequest.mockResolvedValue([+ { agentId: 'agent-1', groupId: null, sessionId: null, title: 'Visible', topicId: 'visible' },+ { agentId: 'agent-2', groupId: null, sessionId: null, title: 'Hidden', topicId: 'hidden' },+ ]);+ mocks.assertCanViewTopicTargets.mockImplementation(async (_ctx, [topicId]) => {+ if (topicId === 'hidden') throw new TRPCError({ code: 'FORBIDDEN' });+ return [];+ });++ expect(+ await caller().lookupPullRequest({ url: 'https://github.com/a/b/pull/1/files#diff' }),+ ).toEqual({+ data: [{ agentId: 'agent-1', groupId: null, title: 'Visible', topicId: 'visible' }],+ success: true,+ });+ expect(mocks.listTopicsByPullRequest).toHaveBeenCalledWith('a/b#1');+ });++ it('bounds concurrent permission checks while returning every visible conversation in order', async () => {+ const topics = Array.from({ length: 21 }, (_, index) => ({+ agentId: `agent-${index}`,+ groupId: null,+ sessionId: null,+ title: `Topic ${index}`,+ topicId: `topic-${index}`,+ }));+ mocks.listTopicsByPullRequest.mockResolvedValue(topics);+ let active = 0;+ let peak = 0;+ mocks.assertCanViewTopicTargets.mockImplementation(async () => {+ active += 1;+ peak = Math.max(peak, active);+ await new Promise<void>((resolve) => setImmediate(resolve));+ active -= 1;+ return [];+ });++ const result = await caller().lookupPullRequest({ url: 'https://github.com/a/b/pull/1' });++ expect(result.data.map((topic) => topic.topicId)).toEqual(topics.map((topic) => topic.topicId));+ expect(peak).toBeLessThanOrEqual(10);+ });++ it('rejects links to GitHub issues before looking up associations', async () => {+ await expect(+ caller().lookupPullRequest({ url: 'https://github.com/a/b/issues/1' }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ expect(mocks.listTopicsByPullRequest).not.toHaveBeenCalled();+ });});diff --git a/apps/server/src/routers/lambda/work.ts b/apps/server/src/routers/lambda/work.tsindex c8a4f57537c..01d8c442bea 100644--- a/apps/server/src/routers/lambda/work.ts+++ b/apps/server/src/routers/lambda/work.ts@@ -7,6 +7,7 @@ import {type WorkVersionCumulativeUsage,} from '@lobechat/types';import { TRPCError } from '@trpc/server';+import pMap from 'p-map';import { z } from 'zod';import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';@@ -30,7 +31,11 @@ import {setTopicPullRequestDismissed,} from '@/server/services/workRegistration';-import { assertCanUseTopicTargets } from './_helpers/conversationResourceGuard';+import {+ assertCanUseTopicTargets,+ assertCanViewTopicTargets,+} from './_helpers/conversationResourceGuard';+import { batchResolveAgentIdFromSessions } from './_helpers/resolveContext';const topicGuardCtx = (ctx: {serverDB: LobeChatDatabase;@@ -51,6 +56,8 @@ const workProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =>});});+const lookupPullRequestInput = z.object({ url: z.string().trim().min(1).max(2048) });+// Task-domain write gate. Task mutations elsewhere (see the task router's// `taskProcedureWrite`) gate on `agent:update`, so a Work registration that// records a task mutation must require the same permission — otherwise a role@@ -319,6 +326,58 @@ export const workRouter = router({}),),+ lookupPullRequest: workProcedure.input(lookupPullRequestInput).query(async ({ ctx, input }) => {+ const pr = parsePullRequestUrl(input.url);+ if (!pr) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'Expected a GitHub pull request URL, e.g. https://github.com/owner/repo/pull/123',+ });+ }++ const topics = await ctx.workModel.listTopicsByPullRequest(pr.identifier);+ const guardCtx = topicGuardCtx(ctx);+ const accessByTarget = new Map<string, Promise<boolean>>();+ const canView = (topic: (typeof topics)[number]) => {+ const key = JSON.stringify([topic.agentId, topic.groupId, topic.sessionId]);+ const cached = accessByTarget.get(key);+ if (cached) return cached;+ const access = assertCanViewTopicTargets(guardCtx, [topic.topicId]).then(+ () => true,+ (error: unknown) => {+ if (error instanceof TRPCError && error.code === 'FORBIDDEN') return false;+ throw error;+ },+ );+ accessByTarget.set(key, access);+ return access;+ };+ const visible = ctx.workspaceId+ ? (+ await pMap(topics, async (topic) => ((await canView(topic)) ? [topic] : []), {+ concurrency: 10,+ })+ ).flat()+ : topics;++ const legacySessionIds = visible.flatMap(({ agentId, groupId, sessionId }) =>+ !agentId && !groupId && sessionId ? [sessionId] : [],+ );+ const sessionAgentIds = await batchResolveAgentIdFromSessions(+ [...new Set(legacySessionIds)],+ ctx.serverDB,+ ctx.userId,+ ctx.workspaceId ?? undefined,+ );+ return {+ data: visible.map(({ sessionId, ...topic }) => ({+ ...topic,+ agentId: topic.agentId ?? (sessionId && sessionAgentIds.get(sessionId)) ?? null,+ })),+ success: true,+ };+ }),+// Better Coding Experience: link the pull requests a `git push` tool call// updated, right after it ran. The push itself is re-read from the persisted// tool message; see `linkPushedPullRequests` for what the device may add.diff --git a/apps/server/src/services/workRegistration/topicPullRequestLinks.test.ts b/apps/server/src/services/workRegistration/topicPullRequestLinks.test.tsindex 7b1ded17df8..16802b1e731 100644--- a/apps/server/src/services/workRegistration/topicPullRequestLinks.test.ts+++ b/apps/server/src/services/workRegistration/topicPullRequestLinks.test.ts@@ -37,6 +37,8 @@ describe('parsePullRequestUrl', () => {url: 'https://github.com/LobeHub/lobehub/pull/12',});expect(parsePullRequestUrl('https://github.com/a/b/issues/1')).toBeNull();+ expect(parsePullRequestUrl('https://github.com/a/b/pull/0')).toBeNull();+ expect(parsePullRequestUrl('https://github.com/a/b/pull/9007199254740993')).toBeNull();expect(parsePullRequestUrl('http://evil.com/a/b/pull/1')).toBeNull();});});diff --git a/packages/database/src/models/work/__tests__/pullRequests.test.ts b/packages/database/src/models/work/__tests__/pullRequests.test.tsindex cb3b72ef001..1adb6f6dd49 100644--- a/packages/database/src/models/work/__tests__/pullRequests.test.ts+++ b/packages/database/src/models/work/__tests__/pullRequests.test.ts@@ -1,8 +1,9 @@// @vitest-environment nodeimport type { RegisterExternalWorkParams } from '@lobechat/types';+import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';-import { topics } from '../../../schemas';+import { topics, works, workspaces, workVersions } from '../../../schemas';import { WorkModel } from '..';import {cleanupWorkTestData,@@ -37,6 +38,127 @@ const pr = (...overrides,});+describe('WorkModel.listTopicsByPullRequest', () => {+ const identifier = 'lobeHub/lobehub#42';+ const link = (source: 'branch' | 'manual') => ({+ identifier,+ linkedAt: '2026-11-01T00:00:00Z',+ source,+ url: 'https://github.com/lobeHub/lobehub/pull/42',+ vouched: true,+ });++ it('returns Work, manual and branch associations once and respects dismissal', async () => {+ await serverDB.insert(topics).values([+ { id: 'work-other', userId },+ { id: 'manual', metadata: { pullRequests: { links: [link('manual')] } }, userId },+ { id: 'branch', metadata: { pullRequests: { links: [link('branch')] } }, userId },+ {+ id: 'dismissed',+ metadata: {+ pullRequests: { dismissed: [identifier.toUpperCase()], links: [link('manual')] },+ },+ userId,+ },+ { id: 'same-number', userId },+ ]);+ await serverDB+ .update(topics)+ .set({ metadata: { pullRequests: { links: [link('manual')] } } })+ .where(eq(topics.id, topicId));+ const model = new WorkModel(serverDB, userId);+ await model.registerExternal(pr(identifier, 'first'));+ await model.registerExternal(pr(identifier, 'again', { changeType: 'updated' }));+ await model.registerExternal(pr(identifier, 'other', { topicId: 'work-other' }));+ await model.registerExternal(pr(identifier, 'dismissed', { topicId: 'dismissed' }));+ await model.registerExternal(pr('another/repo#42', 'another', { topicId: 'same-number' }));++ const matches = await model.listTopicsByPullRequest(identifier.toUpperCase());+ expect(matches.map((topic) => topic.topicId).sort()).toEqual(+ ['branch', 'manual', 'work-other', topicId].sort(),+ );+ expect(await model.listTopicsByPullRequest('lobehub/lobehub#43')).toEqual([]);+ });++ it('keeps personal, workspace, trashed and Agent Share topics fenced', async () => {+ const workspaceId = 'work-pr-lookup-workspace';+ await serverDB.insert(workspaces).values({+ id: workspaceId,+ name: 'Test',+ primaryOwnerId: userId,+ slug: 'pr-lookup',+ });+ try {+ const metadata = { pullRequests: { links: [link('manual')] } };+ await serverDB.insert(topics).values([+ { id: 'mine', metadata, userId },+ { id: 'someone-elses', metadata, userId: userId2 },+ { id: 'team', metadata, userId, workspaceId },+ { id: 'team-work-only', userId, workspaceId },+ { id: 'trashed', isDeleted: true, metadata, userId },+ { id: 'visitor', metadata, senderId: 'visitor-id', userId },+ ]);+ await new WorkModel(serverDB, userId, workspaceId).registerExternal(+ pr(identifier, 'team-work', { topicId: 'team-work-only' }),+ );++ const personal = await new WorkModel(serverDB, userId).listTopicsByPullRequest(identifier);+ expect(personal.map((topic) => topic.topicId)).toEqual(['mine']);+ const team = await new WorkModel(serverDB, userId2, workspaceId).listTopicsByPullRequest(+ identifier,+ );+ expect(team.map((topic) => topic.topicId)).toEqual(['team']);+ } finally {+ await serverDB.delete(workspaces).where(eq(workspaces.id, workspaceId));+ }+ });++ it('matches the sidebar cap on historical Work links per topic', async () => {+ const older = new Date('2026-01-01T00:00:00Z');+ const newer = new Date('2026-02-01T00:00:00Z');+ const resourceIds = [identifier, ...Array.from({ length: 50 }, (_, i) => `a/b#${i + 1}`)];+ const rows = await serverDB+ .insert(works)+ .values(+ resourceIds.map((resourceId) => ({+ resourceId,+ resourceType: 'github_pull_request' as const,+ toolIdentifier: 'github',+ toolName: 'update_pull_request',+ type: 'external' as const,+ userId,+ visibility: 'private' as const,+ })),+ )+ .returning({ id: works.id, resourceId: works.resourceId });+ await serverDB.insert(workVersions).values(+ rows.map((row) => ({+ changeType: 'updated' as const,+ createdAt: row.resourceId === identifier ? older : newer,+ toolIdentifier: 'github',+ toolName: 'update_pull_request',+ topicId,+ version: 1,+ workId: row.id,+ })),+ );++ const model = new WorkModel(serverDB, userId);+ expect(+ (await model.listTopicPullRequests(topicId)).map((item) => item.identifier),+ ).not.toContain(identifier);+ expect(await model.listTopicsByPullRequest(identifier)).toEqual([]);++ await serverDB+ .update(topics)+ .set({ metadata: { pullRequests: { links: [link('manual')] } } })+ .where(eq(topics.id, topicId));+ expect((await model.listTopicsByPullRequest(identifier)).map((topic) => topic.topicId)).toEqual(+ [topicId],+ );+ });+});+describe('WorkModel.listTopicPullRequests', () => {it('lists every pull request linked to the topic once, latest link first', async () => {const model = new WorkModel(serverDB, userId);diff --git a/packages/database/src/models/work/index.ts b/packages/database/src/models/work/index.tsindex c223809f07d..787d33ac708 100644--- a/packages/database/src/models/work/index.ts+++ b/packages/database/src/models/work/index.ts@@ -46,7 +46,7 @@ import {type RegisterGoalReportWorkParams,} from './goalReport';import { normalizeLinearToolResult } from './linearToolResult';-import { listTopicPullRequests } from './pullRequests';+import { listTopicPullRequests, listTopicsByPullRequest } from './pullRequests';import * as queries from './queries';import { registerTaskWork } from './task';import type { ExternalToolWorkOperation } from './toolResultParsing';@@ -275,4 +275,6 @@ export class WorkModel {/** See {@link listTopicPullRequests}. */listTopicPullRequests = (topicId: string) => listTopicPullRequests(this.ctx, topicId);++ listTopicsByPullRequest = (identifier: string) => listTopicsByPullRequest(this.ctx, identifier);}diff --git a/packages/database/src/models/work/pullRequests.ts b/packages/database/src/models/work/pullRequests.tsindex 4881d9591e6..99afe2071b4 100644--- a/packages/database/src/models/work/pullRequests.ts+++ b/packages/database/src/models/work/pullRequests.ts@@ -3,14 +3,28 @@ import type {TopicPullRequestWork,WorkVersionMetadata,} from '@lobechat/types';-import { and, desc, eq, inArray, isNotNull, sql } from 'drizzle-orm';+import { and, desc, eq, inArray, isNotNull, lte, or, sql } from 'drizzle-orm';+import { topics } from '../../schemas/topic';import { works, workVersions } from '../../schemas/work';+import { notShareVisitorTopic } from '../../utils/shareVisitor';+import { buildWorkspaceWhere } from '../../utils/workspace';import { type WorkContext, workOwnership } from './context';/** A topic links a handful of pull requests; this only bounds a runaway topic. */const TOPIC_PULL_REQUEST_LIMIT = 50;+const pullRequestWorkScope = (ctx: WorkContext) =>+ and(+ workOwnership(ctx),+ eq(works.type, 'external'),+ eq(works.resourceType, 'github_pull_request'),+ isNotNull(works.resourceId),+ );++const linkedAt = sql<Date>`max(${workVersions.createdAt})`;+const workLinkOrder = [desc(linkedAt), desc(works.id)];+const parseIdentifier = (resourceId: string) => {const hash = resourceId.lastIndexOf('#');const number = Number(resourceId.slice(hash + 1));@@ -28,7 +42,6 @@ export const listTopicPullRequests = async (ctx: WorkContext,topicId: string,): Promise<TopicPullRequestWork[]> => {- const linkedAt = sql<Date>`max(${workVersions.createdAt})`;// How the topic came to it: an open command here (`gh pr create`) beats a// command naming it, which beats only ever having pushed to its branch.const created = sql<boolean>`bool_or(${workVersions.changeType} = 'created')`;@@ -46,17 +59,10 @@ export const listTopicPullRequests = async (workId: works.id,}).from(workVersions)- .innerJoin(works, and(eq(workVersions.workId, works.id), workOwnership(ctx)))- .where(- and(- eq(workVersions.topicId, topicId),- eq(works.type, 'external'),- eq(works.resourceType, 'github_pull_request'),- isNotNull(works.resourceId),- ),- )+ .innerJoin(works, eq(workVersions.workId, works.id))+ .where(and(eq(workVersions.topicId, topicId), pullRequestWorkScope(ctx))).groupBy(works.id)- .orderBy(desc(linkedAt), desc(works.id))+ .orderBy(...workLinkOrder).limit(TOPIC_PULL_REQUEST_LIMIT);const versionIds = rows.map((row) => row.currentVersionId).filter((id): id is string => !!id);@@ -98,3 +104,68 @@ export const listTopicPullRequests = async (];});};++/** Reverse the sidebar's persisted PR associations within the caller's scope. */+export const listTopicsByPullRequest = (ctx: WorkContext, identifier: string) => {+ const key = identifier.toLowerCase();+ const candidateTopics = ctx.db+ .select({ topicId: workVersions.topicId })+ .from(workVersions)+ .innerJoin(works, eq(workVersions.workId, works.id))+ .where(and(pullRequestWorkScope(ctx), eq(sql`lower(${works.resourceId})`, key)));++ // Rank only topics that touched this PR. The sidebar takes the latest 50+ // Work links per topic before adding metadata links and applying dismissals.+ const rankedLinks = ctx.db.$with('ranked_pr_links').as(+ ctx.db+ .select({+ rank: sql<number>`row_number() over (+ partition by ${workVersions.topicId} order by ${sql.join(workLinkOrder, sql`, `)}+ )`.as('link_rank'),+ resourceId: works.resourceId,+ topicId: workVersions.topicId,+ })+ .from(workVersions)+ .innerJoin(works, eq(workVersions.workId, works.id))+ .where(and(pullRequestWorkScope(ctx), inArray(workVersions.topicId, candidateTopics)))+ .groupBy(works.id, workVersions.topicId),+ );+ const workTopics = ctx.db+ .select({ topicId: rankedLinks.topicId })+ .from(rankedLinks)+ .where(+ and(+ eq(sql`lower(${rankedLinks.resourceId})`, key),+ lte(rankedLinks.rank, TOPIC_PULL_REQUEST_LIMIT),+ ),+ );++ const metadataLink = sql`exists (+ select 1 from jsonb_path_query(${topics.metadata}, '$.pullRequests.links[*]') as link(value)+ where lower(link.value ->> 'identifier') = ${key}+ )`;+ const dismissed = sql`exists (+ select 1 from jsonb_path_query(${topics.metadata}, '$.pullRequests.dismissed[*]') as item(value)+ where lower(item.value #>> '{}') = ${key}+ )`;++ return ctx.db+ .with(rankedLinks)+ .select({+ agentId: topics.agentId,+ groupId: topics.groupId,+ sessionId: topics.sessionId,+ title: topics.title,+ topicId: topics.id,+ })+ .from(topics)+ .where(+ and(+ buildWorkspaceWhere(ctx, topics),+ notShareVisitorTopic(),+ or(inArray(topics.id, workTopics), metadataLink),+ sql`not ${dismissed}`,+ ),+ )+ .orderBy(desc(topics.updatedAt), desc(topics.id));+};diff --git a/packages/utils/src/githubPullRequest.ts b/packages/utils/src/githubPullRequest.tsindex 00624e39280..53a7cb6e189 100644--- a/packages/utils/src/githubPullRequest.ts+++ b/packages/utils/src/githubPullRequest.ts@@ -7,6 +7,7 @@ export const parsePullRequestUrl = (url: string) => {const repoFullName = `${match[1]}/${match[2]}`;const number = Number(match[3]);+ if (!Number.isSafeInteger(number) || number < 1) return null;return {identifier: `${repoFullName}#${number}`,number,