Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions packages/cli/src/acp-integration/session/Session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1151,7 +1151,9 @@ export class Session implements SessionContext {

getRewindableUserTurnCount(): number {
const apiHistory = this.captureHistorySnapshot();
const startIndex = getStartupContextLength(apiHistory);
const startIndex = getStartupContextLength(apiHistory, {
includeCompressed: true,
});
let count = 0;

for (let i = startIndex; i < apiHistory.length; i++) {
Expand Down Expand Up @@ -1187,7 +1189,9 @@ export class Session implements SessionContext {
apiHistory: Content[],
targetTurnIndex: number,
): number {
const startIndex = getStartupContextLength(apiHistory);
const startIndex = getStartupContextLength(apiHistory, {
includeCompressed: true,
});

if (targetTurnIndex === 0) {
return startIndex;
Expand Down
4 changes: 3 additions & 1 deletion packages/cli/src/ui/utils/historyMapping.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,9 @@ export function computeApiTruncationIndex(
}

// Determine the starting index in the API history (skip startup context)
const startIndex = getStartupContextLength(apiHistory);
const startIndex = getStartupContextLength(apiHistory, {
includeCompressed: true,
});

if (uiUserTurnCount === 0) {
// Rewinding to the first user turn: keep only startup context (if any)
Expand Down
115 changes: 115 additions & 0 deletions packages/core/src/utils/environmentContext.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -616,6 +616,121 @@ describe('getStartupContextLength', () => {
);
expect(getStartupContextLength([merged])).toBe(0);
});

// Compressed history prefix: composePostCompactHistory produces
// [user(summary), model(ack), user(postAckParts)?, ...]. The ack sentinel
// is distinct from the legacy ack above.

it('is 0 for compressed prefixes by default', () => {
const history: Content[] = [
{
role: 'user',
parts: [{ text: 'summary text\n\nResume the prior task...' }],
},
{
role: 'model',
parts: [{ text: 'Got it. Thanks for the additional context!' }],
},
];
expect(getStartupContextLength(history)).toBe(0);
});

it('is 2 for rewind when a real prompt follows a compressed prefix', () => {
const history: Content[] = [
{
role: 'user',
parts: [{ text: 'summary text\n\nResume the prior task...' }],
},
{
role: 'model',
parts: [{ text: 'Got it. Thanks for the additional context!' }],
},
{
role: 'user',
parts: [{ text: 'Now do something else' }],
},
];
expect(getStartupContextLength(history, { includeCompressed: true })).toBe(
2,
);
});

it('is 3 for rewind with post-compact attachments', () => {
const history: Content[] = [
{
role: 'user',
parts: [{ text: 'summary text\n\nResume the prior task...' }],
},
{
role: 'model',
parts: [{ text: 'Got it. Thanks for the additional context!' }],
},
{
role: 'user',
parts: [
{
text:
'Recently accessed file (full current content embedded):\n\n' +
'## /repo/file.ts\n\n```ts\nexport const x = 1;\n```',
},
{ text: '<system-reminder>\nplan mode\n</system-reminder>' },
],
},
];
expect(getStartupContextLength(history, { includeCompressed: true })).toBe(
3,
);
});

it('is 4 for rewind with attachments and a trailing function call', () => {
const history: Content[] = [
{
role: 'user',
parts: [{ text: 'summary\n\nResume the prior task...' }],
},
{
role: 'model',
parts: [{ text: 'Got it. Thanks for the additional context!' }],
},
{
role: 'user',
parts: [{ text: '<plan-mode-active>\nplan\n</plan-mode-active>' }],
},
{
role: 'model',
parts: [{ functionCall: { name: 'fn', args: {} } }],
},
];
expect(getStartupContextLength(history, { includeCompressed: true })).toBe(
4,
);
});

it('is 2 for rewind with degraded compression fallback', () => {
const history: Content[] = [
{
role: 'user',
parts: [
{ text: 'summary\n\nResume the prior task...' },
{ text: '<system-reminder>\nplan mode active\n</system-reminder>' },
],
},
{
role: 'model',
parts: [
{ text: 'Got it. Thanks for the additional context!' },
{ functionCall: { name: 'fn', args: {} } },
],
},
{
role: 'user',
parts: [{ functionResponse: { name: 'fn', response: {} } }],
},
];
expect(getStartupContextLength(history, { includeCompressed: true })).toBe(
2,
);
});
});

describe('buildAvailableSkillsReminder', () => {
Expand Down
66 changes: 61 additions & 5 deletions packages/core/src/utils/environmentContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -571,12 +571,23 @@ export async function getInitialChatHistory(
}

/**
* Returns the number of initial API entries occupied by the startup reminder
* (0 or 1). A single user message wrapped in <system-reminder> is the only
* shape getInitialChatHistory currently produces, but routes through this
* helper so detection stays consistent across the CLI and ACP integration.
* Returns the number of initial API entries occupied by structural context
* that should be skipped when counting real user turns:
*
* - The startup reminder prelude (0 or 1 entry) — a single user message
* wrapped in `<system-reminder>…</system-reminder>`, produced by
* `getInitialChatHistory`.
* - The legacy ack-pair prelude (2 entries) — sessions saved before the
* startup context moved into system reminders.
* - The compressed-history prefix (2 or 3 entries) — summary, ack, and
* optionally a post-compact attachments entry produced by
* `composePostCompactHistory`. These synthetic entries must not be
* counted as real user prompts for rewind indexing.
*/
export function getStartupContextLength(history: Content[]): number {
export function getStartupContextLength(
history: Content[],
options: { includeCompressed?: boolean } = {},
): number {
const firstEntry = history[0];
if (firstEntry?.role !== 'user') return 0;
const firstText = firstEntry.parts?.[0]?.text;
Expand All @@ -601,9 +612,54 @@ export function getStartupContextLength(history: Content[]): number {
) {
return 2;
}
if (!options.includeCompressed) return 0;

// Post-compression prefix for rewind indexing only. The startup-context
// refresh/restore paths need compressed history to look like "no startup
// prelude" so they don't strip or skip the compressed summary.
if (
typeof firstText === 'string' &&
firstText.includes('Resume the prior task') &&
history[1]?.role === 'model' &&
history[1]?.parts?.[0]?.text ===
'Got it. Thanks for the additional context!'
) {
if (isPostCompactAttachmentEntry(history[2])) {
if (isModelFunctionCallEntry(history[3])) return 4;
return 3;
}
return 2;
}
return 0;
}

function isPostCompactAttachmentEntry(content: Content | undefined): boolean {
if (content?.role !== 'user') return false;
const parts = content.parts ?? [];
return parts.some(
(part) =>
typeof part.text === 'string' &&
(part.text.startsWith('<plan-mode-active>') ||
part.text.startsWith('<background-tasks>') ||
part.text.startsWith(
'The following files were recently accessed before context was compacted.',
) ||
part.text.startsWith(
'Recently accessed file (full current content embedded):',
) ||
part.text.startsWith(
'Recent visual snapshots preserved from before context was compacted',
)),
);
}

function isModelFunctionCallEntry(content: Content | undefined): boolean {
return (
content?.role === 'model' &&
(content.parts ?? []).some((part) => 'functionCall' in part)
);
}

Comment thread
yiliang114 marked this conversation as resolved.
Resolved
/**
* True when `content` is a *pure* system-reminder entry: it has parts and
* EVERY part is a text part wrapped in `<system-reminder>…</system-reminder>`.
Expand Down
Loading