@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
@@ -25,10 +25,10 @@ import {
25
25
  useSyncExternalStore,
26
26
  } from "./vendor.ts";
27
27
  import stringWidth from "string-width";
28
- import wrapAnsi from "wrap-ansi";
29
28
  import { mentionAt, mentionText, rankPaths } from "./mentions.ts";
30
29
  import { charWidth, edit, empty, layout, moveRow, offsetAt, type EditState } from "./editor.ts";
31
- import { expandTabs, markdownStream, type MdLine } from "./markdown.ts";
30
+ import { expandTabs, markdownStream, softInfo, visibleRow, wrapRows, type MdLine } from "./markdown.ts";
31
+ import { cells, FRAME_MS, Mascot, moodOf, nextChange, title } from "./mascot.ts";
32
32
  import {
33
33
  dim,
34
34
  type Choice,
@@ -101,6 +101,8 @@ interface UiState {
101
101
  /** 对话区离底部滚上去了多少行;0 表示跟着最新的输出 */
102
102
  scroll: number;
103
103
  busy?: { label: string; since: number };
104
+ /** 上一次正常做完(不是中断)的时间,吉祥物据此笑一会儿 */
105
+ doneAt?: number;
104
106
  /** 正在运行的工具最新的一行进度,显示在对话的最后,工具结束时去掉 */
105
107
  progress: { id: string; line: string }[];
106
108
  queued: string[];
@@ -113,9 +115,8 @@ interface UiState {
113
115
  /** 对话最多保留这么多行(折行前),超出时丢掉最早的一段 */
114
116
  const MAX_LINES = 10_000;
115
117
 
116
- /** 按显示宽度折行,保留颜色;每一项是屏幕上的一行。制表符先换成空格:按 0 列算宽度会对不齐、超宽 */
117
- const wrap = (text: string, width: number) =>
118
- wrapAnsi(expandTabs(text), width, { hard: true, trim: false }).split("\n");
118
+ /** 按显示宽度折行,保留颜色;每一项是屏幕上的一行,自动折出来的续行开头带记号(markdown.ts),显示之前用 visibleRow 去掉 */
119
+ const wrap = wrapRows;
119
120
 
120
121
  /**
121
122
  * 对话里的一项:普通的一行,或者可以点击展开、收起的一段。
@@ -403,15 +404,52 @@ const CURSOR_RESET = "\x1b[0 q";
403
404
 
404
405
  /** 工作超过这么久后结束,或者这时弹出要用户选择的对话框,用户多半去做别的了:提醒一下 */
405
406
  const NOTIFY_AFTER = 10_000;
406
- /** 支持 OSC 9 桌面通知的终端;其他终端只响铃(不认识的 OSC 9 在有的终端里会弹别的东西) */
407
+ /** 支持 OSC 9 桌面通知的终端;其他终端什么都不发(不认识的 OSC 9 在有的终端里会弹别的东西) */
407
408
  const OSC9_TERMINALS = new Set(["iTerm.app", "WezTerm", "ghostty"]);
408
409
 
409
- /** 响铃,支持的终端再发一条桌面通知。JADE_NOTIFY=off 关闭 */
410
+ /**
411
+ * 支持的终端发一条桌面通知。不响铃:铃声在很多终端里(例如 Windows Terminal)是系统的错误提示音,听起来像出错了。
412
+ * JADE_NOTIFY=off 关闭
413
+ */
410
414
  function notifier(stdout: NodeJS.WriteStream, env = process.env): (message: string) => void {
411
- if (env.JADE_NOTIFY === "off") return () => {};
412
- const osc9 = OSC9_TERMINALS.has(env.TERM_PROGRAM ?? "");
413
- return (message) =>
414
- stdout.write(osc9 ? `\x1b]9;jade: ${message.replace(/[\x00-\x1f\x7f]/g, " ")}\x07` : "\x07");
415
+ if (env.JADE_NOTIFY === "off" || !OSC9_TERMINALS.has(env.TERM_PROGRAM ?? "")) return () => {};
416
+ return (message) => stdout.write(`\x1b]9;jade: ${message.replace(/[\x00-\x1f\x7f]/g, " ")}\x07`);
417
+ }
418
+
419
+ /** 终端标题里的控制字符换成空格,免得提前结束转义序列 */
420
+ const osc0 = (text: string) => `\x1b]0;${text.replace(/[\x00-\x1f\x7f]/g, " ")}\x07`;
421
+ /** 先把终端原来的标题存进标题栈(xterm 的 CSI 22 t),退出时取回;不支持的终端(如 Windows Terminal)退出时清空标题,回到默认 */
422
+ const TITLE_PUSH = "\x1b[22;0t";
423
+ const TITLE_POP = `${osc0("")}\x1b[23;0t`;
424
+
425
+ /**
426
+ * 让终端标签页标题跟着 jade 的状态走(见 mascot.ts 的 title):空闲时显示标志,运行中转圈,等用户时加感叹号。
427
+ * JADE_TITLE=off 关闭。返回关闭函数,会把标题还原
428
+ */
429
+ function titleBar(stdout: NodeJS.WriteStream, store: Store, env = process.env): () => void {
430
+ if (env.JADE_TITLE === "off") return () => {};
431
+ let shown = "";
432
+ const update = () => {
433
+ const s = store.state;
434
+ const now = Date.now();
435
+ const mood = moodOf({ busy: s.busy?.label, asking: s.dialogs.length > 0, doneAt: s.doneAt }, now);
436
+ const dir = s.status.cwd.split(/[\\/]/).filter(Boolean).at(-1) ?? s.status.cwd;
437
+ const text = title(mood, dir, now);
438
+ if (text === shown) return;
439
+ shown = text;
440
+ stdout.write(osc0(text));
441
+ };
442
+ stdout.write(TITLE_PUSH);
443
+ update();
444
+ const off = store.subscribe(update);
445
+ // 运行中转圈:状态不变时也要按时间换一帧
446
+ const timer = setInterval(() => store.state.busy && update(), 250);
447
+ timer.unref?.();
448
+ return () => {
449
+ off();
450
+ clearInterval(timer);
451
+ stdout.write(TITLE_POP);
452
+ };
415
453
  }
416
454
 
417
455
  export function tuiScreen(opts: TuiOptions): Screen {
@@ -494,33 +532,41 @@ export function tuiScreen(opts: TuiOptions): Screen {
494
532
 
495
533
  // 切到备用屏幕后光标还停在原来的位置(不少终端不会自动归位),Ink 从那里往下画第一帧会让屏幕滚动,
496
534
  // 之后每帧只重写变化的行,整个界面就错位了。所以先自己切过去、清屏、把光标移到左上角
497
- stdout.write("\x1b[?1049h\x1b[2J\x1b[H");
498
535
  const commands = opts.commands;
499
- const instance = render(
500
- h(App, {
501
- store,
502
- copy: (text: string) => void stdout.write(osc52(text)),
503
- version: opts.version,
504
- commands: typeof commands === "function" ? commands : () => commands,
505
- handlers: opts.handlers,
506
- history: opts.history ?? [],
507
- draft,
508
- }),
509
- {
510
- exitOnCtrlC: false,
511
- alternateScreen: true,
512
- // 全屏每帧只重写变化的行
513
- incrementalRendering: true,
514
- ...(opts.io
515
- ? { ...opts.io, interactive: true, patchConsole: false }
516
- : {}),
517
- },
518
- );
519
- stdout.write(MOUSE_ON + CURSOR_BLINK);
536
+ /** 接管终端、画界面。界面的内容都在 store 里,所以让出终端(suspend)之后可以再画一个新的 */
537
+ const mount = () => {
538
+ stdout.write("\x1b[?1049h\x1b[2J\x1b[H");
539
+ const mounted = render(
540
+ h(App, {
541
+ store,
542
+ copy: (text: string) => void stdout.write(osc52(text)),
543
+ version: opts.version,
544
+ commands: typeof commands === "function" ? commands : () => commands,
545
+ handlers: opts.handlers,
546
+ history: opts.history ?? [],
547
+ draft,
548
+ }),
549
+ {
550
+ exitOnCtrlC: false,
551
+ alternateScreen: true,
552
+ // 全屏每帧只重写变化的行
553
+ incrementalRendering: true,
554
+ ...(opts.io
555
+ ? { ...opts.io, interactive: true, patchConsole: false }
556
+ : {}),
557
+ },
558
+ );
559
+ stdout.write(MOUSE_ON + CURSOR_BLINK);
560
+ return mounted;
561
+ };
562
+ let instance = mount();
563
+ /** 让出终端一次只做一回,后来的排在后面 */
564
+ let yielding: Promise<unknown> = Promise.resolve();
565
+ const closeTitle = titleBar(stdout, store);
520
566
  // 没走 close 就退出(process.exit)时也要把终端还原,否则会留在备用屏幕、鼠标上报也开着
521
567
  const restore = () => {
522
568
  try {
523
- writeSync(1, `${MOUSE_OFF}${CURSOR_RESET}\x1b[?1049l\x1b[?25h`);
569
+ writeSync(1, `${MOUSE_OFF}${CURSOR_RESET}${TITLE_POP}\x1b[?1049l\x1b[?25h`);
524
570
  } catch {}
525
571
  };
526
572
  if (!opts.io) process.on("exit", restore);
@@ -589,7 +635,10 @@ export function tuiScreen(opts: TuiOptions): Screen {
589
635
  if (label === undefined) {
590
636
  // 稍等一下再提醒:排队的消息接着开始时(马上又 busy)不算结束
591
637
  if (longBusy()) doneTimer ??= setTimeout(() => notify("done"), 300);
592
- store.update({ busy: undefined });
638
+ store.update({
639
+ busy: undefined,
640
+ ...(current && current.label !== "Interrupting" ? { doneAt: Date.now() } : {}),
641
+ });
593
642
  return;
594
643
  }
595
644
  clearTimeout(doneTimer);
@@ -611,6 +660,29 @@ export function tuiScreen(opts: TuiOptions): Screen {
611
660
  },
612
661
  hint: (text) => store.update({ hint: text ? text.replace(/\r\n?/g, "\n") : undefined }),
613
662
  },
663
+ copy: (text) => void stdout.write(osc52(text)),
664
+ suspend<T>(fn: () => T | Promise<T>): Promise<T> {
665
+ const run = yielding.then(async () => {
666
+ // 输入框里打了一半的字在组件里,卸载就没了:先记下
667
+ const typed = draft.current?.get();
668
+ stdout.write(MOUSE_OFF + CURSOR_RESET);
669
+ // 卸载时 Ink 退出备用屏幕、关掉 raw mode、不再读 stdin:终端回到普通状态,别的程序可以用
670
+ instance.unmount();
671
+ await instance.waitUntilExit();
672
+ delete draft.current;
673
+ try {
674
+ return await fn();
675
+ } finally {
676
+ instance = mount();
677
+ // 等输入框画出来再返回:调用方接着就可能改输入框(编辑器里写好的内容)
678
+ const input = (): DraftBridge["current"] => draft.current;
679
+ for (let i = 0; i < 100 && !input(); i++) await new Promise((r) => setTimeout(r, 10));
680
+ if (typed) input()?.apply(() => ({ value: typed, cursor: typed.length }));
681
+ }
682
+ });
683
+ yielding = run.catch(() => {});
684
+ return run;
685
+ },
614
686
  select: <T>(title: string, choices: Choice<T>[], o?: { body?: string; signal?: AbortSignal }) => {
615
687
  if (longBusy()) notify(title);
616
688
  return ask<T | undefined>(
@@ -646,6 +718,7 @@ export function tuiScreen(opts: TuiOptions): Screen {
646
718
  store.update({ live: undefined, busy: undefined, progress: [] }, true);
647
719
  // 等最后一帧画完再卸载;卸载时 Ink 退出备用屏幕
648
720
  await new Promise((r) => setTimeout(r, 50));
721
+ closeTitle();
649
722
  stdout.write(MOUSE_OFF + CURSOR_RESET);
650
723
  instance.unmount();
651
724
  await instance.waitUntilExit();
@@ -736,17 +809,25 @@ function highlight(line: string, from: number, to: number): string {
736
809
  return out + (on ? INVERSE_OFF : "");
737
810
  }
738
811
 
739
- /** 选中的纯文字:每行去掉行尾空白,用换行连起来(自动折行的地方也是换行) */
740
- function selectedText(s: Selection, row: (i: number) => string | undefined): string {
812
+ /**
813
+ * 选中的纯文字:每行去掉行尾空白,用换行连起来。自动折行出来的续行接回上一行(补上折行时去掉的空格、
814
+ * 跳过排版加的缩进),所以一行很长的命令复制出来还是一行。row 给的是带续行记号的行
815
+ */
816
+ export function selectedText(s: Selection, row: (i: number) => string | undefined): string {
741
817
  const lines: string[] = [];
742
818
  const { anchor: a, focus: f } = s;
743
- for (let r = Math.min(a.row, f.row); r <= Math.max(a.row, f.row); r++) {
819
+ const first = Math.min(a.row, f.row);
820
+ for (let r = first; r <= Math.max(a.row, f.row); r++) {
744
821
  const [from, to] = selectedCols(s, r)!;
822
+ const { text: line, soft, gap, indent } = softInfo(row(r) ?? "");
745
823
  let text = "";
746
- walk(row(r) ?? "", from, to, (ch, inside) => void (inside && (text += ch)));
747
- lines.push(text.trimEnd());
824
+ // 续行开头的缩进、竖线是排版加的
825
+ walk(line, Math.max(from, soft ? indent : 0), to, (ch, inside) => void (inside && (text += ch)));
826
+ if (soft && r > first) lines[lines.length - 1] += " ".repeat(gap) + text;
827
+ // 代码块左边的竖线是排版加的,不是代码的一部分
828
+ else lines.push(text.replace(/^┃ ?/, ""));
748
829
  }
749
- return lines.join("\n");
830
+ return lines.map((l) => l.trimEnd()).join("\n");
750
831
  }
751
832
 
752
833
  /** OSC 52:让终端把文字放进系统剪贴板(Windows Terminal、iTerm2、kitty、WezTerm 等支持) */
@@ -787,16 +868,30 @@ function App({
787
868
  }) {
788
869
  const state = useSyncExternalStore(store.subscribe, store.get);
789
870
  const dialog = state.dialogs[0];
790
- // 运行中每 100ms 整体重画一次,推动转圈动画。不能让 Spinner 自己重画:
871
+ const { columns, rows } = useScreenSize();
872
+ const compact = rows < COMPACT_ROWS;
873
+ // 运行中每一帧(FRAME_MS)整体重画一次,推动转圈和吉祥物的动画。不能让 Spinner、吉祥物自己重画:
791
874
  // Ink 只在输入框也跟着提交的那一帧保留光标,否则把光标藏起来,运行中光标就不见了
792
- const [, tick] = useReducer((n: number) => n + 1, 0);
875
+ const [ticks, tick] = useReducer((n: number) => n + 1, 0);
793
876
  const busy = state.busy !== undefined;
794
877
  useEffect(() => {
795
878
  if (!busy) return;
796
- const t = setInterval(tick, 100);
879
+ const t = setInterval(tick, FRAME_MS);
797
880
  return () => clearInterval(t);
798
881
  }, [busy]);
799
- const { columns, rows } = useScreenSize();
882
+ const now = Date.now();
883
+ const mood = moodOf({ busy: state.busy?.label, asking: dialog !== undefined, doneAt: state.doneAt }, now);
884
+ const mascot = useRef<Mascot>(undefined);
885
+ mascot.current ??= new Mascot();
886
+ const showBot = !compact && columns >= 50;
887
+ const bot = showBot ? mascot.current.frame(mood, now) : undefined;
888
+ // 不在运行时吉祥物也会眨眼、瞟一眼、从上一个表情缓过来:只在它要动的时候按帧重画,其余时间不画
889
+ const moving = showBot && mascot.current.moving(mood, now);
890
+ useEffect(() => {
891
+ if (busy || !showBot) return;
892
+ const t = setTimeout(tick, nextChange(mood, Date.now(), state.doneAt, moving));
893
+ return () => clearTimeout(t);
894
+ }, [busy, showBot, ticks, mood, moving, state.doneAt]);
800
895
 
801
896
  // 对话区占掉标题和底部之外的全部高度,只画能看见的那几行
802
897
  const ref = useRef<DOMElement>(null);
@@ -843,8 +938,10 @@ function App({
843
938
  const [copied, setCopied] = useState<string>();
844
939
  const copiedTimer = useRef<ReturnType<typeof setTimeout>>(undefined);
845
940
  useEffect(() => () => clearTimeout(copiedTimer.current), []);
846
- const copySelection = (s: Selection) => {
847
- const text = selectedText(s, rowAt);
941
+ /** 输入框文字在屏幕上的位置(Prompt 里的 EditableText 每次渲染时写入) */
942
+ const inputPlace = useRef<Placement>(undefined);
943
+ const copySelection = (s: Selection) => copyText(selectedText(s, rowAt));
944
+ const copyText = (text: string) => {
848
945
  copy(text);
849
946
  clearTimeout(copiedTimer.current);
850
947
  setCopied(`Copied ${[...text].length} characters to the clipboard`);
@@ -884,6 +981,10 @@ function App({
884
981
  if (!clamp && (i < 0 || i >= shown.length)) return undefined;
885
982
  return { row: start + Math.min(Math.max(i, 0), shown.length - 1), col: Math.max(0, mouse.x - 1) };
886
983
  };
984
+ // 滚轮在放不下全部文字的输入框上(含上下边框)时由输入框自己翻
985
+ const input = inputPlace.current;
986
+ const overInput = input && input.total > input.rows && mouse.y >= input.y - 1 && mouse.y <= input.y + input.rows;
987
+ if ((mouse.button === 64 || mouse.button === 65) && overInput) return;
887
988
  if (mouse.button === 64) store.scrollBy(WHEEL_LINES, max);
888
989
  else if (mouse.button === 65) store.scrollBy(-WHEEL_LINES, max);
889
990
  else if (mouse.button === 0 && mouse.press) {
@@ -933,7 +1034,7 @@ function App({
933
1034
  h(
934
1035
  Box,
935
1036
  { flexDirection: "column", flexGrow: 1, overflowY: "hidden" },
936
- h(Header, { status: state.status, version, compact: rows < COMPACT_ROWS }),
1037
+ h(Header, { status: state.status, version, compact, bot }),
937
1038
  h(
938
1039
  Box,
939
1040
  {
@@ -945,7 +1046,9 @@ function App({
945
1046
  overflowY: "hidden",
946
1047
  paddingX: 1,
947
1048
  },
948
- shown.map((l, i) => {
1049
+ shown.map((raw, i) => {
1050
+ // 续行的记号不显示
1051
+ const l = visibleRow(raw);
949
1052
  const cols = selection && selectedCols(selection, start + i);
950
1053
  return h(Text, { key: i, wrap: "truncate-end" }, cols ? highlight(l || " ", ...cols) : l || " ");
951
1054
  }),
@@ -981,6 +1084,8 @@ function App({
981
1084
  active: !dialog,
982
1085
  onSubmit: () => store.scrollBy(-max, max),
983
1086
  flash: copied,
1087
+ place: inputPlace,
1088
+ onCopy: copyText,
984
1089
  }),
985
1090
  h(StatusBar, { status: state.status, width: Math.max(10, columns - 2) }),
986
1091
  ),
@@ -989,20 +1094,20 @@ function App({
989
1094
  );
990
1095
  }
991
1096
 
992
- const JADE = "#00a86b";
993
- const SHINE = "#b6f2d4";
994
-
995
1097
  /**
996
- * 标题左边的吉祥物:一个玉做的团子,用半格字符画的像素图,三行高,正好和右边三行文字并排。
997
- * 每个字符上下两个像素;眼睛是玉上挖空的两格,左上角一点高光让它看起来像玉
1098
+ * 标题左边的吉祥物(见 mascot.ts):玉做的团子,按 mood 换表情和动画,三行高,正好和右边三行文字并排
998
1099
  */
999
- function Bot() {
1100
+ function Bot({ pixels }: { pixels: (string | undefined)[][] }) {
1000
1101
  return h(
1001
1102
  Box,
1002
- { flexDirection: "column", flexShrink: 0, marginRight: 2 },
1003
- h(Text, { color: JADE }, " ▄", h(Text, { color: SHINE, backgroundColor: JADE }, "▄"), "████▄"),
1004
- h(Text, { color: JADE }, "██ ███ ██"),
1005
- h(Text, { color: JADE }, "▀███████▀"),
1103
+ { flexDirection: "column", flexShrink: 0, marginRight: 1 },
1104
+ ...cells(pixels).map((row, i) =>
1105
+ h(
1106
+ Text,
1107
+ { key: i },
1108
+ ...row.map((r, j) => h(Text, { key: j, color: r.fg, backgroundColor: r.bg }, r.text)),
1109
+ ),
1110
+ ),
1006
1111
  );
1007
1112
  }
1008
1113
 
@@ -1010,13 +1115,15 @@ function Header({
1010
1115
  status,
1011
1116
  version,
1012
1117
  compact,
1118
+ bot,
1013
1119
  }: {
1014
1120
  status: StatusInfo;
1015
1121
  version: string;
1122
+ /** 吉祥物这一帧的像素(见 mascot.ts);放不下时 undefined */
1123
+ bot?: (string | undefined)[][];
1016
1124
  /** 终端很矮时只占一行,把高度留给对话和输入框 */
1017
1125
  compact: boolean;
1018
1126
  }) {
1019
- const { columns } = useScreenSize();
1020
1127
  // 模型 · 目录 (分支)
1021
1128
  const where = [
1022
1129
  h(Text, { key: "model", color: "cyan" }, status.model),
@@ -1034,7 +1141,7 @@ function Header({
1034
1141
  return h(
1035
1142
  Box,
1036
1143
  { flexShrink: 0, borderStyle: "round", borderColor: "cyan", paddingX: 1 },
1037
- columns >= 50 ? h(Bot) : null,
1144
+ bot ? h(Bot, { pixels: bot }) : null,
1038
1145
  h(
1039
1146
  Box,
1040
1147
  { flexDirection: "column", flexGrow: 1, flexShrink: 1 },
@@ -1254,8 +1361,19 @@ function editKey(s: EditState, input: string, key: Key): EditState | undefined {
1254
1361
  return text ? edit.insert(s, text) : undefined;
1255
1362
  }
1256
1363
 
1257
- /** 可编辑文本在屏幕上的位置:第一个字符的列 x、第一行可见行的行 y、可见的是折行后的第 first 行起的 rows 行 */
1258
- type Placement = { x: number; y: number; first: number; rows: number } | undefined;
1364
+ /**
1365
+ * 可编辑文本在屏幕上的位置:第一个字符的列 x、第一行可见行的行 y、可见的是折行后的第 first 行起的 rows 行,
1366
+ * 折行后一共 total 行
1367
+ */
1368
+ type Placement = { x: number; y: number; first: number; rows: number; total: number } | undefined;
1369
+
1370
+ /** 一行文字里下标 [from, to)(相对这一行)反色显示,和对话区的选中一样 */
1371
+ function inverseRange(row: string, from: number, to: number): string {
1372
+ from = Math.max(0, Math.min(row.length, from));
1373
+ to = Math.max(from, Math.min(row.length, to));
1374
+ if (from === to) return row;
1375
+ return `${row.slice(0, from)}${INVERSE}${row.slice(from, to)}${INVERSE_OFF}${row.slice(to)}`;
1376
+ }
1259
1377
 
1260
1378
  /** 渲染可编辑文本并把终端光标放到输入位置(输入法的候选框跟着它) */
1261
1379
  function EditableText({
@@ -1267,9 +1385,15 @@ function EditableText({
1267
1385
  active,
1268
1386
  maxRows = Infinity,
1269
1387
  place,
1388
+ top,
1389
+ selected,
1270
1390
  }: {
1271
1391
  /** 每次渲染时写入文字的位置,点击换算光标用 */
1272
1392
  place?: { current: Placement };
1393
+ /** 用滚轮翻到的第一行可见行;undefined 时跟着光标 */
1394
+ top?: number;
1395
+ /** 选中的文字:value 里的下标 [from, to) */
1396
+ selected?: [number, number];
1273
1397
  state: EditState;
1274
1398
  width: number;
1275
1399
  prefix: string;
@@ -1288,13 +1412,15 @@ function EditableText({
1288
1412
  : state.cursor;
1289
1413
  const all = layout(shown, cursor, width - prefix.length);
1290
1414
  const { col } = all;
1291
- // 行数超过 maxRows 时滚动,光标所在的行总在可见范围里
1292
- const first = Math.max(
1293
- 0,
1294
- Math.min(all.row - maxRows + 1, all.rows.length - maxRows),
1295
- );
1415
+ // 行数超过 maxRows 时滚动:平时光标所在的行总在可见范围里,用滚轮翻过时停在翻到的地方(光标可能不在里面)
1416
+ const last = Math.max(0, all.rows.length - maxRows);
1417
+ const first =
1418
+ top === undefined
1419
+ ? Math.max(0, Math.min(all.row - maxRows + 1, last))
1420
+ : Math.max(0, Math.min(top, last));
1296
1421
  const rows = all.rows.slice(first, first + maxRows);
1297
1422
  const row = all.row - first;
1423
+ const cursorShown = row >= 0 && row < rows.length;
1298
1424
 
1299
1425
  // 光标位置要在渲染时设:useCursor 在这次提交时交给 Ink,跟这一帧一起画出来。
1300
1426
  // 放在 useEffect 里会晚一帧,光标总是停在上一次按键的位置(只移动光标时最明显)。
@@ -1306,8 +1432,8 @@ function EditableText({
1306
1432
  active && metrics.hasMeasured && ref.current
1307
1433
  ? origin(ref.current)
1308
1434
  : undefined;
1309
- const position = at && { x: at.x + prefix.length + col, y: at.y + row };
1310
- if (place) place.current = at && { x: at.x + prefix.length, y: at.y, first, rows: rows.length };
1435
+ const position = at && cursorShown ? { x: at.x + prefix.length + col, y: at.y + row } : undefined;
1436
+ if (place) place.current = at && { x: at.x + prefix.length, y: at.y, first, rows: rows.length, total: all.rows.length };
1311
1437
  const [, recheck] = useReducer((n: number) => n + 1, 0);
1312
1438
  useEffect(() => {
1313
1439
  if (!at || !ref.current) return;
@@ -1328,9 +1454,15 @@ function EditableText({
1328
1454
  h(
1329
1455
  Text,
1330
1456
  { color: "cyan" },
1331
- first + i === 0 ? prefix : i === 0 ? "↑".padEnd(prefix.length) : " ".repeat(prefix.length),
1457
+ first + i === 0
1458
+ ? prefix
1459
+ : i === 0
1460
+ ? "↑".padEnd(prefix.length)
1461
+ : i === rows.length - 1 && first + rows.length < all.rows.length
1462
+ ? "↓".padEnd(prefix.length)
1463
+ : " ".repeat(prefix.length),
1332
1464
  ),
1333
- r,
1465
+ selected && !mask ? inverseRange(r, selected[0] - all.starts[first + i]!, selected[1] - all.starts[first + i]!) : r,
1334
1466
  ),
1335
1467
  ),
1336
1468
  );
@@ -1369,7 +1501,13 @@ function Prompt({
1369
1501
  active,
1370
1502
  onSubmit,
1371
1503
  flash,
1504
+ place,
1505
+ onCopy,
1372
1506
  }: {
1507
+ /** 输入框文字在屏幕上的位置(见 EditableText 的 place);App 用它判断滚轮是不是在输入框上 */
1508
+ place: { current: Placement };
1509
+ /** 在输入框里拖动选中了文字:复制它 */
1510
+ onCopy(text: string): void;
1373
1511
  /** 当前的命令(随会话的插件增减),每次算菜单时取 */
1374
1512
  commands: () => CommandInfo[];
1375
1513
  handlers: TuiHandlers;
@@ -1378,7 +1516,7 @@ function Prompt({
1378
1516
  bridge: DraftBridge;
1379
1517
  /** 插件设置的灰色提示 */
1380
1518
  hint?: string;
1381
- /** 提示被接受了,或者用户开始打字了:去掉它 */
1519
+ /** 提示随消息发出去了:去掉它 */
1382
1520
  onHintDone(): void;
1383
1521
  busy: boolean;
1384
1522
  /** 有排队等待发送的消息 */
@@ -1399,8 +1537,12 @@ function Prompt({
1399
1537
  const draft = useRef("");
1400
1538
  const lastCtrlC = useRef(0);
1401
1539
  const lastEsc = useRef(0);
1402
- /** 输入框文字在屏幕上的位置,点击时换算光标位置用(见 EditableText 的 place) */
1403
- const place = useRef<Placement>(undefined);
1540
+ /**
1541
+ * 用滚轮翻过输入框时翻到的第一行可见行。只对翻的时候的那份文字和光标有效:打字、移动光标后又跟着光标
1542
+ */
1543
+ const scrolled = useRef<{ top: number; value: string; cursor: number }>(undefined);
1544
+ /** 在输入框里按住左键拖动选中的文字:anchor 是按下的位置,focus 是拖到的位置(value 里的下标);文字改了就作废 */
1545
+ const [getDrag, setDrag] = useLive<{ anchor: number; focus: number; value: string } | undefined>(undefined);
1404
1546
  const { columns, rows } = useScreenSize();
1405
1547
  /** 输入框里文字的宽度:边框、内边距和前面的 "› " 之外 */
1406
1548
  const textWidth = Math.max(10, columns - 5) - 2;
@@ -1499,8 +1641,7 @@ function Prompt({
1499
1641
  /** 提示只在空闲、输入框为空、没有在搜索历史时显示,也只有这时能接受 */
1500
1642
  const hinting = () => hint !== undefined && !busy && current().value === "" && !getSearch();
1501
1643
  const set = (s: EditState) => {
1502
- // 用户开始打字(或者插件改了输入框):提示作废
1503
- if (s.value && hint !== undefined) onHintDone();
1644
+ // 打字时提示只是不显示(hinting() 要求输入框为空),删回空的又出现;发出去才作废
1504
1645
  setState(s);
1505
1646
  setSelected(0);
1506
1647
  setNotice(undefined);
@@ -1515,8 +1656,11 @@ function Prompt({
1515
1656
  };
1516
1657
  const submit = (text: string) => {
1517
1658
  if (!text.trim()) return;
1659
+ if (hint !== undefined) onHintDone();
1518
1660
  remember(text);
1519
1661
  set(empty);
1662
+ // 发出去之后弹出的对话框是用户自己要的(/mode、/model),马上就能回答
1663
+ typedAt = 0;
1520
1664
  onSubmit();
1521
1665
  handlers.submit(text);
1522
1666
  };
@@ -1599,12 +1743,60 @@ function Prompt({
1599
1743
  const search = getSearch();
1600
1744
  if (search) return searchKey(search, input, key);
1601
1745
  const state = current();
1746
+ // 输入框里的鼠标:点击移动光标,按住拖动选中、松开时复制,滚轮翻看放不下的文字
1747
+ const mouse = mouseEvent(input);
1748
+ if (mouse) {
1749
+ const at = place.current;
1750
+ if (!at) return;
1751
+ const row = mouse.y - at.y;
1752
+ // 拖出输入框时停在第一行或最后一行
1753
+ const offset = (r: number) => offsetAt(state.value, textWidth, at.first + Math.max(0, Math.min(at.rows - 1, r)), mouse.x - at.x);
1754
+ // 滚轮:上下边框也算在输入框上
1755
+ if ((mouse.button === 64 || mouse.button === 65) && row >= -1 && row <= at.rows && at.total > at.rows) {
1756
+ const top = Math.max(0, Math.min(at.total - at.rows, at.first + (mouse.button === 64 ? -WHEEL_LINES : WHEEL_LINES)));
1757
+ scrolled.current = { top, value: state.value, cursor: state.cursor };
1758
+ return setState({ ...state });
1759
+ }
1760
+ if (mouse.button === 0 && mouse.press) {
1761
+ if (row < 0 || row >= at.rows) return setDrag(undefined);
1762
+ const cursor = offset(row);
1763
+ if (cursor === undefined) return;
1764
+ setDrag({ anchor: cursor, focus: cursor, value: state.value });
1765
+ // 点在翻过的地方时保持翻到的位置
1766
+ if (scrolled.current) scrolled.current = { ...scrolled.current, cursor };
1767
+ return setState({ ...state, cursor });
1768
+ }
1769
+ const drag = getDrag();
1770
+ if (!drag || drag.value !== state.value) return;
1771
+ if (mouse.button === DRAG) {
1772
+ const focus = offset(row);
1773
+ if (focus === undefined) return;
1774
+ setDrag({ ...drag, focus });
1775
+ if (scrolled.current) scrolled.current = { ...scrolled.current, cursor: focus };
1776
+ return setState({ ...state, cursor: focus });
1777
+ }
1778
+ if (mouse.button === 0 && !mouse.press && drag.anchor !== drag.focus) {
1779
+ onCopy(state.value.slice(Math.min(drag.anchor, drag.focus), Math.max(drag.anchor, drag.focus)));
1780
+ }
1781
+ return;
1782
+ }
1783
+ // 别的键取消输入框里的选中;Ctrl+C 只取消选中(已经在松开时复制过了)
1784
+ const drag = getDrag();
1785
+ if (drag) {
1786
+ setDrag(undefined);
1787
+ if (key.ctrl && input === "c" && drag.anchor !== drag.focus && drag.value === state.value) return;
1788
+ }
1602
1789
  if (key.ctrl && input === "r")
1603
1790
  return history.current.length
1604
1791
  ? setSearch({ query: "", index: 0 })
1605
1792
  : undefined;
1606
1793
  if (key.ctrl && input === "c") {
1607
- if (busy) return handlers.interrupt();
1794
+ if (busy) {
1795
+ // 第一下中断;停不下来时(卡在 Interrupting)再按一下也能退出
1796
+ if (Date.now() - lastCtrlC.current < 2000) return handlers.exit();
1797
+ lastCtrlC.current = Date.now();
1798
+ return handlers.interrupt();
1799
+ }
1608
1800
  if (state.value) return discard();
1609
1801
  if (Date.now() - lastCtrlC.current < 2000) return handlers.exit();
1610
1802
  lastCtrlC.current = Date.now();
@@ -1619,17 +1811,6 @@ function Prompt({
1619
1811
  lastEsc.current = Date.now();
1620
1812
  return;
1621
1813
  }
1622
- // 点击输入框里的文字:光标移到点的位置
1623
- const mouse = mouseEvent(input);
1624
- if (mouse) {
1625
- const at = place.current;
1626
- if (!at || mouse.button !== 0 || !mouse.press) return;
1627
- const row = mouse.y - at.y;
1628
- if (row < 0 || row >= at.rows) return;
1629
- const cursor = offsetAt(state.value, textWidth, at.first + row, mouse.x - at.x);
1630
- if (cursor !== undefined) setState({ ...state, cursor });
1631
- return;
1632
- }
1633
1814
  // 文字和回车在同一块里到达(输入很快时终端可能合并):插入文字后发送
1634
1815
  if (
1635
1816
  !key.ctrl &&
@@ -1640,8 +1821,9 @@ function Prompt({
1640
1821
  return submit(edit.insert(state, input.slice(0, -1)).value.trim());
1641
1822
  }
1642
1823
  if (key.return) {
1643
- // 行尾的 \ 加回车换行;Alt+Enter 也换行
1644
- if (key.meta) return set(edit.insert(state, "\n"));
1824
+ // 行尾的 \ 加回车换行;Alt+Enter 也换行;终端把 Shift+Enter 单独报上来时(kitty 键盘协议、modifyOtherKeys)也换行。
1825
+ // Ctrl+J(Windows Terminal 里 Ctrl+Enter 也是它)发的是 LF,不算回车,在 editKey 里当普通换行插入
1826
+ if (key.meta || key.shift) return set(edit.insert(state, "\n"));
1645
1827
  if (state.value.slice(0, state.cursor).endsWith("\\"))
1646
1828
  return set(edit.insert(edit.backspace(state), "\n"));
1647
1829
  const { pick, file } = derive();
@@ -1652,7 +1834,6 @@ function Prompt({
1652
1834
  }
1653
1835
  // Tab 或 →:把提示变成输入框里的文字,接着可以改
1654
1836
  if (((key.tab && !key.shift) || key.rightArrow) && hinting()) {
1655
- onHintDone();
1656
1837
  browsing.current = -1;
1657
1838
  return set({ value: hint!, cursor: hint!.length });
1658
1839
  }
@@ -1695,18 +1876,32 @@ function Prompt({
1695
1876
  const spec = keySpec(input, key);
1696
1877
  if (spec && handlers.key?.(spec)) return;
1697
1878
  const next = editKey(state, input, key);
1698
- if (next) set(next);
1879
+ if (next) {
1880
+ if (next.value !== state.value) typedAt = Date.now();
1881
+ set(next);
1882
+ }
1699
1883
  },
1700
1884
  { isActive: active },
1701
1885
  );
1702
1886
 
1887
+ const view = scrolled.current;
1888
+ const viewTop = view && view.value === state.value && view.cursor === state.cursor ? view.top : undefined;
1889
+ const drag = getDrag();
1890
+ const dragged: [number, number] | undefined =
1891
+ drag && drag.value === state.value && drag.anchor !== drag.focus
1892
+ ? [Math.min(drag.anchor, drag.focus), Math.max(drag.anchor, drag.focus)]
1893
+ : undefined;
1894
+
1895
+ // ! 开头:这一行是用户自己执行的 shell 命令(/sh),边框换个颜色、上边框的右边写一行说明
1896
+ const bang = !search && state.value.startsWith("!");
1897
+
1703
1898
  // 对话框打开时隐藏但不卸载,输入到一半的内容和历史都保留
1704
1899
  return h(
1705
1900
  Box,
1706
1901
  { flexDirection: "column", marginTop: 1, display: active ? "flex" : "none" },
1707
1902
  h(
1708
1903
  Box,
1709
- { borderStyle: "round", borderColor: busy ? "gray" : "cyan", paddingX: 1 },
1904
+ { borderStyle: "round", borderColor: bang ? "magenta" : busy ? "gray" : "cyan", paddingX: 1 },
1710
1905
  search
1711
1906
  ? h(EditableText, {
1712
1907
  state: { value: search.query, cursor: search.query.length },
@@ -1732,6 +1927,8 @@ function Prompt({
1732
1927
  active,
1733
1928
  maxRows: inputRows,
1734
1929
  place,
1930
+ top: viewTop,
1931
+ selected: dragged,
1735
1932
  }),
1736
1933
  ),
1737
1934
  search
@@ -1801,7 +1998,16 @@ function Prompt({
1801
1998
  ? h(Text, { color: "yellow" }, ` ${notice}`)
1802
1999
  : null,
1803
2000
  // 压在输入框上边框的右边,不占行,出现和消失时下面的内容不跳
1804
- flash ? h(Box, { position: "absolute", top: 0, right: 2 }, h(Text, { color: "green" }, ` ${flash} `)) : null,
2001
+ // ! 开头时同一个位置写这一行是什么(刚复制的提示优先)
2002
+ flash
2003
+ ? h(Box, { position: "absolute", top: 0, right: 2 }, h(Text, { color: "green" }, ` ${flash} `))
2004
+ : bang
2005
+ ? h(
2006
+ Box,
2007
+ { position: "absolute", top: 0, right: 2 },
2008
+ 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 "),
2009
+ )
2010
+ : null,
1805
2011
  );
1806
2012
  }
1807
2013
 
@@ -1819,6 +2025,25 @@ function around(selected: number, total: number, size: number): number {
1819
2025
  return Math.max(0, Math.min(selected - Math.floor(size / 2), total - size));
1820
2026
  }
1821
2027
 
2028
+ /** 用户上一次在输入框里打字的时间;发送之后清零 */
2029
+ let typedAt = 0;
2030
+ /** 打字停下这么久之后,对话框才把回车和字符当成回答 */
2031
+ const TYPING_GRACE = 500;
2032
+
2033
+ /**
2034
+ * 对话框弹出时用户正在输入框里打字(例如在排下一条消息时弹出审批):接着打出来的回车、数字不能当成回答。
2035
+ * 返回 true 表示这个键要丢掉。方向键、Esc 说明用户已经看到对话框了,不再拦
2036
+ */
2037
+ function typedThrough(input: string, key: Key): boolean {
2038
+ if (Date.now() - typedAt >= TYPING_GRACE) return false;
2039
+ if (key.escape || key.upArrow || key.downArrow || key.pageUp || key.pageDown || (key.ctrl && input === "c") || MOUSE.test(input)) {
2040
+ typedAt = 0;
2041
+ return false;
2042
+ }
2043
+ typedAt = Date.now();
2044
+ return true;
2045
+ }
2046
+
1822
2047
  /** 选择框一次最多显示几项 */
1823
2048
  const VISIBLE = 10;
1824
2049
  /** 选项多于这么多时可以打字筛选(这时 j/k 和数字键不再是快捷键) */
@@ -1832,6 +2057,9 @@ function SelectDialog({
1832
2057
  const selection = useContext(SelectionContext);
1833
2058
  const [getSelected, setSelected] = useLive(0);
1834
2059
  const [getQuery, setQuery] = useLive("");
2060
+ /** 预览从第几行开始显示,以及它能翻到哪里、一页几行(放得下时 maxTop 是 0) */
2061
+ const [getTop, setTop] = useLive(0);
2062
+ const scrolling = useRef({ maxTop: 0, page: 1 });
1835
2063
  const { rows, columns } = useScreenSize();
1836
2064
  const filtering = dialog.choices.length > FILTER_FROM;
1837
2065
  const query = getQuery();
@@ -1849,14 +2077,27 @@ function SelectDialog({
1849
2077
  const visible = roomFor(rows, VISIBLE);
1850
2078
  // 预览(例如要写入的文件)过长时截断:整个界面高过终端时 Ink 会每帧清屏重画,底部的选项和提示也会被裁掉。
1851
2079
  // 按折行后的屏幕行数截断(一行长代码会占好几行),每一行单独显示、不再折行
1852
- const lines = !dialog.body ? [] : wrap(dialog.body, Math.max(1, columns - 4));
2080
+ const lines = !dialog.body ? [] : wrap(dialog.body, Math.max(1, columns - 4)).map(visibleRow);
1853
2081
  const room = Math.max(3, rows - Math.min(n, visible) - 16);
2082
+ // 放不下时 PgUp/PgDn 翻看预览(批准之前要能看完整个 diff),最后一行说明还有多少
2083
+ const page = room - 1;
2084
+ const maxTop = Math.max(0, lines.length - page);
2085
+ const top = Math.min(getTop(), maxTop);
2086
+ scrolling.current = { maxTop, page };
1854
2087
  const body =
1855
2088
  lines.length > room
1856
- ? [...lines.slice(0, room - 1), dim(`… ${lines.length - room + 1} more lines`)]
2089
+ ? [
2090
+ ...lines.slice(top, top + page),
2091
+ dim(
2092
+ top < maxTop
2093
+ ? `… ${lines.length - top - page} more lines · PgDn/PgUp to scroll`
2094
+ : `end of ${lines.length} lines · PgUp to scroll back`,
2095
+ ),
2096
+ ]
1857
2097
  : lines;
1858
2098
  useInput((input, key) => {
1859
2099
  if (key.ctrl && input === "c" && selection.active()) return selection.clear();
2100
+ if (typedThrough(input, key)) return;
1860
2101
  const items = filtered();
1861
2102
  const n = items.length;
1862
2103
  const selected = Math.min(getSelected(), Math.max(0, n - 1));
@@ -1874,6 +2115,11 @@ function SelectDialog({
1874
2115
  }
1875
2116
  if (key.escape || (key.ctrl && input === "c"))
1876
2117
  return dialog.resolve(undefined);
2118
+ // 预览放不下时翻预览,否则翻选项
2119
+ const { maxTop, page } = scrolling.current;
2120
+ if (maxTop > 0 && (key.pageDown || key.pageUp)) {
2121
+ return setTop(Math.max(0, Math.min(maxTop, Math.min(getTop(), maxTop) + (key.pageDown ? page : -page))));
2122
+ }
1877
2123
  if (key.pageDown) return setSelected(Math.min(n - 1, selected + visible));
1878
2124
  if (key.pageUp) return setSelected(Math.max(0, selected - visible));
1879
2125
  if (filtering) {
@@ -1951,6 +2197,7 @@ function InputDialog({
1951
2197
  );
1952
2198
  useInput((input, key) => {
1953
2199
  if (key.ctrl && input === "c" && selection.active()) return selection.clear();
2200
+ if (typedThrough(input, key)) return;
1954
2201
  const state = current();
1955
2202
  if (key.return) return dialog.resolve(state.value.trim());
1956
2203
  if (key.escape || (key.ctrl && input === "c"))