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(topic): archive merged-PR topics from their Work rows (#23749)

Bryan412cf3d6ca97
diff --git a/apps/server/src/routers/lambda/work.ts b/apps/server/src/routers/lambda/work.ts
index a26b1708673..8520ba7d1d6 100644
--- a/apps/server/src/routers/lambda/work.ts
+++ b/apps/server/src/routers/lambda/work.ts
@@ -27,6 +27,7 @@ import {
linkPushedPullRequests,
linkTopicPullRequest,
listTopicPullRequestsWithStatus,
+ listTopicsPullRequestsWithStatus,
parsePullRequestUrl,
registerShellWorksForLocalRun,
resolveAgentWorkFile,
@@ -59,6 +60,9 @@ const workProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =>
});
});
+/** Topic ids per `listTopicsPullRequests` read; the client splits longer lists. */
+const TOPIC_PULL_REQUEST_BATCH = 100;
+
const lookupPullRequestInput = z.object({ url: z.string().trim().min(1).max(2048) });
// Task-domain write gate. Task mutations elsewhere (see the task router's
@@ -487,6 +491,23 @@ export const workRouter = router({
}),
),
+ // The same for many topics at once (a topic list's bulk actions), keyed by
+ // topic id; topics without a visible pull request are left out.
+ listTopicsPullRequests: workProcedure
+ .input(z.object({ topicIds: z.array(z.string().min(1)).min(1).max(TOPIC_PULL_REQUEST_BATCH) }))
+ .query(async ({ ctx, input }) =>
+ Object.fromEntries(
+ await listTopicsPullRequestsWithStatus({
+ db: ctx.serverDB,
+ topicIds: input.topicIds,
+ topicModel: ctx.topicModel,
+ userId: ctx.userId,
+ workModel: ctx.workModel,
+ workspaceId: ctx.workspaceId,
+ }),
+ ),
+ ),
+
lookupPullRequest: workProcedure.input(lookupPullRequestInput).query(async ({ ctx, input }) => {
const pr = parsePullRequestUrl(input.url);
if (!pr) {
diff --git a/apps/server/src/services/workRegistration/index.ts b/apps/server/src/services/workRegistration/index.ts
index cfe04a6d300..3f837776e95 100644
--- a/apps/server/src/services/workRegistration/index.ts
+++ b/apps/server/src/services/workRegistration/index.ts
@@ -50,4 +50,5 @@ export {
linkPushedPullRequests,
type LinkPushedPullRequestsResult,
listTopicPullRequestsWithStatus,
+ listTopicsPullRequestsWithStatus,
} from './topicPullRequests';
diff --git a/apps/server/src/services/workRegistration/topicPullRequests.test.ts b/apps/server/src/services/workRegistration/topicPullRequests.test.ts
index a7264ac93bb..a8fb6fefbba 100644
--- a/apps/server/src/services/workRegistration/topicPullRequests.test.ts
+++ b/apps/server/src/services/workRegistration/topicPullRequests.test.ts
@@ -1,6 +1,10 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { linkPushedPullRequests, listTopicPullRequestsWithStatus } from './topicPullRequests';
+import {
+ linkPushedPullRequests,
+ listTopicPullRequestsWithStatus,
+ listTopicsPullRequestsWithStatus,
+} from './topicPullRequests';
const { listByIdentities, listOpenByHeadRefs } = vi.hoisted(() => ({
listByIdentities: vi.fn(),
@@ -12,11 +16,21 @@ vi.mock('@/database/models/scm', () => ({
}));
const db = {} as any;
-const topicModelWith = (pullRequests?: unknown, visibleTopics: Record<string, unknown>[] = []) =>
- ({
- findById: vi.fn(async () => ({ metadata: pullRequests ? { pullRequests } : {} })),
+const topicModelWith = (pullRequests?: unknown, visibleTopics: Record<string, unknown>[] = []) => {
+ const topics = [{ id: 't1', metadata: pullRequests ? { pullRequests } : {} }, ...visibleTopics];
+ return {
findByIds: vi.fn(async (ids: string[]) =>
- visibleTopics.filter((topic) => ids.includes(topic.id as string)),
+ topics.filter((topic) => ids.includes(topic.id as string)),
+ ),
+ } as any;
+};
+
+/** A Work model whose `byTopic` map lists each topic's PR Work rows. */
+const workModelWith = (byTopic: Record<string, unknown[]>) =>
+ ({
+ listTopicsPullRequests: vi.fn(
+ async (ids: string[]) =>
+ new Map(ids.flatMap((id) => (byTopic[id] ? [[id, byTopic[id]] as const] : []))),
),
}) as any;
@@ -36,9 +50,7 @@ describe('listTopicPullRequestsWithStatus', () => {
beforeEach(() => vi.clearAllMocks());
it('attaches the GitHub App state where a row is visible, null elsewhere', async () => {
- const workModel = {
- listTopicPullRequests: vi.fn(async () => [workItem(1), workItem(2)]),
- } as any;
+ const workModel = workModelWith({ t1: [workItem(1), workItem(2)] });
const updatedAt = new Date('2026-11-17T01:00:00Z');
listByIdentities.mockResolvedValue([
{
@@ -93,9 +105,7 @@ describe('listTopicPullRequestsWithStatus', () => {
});
it('reports Auto-fix off and names the other conversation it wakes, when visible', async () => {
- const workModel = {
- listTopicPullRequests: vi.fn(async () => [workItem(1), workItem(2), workItem(3)]),
- } as any;
+ const workModel = workModelWith({ t1: [workItem(1), workItem(2), workItem(3)] });
const row = (number: number, extra: Record<string, unknown>) => ({
id: `scr-${number}`,
isDraft: false,
@@ -125,7 +135,7 @@ describe('listTopicPullRequestsWithStatus', () => {
workModel,
});
- expect(topicModel.findByIds).toHaveBeenCalledWith(['other', 'hidden']);
+ expect(topicModel.findByIds).toHaveBeenLastCalledWith(['other', 'hidden']);
expect(items.map((item) => item.scm?.autoFix)).toEqual([
{
changeRequestId: 'scr-1',
@@ -144,9 +154,7 @@ describe('listTopicPullRequestsWithStatus', () => {
it('adds the topic links, hides removed PRs, and keeps the latest link first', async () => {
listByIdentities.mockResolvedValue([]);
- const workModel = {
- listTopicPullRequests: vi.fn(async () => [workItem(1), workItem(2)]),
- } as any;
+ const workModel = workModelWith({ t1: [workItem(1), workItem(2)] });
const topicModel = topicModelWith({
dismissed: ['LobeHub/lobehub#2'],
links: [
@@ -185,7 +193,7 @@ describe('listTopicPullRequestsWithStatus', () => {
});
it('skips the scm lookup for a topic without pull requests', async () => {
- const workModel = { listTopicPullRequests: vi.fn(async () => []) } as any;
+ const workModel = workModelWith({});
expect(
await listTopicPullRequestsWithStatus({
@@ -200,6 +208,78 @@ describe('listTopicPullRequestsWithStatus', () => {
});
});
+describe('listTopicsPullRequestsWithStatus', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it('reads many topics with one scm lookup and leaves out topics the viewer cannot see', async () => {
+ listByIdentities.mockResolvedValue([
+ {
+ id: 'scr-1',
+ isDraft: false,
+ mergedAt: new Date('2026-11-18T00:00:00Z'),
+ metadata: {},
+ number: 1,
+ repoFullName: 'lobehub/lobehub',
+ state: 'merged',
+ topicId: 't2',
+ updatedAt: new Date(),
+ wakeCount: 0,
+ },
+ ]);
+ const topicModel = topicModelWith(undefined, [
+ { agentId: 'agt-1', id: 't2', metadata: {}, title: 'Second' },
+ ]);
+ const workModel = workModelWith({
+ hidden: [workItem(9)],
+ t1: [workItem(1)],
+ t2: [workItem(1), workItem(2)],
+ });
+
+ const byTopic = await listTopicsPullRequestsWithStatus({
+ db,
+ topicIds: ['t1', 't2', 'hidden', 't1'],
+ topicModel,
+ userId: 'u1',
+ workModel,
+ });
+
+ expect(workModel.listTopicsPullRequests).toHaveBeenCalledWith(['t1', 't2']);
+ expect([...byTopic.keys()]).toEqual(['t1', 't2']);
+ expect(listByIdentities).toHaveBeenCalledTimes(1);
+ expect(listByIdentities.mock.calls[0][2]).toEqual([
+ { number: 1, repoFullName: 'lobehub/lobehub' },
+ { number: 2, repoFullName: 'lobehub/lobehub' },
+ ]);
+ // The owner conversation is in the batch already: named without another read.
+ expect(topicModel.findByIds).toHaveBeenCalledTimes(1);
+ expect(byTopic.get('t1')?.[0].scm).toMatchObject({
+ autoFix: { ownerTopic: { agentId: 'agt-1', id: 't2', title: 'Second' } },
+ state: 'merged',
+ });
+ expect(byTopic.get('t2')?.map((item) => item.scm?.autoFix.ownerTopic ?? null)).toEqual([
+ null,
+ null,
+ ]);
+ expect(byTopic.get('t2')?.[1].scm).toBeNull();
+ });
+
+ it('reads nothing for an empty list', async () => {
+ const topicModel = topicModelWith();
+ expect(
+ (
+ await listTopicsPullRequestsWithStatus({
+ db,
+ topicIds: [],
+ topicModel,
+ userId: 'u1',
+ workModel: workModelWith({}),
+ })
+ ).size,
+ ).toBe(0);
+ expect(topicModel.findByIds).not.toHaveBeenCalled();
+ });
+});
+
describe('linkPushedPullRequests', () => {
const pushRow = {
apiName: 'Bash',
diff --git a/apps/server/src/services/workRegistration/topicPullRequests.ts b/apps/server/src/services/workRegistration/topicPullRequests.ts
index 501010ef546..8f7b2d39ddc 100644
--- a/apps/server/src/services/workRegistration/topicPullRequests.ts
+++ b/apps/server/src/services/workRegistration/topicPullRequests.ts
@@ -80,8 +80,16 @@ const toLinkItem = (link: TopicPullRequestLinkMeta): TopicPullRequestWork | null
};
};
+type TopicPullRequestsParams = {
+ db: LobeChatDatabase;
+ topicModel: TopicModel;
+ userId: string;
+ workModel: WorkModel;
+ workspaceId?: string | null;
+};
+
/**
- * Pull requests linked to a topic — its `github_pull_request` Work rows plus
+ * Pull requests linked to each topic — its `github_pull_request` Work rows plus
* the links kept on the topic (branch match, by hand), minus the ones removed
* from it — latest link first, each with the GitHub App's state when an
* installation the scope can see tracks the repository. `scm: null` means "not
@@ -89,64 +97,102 @@ const toLinkItem = (link: TopicPullRequestLinkMeta): TopicPullRequestWork | null
* confirmed, vouched data may enable merge / close. A tracked PR also carries
* its Auto-fix state and the conversation that Auto-fix wakes — named when it
* is another conversation the viewer can open.
+ *
+ * Only topics the viewer can see are read; the others, and topics without a
+ * pull request, are absent from the map. One read for every topic, so a bulk
+ * action over a topic list costs the same few queries as one topic.
*/
-export const listTopicPullRequestsWithStatus = async (params: {
- db: LobeChatDatabase;
- topicId: string;
- topicModel: TopicModel;
- userId: string;
- workModel: WorkModel;
- workspaceId?: string | null;
-}): Promise<TopicPullRequestItem[]> => {
- const [works, topic] = await Promise.all([
- params.workModel.listTopicPullRequests(params.topicId),
- params.topicModel.findById(params.topicId),
- ]);
- const meta = topic?.metadata?.pullRequests;
- const dismissed = new Set((meta?.dismissed ?? []).map((id) => id.toLowerCase()));
- const fromWorks = new Set(works.map((item) => item.identifier.toLowerCase()));
+export const listTopicsPullRequestsWithStatus = async (
+ params: TopicPullRequestsParams & { topicIds: string[] },
+): Promise<Map<string, TopicPullRequestItem[]>> => {
+ const result = new Map<string, TopicPullRequestItem[]>();
+ const topicIds = [...new Set(params.topicIds)];
+ if (topicIds.length === 0) return result;
+
+ const visibleTopics = await params.topicModel.findByIds(topicIds);
+ const visibleIds = visibleTopics.map((topic) => topic.id);
+ if (visibleIds.length === 0) return result;
+ const worksByTopic = await params.workModel.listTopicsPullRequests(visibleIds);
- const items = [
- // Work rows were parsed by the server from the run's own tool messages.
- ...works.map((item) => ({ item, vouched: true })),
- ...(meta?.links ?? []).flatMap((link) => {
- const item = toLinkItem(link);
- return item && !fromWorks.has(item.identifier.toLowerCase())
- ? [{ item, vouched: link.vouched }]
- : [];
- }),
- ]
- .filter(({ item }) => !dismissed.has(item.identifier.toLowerCase()))
- .sort((a, b) => b.item.linkedAt.getTime() - a.item.linkedAt.getTime());
- if (items.length === 0) return [];
+ const itemsByTopic = new Map<string, { item: TopicPullRequestWork; vouched: boolean }[]>();
+ for (const topic of visibleTopics) {
+ const works = worksByTopic.get(topic.id) ?? [];
+ const meta = topic.metadata?.pullRequests;
+ const dismissed = new Set((meta?.dismissed ?? []).map((id) => id.toLowerCase()));
+ const fromWorks = new Set(works.map((item) => item.identifier.toLowerCase()));
+ const items = [
+ // Work rows were parsed by the server from the run's own tool messages.
+ ...works.map((item) => ({ item, vouched: true })),
+ ...(meta?.links ?? []).flatMap((link) => {
+ const item = toLinkItem(link);
+ return item && !fromWorks.has(item.identifier.toLowerCase())
+ ? [{ item, vouched: link.vouched }]
+ : [];
+ }),
+ ]
+ .filter(({ item }) => !dismissed.has(item.identifier.toLowerCase()))
+ .sort((a, b) => b.item.linkedAt.getTime() - a.item.linkedAt.getTime());
+ if (items.length > 0) itemsByTopic.set(topic.id, items);
+ }
+ if (itemsByTopic.size === 0) return result;
+
+ const identities = new Map<string, { number: number; repoFullName: string }>();
+ for (const items of itemsByTopic.values()) {
+ for (const { item } of items) {
+ identities.set(identityKey(item.repoFullName, item.number), {
+ number: item.number,
+ repoFullName: item.repoFullName,
+ });
+ }
+ }
const rows = await ScmChangeRequestModel.listByIdentities(
params.db,
{ userId: params.userId, workspaceId: params.workspaceId ?? null },
- items.map(({ item }) => ({ number: item.number, repoFullName: item.repoFullName })),
+ [...identities.values()],
);
const byIdentity = new Map(rows.map((row) => [identityKey(row.repoFullName, row.number), row]));
// Scoped to the viewer: a conversation they cannot open stays unnamed.
- const otherTopicIds = [
- ...new Set(
- rows.flatMap((row) => (row.topicId && row.topicId !== params.topicId ? [row.topicId] : [])),
- ),
- ];
- const otherTopics = new Map(
- (await params.topicModel.findByIds(otherTopicIds)).map((topic) => [
+ const ownerTopicIds = [...new Set(rows.flatMap((row) => (row.topicId ? [row.topicId] : [])))];
+ const known = new Map(visibleTopics.map((topic) => [topic.id, topic]));
+ const unknownOwnerIds = ownerTopicIds.filter((id) => !known.has(id));
+ const ownerTopics = new Map(
+ [
+ ...ownerTopicIds.flatMap((id) => {
+ const topic = known.get(id);
+ return topic ? [topic] : [];
+ }),
+ ...(unknownOwnerIds.length > 0 ? await params.topicModel.findByIds(unknownOwnerIds) : []),
+ ].map((topic) => [
topic.id,
{ agentId: topic.agentId ?? null, id: topic.id, title: topic.title ?? null },
]),
);
- return items.map(({ item, vouched }) => {
- const row = byIdentity.get(identityKey(item.repoFullName, item.number));
- const ownerTopic = row?.topicId ? (otherTopics.get(row.topicId) ?? null) : null;
- return { ...item, scm: row ? toScmState(row, ownerTopic) : null, vouched };
- });
+ for (const [topicId, items] of itemsByTopic) {
+ result.set(
+ topicId,
+ items.map(({ item, vouched }) => {
+ const row = byIdentity.get(identityKey(item.repoFullName, item.number));
+ // The conversation the viewer is in needs no name.
+ const ownerTopic =
+ row?.topicId && row.topicId !== topicId ? (ownerTopics.get(row.topicId) ?? null) : null;
+ return { ...item, scm: row ? toScmState(row, ownerTopic) : null, vouched };
+ }),
+ );
+ }
+ return result;
};
+/** {@link listTopicsPullRequestsWithStatus} for one topic. */
+export const listTopicPullRequestsWithStatus = async (
+ params: TopicPullRequestsParams & { topicId: string },
+): Promise<TopicPullRequestItem[]> =>
+ (await listTopicsPullRequestsWithStatus({ ...params, topicIds: [params.topicId] })).get(
+ params.topicId,
+ ) ?? [];
+
/** One pull request the execution device found for a pushed branch (`gh pr list --head`). */
export interface DeviceReportedPullRequest {
headRefName: string;
diff --git a/locales/en-US/topic.json b/locales/en-US/topic.json
index 08915e11387..81d2bcb43bf 100644
--- a/locales/en-US/topic.json
+++ b/locales/en-US/topic.json
@@ -2,6 +2,7 @@
"actions.addNewTopic": "Start New Topic",
"actions.addNewTopicInProject": "Start new topic in {{directory}}",
"actions.archiveMergedPullRequests": "Archive Topics with Merged PRs",
+ "actions.archiveMergedPullRequestsFailed": "Couldn't check which topics have merged PRs. Check your network and try again.",
"actions.archiveMergedPullRequestsNone": "No topics with merged PRs found.",
"actions.archiveMergedPullRequestsOwn": "Archive My Topics with Merged PRs",
"actions.archiveMergedPullRequestsSuccess_one": "Archived {{count}} topic with a merged PR.",
diff --git a/locales/zh-CN/topic.json b/locales/zh-CN/topic.json
index 5ce5c301e7c..8f976973438 100644
--- a/locales/zh-CN/topic.json
+++ b/locales/zh-CN/topic.json
@@ -2,6 +2,7 @@
"actions.addNewTopic": "开启新话题",
"actions.addNewTopicInProject": "在 {{directory}} 中开启新话题",
"actions.archiveMergedPullRequests": "归档 PR 已合并的话题",
+ "actions.archiveMergedPullRequestsFailed": "无法检查哪些话题的 PR 已合并,请检查网络后重试",
"actions.archiveMergedPullRequestsNone": "没有找到 PR 已合并的话题",
"actions.archiveMergedPullRequestsOwn": "归档我创建且 PR 已合并的话题",
"actions.archiveMergedPullRequestsSuccess_one": "已归档 {{count}} 个 PR 已合并的话题",
diff --git a/packages/database/src/models/work/__tests__/pullRequests.test.ts b/packages/database/src/models/work/__tests__/pullRequests.test.ts
index 1f95e7c53c3..8232413b41d 100644
--- a/packages/database/src/models/work/__tests__/pullRequests.test.ts
+++ b/packages/database/src/models/work/__tests__/pullRequests.test.ts
@@ -284,6 +284,41 @@ describe('WorkModel.listTopicPullRequests', () => {
});
});
+describe('WorkModel.listTopicsPullRequests', () => {
+ it('lists each topic its own pull requests in one read, latest link first', async () => {
+ const secondTopicId = 'work-test-second-topic';
+ const emptyTopicId = 'work-test-empty-topic';
+ await serverDB.insert(topics).values([
+ { id: secondTopicId, userId },
+ { id: emptyTopicId, userId },
+ ]);
+ const model = new WorkModel(serverDB, userId);
+ await model.registerExternal(pr('lobehub/lobehub#30', 'call-30'));
+ await model.registerExternal(pr('lobehub/lobehub#31', 'call-31'));
+ // The same PR touched by both topics is listed for each.
+ await model.registerExternal(
+ pr('lobehub/lobehub#30', 'call-30-second', {
+ changeType: 'updated',
+ patchFields: ['identifier', 'status'],
+ status: 'merged',
+ topicId: secondTopicId,
+ }),
+ );
+ await new WorkModel(serverDB, userId2).registerExternal(
+ pr('lobehub/lobehub#32', 'call-user2', { topicId: secondTopicId }),
+ );
+
+ const byTopic = await model.listTopicsPullRequests([topicId, secondTopicId, emptyTopicId]);
+
+ expect(byTopic.get(topicId)?.map((item) => item.number)).toEqual([31, 30]);
+ expect(byTopic.get(secondTopicId)).toEqual([
+ expect.objectContaining({ number: 30, source: 'command', status: 'merged' }),
+ ]);
+ expect(byTopic.has(emptyTopicId)).toBe(false);
+ expect((await model.listTopicsPullRequests([])).size).toBe(0);
+ });
+});
+
describe('WorkModel.listTopicPullRequests with a work that lost its resource id', () => {
it('skips a row whose pull-request identifier is gone', async () => {
await serverDB.insert(works).values({
diff --git a/packages/database/src/models/work/index.ts b/packages/database/src/models/work/index.ts
index 8e933c9ec59..ee0ef2ee63c 100644
--- a/packages/database/src/models/work/index.ts
+++ b/packages/database/src/models/work/index.ts
@@ -67,7 +67,11 @@ import {
type RegisterGoalReportWorkParams,
} from './goalReport';
import { normalizeLinearToolResult } from './linearToolResult';
-import { listTopicPullRequests, listTopicsByPullRequest } from './pullRequests';
+import {
+ listTopicPullRequests,
+ listTopicsByPullRequest,
+ listTopicsPullRequests,
+} from './pullRequests';
import * as queries from './queries';
import { registerTaskWork } from './task';
import type { ExternalToolWorkOperation } from './toolResultParsing';
@@ -358,4 +362,7 @@ export class WorkModel {
listTopicPullRequests = (topicId: string) => listTopicPullRequests(this.ctx, topicId);
listTopicsByPullRequest = (identifier: string) => listTopicsByPullRequest(this.ctx, identifier);
+
+ /** See {@link listTopicsPullRequests}. */
+ listTopicsPullRequests = (topicIds: string[]) => listTopicsPullRequests(this.ctx, topicIds);
}
diff --git a/packages/database/src/models/work/pullRequests.ts b/packages/database/src/models/work/pullRequests.ts
index 99afe2071b4..f586dec0d24 100644
--- a/packages/database/src/models/work/pullRequests.ts
+++ b/packages/database/src/models/work/pullRequests.ts
@@ -33,39 +33,55 @@ const parseIdentifier = (resourceId: string) => {
};
/**
- * GitHub pull requests linked to a topic, most recently linked first. A pull
- * request is linked by ANY version of its Work registered in the topic (any
- * thread), so it shows once however many commands touched it, and a Work
- * first registered elsewhere still appears once the topic touches it.
+ * GitHub pull requests linked to each of the given topics, most recently
+ * linked first. A pull request is linked by ANY version of its Work registered
+ * in the topic (any thread), so it shows once per topic however many commands
+ * touched it, and a Work first registered elsewhere still appears once the
+ * topic touches it. Topics without one are absent from the map.
*/
-export const listTopicPullRequests = async (
+export const listTopicsPullRequests = async (
ctx: WorkContext,
- topicId: string,
-): Promise<TopicPullRequestWork[]> => {
+ topicIds: string[],
+): Promise<Map<string, TopicPullRequestWork[]>> => {
+ const result = new Map<string, TopicPullRequestWork[]>();
+ if (topicIds.length === 0) return result;
+
// 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')`;
const pushOnly = sql<boolean>`bool_and(coalesce(${workVersions.metadata} ->> 'pullRequestLink', '') = 'push')`;
+ const links = ctx.db.$with('topic_pr_links').as(
+ ctx.db
+ .select({
+ created: created.as('created'),
+ currentVersionId: works.currentVersionId,
+ linkedAt: linkedAt.as('linked_at'),
+ pushOnly: pushOnly.as('push_only'),
+ rank: sql<number>`row_number() over (
+ partition by ${workVersions.topicId} order by ${sql.join(workLinkOrder, sql`, `)}
+ )`.as('link_rank'),
+ resourceId: works.resourceId,
+ status: works.status,
+ title: works.title,
+ topicId: workVersions.topicId,
+ url: works.url,
+ workId: works.id,
+ })
+ .from(workVersions)
+ .innerJoin(works, eq(workVersions.workId, works.id))
+ .where(and(inArray(workVersions.topicId, topicIds), pullRequestWorkScope(ctx)))
+ .groupBy(works.id, workVersions.topicId),
+ );
const rows = await ctx.db
- .select({
- created,
- currentVersionId: works.currentVersionId,
- linkedAt,
- pushOnly,
- resourceId: works.resourceId,
- status: works.status,
- title: works.title,
- url: works.url,
- workId: works.id,
- })
- .from(workVersions)
- .innerJoin(works, eq(workVersions.workId, works.id))
- .where(and(eq(workVersions.topicId, topicId), pullRequestWorkScope(ctx)))
- .groupBy(works.id)
- .orderBy(...workLinkOrder)
- .limit(TOPIC_PULL_REQUEST_LIMIT);
+ .with(links)
+ .select()
+ .from(links)
+ .where(lte(links.rank, TOPIC_PULL_REQUEST_LIMIT))
+ .orderBy(links.topicId, links.rank);
- const versionIds = rows.map((row) => row.currentVersionId).filter((id): id is string => !!id);
+ const versionIds = [
+ ...new Set(rows.map((row) => row.currentVersionId).filter((id): id is string => !!id)),
+ ];
// The current version carries the merged branch metadata (an edit that names
// no branch keeps the one captured at create).
const branches = new Map<string, WorkVersionMetadata | null>();
@@ -77,34 +93,42 @@ export const listTopicPullRequests = async (
for (const version of versions) branches.set(version.id, version.metadata);
}
- return rows.flatMap((row) => {
+ for (const row of rows) {
const identity = row.resourceId ? parseIdentifier(row.resourceId) : null;
- if (!identity) return [];
+ if (!identity || !row.topicId) continue;
const metadata = row.currentVersionId ? branches.get(row.currentVersionId) : undefined;
- return [
- {
- ...(metadata?.baseBranch ? { baseBranch: metadata.baseBranch } : {}),
- ...(metadata?.headBranch ? { headBranch: metadata.headBranch } : {}),
- identifier: row.resourceId!,
- // `max()` comes back as text through some drivers.
- linkedAt: new Date(row.linkedAt),
- number: identity.number,
- repoFullName: identity.repoFullName,
- source: (row.created
- ? 'created'
- : row.pushOnly
- ? 'push'
- : 'command') satisfies TopicPullRequestLinkSource,
- status: row.status,
- title: row.title,
- url: row.url,
- workId: row.workId,
- },
- ];
- });
+ const list = result.get(row.topicId) ?? [];
+ list.push({
+ ...(metadata?.baseBranch ? { baseBranch: metadata.baseBranch } : {}),
+ ...(metadata?.headBranch ? { headBranch: metadata.headBranch } : {}),
+ identifier: row.resourceId!,
+ // `max()` comes back as text through some drivers.
+ linkedAt: new Date(row.linkedAt),
+ number: identity.number,
+ repoFullName: identity.repoFullName,
+ source: (row.created
+ ? 'created'
+ : row.pushOnly
+ ? 'push'
+ : 'command') satisfies TopicPullRequestLinkSource,
+ status: row.status,
+ title: row.title,
+ url: row.url,
+ workId: row.workId,
+ });
+ result.set(row.topicId, list);
+ }
+ return result;
};
+/** {@link listTopicsPullRequests} for one topic. */
+export const listTopicPullRequests = async (
+ ctx: WorkContext,
+ topicId: string,
+): Promise<TopicPullRequestWork[]> =>
+ (await listTopicsPullRequests(ctx, [topicId])).get(topicId) ?? [];
+
/** Reverse the sidebar's persisted PR associations within the caller's scope. */
export const listTopicsByPullRequest = (ctx: WorkContext, identifier: string) => {
const key = identifier.toLowerCase();
diff --git a/packages/locales/src/default/topic.ts b/packages/locales/src/default/topic.ts
index 3216cb50955..182ccf2a4a7 100644
--- a/packages/locales/src/default/topic.ts
+++ b/packages/locales/src/default/topic.ts
@@ -17,6 +17,8 @@ export default {
'actions.archiveMergedPullRequestsOwn': 'Archive My Topics with Merged PRs',
'actions.archiveMergedPullRequestsWorkspace': 'Archive All Topics with Merged PRs',
'actions.archiveMergedPullRequestsNone': 'No topics with merged PRs found.',
+ 'actions.archiveMergedPullRequestsFailed':
+ "Couldn't check which topics have merged PRs. Check your network and try again.",
'actions.archiveMergedPullRequestsSuccess_one': 'Archived {{count}} topic with a merged PR.',
'actions.archiveMergedPullRequestsSuccess_other': 'Archived {{count}} topics with merged PRs.',
'actions.confirmArchiveMergedPullRequestsWorkspace':
diff --git a/packages/trpc/src/client/lambda.test.ts b/packages/trpc/src/client/lambda.test.ts
index 00454c7d27c..e2a56e029bc 100644
--- a/packages/trpc/src/client/lambda.test.ts
+++ b/packages/trpc/src/client/lambda.test.ts
@@ -75,6 +75,15 @@ describe('lambdaClient large-input query transport', () => {
'documentIds',
100,
],
+ [
+ 'work.listTopicsPullRequests',
+ () =>
+ lambdaClient.work.listTopicsPullRequests.query({
+ topicIds: Array.from({ length: 100 }, (_, i) => `tpc_${String(i).padStart(16, '0')}`),
+ }),
+ 'topicIds',
+ 100,
+ ],
] as const)(
'sends %s with a large path/id array as a POST request',
async (path, call, arrayField, expectedLength) => {
diff --git a/packages/trpc/src/client/lambda.ts b/packages/trpc/src/client/lambda.ts
index 5373d1bdcac..e0a6f8dcffb 100644
--- a/packages/trpc/src/client/lambda.ts
+++ b/packages/trpc/src/client/lambda.ts
@@ -288,6 +288,9 @@ const LARGE_INPUT_QUERY_PROCEDURES = new Set([
// dozens of ids, and a dropped lookup would let deleted documents back into
// the model context.
'agentDocument.listRevokedDocumentReads',
+ // "Archive merged PR topics" asks for the linked PRs of every listed topic,
+ // 100 ids per read — about 3,000 characters as a GET.
+ 'work.listTopicsPullRequests',
]);
/**
diff --git a/packages/types/src/workingDir.ts b/packages/types/src/workingDir.ts
index f1bbf931939..1a89efd4896 100644
--- a/packages/types/src/workingDir.ts
+++ b/packages/types/src/workingDir.ts
@@ -89,7 +89,15 @@ export interface WorkingDirGitState {
branch?: string;
/** True when the effective working directory is currently detached. */
detached?: boolean;
- /** GitHub-specific branch metadata such as linked PR and check status. */
+ /**
+ * GitHub-specific branch metadata such as linked PR and check status.
+ *
+ * @deprecated Nothing in this app reads it: a topic's PRs come from its Work
+ * rows (`work.listTopicPullRequests`). Kept in the schema because released
+ * desktop clients still write and read this snapshot — dropping it from
+ * `workingDirConfigSchema` would strip it from their writes. Branch changes
+ * still clear it so those clients never show another branch's PR.
+ */
github?: WorkingDirGithubState;
/**
* True when the effective working directory is a linked worktree rather than
@@ -217,6 +225,7 @@ export const workingDirConfigSchema = z.object({
autoCreatedAt: z.string().optional(),
branch: z.string().optional(),
detached: z.boolean().optional(),
+ // Deprecated: see `WorkingDirGitState.github`.
github: z
.object({
extraPullRequestCount: z.number().optional(),
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx
index f21693f7dd3..ae636d8e268 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx
@@ -185,6 +185,23 @@ vi.mock('@/store/chat', () => {
return { useChatStore };
});
+const pullRequestsByTopicMock = vi.hoisted(() => ({ value: {} as Record<string, unknown[]> }));
+const listTopicsPullRequestsMock = vi.hoisted(() =>
+ vi.fn(async (ids: string[]) =>
+ Object.fromEntries(
+ ids.flatMap((id) =>
+ pullRequestsByTopicMock.value[id] ? [[id, pullRequestsByTopicMock.value[id]]] : [],
+ ),
+ ),
+ ),
+);
+vi.mock('@/services/work', () => ({
+ workService: { listTopicsPullRequests: listTopicsPullRequestsMock },
+}));
+vi.mock('@/store/device/gitReview/store', () => ({
+ useGitReviewStore: { getState: () => ({ gitPullRequestDetailMap: {} }) },
+}));
+
vi.mock('@/store/chat/selectors', () => ({
operationSelectors: {
unreadCompletedCountForTopics: () => () => 0,
@@ -417,24 +434,43 @@ describe('Project topic group item', () => {
});
it('archives only this group\'s merged-PR topics from the group "more" menu', async () => {
- const merged = { github: { pullRequest: { mergedAt: '2026-10-01', state: 'closed' } } };
+ const pullRequest = (number: number, status: string) => ({
+ identifier: `lobehub/lobehub#${number}`,
+ linkedAt: new Date('2026-11-20T00:00:00Z'),
+ number,
+ repoFullName: 'lobehub/lobehub',
+ scm: null,
+ source: 'created',
+ status,
+ title: null,
+ url: null,
+ vouched: true,
+ workId: `work-${number}`,
+ });
+ // The PRs come from the topics' Work rows, not a branch snapshot.
+ pullRequestsByTopicMock.value = {
+ 't-done': [pullRequest(2, 'merged')],
+ 't-merged': [pullRequest(1, 'merged')],
+ 't-still-open': [pullRequest(4, 'open'), pullRequest(3, 'merged')],
+ };
render(
<AccordionRoot>
<GroupItem
expanded
group={{
children: [
- {
- id: 't-merged',
- metadata: { workingDirectory: '/tmp/x', workingDirectoryConfig: { git: merged } },
- title: 'Merged',
- },
+ { id: 't-merged', metadata: { workingDirectory: '/tmp/x' }, title: 'Merged' },
{
id: 't-done',
- metadata: { workingDirectory: '/tmp/x', workingDirectoryConfig: { git: merged } },
+ metadata: { workingDirectory: '/tmp/x' },
status: 'completed',
title: 'Already done',
},
+ {
+ id: 't-still-open',
+ metadata: { workingDirectory: '/tmp/x' },
+ title: 'One PR still open',
+ },
{ id: 't-open', metadata: { workingDirectory: '/tmp/x' }, title: 'Open' },
] as any,
id: 'project:/tmp/x',
@@ -448,6 +484,8 @@ describe('Project topic group item', () => {
fireEvent.click(await screen.findByText('actions.archiveMergedPullRequests'));
await waitFor(() => expect(refreshTopicMock).toHaveBeenCalled());
+ // Completed topics are not even asked about.
+ expect(listTopicsPullRequestsMock).toHaveBeenCalledWith(['t-merged', 't-still-open', 't-open']);
expect(updateTopicStatusMock).toHaveBeenCalledTimes(1);
expect(updateTopicStatusMock).toHaveBeenCalledWith({
status: 'completed',
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx
index 305e3c030a9..bde6254c89b 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx
@@ -15,7 +15,6 @@ import {
Icon,
Tag,
Text,
- toast,
} from '@lobehub/ui';
import isEqual from 'fast-deep-equal';
import {
@@ -60,8 +59,8 @@ import { userProfileSelectors } from '@/store/user/selectors';
import { getTopicWorkingDirectorySourcePath } from '@/utils/client/topic';
import { buildPrefixedAgentRoutePath, parseAgentPathname } from '../../../utils/agentPathname';
+import { archiveMergedPullRequestTopics } from '../../archiveMergedPullRequestTopics';
import { useTopicListScope } from '../../TopicListScope';
-import { getMergedPullRequestTopics } from '../../utils/mergedPullRequestTopics';
import { type GroupItemComponentProps } from '../GroupedAccordion';
import { useStartTopicInDirectory } from '../useStartTopicInDirectory';
import { indicatorStyles, useCollapsedIndicators } from './CollapsedIndicators';
@@ -258,22 +257,12 @@ const GroupItem = memo<GroupItemComponentProps>(({ group, expanded }) => {
? 'actions.archiveMergedPullRequestsOwn'
: 'actions.archiveMergedPullRequests',
),
- onClick: async () => {
- const merged = getMergedPullRequestTopics(
- children,
- activeWorkspaceId ? (currentUserId ?? null) : undefined,
- );
- if (merged.length === 0) {
- toast.info(t('actions.archiveMergedPullRequestsNone'));
- return;
- }
- const { refreshTopic, updateTopicStatus } = useChatStore.getState();
- await Promise.all(
- merged.map(({ id }) => updateTopicStatus({ status: 'completed', topicId: id })),
- );
- await refreshTopic();
- toast.success(t('actions.archiveMergedPullRequestsSuccess', { count: merged.length }));
- },
+ onClick: () =>
+ archiveMergedPullRequestTopics({
+ ownerId: activeWorkspaceId ? (currentUserId ?? null) : undefined,
+ t,
+ topics: children,
+ }),
},
],
[activeWorkspaceId, canEditTopic, children, currentUserId, t],
diff --git a/src/features/AgentSidebar/Topic/archiveMergedPullRequestTopics.test.ts b/src/features/AgentSidebar/Topic/archiveMergedPullRequestTopics.test.ts
new file mode 100644
index 00000000000..6a32d3770fa
--- /dev/null
+++ b/src/features/AgentSidebar/Topic/archiveMergedPullRequestTopics.test.ts
@@ -0,0 +1,153 @@
+import { toast } from '@lobehub/ui';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { workService } from '@/services/work';
+import { type ChatTopic } from '@/types/topic';
+
+import {
+ archiveMergedPullRequestTopics,
+ findMergedPullRequestTopics,
+} from './archiveMergedPullRequestTopics';
+
+const { chatState, gitReviewState } = vi.hoisted(() => ({
+ chatState: { refreshTopic: vi.fn(), updateTopicStatus: vi.fn() },
+ gitReviewState: { gitPullRequestDetailMap: {} as Record<string, unknown> },
+}));
+
+vi.mock('@/services/work', () => ({ workService: { listTopicsPullRequests: vi.fn() } }));
+vi.mock('@/store/chat', () => ({ useChatStore: { getState: () => chatState } }));
+vi.mock('@/store/device/gitReview/store', () => ({
+ useGitReviewStore: { getState: () => gitReviewState },
+}));
+
+const topic = (id: string) => ({ createdAt: 0, id, title: id, updatedAt: 0 }) as ChatTopic;
+
+const mergedPr = (number: number) => ({
+ identifier: `lobehub/lobehub#${number}`,
+ linkedAt: new Date('2026-11-20T00:00:00Z'),
+ number,
+ repoFullName: 'lobehub/lobehub',
+ scm: null,
+ source: 'created' as const,
+ status: 'merged',
+ title: null,
+ url: null,
+ vouched: true,
+ workId: `work-${number}`,
+});
+
+const t = ((key: string) => key) as any;
+
+describe('findMergedPullRequestTopics', () => {
+ afterEach(() => vi.mocked(workService.listTopicsPullRequests).mockReset());
+
+ it('asks the server in batches of 100 topics', async () => {
+ const topics = Array.from({ length: 205 }, (_, i) => topic(`t${i}`));
+ const list = vi
+ .spyOn(workService, 'listTopicsPullRequests')
+ .mockImplementation(async (ids) => (ids.includes('t150') ? { t150: [mergedPr(1)] } : {}));
+
+ const merged = await findMergedPullRequestTopics(topics);
+
+ expect(list.mock.calls.map(([ids]) => ids.length)).toEqual([100, 100, 5]);
+ expect(merged.map((item) => item.id)).toEqual(['t150']);
+ });
+
+ it('asks nothing when no topic is left to archive', async () => {
+ const list = vi.spyOn(workService, 'listTopicsPullRequests');
+
+ expect(await findMergedPullRequestTopics([topic('a')], null)).toEqual([]);
+ expect(list).not.toHaveBeenCalled();
+ });
+
+ it('uses the device reads this client holds', async () => {
+ vi.spyOn(workService, 'listTopicsPullRequests').mockResolvedValue({
+ t: [{ ...mergedPr(9), status: 'open' }],
+ });
+ gitReviewState.gitPullRequestDetailMap = {
+ 'device:/repo:9': {
+ value: {
+ detail: {
+ number: 9,
+ repo: { name: 'lobehub', owner: 'lobehub' },
+ state: 'merged',
+ title: 'Merged on GitHub',
+ url: 'https://github.com/lobehub/lobehub/pull/9',
+ } as any,
+ status: 'ok',
+ } as any,
+ },
+ };
+
+ expect((await findMergedPullRequestTopics([topic('t')])).map((item) => item.id)).toEqual(['t']);
+ gitReviewState.gitPullRequestDetailMap = {};
+ });
+ it('keeps a merge the server knows of when this client holds an older open read', async () => {
+ vi.mocked(workService.listTopicsPullRequests).mockResolvedValue({ t: [mergedPr(10)] });
+ gitReviewState.gitPullRequestDetailMap = {
+ 'device:/repo:10': {
+ value: {
+ detail: {
+ number: 10,
+ repo: { name: 'lobehub', owner: 'lobehub' },
+ state: 'open',
+ title: 'Read before the merge',
+ url: 'https://github.com/lobehub/lobehub/pull/10',
+ } as any,
+ status: 'ok',
+ } as any,
+ },
+ };
+
+ expect((await findMergedPullRequestTopics([topic('t')])).map((item) => item.id)).toEqual(['t']);
+ gitReviewState.gitPullRequestDetailMap = {};
+ });
+});
+
+describe('archiveMergedPullRequestTopics', () => {
+ const { refreshTopic, updateTopicStatus } = chatState;
+
+ beforeEach(() => {
+ vi.spyOn(toast, 'error').mockImplementation(() => undefined as any);
+ vi.spyOn(toast, 'info').mockImplementation(() => undefined as any);
+ vi.spyOn(toast, 'success').mockImplementation(() => undefined as any);
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ });
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.mocked(workService.listTopicsPullRequests).mockReset();
+ updateTopicStatus.mockReset();
+ refreshTopic.mockReset();
+ });
+
+ it('completes the merged topics and reports how many', async () => {
+ vi.spyOn(workService, 'listTopicsPullRequests').mockResolvedValue({ a: [mergedPr(1)] });
+
+ await archiveMergedPullRequestTopics({ t, topics: [topic('a'), topic('b')] });
+
+ expect(updateTopicStatus).toHaveBeenCalledExactlyOnceWith({
+ status: 'completed',
+ topicId: 'a',
+ });
+ expect(refreshTopic).toHaveBeenCalledOnce();
+ expect(toast.success).toHaveBeenCalledWith('actions.archiveMergedPullRequestsSuccess');
+ });
+
+ it('says so when no topic has a merged PR', async () => {
+ vi.spyOn(workService, 'listTopicsPullRequests').mockResolvedValue({});
+
+ await archiveMergedPullRequestTopics({ t, topics: [topic('a')] });
+
+ expect(updateTopicStatus).not.toHaveBeenCalled();
+ expect(toast.info).toHaveBeenCalledWith('actions.archiveMergedPullRequestsNone');
+ });
+
+ it('archives nothing and reports the failure when the server read fails', async () => {
+ vi.spyOn(workService, 'listTopicsPullRequests').mockRejectedValue(new Error('offline'));
+
+ await archiveMergedPullRequestTopics({ t, topics: [topic('a')] });
+
+ expect(updateTopicStatus).not.toHaveBeenCalled();
+ expect(toast.error).toHaveBeenCalledWith('actions.archiveMergedPullRequestsFailed');
+ });
+});
diff --git a/src/features/AgentSidebar/Topic/archiveMergedPullRequestTopics.ts b/src/features/AgentSidebar/Topic/archiveMergedPullRequestTopics.ts
new file mode 100644
index 00000000000..106ce67cfe7
--- /dev/null
+++ b/src/features/AgentSidebar/Topic/archiveMergedPullRequestTopics.ts
@@ -0,0 +1,100 @@
+import type { DeviceGitPullRequestDetail, TopicPullRequestItem } from '@lobechat/types';
+import { toast } from '@lobehub/ui';
+import { type TFunction } from 'i18next';
+
+import { workService } from '@/services/work';
+import { useChatStore } from '@/store/chat';
+import { useGitReviewStore } from '@/store/device/gitReview/store';
+import { type ChatTopic } from '@/types/topic';
+
+import {
+ getArchivableTopics,
+ getMergedPullRequestTopics,
+ pullRequestIdentityKey,
+} from './utils/mergedPullRequestTopics';
+
+/** Topic ids per server read — the `work.listTopicsPullRequests` input bound. */
+const TOPIC_BATCH = 100;
+
+/**
+ * Merges seen by the execution devices' `gh pr view` reads loaded in this
+ * client — in practice, PRs of topics opened in this session. Only merges:
+ * merged is final, while an older "open" read must not hide a merge the server
+ * knows of.
+ */
+const readDeviceMergedPullRequests = () => {
+ const details = new Map<string, DeviceGitPullRequestDetail>();
+ for (const read of Object.values(useGitReviewStore.getState().gitPullRequestDetailMap)) {
+ const detail = read?.value?.detail;
+ if (detail?.state !== 'merged') continue;
+ details.set(
+ pullRequestIdentityKey(`${detail.repo.owner}/${detail.repo.name}`, detail.number),
+ detail,
+ );
+ }
+ return details;
+};
+
+/**
+ * Of the given topics, the open ones whose linked pull requests have landed —
+ * read from their Work rows and topic links in one server read per 100 topics.
+ */
+export const findMergedPullRequestTopics = async (
+ topics: ChatTopic[],
+ ownerId?: string | null,
+): Promise<ChatTopic[]> => {
+ const candidates = getArchivableTopics(topics, ownerId);
+ if (candidates.length === 0) return [];
+
+ const ids = candidates.map((topic) => topic.id);
+ const pullRequestsByTopic: Record<string, TopicPullRequestItem[]> = {};
+ // One read at a time: a long topic list must not turn into a burst.
+ for (let i = 0; i < ids.length; i += TOPIC_BATCH) {
+ Object.assign(
+ pullRequestsByTopic,
+ await workService.listTopicsPullRequests(ids.slice(i, i + TOPIC_BATCH)),
+ );
+ }
+
+ return getMergedPullRequestTopics(
+ candidates,
+ pullRequestsByTopic,
+ readDeviceMergedPullRequests(),
+ );
+};
+
+/**
+ * "Archive merged PR topics": mark every open topic among `topics` whose pull
+ * requests have landed as completed, and tell the user how many.
+ */
+export const archiveMergedPullRequestTopics = async ({
+ ownerId,
+ t,
+ topics,
+}: {
+ /** Keep only this user's topics (a workspace member's own scope). */
+ ownerId?: string | null;
+ t: TFunction<'topic'>;
+ topics: ChatTopic[];
+}) => {
+ let merged: ChatTopic[];
+ try {
+ merged = await findMergedPullRequestTopics(topics, ownerId);
+ } catch (error) {
+ console.error('[archiveMergedPullRequestTopics]', error);
+ toast.error(t('actions.archiveMergedPullRequestsFailed'));
+ return;
+ }
+
+ if (merged.length === 0) {
+ toast.info(t('actions.archiveMergedPullRequestsNone'));
+ return;
+ }
+
+ const { refreshTopic, updateTopicStatus } = useChatStore.getState();
+ await Promise.all(
+ merged.map(({ id }) => updateTopicStatus({ status: 'completed', topicId: id })),
+ );
+ await refreshTopic();
+ toast.success(t('actions.archiveMergedPullRequestsSuccess', { count: merged.length }));
+};
diff --git a/src/features/AgentSidebar/Topic/useDropdownMenu.test.tsx b/src/features/AgentSidebar/Topic/useDropdownMenu.test.tsx
index 7c2f2b3a490..839bb159adc 100644
--- a/src/features/AgentSidebar/Topic/useDropdownMenu.test.tsx
+++ b/src/features/AgentSidebar/Topic/useDropdownMenu.test.tsx
@@ -24,7 +24,7 @@ const chatStoreMock = vi.hoisted(() => ({
updateTopicStatus: vi.fn(),
}));
-const messageMock = vi.hoisted(() => ({ info: vi.fn(), success: vi.fn() }));
+const messageMock = vi.hoisted(() => ({ error: vi.fn(), info: vi.fn(), success: vi.fn() }));
const addFolderMock = vi.hoisted(() => ({
item: null as { key: string; label: string; onClick: () => void } | null,
}));
@@ -76,15 +76,57 @@ vi.mock('@/hooks/usePermission', () => ({
}));
vi.mock('@/store/chat', () => ({
- useChatStore: (selector: (state: Record<string, unknown>) => unknown) =>
- selector({
- importTopic: vi.fn(),
- removeSessionTopics: removeSessionTopicsMock,
- removeUnstarredTopic: removeUnstarredTopicMock,
- refreshTopic: chatStoreMock.refreshTopic,
- topics: chatStoreMock.topics,
- updateTopicStatus: chatStoreMock.updateTopicStatus,
- }),
+ useChatStore: Object.assign(
+ (selector: (state: Record<string, unknown>) => unknown) =>
+ selector({
+ importTopic: vi.fn(),
+ removeSessionTopics: removeSessionTopicsMock,
+ removeUnstarredTopic: removeUnstarredTopicMock,
+ refreshTopic: chatStoreMock.refreshTopic,
+ topics: chatStoreMock.topics,
+ updateTopicStatus: chatStoreMock.updateTopicStatus,
+ }),
+ { getState: () => chatStoreMock },
+ ),
+}));
+
+// Each topic's linked PRs come from its Work rows; a fixture's `prStatus`
+// stands for one linked PR in that state.
+vi.mock('@/services/work', () => ({
+ workService: {
+ listTopicsPullRequests: vi.fn(async (ids: string[]) =>
+ Object.fromEntries(
+ chatStoreMock.topics.flatMap((topic) =>
+ ids.includes(topic.id as string) && topic.prStatus
+ ? [
+ [
+ topic.id,
+ [
+ {
+ identifier: 'lobehub/lobehub#1',
+ linkedAt: new Date('2026-11-20T00:00:00Z'),
+ number: 1,
+ repoFullName: 'lobehub/lobehub',
+ scm: null,
+ source: 'created',
+ status: topic.prStatus,
+ title: null,
+ url: null,
+ vouched: true,
+ workId: 'work-1',
+ },
+ ],
+ ],
+ ]
+ : [],
+ ),
+ ),
+ ),
+ },
+}));
+
+vi.mock('@/store/device/gitReview/store', () => ({
+ useGitReviewStore: { getState: () => ({ gitPullRequestDetailMap: {} }) },
}));
vi.mock('@/store/chat/selectors', () => ({
@@ -180,17 +222,13 @@ describe('useTopicActionsDropdownMenu', () => {
chatStoreMock.topics = [
{
id: 'own-merged',
- metadata: {
- workingDirectoryConfig: { git: { github: { pullRequest: { state: 'MERGED' } } } },
- },
+ prStatus: 'merged',
status: 'active',
userId: 'user-1',
},
{
id: 'other-merged',
- metadata: {
- workingDirectoryConfig: { git: { github: { pullRequest: { state: 'MERGED' } } } },
- },
+ prStatus: 'merged',
status: 'active',
userId: 'user-2',
},
@@ -261,17 +299,13 @@ describe('useTopicActionsDropdownMenu', () => {
chatStoreMock.topics = [
{
id: 'own-merged',
- metadata: {
- workingDirectoryConfig: { git: { github: { pullRequest: { state: 'MERGED' } } } },
- },
+ prStatus: 'merged',
status: 'active',
userId: 'user-1',
},
{
id: 'other-merged',
- metadata: {
- workingDirectoryConfig: { git: { github: { pullRequest: { state: 'MERGED' } } } },
- },
+ prStatus: 'merged',
status: 'active',
userId: 'user-2',
},
@@ -298,32 +332,22 @@ describe('useTopicActionsDropdownMenu', () => {
chatStoreMock.topics = [
{
id: 'merged',
- metadata: {
- workingDirectoryConfig: { git: { github: { pullRequest: { state: 'MERGED' } } } },
- },
+ prStatus: 'merged',
status: 'active',
},
{
id: 'open',
- metadata: {
- workingDirectoryConfig: { git: { github: { pullRequest: { state: 'OPEN' } } } },
- },
+ prStatus: 'open',
status: 'active',
},
{
id: 'completed',
- metadata: {
- workingDirectoryConfig: {
- git: { github: { pullRequest: { mergedAt: '2026-07-10T00:00:00Z' } } },
- },
- },
+ prStatus: 'merged',
status: 'completed',
},
{
id: 'unread',
- metadata: {
- workingDirectoryConfig: { git: { github: { pullRequest: { state: 'MERGED' } } } },
- },
+ prStatus: 'merged',
status: 'unread',
},
];
diff --git a/src/features/AgentSidebar/Topic/useDropdownMenu.tsx b/src/features/AgentSidebar/Topic/useDropdownMenu.tsx
index 35e0b301833..9edd4832831 100644
--- a/src/features/AgentSidebar/Topic/useDropdownMenu.tsx
+++ b/src/features/AgentSidebar/Topic/useDropdownMenu.tsx
@@ -16,8 +16,8 @@ import { systemStatusSelectors } from '@/store/global/selectors';
import { useUserStore } from '@/store/user';
import { labPreferSelectors, userProfileSelectors } from '@/store/user/selectors';
+import { archiveMergedPullRequestTopics } from './archiveMergedPullRequestTopics';
import { useAddFolderMenuItem } from './useAddFolderMenuItem';
-import { getMergedPullRequestTopics } from './utils/mergedPullRequestTopics';
const hotArea = css`
&::before {
@@ -46,41 +46,21 @@ export const useTopicActionsDropdownMenu = (
const { allowed: canEditTopic } = usePermission('edit_own_content');
const topics = useChatStore(topicSelectors.currentTopics);
- const [
- removeUnstarredTopic,
- removeAllTopic,
- importTopic,
- updateTopicStatus,
- refreshTopic,
- activeAgentId,
- ] = useChatStore((s) => [
+ const [removeUnstarredTopic, removeAllTopic, importTopic, activeAgentId] = useChatStore((s) => [
s.removeUnstarredTopic,
s.removeSessionTopics,
s.importTopic,
- s.updateTopicStatus,
- s.refreshTopic,
s.activeAgentId,
]);
const handleArchiveMergedPullRequests = useCallback(
- async (scope: TopicMaintenanceScope = 'own') => {
- const mergedTopics = getMergedPullRequestTopics(
- topics ?? [],
- activeWorkspaceId && scope === 'own' ? (currentUserId ?? null) : undefined,
- );
-
- if (mergedTopics.length === 0) {
- toast.info(t('actions.archiveMergedPullRequestsNone'));
- return;
- }
-
- await Promise.all(
- mergedTopics.map(({ id }) => updateTopicStatus({ status: 'completed', topicId: id })),
- );
- await refreshTopic();
- toast.success(t('actions.archiveMergedPullRequestsSuccess', { count: mergedTopics.length }));
- },
- [activeWorkspaceId, currentUserId, refreshTopic, t, topics, updateTopicStatus],
+ (scope: TopicMaintenanceScope = 'own') =>
+ archiveMergedPullRequestTopics({
+ ownerId: activeWorkspaceId && scope === 'own' ? (currentUserId ?? null) : undefined,
+ t,
+ topics: topics ?? [],
+ }),
+ [activeWorkspaceId, currentUserId, t, topics],
);
const handleImport = useCallback(
diff --git a/src/features/AgentSidebar/Topic/utils/mergedPullRequestTopics.test.ts b/src/features/AgentSidebar/Topic/utils/mergedPullRequestTopics.test.ts
new file mode 100644
index 00000000000..08d3c0ce660
--- /dev/null
+++ b/src/features/AgentSidebar/Topic/utils/mergedPullRequestTopics.test.ts
@@ -0,0 +1,142 @@
+import type { DeviceGitPullRequestDetail, TopicPullRequestItem } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { type ChatTopic } from '@/types/topic';
+
+import {
+ getArchivableTopics,
+ getMergedPullRequestTopics,
+ hasLandedPullRequests,
+ pullRequestIdentityKey,
+} from './mergedPullRequestTopics';
+
+const topic = (id: string, extra: Partial<ChatTopic> = {}) =>
+ ({ createdAt: 0, id, title: id, updatedAt: 0, ...extra }) as ChatTopic;
+
+const pr = (
+ number: number,
+ status: string | null,
+ extra: Partial<TopicPullRequestItem> = {},
+): TopicPullRequestItem => ({
+ identifier: `lobehub/lobehub#${number}`,
+ linkedAt: new Date('2026-11-20T00:00:00Z'),
+ number,
+ repoFullName: 'lobehub/lobehub',
+ scm: null,
+ source: 'created',
+ status,
+ title: null,
+ url: null,
+ vouched: true,
+ workId: `work-${number}`,
+ ...extra,
+});
+
+const appState = (state: 'closed' | 'merged' | 'open') =>
+ ({
+ autoFix: {
+ changeRequestId: 'scr',
+ enabled: true,
+ maxWakes: 3,
+ ownerTopic: null,
+ ownerTopicId: null,
+ wakeCount: 0,
+ },
+ ciStatus: null,
+ isDraft: false,
+ mergedAt: state === 'merged' ? new Date('2026-11-21T00:00:00Z') : null,
+ reviewDecision: null,
+ state,
+ title: null,
+ updatedAt: new Date(),
+ }) satisfies TopicPullRequestItem['scm'];
+
+describe('hasLandedPullRequests', () => {
+ it.each([
+ ['one merged PR', [{ state: 'merged' }], true],
+ ['merged plus a superseded closed PR', [{ state: 'merged' }, { state: 'closed' }], true],
+ ['a merged PR next to one still open', [{ state: 'merged' }, { state: 'open' }], false],
+ ['only closed PRs', [{ state: 'closed' }], false],
+ ['no PR', [], false],
+ ] as const)('%s → %s', (_, views, expected) => {
+ expect(hasLandedPullRequests(views.map((view) => ({ ...view, vouched: true })))).toBe(expected);
+ });
+
+ it('ignores PRs the app cannot vouch for', () => {
+ // An unvouched branch match can be someone else's PR: it neither archives…
+ expect(hasLandedPullRequests([{ state: 'merged', vouched: false }])).toBe(false);
+ // …nor keeps a topic whose own PR landed.
+ expect(
+ hasLandedPullRequests([
+ { state: 'merged', vouched: true },
+ { state: 'open', vouched: false },
+ ]),
+ ).toBe(true);
+ });
+});
+
+describe('getArchivableTopics', () => {
+ const topics = [
+ topic('active', { status: 'active', userId: 'u1' }),
+ topic('plain', { userId: 'u2' }),
+ topic('completed', { status: 'completed', userId: 'u1' }),
+ topic('archived', { status: 'archived', userId: 'u1' }),
+ topic('unread', { status: 'unread', userId: 'u1' }),
+ ];
+
+ it('keeps open topics only', () => {
+ expect(getArchivableTopics(topics).map((t) => t.id)).toEqual(['active', 'plain']);
+ });
+
+ it('keeps one owner’s topics when asked, none for an unknown owner', () => {
+ expect(getArchivableTopics(topics, 'u1').map((t) => t.id)).toEqual(['active']);
+ expect(getArchivableTopics(topics, null)).toEqual([]);
+ });
+});
+
+describe('getMergedPullRequestTopics', () => {
+ it('selects the topics whose Work-row PRs have landed', () => {
+ const topics = [
+ topic('agent-merged'),
+ topic('app-merged'),
+ topic('app-reopened'),
+ topic('mixed'),
+ topic('none'),
+ topic('unknown'),
+ ];
+
+ const merged = getMergedPullRequestTopics(topics, {
+ // `gh pr merge` in the conversation left the Work row merged.
+ 'agent-merged': [pr(1, 'merged')],
+ // The GitHub App's state wins over the Work row's.
+ 'app-merged': [pr(2, 'open', { scm: appState('merged') })],
+ 'app-reopened': [pr(3, 'merged', { scm: appState('open') })],
+ 'mixed': [pr(4, 'open'), pr(5, 'merged')],
+ // Linked, but nothing knows its state yet: it may still be open.
+ 'unknown': [pr(6, null)],
+ });
+
+ expect(merged.map((t) => t.id)).toEqual(['agent-merged', 'app-merged']);
+ });
+
+ it('takes a merge only the device saw (merged on GitHub, no App)', () => {
+ const detail = {
+ mergedAt: '2026-11-21T00:00:00Z',
+ number: 7,
+ repo: { name: 'LobeHub', owner: 'LobeHub' },
+ state: 'merged',
+ title: 'Device read',
+ url: 'https://github.com/lobehub/lobehub/pull/7',
+ } as DeviceGitPullRequestDetail;
+ const byTopic = { t: [pr(7, 'open')] };
+
+ expect(getMergedPullRequestTopics([topic('t')], byTopic)).toEqual([]);
+ expect(
+ getMergedPullRequestTopics(
+ [topic('t')],
+ byTopic,
+ new Map([[pullRequestIdentityKey('LobeHub/LobeHub', 7), detail]]),
+ ).map((t) => t.id),
+ ).toEqual(['t']);
+ });
+});
diff --git a/src/features/AgentSidebar/Topic/utils/mergedPullRequestTopics.ts b/src/features/AgentSidebar/Topic/utils/mergedPullRequestTopics.ts
index 238679716f8..d29b08f026b 100644
--- a/src/features/AgentSidebar/Topic/utils/mergedPullRequestTopics.ts
+++ b/src/features/AgentSidebar/Topic/utils/mergedPullRequestTopics.ts
@@ -1,24 +1,68 @@
+import type { DeviceGitPullRequestDetail, TopicPullRequestItem } from '@lobechat/types';
+
+import {
+ resolvePullRequestView,
+ type TopicPullRequestView,
+} from '@/features/TopicPullRequests/pullRequestView';
import { type ChatTopic } from '@/types/topic';
+/** `owner/repo#number`, lower-cased: how device reads are matched to linked PRs. */
+export const pullRequestIdentityKey = (repoFullName: string, number: number) =>
+ `${repoFullName.toLowerCase()}#${number}`;
+
/**
- * Topics whose linked PR has merged and that are still open — the ones the
- * "archive merged PR topics" actions mark as completed. Pass `ownerId` to keep
- * only that user's topics (a workspace member's own scope).
+ * Topics the "archive merged PR topics" actions may touch: still open (not
+ * completed, archived or unread). Pass `ownerId` to keep only that user's
+ * topics (a workspace member's own scope); `null` keeps none.
*/
-export const getMergedPullRequestTopics = (
- topics: ChatTopic[],
- ownerId?: string | null,
-): ChatTopic[] =>
+export const getArchivableTopics = (topics: ChatTopic[], ownerId?: string | null): ChatTopic[] =>
topics.filter((topic) => {
if (ownerId !== undefined && (!ownerId || topic.userId !== ownerId)) return false;
+ return topic.status !== 'completed' && topic.status !== 'archived' && topic.status !== 'unread';
+ });
- const pullRequest = topic.metadata?.workingDirectoryConfig?.git?.github?.pullRequest;
- const isMerged = !!pullRequest?.mergedAt || pullRequest?.state?.toLowerCase() === 'merged';
+/**
+ * Whether a topic's linked pull requests say its work has landed:
+ *
+ * - at least one of them is merged, and
+ * - none is still open (a draft is open too) — the topic is still in flight.
+ *
+ * A PR closed without merging (superseded, abandoned) neither counts nor
+ * blocks. Only PRs the app can vouch belong to the topic count at all: a
+ * branch-name match it cannot vouch for may be someone else's PR. A PR whose
+ * state nothing confirmed reads as the status the agent's commands left, open
+ * when there is none — so an unknown PR keeps the topic.
+ */
+export const hasLandedPullRequests = (
+ views: Pick<TopicPullRequestView, 'state' | 'vouched'>[],
+): boolean => {
+ const vouched = views.filter((view) => view.vouched);
+ return (
+ vouched.some((view) => view.state === 'merged') &&
+ !vouched.some((view) => view.state === 'open')
+ );
+};
- return (
- isMerged &&
- topic.status !== 'completed' &&
- topic.status !== 'archived' &&
- topic.status !== 'unread'
+/**
+ * The topics whose pull requests have landed (see {@link hasLandedPullRequests}),
+ * from their Work-row listing. `deviceMerges` are execution-device
+ * `gh pr view` reads showing a merge, keyed by {@link pullRequestIdentityKey}:
+ * without the GitHub App they are what knows a PR was merged on GitHub rather
+ * than by the agent. Pass merged reads only — a stale "open" read would hide a
+ * merge the server already knows of.
+ */
+export const getMergedPullRequestTopics = (
+ topics: ChatTopic[],
+ pullRequestsByTopic: Record<string, TopicPullRequestItem[]>,
+ deviceMerges: Map<string, DeviceGitPullRequestDetail> = new Map(),
+): ChatTopic[] =>
+ topics.filter((topic) => {
+ const items = pullRequestsByTopic[topic.id];
+ if (!items?.length) return false;
+ return hasLandedPullRequests(
+ items.map((item) => {
+ const detail = deviceMerges.get(pullRequestIdentityKey(item.repoFullName, item.number));
+ return resolvePullRequestView(item, detail ? { confirmed: false, detail } : undefined);
+ }),
);
});
diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.test.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.test.tsx
index 76ab70f17ca..802a6df5843 100644
--- a/src/routes/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.test.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.test.tsx
@@ -24,7 +24,7 @@ const chatStoreMock = vi.hoisted(() => ({
updateTopicStatus: vi.fn(),
}));
-const messageMock = vi.hoisted(() => ({ info: vi.fn(), success: vi.fn() }));
+const messageMock = vi.hoisted(() => ({ error: vi.fn(), info: vi.fn(), success: vi.fn() }));
vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
useActiveWorkspaceId: () => workspaceMock.activeWorkspaceId,
@@ -69,16 +69,58 @@ vi.mock('@/hooks/usePermission', () => ({
}));
vi.mock('@/store/chat', () => ({
- useChatStore: (selector: (state: Record<string, unknown>) => unknown) =>
- selector({
- activeGroupId: 'group-1',
- importTopic: vi.fn(),
- removeGroupTopics: removeGroupTopicsMock,
- removeUnstarredTopic: removeUnstarredTopicMock,
- refreshTopic: chatStoreMock.refreshTopic,
- topics: chatStoreMock.topics,
- updateTopicStatus: chatStoreMock.updateTopicStatus,
- }),
+ useChatStore: Object.assign(
+ (selector: (state: Record<string, unknown>) => unknown) =>
+ selector({
+ activeGroupId: 'group-1',
+ importTopic: vi.fn(),
+ removeGroupTopics: removeGroupTopicsMock,
+ removeUnstarredTopic: removeUnstarredTopicMock,
+ refreshTopic: chatStoreMock.refreshTopic,
+ topics: chatStoreMock.topics,
+ updateTopicStatus: chatStoreMock.updateTopicStatus,
+ }),
+ { getState: () => chatStoreMock },
+ ),
+}));
+
+// Each topic's linked PRs come from its Work rows; a fixture's `prStatus`
+// stands for one linked PR in that state.
+vi.mock('@/services/work', () => ({
+ workService: {
+ listTopicsPullRequests: vi.fn(async (ids: string[]) =>
+ Object.fromEntries(
+ chatStoreMock.topics.flatMap((topic) =>
+ ids.includes(topic.id as string) && topic.prStatus
+ ? [
+ [
+ topic.id,
+ [
+ {
+ identifier: 'lobehub/lobehub#1',
+ linkedAt: new Date('2026-11-20T00:00:00Z'),
+ number: 1,
+ repoFullName: 'lobehub/lobehub',
+ scm: null,
+ source: 'created',
+ status: topic.prStatus,
+ title: null,
+ url: null,
+ vouched: true,
+ workId: 'work-1',
+ },
+ ],
+ ],
+ ]
+ : [],
+ ),
+ ),
+ ),
+ },
+}));
+
+vi.mock('@/store/device/gitReview/store', () => ({
+ useGitReviewStore: { getState: () => ({ gitPullRequestDetailMap: {} }) },
}));
vi.mock('@/store/chat/selectors', () => ({
@@ -149,17 +191,13 @@ describe('group useTopicActionsDropdownMenu', () => {
chatStoreMock.topics = [
{
id: 'own-merged',
- metadata: {
- workingDirectoryConfig: { git: { github: { pullRequest: { state: 'MERGED' } } } },
- },
+ prStatus: 'merged',
status: 'active',
userId: 'user-1',
},
{
id: 'other-merged',
- metadata: {
- workingDirectoryConfig: { git: { github: { pullRequest: { state: 'MERGED' } } } },
- },
+ prStatus: 'merged',
status: 'active',
userId: 'user-2',
},
@@ -227,17 +265,13 @@ describe('group useTopicActionsDropdownMenu', () => {
chatStoreMock.topics = [
{
id: 'own-merged',
- metadata: {
- workingDirectoryConfig: { git: { github: { pullRequest: { state: 'MERGED' } } } },
- },
+ prStatus: 'merged',
status: 'active',
userId: 'user-1',
},
{
id: 'other-merged',
- metadata: {
- workingDirectoryConfig: { git: { github: { pullRequest: { state: 'MERGED' } } } },
- },
+ prStatus: 'merged',
status: 'active',
userId: 'user-2',
},
@@ -264,32 +298,22 @@ describe('group useTopicActionsDropdownMenu', () => {
chatStoreMock.topics = [
{
id: 'merged',
- metadata: {
- workingDirectoryConfig: { git: { github: { pullRequest: { state: 'MERGED' } } } },
- },
+ prStatus: 'merged',
status: 'active',
},
{
id: 'open',
- metadata: {
- workingDirectoryConfig: { git: { github: { pullRequest: { state: 'OPEN' } } } },
- },
+ prStatus: 'open',
status: 'active',
},
{
id: 'completed',
- metadata: {
- workingDirectoryConfig: {
- git: { github: { pullRequest: { mergedAt: '2026-07-10T00:00:00Z' } } },
- },
- },
+ prStatus: 'merged',
status: 'completed',
},
{
id: 'unread',
- metadata: {
- workingDirectoryConfig: { git: { github: { pullRequest: { state: 'MERGED' } } } },
- },
+ prStatus: 'merged',
status: 'unread',
},
];
diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.tsx
index a429bce12b8..966a528cf49 100644
--- a/src/routes/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.tsx
@@ -6,6 +6,7 @@ import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { useIsWorkspaceOwner } from '@/business/client/hooks/useIsWorkspaceOwner';
+import { archiveMergedPullRequestTopics } from '@/features/AgentSidebar/Topic/archiveMergedPullRequestTopics';
import { openWorkspaceDeleteAllModal } from '@/features/WorkspaceDeleteAllModal';
import { usePermission } from '@/hooks/usePermission';
import { useChatStore } from '@/store/chat';
@@ -42,21 +43,9 @@ export const useTopicActionsDropdownMenu = (
const { allowed: canEditTopic } = usePermission('edit_own_content');
const topics = useChatStore(topicSelectors.currentTopics);
- const [
- activeGroupId,
- removeUnstarredTopic,
- removeGroupTopics,
- importTopic,
- updateTopicStatus,
- refreshTopic,
- ] = useChatStore((s) => [
- s.activeGroupId,
- s.removeUnstarredTopic,
- s.removeGroupTopics,
- s.importTopic,
- s.updateTopicStatus,
- s.refreshTopic,
- ]);
+ const [activeGroupId, removeUnstarredTopic, removeGroupTopics, importTopic] = useChatStore(
+ (s) => [s.activeGroupId, s.removeUnstarredTopic, s.removeGroupTopics, s.importTopic],
+ );
const removeAllTopic = useCallback(
async (scope: 'own' | 'workspace' = 'own') => {
@@ -67,39 +56,13 @@ export const useTopicActionsDropdownMenu = (
);
const handleArchiveMergedPullRequests = useCallback(
- async (scope: TopicMaintenanceScope = 'own') => {
- const mergedTopics = (topics ?? []).filter((topic) => {
- if (
- activeWorkspaceId &&
- scope === 'own' &&
- (!currentUserId || topic.userId !== currentUserId)
- ) {
- return false;
- }
-
- const pullRequest = topic.metadata?.workingDirectoryConfig?.git?.github?.pullRequest;
- const isMerged = !!pullRequest?.mergedAt || pullRequest?.state?.toLowerCase() === 'merged';
-
- return (
- isMerged &&
- topic.status !== 'completed' &&
- topic.status !== 'archived' &&
- topic.status !== 'unread'
- );
- });
-
- if (mergedTopics.length === 0) {
- toast.info(t('actions.archiveMergedPullRequestsNone'));
- return;
- }
-
- await Promise.all(
- mergedTopics.map(({ id }) => updateTopicStatus({ status: 'completed', topicId: id })),
- );
- await refreshTopic();
- toast.success(t('actions.archiveMergedPullRequestsSuccess', { count: mergedTopics.length }));
- },
- [activeWorkspaceId, currentUserId, refreshTopic, t, topics, updateTopicStatus],
+ (scope: TopicMaintenanceScope = 'own') =>
+ archiveMergedPullRequestTopics({
+ ownerId: activeWorkspaceId && scope === 'own' ? (currentUserId ?? null) : undefined,
+ t,
+ topics: topics ?? [],
+ }),
+ [activeWorkspaceId, currentUserId, t, topics],
);
const handleImport = useCallback(
diff --git a/src/services/work.ts b/src/services/work.ts
index 5c453742cf6..e4be25a40bb 100644
--- a/src/services/work.ts
+++ b/src/services/work.ts
@@ -136,6 +136,12 @@ class WorkService {
listTopicPullRequests = async (topicId: string): Promise<TopicPullRequestItem[]> =>
lambdaClient.work.listTopicPullRequests.query({ topicId });
+ /** {@link listTopicPullRequests} for up to 100 topics, keyed by topic id. */
+ listTopicsPullRequests = async (
+ topicIds: string[],
+ ): Promise<Record<string, TopicPullRequestItem[]>> =>
+ lambdaClient.work.listTopicsPullRequests.query({ topicIds });
+
/**
* Link the pull requests a `git push` tool call
* updated. `pullRequests` is the execution device's `gh pr list --head`