@miphamai/cli 0.85.32 → 0.85.34

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.
Files changed (53) hide show
  1. package/README.md +1 -1
  2. package/package.json +1 -1
  3. package/src/agent/services.ts +21 -0
  4. package/src/agent/sub-agent.ts +129 -21
  5. package/src/commands/environment.ts +14 -11
  6. package/src/commands/project.ts +43 -12
  7. package/src/config/loader.ts +65 -35
  8. package/src/core/alignment-vocabulary.json +2 -2
  9. package/src/core/constitution-loader.ts +85 -24
  10. package/src/core/credential-masker/env-filter.ts +37 -0
  11. package/src/core/engine.ts +59 -140
  12. package/src/core/permission-rules.ts +163 -14
  13. package/src/core/permission.ts +14 -1
  14. package/src/core/session-log.ts +11 -0
  15. package/src/core/session-store.ts +4 -3
  16. package/src/core/tool-gate.ts +222 -0
  17. package/src/core/workspace-trust.ts +50 -17
  18. package/src/daemon/remote-engine.ts +3 -0
  19. package/src/i18n-core/locales/en-US.json +1 -0
  20. package/src/i18n-core/locales/zh-CN.json +1 -0
  21. package/src/index.tsx +6 -0
  22. package/src/mcp/client.ts +22 -2
  23. package/src/mcp/protocol.ts +16 -2
  24. package/src/plugin/plugin-manager.ts +29 -3
  25. package/src/providers/fetch-utils.ts +49 -0
  26. package/src/providers/openai-compat.ts +28 -2
  27. package/src/shared/git-env.ts +37 -13
  28. package/src/shared/package-info.ts +2 -2
  29. package/src/shared/sanitize.ts +17 -0
  30. package/src/shared/types.ts +8 -0
  31. package/src/skills/fork-executor.ts +11 -1
  32. package/src/skills/marketplace.ts +44 -13
  33. package/src/skills/registry.ts +12 -1
  34. package/src/tools/agent/agent.ts +3 -0
  35. package/src/tools/agent/enter-plan.ts +22 -4
  36. package/src/tools/agent/exit-plan.ts +9 -1
  37. package/src/tools/agent/skill.ts +1 -0
  38. package/src/tools/agent/workflow.ts +1 -0
  39. package/src/tools/computer/browser.ts +13 -0
  40. package/src/tools/exec/git.ts +113 -69
  41. package/src/tools/file/edit.ts +19 -3
  42. package/src/tools/file/grep.ts +5 -1
  43. package/src/tools/file/write.ts +18 -1
  44. package/src/tools/index.ts +2 -2
  45. package/src/tools/network/web-fetch.ts +12 -0
  46. package/src/tools/system/tool-search.ts +35 -3
  47. package/src/ui/app.tsx +105 -4
  48. package/src/ui/chat.tsx +21 -7
  49. package/src/ui/commands.ts +127 -18
  50. package/src/workflow/primitives/agent.ts +12 -1
  51. package/src/workflow/primitives/loop.ts +14 -0
  52. package/src/workflow/primitives/verify.ts +13 -1
  53. package/src/workflow/runtime.ts +1 -0
@@ -40,6 +40,19 @@ export async function browserSnapshot(): Promise<string> {
40
40
  }
41
41
 
42
42
  export async function browserClick(uid: string): Promise<string> {
43
+ // `uid` goes inside a CSS attribute selector. A quote — or an escape that
44
+ // decodes to one — closes the string early and hands the rest of the value to
45
+ // Playwright's selector parser as new CSS, which is a model-supplied value
46
+ // reaching a different layer than the page node it names. Every uid we emit is
47
+ // alphanumeric, so anything else is a respelling error: say what shape is
48
+ // expected rather than trying to escape it.
49
+ if (!/^[A-Za-z0-9_-]+$/.test(uid)) {
50
+ throw new Error(
51
+ `Invalid element uid ${JSON.stringify(uid)}: expected a plain element id ` +
52
+ '([A-Za-z0-9_-]), not a JSON string or an escaped selector. ' +
53
+ 'Take the uid from browser_snapshot and pass it unquoted.',
54
+ )
55
+ }
43
56
  const page = (await getPage()) as {
44
57
  locator: (s: string) => { click: () => Promise<void> }
45
58
  }
@@ -1,7 +1,11 @@
1
1
  import { resolve } from 'node:path'
2
- import type { ToolDefinition } from '../../shared/index.ts'
2
+ import type { CredentialMaskingConfig, ToolDefinition } from '../../shared/index.ts'
3
+ import { DEFAULT_CREDENTIAL_MASKING_CONFIG } from '../../config/defaults'
3
4
  import { findWorktreeMarker } from '../../core/paths.ts'
4
5
  import { isWithin } from '../../security/path.ts'
6
+ import type { Service } from '../../vajra'
7
+ import { toolKey } from '../seam'
8
+ import { withValidation } from '../validation'
5
9
 
6
10
  /** Generous enough for a clone or fetch, short enough to bound a hung git. */
7
11
  const GIT_TIMEOUT_MS = 120_000
@@ -201,91 +205,131 @@ export function splitCommand(command: string): string[] {
201
205
  return tokens
202
206
  }
203
207
 
204
- export const gitTool: ToolDefinition = {
205
- name: 'Git',
206
- description: 'Execute git commands. Dangerous operations (force push, hard reset) are blocked.',
207
- category: 'exec',
208
- permission: 'self',
209
- parameters: {
210
- type: 'object',
211
- properties: {
212
- command: {
213
- type: 'string',
214
- description: 'Git subcommand + args (e.g., "status", "log --oneline")',
208
+ export function createGitTool(
209
+ credentialConfig: CredentialMaskingConfig = DEFAULT_CREDENTIAL_MASKING_CONFIG,
210
+ ): ToolDefinition {
211
+ return {
212
+ name: 'Git',
213
+ description: 'Execute git commands. Dangerous operations (force push, hard reset) are blocked.',
214
+ category: 'exec',
215
+ permission: 'self',
216
+ parameters: {
217
+ type: 'object',
218
+ properties: {
219
+ command: {
220
+ type: 'string',
221
+ description: 'Git subcommand + args (e.g., "status", "log --oneline")',
222
+ },
215
223
  },
224
+ required: ['command'],
216
225
  },
217
- required: ['command'],
218
- },
219
- async execute(params, ctx) {
220
- const command = params.command as string
226
+ async execute(params, ctx) {
227
+ const command = params.command as string
228
+
229
+ // P0-4: Regex-based word-boundary pattern matching
230
+ for (const { pattern, description } of DANGEROUS_GIT_PATTERNS) {
231
+ if (pattern.test(command)) {
232
+ return {
233
+ success: false,
234
+ content: '',
235
+ error: `Dangerous git command blocked: "${description}". Run manually if intended.`,
236
+ }
237
+ }
238
+ }
221
239
 
222
- // P0-4: Regex-based word-boundary pattern matching
223
- for (const { pattern, description } of DANGEROUS_GIT_PATTERNS) {
224
- if (pattern.test(command)) {
240
+ // P0-4: Worktree isolation — block commands referencing outside paths
241
+ const worktreeErr = isOutsideWorktree(command, ctx.cwd)
242
+ if (worktreeErr) {
225
243
  return {
226
244
  success: false,
227
245
  content: '',
228
- error: `Dangerous git command blocked: "${description}". Run manually if intended.`,
246
+ error: `Worktree isolation: ${worktreeErr}. Blocked for safety.`,
229
247
  }
230
248
  }
231
- }
232
249
 
233
- // P0-4: Worktree isolation — block commands referencing outside paths
234
- const worktreeErr = isOutsideWorktree(command, ctx.cwd)
235
- if (worktreeErr) {
236
- return {
237
- success: false,
238
- content: '',
239
- error: `Worktree isolation: ${worktreeErr}. Blocked for safety.`,
250
+ // Git runs without an approval prompt (`permission: 'self'`), so an option
251
+ // that names a program to execute is a code-execution path Bash would have
252
+ // had to ask for. Checked on argv, which is what git is handed below.
253
+ const argv = splitCommand(command)
254
+ const execArg = findProgramExecutingArg(argv)
255
+ if (execArg) {
256
+ return {
257
+ success: false,
258
+ content: '',
259
+ error: `Dangerous git option blocked: "${execArg}" makes git run an arbitrary program. Run manually if intended.`,
260
+ }
240
261
  }
241
- }
242
262
 
243
- // Git runs without an approval prompt (`permission: 'self'`), so an option
244
- // that names a program to execute is a code-execution path Bash would have
245
- // had to ask for. Checked on argv, which is what git is handed below.
246
- const argv = splitCommand(command)
247
- const execArg = findProgramExecutingArg(argv)
248
- if (execArg) {
249
- return {
250
- success: false,
251
- content: '',
252
- error: `Dangerous git option blocked: "${execArg}" makes git run an arbitrary program. Run manually if intended.`,
253
- }
254
- }
263
+ try {
264
+ // The environment a git child gets is the same contract Bash's children
265
+ // get: sensitive variables are replaced by the sentinel, never handed
266
+ // over in the clear. This is not a cosmetic difference — `pre-commit`
267
+ // hooks, `filter.*` drivers and credential helpers are repository-
268
+ // supplied code, and the model can run any of them by asking for
269
+ // `git checkout` / `git commit` in a cloned repository.
270
+ let spawnEnv: Record<string, string | undefined> = process.env as Record<
271
+ string,
272
+ string | undefined
273
+ >
274
+ if (credentialConfig.enabled && credentialConfig.env_filter.enabled) {
275
+ const { filterEnv } = await import('../../core/credential-masker')
276
+ spawnEnv = filterEnv(spawnEnv, credentialConfig)
277
+ }
278
+
279
+ const proc = Bun.spawn(['git', ...argv], {
280
+ cwd: ctx.cwd,
281
+ stdout: 'pipe',
282
+ stderr: 'pipe',
283
+ env: spawnEnv,
284
+ })
285
+
286
+ // Bounded like Bash: a git command that blocks on a pager, a credential
287
+ // prompt, or an unreachable remote would otherwise hang the turn forever.
288
+ const timer = setTimeout(() => proc.kill(), GIT_TIMEOUT_MS)
289
+ const output = await new Response(proc.stdout).text()
290
+ const exitCode = await proc.exited
291
+ clearTimeout(timer)
292
+
293
+ // Output scrubbing, for the same reason `Read`/`Grep`/`Bash` scrub:
294
+ // `git show HEAD:.env` returns a secret verbatim, and a masked read of
295
+ // the same file would not. One contract, every path.
296
+ const scrub = async (text: string): Promise<string> =>
297
+ credentialConfig.enabled && credentialConfig.output_scrubbing.enabled
298
+ ? (await import('../../core/credential-masker')).maskOutput(text, credentialConfig)
299
+ : text
300
+
301
+ if (exitCode !== 0) {
302
+ const stderr = await new Response(proc.stderr).text()
303
+ return {
304
+ success: false,
305
+ content: '',
306
+ error: `Git error (exit ${exitCode}): ${(await scrub(stderr)).slice(0, 1000)}`,
307
+ }
308
+ }
255
309
 
256
- try {
257
- const proc = Bun.spawn(['git', ...argv], {
258
- cwd: ctx.cwd,
259
- stdout: 'pipe',
260
- stderr: 'pipe',
261
- })
262
-
263
- // Bounded like Bash: a git command that blocks on a pager, a credential
264
- // prompt, or an unreachable remote would otherwise hang the turn forever.
265
- const timer = setTimeout(() => proc.kill(), GIT_TIMEOUT_MS)
266
- const output = await new Response(proc.stdout).text()
267
- const exitCode = await proc.exited
268
- clearTimeout(timer)
269
-
270
- if (exitCode !== 0) {
271
- const stderr = await new Response(proc.stderr).text()
310
+ return {
311
+ success: true,
312
+ content: (await scrub(output)).slice(0, 50_000) || '(no output)',
313
+ }
314
+ } catch (err) {
272
315
  return {
273
316
  success: false,
274
317
  content: '',
275
- error: `Git error (exit ${exitCode}): ${stderr.slice(0, 1000)}`,
318
+ error: `Git execution failed: ${String(err)}`,
276
319
  }
277
320
  }
321
+ },
322
+ }
323
+ }
278
324
 
279
- return {
280
- success: true,
281
- content: output.slice(0, 50_000) || '(no output)',
282
- }
283
- } catch (err) {
284
- return {
285
- success: false,
286
- content: '',
287
- error: `Git execution failed: ${String(err)}`,
288
- }
289
- }
325
+ /** Registry entry with credential masking, handed in the same way as Bash's. */
326
+ export const gitToolService: Service = {
327
+ inject: ['credentials'],
328
+ apply(ctx) {
329
+ const credentialConfig = ctx.get<CredentialMaskingConfig>('credentials')
330
+ ctx.provide(toolKey('Git'), withValidation(createGitTool(credentialConfig)))
290
331
  },
291
332
  }
333
+
334
+ /** Unwrapped tool for callers that build a registry by hand (tests). */
335
+ export const gitTool: ToolDefinition = createGitTool()
@@ -1,4 +1,4 @@
1
- import { readFileSync, closeSync, constants } from 'node:fs'
1
+ import { readFileSync, closeSync, constants, fstatSync } from 'node:fs'
2
2
  import type { ToolDefinition } from '../../shared/index.ts'
3
3
  import { resolveSafe } from '../../security/path'
4
4
  import { openNoFollow, writeFileNoFollow, isSymlinkLoop, isValidUtf8 } from '../../security/fd'
@@ -104,9 +104,11 @@ export const editTool: ToolDefinition = {
104
104
  }
105
105
 
106
106
  // O_NOFOLLOW: fail closed on a symlink swapped in after resolveSafe (TOCTOU).
107
+ // O_NONBLOCK: opening a FIFO blocks until a writer appears, and no timer or
108
+ // signal handler can run inside a synchronous open — same gate as Read.
107
109
  let rfd: number
108
110
  try {
109
- rfd = openNoFollow(filePath, constants.O_RDONLY)
111
+ rfd = openNoFollow(filePath, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0))
110
112
  } catch (err) {
111
113
  if (isSymlinkLoop(err)) {
112
114
  return { success: false, content: '', error: `Path is a symbolic link: ${filePath}` }
@@ -115,6 +117,16 @@ export const editTool: ToolDefinition = {
115
117
  }
116
118
  let content: string
117
119
  try {
120
+ // O_NONBLOCK only got us past the *open*. It does not bound the read:
121
+ // `/dev/zero` yields bytes forever (OOM) and a FIFO yields whatever a
122
+ // writer chooses to send. Refuse on file type, not on size.
123
+ if (!fstatSync(rfd).isFile()) {
124
+ return {
125
+ success: false,
126
+ content: '',
127
+ error: `Path is not a regular file (FIFO, socket or device): ${filePath}`,
128
+ }
129
+ }
118
130
  const raw = readFileSync(rfd)
119
131
  if (!isValidUtf8(raw)) {
120
132
  return {
@@ -181,7 +193,11 @@ export const editTool: ToolDefinition = {
181
193
  // O_NOFOLLOW: reject a symlink swapped in after the read (TOCTOU) instead of
182
194
  // writing through it to an out-of-workspace target.
183
195
  try {
184
- writeFileNoFollow(filePath, result, constants.O_WRONLY | constants.O_TRUNC)
196
+ writeFileNoFollow(
197
+ filePath,
198
+ result,
199
+ constants.O_WRONLY | constants.O_TRUNC | (constants.O_NONBLOCK ?? 0),
200
+ )
185
201
  } catch (err) {
186
202
  if (isSymlinkLoop(err)) {
187
203
  return { success: false, content: '', error: `Path is a symbolic link: ${filePath}` }
@@ -6,6 +6,7 @@ import type { Service } from '../../vajra'
6
6
  import { toolKey } from '../seam'
7
7
  import { withValidation } from '../validation'
8
8
  import { maskSearchOutput } from '../../core/credential-masker'
9
+ import { internalProcessEnv } from '../../shared/git-env'
9
10
 
10
11
  /** Grep stall guard: a search over a huge tree (or a pathological regex) must
11
12
  * not hang the session for minutes. Matches the Bash tool's 120s ceiling. */
@@ -30,7 +31,10 @@ export async function runSearch(
30
31
  cwd: string,
31
32
  timeoutMs: number,
32
33
  ): Promise<{ stdout: string; stderr: string; timedOut: boolean; exitCode: number | null }> {
33
- const proc = Bun.spawn(cmd, { cwd, stdout: 'pipe', stderr: 'pipe' })
34
+ // Same reasoning as `internalGitEnv`: this search is ours, not the user's
35
+ // shell — ripgrep never needs an API key, and handing one down only makes it
36
+ // reachable from a config file or a `--pre` child of the search.
37
+ const proc = Bun.spawn(cmd, { cwd, stdout: 'pipe', stderr: 'pipe', env: internalProcessEnv() })
34
38
  let timedOut = false
35
39
  const timers: ReturnType<typeof setTimeout>[] = []
36
40
  timers.push(
@@ -3,6 +3,7 @@ import { dirname } from 'node:path'
3
3
  import type { ToolDefinition } from '../../shared/index.ts'
4
4
  import { resolveSafe } from '../../security/path'
5
5
  import { writeFileNoFollow, isSymlinkLoop, isValidUtf8 } from '../../security/fd'
6
+ import { isRegularFile } from '../../shared/regular-file'
6
7
 
7
8
  export const writeTool: ToolDefinition = {
8
9
  name: 'Write',
@@ -33,6 +34,20 @@ export const writeTool: ToolDefinition = {
33
34
 
34
35
  // ── Read-before-write safety check ──
35
36
  const fileExists = existsSync(filePath)
37
+
38
+ // `existsSync` is true for a FIFO, socket, device node or directory, and
39
+ // none of those is a file this tool can overwrite: reading one to probe for
40
+ // non-UTF-8 bytes blocks forever on a writer-less FIFO (no timer can fire
41
+ // inside a synchronous read) and streams `/dev/zero` until memory runs out.
42
+ // Report the type — "not read this session" would be the wrong reason.
43
+ if (fileExists && !isRegularFile(filePath)) {
44
+ return {
45
+ success: false,
46
+ content: '',
47
+ error: `Path is not a regular file (FIFO, socket or device): ${filePath}`,
48
+ }
49
+ }
50
+
36
51
  const wasRead = ctx.readFiles?.has(filePath) ?? false // fail closed: no tracking = not read
37
52
  if (fileExists && !wasRead) {
38
53
  return {
@@ -89,7 +104,9 @@ export const writeTool: ToolDefinition = {
89
104
  writeFileNoFollow(
90
105
  filePath,
91
106
  content,
92
- constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC,
107
+ // O_NONBLOCK: a FIFO swapped in after the type check would otherwise
108
+ // block this open until a reader appears — fail with ENXIO instead.
109
+ constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | (constants.O_NONBLOCK ?? 0),
93
110
  )
94
111
  } catch (err) {
95
112
  if (isSymlinkLoop(err)) {
@@ -8,7 +8,7 @@ import { editTool } from './file/edit'
8
8
  import { globToolService } from './file/glob'
9
9
  import { grepToolService } from './file/grep'
10
10
  import { bashToolService } from './exec/bash'
11
- import { gitTool } from './exec/git'
11
+ import { gitToolService } from './exec/git'
12
12
  import { taskTool } from './exec/task'
13
13
  import { enterWorktreeTool } from './exec/enter-worktree'
14
14
  import { exitWorktreeTool } from './exec/exit-worktree'
@@ -58,7 +58,6 @@ export function createToolRegistry(
58
58
  writeTool,
59
59
  editTool,
60
60
  // Exec tools
61
- gitTool,
62
61
  taskTool,
63
62
  enterWorktreeTool,
64
63
  exitWorktreeTool,
@@ -103,6 +102,7 @@ export function createToolRegistry(
103
102
  // provider 的 apiKey、MCP server 的 env、inference hook 的 signing_secret。
104
103
  ctx.mount(readToolService)
105
104
  ctx.mount(bashToolService)
105
+ ctx.mount(gitToolService)
106
106
  ctx.mount(grepToolService)
107
107
  ctx.mount(globToolService)
108
108
  ctx.mount(configToolService)
@@ -263,6 +263,18 @@ export const webFetchTool: ToolDefinition = {
263
263
  required: ['url'],
264
264
  },
265
265
  async execute(params, _ctx) {
266
+ // Rechecked at call time, not only when the registry was built: the
267
+ // registration filter drops this tool when the switch is on at startup, but
268
+ // a policy that turns it on later (or any caller holding the tool directly)
269
+ // must not still reach the network. Same variable, same `'1'` — this can
270
+ // only refuse a call the registry would have refused, never widen it.
271
+ if (process.env.MIPHAM_DISABLE_WEB_FETCH === '1') {
272
+ return {
273
+ success: false,
274
+ content: '',
275
+ error: 'WebFetch is disabled (MIPHAM_DISABLE_WEB_FETCH=1).',
276
+ }
277
+ }
266
278
  const rawUrl = params.url as string
267
279
  const prompt = (params.prompt as string) || ''
268
280
  const offset = Math.max(0, Number(params.offset) || 0)
@@ -10,6 +10,25 @@ import type { ToolDefinition } from '../../shared/index.ts'
10
10
  import { McpClient } from '../../mcp/client'
11
11
  import { capMcpText } from '../../mcp/instructions'
12
12
 
13
+ /**
14
+ * Names a search query may be a *typo'd spelling of a built-in* tool, in which
15
+ * case the right answer is "that one is already on your desk, just call it" —
16
+ * not "no tools matching". `WebSearch`, `web_search` and `web search` are the
17
+ * same tool to a model reaching for it by name.
18
+ */
19
+ export function builtInToolMatches(
20
+ query: string,
21
+ registry: Map<string, ToolDefinition> | undefined,
22
+ ): string[] {
23
+ const q = normalizeToolName(query)
24
+ if (!registry || q.length < 2) return []
25
+ return [...registry.keys()].filter((name) => normalizeToolName(name).includes(q))
26
+ }
27
+
28
+ function normalizeToolName(value: string): string {
29
+ return value.toLowerCase().replace(/[^a-z0-9]/g, '')
30
+ }
31
+
13
32
  export const toolSearchTool: ToolDefinition = {
14
33
  name: 'ToolSearch',
15
34
  description:
@@ -37,7 +56,7 @@ export const toolSearchTool: ToolDefinition = {
37
56
  },
38
57
  required: [],
39
58
  },
40
- async execute(params, _ctx) {
59
+ async execute(params, ctx) {
41
60
  const query = ((params.query as string) || '').toLowerCase()
42
61
  const serverFilter = (params.server as string) || ''
43
62
  const limit = (params.limit as number) || 20
@@ -99,12 +118,25 @@ export const toolSearchTool: ToolDefinition = {
99
118
  }
100
119
 
101
120
  if (matches.length === 0) {
121
+ // A zero-hit answer is the wrong answer when the name the caller searched
122
+ // for is a *built-in* tool: nothing is missing, it was never an MCP tool.
123
+ // Saying only "no match" sends the model looking for a server to install
124
+ // for a tool it could have called.
125
+ const alreadyAvailable = builtInToolMatches(query, ctx.toolRegistry)
126
+ const hint =
127
+ alreadyAvailable.length > 0
128
+ ? `\n\n"${query}" matches a built-in tool that is already available — ` +
129
+ `call ${alreadyAvailable.map((n) => `\`${n}\``).join(', ')} directly; ` +
130
+ `ToolSearch only covers MCP servers.`
131
+ : ''
102
132
  return {
103
133
  success: true,
104
134
  content:
105
135
  `── MCP Tool Search ──\n\n` +
106
- `No tools matching "${query}" across ${servers.length} server(s).\n\n` +
107
- `Try a different query, or omit the query to list all tools.`,
136
+ `No tools matching "${query}" across ${servers.length} server(s).${hint}\n\n` +
137
+ (alreadyAvailable.length > 0
138
+ ? `Try a different query for MCP tools, or omit the query to list all MCP tools.`
139
+ : `Try a different query, or omit the query to list all tools.`),
108
140
  }
109
141
  }
110
142
 
package/src/ui/app.tsx CHANGED
@@ -90,6 +90,13 @@ export interface ToolMeta {
90
90
  originalName?: string
91
91
  /** Held back by the auto-mode classifier — rendered as a dim "Not run" row (296-056). */
92
92
  notRun?: boolean
93
+ /**
94
+ * The call finished without producing output (stopped, or a tool that returns
95
+ * nothing). Rendered as "No result recorded" — without it the collapsed group
96
+ * keeps the call row and says nothing about how it ended, which reads as a
97
+ * call still running.
98
+ */
99
+ noResult?: boolean
93
100
  }
94
101
 
95
102
  export interface ChatMessage {
@@ -185,6 +192,31 @@ export function cyclePermissionMode(
185
192
  return permission.getMode()
186
193
  }
187
194
 
195
+ /**
196
+ * A retried turn (`chunk.restart`) supersedes the attempt before it.
197
+ *
198
+ * The engine drops that attempt's accumulated text and tool calls — but the
199
+ * engine's accumulator is not the screen. The bubble the attempt opened stays
200
+ * in the message list, and the retry's text appends to it, so the user reads a
201
+ * reply the model never finished as the beginning of the answer that replaced
202
+ * it. Same class as a stale line left by any retry: what was discarded is still
203
+ * on display.
204
+ *
205
+ * `bubble` is the assistant message *object* this attempt pushed, or `null` if
206
+ * it never got to text (a failure during reasoning has nothing to remove).
207
+ * Identity, not position: tool-result rows can sit after the bubble within the
208
+ * same turn, and a previous answer with identical text must not be the one that
209
+ * disappears.
210
+ */
211
+ export function dropSupersededAttempt<T extends { role: string }>(
212
+ messages: T[],
213
+ bubble: T | null,
214
+ ): T[] {
215
+ if (!bubble || bubble.role !== 'assistant') return messages
216
+ const idx = messages.indexOf(bubble)
217
+ return idx === -1 ? messages : messages.filter((_, i) => i !== idx)
218
+ }
219
+
188
220
  /** 预览截断按 UTF-16 码元计数,落点若正好夹在一个代理对中间,切完就留下
189
221
  * **半个** emoji(终端渲染成 U+FFFD)。落点是高代理时后退一个码元即可。 */
190
222
  export function truncateForDisplay(text: string, max: number): string {
@@ -664,8 +696,36 @@ export function App({
664
696
  }
665
697
  }
666
698
 
699
+ // The assistant message object the current attempt pushed, so a retry can
700
+ // remove exactly that one (see `dropSupersededAttempt`). Cleared whenever
701
+ // `isNewTurn` flips, because the next text run opens a fresh bubble.
702
+ let turnBubble: ChatMessage | null = null
703
+
667
704
  try {
668
705
  for await (const chunk of engine.process(input, ctrl.signal)) {
706
+ if (chunk.restart) {
707
+ // A retried turn: the engine drops what the failed attempt
708
+ // accumulated, and the screen has to drop its bubble too — otherwise
709
+ // the retry's answer is appended to a reply the model never
710
+ // finished and the user reads the two as one.
711
+ const superseded = turnBubble
712
+ turnBubble = null
713
+ assistantContent = ''
714
+ turnContent = ''
715
+ isNewTurn = true
716
+ thinkingRef.current = ''
717
+ if (thinkingTimerRef.current) {
718
+ clearTimeout(thinkingTimerRef.current)
719
+ thinkingTimerRef.current = null
720
+ }
721
+ setThinkingText('')
722
+ if (streamBufferRef.current.timer) {
723
+ clearTimeout(streamBufferRef.current.timer)
724
+ }
725
+ streamBufferRef.current = { turnContent: '', isFirst: false, timer: null }
726
+ setMessages((prev) => dropSupersededAttempt(prev, superseded))
727
+ }
728
+
669
729
  // Reasoning content (DeepSeek V4 thinking mode) — surface as a live
670
730
  // "thinking" indicator so long reasoning passes don't look like a stall.
671
731
  if (chunk.reasoning_content) {
@@ -709,10 +769,13 @@ export function App({
709
769
  turnContent = chunk.content
710
770
  isNewTurn = false
711
771
  streamBufferRef.current = { turnContent: chunk.content, isFirst: false, timer: null }
712
- setMessages((prev) => [
713
- ...prev,
714
- { role: 'assistant' as const, content: chunk.content || '' },
715
- ])
772
+ // Keep the object: a retry removes *this* message, by identity.
773
+ const bubble: ChatMessage = {
774
+ role: 'assistant' as const,
775
+ content: chunk.content || '',
776
+ }
777
+ turnBubble = bubble
778
+ setMessages((prev) => [...prev, bubble])
716
779
  } else {
717
780
  turnContent += chunk.content
718
781
  streamBufferRef.current.turnContent = turnContent
@@ -778,6 +841,8 @@ export function App({
778
841
  flushStreamBuffer()
779
842
  // Mark that next text chunk starts a new turn
780
843
  isNewTurn = true
844
+ // The run that bubble held is finished; the next text opens a new one.
845
+ turnBubble = null
781
846
  }
782
847
 
783
848
  if (chunk.type === 'tool_result') {
@@ -838,6 +903,27 @@ export function App({
838
903
  },
839
904
  },
840
905
  ])
906
+ } else {
907
+ // No output at all — a stopped call, or a tool that returns
908
+ // nothing. The call row above stays, and without this row nothing
909
+ // says how it ended, so a finished call reads as one still
910
+ // running. The input is already on the call line; this row only
911
+ // has to record the ending.
912
+ setMessages((prev) => [
913
+ ...prev,
914
+ {
915
+ role: 'system' as const,
916
+ content: '',
917
+ toolMeta: {
918
+ name: '',
919
+ input: '',
920
+ output: '',
921
+ collapsed: true,
922
+ originalName: chunk.toolUse?.name,
923
+ noResult: true,
924
+ },
925
+ },
926
+ ])
841
927
  }
842
928
  }
843
929
 
@@ -1438,6 +1524,21 @@ export function App({
1438
1524
  currentProvider={providerId}
1439
1525
  currentModel={modelId}
1440
1526
  onSelect={(newProvider, newModel) => {
1527
+ // 远程 attach:`switchProvider` 是 no-op,而页脚状态是本地的 ——
1528
+ // 照旧改会得到「页脚说 A、daemon 跑 B」。宁可不改,也要说清楚。
1529
+ if (engine.isRemote) {
1530
+ setPickerOpen(false)
1531
+ setMessages((prev) => [
1532
+ ...prev,
1533
+ {
1534
+ role: 'system',
1535
+ content:
1536
+ `Model is chosen by the daemon in an attached session — ` +
1537
+ `${newProvider}/${newModel} was not applied.`,
1538
+ },
1539
+ ])
1540
+ return
1541
+ }
1441
1542
  engine.switchProvider(newProvider, newModel)
1442
1543
  setProviderId(newProvider)
1443
1544
  setModelId(newModel)