Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,41 @@ describe('ToolCallEmitter', () => {
);
});

it('should not replay truncated session previews as full diffs', async () => {
await emitter.emitResult({
toolName: 'edit_file',
callId: 'call-edit',
success: true,
message: [],
resultDisplay: {
fileName: '/test/file.ts',
originalContent: 'old preview',
newContent: 'new preview',
truncatedForSession: true,
fileDiffLength: 200000,
fileDiffTruncated: true,
},
});

expect(sendUpdateSpy).toHaveBeenCalledWith(
expect.objectContaining({
sessionUpdate: 'tool_call_update',
toolCallId: 'call-edit',
status: 'completed',
content: [
{
type: 'content',
content: {
type: 'text',
text: 'Full diff omitted from saved session history for /test/file.ts. Original fileDiff length: 200000 chars.',
},
},
],
_meta: { toolName: 'edit_file' },
}),
);
});

it('should transform message parts to content', async () => {
await emitter.emitResult({
toolName: 'test_tool',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import type {
} from '@agentclientprotocol/sdk';
import type { Part } from '@google/genai';
import { ToolNames, Kind } from '@qwen-code/qwen-code-core';
import { buildTruncatedDiffPreviewText } from '../../../utils/truncatedDiffPreview.js';

/**
* Unified tool call event emitter.
Expand Down Expand Up @@ -273,6 +274,16 @@ export class ToolCallEmitter extends BaseEmitter {

// Check if this is a diff display (edit tool result)
if ('fileName' in obj && 'newContent' in obj) {
if (obj['truncatedForSession'] === true) {
return {
type: 'content',
content: {
type: 'text',
text: buildTruncatedDiffPreviewText(obj),
},
};
}

return {
type: 'diff',
path: obj['fileName'] as string,
Expand Down
21 changes: 21 additions & 0 deletions packages/cli/src/ui/components/messages/ToolMessage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,27 @@ describe('<ToolMessage />', () => {
expect(lastFrame()).toMatch(/MockDiff:--- a\/file\.txt/);
});

it('renders a saved-session preview notice for truncated diff results', () => {
const diffResult = {
fileDiff: '--- file.txt\n+++ file.txt\n@@ -1 +1 @@\n-omitted\n+preview',
fileName: 'file.txt',
originalContent: 'old preview',
newContent: 'new preview',
truncatedForSession: true,
fileDiffLength: 123456,
fileDiffTruncated: true,
};
const { lastFrame } = renderWithContext(
<ToolMessage {...baseProps} resultDisplay={diffResult} />,
StreamingState.Idle,
);

expect(lastFrame()).toContain(
'Saved session preview only; full diff omitted from JSONL (123456 chars).',
);
expect(lastFrame()).toContain('MockDiff:--- file.txt');
});

it('renders emphasis correctly', () => {
const { lastFrame: highEmphasisFrame } = renderWithContext(
<ToolMessage {...baseProps} emphasis="high" />,
Expand Down
50 changes: 39 additions & 11 deletions packages/cli/src/ui/components/messages/ToolMessage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import type {
AnsiOutputDisplay,
Config,
McpToolProgressData,
FileDiff,
} from '@qwen-code/qwen-code-core';
import { AgentExecutionDisplay } from '../subagents/index.js';
import { ToolConfirmationMessage } from './ToolConfirmationMessage.js';
Expand Down Expand Up @@ -49,6 +50,14 @@ const DEFAULT_SHELL_OUTPUT_MAX_LINES = 5;
// outputs that will get truncated further MaxSizedBox anyway.
const MAXIMUM_RESULT_DISPLAY_CHARACTERS = 1000000;
export type TextEmphasis = 'high' | 'medium' | 'low';
type DiffResultDisplay = Pick<
FileDiff,
| 'fileDiff'
| 'fileName'
| 'truncatedForSession'
| 'fileDiffLength'
| 'fileDiffTruncated'
>;

function sliceTextForMaxHeight(
text: string,
Expand Down Expand Up @@ -175,7 +184,7 @@ const useResultDisplayRenderer = (
) {
return {
type: 'diff',
data: resultDisplay as { fileDiff: string; fileName: string },
data: resultDisplay as DiffResultDisplay,
};
}

Expand Down Expand Up @@ -378,19 +387,38 @@ const StringResultRenderer: React.FC<{
* Component to render diff results
*/
const DiffResultRenderer: React.FC<{
data: { fileDiff: string; fileName: string };
data: DiffResultDisplay;
availableHeight?: number;
childWidth: number;
settings?: LoadedSettings;
}> = ({ data, availableHeight, childWidth, settings }) => (
<DiffRenderer
diffContent={data.fileDiff}
filename={data.fileName}
availableTerminalHeight={availableHeight}
contentWidth={childWidth}
settings={settings}
/>
);
}> = ({ data, availableHeight, childWidth, settings }) => {
const diffHeight =
data.truncatedForSession && availableHeight !== undefined
? Math.max(1, availableHeight - 1)
: availableHeight;

return (
<Box flexDirection="column">
{data.truncatedForSession && (
<Text color={theme.status.warning} wrap="wrap">
{data.fileDiffTruncated
? 'Saved session preview only; full diff omitted from JSONL'
: 'Saved session preview only; full file contents truncated in JSONL'}
{data.fileDiffTruncated && typeof data.fileDiffLength === 'number'
? ` (${data.fileDiffLength} chars).`
: '.'}
</Text>
)}
<DiffRenderer
diffContent={data.fileDiff}
filename={data.fileName}
availableTerminalHeight={diffHeight}
contentWidth={childWidth}
settings={settings}
/>
</Box>
);
};

export interface ToolMessageProps extends IndividualToolCallDisplay {
availableTerminalHeight?: number;
Expand Down
89 changes: 89 additions & 0 deletions packages/cli/src/ui/utils/export/collect.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/**
* @license
* Copyright 2025 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/

import { describe, expect, it, vi } from 'vitest';
import type { ChatRecord, Config } from '@qwen-code/qwen-code-core';
import { collectSessionData } from './collect.js';

describe('collectSessionData', () => {
const config = {
getToolRegistry: vi.fn().mockReturnValue({
getTool: vi.fn().mockReturnValue(null),
}),
} as unknown as Config;

it('skips line-count fallback for truncated saved-session previews', async () => {
const records: ChatRecord[] = [
{
uuid: 'assistant-1',
parentUuid: null,
sessionId: 'session-1',
timestamp: '2025-01-01T00:00:00.000Z',
type: 'assistant',
cwd: '',
version: '1.0.0',
message: {
role: 'model',
parts: [
{
functionCall: {
id: 'call-1',
name: 'edit_file',
args: { file_path: '/test/file.ts' },
},
},
],
},
},
{
uuid: 'tool-1',
parentUuid: 'assistant-1',
sessionId: 'session-1',
timestamp: '2025-01-01T00:00:01.000Z',
type: 'tool_result',
cwd: '',
version: '1.0.0',
message: {
role: 'user',
parts: [
{
functionResponse: {
id: 'call-1',
name: 'edit_file',
response: { output: 'ok' },
},
},
],
},
toolCallResult: {
callId: 'call-1',
resultDisplay: {
fileName: 'file.ts',
fileDiff:
'--- file.ts\n+++ file.ts\n@@ -1,2 +1,2 @@\n-old\n-preview\n+new\n+preview',
originalContent: 'old\npreview',
newContent: 'new\npreview',
truncatedForSession: true,
},
},
},
];

const data = await collectSessionData(
{
sessionId: 'session-1',
startTime: '2025-01-01T00:00:00.000Z',
messages: records,
},
config,
);

expect(data.metadata?.filesWritten).toBe(1);
expect(data.metadata?.uniqueFiles).toEqual(['/test/file.ts']);
expect(data.metadata?.linesAdded).toBe(0);
expect(data.metadata?.linesRemoved).toBe(0);
});
});
3 changes: 2 additions & 1 deletion packages/cli/src/ui/utils/export/collect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ function calculateFileStats(records: ChatRecord[]): FileOperationStats {
originalContent?: string | null;
newContent?: string;
diffStat?: { model_added_lines?: number; model_removed_lines?: number };
truncatedForSession?: boolean;
};

// Determine operation type based on content fields
Expand All @@ -197,7 +198,7 @@ function calculateFileStats(records: ChatRecord[]): FileOperationStats {
// Use diffStat if available for accurate counts
stats.linesAdded += display.diffStat.model_added_lines ?? 0;
stats.linesRemoved += display.diffStat.model_removed_lines ?? 0;
} else {
} else if (!display.truncatedForSession) {
// Fallback: count lines in content
const oldText = String(display.originalContent ?? '');
const newText = String(display.newContent ?? '');
Expand Down
72 changes: 72 additions & 0 deletions packages/cli/src/ui/utils/export/normalize.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/**
* @license
* Copyright 2025 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/

import { describe, expect, it, vi } from 'vitest';
import type { ChatRecord, Config } from '@qwen-code/qwen-code-core';
import { normalizeSessionData } from './normalize.js';

describe('normalizeSessionData', () => {
const config = {
getToolRegistry: vi.fn().mockReturnValue(undefined),
} as unknown as Config;

it('does not export truncated saved-session previews as full diffs', () => {
const record: ChatRecord = {
uuid: 'tool-1',
parentUuid: null,
sessionId: 'session-1',
timestamp: '2025-01-01T00:00:00.000Z',
type: 'tool_result',
cwd: '',
version: '1.0.0',
message: {
role: 'user',
parts: [
{
functionResponse: {
id: 'call-1',
name: 'edit_file',
response: { output: 'ok' },
},
},
],
},
toolCallResult: {
callId: 'call-1',
resultDisplay: {
fileName: '/test/file.ts',
fileDiff:
'--- /test/file.ts\n+++ /test/file.ts\n@@ -1 +1 @@\n-omitted\n+preview',
originalContent: 'old preview',
newContent: 'new preview',
truncatedForSession: true,
fileDiffLength: 200000,
fileDiffTruncated: true,
},
},
};

const normalized = normalizeSessionData(
{
sessionId: 'session-1',
startTime: '2025-01-01T00:00:00.000Z',
messages: [],
},
[record],
config,
);

expect(normalized.messages[0].toolCall?.content).toEqual([
{
type: 'content',
content: {
type: 'text',
text: 'Full diff omitted from saved session history for /test/file.ts. Original fileDiff length: 200000 chars.',
},
},
]);
});
});
13 changes: 13 additions & 0 deletions packages/cli/src/ui/utils/export/normalize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import type { Part } from '@google/genai';
import { ToolNames } from '@qwen-code/qwen-code-core';
import type { ChatRecord, Config, Kind } from '@qwen-code/qwen-code-core';
import { buildTruncatedDiffPreviewText } from '../../../utils/truncatedDiffPreview.js';
import type { ExportMessage, ExportSessionData } from './types.js';

/**
Expand Down Expand Up @@ -283,6 +284,18 @@ function extractDiffContent(

const display = resultDisplay as Record<string, unknown>;
if ('fileName' in display && 'newContent' in display) {
if (display['truncatedForSession'] === true) {
return [
{
type: 'content',
content: {
type: 'text',
text: buildTruncatedDiffPreviewText(display),
},
},
];
}

return [
{
type: 'diff',
Expand Down
Loading
Loading