Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(agent-documents): stop a failed split modify midway and stop claiming run authorship (#20044)

Arvin Xuc0ad257ad7ac
diff --git a/packages/context-engine/src/providers/AgentDocumentInjector/shared.ts b/packages/context-engine/src/providers/AgentDocumentInjector/shared.ts
index bb2048564d2..e1d5335cc76 100644
--- a/packages/context-engine/src/providers/AgentDocumentInjector/shared.ts
+++ b/packages/context-engine/src/providers/AgentDocumentInjector/shared.ts
@@ -60,9 +60,12 @@ export interface AgentDocumentFilterContext {
currentTime?: Date;
currentUserMessage?: string;
/**
- * When the current run started. Documents created at or after it are marked in
- * the progressive index; the index is rebuilt every step, so without a marker a
- * document the agent just created looks like one that already existed.
+ * When the current run started (the latest user message by default). Documents
+ * created at or after it are marked in the progressive index; the index is
+ * rebuilt every step, so without a marker a document the agent just created
+ * looks like one that already existed. Documents are listed per agent, not per
+ * topic or run, so the marker only states the timestamp fact: a marked doc may
+ * also come from another topic or tab.
*/
runStartedAt?: Date | number | string;
truncateContent?: (content: string, maxTokens: number) => string;
@@ -75,8 +78,8 @@ const toTime = (value: Date | number | string | undefined): number | undefined =
};
/**
- * Anchor the run to the latest user message: everything the agent did after it
- * belongs to the current run. An explicit `runStartedAt` wins.
+ * Anchor the run to the latest user message: documents created after it are
+ * marked as new. An explicit `runStartedAt` wins.
*/
export function withRunStartedAt<T extends AgentDocumentFilterContext>(
context: T,
@@ -195,13 +198,13 @@ function truncate(s: string, max: number): string {
return s.length > max ? `${s.slice(0, max - 1)}…` : s;
}
-const CREATED_THIS_RUN_MARK = '(created this run)';
+const NEW_SINCE_USER_MESSAGE_MARK = '(new since last user message)';
/** Collapsed folders hide their rows, so the folder summary carries the count instead. */
-const withCreatedThisRunCount = (summary: string, count: number) =>
- count > 0 ? `${summary} (${count} created this run)` : summary;
+const withNewSinceUserMessageCount = (summary: string, count: number) =>
+ count > 0 ? `${summary} (${count} new since last user message)` : summary;
-function isCreatedThisRun(doc: AgentContextDocument, context: AgentDocumentFilterContext) {
+function isNewSinceUserMessage(doc: AgentContextDocument, context: AgentDocumentFilterContext) {
const runStartedAt = toTime(context.runStartedAt);
const createdAt = toTime(doc.createdAt);
return runStartedAt !== undefined && createdAt !== undefined && createdAt >= runStartedAt;
@@ -222,7 +225,7 @@ function buildIndexTable(
return {
id: d.id ?? '',
size: formatSize(d),
- title: isCreatedThisRun(d, context) ? `${title} ${CREATED_THIS_RUN_MARK}` : title,
+ title: isNewSinceUserMessage(d, context) ? `${title} ${NEW_SINCE_USER_MESSAGE_MARK}` : title,
updated: formatUpdatedDate(d.updatedAt),
};
});
@@ -326,9 +329,9 @@ function buildFolderTable(folders: FolderGroup[], context: AgentDocumentFilterCo
const rows = folders
.map((f) => ({
id: f.parentId,
- summary: withCreatedThisRunCount(
+ summary: withNewSinceUserMessageCount(
formatFolderSummary(f.docs),
- f.docs.filter((doc) => isCreatedThisRun(doc, context)).length,
+ f.docs.filter((doc) => isNewSinceUserMessage(doc, context)).length,
),
time: newestTime(f.docs),
title: `${FOLDER_ICON} ${truncate(f.title, TITLE_MAX_WIDTH)}`,
@@ -410,9 +413,9 @@ export function combineDocuments(
`Web-crawled docs are available but omitted here β€” call listDocuments(sourceType='web') to discover them.`,
);
}
- if (userDocs.some((doc) => isCreatedThisRun(doc, context))) {
+ if (userDocs.some((doc) => isNewSinceUserMessage(doc, context))) {
headerLines.push(
- `Docs marked ${CREATED_THIS_RUN_MARK} (or counted that way in a folder row) did not exist before this run β€” you created them, so creating them did not overwrite an existing doc.`,
+ `Docs marked ${NEW_SINCE_USER_MESSAGE_MARK} (or counted that way in a folder row) were created after the user's latest message β€” by you or elsewhere (another topic, or the user). A marked doc you created was new; creating it did not overwrite an existing doc.`,
);
}
if (folders.length > 0) {
diff --git a/packages/context-engine/src/providers/__tests__/AgentDocumentInjector.test.ts b/packages/context-engine/src/providers/__tests__/AgentDocumentInjector.test.ts
index 46b11f08e76..b091bc8e59f 100644
--- a/packages/context-engine/src/providers/__tests__/AgentDocumentInjector.test.ts
+++ b/packages/context-engine/src/providers/__tests__/AgentDocumentInjector.test.ts
@@ -228,7 +228,7 @@ describe('AgentDocumentInjector', () => {
// The index is rebuilt every step, so a doc the agent created earlier in the
// same run showed up as if it already existed and was read as "overwritten".
- it('marks docs created during the current run in the progressive index', async () => {
+ it('marks docs created after the latest user message in the progressive index', async () => {
const runStartedAt = new Date('2026-09-23T22:57:30.000Z').getTime();
const provider = new AgentDocumentContextInjector({
documents: [
@@ -265,16 +265,16 @@ describe('AgentDocumentInjector', () => {
expect(result.messages[0].content).toMatchInlineSnapshot(`
"<agent_documents_index>
User-created docs, when present, are listed below β€” use readDocument(id) for full content.
- Docs marked (created this run) (or counted that way in a folder row) did not exist before this run β€” you created them, so creating them did not overwrite an existing doc.
+ Docs marked (new since last user message) (or counted that way in a folder row) were created after the user's latest message β€” by you or elsewhere (another topic, or the user). A marked doc you created was new; creating it did not overwrite an existing doc.
- TITLE ID SIZE UPDATED
- FASE G-2C (created this run) ce2c4f3a empty 2026-09-23
- FASE G-2B 452eea73 empty 2026-09-21
+ TITLE ID SIZE UPDATED
+ FASE G-2C (new since last user message) ce2c4f3a empty 2026-09-23
+ FASE G-2B 452eea73 empty 2026-09-21
</agent_documents_index>"
`);
});
- it('counts docs created during the current run inside collapsed folders', async () => {
+ it('counts docs created after the latest user message inside collapsed folders', async () => {
const runStartedAt = new Date('2026-09-23T22:57:30.000Z').getTime();
const inFolder = (id: string, createdAt: string) => ({
createdAt: new Date(createdAt),
@@ -300,8 +300,40 @@ describe('AgentDocumentInjector', () => {
);
const content = result.messages[0].content as string;
- expect(content).toContain('did not exist before this run');
- expect(content).toMatch(/πŸ“ Reports\s+folder-1\s+2 docs \(1 created this run\)/);
+ expect(content).toContain("were created after the user's latest message");
+ expect(content).toMatch(/πŸ“ Reports\s+folder-1\s+2 docs \(1 new since last user message\)/);
+ });
+
+ // The document query is agent-scoped, so a doc created after the latest
+ // user message may come from another topic or tab: the marker must state the
+ // known timestamp fact instead of claiming the current run created it.
+ it('does not attribute docs created after the latest user message to the current run', async () => {
+ const lastUserMessageAt = new Date('2026-09-23T22:57:30.000Z').getTime();
+ const provider = new AgentDocumentContextInjector({
+ documents: [
+ {
+ createdAt: new Date('2026-09-23T22:58:10.000Z'),
+ filename: 'other-topic.md',
+ id: 'other-1',
+ loadPosition: 'before-first-user',
+ loadRules: { rule: 'always' },
+ policyLoad: 'progressive',
+ title: 'Created in another topic',
+ updatedAt: new Date('2026-09-23T22:58:10.000Z'),
+ },
+ ],
+ });
+
+ const result = await provider.process(
+ createContext([
+ { content: 'go', createdAt: lastUserMessageAt, id: 'user-1', role: 'user' },
+ ]),
+ );
+ const content = result.messages[0].content as string;
+
+ expect(content).not.toContain('this run');
+ expect(content).not.toContain('you created them');
+ expect(content).toContain('Created in another topic (new since last user message)');
});
// https://github.com/lobehub/lobehub/issues/15624 β€” relative times ("15m ago")
diff --git a/packages/editor-runtime/src/EditorRuntime.ts b/packages/editor-runtime/src/EditorRuntime.ts
index e3ae4d783ad..2704241d16e 100644
--- a/packages/editor-runtime/src/EditorRuntime.ts
+++ b/packages/editor-runtime/src/EditorRuntime.ts
@@ -457,11 +457,21 @@ export class EditorRuntime {
// reporting it: the editor drops operations with unknown ids (or that it
// cannot apply) without an error.
// A step may apply only part of one operation (a split `modify`), so an
- // operation succeeds only when none of its steps failed.
+ // operation succeeds only when none of its steps failed. Once a step of an
+ // operation fails, its remaining steps are skipped; a failure after an
+ // earlier step of the same operation applied is reported as partial.
for (const step of planLiteXMLEditSteps(operations, indexLiteXMLDocument(readLiteXML()))) {
+ if (step.indexes.some((index) => results[index].error)) continue;
+
const fail = (error: string) => {
for (const index of step.indexes) {
- results[index] = { ...results[index], error, success: false };
+ const partiallyApplied = results[index].success;
+ results[index] = {
+ ...results[index],
+ error,
+ success: false,
+ ...(partiallyApplied && { partiallyApplied }),
+ };
}
};
diff --git a/packages/editor-runtime/src/__tests__/EditorRuntime.real.test.ts b/packages/editor-runtime/src/__tests__/EditorRuntime.real.test.ts
index bc7fec89eb0..ca270071044 100644
--- a/packages/editor-runtime/src/__tests__/EditorRuntime.real.test.ts
+++ b/packages/editor-runtime/src/__tests__/EditorRuntime.real.test.ts
@@ -279,6 +279,40 @@ describe('EditorRuntime - Real Cases', () => {
expect(editor.getDocument('markdown') as unknown as string).toContain('- a\n');
});
+ it('skips the rest of a split modify once one of its steps fails', async () => {
+ const item = idOf('li', 'b');
+ const result = await runtime.modifyNodes({
+ operations: [
+ {
+ action: 'modify',
+ litexml: ['<p id="zzzz">stale</p>', `<li id="${item}"><span>b2</span></li>`],
+ },
+ ],
+ });
+
+ // The non-list fragment fails first; the list fragment must not be
+ // written behind an operation reported as not applied.
+ expect(result.results[0]).toMatchObject({ success: false });
+ expect(result.results[0].partiallyApplied).toBeUndefined();
+ expect(editor.getDocument('markdown') as unknown as string).not.toContain('b2');
+ });
+
+ it('reports a split modify that fails after its first step as partially applied', async () => {
+ const intro = idOf('p', 'intro');
+ const result = await runtime.modifyNodes({
+ operations: [
+ {
+ action: 'modify',
+ litexml: [`<p id="${intro}">intro2</p>`, '<li id="zzzz"><span>x</span></li>'],
+ },
+ ],
+ });
+
+ expect(result.results[0]).toMatchObject({ partiallyApplied: true, success: false });
+ expect(result.results[0].error).toContain('"zzzz" not found');
+ expect(editor.getDocument('markdown') as unknown as string).toContain('intro2');
+ });
+
it('reports an empty insert as failed even when merged with a real one', async () => {
const anchor = idOf('p', 'intro');
const result = await runtime.modifyNodes({
diff --git a/packages/editor-runtime/src/__tests__/formatModifyNodesResult.test.ts b/packages/editor-runtime/src/__tests__/formatModifyNodesResult.test.ts
index 14158616103..241ae9aa462 100644
--- a/packages/editor-runtime/src/__tests__/formatModifyNodesResult.test.ts
+++ b/packages/editor-runtime/src/__tests__/formatModifyNodesResult.test.ts
@@ -33,4 +33,22 @@ describe('formatModifyNodesResult', () => {
Call getPageContent to get the current node ids before retrying the failed operations."
`);
});
+
+ it('flags an operation that failed after part of it was applied', () => {
+ const content = formatModifyNodesResult({
+ results: [
+ {
+ action: 'modify',
+ error: 'node "zzzz" not found in the document',
+ partiallyApplied: true,
+ success: false,
+ },
+ ],
+ successCount: 0,
+ totalCount: 1,
+ });
+
+ expect(content).toContain('except those marked PARTIALLY APPLIED');
+ expect(content).toContain('- Operation 1 (modify): PARTIALLY APPLIED');
+ });
});
diff --git a/packages/editor-runtime/src/formatModifyNodesResult.ts b/packages/editor-runtime/src/formatModifyNodesResult.ts
index a8dbf6d505e..7a87f2d6cc0 100644
--- a/packages/editor-runtime/src/formatModifyNodesResult.ts
+++ b/packages/editor-runtime/src/formatModifyNodesResult.ts
@@ -2,7 +2,9 @@ import type { ModifyNodesRuntimeResult } from './types';
/**
* Tool message for a page-agent `modifyNodes` call. Failed operations are listed
- * with their reason so the model retries them instead of assuming they applied.
+ * with their reason so the model retries them instead of assuming they applied;
+ * one that failed after part of it was written is flagged so a retry does not
+ * duplicate the applied part.
*/
export const formatModifyNodesResult = ({
results,
@@ -23,16 +25,26 @@ export const formatModifyNodesResult = ({
}
const failures = results
- .map((result, index) =>
- result.success
- ? undefined
- : `- Operation ${index + 1} (${result.action}): ${result.error ?? 'not applied'}`,
- )
+ .map((result, index) => {
+ if (result.success) return undefined;
+
+ const reason = result.error ?? 'not applied';
+ return result.partiallyApplied
+ ? `- Operation ${index + 1} (${result.action}): PARTIALLY APPLIED β€” some of its fragments were already written before it failed: ${reason}`
+ : `- Operation ${index + 1} (${result.action}): ${reason}`;
+ })
.filter(Boolean);
+ const hasPartial = results.some((result) => !result.success && result.partiallyApplied);
return [
- `Only ${successCount}/${totalCount} operations succeeded (${summary} requested). Failed operations were not applied:`,
+ `Only ${successCount}/${totalCount} operations succeeded (${summary} requested). ${
+ hasPartial
+ ? 'Failed operations were not applied, except those marked PARTIALLY APPLIED:'
+ : 'Failed operations were not applied:'
+ }`,
...failures,
- 'Call getPageContent to get the current node ids before retrying the failed operations.',
+ hasPartial
+ ? 'Call getPageContent to get the current node ids and content before retrying; re-send only the parts of a partially applied operation that are still missing.'
+ : 'Call getPageContent to get the current node ids before retrying the failed operations.',
].join('\n');
};
diff --git a/packages/editor-runtime/src/types.ts b/packages/editor-runtime/src/types.ts
index bf38680cb91..cf559a9e713 100644
--- a/packages/editor-runtime/src/types.ts
+++ b/packages/editor-runtime/src/types.ts
@@ -63,6 +63,11 @@ export interface ReplaceTextArgs {
export interface ModifyOperationResult {
action: 'insert' | 'remove' | 'modify';
error?: string;
+ /**
+ * The operation failed after part of it was already written to the page
+ * (a `modify` split into several steps), so it is neither applied nor untouched.
+ */
+ partiallyApplied?: boolean;
success: boolean;
}