Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(session-ref): 不可缩短的邻居不再阻塞锚点回退裁剪
Zhang Yunjin08db6265aa88
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionReferenceResolver.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionReferenceResolver.test.tsindex 2185c3cd0c..23fbaf0854 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionReferenceResolver.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionReferenceResolver.test.ts@@ -286,6 +286,71 @@ describe('sessionReferenceResolver', () => {.toBeLessThanOrEqual(MAX_REFERENCE_TOKENS - 128);});+ it('trims the anchor instead of throwing when only a single-character neighbor remains', async () => {+ // The escaped anchor alone exceeds the final payload budget, and the only+ // neighbor cannot shed content: the fit must fall back to the anchor+ // instead of dropping the whole quote.+ remoteInvoke+ .mockResolvedValueOnce({ ok: true, result: { id: 's-1' } })+ .mockResolvedValueOnce({+ ok: true,+ result: [{+ id: 'anchor-id',+ clientId: 'anchor',+ sessionId: 's-1',+ role: 'assistant',+ content: '"'.repeat(30_000),+ createdAt: 100,+ }],+ })+ .mockResolvedValueOnce(historyPage([]))+ .mockResolvedValueOnce(historyPage([+ { id: 'after-id', sessionId: 's-1', role: 'user', content: 'x', createdAt: 101 },+ ]));++ const [context] = await resolveSessionReferences(+ [{ sessionId: 's-1', deviceId: 'dev-1', messageClientId: 'anchor' }],+ );++ expect(context.truncated).toBe(true);+ expect(context.messages[0]?.content.startsWith('…')).toBe(true);+ expect(context.messages[1]?.content).toBe('x');+ expect(estimateReferenceTokens(serializeSessionReferencePayload([context])))+ .toBeLessThanOrEqual(MAX_REFERENCE_TOKENS - 128);+ });++ it('trims the anchor after a two-character neighbor can no longer shrink', async () => {+ // The neighbor sheds down to one character and then stalls the loop; the+ // anchor fallback must still bring the payload under budget.+ remoteInvoke+ .mockResolvedValueOnce({ ok: true, result: { id: 's-1' } })+ .mockResolvedValueOnce({+ ok: true,+ result: [{+ id: 'anchor-id',+ clientId: 'anchor',+ sessionId: 's-1',+ role: 'assistant',+ content: '"'.repeat(30_000),+ createdAt: 100,+ }],+ })+ .mockResolvedValueOnce(historyPage([]))+ .mockResolvedValueOnce(historyPage([+ { id: 'after-id', sessionId: 's-1', role: 'user', content: 'ab', createdAt: 101 },+ ]));++ const [context] = await resolveSessionReferences(+ [{ sessionId: 's-1', deviceId: 'dev-1', messageClientId: 'anchor' }],+ );++ expect(context.truncated).toBe(true);+ expect(context.messages[0]?.content.startsWith('…')).toBe(true);+ expect(context.messages[1]?.content.length).toBeLessThanOrEqual(1);+ expect(estimateReferenceTokens(serializeSessionReferencePayload([context])))+ .toBeLessThanOrEqual(MAX_REFERENCE_TOKENS - 128);+ });+it('keeps the anchor when a long following message exhausts the token budget', async () => {remoteInvoke.mockResolvedValueOnce({ ok: true, result: { id: 's-1' } })diff --git a/apps/desktop/src/main/maker-ipc/sessionReferenceResolver.ts b/apps/desktop/src/main/maker-ipc/sessionReferenceResolver.tsindex cf6cdfd8da..d80081ee0e 100644--- a/apps/desktop/src/main/maker-ipc/sessionReferenceResolver.ts+++ b/apps/desktop/src/main/maker-ipc/sessionReferenceResolver.ts@@ -220,6 +220,9 @@ function fitSerializedPayloadBudget(for (let messageIndex = 0; messageIndex < context.messages.length; messageIndex += 1) {if (messageIndex === anchorPosition) continue;const message = context.messages[messageIndex];+ // A one-character body cannot shed more content; picking it would stall+ // the loop and mask the anchor fallback below.+ if (message.content.length <= 1) continue;if (!targetMessage || message.content.length > targetMessage.content.length) {targetContext = context;targetMessage = message;@@ -227,9 +230,11 @@ function fitSerializedPayloadBudget(}}if (!targetMessage) {- // Only anchors are left; the payload cap still has to hold.+ // No neighbor can shrink any further; trim the anchor rather than+ // dropping the whole quote.for (const context of contexts) {for (const message of context.messages) {+ if (message.content.length <= 1) continue;if (!targetMessage || message.content.length > targetMessage.content.length) {targetContext = context;targetMessage = message;@@ -237,7 +242,7 @@ function fitSerializedPayloadBudget(}}}- if (targetMessage && targetMessage.content.length > 1) {+ if (targetMessage) {const excess = tokens - FINAL_REFERENCE_PAYLOAD_TOKENS;const drop = Math.min(targetMessage.content.length - 1, Math.max(1, excess));targetMessage.content = `…${targetMessage.content.slice(drop + 1)}`;diff --git a/apps/mobile/src/__tests__/sessionReferences.test.ts b/apps/mobile/src/__tests__/sessionReferences.test.tsindex 444b6ab063..12b9b0dc3e 100644--- a/apps/mobile/src/__tests__/sessionReferences.test.ts+++ b/apps/mobile/src/__tests__/sessionReferences.test.ts@@ -594,6 +594,65 @@ describe('resolveMobileSessionReferences', () => {.toBeLessThanOrEqual(8_000 - 128);});+ it('trims the anchor instead of throwing when only a single-character neighbor remains', async () => {+ // The escaped anchor alone exceeds the final payload budget, and the only+ // neighbor cannot shed content: the fit must fall back to the anchor+ // instead of dropping the whole quote.+ const invoke = asInvoke(async (_deviceId, channel, args) => {+ if (channel === 'local-db:sessions:get') return { id: args[0] };+ if (channel === 'local-db:messages:around-client-id') {+ return [message('s1', '5', 'anchor', '"'.repeat(30_000), 'assistant', 5_000)];+ }+ if (channel === DL_HISTORY_MESSAGES_CHANNEL) {+ const request = args[0] as { order: string };+ return request.order === 'desc'+ ? { items: [], hasMore: false }+ : { items: [message('s1', '6', 'c6', 'x', 'user', 6_000)], hasMore: false };+ }+ throw new Error(`unexpected channel ${channel}`);+ });++ const [context] = await resolveMobileSessionReferences(+ [{ sessionId: 's1', messageClientId: 'anchor', deviceId: 'dev-b' }],+ invoke,+ );++ expect(context.truncated).toBe(true);+ expect(context.messages[0]?.content.startsWith('…')).toBe(true);+ expect(context.messages[1]?.content).toBe('x');+ expect(estimateMobileReferenceTokens(serializeMobileSessionReferencePayload([context])))+ .toBeLessThanOrEqual(8_000 - 128);+ });++ it('trims the anchor after a two-character neighbor can no longer shrink', async () => {+ // The neighbor sheds down to one character and then stalls the loop; the+ // anchor fallback must still bring the payload under budget.+ const invoke = asInvoke(async (_deviceId, channel, args) => {+ if (channel === 'local-db:sessions:get') return { id: args[0] };+ if (channel === 'local-db:messages:around-client-id') {+ return [message('s1', '5', 'anchor', '"'.repeat(30_000), 'assistant', 5_000)];+ }+ if (channel === DL_HISTORY_MESSAGES_CHANNEL) {+ const request = args[0] as { order: string };+ return request.order === 'desc'+ ? { items: [], hasMore: false }+ : { items: [message('s1', '6', 'c6', 'ab', 'user', 6_000)], hasMore: false };+ }+ throw new Error(`unexpected channel ${channel}`);+ });++ const [context] = await resolveMobileSessionReferences(+ [{ sessionId: 's1', messageClientId: 'anchor', deviceId: 'dev-b' }],+ invoke,+ );++ expect(context.truncated).toBe(true);+ expect(context.messages[0]?.content.startsWith('…')).toBe(true);+ expect(context.messages[1]?.content.length).toBeLessThanOrEqual(1);+ expect(estimateMobileReferenceTokens(serializeMobileSessionReferencePayload([context])))+ .toBeLessThanOrEqual(8_000 - 128);+ });+it('marks an anchored neighbor as truncated when it is partially kept', async () => {const invoke = asInvoke(async (_deviceId, channel, args) => {if (channel === 'local-db:sessions:get') return { id: args[0] };diff --git a/apps/mobile/src/session/sessionReferences.ts b/apps/mobile/src/session/sessionReferences.tsindex 4ed6516bff..0fbec3865d 100644--- a/apps/mobile/src/session/sessionReferences.ts+++ b/apps/mobile/src/session/sessionReferences.ts@@ -387,6 +387,9 @@ function fitSerializedPayloadBudget(for (let messageIndex = 0; messageIndex < context.messages.length; messageIndex += 1) {if (messageIndex === anchorPosition) continue;const message = context.messages[messageIndex];+ // A one-character body cannot shed more content; picking it would stall+ // the loop and mask the anchor fallback below.+ if (message.content.length <= 1) continue;if (!targetMessage || message.content.length > targetMessage.content.length) {targetContext = context;targetMessage = message;@@ -394,9 +397,11 @@ function fitSerializedPayloadBudget(}}if (!targetMessage) {- // Only anchors are left; the payload cap still has to hold.+ // No neighbor can shrink any further; trim the anchor rather than+ // dropping the whole quote.for (const context of contexts) {for (const message of context.messages) {+ if (message.content.length <= 1) continue;if (!targetMessage || message.content.length > targetMessage.content.length) {targetContext = context;targetMessage = message;@@ -404,7 +409,7 @@ function fitSerializedPayloadBudget(}}}- if (targetMessage && targetMessage.content.length > 1) {+ if (targetMessage) {const excess = tokens - FINAL_REFERENCE_PAYLOAD_TOKENS;const drop = Math.min(targetMessage.content.length - 1, Math.max(1, excess));targetMessage.content = `…${targetMessage.content.slice(drop + 1)}`;