🤯 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(coding): PR row ⋯ menu with per-PR Auto-fix for GitHub App wakes (#23319)
Bryan5af83a501da8
diff --git a/apps/server/src/routers/lambda/__tests__/scm.test.ts b/apps/server/src/routers/lambda/__tests__/scm.test.tsindex 80b323576be..6962d15cc0d 100644--- a/apps/server/src/routers/lambda/__tests__/scm.test.ts+++ b/apps/server/src/routers/lambda/__tests__/scm.test.ts@@ -28,6 +28,7 @@ const mocks = vi.hoisted(() => ({consumeClaim: vi.fn(),fetchInstallation: vi.fn(),listRepositories: vi.fn(),+ onAutoFixChanged: vi.fn(),}));vi.mock('@/server/services/scm/oauth/stateStore', () => ({consumeScmInstallClaim: mocks.consumeClaim,@@ -36,6 +37,12 @@ vi.mock('@/server/services/scm/github/app', () => ({fetchGitHubInstallation: mocks.fetchInstallation,listGitHubInstallationRepositoryDetails: mocks.listRepositories,}));+// The comment it rewrites is covered with the service; here only that it is asked to.+vi.mock('@/server/services/scm/ScmControlService', () => ({+ ScmControlService: vi.fn().mockImplementation(function () {+ return { onAutoFixChanged: mocks.onAutoFixChanged };+ }),+}));vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {const mod = await vi.importActual<{ trpc: any }>('@/libs/trpc/lambda/init');@@ -305,6 +312,82 @@ describe('scmRouter', () => {).resolves.toMatchObject({ userId, workspaceId: workspace.id });});+ describe('setChangeRequestAutoFix', () => {+ const pullRequest = (scope: { userId: string; workspaceId?: string }) =>+ ScmChangeRequestModel.upsert(serverDB, {+ number: 8,+ provider: 'github',+ repoFullName: 'a/autofix',+ state: 'open',+ url: 'https://github.com/a/autofix/pull/8',+ ...scope,+ });++ it('switches Auto-fix off and back on, starting the wake count over', async () => {+ const row = await pullRequest({ userId });+ await ScmChangeRequestModel.reserveWake(serverDB, row.id, 3, 'ci_failed');++ await expect(+ caller({ userId }).setChangeRequestAutoFix({ changeRequestId: row.id, enabled: false }),+ ).resolves.toEqual({ autoFix: false, maxWakes: 3, wakeCount: 1 });+ await expect(+ caller({ userId }).setChangeRequestAutoFix({ changeRequestId: row.id, enabled: true }),+ ).resolves.toEqual({ autoFix: true, maxWakes: 3, wakeCount: 0 });+ });++ it('refuses a pull request another tenant owns', async () => {+ const row = await pullRequest({ userId });++ await expect(+ caller({ userId: otherUserId }).setChangeRequestAutoFix({+ changeRequestId: row.id,+ enabled: false,+ }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect((await ScmChangeRequestModel.findById(serverDB, row.id))?.metadata.autoFix).toBe(+ undefined,+ );+ });++ it('requires the member role in a workspace', async () => {+ const [workspace] = await serverDB+ .insert(workspaces)+ .values({ name: 'ws', primaryOwnerId: userId, slug: 'scm-ws-autofix' })+ .returning();+ await serverDB.insert(workspaceMembers).values([+ { role: 'viewer', userId: otherUserId, workspaceId: workspace.id },+ { role: 'member', userId, workspaceId: workspace.id },+ ]);+ const row = await pullRequest({ userId, workspaceId: workspace.id });++ await expect(+ caller({ userId: otherUserId, workspaceId: workspace.id }).setChangeRequestAutoFix({+ changeRequestId: row.id,+ enabled: false,+ }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ await expect(+ caller({ userId, workspaceId: workspace.id }).setChangeRequestAutoFix({+ changeRequestId: row.id,+ enabled: false,+ }),+ ).resolves.toMatchObject({ autoFix: false });+ });++ it('rewrites the tracking comment, and keeps the switch when that fails', async () => {+ const row = await pullRequest({ userId });++ await caller({ userId }).setChangeRequestAutoFix({ changeRequestId: row.id, enabled: false });+ expect(mocks.onAutoFixChanged).toHaveBeenCalledWith(row.id);++ mocks.onAutoFixChanged.mockRejectedValueOnce(new Error('rate limited'));+ await expect(+ caller({ userId }).setChangeRequestAutoFix({ changeRequestId: row.id, enabled: true }),+ ).resolves.toMatchObject({ autoFix: true });+ expect((await ScmChangeRequestModel.findById(serverDB, row.id))?.metadata.autoFix).toBe(true);+ });+ });+describe('listRepositories', () => {const repo = (fullName: string, pushedAt: string | null) => ({defaultBranch: 'main',diff --git a/apps/server/src/routers/lambda/scm.ts b/apps/server/src/routers/lambda/scm.tsindex 0556cd946ff..88d71ca8430 100644--- a/apps/server/src/routers/lambda/scm.ts+++ b/apps/server/src/routers/lambda/scm.ts@@ -1,4 +1,5 @@import { TRPCError } from '@trpc/server';+import debug from 'debug';import { z } from 'zod';import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';@@ -17,8 +18,11 @@ import {listScopeGitHubRepositories,ScmRepositoriesUnavailableError,} from '@/server/services/scm/repositories';+import { ScmControlService } from '@/server/services/scm/ScmControlService';import { canWriteScmScope } from '@/server/services/scm/scope';+const log = debug('lobe-server:router:scm');+/** Path the "Connect GitHub" button navigates to; the server route owns the redirect. */export const GITHUB_INSTALL_PATH = '/api/webhooks/github/install';@@ -31,10 +35,10 @@ const scmProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {/*** The SCM integration for the settings page and acceptance views. Reads,- * plus the one write a signed-in user confirms in the app: connecting an+ * plus the writes a signed-in user makes in the app: connecting an* installation that reached the callback without our state (started on- * github.com). Everything else is written by provider webhooks and the- * install callback.+ * github.com), and a pull request's Auto-fix switch. Everything else is+ * written by provider webhooks and the install callback.*/export const scmRouter = router({/**@@ -142,6 +146,41 @@ export const scmRouter = router({ScmChangeRequestModel.listByScope(ctx.serverDB, ctx.scope, { limit: input?.limit }),),+ /**+ * Turn Auto-fix on or off for one tracked pull request: whether its failing+ * CI and review feedback wake the agent of the linked conversation. Only+ * the tenant that owns the row — whose conversation gets woken — may switch+ * it, with the same member role as every other SCM write. Turning it back+ * on starts the wake count over.+ */+ setChangeRequestAutoFix: scmProcedure+ .input(z.object({ changeRequestId: z.string().min(1), enabled: z.boolean() }))+ .mutation(async ({ ctx, input }) => {+ if (!(await canWriteScmScope(ctx.serverDB, ctx.userId, ctx.scope.workspaceId))) {+ throw new TRPCError({ code: 'FORBIDDEN', message: 'workspace member role required' });+ }++ const updated = await ScmChangeRequestModel.setAutoFix(+ ctx.serverDB,+ ctx.scope,+ input.changeRequestId,+ input.enabled,+ );+ if (!updated) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'pull request not found' });+ }++ // The switch is saved; a comment that fails to update catches up on+ // the next event that rewrites it.+ try {+ await new ScmControlService(ctx.serverDB).onAutoFixChanged(input.changeRequestId);+ } catch (error) {+ log('refresh comment after Auto-fix change on %s failed: %O', input.changeRequestId, error);+ }++ return { ...updated, maxWakes: SCM_MAX_WAKES };+ }),+listInstallations: scmProcedure.query(async ({ ctx }) =>ScmInstallationModel.listByScope(ctx.serverDB, ctx.scope),),diff --git a/apps/server/src/services/scm/ScmControlService.ts b/apps/server/src/services/scm/ScmControlService.tsindex b21506726ab..d60acdeca80 100644--- a/apps/server/src/services/scm/ScmControlService.ts+++ b/apps/server/src/services/scm/ScmControlService.ts@@ -70,7 +70,8 @@ export type ScmControlOutcome =* that opened the PR is woken in its conversation with the failing checks* (plus job log tails) or the review feedback. Capped at* {@link SCM_MAX_WAKES} per PR and debounced so a burst of check events- * becomes one wake; a draft PR never wakes anyone.+ * becomes one wake; a draft PR never wakes anyone, nor one whose+ * Auto-fix was turned off (`metadata.autoFix === false`).*/export class ScmControlService {constructor(private db: LobeChatDatabase) {}@@ -117,6 +118,15 @@ export class ScmControlService {return { detail: `${row.state} needs no action`, outcome: 'skipped' };};+ /**+ * Auto-fix was just switched on the pull request (from the conversation's+ * PR row): rewrite the tracking comment so it says so. Never posts a new+ * comment — a pull request without one has nothing to update.+ */+ onAutoFixChanged = async (rowId: string): Promise<void> => {+ await this.refreshComment(rowId);+ };+private route = async ({ event, kind, row }: ScmControlEvent): Promise<ScmControlOutcome> => {switch (kind) {case 'opened':@@ -379,6 +389,7 @@ export class ScmControlService {topicId: row.topicId ?? undefined,v: 1,},+ autoFix: row.metadata?.autoFix !== false,notification:row.wakeCount > 0? { count: row.wakeCount, max: SCM_MAX_WAKES, reason: row.metadata.lastWake?.reason }@@ -479,6 +490,9 @@ export class ScmControlService {if (row.isDraft) return { detail: 'draft pull request', outcome: 'skipped' };if (row.state !== 'open') return { detail: `pull request is ${row.state}`, outcome: 'skipped' };if (!row.topicId) return { detail: 'no linked conversation', outcome: 'skipped' };+ // The per pull request switch, on top of the account's switches the+ // callers already asked. Absent is on.+ if (row.metadata?.autoFix === false) return { detail: 'auto-fix off', outcome: 'skipped' };// An early out on the snapshot so a capped pull request does not pay for// job logs; the cap itself is enforced by the reservation further down.if (row.wakeCount >= SCM_MAX_WAKES) {@@ -502,8 +516,14 @@ export class ScmControlService {// snapshot, and on a Redis-less deployment there is no debounce to stop// two deliveries from passing it together. Handed back below if the run// never starts.+ // The reservation also re-reads Auto-fix: it may have been turned off+ // while the prompt was being built from job logs or review feedback.const count = await ScmChangeRequestModel.reserveWake(this.db, row.id, SCM_MAX_WAKES, reason);if (count === null) {+ const fresh = await ScmChangeRequestModel.findById(this.db, row.id);+ if (fresh?.metadata?.autoFix === false) {+ return { detail: 'auto-fix off', outcome: 'skipped' };+ }return { detail: `wake cap (${SCM_MAX_WAKES}) reached`, outcome: 'skipped' };}diff --git a/apps/server/src/services/scm/__tests__/ScmControlService.test.ts b/apps/server/src/services/scm/__tests__/ScmControlService.test.tsindex f64802bccc7..210bb2e93ea 100644--- a/apps/server/src/services/scm/__tests__/ScmControlService.test.ts+++ b/apps/server/src/services/scm/__tests__/ScmControlService.test.ts@@ -1,13 +1,14 @@// @vitest-environment nodeimport { getTestDB } from '@lobechat/database/test-utils';import type { ScmActorAssociation } from '@lobechat/types';-import { eq } from 'drizzle-orm';+import { eq, sql } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { ScmChangeRequestModel, ScmInstallationModel } from '@/database/models/scm';import {acceptances,agents,+ scmChangeRequests,scmWebhookDeliveries,topics,users,@@ -736,6 +737,161 @@ describe('ScmControlService — wake', () => {});});+describe('ScmControlService — per pull request Auto-fix', () => {+ const linked = async (metadata: Record<string, unknown> = {}) => {+ const topic = await createTopic();+ return ScmChangeRequestModel.upsert(serverDB, {+ ...baseRow,+ links: { topicId: topic.id },+ metadata,+ });+ };++ it('wakes as before when the pull request never set Auto-fix', async () => {+ const row = await linked();+ expect(row.metadata.autoFix).toBeUndefined();++ expect(await control().handle({ event: checksEvent, kind: 'ci_failed', row })).toMatchObject({+ outcome: 'woken',+ });+ });++ it('skips CI failures and review feedback while Auto-fix is off, without spending a wake', async () => {+ const row = await linked({ autoFix: false });++ expect(await control().handle({ event: checksEvent, kind: 'ci_failed', row })).toEqual({+ detail: 'auto-fix off',+ outcome: 'skipped',+ });+ expect(+ await control().handle({ event: reviewEvent('reviewer'), kind: 'review_commented', row }),+ ).toEqual({ detail: 'auto-fix off', outcome: 'skipped' });+ expect(mocks.execAgent).not.toHaveBeenCalled();+ // Nothing built either: the job log is only read for a wake that happens.+ expect(mocks.jobLog).not.toHaveBeenCalled();+ expect((await ScmChangeRequestModel.findById(serverDB, row.id))?.wakeCount).toBe(0);+ });++ it('cannot turn a wake back on that the account switched off', async () => {+ const row = await linked({ autoFix: true });+ await serverDB+ .update(users)+ .set({ preference: { integration: { github: { wakeOnCiFailure: false } } } as any })+ .where(eq(users.id, userId));++ // Both switches have to be on: the account's off wins over the PR's on…+ expect(await control().handle({ event: checksEvent, kind: 'ci_failed', row })).toEqual({+ detail: 'wakeOnCiFailure is off',+ outcome: 'skipped',+ });+ // …and the PR's off wins over the account's on.+ await ScmChangeRequestModel.setAutoFix(serverDB, { userId }, row.id, false);+ const off = (await ScmChangeRequestModel.findById(serverDB, row.id))!;+ expect(+ await control().handle({+ event: reviewEvent('reviewer'),+ kind: 'review_commented',+ row: off,+ }),+ ).toEqual({ detail: 'auto-fix off', outcome: 'skipped' });+ expect(mocks.execAgent).not.toHaveBeenCalled();+ });++ it('wakes again from a spent cap once Auto-fix is turned off and back on', async () => {+ const row = await linked();+ for (let i = 0; i < SCM_MAX_WAKES; i++) {+ await ScmChangeRequestModel.reserveWake(serverDB, row.id, SCM_MAX_WAKES, 'ci_failed');+ }+ const capped = (await ScmChangeRequestModel.findById(serverDB, row.id))!;+ expect(await control().handle({ event: checksEvent, kind: 'ci_failed', row: capped })).toEqual({+ detail: `wake cap (${SCM_MAX_WAKES}) reached`,+ outcome: 'skipped',+ });++ await ScmChangeRequestModel.setAutoFix(serverDB, { userId }, row.id, false);+ const off = (await ScmChangeRequestModel.findById(serverDB, row.id))!;+ expect(await control().handle({ event: checksEvent, kind: 'ci_failed', row: off })).toEqual({+ detail: 'auto-fix off',+ outcome: 'skipped',+ });++ await ScmChangeRequestModel.setAutoFix(serverDB, { userId }, row.id, true);+ const on = (await ScmChangeRequestModel.findById(serverDB, row.id))!;+ expect(+ await control().handle({ event: checksEvent, kind: 'ci_failed', row: on }),+ ).toMatchObject({ outcome: 'woken' });+ expect((await ScmChangeRequestModel.findById(serverDB, row.id))?.wakeCount).toBe(1);+ });++ it('refuses the wake when Auto-fix is turned off while the prompt is being built', async () => {+ const installation = await ScmInstallationModel.bind(serverDB, userInstallationInput(userId));+ const topic = await createTopic();+ const row = await ScmChangeRequestModel.upsert(serverDB, {+ ...baseRow,+ links: { installationId: installation.id, topicId: topic.id },+ });+ const withChecks = await ScmChangeRequestModel.applyChecks(serverDB, row.id, {+ checks: [+ { conclusion: 'failure', externalId: 'check_run:9', name: 'Test', status: 'completed' },+ ],+ headSha: baseRow.headSha,+ });+ // The person switches it off while the job log is still being fetched.+ mocks.jobLog.mockImplementationOnce(async () => {+ await ScmChangeRequestModel.setAutoFix(serverDB, { userId }, row.id, false);+ return 'log';+ });++ expect(+ await control().handle({ event: checksEvent, kind: 'ci_failed', row: withChecks!.row }),+ ).toEqual({ detail: 'auto-fix off', outcome: 'skipped' });+ expect(mocks.jobLog).toHaveBeenCalledTimes(1);+ expect(mocks.execAgent).not.toHaveBeenCalled();+ expect((await ScmChangeRequestModel.findById(serverDB, row.id))?.wakeCount).toBe(0);+ });++ it('drops a held wake instead of delivering it after Auto-fix went off', async () => {+ const row = await linked();+ await ScmChangeRequestModel.markPendingWake(serverDB, row.id, 'ci_failed');+ await serverDB+ .update(scmChangeRequests)+ .set({ metadata: sql`${scmChangeRequests.metadata} || '{"autoFix": false}'::jsonb` })+ .where(eq(scmChangeRequests.id, row.id));+ const off = (await ScmChangeRequestModel.findById(serverDB, row.id))!;++ // An unrelated event flushes the held wake.+ await control().handle({ event: changeRequestEvent('opened'), kind: 'synchronized', row: off });+ expect(mocks.execAgent).not.toHaveBeenCalled();+ expect((await ScmChangeRequestModel.findById(serverDB, row.id))?.metadata.pendingWake).toBe(+ undefined,+ );+ });++ it('says Auto-fix is off in the tracking comment when it is rewritten', async () => {+ const installation = await ScmInstallationModel.bind(serverDB, userInstallationInput(userId));+ const topic = await createTopic();+ const row = await ScmChangeRequestModel.upsert(serverDB, {+ ...baseRow,+ links: { installationId: installation.id, topicId: topic.id },+ metadata: { repoPrivate: true },+ });+ await control().handle({ event: changeRequestEvent('opened'), kind: 'opened', row });++ await ScmChangeRequestModel.setAutoFix(serverDB, { userId }, row.id, false);+ await control().onAutoFixChanged(row.id);++ expect(mocks.updateComment).toHaveBeenCalledTimes(1);+ expect(mocks.updateComment.mock.calls[0][0].body).toContain('⏸ Auto-fix off');+ });++ it('posts nothing when Auto-fix changes on a pull request without a comment', async () => {+ const row = await linked();+ await control().onAutoFixChanged(row.id);+ expect(mocks.postComment).not.toHaveBeenCalled();+ expect(mocks.updateComment).not.toHaveBeenCalled();+ });+});+describe('ScmControlService — the tracking comment in GitHub', () => {const bindAndOpen = async (extra: Record<string, unknown>) => {const topic = await createTopic();diff --git a/apps/server/src/services/scm/__tests__/trackingComment.test.ts b/apps/server/src/services/scm/__tests__/trackingComment.test.tsindex 5724b1f263d..b18ee9e74cd 100644--- a/apps/server/src/services/scm/__tests__/trackingComment.test.ts+++ b/apps/server/src/services/scm/__tests__/trackingComment.test.ts@@ -71,6 +71,30 @@ describe('tracking comment', () => {expect(body).toContain('| — | — | — | — | Jan 5, 2026 12:07am |');});+ it('says Auto-fix is off in the headline and the Notifications cell', () => {+ const on = buildTrackingComment({ marker, updatedAt: new Date('2026-01-05T00:07:00Z') });+ expect(on).toContain('failing checks and review feedback reach the agent that opened it');+ expect(on).not.toContain('Auto-fix off');++ const off = buildTrackingComment({+ autoFix: false,+ marker,+ notification: { count: 2, max: 3, reason: 'ci_failed' },+ updatedAt: new Date('2026-01-05T00:07:00Z'),+ });+ expect(off).toContain(+ 'Auto-fix is off, so failing checks and review feedback do not wake the agent',+ );+ expect(off).toContain('| — | — | — | ⏸ Auto-fix off · 2/3 · CI failed | Jan 5, 2026 12:07am |');++ const offNeverWoken = buildTrackingComment({+ autoFix: false,+ marker,+ updatedAt: new Date('2026-01-05T00:07:00Z'),+ });+ expect(offNeverWoken).toContain('| — | — | — | ⏸ Auto-fix off | Jan 5, 2026 12:07am |');+ });+it('formats UTC the way the Updated column expects', () => {expect(formatUtc(new Date('2026-09-20T00:00:00Z'))).toBe('Sep 20, 2026 12:00am');expect(formatUtc(new Date('2026-09-20T12:30:00Z'))).toBe('Sep 20, 2026 12:30pm');diff --git a/apps/server/src/services/scm/trackingComment.ts b/apps/server/src/services/scm/trackingComment.tsindex e8d8ac39eaf..90920cee3f6 100644--- a/apps/server/src/services/scm/trackingComment.ts+++ b/apps/server/src/services/scm/trackingComment.ts@@ -84,6 +84,8 @@ const label = (text: string) => cell(text.replaceAll(/[\\[\]()*_`~<>]/g, String.export interface TrackingCommentInput {acceptance?: { id: string; status: AcceptanceStatus; url: string } | null;+ /** The pull request's Auto-fix switch; `false` means nobody is woken. Defaults to on. */+ autoFix?: boolean;conversation?: { title?: string | null; url: string } | null;marker: TrackingCommentMarker;/** How often the agent has been notified about this pull request, and why last. */@@ -92,26 +94,32 @@ export interface TrackingCommentInput {}export const buildTrackingComment = (input: TrackingCommentInput): string => {- const { acceptance, conversation, marker, notification, updatedAt } = input;+ const { acceptance, autoFix = true, conversation, marker, notification, updatedAt } = input;const acceptanceCell = acceptance ? `[${acceptance.id.slice(0, 8)}](${acceptance.url})` : '—';const statusCell = acceptance ? (ACCEPTANCE_STATUS[acceptance.status] ?? acceptance.status) : '—';const conversationCell = conversation? `[${label(conversation.title?.trim() || 'Open conversation')} ↗︎](${conversation.url})`: '—';- const notificationCell =+ const countCell =notification && notification.count > 0? `${notification.count}/${notification.max}${notification.reason? ` · ${NOTIFICATION_REASON[notification.reason] ?? notification.reason}`: ''}`- : '—';+ : null;+ const notificationCell = autoFix+ ? (countCell ?? '—')+ : `⏸ Auto-fix off${countCell ? ` · ${countCell}` : ''}`;+ const loop = autoFix+ ? 'failing checks and review feedback reach the agent that opened it'+ : 'Auto-fix is off, so failing checks and review feedback do not wake the agent';return [encodeTrackingMarker(marker),'',- `**${BRANDING_NAME} is tracking this pull request.** Merging accepts the delivery; failing checks and review feedback reach the agent that opened it. [Learn more ↗︎](${GITHUB_INTEGRATION_DOCS_URL})`,+ `**${BRANDING_NAME} is tracking this pull request.** Merging accepts the delivery; ${loop}. [Learn more ↗︎](${GITHUB_INTEGRATION_DOCS_URL})`,'','| Acceptance | Status | Conversation | Notifications | Updated (UTC) |','| :--- | :--- | :--- | :--- | :--- |',diff --git a/apps/server/src/services/workRegistration/topicPullRequests.test.ts b/apps/server/src/services/workRegistration/topicPullRequests.test.tsindex 7ec91d0a946..b9cac75a2a6 100644--- a/apps/server/src/services/workRegistration/topicPullRequests.test.ts+++ b/apps/server/src/services/workRegistration/topicPullRequests.test.ts@@ -19,8 +19,13 @@ vi.mock('@/database/models/scm', () => ({}));const db = {} as any;-const topicModelWith = (pullRequests?: unknown) =>- ({ findById: vi.fn(async () => ({ metadata: pullRequests ? { pullRequests } : {} })) }) as any;+const topicModelWith = (pullRequests?: unknown, visibleTopics: Record<string, unknown>[] = []) =>+ ({+ findById: vi.fn(async () => ({ metadata: pullRequests ? { pullRequests } : {} })),+ findByIds: vi.fn(async (ids: string[]) =>+ visibleTopics.filter((topic) => ids.includes(topic.id as string)),+ ),+ }) as any;const workItem = (number: number, repoFullName = 'lobehub/lobehub') => ({identifier: `${repoFullName}#${number}`,@@ -45,14 +50,18 @@ describe('listTopicPullRequestsWithStatus', () => {listByIdentities.mockResolvedValue([{ciStatus: 'failure',+ id: 'scr-1',isDraft: false,mergedAt: null,+ metadata: {},number: 1,repoFullName: 'LobeHub/LobeHub',reviewDecision: 'approved',state: 'open',title: 'From the App',+ topicId: 't1',updatedAt,+ wakeCount: 1,},]);@@ -70,6 +79,14 @@ describe('listTopicPullRequestsWithStatus', () => {{ number: 2, repoFullName: 'lobehub/lobehub' },]);expect(items[0].scm).toEqual({+ autoFix: {+ changeRequestId: 'scr-1',+ enabled: true,+ maxWakes: 3,+ ownerTopic: null,+ ownerTopicId: 't1',+ wakeCount: 1,+ },ciStatus: 'failure',isDraft: false,mergedAt: null,@@ -82,6 +99,56 @@ describe('listTopicPullRequestsWithStatus', () => {expect(items.every((item) => item.vouched)).toBe(true);});+ 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 row = (number: number, extra: Record<string, unknown>) => ({+ id: `scr-${number}`,+ isDraft: false,+ metadata: {},+ number,+ repoFullName: 'lobehub/lobehub',+ state: 'open',+ topicId: null,+ updatedAt: new Date(),+ wakeCount: 0,+ ...extra,+ });+ listByIdentities.mockResolvedValue([+ row(1, { metadata: { autoFix: false }, topicId: 'other' }),+ row(2, { topicId: 'hidden' }),+ row(3, {}),+ ]);+ const topicModel = topicModelWith(undefined, [+ { agentId: 'agt-2', id: 'other', title: 'Other conversation' },+ ]);++ const items = await listTopicPullRequestsWithStatus({+ db,+ topicId: 't1',+ topicModel,+ userId: 'u1',+ workModel,+ });++ expect(topicModel.findByIds).toHaveBeenCalledWith(['other', 'hidden']);+ expect(items.map((item) => item.scm?.autoFix)).toEqual([+ {+ changeRequestId: 'scr-1',+ enabled: false,+ maxWakes: 3,+ ownerTopic: { agentId: 'agt-2', id: 'other', title: 'Other conversation' },+ ownerTopicId: 'other',+ wakeCount: 0,+ },+ // Woken elsewhere, but not a conversation this viewer can open.+ expect.objectContaining({ enabled: true, ownerTopic: null, ownerTopicId: 'hidden' }),+ // Tracked, but no conversation to wake.+ expect.objectContaining({ ownerTopic: null, ownerTopicId: null }),+ ]);+ });+it('adds the topic links, hides removed PRs, and keeps the latest link first', async () => {listByIdentities.mockResolvedValue([]);const workModel = {diff --git a/apps/server/src/services/workRegistration/topicPullRequests.ts b/apps/server/src/services/workRegistration/topicPullRequests.tsindex 1679ce87eca..e8de15f278c 100644--- a/apps/server/src/services/workRegistration/topicPullRequests.ts+++ b/apps/server/src/services/workRegistration/topicPullRequests.ts@@ -1,4 +1,5 @@import type {+ ScmChangeRequestMetadata,ScmChangeRequestSnapshot,ScmCiStatus,ScmReviewDecision,@@ -14,6 +15,7 @@ import { ScmChangeRequestModel } from '@/database/models/scm';import type { TopicModel } from '@/database/models/topic';import { parseGitPushResult, type WorkModel } from '@/database/models/work';import type { LobeChatDatabase } from '@/database/type';+import { SCM_MAX_WAKES } from '@/server/services/scm/limits';import {createShellPullRequestLinking,@@ -33,11 +35,28 @@ type ScmChangeRequestState = Pick<'isDraft' | 'mergedAt' | 'number' | 'repoFullName' | 'state' | 'title'> & {ciStatus?: ScmCiStatus | null;+ id: string;+ metadata?: ScmChangeRequestMetadata | null;reviewDecision?: ScmReviewDecision | null;+ topicId?: string | null;updatedAt: Date;+ wakeCount: number;};-const toScmState = (row: ScmChangeRequestState): TopicPullRequestScmState => ({+type OwnerTopic = TopicPullRequestScmState['autoFix']['ownerTopic'];++const toScmState = (+ row: ScmChangeRequestState,+ ownerTopic: OwnerTopic,+): TopicPullRequestScmState => ({+ autoFix: {+ changeRequestId: row.id,+ enabled: row.metadata?.autoFix !== false,+ maxWakes: SCM_MAX_WAKES,+ ownerTopic,+ ownerTopicId: row.topicId ?? null,+ wakeCount: row.wakeCount,+ },ciStatus: row.ciStatus ?? null,isDraft: row.isDraft ?? false,mergedAt: row.mergedAt ?? null,@@ -70,7 +89,9 @@ const toLinkItem = (link: TopicPullRequestLinkMeta): TopicPullRequestWork | null* 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* confirmed here": the client then asks the execution device, and only- * confirmed, vouched data may enable merge / close.+ * 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.*/export const listTopicPullRequestsWithStatus = async (params: {db: LobeChatDatabase;@@ -109,9 +130,23 @@ export const listTopicPullRequestsWithStatus = async (params: {);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) => [+ 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));- return { ...item, scm: row ? toScmState(row) : null, vouched };+ const ownerTopic = row?.topicId ? (otherTopics.get(row.topicId) ?? null) : null;+ return { ...item, scm: row ? toScmState(row, ownerTopic) : null, vouched };});};diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex f58577408bd..85453247cf1 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -3745,6 +3745,18 @@"workingPanel.overview.ports.revoked": "Sharing stopped","workingPanel.overview.ports.title": "Ports","workingPanel.overview.ports.unavailable": "Can't read this device's ports right now",+ "workingPanel.overview.pr.autoFix": "Auto-fix",+ "workingPanel.overview.pr.autoFix.capped": "Notified the agent {{count}}/{{max}} times, the limit. Turn it off and on again to allow more",+ "workingPanel.overview.pr.autoFix.desc": "Notify the agent on CI failures and review feedback",+ "workingPanel.overview.pr.autoFix.disableFailed": "Couldn't turn off Auto-fix for {{name}}",+ "workingPanel.overview.pr.autoFix.enableFailed": "Couldn't turn on Auto-fix for {{name}}",+ "workingPanel.overview.pr.autoFix.noApp": "Install the LobeHub GitHub App on this repository to use Auto-fix",+ "workingPanel.overview.pr.autoFix.openOwner": "Go to that topic",+ "workingPanel.overview.pr.autoFix.otherTopic": "Notifies the agent in the topic \"{{title}}\"",+ "workingPanel.overview.pr.autoFix.otherTopicHidden": "Notifies the agent in another topic",+ "workingPanel.overview.pr.autoFix.resetOnEnable": "Notified the agent {{count}}/{{max}} times. Turning it on starts the count over",+ "workingPanel.overview.pr.autoFix.unlinked": "No topic is linked for it to notify",+ "workingPanel.overview.pr.autoFix.woken": "Notified the agent {{count}}/{{max}} times","workingPanel.overview.pr.dismiss": "Remove from this topic","workingPanel.overview.pr.dismissFailed": "Couldn't remove {{name}} from this topic","workingPanel.overview.pr.dismissed": "Removed {{name}} from this topic",@@ -3754,6 +3766,7 @@"workingPanel.overview.pr.linkInvalid": "Paste a GitHub pull request link, like https://github.com/owner/repo/pull/123","workingPanel.overview.pr.linkPlaceholder": "Paste a GitHub pull request link","workingPanel.overview.pr.linked": "Linked {{name}} to this topic",+ "workingPanel.overview.pr.menu": "More actions","workingPanel.overview.pr.unvouched": "Can't confirm this PR comes from this topic's branch, so merging and closing are locked","workingPanel.overview.subagents": "Subagents","workingPanel.overview.subtopics": "Subtopics",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 9344d26b8cc..90be49bd14f 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -3745,6 +3745,18 @@"workingPanel.overview.ports.revoked": "已停止共享","workingPanel.overview.ports.title": "端口","workingPanel.overview.ports.unavailable": "暂时无法读取这台设备的端口",+ "workingPanel.overview.pr.autoFix": "自动修复",+ "workingPanel.overview.pr.autoFix.capped": "已通知智能体 {{count}}/{{max}} 次,达到上限。关闭后重新开启即可继续",+ "workingPanel.overview.pr.autoFix.desc": "CI 失败或收到评审反馈时通知智能体",+ "workingPanel.overview.pr.autoFix.disableFailed": "未能为 {{name}} 关闭自动修复",+ "workingPanel.overview.pr.autoFix.enableFailed": "未能为 {{name}} 开启自动修复",+ "workingPanel.overview.pr.autoFix.noApp": "在这个仓库安装 LobeHub GitHub App 后才能使用自动修复",+ "workingPanel.overview.pr.autoFix.openOwner": "前往该话题",+ "workingPanel.overview.pr.autoFix.otherTopic": "通知的是话题「{{title}}」中的智能体",+ "workingPanel.overview.pr.autoFix.otherTopicHidden": "通知的是另一个话题中的智能体",+ "workingPanel.overview.pr.autoFix.resetOnEnable": "已通知智能体 {{count}}/{{max}} 次,重新开启后重新计数",+ "workingPanel.overview.pr.autoFix.unlinked": "没有关联可通知的话题",+ "workingPanel.overview.pr.autoFix.woken": "已通知智能体 {{count}}/{{max}} 次","workingPanel.overview.pr.dismiss": "从话题中移除","workingPanel.overview.pr.dismissFailed": "未能将 {{name}} 从话题中移除","workingPanel.overview.pr.dismissed": "已将 {{name}} 从话题中移除",@@ -3754,6 +3766,7 @@"workingPanel.overview.pr.linkInvalid": "请粘贴 GitHub PR 链接,例如 https://github.com/owner/repo/pull/123","workingPanel.overview.pr.linkPlaceholder": "粘贴 GitHub PR 链接","workingPanel.overview.pr.linked": "已将 {{name}} 关联到话题",+ "workingPanel.overview.pr.menu": "更多操作","workingPanel.overview.pr.unvouched": "无法确认这个 PR 来自本话题的分支,合并和关闭已锁定","workingPanel.overview.subagents": "子代理","workingPanel.overview.subtopics": "子话题",diff --git a/packages/database/src/models/scm/__tests__/changeRequest.autoFix.test.ts b/packages/database/src/models/scm/__tests__/changeRequest.autoFix.test.tsnew file mode 100644index 00000000000..53e18a6eb52--- /dev/null+++ b/packages/database/src/models/scm/__tests__/changeRequest.autoFix.test.ts@@ -0,0 +1,147 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { scmChangeRequests, topics, users, workspaces } from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import { ScmChangeRequestModel } from '../changeRequest';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'scm-autofix-user';+const otherUserId = 'scm-autofix-other';+const topicId = 'scm-autofix-topic';+const workspaceId = 'scm-autofix-workspace';++const snapshot = {+ headSha: '4'.repeat(40),+ number: 11,+ provider: 'github' as const,+ repoFullName: 'lobehub/lobehub',+ state: 'open' as const,+ url: 'https://github.com/lobehub/lobehub/pull/11',+ userId,+};++const personal = { userId };++beforeEach(async () => {+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+ await serverDB.insert(topics).values({ id: topicId, userId });+ await serverDB+ .insert(workspaces)+ .values({ id: workspaceId, name: workspaceId, primaryOwnerId: userId, slug: workspaceId });+});++afterEach(async () => {+ await serverDB.delete(scmChangeRequests);+ await serverDB.delete(topics);+ await serverDB.delete(workspaces);+ await serverDB.delete(users);+});++const linkedRow = () => ScmChangeRequestModel.upsert(serverDB, { ...snapshot, links: { topicId } });++describe('ScmChangeRequestModel.setAutoFix', () => {+ it('turns Auto-fix off without touching the rest of the metadata', async () => {+ const row = await linkedRow();+ await ScmChangeRequestModel.reserveWake(serverDB, row.id, 3, 'ci_failed');+ await serverDB+ .update(scmChangeRequests)+ .set({ metadata: { ...row.metadata, lobehubCommentId: 'c-1' } })+ .where(eq(scmChangeRequests.id, row.id));++ expect(await ScmChangeRequestModel.setAutoFix(serverDB, personal, row.id, false)).toEqual({+ autoFix: false,+ wakeCount: 1,+ });++ const after = await ScmChangeRequestModel.findById(serverDB, row.id);+ expect(after?.metadata.autoFix).toBe(false);+ expect(after?.metadata.lobehubCommentId).toBe('c-1');+ // Turning it off is not a reset: the count only restarts when it comes back on.+ expect(after?.wakeCount).toBe(1);+ });++ it('drops a held wake when turned off, so the opt-out is never followed by a run', async () => {+ const row = await linkedRow();+ await ScmChangeRequestModel.markPendingWake(serverDB, row.id, 'ci_failed');++ await ScmChangeRequestModel.setAutoFix(serverDB, personal, row.id, false);++ const after = await ScmChangeRequestModel.findById(serverDB, row.id);+ expect(after?.metadata.pendingWake).toBeUndefined();+ });++ it('starts the wake count over only when Auto-fix comes back on from off', async () => {+ const row = await linkedRow();+ for (let i = 0; i < 3; i++) {+ await ScmChangeRequestModel.reserveWake(serverDB, row.id, 3, 'ci_failed');+ }++ // Already on (absent): enabling again keeps the count.+ expect(await ScmChangeRequestModel.setAutoFix(serverDB, personal, row.id, true)).toEqual({+ autoFix: true,+ wakeCount: 3,+ });++ await ScmChangeRequestModel.setAutoFix(serverDB, personal, row.id, false);+ expect(await ScmChangeRequestModel.setAutoFix(serverDB, personal, row.id, true)).toEqual({+ autoFix: true,+ wakeCount: 0,+ });+ // The cap applies again from zero.+ expect(await ScmChangeRequestModel.reserveWake(serverDB, row.id, 3, 'ci_failed')).toBe(1);+ });++ it('refuses a row the scope does not own', async () => {+ const row = await linkedRow();++ expect(+ await ScmChangeRequestModel.setAutoFix(serverDB, { userId: otherUserId }, row.id, false),+ ).toBeNull();+ // The workspace is not the personal row's tenant either.+ expect(+ await ScmChangeRequestModel.setAutoFix(serverDB, { userId, workspaceId }, row.id, false),+ ).toBeNull();+ expect((await ScmChangeRequestModel.findById(serverDB, row.id))?.metadata.autoFix).toBe(+ undefined,+ );+ });++ it('lets any member of the owning workspace scope write it', async () => {+ const row = await ScmChangeRequestModel.upsert(serverDB, { ...snapshot, workspaceId });++ expect(+ await ScmChangeRequestModel.setAutoFix(+ serverDB,+ { userId: otherUserId, workspaceId },+ row.id,+ false,+ ),+ ).toEqual({ autoFix: false, wakeCount: 0 });+ });++ it('refuses to reserve a wake while Auto-fix is off', async () => {+ const row = await linkedRow();+ await ScmChangeRequestModel.setAutoFix(serverDB, personal, row.id, false);++ expect(await ScmChangeRequestModel.reserveWake(serverDB, row.id, 3, 'ci_failed')).toBeNull();+ expect((await ScmChangeRequestModel.findById(serverDB, row.id))?.wakeCount).toBe(0);++ await ScmChangeRequestModel.setAutoFix(serverDB, personal, row.id, true);+ expect(await ScmChangeRequestModel.reserveWake(serverDB, row.id, 3, 'ci_failed')).toBe(1);+ });++ it('stops reporting a wake target while Auto-fix is off', async () => {+ const row = await linkedRow();+ const has = () => ScmChangeRequestModel.hasWakeTarget(serverDB, personal, topicId, 3);++ expect(await has()).toBe(true);+ await ScmChangeRequestModel.setAutoFix(serverDB, personal, row.id, false);+ expect(await has()).toBe(false);+ await ScmChangeRequestModel.setAutoFix(serverDB, personal, row.id, true);+ expect(await has()).toBe(true);+ });+});diff --git a/packages/database/src/models/scm/changeRequest.ts b/packages/database/src/models/scm/changeRequest.tsindex 98d85adb654..1b322beeae6 100644--- a/packages/database/src/models/scm/changeRequest.ts+++ b/packages/database/src/models/scm/changeRequest.ts@@ -338,6 +338,8 @@ export class ScmChangeRequestModel {eq(scmChangeRequests.state, 'open'),eq(scmChangeRequests.isDraft, false),lt(scmChangeRequests.wakeCount, maxWakes),+ // Auto-fix turned off for this pull request: nothing will wake it.+ sql`coalesce(${scmChangeRequests.metadata} ->> 'autoFix', '') <> 'false'`,ownedByScope(scope),),)@@ -945,8 +947,10 @@ export class ScmChangeRequestModel {* Redis there is no debounce, so two webhooks landing together both read* the same `wakeCount` and a read-modify-write would lose one increment.* A conditional `UPDATE … WHERE wake_count < max` lets exactly one of them- * through per remaining slot. Returns the new count, or `null` when the- * cap is already spent.+ * through per remaining slot. The same condition holds the pull request's+ * Auto-fix switch: a wake that read the row before the person turned it+ * off, and was still building its prompt, is refused here. Returns the+ * new count, or `null` when the cap is spent or Auto-fix is off.*/static reserveWake = async (db: LobeChatDatabase,@@ -971,7 +975,13 @@ export class ScmChangeRequestModel {updatedAt: now,wakeCount: sql`${scmChangeRequests.wakeCount} + 1`,})- .where(and(eq(scmChangeRequests.id, id), lt(scmChangeRequests.wakeCount, max)))+ .where(+ and(+ eq(scmChangeRequests.id, id),+ lt(scmChangeRequests.wakeCount, max),+ sql`coalesce(${scmChangeRequests.metadata} ->> 'autoFix', '') <> 'false'`,+ ),+ ).returning({ wakeCount: scmChangeRequests.wakeCount });return reserved?.wakeCount ?? null;@@ -1028,6 +1038,44 @@ export class ScmChangeRequestModel {.where(eq(scmChangeRequests.id, id));};+ /**+ * Turn Auto-fix on or off for one change request the scope owns — the+ * tenant whose conversation it wakes. Atomic on the metadata bag, like+ * every other writer here. Turning it off drops a wake the debounce window+ * is still holding, so an opt-out is never followed by a run; turning it+ * back on from off starts the wake count over, since the person asked the+ * agent to keep fixing. Returns `null` when the scope does not own the row.+ */+ static setAutoFix = async (+ db: LobeChatDatabase,+ scope: { userId: string; workspaceId?: string | null },+ id: string,+ enabled: boolean,+ ): Promise<{ autoFix: boolean; wakeCount: number } | null> => {+ const wasOff = sql`coalesce(${scmChangeRequests.metadata} ->> 'autoFix', '') = 'false'`;+ const flag = sql`${JSON.stringify({ autoFix: enabled })}::jsonb`;++ const [updated] = await db+ .update(scmChangeRequests)+ .set(+ enabled+ ? {+ metadata: sql`${scmChangeRequests.metadata} || ${flag}`,+ updatedAt: new Date(),+ wakeCount: sql`case when ${wasOff} then 0 else ${scmChangeRequests.wakeCount} end`,+ }+ : {+ metadata: sql`(${scmChangeRequests.metadata} - 'pendingWake') || ${flag}`,+ updatedAt: new Date(),+ },+ )+ .where(and(eq(scmChangeRequests.id, id), ownedByScope(scope)))+ .returning({ metadata: scmChangeRequests.metadata, wakeCount: scmChangeRequests.wakeCount });++ if (!updated) return null;+ return { autoFix: updated.metadata?.autoFix !== false, wakeCount: updated.wakeCount };+ };+/** Hand a reserved wake back when the run never started. */static releaseWake = async (db: LobeChatDatabase, id: string): Promise<void> => {await dbdiff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 97cd403361b..87e647da47e 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -3916,6 +3916,21 @@ export default {'workingPanel.overview.changes': 'Changes','workingPanel.overview.changes.none': 'No changes','workingPanel.overview.ci.failure': 'Failed',+ 'workingPanel.overview.pr.autoFix': 'Auto-fix',+ 'workingPanel.overview.pr.autoFix.capped':+ 'Notified the agent {{count}}/{{max}} times, the limit. Turn it off and on again to allow more',+ 'workingPanel.overview.pr.autoFix.desc': 'Notify the agent on CI failures and review feedback',+ 'workingPanel.overview.pr.autoFix.disableFailed': "Couldn't turn off Auto-fix for {{name}}",+ 'workingPanel.overview.pr.autoFix.enableFailed': "Couldn't turn on Auto-fix for {{name}}",+ 'workingPanel.overview.pr.autoFix.noApp':+ 'Install the LobeHub GitHub App on this repository to use Auto-fix',+ 'workingPanel.overview.pr.autoFix.openOwner': 'Go to that topic',+ 'workingPanel.overview.pr.autoFix.otherTopic': 'Notifies the agent in the topic "{{title}}"',+ 'workingPanel.overview.pr.autoFix.otherTopicHidden': 'Notifies the agent in another topic',+ 'workingPanel.overview.pr.autoFix.resetOnEnable':+ 'Notified the agent {{count}}/{{max}} times. Turning it on starts the count over',+ 'workingPanel.overview.pr.autoFix.unlinked': 'No topic is linked for it to notify',+ 'workingPanel.overview.pr.autoFix.woken': 'Notified the agent {{count}}/{{max}} times','workingPanel.overview.pr.dismiss': 'Remove from this topic','workingPanel.overview.pr.dismissFailed': "Couldn't remove {{name}} from this topic",'workingPanel.overview.pr.dismissed': 'Removed {{name}} from this topic',@@ -3926,6 +3941,7 @@ export default {'Paste a GitHub pull request link, like https://github.com/owner/repo/pull/123','workingPanel.overview.pr.linkPlaceholder': 'Paste a GitHub pull request link','workingPanel.overview.pr.linked': 'Linked {{name}} to this topic',+ 'workingPanel.overview.pr.menu': 'More actions','workingPanel.overview.pr.unvouched':"Can't confirm this PR comes from this topic's branch, so merging and closing are locked",'workingPanel.overview.ci.pending': 'Running',diff --git a/packages/types/src/scm.ts b/packages/types/src/scm.tsindex 24c0b851344..1d50d516819 100644--- a/packages/types/src/scm.ts+++ b/packages/types/src/scm.ts@@ -158,6 +158,12 @@ export interface ScmChangeRequestMetadata {[key: string]: unknown;/** Acceptance links parsed out of the change request body. */acceptanceIdsFromBody?: string[];+ /**+ * Per pull request Auto-fix: whether failing CI and review feedback wake+ * the agent of the linked conversation. Absent means on — the account's+ * `wakeOnCiFailure` / `wakeOnReview` switches still apply on top of it.+ */+ autoFix?: boolean;/*** Who is currently posting the tracking comment, as an ISO timestamp.* Taken atomically so concurrent deliveries cannot each post one; goesdiff --git a/packages/types/src/work.ts b/packages/types/src/work.tsindex f03188f77fe..838fd8f2253 100644--- a/packages/types/src/work.ts+++ b/packages/types/src/work.ts@@ -730,7 +730,24 @@ export interface TopicPullRequestWork {* when an installation the viewer can see tracks the repository — that is the* confirmed source; without it the client probes the execution device.*/+/**+ * The pull request's Auto-fix: whether its failing CI and review feedback+ * wake the agent of {@link ownerTopicId}. Only that conversation may switch it.+ */+export interface TopicPullRequestAutoFix {+ changeRequestId: string;+ enabled: boolean;+ /** Wakes allowed before Auto-fix stops on its own; turning it back on starts over. */+ maxWakes: number;+ /** The conversation it wakes, when it is not this one and the viewer can open it. */+ ownerTopic: { agentId: string | null; id: string; title: string | null } | null;+ /** The conversation it wakes; `null` when none is linked. */+ ownerTopicId: string | null;+ wakeCount: number;+}+export interface TopicPullRequestScmState {+ autoFix: TopicPullRequestAutoFix;ciStatus: 'failure' | 'pending' | 'success' | 'unknown' | null;isDraft: boolean;mergedAt: Date | null;diff --git a/src/features/Conversation/WorkingSidebar/Overview/PullRequestRow.tsx b/src/features/Conversation/WorkingSidebar/Overview/PullRequestRow.tsxindex 0ac1ebed78a..9e138a54934 100644--- a/src/features/Conversation/WorkingSidebar/Overview/PullRequestRow.tsx+++ b/src/features/Conversation/WorkingSidebar/Overview/PullRequestRow.tsx@@ -1,9 +1,9 @@import type { DeviceGitLinkedPullRequest } from '@lobechat/types';-import { ActionIcon, Icon, Tooltip } from '@lobehub/ui';+import { Icon, Tooltip } from '@lobehub/ui';import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';import * as stylex from '@stylexjs/stylex';-import { TriangleAlertIcon, XIcon } from 'lucide-react';-import { memo } from 'react';+import { TriangleAlertIcon } from 'lucide-react';+import { memo, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';import {@@ -18,9 +18,9 @@ import { OverviewRow, rowStyles } from './OverviewRow';import { sectionStyles } from './sectionStyles';interface PullRequestRowProps {+ /** Better Coding Experience: the row's "⋯" menu, after the CI pill. */+ actions?: ReactNode;onClick: () => void;- /** Better Coding Experience: remove the PR from the topic's lists. */- onDismiss?: () => void;pullRequest: DeviceGitLinkedPullRequest;/** Defaults to `#number title`. */tooltip?: string;@@ -30,7 +30,7 @@ interface PullRequestRowProps {/** One pull request under the repository card's Changes row: state, number, title, CI. */const PullRequestRow = memo<PullRequestRowProps>(- ({ onClick, onDismiss, pullRequest, tooltip, unvouched }) => {+ ({ actions, onClick, pullRequest, tooltip, unvouched }) => {const { t } = useTranslation('chat');const ciStatus = pullRequest.ciStatus;const ci = getCiVisual(ciStatus);@@ -67,18 +67,7 @@ const PullRequestRow = memo<PullRequestRowProps>(): null}</span>- {onDismiss && (- <ActionIcon- aria-label={t('workingPanel.overview.pr.dismiss')}- icon={XIcon}- size={'small'}- title={t('workingPanel.overview.pr.dismiss')}- onClick={(event) => {- event.stopPropagation();- onDismiss();- }}- />- )}+ {actions}</>}value={diff --git a/src/features/Conversation/WorkingSidebar/Overview/PullRequestRowMenu.tsx b/src/features/Conversation/WorkingSidebar/Overview/PullRequestRowMenu.tsxnew file mode 100644index 00000000000..6b84db40b20--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/Overview/PullRequestRowMenu.tsx@@ -0,0 +1,79 @@+import { AGENT_CHAT_TOPIC_URL } from '@lobechat/const';+import { ActionIcon, copyToClipboard, DropdownMenu, toast } from '@lobehub/ui';+import { EllipsisIcon } from 'lucide-react';+import { type MouseEvent } from 'react';+import { useTranslation } from 'react-i18next';++import type { TopicPullRequestView } from '@/features/TopicPullRequests/pullRequestView';+import { useQueryRoute } from '@/hooks/useQueryRoute';+import { openTrustedExternalUrl } from '@/utils/openTrustedExternalUrl';++import {+ buildPullRequestMenuItems,+ type PullRequestMenuTranslate,+ resolveAutoFixAvailability,+} from './pullRequestMenuItems';+import { useAutoFixToggle } from './useAutoFixToggle';++// The menu sits inside a clickable row, and React bubbles portal events+// through the component tree: without this, picking an item opens the PR too.+const stopRowClick = (event: MouseEvent) => event.stopPropagation();++interface PullRequestRowMenuProps {+ /** Remove the PR from this topic; the caller reports the outcome. */+ onDismiss?: () => void;+ /** The conversation the row is shown in. */+ topicId?: string | null;+ view: TopicPullRequestView;+}++/** Better Coding Experience: the "⋯" menu at the end of a topic's PR row. */+const PullRequestRowMenu = ({ onDismiss, topicId, view }: PullRequestRowMenuProps) => {+ const { t } = useTranslation('chat');+ const router = useQueryRoute();+ const availability = resolveAutoFixAvailability(view.autoFix, topicId);+ const name = `#${view.number}`;+ const autoFix = useAutoFixToggle({+ changeRequestId: availability.kind === 'own' ? availability.changeRequestId : undefined,+ onFailed: (enabled) =>+ toast.error(+ t(+ enabled+ ? 'workingPanel.overview.pr.autoFix.enableFailed'+ : 'workingPanel.overview.pr.autoFix.disableFailed',+ { name },+ ),+ ),+ topicId,+ });++ const items = buildPullRequestMenuItems({+ autoFixChecked: autoFix.pending,+ availability,+ onCopyLink: async () => {+ await copyToClipboard(view.url);+ toast.success(t('workingPanel.pr.menu.copied'));+ },+ onDismiss,+ onOpenOnGithub: () => openTrustedExternalUrl(view.url),+ onOpenOwnerTopic: (topic) => {+ if (topic.agentId) router.push(AGENT_CHAT_TOPIC_URL(topic.agentId, topic.id));+ },+ onToggleAutoFix: (enabled) => void autoFix.toggle(enabled),+ t: t as unknown as PullRequestMenuTranslate,+ });++ return (+ <DropdownMenu items={items} placement={'bottomRight'} popupProps={{ onClick: stopRowClick }}>+ <ActionIcon+ aria-label={t('workingPanel.overview.pr.menu')}+ icon={EllipsisIcon}+ size={'small'}+ title={t('workingPanel.overview.pr.menu')}+ onClick={stopRowClick}+ />+ </DropdownMenu>+ );+};++export default PullRequestRowMenu;diff --git a/src/features/Conversation/WorkingSidebar/Overview/__tests__/pullRequestMenuItems.test.ts b/src/features/Conversation/WorkingSidebar/Overview/__tests__/pullRequestMenuItems.test.tsnew file mode 100644index 00000000000..f34b1fdd5b4--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/Overview/__tests__/pullRequestMenuItems.test.ts@@ -0,0 +1,224 @@+import type { TopicPullRequestAutoFix } from '@lobechat/types';+import { describe, expect, it, vi } from 'vitest';++import {+ buildPullRequestMenuItems,+ describeAutoFix,+ type PullRequestMenuParams,+ resolveAutoFixAvailability,+} from '../pullRequestMenuItems';++const t = (key: string, options?: Record<string, unknown>) =>+ options ? `${key} ${JSON.stringify(options)}` : key;++const autoFix = (overrides: Partial<TopicPullRequestAutoFix> = {}): TopicPullRequestAutoFix => ({+ changeRequestId: 'scr-1',+ enabled: true,+ maxWakes: 3,+ ownerTopic: null,+ ownerTopicId: 'tpc-here',+ wakeCount: 0,+ ...overrides,+});++const handlers = () => ({+ onCopyLink: vi.fn(),+ onDismiss: vi.fn(),+ onOpenOnGithub: vi.fn(),+ onOpenOwnerTopic: vi.fn(),+ onToggleAutoFix: vi.fn(),+});++const build = (overrides: Partial<PullRequestMenuParams> = {}) =>+ buildPullRequestMenuItems({+ availability: resolveAutoFixAvailability(autoFix(), 'tpc-here'),+ ...handlers(),+ t,+ ...overrides,+ });++const flatten = (items: ReturnType<typeof build>): any[] =>+ items.flatMap((item: any) => (item?.type === 'group' ? [item, ...item.children] : [item]));++const byKey = (items: ReturnType<typeof build>, key: string) =>+ flatten(items).find((item) => item && 'key' in item && item.key === key);++const keysOf = (items: ReturnType<typeof build>) =>+ items.map((item: any) =>+ item?.type === 'group'+ ? item.children.map((child: any) => child.key)+ : (item?.key ?? item?.type),+ );++describe('resolveAutoFixAvailability', () => {+ it('is switchable only from the conversation it wakes', () => {+ expect(resolveAutoFixAvailability(autoFix({ wakeCount: 2 }), 'tpc-here')).toEqual({+ changeRequestId: 'scr-1',+ enabled: true,+ kind: 'own',+ maxWakes: 3,+ wakeCount: 2,+ });+ });++ it('needs the GitHub App, a linked conversation, and that it is this one', () => {+ expect(resolveAutoFixAvailability(undefined, 'tpc-here')).toEqual({ kind: 'noApp' });+ expect(resolveAutoFixAvailability(autoFix({ ownerTopicId: null }), 'tpc-here')).toEqual({+ kind: 'unlinked',+ });+ const ownerTopic = { agentId: 'agt-2', id: 'tpc-other', title: 'Other' };+ expect(+ resolveAutoFixAvailability(autoFix({ ownerTopic, ownerTopicId: 'tpc-other' }), 'tpc-here'),+ ).toEqual({ kind: 'otherTopic', ownerTopic });+ // A new conversation has no topic yet: whatever the PR wakes, it is not this.+ expect(resolveAutoFixAvailability(autoFix(), undefined)).toMatchObject({+ kind: 'otherTopic',+ });+ });+});++describe('describeAutoFix', () => {+ const own = (enabled: boolean, wakeCount: number) =>+ resolveAutoFixAvailability(autoFix({ enabled, wakeCount }), 'tpc-here');++ it('explains what it does, then how far it has got', () => {+ expect(describeAutoFix(own(true, 0), t)).toBe('workingPanel.overview.pr.autoFix.desc');+ expect(describeAutoFix(own(true, 1), t)).toBe(+ 'workingPanel.overview.pr.autoFix.woken {"count":1,"max":3}',+ );+ expect(describeAutoFix(own(true, 3), t)).toBe(+ 'workingPanel.overview.pr.autoFix.capped {"count":3,"max":3}',+ );+ // Off with wakes spent: turning it on starts over.+ expect(describeAutoFix(own(false, 3), t)).toBe(+ 'workingPanel.overview.pr.autoFix.resetOnEnable {"count":3,"max":3}',+ );+ });++ it('says why it cannot be switched here', () => {+ expect(describeAutoFix({ kind: 'noApp' }, t)).toBe('workingPanel.overview.pr.autoFix.noApp');+ expect(describeAutoFix({ kind: 'unlinked' }, t)).toBe(+ 'workingPanel.overview.pr.autoFix.unlinked',+ );+ expect(+ describeAutoFix(+ { kind: 'otherTopic', ownerTopic: { agentId: 'a', id: 'tpc-2', title: ' Fix CI ' } },+ t,+ ),+ ).toBe('workingPanel.overview.pr.autoFix.otherTopic {"title":"Fix CI"}');+ // Not one the viewer can open, or untitled: no name to give.+ expect(describeAutoFix({ kind: 'otherTopic', ownerTopic: null }, t)).toBe(+ 'workingPanel.overview.pr.autoFix.otherTopicHidden',+ );+ expect(+ describeAutoFix(+ { kind: 'otherTopic', ownerTopic: { agentId: 'a', id: 'x', title: null } },+ t,+ ),+ ).toBe('workingPanel.overview.pr.autoFix.otherTopicHidden');+ });+});++describe('buildPullRequestMenuItems', () => {+ it('lists open, copy, Auto-fix and remove, with dividers between the groups', () => {+ const items = build();+ expect(keysOf(items)).toEqual([+ 'openOnGithub',+ 'copyLink',+ 'divider',+ ['autoFix'],+ 'divider',+ 'dismiss',+ ]);+ expect(byKey(items, 'dismiss')).toMatchObject({ danger: true });+ });++ it('puts the Auto-fix mark in the leading slot: alone in its group, with no icon beside it', () => {+ // lobe-ui moves a checkbox's mark to the right edge when its list also+ // holds items with icons; the Auto-fix group must hold only checkboxes.+ const ownerTopic = { agentId: 'agt-2', id: 'tpc-other', title: 'Other' };+ for (const availability of [+ resolveAutoFixAvailability(autoFix(), 'tpc-here'),+ resolveAutoFixAvailability(autoFix({ ownerTopic, ownerTopicId: 'tpc-other' }), 'tpc-here'),+ ]) {+ const group = build({ availability }).find((item: any) => item?.type === 'group') as any;+ expect(group.children).toHaveLength(1);+ expect(group.children[0]).toMatchObject({ key: 'autoFix', type: 'checkbox' });+ expect(group.children.some((child: any) => child.icon)).toBe(false);+ }+ });++ it('runs each handler from its item', () => {+ const h = handlers();+ const items = build(h);++ byKey(items, 'openOnGithub').onClick();+ byKey(items, 'copyLink').onClick();+ byKey(items, 'dismiss').onClick();+ byKey(items, 'autoFix').onCheckedChange(false);++ expect(h.onOpenOnGithub).toHaveBeenCalledTimes(1);+ expect(h.onCopyLink).toHaveBeenCalledTimes(1);+ expect(h.onDismiss).toHaveBeenCalledTimes(1);+ expect(h.onToggleAutoFix).toHaveBeenCalledWith(false);+ });++ it('shows the switch as last set, ahead of the server, and keeps the menu open', () => {+ const items = build({+ autoFixChecked: false,+ availability: resolveAutoFixAvailability(autoFix({ enabled: true }), 'tpc-here'),+ });+ expect(byKey(items, 'autoFix')).toMatchObject({+ checked: false,+ closeOnClick: false,+ disabled: false,+ type: 'checkbox',+ });+ expect(byKey(build(), 'autoFix').checked).toBe(true);+ });++ it('greys Auto-fix out without the GitHub App', () => {+ const items = build({ availability: { kind: 'noApp' } });+ expect(byKey(items, 'autoFix')).toMatchObject({+ checked: false,+ desc: 'workingPanel.overview.pr.autoFix.noApp',+ disabled: true,+ });+ expect(byKey(items, 'openOwnerTopic')).toBeUndefined();+ });++ it('greys Auto-fix out when it wakes another topic, and offers to go there', () => {+ const h = handlers();+ const ownerTopic = { agentId: 'agt-2', id: 'tpc-other', title: 'Other' };+ const items = build({+ ...h,+ availability: resolveAutoFixAvailability(+ autoFix({ enabled: true, ownerTopic, ownerTopicId: 'tpc-other' }),+ 'tpc-here',+ ),+ });++ // Its own on/off is not this topic's to show or change.+ expect(byKey(items, 'autoFix')).toMatchObject({+ checked: false,+ desc: 'workingPanel.overview.pr.autoFix.otherTopic {"title":"Other"}',+ disabled: true,+ });+ const keys = keysOf(items);+ expect(keys[keys.findIndex((key) => Array.isArray(key)) + 1]).toBe('openOwnerTopic');+ byKey(items, 'openOwnerTopic').onClick();+ expect(h.onOpenOwnerTopic).toHaveBeenCalledWith(ownerTopic);+ });++ it('offers no jump to a topic the viewer cannot open', () => {+ const items = build({ availability: { kind: 'otherTopic', ownerTopic: null } });+ expect(byKey(items, 'openOwnerTopic')).toBeUndefined();+ expect(byKey(items, 'autoFix').disabled).toBe(true);+ });++ it('leaves remove out where the row cannot be removed', () => {+ const items = build({ onDismiss: undefined });+ expect(byKey(items, 'dismiss')).toBeUndefined();+ expect(items.at(-1)).toMatchObject({ key: 'autoFixGroup', type: 'group' });+ });+});diff --git a/src/features/Conversation/WorkingSidebar/Overview/__tests__/useAutoFixToggle.test.ts b/src/features/Conversation/WorkingSidebar/Overview/__tests__/useAutoFixToggle.test.tsnew file mode 100644index 00000000000..82b16227bc2--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/Overview/__tests__/useAutoFixToggle.test.ts@@ -0,0 +1,93 @@+/**+ * @vitest-environment happy-dom+ */+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { scmKeys } from '@/libs/swr/keys';++import { useAutoFixToggle } from '../useAutoFixToggle';++const mocks = vi.hoisted(() => ({+ mutate: vi.fn(async () => undefined),+ refreshTopicPullRequests: vi.fn(async () => undefined),+ setChangeRequestAutoFix: vi.fn(async () => ({ autoFix: true, maxWakes: 3, wakeCount: 0 })),+}));++vi.mock('@/libs/swr', () => ({ mutate: mocks.mutate }));+vi.mock('@/services/scm', () => ({+ scmService: { setChangeRequestAutoFix: mocks.setChangeRequestAutoFix },+}));+vi.mock('@/services/work', () => ({+ workService: { refreshTopicPullRequests: mocks.refreshTopicPullRequests },+}));++const setup = (+ { changeRequestId }: { changeRequestId?: string } = { changeRequestId: 'scr-1' },+) => {+ const onFailed = vi.fn();+ const hook = renderHook(() => useAutoFixToggle({ changeRequestId, onFailed, topicId: 'tpc-1' }));+ return { hook, onFailed };+};++describe('useAutoFixToggle', () => {+ beforeEach(() => vi.clearAllMocks());++ it('saves, then refreshes the PR list and whether the open topic can be woken', async () => {+ const { hook, onFailed } = setup();++ await act(() => hook.result.current.toggle(true));++ expect(mocks.setChangeRequestAutoFix).toHaveBeenCalledWith({+ changeRequestId: 'scr-1',+ enabled: true,+ });+ expect(mocks.refreshTopicPullRequests).toHaveBeenCalledWith('tpc-1');+ // Without this, an idle open topic keeps its cached "nothing can wake me"+ // and misses the next GitHub wake until focus or remount.+ expect(mocks.mutate).toHaveBeenCalledWith(scmKeys.wakeTarget('tpc-1'));+ expect(onFailed).not.toHaveBeenCalled();+ expect(hook.result.current.pending).toBeUndefined();+ });++ it('shows the new state until the refreshed list carries it', async () => {+ let release!: () => void;+ mocks.refreshTopicPullRequests.mockImplementationOnce(+ () => new Promise<undefined>((resolve) => (release = () => resolve(undefined))),+ );+ const { hook } = setup();++ let done!: Promise<void>;+ act(() => {+ done = hook.result.current.toggle(false);+ });+ await vi.waitFor(() => expect(mocks.refreshTopicPullRequests).toHaveBeenCalled());+ expect(hook.result.current.pending).toBe(false);++ await act(async () => {+ release();+ await done;+ });+ expect(hook.result.current.pending).toBeUndefined();+ });++ it('puts the state back and reports a save that failed, refreshing nothing', async () => {+ mocks.setChangeRequestAutoFix.mockRejectedValueOnce(new Error('forbidden'));+ const { hook, onFailed } = setup();++ await act(() => hook.result.current.toggle(false));++ expect(onFailed).toHaveBeenCalledWith(false);+ expect(hook.result.current.pending).toBeUndefined();+ expect(mocks.refreshTopicPullRequests).not.toHaveBeenCalled();+ expect(mocks.mutate).not.toHaveBeenCalled();+ });++ it('does nothing where Auto-fix cannot be switched', async () => {+ const { hook } = setup({});++ await act(() => hook.result.current.toggle(true));++ expect(mocks.setChangeRequestAutoFix).not.toHaveBeenCalled();+ });+});diff --git a/src/features/Conversation/WorkingSidebar/Overview/index.tsx b/src/features/Conversation/WorkingSidebar/Overview/index.tsxindex 408160b5213..adf3da60d24 100644--- a/src/features/Conversation/WorkingSidebar/Overview/index.tsx+++ b/src/features/Conversation/WorkingSidebar/Overview/index.tsx@@ -59,6 +59,7 @@ import OverviewHeader from './OverviewHeader';import { ChevronRight, OverviewRow, PickerGlyph, rowStyles } from './OverviewRow';import PortSwitcher from './PortSwitcher';import PullRequestRow from './PullRequestRow';+import PullRequestRowMenu from './PullRequestRowMenu';import { sectionProps, sectionStyles } from './sectionStyles';import { TerminalRow } from './TerminalRow';@@ -302,21 +303,27 @@ const Overview = memo<OverviewProps>(pullRequest={toLinkedPullRequest(view)}tooltip={`${view.repoFullName}#${view.number} ${view.title}`}unvouched={!view.vouched}- onClick={() => onOpenPullRequest?.(view)}- onDismiss={- onDismissPullRequest &&- (() =>- void onDismissPullRequest(view).then(- () =>- toast.info(- t('workingPanel.overview.pr.dismissed', { name: `#${view.number}` }),- ),- () =>- toast.error(- t('workingPanel.overview.pr.dismissFailed', { name: `#${view.number}` }),- ),- ))+ actions={+ <PullRequestRowMenu+ topicId={topicId}+ view={view}+ onDismiss={+ onDismissPullRequest &&+ (() =>+ void onDismissPullRequest(view).then(+ () =>+ toast.info(+ t('workingPanel.overview.pr.dismissed', { name: `#${view.number}` }),+ ),+ () =>+ toast.error(+ t('workingPanel.overview.pr.dismissFailed', { name: `#${view.number}` }),+ ),+ ))+ }+ />}+ onClick={() => onOpenPullRequest?.(view)}/>))}{onLinkPullRequest && <LinkPullRequestRow onLink={onLinkPullRequest} />}diff --git a/src/features/Conversation/WorkingSidebar/Overview/pullRequestMenuItems.ts b/src/features/Conversation/WorkingSidebar/Overview/pullRequestMenuItems.tsnew file mode 100644index 00000000000..81c6ff477ce--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/Overview/pullRequestMenuItems.ts@@ -0,0 +1,187 @@+import type { TopicPullRequestAutoFix } from '@lobechat/types';+import type { DropdownItem } from '@lobehub/ui';+import { ExternalLinkIcon, LinkIcon, MessageSquareShareIcon, XIcon } from 'lucide-react';++type OwnerTopic = NonNullable<TopicPullRequestAutoFix['ownerTopic']>;++/**+ * What the PR row can do with Auto-fix, from the GitHub App's view of the PR+ * and the conversation the row sits in. Auto-fix wakes exactly one+ * conversation, so only that conversation may switch it.+ */+export type AutoFixAvailability =+ /** No GitHub App installation tracks the repository: nothing would wake anyone. */+ | { kind: 'noApp' }+ /** Tracked, but no conversation is linked for it to wake. */+ | { kind: 'unlinked' }+ /** It wakes another conversation — named when the viewer can open it. */+ | { kind: 'otherTopic'; ownerTopic: OwnerTopic | null }+ | {+ changeRequestId: string;+ enabled: boolean;+ kind: 'own';+ maxWakes: number;+ wakeCount: number;+ };++export const resolveAutoFixAvailability = (+ autoFix: TopicPullRequestAutoFix | undefined,+ topicId: string | null | undefined,+): AutoFixAvailability => {+ if (!autoFix) return { kind: 'noApp' };+ if (!autoFix.ownerTopicId) return { kind: 'unlinked' };+ if (autoFix.ownerTopicId !== topicId) {+ return { kind: 'otherTopic', ownerTopic: autoFix.ownerTopic };+ }+ return {+ changeRequestId: autoFix.changeRequestId,+ enabled: autoFix.enabled,+ kind: 'own',+ maxWakes: autoFix.maxWakes,+ wakeCount: autoFix.wakeCount,+ };+};++export type PullRequestMenuKey =+ | 'workingPanel.overview.pr.autoFix'+ | 'workingPanel.overview.pr.autoFix.capped'+ | 'workingPanel.overview.pr.autoFix.desc'+ | 'workingPanel.overview.pr.autoFix.noApp'+ | 'workingPanel.overview.pr.autoFix.otherTopic'+ | 'workingPanel.overview.pr.autoFix.otherTopicHidden'+ | 'workingPanel.overview.pr.autoFix.openOwner'+ | 'workingPanel.overview.pr.autoFix.resetOnEnable'+ | 'workingPanel.overview.pr.autoFix.unlinked'+ | 'workingPanel.overview.pr.autoFix.woken'+ | 'workingPanel.overview.pr.dismiss'+ | 'workingPanel.pr.menu.copyLink'+ | 'workingPanel.pr.menu.openOnGithub';++export type PullRequestMenuTranslate = (+ key: PullRequestMenuKey,+ options?: Record<string, unknown>,+) => string;++/** The line under Auto-fix: why it cannot be switched here, or how far it has got. */+export const describeAutoFix = (+ availability: AutoFixAvailability,+ t: PullRequestMenuTranslate,+): string => {+ switch (availability.kind) {+ case 'noApp': {+ return t('workingPanel.overview.pr.autoFix.noApp');+ }+ case 'unlinked': {+ return t('workingPanel.overview.pr.autoFix.unlinked');+ }+ case 'otherTopic': {+ const title = availability.ownerTopic?.title?.trim();+ return title+ ? t('workingPanel.overview.pr.autoFix.otherTopic', { title })+ : t('workingPanel.overview.pr.autoFix.otherTopicHidden');+ }+ case 'own': {+ const { enabled, maxWakes: max, wakeCount: count } = availability;+ if (count === 0) return t('workingPanel.overview.pr.autoFix.desc');+ // Turning it back on starts over; say so while that is what the switch would do.+ if (!enabled) return t('workingPanel.overview.pr.autoFix.resetOnEnable', { count, max });+ if (count >= max) return t('workingPanel.overview.pr.autoFix.capped', { count, max });+ return t('workingPanel.overview.pr.autoFix.woken', { count, max });+ }+ }+};++export interface PullRequestMenuParams {+ /** The switch as the person last set it, ahead of the server's answer. */+ autoFixChecked?: boolean;+ availability: AutoFixAvailability;+ onCopyLink: () => void;+ /** Remove the PR from this topic; absent where the row cannot be removed. */+ onDismiss?: () => void;+ onOpenOnGithub: () => void;+ onOpenOwnerTopic: (topic: OwnerTopic) => void;+ onToggleAutoFix: (enabled: boolean) => void;+ t: PullRequestMenuTranslate;+}++/**+ * The PR row's "⋯" menu: open, copy, Auto-fix, remove. Auto-fix is always+ * listed so the person learns it exists; where it cannot be switched here+ * the line under it says why — and, when it wakes another conversation the+ * viewer can open, the next item goes there.+ */+export const buildPullRequestMenuItems = ({+ availability,+ autoFixChecked,+ onCopyLink,+ onDismiss,+ onOpenOnGithub,+ onOpenOwnerTopic,+ onToggleAutoFix,+ t,+}: PullRequestMenuParams): DropdownItem[] => {+ const own = availability.kind === 'own';+ // A conversation without an agent has no address to go to.+ const ownerTopic =+ availability.kind === 'otherTopic' && availability.ownerTopic?.agentId+ ? availability.ownerTopic+ : null;++ return [+ {+ icon: ExternalLinkIcon,+ key: 'openOnGithub',+ label: t('workingPanel.pr.menu.openOnGithub'),+ onClick: onOpenOnGithub,+ },+ {+ icon: LinkIcon,+ key: 'copyLink',+ label: t('workingPanel.pr.menu.copyLink'),+ onClick: onCopyLink,+ },+ { type: 'divider' },+ {+ // A group of its own: in a list that also has icons, the menu moves a+ // checkbox's mark to the right edge; alone here it takes the leading+ // icon slot, where the other items show their icons.+ children: [+ {+ checked: own ? (autoFixChecked ?? availability.enabled) : false,+ // Stay open so the count under it visibly starts over.+ closeOnClick: false,+ desc: describeAutoFix(availability, t),+ disabled: !own,+ key: 'autoFix',+ label: t('workingPanel.overview.pr.autoFix'),+ onCheckedChange: onToggleAutoFix,+ type: 'checkbox',+ },+ ],+ key: 'autoFixGroup',+ type: 'group',+ },+ ...(ownerTopic+ ? [+ {+ icon: MessageSquareShareIcon,+ key: 'openOwnerTopic',+ label: t('workingPanel.overview.pr.autoFix.openOwner'),+ onClick: () => onOpenOwnerTopic(ownerTopic),+ },+ ]+ : []),+ ...(onDismiss+ ? [+ { type: 'divider' as const },+ {+ danger: true,+ icon: XIcon,+ key: 'dismiss',+ label: t('workingPanel.overview.pr.dismiss'),+ onClick: onDismiss,+ },+ ]+ : []),+ ];+};diff --git a/src/features/Conversation/WorkingSidebar/Overview/useAutoFixToggle.ts b/src/features/Conversation/WorkingSidebar/Overview/useAutoFixToggle.tsnew file mode 100644index 00000000000..738fde37298--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/Overview/useAutoFixToggle.ts@@ -0,0 +1,44 @@+import { useState } from 'react';++import { mutate } from '@/libs/swr';+import { scmKeys } from '@/libs/swr/keys';+import { scmService } from '@/services/scm';+import { workService } from '@/services/work';++/**+ * Switch a pull request's Auto-fix from the conversation it wakes. The new+ * state shows at once and holds until the refreshed list carries it (with+ * the reset count); a save that fails puts it back and calls `onFailed`.+ */+export const useAutoFixToggle = (params: {+ changeRequestId?: string;+ onFailed: (enabled: boolean) => void;+ topicId?: string | null;+}) => {+ const { changeRequestId, onFailed, topicId } = params;+ const [pending, setPending] = useState<boolean>();++ const toggle = async (enabled: boolean) => {+ if (!changeRequestId) return;+ setPending(enabled);+ try {+ await scmService.setChangeRequestAutoFix({ changeRequestId, enabled });+ } catch {+ setPending(undefined);+ onFailed(enabled);+ return;+ }+ try {+ await Promise.all([+ workService.refreshTopicPullRequests(topicId),+ // An idle open conversation polls for server-started runs only while+ // something can still wake it; turning Auto-fix on (or off) changes that.+ topicId ? mutate(scmKeys.wakeTarget(topicId)) : undefined,+ ]);+ } finally {+ setPending(undefined);+ }+ };++ return { pending, toggle };+};diff --git a/src/features/TopicPullRequests/pullRequestView.test.ts b/src/features/TopicPullRequests/pullRequestView.test.tsindex ef4a34c0231..e4e36055a00 100644--- a/src/features/TopicPullRequests/pullRequestView.test.ts+++ b/src/features/TopicPullRequests/pullRequestView.test.ts@@ -30,13 +30,29 @@ const detail = (overrides: Record<string, unknown> = {}) =>describe('resolvePullRequestView', () => {it('prefers the GitHub App state and marks it confirmed', () => {+ const autoFix = {+ changeRequestId: 'scr-1',+ enabled: false,+ maxWakes: 3,+ ownerTopic: null,+ ownerTopicId: 't1',+ wakeCount: 2,+ };const view = resolvePullRequestView(item(1, {- scm: { ciStatus: 'failure', isDraft: false, mergedAt: null, state: 'open', title: 'App' },+ scm: {+ autoFix,+ ciStatus: 'failure',+ isDraft: false,+ mergedAt: null,+ state: 'open',+ title: 'App',+ },}),{ confirmed: false, detail: detail() },);expect(view).toMatchObject({+ autoFix,ciStatus: 'failure',confirmed: true,state: 'open',@@ -56,6 +72,8 @@ describe('resolvePullRequestView', () => {detail: detail({ repo: { name: 'other', owner: 'x' } }),});expect(other).toMatchObject({ confirmed: false, state: 'open', title: 'PR 1' });+ // Auto-fix rides on the GitHub App's webhooks; without its row there is none.+ expect(other.autoFix).toBeUndefined();});it('falls back to the status the agent commands recorded', () => {diff --git a/src/features/TopicPullRequests/pullRequestView.ts b/src/features/TopicPullRequests/pullRequestView.tsindex c2bdcf952c3..bba730218cc 100644--- a/src/features/TopicPullRequests/pullRequestView.ts+++ b/src/features/TopicPullRequests/pullRequestView.ts@@ -2,6 +2,7 @@ import type {DeviceGitPullRequestCheck,DeviceGitPullRequestCiStatus,DeviceGitPullRequestDetail,+ TopicPullRequestAutoFix,TopicPullRequestItem,TopicPullRequestLinkSource,} from '@lobechat/types';@@ -15,6 +16,8 @@ import type { PullRequestState } from '@/features/AgentSidebar/Topic/List/Item/m* known), or the status the agent's own commands left on the Work row.*/export interface TopicPullRequestView {+ /** Present only when the GitHub App tracks the PR: Auto-fix needs its webhooks. */+ autoFix?: TopicPullRequestAutoFix;ciStatus?: DeviceGitPullRequestCiStatus;/** Confirmed by the GitHub App or by the device in this session. */confirmed: boolean;@@ -81,6 +84,7 @@ export const resolvePullRequestView = (if (item.scm) {return {...base,+ autoFix: item.scm.autoFix,ciStatus: item.scm.ciStatus ?? undefined,confirmed: true,isDraft: item.scm.isDraft,diff --git a/src/services/scm.ts b/src/services/scm.tsindex 02443343783..c60edd555df 100644--- a/src/services/scm.ts+++ b/src/services/scm.ts@@ -17,6 +17,10 @@ class ScmService {listInstallations = async () => lambdaClient.scm.listInstallations.query();listRepositories = async () => lambdaClient.scm.listRepositories.query();++ /** Turn a tracked pull request's Auto-fix on or off; back on starts the wake count over. */+ setChangeRequestAutoFix = async (params: { changeRequestId: string; enabled: boolean }) =>+ lambdaClient.scm.setChangeRequestAutoFix.mutate(params);}export const scmService = new ScmService();