@uncarved/jade 0.5.0 → 0.5.2

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 (86) hide show
  1. package/README.md +320 -317
  2. package/dist/api.d.ts +1 -1
  3. package/dist/api.js +1 -1
  4. package/dist/install.js +5 -0
  5. package/dist/install.js.map +1 -1
  6. package/dist/membrane.d.ts +5 -2
  7. package/dist/membrane.js +8 -3
  8. package/dist/membrane.js.map +1 -1
  9. package/dist/session.d.ts +10 -1
  10. package/dist/session.js +110 -16
  11. package/dist/session.js.map +1 -1
  12. package/package.json +6 -6
  13. package/plugins/approval/index.ts +129 -13
  14. package/plugins/approval/plugin.json +4 -1
  15. package/plugins/approval/policy.ts +127 -7
  16. package/plugins/approval/review.ts +188 -45
  17. package/plugins/ask/index.ts +29 -1
  18. package/plugins/budget/index.ts +44 -6
  19. package/plugins/budget/plugin.json +1 -2
  20. package/plugins/compact/compact.ts +153 -39
  21. package/plugins/compact/index.ts +39 -5
  22. package/plugins/compact/plugin.json +5 -2
  23. package/plugins/cost/cache.ts +114 -0
  24. package/plugins/cost/index.ts +109 -51
  25. package/plugins/cost/plugin.json +3 -2
  26. package/plugins/memory/memory.ts +51 -28
  27. package/plugins/models/configure.ts +344 -125
  28. package/plugins/models/index.ts +44 -9
  29. package/plugins/models/price.ts +291 -0
  30. package/plugins/models/provider.ts +40 -8
  31. package/plugins/models/saved.ts +20 -4
  32. package/plugins/modes/index.ts +3 -4
  33. package/plugins/prompts/prompts.ts +5 -1
  34. package/plugins/serve/index.ts +7 -0
  35. package/plugins/task/index.ts +31 -10
  36. package/plugins/task/plugin.json +5 -2
  37. package/plugins/task/subagent.ts +21 -4
  38. package/plugins/todo/index.ts +62 -1
  39. package/plugins/todo/plugin.json +1 -1
  40. package/plugins/tui/frontend.ts +31 -5
  41. package/plugins/tui/index.ts +2 -1
  42. package/plugins/tui/plugin.json +1 -1
  43. package/plugins/tui/screen.ts +17 -5
  44. package/plugins/tui/transcript.ts +518 -507
  45. package/plugins/tui/tui.ts +212 -54
  46. package/plugins/withdraw/index.ts +111 -0
  47. package/plugins/withdraw/plugin.json +8 -0
  48. package/plugins-dist/approval/index.js +103 -9
  49. package/plugins-dist/approval/plugin.json +4 -1
  50. package/plugins-dist/approval/policy.js +112 -9
  51. package/plugins-dist/approval/review.js +141 -34
  52. package/plugins-dist/ask/index.js +28 -2
  53. package/plugins-dist/budget/index.js +30 -7
  54. package/plugins-dist/budget/plugin.json +1 -2
  55. package/plugins-dist/compact/compact.js +106 -32
  56. package/plugins-dist/compact/index.js +27 -3
  57. package/plugins-dist/compact/plugin.json +6 -2
  58. package/plugins-dist/cost/cache.js +100 -0
  59. package/plugins-dist/cost/index.js +87 -38
  60. package/plugins-dist/cost/plugin.json +5 -2
  61. package/plugins-dist/memory/memory.js +51 -32
  62. package/plugins-dist/models/configure.js +285 -105
  63. package/plugins-dist/models/index.js +33 -2
  64. package/plugins-dist/models/price.js +244 -0
  65. package/plugins-dist/models/provider.js +22 -4
  66. package/plugins-dist/models/saved.js +13 -3
  67. package/plugins-dist/modes/index.js +2 -3
  68. package/plugins-dist/prompts/prompts.js +5 -1
  69. package/plugins-dist/serve/index.js +6 -0
  70. package/plugins-dist/task/index.js +25 -7
  71. package/plugins-dist/task/plugin.json +5 -2
  72. package/plugins-dist/task/subagent.js +15 -6
  73. package/plugins-dist/todo/index.js +50 -0
  74. package/plugins-dist/todo/plugin.json +1 -1
  75. package/plugins-dist/tui/frontend.js +26 -4
  76. package/plugins-dist/tui/index.js +2 -1
  77. package/plugins-dist/tui/plugin.json +2 -1
  78. package/plugins-dist/tui/screen.js +7 -3
  79. package/plugins-dist/tui/transcript.js +13 -5
  80. package/plugins-dist/tui/tui.js +197 -50
  81. package/plugins-dist/withdraw/index.js +88 -0
  82. package/plugins-dist/withdraw/plugin.json +12 -0
  83. package/src/api.ts +1 -1
  84. package/src/install.ts +5 -0
  85. package/src/membrane.ts +8 -3
  86. package/src/session.ts +124 -20
@@ -533,11 +533,11 @@ export interface TuiOptions {
533
533
  }
534
534
 
535
535
  /**
536
- * 开关鼠标事件上报(SGR 格式),用来接收滚轮、点击和按住左键拖动(1002)。
536
+ * 开关鼠标事件上报(SGR 格式),用来接收滚轮、点击、按住左键拖动(1002)和不按键的移动(1003,悬停提示用)。
537
537
  * 开着时终端自己不再处理点击,所以对话区的文字由 jade 自己选中和复制(见 Selection)
538
538
  */
539
- const MOUSE_ON = "\x1b[?1000h\x1b[?1002h\x1b[?1006h";
540
- const MOUSE_OFF = "\x1b[?1006l\x1b[?1002l\x1b[?1000l";
539
+ const MOUSE_ON = "\x1b[?1000h\x1b[?1002h\x1b[?1003h\x1b[?1006h";
540
+ const MOUSE_OFF = "\x1b[?1006l\x1b[?1003l\x1b[?1002l\x1b[?1000l";
541
541
  /**
542
542
  * 光标样式:闪烁的竖线(DECSCUSR 5,再加上 ATT610 的"开始闪烁"给只认它的终端),一眼能看出输入框有焦点;
543
543
  * 退出时还原成终端自己的默认样式。光标什么时候显示仍由 Ink 管(只有输入框或输入对话框有焦点时才显示)
@@ -923,6 +923,8 @@ const WHEEL_LINES = 3;
923
923
 
924
924
  /** 按住左键拖动时的按钮号(左键 0 加上移动位 32) */
925
925
  const DRAG = 32;
926
+ /** 不按键移动鼠标时的按钮号("没有按键" 3 加上移动位 32) */
927
+ const MOVE = 35;
926
928
  /** "已复制"的提示显示多久 */
927
929
  const COPIED_MS = 2000;
928
930
 
@@ -1100,6 +1102,8 @@ function App({
1100
1102
  // 对话区占掉标题和底部之外的全部高度,只画能看见的那几行
1101
1103
  const ref = useRef<DOMElement>(null);
1102
1104
  const { height, top } = useBoxMetrics(ref);
1105
+ /** 标题里放文字的 Box:点上面的字段复制它(见 headerFields) */
1106
+ const headerRef = useRef<DOMElement>(null);
1103
1107
  const width = Math.max(10, columns - 2);
1104
1108
  // 往上翻看时要折到能看见的地方;多要一屏给翻页
1105
1109
  const done = store.lines(width, state.scroll + 2 * rows);
@@ -1169,6 +1173,9 @@ function App({
1169
1173
  useEffect(() => () => clearTimeout(copiedTimer.current), []);
1170
1174
  /** 输入框文字在屏幕上的位置(Prompt 里的 EditableText 每次渲染时写入) */
1171
1175
  const inputPlace = useRef<Placement>(undefined);
1176
+ // 鼠标停在状态栏里后台的事那一段上:那一段反色,看得出能点
1177
+ const [hover, setHover] = useState(false);
1178
+ const hovering = useRef(false);
1172
1179
  const copySelection = (s: Selection) => copyText(selectedText(s, (i) => rowAt(i + front)));
1173
1180
  const copyText = (text: string) => {
1174
1181
  copy(text);
@@ -1191,10 +1198,20 @@ function App({
1191
1198
  if (key.ctrl && input === "t") return store.openJobs();
1192
1199
  const mouse = mouseEvent(input);
1193
1200
  if (mouse) {
1194
- // 点状态栏(界面的最后一行,比终端少一行)里后台的事那一段也能打开列表:终端自己占用了 ctrl+t 时用
1195
- if (mouse.button === 0 && mouse.press && mouse.y === rows - 2) {
1196
- const cols = jobsColumns(statusSegments(state.status, state.jobs, statusWidth));
1197
- if (cols && mouse.x >= cols[0] && mouse.x <= cols[1]) return store.openJobs();
1201
+ // 状态栏(界面的最后一行,比终端少一行)里后台的事那一段:悬停时反色,点它打开列表(终端自己占用了 ctrl+t 时用)
1202
+ const cols = mouse.y === rows - 2 ? jobsColumns(statusSegments(state.status, state.jobs, statusWidth)) : undefined;
1203
+ const overJobs = cols !== undefined && mouse.x >= cols[0] && mouse.x <= cols[1];
1204
+ if (overJobs !== hovering.current) {
1205
+ hovering.current = overJobs;
1206
+ setHover(overJobs);
1207
+ }
1208
+ if (mouse.button === MOVE) return;
1209
+ if (mouse.button === 0 && mouse.press && overJobs) return store.openJobs();
1210
+ // 点标题里的 session、模型、目录、分支:复制它(不用按住 Shift 让终端自己选)
1211
+ if (mouse.button === 0 && mouse.press && headerRef.current) {
1212
+ const o = origin(headerRef.current);
1213
+ const hit = headerFields(state.status, version, compact).find((f) => mouse.y - o.y === f.row && mouse.x - o.x >= f.from && mouse.x - o.x < f.to);
1214
+ if (hit) return copyText(hit.text);
1198
1215
  }
1199
1216
  // 对话区里的位置;clamp 时拖出对话区停在第一行或最后一行,否则在对话区外返回 undefined
1200
1217
  const at = (clamp: boolean): Point | undefined => {
@@ -1205,7 +1222,8 @@ function App({
1205
1222
  // 滚轮在放不下全部文字的输入框上(含上下边框)时由输入框自己翻
1206
1223
  const input = inputPlace.current;
1207
1224
  const overInput = input && input.total > input.rows && mouse.y >= input.y - 1 && mouse.y <= input.y + input.rows;
1208
- if ((mouse.button === 64 || mouse.button === 65) && overInput) return;
1225
+ // 后台的事的列表、选择框开着时滚轮由它们自己处理
1226
+ if ((mouse.button === 64 || mouse.button === 65) && (overInput || dialog?.kind === "jobs" || dialog?.kind === "select")) return;
1209
1227
  if (mouse.button === 64) store.scrollBy(WHEEL_LINES, max);
1210
1228
  else if (mouse.button === 65) store.scrollBy(-WHEEL_LINES, max);
1211
1229
  else if (mouse.button === 0 && mouse.press) {
@@ -1275,7 +1293,7 @@ function App({
1275
1293
  h(
1276
1294
  Box,
1277
1295
  { flexDirection: "column", flexGrow: 1, overflowY: "hidden" },
1278
- h(Header, { status: state.status, version, compact, bot, completions: handlers.completions?.() ?? [] }),
1296
+ h(Header, { status: state.status, version, compact, bot, textRef: headerRef, completions: handlers.completions?.() ?? [] }),
1279
1297
  h(
1280
1298
  Box,
1281
1299
  {
@@ -1336,7 +1354,7 @@ function App({
1336
1354
  place: inputPlace,
1337
1355
  onCopy: copyText,
1338
1356
  }),
1339
- h(StatusBar, { status: state.status, jobs: state.jobs, width: statusWidth }),
1357
+ h(StatusBar, { status: state.status, jobs: state.jobs, width: statusWidth, hover }),
1340
1358
  ),
1341
1359
  ),
1342
1360
  ),
@@ -1366,9 +1384,12 @@ function Header({
1366
1384
  version,
1367
1385
  compact,
1368
1386
  bot,
1387
+ textRef,
1369
1388
  }: {
1370
1389
  status: StatusInfo;
1371
1390
  version: string;
1391
+ /** 放文字的那个 Box(见 headerFields) */
1392
+ textRef: { current: DOMElement | null };
1372
1393
  /** 吉祥物这一帧的像素(见 mascot.ts);放不下时 undefined */
1373
1394
  bot?: (string | undefined)[][];
1374
1395
  /** 终端很矮时只占一行,把高度留给对话和输入框 */
@@ -1386,7 +1407,7 @@ function Header({
1386
1407
  if (compact)
1387
1408
  return h(
1388
1409
  Box,
1389
- { flexShrink: 0, paddingX: 1 },
1410
+ { ref: textRef, flexShrink: 0, paddingX: 1 },
1390
1411
  h(Text, { wrap: "truncate-end" }, name, h(Text, { key: "dot", dimColor: true }, " · "), ...where),
1391
1412
  );
1392
1413
  return h(
@@ -1395,7 +1416,7 @@ function Header({
1395
1416
  bot ? h(Bot, { pixels: bot }) : null,
1396
1417
  h(
1397
1418
  Box,
1398
- { flexDirection: "column", flexGrow: 1, flexShrink: 1 },
1419
+ { ref: textRef, flexDirection: "column", flexGrow: 1, flexShrink: 1 },
1399
1420
  h(
1400
1421
  Text,
1401
1422
  { wrap: "truncate-end" },
@@ -1409,6 +1430,29 @@ function Header({
1409
1430
  );
1410
1431
  }
1411
1432
 
1433
+ /**
1434
+ * 标题里点一下就复制的字段(session、模型、目录、分支):row、from、to 相对 textRef 那个 Box 的左上角,to 不含。
1435
+ * 要和 Header 画的文字对得上
1436
+ */
1437
+ export function headerFields(status: StatusInfo, version: string, compact: boolean): { row: number; from: number; to: number; text: string }[] {
1438
+ const out: { row: number; from: number; to: number; text: string }[] = [];
1439
+ const line = (row: number, x: number, parts: [text: string, copy: boolean][]) => {
1440
+ for (const [text, copy] of parts) {
1441
+ const w = visibleWidth(text);
1442
+ if (copy && text) out.push({ row, from: x, to: x + w, text });
1443
+ x += w;
1444
+ }
1445
+ };
1446
+ const where: [string, boolean][] = [[status.model, true], [" · ", false], [status.cwd, true], ...(status.branch ? ([[" (", false], [status.branch, true]] as [string, boolean][]) : [])];
1447
+ // 紧凑的标题只有一行,Box 左边有一格 padding
1448
+ if (compact) line(0, 1, [["jade · ", false], ...where]);
1449
+ else {
1450
+ if (status.session) line(0, 0, [[`jade v${version} · session `, false], [status.session, true]]);
1451
+ line(1, 0, where);
1452
+ }
1453
+ return out;
1454
+ }
1455
+
1412
1456
  const dialogIds = new WeakMap<Dialog, number>();
1413
1457
  let dialogCounter = 0;
1414
1458
  function dialogKey(d: Dialog): number {
@@ -1446,6 +1490,8 @@ interface Segment {
1446
1490
  dropAt?: number;
1447
1491
  color?: string;
1448
1492
  dim?: boolean;
1493
+ /** 反色显示(鼠标停在能点的段上) */
1494
+ inverse?: boolean;
1449
1495
  /** 后台的事的那一段:点一下打开列表 */
1450
1496
  jobs?: boolean;
1451
1497
  }
@@ -1475,10 +1521,14 @@ export function fitSegments(segments: Segment[], width: number): Segment[] {
1475
1521
  }
1476
1522
 
1477
1523
  /** 状态栏的内容,已经按宽度缩短 */
1478
- function statusSegments(status: StatusInfo, jobs: JobInfo[], width: number): Segment[] {
1524
+ export function statusSegments(status: StatusInfo, jobs: JobInfo[], width: number, hover = false): Segment[] {
1479
1525
  const ctx = status.context;
1480
1526
  const pct = ctx ? Math.round((ctx.used / ctx.limit) * 100) : 0;
1481
1527
  const nearFull = pct >= 80;
1528
+ const cache = status.cache;
1529
+ const percent = (r: number) => `${Math.round(r * 1000) / 10}%`;
1530
+ // 这一次命中不到一半、又比平均低(第一次请求没有缓存可命中,不算):缓存多半断了或过期了
1531
+ const cacheLow = cache !== undefined && cache.last < 0.5 && cache.last < cache.avg;
1482
1532
  const speed = status.speed;
1483
1533
  // 插件的段落:要一直留着的(keep,例如 jade/modes 的当前模式)放在最前,窄的时候换成短写法;其余的比提示晚、比缓存早去掉
1484
1534
  const plugin = (p: { text: string | StatusSegment }, keep: boolean): Segment => {
@@ -1492,12 +1542,12 @@ function statusSegments(status: StatusInfo, jobs: JobInfo[], width: number): Seg
1492
1542
  };
1493
1543
  const kept = (status.plugins ?? []).filter((p) => typeof p.text !== "string" && p.text.keep);
1494
1544
  const others = (status.plugins ?? []).filter((p) => !kept.includes(p));
1495
- // 窄的时候依次:提示变短、去掉提示、用量变短、去掉缓存、模式变短、去掉用量、上下文变短、去掉速度
1545
+ // 窄的时候依次:用量变短、缓存去掉平均值、去掉缓存、模式变短、去掉用量、上下文变短、去掉速度
1496
1546
  const running = runningJobs(jobs);
1497
1547
  const segments: Segment[] = [
1498
1548
  ...kept.map((p) => plugin(p, true)),
1499
- // 在后台运行的事:一直留着,窄的时候去掉按键说明
1500
- ...(running ? [{ text: `${running} · click or ctrl+t to view`, short: running, shortAt: 6.5, color: "cyan", jobs: true }] : []),
1549
+ // 在后台运行的事:一直留着;鼠标停在上面时反色,像个按钮,宽度不变,旁边的段不会跟着挪
1550
+ ...(running ? [{ text: running, color: "cyan", inverse: hover, jobs: true }] : []),
1501
1551
  ctx
1502
1552
  ? {
1503
1553
  text: `ctx ${tokens(ctx.used)}/${tokens(ctx.limit)} (${pct}%)`,
@@ -1516,8 +1566,17 @@ function statusSegments(status: StatusInfo, jobs: JobInfo[], width: number): Seg
1516
1566
  },
1517
1567
  ]
1518
1568
  : []),
1519
- ...(status.cache !== undefined
1520
- ? [{ text: `cache ${Math.round(status.cache * 1000) / 10}%`, dropAt: 7, dim: true }]
1569
+ ...(cache
1570
+ ? [
1571
+ {
1572
+ text: `cache ${percent(cache.last)} (avg ${percent(cache.avg)})`,
1573
+ short: `cache ${percent(cache.last)}`,
1574
+ shortAt: 7.8,
1575
+ dropAt: 7,
1576
+ color: cacheLow ? "yellow" : undefined,
1577
+ dim: !cacheLow,
1578
+ },
1579
+ ]
1521
1580
  : []),
1522
1581
  ...(status.spent
1523
1582
  ? [
@@ -1531,13 +1590,6 @@ function statusSegments(status: StatusInfo, jobs: JobInfo[], width: number): Seg
1531
1590
  ]
1532
1591
  : []),
1533
1592
  ...others.map((p) => plugin(p, false)),
1534
- {
1535
- text: "PgUp/PgDn scroll · click ▸ or ctrl+o to expand · drag to select and copy",
1536
- short: "ctrl+o to expand",
1537
- shortAt: 10,
1538
- dropAt: 9,
1539
- dim: true,
1540
- },
1541
1593
  ];
1542
1594
  return fitSegments(segments, width);
1543
1595
  }
@@ -1558,8 +1610,8 @@ function jobsColumns(segments: Segment[]): [number, number] | undefined {
1558
1610
  return undefined;
1559
1611
  }
1560
1612
 
1561
- function StatusBar({ status, jobs, width }: { status: StatusInfo; jobs: JobInfo[]; width: number }) {
1562
- const shown = statusSegments(status, jobs, width);
1613
+ function StatusBar({ status, jobs, width, hover }: { status: StatusInfo; jobs: JobInfo[]; width: number; hover: boolean }) {
1614
+ const shown = statusSegments(status, jobs, width, hover);
1563
1615
  return h(
1564
1616
  Box,
1565
1617
  { paddingX: 1 },
@@ -1567,7 +1619,7 @@ function StatusBar({ status, jobs, width }: { status: StatusInfo; jobs: JobInfo[
1567
1619
  Text,
1568
1620
  { wrap: "truncate-end" },
1569
1621
  shown.map((s, i) =>
1570
- h(Text, { key: i }, i ? h(Text, { dimColor: true }, " · ") : null, h(Text, { color: s.color, dimColor: s.dim }, s.text)),
1622
+ h(Text, { key: i }, i ? h(Text, { dimColor: true }, " · ") : null, h(Text, { color: s.color, dimColor: s.dim, inverse: s.inverse }, s.text)),
1571
1623
  ),
1572
1624
  ),
1573
1625
  );
@@ -2368,7 +2420,8 @@ function SelectDialog({
2368
2420
  dialog: Extract<Dialog, { kind: "select" }>;
2369
2421
  }) {
2370
2422
  const selection = useContext(SelectionContext);
2371
- const [getSelected, setSelected] = useLive(0);
2423
+ // 打开时选中现在用着的那一项
2424
+ const [getSelected, setSelected] = useLive(Math.max(0, dialog.choices.findIndex((c) => c.current)));
2372
2425
  const [getQuery, setQuery] = useLive("");
2373
2426
  /** 预览从第几行开始显示,以及它能翻到哪里、一页几行(放得下时 maxTop 是 0) */
2374
2427
  const [getTop, setTop] = useLive(0);
@@ -2381,7 +2434,7 @@ function SelectDialog({
2381
2434
  const q = getQuery().toLowerCase();
2382
2435
  return dialog.choices
2383
2436
  .map((c, i) => ({ c, i }))
2384
- .filter(({ c }) => !q || `${c.label} ${c.hint ?? ""}`.toLowerCase().includes(q));
2437
+ .filter(({ c }) => !q || `${c.label} ${c.hint ?? ""} ${c.group ?? ""}`.toLowerCase().includes(q));
2385
2438
  };
2386
2439
  const items = filtered();
2387
2440
  const n = items.length;
@@ -2414,6 +2467,15 @@ function SelectDialog({
2414
2467
  const items = filtered();
2415
2468
  const n = items.length;
2416
2469
  const selected = Math.min(getSelected(), Math.max(0, n - 1));
2470
+ // 滚轮:预览放不下时翻预览(同 PgUp/PgDn),否则上下移动选中项
2471
+ const mouse = mouseEvent(input);
2472
+ if (mouse) {
2473
+ const wheel = mouse.button === 64 ? -1 : mouse.button === 65 ? 1 : 0;
2474
+ if (!wheel) return;
2475
+ const { maxTop } = scrolling.current;
2476
+ if (maxTop > 0) return setTop(Math.max(0, Math.min(maxTop, Math.min(getTop(), maxTop) + wheel * WHEEL_LINES)));
2477
+ return n && setSelected(Math.max(0, Math.min(n - 1, selected + wheel)));
2478
+ }
2417
2479
  if (key.upArrow || (!filtering && input === "k"))
2418
2480
  return n && setSelected((selected - 1 + n) % n);
2419
2481
  if (key.downArrow || (!filtering && input === "j"))
@@ -2452,8 +2514,24 @@ function SelectDialog({
2452
2514
  if (Number.isInteger(digit) && digit >= 1 && digit <= Math.min(n, 9))
2453
2515
  dialog.resolve(items[digit - 1]!.c.value);
2454
2516
  });
2455
- // 选项多时只显示选中项附近的一段
2456
- const start = around(selected, n, visible);
2517
+ // 选项多时只显示选中项附近的一段。分组的标题也占一行:第一项有分组时总带上它的标题,
2518
+ // 放不下选中项时往后挪
2519
+ const shownFrom = (from: number) => {
2520
+ const out: { k: number; head?: string }[] = [];
2521
+ for (let k = from, used = 0; k < n; k++) {
2522
+ const g = items[k]!.c.group;
2523
+ const head = g !== undefined && (k === from || items[k - 1]!.c.group !== g) ? g : undefined;
2524
+ const rows = head === undefined ? 1 : 2;
2525
+ if (used + rows > visible && out.length) break;
2526
+ out.push({ k, ...(head === undefined ? {} : { head }) });
2527
+ used += rows;
2528
+ }
2529
+ return out;
2530
+ };
2531
+ let start = around(selected, n, visible);
2532
+ let shown = shownFrom(start);
2533
+ while (start < selected && !shown.some((r) => r.k === selected)) shown = shownFrom(++start);
2534
+ const end = shown.length ? shown.at(-1)!.k + 1 : start;
2457
2535
  return h(
2458
2536
  Box,
2459
2537
  { flexDirection: "column", borderStyle: "round", borderColor: "yellow", paddingX: 1, marginTop: 1 },
@@ -2472,16 +2550,19 @@ function SelectDialog({
2472
2550
  { flexDirection: "column", marginTop: filtering ? 0 : 1 },
2473
2551
  start > 0 ? h(Text, { dimColor: true }, ` ↑ ${start} more`) : null,
2474
2552
  n === 0 ? h(Text, { dimColor: true }, " no match") : null,
2475
- items.slice(start, start + visible).map(({ c, i }, j) => {
2476
- const on = start + j === selected;
2477
- return h(
2553
+ shown.flatMap(({ k, head }) => {
2554
+ const { c, i } = items[k]!;
2555
+ const on = k === selected;
2556
+ const row = h(
2478
2557
  Text,
2479
2558
  { key: i, wrap: "truncate-end" },
2480
- h(Text, { color: on ? "cyan" : undefined, bold: on }, on ? "❯ " : " ", filtering ? "" : `${i + 1}. `, c.label),
2559
+ h(Text, { color: on ? "cyan" : c.current ? "green" : undefined, bold: on || c.current }, on ? "❯ " : " ", filtering ? "" : `${i + 1}. `, c.label),
2560
+ c.current ? h(Text, { color: "green", bold: true }, " ● current") : null,
2481
2561
  c.hint ? h(Text, { dimColor: true }, ` ${c.hint}`) : null,
2482
2562
  );
2563
+ return head === undefined ? [row] : [h(Text, { key: `group-${i}`, bold: true, dimColor: true, wrap: "truncate-end" }, ` ${head}`), row];
2483
2564
  }),
2484
- start + visible < n ? h(Text, { dimColor: true }, ` ↓ ${n - start - visible} more`) : null,
2565
+ end < n ? h(Text, { dimColor: true }, ` ↓ ${n - end} more`) : null,
2485
2566
  ),
2486
2567
  h(Hint, {
2487
2568
  width: Math.max(10, columns - 4),
@@ -2502,9 +2583,43 @@ export function runningJobs(jobs: readonly JobInfo[]): string {
2502
2583
  /** 查看一件后台的事时,输出只折最后这么多行 */
2503
2584
  const JOB_TAIL_LINES = 2000;
2504
2585
 
2586
+ /** 后台的事的输出折好的一行;line 是它属于输出的哪一行,那一行挂着可以展开的内容时才有 */
2587
+ type JobRow = { text: string; line?: number };
2588
+
2589
+ /** 把后台的事的输出折成行:挂着内容(JobInfo.details)的行末尾画 ▸,展开的(open)在它下面接着画内容 */
2590
+ export function jobRows(job: JobInfo, width: number, open: ReadonlySet<number>): JobRow[] {
2591
+ const output = job.output.replace(/\n+$/, "");
2592
+ if (!output) return [];
2593
+ const all = output.split("\n");
2594
+ const from = Math.max(0, all.length - JOB_TAIL_LINES);
2595
+ const rows = (text: string, line?: number) => wrap(text, width).map((r) => (line === undefined ? { text: visibleRow(r) } : { text: visibleRow(r), line }));
2596
+ const details = new Map((job.details ?? []).map((d) => [d.line, d.text]));
2597
+ if (details.size === 0) return rows(all.slice(from).join("\n"));
2598
+ // 没挂内容的相邻几行一起折:颜色可能跨行
2599
+ const out: JobRow[] = [];
2600
+ let plain: string[] = [];
2601
+ const flush = () => {
2602
+ if (plain.length) out.push(...rows(plain.join("\n")));
2603
+ plain = [];
2604
+ };
2605
+ for (let i = from; i < all.length; i++) {
2606
+ const detail = details.get(i);
2607
+ if (detail === undefined) {
2608
+ plain.push(all[i]!);
2609
+ continue;
2610
+ }
2611
+ flush();
2612
+ const on = open.has(i);
2613
+ out.push(...rows(`${all[i]}${dim(on ? " ▾" : " ▸")}`, i));
2614
+ if (on) out.push(...rows(detail.replace(/\s+$/, "").replace(/^/gm, " "), i));
2615
+ }
2616
+ flush();
2617
+ return out;
2618
+ }
2619
+
2505
2620
  /**
2506
- * 后台的事(ctrl+t):列表里选一件,enter 看它的输出(跟着最新的,PgUp/PgDn 翻看),x 停掉,esc 返回、关掉。
2507
- * 正在看的那件被去掉了(子 Agent 交了报告)时回到列表
2621
+ * 后台的事(ctrl+t):列表里选一件(或点它),enter 看它的输出(跟着最新的,PgUp/PgDn、滚轮翻看),
2622
+ * 点带 ▸ 的行展开它挂着的内容,x 停掉,esc 返回、关掉。正在看的那件被去掉了(子 Agent 交了报告)时回到列表
2508
2623
  */
2509
2624
  function JobsDialog({ dialog, jobs }: { dialog: Extract<Dialog, { kind: "jobs" }>; jobs: JobInfo[] }) {
2510
2625
  const selection = useContext(SelectionContext);
@@ -2512,24 +2627,69 @@ function JobsDialog({ dialog, jobs }: { dialog: Extract<Dialog, { kind: "jobs" }
2512
2627
  const [getViewing, setViewing] = useLive<number | undefined>(undefined);
2513
2628
  /** 看输出时离底部翻上去了多少行 */
2514
2629
  const [getBack, setBack] = useLive(0);
2630
+ /** 看输出时展开了的行(输出的第几行) */
2631
+ const [getOpen, setOpen] = useLive<ReadonlySet<number>>(new Set());
2515
2632
  const { rows, columns } = useScreenSize();
2516
2633
  const width = Math.max(10, columns - 4);
2517
2634
  const viewing = jobs.find((j) => j.id === getViewing());
2518
2635
  const selected = Math.min(getSelected(), Math.max(0, jobs.length - 1));
2519
2636
  const room = Math.max(3, rows - 14);
2520
2637
  // 输出折好行,只显示末尾 room 行(往上翻了 back 行)
2521
- const lines = viewing ? wrap(viewing.output.replace(/\n+$/, "").split("\n").slice(-JOB_TAIL_LINES).join("\n"), width).map(visibleRow) : [];
2638
+ const lines = viewing ? jobRows(viewing, width, getOpen()) : [];
2522
2639
  const maxBack = Math.max(0, lines.length - room);
2523
2640
  const back = Math.min(getBack(), maxBack);
2524
- const scrolling = useRef({ maxBack, room });
2525
- scrolling.current = { maxBack, room };
2641
+ const shown = lines.slice(lines.length - room - back, lines.length - back);
2642
+ const visible = roomFor(rows, VISIBLE);
2643
+ const start = around(selected, jobs.length, visible);
2644
+ // 点击时按这一帧画出来的样子换算是哪一行
2645
+ const box = useRef<DOMElement>(null);
2646
+ const drawn = useRef({ maxBack, room, lines, shown, width, start, visible });
2647
+ drawn.current = { maxBack, room, lines, shown, width, start, visible };
2648
+ const view = (id: number) => {
2649
+ setBack(0);
2650
+ setOpen(new Set());
2651
+ setViewing(id);
2652
+ };
2526
2653
  useInput((input, key) => {
2527
2654
  if (key.ctrl && input === "c" && selection.active()) return selection.clear();
2528
2655
  const current = jobs.find((j) => j.id === getViewing());
2656
+ const mouse = mouseEvent(input);
2657
+ if (mouse) {
2658
+ const wheel = mouse.button === 64 ? 1 : mouse.button === 65 ? -1 : 0;
2659
+ const click = mouse.button === 0 && mouse.press;
2660
+ if (!wheel && !click) return;
2661
+ const d = drawn.current;
2662
+ // 框的上边框下面一行是标题,内容从再下一行开始
2663
+ const row = box.current ? mouse.y - origin(box.current).y - 2 : -1;
2664
+ if (current) {
2665
+ if (wheel) return setBack(Math.max(0, Math.min(d.maxBack, Math.min(getBack(), d.maxBack) + wheel * WHEEL_LINES)));
2666
+ const above = d.lines.length > d.room + Math.min(getBack(), d.maxBack) ? 1 : 0;
2667
+ const line = d.shown[row - above]?.line;
2668
+ if (line === undefined) return;
2669
+ const open = new Set(getOpen());
2670
+ if (!open.delete(line)) open.add(line);
2671
+ // 点的那一行尽量留在原地:它下面多出(少了)几行,离底部就多(少)几行。
2672
+ // 展开时下面放不下的话往上挪,让展开的内容露出来,但那一行不挪出顶上
2673
+ const added = jobRows(current, d.width, open).length - d.lines.length;
2674
+ const first = d.shown.findIndex((r) => r.line === line);
2675
+ const below = d.shown.length - 1 - d.shown.findLastIndex((r) => r.line === line);
2676
+ const up = added > 0 ? Math.min(first, Math.max(0, added - below)) : 0;
2677
+ setOpen(open);
2678
+ return setBack(Math.max(0, Math.min(getBack(), d.maxBack) + added - up));
2679
+ }
2680
+ const n = jobs.length;
2681
+ if (wheel) return n && setSelected(Math.max(0, Math.min(n - 1, Math.min(getSelected(), n - 1) - wheel)));
2682
+ const i = d.start + row - (d.start > 0 ? 1 : 0);
2683
+ if (i >= d.start && i < Math.min(n, d.start + d.visible)) {
2684
+ setSelected(i);
2685
+ return view(jobs[i]!.id);
2686
+ }
2687
+ return;
2688
+ }
2529
2689
  const target = current ?? jobs[Math.min(getSelected(), jobs.length - 1)];
2530
2690
  if (input === "x" && target && !target.done && target.stop) return target.stop();
2531
2691
  if (current) {
2532
- const { maxBack, room } = scrolling.current;
2692
+ const { maxBack, room } = drawn.current;
2533
2693
  const by = (n: number) => setBack(Math.max(0, Math.min(maxBack, Math.min(getBack(), maxBack) + n)));
2534
2694
  if (key.pageUp) return by(room - 1);
2535
2695
  if (key.pageDown) return by(-(room - 1));
@@ -2544,33 +2704,31 @@ function JobsDialog({ dialog, jobs }: { dialog: Extract<Dialog, { kind: "jobs" }
2544
2704
  const n = jobs.length;
2545
2705
  if (key.upArrow || input === "k") return n && setSelected((Math.min(getSelected(), n - 1) - 1 + n) % n);
2546
2706
  if (key.downArrow || input === "j") return n && setSelected((Math.min(getSelected(), n - 1) + 1) % n);
2547
- if ((key.return || key.rightArrow) && target) {
2548
- setBack(0);
2549
- return setViewing(target.id);
2550
- }
2707
+ if ((key.return || key.rightArrow) && target) return view(target.id);
2551
2708
  if (key.escape || (key.ctrl && input === "c")) return dialog.resolve(undefined);
2552
2709
  });
2553
2710
  const mark = (j: JobInfo) => (j.done ? h(Text, { dimColor: true }, "○ ") : h(Text, { color: "green" }, "● "));
2554
2711
  const canStop = (j: JobInfo | undefined) => j !== undefined && !j.done && j.stop !== undefined;
2555
- const frame = { flexDirection: "column", borderStyle: "round", borderColor: "cyan", paddingX: 1, marginTop: 1 } as const;
2712
+ const frame = { ref: box, flexDirection: "column", borderStyle: "round", borderColor: "cyan", paddingX: 1, marginTop: 1 } as const;
2556
2713
  if (viewing) {
2557
- const shown = lines.slice(lines.length - room - back, lines.length - back);
2714
+ const expandable = lines.some((l) => l.line !== undefined);
2558
2715
  return h(
2559
2716
  Box,
2560
2717
  frame,
2561
2718
  h(Text, { wrap: "truncate-end" }, mark(viewing), h(Text, { bold: true }, `${viewing.kind} · ${viewing.title}`), viewing.status ? h(Text, { dimColor: true }, ` · ${viewing.status}`) : null),
2562
2719
  lines.length > room + back ? h(Text, { dimColor: true }, ` ↑ ${lines.length - room - back} more lines`) : null,
2563
2720
  lines.length === 0 ? h(Text, { dimColor: true }, " (no output yet)") : null,
2564
- shown.map((l, i) => h(Text, { key: i, wrap: "truncate-end" }, l || " ")),
2721
+ shown.map((l, i) => h(Text, { key: i, wrap: "truncate-end" }, l.text || " ")),
2565
2722
  back > 0 ? h(Text, { dimColor: true }, ` ↓ ${back} more lines`) : null,
2566
2723
  h(Hint, {
2567
2724
  width,
2568
- variants: [`PgUp/PgDn ↑↓ scroll${canStop(viewing) ? " · x stop" : ""} · esc back`, `↑↓${canStop(viewing) ? " · x" : ""} · esc`],
2725
+ variants: [
2726
+ `wheel PgUp/PgDn ↑↓ scroll${expandable ? " · click ▸ to expand" : ""}${canStop(viewing) ? " · x stop" : ""} · esc back`,
2727
+ `↑↓${expandable ? " · click ▸" : ""}${canStop(viewing) ? " · x" : ""} · esc`,
2728
+ ],
2569
2729
  }),
2570
2730
  );
2571
2731
  }
2572
- const visible = roomFor(rows, VISIBLE);
2573
- const start = around(selected, jobs.length, visible);
2574
2732
  return h(
2575
2733
  Box,
2576
2734
  frame,
@@ -2592,7 +2750,7 @@ function JobsDialog({ dialog, jobs }: { dialog: Extract<Dialog, { kind: "jobs" }
2592
2750
  h(Hint, {
2593
2751
  width,
2594
2752
  variants: jobs.length
2595
- ? [`↑↓ select · enter view output${canStop(jobs[selected]) ? " · x stop" : ""} · esc close`, `↑↓ · enter${canStop(jobs[selected]) ? " · x" : ""} · esc`]
2753
+ ? [`↑↓ select · enter or click view output${canStop(jobs[selected]) ? " · x stop" : ""} · esc close`, `↑↓ · enter${canStop(jobs[selected]) ? " · x" : ""} · esc`]
2596
2754
  : ["esc close"],
2597
2755
  }),
2598
2756
  );
@@ -0,0 +1,111 @@
1
+ // jade/withdraw:用户中断一轮时模型还没有回复(例如消息发错了、马上按了 esc),撤回这条消息,文字放回输入框,会话还是这一个。
2
+ //
3
+ // 日志只追加,内核状态里这条消息还在:撤回记进 derived(消息的下标),context.project 把它从投影里去掉,模型不会再看到它。
4
+ // 只有最后一条消息会被撤回,去掉它不改变前面消息的下标,所以按下标记东西的插件不受影响:
5
+ // 排在这里之前的(jade/mentions)按内核里的下标记,撤回的消息带着它的附件一起去掉;
6
+ // 排在这里之后的(prompts@1 的 note、jade/steer、压缩)按去掉之后的下标记,附在撤回的消息上的说明落到下一条消息上,不会丢。
7
+ //
8
+ // 要不要撤回由前端决定(arm,在中止之前调用):插件、退出中止的一轮不撤回。
9
+ // 最后一条消息撤回了却还要请求模型(/retry)时这一轮出错:没有用户的消息可以交给模型。
10
+
11
+ import type { Message } from "uncarved";
12
+ import { definePlugin, type Span } from "@uncarved/jade-api";
13
+ import type { Renderers, Withdraw } from "@uncarved/jade-api/services";
14
+
15
+ const ID = "jade/withdraw";
16
+ /** derived 里:撤回的消息在内核状态里的下标 */
17
+ const KEY = `${ID}/withdrawn`;
18
+
19
+ interface Entry {
20
+ /** 前端要中断这一轮 */
21
+ armed: boolean;
22
+ running(): boolean;
23
+ }
24
+
25
+ /** 打开着的会话。模块每个进程只加载一次,进程级和会话级共用 */
26
+ const sessions = new Map<string, Entry>();
27
+
28
+ const dim = (text: string): Span => ({ text, style: "dim" });
29
+
30
+ /** 用户自己写的文字;插件附上的内容不算 */
31
+ const userText = (m: Message) => m.content.flatMap((b) => (b.kind === "text" && b.origin.by === "user" ? [b.text] : [])).join("\n");
32
+
33
+ export default definePlugin({
34
+ process(ctx) {
35
+ ctx.provide("withdraw@1", (caller): Withdraw => ({
36
+ arm(session) {
37
+ if (caller.layer === "project") throw new Error("withdraw.arm: project plugins cannot withdraw the user's messages");
38
+ const s = sessions.get(session);
39
+ if (!s?.running()) return false;
40
+ s.armed = true;
41
+ return true;
42
+ },
43
+ }));
44
+
45
+ // 恢复的会话重新显示时也在原来的位置
46
+ ctx.service<Renderers>("renderers@1")?.event({
47
+ event: "withdrawn",
48
+ render: () => ({ line: dim("[withdrawn: the model will not see this message]") }),
49
+ });
50
+ },
51
+
52
+ async session(ctx) {
53
+ // 子会话(子 Agent)没有用户按 esc
54
+ if (ctx.session.parent) return;
55
+ const id = ctx.session.id;
56
+ const entry: Entry = {
57
+ armed: false,
58
+ running() {
59
+ try {
60
+ const phase = ctx.session.phase();
61
+ return phase !== "new" && phase !== "idle" && phase !== "ended";
62
+ } catch {
63
+ // 会话还没建好,或者已经关了
64
+ return false;
65
+ }
66
+ },
67
+ };
68
+ sessions.set(id, entry);
69
+ await ctx.effect(() => () => {
70
+ if (sessions.get(id) === entry) sessions.delete(id);
71
+ });
72
+
73
+ ctx.kernel.hook({
74
+ kind: "observe",
75
+ point: "event",
76
+ fn: async (e, hook) => {
77
+ if (e.type !== "turn.ended") return;
78
+ const armed = entry.armed;
79
+ entry.armed = false;
80
+ if (!armed || (e.data as { reason?: unknown }).reason !== "aborted") return;
81
+ const messages = ctx.session.state().messages;
82
+ const at = messages.length - 1;
83
+ const last = messages[at];
84
+ // 模型回复过(最后一条是它的回复,或者工具的结果)就不撤回:那时已经做了事
85
+ if (!last || last.role !== "user" || last.content.some((b) => b.kind === "tool_result")) return;
86
+ const done = (hook.derived[KEY] as number[] | undefined) ?? [];
87
+ if (done.includes(at)) return;
88
+ const text = userText(last);
89
+ await hook.record(KEY, [...done, at]);
90
+ await hook.emit("withdrawn", { text });
91
+ // 放在已经输入的内容前面(中断时取回的排队消息也在那里)
92
+ const typed = ctx.input?.text() ?? "";
93
+ if (text) ctx.input?.set(typed.trim() ? `${text}\n${typed}` : text);
94
+ },
95
+ });
96
+
97
+ ctx.kernel.hook({
98
+ kind: "transform",
99
+ point: "context.project",
100
+ // jade/mentions(-50)之后、prompts@1 的 note(-40)和 jade/steer(-39)之前,见文件开头
101
+ order: -45,
102
+ fn: (messages, hook) => {
103
+ const done = hook.derived[KEY] as number[] | undefined;
104
+ if (!done?.length) return messages;
105
+ const drop = new Set(done);
106
+ if (drop.has(messages.length - 1)) throw new Error("nothing to send: your last message was withdrawn");
107
+ return messages.filter((_, i) => !drop.has(i));
108
+ },
109
+ });
110
+ },
111
+ });
@@ -0,0 +1,8 @@
1
+ {
2
+ "id": "jade/withdraw",
3
+ "version": "0.1.0",
4
+ "api": "^1",
5
+ "entry": "./index.ts",
6
+ "provides": ["withdraw@1"],
7
+ "optional": ["renderers@1"]
8
+ }