From 425430debb567d6c3f534e11915094eb54f8d70b Mon Sep 17 00:00:00 2001 From: Abdelrhman Kamal Mahmoud Ali Slim Date: Sun, 20 Apr 2025 08:52:14 -0700 Subject: [PATCH] fix(cli): ensure /clear resets context and exclude system messages from approximateTokenUsed count (#443) https://github.com/user-attachments/assets/58b8f261-a359-4cd8-8c84-90d8d91a5592 --- .../components/chat/terminal-chat-input.tsx | 30 +++++++++++++------ .../src/utils/approximate-tokens-used.ts | 4 +++ 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/codex-cli/src/components/chat/terminal-chat-input.tsx b/codex-cli/src/components/chat/terminal-chat-input.tsx index e783f845..af1ebe1f 100644 --- a/codex-cli/src/components/chat/terminal-chat-input.tsx +++ b/codex-cli/src/components/chat/terminal-chat-input.tsx @@ -345,15 +345,27 @@ export default function TerminalChatInput({ // Emit a system message to confirm the clear action. We *append* // it so Ink's treats it as new output and actually renders it. - setItems((prev) => [ - ...prev, - { - id: `clear-${Date.now()}`, - type: "message", - role: "system", - content: [{ type: "input_text", text: "Context cleared" }], - }, - ]); + setItems((prev) => { + const filteredOldItems = prev.filter((item) => { + if ( + item.type === "message" && + (item.role === "user" || item.role === "assistant") + ) { + return false; + } + return true; + }); + + return [ + ...filteredOldItems, + { + id: `clear-${Date.now()}`, + type: "message", + role: "system", + content: [{ type: "input_text", text: "Terminal cleared" }], + }, + ]; + }); return; } else if (inputValue === "/clearhistory") { diff --git a/codex-cli/src/utils/approximate-tokens-used.ts b/codex-cli/src/utils/approximate-tokens-used.ts index a50dd730..569ccebd 100644 --- a/codex-cli/src/utils/approximate-tokens-used.ts +++ b/codex-cli/src/utils/approximate-tokens-used.ts @@ -19,6 +19,10 @@ export function approximateTokensUsed(items: Array): number { for (const item of items) { switch (item.type) { case "message": { + if (item.role !== "user" && item.role !== "assistant") { + continue; + } + for (const c of item.content) { if (c.type === "input_text" || c.type === "output_text") { charCount += c.text.length;