@uncarved/jade 0.3.1 → 0.4.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 (206) hide show
  1. package/README.md +1 -0
  2. package/dist/api.d.ts +1 -1
  3. package/dist/api.js +1 -1
  4. package/dist/host.d.ts +2 -0
  5. package/dist/host.js +39 -5
  6. package/dist/host.js.map +1 -1
  7. package/dist/remote.js +5 -0
  8. package/dist/remote.js.map +1 -1
  9. package/dist/session.d.ts +7 -0
  10. package/dist/session.js +490 -29
  11. package/dist/session.js.map +1 -1
  12. package/package.json +4 -4
  13. package/plugins/approval/index.ts +36 -14
  14. package/plugins/approval/policy.ts +15 -10
  15. package/plugins/approval/review.ts +9 -5
  16. package/plugins/checks/checks.ts +10 -7
  17. package/plugins/checks/index.ts +13 -13
  18. package/plugins/checks/plugin.json +1 -1
  19. package/plugins/checks/project.ts +37 -38
  20. package/plugins/commands/index.ts +27 -3
  21. package/plugins/compact/compact.ts +13 -5
  22. package/plugins/compact/index.ts +20 -3
  23. package/plugins/compact/style.ts +13 -14
  24. package/plugins/completions/index.ts +35 -0
  25. package/plugins/completions/plugin.json +7 -0
  26. package/plugins/copy/index.ts +46 -0
  27. package/plugins/copy/plugin.json +7 -0
  28. package/plugins/editor/index.ts +10 -4
  29. package/plugins/fs/diff.ts +7 -6
  30. package/plugins/fs/fs.ts +8 -4
  31. package/plugins/fs/grep.ts +42 -9
  32. package/plugins/fs/index.ts +2 -7
  33. package/plugins/fs/plugin.json +1 -1
  34. package/plugins/fs/renderers.ts +16 -15
  35. package/plugins/fs/style.ts +16 -15
  36. package/plugins/hooks/index.ts +3 -2
  37. package/plugins/keys/index.ts +5 -1
  38. package/plugins/mcp/index.ts +197 -78
  39. package/plugins/mcp/install.ts +5 -3
  40. package/plugins/mcp/mcp.ts +163 -11
  41. package/plugins/mcp/plugin.json +2 -1
  42. package/plugins/mcp/project.ts +47 -50
  43. package/plugins/memory/index.ts +4 -4
  44. package/plugins/memory/style.ts +13 -14
  45. package/plugins/mentions/candidates.ts +67 -0
  46. package/plugins/mentions/index.ts +12 -5
  47. package/plugins/mentions/plugin.json +1 -1
  48. package/plugins/mentions/style.ts +13 -14
  49. package/plugins/models/configure.ts +47 -12
  50. package/plugins/models/index.ts +27 -1
  51. package/plugins/models/provider.ts +24 -0
  52. package/plugins/models/saved.ts +1 -1
  53. package/plugins/modes/index.ts +13 -2
  54. package/plugins/print/index.ts +7 -4
  55. package/plugins/prompts/index.ts +0 -0
  56. package/plugins/renderers/index.ts +10 -5
  57. package/plugins/repeats/index.ts +8 -8
  58. package/plugins/schedule/index.ts +5 -1
  59. package/plugins/screenshot/browser.ts +10 -0
  60. package/plugins/sessions/index.ts +48 -2
  61. package/plugins/shell/index.ts +27 -28
  62. package/plugins/shell/plugin.json +1 -1
  63. package/plugins/shell/renderers.ts +9 -7
  64. package/plugins/shell/shell.ts +3 -1
  65. package/plugins/skills/index.ts +28 -19
  66. package/plugins/skills/project.ts +12 -7
  67. package/plugins/steer/index.ts +5 -4
  68. package/plugins/task/index.ts +80 -50
  69. package/plugins/task/plugin.json +6 -2
  70. package/plugins/task/style.ts +13 -14
  71. package/plugins/task/subagent.ts +67 -184
  72. package/plugins/todo/index.ts +39 -9
  73. package/plugins/tools/index.ts +9 -2
  74. package/plugins/tui/frontend.ts +139 -89
  75. package/plugins/tui/index.ts +2 -3
  76. package/plugins/tui/mentions.ts +11 -80
  77. package/plugins/tui/plugin.json +1 -1
  78. package/plugins/tui/screen.ts +55 -5
  79. package/plugins/tui/transcript.ts +17 -7
  80. package/plugins/tui/tui.ts +337 -101
  81. package/plugins/tui/vendor.ts +1 -1
  82. package/plugins/undo/checkpoint.ts +8 -4
  83. package/plugins/undo/index.ts +170 -31
  84. package/plugins/undo/plugin.json +1 -0
  85. package/plugins/undo/snapshot.ts +87 -14
  86. package/plugins/undo/style.ts +13 -14
  87. package/plugins/web/index.ts +7 -18
  88. package/plugins/web/plugin.json +1 -1
  89. package/plugins-dist/approval/index.js +363 -418
  90. package/plugins-dist/approval/policy.js +391 -508
  91. package/plugins-dist/approval/review.js +132 -158
  92. package/plugins-dist/approval/schema.js +50 -55
  93. package/plugins-dist/ask/index.js +115 -129
  94. package/plugins-dist/budget/index.js +27 -31
  95. package/plugins-dist/checks/checks.js +293 -329
  96. package/plugins-dist/checks/index.js +119 -139
  97. package/plugins-dist/checks/plugin.json +2 -1
  98. package/plugins-dist/checks/project.js +57 -65
  99. package/plugins-dist/commands/index.js +47 -29
  100. package/plugins-dist/compact/compact.js +233 -249
  101. package/plugins-dist/compact/index.js +98 -95
  102. package/plugins-dist/compact/style.js +9 -14
  103. package/plugins-dist/completions/index.js +30 -0
  104. package/plugins-dist/completions/plugin.json +9 -0
  105. package/plugins-dist/continue/index.js +40 -52
  106. package/plugins-dist/copy/index.js +40 -0
  107. package/plugins-dist/copy/plugin.json +9 -0
  108. package/plugins-dist/cost/index.js +98 -115
  109. package/plugins-dist/custom-commands/index.js +55 -72
  110. package/plugins-dist/editor/index.js +64 -72
  111. package/plugins-dist/fs/diff.js +111 -124
  112. package/plugins-dist/fs/fs.js +426 -469
  113. package/plugins-dist/fs/grep.js +262 -253
  114. package/plugins-dist/fs/index.js +20 -34
  115. package/plugins-dist/fs/plugin.json +1 -2
  116. package/plugins-dist/fs/renderers.js +100 -112
  117. package/plugins-dist/fs/style.js +11 -15
  118. package/plugins-dist/fs/sys.js +31 -43
  119. package/plugins-dist/hooks/index.js +107 -127
  120. package/plugins-dist/keys/index.js +27 -31
  121. package/plugins-dist/mcp/index.js +271 -199
  122. package/plugins-dist/mcp/install.js +123 -137
  123. package/plugins-dist/mcp/mcp.js +638 -577
  124. package/plugins-dist/mcp/plugin.json +3 -1
  125. package/plugins-dist/mcp/project.js +98 -115
  126. package/plugins-dist/memory/index.js +83 -88
  127. package/plugins-dist/memory/memory.js +111 -128
  128. package/plugins-dist/memory/style.js +9 -14
  129. package/plugins-dist/mentions/attach.js +91 -99
  130. package/plugins-dist/mentions/candidates.js +49 -0
  131. package/plugins-dist/mentions/index.js +71 -81
  132. package/plugins-dist/mentions/plugin.json +2 -1
  133. package/plugins-dist/mentions/style.js +9 -14
  134. package/plugins-dist/models/config.js +29 -43
  135. package/plugins-dist/models/configure.js +421 -474
  136. package/plugins-dist/models/context.js +14 -22
  137. package/plugins-dist/models/index.js +182 -189
  138. package/plugins-dist/models/provider.js +263 -307
  139. package/plugins-dist/models/saved.js +60 -72
  140. package/plugins-dist/modes/index.js +138 -165
  141. package/plugins-dist/plugins/index.js +34 -34
  142. package/plugins-dist/print/index.js +192 -175
  143. package/plugins-dist/prompts/index.js +86 -89
  144. package/plugins-dist/prompts/notes.js +31 -37
  145. package/plugins-dist/prompts/prompts.js +155 -193
  146. package/plugins-dist/prompts/results.js +40 -53
  147. package/plugins-dist/prompts/sys.js +39 -50
  148. package/plugins-dist/renderers/index.js +32 -32
  149. package/plugins-dist/repeats/index.js +131 -174
  150. package/plugins-dist/schedule/cron.js +49 -56
  151. package/plugins-dist/schedule/index.js +230 -247
  152. package/plugins-dist/schedule/store.js +93 -109
  153. package/plugins-dist/scratch/index.js +12 -18
  154. package/plugins-dist/screenshot/browser.js +136 -154
  155. package/plugins-dist/screenshot/index.js +37 -46
  156. package/plugins-dist/screenshot/sys.js +53 -65
  157. package/plugins-dist/screenshot/tool.js +98 -126
  158. package/plugins-dist/sessions/index.js +149 -117
  159. package/plugins-dist/shell/index.js +117 -135
  160. package/plugins-dist/shell/plugin.json +1 -1
  161. package/plugins-dist/shell/renderers.js +28 -33
  162. package/plugins-dist/shell/service.js +17 -23
  163. package/plugins-dist/shell/shell.js +307 -362
  164. package/plugins-dist/shell/sys.js +64 -79
  165. package/plugins-dist/skills/index.js +193 -211
  166. package/plugins-dist/skills/install.js +122 -149
  167. package/plugins-dist/skills/project.js +65 -73
  168. package/plugins-dist/skills/skills.js +135 -171
  169. package/plugins-dist/steer/index.js +108 -125
  170. package/plugins-dist/suggest/index.js +235 -259
  171. package/plugins-dist/task/index.js +130 -117
  172. package/plugins-dist/task/plugin.json +5 -2
  173. package/plugins-dist/task/style.js +9 -14
  174. package/plugins-dist/task/subagent.js +156 -279
  175. package/plugins-dist/todo/index.js +79 -63
  176. package/plugins-dist/tools/index.js +36 -42
  177. package/plugins-dist/tui/editor.js +145 -160
  178. package/plugins-dist/tui/frontend.js +639 -678
  179. package/plugins-dist/tui/history.js +34 -37
  180. package/plugins-dist/tui/index.js +16 -18
  181. package/plugins-dist/tui/markdown.js +203 -247
  182. package/plugins-dist/tui/mascot.js +266 -355
  183. package/plugins-dist/tui/mentions.js +67 -144
  184. package/plugins-dist/tui/plugin.json +1 -2
  185. package/plugins-dist/tui/render.js +35 -45
  186. package/plugins-dist/tui/screen.js +197 -180
  187. package/plugins-dist/tui/transcript.js +436 -468
  188. package/plugins-dist/tui/tui.js +1554 -1656
  189. package/plugins-dist/tui/vendor.js +1088 -1388
  190. package/plugins-dist/undo/checkpoint.js +97 -118
  191. package/plugins-dist/undo/index.js +281 -192
  192. package/plugins-dist/undo/plugin.json +3 -0
  193. package/plugins-dist/undo/snapshot.js +134 -99
  194. package/plugins-dist/undo/style.js +9 -14
  195. package/plugins-dist/update/index.js +26 -28
  196. package/plugins-dist/web/env.js +55 -68
  197. package/plugins-dist/web/index.js +80 -110
  198. package/plugins-dist/web/plugin.json +1 -2
  199. package/plugins-dist/web/renderers.js +4 -5
  200. package/plugins-dist/web/web.js +514 -593
  201. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  202. package/sdk/python/jade_plugin.py +9 -2
  203. package/src/api.ts +1 -1
  204. package/src/host.ts +39 -4
  205. package/src/remote.ts +6 -1
  206. package/src/session.ts +496 -36
@@ -6,6 +6,7 @@
6
6
 
7
7
  import { writeSync } from "node:fs";
8
8
  import type { DOMElement, Key } from "ink";
9
+ import type { StatusSegment } from "@uncarved/jade-api";
9
10
  import {
10
11
  Box,
11
12
  render,
@@ -14,7 +15,6 @@ import {
14
15
  useCursor,
15
16
  useInput,
16
17
  usePaste,
17
- useWindowSize,
18
18
  createContext,
19
19
  createElement as h,
20
20
  useContext,
@@ -33,6 +33,7 @@ import {
33
33
  dim,
34
34
  type Choice,
35
35
  type CommandInfo,
36
+ type CompletionInfo,
36
37
  type Screen,
37
38
  type StatusInfo,
38
39
  } from "./screen.ts";
@@ -43,10 +44,26 @@ import {
43
44
  * 紧跟的 ESC[K 会把最后一个字符擦掉,输入框之类的右边框就缺了一块。留出最后一列就不会这样
44
45
  */
45
46
  function useScreenSize(): { columns: number; rows: number } {
46
- const { columns, rows } = useWindowSize();
47
+ const { columns, rows } = useContext(SizeContext);
47
48
  return { columns: Math.max(1, columns - 1), rows };
48
49
  }
49
50
 
51
+ /** 终端尺寸:由 store 在窗口停止缩放之后才更新(见 tuiScreen 里的 onResize),不用 Ink 的 useWindowSize */
52
+ const SizeContext = createContext<Size>({ columns: 80, rows: 24 });
53
+ type Size = { columns: number; rows: number };
54
+
55
+ /** 最后一个 resize 事件之后等这么久才按新尺寸重画;拖动窗口时一连串的事件只画一次 */
56
+ const RESIZE_SETTLE_MS = 100;
57
+ /** 拖动窗口时最多隔这么久按新尺寸整帧重画一次:每次都画会一直闪(Windows 上每帧清屏),一直不画就只剩终端折乱的旧画面 */
58
+ const RESIZE_FRAME_MS = 200;
59
+ /**
60
+ * 整帧重画之前先停这么久不画:要比 Ink 的帧间隔(30fps,约 33ms)长,
61
+ * 重画那次提交才会马上画出来(节流的第一下),而不是被推迟、和下一次提交合并掉
62
+ */
63
+ const REPAINT_GAP_MS = 40;
64
+ /** 宽度变了之后在后台重新折行,每批折这么多项 */
65
+ const REWRAP_BATCH = 1000;
66
+
50
67
  export interface TuiHandlers {
51
68
  /** 用户在输入框里提交了一行(消息或命令) */
52
69
  submit(text: string): void;
@@ -56,11 +73,11 @@ export interface TuiHandlers {
56
73
  unqueue?(): boolean;
57
74
  /** 空闲时连按两次 Ctrl+C */
58
75
  exit(): void;
59
- /** 输入 @ 时补全用的路径(目录以 / 结尾);每次开始输入一个新的 @ 引用时取一次 */
60
- files?(): Promise<string[]>;
61
- /** Shift+Tab:切换到下一个权限模式 */
62
- cycleMode?(): void;
63
- /** 输入框有焦点时按下 jade 自己不用的 ctrl+<字母>、alt+<字母或数字>(见 keySpec);返回 true 表示有插件处理了 */
76
+ /** 登记了的补全(completions@1):触发字符、占位提示里的说明、候选菜单下的说明;每次渲染时取 */
77
+ completions?(): CompletionInfo[];
78
+ /** 打了触发字符时的候选(像路径一样用 / 分层,目录以 / 结尾);每次开始输入一段新的补全时取一次 */
79
+ complete?(trigger: string): Promise<string[]>;
80
+ /** 输入框有焦点时按下 jade 自己不用的 ctrl+<字母>、alt+<字母或数字>、shift+tab(见 keySpec);返回 true 表示有插件处理了 */
64
81
  key?(spec: string): boolean;
65
82
  }
66
83
 
@@ -110,6 +127,9 @@ interface UiState {
110
127
  status: StatusInfo;
111
128
  /** 插件设置的灰色提示(ctx.input.hint):输入框为空时显示,Tab 或 → 接受 */
112
129
  hint?: string;
130
+ size: Size;
131
+ /** 这一帧比终端高,让 Ink 清屏从左上角整帧重画(见 Store.repaint) */
132
+ repaint?: boolean;
113
133
  }
114
134
 
115
135
  /** 对话最多保留这么多行(折行前),超出时丢掉最早的一段 */
@@ -220,8 +240,8 @@ function wrapLine(l: Line, width: number): string[] {
220
240
  return l.details === undefined ? head : [...head, ...wrap(l.details, width)];
221
241
  }
222
242
 
223
- /** 状态容器:频繁的流式更新合并到一帧再通知界面 */
224
- class Store {
243
+ /** 状态容器:频繁的流式更新合并到一帧再通知界面。导出给测试用 */
244
+ export class Store {
225
245
  state: UiState;
226
246
  #listeners = new Set<() => void>();
227
247
  #timer: ReturnType<typeof setTimeout> | undefined;
@@ -234,9 +254,31 @@ class Store {
234
254
  /** 带名字的项,amend 用 */
235
255
  #named = new Map<string, Line>();
236
256
  #width = 0;
257
+ /**
258
+ * 一共往 #wrapped 前面补过多少行(宽度变了之后分批补上前面的)。补了之后已有的行号都往后挪,
259
+ * 界面上记着行号的东西(选区)减掉它存,就不会跟着跳到别的行(见 App 的 stable)
260
+ */
261
+ #front = 0;
262
+ /** 行号整体重来(宽度变了、裁掉了最早的行、清空)的次数:变了之后记着的行号都作废 */
263
+ #generation = 0;
264
+ get front(): number {
265
+ return this.#front;
266
+ }
267
+ get generation(): number {
268
+ return this.#generation;
269
+ }
270
+ /** #lines 里前这么多项还没按 #width 折行:宽度变了先折看得见的最后一段,前面的在后台分批补上 */
271
+ #unwrapped = 0;
272
+ #rewrap: ReturnType<typeof setTimeout> | undefined;
273
+ #repaintTimer: ReturnType<typeof setTimeout> | undefined;
274
+ /**
275
+ * 先不通知界面重画:窗口正在缩放(等停下来按新尺寸画一次;按旧尺寸画的帧在终端里会错位,
276
+ * Windows 上还会每帧清屏,拖动窗口时就是一直在闪),或者整帧重画之前的空档(见 REPAINT_GAP_MS)
277
+ */
278
+ paused = false;
237
279
 
238
- constructor(status: StatusInfo) {
239
- this.state = { version: 0, scroll: 0, progress: [], queued: [], dialogs: [], status };
280
+ constructor(status: StatusInfo, size: Size) {
281
+ this.state = { version: 0, scroll: 0, progress: [], queued: [], dialogs: [], status, size };
240
282
  }
241
283
 
242
284
  subscribe = (fn: () => void) => {
@@ -254,9 +296,38 @@ class Store {
254
296
  #emit() {
255
297
  clearTimeout(this.#timer);
256
298
  this.#timer = undefined;
299
+ if (this.paused) return;
257
300
  for (const fn of this.#listeners) fn();
258
301
  }
259
302
 
303
+ /** 窗口正在缩放:停下来之前不画 */
304
+ resizing() {
305
+ clearTimeout(this.#repaintTimer);
306
+ this.paused = true;
307
+ }
308
+
309
+ /** 窗口停止缩放,或者拖动中隔一段的那次:按新尺寸整帧重画。之前已经停了一阵没画,不用再等 */
310
+ resized(size: Size) {
311
+ this.#repaintNow({ size });
312
+ }
313
+
314
+ /**
315
+ * 让一次提交比终端高,Ink 会清屏、从左上角整帧重画(包在同步输出里),下一次提交恢复(见 App)。
316
+ * Ink 增量渲染只用相对光标移动,起点一旦偏了(窗口缩放、别的输出插进来),之后每帧都会画错行,这样能把它拉回来。
317
+ * 只能有一次提交是这样:比终端高的帧不管内容变没变,Ink 每画一次就清一次屏
318
+ */
319
+ repaint() {
320
+ clearTimeout(this.#repaintTimer);
321
+ this.paused = true;
322
+ this.#repaintTimer = setTimeout(() => this.#repaintNow(), REPAINT_GAP_MS);
323
+ }
324
+
325
+ #repaintNow(patch: Partial<UiState> = {}) {
326
+ clearTimeout(this.#repaintTimer);
327
+ this.paused = false;
328
+ this.update({ ...patch, repaint: true }, true);
329
+ }
330
+
260
331
  /** 追加普通的行;带 item 时 texts 合成一项(可折叠、可以之后补充),texts 是收起时显示的部分 */
261
332
  append(texts: string[], item?: Omit<Line, "text">) {
262
333
  if (texts.length === 0) return;
@@ -270,6 +341,7 @@ class Store {
270
341
  this.#lines = this.#lines.slice(-MAX_LINES * 0.8);
271
342
  this.#named = new Map(this.#lines.flatMap((l) => (l.id === undefined ? [] : [[l.id, l] as const])));
272
343
  this.#width = 0;
344
+ this.#generation++;
273
345
  }
274
346
  const before = this.#wrapped.length;
275
347
  if (this.#width) for (const l of lines) this.#push(l);
@@ -311,17 +383,55 @@ class Store {
311
383
  for (const _ of rows) this.#owners.push(l);
312
384
  }
313
385
 
314
- /** 按给定宽度折好的全部输出;宽度变了(终端缩放)才重新折行 */
315
- lines(width: number): string[] {
386
+ /**
387
+ * 按给定宽度折好的输出,至少有末尾的 need 行(或者全部)。
388
+ * 宽度变了(终端缩放)才重新折行:同步只折到够 need 行,前面的分批在后台补上,长对话缩放后不用等全部折完才画出来
389
+ */
390
+ lines(width: number, need = Infinity): string[] {
316
391
  if (width !== this.#width) {
392
+ if (this.#width) this.#generation++;
317
393
  this.#width = width;
318
394
  this.#wrapped = [];
319
395
  this.#owners = [];
320
- for (const l of this.#lines) this.#push(l);
396
+ this.#unwrapped = this.#lines.length;
397
+ clearTimeout(this.#rewrap);
398
+ this.#rewrap = undefined;
321
399
  }
400
+ this.#wrapEarlier((n) => this.#wrapped.length + n >= need, Infinity);
401
+ if (this.#unwrapped > 0) this.#rewrap ??= setTimeout(this.#rewrapBatch, 0);
322
402
  return this.#wrapped;
323
403
  }
324
404
 
405
+ #rewrapBatch = () => {
406
+ this.#rewrap = undefined;
407
+ if (!this.#width || this.#unwrapped === 0) return;
408
+ const before = this.#wrapped.length;
409
+ this.#wrapEarlier(() => false, REWRAP_BATCH);
410
+ if (this.#unwrapped > 0) this.#rewrap = setTimeout(this.#rewrapBatch, 0);
411
+ // 补上的行在前面,离底部的距离(scroll)不变,看的地方也就不动;只是行号变了,所以要重画
412
+ if (this.#wrapped.length !== before) this.update({ version: this.state.version + 1 });
413
+ };
414
+
415
+ /** 从后往前折还没折的项,直到 enough(新折出的行数) 或者折了 max 项 */
416
+ #wrapEarlier(enough: (rows: number) => boolean, max: number) {
417
+ const rows: string[][] = [];
418
+ const owners: Line[] = [];
419
+ let count = 0;
420
+ while (this.#unwrapped > 0 && rows.length < max && !enough(count)) {
421
+ const l = this.#lines[--this.#unwrapped]!;
422
+ const r = wrapLine(l, this.#width);
423
+ rows.push(r);
424
+ owners.push(l);
425
+ count += r.length;
426
+ }
427
+ if (rows.length === 0) return;
428
+ rows.reverse();
429
+ owners.reverse();
430
+ this.#front += count;
431
+ this.#wrapped = [...rows.flat(), ...this.#wrapped];
432
+ this.#owners = [...owners.flatMap((l, i) => rows[i]!.map(() => l)), ...this.#owners];
433
+ }
434
+
325
435
  /**
326
436
  * 展开或收起第 row 行(折好的行)所在的项;不是可折叠项时什么也不做。
327
437
  * start、view 是当前可见的第一行和可见行数:可见部分的开头保持不动;
@@ -352,9 +462,11 @@ class Store {
352
462
  }
353
463
 
354
464
  clear() {
465
+ this.#generation++;
355
466
  this.#lines = [];
356
467
  this.#wrapped = [];
357
468
  this.#owners = [];
469
+ this.#unwrapped = 0;
358
470
  this.#named.clear();
359
471
  this.update(
360
472
  { version: this.state.version + 1, live: undefined, progress: [], scroll: 0, hint: undefined },
@@ -454,7 +566,25 @@ function titleBar(stdout: NodeJS.WriteStream, store: Store, env = process.env):
454
566
 
455
567
  export function tuiScreen(opts: TuiOptions): Screen {
456
568
  const stdout = opts.io?.stdout ?? process.stdout;
457
- const store = new Store(opts.status);
569
+ const size = (): Size => ({ columns: stdout.columns || 80, rows: stdout.rows || 24 });
570
+ const store = new Store(opts.status, size());
571
+ let settle: ReturnType<typeof setTimeout> | undefined;
572
+ let lastResizeFrame = 0;
573
+ const onResize = () => {
574
+ clearTimeout(settle);
575
+ // 终端已经按新宽度把画着的那一帧重新折过行(边框断成两截、两行拼成一行):拖动时每隔一段按新尺寸整帧重画一次,
576
+ // 中间不画(Ink 增量画的帧在折乱的屏幕上会错位);停下后再画最后一次
577
+ const now = Date.now();
578
+ if (now - lastResizeFrame >= RESIZE_FRAME_MS) {
579
+ lastResizeFrame = now;
580
+ store.resized(size());
581
+ } else store.resizing();
582
+ settle = setTimeout(() => {
583
+ lastResizeFrame = Date.now();
584
+ store.resized(size());
585
+ }, RESIZE_SETTLE_MS);
586
+ };
587
+ stdout.on("resize", onResize);
458
588
  const draft: DraftBridge = {};
459
589
  const notify = notifier(stdout);
460
590
  /** 已经工作了很久(见 NOTIFY_AFTER) */
@@ -536,6 +666,7 @@ export function tuiScreen(opts: TuiOptions): Screen {
536
666
  /** 接管终端、画界面。界面的内容都在 store 里,所以让出终端(suspend)之后可以再画一个新的 */
537
667
  const mount = () => {
538
668
  stdout.write("\x1b[?1049h\x1b[2J\x1b[H");
669
+ const ours = new Set(stdout.listeners("resize"));
539
670
  const mounted = render(
540
671
  h(App, {
541
672
  store,
@@ -556,6 +687,10 @@ export function tuiScreen(opts: TuiOptions): Screen {
556
687
  : {}),
557
688
  },
558
689
  );
690
+ // Ink 自己也听 resize:每个事件都马上按旧的布局画一帧(变窄时还先逐行擦掉上一帧),
691
+ // 拖动窗口时就是一连串错位的帧,Windows 上每帧还清屏。尺寸改由上面的 onResize 在停下之后统一处理,
692
+ // Ink 每次提交都会按终端当前的宽度重新排版,不需要它自己的监听
693
+ for (const l of stdout.listeners("resize")) if (!ours.has(l)) stdout.off("resize", l as () => void);
559
694
  stdout.write(MOUSE_ON + CURSOR_BLINK);
560
695
  return mounted;
561
696
  };
@@ -719,6 +854,8 @@ export function tuiScreen(opts: TuiOptions): Screen {
719
854
  // 等最后一帧画完再卸载;卸载时 Ink 退出备用屏幕
720
855
  await new Promise((r) => setTimeout(r, 50));
721
856
  closeTitle();
857
+ clearTimeout(settle);
858
+ stdout.off("resize", onResize);
722
859
  stdout.write(MOUSE_OFF + CURSOR_RESET);
723
860
  instance.unmount();
724
861
  await instance.waitUntilExit();
@@ -838,6 +975,25 @@ const osc52 = (text: string) => `\x1b]52;c;${Buffer.from(text, "utf8").toString(
838
975
  * 不中断模型、不清空输入、不取消对话框
839
976
  */
840
977
  const SelectionContext = createContext<{ active(): boolean; clear(): void }>({ active: () => false, clear: () => {} });
978
+ /**
979
+ * 对话区一共 total 行、高 height 行、离底部 scroll 行时能看见哪几行 [start, end)。
980
+ * 往上翻看时最后一行用来提示(scrolled),能看见的少一行(view)。
981
+ * 最多能翻多远(max)按翻上去之后的可见行数算:还在底部时按 height 算,翻到顶会少一行,第一行看不见
982
+ */
983
+ function viewport(total: number, height: number, wanted: number) {
984
+ const scrolled = wanted > 0 && total > height;
985
+ const view = Math.max(0, scrolled ? height - 1 : height);
986
+ const max = total > height ? total - Math.max(0, height - 1) : 0;
987
+ const scroll = Math.min(wanted, max);
988
+ const end = total - scroll;
989
+ return { scrolled, view, max, scroll, end, start: Math.max(0, end - view) };
990
+ }
991
+
992
+ /** 拖选时鼠标停在对话区上面或下面,隔这么久滚一次 */
993
+ const DRAG_SCROLL_MS = 50;
994
+ /** 每次滚几行:离对话区越远滚得越快,最多这么多行 */
995
+ const DRAG_SCROLL_MAX = 8;
996
+
841
997
  /** 终端矮于这么多行时标题只占一行 */
842
998
  const COMPACT_ROWS = 24;
843
999
 
@@ -868,11 +1024,14 @@ function App({
868
1024
  }) {
869
1025
  const state = useSyncExternalStore(store.subscribe, store.get);
870
1026
  const dialog = state.dialogs[0];
871
- const { columns, rows } = useScreenSize();
1027
+ const columns = Math.max(1, state.size.columns - 1);
1028
+ const rows = state.size.rows;
872
1029
  const compact = rows < COMPACT_ROWS;
873
1030
  // 运行中每一帧(FRAME_MS)整体重画一次,推动转圈和吉祥物的动画。不能让 Spinner、吉祥物自己重画:
874
- // Ink 只在输入框也跟着提交的那一帧保留光标,否则把光标藏起来,运行中光标就不见了
875
- const [ticks, tick] = useReducer((n: number) => n + 1, 0);
1031
+ // Ink 只在输入框也跟着提交的那一帧保留光标,否则把光标藏起来,运行中光标就不见了。
1032
+ // 窗口缩放时和整帧重画之前不画(见 Store.paused)
1033
+ const [ticks, tickNow] = useReducer((n: number) => n + 1, 0);
1034
+ const tick = () => store.paused || tickNow();
876
1035
  const busy = state.busy !== undefined;
877
1036
  useEffect(() => {
878
1037
  if (!busy) return;
@@ -891,13 +1050,17 @@ function App({
891
1050
  if (busy || !showBot) return;
892
1051
  const t = setTimeout(tick, nextChange(mood, Date.now(), state.doneAt, moving));
893
1052
  return () => clearTimeout(t);
894
- }, [busy, showBot, ticks, mood, moving, state.doneAt]);
1053
+ // 缩放时跳过的那一下靠 state.size 变了再排上
1054
+ }, [busy, showBot, ticks, mood, moving, state.doneAt, state.size]);
895
1055
 
896
1056
  // 对话区占掉标题和底部之外的全部高度,只画能看见的那几行
897
1057
  const ref = useRef<DOMElement>(null);
898
1058
  const { height, top } = useBoxMetrics(ref);
899
1059
  const width = Math.max(10, columns - 2);
900
- const done = store.lines(width);
1060
+ // 往上翻看时要折到能看见的地方;多要一屏给翻页
1061
+ const done = store.lines(width, state.scroll + 2 * rows);
1062
+ // 选区记的是减掉 front 的行号(见 Store.front):宽度变了之后前面分批补上行,看着的那几行行号会变,选区不能跟着跳
1063
+ const front = store.front;
901
1064
  // 还没结束的流式块和正在运行的工具的进度:思考只显示最新的一行,进度每个工具一行
902
1065
  const live = [
903
1066
  ...(state.live?.pending ?? []).flatMap((l) => mdRows(l, width)),
@@ -905,13 +1068,7 @@ function App({
905
1068
  ...state.progress.map((p) => oneRow(p.line, width).row),
906
1069
  ];
907
1070
  const total = done.length + live.length;
908
- // 往上翻看时最后一行用来提示
909
- const scrolled = state.scroll > 0 && total > height;
910
- const view = Math.max(0, scrolled ? height - 1 : height);
911
- const max = Math.max(0, total - view);
912
- const scroll = Math.min(state.scroll, max);
913
- const end = total - scroll;
914
- const start = Math.max(0, end - view);
1071
+ const { scrolled, view, max, scroll, end, start } = viewport(total, height, state.scroll);
915
1072
  const shown = [
916
1073
  ...done.slice(start, Math.min(end, done.length)),
917
1074
  ...live.slice(
@@ -922,7 +1079,8 @@ function App({
922
1079
  const page = Math.max(1, view - 2);
923
1080
 
924
1081
  // 选中文字:按下左键记下位置,拖动时更新,松开时复制;点一下(没拖动)还是展开或收起那一项。
925
- // 几个事件可能在同一块输入里连着到达,来不及重画,所以另外用 ref 记着最新的值
1082
+ // 几个事件可能在同一块输入里连着到达,来不及重画,所以另外用 ref 记着最新的值。
1083
+ // pressed、selected 里的行号都是减掉 front 的(见上)
926
1084
  const [selection, setSelectionState] = useState<Selection>();
927
1085
  const selected = useRef<Selection>(undefined);
928
1086
  const pressed = useRef<Point>(undefined);
@@ -931,8 +1089,35 @@ function App({
931
1089
  setSelectionState(s);
932
1090
  };
933
1091
  const [selectionApi] = useState(() => ({ active: () => selected.current !== undefined, clear: () => setSelection(undefined) }));
934
- // 宽度变了,行重新折过,原来的位置对不上了
935
- useEffect(() => setSelection(undefined), [width]);
1092
+ // 拖选时鼠标停在对话区外面,终端不再发事件(只在移动时发),所以由定时器接着滚、接着扩大选区。
1093
+ // 定时器里要用最新一帧的行数和高度,每次渲染写进 geometry
1094
+ const geometry = useRef({ total, height, front });
1095
+ geometry.current = { total, height, front };
1096
+ const dragScroll = useRef<{ timer: ReturnType<typeof setInterval>; dir: 1 | -1; lines: number; col: number }>(undefined);
1097
+ const stopDragScroll = () => {
1098
+ clearInterval(dragScroll.current?.timer);
1099
+ dragScroll.current = undefined;
1100
+ };
1101
+ const dragScrollTick = () => {
1102
+ const d = dragScroll.current;
1103
+ const anchor = pressed.current;
1104
+ if (!d || !anchor) return stopDragScroll();
1105
+ const g = geometry.current;
1106
+ store.scrollBy(d.dir * d.lines, viewport(g.total, g.height, 0).max);
1107
+ const v = viewport(g.total, g.height, store.get().scroll);
1108
+ if (v.end <= v.start) return;
1109
+ // 往上滚时选到看得见的第一行,往下滚时选到最后一行
1110
+ const focus = { row: (d.dir > 0 ? v.start : v.end - 1) - g.front, col: d.col };
1111
+ const s = selected.current;
1112
+ if (!s || !same(s.focus, focus)) setSelection({ anchor, focus });
1113
+ };
1114
+ useEffect(() => stopDragScroll, []);
1115
+ // 宽度变了、裁掉了最早的行、清空了:行号整体重来,原来的位置对不上了
1116
+ useEffect(() => {
1117
+ stopDragScroll();
1118
+ pressed.current = undefined;
1119
+ setSelection(undefined);
1120
+ }, [width, store.generation]);
936
1121
  const rowAt = (i: number) => (i < done.length ? done[i] : live[i - done.length]);
937
1122
  // 复制之后在输入框下面提示一会儿
938
1123
  const [copied, setCopied] = useState<string>();
@@ -940,7 +1125,7 @@ function App({
940
1125
  useEffect(() => () => clearTimeout(copiedTimer.current), []);
941
1126
  /** 输入框文字在屏幕上的位置(Prompt 里的 EditableText 每次渲染时写入) */
942
1127
  const inputPlace = useRef<Placement>(undefined);
943
- const copySelection = (s: Selection) => copyText(selectedText(s, rowAt));
1128
+ const copySelection = (s: Selection) => copyText(selectedText(s, (i) => rowAt(i + front)));
944
1129
  const copyText = (text: string) => {
945
1130
  copy(text);
946
1131
  clearTimeout(copiedTimer.current);
@@ -948,29 +1133,17 @@ function App({
948
1133
  copiedTimer.current = setTimeout(() => setCopied(undefined), COPIED_MS);
949
1134
  };
950
1135
 
951
- // Ink 增量渲染只用相对光标移动,第一帧起点一旦偏了(启动时终端尺寸还没稳定、窗口缩放、别的输出插进来),
952
- // 之后每帧都会画错行。尺寸变化后和按 Ctrl+L 时让一帧比终端高,Ink 会清屏从左上角整帧重画(包在同步输出里),下一帧再恢复。
953
- // 启动时不重画:第一帧之前已经清屏、光标在左上角;这两次清屏在不支持同步输出的终端上(Windows 上常见)看得出闪一下
954
- const [redraws, setRedraws] = useState(0);
955
- const [repaint, setRepaint] = useState(false);
956
- const mounted = useRef(false);
957
- useEffect(() => {
958
- if (!mounted.current) {
959
- mounted.current = true;
960
- return;
961
- }
962
- const t = setTimeout(() => setRepaint(true), 100);
963
- return () => clearTimeout(t);
964
- }, [columns, rows, redraws]);
1136
+ // 窗口停止缩放后和按 Ctrl+L 时整帧重画一次(见 Store.repaint)。
1137
+ // 启动时不重画:第一帧之前已经清屏、光标在左上角;整帧重画在不支持同步输出的终端上(Windows 上常见)看得出闪一下
1138
+ const repaint = state.repaint === true;
1139
+ // 整帧重画那次提交已经马上画出来了(见 Store.repaint),下一次提交就恢复;
1140
+ // 这一轮里别的组件跟着改的状态(量出来的高度)和恢复合在同一次提交里,不会再画一帧比终端高的
965
1141
  useEffect(() => {
966
- if (!repaint) return;
967
- // 要比 Ink 的帧间隔长,否则这一帧会被合并掉
968
- const t = setTimeout(() => setRepaint(false), 50);
969
- return () => clearTimeout(t);
1142
+ if (repaint) store.update({ repaint: false });
970
1143
  }, [repaint]);
971
1144
 
972
1145
  useInput((input, key) => {
973
- if (key.ctrl && input === "l") return setRedraws((n) => n + 1);
1146
+ if (key.ctrl && input === "l") return store.repaint();
974
1147
  // 展开或收起最近的一项(工具结果、思考、检查报告),鼠标点不了时也能看完整内容
975
1148
  if (key.ctrl && input === "o") return store.toggleLatest(start, view);
976
1149
  const mouse = mouseEvent(input);
@@ -979,7 +1152,7 @@ function App({
979
1152
  const at = (clamp: boolean): Point | undefined => {
980
1153
  const i = mouse.y - top;
981
1154
  if (!clamp && (i < 0 || i >= shown.length)) return undefined;
982
- return { row: start + Math.min(Math.max(i, 0), shown.length - 1), col: Math.max(0, mouse.x - 1) };
1155
+ return { row: start + Math.min(Math.max(i, 0), shown.length - 1) - front, col: Math.max(0, mouse.x - 1) };
983
1156
  };
984
1157
  // 滚轮在放不下全部文字的输入框上(含上下边框)时由输入框自己翻
985
1158
  const input = inputPlace.current;
@@ -988,11 +1161,27 @@ function App({
988
1161
  if (mouse.button === 64) store.scrollBy(WHEEL_LINES, max);
989
1162
  else if (mouse.button === 65) store.scrollBy(-WHEEL_LINES, max);
990
1163
  else if (mouse.button === 0 && mouse.press) {
1164
+ stopDragScroll();
991
1165
  if (selected.current) setSelection(undefined);
992
1166
  pressed.current = at(false);
993
1167
  } else if (mouse.button === DRAG && pressed.current) {
994
1168
  setSelection({ anchor: pressed.current, focus: at(true)! });
1169
+ // 拖到对话区上面或下面:一直滚,直到拖回来或者松开
1170
+ const above = top - mouse.y;
1171
+ const below = mouse.y - (top + shown.length - 1);
1172
+ const dir = above > 0 ? 1 : below > 0 && shown.length >= view ? -1 : 0;
1173
+ if (dir === 0) stopDragScroll();
1174
+ else {
1175
+ const lines = Math.min(DRAG_SCROLL_MAX, dir > 0 ? above : below);
1176
+ const col = Math.max(0, mouse.x - 1);
1177
+ if (dragScroll.current) Object.assign(dragScroll.current, { dir, lines, col });
1178
+ else {
1179
+ dragScroll.current = { timer: setInterval(dragScrollTick, DRAG_SCROLL_MS), dir, lines, col };
1180
+ dragScrollTick();
1181
+ }
1182
+ }
995
1183
  } else if (mouse.button === 0 && !mouse.press && pressed.current) {
1184
+ stopDragScroll();
996
1185
  const p = pressed.current;
997
1186
  pressed.current = undefined;
998
1187
  const s = selected.current;
@@ -1000,13 +1189,17 @@ function App({
1000
1189
  else {
1001
1190
  if (s) setSelection(undefined);
1002
1191
  // 点在对话区里已经完成的输出上:展开或收起那一项
1003
- if (p.row < done.length) store.toggle(p.row, start, view);
1192
+ if (p.row + front < done.length) store.toggle(p.row + front, start, view);
1004
1193
  }
1005
1194
  }
1006
1195
  return;
1007
1196
  }
1008
1197
  // 按别的键取消选中;Ctrl+C 由输入框和对话框处理(见 SelectionContext)
1009
- if (selected.current && !(key.ctrl && input === "c")) setSelection(undefined);
1198
+ if (selected.current && !(key.ctrl && input === "c")) {
1199
+ stopDragScroll();
1200
+ pressed.current = undefined;
1201
+ setSelection(undefined);
1202
+ }
1010
1203
  // 选择框自己用 PgUp/PgDn 翻选项
1011
1204
  if (dialog?.kind === "select") return;
1012
1205
  if (key.pageUp) store.scrollBy(page, max);
@@ -1018,7 +1211,7 @@ function App({
1018
1211
  // 总高度要比终端少一行,否则 Ink 认为输出占满了屏幕,每帧清屏重画。
1019
1212
  // 重画那一帧上下各垫一行空白:终端把顶上那行滚出去后,看到的和平时逐行一样,所以不会闪。
1020
1213
  // 只做纵向裁剪:每行都已按宽度折好或截断,横向裁剪会让 Ink 每帧对每一行再切一遍 ANSI 字符串
1021
- return h(
1214
+ return h(SizeContext.Provider, { value: state.size }, h(
1022
1215
  SelectionContext.Provider,
1023
1216
  { value: selectionApi },
1024
1217
  h(
@@ -1034,7 +1227,7 @@ function App({
1034
1227
  h(
1035
1228
  Box,
1036
1229
  { flexDirection: "column", flexGrow: 1, overflowY: "hidden" },
1037
- h(Header, { status: state.status, version, compact, bot }),
1230
+ h(Header, { status: state.status, version, compact, bot, completions: handlers.completions?.() ?? [] }),
1038
1231
  h(
1039
1232
  Box,
1040
1233
  {
@@ -1049,7 +1242,7 @@ function App({
1049
1242
  shown.map((raw, i) => {
1050
1243
  // 续行的记号不显示
1051
1244
  const l = visibleRow(raw);
1052
- const cols = selection && selectedCols(selection, start + i);
1245
+ const cols = selection && selectedCols(selection, start + i - front);
1053
1246
  return h(Text, { key: i, wrap: "truncate-end" }, cols ? highlight(l || " ", ...cols) : l || " ");
1054
1247
  }),
1055
1248
  scrolled
@@ -1064,6 +1257,12 @@ function App({
1064
1257
  Box,
1065
1258
  { flexDirection: "column", flexShrink: 0 },
1066
1259
  state.busy && !dialog ? h(Spinner, { label: state.busy.label, since: state.busy.since }) : null,
1260
+ // 插件的块(例如任务清单):对话框占着地方时先不显示
1261
+ dialog
1262
+ ? null
1263
+ : (state.status.panels ?? []).flatMap((p) =>
1264
+ p.text.split("\n").map((l, i) => h(Text, { key: `${p.plugin}:${i}`, wrap: "truncate-end" }, " ", l || " ")),
1265
+ ),
1067
1266
  state.queued.map((q, i) =>
1068
1267
  h(Text, { key: i, dimColor: true, wrap: "truncate-end" }, " ↳ queued: ", q.replace(/\s+/g, " ")),
1069
1268
  ),
@@ -1091,7 +1290,7 @@ function App({
1091
1290
  ),
1092
1291
  ),
1093
1292
  ),
1094
- );
1293
+ ));
1095
1294
  }
1096
1295
 
1097
1296
  /**
@@ -1112,6 +1311,7 @@ function Bot({ pixels }: { pixels: (string | undefined)[][] }) {
1112
1311
  }
1113
1312
 
1114
1313
  function Header({
1314
+ completions,
1115
1315
  status,
1116
1316
  version,
1117
1317
  compact,
@@ -1123,6 +1323,7 @@ function Header({
1123
1323
  bot?: (string | undefined)[][];
1124
1324
  /** 终端很矮时只占一行,把高度留给对话和输入框 */
1125
1325
  compact: boolean;
1326
+ completions: CompletionInfo[];
1126
1327
  }) {
1127
1328
  // 模型 · 目录 (分支)
1128
1329
  const where = [
@@ -1153,7 +1354,7 @@ function Header({
1153
1354
  status.session ? h(Text, { dimColor: true }, ` · session ${status.session}`) : null,
1154
1355
  ),
1155
1356
  h(Text, { wrap: "truncate-end" }, ...where),
1156
- h(Text, { dimColor: true, wrap: "truncate-end" }, "/help for commands · @ to attach files"),
1357
+ h(Text, { dimColor: true, wrap: "truncate-end" }, ["/help for commands", ...completions.map((c) => `${c.trigger} ${c.label}`)].join(" · ")),
1157
1358
  ),
1158
1359
  );
1159
1360
  }
@@ -1197,6 +1398,9 @@ interface Segment {
1197
1398
  dim?: boolean;
1198
1399
  }
1199
1400
 
1401
+ /** 插件段落的语义颜色怎么画 */
1402
+ const TONE: Record<NonNullable<StatusSegment["tone"]>, string> = { ok: "green", warn: "yellow", error: "red", accent: "magenta" };
1403
+
1200
1404
  /** 在 width 列里放下尽量多的内容(保持原来的顺序) */
1201
1405
  export function fitSegments(segments: Segment[], width: number): Segment[] {
1202
1406
  const kept = segments.map((s) => ({ ...s }));
@@ -1221,32 +1425,30 @@ export function fitSegments(segments: Segment[], width: number): Segment[] {
1221
1425
  function StatusBar({ status, width }: { status: StatusInfo; width: number }) {
1222
1426
  const ctx = status.context;
1223
1427
  const pct = ctx ? Math.round((ctx.used / ctx.limit) * 100) : 0;
1224
- /** 离自动压缩还有多远:到阈值的 85% 起变黄 */
1225
- const nearCompact = ctx?.compactAt ? ctx.used >= ctx.compactAt * 0.85 : pct >= 80;
1226
- const modeColor =
1227
- status.mode === "yolo"
1228
- ? "red"
1229
- : status.mode === "auto"
1230
- ? "yellow"
1231
- : status.mode === "plan"
1232
- ? "magenta"
1233
- : "green";
1428
+ const nearFull = pct >= 80;
1234
1429
  const speed = status.speed;
1430
+ // 插件的段落:要一直留着的(keep,例如 jade/modes 的当前模式)放在最前,窄的时候换成短写法;其余的比提示晚、比缓存早去掉
1431
+ const plugin = (p: { text: string | StatusSegment }, keep: boolean): Segment => {
1432
+ const seg = typeof p.text === "string" ? { text: p.text } : p.text;
1433
+ return {
1434
+ text: seg.text,
1435
+ ...(seg.short !== undefined ? { short: seg.short, shortAt: keep ? 6 : 7.6 } : {}),
1436
+ ...(keep ? {} : { dropAt: 7.5 }),
1437
+ ...(seg.tone ? { color: TONE[seg.tone] } : { dim: true }),
1438
+ };
1439
+ };
1440
+ const kept = (status.plugins ?? []).filter((p) => typeof p.text !== "string" && p.text.keep);
1441
+ const others = (status.plugins ?? []).filter((p) => !kept.includes(p));
1235
1442
  // 窄的时候依次:提示变短、去掉提示、用量变短、去掉缓存、模式变短、去掉用量、上下文变短、去掉速度
1236
1443
  const segments: Segment[] = [
1237
- {
1238
- text: `${status.mode} (shift+tab)`,
1239
- short: status.mode,
1240
- shortAt: 6,
1241
- color: modeColor,
1242
- },
1444
+ ...kept.map((p) => plugin(p, true)),
1243
1445
  ctx
1244
1446
  ? {
1245
- text: `ctx ${tokens(ctx.used)}/${tokens(ctx.limit)} (${pct}%)${ctx.compactAt ? `, compacts at ${tokens(ctx.compactAt)}` : ""}`,
1447
+ text: `ctx ${tokens(ctx.used)}/${tokens(ctx.limit)} (${pct}%)`,
1246
1448
  short: `ctx ${pct}%`,
1247
1449
  shortAt: 4,
1248
- color: nearCompact ? "yellow" : undefined,
1249
- dim: !nearCompact,
1450
+ color: nearFull ? "yellow" : undefined,
1451
+ dim: !nearFull,
1250
1452
  }
1251
1453
  : { text: "ctx —", dim: true },
1252
1454
  ...(speed
@@ -1272,8 +1474,7 @@ function StatusBar({ status, width }: { status: StatusInfo; width: number }) {
1272
1474
  },
1273
1475
  ]
1274
1476
  : []),
1275
- // 插件的段落:比提示晚、比缓存早去掉
1276
- ...(status.plugins ?? []).map((p) => ({ text: p.text, dropAt: 7.5, dim: true })),
1477
+ ...others.map((p) => plugin(p, false)),
1277
1478
  {
1278
1479
  text: "PgUp/PgDn scroll · click ▸ or ctrl+o to expand · drag to select and copy",
1279
1480
  short: "ctrl+o to expand",
@@ -1329,8 +1530,9 @@ function useLive<T>(initial: T): [get: () => T, set: (v: T) => void] {
1329
1530
 
1330
1531
  /** 编辑按键的通用处理;返回编辑后的状态,不是编辑键时返回 undefined */
1331
1532
  function editKey(s: EditState, input: string, key: Key): EditState | undefined {
1332
- if (key.leftArrow) return edit.left(s);
1333
- if (key.rightArrow) return edit.right(s);
1533
+ // Ctrl+←/→ 按词移动(Windows 上的习惯),同 Alt+B / Alt+F
1534
+ if (key.leftArrow) return key.ctrl ? edit.wordLeft(s) : edit.left(s);
1535
+ if (key.rightArrow) return key.ctrl ? edit.wordRight(s) : edit.right(s);
1334
1536
  if (key.home || (key.ctrl && input === "a")) return edit.home(s);
1335
1537
  if (key.end || (key.ctrl && input === "e")) return edit.end(s);
1336
1538
  if (key.backspace) return key.meta ? edit.deleteWord(s) : edit.backspace(s);
@@ -1561,6 +1763,8 @@ function Prompt({
1561
1763
  >(undefined);
1562
1764
 
1563
1765
  const usageOf = (c: CommandInfo) => `/${c.name}${c.args ? ` ${c.args}` : ""}`;
1766
+ const completions = handlers.completions?.() ?? [];
1767
+ const triggers = completions.map((c) => c.trigger);
1564
1768
  const column = Math.max(...commands().map((c) => usageOf(c).length)) + 2;
1565
1769
 
1566
1770
  /** 由最新的输入算出补全菜单和搜索结果;渲染和按键处理都用它 */
@@ -1581,7 +1785,7 @@ function Prompt({
1581
1785
  const pick = matches[Math.min(selected, matches.length - 1)];
1582
1786
  // @ 引用:光标处正在输入的路径和补全候选
1583
1787
  const mention =
1584
- naming || recalled ? undefined : mentionAt(state.value, state.cursor);
1788
+ naming || recalled ? undefined : mentionAt(state.value, state.cursor, triggers);
1585
1789
  let found: string[] = [];
1586
1790
  if (mention) {
1587
1791
  const paths = getPaths();
@@ -1620,12 +1824,13 @@ function Prompt({
1620
1824
  derive();
1621
1825
  const notice = getNotice();
1622
1826
 
1623
- const mentioning = mention !== undefined;
1624
- // 每次开始输入一个新的 @ 引用时重新取一次:文件可能已经变了
1827
+ const mentioning = mention?.trigger;
1828
+ // 每次开始输入一段新的补全时重新取一次:候选可能已经变了(例如文件)
1625
1829
  useEffect(() => {
1626
- if (!mentioning || !handlers.files) return;
1830
+ if (mentioning === undefined || !handlers.complete) return;
1627
1831
  let live = true;
1628
- handlers.files().then(
1832
+ setPaths([]);
1833
+ handlers.complete(mentioning).then(
1629
1834
  (p) => void (live && setPaths(p)),
1630
1835
  () => {},
1631
1836
  );
@@ -1633,6 +1838,7 @@ function Prompt({
1633
1838
  live = false;
1634
1839
  };
1635
1840
  }, [mentioning]);
1841
+ const completion = completions.find((c) => c.trigger === mentioning);
1636
1842
  // 结果多时只显示选中项附近的几条
1637
1843
  const first = around(hit, results.length, menuRows);
1638
1844
  const firstMatch = around(Math.max(0, matches.indexOf(pick!)), matches.length, menuRows);
@@ -1654,8 +1860,16 @@ function Prompt({
1654
1860
  ].slice(-100);
1655
1861
  browsing.current = -1;
1656
1862
  };
1657
- const submit = (text: string) => {
1658
- if (!text.trim()) return;
1863
+ /**
1864
+ * 大段粘贴在输入框里只占一个占位符,发送(和放进历史、给插件读)时换回原文。
1865
+ * 占位符被删掉一部分时认不出来,按打出来的样子发送。发送、清空之后原文已经换回去了(历史里存的也是原文),不再留着
1866
+ */
1867
+ const pastes = useRef(new Map<string, string>());
1868
+ const unfold = (text: string) => (pastes.current.size ? text.replace(PASTED, (m) => pastes.current.get(m) ?? m) : text);
1869
+ const submit = (folded: string) => {
1870
+ if (!folded.trim()) return;
1871
+ const text = unfold(folded);
1872
+ pastes.current.clear();
1659
1873
  if (hint !== undefined) onHintDone();
1660
1874
  remember(text);
1661
1875
  set(empty);
@@ -1666,14 +1880,15 @@ function Prompt({
1666
1880
  };
1667
1881
  /** 清空输入;清掉的内容放进(本次运行的)历史,按 ↑ 能找回来 */
1668
1882
  const discard = () => {
1669
- const text = current().value;
1883
+ const text = unfold(current().value);
1884
+ pastes.current.clear();
1670
1885
  if (text.trim()) remember(text);
1671
1886
  set(empty);
1672
1887
  };
1673
1888
  /** 用选中的路径替换正在输入的 @ 引用;目录不加空格,接着补全里面的文件 */
1674
1889
  const complete = (p: string) => {
1675
1890
  const { state, mention } = derive();
1676
- const text = mentionText(p) + (p.endsWith("/") ? "" : " ");
1891
+ const text = mentionText(mention!.trigger, p) + (p.endsWith("/") ? "" : " ");
1677
1892
  set({
1678
1893
  value:
1679
1894
  state.value.slice(0, mention!.start) +
@@ -1682,7 +1897,7 @@ function Prompt({
1682
1897
  cursor: mention!.start + text.length,
1683
1898
  });
1684
1899
  };
1685
- bridge.current = { get: () => current().value, apply: (f) => set(f(current())) };
1900
+ bridge.current = { get: () => unfold(current().value), apply: (f) => set(f(current())) };
1686
1901
  const recall = (i: number) => {
1687
1902
  browsing.current = i;
1688
1903
  const value =
@@ -1700,7 +1915,14 @@ function Prompt({
1700
1915
  query: search.query + text.replace(/\s+/g, " "),
1701
1916
  index: 0,
1702
1917
  });
1703
- else set(edit.insert(current(), text.replace(/\r\n?/g, "\n")));
1918
+ else {
1919
+ const pasted = text.replace(/\r\n?/g, "\n");
1920
+ const lines = pasted.replace(/\n$/, "").split("\n").length;
1921
+ if (lines <= FOLD_PASTE_LINES && pasted.length <= FOLD_PASTE_CHARS) return set(edit.insert(current(), pasted));
1922
+ const tag = `[Pasted text #${pastes.current.size + 1} ${lines > 1 ? `+${lines} lines` : `${pasted.length} chars`}]`;
1923
+ pastes.current.set(tag, pasted);
1924
+ set(edit.insert(current(), tag));
1925
+ }
1704
1926
  },
1705
1927
  { isActive: active },
1706
1928
  );
@@ -1837,7 +2059,8 @@ function Prompt({
1837
2059
  browsing.current = -1;
1838
2060
  return set({ value: hint!, cursor: hint!.length });
1839
2061
  }
1840
- if (key.tab && key.shift) return handlers.cycleMode?.();
2062
+ // shift+tab 交给插件的快捷键(例如 jade/modes 切换模式)
2063
+ if (key.tab && key.shift) return void handlers.key?.("shift+tab");
1841
2064
  if (key.tab) {
1842
2065
  const { pick, file } = derive();
1843
2066
  if (pick)
@@ -1892,8 +2115,17 @@ function Prompt({
1892
2115
  ? [Math.min(drag.anchor, drag.focus), Math.max(drag.anchor, drag.focus)]
1893
2116
  : undefined;
1894
2117
 
1895
- // ! 开头:这一行是用户自己执行的 shell 命令(/sh),边框换个颜色、上边框的右边写一行说明
1896
- const bang = !search && state.value.startsWith("!");
2118
+ // 以命令的简写开头(例如 jade/shell 的 !):这一行是那条命令,边框换个颜色、上边框的右边写一行说明
2119
+ const prefixed = search ? undefined : commands().find((c) => c.prefix !== undefined && state.value.startsWith(c.prefix));
2120
+ const bang = prefixed !== undefined;
2121
+ const prefixLabel = (() => {
2122
+ if (!prefixed) return "";
2123
+ const hint = prefixed.prefixHint ?? `/${prefixed.name}`;
2124
+ const head = hint.split(" · ")[0]!;
2125
+ // 窄的时候只留第一句;运行中排队,说明这一点
2126
+ return columns >= 70 ? (busy ? `${head} · runs after this turn · esc stops it` : `${hint} · esc stops it`) : head;
2127
+ })();
2128
+ const placeholder = ["Message jade", "/ commands", ...completions.map((c) => `${c.trigger} ${c.label}`)].join(" · ");
1897
2129
 
1898
2130
  // 对话框打开时隐藏但不卸载,输入到一半的内容和历史都保留
1899
2131
  return h(
@@ -1922,8 +2154,8 @@ function Prompt({
1922
2154
  : busy
1923
2155
  ? "Type to queue a message · esc to interrupt"
1924
2156
  : columns >= 70
1925
- ? "Message jade · / commands · @ files · ↑ or ctrl+r for history"
1926
- : "Message jade · / commands · @ files",
2157
+ ? `${placeholder} · ↑ or ctrl+r for history`
2158
+ : placeholder,
1927
2159
  active,
1928
2160
  maxRows: inputRows,
1929
2161
  place,
@@ -1988,8 +2220,8 @@ function Prompt({
1988
2220
  h(Hint, {
1989
2221
  width: hintWidth,
1990
2222
  variants: [
1991
- " ↑↓ select · enter/tab insert the path · the file's content is sent with the message",
1992
- " ↑↓ select · enter/tab insert the path",
2223
+ ...(completion?.hint ? [` ↑↓ select · enter/tab insert · ${completion.hint}`] : []),
2224
+ " ↑↓ select · enter/tab insert",
1993
2225
  " ↑↓ · enter insert",
1994
2226
  ],
1995
2227
  }),
@@ -1998,14 +2230,14 @@ function Prompt({
1998
2230
  ? h(Text, { color: "yellow" }, ` ${notice}`)
1999
2231
  : null,
2000
2232
  // 压在输入框上边框的右边,不占行,出现和消失时下面的内容不跳
2001
- // ! 开头时同一个位置写这一行是什么(刚复制的提示优先)
2233
+ // 以命令的简写开头时同一个位置写这一行是什么(刚复制的提示优先)
2002
2234
  flash
2003
2235
  ? h(Box, { position: "absolute", top: 0, right: 2 }, h(Text, { color: "green" }, ` ${flash} `))
2004
2236
  : bang
2005
2237
  ? h(
2006
2238
  Box,
2007
2239
  { 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 "),
2240
+ h(Text, { color: "magenta" }, ` ${prefixLabel} `),
2009
2241
  )
2010
2242
  : null,
2011
2243
  );
@@ -2019,6 +2251,10 @@ const hintLine = (hint: string) => {
2019
2251
 
2020
2252
  /** @ 补全最多显示几项 */
2021
2253
  const MENTION_ROWS = 8;
2254
+ /** 粘贴超过这么多行或这么多字符时,输入框里只放一个占位符 */
2255
+ const FOLD_PASTE_LINES = 10;
2256
+ const FOLD_PASTE_CHARS = 2000;
2257
+ const PASTED = /\[Pasted text #\d+ (?:\+\d+ lines|\d+ chars)\]/g;
2022
2258
 
2023
2259
  /** 长列表只显示 size 项时,为了让第 selected 项在中间附近,从第几项开始显示 */
2024
2260
  function around(selected: number, total: number, size: number): number {