@uncarved/jade 0.2.1 → 0.3.1

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 (227) hide show
  1. package/README.md +65 -2
  2. package/assets/logo.svg +1 -0
  3. package/bin/jade.js +4 -0
  4. package/dist/api.d.ts +5 -250
  5. package/dist/api.js +5 -7
  6. package/dist/api.js.map +1 -1
  7. package/dist/fetch.d.ts +8 -0
  8. package/dist/fetch.js +19 -17
  9. package/dist/fetch.js.map +1 -1
  10. package/dist/host.d.ts +12 -1
  11. package/dist/host.js +49 -1
  12. package/dist/host.js.map +1 -1
  13. package/dist/index.d.ts +1 -1
  14. package/dist/index.js +1 -1
  15. package/dist/index.js.map +1 -1
  16. package/dist/main.js +26 -4
  17. package/dist/main.js.map +1 -1
  18. package/dist/remote.js +4 -0
  19. package/dist/remote.js.map +1 -1
  20. package/dist/session.d.ts +2 -0
  21. package/dist/session.js +133 -13
  22. package/dist/session.js.map +1 -1
  23. package/dist/source.d.ts +2 -10
  24. package/dist/source.js.map +1 -1
  25. package/dist/update.d.ts +8 -20
  26. package/dist/update.js +12 -1
  27. package/dist/update.js.map +1 -1
  28. package/package.json +4 -2
  29. package/plugins/approval/index.ts +236 -85
  30. package/plugins/approval/plugin.json +1 -1
  31. package/plugins/approval/policy.ts +36 -17
  32. package/plugins/approval/review.ts +1 -1
  33. package/plugins/ask/index.ts +2 -2
  34. package/plugins/budget/index.ts +1 -1
  35. package/plugins/checks/checks.ts +3 -2
  36. package/plugins/checks/index.ts +2 -5
  37. package/plugins/commands/index.ts +2 -44
  38. package/plugins/compact/compact.ts +8 -3
  39. package/plugins/compact/index.ts +13 -16
  40. package/plugins/continue/index.ts +1 -1
  41. package/plugins/cost/index.ts +143 -0
  42. package/plugins/cost/plugin.json +13 -0
  43. package/plugins/custom-commands/index.ts +85 -0
  44. package/plugins/custom-commands/plugin.json +8 -0
  45. package/plugins/editor/index.ts +88 -0
  46. package/plugins/editor/plugin.json +17 -0
  47. package/plugins/fs/fs.ts +33 -6
  48. package/plugins/fs/grep.ts +19 -7
  49. package/plugins/fs/index.ts +6 -7
  50. package/plugins/fs/plugin.json +1 -1
  51. package/plugins/fs/renderers.ts +1 -1
  52. package/plugins/hooks/index.ts +152 -0
  53. package/plugins/hooks/plugin.json +14 -0
  54. package/plugins/keys/index.ts +2 -18
  55. package/plugins/mcp/index.ts +43 -15
  56. package/plugins/mcp/install.ts +139 -0
  57. package/plugins/mcp/mcp.ts +2 -1
  58. package/plugins/mcp/plugin.json +1 -1
  59. package/plugins/mcp/project.ts +37 -1
  60. package/plugins/memory/index.ts +4 -9
  61. package/plugins/memory/plugin.json +1 -1
  62. package/plugins/mentions/index.ts +2 -2
  63. package/plugins/models/configure.ts +258 -150
  64. package/plugins/models/context.ts +2 -2
  65. package/plugins/models/index.ts +39 -45
  66. package/plugins/models/plugin.json +1 -1
  67. package/plugins/models/provider.ts +34 -5
  68. package/plugins/models/saved.ts +8 -4
  69. package/plugins/modes/index.ts +2 -17
  70. package/plugins/plugins/index.ts +2 -2
  71. package/plugins/print/index.ts +36 -6
  72. package/plugins/print/plugin.json +1 -0
  73. package/plugins/prompts/index.ts +22 -14
  74. package/plugins/{memory → prompts}/notes.ts +21 -9
  75. package/plugins/prompts/plugin.json +8 -2
  76. package/plugins/prompts/prompts.ts +5 -4
  77. package/plugins/renderers/index.ts +2 -43
  78. package/plugins/repeats/index.ts +32 -2
  79. package/plugins/schedule/index.ts +2 -2
  80. package/plugins/scratch/index.ts +2 -3
  81. package/plugins/screenshot/browser.ts +221 -0
  82. package/plugins/screenshot/index.ts +29 -15
  83. package/plugins/screenshot/plugin.json +1 -1
  84. package/plugins/screenshot/tool.ts +27 -51
  85. package/plugins/sessions/index.ts +2 -17
  86. package/plugins/shell/index.ts +115 -7
  87. package/plugins/shell/plugin.json +3 -1
  88. package/plugins/shell/renderers.ts +1 -1
  89. package/plugins/shell/service.ts +2 -13
  90. package/plugins/shell/shell.ts +119 -47
  91. package/plugins/skills/index.ts +172 -37
  92. package/plugins/skills/install.ts +212 -0
  93. package/plugins/skills/plugin.json +3 -2
  94. package/plugins/skills/project.ts +38 -1
  95. package/plugins/skills/skills.ts +28 -9
  96. package/plugins/steer/index.ts +142 -0
  97. package/plugins/steer/plugin.json +8 -0
  98. package/plugins/suggest/index.ts +16 -11
  99. package/plugins/suggest/plugin.json +1 -1
  100. package/plugins/task/index.ts +18 -57
  101. package/plugins/task/plugin.json +9 -3
  102. package/plugins/task/subagent.ts +25 -7
  103. package/plugins/todo/index.ts +2 -2
  104. package/plugins/tools/index.ts +50 -0
  105. package/plugins/tools/plugin.json +7 -0
  106. package/plugins/tui/editor.ts +10 -2
  107. package/plugins/tui/frontend.ts +129 -23
  108. package/plugins/tui/index.ts +3 -8
  109. package/plugins/tui/markdown.ts +51 -6
  110. package/plugins/tui/mascot.ts +506 -0
  111. package/plugins/tui/plugin.json +2 -2
  112. package/plugins/tui/screen.ts +6 -0
  113. package/plugins/tui/transcript.ts +17 -2
  114. package/plugins/tui/tui.ts +344 -97
  115. package/plugins/undo/checkpoint.ts +2 -2
  116. package/plugins/undo/index.ts +84 -26
  117. package/plugins/undo/plugin.json +8 -2
  118. package/plugins/undo/snapshot.ts +129 -0
  119. package/plugins/update/index.ts +11 -15
  120. package/plugins/update/plugin.json +2 -1
  121. package/plugins/web/index.ts +8 -11
  122. package/plugins/web/plugin.json +1 -1
  123. package/plugins/web/renderers.ts +1 -1
  124. package/plugins-dist/approval/index.js +221 -51
  125. package/plugins-dist/approval/plugin.json +1 -1
  126. package/plugins-dist/approval/policy.js +30 -15
  127. package/plugins-dist/ask/index.js +1 -1
  128. package/plugins-dist/budget/index.js +1 -1
  129. package/plugins-dist/checks/checks.js +2 -1
  130. package/plugins-dist/checks/index.js +1 -1
  131. package/plugins-dist/commands/index.js +1 -1
  132. package/plugins-dist/compact/compact.js +6 -1
  133. package/plugins-dist/compact/index.js +12 -8
  134. package/plugins-dist/continue/index.js +1 -1
  135. package/plugins-dist/cost/index.js +135 -0
  136. package/plugins-dist/cost/plugin.json +16 -0
  137. package/plugins-dist/custom-commands/index.js +86 -0
  138. package/plugins-dist/custom-commands/plugin.json +12 -0
  139. package/plugins-dist/editor/index.js +89 -0
  140. package/plugins-dist/editor/plugin.json +21 -0
  141. package/plugins-dist/fs/fs.js +34 -6
  142. package/plugins-dist/fs/grep.js +17 -6
  143. package/plugins-dist/fs/index.js +6 -6
  144. package/plugins-dist/fs/plugin.json +1 -1
  145. package/plugins-dist/hooks/index.js +145 -0
  146. package/plugins-dist/hooks/plugin.json +19 -0
  147. package/plugins-dist/keys/index.js +1 -1
  148. package/plugins-dist/mcp/index.js +45 -13
  149. package/plugins-dist/mcp/install.js +160 -0
  150. package/plugins-dist/mcp/mcp.js +2 -1
  151. package/plugins-dist/mcp/plugin.json +2 -1
  152. package/plugins-dist/mcp/project.js +42 -1
  153. package/plugins-dist/memory/index.js +3 -5
  154. package/plugins-dist/memory/plugin.json +1 -1
  155. package/plugins-dist/mentions/index.js +1 -1
  156. package/plugins-dist/models/configure.js +252 -151
  157. package/plugins-dist/models/context.js +2 -2
  158. package/plugins-dist/models/index.js +41 -17
  159. package/plugins-dist/models/plugin.json +1 -1
  160. package/plugins-dist/models/provider.js +17 -3
  161. package/plugins-dist/models/saved.js +9 -4
  162. package/plugins-dist/modes/index.js +1 -1
  163. package/plugins-dist/plugins/index.js +1 -1
  164. package/plugins-dist/print/index.js +37 -3
  165. package/plugins-dist/print/plugin.json +3 -0
  166. package/plugins-dist/prompts/index.js +22 -3
  167. package/plugins-dist/{memory → prompts}/notes.js +10 -7
  168. package/plugins-dist/prompts/plugin.json +8 -2
  169. package/plugins-dist/prompts/prompts.js +5 -4
  170. package/plugins-dist/renderers/index.js +1 -1
  171. package/plugins-dist/repeats/index.js +28 -2
  172. package/plugins-dist/schedule/index.js +1 -1
  173. package/plugins-dist/scratch/index.js +1 -1
  174. package/plugins-dist/screenshot/browser.js +187 -0
  175. package/plugins-dist/screenshot/index.js +28 -13
  176. package/plugins-dist/screenshot/plugin.json +1 -1
  177. package/plugins-dist/screenshot/tool.js +27 -49
  178. package/plugins-dist/sessions/index.js +1 -1
  179. package/plugins-dist/shell/index.js +119 -4
  180. package/plugins-dist/shell/plugin.json +3 -1
  181. package/plugins-dist/shell/shell.js +106 -36
  182. package/plugins-dist/skills/index.js +184 -35
  183. package/plugins-dist/skills/install.js +178 -0
  184. package/plugins-dist/skills/plugin.json +6 -2
  185. package/plugins-dist/skills/project.js +43 -1
  186. package/plugins-dist/skills/skills.js +27 -10
  187. package/plugins-dist/steer/index.js +135 -0
  188. package/plugins-dist/steer/plugin.json +12 -0
  189. package/plugins-dist/suggest/index.js +15 -9
  190. package/plugins-dist/suggest/plugin.json +1 -1
  191. package/plugins-dist/task/index.js +17 -46
  192. package/plugins-dist/task/plugin.json +11 -5
  193. package/plugins-dist/task/subagent.js +21 -6
  194. package/plugins-dist/todo/index.js +1 -1
  195. package/plugins-dist/tools/index.js +49 -0
  196. package/plugins-dist/tools/plugin.json +9 -0
  197. package/plugins-dist/tui/editor.js +7 -2
  198. package/plugins-dist/tui/frontend.js +134 -15
  199. package/plugins-dist/tui/index.js +2 -1
  200. package/plugins-dist/tui/markdown.js +48 -6
  201. package/plugins-dist/tui/mascot.js +441 -0
  202. package/plugins-dist/tui/plugin.json +3 -2
  203. package/plugins-dist/tui/screen.js +2 -0
  204. package/plugins-dist/tui/transcript.js +16 -1
  205. package/plugins-dist/tui/tui.js +320 -88
  206. package/plugins-dist/tui/vendor.js +1388 -1088
  207. package/plugins-dist/undo/checkpoint.js +1 -1
  208. package/plugins-dist/undo/index.js +91 -24
  209. package/plugins-dist/undo/plugin.json +10 -3
  210. package/plugins-dist/undo/snapshot.js +111 -0
  211. package/plugins-dist/update/index.js +9 -10
  212. package/plugins-dist/update/plugin.json +4 -1
  213. package/plugins-dist/web/index.js +7 -7
  214. package/plugins-dist/web/plugin.json +1 -1
  215. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  216. package/sdk/python/jade_plugin.py +8 -0
  217. package/src/api.ts +7 -262
  218. package/src/fetch.ts +18 -16
  219. package/src/host.ts +49 -1
  220. package/src/index.ts +1 -1
  221. package/src/main.ts +23 -5
  222. package/src/remote.ts +2 -0
  223. package/src/session.ts +134 -15
  224. package/src/source.ts +2 -11
  225. package/src/update.ts +16 -10
  226. package/plugins/undo/notes.ts +0 -43
  227. package/plugins-dist/undo/notes.js +0 -36
@@ -6,10 +6,10 @@
6
6
  import { writeSync } from "node:fs";
7
7
  import { Box, render, Text, useBoxMetrics, useCursor, useInput, usePaste, useWindowSize, createContext, createElement as h, useContext, useEffect, useReducer, useRef, useState, useSyncExternalStore, } from "./vendor.js";
8
8
  import stringWidth from "string-width";
9
- import wrapAnsi from "wrap-ansi";
10
9
  import { mentionAt, mentionText, rankPaths } from "./mentions.js";
11
10
  import { charWidth, edit, empty, layout, moveRow, offsetAt } from "./editor.js";
12
- import { expandTabs, markdownStream } from "./markdown.js";
11
+ import { expandTabs, markdownStream, softInfo, visibleRow, wrapRows } from "./markdown.js";
12
+ import { cells, FRAME_MS, Mascot, moodOf, nextChange, title } from "./mascot.js";
13
13
  import { dim, } from "./screen.js";
14
14
  /**
15
15
  * 界面可用的尺寸:宽度比终端少一列。
@@ -33,8 +33,8 @@ function keySpec(input, key) {
33
33
  }
34
34
  /** 对话最多保留这么多行(折行前),超出时丢掉最早的一段 */
35
35
  const MAX_LINES = 10_000;
36
- /** 按显示宽度折行,保留颜色;每一项是屏幕上的一行。制表符先换成空格:按 0 列算宽度会对不齐、超宽 */
37
- const wrap = (text, width) => wrapAnsi(expandTabs(text), width, { hard: true, trim: false }).split("\n");
36
+ /** 按显示宽度折行,保留颜色;每一项是屏幕上的一行,自动折出来的续行开头带记号(markdown.ts),显示之前用 visibleRow 去掉 */
37
+ const wrap = wrapRows;
38
38
  /** Markdown 排好的一行折成屏幕上的行 */
39
39
  const mdRows = (l, width) => typeof l === "string" ? wrap(l, width) : l.render(width);
40
40
  /** 按宽度截成一行,截掉了内容时以 … 结尾;留出两列给 … 和展开标记 */
@@ -272,14 +272,52 @@ const CURSOR_BLINK = "\x1b[5 q\x1b[?12h";
272
272
  const CURSOR_RESET = "\x1b[0 q";
273
273
  /** 工作超过这么久后结束,或者这时弹出要用户选择的对话框,用户多半去做别的了:提醒一下 */
274
274
  const NOTIFY_AFTER = 10_000;
275
- /** 支持 OSC 9 桌面通知的终端;其他终端只响铃(不认识的 OSC 9 在有的终端里会弹别的东西) */
275
+ /** 支持 OSC 9 桌面通知的终端;其他终端什么都不发(不认识的 OSC 9 在有的终端里会弹别的东西) */
276
276
  const OSC9_TERMINALS = new Set(["iTerm.app", "WezTerm", "ghostty"]);
277
- /** 响铃,支持的终端再发一条桌面通知。JADE_NOTIFY=off 关闭 */
277
+ /**
278
+ * 支持的终端发一条桌面通知。不响铃:铃声在很多终端里(例如 Windows Terminal)是系统的错误提示音,听起来像出错了。
279
+ * JADE_NOTIFY=off 关闭
280
+ */
278
281
  function notifier(stdout, env = process.env) {
279
- if (env.JADE_NOTIFY === "off")
282
+ if (env.JADE_NOTIFY === "off" || !OSC9_TERMINALS.has(env.TERM_PROGRAM ?? ""))
280
283
  return () => { };
281
- const osc9 = OSC9_TERMINALS.has(env.TERM_PROGRAM ?? "");
282
- return (message) => stdout.write(osc9 ? `\x1b]9;jade: ${message.replace(/[\x00-\x1f\x7f]/g, " ")}\x07` : "\x07");
284
+ return (message) => stdout.write(`\x1b]9;jade: ${message.replace(/[\x00-\x1f\x7f]/g, " ")}\x07`);
285
+ }
286
+ /** 终端标题里的控制字符换成空格,免得提前结束转义序列 */
287
+ const osc0 = (text) => `\x1b]0;${text.replace(/[\x00-\x1f\x7f]/g, " ")}\x07`;
288
+ /** 先把终端原来的标题存进标题栈(xterm 的 CSI 22 t),退出时取回;不支持的终端(如 Windows Terminal)退出时清空标题,回到默认 */
289
+ const TITLE_PUSH = "\x1b[22;0t";
290
+ const TITLE_POP = `${osc0("")}\x1b[23;0t`;
291
+ /**
292
+ * 让终端标签页标题跟着 jade 的状态走(见 mascot.ts 的 title):空闲时显示标志,运行中转圈,等用户时加感叹号。
293
+ * JADE_TITLE=off 关闭。返回关闭函数,会把标题还原
294
+ */
295
+ function titleBar(stdout, store, env = process.env) {
296
+ if (env.JADE_TITLE === "off")
297
+ return () => { };
298
+ let shown = "";
299
+ const update = () => {
300
+ const s = store.state;
301
+ const now = Date.now();
302
+ const mood = moodOf({ busy: s.busy?.label, asking: s.dialogs.length > 0, doneAt: s.doneAt }, now);
303
+ const dir = s.status.cwd.split(/[\\/]/).filter(Boolean).at(-1) ?? s.status.cwd;
304
+ const text = title(mood, dir, now);
305
+ if (text === shown)
306
+ return;
307
+ shown = text;
308
+ stdout.write(osc0(text));
309
+ };
310
+ stdout.write(TITLE_PUSH);
311
+ update();
312
+ const off = store.subscribe(update);
313
+ // 运行中转圈:状态不变时也要按时间换一帧
314
+ const timer = setInterval(() => store.state.busy && update(), 250);
315
+ timer.unref?.();
316
+ return () => {
317
+ off();
318
+ clearInterval(timer);
319
+ stdout.write(TITLE_POP);
320
+ };
283
321
  }
284
322
  export function tuiScreen(opts) {
285
323
  const stdout = opts.io?.stdout ?? process.stdout;
@@ -358,30 +396,38 @@ export function tuiScreen(opts) {
358
396
  });
359
397
  // 切到备用屏幕后光标还停在原来的位置(不少终端不会自动归位),Ink 从那里往下画第一帧会让屏幕滚动,
360
398
  // 之后每帧只重写变化的行,整个界面就错位了。所以先自己切过去、清屏、把光标移到左上角
361
- stdout.write("\x1b[?1049h\x1b[2J\x1b[H");
362
399
  const commands = opts.commands;
363
- const instance = render(h(App, {
364
- store,
365
- copy: (text) => void stdout.write(osc52(text)),
366
- version: opts.version,
367
- commands: typeof commands === "function" ? commands : () => commands,
368
- handlers: opts.handlers,
369
- history: opts.history ?? [],
370
- draft,
371
- }), {
372
- exitOnCtrlC: false,
373
- alternateScreen: true,
374
- // 全屏每帧只重写变化的行
375
- incrementalRendering: true,
376
- ...(opts.io
377
- ? { ...opts.io, interactive: true, patchConsole: false }
378
- : {}),
379
- });
380
- stdout.write(MOUSE_ON + CURSOR_BLINK);
400
+ /** 接管终端、画界面。界面的内容都在 store 里,所以让出终端(suspend)之后可以再画一个新的 */
401
+ const mount = () => {
402
+ stdout.write("\x1b[?1049h\x1b[2J\x1b[H");
403
+ const mounted = render(h(App, {
404
+ store,
405
+ copy: (text) => void stdout.write(osc52(text)),
406
+ version: opts.version,
407
+ commands: typeof commands === "function" ? commands : () => commands,
408
+ handlers: opts.handlers,
409
+ history: opts.history ?? [],
410
+ draft,
411
+ }), {
412
+ exitOnCtrlC: false,
413
+ alternateScreen: true,
414
+ // 全屏每帧只重写变化的行
415
+ incrementalRendering: true,
416
+ ...(opts.io
417
+ ? { ...opts.io, interactive: true, patchConsole: false }
418
+ : {}),
419
+ });
420
+ stdout.write(MOUSE_ON + CURSOR_BLINK);
421
+ return mounted;
422
+ };
423
+ let instance = mount();
424
+ /** 让出终端一次只做一回,后来的排在后面 */
425
+ let yielding = Promise.resolve();
426
+ const closeTitle = titleBar(stdout, store);
381
427
  // 没走 close 就退出(process.exit)时也要把终端还原,否则会留在备用屏幕、鼠标上报也开着
382
428
  const restore = () => {
383
429
  try {
384
- writeSync(1, `${MOUSE_OFF}${CURSOR_RESET}\x1b[?1049l\x1b[?25h`);
430
+ writeSync(1, `${MOUSE_OFF}${CURSOR_RESET}${TITLE_POP}\x1b[?1049l\x1b[?25h`);
385
431
  }
386
432
  catch { }
387
433
  };
@@ -450,7 +496,10 @@ export function tuiScreen(opts) {
450
496
  // 稍等一下再提醒:排队的消息接着开始时(马上又 busy)不算结束
451
497
  if (longBusy())
452
498
  doneTimer ??= setTimeout(() => notify("done"), 300);
453
- store.update({ busy: undefined });
499
+ store.update({
500
+ busy: undefined,
501
+ ...(current && current.label !== "Interrupting" ? { doneAt: Date.now() } : {}),
502
+ });
454
503
  return;
455
504
  }
456
505
  clearTimeout(doneTimer);
@@ -472,6 +521,32 @@ export function tuiScreen(opts) {
472
521
  },
473
522
  hint: (text) => store.update({ hint: text ? text.replace(/\r\n?/g, "\n") : undefined }),
474
523
  },
524
+ copy: (text) => void stdout.write(osc52(text)),
525
+ suspend(fn) {
526
+ const run = yielding.then(async () => {
527
+ // 输入框里打了一半的字在组件里,卸载就没了:先记下
528
+ const typed = draft.current?.get();
529
+ stdout.write(MOUSE_OFF + CURSOR_RESET);
530
+ // 卸载时 Ink 退出备用屏幕、关掉 raw mode、不再读 stdin:终端回到普通状态,别的程序可以用
531
+ instance.unmount();
532
+ await instance.waitUntilExit();
533
+ delete draft.current;
534
+ try {
535
+ return await fn();
536
+ }
537
+ finally {
538
+ instance = mount();
539
+ // 等输入框画出来再返回:调用方接着就可能改输入框(编辑器里写好的内容)
540
+ const input = () => draft.current;
541
+ for (let i = 0; i < 100 && !input(); i++)
542
+ await new Promise((r) => setTimeout(r, 10));
543
+ if (typed)
544
+ input()?.apply(() => ({ value: typed, cursor: typed.length }));
545
+ }
546
+ });
547
+ yielding = run.catch(() => { });
548
+ return run;
549
+ },
475
550
  select: (title, choices, o) => {
476
551
  if (longBusy())
477
552
  notify(title);
@@ -501,6 +576,7 @@ export function tuiScreen(opts) {
501
576
  store.update({ live: undefined, busy: undefined, progress: [] }, true);
502
577
  // 等最后一帧画完再卸载;卸载时 Ink 退出备用屏幕
503
578
  await new Promise((r) => setTimeout(r, 50));
579
+ closeTitle();
504
580
  stdout.write(MOUSE_OFF + CURSOR_RESET);
505
581
  instance.unmount();
506
582
  await instance.waitUntilExit();
@@ -572,17 +648,27 @@ function highlight(line, from, to) {
572
648
  }, (seq) => (out += seq + (on ? INVERSE : "")));
573
649
  return out + (on ? INVERSE_OFF : "");
574
650
  }
575
- /** 选中的纯文字:每行去掉行尾空白,用换行连起来(自动折行的地方也是换行) */
576
- function selectedText(s, row) {
651
+ /**
652
+ * 选中的纯文字:每行去掉行尾空白,用换行连起来。自动折行出来的续行接回上一行(补上折行时去掉的空格、
653
+ * 跳过排版加的缩进),所以一行很长的命令复制出来还是一行。row 给的是带续行记号的行
654
+ */
655
+ export function selectedText(s, row) {
577
656
  const lines = [];
578
657
  const { anchor: a, focus: f } = s;
579
- for (let r = Math.min(a.row, f.row); r <= Math.max(a.row, f.row); r++) {
658
+ const first = Math.min(a.row, f.row);
659
+ for (let r = first; r <= Math.max(a.row, f.row); r++) {
580
660
  const [from, to] = selectedCols(s, r);
661
+ const { text: line, soft, gap, indent } = softInfo(row(r) ?? "");
581
662
  let text = "";
582
- walk(row(r) ?? "", from, to, (ch, inside) => void (inside && (text += ch)));
583
- lines.push(text.trimEnd());
663
+ // 续行开头的缩进、竖线是排版加的
664
+ walk(line, Math.max(from, soft ? indent : 0), to, (ch, inside) => void (inside && (text += ch)));
665
+ if (soft && r > first)
666
+ lines[lines.length - 1] += " ".repeat(gap) + text;
667
+ // 代码块左边的竖线是排版加的,不是代码的一部分
668
+ else
669
+ lines.push(text.replace(/^┃ ?/, ""));
584
670
  }
585
- return lines.join("\n");
671
+ return lines.map((l) => l.trimEnd()).join("\n");
586
672
  }
587
673
  /** OSC 52:让终端把文字放进系统剪贴板(Windows Terminal、iTerm2、kitty、WezTerm 等支持) */
588
674
  const osc52 = (text) => `\x1b]52;c;${Buffer.from(text, "utf8").toString("base64")}\x07`;
@@ -601,17 +687,32 @@ const roomFor = (rows, max) => Math.max(3, Math.min(max, Math.floor((rows - 10)
601
687
  function App({ store, copy, version, commands, handlers, history, draft, }) {
602
688
  const state = useSyncExternalStore(store.subscribe, store.get);
603
689
  const dialog = state.dialogs[0];
604
- // 运行中每 100ms 整体重画一次,推动转圈动画。不能让 Spinner 自己重画:
690
+ const { columns, rows } = useScreenSize();
691
+ const compact = rows < COMPACT_ROWS;
692
+ // 运行中每一帧(FRAME_MS)整体重画一次,推动转圈和吉祥物的动画。不能让 Spinner、吉祥物自己重画:
605
693
  // Ink 只在输入框也跟着提交的那一帧保留光标,否则把光标藏起来,运行中光标就不见了
606
- const [, tick] = useReducer((n) => n + 1, 0);
694
+ const [ticks, tick] = useReducer((n) => n + 1, 0);
607
695
  const busy = state.busy !== undefined;
608
696
  useEffect(() => {
609
697
  if (!busy)
610
698
  return;
611
- const t = setInterval(tick, 100);
699
+ const t = setInterval(tick, FRAME_MS);
612
700
  return () => clearInterval(t);
613
701
  }, [busy]);
614
- const { columns, rows } = useScreenSize();
702
+ const now = Date.now();
703
+ const mood = moodOf({ busy: state.busy?.label, asking: dialog !== undefined, doneAt: state.doneAt }, now);
704
+ const mascot = useRef(undefined);
705
+ mascot.current ??= new Mascot();
706
+ const showBot = !compact && columns >= 50;
707
+ const bot = showBot ? mascot.current.frame(mood, now) : undefined;
708
+ // 不在运行时吉祥物也会眨眼、瞟一眼、从上一个表情缓过来:只在它要动的时候按帧重画,其余时间不画
709
+ const moving = showBot && mascot.current.moving(mood, now);
710
+ useEffect(() => {
711
+ if (busy || !showBot)
712
+ return;
713
+ const t = setTimeout(tick, nextChange(mood, Date.now(), state.doneAt, moving));
714
+ return () => clearTimeout(t);
715
+ }, [busy, showBot, ticks, mood, moving, state.doneAt]);
615
716
  // 对话区占掉标题和底部之外的全部高度,只画能看见的那几行
616
717
  const ref = useRef(null);
617
718
  const { height, top } = useBoxMetrics(ref);
@@ -653,8 +754,10 @@ function App({ store, copy, version, commands, handlers, history, draft, }) {
653
754
  const [copied, setCopied] = useState();
654
755
  const copiedTimer = useRef(undefined);
655
756
  useEffect(() => () => clearTimeout(copiedTimer.current), []);
656
- const copySelection = (s) => {
657
- const text = selectedText(s, rowAt);
757
+ /** 输入框文字在屏幕上的位置(Prompt 里的 EditableText 每次渲染时写入) */
758
+ const inputPlace = useRef(undefined);
759
+ const copySelection = (s) => copyText(selectedText(s, rowAt));
760
+ const copyText = (text) => {
658
761
  copy(text);
659
762
  clearTimeout(copiedTimer.current);
660
763
  setCopied(`Copied ${[...text].length} characters to the clipboard`);
@@ -696,6 +799,11 @@ function App({ store, copy, version, commands, handlers, history, draft, }) {
696
799
  return undefined;
697
800
  return { row: start + Math.min(Math.max(i, 0), shown.length - 1), col: Math.max(0, mouse.x - 1) };
698
801
  };
802
+ // 滚轮在放不下全部文字的输入框上(含上下边框)时由输入框自己翻
803
+ const input = inputPlace.current;
804
+ const overInput = input && input.total > input.rows && mouse.y >= input.y - 1 && mouse.y <= input.y + input.rows;
805
+ if ((mouse.button === 64 || mouse.button === 65) && overInput)
806
+ return;
699
807
  if (mouse.button === 64)
700
808
  store.scrollBy(WHEEL_LINES, max);
701
809
  else if (mouse.button === 65)
@@ -750,7 +858,7 @@ function App({ store, copy, version, commands, handlers, history, draft, }) {
750
858
  overflowY: "hidden",
751
859
  },
752
860
  // 垫的空白放在外层:里面这层在重画那一帧和平时一样高,对话区的 top(相对父节点)不变,点击换算的行号不会差一行
753
- h(Box, { flexDirection: "column", flexGrow: 1, overflowY: "hidden" }, h(Header, { status: state.status, version, compact: rows < COMPACT_ROWS }), h(Box, {
861
+ h(Box, { flexDirection: "column", flexGrow: 1, overflowY: "hidden" }, h(Header, { status: state.status, version, compact, bot }), h(Box, {
754
862
  ref,
755
863
  flexDirection: "column",
756
864
  flexGrow: 1,
@@ -758,7 +866,9 @@ function App({ store, copy, version, commands, handlers, history, draft, }) {
758
866
  flexBasis: 0,
759
867
  overflowY: "hidden",
760
868
  paddingX: 1,
761
- }, shown.map((l, i) => {
869
+ }, shown.map((raw, i) => {
870
+ // 续行的记号不显示
871
+ const l = visibleRow(raw);
762
872
  const cols = selection && selectedCols(selection, start + i);
763
873
  return h(Text, { key: i, wrap: "truncate-end" }, cols ? highlight(l || " ", ...cols) : l || " ");
764
874
  }), scrolled
@@ -779,19 +889,17 @@ function App({ store, copy, version, commands, handlers, history, draft, }) {
779
889
  active: !dialog,
780
890
  onSubmit: () => store.scrollBy(-max, max),
781
891
  flash: copied,
892
+ place: inputPlace,
893
+ onCopy: copyText,
782
894
  }), h(StatusBar, { status: state.status, width: Math.max(10, columns - 2) })))));
783
895
  }
784
- const JADE = "#00a86b";
785
- const SHINE = "#b6f2d4";
786
896
  /**
787
- * 标题左边的吉祥物:一个玉做的团子,用半格字符画的像素图,三行高,正好和右边三行文字并排。
788
- * 每个字符上下两个像素;眼睛是玉上挖空的两格,左上角一点高光让它看起来像玉
897
+ * 标题左边的吉祥物(见 mascot.ts):玉做的团子,按 mood 换表情和动画,三行高,正好和右边三行文字并排
789
898
  */
790
- function Bot() {
791
- return h(Box, { flexDirection: "column", flexShrink: 0, marginRight: 2 }, h(Text, { color: JADE }, " ▄", h(Text, { color: SHINE, backgroundColor: JADE }, "▄"), "████▄"), h(Text, { color: JADE }, "██ ███ ██"), h(Text, { color: JADE }, "▀███████▀"));
899
+ function Bot({ pixels }) {
900
+ return h(Box, { flexDirection: "column", flexShrink: 0, marginRight: 1 }, ...cells(pixels).map((row, i) => h(Text, { key: i }, ...row.map((r, j) => h(Text, { key: j, color: r.fg, backgroundColor: r.bg }, r.text)))));
792
901
  }
793
- function Header({ status, version, compact, }) {
794
- const { columns } = useScreenSize();
902
+ function Header({ status, version, compact, bot, }) {
795
903
  // 模型 · 目录 (分支)
796
904
  const where = [
797
905
  h(Text, { key: "model", color: "cyan" }, status.model),
@@ -802,7 +910,7 @@ function Header({ status, version, compact, }) {
802
910
  const name = h(Text, { key: "name", color: "cyan", bold: true }, "jade");
803
911
  if (compact)
804
912
  return h(Box, { flexShrink: 0, paddingX: 1 }, h(Text, { wrap: "truncate-end" }, name, h(Text, { key: "dot", dimColor: true }, " · "), ...where));
805
- return h(Box, { flexShrink: 0, borderStyle: "round", borderColor: "cyan", paddingX: 1 }, columns >= 50 ? h(Bot) : null, h(Box, { flexDirection: "column", flexGrow: 1, flexShrink: 1 }, h(Text, { wrap: "truncate-end" }, name, h(Text, { dimColor: true }, ` v${version}`), status.session ? h(Text, { dimColor: true }, ` · session ${status.session}`) : null), h(Text, { wrap: "truncate-end" }, ...where), h(Text, { dimColor: true, wrap: "truncate-end" }, "/help for commands · @ to attach files")));
913
+ return h(Box, { flexShrink: 0, borderStyle: "round", borderColor: "cyan", paddingX: 1 }, bot ? h(Bot, { pixels: bot }) : null, h(Box, { flexDirection: "column", flexGrow: 1, flexShrink: 1 }, h(Text, { wrap: "truncate-end" }, name, h(Text, { dimColor: true }, ` v${version}`), status.session ? h(Text, { dimColor: true }, ` · session ${status.session}`) : null), h(Text, { wrap: "truncate-end" }, ...where), h(Text, { dimColor: true, wrap: "truncate-end" }, "/help for commands · @ to attach files")));
806
914
  }
807
915
  const dialogIds = new WeakMap();
808
916
  let dialogCounter = 0;
@@ -975,8 +1083,16 @@ function editKey(s, input, key) {
975
1083
  .replace(/[\x00-\x09\x0b-\x1f\x7f]/g, "");
976
1084
  return text ? edit.insert(s, text) : undefined;
977
1085
  }
1086
+ /** 一行文字里下标 [from, to)(相对这一行)反色显示,和对话区的选中一样 */
1087
+ function inverseRange(row, from, to) {
1088
+ from = Math.max(0, Math.min(row.length, from));
1089
+ to = Math.max(from, Math.min(row.length, to));
1090
+ if (from === to)
1091
+ return row;
1092
+ return `${row.slice(0, from)}${INVERSE}${row.slice(from, to)}${INVERSE_OFF}${row.slice(to)}`;
1093
+ }
978
1094
  /** 渲染可编辑文本并把终端光标放到输入位置(输入法的候选框跟着它) */
979
- function EditableText({ state, width, prefix, mask, placeholder, active, maxRows = Infinity, place, }) {
1095
+ function EditableText({ state, width, prefix, mask, placeholder, active, maxRows = Infinity, place, top, selected, }) {
980
1096
  const ref = useRef(null);
981
1097
  // 只用来在布局变化后重画一次、重新计算光标位置;它给的是相对父元素的坐标,光标要的是相对整个输出
982
1098
  const metrics = useBoxMetrics(ref);
@@ -986,10 +1102,14 @@ function EditableText({ state, width, prefix, mask, placeholder, active, maxRows
986
1102
  : state.cursor;
987
1103
  const all = layout(shown, cursor, width - prefix.length);
988
1104
  const { col } = all;
989
- // 行数超过 maxRows 时滚动,光标所在的行总在可见范围里
990
- const first = Math.max(0, Math.min(all.row - maxRows + 1, all.rows.length - maxRows));
1105
+ // 行数超过 maxRows 时滚动:平时光标所在的行总在可见范围里,用滚轮翻过时停在翻到的地方(光标可能不在里面)
1106
+ const last = Math.max(0, all.rows.length - maxRows);
1107
+ const first = top === undefined
1108
+ ? Math.max(0, Math.min(all.row - maxRows + 1, last))
1109
+ : Math.max(0, Math.min(top, last));
991
1110
  const rows = all.rows.slice(first, first + maxRows);
992
1111
  const row = all.row - first;
1112
+ const cursorShown = row >= 0 && row < rows.length;
993
1113
  // 光标位置要在渲染时设:useCursor 在这次提交时交给 Ink,跟这一帧一起画出来。
994
1114
  // 放在 useEffect 里会晚一帧,光标总是停在上一次按键的位置(只移动光标时最明显)。
995
1115
  // 这里用的是上一次的布局,提交后要核对一遍:
@@ -999,9 +1119,9 @@ function EditableText({ state, width, prefix, mask, placeholder, active, maxRows
999
1119
  const at = active && metrics.hasMeasured && ref.current
1000
1120
  ? origin(ref.current)
1001
1121
  : undefined;
1002
- const position = at && { x: at.x + prefix.length + col, y: at.y + row };
1122
+ const position = at && cursorShown ? { x: at.x + prefix.length + col, y: at.y + row } : undefined;
1003
1123
  if (place)
1004
- place.current = at && { x: at.x + prefix.length, y: at.y, first, rows: rows.length };
1124
+ place.current = at && { x: at.x + prefix.length, y: at.y, first, rows: rows.length, total: all.rows.length };
1005
1125
  const [, recheck] = useReducer((n) => n + 1, 0);
1006
1126
  useEffect(() => {
1007
1127
  if (!at || !ref.current)
@@ -1012,7 +1132,13 @@ function EditableText({ state, width, prefix, mask, placeholder, active, maxRows
1012
1132
  });
1013
1133
  return h(Box, { ref, flexDirection: "column" }, active ? h(CursorAt, { position }) : null, state.value === "" && placeholder
1014
1134
  ? h(Text, { wrap: "truncate-end" }, h(Text, { color: "cyan" }, prefix), h(Text, { dimColor: true }, placeholder))
1015
- : rows.map((r, i) => h(Text, { key: first + i, wrap: "truncate-end" }, h(Text, { color: "cyan" }, first + i === 0 ? prefix : i === 0 ? "↑".padEnd(prefix.length) : " ".repeat(prefix.length)), r)));
1135
+ : rows.map((r, i) => h(Text, { key: first + i, wrap: "truncate-end" }, h(Text, { color: "cyan" }, first + i === 0
1136
+ ? prefix
1137
+ : i === 0
1138
+ ? "↑".padEnd(prefix.length)
1139
+ : i === rows.length - 1 && first + rows.length < all.rows.length
1140
+ ? "↓".padEnd(prefix.length)
1141
+ : " ".repeat(prefix.length)), selected && !mask ? inverseRange(r, selected[0] - all.starts[first + i], selected[1] - all.starts[first + i]) : r)));
1016
1142
  }
1017
1143
  /**
1018
1144
  * 终端光标只有一个,每个 useCursor 每次提交都会设一遍。没有焦点的输入框(弹出输入框时下面的主输入框)
@@ -1033,7 +1159,7 @@ function origin(node) {
1033
1159
  }
1034
1160
  return { x, y };
1035
1161
  }
1036
- function Prompt({ commands, handlers, history: initial, bridge, hint, onHintDone, busy, queued, active, onSubmit, flash, }) {
1162
+ function Prompt({ commands, handlers, history: initial, bridge, hint, onHintDone, busy, queued, active, onSubmit, flash, place, onCopy, }) {
1037
1163
  const selection = useContext(SelectionContext);
1038
1164
  const [current, setState] = useLive(empty);
1039
1165
  const [getSelected, setSelected] = useLive(0);
@@ -1044,8 +1170,12 @@ function Prompt({ commands, handlers, history: initial, bridge, hint, onHintDone
1044
1170
  const draft = useRef("");
1045
1171
  const lastCtrlC = useRef(0);
1046
1172
  const lastEsc = useRef(0);
1047
- /** 输入框文字在屏幕上的位置,点击时换算光标位置用(见 EditableText 的 place) */
1048
- const place = useRef(undefined);
1173
+ /**
1174
+ * 用滚轮翻过输入框时翻到的第一行可见行。只对翻的时候的那份文字和光标有效:打字、移动光标后又跟着光标
1175
+ */
1176
+ const scrolled = useRef(undefined);
1177
+ /** 在输入框里按住左键拖动选中的文字:anchor 是按下的位置,focus 是拖到的位置(value 里的下标);文字改了就作废 */
1178
+ const [getDrag, setDrag] = useLive(undefined);
1049
1179
  const { columns, rows } = useScreenSize();
1050
1180
  /** 输入框里文字的宽度:边框、内边距和前面的 "› " 之外 */
1051
1181
  const textWidth = Math.max(10, columns - 5) - 2;
@@ -1130,9 +1260,7 @@ function Prompt({ commands, handlers, history: initial, bridge, hint, onHintDone
1130
1260
  /** 提示只在空闲、输入框为空、没有在搜索历史时显示,也只有这时能接受 */
1131
1261
  const hinting = () => hint !== undefined && !busy && current().value === "" && !getSearch();
1132
1262
  const set = (s) => {
1133
- // 用户开始打字(或者插件改了输入框):提示作废
1134
- if (s.value && hint !== undefined)
1135
- onHintDone();
1263
+ // 打字时提示只是不显示(hinting() 要求输入框为空),删回空的又出现;发出去才作废
1136
1264
  setState(s);
1137
1265
  setSelected(0);
1138
1266
  setNotice(undefined);
@@ -1148,8 +1276,12 @@ function Prompt({ commands, handlers, history: initial, bridge, hint, onHintDone
1148
1276
  const submit = (text) => {
1149
1277
  if (!text.trim())
1150
1278
  return;
1279
+ if (hint !== undefined)
1280
+ onHintDone();
1151
1281
  remember(text);
1152
1282
  set(empty);
1283
+ // 发出去之后弹出的对话框是用户自己要的(/mode、/model),马上就能回答
1284
+ typedAt = 0;
1153
1285
  onSubmit();
1154
1286
  handlers.submit(text);
1155
1287
  };
@@ -1227,13 +1359,69 @@ function Prompt({ commands, handlers, history: initial, bridge, hint, onHintDone
1227
1359
  if (search)
1228
1360
  return searchKey(search, input, key);
1229
1361
  const state = current();
1362
+ // 输入框里的鼠标:点击移动光标,按住拖动选中、松开时复制,滚轮翻看放不下的文字
1363
+ const mouse = mouseEvent(input);
1364
+ if (mouse) {
1365
+ const at = place.current;
1366
+ if (!at)
1367
+ return;
1368
+ const row = mouse.y - at.y;
1369
+ // 拖出输入框时停在第一行或最后一行
1370
+ const offset = (r) => offsetAt(state.value, textWidth, at.first + Math.max(0, Math.min(at.rows - 1, r)), mouse.x - at.x);
1371
+ // 滚轮:上下边框也算在输入框上
1372
+ if ((mouse.button === 64 || mouse.button === 65) && row >= -1 && row <= at.rows && at.total > at.rows) {
1373
+ const top = Math.max(0, Math.min(at.total - at.rows, at.first + (mouse.button === 64 ? -WHEEL_LINES : WHEEL_LINES)));
1374
+ scrolled.current = { top, value: state.value, cursor: state.cursor };
1375
+ return setState({ ...state });
1376
+ }
1377
+ if (mouse.button === 0 && mouse.press) {
1378
+ if (row < 0 || row >= at.rows)
1379
+ return setDrag(undefined);
1380
+ const cursor = offset(row);
1381
+ if (cursor === undefined)
1382
+ return;
1383
+ setDrag({ anchor: cursor, focus: cursor, value: state.value });
1384
+ // 点在翻过的地方时保持翻到的位置
1385
+ if (scrolled.current)
1386
+ scrolled.current = { ...scrolled.current, cursor };
1387
+ return setState({ ...state, cursor });
1388
+ }
1389
+ const drag = getDrag();
1390
+ if (!drag || drag.value !== state.value)
1391
+ return;
1392
+ if (mouse.button === DRAG) {
1393
+ const focus = offset(row);
1394
+ if (focus === undefined)
1395
+ return;
1396
+ setDrag({ ...drag, focus });
1397
+ if (scrolled.current)
1398
+ scrolled.current = { ...scrolled.current, cursor: focus };
1399
+ return setState({ ...state, cursor: focus });
1400
+ }
1401
+ if (mouse.button === 0 && !mouse.press && drag.anchor !== drag.focus) {
1402
+ onCopy(state.value.slice(Math.min(drag.anchor, drag.focus), Math.max(drag.anchor, drag.focus)));
1403
+ }
1404
+ return;
1405
+ }
1406
+ // 别的键取消输入框里的选中;Ctrl+C 只取消选中(已经在松开时复制过了)
1407
+ const drag = getDrag();
1408
+ if (drag) {
1409
+ setDrag(undefined);
1410
+ if (key.ctrl && input === "c" && drag.anchor !== drag.focus && drag.value === state.value)
1411
+ return;
1412
+ }
1230
1413
  if (key.ctrl && input === "r")
1231
1414
  return history.current.length
1232
1415
  ? setSearch({ query: "", index: 0 })
1233
1416
  : undefined;
1234
1417
  if (key.ctrl && input === "c") {
1235
- if (busy)
1418
+ if (busy) {
1419
+ // 第一下中断;停不下来时(卡在 Interrupting)再按一下也能退出
1420
+ if (Date.now() - lastCtrlC.current < 2000)
1421
+ return handlers.exit();
1422
+ lastCtrlC.current = Date.now();
1236
1423
  return handlers.interrupt();
1424
+ }
1237
1425
  if (state.value)
1238
1426
  return discard();
1239
1427
  if (Date.now() - lastCtrlC.current < 2000)
@@ -1253,20 +1441,6 @@ function Prompt({ commands, handlers, history: initial, bridge, hint, onHintDone
1253
1441
  lastEsc.current = Date.now();
1254
1442
  return;
1255
1443
  }
1256
- // 点击输入框里的文字:光标移到点的位置
1257
- const mouse = mouseEvent(input);
1258
- if (mouse) {
1259
- const at = place.current;
1260
- if (!at || mouse.button !== 0 || !mouse.press)
1261
- return;
1262
- const row = mouse.y - at.y;
1263
- if (row < 0 || row >= at.rows)
1264
- return;
1265
- const cursor = offsetAt(state.value, textWidth, at.first + row, mouse.x - at.x);
1266
- if (cursor !== undefined)
1267
- setState({ ...state, cursor });
1268
- return;
1269
- }
1270
1444
  // 文字和回车在同一块里到达(输入很快时终端可能合并):插入文字后发送
1271
1445
  if (!key.ctrl &&
1272
1446
  !key.meta &&
@@ -1275,8 +1449,9 @@ function Prompt({ commands, handlers, history: initial, bridge, hint, onHintDone
1275
1449
  return submit(edit.insert(state, input.slice(0, -1)).value.trim());
1276
1450
  }
1277
1451
  if (key.return) {
1278
- // 行尾的 \ 加回车换行;Alt+Enter 也换行
1279
- if (key.meta)
1452
+ // 行尾的 \ 加回车换行;Alt+Enter 也换行;终端把 Shift+Enter 单独报上来时(kitty 键盘协议、modifyOtherKeys)也换行。
1453
+ // Ctrl+J(Windows Terminal 里 Ctrl+Enter 也是它)发的是 LF,不算回车,在 editKey 里当普通换行插入
1454
+ if (key.meta || key.shift)
1280
1455
  return set(edit.insert(state, "\n"));
1281
1456
  if (state.value.slice(0, state.cursor).endsWith("\\"))
1282
1457
  return set(edit.insert(edit.backspace(state), "\n"));
@@ -1289,7 +1464,6 @@ function Prompt({ commands, handlers, history: initial, bridge, hint, onHintDone
1289
1464
  }
1290
1465
  // Tab 或 →:把提示变成输入框里的文字,接着可以改
1291
1466
  if (((key.tab && !key.shift) || key.rightArrow) && hinting()) {
1292
- onHintDone();
1293
1467
  browsing.current = -1;
1294
1468
  return set({ value: hint, cursor: hint.length });
1295
1469
  }
@@ -1341,11 +1515,22 @@ function Prompt({ commands, handlers, history: initial, bridge, hint, onHintDone
1341
1515
  if (spec && handlers.key?.(spec))
1342
1516
  return;
1343
1517
  const next = editKey(state, input, key);
1344
- if (next)
1518
+ if (next) {
1519
+ if (next.value !== state.value)
1520
+ typedAt = Date.now();
1345
1521
  set(next);
1522
+ }
1346
1523
  }, { isActive: active });
1524
+ const view = scrolled.current;
1525
+ const viewTop = view && view.value === state.value && view.cursor === state.cursor ? view.top : undefined;
1526
+ const drag = getDrag();
1527
+ const dragged = drag && drag.value === state.value && drag.anchor !== drag.focus
1528
+ ? [Math.min(drag.anchor, drag.focus), Math.max(drag.anchor, drag.focus)]
1529
+ : undefined;
1530
+ // ! 开头:这一行是用户自己执行的 shell 命令(/sh),边框换个颜色、上边框的右边写一行说明
1531
+ const bang = !search && state.value.startsWith("!");
1347
1532
  // 对话框打开时隐藏但不卸载,输入到一半的内容和历史都保留
1348
- return h(Box, { flexDirection: "column", marginTop: 1, display: active ? "flex" : "none" }, h(Box, { borderStyle: "round", borderColor: busy ? "gray" : "cyan", paddingX: 1 }, search
1533
+ return h(Box, { flexDirection: "column", marginTop: 1, display: active ? "flex" : "none" }, h(Box, { borderStyle: "round", borderColor: bang ? "magenta" : busy ? "gray" : "cyan", paddingX: 1 }, search
1349
1534
  ? h(EditableText, {
1350
1535
  state: { value: search.query, cursor: search.query.length },
1351
1536
  width: Math.max(10, columns - 5),
@@ -1370,6 +1555,8 @@ function Prompt({ commands, handlers, history: initial, bridge, hint, onHintDone
1370
1555
  active,
1371
1556
  maxRows: inputRows,
1372
1557
  place,
1558
+ top: viewTop,
1559
+ selected: dragged,
1373
1560
  })), search
1374
1561
  ? h(Box, { flexDirection: "column", paddingX: 2 }, results.length
1375
1562
  ? results.slice(first, first + menuRows).map((item, i) => {
@@ -1407,7 +1594,12 @@ function Prompt({ commands, handlers, history: initial, bridge, hint, onHintDone
1407
1594
  ? h(Text, { color: "yellow" }, ` ${notice}`)
1408
1595
  : null,
1409
1596
  // 压在输入框上边框的右边,不占行,出现和消失时下面的内容不跳
1410
- flash ? h(Box, { position: "absolute", top: 0, right: 2 }, h(Text, { color: "green" }, ` ${flash} `)) : null);
1597
+ // ! 开头时同一个位置写这一行是什么(刚复制的提示优先)
1598
+ flash
1599
+ ? h(Box, { position: "absolute", top: 0, right: 2 }, h(Text, { color: "green" }, ` ${flash} `))
1600
+ : bang
1601
+ ? h(Box, { position: "absolute", top: 0, right: 2 }, h(Text, { color: "magenta" }, columns >= 70 ? (busy ? " shell command · runs after this turn · esc stops it " : " shell command · you run it, not the agent · esc stops it ") : " shell command "))
1602
+ : null);
1411
1603
  }
1412
1604
  /** 提示在输入框里只显示第一行,后面还有时加 … */
1413
1605
  const hintLine = (hint) => {
@@ -1420,6 +1612,24 @@ const MENTION_ROWS = 8;
1420
1612
  function around(selected, total, size) {
1421
1613
  return Math.max(0, Math.min(selected - Math.floor(size / 2), total - size));
1422
1614
  }
1615
+ /** 用户上一次在输入框里打字的时间;发送之后清零 */
1616
+ let typedAt = 0;
1617
+ /** 打字停下这么久之后,对话框才把回车和字符当成回答 */
1618
+ const TYPING_GRACE = 500;
1619
+ /**
1620
+ * 对话框弹出时用户正在输入框里打字(例如在排下一条消息时弹出审批):接着打出来的回车、数字不能当成回答。
1621
+ * 返回 true 表示这个键要丢掉。方向键、Esc 说明用户已经看到对话框了,不再拦
1622
+ */
1623
+ function typedThrough(input, key) {
1624
+ if (Date.now() - typedAt >= TYPING_GRACE)
1625
+ return false;
1626
+ if (key.escape || key.upArrow || key.downArrow || key.pageUp || key.pageDown || (key.ctrl && input === "c") || MOUSE.test(input)) {
1627
+ typedAt = 0;
1628
+ return false;
1629
+ }
1630
+ typedAt = Date.now();
1631
+ return true;
1632
+ }
1423
1633
  /** 选择框一次最多显示几项 */
1424
1634
  const VISIBLE = 10;
1425
1635
  /** 选项多于这么多时可以打字筛选(这时 j/k 和数字键不再是快捷键) */
@@ -1428,6 +1638,9 @@ function SelectDialog({ dialog, }) {
1428
1638
  const selection = useContext(SelectionContext);
1429
1639
  const [getSelected, setSelected] = useLive(0);
1430
1640
  const [getQuery, setQuery] = useLive("");
1641
+ /** 预览从第几行开始显示,以及它能翻到哪里、一页几行(放得下时 maxTop 是 0) */
1642
+ const [getTop, setTop] = useLive(0);
1643
+ const scrolling = useRef({ maxTop: 0, page: 1 });
1431
1644
  const { rows, columns } = useScreenSize();
1432
1645
  const filtering = dialog.choices.length > FILTER_FROM;
1433
1646
  const query = getQuery();
@@ -1445,14 +1658,26 @@ function SelectDialog({ dialog, }) {
1445
1658
  const visible = roomFor(rows, VISIBLE);
1446
1659
  // 预览(例如要写入的文件)过长时截断:整个界面高过终端时 Ink 会每帧清屏重画,底部的选项和提示也会被裁掉。
1447
1660
  // 按折行后的屏幕行数截断(一行长代码会占好几行),每一行单独显示、不再折行
1448
- const lines = !dialog.body ? [] : wrap(dialog.body, Math.max(1, columns - 4));
1661
+ const lines = !dialog.body ? [] : wrap(dialog.body, Math.max(1, columns - 4)).map(visibleRow);
1449
1662
  const room = Math.max(3, rows - Math.min(n, visible) - 16);
1663
+ // 放不下时 PgUp/PgDn 翻看预览(批准之前要能看完整个 diff),最后一行说明还有多少
1664
+ const page = room - 1;
1665
+ const maxTop = Math.max(0, lines.length - page);
1666
+ const top = Math.min(getTop(), maxTop);
1667
+ scrolling.current = { maxTop, page };
1450
1668
  const body = lines.length > room
1451
- ? [...lines.slice(0, room - 1), dim(`… ${lines.length - room + 1} more lines`)]
1669
+ ? [
1670
+ ...lines.slice(top, top + page),
1671
+ dim(top < maxTop
1672
+ ? `… ${lines.length - top - page} more lines · PgDn/PgUp to scroll`
1673
+ : `end of ${lines.length} lines · PgUp to scroll back`),
1674
+ ]
1452
1675
  : lines;
1453
1676
  useInput((input, key) => {
1454
1677
  if (key.ctrl && input === "c" && selection.active())
1455
1678
  return selection.clear();
1679
+ if (typedThrough(input, key))
1680
+ return;
1456
1681
  const items = filtered();
1457
1682
  const n = items.length;
1458
1683
  const selected = Math.min(getSelected(), Math.max(0, n - 1));
@@ -1471,6 +1696,11 @@ function SelectDialog({ dialog, }) {
1471
1696
  }
1472
1697
  if (key.escape || (key.ctrl && input === "c"))
1473
1698
  return dialog.resolve(undefined);
1699
+ // 预览放不下时翻预览,否则翻选项
1700
+ const { maxTop, page } = scrolling.current;
1701
+ if (maxTop > 0 && (key.pageDown || key.pageUp)) {
1702
+ return setTop(Math.max(0, Math.min(maxTop, Math.min(getTop(), maxTop) + (key.pageDown ? page : -page))));
1703
+ }
1474
1704
  if (key.pageDown)
1475
1705
  return setSelected(Math.min(n - 1, selected + visible));
1476
1706
  if (key.pageUp)
@@ -1520,6 +1750,8 @@ function InputDialog({ dialog, }) {
1520
1750
  useInput((input, key) => {
1521
1751
  if (key.ctrl && input === "c" && selection.active())
1522
1752
  return selection.clear();
1753
+ if (typedThrough(input, key))
1754
+ return;
1523
1755
  const state = current();
1524
1756
  if (key.return)
1525
1757
  return dialog.resolve(state.value.trim());