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.

✨ feat(scm): close the loop — merge accepts the acceptance, CI failures and reviews wake the agent (#19728)

Arvin Xu11f36ddde790
diff --git a/apps/server/src/router-hono/webhooks/handlers/github.ts b/apps/server/src/router-hono/webhooks/handlers/github.ts
index 8997c85bb54..788cbb3fbd9 100644
--- a/apps/server/src/router-hono/webhooks/handlers/github.ts
+++ b/apps/server/src/router-hono/webhooks/handlers/github.ts
@@ -10,6 +10,7 @@ import {
normalizeGitHubEvent,
} from '@/server/services/scm/github/normalize';
import { verifyGitHubSignature } from '@/server/services/scm/github/signature';
+import { ScmControlService } from '@/server/services/scm/ScmControlService';
import { ScmIngestService } from '@/server/services/scm/ScmIngestService';
/**
@@ -80,7 +81,18 @@ export const githubWebhook = async (c: Context): Promise<Response> => {
const key = { deliveryId, provider: 'github' as const };
try {
const normalized = normalizeGitHubEvent(event, payload);
- const outcome = await new ScmIngestService(db).apply(normalized);
+ const ingest = new ScmIngestService(db);
+ const control = new ScmControlService(db);
+ ingest.onChangeRequestEvent = async (params) => {
+ const result = await control.handle(params);
+ log(
+ 'control %s -> %s %s',
+ params.kind,
+ result.outcome,
+ 'detail' in result ? (result.detail ?? '') : '',
+ );
+ };
+ const outcome = await ingest.apply(normalized);
await ScmWebhookDeliveryModel.settle(db, key, {
error: outcome.detail,
status: outcome.status,
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index b36f1787879..35788651591 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -669,6 +669,7 @@ export class AiAgentService {
botContext,
botSender,
createdThreadId,
+ externalOrigin,
clientIp,
userAgent,
deviceId: requestedDeviceId,
@@ -990,6 +991,7 @@ export class AiAgentService {
continuationAssistantId,
conversationAgentId,
createdThreadId,
+ externalOrigin,
cronJobId,
files,
modelOverride,
diff --git a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
index c77708daf51..f35f2167750 100644
--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
@@ -331,6 +331,7 @@ export interface TurnSetupInput {
conversationAgentId: string;
createdThreadId?: string;
cronJobId?: string;
+ externalOrigin?: InternalExecAgentParams['externalOrigin'];
files?: InternalExecAgentParams['files'];
modelOverride?: string;
operationTaskId?: string;
@@ -406,6 +407,7 @@ export const setupTurn = async (
continuationAssistantId,
conversationAgentId,
createdThreadId,
+ externalOrigin,
cronJobId,
files,
modelOverride,
@@ -657,6 +659,8 @@ export const setupTurn = async (
// Bot-channel turns are inserted under the OWNER's userId; keep the real
// platform author alongside so the UI can attribute the bubble correctly.
...(botSender ? { botSender } : undefined),
+ // A provider event that injected this turn keeps its source on the row.
+ ...(externalOrigin ? { externalOrigin } : undefined),
// A follow-up queued behind a running turn renders as that turn's
// continuation; the client's optimistic row is replaced by this one.
...(steer ? { steer: true as const } : undefined),
diff --git a/apps/server/src/services/aiAgent/types.ts b/apps/server/src/services/aiAgent/types.ts
index 65712b03963..a053f94b924 100644
--- a/apps/server/src/services/aiAgent/types.ts
+++ b/apps/server/src/services/aiAgent/types.ts
@@ -3,6 +3,7 @@ import type {
BotSenderMetadata,
ChatTopicBotContext,
ExecAgentParams,
+ ExternalOriginMetadata,
LobeAgentChatConfig,
RuntimeMentionedAgent,
UserInterventionConfig,
@@ -134,6 +135,12 @@ export interface InternalExecAgentParams extends ExecAgentParams {
* as well as activator-discoverable manifests.
*/
exclusivePluginIds?: string[];
+ /**
+ * Provider event that produced this server-injected turn (a GitHub CI
+ * failure waking the agent, …), persisted on the user message as
+ * `metadata.externalOrigin` so the bubble carries its source.
+ */
+ externalOrigin?: ExternalOriginMetadata;
/** External files to upload to S3 and attach to the user message */
files?: Array<{
/** Pre-downloaded buffer (from adapter/platform layer) */
diff --git a/apps/server/src/services/scm/ScmControlService.ts b/apps/server/src/services/scm/ScmControlService.ts
new file mode 100644
index 00000000000..6f583570cdb
--- /dev/null
+++ b/apps/server/src/services/scm/ScmControlService.ts
@@ -0,0 +1,550 @@
+import type { GithubIntegrationPreference } from '@lobechat/types';
+import { RequestTrigger, SCM_TRUSTED_ASSOCIATIONS } from '@lobechat/types';
+import debug from 'debug';
+import { eq } from 'drizzle-orm';
+
+import { isFailingCheck, ScmChangeRequestModel, ScmInstallationModel } from '@/database/models/scm';
+import { TopicModel } from '@/database/models/topic';
+import { UserModel } from '@/database/models/user';
+import type { ScmChangeRequestItem } from '@/database/schemas';
+import { acceptances, works, workspaces } from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
+import { appEnv } from '@/envs/app';
+import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';
+import { AiAgentService } from '@/server/services/aiAgent';
+import { AcceptanceService } from '@/server/services/verify/acceptanceService';
+
+import type { GitHubReviewFeedback } from './github/app';
+import {
+ fetchGitHubJobLogTail,
+ fetchGitHubReviewFeedback,
+ postGitHubPullRequestComment,
+ updateGitHubPullRequestComment,
+} from './github/app';
+import { buildTrackingComment } from './trackingComment';
+import type { ScmInboundEvent } from './types';
+import { buildCiFailurePrompt, buildReviewPrompt, type ScmWakeReason } from './wakePrompt';
+
+const log = debug('lobe-server:scm:control');
+
+/** Wakes per change request before the loop hands over to a human. */
+export const SCM_MAX_WAKES = 3;
+/** Window in which repeated events on one change request collapse into one wake. */
+const WAKE_DEBOUNCE_SECONDS = 60;
+/** How far back review feedback is collected for a wake. */
+const REVIEW_LOOKBACK_MS = 15 * 60 * 1000;
+
+/** The automation switch each wake reason answers to. */
+const WAKE_PREFERENCE: Record<ScmWakeReason, keyof GithubIntegrationPreference> = {
+ ci_failed: 'wakeOnCiFailure',
+ review_changes_requested: 'wakeOnReview',
+ review_commented: 'wakeOnReview',
+};
+
+export interface ScmControlEvent {
+ event: Extract<ScmInboundEvent, { type: 'change_request' | 'checks' | 'review' }>;
+ kind: string;
+ row: ScmChangeRequestItem;
+}
+
+export type ScmControlOutcome =
+ | { detail?: string; outcome: 'accepted'; acceptanceId: string }
+ | { commentId: string; outcome: 'commented'; updated: boolean }
+ | { detail?: string; outcome: 'skipped' }
+ | { operationId: string; outcome: 'woken'; reason: ScmWakeReason };
+
+/**
+ * The control half of the closed loop, plugged into
+ * `ScmIngestService.onChangeRequestEvent`. Two behaviours:
+ *
+ * - **opened / synchronized / …** → one tracking comment on the pull request,
+ * linking the acceptance and the conversation, rewritten in place as the
+ * loop moves.
+ * - **merged** → the linked acceptance is accepted (merging is the strongest
+ * signal a user can give) and the registered Work flips to merged. With
+ * stacked pull requests, every linked open PR must be merged or closed
+ * before the acceptance closes.
+ * - **ci_failed / review_changes_requested / review_commented** → the agent
+ * 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.
+ */
+export class ScmControlService {
+ constructor(private db: LobeChatDatabase) {}
+
+ handle = async (params: ScmControlEvent): Promise<ScmControlOutcome> => {
+ const outcome = await this.route(params);
+ // A failure the debounce window swallowed rides along with the next
+ // event, whatever that event was.
+ if (outcome.outcome !== 'woken') await this.flushPendingWake(params.row.id);
+ return outcome;
+ };
+
+ private route = async ({ event, kind, row }: ScmControlEvent): Promise<ScmControlOutcome> => {
+ switch (kind) {
+ case 'opened':
+ case 'ready_for_review':
+ case 'reopened':
+ case 'synchronized': {
+ return this.syncComment(row);
+ }
+ case 'merged': {
+ // The Work row mirrors what GitHub says about the pull request, so
+ // it follows the merge whatever the automation switches say; only
+ // the acceptance verdict is opt-out.
+ if (row.workId) {
+ await this.db.update(works).set({ status: 'merged' }).where(eq(works.id, row.workId));
+ }
+ if (!(await this.isEnabled(row, 'acceptOnMerge'))) {
+ return { detail: 'acceptOnMerge is off', outcome: 'skipped' };
+ }
+ const outcome = await this.onMerged(row);
+ await this.refreshComment(row.id);
+ return outcome;
+ }
+ case 'ci_failed': {
+ if (!(await this.isEnabled(row, WAKE_PREFERENCE[kind]))) {
+ return { detail: `${WAKE_PREFERENCE[kind]} is off`, outcome: 'skipped' };
+ }
+ return this.wakeAndRefresh(row, kind);
+ }
+ case 'review_changes_requested':
+ case 'review_commented': {
+ // A comment by the PR author (or the agent acting as them) is not
+ // feedback to act on.
+ if (event.type === 'review' && event.actor?.login === row.authorExternalLogin) {
+ return { detail: 'self comment', outcome: 'skipped' };
+ }
+ // Review text becomes the prompt of an unattended run with tools, so
+ // only someone the repository already trusts may steer it. Anyone
+ // else is still free to comment; their words just do not become
+ // instructions.
+ const association = event.type === 'review' ? event.actor?.association : undefined;
+ if (!association || !SCM_TRUSTED_ASSOCIATIONS.has(association)) {
+ return { detail: `reviewer is ${association ?? 'unknown'}`, outcome: 'skipped' };
+ }
+ if (!(await this.isEnabled(row, WAKE_PREFERENCE[kind]))) {
+ return { detail: `${WAKE_PREFERENCE[kind]} is off`, outcome: 'skipped' };
+ }
+ // The webhook already carries the text that triggered this wake, and
+ // it is the only copy we are sure of: the list endpoint can be rate
+ // limited, fail, or not show the review yet. Carry it along so the
+ // agent is never woken with "the review carried no text".
+ const trigger: GitHubReviewFeedback | undefined =
+ event.type === 'review' && event.review.body?.trim()
+ ? {
+ association,
+ author: event.actor?.login ?? 'unknown',
+ body: event.review.body,
+ line: event.review.line,
+ path: event.review.path,
+ submittedAt: event.occurredAt?.toISOString(),
+ url: event.review.url ?? undefined,
+ }
+ : undefined;
+ return this.wakeAndRefresh(row, kind, trigger);
+ }
+ default: {
+ return { detail: `${kind} needs no action`, outcome: 'skipped' };
+ }
+ }
+ };
+
+ /**
+ * The automation switches on Settings → Integrations → GitHub, read from
+ * the preference of the user who connected the installation. Absent means
+ * on: the closed loop is the default and the switch is the opt-out.
+ */
+ private isEnabled = async (
+ row: ScmChangeRequestItem,
+ key: keyof GithubIntegrationPreference,
+ ): Promise<boolean> => (await this.preference(row))?.[key] !== false;
+
+ private preference = async (
+ row: ScmChangeRequestItem,
+ ): Promise<GithubIntegrationPreference | undefined> =>
+ (await new UserModel(this.db, row.userId).getUserPreference())?.integration?.github;
+
+ // --------------- tracking comment ---------------
+
+ /**
+ * One comment per pull request, kept current: it links the acceptance it
+ * delivers and the conversation that opened it, and its status table is
+ * rewritten as the acceptance moves and the agent gets notified. Posted
+ * only when at least one link exists (a bare "tracked" comment says
+ * nothing) and only for the repository visibility the user allowed; once
+ * posted, later events update it in place.
+ */
+ private syncComment = async (row: ScmChangeRequestItem): Promise<ScmControlOutcome> => {
+ if (!row.acceptanceId && !row.topicId)
+ return { detail: 'no links to share', outcome: 'skipped' };
+ if (!row.installationId) return { detail: 'no installation', outcome: 'skipped' };
+ if (row.metadata.lobehubCommentId)
+ return this.updateComment(row, row.metadata.lobehubCommentId);
+
+ const isPrivate = row.metadata.repoPrivate;
+ if (isPrivate === undefined)
+ return { detail: 'repository visibility unknown', outcome: 'skipped' };
+ const key = isPrivate ? 'commentOnPrivateRepositories' : 'commentOnPublicRepositories';
+ const preference = await this.preference(row);
+ const allowed = isPrivate ? preference?.[key] !== false : preference?.[key] === true;
+ if (!allowed) return { detail: `${key} is off`, outcome: 'skipped' };
+
+ // `opened` and the `synchronize` that follows the first push arrive a
+ // second apart and are handled concurrently; the row each handler holds
+ // predates the other's write, so the claim decides who posts. It has to
+ // be the database's: posting is irreversible, and a Redis-less
+ // deployment would otherwise leave an orphan comment nothing updates.
+ if (!(await ScmChangeRequestModel.claimCommentSlot(this.db, row.id))) {
+ const fresh = await ScmChangeRequestModel.findById(this.db, row.id);
+ if (fresh?.metadata.lobehubCommentId)
+ return this.updateComment(fresh, fresh.metadata.lobehubCommentId);
+ return { detail: 'comment already in flight', outcome: 'skipped' };
+ }
+ const fresh = await ScmChangeRequestModel.findById(this.db, row.id);
+
+ const installationId = await this.providerInstallationId(row.installationId);
+ if (!installationId) {
+ await ScmChangeRequestModel.releaseCommentSlot(this.db, row.id);
+ return { detail: 'installation not found', outcome: 'skipped' };
+ }
+
+ const commentId = await postGitHubPullRequestComment({
+ body: await this.buildCommentBody(fresh ?? row),
+ installationId,
+ number: row.number,
+ repoFullName: row.repoFullName,
+ });
+ if (!commentId) {
+ await ScmChangeRequestModel.releaseCommentSlot(this.db, row.id);
+ return { detail: 'comment failed', outcome: 'skipped' };
+ }
+
+ await ScmChangeRequestModel.upsert(this.db, {
+ metadata: { lobehubCommentId: commentId },
+ number: row.number,
+ provider: row.provider,
+ repoFullName: row.repoFullName,
+ state: row.state,
+ url: row.url,
+ userId: row.userId,
+ workspaceId: row.workspaceId,
+ });
+ log('commented on %s#%d (%s)', row.repoFullName, row.number, commentId);
+ return { commentId, outcome: 'commented', updated: false };
+ };
+
+ private updateComment = async (
+ row: ScmChangeRequestItem,
+ commentId: string,
+ ): Promise<ScmControlOutcome> => {
+ if (!row.installationId) return { detail: 'no installation', outcome: 'skipped' };
+ const installationId = await this.providerInstallationId(row.installationId);
+ if (!installationId) return { detail: 'installation not found', outcome: 'skipped' };
+
+ const updated = await updateGitHubPullRequestComment({
+ body: await this.buildCommentBody(row),
+ commentId,
+ installationId,
+ repoFullName: row.repoFullName,
+ });
+ if (!updated) return { detail: 'comment update failed', outcome: 'skipped' };
+ log('updated comment %s on %s#%d', commentId, row.repoFullName, row.number);
+ return { commentId, outcome: 'commented', updated: true };
+ };
+
+ /** After a merge or a wake: re-read the row and rewrite the comment, if there is one. */
+ private refreshComment = async (rowId: string) => {
+ const fresh = await ScmChangeRequestModel.findById(this.db, rowId);
+ if (!fresh?.metadata.lobehubCommentId) return;
+ await this.updateComment(fresh, fresh.metadata.lobehubCommentId);
+ };
+
+ private buildCommentBody = async (row: ScmChangeRequestItem): Promise<string> => {
+ const origin = appEnv.APP_URL.replace(/\/$/, '');
+
+ let acceptance: {
+ id: string;
+ status: (typeof acceptances.$inferSelect)['status'];
+ url: string;
+ } | null = null;
+ if (row.acceptanceId) {
+ const [found] = await this.db
+ .select({ id: acceptances.id, status: acceptances.status })
+ .from(acceptances)
+ .where(eq(acceptances.id, row.acceptanceId));
+ if (found) acceptance = { ...found, url: `${origin}/acceptance/${found.id}` };
+ }
+
+ let conversation: { title?: string | null; url: string } | null = null;
+ if (row.topicId) {
+ const topic = await new TopicModel(
+ this.db,
+ row.userId,
+ row.workspaceId ?? undefined,
+ ).findById(row.topicId);
+ if (topic?.agentId) {
+ // A workspace agent only resolves under its workspace prefix; the
+ // acceptance link stays global.
+ const slug = row.workspaceId ? await this.workspaceSlug(row.workspaceId) : null;
+ conversation = {
+ title: topic.title,
+ url: `${origin}${slug ? `/${slug}` : ''}/agent/${topic.agentId}/${row.topicId}`,
+ };
+ }
+ }
+
+ return buildTrackingComment({
+ acceptance,
+ conversation,
+ marker: {
+ acceptanceId: row.acceptanceId ?? undefined,
+ changeRequestId: row.id,
+ provider: row.provider,
+ topicId: row.topicId ?? undefined,
+ v: 1,
+ },
+ notification:
+ row.wakeCount > 0
+ ? { count: row.wakeCount, max: SCM_MAX_WAKES, reason: row.metadata.lastWake?.reason }
+ : null,
+ updatedAt: new Date(),
+ });
+ };
+
+ // --------------- merge → accepted ---------------
+
+ private onMerged = async (row: ScmChangeRequestItem): Promise<ScmControlOutcome> => {
+ if (!row.acceptanceId) return { detail: 'no linked acceptance', outcome: 'skipped' };
+
+ // Stacked PRs: the acceptance closes when the last linked PR lands.
+ const siblings = await ScmChangeRequestModel.listByAcceptance(this.db, row.acceptanceId);
+ const pending = siblings.filter((s) => s.state === 'open');
+ if (pending.length > 0) {
+ return {
+ detail: `${pending.length} linked pull request(s) still open`,
+ outcome: 'skipped',
+ };
+ }
+
+ const service = new AcceptanceService(this.db, row.userId, row.workspaceId ?? undefined);
+ const accepted = await service.acceptFromScmMerge(row.acceptanceId, {
+ mergedByExternalId: row.mergedByExternalId ?? undefined,
+ number: row.number,
+ provider: row.provider,
+ repoFullName: row.repoFullName,
+ url: row.url,
+ });
+ if (!accepted) return { detail: 'acceptance no longer exists', outcome: 'skipped' };
+ return { acceptanceId: accepted.id, outcome: 'accepted' };
+ };
+
+ // --------------- CI / review → wake ---------------
+
+ private wakeAndRefresh = async (
+ row: ScmChangeRequestItem,
+ reason: ScmWakeReason,
+ trigger?: GitHubReviewFeedback,
+ ): Promise<ScmControlOutcome> => {
+ const outcome = await this.wake(row, reason, trigger);
+ if (outcome.outcome === 'woken') await this.refreshComment(row.id);
+ return outcome;
+ };
+
+ /**
+ * Deliver a wake the debounce window swallowed. Called after every event
+ * on a change request, so the last failure of a burst reaches the agent
+ * on the next delivery instead of waiting for an unrelated one. The wake
+ * itself re-reads the row, so the prompt carries every failing check by
+ * then — not just the one that was dropped.
+ */
+ private flushPendingWake = async (rowId: string): Promise<void> => {
+ const fresh = await ScmChangeRequestModel.findById(this.db, rowId);
+ const pending = fresh?.metadata.pendingWake;
+ if (!fresh || !pending) return;
+
+ const reason = pending.reason as ScmWakeReason;
+ // The marker outlives the window it was written in, and the user may
+ // have turned the automation off in between. `route()` guards the
+ // direct path; this one has to ask the same question, or an explicit
+ // opt-out would still be followed by a headless run.
+ const preference = WAKE_PREFERENCE[reason];
+ if (preference && !(await this.isEnabled(fresh, preference))) {
+ await ScmChangeRequestModel.clearPendingWake(this.db, rowId);
+ return;
+ }
+
+ const outcome = await this.wake(fresh, reason);
+ // Still inside the window: leave the marker for the next delivery.
+ if (outcome.outcome === 'skipped' && outcome.detail === 'debounced') return;
+
+ await ScmChangeRequestModel.clearPendingWake(this.db, rowId);
+ if (outcome.outcome === 'woken') await this.refreshComment(rowId);
+ };
+
+ private wake = async (
+ row: ScmChangeRequestItem,
+ reason: ScmWakeReason,
+ trigger?: GitHubReviewFeedback,
+ ): Promise<ScmControlOutcome> => {
+ 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' };
+ // 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) {
+ return { detail: `wake cap (${SCM_MAX_WAKES}) reached`, outcome: 'skipped' };
+ }
+ if (!(await this.claimWakeWindow(row.id))) {
+ // The burst is collapsed into the wake already in flight, but the
+ // prompt was built before this event landed. Remember it so the next
+ // delivery on this pull request carries it rather than dropping it.
+ await ScmChangeRequestModel.markPendingWake(this.db, row.id, reason);
+ return { detail: 'debounced', outcome: 'skipped' };
+ }
+
+ const topicModel = new TopicModel(this.db, row.userId, row.workspaceId ?? undefined);
+ const topic = await topicModel.findById(row.topicId);
+ if (!topic?.agentId) return { detail: 'conversation has no agent', outcome: 'skipped' };
+
+ const prompt = await this.buildPrompt(row, reason, trigger);
+ const running = Boolean(topic.metadata?.runningOperation);
+
+ // Take the slot before starting anything: the check above read a row
+ // 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.
+ const count = await ScmChangeRequestModel.reserveWake(this.db, row.id, SCM_MAX_WAKES, reason);
+ if (count === null) {
+ return { detail: `wake cap (${SCM_MAX_WAKES}) reached`, outcome: 'skipped' };
+ }
+
+ // A busy topic: execAgent's reservation retries briefly for the running
+ // turn to hand back (queued-steer semantics); if it does not, the wake is
+ // dropped and the next event tries again.
+ let operationId: string;
+ try {
+ const result = await new AiAgentService(this.db, row.userId, {
+ workspaceId: row.workspaceId ?? undefined,
+ }).execAgent({
+ agentId: topic.agentId,
+ appContext: { topicId: row.topicId },
+ autoStart: true,
+ externalOrigin: {
+ kind: reason,
+ label: `${row.repoFullName}#${row.number}`,
+ provider: row.provider,
+ resourceId: row.id,
+ url: row.url,
+ },
+ prompt,
+ steer: running,
+ trigger: RequestTrigger.Scm,
+ userInterventionConfig: { approvalMode: 'headless' },
+ });
+ operationId = result.operationId;
+ } catch (error) {
+ log('wake %s on %s failed: %O', reason, row.id, error);
+ await ScmChangeRequestModel.releaseWake(this.db, row.id);
+ return {
+ detail: `wake failed: ${error instanceof Error ? error.message : String(error)}`,
+ outcome: 'skipped',
+ };
+ }
+
+ log(
+ 'woke agent %s in topic %s for %s (%s#%d, wake %d/%d, op %s)',
+ topic.agentId,
+ row.topicId,
+ reason,
+ row.repoFullName,
+ row.number,
+ count,
+ SCM_MAX_WAKES,
+ operationId,
+ );
+ return { operationId, outcome: 'woken', reason };
+ };
+
+ private buildPrompt = async (
+ row: ScmChangeRequestItem,
+ reason: ScmWakeReason,
+ trigger?: GitHubReviewFeedback,
+ ) => {
+ if (reason === 'ci_failed') {
+ const logs: Record<string, string | null> = {};
+ if (row.installationId) {
+ const installationId = await this.providerInstallationId(row.installationId);
+ for (const check of row.checks ?? []) {
+ if (!isFailingCheck(check)) continue;
+ const jobId = check.externalId.startsWith('check_run:')
+ ? check.externalId.slice('check_run:'.length)
+ : null;
+ logs[check.externalId] =
+ installationId && jobId
+ ? await fetchGitHubJobLogTail({
+ installationId,
+ jobId,
+ repoFullName: row.repoFullName,
+ })
+ : null;
+ }
+ }
+ return buildCiFailurePrompt({ logs, row });
+ }
+
+ const installationId = row.installationId
+ ? await this.providerInstallationId(row.installationId)
+ : null;
+ const feedback = installationId
+ ? await fetchGitHubReviewFeedback({
+ installationId,
+ number: row.number,
+ repoFullName: row.repoFullName,
+ since: new Date(Date.now() - REVIEW_LOOKBACK_MS),
+ })
+ : [];
+ // The window may also hold comments from people the repository does not
+ // trust; the agent is told about the trusted ones only.
+ const trusted = feedback.filter((item) => SCM_TRUSTED_ASSOCIATIONS.has(item.association));
+ const known = new Set(trusted.map((item) => item.url ?? `${item.author}:${item.body}`));
+ const all =
+ trigger && !known.has(trigger.url ?? `${trigger.author}:${trigger.body}`)
+ ? [...trusted, trigger]
+ : trusted;
+
+ return buildReviewPrompt({
+ feedback: all.sort((a, b) => (a.submittedAt ?? '').localeCompare(b.submittedAt ?? '')),
+ reason,
+ row,
+ });
+ };
+
+ /** Slug the workspace-aware routes are mirrored under, for links we hand to GitHub. */
+ private workspaceSlug = async (workspaceId: string): Promise<string | null> => {
+ const [row] = await this.db
+ .select({ slug: workspaces.slug })
+ .from(workspaces)
+ .where(eq(workspaces.id, workspaceId));
+ return row?.slug ?? null;
+ };
+
+ /** Provider-side installation id for a `scm_installations` row id. */
+ private providerInstallationId = async (installationRowId: string) => {
+ const installation = await ScmInstallationModel.findById(this.db, installationRowId);
+ return installation?.installationId ?? null;
+ };
+
+ /** One wake per change request per window; Redis-less deployments never debounce. */
+ private claimWakeWindow = (changeRequestId: string): Promise<boolean> =>
+ this.claimOnce(`scm:wake:${changeRequestId}`, WAKE_DEBOUNCE_SECONDS);
+
+ /** Redis SETNX with a TTL; without Redis every claim succeeds. */
+ private claimOnce = async (key: string, ttlSeconds: number): Promise<boolean> => {
+ const redis = getAgentRuntimeRedisClient();
+ if (!redis) return true;
+ const claimed = await redis.set(key, '1', 'EX', ttlSeconds, 'NX');
+ return claimed === 'OK';
+ };
+}
diff --git a/apps/server/src/services/scm/ScmIngestService.ts b/apps/server/src/services/scm/ScmIngestService.ts
index f1d69d88974..51a6d555a3a 100644
--- a/apps/server/src/services/scm/ScmIngestService.ts
+++ b/apps/server/src/services/scm/ScmIngestService.ts
@@ -237,7 +237,16 @@ export class ScmIngestService {
// Emit per-check failure the moment it lands, and the green rollup once
// nothing is pending — those two are what the control half acts on.
- const failedNow = event.checks.some(isFailingCheck);
+ //
+ // Read the failure off the *merged* row, not off the payload: a
+ // redelivered or late failure for a check that has since gone green
+ // loses to the newer result in `mergeChecks`, and classifying it from
+ // the payload would wake the agent against a green row with nothing
+ // to fix — and spend one of its three wakes doing it.
+ const arrived = new Set(event.checks.filter(isFailingCheck).map((c) => c.externalId));
+ const failedNow = (result.row.checks ?? []).some(
+ (check) => isFailingCheck(check) && arrived.has(check.externalId),
+ );
const kind = failedNow
? 'ci_failed'
: result.ciStatus === 'success' && result.previousCiStatus !== 'success'
diff --git a/apps/server/src/services/scm/__tests__/ScmControlService.test.ts b/apps/server/src/services/scm/__tests__/ScmControlService.test.ts
new file mode 100644
index 00000000000..dd2507b801c
--- /dev/null
+++ b/apps/server/src/services/scm/__tests__/ScmControlService.test.ts
@@ -0,0 +1,777 @@
+// @vitest-environment node
+import { getTestDB } from '@lobechat/database/test-utils';
+import type { ScmActorAssociation } from '@lobechat/types';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ScmChangeRequestModel, ScmInstallationModel } from '@/database/models/scm';
+import {
+ acceptances,
+ agents,
+ scmWebhookDeliveries,
+ topics,
+ users,
+ verifyRuns,
+ works,
+} from '@/database/schemas';
+
+import { SCM_MAX_WAKES, ScmControlService } from '../ScmControlService';
+import { parseTrackingMarker } from '../trackingComment';
+import type { ScmInboundEvent } from '../types';
+
+const serverDB = await getTestDB();
+const userId = 'scm-control-user';
+
+const mocks = vi.hoisted(() => ({
+ execAgent: vi.fn(),
+ jobLog: vi.fn(),
+ postComment: vi.fn(),
+ redisSet: vi.fn(),
+ reviewFeedback: vi.fn(),
+ updateComment: vi.fn(),
+}));
+
+vi.mock('@/server/services/aiAgent', () => ({
+ AiAgentService: vi.fn().mockImplementation(function () {
+ return { execAgent: mocks.execAgent };
+ }),
+}));
+vi.mock('@/server/modules/AgentRuntime/redis', () => ({
+ getAgentRuntimeRedisClient: () => ({ set: mocks.redisSet }),
+}));
+vi.mock('../github/app', () => ({
+ fetchGitHubJobLogTail: mocks.jobLog,
+ fetchGitHubReviewFeedback: mocks.reviewFeedback,
+ postGitHubPullRequestComment: mocks.postComment,
+ updateGitHubPullRequestComment: mocks.updateComment,
+}));
+vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: 'https://app.test/' } }));
+vi.mock('@/server/workflows/expertiseRejection', () => ({
+ ExpertiseRejectionWorkflow: { trigger: vi.fn(async () => {}) },
+}));
+
+const control = () => new ScmControlService(serverDB);
+
+const baseRow = {
+ headSha: 'c'.repeat(40),
+ number: 5,
+ provider: 'github' as const,
+ repoFullName: 'arvinxx/sandbox',
+ state: 'open' as const,
+ url: 'https://github.com/arvinxx/sandbox/pull/5',
+ userId,
+};
+
+const changeRequestEvent = (kind: 'merged' | 'opened') =>
+ ({
+ changeRequest: baseRow,
+ installationId: '90001',
+ kind,
+ type: 'change_request',
+ }) as const;
+
+const checksEvent: Extract<ScmInboundEvent, { type: 'checks' }> = {
+ checks: [],
+ headSha: baseRow.headSha,
+ installationId: '90001',
+ numbers: [5],
+ repoFullName: baseRow.repoFullName,
+ type: 'checks',
+};
+
+const reviewEvent = (login: string, association: ScmActorAssociation = 'collaborator') =>
+ ({
+ actor: { association, externalId: '1', login },
+ installationId: '90001',
+ kind: 'review_commented',
+ number: 5,
+ repoFullName: baseRow.repoFullName,
+ review: { externalId: 'r1' },
+ type: 'review',
+ }) as const;
+
+beforeEach(async () => {
+ await serverDB.insert(users).values({ id: userId });
+ mocks.execAgent.mockResolvedValue({ operationId: 'op_1' });
+ mocks.redisSet.mockResolvedValue('OK');
+ mocks.jobLog.mockResolvedValue('npm ERR! test failed\n');
+ mocks.reviewFeedback.mockResolvedValue([]);
+ mocks.postComment.mockResolvedValue('c-1');
+ mocks.updateComment.mockResolvedValue(true);
+});
+
+afterEach(async () => {
+ await serverDB.delete(scmWebhookDeliveries);
+ await serverDB.delete(users);
+ vi.clearAllMocks();
+});
+
+const createTopic = async () => {
+ await serverDB.insert(agents).values({ id: 'agt_control', slug: 'agt_control', userId });
+ const [topic] = await serverDB
+ .insert(topics)
+ .values({ agentId: 'agt_control', title: 'PR topic', userId })
+ .returning();
+ return topic;
+};
+
+describe('ScmControlService — merge', () => {
+ it('accepts the linked acceptance, stamps the round, and flips the Work', async () => {
+ const [acceptance] = await serverDB
+ .insert(acceptances)
+ .values({ status: 'verifying', subjectId: 's', subjectType: 'standalone', userId })
+ .returning();
+ const [run] = await serverDB
+ .insert(verifyRuns)
+ .values({ acceptanceId: acceptance.id, roundIndex: 1, userId })
+ .returning();
+ const [work] = await serverDB
+ .insert(works)
+ .values({
+ resourceId: 'arvinxx/sandbox#5',
+ resourceType: 'github_pull_request',
+ status: 'open',
+ toolIdentifier: 'lobe-local-system',
+ toolName: 'runCommand',
+ type: 'external',
+ userId,
+ visibility: 'private',
+ })
+ .returning();
+ const row = await ScmChangeRequestModel.upsert(serverDB, {
+ ...baseRow,
+ links: { acceptanceId: acceptance.id, workId: work.id },
+ mergedByExternalId: '42',
+ state: 'merged',
+ });
+
+ const outcome = await control().handle({
+ event: changeRequestEvent('merged'),
+ kind: 'merged',
+ row,
+ });
+ expect(outcome).toEqual({ acceptanceId: acceptance.id, outcome: 'accepted' });
+
+ const [after] = await serverDB
+ .select()
+ .from(acceptances)
+ .where(eq(acceptances.id, acceptance.id));
+ expect(after.status).toBe('accepted');
+ expect(after.completedAt).not.toBeNull();
+
+ const [decided] = await serverDB.select().from(verifyRuns).where(eq(verifyRuns.id, run.id));
+ expect(decided.userDecision).toBe('accept');
+ expect(decided.decisionDetail).toMatchObject({
+ changeRequest: { number: 5, repoFullName: 'arvinxx/sandbox' },
+ source: 'scm_merge',
+ });
+
+ const [flipped] = await serverDB.select().from(works).where(eq(works.id, work.id));
+ expect(flipped.status).toBe('merged');
+ });
+
+ it('waits for every linked pull request of a stack before accepting', async () => {
+ const [acceptance] = await serverDB
+ .insert(acceptances)
+ .values({ subjectId: 's', subjectType: 'standalone', userId })
+ .returning();
+ const merged = await ScmChangeRequestModel.upsert(serverDB, {
+ ...baseRow,
+ links: { acceptanceId: acceptance.id },
+ state: 'merged',
+ });
+ await ScmChangeRequestModel.upsert(serverDB, {
+ ...baseRow,
+ links: { acceptanceId: acceptance.id },
+ number: 6,
+ url: 'https://github.com/arvinxx/sandbox/pull/6',
+ });
+
+ const outcome = await control().handle({
+ event: changeRequestEvent('merged'),
+ kind: 'merged',
+ row: merged,
+ });
+ expect(outcome).toMatchObject({
+ outcome: 'skipped',
+ detail: expect.stringContaining('still open'),
+ });
+ const [after] = await serverDB
+ .select()
+ .from(acceptances)
+ .where(eq(acceptances.id, acceptance.id));
+ expect(after.status).toBe('pending');
+ });
+});
+
+describe('ScmControlService — wake', () => {
+ it('wakes the agent of the linked conversation with the failing check and its log', async () => {
+ const topic = await createTopic();
+ const installation = await ScmInstallationModel.bind(serverDB, {
+ accountExternalId: '1',
+ accountLogin: 'arvinxx',
+ accountType: 'user',
+ installationId: '90001',
+ provider: 'github',
+ repositorySelection: 'all',
+ userId,
+ });
+ const row = await ScmChangeRequestModel.upsert(serverDB, {
+ ...baseRow,
+ headRef: 'feat/x',
+ links: { installationId: installation.id, topicId: topic.id },
+ });
+ const withChecks = await ScmChangeRequestModel.applyChecks(serverDB, row.id, {
+ checks: [
+ {
+ conclusion: 'failure',
+ externalId: 'check_run:777',
+ name: 'Test',
+ status: 'completed',
+ url: 'https://github.com/arvinxx/sandbox/actions/runs/1/job/777',
+ },
+ ],
+ headSha: baseRow.headSha,
+ });
+
+ const outcome = await control().handle({
+ event: checksEvent,
+ kind: 'ci_failed',
+ row: withChecks!.row,
+ });
+ expect(outcome).toEqual({ operationId: 'op_1', outcome: 'woken', reason: 'ci_failed' });
+
+ expect(mocks.jobLog).toHaveBeenCalledWith({
+ installationId: '90001',
+ jobId: '777',
+ repoFullName: 'arvinxx/sandbox',
+ });
+ const call = mocks.execAgent.mock.calls[0][0];
+ expect(call).toMatchObject({
+ agentId: 'agt_control',
+ appContext: { topicId: topic.id },
+ externalOrigin: {
+ kind: 'ci_failed',
+ label: 'arvinxx/sandbox#5',
+ provider: 'github',
+ resourceId: row.id,
+ url: baseRow.url,
+ },
+ steer: false,
+ trigger: 'scm',
+ userInterventionConfig: { approvalMode: 'headless' },
+ });
+ expect(call.prompt).toContain('repo="arvinxx/sandbox"');
+ expect(call.prompt).toContain('<check conclusion="failure" name="Test"');
+ expect(call.prompt).toContain('npm ERR! test failed');
+ expect(call.prompt).toContain('branch="feat/x"');
+
+ const after = await ScmChangeRequestModel.findById(serverDB, row.id);
+ expect(after?.wakeCount).toBe(1);
+ expect(after?.metadata.lastWake?.reason).toBe('ci_failed');
+ });
+
+ it('steers instead of starting a new turn when the conversation is running', async () => {
+ const topic = await createTopic();
+ await serverDB
+ .update(topics)
+ .set({
+ metadata: { runningOperation: { assistantMessageId: 'm', operationId: 'op_0' } } as any,
+ })
+ .where(eq(topics.id, topic.id));
+ const row = await ScmChangeRequestModel.upsert(serverDB, {
+ ...baseRow,
+ links: { topicId: topic.id },
+ });
+
+ await control().handle({
+ event: reviewEvent('reviewer'),
+ kind: 'review_changes_requested',
+ row,
+ });
+ expect(mocks.execAgent.mock.calls[0][0]).toMatchObject({ steer: true });
+ expect(mocks.execAgent.mock.calls[0][0].prompt).toContain('requested changes');
+ });
+
+ it('skips drafts, unlinked rows, self comments, debounced bursts, and the wake cap', async () => {
+ const topic = await createTopic();
+ const linked = await ScmChangeRequestModel.upsert(serverDB, {
+ ...baseRow,
+ authorExternalLogin: 'the-agent',
+ links: { topicId: topic.id },
+ });
+
+ expect(
+ await control().handle({
+ event: checksEvent,
+ kind: 'ci_failed',
+ row: { ...linked, isDraft: true },
+ }),
+ ).toMatchObject({ outcome: 'skipped', detail: 'draft pull request' });
+
+ expect(
+ await control().handle({
+ event: checksEvent,
+ kind: 'ci_failed',
+ row: { ...linked, topicId: null },
+ }),
+ ).toMatchObject({ outcome: 'skipped', detail: 'no linked conversation' });
+
+ expect(
+ await control().handle({
+ event: checksEvent,
+ kind: 'ci_failed',
+ row: { ...linked, state: 'merged' },
+ }),
+ ).toMatchObject({ outcome: 'skipped', detail: 'pull request is merged' });
+
+ expect(
+ await control().handle({
+ event: reviewEvent('the-agent'),
+ kind: 'review_commented',
+ row: linked,
+ }),
+ ).toMatchObject({ outcome: 'skipped', detail: 'self comment' });
+
+ expect(
+ await control().handle({
+ event: checksEvent,
+ kind: 'ci_failed',
+ row: { ...linked, wakeCount: SCM_MAX_WAKES },
+ }),
+ ).toMatchObject({ outcome: 'skipped', detail: expect.stringContaining('wake cap') });
+
+ expect(mocks.execAgent).not.toHaveBeenCalled();
+ });
+
+ it('ignores review feedback from someone the repository does not trust', async () => {
+ const topic = await createTopic();
+ const row = await ScmChangeRequestModel.upsert(serverDB, {
+ ...baseRow,
+ links: { topicId: topic.id },
+ });
+
+ for (const association of ['none', 'contributor', 'unknown'] as const) {
+ expect(
+ await control().handle({
+ event: reviewEvent('drive-by', association),
+ kind: 'review_changes_requested',
+ row,
+ }),
+ ).toMatchObject({ detail: `reviewer is ${association}`, outcome: 'skipped' });
+ }
+ expect(mocks.execAgent).not.toHaveBeenCalled();
+
+ // A collaborator's feedback still wakes the agent.
+ expect(
+ await control().handle({
+ event: reviewEvent('maintainer', 'member'),
+ kind: 'review_changes_requested',
+ row,
+ }),
+ ).toMatchObject({ outcome: 'woken' });
+ });
+
+ it('delivers a failure the debounce window swallowed on the next event', async () => {
+ const topic = await createTopic();
+ const row = await ScmChangeRequestModel.upsert(serverDB, {
+ ...baseRow,
+ links: { topicId: topic.id },
+ });
+
+ // Second job of the burst: the window is still held by the first wake,
+ // so nothing is sent — not by this event, and not by the flush either.
+ mocks.redisSet.mockResolvedValue(null);
+ expect(await control().handle({ event: checksEvent, kind: 'ci_failed', row })).toMatchObject({
+ detail: 'debounced',
+ outcome: 'skipped',
+ });
+ expect(mocks.execAgent).not.toHaveBeenCalled();
+ expect(
+ (await ScmChangeRequestModel.findById(serverDB, row.id))?.metadata.pendingWake?.reason,
+ ).toBe('ci_failed');
+
+ // Once the window frees up, any later delivery carries it and the
+ // marker is cleared.
+ mocks.redisSet.mockResolvedValue('OK');
+ const fresh = (await ScmChangeRequestModel.findById(serverDB, row.id))!;
+ await control().handle({
+ event: changeRequestEvent('opened'),
+ kind: 'synchronized',
+ row: fresh,
+ });
+ expect(mocks.execAgent).toHaveBeenCalledTimes(1);
+ expect(
+ (await ScmChangeRequestModel.findById(serverDB, row.id))?.metadata.pendingWake,
+ ).toBeUndefined();
+ });
+
+ it('respects the automation switches of the user who connected the installation', async () => {
+ const topic = await createTopic();
+ const [acceptance] = await serverDB
+ .insert(acceptances)
+ .values({ subjectId: 's', subjectType: 'standalone', userId })
+ .returning();
+ const row = await ScmChangeRequestModel.upsert(serverDB, {
+ ...baseRow,
+ links: { acceptanceId: acceptance.id, topicId: topic.id },
+ });
+ await serverDB
+ .update(users)
+ .set({
+ preference: {
+ integration: { github: { acceptOnMerge: false, wakeOnCiFailure: false } },
+ } as any,
+ })
+ .where(eq(users.id, userId));
+
+ expect(await control().handle({ event: checksEvent, kind: 'ci_failed', row })).toMatchObject({
+ outcome: 'skipped',
+ detail: 'wakeOnCiFailure is off',
+ });
+ expect(
+ await control().handle({
+ event: changeRequestEvent('merged'),
+ kind: 'merged',
+ row: { ...row, state: 'merged' },
+ }),
+ ).toMatchObject({ outcome: 'skipped', detail: 'acceptOnMerge is off' });
+ expect(mocks.execAgent).not.toHaveBeenCalled();
+ const [after] = await serverDB
+ .select()
+ .from(acceptances)
+ .where(eq(acceptances.id, acceptance.id));
+ expect(after.status).toBe('pending');
+
+ // wakeOnReview was left unset, so review feedback still wakes the agent.
+ expect(
+ await control().handle({ event: reviewEvent('reviewer'), kind: 'review_commented', row }),
+ ).toMatchObject({ outcome: 'woken' });
+ });
+
+ it('wakes with the review text from the webhook when the list endpoint gives nothing', async () => {
+ const topic = await createTopic();
+ const row = await ScmChangeRequestModel.upsert(serverDB, {
+ ...baseRow,
+ links: { topicId: topic.id },
+ });
+ // Rate limited, transiently failing, or simply not showing the review
+ // yet — all three look like this.
+ mocks.reviewFeedback.mockResolvedValue([]);
+
+ const event = {
+ ...reviewEvent('maintainer', 'member'),
+ review: {
+ body: 'Please rename the helper, it shadows the model method.',
+ externalId: 'r1',
+ line: 12,
+ path: 'src/a.ts',
+ url: 'https://github.com/arvinxx/sandbox/pull/5#r1',
+ },
+ } as Extract<ScmInboundEvent, { type: 'review' }>;
+
+ expect(await control().handle({ event, kind: 'review_changes_requested', row })).toMatchObject({
+ outcome: 'woken',
+ });
+
+ const prompt = mocks.execAgent.mock.calls[0][0].prompt as string;
+ expect(prompt).toContain('Please rename the helper, it shadows the model method.');
+ expect(prompt).toContain('src/a.ts');
+ });
+
+ it('does not repeat the triggering review when the list endpoint already has it', async () => {
+ const topic = await createTopic();
+ const row = await ScmChangeRequestModel.upsert(serverDB, {
+ ...baseRow,
+ links: { topicId: topic.id },
+ });
+ mocks.reviewFeedback.mockResolvedValue([
+ {
+ association: 'member',
+ author: 'maintainer',
+ body: 'Rename the helper.',
+ url: 'https://github.com/arvinxx/sandbox/pull/5#r1',
+ },
+ ]);
+
+ const event = {
+ ...reviewEvent('maintainer', 'member'),
+ review: {
+ body: 'Rename the helper.',
+ externalId: 'r1',
+ url: 'https://github.com/arvinxx/sandbox/pull/5#r1',
+ },
+ } as Extract<ScmInboundEvent, { type: 'review' }>;
+
+ await control().handle({ event, kind: 'review_changes_requested', row });
+
+ const prompt = mocks.execAgent.mock.calls[0][0].prompt as string;
+ expect(prompt.match(/Rename the helper\./g)).toHaveLength(1);
+ });
+
+ it('drops a pending wake when the automation was switched off in between', async () => {
+ const topic = await createTopic();
+ const row = await ScmChangeRequestModel.upsert(serverDB, {
+ ...baseRow,
+ links: { topicId: topic.id },
+ });
+
+ // A burst leaves a marker behind.
+ mocks.redisSet.mockResolvedValue(null);
+ await control().handle({ event: checksEvent, kind: 'ci_failed', row });
+ expect(
+ (await ScmChangeRequestModel.findById(serverDB, row.id))?.metadata.pendingWake?.reason,
+ ).toBe('ci_failed');
+
+ // The user turns CI notifications off before the next delivery. The
+ // marker must not outlive that decision.
+ await serverDB
+ .update(users)
+ .set({ preference: { integration: { github: { wakeOnCiFailure: false } } } as any })
+ .where(eq(users.id, userId));
+ mocks.redisSet.mockResolvedValue('OK');
+
+ const fresh = (await ScmChangeRequestModel.findById(serverDB, row.id))!;
+ await control().handle({
+ event: changeRequestEvent('opened'),
+ kind: 'synchronized',
+ row: fresh,
+ });
+
+ expect(mocks.execAgent).not.toHaveBeenCalled();
+ const after = await ScmChangeRequestModel.findById(serverDB, row.id);
+ expect(after?.metadata.pendingWake).toBeUndefined();
+ expect(after?.wakeCount).toBe(0);
+ });
+
+ it('holds the wake cap when two deliveries race on the same stale row', async () => {
+ const topic = await createTopic();
+ const row = await ScmChangeRequestModel.upsert(serverDB, {
+ ...baseRow,
+ links: { topicId: topic.id },
+ });
+ // One slot left, and both deliveries hold the snapshot that says so —
+ // which is what a Redis-less deployment looks like, since nothing
+ // debounces them.
+ await ScmChangeRequestModel.reserveWake(serverDB, row.id, SCM_MAX_WAKES, 'ci_failed');
+ await ScmChangeRequestModel.reserveWake(serverDB, row.id, SCM_MAX_WAKES, 'ci_failed');
+ const stale = { ...row, wakeCount: SCM_MAX_WAKES - 1 };
+
+ const outcomes = await Promise.all([
+ control().handle({ event: checksEvent, kind: 'ci_failed', row: stale }),
+ control().handle({ event: checksEvent, kind: 'ci_failed', row: stale }),
+ ]);
+
+ expect(outcomes.filter((o) => o.outcome === 'woken')).toHaveLength(1);
+ expect(mocks.execAgent).toHaveBeenCalledTimes(1);
+ expect((await ScmChangeRequestModel.findById(serverDB, row.id))?.wakeCount).toBe(SCM_MAX_WAKES);
+ });
+
+ it('flips the Work to merged even when accepting on merge is off', async () => {
+ const [work] = await serverDB
+ .insert(works)
+ .values({
+ resourceId: 'arvinxx/sandbox#5',
+ resourceType: 'github_pull_request',
+ status: 'open',
+ toolIdentifier: 'lobe-local-system',
+ toolName: 'runCommand',
+ type: 'external',
+ userId,
+ visibility: 'private',
+ })
+ .returning();
+ const row = await ScmChangeRequestModel.upsert(serverDB, {
+ ...baseRow,
+ links: { workId: work.id },
+ state: 'merged',
+ });
+ await serverDB
+ .update(users)
+ .set({ preference: { integration: { github: { acceptOnMerge: false } } } as any })
+ .where(eq(users.id, userId));
+
+ expect(
+ await control().handle({ event: changeRequestEvent('merged'), kind: 'merged', row }),
+ ).toMatchObject({ outcome: 'skipped', detail: 'acceptOnMerge is off' });
+
+ // The switch only governs the verdict; the Work row mirrors GitHub.
+ const [flipped] = await serverDB.select().from(works).where(eq(works.id, work.id));
+ expect(flipped.status).toBe('merged');
+ });
+
+ it('reports a failed wake without counting it', async () => {
+ const topic = await createTopic();
+ const row = await ScmChangeRequestModel.upsert(serverDB, {
+ ...baseRow,
+ links: { topicId: topic.id },
+ });
+ mocks.execAgent.mockRejectedValueOnce(new Error('topic busy'));
+
+ expect(await control().handle({ event: checksEvent, kind: 'ci_failed', row })).toMatchObject({
+ outcome: 'skipped',
+ detail: 'wake failed: topic busy',
+ });
+ expect((await ScmChangeRequestModel.findById(serverDB, row.id))?.wakeCount).toBe(0);
+ });
+});
+
+describe('ScmControlService — the tracking comment in GitHub', () => {
+ const bindAndOpen = async (extra: Record<string, unknown>) => {
+ const topic = await createTopic();
+ const installation = await ScmInstallationModel.bind(serverDB, {
+ accountExternalId: '1',
+ accountLogin: 'arvinxx',
+ accountType: 'user',
+ installationId: '90001',
+ provider: 'github',
+ repositorySelection: 'all',
+ userId,
+ });
+ const [acceptance] = await serverDB
+ .insert(acceptances)
+ .values({ status: 'delivered', subjectId: 's', subjectType: 'standalone', userId })
+ .returning();
+ return ScmChangeRequestModel.upsert(serverDB, {
+ ...baseRow,
+ links: { acceptanceId: acceptance.id, installationId: installation.id, topicId: topic.id },
+ ...extra,
+ });
+ };
+
+ it('posts one comment with a hidden marker and a status table, then rewrites it in place', async () => {
+ const row = await bindAndOpen({ metadata: { repoPrivate: true } });
+
+ const first = await control().handle({
+ event: changeRequestEvent('opened'),
+ kind: 'opened',
+ row,
+ });
+ expect(first).toEqual({ commentId: 'c-1', outcome: 'commented', updated: false });
+ expect(mocks.postComment).toHaveBeenCalledTimes(1);
+ const body = mocks.postComment.mock.calls[0][0].body as string;
+ expect(parseTrackingMarker(body)).toEqual({
+ acceptanceId: row.acceptanceId,
+ changeRequestId: row.id,
+ provider: 'github',
+ topicId: row.topicId,
+ v: 1,
+ });
+ expect(body).toContain(`https://app.test/acceptance/${row.acceptanceId}`);
+ expect(body).toContain(`https://app.test/agent/agt_control/${row.topicId}`);
+ expect(body).toContain('| 🟡 Delivered |');
+ expect(body).toContain('[PR topic ↗︎]');
+
+ const stored = await ScmChangeRequestModel.findById(serverDB, row.id);
+ expect(stored?.metadata.lobehubCommentId).toBe('c-1');
+
+ // The next event rewrites the same comment instead of posting again.
+ const again = await control().handle({
+ event: changeRequestEvent('opened'),
+ kind: 'synchronized',
+ row: stored!,
+ });
+ expect(again).toEqual({ commentId: 'c-1', outcome: 'commented', updated: true });
+ expect(mocks.postComment).toHaveBeenCalledTimes(1);
+ expect(mocks.updateComment).toHaveBeenCalledWith(
+ expect.objectContaining({ commentId: 'c-1', installationId: '90001' }),
+ );
+
+ // A concurrent handler still holding the pre-comment row is steered to
+ // the update path by the fresh read even when its claim goes through.
+ const stale = await control().handle({
+ event: changeRequestEvent('opened'),
+ kind: 'synchronized',
+ row,
+ });
+ expect(stale).toMatchObject({ outcome: 'commented', updated: true });
+ expect(mocks.postComment).toHaveBeenCalledTimes(1);
+
+ // And when another delivery already holds the claim, nothing is posted.
+ const unclaimed = await ScmChangeRequestModel.upsert(serverDB, {
+ ...baseRow,
+ links: { acceptanceId: row.acceptanceId, installationId: row.installationId },
+ metadata: { repoPrivate: true },
+ number: 6,
+ url: 'https://github.com/arvinxx/sandbox/pull/6',
+ });
+ await ScmChangeRequestModel.claimCommentSlot(serverDB, unclaimed.id);
+ expect(
+ await control().handle({
+ event: changeRequestEvent('opened'),
+ kind: 'opened',
+ row: unclaimed,
+ }),
+ ).toMatchObject({ outcome: 'skipped', detail: 'comment already in flight' });
+ expect(mocks.postComment).toHaveBeenCalledTimes(1);
+ });
+
+ it('posts once when opened and synchronize race, with no Redis to arbitrate', async () => {
+ const row = await bindAndOpen({ metadata: { repoPrivate: true } });
+ // Both handlers hold the pre-comment row, which is what a Redis-less
+ // deployment looks like: nothing outside the database serialises them.
+ const outcomes = await Promise.all([
+ control().handle({ event: changeRequestEvent('opened'), kind: 'opened', row }),
+ control().handle({ event: changeRequestEvent('opened'), kind: 'synchronized', row }),
+ ]);
+
+ expect(mocks.postComment).toHaveBeenCalledTimes(1);
+ expect(outcomes.filter((o) => o.outcome === 'commented' && !o.updated)).toHaveLength(1);
+ expect(
+ (await ScmChangeRequestModel.findById(serverDB, row.id))?.metadata.lobehubCommentId,
+ ).toBe('c-1');
+ });
+
+ it('reflects the merge and the notifications in the comment', async () => {
+ const row = await bindAndOpen({ metadata: { repoPrivate: true } });
+ await control().handle({ event: changeRequestEvent('opened'), kind: 'opened', row });
+ const stored = (await ScmChangeRequestModel.findById(serverDB, row.id))!;
+
+ await control().handle({ event: checksEvent, kind: 'ci_failed', row: stored });
+ expect(mocks.updateComment).toHaveBeenCalledTimes(1);
+ expect(mocks.updateComment.mock.calls[0][0].body).toContain('| 1/3 · CI failed |');
+
+ // The ingest half lands the merge on the row before the control half runs.
+ const merged = await ScmChangeRequestModel.upsert(serverDB, { ...baseRow, state: 'merged' });
+ await control().handle({ event: changeRequestEvent('merged'), kind: 'merged', row: merged });
+ expect(mocks.updateComment).toHaveBeenCalledTimes(2);
+ expect(mocks.updateComment.mock.calls[1][0].body).toContain('| ✅ Accepted |');
+ });
+
+ it('stays quiet on public repositories unless opted in, and without links', async () => {
+ const publicRow = await bindAndOpen({ metadata: { repoPrivate: false } });
+ expect(
+ await control().handle({
+ event: changeRequestEvent('opened'),
+ kind: 'opened',
+ row: publicRow,
+ }),
+ ).toMatchObject({ outcome: 'skipped', detail: 'commentOnPublicRepositories is off' });
+
+ await serverDB
+ .update(users)
+ .set({ preference: { integration: { github: { commentOnPublicRepositories: true } } } })
+ .where(eq(users.id, userId));
+ expect(
+ await control().handle({
+ event: changeRequestEvent('opened'),
+ kind: 'opened',
+ row: publicRow,
+ }),
+ ).toMatchObject({ outcome: 'commented' });
+
+ const unlinked = await ScmChangeRequestModel.upsert(serverDB, {
+ ...baseRow,
+ metadata: { repoPrivate: true },
+ number: 9,
+ url: 'https://github.com/arvinxx/sandbox/pull/9',
+ });
+ expect(
+ await control().handle({
+ event: changeRequestEvent('opened'),
+ kind: 'opened',
+ row: unlinked,
+ }),
+ ).toMatchObject({ outcome: 'skipped', detail: 'no links to share' });
+ });
+});
diff --git a/apps/server/src/services/scm/__tests__/ScmIngestService.test.ts b/apps/server/src/services/scm/__tests__/ScmIngestService.test.ts
index fc03c344498..9a3e16c7129 100644
--- a/apps/server/src/services/scm/__tests__/ScmIngestService.test.ts
+++ b/apps/server/src/services/scm/__tests__/ScmIngestService.test.ts
@@ -217,6 +217,32 @@ describe('ScmIngestService', () => {
expect(row).toMatchObject({ ciStatus: 'success', lastEventKind: 'ci_passed' });
});
+ it('does not classify a redelivered failure that lost to a newer success', async () => {
+ await bindInstallation();
+ await ingest('pull_request', fx.pullRequestEvent('opened'));
+
+ // The job was rerun and went green.
+ await ingest(
+ 'check_run',
+ fx.checkRunEvent({ completed_at: '2026-09-20T07:00:00Z', conclusion: 'success', id: 9 }),
+ );
+ let row = await ScmChangeRequestModel.findByIdentity(
+ serverDB,
+ 'github',
+ 'lobehub/lobehub',
+ 19_719,
+ );
+ expect(row).toMatchObject({ ciStatus: 'success', lastEventKind: 'ci_passed' });
+
+ // The original failure is redelivered afterwards — we use redelivery as
+ // the recovery path, so this is ordinary traffic. It loses to the newer
+ // result, and must not be classified as a fresh failure: the row is
+ // green, so the wake would carry nothing and still spend a slot.
+ await ingest('check_run', fx.checkRunEvent());
+ row = await ScmChangeRequestModel.findById(serverDB, row!.id);
+ expect(row).toMatchObject({ ciStatus: 'success', lastEventKind: 'ci_passed' });
+ });
+
it('maintains the installation from lifecycle events', async () => {
const installation = await bindInstallation();
diff --git a/apps/server/src/services/scm/__tests__/trackingComment.test.ts b/apps/server/src/services/scm/__tests__/trackingComment.test.ts
new file mode 100644
index 00000000000..5724b1f263d
--- /dev/null
+++ b/apps/server/src/services/scm/__tests__/trackingComment.test.ts
@@ -0,0 +1,79 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ buildTrackingComment,
+ encodeTrackingMarker,
+ formatUtc,
+ parseTrackingMarker,
+} from '../trackingComment';
+
+const marker = {
+ acceptanceId: '1042abc6-4d38-49a6-b4b9-5c5a606d762e',
+ changeRequestId: 'scr_1',
+ provider: 'github' as const,
+ topicId: 'tpc_1',
+ v: 1 as const,
+};
+
+describe('tracking comment', () => {
+ it('hides the identity in a link reference definition that round-trips', () => {
+ const body = buildTrackingComment({ marker, updatedAt: new Date('2026-09-20T15:12:00Z') });
+ expect(body.startsWith('[lobehub]: #')).toBe(true);
+ expect(parseTrackingMarker(body)).toEqual(marker);
+ expect(parseTrackingMarker('just a comment')).toBeNull();
+ expect(parseTrackingMarker('[lobehub]: #not-base64-json')).toBeNull();
+ expect(encodeTrackingMarker(marker)).not.toContain('scr_1');
+ });
+
+ it('renders a status table with the acceptance, conversation and notifications', () => {
+ const body = buildTrackingComment({
+ acceptance: {
+ id: marker.acceptanceId,
+ status: 'delivered',
+ url: 'https://app.test/acceptance/1042abc6-4d38-49a6-b4b9-5c5a606d762e',
+ },
+ conversation: { title: 'Fix | the thing\nnow', url: 'https://app.test/agent/a/tpc_1' },
+ marker,
+ notification: { count: 1, max: 3, reason: 'ci_failed' },
+ updatedAt: new Date('2026-09-20T15:12:00Z'),
+ });
+
+ expect(body).toContain('**LobeHub is tracking this pull request.**');
+ expect(body).toContain(
+ '| Acceptance | Status | Conversation | Notifications | Updated (UTC) |',
+ );
+ expect(body).toContain(
+ '| [1042abc6](https://app.test/acceptance/1042abc6-4d38-49a6-b4b9-5c5a606d762e) | 🟡 Delivered | [Fix \\| the thing now ↗︎](https://app.test/agent/a/tpc_1) | 1/3 · CI failed | Sep 20, 2026 3:12pm |',
+ );
+ });
+
+ it('keeps a hostile conversation title inside its own link label', () => {
+ const body = buildTrackingComment({
+ conversation: {
+ title: '](https://evil.example) [click me',
+ url: 'https://app.test/agent/a/tpc_1',
+ },
+ marker,
+ updatedAt: new Date('2026-09-20T15:12:00Z'),
+ });
+
+ // The title is a user- or model-written string on a public pull
+ // request: unescaped, `](` would close our link and let the rest of it
+ // become markdown of the author's choosing.
+ expect(body).not.toContain('https://evil.example)');
+ expect(body).toContain(
+ String.raw`[\]\(https://evil.example\) \[click me ↗︎](https://app.test/agent/a/tpc_1)`,
+ );
+ });
+
+ it('shows dashes for what is not linked yet', () => {
+ const body = buildTrackingComment({ marker, updatedAt: new Date('2026-01-05T00:07:00Z') });
+ expect(body).toContain('| — | — | — | — | 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');
+ expect(formatUtc(new Date('2026-09-20T23:59:00Z'))).toBe('Sep 20, 2026 11:59pm');
+ });
+});
diff --git a/apps/server/src/services/scm/__tests__/wakePrompt.test.ts b/apps/server/src/services/scm/__tests__/wakePrompt.test.ts
new file mode 100644
index 00000000000..24c1e946f26
--- /dev/null
+++ b/apps/server/src/services/scm/__tests__/wakePrompt.test.ts
@@ -0,0 +1,112 @@
+import { describe, expect, it } from 'vitest';
+
+import type { ScmChangeRequestItem } from '@/database/schemas';
+
+import { buildCiFailurePrompt, buildReviewPrompt } from '../wakePrompt';
+
+const row = {
+ checks: [
+ { conclusion: 'success', externalId: 'check_run:1', name: 'Lint', status: 'completed' },
+ {
+ conclusion: 'failure',
+ externalId: 'check_run:2',
+ name: 'Test',
+ status: 'completed',
+ url: 'https://github.com/o/r/actions/runs/9/job/2',
+ },
+ { conclusion: 'failure', externalId: 'check_run:4', name: 'Build "x"', status: 'completed' },
+ { conclusion: 'cancelled', externalId: 'check_run:5', name: 'Cancelled', status: 'completed' },
+ { conclusion: 'skipped', externalId: 'check_run:6', name: 'Skipped', status: 'completed' },
+ { conclusion: 'neutral', externalId: 'check_run:7', name: 'Neutral', status: 'completed' },
+ { externalId: 'check_run:3', name: 'Deploy', status: 'in_progress' },
+ ],
+ headRef: 'feat/x',
+ headSha: 'abcdef0123456789',
+ number: 7,
+ provider: 'github',
+ repoFullName: 'o/r',
+ url: 'https://github.com/o/r/pull/7',
+} as unknown as ScmChangeRequestItem;
+
+/** CommonMark closes an HTML block at the first blank line; the block must not contain one. */
+const hasBlankLine = (text: string) => /\n\s*\n/.test(text);
+
+describe('buildCiFailurePrompt', () => {
+ it('emits one scmEvent block with failed checks, their log tails and the instruction', () => {
+ const prompt = buildCiFailurePrompt({
+ logs: { 'check_run:2': 'FAIL src/a.test.ts\n\n expected 1\n\n' },
+ row,
+ });
+
+ expect(prompt.startsWith('<scmEvent ')).toBe(true);
+ expect(prompt.endsWith('</scmEvent>')).toBe(true);
+ expect(prompt).toContain(
+ 'branch="feat/x" kind="ci_failed" number="7" provider="github" repo="o/r" sha="abcdef0" url="https://github.com/o/r/pull/7"',
+ );
+ expect(prompt).toContain(
+ '<check conclusion="failure" name="Test" url="https://github.com/o/r/actions/runs/9/job/2">',
+ );
+ expect(prompt).toContain('<log><![CDATA[\nFAIL src/a.test.ts\n expected 1\n]]></log>');
+ // A failing check without a log is self-closing; attribute values are escaped.
+ expect(prompt).toContain('<check conclusion="failure" name="Build &quot;x&quot;" />');
+ expect(prompt).not.toContain('name="Lint"');
+ expect(prompt).not.toContain('name="Deploy"');
+ // Cancelled / skipped / neutral runs completed without failing; asking
+ // the agent to fix them would send it after a check that never ran.
+ expect(prompt).not.toContain('name="Cancelled"');
+ expect(prompt).not.toContain('name="Skipped"');
+ expect(prompt).not.toContain('name="Neutral"');
+ expect(prompt).toContain(
+ '<instruction>\nGitHub reported a failing check on pull request o/r#7',
+ );
+ expect(prompt).toContain('push the fix to the branch `feat/x`');
+ expect(hasBlankLine(prompt)).toBe(false);
+ });
+
+ it('keeps a CDATA terminator inside a log from ending the section', () => {
+ const prompt = buildCiFailurePrompt({ logs: { 'check_run:2': 'a ]]> b' }, row });
+ expect(prompt).toContain('a ]]]]><![CDATA[> b');
+ });
+});
+
+describe('buildReviewPrompt', () => {
+ it('renders review bodies and inline comments with their location', () => {
+ const prompt = buildReviewPrompt({
+ feedback: [
+ {
+ association: 'collaborator' as const,
+ author: 'codex',
+ body: 'Please split the handler.',
+ state: 'CHANGES_REQUESTED',
+ url: 'https://github.com/o/r/pull/7#pullrequestreview-1',
+ },
+ {
+ association: 'member' as const,
+ author: 'codex',
+ body: 'Guard is inverted.\n\nSee line 40.',
+ line: 42,
+ path: 'src/x.ts',
+ },
+ ],
+ reason: 'review_changes_requested',
+ row,
+ });
+
+ expect(prompt).toContain('kind="review_changes_requested"');
+ expect(prompt).toContain(
+ '<review author="codex" state="changes_requested" url="https://github.com/o/r/pull/7#pullrequestreview-1"><![CDATA[\nPlease split the handler.\n]]></review>',
+ );
+ expect(prompt).toContain(
+ '<review author="codex" line="42" path="src/x.ts"><![CDATA[\nGuard is inverted.\nSee line 40.\n]]></review>',
+ );
+ expect(prompt).toContain('A reviewer requested changes on pull request o/r#7');
+ expect(hasBlankLine(prompt)).toBe(false);
+ });
+
+ it('says so when the review carried no text', () => {
+ const prompt = buildReviewPrompt({ feedback: [], reason: 'review_commented', row });
+ expect(prompt).not.toContain('<review');
+ expect(prompt).toContain('Reviewers left feedback on pull request o/r#7');
+ expect(prompt).toContain('The review carried no text');
+ });
+});
diff --git a/apps/server/src/services/scm/github/__tests__/fixtures.ts b/apps/server/src/services/scm/github/__tests__/fixtures.ts
index cee148e74ed..f0557508fc9 100644
--- a/apps/server/src/services/scm/github/__tests__/fixtures.ts
+++ b/apps/server/src/services/scm/github/__tests__/fixtures.ts
@@ -67,6 +67,7 @@ export const reviewEvent = (state: string) => ({
pull_request: { number: 19_719 },
repository,
review: {
+ author_association: 'COLLABORATOR',
body: 'Please split the handler.',
html_url: 'https://github.com/lobehub/lobehub/pull/19719#pullrequestreview-7',
id: 7,
diff --git a/apps/server/src/services/scm/github/__tests__/normalize.test.ts b/apps/server/src/services/scm/github/__tests__/normalize.test.ts
index b26e364efde..268fee0af6b 100644
--- a/apps/server/src/services/scm/github/__tests__/normalize.test.ts
+++ b/apps/server/src/services/scm/github/__tests__/normalize.test.ts
@@ -22,7 +22,7 @@ describe('normalizeGitHubEvent', () => {
headSha: 'a'.repeat(40),
isDraft: false,
mergeStateStatus: 'CLEAN',
- metadata: { mergeable: 'true' },
+ metadata: { mergeable: 'true', repoPrivate: false },
number: 19_719,
provider: 'github',
repoFullName: 'lobehub/lobehub',
@@ -81,7 +81,7 @@ describe('normalizeGitHubEvent', () => {
expect(
normalizeGitHubEvent('pull_request_review', fx.reviewEvent('changes_requested')),
).toMatchObject({
- actor: { externalId: '77' },
+ actor: { association: 'collaborator', externalId: '77' },
kind: 'review_changes_requested',
number: 19_719,
review: { body: 'Please split the handler.', externalId: '7' },
@@ -113,6 +113,23 @@ describe('normalizeGitHubEvent', () => {
).toMatchObject({ type: 'ignored' });
});
+ it('marks an actor the repository does not vouch for as untrusted', () => {
+ // The association decides whether the text may steer an unattended
+ // agent, so anything unexpected has to land outside the trusted set.
+ expect(
+ normalizeGitHubEvent('pull_request_review', {
+ ...fx.reviewEvent('changes_requested'),
+ review: { ...fx.reviewEvent('changes_requested').review, author_association: 'NONE' },
+ }),
+ ).toMatchObject({ actor: { association: 'none' } });
+ expect(
+ normalizeGitHubEvent('pull_request_review', {
+ ...fx.reviewEvent('changes_requested'),
+ review: { ...fx.reviewEvent('changes_requested').review, author_association: undefined },
+ }),
+ ).toMatchObject({ actor: { association: 'unknown' } });
+ });
+
it('maps an inline review comment with its file location', () => {
expect(
normalizeGitHubEvent('pull_request_review_comment', fx.reviewCommentEvent()),
diff --git a/apps/server/src/services/scm/github/__tests__/reviewFeedback.test.ts b/apps/server/src/services/scm/github/__tests__/reviewFeedback.test.ts
new file mode 100644
index 00000000000..98590241708
--- /dev/null
+++ b/apps/server/src/services/scm/github/__tests__/reviewFeedback.test.ts
@@ -0,0 +1,95 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ request: vi.fn(),
+ scmEnv: {
+ ENABLED_GITHUB_APP: true,
+ GITHUB_APP_ID: '1',
+ GITHUB_APP_PRIVATE_KEY: 'key',
+ },
+}));
+
+vi.mock('@/envs/scm', () => ({ scmEnv: mocks.scmEnv }));
+vi.mock('octokit', () => ({
+ App: vi.fn().mockImplementation(function () {
+ return { getInstallationOctokit: async () => ({ request: mocks.request }) };
+ }),
+}));
+
+const { fetchGitHubReviewFeedback, resetGitHubApp } = await import('../app');
+
+const NOW = Date.UTC(2026, 8, 22, 12, 0, 0);
+const at = (minutesAgo: number) => new Date(NOW - minutesAgo * 60_000).toISOString();
+
+const review = (id: number, submittedAt: string) => ({
+ author_association: 'MEMBER',
+ body: `review ${id}`,
+ html_url: `https://github.com/o/r/pull/1#r${id}`,
+ state: 'COMMENTED',
+ submitted_at: submittedAt,
+ user: { login: 'reviewer' },
+});
+
+/** Three pages of reviews; only the last page is inside the wake window. */
+const pages: Record<number, ReturnType<typeof review>[]> = {
+ 1: [review(1, at(600)), review(2, at(590))],
+ 2: [review(3, at(500)), review(4, at(480))],
+ 3: [review(5, at(5)), review(6, at(2))],
+};
+
+describe('fetchGitHubReviewFeedback', () => {
+ beforeEach(() => {
+ resetGitHubApp();
+ mocks.request.mockReset();
+ mocks.request.mockImplementation(async (route: string, params: Record<string, unknown>) => {
+ if (route.endsWith('/comments')) return { data: [], headers: {} };
+ const page = Number(params.page ?? 1);
+ return {
+ data: pages[page] ?? [],
+ headers: {
+ link: '<https://api.github.com/repositories/1/pulls/1/reviews?page=3>; rel="last"',
+ },
+ };
+ });
+ });
+
+ it('walks back from the last page so recent reviews on a long pull request still reach the prompt', async () => {
+ const feedback = await fetchGitHubReviewFeedback({
+ installationId: '1',
+ number: 1,
+ repoFullName: 'o/r',
+ since: new Date(NOW - 15 * 60_000),
+ });
+
+ // Page one alone would have yielded nothing: its reviews are hours old.
+ expect(feedback.map((item) => item.body)).toEqual(['review 5', 'review 6']);
+ const requested = mocks.request.mock.calls
+ .filter(([route]) => route.endsWith('/reviews'))
+ .map(([, params]) => params.page ?? 1);
+ // Page one is the probe that carries the `rel="last"` link; the walk
+ // then runs backwards from the end and stops at the first page that
+ // starts before the window.
+ expect(requested).toEqual([1, 3, 2]);
+ });
+
+ it('reads one page when the pull request has only one', async () => {
+ mocks.request.mockImplementation(async (route: string) =>
+ route.endsWith('/comments')
+ ? { data: [], headers: {} }
+ : { data: [review(9, at(1))], headers: {} },
+ );
+
+ const feedback = await fetchGitHubReviewFeedback({
+ installationId: '1',
+ number: 1,
+ repoFullName: 'o/r',
+ since: new Date(NOW - 15 * 60_000),
+ });
+
+ expect(feedback.map((item) => item.body)).toEqual(['review 9']);
+ expect(mocks.request.mock.calls.filter(([route]) => route.endsWith('/reviews'))).toHaveLength(
+ 1,
+ );
+ });
+});
diff --git a/apps/server/src/services/scm/github/__tests__/trimJobLog.test.ts b/apps/server/src/services/scm/github/__tests__/trimJobLog.test.ts
new file mode 100644
index 00000000000..1fc1a92edce
--- /dev/null
+++ b/apps/server/src/services/scm/github/__tests__/trimJobLog.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from 'vitest';
+
+import { trimJobLog } from '../app';
+
+const stamp = (line: string, index: number) =>
+ `2026-09-20T07:00:${String(index % 60).padStart(2, '0')}.0000000Z ${line}`;
+
+describe('trimJobLog', () => {
+ it('centres the window on the first ##[error] and strips timestamps', () => {
+ const noise = Array.from({ length: 200 }, (_, i) =>
+ stamp(`[command]/usr/bin/git step ${i}`, i),
+ );
+ const failing = [
+ stamp('##[group]Run bash ci.sh', 200),
+ stamp('STATUS=fail', 201),
+ stamp('##[error]tests failed on purpose (STATUS=fail)', 202),
+ stamp('##[error]Process completed with exit code 1.', 203),
+ ...Array.from({ length: 50 }, (_, i) => stamp(`Post job cleanup ${i}`, i)),
+ ];
+ const trimmed = trimJobLog([...noise, ...failing].join('\n'));
+
+ expect(trimmed).toContain('STATUS=fail');
+ expect(trimmed).toContain('##[error]tests failed on purpose');
+ expect(trimmed).not.toMatch(/2026-09-20T/);
+ expect(trimmed).not.toContain('git step 100');
+ expect(trimmed).toContain('git step 199');
+ expect(trimmed).not.toContain('Post job cleanup 30');
+ });
+
+ it('falls back to the tail when there is no annotation', () => {
+ const lines = Array.from({ length: 30 }, (_, i) => `line ${i}`);
+ const trimmed = trimJobLog(lines.join('\n'), 40);
+ expect(trimmed.length).toBeLessThanOrEqual(40);
+ expect(trimmed.endsWith('line 29')).toBe(true);
+ expect(trimmed).not.toContain('line 0\n');
+ });
+});
diff --git a/apps/server/src/services/scm/github/app.ts b/apps/server/src/services/scm/github/app.ts
index c396f0968ed..f18dac7a7a8 100644
--- a/apps/server/src/services/scm/github/app.ts
+++ b/apps/server/src/services/scm/github/app.ts
@@ -1,4 +1,8 @@
-import type { ScmInstallationRepository, ScmInstallationSnapshot } from '@lobechat/types';
+import type {
+ ScmActorAssociation,
+ ScmInstallationRepository,
+ ScmInstallationSnapshot,
+} from '@lobechat/types';
import debug from 'debug';
import { App, Octokit } from 'octokit';
@@ -142,6 +146,239 @@ export const listGitHubInstallationRepositories = async (
return repositories;
};
+/**
+ * Cut an Actions job log down to the part that explains the failure. Logs
+ * open with hundreds of lines of checkout noise; the first `##[error]`
+ * annotation marks where the failing step reported, so the window is
+ * centred there (context before, aftermath after) and only falls back to
+ * the tail when there is no annotation. Timestamps are stripped: they cost
+ * 29 chars per line and tell the agent nothing.
+ */
+export const trimJobLog = (raw: string, maxChars = 6000): string => {
+ const lines = raw.split(/\r?\n/).map((line) => line.replace(/^\d{4}-\d{2}-\d{2}T[\d:.]+Z /, ''));
+ const errorAt = lines.findIndex((line) => line.includes('##[error]'));
+ const window =
+ errorAt === -1
+ ? lines
+ : lines.slice(Math.max(0, errorAt - 60), Math.min(lines.length, errorAt + 20));
+ const text = window.join('\n').trim();
+ return text.length > maxChars ? text.slice(-maxChars) : text;
+};
+
+const parseRepo = (repoFullName: string) => {
+ const [owner, repo] = repoFullName.split('/');
+ return { owner, repo };
+};
+
+/**
+ * Tail of a GitHub Actions job log, for the wake-up prompt after a failing
+ * check. Actions check runs share their id with the job, so a check's
+ * `externalId` of `check_run:<id>` is the job id. Best-effort: a missing log
+ * (non-Actions check, expired log) yields `null`, never a thrown error.
+ */
+export const fetchGitHubJobLogTail = async (params: {
+ installationId: string;
+ jobId: string;
+ maxChars?: number;
+ repoFullName: string;
+}): Promise<string | null> => {
+ const app = getGitHubApp();
+ if (!app) return null;
+
+ try {
+ const octokit = await app.getInstallationOctokit(Number(params.installationId));
+ const { data } = await octokit.request('GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs', {
+ ...parseRepo(params.repoFullName),
+ job_id: Number(params.jobId),
+ });
+ const text = typeof data === 'string' ? data : String(data ?? '');
+ if (!text) return null;
+ return trimJobLog(text, params.maxChars ?? 6000);
+ } catch (error) {
+ log('job log %s for %s unavailable: %O', params.jobId, params.repoFullName, error);
+ return null;
+ }
+};
+
+const ASSOCIATIONS = new Set<ScmActorAssociation>([
+ 'collaborator',
+ 'contributor',
+ 'member',
+ 'none',
+ 'owner',
+]);
+
+const normalizeAssociation = (value: unknown): ScmActorAssociation => {
+ const lowered = String(value ?? '').toLowerCase() as ScmActorAssociation;
+ return ASSOCIATIONS.has(lowered) ? lowered : 'unknown';
+};
+
+export interface GitHubReviewFeedback {
+ /** Repository relationship GitHub reported for the author. */
+ association: ScmActorAssociation;
+ author: string;
+ body: string;
+ line?: number | null;
+ path?: string | null;
+ state?: string;
+ submittedAt?: string;
+ url?: string;
+}
+
+/** Reviews per page when walking back from the newest ones. */
+const REVIEW_PAGE_SIZE = 100;
+/** How far back to walk; a window's worth of reviews never spans more. */
+const MAX_REVIEW_PAGES = 3;
+
+/** The `page` of the `rel="last"` entry in a GitHub Link header, if any. */
+const lastPageOf = (link: string | undefined): number | null => {
+ const match = link?.match(/<([^>]+)>;\s*rel="last"/);
+ if (!match) return null;
+ const page = Number(new URL(match[1]).searchParams.get('page'));
+ return Number.isFinite(page) && page > 1 ? page : null;
+};
+
+/**
+ * Reviews and inline review comments on a pull request since a given time,
+ * for the wake-up prompt after review feedback. One fetch per wake, so the
+ * prompt carries everything a reviewer said in the debounce window instead
+ * of one event's worth.
+ *
+ * The reviews endpoint has no `since`, and returns oldest first — so on a
+ * long-running pull request the reviews we want are on the *last* page.
+ * Reading page one would wake the agent with no feedback at all; walk back
+ * from the end until a page starts before the window.
+ */
+export const fetchGitHubReviewFeedback = async (params: {
+ installationId: string;
+ number: number;
+ repoFullName: string;
+ since: Date;
+}): Promise<GitHubReviewFeedback[]> => {
+ const app = getGitHubApp();
+ if (!app) return [];
+
+ try {
+ const octokit = await app.getInstallationOctokit(Number(params.installationId));
+ const repo = parseRepo(params.repoFullName);
+ const sinceMs = params.since.getTime();
+ const [reviews, comments] = await Promise.all([
+ (async () => {
+ const first = await octokit.request(
+ 'GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews',
+ { ...repo, per_page: REVIEW_PAGE_SIZE, pull_number: params.number },
+ );
+ const last = lastPageOf(first.headers.link as string | undefined);
+ if (!last) return first.data;
+
+ const collected: typeof first.data = [];
+ for (let page = last; page >= 1 && last - page < MAX_REVIEW_PAGES; page--) {
+ const data =
+ page === 1
+ ? first.data
+ : (
+ await octokit.request('GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews', {
+ ...repo,
+ page,
+ per_page: REVIEW_PAGE_SIZE,
+ pull_number: params.number,
+ })
+ ).data;
+ collected.unshift(...data);
+ const oldest = data.find((review) => review.submitted_at)?.submitted_at;
+ if (oldest && new Date(oldest).getTime() < sinceMs) break;
+ }
+ return collected;
+ })(),
+ octokit.request('GET /repos/{owner}/{repo}/pulls/{pull_number}/comments', {
+ ...repo,
+ per_page: 100,
+ pull_number: params.number,
+ since: params.since.toISOString(),
+ }),
+ ]);
+
+ const feedback: GitHubReviewFeedback[] = [];
+ for (const review of reviews) {
+ if (!review.body || !review.submitted_at) continue;
+ if (new Date(review.submitted_at).getTime() < sinceMs) continue;
+ feedback.push({
+ association: normalizeAssociation(review.author_association),
+ author: review.user?.login ?? 'unknown',
+ body: review.body,
+ state: review.state,
+ submittedAt: review.submitted_at,
+ url: review.html_url,
+ });
+ }
+ for (const comment of comments.data) {
+ feedback.push({
+ association: normalizeAssociation(comment.author_association),
+ author: comment.user?.login ?? 'unknown',
+ body: comment.body,
+ line: comment.line ?? comment.original_line ?? null,
+ path: comment.path,
+ submittedAt: comment.created_at,
+ url: comment.html_url,
+ });
+ }
+ return feedback.sort((a, b) => (a.submittedAt ?? '').localeCompare(b.submittedAt ?? ''));
+ } catch (error) {
+ log('review feedback for %s#%d unavailable: %O', params.repoFullName, params.number, error);
+ return [];
+ }
+};
+
+/**
+ * Post a comment on a pull request (GitHub keeps PR comments on the issues
+ * endpoint) and return its id, or `null` when the App cannot write there.
+ */
+export const postGitHubPullRequestComment = async (params: {
+ body: string;
+ installationId: string;
+ number: number;
+ repoFullName: string;
+}): Promise<string | null> => {
+ const app = getGitHubApp();
+ if (!app) return null;
+
+ try {
+ const octokit = await app.getInstallationOctokit(Number(params.installationId));
+ const { data } = await octokit.request(
+ 'POST /repos/{owner}/{repo}/issues/{issue_number}/comments',
+ { ...parseRepo(params.repoFullName), body: params.body, issue_number: params.number },
+ );
+ return String(data.id);
+ } catch (error) {
+ log('comment on %s#%d failed: %O', params.repoFullName, params.number, error);
+ return null;
+ }
+};
+
+/** Rewrite a comment LobeHub posted earlier. `false` when the App cannot write there any more. */
+export const updateGitHubPullRequestComment = async (params: {
+ body: string;
+ commentId: string;
+ installationId: string;
+ repoFullName: string;
+}): Promise<boolean> => {
+ const app = getGitHubApp();
+ if (!app) return false;
+
+ try {
+ const octokit = await app.getInstallationOctokit(Number(params.installationId));
+ await octokit.request('PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}', {
+ ...parseRepo(params.repoFullName),
+ body: params.body,
+ comment_id: Number(params.commentId),
+ });
+ return true;
+ } catch (error) {
+ log('comment %s on %s update failed: %O', params.commentId, params.repoFullName, error);
+ return false;
+ }
+};
+
/**
* The installations the *user* can see, read with their own token. This is
* the only signal that ties a person to an installation: the app-level
diff --git a/apps/server/src/services/scm/github/normalize.ts b/apps/server/src/services/scm/github/normalize.ts
index 806f9f7681c..f9c51d76480 100644
--- a/apps/server/src/services/scm/github/normalize.ts
+++ b/apps/server/src/services/scm/github/normalize.ts
@@ -1,4 +1,5 @@
import type {
+ ScmActorAssociation,
ScmChangeRequestEventKind,
ScmChangeRequestSnapshot,
ScmChangeRequestState,
@@ -32,9 +33,27 @@ const date = (value: unknown): Date | null => {
return Number.isNaN(parsed.getTime()) ? null : parsed;
};
-const actor = (user: Json | null | undefined): ScmActor | undefined =>
+const ASSOCIATIONS = new Set<ScmActorAssociation>([
+ 'collaborator',
+ 'contributor',
+ 'member',
+ 'none',
+ 'owner',
+]);
+
+/** GitHub's `author_association`, normalized; anything unknown stays untrusted. */
+const association = (value: unknown): ScmActorAssociation => {
+ const lowered = String(value ?? '').toLowerCase() as ScmActorAssociation;
+ return ASSOCIATIONS.has(lowered) ? lowered : 'unknown';
+};
+
+const actor = (user: Json | null | undefined, authorAssociation?: unknown): ScmActor | undefined =>
user && user.id !== undefined && user.login
- ? { externalId: String(user.id), login: String(user.login) }
+ ? {
+ association: association(authorAssociation),
+ externalId: String(user.id),
+ login: String(user.login),
+ }
: undefined;
const repository = (repo: Json | null | undefined): ScmInstallationRepository | null =>
@@ -78,8 +97,12 @@ const pullRequestSnapshot = (repo: Json, pr: Json): ScmChangeRequestSnapshot =>
mergeStateStatus: str(pr.mergeable_state)?.toUpperCase() ?? null,
mergedAt: date(pr.merged_at),
mergedByExternalId: str(pr.merged_by?.id),
- metadata:
- pr.mergeable === null || pr.mergeable === undefined ? {} : { mergeable: String(pr.mergeable) },
+ metadata: {
+ ...(pr.mergeable === null || pr.mergeable === undefined
+ ? {}
+ : { mergeable: String(pr.mergeable) }),
+ ...(typeof repo.private === 'boolean' ? { repoPrivate: repo.private } : {}),
+ },
number: Number(pr.number),
provider: 'github',
repoExternalId: str(repo.id),
@@ -154,7 +177,7 @@ const normalizePullRequestReview = (payload: Json): ScmInboundEvent => {
if (!kind) return { reason: `review state ${review.state} not tracked`, type: 'ignored' };
return {
- actor: actor(review.user),
+ actor: actor(review.user, review.author_association),
installationId,
kind,
number: Number(pr.number),
@@ -186,7 +209,7 @@ const normalizePullRequestReviewComment = (payload: Json): ScmInboundEvent => {
}
return {
- actor: actor(comment.user),
+ actor: actor(comment.user, comment.author_association),
installationId,
kind: 'review_commented',
number: Number(pr.number),
diff --git a/apps/server/src/services/scm/trackingComment.ts b/apps/server/src/services/scm/trackingComment.ts
new file mode 100644
index 00000000000..28a74f0f75e
--- /dev/null
+++ b/apps/server/src/services/scm/trackingComment.ts
@@ -0,0 +1,120 @@
+import type { AcceptanceStatus, ScmProvider } from '@lobechat/types';
+
+/**
+ * The comment LobeHub keeps on a tracked pull request. Modelled on Vercel's
+ * bot comment: a hidden marker line that carries machine-readable identity,
+ * a one-line headline, and a status table that is rewritten in place as
+ * the pull request moves — one comment per pull request, never a thread.
+ */
+
+export const TRACKING_MARKER_LABEL = 'lobehub';
+export const GITHUB_INTEGRATION_DOCS_URL = 'https://lobehub.com/docs/usage/integrations/github';
+
+export interface TrackingCommentMarker {
+ acceptanceId?: string;
+ changeRequestId: string;
+ provider: ScmProvider;
+ topicId?: string;
+ v: 1;
+}
+
+/**
+ * A link reference definition renders as nothing on GitHub, which makes it
+ * the conventional place to hide state: `[lobehub]: #<base64 json>`.
+ */
+export const encodeTrackingMarker = (marker: TrackingCommentMarker) =>
+ `[${TRACKING_MARKER_LABEL}]: #${Buffer.from(JSON.stringify(marker)).toString('base64')}`;
+
+export const parseTrackingMarker = (body: string): TrackingCommentMarker | null => {
+ const match = new RegExp(String.raw`^\[${TRACKING_MARKER_LABEL}\]: #(\S+)`, 'm').exec(body);
+ if (!match) return null;
+ try {
+ const parsed = JSON.parse(Buffer.from(match[1], 'base64').toString('utf8'));
+ return parsed && parsed.v === 1 && typeof parsed.changeRequestId === 'string' ? parsed : null;
+ } catch {
+ return null;
+ }
+};
+
+const ACCEPTANCE_STATUS: Record<AcceptanceStatus, string> = {
+ accepted: '✅ Accepted',
+ closed: '⚫ Closed',
+ delivered: '🟡 Delivered',
+ errored: '⚠️ Errored',
+ pending: '⚪ Pending',
+ planned: '⚪ Planned',
+ rejected: '❌ Rejected',
+ repairing: '🔧 Repairing',
+ verifying: '🔄 Verifying',
+};
+
+const NOTIFICATION_REASON: Record<string, string> = {
+ ci_failed: 'CI failed',
+ review_changes_requested: 'Changes requested',
+ review_commented: 'Review comment',
+};
+
+const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
+
+/** `Sep 20, 2026 3:12pm`, in UTC, the way Vercel prints its Updated column. */
+export const formatUtc = (date: Date) => {
+ const hours24 = date.getUTCHours();
+ const hours = hours24 % 12 || 12;
+ const minutes = String(date.getUTCMinutes()).padStart(2, '0');
+ const meridiem = hours24 < 12 ? 'am' : 'pm';
+ return `${MONTHS[date.getUTCMonth()]} ${date.getUTCDate()}, ${date.getUTCFullYear()} ${hours}:${minutes}${meridiem}`;
+};
+
+/** Table cells cannot contain a pipe or a line break. */
+const cell = (text: string) =>
+ text
+ .replaceAll('|', '\\|')
+ .replaceAll(/\s*\n\s*/g, ' ')
+ .trim();
+
+/**
+ * A conversation title is written by a user or a model, and it goes into a
+ * link label on a public pull request. Left alone, a `](` in it closes our
+ * link early and everything after it becomes markdown of the author's
+ * choosing — including another link. Escape what can end a label or start
+ * emphasis, on top of the table-cell rules.
+ */
+const label = (text: string) => cell(text.replaceAll(/[\\[\]()*_`~<>]/g, String.raw`\$&`));
+
+export interface TrackingCommentInput {
+ acceptance?: { id: string; status: AcceptanceStatus; url: string } | null;
+ conversation?: { title?: string | null; url: string } | null;
+ marker: TrackingCommentMarker;
+ /** How often the agent has been notified about this pull request, and why last. */
+ notification?: { count: number; max: number; reason?: string } | null;
+ updatedAt: Date;
+}
+
+export const buildTrackingComment = (input: TrackingCommentInput): string => {
+ const { acceptance, 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 =
+ notification && notification.count > 0
+ ? `${notification.count}/${notification.max}${
+ notification.reason
+ ? ` · ${NOTIFICATION_REASON[notification.reason] ?? notification.reason}`
+ : ''
+ }`
+ : '—';
+
+ return [
+ encodeTrackingMarker(marker),
+ '',
+ `**LobeHub 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})`,
+ '',
+ '| Acceptance | Status | Conversation | Notifications | Updated (UTC) |',
+ '| :--- | :--- | :--- | :--- | :--- |',
+ `| ${acceptanceCell} | ${statusCell} | ${conversationCell} | ${notificationCell} | ${formatUtc(updatedAt)} |`,
+ '',
+ ].join('\n');
+};
diff --git a/apps/server/src/services/scm/types.ts b/apps/server/src/services/scm/types.ts
index 59aa6f64869..dbc567aebe0 100644
--- a/apps/server/src/services/scm/types.ts
+++ b/apps/server/src/services/scm/types.ts
@@ -1,4 +1,5 @@
import type {
+ ScmActorAssociation,
ScmChangeRequestEventKind,
ScmChangeRequestSnapshot,
ScmCheck,
@@ -9,6 +10,8 @@ import type {
/** A provider user as it appears on an event. */
export interface ScmActor {
+ /** Repository relationship the provider reported for this actor. */
+ association?: ScmActorAssociation;
externalId: string;
login: string;
}
diff --git a/apps/server/src/services/scm/wakePrompt.ts b/apps/server/src/services/scm/wakePrompt.ts
new file mode 100644
index 00000000000..39decdd03d7
--- /dev/null
+++ b/apps/server/src/services/scm/wakePrompt.ts
@@ -0,0 +1,123 @@
+import { SCM_EVENT_TAG } from '@lobechat/const';
+
+import { isFailingCheck } from '@/database/models/scm';
+import type { ScmChangeRequestItem } from '@/database/schemas';
+
+import type { GitHubReviewFeedback } from './github/app';
+
+/** Reasons the control half wakes the agent that opened a change request. */
+export type ScmWakeReason = 'ci_failed' | 'review_changes_requested' | 'review_commented';
+
+/**
+ * The wake-up message is one `<scmEvent>` block: attributes name the change
+ * request, children carry the checks (with log tails), the review feedback
+ * and the instruction. The model reads it as structured context; the client
+ * renders it as a card ({@link SCM_EVENT_TAG} markdown plugin).
+ *
+ * The block must survive markdown parsing as a single HTML block, which
+ * CommonMark ends at the first blank line — so nothing here may emit one:
+ * quoted text has its blank lines dropped and sits inside CDATA.
+ */
+
+const escapeAttribute = (value: string) =>
+ value.replaceAll('&', '&amp;').replaceAll('"', '&quot;').replaceAll('<', '&lt;');
+
+const attributes = (values: Record<string, number | string | null | undefined>) =>
+ Object.entries(values)
+ .filter(([, value]) => value !== undefined && value !== null && value !== '')
+ .map(([key, value]) => `${key}="${escapeAttribute(String(value))}"`)
+ .join(' ');
+
+const withoutBlankLines = (text: string) =>
+ text
+ .split(/\r?\n/)
+ .filter((line) => line.trim().length > 0)
+ .join('\n');
+
+const cdata = (text: string) =>
+ `<![CDATA[\n${withoutBlankLines(text).replaceAll(']]>', ']]]]><![CDATA[>')}\n]]>`;
+
+const openTag = (row: ScmChangeRequestItem, kind: ScmWakeReason) =>
+ `<${SCM_EVENT_TAG} ${attributes({
+ branch: row.headRef,
+ kind,
+ number: row.number,
+ provider: row.provider,
+ repo: row.repoFullName,
+ sha: row.headSha ? row.headSha.slice(0, 7) : null,
+ url: row.url,
+ })}>`;
+
+const closeTag = `</${SCM_EVENT_TAG}>`;
+
+const sameCheckout = (row: ScmChangeRequestItem) =>
+ `Work in the same checkout you used for this pull request, push the fix to the branch \`${row.headRef ?? 'of the pull request'}\`, and reply here with a short summary of what changed and why.`;
+
+const instruction = (text: string) => `<instruction>\n${withoutBlankLines(text)}\n</instruction>`;
+
+/**
+ * The message an agent receives when a check fails on its pull request. The
+ * failing checks come from the stored rollup; job logs, when the fetcher
+ * could get them, are quoted so the agent can act without polling GitHub.
+ */
+export const buildCiFailurePrompt = (params: {
+ logs: Record<string, string | null>;
+ row: ScmChangeRequestItem;
+}): string => {
+ const { row, logs } = params;
+ // `cancelled`, `skipped` and `neutral` are completed but not failures;
+ // listing them would ask the agent to fix a check that never ran.
+ const failing = (row.checks ?? []).filter((check) => isFailingCheck(check));
+
+ const lines = [openTag(row, 'ci_failed')];
+ for (const check of failing) {
+ const attrs = attributes({
+ conclusion: check.conclusion ?? 'failure',
+ name: check.name,
+ url: check.url,
+ });
+ const tail = logs[check.externalId]?.trim();
+ if (tail) lines.push(`<check ${attrs}>`, `<log>${cdata(tail)}</log>`, '</check>');
+ else lines.push(`<check ${attrs} />`);
+ }
+ lines.push(
+ instruction(
+ `GitHub reported a failing check on pull request ${row.repoFullName}#${row.number}, which you opened from this conversation. Investigate the failure and fix it. ${sameCheckout(row)}`,
+ ),
+ closeTag,
+ );
+ return lines.join('\n');
+};
+
+/** The message an agent receives when reviewers request changes or comment. */
+export const buildReviewPrompt = (params: {
+ feedback: GitHubReviewFeedback[];
+ reason: Exclude<ScmWakeReason, 'ci_failed'>;
+ row: ScmChangeRequestItem;
+}): string => {
+ const { row, feedback, reason } = params;
+ const lines = [openTag(row, reason)];
+ for (const item of feedback) {
+ const attrs = attributes({
+ author: item.author,
+ line: item.line,
+ path: item.path,
+ state: item.state?.toLowerCase(),
+ url: item.url,
+ });
+ lines.push(`<review ${attrs}>${cdata(item.body.trim())}</review>`);
+ }
+ const lead =
+ reason === 'review_changes_requested'
+ ? `A reviewer requested changes on pull request ${row.repoFullName}#${row.number}, which you opened from this conversation.`
+ : `Reviewers left feedback on pull request ${row.repoFullName}#${row.number}, which you opened from this conversation.`;
+ const missing =
+ feedback.length === 0 ? ' The review carried no text; open the pull request to read it.' : '';
+ lines.push(
+ instruction(
+ `${lead}${missing} Address each point, or explain in your reply why it should stay as is. ${sameCheckout(row)}`,
+ ),
+ closeTag,
+ );
+ return lines.join('\n');
+};
diff --git a/apps/server/src/services/verify/acceptanceService.ts b/apps/server/src/services/verify/acceptanceService.ts
index 1c0ef99d828..ff91824a9ae 100644
--- a/apps/server/src/services/verify/acceptanceService.ts
+++ b/apps/server/src/services/verify/acceptanceService.ts
@@ -878,6 +878,51 @@ export class AcceptanceService {
return (await this.acceptanceModel.findById(acceptanceId))!;
};
+ /**
+ * A merged pull request accepts the delivery it was linked to. Merging is
+ * the strongest signal a user can give, so unlike {@link accept} this does
+ * not wait for the round to settle: any non-accepted status becomes
+ * `accepted`, a round still in flight is stamped as decided by the merge,
+ * and an acceptance that never had a round is simply closed as accepted.
+ * The decision detail records the merge so the acceptance board and the
+ * verifier-training pipeline can tell it apart from a human verdict.
+ *
+ * Idempotent: an already-accepted acceptance is returned unchanged.
+ */
+ acceptFromScmMerge = async (
+ acceptanceId: string,
+ changeRequest: NonNullable<VerifyRunDecisionDetail['changeRequest']>,
+ ): Promise<AcceptanceItem | null> => {
+ const acceptance = await this.acceptanceModel.findById(acceptanceId);
+ if (!acceptance) return null;
+ if (acceptance.status === 'accepted') return acceptance;
+
+ const runs = await this.runModel.listByAcceptance(acceptanceId);
+ const current = runs.at(-1);
+ if (current) {
+ const detail: VerifyRunDecisionDetail = {
+ changeRequest,
+ decidedAt: new Date().toISOString(),
+ decidedBy: this.actorUserId,
+ source: 'scm_merge',
+ };
+ await this.runModel.setDecision(current.id, 'accept', detail);
+ }
+
+ await this.acceptanceModel.updateStatus(acceptanceId, 'accepted');
+ if (current) this.distilSettledRound(acceptanceId, current.id);
+ if (acceptance.subjectType === 'task') await this.completeTaskSubject(acceptance.subjectId);
+
+ log(
+ 'acceptance %s accepted by merge of %s#%d (was %s)',
+ acceptanceId,
+ changeRequest.repoFullName,
+ changeRequest.number,
+ acceptance.status,
+ );
+ return (await this.acceptanceModel.findById(acceptanceId))!;
+ };
+
/**
* The user rejects the delivery. The comment is the re-tasking input: it is
* recorded on the round's decision detail, where the next repair/verify round
diff --git a/locales/en-US/integration.json b/locales/en-US/integration.json
index 27dfbec5c26..09c7bd81c5e 100644
--- a/locales/en-US/integration.json
+++ b/locales/en-US/integration.json
@@ -44,10 +44,6 @@
"github.pending.failed": "Could not connect the installation. Please try again from Connect account.",
"github.pending.title": "Connect GitHub installation",
"github.tagline": "Sync pull requests, CI results and reviews with your agents",
- "origin.event.ci_failed": "CI failed",
- "origin.event.review_changes_requested": "Changes requested",
- "origin.event.review_commented": "Review comment",
- "origin.provider.github": "GitHub",
"overview.all": "All integrations",
"overview.comingSoon": "Coming soon",
"overview.description": "Connect the platforms you already use",
@@ -56,6 +52,13 @@
"overview.status.enabled": "Enabled",
"overview.status.notConnected": "Not connected",
"overview.title": "Integrations",
+ "scmEvent.details": "Details",
+ "scmEvent.failedChecks": "{{count}} checks failed",
+ "scmEvent.hideLog": "Hide log",
+ "scmEvent.kind.ci_failed": "CI failed",
+ "scmEvent.kind.review_changes_requested": "Changes requested",
+ "scmEvent.kind.review_commented": "Review comment",
+ "scmEvent.showLog": "Show log",
"upcoming.cloudflare.tagline": "Notify the agent when a Workers or Pages build fails",
"upcoming.notion.tagline": "Sync Notion documents automatically",
"upcoming.railway.tagline": "Notify the agent when a deploy fails or a service crashes",
diff --git a/locales/zh-CN/integration.json b/locales/zh-CN/integration.json
index 304afd8a0c2..15122c0be61 100644
--- a/locales/zh-CN/integration.json
+++ b/locales/zh-CN/integration.json
@@ -44,10 +44,6 @@
"github.pending.failed": "连接安装失败,请从「连接账号」重试。",
"github.pending.title": "连接 GitHub 安装",
"github.tagline": "把 Pull Request、CI 结果和评审同步给你的智能体",
- "origin.event.ci_failed": "CI 失败",
- "origin.event.review_changes_requested": "要求修改",
- "origin.event.review_commented": "评审评论",
- "origin.provider.github": "GitHub",
"overview.all": "全部集成",
"overview.comingSoon": "即将支持",
"overview.description": "连接到你正在使用的平台",
@@ -56,6 +52,13 @@
"overview.status.enabled": "已启用",
"overview.status.notConnected": "未连接",
"overview.title": "集成",
+ "scmEvent.details": "详情",
+ "scmEvent.failedChecks": "{{count}} 项检查未通过",
+ "scmEvent.hideLog": "收起日志",
+ "scmEvent.kind.ci_failed": "CI 失败",
+ "scmEvent.kind.review_changes_requested": "要求修改",
+ "scmEvent.kind.review_commented": "评审评论",
+ "scmEvent.showLog": "查看日志",
"upcoming.cloudflare.tagline": "Workers / Pages 构建失败时通知智能体",
"upcoming.notion.tagline": "自动同步 Notion 文档",
"upcoming.railway.tagline": "部署失败或服务崩溃时通知智能体",
diff --git a/packages/const/src/plugin.ts b/packages/const/src/plugin.ts
index 08f5129dc89..8b21464e5a2 100644
--- a/packages/const/src/plugin.ts
+++ b/packages/const/src/plugin.ts
@@ -30,6 +30,8 @@ export const THINKING_TAG = 'think';
export const LOCAL_FILE_TAG = 'localFile';
export const SKILL_TAG = 'skill';
export const TASK_TAG = 'task';
+/** Provider activity (CI failure, review feedback) injected into a conversation by the SCM integration. */
+export const SCM_EVENT_TAG = 'scmEvent';
export const TOOL_TAG = 'tool';
export const USER_FEEDBACK_TAG = 'user_feedback';
// https://regex101.com/r/TwzTkf/2
diff --git a/packages/database/src/models/scm/__tests__/changeRequest.test.ts b/packages/database/src/models/scm/__tests__/changeRequest.test.ts
index ea8416d3761..a1c0b3083b1 100644
--- a/packages/database/src/models/scm/__tests__/changeRequest.test.ts
+++ b/packages/database/src/models/scm/__tests__/changeRequest.test.ts
@@ -1,6 +1,6 @@
// @vitest-environment node
import { eq } from 'drizzle-orm';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getTestDB } from '../../../core/getTestDB';
import { acceptances, scmWebhookDeliveries, users } from '../../../schemas';
@@ -547,11 +547,70 @@ describe('ScmChangeRequestModel', () => {
expect((after?.repositories ?? []).map((r) => r.externalId).sort()).toEqual(['2', '3', '4']);
});
- it('counts wakes', async () => {
+ it('changes pendingWake in place, without reading the metadata bag first', async () => {
+ const row = await ScmChangeRequestModel.upsert(serverDB, {
+ ...snapshot,
+ metadata: { lobehubCommentId: 'c-1' },
+ });
+
+ // Deliveries for one pull request are handled concurrently, so a
+ // read-modify-write on the whole column would let one handler erase
+ // what another stored in between — the tracking comment id here, which
+ // would then be posted a second time. The invariant is stronger than
+ // any interleaving a test can stage: these two never read the row.
+ const reads = vi.fn();
+ const watched = new Proxy(serverDB, {
+ get(target, prop, receiver) {
+ if (prop === 'select') reads();
+ return Reflect.get(target, prop, receiver);
+ },
+ }) as typeof serverDB;
+
+ await ScmChangeRequestModel.markPendingWake(watched, row.id, 'ci_failed');
+ // First reason of the burst wins; a second mark is a no-op.
+ await ScmChangeRequestModel.markPendingWake(watched, row.id, 'review_commented');
+ expect(reads).not.toHaveBeenCalled();
+
+ let after = await ScmChangeRequestModel.findById(serverDB, row.id);
+ expect(after?.metadata).toMatchObject({
+ lobehubCommentId: 'c-1',
+ pendingWake: { reason: 'ci_failed' },
+ });
+
+ await ScmChangeRequestModel.clearPendingWake(watched, row.id);
+ expect(reads).not.toHaveBeenCalled();
+
+ after = await ScmChangeRequestModel.findById(serverDB, row.id);
+ expect(after?.metadata.pendingWake).toBeUndefined();
+ expect(after?.metadata.lobehubCommentId).toBe('c-1');
+ });
+
+ it('counts wakes up to the cap, and keeps the rest of the metadata bag', async () => {
+ const row = await ScmChangeRequestModel.upsert(serverDB, {
+ ...snapshot,
+ metadata: { repoPrivate: true },
+ });
+ expect(await ScmChangeRequestModel.reserveWake(serverDB, row.id, 2)).toBe(1);
+ expect(await ScmChangeRequestModel.reserveWake(serverDB, row.id, 2, 'ci_failed')).toBe(2);
+ // Spent: the cap is the WHERE clause, so the row is simply not updated.
+ expect(await ScmChangeRequestModel.reserveWake(serverDB, row.id, 2, 'ci_failed')).toBeNull();
+
+ const after = await ScmChangeRequestModel.findById(serverDB, row.id);
+ expect(after?.wakeCount).toBe(2);
+ expect(after?.lastWakeAt).not.toBeNull();
+ expect(after?.metadata).toMatchObject({
+ lastWake: { at: expect.any(String), reason: 'ci_failed' },
+ repoPrivate: true,
+ });
+
+ await ScmChangeRequestModel.releaseWake(serverDB, row.id);
+ expect((await ScmChangeRequestModel.findById(serverDB, row.id))?.wakeCount).toBe(1);
+ });
+
+ it('never lets a released wake take the counter below zero', async () => {
const row = await ScmChangeRequestModel.upsert(serverDB, snapshot);
- expect(await ScmChangeRequestModel.recordWake(serverDB, row.id)).toBe(1);
- expect(await ScmChangeRequestModel.recordWake(serverDB, row.id)).toBe(2);
- expect((await ScmChangeRequestModel.findById(serverDB, row.id))?.lastWakeAt).not.toBeNull();
+ await ScmChangeRequestModel.releaseWake(serverDB, row.id);
+ expect((await ScmChangeRequestModel.findById(serverDB, row.id))?.wakeCount).toBe(0);
});
});
diff --git a/packages/database/src/models/scm/changeRequest.ts b/packages/database/src/models/scm/changeRequest.ts
index 07c5efd36e2..2406135a07c 100644
--- a/packages/database/src/models/scm/changeRequest.ts
+++ b/packages/database/src/models/scm/changeRequest.ts
@@ -9,7 +9,7 @@ import type {
ScmReviewDecision,
ScmUpsertChangeRequestParams,
} from '@lobechat/types';
-import { and, desc, eq, isNull } from 'drizzle-orm';
+import { and, desc, eq, isNull, lt, sql } from 'drizzle-orm';
import type { ScmChangeRequestItem } from '../../schemas';
import { scmChangeRequests } from '../../schemas';
@@ -575,16 +575,143 @@ export class ScmChangeRequestModel {
.where(eq(scmChangeRequests.id, id));
};
- /** Bump the wake counter; returns the new count so the caller can enforce its cap. */
- static recordWake = async (db: LobeChatDatabase, id: string): Promise<number> => {
- const existing = await ScmChangeRequestModel.findById(db, id);
- if (!existing) return 0;
+ /**
+ * Note a wake the debounce window swallowed, for the next delivery to
+ * carry. Touches only its own key: deliveries for one change request are
+ * handled concurrently, so writing the whole metadata column back would
+ * let a read-modify-write erase whatever another handler stored in
+ * between — the tracking comment id, the last wake, held checks.
+ */
+ static markPendingWake = async (
+ db: LobeChatDatabase,
+ id: string,
+ reason: string,
+ ): Promise<void> => {
+ await db
+ .update(scmChangeRequests)
+ .set({
+ metadata: sql`${scmChangeRequests.metadata} || ${JSON.stringify({
+ pendingWake: { reason, since: new Date().toISOString() },
+ })}::jsonb`,
+ updatedAt: new Date(),
+ })
+ .where(
+ and(
+ eq(scmChangeRequests.id, id),
+ // First reason of the burst wins, as before.
+ sql`not coalesce(jsonb_exists(${scmChangeRequests.metadata}, 'pendingWake'), false)`,
+ ),
+ );
+ };
+
+ static clearPendingWake = async (db: LobeChatDatabase, id: string): Promise<void> => {
+ await db
+ .update(scmChangeRequests)
+ .set({
+ metadata: sql`${scmChangeRequests.metadata} - 'pendingWake'`,
+ updatedAt: new Date(),
+ })
+ .where(eq(scmChangeRequests.id, id));
+ };
+
+ /**
+ * Claim one of the `max` wakes this change request is allowed, atomically.
+ *
+ * The cap has to be enforced by the database, not by the caller: without
+ * 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.
+ */
+ static reserveWake = async (
+ db: LobeChatDatabase,
+ id: string,
+ max: number,
+ reason?: string,
+ ): Promise<number | null> => {
+ const now = new Date();
+ // jsonb concat rather than a read-modify-write: it merges the one key
+ // this update owns and leaves every other key as the row has it.
+ const metadata = reason
+ ? sql`${scmChangeRequests.metadata} || ${JSON.stringify({
+ lastWake: { at: now.toISOString(), reason },
+ })}::jsonb`
+ : undefined;
+
+ const [reserved] = await db
+ .update(scmChangeRequests)
+ .set({
+ lastWakeAt: now,
+ ...(metadata ? { metadata } : {}),
+ updatedAt: now,
+ wakeCount: sql`${scmChangeRequests.wakeCount} + 1`,
+ })
+ .where(and(eq(scmChangeRequests.id, id), lt(scmChangeRequests.wakeCount, max)))
+ .returning({ wakeCount: scmChangeRequests.wakeCount });
+
+ return reserved?.wakeCount ?? null;
+ };
+
+ /**
+ * Take the right to post the tracking comment, atomically.
+ *
+ * Posting a comment is irreversible, so the single-writer decision cannot
+ * live in the application: `opened` and the `synchronize` a second later
+ * are handled concurrently, and on a deployment without Redis nothing
+ * else stops them both from seeing an unposted row. A conditional update
+ * on the metadata bag lets exactly one through; the claim goes stale
+ * after `staleAfterMs` so a crashed post does not block the row forever.
+ */
+ static claimCommentSlot = async (
+ db: LobeChatDatabase,
+ id: string,
+ staleAfterMs = 5 * 60 * 1000,
+ ): Promise<boolean> => {
+ const now = new Date();
+ const staleBefore = new Date(now.getTime() - staleAfterMs).toISOString();
+
+ const [claimed] = await db
+ .update(scmChangeRequests)
+ .set({
+ metadata: sql`${scmChangeRequests.metadata} || ${JSON.stringify({
+ commentClaimedAt: now.toISOString(),
+ })}::jsonb`,
+ updatedAt: now,
+ })
+ .where(
+ and(
+ eq(scmChangeRequests.id, id),
+ // Key existence, not `->> … IS NULL`: an IS NULL on an extracted
+ // jsonb value takes the planner down on any bm25-indexed table.
+ sql`coalesce(${scmChangeRequests.metadata} ->> 'lobehubCommentId', '') = ''`,
+ sql`coalesce(${scmChangeRequests.metadata} ->> 'commentClaimedAt', '') < ${staleBefore}`,
+ ),
+ )
+ .returning({ id: scmChangeRequests.id });
+
+ return Boolean(claimed);
+ };
+
+ /** Give the comment slot back when the post never happened. */
+ static releaseCommentSlot = async (db: LobeChatDatabase, id: string): Promise<void> => {
+ await db
+ .update(scmChangeRequests)
+ .set({
+ metadata: sql`${scmChangeRequests.metadata} - 'commentClaimedAt'`,
+ updatedAt: new Date(),
+ })
+ .where(eq(scmChangeRequests.id, id));
+ };
- const wakeCount = existing.wakeCount + 1;
+ /** Hand a reserved wake back when the run never started. */
+ static releaseWake = async (db: LobeChatDatabase, id: string): Promise<void> => {
await db
.update(scmChangeRequests)
- .set({ lastWakeAt: new Date(), updatedAt: new Date(), wakeCount })
+ .set({
+ updatedAt: new Date(),
+ wakeCount: sql`greatest(${scmChangeRequests.wakeCount} - 1, 0)`,
+ })
.where(eq(scmChangeRequests.id, id));
- return wakeCount;
};
}
diff --git a/packages/locales/src/default/integration.ts b/packages/locales/src/default/integration.ts
index 9497aec0aee..7f55ffa44c0 100644
--- a/packages/locales/src/default/integration.ts
+++ b/packages/locales/src/default/integration.ts
@@ -58,10 +58,6 @@ export default {
'Could not connect the installation. Please try again from Connect account.',
'github.pending.title': 'Connect GitHub installation',
'github.tagline': 'Sync pull requests, CI results and reviews with your agents',
- 'origin.event.ci_failed': 'CI failed',
- 'origin.event.review_changes_requested': 'Changes requested',
- 'origin.event.review_commented': 'Review comment',
- 'origin.provider.github': 'GitHub',
'overview.all': 'All integrations',
'overview.comingSoon': 'Coming soon',
'overview.description': 'Connect the platforms you already use',
@@ -70,6 +66,13 @@ export default {
'overview.status.enabled': 'Enabled',
'overview.status.notConnected': 'Not connected',
'overview.title': 'Integrations',
+ 'scmEvent.details': 'Details',
+ 'scmEvent.failedChecks': '{{count}} checks failed',
+ 'scmEvent.hideLog': 'Hide log',
+ 'scmEvent.kind.ci_failed': 'CI failed',
+ 'scmEvent.kind.review_changes_requested': 'Changes requested',
+ 'scmEvent.kind.review_commented': 'Review comment',
+ 'scmEvent.showLog': 'Show log',
'upcoming.cloudflare.tagline': 'Notify the agent when a Workers or Pages build fails',
'upcoming.notion.tagline': 'Sync Notion documents automatically',
'upcoming.railway.tagline': 'Notify the agent when a deploy fails or a service crashes',
diff --git a/packages/types/src/agentRuntime.ts b/packages/types/src/agentRuntime.ts
index 0ffa98cb93f..cd33737a0a6 100644
--- a/packages/types/src/agentRuntime.ts
+++ b/packages/types/src/agentRuntime.ts
@@ -30,6 +30,8 @@ export enum RequestTrigger {
Openapi = 'openapi',
/** A run the user deferred to a future time (`topic.metadata.scheduledRun`). */
Scheduled = 'scheduled',
+ /** A provider event on a pull request (CI failure, review) woke the agent that opened it. */
+ Scm = 'scm',
SemanticSearch = 'semantic_search',
SignupEmailLLMReview = 'signup_email_llm_review',
Topic = 'topic',
diff --git a/packages/types/src/message/common/metadata.ts b/packages/types/src/message/common/metadata.ts
index dbb435f0a97..5428f908df1 100644
--- a/packages/types/src/message/common/metadata.ts
+++ b/packages/types/src/message/common/metadata.ts
@@ -195,6 +195,32 @@ export interface AgentDispatchMetadata {
visibility: 'internal';
}
+/**
+ * Where a server-injected user turn came from when no human typed it: a
+ * provider event (GitHub CI failure, review feedback, …) that woke the
+ * agent. Rendered as a badge on the bubble and usable as a filter key.
+ */
+export interface ExternalOriginMetadata {
+ /** What happened, in the provider's event vocabulary (`ci_failed`, `review_changes_requested`, …). */
+ kind: string;
+ /** Human label of the resource, e.g. `lobehub/lobehub#19728`. */
+ label: string;
+ /** Provider id, e.g. `github`. */
+ provider: string;
+ /** LobeHub-side id of the tracked resource (`scm_change_requests.id`), for lookups. */
+ resourceId?: string;
+ /** Link to the provider resource. */
+ url?: string;
+}
+
+export const ExternalOriginMetadataSchema = z.object({
+ kind: z.string(),
+ label: z.string(),
+ provider: z.string(),
+ resourceId: z.string().optional(),
+ url: z.string().optional(),
+});
+
export const BotSenderMetadataSchema = z.object({
avatar: z.string().optional(),
fullName: z.string().optional(),
@@ -224,6 +250,7 @@ export interface BotSenderMetadata {
export const MessageMetadataSchema = ModelUsageSchema.merge(ModelPerformanceSchema).extend({
botSender: BotSenderMetadataSchema.optional(),
+ externalOrigin: ExternalOriginMetadataSchema.optional(),
agentDispatch: AgentDispatchMetadataSchema.optional(),
collapsed: z.boolean().optional(),
contextSelections: z.array(ContextSelectionSchema).optional(),
@@ -346,6 +373,11 @@ export interface MessageMetadata {
cost?: number;
/** @deprecated use `metadata.performance` instead */
duration?: number;
+ /**
+ * The provider event that produced this server-injected user turn
+ * (GitHub CI failure, review feedback, …). See {@link ExternalOriginMetadata}.
+ */
+ externalOrigin?: ExternalOriginMetadata;
finishType?: string;
/** Operation owning the durable heterogeneous tool-state watermark. */
heterogeneousToolStateOperationId?: string;
@@ -417,11 +449,11 @@ export interface MessageMetadata {
isSupervisor?: boolean;
/** @deprecated use `metadata.performance` instead */
latency?: number;
+
/**
* Local-system tool snapshots materialized when the user sent @file mentions.
*/
localSystemToolSnapshots?: LocalSystemToolSnapshot[];
-
/**
* Orchestration role of the message author within a group conversation.
* `'supervisor'` = the group's coordinating agent, `'member'` = a delegated
diff --git a/packages/types/src/scm.ts b/packages/types/src/scm.ts
index a64e659aa95..bdaac205a52 100644
--- a/packages/types/src/scm.ts
+++ b/packages/types/src/scm.ts
@@ -20,6 +20,24 @@ export type ScmInstallationAccountType = 'organization' | 'user';
/** Whether the installation covers every repository of the account or a chosen subset. */
export type ScmRepositorySelection = 'all' | 'selected';
+/**
+ * How the provider relates an actor to the repository. GitHub's
+ * `author_association`, lower-cased; `none` covers a passer-by.
+ */
+export type ScmActorAssociation =
+ 'collaborator' | 'contributor' | 'member' | 'none' | 'owner' | 'unknown';
+
+/**
+ * Associations whose word is trusted enough to steer an unattended agent.
+ * Anyone below this bar can still comment; their text simply does not
+ * become an instruction with tools behind it.
+ */
+export const SCM_TRUSTED_ASSOCIATIONS: ReadonlySet<ScmActorAssociation> = new Set([
+ 'collaborator',
+ 'member',
+ 'owner',
+]);
+
/** One repository granted to an installation. Snapshot maintained from provider events. */
export interface ScmInstallationRepository {
externalId: string;
@@ -109,6 +127,12 @@ export interface ScmChangeRequestMetadata {
[key: string]: unknown;
/** Acceptance links parsed out of the change request body. */
acceptanceIdsFromBody?: string[];
+ /**
+ * Who is currently posting the tracking comment, as an ISO timestamp.
+ * Taken atomically so concurrent deliveries cannot each post one; goes
+ * stale on its own if the post never finishes.
+ */
+ commentClaimedAt?: string;
/**
* Provider-clock timestamp of the newest change-request event applied.
* Kept apart from the `lastEventAt` column, which also records events we
@@ -116,6 +140,10 @@ export interface ScmChangeRequestMetadata {
* two provider timestamps.
*/
lastProviderEventAt?: string;
+ /** The most recent time the agent was notified about this change request, and why. */
+ lastWake?: { at: string; reason: string };
+ /** Provider id of the LobeHub comment posted on this change request, once posted. */
+ lobehubCommentId?: string;
/** Provider's mergeability verdict, when it exposes one (`MERGEABLE`, `CONFLICTING`, …). */
mergeable?: string;
/**
@@ -125,6 +153,13 @@ export interface ScmChangeRequestMetadata {
* rollup when that job never reports again.
*/
pendingChecks?: { checks: ScmCheck[]; sha: string };
+ /**
+ * A wake the debounce window swallowed. The next event on this change
+ * request delivers it, so the last failure of a burst is not lost.
+ */
+ pendingWake?: { reason: string; since: string };
+ /** Whether the repository is private, when the provider said. Drives the comment switches. */
+ repoPrivate?: boolean;
/**
* Latest effective verdict per reviewer, keyed by provider user id. The
* change request's `reviewDecision` is the rollup of these: one
diff --git a/packages/types/src/verify.ts b/packages/types/src/verify.ts
index 7ac954a8101..754052094ae 100644
--- a/packages/types/src/verify.ts
+++ b/packages/types/src/verify.ts
@@ -375,6 +375,19 @@ export type VerifyEvidenceCapturedBy =
* `verify_runs.user_decision` verb stays the queryable field.
*/
export interface VerifyRunDecisionDetail {
+ /**
+ * The provider change request whose merge made this decision, when
+ * `source` is `scm_merge`. Lets the board and the verifier-training
+ * pipeline tell a human verdict apart from a merge-driven one.
+ */
+ changeRequest?: {
+ /** Provider user id of whoever merged; resolves through the SCM identities. */
+ mergedByExternalId?: string;
+ number: number;
+ provider: string;
+ repoFullName: string;
+ url: string;
+ };
/** Free-form reason, e.g. the reject note that seeds the next repair round. */
comment?: string;
/** When the decision was made (ISO 8601). */
@@ -391,6 +404,12 @@ export interface VerifyRunDecisionDetail {
* staleness falls out of the round chain.
*/
groupFeedback?: VerifyRunGroupFeedbackEntry[];
+ /**
+ * What made the decision. Absent means a human clicked accept / reject;
+ * `scm_merge` means the linked pull request was merged, which LobeHub
+ * treats as the strongest possible acceptance signal.
+ */
+ source?: 'scm_merge';
}
/**
diff --git a/src/features/Conversation/Markdown/plugins/ScmEvent/Render.tsx b/src/features/Conversation/Markdown/plugins/ScmEvent/Render.tsx
new file mode 100644
index 00000000000..d3113e8f668
--- /dev/null
+++ b/src/features/Conversation/Markdown/plugins/ScmEvent/Render.tsx
@@ -0,0 +1,367 @@
+'use client';
+
+import { Github } from '@lobehub/icons';
+import { Flexbox, Icon } from '@lobehub/ui';
+import { Text } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cx } from 'antd-style';
+import {
+ ChevronRightIcon,
+ CircleCheckIcon,
+ CircleXIcon,
+ ExternalLinkIcon,
+ MessageSquareTextIcon,
+} from 'lucide-react';
+import { memo, type ReactNode, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { type MarkdownElementProps } from '../type';
+import {
+ type ParsedScmEvent,
+ parseScmEvent,
+ safeScmUrl,
+ type ScmEventAttributes,
+ type ScmEventCheck,
+ type ScmEventReview,
+} from './parseScmEvent';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ body: css`
+ padding-block: 2px;
+ padding-inline: 0;
+ `,
+ check: css`
+ padding-block: 8px;
+
+ &:not(:last-child) {
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+ }
+ `,
+ checkFailed: css`
+ color: ${cssVar.colorError};
+ `,
+ checkPassed: css`
+ color: ${cssVar.colorSuccess};
+ `,
+ header: css`
+ padding-block: 4px 10px;
+ padding-inline: 0;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+ `,
+ instruction: css`
+ padding-block: 8px 2px;
+ padding-inline: 0;
+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};
+
+ font-size: 12px;
+ line-height: 1.6;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ link: css`
+ /* The Markdown host paints anchors in the link colour; inside the card
+ a link reads as text and the trailing icon says it can be clicked. */
+ display: inline-flex;
+ gap: 4px;
+ align-items: center;
+
+ color: inherit !important;
+ text-decoration: none;
+
+ &:hover {
+ color: ${cssVar.colorTextSecondary} !important;
+ text-decoration: none;
+ }
+ `,
+ log: css`
+ overflow: auto;
+
+ max-block-size: 320px;
+ margin-block: 6px 0;
+ margin-inline: 0;
+ padding-block: 8px;
+ padding-inline: 10px;
+ border-radius: ${cssVar.borderRadiusSM};
+
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 11px;
+ line-height: 1.5;
+ color: ${cssVar.colorTextSecondary};
+ white-space: pre;
+
+ background: ${cssVar.colorFillQuaternary};
+ `,
+ logToggle: css`
+ cursor: pointer;
+ user-select: none;
+
+ display: inline-flex;
+ flex: none;
+ gap: 2px;
+ align-items: center;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+
+ &:hover {
+ color: ${cssVar.colorText};
+ }
+ `,
+ logToggleOpen: css`
+ svg {
+ transform: rotate(90deg);
+ }
+ `,
+ mark: css`
+ display: flex;
+ flex: none;
+ align-items: center;
+ justify-content: center;
+
+ inline-size: 28px;
+ block-size: 28px;
+ border-radius: 6px;
+
+ color: ${cssVar.colorText};
+
+ background: ${cssVar.colorFillTertiary};
+ `,
+ mono: css`
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 12px;
+ `,
+ pill: css`
+ flex: none;
+
+ padding-block: 2px;
+ padding-inline: 8px;
+ border-radius: 999px;
+
+ font-size: 12px;
+ font-weight: 500;
+ line-height: 18px;
+ `,
+ pillDanger: css`
+ color: ${cssVar.colorError};
+ background: ${cssVar.colorErrorBg};
+ `,
+ pillNeutral: css`
+ color: ${cssVar.colorTextSecondary};
+ background: ${cssVar.colorFillSecondary};
+ `,
+ pillWarning: css`
+ color: ${cssVar.colorWarning};
+ background: ${cssVar.colorWarningBg};
+ `,
+ review: css`
+ padding-block: 8px;
+
+ &:not(:last-child) {
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+ }
+ `,
+ reviewBody: css`
+ font-size: 13px;
+ line-height: 1.6;
+ color: ${cssVar.colorText};
+ word-break: break-word;
+ white-space: pre-wrap;
+ `,
+ root: css`
+ overflow: hidden;
+
+ inline-size: 100%;
+ min-inline-size: 320px;
+
+ font-size: 13px;
+ text-align: start;
+ `,
+}));
+
+const PILL_STYLE: Record<string, string> = {
+ ci_failed: styles.pillDanger,
+ review_changes_requested: styles.pillWarning,
+ review_commented: styles.pillNeutral,
+};
+
+const isFailed = (check: ScmEventCheck) =>
+ check.conclusion !== undefined && check.conclusion !== 'success';
+
+/**
+ * One line per check: what leads the line (the event pill when this is the
+ * only check, else a pass/fail glyph), the name and conclusion, then the
+ * details link and the log toggle on the same line. The log itself folds
+ * out underneath.
+ */
+const CheckRow = memo<{ check: ScmEventCheck; leading?: ReactNode }>(({ check, leading }) => {
+ const { t } = useTranslation('integration');
+ const [open, setOpen] = useState(false);
+ const failed = isFailed(check);
+
+ return (
+ <Flexbox className={styles.check} gap={4}>
+ <Flexbox horizontal align="center" gap={8}>
+ {leading ?? (
+ <Icon
+ className={failed ? styles.checkFailed : styles.checkPassed}
+ icon={failed ? CircleXIcon : CircleCheckIcon}
+ size="small"
+ />
+ )}
+ <Text ellipsis style={{ minWidth: 0 }} weight={500}>
+ {check.name}
+ </Text>
+ {check.conclusion ? (
+ <Text style={{ flex: 'none', fontSize: 12 }} type="secondary">
+ {check.conclusion}
+ </Text>
+ ) : null}
+ <span style={{ flex: 1 }} />
+ {check.url ? (
+ <a className={styles.link} href={check.url} rel="noreferrer" target="_blank">
+ <Text style={{ fontSize: 12 }} type="secondary">
+ {t('scmEvent.details')}
+ </Text>
+ <Icon icon={ExternalLinkIcon} size={12} />
+ </a>
+ ) : null}
+ {check.log ? (
+ <span
+ className={cx(styles.logToggle, open && styles.logToggleOpen)}
+ onClick={() => setOpen((v) => !v)}
+ >
+ {open ? t('scmEvent.hideLog') : t('scmEvent.showLog')}
+ <Icon icon={ChevronRightIcon} size={12} />
+ </span>
+ ) : null}
+ </Flexbox>
+ {check.log && open ? <pre className={styles.log}>{check.log}</pre> : null}
+ </Flexbox>
+ );
+});
+
+CheckRow.displayName = 'ScmEventCheckRow';
+
+const ReviewRow = memo<{ review: ScmEventReview }>(({ review }) => {
+ const location = review.path
+ ? `${review.path}${review.line ? `:${review.line}` : ''}`
+ : undefined;
+ const meta = [review.state?.replaceAll('_', ' '), location].filter(Boolean).join(' · ');
+ const author = review.url ? (
+ <a className={styles.link} href={review.url} rel="noreferrer" target="_blank">
+ @{review.author}
+ <Icon icon={ExternalLinkIcon} size={12} />
+ </a>
+ ) : (
+ `@${review.author}`
+ );
+
+ return (
+ <Flexbox className={styles.review} gap={4}>
+ <Flexbox horizontal align="center" gap={8}>
+ <Icon icon={MessageSquareTextIcon} size="small" style={{ opacity: 0.6 }} />
+ <Text weight={500}>{author}</Text>
+ {meta ? (
+ <Text className={styles.mono} type="secondary">
+ {meta}
+ </Text>
+ ) : null}
+ </Flexbox>
+ <div className={styles.reviewBody} style={{ paddingInlineStart: 24 }}>
+ {review.body}
+ </div>
+ </Flexbox>
+ );
+});
+
+ReviewRow.displayName = 'ScmEventReviewRow';
+
+/**
+ * A GitHub-styled card for the wake-up message the SCM integration injects
+ * into a conversation: the pull request in the header, then one status
+ * line that carries the event (as a pill) together with what it is about —
+ * the failing check with its details link and log toggle, or the reviewers
+ * — and the instruction the agent was given as a footer.
+ */
+const Render = memo<MarkdownElementProps<ScmEventAttributes>>(({ children, node }) => {
+ const { t } = useTranslation('integration');
+ const attrs = node?.properties ?? ({} as ScmEventAttributes);
+ const text = typeof children === 'string' ? children : String(children ?? '');
+ const parsed = useMemo<ParsedScmEvent>(() => parseScmEvent(text), [text]);
+
+ const title = attrs.repo
+ ? `${attrs.repo}${attrs.number ? ` #${attrs.number}` : ''}`
+ : (attrs.url ?? '');
+ const kindLabel = t(`scmEvent.kind.${attrs.kind}` as any, { defaultValue: attrs.kind });
+ const subtitle = [attrs.branch, attrs.sha].filter(Boolean).join(' @ ');
+ const pill = (
+ <span className={cx(styles.pill, PILL_STYLE[attrs.kind] ?? styles.pillNeutral)}>
+ {kindLabel}
+ </span>
+ );
+
+ // The header link is a tag attribute, so it skips the parser's guard.
+ const headerUrl = safeScmUrl(attrs.url);
+ const single = parsed.checks.length === 1 ? parsed.checks[0] : null;
+ const many = parsed.checks.length > 1 ? parsed.checks : null;
+ const reviewers = [...new Set(parsed.reviews.map((review) => `@${review.author}`))];
+
+ return (
+ <div className={styles.root}>
+ <Flexbox horizontal align="center" className={styles.header} gap={10}>
+ <span className={styles.mark}>
+ <Github size={16} />
+ </span>
+ <Flexbox flex={1} gap={1} style={{ minWidth: 0 }}>
+ <Text ellipsis weight={500}>
+ {headerUrl ? (
+ <a className={styles.link} href={headerUrl} rel="noreferrer" target="_blank">
+ {title}
+ <Icon icon={ExternalLinkIcon} size={12} />
+ </a>
+ ) : (
+ title
+ )}
+ </Text>
+ {subtitle ? (
+ <Text ellipsis className={styles.mono} type="secondary">
+ {subtitle}
+ </Text>
+ ) : null}
+ </Flexbox>
+ </Flexbox>
+
+ <div className={styles.body}>
+ {single ? <CheckRow check={single} leading={pill} /> : null}
+ {many ? (
+ <>
+ <Flexbox horizontal align="center" className={styles.check} gap={8}>
+ {pill}
+ <Text type="secondary">
+ {t('scmEvent.failedChecks', {
+ count: many.filter((check) => isFailed(check)).length,
+ })}
+ </Text>
+ </Flexbox>
+ {many.map((check, index) => (
+ <CheckRow check={check} key={`${check.name}-${index}`} />
+ ))}
+ </>
+ ) : null}
+ {!single && !many ? (
+ <Flexbox horizontal align="center" className={styles.check} gap={8}>
+ {pill}
+ {reviewers.length > 0 ? <Text type="secondary">{reviewers.join(' · ')}</Text> : null}
+ </Flexbox>
+ ) : null}
+ {parsed.reviews.map((review, index) => (
+ <ReviewRow key={`${review.author}-${index}`} review={review} />
+ ))}
+ </div>
+
+ {parsed.instruction ? <div className={styles.instruction}>{parsed.instruction}</div> : null}
+ </div>
+ );
+});
+
+Render.displayName = 'ScmEventRender';
+
+export default Render;
diff --git a/src/features/Conversation/Markdown/plugins/ScmEvent/index.ts b/src/features/Conversation/Markdown/plugins/ScmEvent/index.ts
new file mode 100644
index 00000000000..e22fb052c45
--- /dev/null
+++ b/src/features/Conversation/Markdown/plugins/ScmEvent/index.ts
@@ -0,0 +1,14 @@
+import { SCM_EVENT_TAG } from '@/const/plugin';
+
+import { type MarkdownElement } from '../type';
+import { remarkScmEventBlock } from './remarkScmEventBlock';
+import Component from './Render';
+
+const ScmEventElement: MarkdownElement = {
+ Component,
+ remarkPlugin: remarkScmEventBlock,
+ scope: 'user',
+ tag: SCM_EVENT_TAG,
+};
+
+export default ScmEventElement;
diff --git a/src/features/Conversation/Markdown/plugins/ScmEvent/integration.test.ts b/src/features/Conversation/Markdown/plugins/ScmEvent/integration.test.ts
new file mode 100644
index 00000000000..be5f03f08f5
--- /dev/null
+++ b/src/features/Conversation/Markdown/plugins/ScmEvent/integration.test.ts
@@ -0,0 +1,72 @@
+import remarkParse from 'remark-parse';
+import { unified } from 'unified';
+import { describe, expect, it } from 'vitest';
+
+import { remarkScmEventBlock } from './remarkScmEventBlock';
+
+const runRemark = (markdown: string) => {
+ const processor = unified().use(remarkParse).use(remarkScmEventBlock);
+ const tree = processor.parse(markdown);
+ return processor.runSync(tree);
+};
+
+const blocks = (tree: any) => (tree.children as any[]).filter((c) => c.type === 'scmEventBlock');
+
+describe('scmEvent remark integration', () => {
+ it('captures the server-shaped block verbatim, with the open tag attributes as properties', () => {
+ const markdown = `<scmEvent branch="feat/x" kind="ci_failed" number="7" provider="github" repo="o/r" sha="abcdef0" url="https://github.com/o/r/pull/7">
+<check conclusion="failure" name="Test" url="https://github.com/o/r/actions/runs/9/job/2">
+<log><![CDATA[
+FAIL src/a.test.ts
+ expected 1
+]]></log>
+</check>
+<instruction>
+Investigate the failure and fix it.
+</instruction>
+</scmEvent>`;
+
+ const tree: any = runRemark(markdown);
+ const found = blocks(tree);
+ expect(found).toHaveLength(1);
+ expect(found[0].data.hProperties).toEqual({
+ branch: 'feat/x',
+ kind: 'ci_failed',
+ number: '7',
+ provider: 'github',
+ repo: 'o/r',
+ sha: 'abcdef0',
+ url: 'https://github.com/o/r/pull/7',
+ });
+ const inner = found[0].data.hChildren[0].value as string;
+ expect(inner).toContain('<log><![CDATA[\nFAIL src/a.test.ts\n expected 1\n]]></log>');
+ expect(inner).toContain('<instruction>\nInvestigate the failure and fix it.\n</instruction>');
+ });
+
+ it('still finds the closing tag when a blank line split the block', () => {
+ const markdown = `<scmEvent kind="review_commented" provider="github" repo="o/r">
+<review author="codex"><![CDATA[
+first
+]]></review>
+
+<instruction>
+Address it.
+</instruction>
+</scmEvent>
+
+Trailing paragraph.`;
+
+ const tree: any = runRemark(markdown);
+ const found = blocks(tree);
+ expect(found).toHaveLength(1);
+ const inner = found[0].data.hChildren[0].value as string;
+ expect(inner).toContain('<review author="codex">');
+ expect(inner).toContain('Address it.');
+ expect(tree.children.at(-1).type).toBe('paragraph');
+ });
+
+ it('leaves messages without the tag alone', () => {
+ const tree: any = runRemark('Plain user text with <b>html</b>.');
+ expect(blocks(tree)).toHaveLength(0);
+ });
+});
diff --git a/src/features/Conversation/Markdown/plugins/ScmEvent/parseScmEvent.test.ts b/src/features/Conversation/Markdown/plugins/ScmEvent/parseScmEvent.test.ts
new file mode 100644
index 00000000000..419c9796dd1
--- /dev/null
+++ b/src/features/Conversation/Markdown/plugins/ScmEvent/parseScmEvent.test.ts
@@ -0,0 +1,116 @@
+import { describe, expect, it } from 'vitest';
+
+import { parseAttributes, parseScmEvent, safeScmUrl } from './parseScmEvent';
+
+// Mirrors what apps/server/src/services/scm/wakePrompt.ts emits.
+const ciInner = `<check conclusion="failure" name="Test" url="https://github.com/o/r/actions/runs/9/job/2">
+<log><![CDATA[
+FAIL src/a.test.ts
+ expected 1
+]]></log>
+</check>
+<check conclusion="failure" name="Build &quot;x&quot;" />
+<instruction>
+GitHub reported a failing check on pull request o/r#7, which you opened from this conversation. Investigate the failure and fix it.
+</instruction>`;
+
+const reviewInner = `<review author="codex" state="changes_requested" url="https://github.com/o/r/pull/7#pullrequestreview-1"><![CDATA[
+Please split the handler.
+]]></review>
+<review author="codex" line="42" path="src/x.ts"><![CDATA[
+Guard is inverted.
+See line 40.
+]]></review>
+<instruction>
+A reviewer requested changes on pull request o/r#7.
+</instruction>`;
+
+describe('parseScmEvent', () => {
+ it('reads checks with their log tails, self-closing checks, and the instruction', () => {
+ const parsed = parseScmEvent(ciInner);
+ expect(parsed.checks).toEqual([
+ {
+ conclusion: 'failure',
+ log: 'FAIL src/a.test.ts\n expected 1',
+ name: 'Test',
+ url: 'https://github.com/o/r/actions/runs/9/job/2',
+ },
+ { conclusion: 'failure', log: undefined, name: 'Build "x"', url: undefined },
+ ]);
+ expect(parsed.reviews).toEqual([]);
+ expect(parsed.instruction).toBe(
+ 'GitHub reported a failing check on pull request o/r#7, which you opened from this conversation. Investigate the failure and fix it.',
+ );
+ });
+
+ it('reads reviews with their location and state', () => {
+ const parsed = parseScmEvent(reviewInner);
+ expect(parsed.reviews).toEqual([
+ {
+ author: 'codex',
+ body: 'Please split the handler.',
+ line: undefined,
+ path: undefined,
+ state: 'changes_requested',
+ url: 'https://github.com/o/r/pull/7#pullrequestreview-1',
+ },
+ {
+ author: 'codex',
+ body: 'Guard is inverted.\nSee line 40.',
+ line: 42,
+ path: 'src/x.ts',
+ state: undefined,
+ url: undefined,
+ },
+ ]);
+ });
+
+ it('joins a log whose CDATA had to be split around a terminator', () => {
+ const parsed = parseScmEvent(
+ '<check name="T"><log><![CDATA[\na ]]]]><![CDATA[> b\n]]></log></check>',
+ );
+ expect(parsed.checks[0].log).toBe('a ]]> b');
+ });
+
+ it('degrades to an empty event on garbage', () => {
+ expect(parseScmEvent('')).toEqual({ checks: [], reviews: [] });
+ expect(parseScmEvent('<check>')).toEqual({ checks: [], reviews: [] });
+ });
+
+ it('unescapes attribute values', () => {
+ expect(parseAttributes('repo="o/r" name="a &amp; b &lt;c&gt;"')).toEqual({
+ name: 'a & b <c>',
+ repo: 'o/r',
+ });
+ });
+});
+
+describe('safeScmUrl', () => {
+ it('keeps http(s) and drops every other scheme', () => {
+ expect(safeScmUrl('https://github.com/o/r/pull/7')).toBe('https://github.com/o/r/pull/7');
+ expect(safeScmUrl('http://localhost:3000/x')).toBe('http://localhost:3000/x');
+ // The block is markdown anyone can write, and on desktop a click on the
+ // card's anchor reaches shell.openExternal — an OS handler must not be
+ // one message away.
+ for (const hostile of [
+ 'vscode://file/etc/passwd',
+ 'file:///etc/passwd',
+ 'javascript:alert(1)',
+ 'not a url',
+ '',
+ ]) {
+ expect(safeScmUrl(hostile)).toBeUndefined();
+ }
+ expect(safeScmUrl(undefined)).toBeUndefined();
+ });
+
+ it('strips a hostile url off the parsed checks and reviews', () => {
+ const parsed = parseScmEvent(
+ '<check name="Test" url="vscode://file/etc/passwd" />' +
+ '<review author="a" url="javascript:alert(1)"><![CDATA[hi]]></review>',
+ );
+
+ expect(parsed.checks[0]).toMatchObject({ name: 'Test', url: undefined });
+ expect(parsed.reviews[0]).toMatchObject({ author: 'a', url: undefined });
+ });
+});
diff --git a/src/features/Conversation/Markdown/plugins/ScmEvent/parseScmEvent.ts b/src/features/Conversation/Markdown/plugins/ScmEvent/parseScmEvent.ts
new file mode 100644
index 00000000000..071ef1b8348
--- /dev/null
+++ b/src/features/Conversation/Markdown/plugins/ScmEvent/parseScmEvent.ts
@@ -0,0 +1,118 @@
+export type ScmEventKind = 'ci_failed' | 'review_changes_requested' | 'review_commented';
+
+export interface ScmEventCheck {
+ conclusion?: string;
+ log?: string;
+ name: string;
+ url?: string;
+}
+
+export interface ScmEventReview {
+ author: string;
+ body: string;
+ line?: number;
+ path?: string;
+ state?: string;
+ url?: string;
+}
+
+export interface ScmEventAttributes {
+ branch?: string;
+ kind: ScmEventKind | string;
+ number?: string;
+ provider: string;
+ repo?: string;
+ sha?: string;
+ url?: string;
+}
+
+export interface ParsedScmEvent {
+ checks: ScmEventCheck[];
+ instruction?: string;
+ reviews: ScmEventReview[];
+}
+
+/**
+ * A card link the renderer may turn into an anchor.
+ *
+ * The block is markdown a message author can write by hand, and on desktop
+ * a click on an anchor reaches `shell.openExternal` — so an `scmEvent` with
+ * a `vscode:` or `file:` url would launch an OS protocol handler. Only
+ * http(s) survives parsing; anything else is dropped and the field renders
+ * as plain text. Same rule as `openTrustedExternalUrl`, applied one layer
+ * earlier so every consumer of the parsed event inherits it.
+ */
+export const safeScmUrl = (value: string | undefined): string | undefined => {
+ if (!value) return undefined;
+ try {
+ const { protocol, href } = new URL(value);
+ return protocol === 'http:' || protocol === 'https:' ? href : undefined;
+ } catch {
+ return undefined;
+ }
+};
+
+const unescapeAttribute = (value: string) =>
+ value
+ .replaceAll('&quot;', '"')
+ .replaceAll('&lt;', '<')
+ .replaceAll('&gt;', '>')
+ .replaceAll('&amp;', '&');
+
+/** `key="value"` pairs of an open tag, values unescaped. */
+export const parseAttributes = (raw: string): Record<string, string> => {
+ const result: Record<string, string> = {};
+ for (const match of raw.matchAll(/([\w:-]+)="([^"]*)"/g)) {
+ result[match[1]] = unescapeAttribute(match[2]);
+ }
+ return result;
+};
+
+/** The text of every CDATA section in `raw`, joined; plain text when there is none. */
+const cdataText = (raw: string) => {
+ const sections = [...raw.matchAll(/<!\[CDATA\[([\S\s]*?)\]\]>/g)].map((m) => m[1]);
+ const text = sections.length > 0 ? sections.join('') : raw;
+ return text.replace(/^\n/, '').replace(/\n$/, '');
+};
+
+/**
+ * Parses the children of a `<scmEvent>` block emitted by the server's wake
+ * prompt: `<check … />` or `<check …><log><![CDATA[…]]></log></check>`,
+ * `<review …><![CDATA[…]]></review>` and `<instruction>…</instruction>`.
+ * Tolerant by design — anything it does not recognise is ignored, never
+ * thrown on, so a malformed block degrades to an empty card, not a crash.
+ */
+export const parseScmEvent = (raw: string): ParsedScmEvent => {
+ const result: ParsedScmEvent = { checks: [], reviews: [] };
+ if (!raw) return result;
+
+ for (const match of raw.matchAll(/<check\b([^>]*?)(?:\/>|>([\S\s]*?)<\/check>)/g)) {
+ const attrs = parseAttributes(match[1] ?? '');
+ if (!attrs.name) continue;
+ const logMatch = match[2] ? /<log>([\S\s]*?)<\/log>/.exec(match[2]) : null;
+ result.checks.push({
+ conclusion: attrs.conclusion,
+ log: logMatch ? cdataText(logMatch[1]) : undefined,
+ name: attrs.name,
+ url: safeScmUrl(attrs.url),
+ });
+ }
+
+ for (const match of raw.matchAll(/<review\b([^>]*)>([\S\s]*?)<\/review>/g)) {
+ const attrs = parseAttributes(match[1] ?? '');
+ const line = attrs.line ? Number(attrs.line) : undefined;
+ result.reviews.push({
+ author: attrs.author ?? 'unknown',
+ body: cdataText(match[2]),
+ line: Number.isFinite(line) ? line : undefined,
+ path: attrs.path,
+ state: attrs.state,
+ url: safeScmUrl(attrs.url),
+ });
+ }
+
+ const instruction = /<instruction>([\S\s]*?)<\/instruction>/.exec(raw);
+ if (instruction) result.instruction = instruction[1].trim();
+
+ return result;
+};
diff --git a/src/features/Conversation/Markdown/plugins/ScmEvent/remarkScmEventBlock.ts b/src/features/Conversation/Markdown/plugins/ScmEvent/remarkScmEventBlock.ts
new file mode 100644
index 00000000000..bbb1fe8ea44
--- /dev/null
+++ b/src/features/Conversation/Markdown/plugins/ScmEvent/remarkScmEventBlock.ts
@@ -0,0 +1,71 @@
+import { SKIP, visit } from 'unist-util-visit';
+
+import { SCM_EVENT_TAG } from '@/const/plugin';
+
+import { treeNodeToString } from '../remarkPlugins/getNodeContent';
+import { parseAttributes } from './parseScmEvent';
+
+const OPEN_RE = new RegExp(String.raw`<${SCM_EVENT_TAG}\b([^>]*)>`);
+const CLOSE_TAG = `</${SCM_EVENT_TAG}>`;
+
+/**
+ * Captures `<scmEvent …>…</scmEvent>` blocks from a markdown AST into one
+ * node carrying the open tag's attributes as properties and the raw inner
+ * text as its only child.
+ *
+ * The server emits the block without blank lines, so CommonMark keeps it in
+ * a single `html` node and the inner text arrives verbatim. Should a blank
+ * line ever sneak in, the closing tag is searched in the following siblings
+ * and their content re-serialised, at the cost of exact whitespace.
+ */
+export const remarkScmEventBlock = () => (tree: any) => {
+ visit(tree, 'html', (node, index, parent) => {
+ if (!parent || index == null || typeof node.value !== 'string') return;
+
+ const open = OPEN_RE.exec(node.value);
+ if (!open) return;
+ const attributes = parseAttributes(open[1] ?? '');
+ const afterOpen = open.index + open[0].length;
+
+ const sameNodeClose = node.value.indexOf(CLOSE_TAG, afterOpen);
+ if (sameNodeClose !== -1) {
+ const inner = node.value.slice(afterOpen, sameNodeClose).trim();
+ parent.children.splice(index, 1, buildNode(attributes, inner, node.position));
+ return [SKIP, index + 1];
+ }
+
+ const collected: string[] = [node.value.slice(afterOpen)];
+ let cursor = index + 1;
+ let closed = false;
+ while (cursor < parent.children.length) {
+ const sibling = parent.children[cursor];
+ const text =
+ sibling.type === 'html' && typeof sibling.value === 'string'
+ ? sibling.value
+ : treeNodeToString([sibling]);
+ const closeAt = text.indexOf(CLOSE_TAG);
+ if (closeAt !== -1) {
+ collected.push(text.slice(0, closeAt));
+ closed = true;
+ break;
+ }
+ collected.push(text);
+ cursor++;
+ }
+ if (!closed) return;
+
+ const inner = collected.join('\n').trim();
+ parent.children.splice(index, cursor - index + 1, buildNode(attributes, inner, node.position));
+ return [SKIP, index + 1];
+ });
+};
+
+const buildNode = (attributes: Record<string, string>, inner: string, position?: any) => ({
+ data: {
+ hChildren: [{ type: 'text', value: inner }],
+ hName: SCM_EVENT_TAG,
+ hProperties: attributes,
+ },
+ position,
+ type: `${SCM_EVENT_TAG}Block`,
+});
diff --git a/src/features/Conversation/Markdown/plugins/index.ts b/src/features/Conversation/Markdown/plugins/index.ts
index ee206e70c76..b9bc0f1db24 100644
--- a/src/features/Conversation/Markdown/plugins/index.ts
+++ b/src/features/Conversation/Markdown/plugins/index.ts
@@ -7,6 +7,7 @@ import LobeThinking from './LobeThinking';
import LocalFile from './LocalFile';
import LocalFileLink from './LocalFileLink';
import Mention from './Mention';
+import ScmEvent from './ScmEvent';
import Skill from './Skill';
import Task from './Task';
import Thinking from './Thinking';
@@ -25,6 +26,7 @@ export const markdownElements: MarkdownElement[] = [
Skill,
Tool,
Task,
+ ScmEvent,
UserFeedback,
ImageSearchRef,
LobeAgents,