Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(review): keep review context current

Chris7be1495ef20e
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index e8e0b886e0..ebeef6bf4e 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -185,6 +185,7 @@ import { buildReviewPrompt } from '../reviewer/reviewPrompt.js';
import {
listReviewHistoricalAttachments,
loadReviewEvidence,
+ readReviewContextFingerprint,
readReviewWorkspaceSnapshot,
resolveReviewArtifactPath,
SensitiveReviewPathError,
@@ -202,6 +203,7 @@ import {
import { fingerprintReviewArtifacts } from '../reviewer/reviewArtifactFingerprint.js';
import { enforceReviewCreateOptions } from '../reviewer/reviewSessionPolicy.js';
import { reviewSourceIdentityMatches } from '../reviewer/reviewSourceIdentity.js';
+import { buildReviewSessionTitle } from '../reviewer/reviewSessionTitle.js';
import { readReviewRunFromAgentMeta, type ReviewRunMeta } from '../../shared/reviewRun.js';
import {
applyAgentSwitchToSessionRow,
@@ -6791,7 +6793,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
effort: source.effort as CreateOpts['effort'],
fastMode: !!source.fastMode,
providerId: source.providerId,
- title: `审查 · ${source.title}`.slice(0, 120),
+ title: buildReviewSessionTitle(source.title),
permissionMode: 'ask',
planMode: false,
reviewMode: true,
@@ -6800,6 +6802,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
...(readRoots.size > 0 ? { extraDirs: [...readRoots] } : {}),
}),
verifyBeforeStart: async () => {
+ if (
+ maker.getSession(source.id)?.isTurnRunning() ||
+ (await readReviewContextFingerprint(source.id)) !== evidence.contextFingerprint
+ ) {
+ throw new Error(
+ 'The task conversation changed before Review started. Run /review again for the current context.',
+ );
+ }
if (
(await fingerprintReviewArtifacts(authorizedArtifactPaths)) !==
sourceArtifactFingerprint
@@ -6822,6 +6832,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (!reviewSourceIdentityMatches(source, currentSource ?? null)) {
return 'The source task workspace changed while Review was running. Run /review again in the current workspace.';
}
+ if (
+ maker.getSession(source.id)?.isTurnRunning() ||
+ (await readReviewContextFingerprint(source.id)) !== evidence.contextFingerprint
+ ) {
+ return 'The task conversation changed while Review was running. Run /review again for the current context.';
+ }
if (evidence.workspaceFingerprint) {
const currentWorkspace = await readReviewWorkspaceSnapshot(source.id);
if (currentWorkspace?.fingerprint !== evidence.workspaceFingerprint) {
diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewEvidence.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewEvidence.test.ts
index cae39df38f..3cd5ed1c84 100644
--- a/apps/desktop/src/main/reviewer/__tests__/reviewEvidence.test.ts
+++ b/apps/desktop/src/main/reviewer/__tests__/reviewEvidence.test.ts
@@ -17,7 +17,7 @@ vi.mock('../../localDb/client/current.js', () => ({
select: () => ({
from: () => ({
where: () => ({
- orderBy: () => ({ limit: async () => reviewRows }),
+ orderBy: () => ({ limit: async (limit: number) => reviewRows.slice(0, limit) }),
}),
}),
}),
@@ -50,7 +50,11 @@ import {
} from '../reviewArtifactAuthorization.js';
import type { ReviewPdfUtilityChildLike } from '../reviewPdfProcess.js';
import type { ReviewPdfUtilityRequest } from '../reviewPdfProcessProtocol.js';
-import { listReviewHistoricalAttachments, loadReviewEvidence } from '../reviewEvidence.js';
+import {
+ listReviewHistoricalAttachments,
+ loadReviewEvidence,
+ readReviewContextFingerprint,
+} from '../reviewEvidence.js';
const tempDirs: string[] = [];
@@ -89,6 +93,90 @@ afterEach(async () => {
});
describe('loadReviewEvidence attachment boundaries', () => {
+ it('fingerprints source-task activity while ignoring Review lifecycle cards', async () => {
+ const workingDir = await tempDir();
+ reviewRows.push({
+ role: 'user',
+ content: JSON.stringify({ text: 'original request' }),
+ agentMeta: null,
+ createdAt: 1,
+ id: 'message-1',
+ });
+
+ const evidence = await loadReviewEvidence({
+ sourceSessionId: 'source',
+ workingDir,
+ attachments: [],
+ explicitArtifactGrant: {
+ paths: [],
+ pathIdentities: new Map(),
+ inlineAttachmentKeys: [],
+ },
+ });
+ expect(await readReviewContextFingerprint('source')).toBe(evidence.contextFingerprint);
+
+ reviewRows.push({
+ role: 'assistant',
+ content: JSON.stringify({ text: 'new result without file changes' }),
+ agentMeta: null,
+ createdAt: 2,
+ id: 'message-2',
+ });
+ const changedFingerprint = await readReviewContextFingerprint('source');
+ expect(changedFingerprint).not.toBe(evidence.contextFingerprint);
+
+ reviewRows.push({
+ role: 'assistant',
+ content: '',
+ agentMeta: JSON.stringify({ internalOnly: true }),
+ createdAt: 3,
+ id: 'hidden-card',
+ });
+ expect(await readReviewContextFingerprint('source')).toBe(changedFingerprint);
+
+ reviewRows.push({
+ role: 'assistant',
+ content: '',
+ agentMeta: JSON.stringify({
+ reviewRun: {
+ version: 1,
+ runId: 'review-run',
+ sourceSessionId: 'source',
+ reviewerSessionId: 'reviewer',
+ status: 'running',
+ targetKind: 'mixed',
+ startedAt: 3,
+ },
+ }),
+ createdAt: 4,
+ id: 'review-card',
+ });
+ expect(await readReviewContextFingerprint('source')).toBe(changedFingerprint);
+ });
+
+ it('does not let a hidden lifecycle row evict the twentieth visible context message', async () => {
+ reviewRows.push(
+ ...Array.from({ length: 20 }, (_, index) => ({
+ role: index % 2 === 0 ? 'user' : 'assistant',
+ content: JSON.stringify({ text: `visible-${20 - index}` }),
+ agentMeta: null,
+ createdAt: 20 - index,
+ id: `message-${String(20 - index).padStart(2, '0')}`,
+ })),
+ );
+ const initialFingerprint = await readReviewContextFingerprint('source');
+
+ reviewRows.unshift({
+ role: 'assistant',
+ content: '',
+ agentMeta: JSON.stringify({ goalCompletion: { status: 'completed' } }),
+ createdAt: 21,
+ id: 'hidden-goal-card',
+ });
+
+ expect(await readReviewContextFingerprint('source')).toBe(initialFingerprint);
+ });
+
it('uses MIME-only image classification for the harness block', async () => {
const workingDir = await tempDir();
const requestedPath = path.join(workingDir, 'poster');
diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewSessionTitle.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewSessionTitle.test.ts
new file mode 100644
index 0000000000..76b466d73c
--- /dev/null
+++ b/apps/desktop/src/main/reviewer/__tests__/reviewSessionTitle.test.ts
@@ -0,0 +1,23 @@
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { setMainLocale } from '../../i18n.js';
+import { buildReviewSessionTitle } from '../reviewSessionTitle.js';
+
+afterEach(() => setMainLocale('en'));
+
+describe('buildReviewSessionTitle', () => {
+ it.each([
+ ['en', 'Review · Source task'],
+ ['zh-CN', '审查 · Source task'],
+ ['ja', 'レビュー · Source task'],
+ ['ko', '검토 · Source task'],
+ ] as const)('uses the active %s locale', (locale, expected) => {
+ setMainLocale(locale);
+ expect(buildReviewSessionTitle('Source task')).toBe(expected);
+ });
+
+ it('preserves the existing persisted-title bound', () => {
+ setMainLocale('en');
+ expect(buildReviewSessionTitle('x'.repeat(200))).toHaveLength(120);
+ });
+});
diff --git a/apps/desktop/src/main/reviewer/reviewEvidence.ts b/apps/desktop/src/main/reviewer/reviewEvidence.ts
index e867a9c20f..b0a29fd7cd 100644
--- a/apps/desktop/src/main/reviewer/reviewEvidence.ts
+++ b/apps/desktop/src/main/reviewer/reviewEvidence.ts
@@ -3,7 +3,7 @@ import path from 'node:path';
import { createHash } from 'node:crypto';
import { isReviewSensitiveCredentialPath } from '@cindy/maker-core';
-import { and, desc, eq, inArray, isNull } from 'drizzle-orm';
+import { and, desc, eq, inArray, isNull, lt, ne, notLike, or } from 'drizzle-orm';
import { getDbClient } from '../localDb/client/current.js';
import { visibleMessageTextForConversationSearch } from '../localDb/conversationSearch.pure.js';
@@ -59,6 +59,7 @@ export interface ReviewAttachmentBlock {
export interface LoadedReviewEvidence {
context: ReviewContextMessage[];
+ contextFingerprint: string;
workspace: ReviewWorkspaceEvidence | null;
workspaceFingerprint: string | null;
changeSet: TurnChangeSetDetail | null;
@@ -73,6 +74,7 @@ export interface LoadedReviewEvidence {
}
const MAX_CONTEXT_ROWS = 20;
+const CONTEXT_QUERY_PAGE_SIZE = 64;
// A single invocation accepts at most 20 explicit attachments plus one focus
// path. Keep a small margin for task-history artifacts before declaring the
// evidence list partial.
@@ -152,27 +154,103 @@ function hasReviewRunMeta(raw: unknown): boolean {
return readReviewRunFromAgentMeta(raw) !== null;
}
-async function readReviewVisibleRows(sourceSessionId: string) {
+type ReviewVisibleRow = {
+ role: 'user' | 'assistant';
+ content: string;
+ agentMeta: string | null;
+ createdAt: number;
+ id: string;
+};
+
+async function readReviewVisibleRows(sourceSessionId: string): Promise<ReviewVisibleRow[]> {
const db = getDbClient().drizzle;
- const rows = await db
- .select({
- role: messages.role,
- content: messages.content,
- agentMeta: messages.agentMeta,
- createdAt: messages.createdAt,
- id: messages.id,
- })
- .from(messages)
- .where(
- and(
- eq(messages.sessionId, sourceSessionId),
- inArray(messages.role, ['user', 'assistant']),
- isNull(messages.rewindAt),
- ),
- )
- .orderBy(desc(messages.createdAt), desc(messages.id))
- .limit(MAX_CONTEXT_ROWS);
- return rows.filter((row) => !hasReviewRunMeta(row.agentMeta)).reverse();
+ const rows: ReviewVisibleRow[] = [];
+ let cursor: { createdAt: number; id: string } | null = null;
+
+ while (rows.length < MAX_CONTEXT_ROWS) {
+ const page = (await db
+ .select({
+ role: messages.role,
+ content: messages.content,
+ agentMeta: messages.agentMeta,
+ createdAt: messages.createdAt,
+ id: messages.id,
+ })
+ .from(messages)
+ .where(
+ and(
+ eq(messages.sessionId, sourceSessionId),
+ inArray(messages.role, ['user', 'assistant']),
+ isNull(messages.rewindAt),
+ ne(messages.content, ''),
+ // Exclude Review status cards in SQL so they cannot consume query
+ // pages. The JS parser below remains the fail-closed authority.
+ or(isNull(messages.agentMeta), notLike(messages.agentMeta, '%"reviewRun"%')),
+ cursor
+ ? or(
+ lt(messages.createdAt, cursor.createdAt),
+ and(eq(messages.createdAt, cursor.createdAt), lt(messages.id, cursor.id)),
+ )
+ : undefined,
+ ),
+ )
+ .orderBy(desc(messages.createdAt), desc(messages.id))
+ .limit(CONTEXT_QUERY_PAGE_SIZE)) as ReviewVisibleRow[];
+ if (page.length === 0) break;
+
+ const last: ReviewVisibleRow = page[page.length - 1]!;
+ cursor = { createdAt: last.createdAt, id: last.id };
+ for (const row of page) {
+ const visibleRow = row;
+ if (hasReviewRunMeta(visibleRow.agentMeta)) continue;
+ const hasVisibleText =
+ visibleMessageTextForConversationSearch(visibleRow.role, visibleRow.content).length > 0;
+ const hasHistoricalArtifact = historicalAttachmentsFromRows([visibleRow]).length > 0;
+ if (!hasVisibleText && !hasHistoricalArtifact) continue;
+ rows.push(visibleRow);
+ if (rows.length === MAX_CONTEXT_ROWS) break;
+ }
+ if (page.length < CONTEXT_QUERY_PAGE_SIZE) break;
+ }
+
+ return rows.reverse();
+}
+
+function fingerprintReviewContextRows(rows: readonly ReviewVisibleRow[]): string {
+ const visibleMessages = rows.flatMap((row) => {
+ const text = visibleMessageTextForConversationSearch(row.role, row.content);
+ return text
+ ? [
+ {
+ id: row.id,
+ createdAt: row.createdAt,
+ role: row.role,
+ text,
+ },
+ ]
+ : [];
+ });
+ const historicalArtifacts = historicalAttachmentsFromRows(rows).map((attachment) => ({
+ name: attachment.name,
+ path: attachment.path,
+ url: attachment.url,
+ category: attachment.category,
+ mimeType: attachment.mimeType,
+ originalName: attachment.originalName,
+ }));
+ return createHash('sha256')
+ .update(JSON.stringify({ visibleMessages, historicalArtifacts }))
+ .digest('hex');
+}
+
+/**
+ * Fingerprint the bounded visible text and historical artifact references
+ * supplied to a reviewer. Hidden row fields and Review status cards are
+ * deliberately absent, so lifecycle updates cannot invalidate their own run
+ * while genuine task activity does.
+ */
+export async function readReviewContextFingerprint(sourceSessionId: string): Promise<string> {
+ return fingerprintReviewContextRows(await readReviewVisibleRows(sourceSessionId));
}
function persistedFileRefs(content: unknown): Array<{ path: string; name?: string }> {
@@ -191,9 +269,7 @@ function persistedFileRefs(content: unknown): Array<{ path: string; name?: strin
return refs;
}
-function historicalAttachmentsFromRows(
- rows: Awaited<ReturnType<typeof readReviewVisibleRows>>,
-): ReviewAttachmentInput[] {
+function historicalAttachmentsFromRows(rows: readonly ReviewVisibleRow[]): ReviewAttachmentInput[] {
const attachments: ReviewAttachmentInput[] = [];
for (const row of rows) {
for (const url of imageCacheStore.collectSessionImageUrls(row.content)) {
@@ -488,6 +564,7 @@ export async function loadReviewEvidence(input: {
return {
context,
+ contextFingerprint: fingerprintReviewContextRows(visibleRows),
workspace,
workspaceFingerprint: workspaceSnapshot?.fingerprint ?? null,
changeSet,
diff --git a/apps/desktop/src/main/reviewer/reviewSessionTitle.ts b/apps/desktop/src/main/reviewer/reviewSessionTitle.ts
new file mode 100644
index 0000000000..6db4b23b85
--- /dev/null
+++ b/apps/desktop/src/main/reviewer/reviewSessionTitle.ts
@@ -0,0 +1,9 @@
+import { t } from '../i18n.js';
+
+const MAX_REVIEW_SESSION_TITLE_LENGTH = 120;
+
+export function buildReviewSessionTitle(sourceTitle: string): string {
+ return t('review.sessionTitle')
+ .replaceAll('{{title}}', sourceTitle)
+ .slice(0, MAX_REVIEW_SESSION_TITLE_LENGTH);
+}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 767694a212..7b1dd2da50 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -8779,6 +8779,7 @@
}
},
"review": {
+ "sessionTitle": "Review · {{title}}",
"toast": {
"failed": "Couldn't start review",
"remoteUnsupported": "This version can only review local tasks"
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index bc4e1cdfe2..fd44b54c5f 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -8765,6 +8765,7 @@
}
},
"review": {
+ "sessionTitle": "レビュー · {{title}}",
"toast": {
"failed": "レビューを開始できませんでした",
"remoteUnsupported": "このバージョンではローカルタスクのみレビューできます"
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 6c1130ea98..b8ac5283eb 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -8765,6 +8765,7 @@
}
},
"review": {
+ "sessionTitle": "검토 · {{title}}",
"toast": {
"failed": "검토를 시작할 수 없습니다",
"remoteUnsupported": "이 버전에서는 로컬 작업만 검토할 수 있습니다"
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index c4745dca5c..037a6bf1ad 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -8765,6 +8765,7 @@
}
},
"review": {
+ "sessionTitle": "审查 · {{title}}",
"toast": {
"failed": "无法开始审查",
"remoteUnsupported": "当前版本只支持审查本机任务"