Skip to content
Prev Previous commit
Next Next commit
refactor(cli): share one text rule between /copy counting and copying
Count AI messages by the same non-thought text that /copy extracts, so
the counted set and the copyable set cannot drift, and drop the "contains
no text to copy" branch that this made unreachable. Document that /copy
and /copy N skip turns with no visible text, and pin the preamble plus
tool call turn and the bare /copy cases with tests.
  • Loading branch information
burrows99 committed Nov 15, 2026
commit a5ba6040916ac8cbdde6a5626b2dc0d2179b80a1
7 changes: 5 additions & 2 deletions docs/users/features/markdown-rendering.md
Original file line number Diff line number Diff line change
Expand Up @@ -170,8 +170,11 @@ substantive output is one or two turns back.
| `/copy 2 code python` | Copies the last `python` code block from the 2nd-last. |
| `/copy 3 latex` | Copies the last LaTeX block from the 3rd-last message. |

`/copy 1` is equivalent to `/copy`. If `N` exceeds the number of AI messages
in the session, `/copy` reports the actual count instead of copying anything.
`/copy 1` is equivalent to `/copy`. Only AI messages with visible text are
counted: a turn that only calls a tool (or only thinks) is skipped, so `/copy`
and `/copy N` always land on a reply you can see. If `N` exceeds the number of
AI messages in the session, `/copy` reports the actual count instead of
copying anything.
Without a leading integer, sub-selectors such as `/copy code python 2` keep
their existing meaning (the 2nd `python` block in the last message).

Expand Down
69 changes: 69 additions & 0 deletions packages/cli/src/ui/commands/copyCommand.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1011,6 +1011,75 @@ math then literal: $x^2\$$`,
expect(mockCopyToClipboard).not.toHaveBeenCalled();
});

it('should count a model turn with preamble text and a tool call', async () => {
if (!copyCommand.action) throw new Error('Command has no action');

const history = [
{ role: 'model', parts: [{ text: 'older reply' }] },
{ role: 'user', parts: [{ text: 'question' }] },
{
role: 'model',
parts: [
{ text: 'Let me check.' },
{ functionCall: { name: 'glob', args: { pattern: '*' } } },
],
},
{
role: 'user',
parts: [{ functionResponse: { name: 'glob', response: {} } }],
},
{ role: 'model', parts: [{ text: 'final reply' }] },
];

mockGetHistoryShallow.mockReturnValue(history);
mockCopyToClipboard.mockResolvedValue(undefined);

expect(await copyCommand.action(mockContext, '2')).toEqual({
type: 'message',
messageType: 'info',
content: 'AI message 2 copied to the clipboard',
});
expect(mockCopyToClipboard).toHaveBeenLastCalledWith('Let me check.');

expect(await copyCommand.action(mockContext, '3')).toEqual({
type: 'message',
messageType: 'info',
content: 'AI message 3 copied to the clipboard',
});
expect(mockCopyToClipboard).toHaveBeenLastCalledWith('older reply');

expect(await copyCommand.action(mockContext, '4')).toEqual({
type: 'message',
messageType: 'info',
content: 'Only 3 AI messages in this session.',
});
});

it('should copy the last reply with text when the newest turn only called a tool', async () => {
if (!copyCommand.action) throw new Error('Command has no action');

// e.g. the turn was interrupted after the tool call, before any reply.
const history = [
{ role: 'user', parts: [{ text: 'question' }] },
{ role: 'model', parts: [{ text: 'earlier reply' }] },
{ role: 'user', parts: [{ text: 'follow-up' }] },
{
role: 'model',
parts: [{ functionCall: { name: 'glob', args: { pattern: '*' } } }],
},
];

mockGetHistoryShallow.mockReturnValue(history);
mockCopyToClipboard.mockResolvedValue(undefined);

expect(await copyCommand.action(mockContext, '')).toEqual({
type: 'message',
messageType: 'info',
content: 'Last output copied to the clipboard',
});
expect(mockCopyToClipboard).toHaveBeenLastCalledWith('earlier reply');
});

it('should label the error with AI message N when /copy N <selector> misses', async () => {
if (!copyCommand.action) throw new Error('Command has no action');

Expand Down
134 changes: 61 additions & 73 deletions packages/cli/src/ui/commands/copyCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -367,14 +367,19 @@ export const copyCommand: SlashCommand = {
action: async (context, args): Promise<SlashCommandActionReturn | void> => {
const chat = await context.services.config?.getLlmClient()?.getChat();
const history = chat?.getHistoryShallow();
// A tool-call-only model turn shows no reply on screen, so it must not
// shift the N in `/copy N`.
// A tool-call-only or thinking-only model turn shows no reply on screen,
Comment thread
burrows99 marked this conversation as resolved.
Resolved
// so it must not shift the N in `/copy N`; counting the extracted text
// keeps the counted set and the copyable set the same.
const aiMessages =
history?.filter(
(item) =>
item.role === 'model' &&
item.parts?.some((part) => part.text && !part.thought),
) ?? [];
history
?.filter((item) => item.role === 'model')
.map((item) =>
(item.parts ?? [])
Comment thread
burrows99 marked this conversation as resolved.
Resolved
.filter((part) => part.text && !part.thought)
.map((part) => part.text)
.join(''),
)
.filter((text) => text.length > 0) ?? [];
Comment thread
burrows99 marked this conversation as resolved.
Resolved

if (aiMessages.length === 0) {
Comment thread
burrows99 marked this conversation as resolved.
Resolved
return {
Expand All @@ -386,7 +391,7 @@ export const copyCommand: SlashCommand = {

const { messageIndex, subArgs } = parseLeadingMessageIndex(args);

let selectedAiMessage;
let aiOutput;
if (messageIndex !== null) {
if (messageIndex < 1) {
return {
Expand All @@ -405,92 +410,75 @@ export const copyCommand: SlashCommand = {
content: `Only ${aiMessages.length} ${turnLabel} in this session.`,
};
}
selectedAiMessage = aiMessages[aiMessages.length - messageIndex];
aiOutput = aiMessages[aiMessages.length - messageIndex];
} else {
selectedAiMessage = aiMessages[aiMessages.length - 1];
aiOutput = aiMessages[aiMessages.length - 1];
}

const isIndexed = messageIndex !== null && messageIndex > 1;
const sourceLabel = isIndexed
? `AI message ${messageIndex}`
: 'the last AI output';
const sourceLabelCapitalized = isIndexed
? `AI message ${messageIndex}`
: 'Last AI output';

// Extract text from the parts
const aiOutput = selectedAiMessage.parts
?.filter((part) => part.text && !part.thought)
.map((part) => part.text)
.join('');

if (aiOutput) {
try {
const selectedLatexBlock = selectLatexBlock(aiOutput, subArgs);
if (selectedLatexBlock === null) {
return {
type: 'message',
messageType: 'info',
content:
subArgs
.trim()
.split(/\s+/)
.some((token) => token === 'inline') ||
subArgs.trim().toLowerCase().startsWith('inline-latex')
? `No matching inline LaTeX expression found in ${sourceLabel}.`
: `No matching LaTeX block found in ${sourceLabel}.`,
};
}
if (selectedLatexBlock !== undefined) {
const copiedLatex =
'expression' in selectedLatexBlock
? selectedLatexBlock.expression.content
: selectedLatexBlock.block.content;
await copyToClipboard(copiedLatex);

return {
type: 'message',
messageType: 'info',
content: `${selectedLatexBlock.label} copied to the clipboard`,
};
}

const selectedCodeBlock = selectCodeBlock(aiOutput, subArgs);
if (selectedCodeBlock === null) {
return {
type: 'message',
messageType: 'info',
content: `No matching code block found in ${sourceLabel}.`,
};
}

const copiedText = selectedCodeBlock?.block.content ?? aiOutput;
await copyToClipboard(copiedText);
try {
const selectedLatexBlock = selectLatexBlock(aiOutput, subArgs);
if (selectedLatexBlock === null) {
return {
type: 'message',
messageType: 'info',
content:
subArgs
.trim()
.split(/\s+/)
.some((token) => token === 'inline') ||
subArgs.trim().toLowerCase().startsWith('inline-latex')
? `No matching inline LaTeX expression found in ${sourceLabel}.`
: `No matching LaTeX block found in ${sourceLabel}.`,
};
}
if (selectedLatexBlock !== undefined) {
const copiedLatex =
'expression' in selectedLatexBlock
? selectedLatexBlock.expression.content
: selectedLatexBlock.block.content;
await copyToClipboard(copiedLatex);

return {
type: 'message',
messageType: 'info',
content: selectedCodeBlock
? `${selectedCodeBlock.label} copied to the clipboard`
: isIndexed
? `AI message ${messageIndex} copied to the clipboard`
: 'Last output copied to the clipboard',
content: `${selectedLatexBlock.label} copied to the clipboard`,
};
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
context.services.config?.getDebugLogger().debug(message);
}

const selectedCodeBlock = selectCodeBlock(aiOutput, subArgs);
if (selectedCodeBlock === null) {
return {
type: 'message',
messageType: 'error',
content: `Failed to copy to the clipboard. ${message}`,
messageType: 'info',
content: `No matching code block found in ${sourceLabel}.`,
};
}
} else {

const copiedText = selectedCodeBlock?.block.content ?? aiOutput;
await copyToClipboard(copiedText);

return {
type: 'message',
messageType: 'info',
content: `${sourceLabelCapitalized} contains no text to copy.`,
content: selectedCodeBlock
? `${selectedCodeBlock.label} copied to the clipboard`
: isIndexed
? `AI message ${messageIndex} copied to the clipboard`
: 'Last output copied to the clipboard',
};
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
context.services.config?.getDebugLogger().debug(message);

return {
type: 'message',
messageType: 'error',
content: `Failed to copy to the clipboard. ${message}`,
};
}
},
Expand Down
Loading