@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
@@ -1,1772 +1,1670 @@
1
- // 终端界面(Ink):全屏(备用屏幕缓冲区)分三块——顶部标题(版本、模型、目录),中间是对话,
2
- // 自己滚动(滚轮、PgUp/PgDn),底部固定显示运行状态、排队的消息、输入框(或对话框)和状态栏。
3
- // 运行中也能输入:提交的内容由宿主决定立即执行还是排队。
4
- //
5
- // 不用 JSX:插件以 .ts 源码加载,Node 的类型剥离不处理 .tsx,所以组件用 createElement(h)写。
6
1
  import { writeSync } from "node:fs";
7
- import { Box, render, Text, useBoxMetrics, useCursor, useInput, usePaste, useWindowSize, createContext, createElement as h, useContext, useEffect, useReducer, useRef, useState, useSyncExternalStore, } from "./vendor.js";
2
+ import {
3
+ Box,
4
+ render,
5
+ Text,
6
+ useBoxMetrics,
7
+ useCursor,
8
+ useInput,
9
+ usePaste,
10
+ createContext,
11
+ createElement as h,
12
+ useContext,
13
+ useEffect,
14
+ useReducer,
15
+ useRef,
16
+ useState,
17
+ useSyncExternalStore
18
+ } from "./vendor.js";
8
19
  import stringWidth from "string-width";
9
20
  import { mentionAt, mentionText, rankPaths } from "./mentions.js";
10
21
  import { charWidth, edit, empty, layout, moveRow, offsetAt } from "./editor.js";
11
22
  import { expandTabs, markdownStream, softInfo, visibleRow, wrapRows } from "./markdown.js";
12
23
  import { cells, FRAME_MS, Mascot, moodOf, nextChange, title } from "./mascot.js";
13
- import { dim, } from "./screen.js";
14
- /**
15
- * 界面可用的尺寸:宽度比终端少一列。
16
- * Ink 增量重画时每行写成「内容 + ESC[K」;一行正好占满终端宽度时光标停在最后一列(等待换行),
17
- * 紧跟的 ESC[K 会把最后一个字符擦掉,输入框之类的右边框就缺了一块。留出最后一列就不会这样
18
- */
24
+ import {
25
+ dim
26
+ } from "./screen.js";
19
27
  function useScreenSize() {
20
- const { columns, rows } = useWindowSize();
21
- return { columns: Math.max(1, columns - 1), rows };
28
+ const { columns, rows } = useContext(SizeContext);
29
+ return { columns: Math.max(1, columns - 1), rows };
22
30
  }
23
- /** 按键写成 "ctrl+g"、"alt+v"(小写);别的键返回 undefined */
31
+ const SizeContext = createContext({ columns: 80, rows: 24 });
32
+ const RESIZE_SETTLE_MS = 100;
33
+ const RESIZE_FRAME_MS = 200;
34
+ const REPAINT_GAP_MS = 40;
35
+ const REWRAP_BATCH = 1000;
24
36
  function keySpec(input, key) {
25
- if (input.length !== 1)
26
- return undefined;
27
- const c = input.toLowerCase();
28
- if (key.ctrl && !key.meta && /^[a-z]$/.test(c))
29
- return `ctrl+${c}`;
30
- if (key.meta && !key.ctrl && /^[a-z0-9]$/.test(c))
31
- return `alt+${c}`;
32
- return undefined;
37
+ if (input.length !== 1)
38
+ return;
39
+ const c = input.toLowerCase();
40
+ if (key.ctrl && !key.meta && /^[a-z]$/.test(c))
41
+ return `ctrl+${c}`;
42
+ if (key.meta && !key.ctrl && /^[a-z0-9]$/.test(c))
43
+ return `alt+${c}`;
44
+ return;
33
45
  }
34
- /** 对话最多保留这么多行(折行前),超出时丢掉最早的一段 */
35
- const MAX_LINES = 10_000;
36
- /** 按显示宽度折行,保留颜色;每一项是屏幕上的一行,自动折出来的续行开头带记号(markdown.ts),显示之前用 visibleRow 去掉 */
46
+ const MAX_LINES = 1e4;
37
47
  const wrap = wrapRows;
38
- /** Markdown 排好的一行折成屏幕上的行 */
39
48
  const mdRows = (l, width) => typeof l === "string" ? wrap(l, width) : l.render(width);
40
- /** 按宽度截成一行,截掉了内容时以 … 结尾;留出两列给 … 和展开标记 */
41
49
  function oneRow(text, width) {
42
- const rows = wrap(text, Math.max(1, width - 3));
43
- const cut = rows.length > 1;
44
- return { row: cut ? `${rows[0]}${dim("…")}` : rows[0], cut };
50
+ const rows = wrap(text, Math.max(1, width - 3));
51
+ const cut = rows.length > 1;
52
+ return { row: cut ? `${rows[0]}${dim("…")}` : rows[0], cut };
45
53
  }
46
- /** 这一项能不能展开:有折叠的内容,或者收起时被截掉了一部分 */
47
54
  function foldable(l, width) {
48
- if (l.think)
49
- return l.think.text.trim() !== "";
50
- return l.details !== undefined || (Boolean(l.oneRow) && oneRow(l.text, width).cut);
55
+ if (l.think)
56
+ return l.think.text.trim() !== "";
57
+ return l.details !== undefined || Boolean(l.oneRow) && oneRow(l.text, width).cut;
51
58
  }
52
59
  const elapsed = (t) => `${Math.max(0, Math.round(((t.end ?? Date.now()) - t.start) / 1000))}s`;
53
- /** 按显示宽度取 text 末尾最多 cols 列;截掉了开头时以 … 开头 */
54
60
  export function tail(text, cols) {
55
- if (stringWidth(text) <= cols)
56
- return text;
57
- const chars = [...text];
58
- let out = "";
59
- let w = 1;
60
- for (let i = chars.length - 1; i >= 0; i--) {
61
- const cw = stringWidth(chars[i]);
62
- if (w + cw > cols)
63
- break;
64
- out = chars[i] + out;
65
- w += cw;
66
- }
67
- return `…${out}`;
61
+ if (stringWidth(text) <= cols)
62
+ return text;
63
+ const chars = [...text];
64
+ let out = "";
65
+ let w = 1;
66
+ for (let i = chars.length - 1;i >= 0; i--) {
67
+ const cw = stringWidth(chars[i]);
68
+ if (w + cw > cols)
69
+ break;
70
+ out = chars[i] + out;
71
+ w += cw;
72
+ }
73
+ return `…${out}`;
68
74
  }
69
- /**
70
- * 思考收起时的一行(不含展开标记):思考中显示"✻ Thinking 12s · "加上最新一行的末尾,跟着模型实时往前走;
71
- * 结束后显示"✻ Thought for 12s"
72
- */
73
75
  function thinkingRow(t, width) {
74
- if (t.end !== undefined)
75
- return dim(`✻ Thought for ${elapsed(t)}`);
76
- const label = `✻ Thinking ${elapsed(t)}`;
77
- const latest = t.text
78
- .split("\n")
79
- .findLast((l) => l.trim())
80
- ?.trim()
81
- .replace(/\s+/g, " ");
82
- // 留出 " · "、" ▸" 和一列余量
83
- const room = width - stringWidth(label) - 6;
84
- return dim(latest && room >= 8 ? `${label} · ${tail(latest, room)}` : `${label}…`);
76
+ if (t.end !== undefined)
77
+ return dim(`✻ Thought for ${elapsed(t)}`);
78
+ const label = `✻ Thinking ${elapsed(t)}`;
79
+ const latest = t.text.split(`
80
+ `).findLast((l) => l.trim())?.trim().replace(/\s+/g, " ");
81
+ const room = width - stringWidth(label) - 6;
82
+ return dim(latest && room >= 8 ? `${label} · ${tail(latest, room)}` : `${label}…`);
85
83
  }
86
84
  function wrapLine(l, width) {
87
- if (l.render)
88
- return l.render(width);
89
- if (l.think) {
90
- if (!foldable(l, width))
91
- return [thinkingRow(l.think, width)];
92
- if (!l.open)
93
- return [`${thinkingRow(l.think, width)}${dim(" ▸")}`];
94
- const t = l.think;
95
- const title = dim(t.end === undefined ? `✻ Thinking ${elapsed(t)}` : `✻ Thought for ${elapsed(t)}`);
96
- const body = t.text
97
- .replace(/\s+$/, "")
98
- .split("\n")
99
- .map((r) => (r ? dim(` ${r}`) : r))
100
- .join("\n");
101
- return [...wrap(`${title}${dim(" ▾")}`, width), ...wrap(body, width)];
102
- }
85
+ if (l.render)
86
+ return l.render(width);
87
+ if (l.think) {
103
88
  if (!foldable(l, width))
104
- return wrap(l.text, width);
105
- if (!l.open) {
106
- const head = l.oneRow ? oneRow(l.text, width).row : l.text;
107
- return wrap(`${head}${dim(" ▸")}`, width);
108
- }
109
- const head = wrap(`${l.title ?? l.text}${dim(" ▾")}`, width);
110
- return l.details === undefined ? head : [...head, ...wrap(l.details, width)];
89
+ return [thinkingRow(l.think, width)];
90
+ if (!l.open)
91
+ return [`${thinkingRow(l.think, width)}${dim(" ▸")}`];
92
+ const t = l.think;
93
+ const title = dim(t.end === undefined ? `✻ Thinking ${elapsed(t)}` : `✻ Thought for ${elapsed(t)}`);
94
+ const body = t.text.replace(/\s+$/, "").split(`
95
+ `).map((r) => r ? dim(` ${r}`) : r).join(`
96
+ `);
97
+ return [...wrap(`${title}${dim(" ▾")}`, width), ...wrap(body, width)];
98
+ }
99
+ if (!foldable(l, width))
100
+ return wrap(l.text, width);
101
+ if (!l.open) {
102
+ const head = l.oneRow ? oneRow(l.text, width).row : l.text;
103
+ return wrap(`${head}${dim(" ▸")}`, width);
104
+ }
105
+ const head = wrap(`${l.title ?? l.text}${dim(" ▾")}`, width);
106
+ return l.details === undefined ? head : [...head, ...wrap(l.details, width)];
111
107
  }
112
- /** 状态容器:频繁的流式更新合并到一帧再通知界面 */
113
- class Store {
114
- state;
115
- #listeners = new Set();
116
- #timer;
117
- /** 已经完成的输出(折行前);普通的一项一行 */
118
- #lines = [];
119
- /** 按 #width 折好的行 */
120
- #wrapped = [];
121
- /** #wrapped 的每一行属于哪一项 */
122
- #owners = [];
123
- /** 带名字的项,amend 用 */
124
- #named = new Map();
125
- #width = 0;
126
- constructor(status) {
127
- this.state = { version: 0, scroll: 0, progress: [], queued: [], dialogs: [], status };
128
- }
129
- subscribe = (fn) => {
130
- this.#listeners.add(fn);
131
- return () => this.#listeners.delete(fn);
132
- };
133
- get = () => this.state;
134
- update(patch, now = false) {
135
- this.state = { ...this.state, ...patch };
136
- if (now)
137
- return this.#emit();
138
- this.#timer ??= setTimeout(() => this.#emit(), 16);
139
- }
140
- #emit() {
141
- clearTimeout(this.#timer);
142
- this.#timer = undefined;
143
- for (const fn of this.#listeners)
144
- fn();
145
- }
146
- /** 追加普通的行;带 item 时 texts 合成一项(可折叠、可以之后补充),texts 是收起时显示的部分 */
147
- append(texts, item) {
148
- if (texts.length === 0)
149
- return;
150
- const lines = item === undefined
151
- ? texts.flatMap((t) => t.split("\n")).map((text) => ({ text }))
152
- : [{ ...item, text: texts.join("\n") }];
153
- this.#lines.push(...lines);
154
- for (const l of lines)
155
- if (l.id !== undefined)
156
- this.#named.set(l.id, l);
157
- if (this.#lines.length > MAX_LINES) {
158
- this.#lines = this.#lines.slice(-MAX_LINES * 0.8);
159
- this.#named = new Map(this.#lines.flatMap((l) => (l.id === undefined ? [] : [[l.id, l]])));
160
- this.#width = 0;
161
- }
162
- const before = this.#wrapped.length;
163
- if (this.#width)
164
- for (const l of lines)
165
- this.#push(l);
166
- // 往上翻看时新内容不能把正在看的地方顶走
167
- const scroll = this.state.scroll > 0
168
- ? this.state.scroll + this.#wrapped.length - before
169
- : 0;
170
- this.update({ version: this.state.version + 1, scroll });
108
+
109
+ export class Store {
110
+ state;
111
+ #listeners = new Set;
112
+ #timer;
113
+ #lines = [];
114
+ #wrapped = [];
115
+ #owners = [];
116
+ #named = new Map;
117
+ #width = 0;
118
+ #front = 0;
119
+ #generation = 0;
120
+ get front() {
121
+ return this.#front;
122
+ }
123
+ get generation() {
124
+ return this.#generation;
125
+ }
126
+ #unwrapped = 0;
127
+ #rewrap;
128
+ #repaintTimer;
129
+ paused = false;
130
+ constructor(status, size) {
131
+ this.state = { version: 0, scroll: 0, progress: [], queued: [], dialogs: [], status, size };
132
+ }
133
+ subscribe = (fn) => {
134
+ this.#listeners.add(fn);
135
+ return () => this.#listeners.delete(fn);
136
+ };
137
+ get = () => this.state;
138
+ update(patch, now = false) {
139
+ this.state = { ...this.state, ...patch };
140
+ if (now)
141
+ return this.#emit();
142
+ this.#timer ??= setTimeout(() => this.#emit(), 16);
143
+ }
144
+ #emit() {
145
+ clearTimeout(this.#timer);
146
+ this.#timer = undefined;
147
+ if (this.paused)
148
+ return;
149
+ for (const fn of this.#listeners)
150
+ fn();
151
+ }
152
+ resizing() {
153
+ clearTimeout(this.#repaintTimer);
154
+ this.paused = true;
155
+ }
156
+ resized(size) {
157
+ this.#repaintNow({ size });
158
+ }
159
+ repaint() {
160
+ clearTimeout(this.#repaintTimer);
161
+ this.paused = true;
162
+ this.#repaintTimer = setTimeout(() => this.#repaintNow(), REPAINT_GAP_MS);
163
+ }
164
+ #repaintNow(patch = {}) {
165
+ clearTimeout(this.#repaintTimer);
166
+ this.paused = false;
167
+ this.update({ ...patch, repaint: true }, true);
168
+ }
169
+ append(texts, item) {
170
+ if (texts.length === 0)
171
+ return;
172
+ const lines = item === undefined ? texts.flatMap((t) => t.split(`
173
+ `)).map((text) => ({ text })) : [{ ...item, text: texts.join(`
174
+ `) }];
175
+ this.#lines.push(...lines);
176
+ for (const l of lines)
177
+ if (l.id !== undefined)
178
+ this.#named.set(l.id, l);
179
+ if (this.#lines.length > MAX_LINES) {
180
+ this.#lines = this.#lines.slice(-MAX_LINES * 0.8);
181
+ this.#named = new Map(this.#lines.flatMap((l) => l.id === undefined ? [] : [[l.id, l]]));
182
+ this.#width = 0;
183
+ this.#generation++;
171
184
  }
172
- /** 改写带名字的那一项;找不到时返回 false */
173
- amend(id, change) {
174
- const line = this.#named.get(id);
175
- if (!line)
176
- return false;
177
- change(line);
178
- if (!this.#width) {
179
- this.update({ version: this.state.version + 1 });
180
- return true;
181
- }
182
- const first = this.#owners.indexOf(line);
183
- let count = 0;
184
- while (first >= 0 && this.#owners[first + count] === line)
185
- count++;
186
- const rows = wrapLine(line, this.#width);
187
- let scroll = this.state.scroll;
188
- if (first >= 0) {
189
- this.#wrapped.splice(first, count, ...rows);
190
- this.#owners.splice(first, count, ...rows.map(() => line));
191
- // 这一项在往上翻看时的可见部分下面,行数变了要跟着调,看的地方才不动
192
- if (scroll > 0 && first >= this.#wrapped.length - scroll)
193
- scroll += rows.length - count;
194
- }
195
- this.update({ version: this.state.version + 1, scroll });
196
- return true;
185
+ const before = this.#wrapped.length;
186
+ if (this.#width)
187
+ for (const l of lines)
188
+ this.#push(l);
189
+ const scroll = this.state.scroll > 0 ? this.state.scroll + this.#wrapped.length - before : 0;
190
+ this.update({ version: this.state.version + 1, scroll });
191
+ }
192
+ amend(id, change) {
193
+ const line = this.#named.get(id);
194
+ if (!line)
195
+ return false;
196
+ change(line);
197
+ if (!this.#width) {
198
+ this.update({ version: this.state.version + 1 });
199
+ return true;
197
200
  }
198
- #push(l) {
199
- const rows = wrapLine(l, this.#width);
200
- this.#wrapped.push(...rows);
201
- for (const _ of rows)
202
- this.#owners.push(l);
201
+ const first = this.#owners.indexOf(line);
202
+ let count = 0;
203
+ while (first >= 0 && this.#owners[first + count] === line)
204
+ count++;
205
+ const rows = wrapLine(line, this.#width);
206
+ let scroll = this.state.scroll;
207
+ if (first >= 0) {
208
+ this.#wrapped.splice(first, count, ...rows);
209
+ this.#owners.splice(first, count, ...rows.map(() => line));
210
+ if (scroll > 0 && first >= this.#wrapped.length - scroll)
211
+ scroll += rows.length - count;
203
212
  }
204
- /** 按给定宽度折好的全部输出;宽度变了(终端缩放)才重新折行 */
205
- lines(width) {
206
- if (width !== this.#width) {
207
- this.#width = width;
208
- this.#wrapped = [];
209
- this.#owners = [];
210
- for (const l of this.#lines)
211
- this.#push(l);
212
- }
213
- return this.#wrapped;
214
- }
215
- /**
216
- * 展开或收起第 row 行(折好的行)所在的项;不是可折叠项时什么也不做。
217
- * start、view 是当前可见的第一行和可见行数:可见部分的开头保持不动;
218
- * 展开时标题如果在可见部分的底部,往下滚到能看见展开的内容,但标题不滚出去
219
- */
220
- toggle(row, start, view) {
221
- const line = this.#owners[row];
222
- if (!line || !foldable(line, this.#width))
223
- return;
224
- let first = row;
225
- while (first > 0 && this.#owners[first - 1] === line)
226
- first--;
227
- let count = 0;
228
- while (this.#owners[first + count] === line)
229
- count++;
230
- line.open = !line.open;
231
- const rows = wrapLine(line, this.#width);
232
- this.#wrapped.splice(first, count, ...rows);
233
- this.#owners.splice(first, count, ...rows.map(() => line));
234
- const end = Math.max(start + view, line.open ? Math.min(first + rows.length, first + view) : 0);
235
- this.update({
236
- version: this.state.version + 1,
237
- scroll: Math.max(0, this.#wrapped.length - end),
238
- }, true);
239
- }
240
- clear() {
241
- this.#lines = [];
242
- this.#wrapped = [];
243
- this.#owners = [];
244
- this.#named.clear();
245
- this.update({ version: this.state.version + 1, live: undefined, progress: [], scroll: 0, hint: undefined }, true);
213
+ this.update({ version: this.state.version + 1, scroll });
214
+ return true;
215
+ }
216
+ #push(l) {
217
+ const rows = wrapLine(l, this.#width);
218
+ this.#wrapped.push(...rows);
219
+ for (const _ of rows)
220
+ this.#owners.push(l);
221
+ }
222
+ lines(width, need = 1 / 0) {
223
+ if (width !== this.#width) {
224
+ if (this.#width)
225
+ this.#generation++;
226
+ this.#width = width;
227
+ this.#wrapped = [];
228
+ this.#owners = [];
229
+ this.#unwrapped = this.#lines.length;
230
+ clearTimeout(this.#rewrap);
231
+ this.#rewrap = undefined;
246
232
  }
247
- /** 展开或收起最后一个可折叠的项(Ctrl+O);start、view 同 toggle */
248
- toggleLatest(start, view) {
249
- for (let r = this.#owners.length - 1; r >= 0; r--) {
250
- if (foldable(this.#owners[r], this.#width))
251
- return this.toggle(r, start, view);
252
- }
233
+ this.#wrapEarlier((n) => this.#wrapped.length + n >= need, 1 / 0);
234
+ if (this.#unwrapped > 0)
235
+ this.#rewrap ??= setTimeout(this.#rewrapBatch, 0);
236
+ return this.#wrapped;
237
+ }
238
+ #rewrapBatch = () => {
239
+ this.#rewrap = undefined;
240
+ if (!this.#width || this.#unwrapped === 0)
241
+ return;
242
+ const before = this.#wrapped.length;
243
+ this.#wrapEarlier(() => false, REWRAP_BATCH);
244
+ if (this.#unwrapped > 0)
245
+ this.#rewrap = setTimeout(this.#rewrapBatch, 0);
246
+ if (this.#wrapped.length !== before)
247
+ this.update({ version: this.state.version + 1 });
248
+ };
249
+ #wrapEarlier(enough, max) {
250
+ const rows = [];
251
+ const owners = [];
252
+ let count = 0;
253
+ while (this.#unwrapped > 0 && rows.length < max && !enough(count)) {
254
+ const l = this.#lines[--this.#unwrapped];
255
+ const r = wrapLine(l, this.#width);
256
+ rows.push(r);
257
+ owners.push(l);
258
+ count += r.length;
253
259
  }
254
- /** 往上(正数)或往下滚 n 行,不超过 max */
255
- scrollBy(n, max) {
256
- const scroll = Math.max(0, Math.min(max, this.state.scroll + n));
257
- if (scroll !== this.state.scroll)
258
- this.update({ scroll }, true);
260
+ if (rows.length === 0)
261
+ return;
262
+ rows.reverse();
263
+ owners.reverse();
264
+ this.#front += count;
265
+ this.#wrapped = [...rows.flat(), ...this.#wrapped];
266
+ this.#owners = [...owners.flatMap((l, i) => rows[i].map(() => l)), ...this.#owners];
267
+ }
268
+ toggle(row, start, view) {
269
+ const line = this.#owners[row];
270
+ if (!line || !foldable(line, this.#width))
271
+ return;
272
+ let first = row;
273
+ while (first > 0 && this.#owners[first - 1] === line)
274
+ first--;
275
+ let count = 0;
276
+ while (this.#owners[first + count] === line)
277
+ count++;
278
+ line.open = !line.open;
279
+ const rows = wrapLine(line, this.#width);
280
+ this.#wrapped.splice(first, count, ...rows);
281
+ this.#owners.splice(first, count, ...rows.map(() => line));
282
+ const end = Math.max(start + view, line.open ? Math.min(first + rows.length, first + view) : 0);
283
+ this.update({
284
+ version: this.state.version + 1,
285
+ scroll: Math.max(0, this.#wrapped.length - end)
286
+ }, true);
287
+ }
288
+ clear() {
289
+ this.#generation++;
290
+ this.#lines = [];
291
+ this.#wrapped = [];
292
+ this.#owners = [];
293
+ this.#unwrapped = 0;
294
+ this.#named.clear();
295
+ this.update({ version: this.state.version + 1, live: undefined, progress: [], scroll: 0, hint: undefined }, true);
296
+ }
297
+ toggleLatest(start, view) {
298
+ for (let r = this.#owners.length - 1;r >= 0; r--) {
299
+ if (foldable(this.#owners[r], this.#width))
300
+ return this.toggle(r, start, view);
259
301
  }
302
+ }
303
+ scrollBy(n, max) {
304
+ const scroll = Math.max(0, Math.min(max, this.state.scroll + n));
305
+ if (scroll !== this.state.scroll)
306
+ this.update({ scroll }, true);
307
+ }
260
308
  }
261
- /**
262
- * 开关鼠标事件上报(SGR 格式),用来接收滚轮、点击和按住左键拖动(1002)。
263
- * 开着时终端自己不再处理点击,所以对话区的文字由 jade 自己选中和复制(见 Selection)
264
- */
265
- const MOUSE_ON = "\x1b[?1000h\x1b[?1002h\x1b[?1006h";
266
- const MOUSE_OFF = "\x1b[?1006l\x1b[?1002l\x1b[?1000l";
267
- /**
268
- * 光标样式:闪烁的竖线(DECSCUSR 5,再加上 ATT610 的"开始闪烁"给只认它的终端),一眼能看出输入框有焦点;
269
- * 退出时还原成终端自己的默认样式。光标什么时候显示仍由 Ink 管(只有输入框或输入对话框有焦点时才显示)
270
- */
271
- const CURSOR_BLINK = "\x1b[5 q\x1b[?12h";
272
- const CURSOR_RESET = "\x1b[0 q";
273
- /** 工作超过这么久后结束,或者这时弹出要用户选择的对话框,用户多半去做别的了:提醒一下 */
274
- const NOTIFY_AFTER = 10_000;
275
- /** 支持 OSC 9 桌面通知的终端;其他终端什么都不发(不认识的 OSC 9 在有的终端里会弹别的东西) */
309
+ const MOUSE_ON = "\x1B[?1000h\x1B[?1002h\x1B[?1006h";
310
+ const MOUSE_OFF = "\x1B[?1006l\x1B[?1002l\x1B[?1000l";
311
+ const CURSOR_BLINK = "\x1B[5 q\x1B[?12h";
312
+ const CURSOR_RESET = "\x1B[0 q";
313
+ const NOTIFY_AFTER = 1e4;
276
314
  const OSC9_TERMINALS = new Set(["iTerm.app", "WezTerm", "ghostty"]);
277
- /**
278
- * 支持的终端发一条桌面通知。不响铃:铃声在很多终端里(例如 Windows Terminal)是系统的错误提示音,听起来像出错了。
279
- * JADE_NOTIFY=off 关闭
280
- */
281
315
  function notifier(stdout, env = process.env) {
282
- if (env.JADE_NOTIFY === "off" || !OSC9_TERMINALS.has(env.TERM_PROGRAM ?? ""))
283
- return () => { };
284
- return (message) => stdout.write(`\x1b]9;jade: ${message.replace(/[\x00-\x1f\x7f]/g, " ")}\x07`);
316
+ if (env.JADE_NOTIFY === "off" || !OSC9_TERMINALS.has(env.TERM_PROGRAM ?? ""))
317
+ return () => {};
318
+ return (message) => stdout.write(`\x1B]9;jade: ${message.replace(/[\x00-\x1f\x7f]/g, " ")}\x07`);
285
319
  }
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
- */
320
+ const osc0 = (text) => `\x1B]0;${text.replace(/[\x00-\x1f\x7f]/g, " ")}\x07`;
321
+ const TITLE_PUSH = "\x1B[22;0t";
322
+ const TITLE_POP = `${osc0("")}\x1B[23;0t`;
295
323
  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
- };
324
+ if (env.JADE_TITLE === "off")
325
+ return () => {};
326
+ let shown = "";
327
+ const update = () => {
328
+ const s = store.state;
329
+ const now = Date.now();
330
+ const mood = moodOf({ busy: s.busy?.label, asking: s.dialogs.length > 0, doneAt: s.doneAt }, now);
331
+ const dir = s.status.cwd.split(/[\\/]/).filter(Boolean).at(-1) ?? s.status.cwd;
332
+ const text = title(mood, dir, now);
333
+ if (text === shown)
334
+ return;
335
+ shown = text;
336
+ stdout.write(osc0(text));
337
+ };
338
+ stdout.write(TITLE_PUSH);
339
+ update();
340
+ const off = store.subscribe(update);
341
+ const timer = setInterval(() => store.state.busy && update(), 250);
342
+ timer.unref?.();
343
+ return () => {
344
+ off();
345
+ clearInterval(timer);
346
+ stdout.write(TITLE_POP);
347
+ };
321
348
  }
322
349
  export function tuiScreen(opts) {
323
- const stdout = opts.io?.stdout ?? process.stdout;
324
- const store = new Store(opts.status);
325
- const draft = {};
326
- const notify = notifier(stdout);
327
- /** 已经工作了很久(见 NOTIFY_AFTER) */
328
- const longBusy = () => {
329
- const since = store.state.busy?.since;
330
- return since !== undefined && Date.now() - since >= NOTIFY_AFTER;
331
- };
332
- let doneTimer;
333
- /**
334
- * 正在进行的思考:一开始就作为一项放进对话(可以点击展开),之后的增量攒起来,每隔一小段时间改写一次那一项。
335
- * 收起时只占一行,显示模型最新想到了哪里;结束时换成用了多久
336
- */
337
- let thinking;
338
- let thinkingCount = 0;
339
- const redrawThinking = () => {
340
- if (!thinking)
341
- return;
342
- clearTimeout(thinking.timer);
343
- thinking.timer = undefined;
344
- store.amend(thinking.id, () => { });
345
- };
346
- const endThinking = () => {
347
- if (!thinking)
348
- return;
349
- thinking.think.end = Date.now();
350
- redrawThinking();
351
- thinking = undefined;
350
+ const stdout = opts.io?.stdout ?? process.stdout;
351
+ const size = () => ({ columns: stdout.columns || 80, rows: stdout.rows || 24 });
352
+ const store = new Store(opts.status, size());
353
+ let settle;
354
+ let lastResizeFrame = 0;
355
+ const onResize = () => {
356
+ clearTimeout(settle);
357
+ const now = Date.now();
358
+ if (now - lastResizeFrame >= RESIZE_FRAME_MS) {
359
+ lastResizeFrame = now;
360
+ store.resized(size());
361
+ } else
362
+ store.resizing();
363
+ settle = setTimeout(() => {
364
+ lastResizeFrame = Date.now();
365
+ store.resized(size());
366
+ }, RESIZE_SETTLE_MS);
367
+ };
368
+ stdout.on("resize", onResize);
369
+ const draft = {};
370
+ const notify = notifier(stdout);
371
+ const longBusy = () => {
372
+ const since = store.state.busy?.since;
373
+ return since !== undefined && Date.now() - since >= NOTIFY_AFTER;
374
+ };
375
+ let doneTimer;
376
+ let thinking;
377
+ let thinkingCount = 0;
378
+ const redrawThinking = () => {
379
+ if (!thinking)
380
+ return;
381
+ clearTimeout(thinking.timer);
382
+ thinking.timer = undefined;
383
+ store.amend(thinking.id, () => {});
384
+ };
385
+ const endThinking = () => {
386
+ if (!thinking)
387
+ return;
388
+ thinking.think.end = Date.now();
389
+ redrawThinking();
390
+ thinking = undefined;
391
+ };
392
+ let md = markdownStream();
393
+ const appendMd = (lines) => {
394
+ for (const l of lines) {
395
+ if (typeof l === "string")
396
+ store.append([l]);
397
+ else
398
+ store.append([""], { render: l.render });
399
+ }
400
+ };
401
+ const flushLive = (all = false) => {
402
+ if (all)
403
+ endThinking();
404
+ const live = store.state.live;
405
+ if (!live)
406
+ return;
407
+ const lines = live.text.split(`
408
+ `);
409
+ const rest = all ? "" : lines.pop();
410
+ if (all && lines.at(-1) === "")
411
+ lines.pop();
412
+ appendMd(lines.flatMap((l) => md.push(expandTabs(l))));
413
+ if (all) {
414
+ appendMd(md.flush());
415
+ md = markdownStream();
416
+ }
417
+ store.update({ live: rest || !all ? { text: rest, pending: md.pending() } : undefined });
418
+ };
419
+ const ask = (dialog, signal) => new Promise((resolve) => {
420
+ if (signal?.aborted)
421
+ return resolve(undefined);
422
+ const close = () => d.resolve(undefined);
423
+ const d = {
424
+ ...dialog,
425
+ resolve: (v) => {
426
+ signal?.removeEventListener("abort", close);
427
+ store.update({ dialogs: store.state.dialogs.filter((x) => x !== d) }, true);
428
+ resolve(v);
429
+ }
352
430
  };
353
- /** 正文按 Markdown 排版;一段正文结束时换一个新的,清掉代码块、表格的状态 */
354
- let md = markdownStream();
355
- const appendMd = (lines) => {
356
- for (const l of lines) {
357
- if (typeof l === "string")
358
- store.append([l]);
359
- else
360
- store.append([""], { render: l.render });
431
+ signal?.addEventListener("abort", close, { once: true });
432
+ store.update({ dialogs: [...store.state.dialogs, d] }, true);
433
+ });
434
+ const commands = opts.commands;
435
+ const mount = () => {
436
+ stdout.write("\x1B[?1049h\x1B[2J\x1B[H");
437
+ const ours = new Set(stdout.listeners("resize"));
438
+ const mounted = render(h(App, {
439
+ store,
440
+ copy: (text) => void stdout.write(osc52(text)),
441
+ version: opts.version,
442
+ commands: typeof commands === "function" ? commands : () => commands,
443
+ handlers: opts.handlers,
444
+ history: opts.history ?? [],
445
+ draft
446
+ }), {
447
+ exitOnCtrlC: false,
448
+ alternateScreen: true,
449
+ incrementalRendering: true,
450
+ ...opts.io ? { ...opts.io, interactive: true, patchConsole: false } : {}
451
+ });
452
+ for (const l of stdout.listeners("resize"))
453
+ if (!ours.has(l))
454
+ stdout.off("resize", l);
455
+ stdout.write(MOUSE_ON + CURSOR_BLINK);
456
+ return mounted;
457
+ };
458
+ let instance = mount();
459
+ let yielding = Promise.resolve();
460
+ const closeTitle = titleBar(stdout, store);
461
+ const restore = () => {
462
+ try {
463
+ writeSync(1, `${MOUSE_OFF}${CURSOR_RESET}${TITLE_POP}\x1B[?1049l\x1B[?25h`);
464
+ } catch {}
465
+ };
466
+ if (!opts.io)
467
+ process.on("exit", restore);
468
+ return {
469
+ interactive: true,
470
+ log(text, o) {
471
+ flushLive(true);
472
+ store.update({ live: undefined });
473
+ store.append(text.split(`
474
+ `), o?.details !== undefined || o?.id !== undefined ? { details: o.details, id: o.id, oneRow: o.id !== undefined } : undefined);
475
+ },
476
+ amend(id, text, o) {
477
+ flushLive(true);
478
+ const found = store.amend(id, (l) => {
479
+ l.text = `${l.text} ${text}`;
480
+ if (o?.details !== undefined)
481
+ l.details = o.details;
482
+ });
483
+ if (!found)
484
+ store.append([` ${text}`], o?.details !== undefined ? { details: o.details } : undefined);
485
+ },
486
+ progress(id, line) {
487
+ const rest = store.state.progress.filter((p) => p.id !== id);
488
+ store.update({
489
+ progress: line === undefined ? rest : [...rest, { id, line }]
490
+ });
491
+ },
492
+ stream(kind, text) {
493
+ if (kind === "thinking") {
494
+ if (store.state.live) {
495
+ flushLive(true);
496
+ store.update({ live: undefined });
361
497
  }
362
- };
363
- /** 推进正文:已经完整的行排版后移进对话,只把最后不完整的一行留在底部;all 时全部移进去,连同思考一起结束 */
364
- const flushLive = (all = false) => {
365
- if (all)
366
- endThinking();
367
- const live = store.state.live;
368
- if (!live)
498
+ if (!thinking) {
499
+ if (!text.trim())
369
500
  return;
370
- const lines = live.text.split("\n");
371
- const rest = all ? "" : lines.pop();
372
- if (all && lines.at(-1) === "")
373
- lines.pop();
374
- appendMd(lines.flatMap((l) => md.push(expandTabs(l))));
375
- if (all) {
376
- appendMd(md.flush());
377
- md = markdownStream();
501
+ const think = { text: "", start: Date.now() };
502
+ thinking = { id: `\x00thinking-${thinkingCount++}`, think };
503
+ store.append([""], { id: thinking.id, think });
378
504
  }
379
- store.update({ live: rest || !all ? { text: rest, pending: md.pending() } : undefined });
380
- };
381
- /** signal 中止时关掉对话框,返回 undefined */
382
- const ask = (dialog, signal) => new Promise((resolve) => {
383
- if (signal?.aborted)
384
- return resolve(undefined);
385
- const close = () => d.resolve(undefined);
386
- const d = {
387
- ...dialog,
388
- resolve: (v) => {
389
- signal?.removeEventListener("abort", close);
390
- store.update({ dialogs: store.state.dialogs.filter((x) => x !== d) }, true);
391
- resolve(v);
392
- },
393
- };
394
- signal?.addEventListener("abort", close, { once: true });
395
- store.update({ dialogs: [...store.state.dialogs, d] }, true);
396
- });
397
- // 切到备用屏幕后光标还停在原来的位置(不少终端不会自动归位),Ink 从那里往下画第一帧会让屏幕滚动,
398
- // 之后每帧只重写变化的行,整个界面就错位了。所以先自己切过去、清屏、把光标移到左上角
399
- const commands = opts.commands;
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
- : {}),
505
+ thinking.think.text += text;
506
+ thinking.timer ??= setTimeout(redrawThinking, 50);
507
+ return;
508
+ }
509
+ endThinking();
510
+ if (!store.state.live) {
511
+ text = text.replace(/^\n+/, "");
512
+ if (!text)
513
+ return;
514
+ }
515
+ store.update({ live: { text: (store.state.live?.text ?? "") + text } });
516
+ if (text.includes(`
517
+ `))
518
+ flushLive();
519
+ },
520
+ endStream() {
521
+ flushLive(true);
522
+ store.update({ live: undefined });
523
+ },
524
+ busy(label) {
525
+ const current = store.state.busy;
526
+ if (label === undefined) {
527
+ if (longBusy())
528
+ doneTimer ??= setTimeout(() => notify("done"), 300);
529
+ store.update({
530
+ busy: undefined,
531
+ ...current && current.label !== "Interrupting" ? { doneAt: Date.now() } : {}
419
532
  });
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);
427
- // 没走 close 就退出(process.exit)时也要把终端还原,否则会留在备用屏幕、鼠标上报也开着
428
- const restore = () => {
533
+ return;
534
+ }
535
+ clearTimeout(doneTimer);
536
+ doneTimer = undefined;
537
+ store.update({ busy: { label, since: current?.since ?? Date.now() } });
538
+ },
539
+ status(info) {
540
+ store.update({ status: { ...store.state.status, ...info } });
541
+ },
542
+ queued(items) {
543
+ store.update({ queued: [...items] });
544
+ },
545
+ draft: {
546
+ text: () => draft.current?.get() ?? "",
547
+ insert: (text) => draft.current?.apply((s) => edit.insert(s, text.replace(/\r\n?/g, `
548
+ `))),
549
+ set: (text) => {
550
+ const value = text.replace(/\r\n?/g, `
551
+ `);
552
+ draft.current?.apply(() => ({ value, cursor: value.length }));
553
+ },
554
+ hint: (text) => store.update({ hint: text ? text.replace(/\r\n?/g, `
555
+ `) : undefined })
556
+ },
557
+ copy: (text) => void stdout.write(osc52(text)),
558
+ suspend(fn) {
559
+ const run = yielding.then(async () => {
560
+ const typed = draft.current?.get();
561
+ stdout.write(MOUSE_OFF + CURSOR_RESET);
562
+ instance.unmount();
563
+ await instance.waitUntilExit();
564
+ delete draft.current;
429
565
  try {
430
- writeSync(1, `${MOUSE_OFF}${CURSOR_RESET}${TITLE_POP}\x1b[?1049l\x1b[?25h`);
566
+ return await fn();
567
+ } finally {
568
+ instance = mount();
569
+ const input = () => draft.current;
570
+ for (let i = 0;i < 100 && !input(); i++)
571
+ await new Promise((r) => setTimeout(r, 10));
572
+ if (typed)
573
+ input()?.apply(() => ({ value: typed, cursor: typed.length }));
431
574
  }
432
- catch { }
433
- };
434
- if (!opts.io)
435
- process.on("exit", restore);
436
- return {
437
- interactive: true,
438
- log(text, o) {
439
- flushLive(true);
440
- store.update({ live: undefined });
441
- // 带名字的项(工具调用)收起时只占一行,结果用 amend 接在后面
442
- store.append(text.split("\n"), o?.details !== undefined || o?.id !== undefined
443
- ? { details: o.details, id: o.id, oneRow: o.id !== undefined }
444
- : undefined);
445
- },
446
- amend(id, text, o) {
447
- flushLive(true);
448
- const found = store.amend(id, (l) => {
449
- l.text = `${l.text} ${text}`;
450
- if (o?.details !== undefined)
451
- l.details = o.details;
452
- });
453
- if (!found)
454
- store.append([` ${text}`], o?.details !== undefined ? { details: o.details } : undefined);
455
- },
456
- progress(id, line) {
457
- const rest = store.state.progress.filter((p) => p.id !== id);
458
- store.update({
459
- progress: line === undefined ? rest : [...rest, { id, line }],
460
- });
461
- },
462
- stream(kind, text) {
463
- if (kind === "thinking") {
464
- if (store.state.live) {
465
- flushLive(true);
466
- store.update({ live: undefined });
467
- }
468
- if (!thinking) {
469
- if (!text.trim())
470
- return;
471
- const think = { text: "", start: Date.now() };
472
- thinking = { id: `\0thinking-${thinkingCount++}`, think };
473
- store.append([""], { id: thinking.id, think });
474
- }
475
- thinking.think.text += text;
476
- thinking.timer ??= setTimeout(redrawThinking, 50);
477
- return;
478
- }
479
- endThinking();
480
- if (!store.state.live) {
481
- text = text.replace(/^\n+/, "");
482
- if (!text)
483
- return;
484
- }
485
- store.update({ live: { text: (store.state.live?.text ?? "") + text } });
486
- if (text.includes("\n"))
487
- flushLive();
488
- },
489
- endStream() {
490
- flushLive(true);
491
- store.update({ live: undefined });
492
- },
493
- busy(label) {
494
- const current = store.state.busy;
495
- if (label === undefined) {
496
- // 稍等一下再提醒:排队的消息接着开始时(马上又 busy)不算结束
497
- if (longBusy())
498
- doneTimer ??= setTimeout(() => notify("done"), 300);
499
- store.update({
500
- busy: undefined,
501
- ...(current && current.label !== "Interrupting" ? { doneAt: Date.now() } : {}),
502
- });
503
- return;
504
- }
505
- clearTimeout(doneTimer);
506
- doneTimer = undefined;
507
- store.update({ busy: { label, since: current?.since ?? Date.now() } });
508
- },
509
- status(info) {
510
- store.update({ status: { ...store.state.status, ...info } });
511
- },
512
- queued(items) {
513
- store.update({ queued: [...items] });
514
- },
515
- draft: {
516
- text: () => draft.current?.get() ?? "",
517
- insert: (text) => draft.current?.apply((s) => edit.insert(s, text.replace(/\r\n?/g, "\n"))),
518
- set: (text) => {
519
- const value = text.replace(/\r\n?/g, "\n");
520
- draft.current?.apply(() => ({ value, cursor: value.length }));
521
- },
522
- hint: (text) => store.update({ hint: text ? text.replace(/\r\n?/g, "\n") : undefined }),
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
- },
550
- select: (title, choices, o) => {
551
- if (longBusy())
552
- notify(title);
553
- return ask({
554
- kind: "select",
555
- title,
556
- body: o?.body,
557
- choices: choices,
558
- resolve: () => { },
559
- }, o?.signal);
560
- },
561
- input: (title, { signal, ...o } = {}) => ask({
562
- kind: "input",
563
- title,
564
- ...o,
565
- resolve: () => { },
566
- }, signal),
567
- clear() {
568
- clearTimeout(thinking?.timer);
569
- thinking = undefined;
570
- md = markdownStream();
571
- store.clear();
572
- },
573
- async close() {
574
- clearTimeout(doneTimer);
575
- flushLive(true);
576
- store.update({ live: undefined, busy: undefined, progress: [] }, true);
577
- // 等最后一帧画完再卸载;卸载时 Ink 退出备用屏幕
578
- await new Promise((r) => setTimeout(r, 50));
579
- closeTitle();
580
- stdout.write(MOUSE_OFF + CURSOR_RESET);
581
- instance.unmount();
582
- await instance.waitUntilExit();
583
- process.off("exit", restore);
584
- },
585
- };
575
+ });
576
+ yielding = run.catch(() => {});
577
+ return run;
578
+ },
579
+ select: (title, choices, o) => {
580
+ if (longBusy())
581
+ notify(title);
582
+ return ask({
583
+ kind: "select",
584
+ title,
585
+ body: o?.body,
586
+ choices,
587
+ resolve: () => {}
588
+ }, o?.signal);
589
+ },
590
+ input: (title, { signal, ...o } = {}) => ask({
591
+ kind: "input",
592
+ title,
593
+ ...o,
594
+ resolve: () => {}
595
+ }, signal),
596
+ clear() {
597
+ clearTimeout(thinking?.timer);
598
+ thinking = undefined;
599
+ md = markdownStream();
600
+ store.clear();
601
+ },
602
+ async close() {
603
+ clearTimeout(doneTimer);
604
+ flushLive(true);
605
+ store.update({ live: undefined, busy: undefined, progress: [] }, true);
606
+ await new Promise((r) => setTimeout(r, 50));
607
+ closeTitle();
608
+ clearTimeout(settle);
609
+ stdout.off("resize", onResize);
610
+ stdout.write(MOUSE_OFF + CURSOR_RESET);
611
+ instance.unmount();
612
+ await instance.waitUntilExit();
613
+ process.off("exit", restore);
614
+ }
615
+ };
586
616
  }
587
- // ---------- 组件 ----------
588
- /**
589
- * SGR 鼠标事件(Ink 去掉了开头的 ESC):按钮号、列、行(从 1 开始),M 是按下、m 是松开。
590
- * 按钮号去掉 Shift/Alt/Ctrl 位后 0 是左键,64 是滚轮向上,65 向下
591
- */
592
617
  const MOUSE = /^\[<(\d+);(\d+);(\d+)([Mm])$/;
593
- /** 解析鼠标事件:button 是去掉 Shift/Alt/Ctrl 位的按钮号,press 表示按下;x、y 是屏幕上的列和行(从 0 开始) */
594
618
  function mouseEvent(input) {
595
- const m = MOUSE.exec(input);
596
- if (!m)
597
- return undefined;
598
- return { button: Number(m[1]) & ~0b11100, press: m[4] === "M", x: Number(m[2]) - 1, y: Number(m[3]) - 1 };
619
+ const m = MOUSE.exec(input);
620
+ if (!m)
621
+ return;
622
+ return { button: Number(m[1]) & ~28, press: m[4] === "M", x: Number(m[2]) - 1, y: Number(m[3]) - 1 };
599
623
  }
600
624
  const WHEEL_LINES = 3;
601
- /** 按住左键拖动时的按钮号(左键 0 加上移动位 32) */
602
625
  const DRAG = 32;
603
- /** "已复制"的提示显示多久 */
604
626
  const COPIED_MS = 2000;
605
627
  const same = (a, b) => a.row === b.row && a.col === b.col;
606
- /** 第 row 行选中的列 [from, to);这一行不在选区里时 undefined */
607
628
  function selectedCols(s, row) {
608
- const { anchor: a, focus: f } = s;
609
- const [first, last] = a.row < f.row || (a.row === f.row && a.col <= f.col) ? [a, f] : [f, a];
610
- if (row < first.row || row > last.row)
611
- return undefined;
612
- return [row === first.row ? first.col : 0, row === last.row ? last.col + 1 : Infinity];
629
+ const { anchor: a, focus: f } = s;
630
+ const [first, last] = a.row < f.row || a.row === f.row && a.col <= f.col ? [a, f] : [f, a];
631
+ if (row < first.row || row > last.row)
632
+ return;
633
+ return [row === first.row ? first.col : 0, row === last.row ? last.col + 1 : 1 / 0];
613
634
  }
614
- /** ANSI 转义序列(CSI,和以 BEL 或 ST 结束的 OSC,例如超链接) */
615
635
  const ANSI = /\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/y;
616
- const INVERSE = "\x1b[7m";
617
- const INVERSE_OFF = "\x1b[27m";
618
- /**
619
- * 逐个走过一行里的字符:visit 收到每个字符和它是否落在列 [from, to) 里(宽字符跨进去一半也算)。
620
- * 转义序列原样交给 escape
621
- */
636
+ const INVERSE = "\x1B[7m";
637
+ const INVERSE_OFF = "\x1B[27m";
622
638
  function walk(line, from, to, visit, escape) {
623
- let col = 0;
624
- for (let i = 0; i < line.length;) {
625
- ANSI.lastIndex = i;
626
- const m = ANSI.exec(line);
627
- if (m) {
628
- escape?.(m[0]);
629
- i += m[0].length;
630
- continue;
631
- }
632
- const ch = String.fromCodePoint(line.codePointAt(i));
633
- const w = charWidth(ch);
634
- visit(ch, col < to && col + Math.max(w, 1) > from);
635
- col += w;
636
- i += ch.length;
639
+ let col = 0;
640
+ for (let i = 0;i < line.length; ) {
641
+ ANSI.lastIndex = i;
642
+ const m = ANSI.exec(line);
643
+ if (m) {
644
+ escape?.(m[0]);
645
+ i += m[0].length;
646
+ continue;
637
647
  }
648
+ const ch = String.fromCodePoint(line.codePointAt(i));
649
+ const w = charWidth(ch);
650
+ visit(ch, col < to && col + Math.max(w, 1) > from);
651
+ col += w;
652
+ i += ch.length;
653
+ }
638
654
  }
639
- /** 给一行里选中的部分加上反色;中间的转义序列可能关掉反色,之后重新打开 */
640
655
  function highlight(line, from, to) {
641
- let out = "";
642
- let on = false;
643
- walk(line, from, to, (ch, inside) => {
644
- if (inside !== on)
645
- out += inside ? INVERSE : INVERSE_OFF;
646
- on = inside;
647
- out += ch;
648
- }, (seq) => (out += seq + (on ? INVERSE : "")));
649
- return out + (on ? INVERSE_OFF : "");
656
+ let out = "";
657
+ let on = false;
658
+ walk(line, from, to, (ch, inside) => {
659
+ if (inside !== on)
660
+ out += inside ? INVERSE : INVERSE_OFF;
661
+ on = inside;
662
+ out += ch;
663
+ }, (seq) => out += seq + (on ? INVERSE : ""));
664
+ return out + (on ? INVERSE_OFF : "");
650
665
  }
651
- /**
652
- * 选中的纯文字:每行去掉行尾空白,用换行连起来。自动折行出来的续行接回上一行(补上折行时去掉的空格、
653
- * 跳过排版加的缩进),所以一行很长的命令复制出来还是一行。row 给的是带续行记号的行
654
- */
655
666
  export function selectedText(s, row) {
656
- const lines = [];
657
- const { anchor: a, focus: f } = s;
658
- const first = Math.min(a.row, f.row);
659
- for (let r = first; r <= Math.max(a.row, f.row); r++) {
660
- const [from, to] = selectedCols(s, r);
661
- const { text: line, soft, gap, indent } = softInfo(row(r) ?? "");
662
- let text = "";
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(/^┃ ?/, ""));
670
- }
671
- return lines.map((l) => l.trimEnd()).join("\n");
667
+ const lines = [];
668
+ const { anchor: a, focus: f } = s;
669
+ const first = Math.min(a.row, f.row);
670
+ for (let r = first;r <= Math.max(a.row, f.row); r++) {
671
+ const [from, to] = selectedCols(s, r);
672
+ const { text: line, soft, gap, indent } = softInfo(row(r) ?? "");
673
+ let text = "";
674
+ walk(line, Math.max(from, soft ? indent : 0), to, (ch, inside) => void (inside && (text += ch)));
675
+ if (soft && r > first)
676
+ lines[lines.length - 1] += " ".repeat(gap) + text;
677
+ else
678
+ lines.push(text.replace(/^┃ ?/, ""));
679
+ }
680
+ return lines.map((l) => l.trimEnd()).join(`
681
+ `);
672
682
  }
673
- /** OSC 52:让终端把文字放进系统剪贴板(Windows Terminal、iTerm2、kitty、WezTerm 等支持) */
674
- const osc52 = (text) => `\x1b]52;c;${Buffer.from(text, "utf8").toString("base64")}\x07`;
675
- /**
676
- * 输入框和对话框用:有选中的文字时 Ctrl+C 只取消选中(很多人选完习惯按 Ctrl+C 复制),
677
- * 不中断模型、不清空输入、不取消对话框
678
- */
679
- const SelectionContext = createContext({ active: () => false, clear: () => { } });
680
- /** 终端矮于这么多行时标题只占一行 */
683
+ const osc52 = (text) => `\x1B]52;c;${Buffer.from(text, "utf8").toString("base64")}\x07`;
684
+ const SelectionContext = createContext({ active: () => false, clear: () => {} });
685
+ function viewport(total, height, wanted) {
686
+ const scrolled = wanted > 0 && total > height;
687
+ const view = Math.max(0, scrolled ? height - 1 : height);
688
+ const max = total > height ? total - Math.max(0, height - 1) : 0;
689
+ const scroll = Math.min(wanted, max);
690
+ const end = total - scroll;
691
+ return { scrolled, view, max, scroll, end, start: Math.max(0, end - view) };
692
+ }
693
+ const DRAG_SCROLL_MS = 50;
694
+ const DRAG_SCROLL_MAX = 8;
681
695
  const COMPACT_ROWS = 24;
682
- /**
683
- * 底部的菜单、选择框、多行输入最多占多少行:终端很矮时整个界面会高过终端,
684
- * 超出的部分被裁掉,输入框的边框和状态栏就显示不全了
685
- */
686
696
  const roomFor = (rows, max) => Math.max(3, Math.min(max, Math.floor((rows - 10) / 2)));
687
- function App({ store, copy, version, commands, handlers, history, draft, }) {
688
- const state = useSyncExternalStore(store.subscribe, store.get);
689
- const dialog = state.dialogs[0];
690
- const { columns, rows } = useScreenSize();
691
- const compact = rows < COMPACT_ROWS;
692
- // 运行中每一帧(FRAME_MS)整体重画一次,推动转圈和吉祥物的动画。不能让 Spinner、吉祥物自己重画:
693
- // Ink 只在输入框也跟着提交的那一帧保留光标,否则把光标藏起来,运行中光标就不见了
694
- const [ticks, tick] = useReducer((n) => n + 1, 0);
695
- const busy = state.busy !== undefined;
696
- useEffect(() => {
697
- if (!busy)
698
- return;
699
- const t = setInterval(tick, FRAME_MS);
700
- return () => clearInterval(t);
701
- }, [busy]);
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]);
716
- // 对话区占掉标题和底部之外的全部高度,只画能看见的那几行
717
- const ref = useRef(null);
718
- const { height, top } = useBoxMetrics(ref);
719
- const width = Math.max(10, columns - 2);
720
- const done = store.lines(width);
721
- // 还没结束的流式块和正在运行的工具的进度:思考只显示最新的一行,进度每个工具一行
722
- const live = [
723
- ...(state.live?.pending ?? []).flatMap((l) => mdRows(l, width)),
724
- ...(state.live?.text ? wrap(state.live.text, width) : []),
725
- ...state.progress.map((p) => oneRow(p.line, width).row),
726
- ];
727
- const total = done.length + live.length;
728
- // 往上翻看时最后一行用来提示
729
- const scrolled = state.scroll > 0 && total > height;
730
- const view = Math.max(0, scrolled ? height - 1 : height);
731
- const max = Math.max(0, total - view);
732
- const scroll = Math.min(state.scroll, max);
733
- const end = total - scroll;
734
- const start = Math.max(0, end - view);
735
- const shown = [
736
- ...done.slice(start, Math.min(end, done.length)),
737
- ...live.slice(Math.max(0, start - done.length), Math.max(0, end - done.length)),
738
- ];
739
- const page = Math.max(1, view - 2);
740
- // 选中文字:按下左键记下位置,拖动时更新,松开时复制;点一下(没拖动)还是展开或收起那一项。
741
- // 几个事件可能在同一块输入里连着到达,来不及重画,所以另外用 ref 记着最新的值
742
- const [selection, setSelectionState] = useState();
743
- const selected = useRef(undefined);
744
- const pressed = useRef(undefined);
745
- const setSelection = (s) => {
746
- selected.current = s;
747
- setSelectionState(s);
748
- };
749
- const [selectionApi] = useState(() => ({ active: () => selected.current !== undefined, clear: () => setSelection(undefined) }));
750
- // 宽度变了,行重新折过,原来的位置对不上了
751
- useEffect(() => setSelection(undefined), [width]);
752
- const rowAt = (i) => (i < done.length ? done[i] : live[i - done.length]);
753
- // 复制之后在输入框下面提示一会儿
754
- const [copied, setCopied] = useState();
755
- const copiedTimer = useRef(undefined);
756
- useEffect(() => () => clearTimeout(copiedTimer.current), []);
757
- /** 输入框文字在屏幕上的位置(Prompt 里的 EditableText 每次渲染时写入) */
758
- const inputPlace = useRef(undefined);
759
- const copySelection = (s) => copyText(selectedText(s, rowAt));
760
- const copyText = (text) => {
761
- copy(text);
762
- clearTimeout(copiedTimer.current);
763
- setCopied(`Copied ${[...text].length} characters to the clipboard`);
764
- copiedTimer.current = setTimeout(() => setCopied(undefined), COPIED_MS);
765
- };
766
- // Ink 增量渲染只用相对光标移动,第一帧起点一旦偏了(启动时终端尺寸还没稳定、窗口缩放、别的输出插进来),
767
- // 之后每帧都会画错行。尺寸变化后和按 Ctrl+L 时让一帧比终端高,Ink 会清屏从左上角整帧重画(包在同步输出里),下一帧再恢复。
768
- // 启动时不重画:第一帧之前已经清屏、光标在左上角;这两次清屏在不支持同步输出的终端上(Windows 上常见)看得出闪一下
769
- const [redraws, setRedraws] = useState(0);
770
- const [repaint, setRepaint] = useState(false);
771
- const mounted = useRef(false);
772
- useEffect(() => {
773
- if (!mounted.current) {
774
- mounted.current = true;
775
- return;
697
+ function App({
698
+ store,
699
+ copy,
700
+ version,
701
+ commands,
702
+ handlers,
703
+ history,
704
+ draft
705
+ }) {
706
+ const state = useSyncExternalStore(store.subscribe, store.get);
707
+ const dialog = state.dialogs[0];
708
+ const columns = Math.max(1, state.size.columns - 1);
709
+ const rows = state.size.rows;
710
+ const compact = rows < COMPACT_ROWS;
711
+ const [ticks, tickNow] = useReducer((n) => n + 1, 0);
712
+ const tick = () => store.paused || tickNow();
713
+ const busy = state.busy !== undefined;
714
+ useEffect(() => {
715
+ if (!busy)
716
+ return;
717
+ const t = setInterval(tick, FRAME_MS);
718
+ return () => clearInterval(t);
719
+ }, [busy]);
720
+ const now = Date.now();
721
+ const mood = moodOf({ busy: state.busy?.label, asking: dialog !== undefined, doneAt: state.doneAt }, now);
722
+ const mascot = useRef(undefined);
723
+ mascot.current ??= new Mascot;
724
+ const showBot = !compact && columns >= 50;
725
+ const bot = showBot ? mascot.current.frame(mood, now) : undefined;
726
+ const moving = showBot && mascot.current.moving(mood, now);
727
+ useEffect(() => {
728
+ if (busy || !showBot)
729
+ return;
730
+ const t = setTimeout(tick, nextChange(mood, Date.now(), state.doneAt, moving));
731
+ return () => clearTimeout(t);
732
+ }, [busy, showBot, ticks, mood, moving, state.doneAt, state.size]);
733
+ const ref = useRef(null);
734
+ const { height, top } = useBoxMetrics(ref);
735
+ const width = Math.max(10, columns - 2);
736
+ const done = store.lines(width, state.scroll + 2 * rows);
737
+ const front = store.front;
738
+ const live = [
739
+ ...(state.live?.pending ?? []).flatMap((l) => mdRows(l, width)),
740
+ ...state.live?.text ? wrap(state.live.text, width) : [],
741
+ ...state.progress.map((p) => oneRow(p.line, width).row)
742
+ ];
743
+ const total = done.length + live.length;
744
+ const { scrolled, view, max, scroll, end, start } = viewport(total, height, state.scroll);
745
+ const shown = [
746
+ ...done.slice(start, Math.min(end, done.length)),
747
+ ...live.slice(Math.max(0, start - done.length), Math.max(0, end - done.length))
748
+ ];
749
+ const page = Math.max(1, view - 2);
750
+ const [selection, setSelectionState] = useState();
751
+ const selected = useRef(undefined);
752
+ const pressed = useRef(undefined);
753
+ const setSelection = (s) => {
754
+ selected.current = s;
755
+ setSelectionState(s);
756
+ };
757
+ const [selectionApi] = useState(() => ({ active: () => selected.current !== undefined, clear: () => setSelection(undefined) }));
758
+ const geometry = useRef({ total, height, front });
759
+ geometry.current = { total, height, front };
760
+ const dragScroll = useRef(undefined);
761
+ const stopDragScroll = () => {
762
+ clearInterval(dragScroll.current?.timer);
763
+ dragScroll.current = undefined;
764
+ };
765
+ const dragScrollTick = () => {
766
+ const d = dragScroll.current;
767
+ const anchor = pressed.current;
768
+ if (!d || !anchor)
769
+ return stopDragScroll();
770
+ const g = geometry.current;
771
+ store.scrollBy(d.dir * d.lines, viewport(g.total, g.height, 0).max);
772
+ const v = viewport(g.total, g.height, store.get().scroll);
773
+ if (v.end <= v.start)
774
+ return;
775
+ const focus = { row: (d.dir > 0 ? v.start : v.end - 1) - g.front, col: d.col };
776
+ const s = selected.current;
777
+ if (!s || !same(s.focus, focus))
778
+ setSelection({ anchor, focus });
779
+ };
780
+ useEffect(() => stopDragScroll, []);
781
+ useEffect(() => {
782
+ stopDragScroll();
783
+ pressed.current = undefined;
784
+ setSelection(undefined);
785
+ }, [width, store.generation]);
786
+ const rowAt = (i) => i < done.length ? done[i] : live[i - done.length];
787
+ const [copied, setCopied] = useState();
788
+ const copiedTimer = useRef(undefined);
789
+ useEffect(() => () => clearTimeout(copiedTimer.current), []);
790
+ const inputPlace = useRef(undefined);
791
+ const copySelection = (s) => copyText(selectedText(s, (i) => rowAt(i + front)));
792
+ const copyText = (text) => {
793
+ copy(text);
794
+ clearTimeout(copiedTimer.current);
795
+ setCopied(`Copied ${[...text].length} characters to the clipboard`);
796
+ copiedTimer.current = setTimeout(() => setCopied(undefined), COPIED_MS);
797
+ };
798
+ const repaint = state.repaint === true;
799
+ useEffect(() => {
800
+ if (repaint)
801
+ store.update({ repaint: false });
802
+ }, [repaint]);
803
+ useInput((input, key) => {
804
+ if (key.ctrl && input === "l")
805
+ return store.repaint();
806
+ if (key.ctrl && input === "o")
807
+ return store.toggleLatest(start, view);
808
+ const mouse = mouseEvent(input);
809
+ if (mouse) {
810
+ const at = (clamp) => {
811
+ const i = mouse.y - top;
812
+ if (!clamp && (i < 0 || i >= shown.length))
813
+ return;
814
+ return { row: start + Math.min(Math.max(i, 0), shown.length - 1) - front, col: Math.max(0, mouse.x - 1) };
815
+ };
816
+ const input = inputPlace.current;
817
+ const overInput = input && input.total > input.rows && mouse.y >= input.y - 1 && mouse.y <= input.y + input.rows;
818
+ if ((mouse.button === 64 || mouse.button === 65) && overInput)
819
+ return;
820
+ if (mouse.button === 64)
821
+ store.scrollBy(WHEEL_LINES, max);
822
+ else if (mouse.button === 65)
823
+ store.scrollBy(-WHEEL_LINES, max);
824
+ else if (mouse.button === 0 && mouse.press) {
825
+ stopDragScroll();
826
+ if (selected.current)
827
+ setSelection(undefined);
828
+ pressed.current = at(false);
829
+ } else if (mouse.button === DRAG && pressed.current) {
830
+ setSelection({ anchor: pressed.current, focus: at(true) });
831
+ const above = top - mouse.y;
832
+ const below = mouse.y - (top + shown.length - 1);
833
+ const dir = above > 0 ? 1 : below > 0 && shown.length >= view ? -1 : 0;
834
+ if (dir === 0)
835
+ stopDragScroll();
836
+ else {
837
+ const lines = Math.min(DRAG_SCROLL_MAX, dir > 0 ? above : below);
838
+ const col = Math.max(0, mouse.x - 1);
839
+ if (dragScroll.current)
840
+ Object.assign(dragScroll.current, { dir, lines, col });
841
+ else {
842
+ dragScroll.current = { timer: setInterval(dragScrollTick, DRAG_SCROLL_MS), dir, lines, col };
843
+ dragScrollTick();
844
+ }
776
845
  }
777
- const t = setTimeout(() => setRepaint(true), 100);
778
- return () => clearTimeout(t);
779
- }, [columns, rows, redraws]);
780
- useEffect(() => {
781
- if (!repaint)
782
- return;
783
- // 要比 Ink 的帧间隔长,否则这一帧会被合并掉
784
- const t = setTimeout(() => setRepaint(false), 50);
785
- return () => clearTimeout(t);
786
- }, [repaint]);
787
- useInput((input, key) => {
788
- if (key.ctrl && input === "l")
789
- return setRedraws((n) => n + 1);
790
- // 展开或收起最近的一项(工具结果、思考、检查报告),鼠标点不了时也能看完整内容
791
- if (key.ctrl && input === "o")
792
- return store.toggleLatest(start, view);
793
- const mouse = mouseEvent(input);
794
- if (mouse) {
795
- // 对话区里的位置;clamp 时拖出对话区停在第一行或最后一行,否则在对话区外返回 undefined
796
- const at = (clamp) => {
797
- const i = mouse.y - top;
798
- if (!clamp && (i < 0 || i >= shown.length))
799
- return undefined;
800
- return { row: start + Math.min(Math.max(i, 0), shown.length - 1), col: Math.max(0, mouse.x - 1) };
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;
807
- if (mouse.button === 64)
808
- store.scrollBy(WHEEL_LINES, max);
809
- else if (mouse.button === 65)
810
- store.scrollBy(-WHEEL_LINES, max);
811
- else if (mouse.button === 0 && mouse.press) {
812
- if (selected.current)
813
- setSelection(undefined);
814
- pressed.current = at(false);
815
- }
816
- else if (mouse.button === DRAG && pressed.current) {
817
- setSelection({ anchor: pressed.current, focus: at(true) });
818
- }
819
- else if (mouse.button === 0 && !mouse.press && pressed.current) {
820
- const p = pressed.current;
821
- pressed.current = undefined;
822
- const s = selected.current;
823
- if (s && !same(s.anchor, s.focus))
824
- copySelection(s);
825
- else {
826
- if (s)
827
- setSelection(undefined);
828
- // 点在对话区里已经完成的输出上:展开或收起那一项
829
- if (p.row < done.length)
830
- store.toggle(p.row, start, view);
831
- }
832
- }
833
- return;
834
- }
835
- // 按别的键取消选中;Ctrl+C 由输入框和对话框处理(见 SelectionContext)
836
- if (selected.current && !(key.ctrl && input === "c"))
846
+ } else if (mouse.button === 0 && !mouse.press && pressed.current) {
847
+ stopDragScroll();
848
+ const p = pressed.current;
849
+ pressed.current = undefined;
850
+ const s = selected.current;
851
+ if (s && !same(s.anchor, s.focus))
852
+ copySelection(s);
853
+ else {
854
+ if (s)
837
855
  setSelection(undefined);
838
- // 选择框自己用 PgUp/PgDn 翻选项
839
- if (dialog?.kind === "select")
840
- return;
841
- if (key.pageUp)
842
- store.scrollBy(page, max);
843
- else if (key.pageDown)
844
- store.scrollBy(-page, max);
845
- else if (key.ctrl && key.home)
846
- store.scrollBy(max, max);
847
- else if (key.ctrl && key.end)
848
- store.scrollBy(-max, max);
849
- });
850
- // 总高度要比终端少一行,否则 Ink 认为输出占满了屏幕,每帧清屏重画。
851
- // 重画那一帧上下各垫一行空白:终端把顶上那行滚出去后,看到的和平时逐行一样,所以不会闪。
852
- // 只做纵向裁剪:每行都已按宽度折好或截断,横向裁剪会让 Ink 每帧对每一行再切一遍 ANSI 字符串
853
- return h(SelectionContext.Provider, { value: selectionApi }, h(Box, {
854
- flexDirection: "column",
855
- width: columns,
856
- height: repaint ? rows + 1 : Math.max(1, rows - 1),
857
- paddingY: repaint ? 1 : 0,
858
- overflowY: "hidden",
859
- },
860
- // 垫的空白放在外层:里面这层在重画那一帧和平时一样高,对话区的 top(相对父节点)不变,点击换算的行号不会差一行
861
- h(Box, { flexDirection: "column", flexGrow: 1, overflowY: "hidden" }, h(Header, { status: state.status, version, compact, bot }), h(Box, {
862
- ref,
863
- flexDirection: "column",
864
- flexGrow: 1,
865
- flexShrink: 1,
866
- flexBasis: 0,
867
- overflowY: "hidden",
868
- paddingX: 1,
869
- }, shown.map((raw, i) => {
870
- // 续行的记号不显示
871
- const l = visibleRow(raw);
872
- const cols = selection && selectedCols(selection, start + i);
873
- return h(Text, { key: i, wrap: "truncate-end" }, cols ? highlight(l || " ", ...cols) : l || " ");
874
- }), scrolled
875
- ? h(Text, { dimColor: true, wrap: "truncate-end" }, `── ↓ ${scroll} more lines · wheel / PgDn to scroll · ctrl+end to jump to the bottom ──`)
876
- : null), h(Box, { flexDirection: "column", flexShrink: 0 }, state.busy && !dialog ? h(Spinner, { label: state.busy.label, since: state.busy.since }) : null, state.queued.map((q, i) => h(Text, { key: i, dimColor: true, wrap: "truncate-end" }, " ↳ queued: ", q.replace(/\s+/g, " "))), dialog
877
- ? dialog.kind === "select"
878
- ? h(SelectDialog, { key: dialogKey(dialog), dialog })
879
- : h(InputDialog, { key: dialogKey(dialog), dialog })
880
- : null, h(Prompt, {
881
- commands,
882
- handlers,
883
- history,
884
- bridge: draft,
885
- hint: state.hint,
886
- onHintDone: () => store.update({ hint: undefined }),
887
- busy: Boolean(state.busy),
888
- queued: state.queued.length > 0,
889
- active: !dialog,
890
- onSubmit: () => store.scrollBy(-max, max),
891
- flash: copied,
892
- place: inputPlace,
893
- onCopy: copyText,
894
- }), h(StatusBar, { status: state.status, width: Math.max(10, columns - 2) })))));
856
+ if (p.row + front < done.length)
857
+ store.toggle(p.row + front, start, view);
858
+ }
859
+ }
860
+ return;
861
+ }
862
+ if (selected.current && !(key.ctrl && input === "c")) {
863
+ stopDragScroll();
864
+ pressed.current = undefined;
865
+ setSelection(undefined);
866
+ }
867
+ if (dialog?.kind === "select")
868
+ return;
869
+ if (key.pageUp)
870
+ store.scrollBy(page, max);
871
+ else if (key.pageDown)
872
+ store.scrollBy(-page, max);
873
+ else if (key.ctrl && key.home)
874
+ store.scrollBy(max, max);
875
+ else if (key.ctrl && key.end)
876
+ store.scrollBy(-max, max);
877
+ });
878
+ return h(SizeContext.Provider, { value: state.size }, h(SelectionContext.Provider, { value: selectionApi }, h(Box, {
879
+ flexDirection: "column",
880
+ width: columns,
881
+ height: repaint ? rows + 1 : Math.max(1, rows - 1),
882
+ paddingY: repaint ? 1 : 0,
883
+ overflowY: "hidden"
884
+ }, h(Box, { flexDirection: "column", flexGrow: 1, overflowY: "hidden" }, h(Header, { status: state.status, version, compact, bot, completions: handlers.completions?.() ?? [] }), h(Box, {
885
+ ref,
886
+ flexDirection: "column",
887
+ flexGrow: 1,
888
+ flexShrink: 1,
889
+ flexBasis: 0,
890
+ overflowY: "hidden",
891
+ paddingX: 1
892
+ }, shown.map((raw, i) => {
893
+ const l = visibleRow(raw);
894
+ const cols = selection && selectedCols(selection, start + i - front);
895
+ return h(Text, { key: i, wrap: "truncate-end" }, cols ? highlight(l || " ", ...cols) : l || " ");
896
+ }), scrolled ? h(Text, { dimColor: true, wrap: "truncate-end" }, `── ↓ ${scroll} more lines · wheel / PgDn to scroll · ctrl+end to jump to the bottom ──`) : null), h(Box, { flexDirection: "column", flexShrink: 0 }, state.busy && !dialog ? h(Spinner, { label: state.busy.label, since: state.busy.since }) : null, dialog ? null : (state.status.panels ?? []).flatMap((p) => p.text.split(`
897
+ `).map((l, i) => h(Text, { key: `${p.plugin}:${i}`, wrap: "truncate-end" }, " ", l || " "))), state.queued.map((q, i) => h(Text, { key: i, dimColor: true, wrap: "truncate-end" }, " ↳ queued: ", q.replace(/\s+/g, " "))), dialog ? dialog.kind === "select" ? h(SelectDialog, { key: dialogKey(dialog), dialog }) : h(InputDialog, { key: dialogKey(dialog), dialog }) : null, h(Prompt, {
898
+ commands,
899
+ handlers,
900
+ history,
901
+ bridge: draft,
902
+ hint: state.hint,
903
+ onHintDone: () => store.update({ hint: undefined }),
904
+ busy: Boolean(state.busy),
905
+ queued: state.queued.length > 0,
906
+ active: !dialog,
907
+ onSubmit: () => store.scrollBy(-max, max),
908
+ flash: copied,
909
+ place: inputPlace,
910
+ onCopy: copyText
911
+ }), h(StatusBar, { status: state.status, width: Math.max(10, columns - 2) }))))));
895
912
  }
896
- /**
897
- * 标题左边的吉祥物(见 mascot.ts):玉做的团子,按 mood 换表情和动画,三行高,正好和右边三行文字并排
898
- */
899
913
  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)))));
914
+ 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)))));
901
915
  }
902
- function Header({ status, version, compact, bot, }) {
903
- // 模型 · 目录 (分支)
904
- const where = [
905
- h(Text, { key: "model", color: "cyan" }, status.model),
906
- h(Text, { key: "sep", dimColor: true }, " · "),
907
- h(Text, { key: "cwd" }, status.cwd),
908
- status.branch ? h(Text, { key: "branch", color: "magenta" }, ` (${status.branch})`) : null,
909
- ];
910
- const name = h(Text, { key: "name", color: "cyan", bold: true }, "jade");
911
- if (compact)
912
- return h(Box, { flexShrink: 0, paddingX: 1 }, h(Text, { wrap: "truncate-end" }, name, h(Text, { key: "dot", dimColor: true }, " · "), ...where));
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")));
916
+ function Header({
917
+ completions,
918
+ status,
919
+ version,
920
+ compact,
921
+ bot
922
+ }) {
923
+ const where = [
924
+ h(Text, { key: "model", color: "cyan" }, status.model),
925
+ h(Text, { key: "sep", dimColor: true }, " · "),
926
+ h(Text, { key: "cwd" }, status.cwd),
927
+ status.branch ? h(Text, { key: "branch", color: "magenta" }, ` (${status.branch})`) : null
928
+ ];
929
+ const name = h(Text, { key: "name", color: "cyan", bold: true }, "jade");
930
+ if (compact)
931
+ return h(Box, { flexShrink: 0, paddingX: 1 }, h(Text, { wrap: "truncate-end" }, name, h(Text, { key: "dot", dimColor: true }, " · "), ...where));
932
+ 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", ...completions.map((c) => `${c.trigger} ${c.label}`)].join(" · "))));
914
933
  }
915
- const dialogIds = new WeakMap();
934
+ const dialogIds = new WeakMap;
916
935
  let dialogCounter = 0;
917
936
  function dialogKey(d) {
918
- if (!dialogIds.has(d))
919
- dialogIds.set(d, dialogCounter++);
920
- return dialogIds.get(d);
937
+ if (!dialogIds.has(d))
938
+ dialogIds.set(d, dialogCounter++);
939
+ return dialogIds.get(d);
921
940
  }
922
941
  const FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
923
- /** 转圈动画由 App 每 100ms 整体重画一次推动(见 App 里的 tick),这里只按当前时间画 */
924
942
  function Spinner({ label, since }) {
925
- const now = Date.now();
926
- const seconds = Math.floor((now - since) / 1000);
927
- return h(Box, { marginTop: 1 }, h(Text, { wrap: "truncate-end" }, h(Text, { color: "cyan" }, `${FRAMES[Math.floor(now / 100) % FRAMES.length]} `), h(Text, null, `${label}… `), h(Text, { dimColor: true }, `(${seconds}s · esc to interrupt)`)));
943
+ const now = Date.now();
944
+ const seconds = Math.floor((now - since) / 1000);
945
+ return h(Box, { marginTop: 1 }, h(Text, { wrap: "truncate-end" }, h(Text, { color: "cyan" }, `${FRAMES[Math.floor(now / 100) % FRAMES.length]} `), h(Text, null, `${label}… `), h(Text, { dimColor: true }, `(${seconds}s · esc to interrupt)`)));
928
946
  }
929
- /** 在 width 列里放下尽量多的内容(保持原来的顺序) */
947
+ const TONE = { ok: "green", warn: "yellow", error: "red", accent: "magenta" };
930
948
  export function fitSegments(segments, width) {
931
- const kept = segments.map((s) => ({ ...s }));
932
- const total = () => kept.reduce((n, s, i) => n + stringWidth(s.text) + (i ? 3 : 0), 0);
933
- const steps = kept
934
- .flatMap((s) => [
935
- ...(s.short !== undefined && s.shortAt !== undefined
936
- ? [{ s, at: s.shortAt, drop: false }]
937
- : []),
938
- ...(s.dropAt !== undefined ? [{ s, at: s.dropAt, drop: true }] : []),
939
- ])
940
- .sort((a, b) => b.at - a.at);
941
- for (const { s, drop } of steps) {
942
- if (total() <= width)
943
- break;
944
- if (drop)
945
- kept.splice(kept.indexOf(s), 1);
946
- else
947
- s.text = s.short;
948
- }
949
- return kept;
949
+ const kept = segments.map((s) => ({ ...s }));
950
+ const total = () => kept.reduce((n, s, i) => n + stringWidth(s.text) + (i ? 3 : 0), 0);
951
+ const steps = kept.flatMap((s) => [
952
+ ...s.short !== undefined && s.shortAt !== undefined ? [{ s, at: s.shortAt, drop: false }] : [],
953
+ ...s.dropAt !== undefined ? [{ s, at: s.dropAt, drop: true }] : []
954
+ ]).sort((a, b) => b.at - a.at);
955
+ for (const { s, drop } of steps) {
956
+ if (total() <= width)
957
+ break;
958
+ if (drop)
959
+ kept.splice(kept.indexOf(s), 1);
960
+ else
961
+ s.text = s.short;
962
+ }
963
+ return kept;
950
964
  }
951
965
  function StatusBar({ status, width }) {
952
- const ctx = status.context;
953
- const pct = ctx ? Math.round((ctx.used / ctx.limit) * 100) : 0;
954
- /** 离自动压缩还有多远:到阈值的 85% 起变黄 */
955
- const nearCompact = ctx?.compactAt ? ctx.used >= ctx.compactAt * 0.85 : pct >= 80;
956
- const modeColor = status.mode === "yolo"
957
- ? "red"
958
- : status.mode === "auto"
959
- ? "yellow"
960
- : status.mode === "plan"
961
- ? "magenta"
962
- : "green";
963
- const speed = status.speed;
964
- // 窄的时候依次:提示变短、去掉提示、用量变短、去掉缓存、模式变短、去掉用量、上下文变短、去掉速度
965
- const segments = [
966
- {
967
- text: `${status.mode} (shift+tab)`,
968
- short: status.mode,
969
- shortAt: 6,
970
- color: modeColor,
971
- },
972
- ctx
973
- ? {
974
- text: `ctx ${tokens(ctx.used)}/${tokens(ctx.limit)} (${pct}%)${ctx.compactAt ? `, compacts at ${tokens(ctx.compactAt)}` : ""}`,
975
- short: `ctx ${pct}%`,
976
- shortAt: 4,
977
- color: nearCompact ? "yellow" : undefined,
978
- dim: !nearCompact,
979
- }
980
- : { text: "ctx —", dim: true },
981
- ...(speed
982
- ? [
983
- {
984
- text: `${speed.live ? "~" : ""}${speed.tps >= 100 ? Math.round(speed.tps) : speed.tps.toFixed(1)} tok/s`,
985
- dropAt: 3,
986
- dim: true,
987
- },
988
- ]
989
- : []),
990
- ...(status.cache !== undefined
991
- ? [{ text: `cache ${Math.round(status.cache * 100)}%`, dropAt: 7, dim: true }]
992
- : []),
993
- ...(status.spent
994
- ? [
995
- {
996
- text: `session ${tokens(status.spent.input)} in / ${tokens(status.spent.output)} out`,
997
- short: `${tokens(status.spent.input)} in / ${tokens(status.spent.output)} out`,
998
- shortAt: 8,
999
- dropAt: 5,
1000
- dim: true,
1001
- },
1002
- ]
1003
- : []),
1004
- // 插件的段落:比提示晚、比缓存早去掉
1005
- ...(status.plugins ?? []).map((p) => ({ text: p.text, dropAt: 7.5, dim: true })),
1006
- {
1007
- text: "PgUp/PgDn scroll · click ▸ or ctrl+o to expand · drag to select and copy",
1008
- short: "ctrl+o to expand",
1009
- shortAt: 10,
1010
- dropAt: 9,
1011
- dim: true,
1012
- },
1013
- ];
1014
- const shown = fitSegments(segments, width);
1015
- return h(Box, { paddingX: 1 }, h(Text, { wrap: "truncate-end" }, shown.map((s, i) => h(Text, { key: i }, i ? h(Text, { dimColor: true }, " · ") : null, h(Text, { color: s.color, dimColor: s.dim }, s.text)))));
966
+ const ctx = status.context;
967
+ const pct = ctx ? Math.round(ctx.used / ctx.limit * 100) : 0;
968
+ const nearFull = pct >= 80;
969
+ const speed = status.speed;
970
+ const plugin = (p, keep) => {
971
+ const seg = typeof p.text === "string" ? { text: p.text } : p.text;
972
+ return {
973
+ text: seg.text,
974
+ ...seg.short !== undefined ? { short: seg.short, shortAt: keep ? 6 : 7.6 } : {},
975
+ ...keep ? {} : { dropAt: 7.5 },
976
+ ...seg.tone ? { color: TONE[seg.tone] } : { dim: true }
977
+ };
978
+ };
979
+ const kept = (status.plugins ?? []).filter((p) => typeof p.text !== "string" && p.text.keep);
980
+ const others = (status.plugins ?? []).filter((p) => !kept.includes(p));
981
+ const segments = [
982
+ ...kept.map((p) => plugin(p, true)),
983
+ ctx ? {
984
+ text: `ctx ${tokens(ctx.used)}/${tokens(ctx.limit)} (${pct}%)`,
985
+ short: `ctx ${pct}%`,
986
+ shortAt: 4,
987
+ color: nearFull ? "yellow" : undefined,
988
+ dim: !nearFull
989
+ } : { text: "ctx —", dim: true },
990
+ ...speed ? [
991
+ {
992
+ text: `${speed.live ? "~" : ""}${speed.tps >= 100 ? Math.round(speed.tps) : speed.tps.toFixed(1)} tok/s`,
993
+ dropAt: 3,
994
+ dim: true
995
+ }
996
+ ] : [],
997
+ ...status.cache !== undefined ? [{ text: `cache ${Math.round(status.cache * 100)}%`, dropAt: 7, dim: true }] : [],
998
+ ...status.spent ? [
999
+ {
1000
+ text: `session ${tokens(status.spent.input)} in / ${tokens(status.spent.output)} out`,
1001
+ short: `${tokens(status.spent.input)} in / ${tokens(status.spent.output)} out`,
1002
+ shortAt: 8,
1003
+ dropAt: 5,
1004
+ dim: true
1005
+ }
1006
+ ] : [],
1007
+ ...others.map((p) => plugin(p, false)),
1008
+ {
1009
+ text: "PgUp/PgDn scroll · click ▸ or ctrl+o to expand · drag to select and copy",
1010
+ short: "ctrl+o to expand",
1011
+ shortAt: 10,
1012
+ dropAt: 9,
1013
+ dim: true
1014
+ }
1015
+ ];
1016
+ const shown = fitSegments(segments, width);
1017
+ return h(Box, { paddingX: 1 }, h(Text, { wrap: "truncate-end" }, shown.map((s, i) => h(Text, { key: i }, i ? h(Text, { dimColor: true }, " · ") : null, h(Text, { color: s.color, dimColor: s.dim }, s.text)))));
1016
1018
  }
1017
- /** 一行提示:按宽度选第一个放得下的写法,都放不下时用最后一个并截断 */
1018
1019
  function Hint({ variants, width }) {
1019
- const text = variants.find((v) => stringWidth(v) <= width) ?? variants.at(-1);
1020
- return h(Text, { dimColor: true, wrap: "truncate-end" }, text);
1020
+ const text = variants.find((v) => stringWidth(v) <= width) ?? variants.at(-1);
1021
+ return h(Text, { dimColor: true, wrap: "truncate-end" }, text);
1021
1022
  }
1022
- const tokens = (n) => n >= 1_000_000
1023
- ? `${(n / 1_000_000).toFixed(n >= 10_000_000 ? 0 : 1)}M`
1024
- : n >= 1000
1025
- ? `${(n / 1000).toFixed(n >= 10_000 ? 0 : 1)}k`
1026
- : String(n);
1027
- /**
1028
- * 同一块输入里的多个按键(按住退格、输入很快时终端会合并)由 Ink 连续交给处理函数,中间不重新渲染,
1029
- * 处理函数里读 useState 的值会是旧的,后面的按键就丢了。这里的值放在 ref 里同步更新:
1030
- * get() 总是最新的,set() 之后安排一次重画(同一块里的多次 set 合并成一次)
1031
- */
1023
+ const tokens = (n) => n >= 1e6 ? `${(n / 1e6).toFixed(n >= 1e7 ? 0 : 1)}M` : n >= 1000 ? `${(n / 1000).toFixed(n >= 1e4 ? 0 : 1)}k` : String(n);
1032
1024
  function useLive(initial) {
1033
- const ref = useRef(initial);
1034
- const [, rerender] = useReducer((n) => n + 1, 0);
1035
- return [
1036
- () => ref.current,
1037
- (v) => {
1038
- ref.current = v;
1039
- rerender();
1040
- },
1041
- ];
1025
+ const ref = useRef(initial);
1026
+ const [, rerender] = useReducer((n) => n + 1, 0);
1027
+ return [
1028
+ () => ref.current,
1029
+ (v) => {
1030
+ ref.current = v;
1031
+ rerender();
1032
+ }
1033
+ ];
1042
1034
  }
1043
- /** 编辑按键的通用处理;返回编辑后的状态,不是编辑键时返回 undefined */
1044
1035
  function editKey(s, input, key) {
1045
- if (key.leftArrow)
1046
- return edit.left(s);
1047
- if (key.rightArrow)
1048
- return edit.right(s);
1049
- if (key.home || (key.ctrl && input === "a"))
1050
- return edit.home(s);
1051
- if (key.end || (key.ctrl && input === "e"))
1052
- return edit.end(s);
1053
- if (key.backspace)
1054
- return key.meta ? edit.deleteWord(s) : edit.backspace(s);
1055
- if (key.delete || (key.ctrl && input === "d"))
1056
- return edit.del(s);
1057
- if (key.ctrl && input === "w")
1058
- return edit.deleteWord(s);
1059
- if (key.meta && !key.ctrl && input === "f")
1060
- return edit.wordRight(s);
1061
- if (key.meta && !key.ctrl && input === "b")
1062
- return edit.wordLeft(s);
1063
- if (key.ctrl && input === "u")
1064
- return edit.killBefore(s);
1065
- if (key.ctrl && input === "k")
1066
- return edit.killAfter(s);
1067
- if (key.ctrl ||
1068
- key.meta ||
1069
- key.escape ||
1070
- key.return ||
1071
- key.tab ||
1072
- key.upArrow ||
1073
- key.downArrow ||
1074
- key.pageUp ||
1075
- key.pageDown)
1076
- return undefined;
1077
- // 鼠标事件由 App 处理
1078
- if (MOUSE.test(input))
1079
- return undefined;
1080
- // 其余是普通输入;快速输入时一次可能有多个字符
1081
- const text = input
1082
- .replace(/\r\n?/g, "\n")
1083
- .replace(/[\x00-\x09\x0b-\x1f\x7f]/g, "");
1084
- return text ? edit.insert(s, text) : undefined;
1036
+ if (key.leftArrow)
1037
+ return key.ctrl ? edit.wordLeft(s) : edit.left(s);
1038
+ if (key.rightArrow)
1039
+ return key.ctrl ? edit.wordRight(s) : edit.right(s);
1040
+ if (key.home || key.ctrl && input === "a")
1041
+ return edit.home(s);
1042
+ if (key.end || key.ctrl && input === "e")
1043
+ return edit.end(s);
1044
+ if (key.backspace)
1045
+ return key.meta ? edit.deleteWord(s) : edit.backspace(s);
1046
+ if (key.delete || key.ctrl && input === "d")
1047
+ return edit.del(s);
1048
+ if (key.ctrl && input === "w")
1049
+ return edit.deleteWord(s);
1050
+ if (key.meta && !key.ctrl && input === "f")
1051
+ return edit.wordRight(s);
1052
+ if (key.meta && !key.ctrl && input === "b")
1053
+ return edit.wordLeft(s);
1054
+ if (key.ctrl && input === "u")
1055
+ return edit.killBefore(s);
1056
+ if (key.ctrl && input === "k")
1057
+ return edit.killAfter(s);
1058
+ if (key.ctrl || key.meta || key.escape || key.return || key.tab || key.upArrow || key.downArrow || key.pageUp || key.pageDown)
1059
+ return;
1060
+ if (MOUSE.test(input))
1061
+ return;
1062
+ const text = input.replace(/\r\n?/g, `
1063
+ `).replace(/[\x00-\x09\x0b-\x1f\x7f]/g, "");
1064
+ return text ? edit.insert(s, text) : undefined;
1085
1065
  }
1086
- /** 一行文字里下标 [from, to)(相对这一行)反色显示,和对话区的选中一样 */
1087
1066
  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)}`;
1067
+ from = Math.max(0, Math.min(row.length, from));
1068
+ to = Math.max(from, Math.min(row.length, to));
1069
+ if (from === to)
1070
+ return row;
1071
+ return `${row.slice(0, from)}${INVERSE}${row.slice(from, to)}${INVERSE_OFF}${row.slice(to)}`;
1093
1072
  }
1094
- /** 渲染可编辑文本并把终端光标放到输入位置(输入法的候选框跟着它) */
1095
- function EditableText({ state, width, prefix, mask, placeholder, active, maxRows = Infinity, place, top, selected, }) {
1096
- const ref = useRef(null);
1097
- // 只用来在布局变化后重画一次、重新计算光标位置;它给的是相对父元素的坐标,光标要的是相对整个输出
1098
- const metrics = useBoxMetrics(ref);
1099
- const shown = mask ? "•".repeat([...state.value].length) : state.value;
1100
- const cursor = mask
1101
- ? [...state.value.slice(0, state.cursor)].length
1102
- : state.cursor;
1103
- const all = layout(shown, cursor, width - prefix.length);
1104
- const { col } = all;
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));
1110
- const rows = all.rows.slice(first, first + maxRows);
1111
- const row = all.row - first;
1112
- const cursorShown = row >= 0 && row < rows.length;
1113
- // 光标位置要在渲染时设:useCursor 在这次提交时交给 Ink,跟这一帧一起画出来。
1114
- // 放在 useEffect 里会晚一帧,光标总是停在上一次按键的位置(只移动光标时最明显)。
1115
- // 这里用的是上一次的布局,提交后要核对一遍:
1116
- // - 输入框相对父元素挪了位置时 useBoxMetrics 会再触发一次渲染
1117
- // - 只有祖先挪了位置时(窗口尺寸变化后整帧重画那一帧上下各垫一行,下一帧再去掉)它看不出来,
1118
- // 光标会停在比输入行低一行的地方,要自己比一下整体位置
1119
- const at = active && metrics.hasMeasured && ref.current
1120
- ? origin(ref.current)
1121
- : undefined;
1122
- const position = at && cursorShown ? { x: at.x + prefix.length + col, y: at.y + row } : undefined;
1123
- if (place)
1124
- place.current = at && { x: at.x + prefix.length, y: at.y, first, rows: rows.length, total: all.rows.length };
1125
- const [, recheck] = useReducer((n) => n + 1, 0);
1126
- useEffect(() => {
1127
- if (!at || !ref.current)
1128
- return;
1129
- const now = origin(ref.current);
1130
- if (now.x !== at.x || now.y !== at.y)
1131
- recheck();
1132
- });
1133
- return h(Box, { ref, flexDirection: "column" }, active ? h(CursorAt, { position }) : null, state.value === "" && placeholder
1134
- ? h(Text, { wrap: "truncate-end" }, h(Text, { color: "cyan" }, prefix), h(Text, { dimColor: true }, placeholder))
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)));
1073
+ function EditableText({
1074
+ state,
1075
+ width,
1076
+ prefix,
1077
+ mask,
1078
+ placeholder,
1079
+ active,
1080
+ maxRows = 1 / 0,
1081
+ place,
1082
+ top,
1083
+ selected
1084
+ }) {
1085
+ const ref = useRef(null);
1086
+ const metrics = useBoxMetrics(ref);
1087
+ const shown = mask ? "•".repeat([...state.value].length) : state.value;
1088
+ const cursor = mask ? [...state.value.slice(0, state.cursor)].length : state.cursor;
1089
+ const all = layout(shown, cursor, width - prefix.length);
1090
+ const { col } = all;
1091
+ const last = Math.max(0, all.rows.length - maxRows);
1092
+ const first = top === undefined ? Math.max(0, Math.min(all.row - maxRows + 1, last)) : Math.max(0, Math.min(top, last));
1093
+ const rows = all.rows.slice(first, first + maxRows);
1094
+ const row = all.row - first;
1095
+ const cursorShown = row >= 0 && row < rows.length;
1096
+ const at = active && metrics.hasMeasured && ref.current ? origin(ref.current) : undefined;
1097
+ const position = at && cursorShown ? { x: at.x + prefix.length + col, y: at.y + row } : undefined;
1098
+ if (place)
1099
+ place.current = at && { x: at.x + prefix.length, y: at.y, first, rows: rows.length, total: all.rows.length };
1100
+ const [, recheck] = useReducer((n) => n + 1, 0);
1101
+ useEffect(() => {
1102
+ if (!at || !ref.current)
1103
+ return;
1104
+ const now = origin(ref.current);
1105
+ if (now.x !== at.x || now.y !== at.y)
1106
+ recheck();
1107
+ });
1108
+ return h(Box, { ref, flexDirection: "column" }, active ? h(CursorAt, { position }) : null, state.value === "" && placeholder ? h(Text, { wrap: "truncate-end" }, h(Text, { color: "cyan" }, prefix), h(Text, { dimColor: true }, placeholder)) : 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) : i === rows.length - 1 && first + rows.length < all.rows.length ? "↓".padEnd(prefix.length) : " ".repeat(prefix.length)), selected && !mask ? inverseRange(r, selected[0] - all.starts[first + i], selected[1] - all.starts[first + i]) : r)));
1142
1109
  }
1143
- /**
1144
- * 终端光标只有一个,每个 useCursor 每次提交都会设一遍。没有焦点的输入框(弹出输入框时下面的主输入框)
1145
- * 不能用它,否则它设的"不显示"会盖掉有焦点的那个,所以只在有焦点时挂上
1146
- */
1147
1110
  function CursorAt({ position }) {
1148
- const { setCursorPosition } = useCursor();
1149
- setCursorPosition(position);
1150
- return null;
1111
+ const { setCursorPosition } = useCursor();
1112
+ setCursorPosition(position);
1113
+ return null;
1151
1114
  }
1152
- /** 元素相对整个动态输出(Static 之外的部分)左上角的位置 */
1153
1115
  function origin(node) {
1154
- let x = 0;
1155
- let y = 0;
1156
- for (let n = node; n?.yogaNode; n = n.parentNode) {
1157
- x += n.yogaNode.getComputedLeft();
1158
- y += n.yogaNode.getComputedTop();
1159
- }
1160
- return { x, y };
1116
+ let x = 0;
1117
+ let y = 0;
1118
+ for (let n = node;n?.yogaNode; n = n.parentNode) {
1119
+ x += n.yogaNode.getComputedLeft();
1120
+ y += n.yogaNode.getComputedTop();
1121
+ }
1122
+ return { x, y };
1161
1123
  }
1162
- function Prompt({ commands, handlers, history: initial, bridge, hint, onHintDone, busy, queued, active, onSubmit, flash, place, onCopy, }) {
1163
- const selection = useContext(SelectionContext);
1164
- const [current, setState] = useLive(empty);
1165
- const [getSelected, setSelected] = useLive(0);
1166
- const [getNotice, setNotice] = useLive(undefined);
1167
- const history = useRef(initial);
1168
- /** 正在看的历史条目;-1 表示当前输入 */
1169
- const browsing = useRef(-1);
1170
- const draft = useRef("");
1171
- const lastCtrlC = useRef(0);
1172
- const lastEsc = useRef(0);
1173
- /**
1174
- * 用滚轮翻过输入框时翻到的第一行可见行。只对翻的时候的那份文字和光标有效:打字、移动光标后又跟着光标
1175
- */
1176
- const scrolled = useRef(undefined);
1177
- /** 在输入框里按住左键拖动选中的文字:anchor 是按下的位置,focus 是拖到的位置(value 里的下标);文字改了就作废 */
1178
- const [getDrag, setDrag] = useLive(undefined);
1179
- const { columns, rows } = useScreenSize();
1180
- /** 输入框里文字的宽度:边框、内边距和前面的 "› " 之外 */
1181
- const textWidth = Math.max(10, columns - 5) - 2;
1182
- /** 补全菜单、搜索结果最多显示几项;输入框最多几行 */
1183
- const menuRows = roomFor(rows, MENTION_ROWS);
1184
- const inputRows = roomFor(rows, 10);
1185
- const hintWidth = Math.max(10, columns - 3);
1186
- // @ 引用补全用的路径;排好的结果按(路径表,查询)缓存,按键处理和渲染都要用时不重复排
1187
- const [getPaths, setPaths] = useLive([]);
1188
- const ranked = useRef(undefined);
1189
- // Ctrl+R 搜索历史:结果新的在前,index 是选中的那条
1190
- const [getSearch, setSearch] = useLive(undefined);
1191
- const usageOf = (c) => `/${c.name}${c.args ? ` ${c.args}` : ""}`;
1192
- const column = Math.max(...commands().map((c) => usageOf(c).length)) + 2;
1193
- /** 由最新的输入算出补全菜单和搜索结果;渲染和按键处理都用它 */
1194
- const derive = () => {
1195
- const state = current();
1196
- const selected = getSelected();
1197
- const search = getSearch();
1198
- // 翻到的历史条目原样未改时不弹补全菜单,否则菜单会占住 ↑/↓,翻不过 /命令 这样的条目
1199
- const recalled = browsing.current >= 0 &&
1200
- state.value ===
1201
- history.current[history.current.length - 1 - browsing.current];
1202
- const naming = !recalled && state.value.startsWith("/") && !/\s/.test(state.value);
1203
- const matches = naming
1204
- ? commands().filter((c) => `/${c.name}`.startsWith(state.value))
1205
- : [];
1206
- const pick = matches[Math.min(selected, matches.length - 1)];
1207
- // @ 引用:光标处正在输入的路径和补全候选
1208
- const mention = naming || recalled ? undefined : mentionAt(state.value, state.cursor);
1209
- let found = [];
1210
- if (mention) {
1211
- const paths = getPaths();
1212
- const r = ranked.current;
1213
- found =
1214
- r && r.paths === paths && r.query === mention.query
1215
- ? r.result
1216
- : rankPaths(paths, mention.query, MENTION_ROWS);
1217
- ranked.current = { paths, query: mention.query, result: found };
1218
- }
1219
- const file = found[Math.min(selected, found.length - 1)];
1220
- const menu = matches.length || found.length;
1221
- const results = search
1222
- ? history.current
1223
- .toReversed()
1224
- .filter((h) => h.toLowerCase().includes(search.query.toLowerCase()))
1225
- : [];
1226
- const hit = search
1227
- ? Math.max(0, Math.min(search.index, results.length - 1))
1228
- : 0;
1229
- return {
1230
- state,
1231
- selected,
1232
- search,
1233
- matches,
1234
- pick,
1235
- mention,
1236
- found,
1237
- file,
1238
- menu,
1239
- results,
1240
- hit,
1241
- };
1124
+ function Prompt({
1125
+ commands,
1126
+ handlers,
1127
+ history: initial,
1128
+ bridge,
1129
+ hint,
1130
+ onHintDone,
1131
+ busy,
1132
+ queued,
1133
+ active,
1134
+ onSubmit,
1135
+ flash,
1136
+ place,
1137
+ onCopy
1138
+ }) {
1139
+ const selection = useContext(SelectionContext);
1140
+ const [current, setState] = useLive(empty);
1141
+ const [getSelected, setSelected] = useLive(0);
1142
+ const [getNotice, setNotice] = useLive(undefined);
1143
+ const history = useRef(initial);
1144
+ const browsing = useRef(-1);
1145
+ const draft = useRef("");
1146
+ const lastCtrlC = useRef(0);
1147
+ const lastEsc = useRef(0);
1148
+ const scrolled = useRef(undefined);
1149
+ const [getDrag, setDrag] = useLive(undefined);
1150
+ const { columns, rows } = useScreenSize();
1151
+ const textWidth = Math.max(10, columns - 5) - 2;
1152
+ const menuRows = roomFor(rows, MENTION_ROWS);
1153
+ const inputRows = roomFor(rows, 10);
1154
+ const hintWidth = Math.max(10, columns - 3);
1155
+ const [getPaths, setPaths] = useLive([]);
1156
+ const ranked = useRef(undefined);
1157
+ const [getSearch, setSearch] = useLive(undefined);
1158
+ const usageOf = (c) => `/${c.name}${c.args ? ` ${c.args}` : ""}`;
1159
+ const completions = handlers.completions?.() ?? [];
1160
+ const triggers = completions.map((c) => c.trigger);
1161
+ const column = Math.max(...commands().map((c) => usageOf(c).length)) + 2;
1162
+ const derive = () => {
1163
+ const state = current();
1164
+ const selected = getSelected();
1165
+ const search = getSearch();
1166
+ const recalled = browsing.current >= 0 && state.value === history.current[history.current.length - 1 - browsing.current];
1167
+ const naming = !recalled && state.value.startsWith("/") && !/\s/.test(state.value);
1168
+ const matches = naming ? commands().filter((c) => `/${c.name}`.startsWith(state.value)) : [];
1169
+ const pick = matches[Math.min(selected, matches.length - 1)];
1170
+ const mention = naming || recalled ? undefined : mentionAt(state.value, state.cursor, triggers);
1171
+ let found = [];
1172
+ if (mention) {
1173
+ const paths = getPaths();
1174
+ const r = ranked.current;
1175
+ found = r && r.paths === paths && r.query === mention.query ? r.result : rankPaths(paths, mention.query, MENTION_ROWS);
1176
+ ranked.current = { paths, query: mention.query, result: found };
1177
+ }
1178
+ const file = found[Math.min(selected, found.length - 1)];
1179
+ const menu = matches.length || found.length;
1180
+ const results = search ? history.current.toReversed().filter((h) => h.toLowerCase().includes(search.query.toLowerCase())) : [];
1181
+ const hit = search ? Math.max(0, Math.min(search.index, results.length - 1)) : 0;
1182
+ return {
1183
+ state,
1184
+ selected,
1185
+ search,
1186
+ matches,
1187
+ pick,
1188
+ mention,
1189
+ found,
1190
+ file,
1191
+ menu,
1192
+ results,
1193
+ hit
1242
1194
  };
1243
- const { state, search, matches, pick, mention, found, file, results, hit } = derive();
1244
- const notice = getNotice();
1245
- const mentioning = mention !== undefined;
1246
- // 每次开始输入一个新的 @ 引用时重新取一次:文件可能已经变了
1247
- useEffect(() => {
1248
- if (!mentioning || !handlers.files)
1249
- return;
1250
- let live = true;
1251
- handlers.files().then((p) => void (live && setPaths(p)), () => { });
1252
- return () => {
1253
- live = false;
1254
- };
1255
- }, [mentioning]);
1256
- // 结果多时只显示选中项附近的几条
1257
- const first = around(hit, results.length, menuRows);
1258
- const firstMatch = around(Math.max(0, matches.indexOf(pick)), matches.length, menuRows);
1259
- const firstFound = around(Math.max(0, found.indexOf(file)), found.length, menuRows);
1260
- /** 提示只在空闲、输入框为空、没有在搜索历史时显示,也只有这时能接受 */
1261
- const hinting = () => hint !== undefined && !busy && current().value === "" && !getSearch();
1262
- const set = (s) => {
1263
- // 打字时提示只是不显示(hinting() 要求输入框为空),删回空的又出现;发出去才作废
1264
- setState(s);
1265
- setSelected(0);
1266
- setNotice(undefined);
1267
- lastEsc.current = 0;
1195
+ };
1196
+ const { state, search, matches, pick, mention, found, file, results, hit } = derive();
1197
+ const notice = getNotice();
1198
+ const mentioning = mention?.trigger;
1199
+ useEffect(() => {
1200
+ if (mentioning === undefined || !handlers.complete)
1201
+ return;
1202
+ let live = true;
1203
+ setPaths([]);
1204
+ handlers.complete(mentioning).then((p) => void (live && setPaths(p)), () => {});
1205
+ return () => {
1206
+ live = false;
1268
1207
  };
1269
- const remember = (text) => {
1270
- history.current = [
1271
- ...history.current.filter((h) => h !== text),
1272
- text,
1273
- ].slice(-100);
1208
+ }, [mentioning]);
1209
+ const completion = completions.find((c) => c.trigger === mentioning);
1210
+ const first = around(hit, results.length, menuRows);
1211
+ const firstMatch = around(Math.max(0, matches.indexOf(pick)), matches.length, menuRows);
1212
+ const firstFound = around(Math.max(0, found.indexOf(file)), found.length, menuRows);
1213
+ const hinting = () => hint !== undefined && !busy && current().value === "" && !getSearch();
1214
+ const set = (s) => {
1215
+ setState(s);
1216
+ setSelected(0);
1217
+ setNotice(undefined);
1218
+ lastEsc.current = 0;
1219
+ };
1220
+ const remember = (text) => {
1221
+ history.current = [
1222
+ ...history.current.filter((h) => h !== text),
1223
+ text
1224
+ ].slice(-100);
1225
+ browsing.current = -1;
1226
+ };
1227
+ const pastes = useRef(new Map);
1228
+ const unfold = (text) => pastes.current.size ? text.replace(PASTED, (m) => pastes.current.get(m) ?? m) : text;
1229
+ const submit = (folded) => {
1230
+ if (!folded.trim())
1231
+ return;
1232
+ const text = unfold(folded);
1233
+ pastes.current.clear();
1234
+ if (hint !== undefined)
1235
+ onHintDone();
1236
+ remember(text);
1237
+ set(empty);
1238
+ typedAt = 0;
1239
+ onSubmit();
1240
+ handlers.submit(text);
1241
+ };
1242
+ const discard = () => {
1243
+ const text = unfold(current().value);
1244
+ pastes.current.clear();
1245
+ if (text.trim())
1246
+ remember(text);
1247
+ set(empty);
1248
+ };
1249
+ const complete = (p) => {
1250
+ const { state, mention } = derive();
1251
+ const text = mentionText(mention.trigger, p) + (p.endsWith("/") ? "" : " ");
1252
+ set({
1253
+ value: state.value.slice(0, mention.start) + text + state.value.slice(state.cursor),
1254
+ cursor: mention.start + text.length
1255
+ });
1256
+ };
1257
+ bridge.current = { get: () => unfold(current().value), apply: (f) => set(f(current())) };
1258
+ const recall = (i) => {
1259
+ browsing.current = i;
1260
+ const value = i === -1 ? draft.current : history.current[history.current.length - 1 - i];
1261
+ set({ value, cursor: value.length });
1262
+ };
1263
+ usePaste((text) => {
1264
+ const search = getSearch();
1265
+ if (search)
1266
+ setSearch({
1267
+ query: search.query + text.replace(/\s+/g, " "),
1268
+ index: 0
1269
+ });
1270
+ else {
1271
+ const pasted = text.replace(/\r\n?/g, `
1272
+ `);
1273
+ const lines = pasted.replace(/\n$/, "").split(`
1274
+ `).length;
1275
+ if (lines <= FOLD_PASTE_LINES && pasted.length <= FOLD_PASTE_CHARS)
1276
+ return set(edit.insert(current(), pasted));
1277
+ const tag = `[Pasted text #${pastes.current.size + 1} ${lines > 1 ? `+${lines} lines` : `${pasted.length} chars`}]`;
1278
+ pastes.current.set(tag, pasted);
1279
+ set(edit.insert(current(), tag));
1280
+ }
1281
+ }, { isActive: active });
1282
+ const searchKey = (s, input, key) => {
1283
+ const { results, hit } = derive();
1284
+ if (key.escape || key.ctrl && (input === "c" || input === "g"))
1285
+ return setSearch(undefined);
1286
+ if (key.return || key.tab) {
1287
+ setSearch(undefined);
1288
+ const picked = results[hit];
1289
+ if (picked !== undefined) {
1274
1290
  browsing.current = -1;
1275
- };
1276
- const submit = (text) => {
1277
- if (!text.trim())
1278
- return;
1279
- if (hint !== undefined)
1280
- onHintDone();
1281
- remember(text);
1282
- set(empty);
1283
- // 发出去之后弹出的对话框是用户自己要的(/mode、/model),马上就能回答
1284
- typedAt = 0;
1285
- onSubmit();
1286
- handlers.submit(text);
1287
- };
1288
- /** 清空输入;清掉的内容放进(本次运行的)历史,按 ↑ 能找回来 */
1289
- const discard = () => {
1290
- const text = current().value;
1291
- if (text.trim())
1292
- remember(text);
1293
- set(empty);
1294
- };
1295
- /** 用选中的路径替换正在输入的 @ 引用;目录不加空格,接着补全里面的文件 */
1296
- const complete = (p) => {
1297
- const { state, mention } = derive();
1298
- const text = mentionText(p) + (p.endsWith("/") ? "" : " ");
1291
+ set({ value: picked, cursor: picked.length });
1292
+ }
1293
+ return;
1294
+ }
1295
+ if (key.upArrow || key.ctrl && input === "r")
1296
+ return setSearch({
1297
+ ...s,
1298
+ index: Math.min(hit + 1, Math.max(0, results.length - 1))
1299
+ });
1300
+ if (key.downArrow)
1301
+ return setSearch({ ...s, index: Math.max(0, hit - 1) });
1302
+ if (key.backspace || key.delete)
1303
+ return setSearch({ query: [...s.query].slice(0, -1).join(""), index: 0 });
1304
+ if (key.ctrl && input === "u")
1305
+ return setSearch({ query: "", index: 0 });
1306
+ if (key.ctrl || key.meta || MOUSE.test(input))
1307
+ return;
1308
+ const text = input.replace(/[\x00-\x1f\x7f]/g, "");
1309
+ if (text)
1310
+ setSearch({ query: s.query + text, index: 0 });
1311
+ };
1312
+ useInput((input, key) => {
1313
+ if (key.ctrl && input === "c" && selection.active())
1314
+ return selection.clear();
1315
+ const search = getSearch();
1316
+ if (search)
1317
+ return searchKey(search, input, key);
1318
+ const state = current();
1319
+ const mouse = mouseEvent(input);
1320
+ if (mouse) {
1321
+ const at = place.current;
1322
+ if (!at)
1323
+ return;
1324
+ const row = mouse.y - at.y;
1325
+ const offset = (r) => offsetAt(state.value, textWidth, at.first + Math.max(0, Math.min(at.rows - 1, r)), mouse.x - at.x);
1326
+ if ((mouse.button === 64 || mouse.button === 65) && row >= -1 && row <= at.rows && at.total > at.rows) {
1327
+ const top = Math.max(0, Math.min(at.total - at.rows, at.first + (mouse.button === 64 ? -WHEEL_LINES : WHEEL_LINES)));
1328
+ scrolled.current = { top, value: state.value, cursor: state.cursor };
1329
+ return setState({ ...state });
1330
+ }
1331
+ if (mouse.button === 0 && mouse.press) {
1332
+ if (row < 0 || row >= at.rows)
1333
+ return setDrag(undefined);
1334
+ const cursor = offset(row);
1335
+ if (cursor === undefined)
1336
+ return;
1337
+ setDrag({ anchor: cursor, focus: cursor, value: state.value });
1338
+ if (scrolled.current)
1339
+ scrolled.current = { ...scrolled.current, cursor };
1340
+ return setState({ ...state, cursor });
1341
+ }
1342
+ const drag = getDrag();
1343
+ if (!drag || drag.value !== state.value)
1344
+ return;
1345
+ if (mouse.button === DRAG) {
1346
+ const focus = offset(row);
1347
+ if (focus === undefined)
1348
+ return;
1349
+ setDrag({ ...drag, focus });
1350
+ if (scrolled.current)
1351
+ scrolled.current = { ...scrolled.current, cursor: focus };
1352
+ return setState({ ...state, cursor: focus });
1353
+ }
1354
+ if (mouse.button === 0 && !mouse.press && drag.anchor !== drag.focus) {
1355
+ onCopy(state.value.slice(Math.min(drag.anchor, drag.focus), Math.max(drag.anchor, drag.focus)));
1356
+ }
1357
+ return;
1358
+ }
1359
+ const drag = getDrag();
1360
+ if (drag) {
1361
+ setDrag(undefined);
1362
+ if (key.ctrl && input === "c" && drag.anchor !== drag.focus && drag.value === state.value)
1363
+ return;
1364
+ }
1365
+ if (key.ctrl && input === "r")
1366
+ return history.current.length ? setSearch({ query: "", index: 0 }) : undefined;
1367
+ if (key.ctrl && input === "c") {
1368
+ if (busy) {
1369
+ if (Date.now() - lastCtrlC.current < 2000)
1370
+ return handlers.exit();
1371
+ lastCtrlC.current = Date.now();
1372
+ return handlers.interrupt();
1373
+ }
1374
+ if (state.value)
1375
+ return discard();
1376
+ if (Date.now() - lastCtrlC.current < 2000)
1377
+ return handlers.exit();
1378
+ lastCtrlC.current = Date.now();
1379
+ return setNotice("Press Ctrl+C again to exit");
1380
+ }
1381
+ if (key.escape) {
1382
+ if (busy)
1383
+ return handlers.interrupt();
1384
+ if (!state.value)
1385
+ return;
1386
+ if (Date.now() - lastEsc.current < 1500)
1387
+ return discard();
1388
+ setNotice("Press Esc again to clear the input");
1389
+ lastEsc.current = Date.now();
1390
+ return;
1391
+ }
1392
+ if (!key.ctrl && !key.meta && input.length > 1 && input.indexOf("\r") === input.length - 1) {
1393
+ return submit(edit.insert(state, input.slice(0, -1)).value.trim());
1394
+ }
1395
+ if (key.return) {
1396
+ if (key.meta || key.shift)
1397
+ return set(edit.insert(state, `
1398
+ `));
1399
+ if (state.value.slice(0, state.cursor).endsWith("\\"))
1400
+ return set(edit.insert(edit.backspace(state), `
1401
+ `));
1402
+ const { pick, file } = derive();
1403
+ if (pick && state.value !== `/${pick.name}`)
1404
+ return submit(`/${pick.name}`);
1405
+ if (file)
1406
+ return complete(file);
1407
+ return submit(state.value.trim());
1408
+ }
1409
+ if ((key.tab && !key.shift || key.rightArrow) && hinting()) {
1410
+ browsing.current = -1;
1411
+ return set({ value: hint, cursor: hint.length });
1412
+ }
1413
+ if (key.tab && key.shift)
1414
+ return void handlers.key?.("shift+tab");
1415
+ if (key.tab) {
1416
+ const { pick, file } = derive();
1417
+ if (pick)
1299
1418
  set({
1300
- value: state.value.slice(0, mention.start) +
1301
- text +
1302
- state.value.slice(state.cursor),
1303
- cursor: mention.start + text.length,
1419
+ value: `/${pick.name}${pick.args ? " " : ""}`,
1420
+ cursor: pick.name.length + 1 + (pick.args ? 1 : 0)
1304
1421
  });
1305
- };
1306
- bridge.current = { get: () => current().value, apply: (f) => set(f(current())) };
1307
- const recall = (i) => {
1308
- browsing.current = i;
1309
- const value = i === -1
1310
- ? draft.current
1311
- : history.current[history.current.length - 1 - i];
1312
- set({ value, cursor: value.length });
1313
- };
1314
- usePaste((text) => {
1315
- const search = getSearch();
1316
- if (search)
1317
- setSearch({
1318
- query: search.query + text.replace(/\s+/g, " "),
1319
- index: 0,
1320
- });
1321
- else
1322
- set(edit.insert(current(), text.replace(/\r\n?/g, "\n")));
1323
- }, { isActive: active });
1324
- /** 搜索时的按键:上下(或再按 Ctrl+R)换一条,回车/Tab 放进输入框接着改,Esc 退出 */
1325
- const searchKey = (s, input, key) => {
1326
- const { results, hit } = derive();
1327
- if (key.escape || (key.ctrl && (input === "c" || input === "g")))
1328
- return setSearch(undefined);
1329
- if (key.return || key.tab) {
1330
- setSearch(undefined);
1331
- const picked = results[hit];
1332
- if (picked !== undefined) {
1333
- browsing.current = -1;
1334
- set({ value: picked, cursor: picked.length });
1335
- }
1336
- return;
1337
- }
1338
- if (key.upArrow || (key.ctrl && input === "r"))
1339
- return setSearch({
1340
- ...s,
1341
- index: Math.min(hit + 1, Math.max(0, results.length - 1)),
1342
- });
1343
- if (key.downArrow)
1344
- return setSearch({ ...s, index: Math.max(0, hit - 1) });
1345
- if (key.backspace || key.delete)
1346
- return setSearch({ query: [...s.query].slice(0, -1).join(""), index: 0 });
1347
- if (key.ctrl && input === "u")
1348
- return setSearch({ query: "", index: 0 });
1349
- if (key.ctrl || key.meta || MOUSE.test(input))
1350
- return;
1351
- const text = input.replace(/[\x00-\x1f\x7f]/g, "");
1352
- if (text)
1353
- setSearch({ query: s.query + text, index: 0 });
1354
- };
1355
- useInput((input, key) => {
1356
- if (key.ctrl && input === "c" && selection.active())
1357
- return selection.clear();
1358
- const search = getSearch();
1359
- if (search)
1360
- return searchKey(search, input, key);
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
- }
1413
- if (key.ctrl && input === "r")
1414
- return history.current.length
1415
- ? setSearch({ query: "", index: 0 })
1416
- : undefined;
1417
- if (key.ctrl && input === "c") {
1418
- if (busy) {
1419
- // 第一下中断;停不下来时(卡在 Interrupting)再按一下也能退出
1420
- if (Date.now() - lastCtrlC.current < 2000)
1421
- return handlers.exit();
1422
- lastCtrlC.current = Date.now();
1423
- return handlers.interrupt();
1424
- }
1425
- if (state.value)
1426
- return discard();
1427
- if (Date.now() - lastCtrlC.current < 2000)
1428
- return handlers.exit();
1429
- lastCtrlC.current = Date.now();
1430
- return setNotice("Press Ctrl+C again to exit");
1431
- }
1432
- if (key.escape) {
1433
- if (busy)
1434
- return handlers.interrupt();
1435
- if (!state.value)
1436
- return;
1437
- // 误按一下 Esc 不清掉写了半天的内容:连按两次才清空
1438
- if (Date.now() - lastEsc.current < 1500)
1439
- return discard();
1440
- setNotice("Press Esc again to clear the input");
1441
- lastEsc.current = Date.now();
1442
- return;
1443
- }
1444
- // 文字和回车在同一块里到达(输入很快时终端可能合并):插入文字后发送
1445
- if (!key.ctrl &&
1446
- !key.meta &&
1447
- input.length > 1 &&
1448
- input.indexOf("\r") === input.length - 1) {
1449
- return submit(edit.insert(state, input.slice(0, -1)).value.trim());
1450
- }
1451
- if (key.return) {
1452
- // 行尾的 \ 加回车换行;Alt+Enter 也换行;终端把 Shift+Enter 单独报上来时(kitty 键盘协议、modifyOtherKeys)也换行。
1453
- // Ctrl+J(Windows Terminal 里 Ctrl+Enter 也是它)发的是 LF,不算回车,在 editKey 里当普通换行插入
1454
- if (key.meta || key.shift)
1455
- return set(edit.insert(state, "\n"));
1456
- if (state.value.slice(0, state.cursor).endsWith("\\"))
1457
- return set(edit.insert(edit.backspace(state), "\n"));
1458
- const { pick, file } = derive();
1459
- if (pick && state.value !== `/${pick.name}`)
1460
- return submit(`/${pick.name}`);
1461
- if (file)
1462
- return complete(file);
1463
- return submit(state.value.trim());
1464
- }
1465
- // Tab 或 →:把提示变成输入框里的文字,接着可以改
1466
- if (((key.tab && !key.shift) || key.rightArrow) && hinting()) {
1467
- browsing.current = -1;
1468
- return set({ value: hint, cursor: hint.length });
1469
- }
1470
- if (key.tab && key.shift)
1471
- return handlers.cycleMode?.();
1472
- if (key.tab) {
1473
- const { pick, file } = derive();
1474
- if (pick)
1475
- set({
1476
- value: `/${pick.name}${pick.args ? " " : ""}`,
1477
- cursor: pick.name.length + 1 + (pick.args ? 1 : 0),
1478
- });
1479
- else if (file)
1480
- complete(file);
1481
- return;
1482
- }
1483
- if (key.upArrow) {
1484
- const { menu, selected } = derive();
1485
- if (menu)
1486
- return setSelected((selected - 1 + menu) % menu);
1487
- // 按折行后的屏幕行移动:一大段没有换行的文字也能上下走,到了第一行才翻历史
1488
- const up = moveRow(state, textWidth, -1);
1489
- if (up)
1490
- return setState(up);
1491
- // 先取回排队的消息,取完了再翻历史
1492
- if (handlers.unqueue?.()) {
1493
- browsing.current = -1;
1494
- return;
1495
- }
1496
- if (browsing.current + 1 < history.current.length) {
1497
- if (browsing.current === -1)
1498
- draft.current = state.value;
1499
- recall(browsing.current + 1);
1500
- }
1501
- return;
1502
- }
1503
- if (key.downArrow) {
1504
- const { menu, selected } = derive();
1505
- if (menu)
1506
- return setSelected((selected + 1) % menu);
1507
- const down = moveRow(state, textWidth, 1);
1508
- if (down)
1509
- return setState(down);
1510
- if (browsing.current >= 0)
1511
- recall(browsing.current - 1);
1512
- return;
1513
- }
1514
- const spec = keySpec(input, key);
1515
- if (spec && handlers.key?.(spec))
1516
- return;
1517
- const next = editKey(state, input, key);
1518
- if (next) {
1519
- if (next.value !== state.value)
1520
- typedAt = Date.now();
1521
- set(next);
1522
- }
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("!");
1532
- // 对话框打开时隐藏但不卸载,输入到一半的内容和历史都保留
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
1534
- ? h(EditableText, {
1535
- state: { value: search.query, cursor: search.query.length },
1536
- width: Math.max(10, columns - 5),
1537
- prefix: "search history› ",
1538
- placeholder: "type to filter",
1539
- active,
1540
- maxRows: inputRows,
1541
- })
1542
- : h(EditableText, {
1543
- state,
1544
- width: Math.max(10, columns - 5),
1545
- prefix: "› ",
1546
- placeholder: hinting()
1547
- ? hintLine(hint)
1548
- : queued
1549
- ? "↑ to edit queued messages · esc to interrupt"
1550
- : busy
1551
- ? "Type to queue a message · esc to interrupt"
1552
- : columns >= 70
1553
- ? "Message jade · / commands · @ files · ↑ or ctrl+r for history"
1554
- : "Message jade · / commands · @ files",
1555
- active,
1556
- maxRows: inputRows,
1557
- place,
1558
- top: viewTop,
1559
- selected: dragged,
1560
- })), search
1561
- ? h(Box, { flexDirection: "column", paddingX: 2 }, results.length
1562
- ? results.slice(first, first + menuRows).map((item, i) => {
1563
- const on = first + i === hit;
1564
- return h(Text, { key: first + i, wrap: "truncate-end", color: on ? "cyan" : undefined, bold: on }, on ? "❯ " : " ", item.replace(/\s*\n\s*/g, " ⏎ "));
1565
- })
1566
- : h(Text, { dimColor: true }, " no match"), h(Hint, {
1567
- width: hintWidth,
1568
- variants: [" ↑↓ or ctrl+r select · enter/tab put in the input · esc cancel", " ↑↓ select · enter use · esc cancel"],
1569
- }))
1570
- : matches.length
1571
- ? h(Box, { flexDirection: "column", paddingX: 2 }, matches.slice(firstMatch, firstMatch + menuRows).map((c) => {
1572
- const on = c === pick;
1573
- return h(Text, { key: c.name, wrap: "truncate-end" }, h(Text, { color: on ? "cyan" : undefined, bold: on }, on ? "❯ " : " ", usageOf(c).padEnd(column)), h(Text, { dimColor: true }, c.about));
1574
- }), h(Hint, {
1575
- width: hintWidth,
1576
- variants: [
1577
- ` ↑↓ select · enter run · tab complete${matches.length > menuRows ? ` · ${matches.length} commands` : ""}`,
1578
- " ↑↓ · enter run · tab complete",
1579
- ],
1580
- }))
1581
- : found.length
1582
- ? h(Box, { flexDirection: "column", paddingX: 2 }, found.slice(firstFound, firstFound + menuRows).map((p) => {
1583
- const on = p === file;
1584
- return h(Text, { key: p, wrap: "truncate-middle", color: on ? "cyan" : p.endsWith("/") ? "blue" : undefined, bold: on }, on ? "❯ " : " ", p);
1585
- }), h(Hint, {
1586
- width: hintWidth,
1587
- variants: [
1588
- " ↑↓ select · enter/tab insert the path · the file's content is sent with the message",
1589
- " ↑↓ select · enter/tab insert the path",
1590
- " ↑↓ · enter insert",
1591
- ],
1592
- }))
1593
- : notice
1594
- ? h(Text, { color: "yellow" }, ` ${notice}`)
1595
- : null,
1596
- // 压在输入框上边框的右边,不占行,出现和消失时下面的内容不跳
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);
1422
+ else if (file)
1423
+ complete(file);
1424
+ return;
1425
+ }
1426
+ if (key.upArrow) {
1427
+ const { menu, selected } = derive();
1428
+ if (menu)
1429
+ return setSelected((selected - 1 + menu) % menu);
1430
+ const up = moveRow(state, textWidth, -1);
1431
+ if (up)
1432
+ return setState(up);
1433
+ if (handlers.unqueue?.()) {
1434
+ browsing.current = -1;
1435
+ return;
1436
+ }
1437
+ if (browsing.current + 1 < history.current.length) {
1438
+ if (browsing.current === -1)
1439
+ draft.current = state.value;
1440
+ recall(browsing.current + 1);
1441
+ }
1442
+ return;
1443
+ }
1444
+ if (key.downArrow) {
1445
+ const { menu, selected } = derive();
1446
+ if (menu)
1447
+ return setSelected((selected + 1) % menu);
1448
+ const down = moveRow(state, textWidth, 1);
1449
+ if (down)
1450
+ return setState(down);
1451
+ if (browsing.current >= 0)
1452
+ recall(browsing.current - 1);
1453
+ return;
1454
+ }
1455
+ const spec = keySpec(input, key);
1456
+ if (spec && handlers.key?.(spec))
1457
+ return;
1458
+ const next = editKey(state, input, key);
1459
+ if (next) {
1460
+ if (next.value !== state.value)
1461
+ typedAt = Date.now();
1462
+ set(next);
1463
+ }
1464
+ }, { isActive: active });
1465
+ const view = scrolled.current;
1466
+ const viewTop = view && view.value === state.value && view.cursor === state.cursor ? view.top : undefined;
1467
+ const drag = getDrag();
1468
+ const dragged = drag && drag.value === state.value && drag.anchor !== drag.focus ? [Math.min(drag.anchor, drag.focus), Math.max(drag.anchor, drag.focus)] : undefined;
1469
+ const prefixed = search ? undefined : commands().find((c) => c.prefix !== undefined && state.value.startsWith(c.prefix));
1470
+ const bang = prefixed !== undefined;
1471
+ const prefixLabel = (() => {
1472
+ if (!prefixed)
1473
+ return "";
1474
+ const hint = prefixed.prefixHint ?? `/${prefixed.name}`;
1475
+ const head = hint.split(" · ")[0];
1476
+ return columns >= 70 ? busy ? `${head} · runs after this turn · esc stops it` : `${hint} · esc stops it` : head;
1477
+ })();
1478
+ const placeholder = ["Message jade", "/ commands", ...completions.map((c) => `${c.trigger} ${c.label}`)].join(" · ");
1479
+ return h(Box, { flexDirection: "column", marginTop: 1, display: active ? "flex" : "none" }, h(Box, { borderStyle: "round", borderColor: bang ? "magenta" : busy ? "gray" : "cyan", paddingX: 1 }, search ? h(EditableText, {
1480
+ state: { value: search.query, cursor: search.query.length },
1481
+ width: Math.max(10, columns - 5),
1482
+ prefix: "search history› ",
1483
+ placeholder: "type to filter",
1484
+ active,
1485
+ maxRows: inputRows
1486
+ }) : h(EditableText, {
1487
+ state,
1488
+ width: Math.max(10, columns - 5),
1489
+ prefix: "› ",
1490
+ placeholder: hinting() ? hintLine(hint) : queued ? "↑ to edit queued messages · esc to interrupt" : busy ? "Type to queue a message · esc to interrupt" : columns >= 70 ? `${placeholder} · ↑ or ctrl+r for history` : placeholder,
1491
+ active,
1492
+ maxRows: inputRows,
1493
+ place,
1494
+ top: viewTop,
1495
+ selected: dragged
1496
+ })), search ? h(Box, { flexDirection: "column", paddingX: 2 }, results.length ? results.slice(first, first + menuRows).map((item, i) => {
1497
+ const on = first + i === hit;
1498
+ return h(Text, { key: first + i, wrap: "truncate-end", color: on ? "cyan" : undefined, bold: on }, on ? "❯ " : " ", item.replace(/\s*\n\s*/g, " ⏎ "));
1499
+ }) : h(Text, { dimColor: true }, " no match"), h(Hint, {
1500
+ width: hintWidth,
1501
+ variants: [" ↑↓ or ctrl+r select · enter/tab put in the input · esc cancel", " ↑↓ select · enter use · esc cancel"]
1502
+ })) : matches.length ? h(Box, { flexDirection: "column", paddingX: 2 }, matches.slice(firstMatch, firstMatch + menuRows).map((c) => {
1503
+ const on = c === pick;
1504
+ return h(Text, { key: c.name, wrap: "truncate-end" }, h(Text, { color: on ? "cyan" : undefined, bold: on }, on ? "❯ " : " ", usageOf(c).padEnd(column)), h(Text, { dimColor: true }, c.about));
1505
+ }), h(Hint, {
1506
+ width: hintWidth,
1507
+ variants: [
1508
+ ` ↑↓ select · enter run · tab complete${matches.length > menuRows ? ` · ${matches.length} commands` : ""}`,
1509
+ " ↑↓ · enter run · tab complete"
1510
+ ]
1511
+ })) : found.length ? h(Box, { flexDirection: "column", paddingX: 2 }, found.slice(firstFound, firstFound + menuRows).map((p) => {
1512
+ const on = p === file;
1513
+ return h(Text, { key: p, wrap: "truncate-middle", color: on ? "cyan" : p.endsWith("/") ? "blue" : undefined, bold: on }, on ? "❯ " : " ", p);
1514
+ }), h(Hint, {
1515
+ width: hintWidth,
1516
+ variants: [
1517
+ ...completion?.hint ? [` ↑↓ select · enter/tab insert · ${completion.hint}`] : [],
1518
+ " ↑↓ select · enter/tab insert",
1519
+ " ↑↓ · enter insert"
1520
+ ]
1521
+ })) : notice ? h(Text, { color: "yellow" }, ` ${notice}`) : null, flash ? h(Box, { position: "absolute", top: 0, right: 2 }, h(Text, { color: "green" }, ` ${flash} `)) : bang ? h(Box, { position: "absolute", top: 0, right: 2 }, h(Text, { color: "magenta" }, ` ${prefixLabel} `)) : null);
1603
1522
  }
1604
- /** 提示在输入框里只显示第一行,后面还有时加 … */
1605
1523
  const hintLine = (hint) => {
1606
- const [first, ...rest] = hint.split("\n");
1607
- return `${first}${rest.length ? " …" : ""}`;
1524
+ const [first, ...rest] = hint.split(`
1525
+ `);
1526
+ return `${first}${rest.length ? " …" : ""}`;
1608
1527
  };
1609
- /** @ 补全最多显示几项 */
1610
1528
  const MENTION_ROWS = 8;
1611
- /** 长列表只显示 size 项时,为了让第 selected 项在中间附近,从第几项开始显示 */
1529
+ const FOLD_PASTE_LINES = 10;
1530
+ const FOLD_PASTE_CHARS = 2000;
1531
+ const PASTED = /\[Pasted text #\d+ (?:\+\d+ lines|\d+ chars)\]/g;
1612
1532
  function around(selected, total, size) {
1613
- return Math.max(0, Math.min(selected - Math.floor(size / 2), total - size));
1533
+ return Math.max(0, Math.min(selected - Math.floor(size / 2), total - size));
1614
1534
  }
1615
- /** 用户上一次在输入框里打字的时间;发送之后清零 */
1616
1535
  let typedAt = 0;
1617
- /** 打字停下这么久之后,对话框才把回车和字符当成回答 */
1618
1536
  const TYPING_GRACE = 500;
1619
- /**
1620
- * 对话框弹出时用户正在输入框里打字(例如在排下一条消息时弹出审批):接着打出来的回车、数字不能当成回答。
1621
- * 返回 true 表示这个键要丢掉。方向键、Esc 说明用户已经看到对话框了,不再拦
1622
- */
1623
1537
  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;
1538
+ if (Date.now() - typedAt >= TYPING_GRACE)
1539
+ return false;
1540
+ if (key.escape || key.upArrow || key.downArrow || key.pageUp || key.pageDown || key.ctrl && input === "c" || MOUSE.test(input)) {
1541
+ typedAt = 0;
1542
+ return false;
1543
+ }
1544
+ typedAt = Date.now();
1545
+ return true;
1632
1546
  }
1633
- /** 选择框一次最多显示几项 */
1634
1547
  const VISIBLE = 10;
1635
- /** 选项多于这么多时可以打字筛选(这时 j/k 和数字键不再是快捷键) */
1636
1548
  const FILTER_FROM = 10;
1637
- function SelectDialog({ dialog, }) {
1638
- const selection = useContext(SelectionContext);
1639
- const [getSelected, setSelected] = useLive(0);
1640
- const [getQuery, setQuery] = useLive("");
1641
- /** 预览从第几行开始显示,以及它能翻到哪里、一页几行(放得下时 maxTop 是 0) */
1642
- const [getTop, setTop] = useLive(0);
1643
- const scrolling = useRef({ maxTop: 0, page: 1 });
1644
- const { rows, columns } = useScreenSize();
1645
- const filtering = dialog.choices.length > FILTER_FROM;
1646
- const query = getQuery();
1647
- /** 筛选后的选项和它们原来的序号 */
1648
- const filtered = () => {
1649
- const q = getQuery().toLowerCase();
1650
- return dialog.choices
1651
- .map((c, i) => ({ c, i }))
1652
- .filter(({ c }) => !q || `${c.label} ${c.hint ?? ""}`.toLowerCase().includes(q));
1653
- };
1549
+ function SelectDialog({
1550
+ dialog
1551
+ }) {
1552
+ const selection = useContext(SelectionContext);
1553
+ const [getSelected, setSelected] = useLive(0);
1554
+ const [getQuery, setQuery] = useLive("");
1555
+ const [getTop, setTop] = useLive(0);
1556
+ const scrolling = useRef({ maxTop: 0, page: 1 });
1557
+ const { rows, columns } = useScreenSize();
1558
+ const filtering = dialog.choices.length > FILTER_FROM;
1559
+ const query = getQuery();
1560
+ const filtered = () => {
1561
+ const q = getQuery().toLowerCase();
1562
+ return dialog.choices.map((c, i) => ({ c, i })).filter(({ c }) => !q || `${c.label} ${c.hint ?? ""}`.toLowerCase().includes(q));
1563
+ };
1564
+ const items = filtered();
1565
+ const n = items.length;
1566
+ const selected = Math.min(getSelected(), Math.max(0, n - 1));
1567
+ const visible = roomFor(rows, VISIBLE);
1568
+ const lines = !dialog.body ? [] : wrap(dialog.body, Math.max(1, columns - 4)).map(visibleRow);
1569
+ const room = Math.max(3, rows - Math.min(n, visible) - 16);
1570
+ const page = room - 1;
1571
+ const maxTop = Math.max(0, lines.length - page);
1572
+ const top = Math.min(getTop(), maxTop);
1573
+ scrolling.current = { maxTop, page };
1574
+ const body = lines.length > room ? [
1575
+ ...lines.slice(top, top + page),
1576
+ dim(top < maxTop ? `… ${lines.length - top - page} more lines · PgDn/PgUp to scroll` : `end of ${lines.length} lines · PgUp to scroll back`)
1577
+ ] : lines;
1578
+ useInput((input, key) => {
1579
+ if (key.ctrl && input === "c" && selection.active())
1580
+ return selection.clear();
1581
+ if (typedThrough(input, key))
1582
+ return;
1654
1583
  const items = filtered();
1655
1584
  const n = items.length;
1656
1585
  const selected = Math.min(getSelected(), Math.max(0, n - 1));
1657
- // 终端矮时少显示几项,加上预览一起不超过终端的高度
1658
- const visible = roomFor(rows, VISIBLE);
1659
- // 预览(例如要写入的文件)过长时截断:整个界面高过终端时 Ink 会每帧清屏重画,底部的选项和提示也会被裁掉。
1660
- // 按折行后的屏幕行数截断(一行长代码会占好几行),每一行单独显示、不再折行
1661
- const lines = !dialog.body ? [] : wrap(dialog.body, Math.max(1, columns - 4)).map(visibleRow);
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 };
1668
- const body = lines.length > room
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
- ]
1675
- : lines;
1676
- useInput((input, key) => {
1677
- if (key.ctrl && input === "c" && selection.active())
1678
- return selection.clear();
1679
- if (typedThrough(input, key))
1680
- return;
1681
- const items = filtered();
1682
- const n = items.length;
1683
- const selected = Math.min(getSelected(), Math.max(0, n - 1));
1684
- if (key.upArrow || (!filtering && input === "k"))
1685
- return n && setSelected((selected - 1 + n) % n);
1686
- if (key.downArrow || (!filtering && input === "j"))
1687
- return n && setSelected((selected + 1) % n);
1688
- if (key.return) {
1689
- if (n)
1690
- dialog.resolve(items[selected].c.value);
1691
- return;
1692
- }
1693
- if (key.escape && filtering && getQuery()) {
1694
- setQuery("");
1695
- return setSelected(0);
1696
- }
1697
- if (key.escape || (key.ctrl && input === "c"))
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
- }
1704
- if (key.pageDown)
1705
- return setSelected(Math.min(n - 1, selected + visible));
1706
- if (key.pageUp)
1707
- return setSelected(Math.max(0, selected - visible));
1708
- if (filtering) {
1709
- if (key.backspace || key.delete) {
1710
- setQuery([...getQuery()].slice(0, -1).join(""));
1711
- return setSelected(0);
1712
- }
1713
- if (key.ctrl || key.meta || key.tab || MOUSE.test(input))
1714
- return;
1715
- const text = input.replace(/[\x00-\x1f\x7f]/g, "");
1716
- if (text) {
1717
- setQuery(getQuery() + text);
1718
- setSelected(0);
1719
- }
1720
- return;
1721
- }
1722
- const digit = Number(input);
1723
- if (Number.isInteger(digit) && digit >= 1 && digit <= Math.min(n, 9))
1724
- dialog.resolve(items[digit - 1].c.value);
1725
- });
1726
- // 选项多时只显示选中项附近的一段
1727
- const start = around(selected, n, visible);
1728
- return h(Box, { flexDirection: "column", borderStyle: "round", borderColor: "yellow", paddingX: 1, marginTop: 1 }, h(Text, { bold: true, wrap: "truncate-end" }, dialog.title), body.map((l, i) => h(Text, { key: i, wrap: "truncate-end" }, l || " ")), filtering
1729
- ? h(Text, { wrap: "truncate-end" }, h(Text, { color: "cyan" }, "filter› "), query ? h(Text, null, query) : h(Text, { dimColor: true }, `type to filter ${dialog.choices.length} items`))
1730
- : null, h(Box, { flexDirection: "column", marginTop: filtering ? 0 : 1 }, start > 0 ? h(Text, { dimColor: true }, ` ↑ ${start} more`) : null, n === 0 ? h(Text, { dimColor: true }, " no match") : null, items.slice(start, start + visible).map(({ c, i }, j) => {
1731
- const on = start + j === selected;
1732
- return h(Text, { key: i, wrap: "truncate-end" }, h(Text, { color: on ? "cyan" : undefined, bold: on }, on ? "❯ " : " ", filtering ? "" : `${i + 1}. `, c.label), c.hint ? h(Text, { dimColor: true }, ` ${c.hint}`) : null);
1733
- }), start + visible < n ? h(Text, { dimColor: true }, ` ↓ ${n - start - visible} more`) : null), h(Hint, {
1734
- width: Math.max(10, columns - 4),
1735
- variants: filtering
1736
- ? ["↑↓ select · type to filter · enter confirm · esc clear/cancel", "↑↓ · enter · esc"]
1737
- : ["↑↓ select · enter confirm · esc cancel", "↑↓ · enter · esc"],
1738
- }));
1586
+ if (key.upArrow || !filtering && input === "k")
1587
+ return n && setSelected((selected - 1 + n) % n);
1588
+ if (key.downArrow || !filtering && input === "j")
1589
+ return n && setSelected((selected + 1) % n);
1590
+ if (key.return) {
1591
+ if (n)
1592
+ dialog.resolve(items[selected].c.value);
1593
+ return;
1594
+ }
1595
+ if (key.escape && filtering && getQuery()) {
1596
+ setQuery("");
1597
+ return setSelected(0);
1598
+ }
1599
+ if (key.escape || key.ctrl && input === "c")
1600
+ return dialog.resolve(undefined);
1601
+ const { maxTop, page } = scrolling.current;
1602
+ if (maxTop > 0 && (key.pageDown || key.pageUp)) {
1603
+ return setTop(Math.max(0, Math.min(maxTop, Math.min(getTop(), maxTop) + (key.pageDown ? page : -page))));
1604
+ }
1605
+ if (key.pageDown)
1606
+ return setSelected(Math.min(n - 1, selected + visible));
1607
+ if (key.pageUp)
1608
+ return setSelected(Math.max(0, selected - visible));
1609
+ if (filtering) {
1610
+ if (key.backspace || key.delete) {
1611
+ setQuery([...getQuery()].slice(0, -1).join(""));
1612
+ return setSelected(0);
1613
+ }
1614
+ if (key.ctrl || key.meta || key.tab || MOUSE.test(input))
1615
+ return;
1616
+ const text = input.replace(/[\x00-\x1f\x7f]/g, "");
1617
+ if (text) {
1618
+ setQuery(getQuery() + text);
1619
+ setSelected(0);
1620
+ }
1621
+ return;
1622
+ }
1623
+ const digit = Number(input);
1624
+ if (Number.isInteger(digit) && digit >= 1 && digit <= Math.min(n, 9))
1625
+ dialog.resolve(items[digit - 1].c.value);
1626
+ });
1627
+ const start = around(selected, n, visible);
1628
+ return h(Box, { flexDirection: "column", borderStyle: "round", borderColor: "yellow", paddingX: 1, marginTop: 1 }, h(Text, { bold: true, wrap: "truncate-end" }, dialog.title), body.map((l, i) => h(Text, { key: i, wrap: "truncate-end" }, l || " ")), filtering ? h(Text, { wrap: "truncate-end" }, h(Text, { color: "cyan" }, "filter› "), query ? h(Text, null, query) : h(Text, { dimColor: true }, `type to filter ${dialog.choices.length} items`)) : null, h(Box, { flexDirection: "column", marginTop: filtering ? 0 : 1 }, start > 0 ? h(Text, { dimColor: true }, ` ↑ ${start} more`) : null, n === 0 ? h(Text, { dimColor: true }, " no match") : null, items.slice(start, start + visible).map(({ c, i }, j) => {
1629
+ const on = start + j === selected;
1630
+ return h(Text, { key: i, wrap: "truncate-end" }, h(Text, { color: on ? "cyan" : undefined, bold: on }, on ? "❯ " : " ", filtering ? "" : `${i + 1}. `, c.label), c.hint ? h(Text, { dimColor: true }, ` ${c.hint}`) : null);
1631
+ }), start + visible < n ? h(Text, { dimColor: true }, ` ↓ ${n - start - visible} more`) : null), h(Hint, {
1632
+ width: Math.max(10, columns - 4),
1633
+ variants: filtering ? ["↑↓ select · type to filter · enter confirm · esc clear/cancel", "↑↓ · enter · esc"] : ["↑↓ select · enter confirm · esc cancel", "↑↓ · enter · esc"]
1634
+ }));
1739
1635
  }
1740
- function InputDialog({ dialog, }) {
1741
- const selection = useContext(SelectionContext);
1742
- const initial = dialog.initial ?? "";
1743
- const [current, setState] = useLive({
1744
- value: initial,
1745
- cursor: initial.length,
1746
- });
1636
+ function InputDialog({
1637
+ dialog
1638
+ }) {
1639
+ const selection = useContext(SelectionContext);
1640
+ const initial = dialog.initial ?? "";
1641
+ const [current, setState] = useLive({
1642
+ value: initial,
1643
+ cursor: initial.length
1644
+ });
1645
+ const state = current();
1646
+ const { columns } = useScreenSize();
1647
+ usePaste((text) => setState(edit.insert(current(), text.replace(/\r?\n/g, ""))));
1648
+ useInput((input, key) => {
1649
+ if (key.ctrl && input === "c" && selection.active())
1650
+ return selection.clear();
1651
+ if (typedThrough(input, key))
1652
+ return;
1747
1653
  const state = current();
1748
- const { columns } = useScreenSize();
1749
- usePaste((text) => setState(edit.insert(current(), text.replace(/\r?\n/g, ""))));
1750
- useInput((input, key) => {
1751
- if (key.ctrl && input === "c" && selection.active())
1752
- return selection.clear();
1753
- if (typedThrough(input, key))
1754
- return;
1755
- const state = current();
1756
- if (key.return)
1757
- return dialog.resolve(state.value.trim());
1758
- if (key.escape || (key.ctrl && input === "c"))
1759
- return dialog.resolve(undefined);
1760
- const next = editKey(state, input, key);
1761
- if (next)
1762
- setState(next);
1763
- });
1764
- return h(Box, { flexDirection: "column", borderStyle: "round", borderColor: "yellow", paddingX: 1, marginTop: 1 }, h(Text, { bold: true }, dialog.title), h(EditableText, {
1765
- state,
1766
- width: Math.max(10, columns - 6),
1767
- prefix: "› ",
1768
- mask: dialog.mask,
1769
- placeholder: dialog.placeholder,
1770
- active: true,
1771
- }), h(Text, { dimColor: true }, "enter confirm · esc cancel"));
1654
+ if (key.return)
1655
+ return dialog.resolve(state.value.trim());
1656
+ if (key.escape || key.ctrl && input === "c")
1657
+ return dialog.resolve(undefined);
1658
+ const next = editKey(state, input, key);
1659
+ if (next)
1660
+ setState(next);
1661
+ });
1662
+ return h(Box, { flexDirection: "column", borderStyle: "round", borderColor: "yellow", paddingX: 1, marginTop: 1 }, h(Text, { bold: true }, dialog.title), h(EditableText, {
1663
+ state,
1664
+ width: Math.max(10, columns - 6),
1665
+ prefix: "› ",
1666
+ mask: dialog.mask,
1667
+ placeholder: dialog.placeholder,
1668
+ active: true
1669
+ }), h(Text, { dimColor: true }, "enter confirm · esc cancel"));
1772
1670
  }