@miphamai/cli 0.85.19 → 0.85.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -29,6 +29,24 @@ export function isSymlinkLoop(err: unknown): boolean {
29
29
  return (err as NodeJS.ErrnoException)?.code === 'ELOOP'
30
30
  }
31
31
 
32
+ /**
33
+ * True iff `buf` is well-formed UTF-8.
34
+ *
35
+ * Read-modify-write tools (Edit, Write) decode with 'utf-8' and re-encode the
36
+ * result. For a *valid* UTF-8 file that round-trips byte-for-byte, but a
37
+ * Windows-1252 / Shift-JIS / GBK / Latin-1 file decodes every invalid byte to
38
+ * U+FFFD and writing it back destroys the original bytes — with no error. This
39
+ * gate lets the caller refuse instead of corrupting silently.
40
+ */
41
+ export function isValidUtf8(buf: Buffer): boolean {
42
+ try {
43
+ new TextDecoder('utf-8', { fatal: true }).decode(buf)
44
+ return true
45
+ } catch {
46
+ return false
47
+ }
48
+ }
49
+
32
50
  /**
33
51
  * Open a file O_WRONLY|O_NOFOLLOW, write `content`, and close. Used by Write
34
52
  * and Edit so a symlink swapped in after `resolveSafe` is rejected rather than
@@ -9,7 +9,7 @@
9
9
  export const PACKAGE_NAME = '@miphamai/cli' as const
10
10
 
11
11
  /** 当前发布版本 */
12
- export const PACKAGE_VERSION = '0.85.19' as const
12
+ export const PACKAGE_VERSION = '0.85.21' as const
13
13
 
14
14
  /** npm install 全局安装命令 */
15
15
  export const NPM_INSTALL_COMMAND = `npm install -g ${PACKAGE_NAME}` as const
@@ -90,4 +90,4 @@ export const TOOL_COUNT = 31 as const
90
90
  * —— `test/e2e/full-pipeline.test.ts` 在 Linux 上整文件 skip、在 macOS 上跑 ——
91
91
  * 但**总数相同**(两边都把被 skip 的算进去)。
92
92
  */
93
- export const TEST_COUNT = 4141 as const
93
+ export const TEST_COUNT = 4231 as const
@@ -239,11 +239,15 @@ export function decodeDisplayEntities(input: string): string {
239
239
  *
240
240
  * Newlines are stripped as well, unlike `stripControlCharsForCheck` (which keeps
241
241
  * `\n` for multi-line shell commands): these values sit on one output line, so an
242
- * embedded newline forges an extra row in the listing.
242
+ * embedded newline forges an extra row in the listing. C1 (U+0080–U+009F) goes with
243
+ * them — its 8-bit CSI is the same introducer as ESC's, in a different encoding (see
244
+ * `stripControlCharsForDisplay`, which drops the same family); leaving it out here
245
+ * would mean the one-line port and the multi-line one disagree about it, and a
246
+ * one-line field is exactly where a `\u009b…` payload is cheapest to hide.
243
247
  */
244
248
  export function sanitizeInlineField(input: string): string {
245
249
  if (!input) return input
246
- return stripDangerousUnicode(input).replace(/[\x00-\x1f\x7f]/g, '')
250
+ return stripDangerousUnicode(input).replace(/[\x00-\x1f\x7f\x80-\x9f]/g, '')
247
251
  }
248
252
 
249
253
  /**
@@ -101,6 +101,16 @@ export interface ToolResult {
101
101
  success: boolean
102
102
  content: string
103
103
  error?: string
104
+ /**
105
+ * The call was **held back, not judged** — `auto` mode asked the classifier and
106
+ * got no usable answer, so nothing ran and asking again is appropriate (296-056).
107
+ *
108
+ * It is not a third failure state: `success` stays `false` and `error` still
109
+ * carries the text the model reads. This bit exists only so the *display* can
110
+ * tell "held back" from "ran and returned this", which are otherwise the same
111
+ * shape (both are `success: false` + an error string).
112
+ */
113
+ notRun?: boolean
104
114
  }
105
115
 
106
116
  // ── Task Notification Types ──
@@ -134,6 +144,12 @@ export interface StreamChunk {
134
144
  * either the output or the error text, and the two are indistinguishable.
135
145
  */
136
146
  isError?: boolean
147
+ /**
148
+ * `type: 'tool_result'` only. The call never ran because `auto` mode's
149
+ * classifier had no usable answer — held back, not judged (296-056). Distinct
150
+ * from the `retryable` field below, which describes a *provider* error.
151
+ */
152
+ notRun?: boolean
137
153
  error?: string
138
154
  /**
139
155
  * `type: 'error'` only. `false` means the provider knows the failure is
@@ -64,20 +64,30 @@ export function isValidSkillName(name: string): boolean {
64
64
  }
65
65
 
66
66
  /**
67
- * Read the marketplace sources from disk. A missing or corrupt file falls back
68
- * to the default Anthropic sources.
67
+ * Read the marketplace sources from disk. A missing file falls back to the
68
+ * default Anthropic sources silently — that is the ordinary first run. A
69
+ * **present but unusable** file also falls back, but reports through `warn`
70
+ * when given: the fallback value is what the next write persists, so quietly
71
+ * swapping a user's sources for the defaults is a silent data loss.
69
72
  */
70
- export function readMarketplaces(readFile: (path: string) => string | null): MarketplaceSource[] {
73
+ export function readMarketplaces(
74
+ readFile: (path: string) => string | null,
75
+ warn?: (message: string) => void,
76
+ ): MarketplaceSource[] {
71
77
  const raw = readFile(MARKETPLACES_PATH)
72
78
  if (raw === null) return [...DEFAULT_MARKETPLACES]
73
79
  try {
74
80
  const parsed = JSON.parse(raw)
75
- if (!Array.isArray(parsed)) return [...DEFAULT_MARKETPLACES]
81
+ if (!Array.isArray(parsed)) {
82
+ warn?.(`Marketplace file is not a list; using defaults (${MARKETPLACES_PATH})`)
83
+ return [...DEFAULT_MARKETPLACES]
84
+ }
76
85
  return parsed.filter(
77
86
  (s): s is MarketplaceSource =>
78
87
  !!s && typeof s === 'object' && typeof s.owner === 'string' && typeof s.repo === 'string',
79
88
  )
80
- } catch {
89
+ } catch (err) {
90
+ warn?.(`Could not read marketplace file (${MARKETPLACES_PATH}): ${String(err)}`)
81
91
  return [...DEFAULT_MARKETPLACES]
82
92
  }
83
93
  }
@@ -208,7 +208,10 @@ async function installFromMarketplace(
208
208
  skillName: string,
209
209
  marketplaceConfig?: MiphamConfig['marketplace'],
210
210
  ): Promise<InstallResult> {
211
- const sources = readMarketplaces((p) => (existsSync(p) ? readFileSync(p, 'utf-8') : null))
211
+ const sources = readMarketplaces(
212
+ (p) => (existsSync(p) ? readFileSync(p, 'utf-8') : null),
213
+ (m) => console.error(`⚠ ${m}`),
214
+ )
212
215
  const found = await findSkillInMarketplaces(skillName, sources, globalThis.fetch, downloadFile)
213
216
 
214
217
  if (!found) {
@@ -1,7 +1,7 @@
1
1
  import { readFileSync, closeSync, constants } from 'node:fs'
2
2
  import type { ToolDefinition } from '../../shared/index.ts'
3
3
  import { resolveSafe } from '../../security/path'
4
- import { openNoFollow, writeFileNoFollow, isSymlinkLoop } from '../../security/fd'
4
+ import { openNoFollow, writeFileNoFollow, isSymlinkLoop, isValidUtf8 } from '../../security/fd'
5
5
 
6
6
  /**
7
7
  * Characters considered part of an identifier in source code.
@@ -102,7 +102,18 @@ export const editTool: ToolDefinition = {
102
102
  }
103
103
  let content: string
104
104
  try {
105
- content = readFileSync(rfd, 'utf-8')
105
+ const raw = readFileSync(rfd)
106
+ if (!isValidUtf8(raw)) {
107
+ return {
108
+ success: false,
109
+ content: '',
110
+ error:
111
+ `File is not valid UTF-8 (likely Windows-1252 / Shift-JIS / GBK / Latin-1): ${filePath}. ` +
112
+ 'Editing it would decode invalid bytes to U+FFFD and overwrite the originals on save. ' +
113
+ 'Convert the file to UTF-8 with an external tool first.',
114
+ }
115
+ }
116
+ content = raw.toString('utf-8')
106
117
  } finally {
107
118
  closeSync(rfd)
108
119
  }
@@ -20,6 +20,17 @@ const CHUNK_BYTES = 64 * 1024
20
20
  */
21
21
  const MAX_SCAN_BYTES = 50_000_000
22
22
 
23
+ /**
24
+ * Scan budget when the caller passes `allow_large: true`.
25
+ *
26
+ * Reaching a line window near the end of a multi-GB log means scanning past the
27
+ * default 50 MB. That scan is real work, so it stays opt-in — but a caller who
28
+ * knows the file is huge and wants a window deep inside it can say so instead of
29
+ * being told to shell out. Still bounded (1 GB), so `allow_large` is "scan more",
30
+ * not "scan without limit".
31
+ */
32
+ const MAX_SCAN_BYTES_LARGE = 1_000_000_000
33
+
23
34
  /** Render a line window the way the tool reports it: ` 123\ttext`. */
24
35
  function formatLines(lines: string[], offset: number): string {
25
36
  return lines.map((l, i) => `${String(offset + i + 1).padStart(6, ' ')}\t${l}`).join('\n')
@@ -63,7 +74,12 @@ function windowFromString(content: string, offset: number, limit: number): strin
63
74
  * a character. Returns null when the window cannot be located within
64
75
  * `MAX_SCAN_BYTES`.
65
76
  */
66
- function windowFromFd(fd: number, offset: number, limit: number): string[] | null {
77
+ function windowFromFd(
78
+ fd: number,
79
+ offset: number,
80
+ limit: number,
81
+ maxScanBytes: number = MAX_SCAN_BYTES,
82
+ ): string[] | null {
67
83
  if (limit <= 0) return []
68
84
 
69
85
  const buf = Buffer.allocUnsafe(CHUNK_BYTES)
@@ -73,7 +89,7 @@ function windowFromFd(fd: number, offset: number, limit: number): string[] | nul
73
89
  let windowEnd = -1
74
90
  let eof = false
75
91
 
76
- while (windowEnd === -1 && scanned < MAX_SCAN_BYTES) {
92
+ while (windowEnd === -1 && scanned < maxScanBytes) {
77
93
  const n = readSync(fd, buf, 0, buf.length, scanned)
78
94
  if (n <= 0) {
79
95
  eof = true
@@ -128,6 +144,11 @@ export function createReadTool(credentialConfig?: CredentialMaskingConfig): Tool
128
144
  file_path: { type: 'string', description: 'Absolute path to the file to read' },
129
145
  offset: { type: 'integer', description: 'Line number to start reading from' },
130
146
  limit: { type: 'integer', description: 'Number of lines to read' },
147
+ allow_large: {
148
+ type: 'boolean',
149
+ description:
150
+ 'Allow scanning past 50 MB to locate the requested window in a very large file (opt-in; default false).',
151
+ },
131
152
  },
132
153
  required: ['file_path'],
133
154
  },
@@ -179,15 +200,18 @@ export function createReadTool(credentialConfig?: CredentialMaskingConfig): Tool
179
200
  }
180
201
 
181
202
  if (result === null) {
182
- const lines = windowFromFd(fd, offset, limit)
203
+ const allowLarge = params.allow_large === true
204
+ const scanBudget = allowLarge ? MAX_SCAN_BYTES_LARGE : MAX_SCAN_BYTES
205
+ const lines = windowFromFd(fd, offset, limit, scanBudget)
183
206
  if (lines === null) {
184
207
  return {
185
208
  success: false,
186
209
  content: '',
187
210
  error:
188
- `File too large: scanned ${MAX_SCAN_BYTES / 1e6} MB without reaching the end of lines ` +
189
- `${offset}–${offset + limit - 1}. Narrow the range (smaller offset or limit), or use a ` +
190
- `shell tool to slice the file.`,
211
+ `File too large: scanned ${scanBudget / 1e6} MB without reaching the end of lines ` +
212
+ `${offset}–${offset + limit - 1}. Narrow the range (smaller offset or limit)` +
213
+ (allowLarge ? '' : ', pass allow_large: true to scan further') +
214
+ `, or use a shell tool to slice the file.`,
191
215
  }
192
216
  }
193
217
  result = formatLines(lines, offset)
@@ -1,8 +1,8 @@
1
- import { mkdirSync, existsSync, constants } from 'node:fs'
1
+ import { mkdirSync, existsSync, readFileSync, constants } from 'node:fs'
2
2
  import { dirname } from 'node:path'
3
3
  import type { ToolDefinition } from '../../shared/index.ts'
4
4
  import { resolveSafe } from '../../security/path'
5
- import { writeFileNoFollow, isSymlinkLoop } from '../../security/fd'
5
+ import { writeFileNoFollow, isSymlinkLoop, isValidUtf8 } from '../../security/fd'
6
6
 
7
7
  export const writeTool: ToolDefinition = {
8
8
  name: 'Write',
@@ -42,6 +42,26 @@ export const writeTool: ToolDefinition = {
42
42
  }
43
43
  }
44
44
 
45
+ // ── Non-UTF-8 guard: refuse to clobber a file we cannot represent ──
46
+ // A Windows-1252 / Shift-JIS / GBK file read into the model came back as
47
+ // U+FFFD garbage; writing UTF-8 content over it would erase the originals
48
+ // with no error. Same-source as the Edit guard (`isValidUtf8`).
49
+ if (fileExists) {
50
+ try {
51
+ if (!isValidUtf8(readFileSync(filePath))) {
52
+ return {
53
+ success: false,
54
+ content: '',
55
+ error:
56
+ `File "${filePath}" is not valid UTF-8 (likely Windows-1252 / Shift-JIS / GBK / Latin-1). ` +
57
+ 'Overwriting it would destroy the original bytes. Convert it to UTF-8 or delete it first.',
58
+ }
59
+ }
60
+ } catch {
61
+ // Unreadable for another reason — let the write itself surface that.
62
+ }
63
+ }
64
+
45
65
  mkdirSync(dirname(filePath), { recursive: true })
46
66
 
47
67
  // O_NOFOLLOW: reject a symlink swapped in after resolveSafe (TOCTOU) —
@@ -8,6 +8,7 @@
8
8
 
9
9
  import type { ToolDefinition } from '../../shared/index.ts'
10
10
  import { McpClient } from '../../mcp/client'
11
+ import { capMcpText } from '../../mcp/instructions'
11
12
 
12
13
  export const toolSearchTool: ToolDefinition = {
13
14
  name: 'ToolSearch',
@@ -88,7 +89,7 @@ export const toolSearchTool: ToolDefinition = {
88
89
  matches.push({
89
90
  server: serverName,
90
91
  tool: tool.name,
91
- description: (tool.description || '').slice(0, 120),
92
+ description: capMcpText(tool.description || ''),
92
93
  })
93
94
  }
94
95
  }
@@ -1,6 +1,18 @@
1
1
  import React from 'react'
2
2
  import { Box, Text } from 'ink'
3
3
  import { useI18n } from '../i18n-context'
4
+ import { sanitizeInlineField } from '../shared/sanitize'
5
+
6
+ /**
7
+ * 页脚也是本文件通往终端的一道口 —— 且它内插的字全是**模型写出来的**:
8
+ * `activeTool` 的名称与详情来自工具调用参数(`ui/app.tsx` 的 `formatToolDetail`
9
+ * 只把 Bash 那支递给 `sanitizeForDisplay`,而那个函数**不剥** ESC / BEL / C1),
10
+ * agent 的名称与描述来自子代理定义。原样内插的话,模型在命令里写一个 `\x1b[2J`
11
+ * 就会被终端当清屏序列执行,而不是当文字显示。
12
+ *
13
+ * 三处内插一律过 `sanitizeInlineField`(单行口)。姊妹件是 `ui/chat.tsx` 的
14
+ * `display()` —— 那是**多行**口(工具输出要保换行),两者只差 `\n` 一个字。
15
+ */
4
16
 
5
17
  export interface AgentEntry {
6
18
  id: string
@@ -118,7 +130,8 @@ export function AgentFooter({ agents, tick, activeTool, agentProgress }: AgentFo
118
130
  {hasTool && (
119
131
  <Box>
120
132
  <Text color={toolIndicatorColor(activeTool!.name)}>
121
- {' '}[{activeTool!.name} {activeTool!.detail.slice(0, 60)}
133
+ {' '}[{sanitizeInlineField(activeTool!.name)}{' '}
134
+ {sanitizeInlineField(activeTool!.detail).slice(0, 60)}
122
135
  {animatedDots(tick)}]
123
136
  </Text>
124
137
  <Box flexGrow={1} />
@@ -165,9 +178,9 @@ export function AgentFooter({ agents, tick, activeTool, agentProgress }: AgentFo
165
178
  {symbol}{' '}
166
179
  </Text>
167
180
  <Text bold color={isRunning ? 'cyan' : undefined} dimColor={!isRunning}>
168
- {agent.name}
181
+ {sanitizeInlineField(agent.name)}
169
182
  </Text>
170
- <Text dimColor> {desc}</Text>
183
+ <Text dimColor> {sanitizeInlineField(desc)}</Text>
171
184
  {/* Spacer pushes elapsed + tokens to the right edge */}
172
185
  <Box flexGrow={1} />
173
186
  <Text dimColor>
package/src/ui/app.tsx CHANGED
@@ -30,6 +30,7 @@ import {
30
30
  import { ChatPanel } from './chat'
31
31
  import { InputBar } from './input'
32
32
  import { ModelPicker } from './picker'
33
+ import { CopyPicker, type CopyPickerItem } from './copy-picker'
33
34
  import { AgentFooter, type AgentEntry } from './agent-footer'
34
35
  import { GraftStatusLine } from './graft-status'
35
36
  import { checkForUpdatesAsync, type UpdateStatus } from '../shared/update'
@@ -86,6 +87,8 @@ export interface ToolMeta {
86
87
  collapsed: boolean
87
88
  /** Original tool name before Claude Code display renaming (e.g. Write→Update). */
88
89
  originalName?: string
90
+ /** Held back by the auto-mode classifier — rendered as a dim "Not run" row (296-056). */
91
+ notRun?: boolean
89
92
  }
90
93
 
91
94
  export interface ChatMessage {
@@ -220,6 +223,24 @@ export function formatToolDetail(name: string, input: Record<string, unknown>):
220
223
  }
221
224
 
222
225
  /** Claude Code display name: maps Write/Edit → Update for parity. */
226
+ /**
227
+ * Put text on the system clipboard. macOS/Windows only; Linux is left alone to
228
+ * avoid a hard dependency on xclip/wl-copy. Failures are swallowed — the content
229
+ * was still shown on screen, and a clipboard miss is not worth an error frame.
230
+ */
231
+ async function writeClipboard(text: string): Promise<void> {
232
+ try {
233
+ const { execSync } = await import('node:child_process')
234
+ if (process.platform === 'darwin') {
235
+ execSync('pbcopy', { input: text })
236
+ } else if (process.platform === 'win32') {
237
+ execSync('clip', { input: text })
238
+ }
239
+ } catch {
240
+ /* content is still displayed */
241
+ }
242
+ }
243
+
223
244
  function toolDisplayName(name: string): string {
224
245
  if (name === 'Write' || name === 'Edit') return 'Update'
225
246
  return name
@@ -290,6 +311,8 @@ export function App({
290
311
  const [providerId, setProviderId] = useState(initialProvider || config.defaultProvider)
291
312
  const [modelId, setModelId] = useState(initialModel || config.defaultModel)
292
313
  const [pickerOpen, setPickerOpen] = useState(false)
314
+ /** `/copy` with no argument — candidates for the interactive copy picker. */
315
+ const [copyPicker, setCopyPicker] = useState<{ items: CopyPickerItem[] } | null>(null)
293
316
  // ↑/↓ 翻历史用的已提交输入。**必须住在这里而不是 InputBar 里** —— InputBar 会被
294
317
  // 卸载(pickerOpen 三元 / apiKeyPrompt 早退 / Ctrl+G),组件内 state 随之清零,
295
318
  // 于是「开一次模型选择器,历史就没了」(ROADMAP D7)。
@@ -749,7 +772,27 @@ export function App({
749
772
  // Sync background agents (e.g. Agent tool may have spawned them)
750
773
  syncBgAgents()
751
774
  const output = chunk.content ? String(chunk.content).trim() : ''
752
- if (output && output !== '(no matches)' && output.length > 20) {
775
+ if (chunk.notRun) {
776
+ // Held back by the classifier — it never ran. Row shape is owned by
777
+ // `chat.tsx` (`toolMeta.notRun`), which labels it "Not run" instead
778
+ // of letting it read as the tool's output (296-056). Shown even when
779
+ // the reason is short: the whole point is that this row exists.
780
+ setMessages((prev) => [
781
+ ...prev,
782
+ {
783
+ role: 'system' as const,
784
+ content: output,
785
+ toolMeta: {
786
+ name: '',
787
+ input: '',
788
+ output,
789
+ collapsed: true,
790
+ originalName: chunk.toolUse?.name,
791
+ notRun: true,
792
+ },
793
+ },
794
+ ])
795
+ } else if (output && output !== '(no matches)' && output.length > 20) {
753
796
  // Generate diff-style summary for file operations (Claude Code parity)
754
797
  let preview: string
755
798
  const isFileOp = chunk.toolUse?.name === 'Write' || chunk.toolUse?.name === 'Edit'
@@ -1114,18 +1157,10 @@ export function App({
1114
1157
  }
1115
1158
  }
1116
1159
  if (result.copyContent) {
1117
- // Copy to clipboard via pbcopy (macOS) or clip (Windows)
1118
- try {
1119
- const { execSync } = await import('node:child_process')
1120
- if (process.platform === 'darwin') {
1121
- execSync('pbcopy', { input: result.copyContent })
1122
- } else if (process.platform === 'win32') {
1123
- execSync('clip', { input: result.copyContent })
1124
- }
1125
- // Linux: xclip or wl-copy not attempted to avoid dependency issues
1126
- } catch {
1127
- // Silent fail — content is still displayed
1128
- }
1160
+ await writeClipboard(result.copyContent)
1161
+ }
1162
+ if (result.openCopyPicker) {
1163
+ setCopyPicker({ items: result.openCopyPicker })
1129
1164
  }
1130
1165
  }
1131
1166
 
@@ -1212,6 +1247,10 @@ export function App({
1212
1247
  setPickerOpen(false)
1213
1248
  return true
1214
1249
  }
1250
+ if (copyPicker) {
1251
+ setCopyPicker(null)
1252
+ return true
1253
+ }
1215
1254
  if (isLoading && abortRef.current) {
1216
1255
  abortRef.current.abort()
1217
1256
  return true
@@ -1355,7 +1394,20 @@ export function App({
1355
1394
  })()}
1356
1395
 
1357
1396
  {/* Input with separator lines */}
1358
- {pickerOpen ? (
1397
+ {copyPicker ? (
1398
+ <CopyPicker
1399
+ items={copyPicker.items}
1400
+ onSelect={(item) => {
1401
+ void writeClipboard(item.text)
1402
+ setCopyPicker(null)
1403
+ setMessages((prev) => [
1404
+ ...prev,
1405
+ { role: 'system', content: t('commands.copy.confirmed', { count: '1' }) },
1406
+ ])
1407
+ }}
1408
+ onClose={() => setCopyPicker(null)}
1409
+ />
1410
+ ) : pickerOpen ? (
1359
1411
  <ModelPicker
1360
1412
  config={config}
1361
1413
  currentProvider={providerId}
package/src/ui/chat.tsx CHANGED
@@ -2,7 +2,11 @@ import React, { useMemo } from 'react'
2
2
  import { Box, Text } from 'ink'
3
3
  import { useI18n } from '../i18n-context'
4
4
  import type { ChatMessage } from './app'
5
- import { decodeDisplayEntities, stripControlCharsForDisplay } from '../shared/sanitize'
5
+ import {
6
+ decodeDisplayEntities,
7
+ sanitizeInlineField,
8
+ stripControlCharsForDisplay,
9
+ } from '../shared/sanitize'
6
10
  import { homedir } from 'node:os'
7
11
 
8
12
  interface ChatPanelProps {
@@ -13,18 +17,52 @@ interface ChatPanelProps {
13
17
  }
14
18
 
15
19
  /**
16
- * The single point where untrusted text becomes terminal output.
20
+ * The port untrusted **multi-line** text takes to terminal output.
17
21
  *
18
- * Everything this component prints that did not come from a literal in the file —
19
- * tool arguments, tool output, model prose — passes through here. Control
20
- * characters in those strings are not visible content; they are terminal
21
- * instructions (CR overwrites the row, ESC starts a sequence), so they are removed
22
- * rather than shown. See `stripControlCharsForDisplay` for what is kept and why.
22
+ * Tool arguments, tool output and model prose pass through here; `\n` is kept
23
+ * because those are legitimately multi-line. Control characters in them are not
24
+ * visible content; they are terminal instructions (CR overwrites the row, ESC
25
+ * starts a sequence), so they are removed rather than shown. See
26
+ * `stripControlCharsForDisplay` for what is kept and why.
27
+ *
28
+ * **One-line fields do not come through here.** A tool *name* is rendered on a row
29
+ * of its own, where the `\n` this function keeps forges an extra row — so names go
30
+ * through `sanitizeInlineField` (the same recipe minus `\n`), the way
31
+ * `agent-footer.tsx` and `input.tsx` already do. The name below used to be
32
+ * interpolated raw, on the theory that this function was the only way in; it is not.
33
+ * The same holds for the `↳ name1 ↳ name2` line `summarizeToolGroup` composes: one
34
+ * line, names straight off the model's `tool_use`, so the single-line gate.
23
35
  */
24
36
  function display(text: string): string {
25
37
  return stripControlCharsForDisplay(text)
26
38
  }
27
39
 
40
+ /**
41
+ * Render at most this many lines of a message body.
42
+ *
43
+ * Ink lays out the *whole* string on every render, and a streamed turn re-renders
44
+ * continuously — so a model answer of tens of thousands of lines (a dumped file,
45
+ * a runaway loop) makes every chunk reflow the entire body, at ~16 fps. The tail
46
+ * is dropped with a visible count rather than silently: the model may well have
47
+ * written something worth scrolling to, and a truncated view that says so lets
48
+ * the user ask for the rest instead of believing they saw all of it.
49
+ *
50
+ * Applied to every non-tool body (user pastes hit the same wall).
51
+ */
52
+ const MAX_RENDERED_LINES = 50
53
+
54
+ function capRenderedLines(text: string): string {
55
+ let newlines = 0
56
+ for (let i = 0; i < text.length; i++) if (text.charCodeAt(i) === 10) newlines++
57
+ if (newlines < MAX_RENDERED_LINES) return text
58
+ const lines = text.split('\n')
59
+ const hidden = lines.length - MAX_RENDERED_LINES
60
+ return (
61
+ lines.slice(0, MAX_RENDERED_LINES).join('\n') +
62
+ `\n… ${hidden} more line${hidden === 1 ? '' : 's'}`
63
+ )
64
+ }
65
+
28
66
  /** Format cwd for display: replace HOME with ~, truncate if too long */
29
67
  function displayCwd(): string {
30
68
  const cwd = process.cwd()
@@ -80,12 +118,21 @@ const MessageRow = React.memo(
80
118
  {/* Tool call line: ⏺ ToolName(detail) — Claude Code parity */}
81
119
  {msg.toolMeta.name ? (
82
120
  <Text color={toolColor(msg.toolMeta.name)}>
83
- {msg.toolMeta.collapsed ? '⏺' : '⏺ ▼'} {msg.toolMeta.name}
121
+ {msg.toolMeta.collapsed ? '⏺' : '⏺ ▼'} {sanitizeInlineField(msg.toolMeta.name)}
84
122
  {msg.toolMeta.input ? ` (${display(msg.toolMeta.input).slice(0, 120)})` : ''}
85
123
  </Text>
86
124
  ) : null}
87
125
  {/* Tool result line: ⎿ summary text */}
88
- {msg.toolMeta.output ? (
126
+ {msg.toolMeta.notRun ? (
127
+ // Held back by the auto-mode classifier: it never ran, so the text
128
+ // below is the *reason*, not output. Labelling it keeps a held-back
129
+ // call from reading as a tool that ran and returned this (296-056).
130
+ <Text dimColor>
131
+ {' ⎿ '}
132
+ {t('ui.tool.not_run')}
133
+ {msg.toolMeta.output ? ` — ${display(msg.toolMeta.output).slice(0, 300)}` : ''}
134
+ </Text>
135
+ ) : msg.toolMeta.output ? (
89
136
  <Text dimColor>
90
137
  {' ⎿ '}
91
138
  {display(msg.toolMeta.output).slice(0, 300)}
@@ -109,7 +156,7 @@ const MessageRow = React.memo(
109
156
  ⚠ {t('ui.system.role_label')}:
110
157
  </Text>
111
158
  ) : null}
112
- <Text>{display(decodeDisplayEntities(msg.content))}</Text>
159
+ <Text>{capRenderedLines(display(decodeDisplayEntities(msg.content)))}</Text>
113
160
  </>
114
161
  )}
115
162
  </Box>
@@ -217,6 +264,9 @@ function compactToolGroups(messages: ChatMessage[]): ChatMessage[] {
217
264
  toolMeta: {
218
265
  ...current.toolMeta!,
219
266
  output: msg.toolMeta.output,
267
+ // 结果行上的标记必须跟着合并走:合并把结果行的 toolMeta 并进工具调用行,
268
+ // 漏掉它,`notRun` 就停在**没人渲染的那一份**上(296-056)。
269
+ ...(msg.toolMeta.notRun ? { notRun: true } : {}),
220
270
  },
221
271
  }
222
272
  }
@@ -270,11 +320,24 @@ function compactForFocus(messages: ChatMessage[]): ChatMessage[] {
270
320
  return result
271
321
  }
272
322
 
273
- /** Summarize a group of tool calls into a single compact message. */
274
- function summarizeToolGroup(tools: ChatMessage[]): ChatMessage {
323
+ /**
324
+ * Summarize a group of tool calls into a single compact message.
325
+ *
326
+ * Exported for `test/ui/chat-control-chars.test.ts`, which pins the composition
327
+ * itself: names come from the model's `tool_use`, and this line is a **one-line**
328
+ * display string, so each name goes through the single-line gate rather than
329
+ * `display()` — the latter keeps `\n` for legitimately multi-line bodies, and a
330
+ * `\n` in a name forges a row here just as it did on the tool-call row.
331
+ *
332
+ * That line is not rendered by today's `MessageRow` (the `toolMeta` branch is
333
+ * taken, where `output` wins and `collapsed: true` blocks the `content`
334
+ * fallback) — so this is hardening the composed value, not fixing an observed
335
+ * leak. It keeps the string safe under whichever renderer reads it next.
336
+ */
337
+ export function summarizeToolGroup(tools: ChatMessage[]): ChatMessage {
275
338
  const names = tools.map((t) => t.toolMeta!.name)
276
339
  const uniqueNames = [...new Set(names)]
277
- const toolList = uniqueNames.map((n) => `↳ ${n}`).join(' ')
340
+ const toolList = uniqueNames.map((n) => `↳ ${sanitizeInlineField(n)}`).join(' ')
278
341
  return {
279
342
  role: 'system',
280
343
  content: `[▶ ${tools.length} tool${tools.length > 1 ? 's' : ''}] ${toolList}`,