@uncarved/jade 0.4.3 → 0.5.0

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 (39) hide show
  1. package/README.md +317 -279
  2. package/dist/api.d.ts +1 -1
  3. package/dist/api.js +1 -1
  4. package/dist/session.d.ts +4 -2
  5. package/dist/session.js +54 -6
  6. package/dist/session.js.map +1 -1
  7. package/package.json +3 -3
  8. package/plugins/keys/index.ts +2 -2
  9. package/plugins/memory/index.ts +6 -4
  10. package/plugins/memory/memory.ts +101 -31
  11. package/plugins/models/index.ts +67 -9
  12. package/plugins/models/provider.ts +81 -24
  13. package/plugins/serve/index.ts +229 -0
  14. package/plugins/serve/plugin.json +8 -0
  15. package/plugins/shell/index.ts +35 -1
  16. package/plugins/shell/shell.ts +5 -0
  17. package/plugins/task/index.ts +3 -1
  18. package/plugins/task/subagent.ts +49 -3
  19. package/plugins/tui/frontend.ts +73 -4
  20. package/plugins/tui/screen.ts +23 -0
  21. package/plugins/tui/tui.ts +176 -11
  22. package/plugins-dist/keys/index.js +1 -1
  23. package/plugins-dist/memory/index.js +7 -3
  24. package/plugins-dist/memory/memory.js +81 -34
  25. package/plugins-dist/models/index.js +62 -7
  26. package/plugins-dist/models/provider.js +47 -14
  27. package/plugins-dist/serve/index.js +238 -0
  28. package/plugins-dist/serve/plugin.json +14 -0
  29. package/plugins-dist/shell/index.js +33 -0
  30. package/plugins-dist/shell/shell.js +3 -0
  31. package/plugins-dist/task/index.js +3 -1
  32. package/plugins-dist/task/subagent.js +47 -2
  33. package/plugins-dist/tui/frontend.js +67 -3
  34. package/plugins-dist/tui/screen.js +3 -0
  35. package/plugins-dist/tui/tui.js +132 -9
  36. package/plugins-dist/tui/vendor.js +1388 -1088
  37. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  38. package/src/api.ts +1 -1
  39. package/src/session.ts +57 -5
@@ -6,7 +6,7 @@
6
6
 
7
7
  import type { Block, ChildRef, EventDataMap, Message, SessionRef, Tool, ToolResult, Usage } from "uncarved";
8
8
  import { ProviderError } from "uncarved";
9
- import type { ChildSession } from "@uncarved/jade-api";
9
+ import type { ChildSession, Job, Text } from "@uncarved/jade-api";
10
10
 
11
11
  /** ctx.progress 推送的内容 */
12
12
  export type TaskProgress =
@@ -38,6 +38,12 @@ export interface TaskOptions {
38
38
  register(child: string, control: Control): () => void;
39
39
  /** 子 Agent 跑完时(成功、失败、中止都算)调用,给出它这次调用模型的用量合计 */
40
40
  usage?(toolUseId: string, usage: Usage): void;
41
+ /**
42
+ * 把子 Agent 登记到前端的后台列表里(UI.job),用户能看它在做什么、单独停掉它;前端不支持时返回 undefined。
43
+ * describe 给出工具调用括号里的一行摘要
44
+ */
45
+ job?(description: string, stop: () => void): Job | undefined;
46
+ describe?(name: string, input: unknown): Text;
41
47
  }
42
48
 
43
49
  /** 历史到了上下文窗口的这个比例就停下来写报告:子 Agent 没有压缩,再读几个大文件就会超出窗口 */
@@ -60,6 +66,12 @@ export const WRAP_UP =
60
66
  export const READ_ONLY_REASON = (name: string) =>
61
67
  `${name}: sub-agents can only run read-only commands inside the working directory (for example git log, git diff, ls, rg). Describe anything else in your report instead.`;
62
68
 
69
+ /** 用户在后台列表里停掉子 Agent 时,task 的结果 */
70
+ export const STOPPED = "The user stopped this sub-agent before it finished. Do not start it again unless the user asks.";
71
+
72
+ /** 后台列表里工具结果只显示第一行,最多这么多个字符 */
73
+ const JOB_RESULT_CHARS = 160;
74
+
63
75
  /** 返回给主会话的报告上限,免得一个子 Agent 撑满主会话的上下文 */
64
76
  const MAX_REPORT_CHARS = 20_000;
65
77
 
@@ -145,20 +157,42 @@ export function taskTool(opts: TaskOptions): Tool {
145
157
  const unregister = opts.register(child.id, control);
146
158
  const progress = (p: TaskProgress) => ctx.progress(p);
147
159
  progress({ kind: "task-start", sessionId: child.id, description });
160
+ // 用户在后台列表里停掉它:只停这个子 Agent,主会话这一轮照常进行
161
+ let stopped = false;
162
+ const job = opts.job?.(description, () => {
163
+ stopped = true;
164
+ child.abort("stopped by the user");
165
+ });
166
+ job?.status("starting");
167
+ const describe = (name: string, input: unknown): Text => opts.describe?.(name, input) ?? clipText(JSON.stringify(input) ?? "", JOB_RESULT_CHARS);
148
168
  const names = new Map<string, string>();
149
169
  const unsubscribe = child.subscribe((n) => {
150
170
  if (n.type !== "event") return;
151
171
  if (n.event.type === "model.requested") {
152
172
  progress({ kind: "task-model" });
173
+ job?.status("thinking");
153
174
  } else if (n.event.type === "model.responded") {
154
175
  const data = n.event.data as EventDataMap["model.responded"];
155
176
  for (const b of data.content) if (b.kind === "tool_use") names.set(b.id, b.name);
177
+ const said = data.content.flatMap((b) => (b.kind === "text" && b.text.trim() ? [b.text.trim()] : [])).join("\n");
178
+ if (said) job?.append(`${said}\n\n`);
156
179
  for (const k of Object.keys(used) as (keyof Usage)[]) used[k] += data.usage?.[k] ?? 0;
157
180
  // 输入 token 已含缓存部分(各 provider 的 Usage 约定);这次的输出也会进下一次请求
158
181
  if (data.usage) control.lastTokens = (data.usage.inputTokens ?? 0) + (data.usage.outputTokens ?? 0);
159
182
  } else if (n.event.type === "tool.decided") {
160
183
  const d = n.event.data as EventDataMap["tool.decided"];
161
- progress({ kind: "task-tool", name: names.get(d.toolUseId) ?? "?", input: d.input, decision: d.decision });
184
+ const name = names.get(d.toolUseId) ?? "?";
185
+ progress({ kind: "task-tool", name, input: d.input, decision: d.decision });
186
+ if (job) {
187
+ const call: Text = [`● ${name}(`, describe(name, d.input), ")"];
188
+ job.status(`${name}(${plain(describe(name, d.input))})`);
189
+ job.append(d.decision === "deny" ? [call, { text: ` ✗ denied${d.reason ? `: ${d.reason}` : ""}`, style: "error" }, "\n"] : [call, "\n"]);
190
+ }
191
+ } else if (n.event.type === "tool.completed" && job) {
192
+ const d = n.event.data as EventDataMap["tool.completed"];
193
+ const out = d.content.flatMap((b) => (b.kind === "text" ? [b.text] : [])).join("\n").trim().split("\n");
194
+ const more = out.length > 1 ? ` (+${out.length - 1} lines)` : "";
195
+ job.append([{ text: ` ⎿ ${clipText(out[0] ?? "", JOB_RESULT_CHARS)}${more}`, style: d.isError ? "error" : "dim" }, "\n"]);
162
196
  }
163
197
  });
164
198
  const forward = () => child.abort(String(ctx.signal.reason ?? "aborted"));
@@ -179,7 +213,7 @@ export function taskTool(opts: TaskOptions): Tool {
179
213
  // 再要一次报告,否则前面的调研全白做了。重试已经用完的错误(限流、服务不可用)不再要:再试一次也一样,还要再等很久
180
214
  const cause = unwrap(failure);
181
215
  const exhausted = cause instanceof ProviderError && cause.retryable;
182
- if (!ctx.signal.aborted && !exhausted && !lastText(child.state.messages)) {
216
+ if (!ctx.signal.aborted && !stopped && !exhausted && !lastText(child.state.messages)) {
183
217
  control.wrapUp = true;
184
218
  try {
185
219
  await turn(WRAP_UP);
@@ -195,6 +229,7 @@ export function taskTool(opts: TaskOptions): Tool {
195
229
  messages = child.state.messages;
196
230
  ref = await child.close().catch(() => undefined);
197
231
  unregister();
232
+ job?.dispose();
198
233
  opts.usage?.(ctx.toolUseId, used);
199
234
  }
200
235
  if (ctx.signal.aborted) throw failure ?? ctx.signal.reason;
@@ -202,6 +237,8 @@ export function taskTool(opts: TaskOptions): Tool {
202
237
  const linked = ref ? { child: ref } : {};
203
238
  // 还是没有报告时,把它一路上说过的话都带回去
204
239
  const text = clip(lastText(messages) || allText(messages));
240
+ // 跑完以后才按的停(在关子会话时)不算:报告已经有了
241
+ if (stopped && failure) return { content: `${STOPPED}${text ? `\nWhat it had written so far:\n${text}` : ""}`, isError: true, ...linked };
205
242
  if (failure) {
206
243
  const msg = failure instanceof Error ? failure.message : String(failure);
207
244
  return { content: `Sub-agent failed: ${msg}${text ? `\nLast output:\n${text}` : ""}`, isError: true, ...linked };
@@ -239,6 +276,15 @@ function allText(messages: Message[]): string {
239
276
  .join("\n\n");
240
277
  }
241
278
 
279
+ const clipText = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)}…` : s);
280
+
281
+ /** 带样式的文字只取字 */
282
+ function plain(t: Text): string {
283
+ if (typeof t === "string") return t;
284
+ if (Array.isArray(t)) return (t as readonly Text[]).map(plain).join("");
285
+ return String((t as { text?: unknown }).text ?? "");
286
+ }
287
+
242
288
  function clip(s: string): string {
243
289
  return s.length > MAX_REPORT_CHARS ? `${s.slice(0, MAX_REPORT_CHARS)}\n… (report truncated: ${s.length - MAX_REPORT_CHARS} more characters)` : s;
244
290
  }
@@ -10,10 +10,10 @@ import { readFileSync } from "node:fs";
10
10
  import os from "node:os";
11
11
  import path from "node:path";
12
12
  import type { Block } from "uncarved";
13
- import type { Frontend, OpenOptions, Session, SessionManager, SessionUI, StatusSegment, Text, UI } from "@uncarved/jade-api";
13
+ import type { Frontend, Job, JobRequest, OpenOptions, Session, SessionManager, SessionUI, StatusSegment, Text, UI } from "@uncarved/jade-api";
14
14
  import type { CommandContext, Commands, Completions, EventRenderer, Keys, Models, Renderers, SessionIndex, Steer, ToolRenderer } from "@uncarved/jade-api/services";
15
15
  import { InputHistory } from "./history.ts";
16
- import { ansi, dim, red, safeScreen, yellow, type CommandInfo, type CompletionInfo, type Screen } from "./screen.ts";
16
+ import { ansi, dim, red, safeScreen, yellow, type CommandInfo, type CompletionInfo, type JobInfo, type Screen } from "./screen.ts";
17
17
  import { transcript, type Transcript } from "./transcript.ts";
18
18
 
19
19
  /**
@@ -45,6 +45,7 @@ jade's own commands (plugins, update, --safe): jade help`;
45
45
  /** 前端自己的命令:帮助和退出。其余命令都来自 commands@1 */
46
46
  const OWN: CommandInfo[] = [
47
47
  { name: "help", about: "list the commands and keys" },
48
+ { name: "tasks", about: "list sub-agents and background commands (same as ctrl+t)" },
48
49
  { name: "exit", about: "quit (the session stays resumable)" },
49
50
  ];
50
51
 
@@ -53,7 +54,7 @@ const KEYS = [
53
54
  " send enter send · ctrl+j, alt+enter or \\ then enter: new line · tab completes /commands",
54
55
  " input ↑↓ history · ctrl+r search history · ↑ on the first line edits queued messages · esc twice or ctrl+c clears the input",
55
56
  " editing ctrl+←/→ or alt+b/f move by words · ctrl+w or alt+backspace delete a word · ctrl+a/e line start/end · ctrl+u/k delete to start/end",
56
- " running esc interrupt (twice to also move queued messages back to the input) · ctrl+c twice to exit",
57
+ " running esc interrupt (twice to also move queued messages back to the input) · ctrl+c twice to exit · ctrl+t, /tasks or a click on the status bar lists sub-agents and background commands",
57
58
  " transcript pgup/pgdn scroll · ctrl+home/end top/bottom · ctrl+o expands the latest item, a click the one under it · drag to select and copy · ctrl+l redraw",
58
59
  ].join("\n");
59
60
 
@@ -155,16 +156,30 @@ export class ScreenBridge {
155
156
  #panels = new Map<string, Map<string, string>>();
156
157
  /** 界面现在显示哪个会话;换会话时由前端调用 show */
157
158
  #session: string | undefined;
159
+ /** UI.notice 给每条提示编号,作为它在界面里的 id */
160
+ #notices = 0;
161
+ /** UI.job 登记的事(所有会话的);界面只显示正在显示的会话的 */
162
+ #jobs: (JobInfo & { session: string })[] = [];
163
+ #nextJob = 0;
164
+ /** 输出攒一小段时间再交给界面,后台命令输出很快时不至于每一块都重画 */
165
+ #jobTimer: ReturnType<typeof setTimeout> | undefined;
158
166
 
159
167
  readonly ui: UI = {
160
168
  interactive: true,
161
169
  notify: (message, level = "info") => {
162
- const text = level === "error" ? red(`[error] ${message}`) : level === "warning" ? yellow(`[warning] ${message}`) : dim(message);
170
+ const text = noticeText(message, level);
163
171
  if (this.#held) this.#held.push(text);
164
172
  else if (this.screen) this.screen.log(text);
165
173
  else if (this.#closed) process.stderr.write(`jade: ${message}\n`);
166
174
  else this.#early.push(text);
167
175
  },
176
+ // 只有终端界面能原地改写;攒着提示(正在打开会话)时也不行,调用方改用 notify
177
+ notice: (message, level = "info") => {
178
+ if (this.#held || !this.screen?.note) return undefined;
179
+ const id = `\0notice-${++this.#notices}`;
180
+ this.screen.note(id, noticeText(message, level));
181
+ return { update: (m, l = "info") => this.screen?.note?.(id, noticeText(m, l)) };
182
+ },
168
183
  select: async (req, signal) => {
169
184
  if (!this.screen) return undefined;
170
185
  return this.screen.select(req.title, req.options.map((o) => ({ label: o.label, value: o.value, ...(o.hint ? { hint: o.hint } : {}) })), { ...(req.detail ? { body: ansi(req.detail) } : {}), ...(signal ? { signal } : {}) });
@@ -181,6 +196,7 @@ export class ScreenBridge {
181
196
  // 界面没有占着终端(不是终端界面、还没起来)时没有什么要让的,直接执行
182
197
  suspend: async (fn) => (this.screen?.suspend ? this.screen.suspend(fn) : fn()),
183
198
  session: ({ session, plugin }) => this.#sessionUI(session, plugin),
199
+ job: (req) => this.#job(req),
184
200
  };
185
201
 
186
202
  attach(screen: Screen): void {
@@ -204,6 +220,7 @@ export class ScreenBridge {
204
220
  }
205
221
 
206
222
  detach(): void {
223
+ clearTimeout(this.#jobTimer);
207
224
  this.screen = undefined;
208
225
  this.#closed = true;
209
226
  }
@@ -212,6 +229,45 @@ export class ScreenBridge {
212
229
  show(session: string | undefined): void {
213
230
  this.#session = session;
214
231
  this.#apply();
232
+ this.#applyJobs();
233
+ }
234
+
235
+ #job(req: JobRequest): Job {
236
+ const entry: JobInfo & { session: string } = {
237
+ id: ++this.#nextJob,
238
+ session: String(req.session),
239
+ kind: String(req.kind),
240
+ title: String(req.title),
241
+ status: "",
242
+ done: false,
243
+ output: "",
244
+ ...(req.stop ? { stop: () => req.stop!() } : {}),
245
+ };
246
+ this.#jobs = [...this.#jobs, { ...entry }];
247
+ this.#applyJobs();
248
+ // entry 是最新的值;列表里每次换成它的一份新拷贝,界面按引用判断哪一项变了。已经去掉的不再更新
249
+ const update = (patch: Partial<JobInfo>, soon = false) => {
250
+ if (!this.#jobs.some((j) => j.id === entry.id)) return;
251
+ Object.assign(entry, patch);
252
+ this.#jobs = this.#jobs.map((j) => (j.id === entry.id ? { ...entry } : j));
253
+ if (soon) this.#jobTimer ??= setTimeout(() => this.#applyJobs(), JOB_REDRAW_MS);
254
+ else this.#applyJobs();
255
+ };
256
+ return {
257
+ append: (text) => update({ output: (entry.output + ansi(text)).slice(-MAX_JOB_OUTPUT) }, true),
258
+ status: (text, done) => update({ status: String(text), done: done === true }),
259
+ dispose: () => {
260
+ const before = this.#jobs.length;
261
+ this.#jobs = this.#jobs.filter((j) => j.id !== entry.id);
262
+ if (this.#jobs.length !== before) this.#applyJobs();
263
+ },
264
+ };
265
+ }
266
+
267
+ #applyJobs(): void {
268
+ clearTimeout(this.#jobTimer);
269
+ this.#jobTimer = undefined;
270
+ this.screen?.jobs?.(this.#jobs.filter((j) => j.session === this.#session));
215
271
  }
216
272
 
217
273
  #apply(): void {
@@ -264,6 +320,14 @@ export class ScreenBridge {
264
320
  }
265
321
  }
266
322
 
323
+ /** 每件后台的事最多留这么多个字符的输出 */
324
+ const MAX_JOB_OUTPUT = 100_000;
325
+ /** 后台的事的输出攒这么久交给界面一次 */
326
+ const JOB_REDRAW_MS = 100;
327
+
328
+ const noticeText = (message: string, level: "info" | "warning" | "error") =>
329
+ level === "error" ? red(`[error] ${message}`) : level === "warning" ? yellow(`[warning] ${message}`) : dim(message);
330
+
267
331
  /** 输入框上方的一块最多这么多行,多出的最后一行写成还有几行;每行在界面里按宽度截断 */
268
332
  function clipPanel(text: string): string {
269
333
  const lines = String(text).replace(/\r\n?/g, "\n").replace(/\n+$/, "").split("\n");
@@ -630,6 +694,11 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
630
694
  const name = input.slice(1).split(/\s+/)[0]!.toLowerCase();
631
695
  const rest = input.slice(1).replace(/^\S+\s*/, "");
632
696
  if (name === "exit" || name === "quit") return false;
697
+ if (name === "tasks") {
698
+ if (screen.showJobs) screen.showJobs();
699
+ else screen.log(dim("[background tasks are only listed in the terminal interface]"));
700
+ return true;
701
+ }
633
702
  if (name === "help") {
634
703
  // 快捷键在前、命令在后:屏幕放不下时,紧挨着输入框的命令列表还看得见
635
704
  // 命令的简写、输入框的补全来自插件,跟着列出来
@@ -49,6 +49,20 @@ export interface CompletionInfo {
49
49
  hint?: string;
50
50
  }
51
51
 
52
+ /** 后台的一件事(UI.job 登记的子 Agent、后台命令) */
53
+ export interface JobInfo {
54
+ id: number;
55
+ kind: string;
56
+ title: string;
57
+ status: string;
58
+ /** 不再在运行 */
59
+ done: boolean;
60
+ /** 输出的末尾一段,可以带 ANSI 颜色 */
61
+ output: string;
62
+ /** 用户停掉它;没有时不能停 */
63
+ stop?(): void;
64
+ }
65
+
52
66
  export interface Screen {
53
67
  /** 能向用户提问;为 false 时 select / input 直接返回 undefined */
54
68
  readonly interactive: boolean;
@@ -63,6 +77,8 @@ export interface Screen {
63
77
  * 纯文本输出另起一行缩进显示。找不到那一项时也是另起一行
64
78
  */
65
79
  amend(id: string, text: string, opts?: { details?: string }): void;
80
+ /** 能改写的一行:第一次用这个 id 时追加,之后用同一个 id 原地改写成 text。只有终端界面有 */
81
+ note?(id: string, text: string): void;
66
82
  /**
67
83
  * 正在运行的工具 id 的一行进度(已经排好版);undefined 表示工具结束了。
68
84
  * 终端界面只在对话最后显示每个工具最新的一行,结束时去掉;纯文本输出逐行打印。
@@ -84,6 +100,10 @@ export interface Screen {
84
100
  input(title: string, opts?: { initial?: string; mask?: boolean; placeholder?: string; signal?: AbortSignal }): Promise<string | undefined>;
85
101
  /** 输入框里还没提交的文字和灰色提示(插件的 ctx.input 用);只有终端界面有 */
86
102
  readonly draft?: { text(): string; insert(text: string): void; set(text: string): void; hint(text: string | undefined): void };
103
+ /** 后台的事(当前会话的全部,按登记的先后);只有终端界面有 */
104
+ jobs?(jobs: JobInfo[]): void;
105
+ /** 打开后台的事的列表(同 ctrl+t);只有终端界面有 */
106
+ showJobs?(): void;
87
107
  /** 把文字放进系统剪贴板(OSC 52);只有终端界面有 */
88
108
  copy?(text: string): void;
89
109
  /** 把终端让出来执行 fn(例如启动 $EDITOR),结束后重新接管、重画界面;只有终端界面有 */
@@ -178,6 +198,9 @@ export function safeScreen(screen: Screen): Screen {
178
198
  interactive: screen.interactive,
179
199
  log: (text, o) => screen.log(s(text), o && { ...o, details: opt(o.details) }),
180
200
  amend: (id, text, o) => screen.amend(id, s(text), o && { ...o, details: opt(o.details) }),
201
+ ...(screen.note ? { note: (id: string, text: string) => screen.note!(id, s(text)) } : {}),
202
+ ...(screen.jobs ? { jobs: (jobs: JobInfo[]) => screen.jobs!(jobs.map((j) => ({ ...j, title: s(j.title), status: s(j.status), output: s(j.output) }))) } : {}),
203
+ ...(screen.showJobs ? { showJobs: () => screen.showJobs!() } : {}),
181
204
  progress: (id, line, o) => screen.progress(id, opt(line), o),
182
205
  stream: (kind, text) => {
183
206
  // 上一段末尾没完的转义序列接到这一段前面再过滤,不然它被拆成两半,后一半当成文字显示出来
@@ -34,6 +34,7 @@ import {
34
34
  type Choice,
35
35
  type CommandInfo,
36
36
  type CompletionInfo,
37
+ type JobInfo,
37
38
  type Screen,
38
39
  type StatusInfo,
39
40
  } from "./screen.ts";
@@ -108,7 +109,9 @@ type Dialog =
108
109
  mask?: boolean;
109
110
  placeholder?: string;
110
111
  resolve(v: string | undefined): void;
111
- };
112
+ }
113
+ /** 后台的事的列表(ctrl+t):不是提问,别的对话框来了先让给它们 */
114
+ | { kind: "jobs"; resolve(v: unknown): void };
112
115
 
113
116
  interface UiState {
114
117
  /** 对话内容变化时递增,让界面重画 */
@@ -124,6 +127,8 @@ interface UiState {
124
127
  progress: { id: string; line: string }[];
125
128
  queued: string[];
126
129
  dialogs: Dialog[];
130
+ /** 后台的事(子 Agent、后台命令),ctrl+t 打开列表 */
131
+ jobs: JobInfo[];
127
132
  status: StatusInfo;
128
133
  /** 插件设置的灰色提示(ctx.input.hint):输入框为空时显示,Tab 或 → 接受 */
129
134
  hint?: string;
@@ -278,7 +283,7 @@ export class Store {
278
283
  paused = false;
279
284
 
280
285
  constructor(status: StatusInfo, size: Size) {
281
- this.state = { version: 0, scroll: 0, progress: [], queued: [], dialogs: [], status, size };
286
+ this.state = { version: 0, scroll: 0, progress: [], queued: [], dialogs: [], jobs: [], status, size };
282
287
  }
283
288
 
284
289
  subscribe = (fn: () => void) => {
@@ -322,6 +327,13 @@ export class Store {
322
327
  this.#repaintTimer = setTimeout(() => this.#repaintNow(), REPAINT_GAP_MS);
323
328
  }
324
329
 
330
+ /** 打开后台的事的列表(ctrl+t、点状态栏、/tasks);已经开着对话框时不开 */
331
+ openJobs() {
332
+ if (this.state.dialogs.length) return;
333
+ const d: Dialog = { kind: "jobs", resolve: () => this.update({ dialogs: this.state.dialogs.filter((x) => x !== d) }, true) };
334
+ this.update({ dialogs: [...this.state.dialogs, d] }, true);
335
+ }
336
+
325
337
  #repaintNow(patch: Partial<UiState> = {}) {
326
338
  clearTimeout(this.#repaintTimer);
327
339
  this.paused = false;
@@ -751,6 +763,12 @@ export function tuiScreen(opts: TuiOptions): Screen {
751
763
  o?.details !== undefined ? { details: o.details } : undefined,
752
764
  );
753
765
  },
766
+ note(id, text) {
767
+ if (store.amend(id, (l) => void (l.text = text))) return;
768
+ flushLive(true);
769
+ store.update({ live: undefined });
770
+ store.append([text], { id });
771
+ },
754
772
  progress(id, line) {
755
773
  const rest = store.state.progress.filter((p) => p.id !== id);
756
774
  store.update({
@@ -806,6 +824,10 @@ export function tuiScreen(opts: TuiOptions): Screen {
806
824
  queued(items) {
807
825
  store.update({ queued: [...items] });
808
826
  },
827
+ jobs(jobs) {
828
+ store.update({ jobs });
829
+ },
830
+ showJobs: () => store.openJobs(),
809
831
  draft: {
810
832
  text: () => draft.current?.get() ?? "",
811
833
  insert: (text) => draft.current?.apply((s) => edit.insert(s, text.replace(/\r\n?/g, "\n"))),
@@ -1043,9 +1065,11 @@ function App({
1043
1065
  draft: DraftBridge;
1044
1066
  }) {
1045
1067
  const state = useSyncExternalStore(store.subscribe, store.get);
1046
- const dialog = state.dialogs[0];
1068
+ // 后台的事的列表只是查看:提问(审批之类)来了先显示提问
1069
+ const dialog = state.dialogs.find((d) => d.kind !== "jobs") ?? state.dialogs[0];
1047
1070
  const columns = Math.max(1, state.size.columns - 1);
1048
1071
  const rows = state.size.rows;
1072
+ const statusWidth = Math.max(10, columns - 2);
1049
1073
  const compact = rows < COMPACT_ROWS;
1050
1074
  // 运行中每一帧(FRAME_MS)整体重画一次,推动转圈和吉祥物的动画。不能让 Spinner、吉祥物自己重画:
1051
1075
  // Ink 只在输入框也跟着提交的那一帧保留光标,否则把光标藏起来,运行中光标就不见了。
@@ -1059,7 +1083,7 @@ function App({
1059
1083
  return () => clearInterval(t);
1060
1084
  }, [busy]);
1061
1085
  const now = Date.now();
1062
- const mood = moodOf({ busy: state.busy?.label, asking: dialog !== undefined, doneAt: state.doneAt }, now);
1086
+ const mood = moodOf({ busy: state.busy?.label, asking: dialog !== undefined && dialog.kind !== "jobs", doneAt: state.doneAt }, now);
1063
1087
  const mascot = useRef<Mascot>(undefined);
1064
1088
  mascot.current ??= new Mascot();
1065
1089
  const showBot = !compact && columns >= 50;
@@ -1163,8 +1187,15 @@ function App({
1163
1187
  if (key.ctrl && input === "l") return store.repaint();
1164
1188
  // 展开或收起最近的一项(工具结果、思考、检查报告),鼠标点不了时也能看完整内容
1165
1189
  if (key.ctrl && input === "o") return store.toggleLatest(start, view);
1190
+ // 后台的事的列表
1191
+ if (key.ctrl && input === "t") return store.openJobs();
1166
1192
  const mouse = mouseEvent(input);
1167
1193
  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();
1198
+ }
1168
1199
  // 对话区里的位置;clamp 时拖出对话区停在第一行或最后一行,否则在对话区外返回 undefined
1169
1200
  const at = (clamp: boolean): Point | undefined => {
1170
1201
  const i = mouse.y - top;
@@ -1217,8 +1248,8 @@ function App({
1217
1248
  pressed.current = undefined;
1218
1249
  setSelection(undefined);
1219
1250
  }
1220
- // 选择框自己用 PgUp/PgDn 翻选项
1221
- if (dialog?.kind === "select") return;
1251
+ // 选择框自己用 PgUp/PgDn 翻选项,后台的事的列表用它翻输出
1252
+ if (dialog?.kind === "select" || dialog?.kind === "jobs") return;
1222
1253
  if (key.pageUp) store.scrollBy(page, max);
1223
1254
  else if (key.pageDown) store.scrollBy(-page, max);
1224
1255
  else if (key.ctrl && key.home) store.scrollBy(max, max);
@@ -1286,7 +1317,9 @@ function App({
1286
1317
  dialog
1287
1318
  ? dialog.kind === "select"
1288
1319
  ? h(SelectDialog, { key: dialogKey(dialog), dialog })
1289
- : h(InputDialog, { key: dialogKey(dialog), dialog })
1320
+ : dialog.kind === "jobs"
1321
+ ? h(JobsDialog, { key: dialogKey(dialog), dialog, jobs: state.jobs })
1322
+ : h(InputDialog, { key: dialogKey(dialog), dialog })
1290
1323
  : null,
1291
1324
  h(Prompt, {
1292
1325
  commands,
@@ -1303,7 +1336,7 @@ function App({
1303
1336
  place: inputPlace,
1304
1337
  onCopy: copyText,
1305
1338
  }),
1306
- h(StatusBar, { status: state.status, width: Math.max(10, columns - 2) }),
1339
+ h(StatusBar, { status: state.status, jobs: state.jobs, width: statusWidth }),
1307
1340
  ),
1308
1341
  ),
1309
1342
  ),
@@ -1413,6 +1446,8 @@ interface Segment {
1413
1446
  dropAt?: number;
1414
1447
  color?: string;
1415
1448
  dim?: boolean;
1449
+ /** 后台的事的那一段:点一下打开列表 */
1450
+ jobs?: boolean;
1416
1451
  }
1417
1452
 
1418
1453
  /** 插件段落的语义颜色怎么画 */
@@ -1439,7 +1474,8 @@ export function fitSegments(segments: Segment[], width: number): Segment[] {
1439
1474
  return kept;
1440
1475
  }
1441
1476
 
1442
- function StatusBar({ status, width }: { status: StatusInfo; width: number }) {
1477
+ /** 状态栏的内容,已经按宽度缩短 */
1478
+ function statusSegments(status: StatusInfo, jobs: JobInfo[], width: number): Segment[] {
1443
1479
  const ctx = status.context;
1444
1480
  const pct = ctx ? Math.round((ctx.used / ctx.limit) * 100) : 0;
1445
1481
  const nearFull = pct >= 80;
@@ -1457,8 +1493,11 @@ function StatusBar({ status, width }: { status: StatusInfo; width: number }) {
1457
1493
  const kept = (status.plugins ?? []).filter((p) => typeof p.text !== "string" && p.text.keep);
1458
1494
  const others = (status.plugins ?? []).filter((p) => !kept.includes(p));
1459
1495
  // 窄的时候依次:提示变短、去掉提示、用量变短、去掉缓存、模式变短、去掉用量、上下文变短、去掉速度
1496
+ const running = runningJobs(jobs);
1460
1497
  const segments: Segment[] = [
1461
1498
  ...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 }] : []),
1462
1501
  ctx
1463
1502
  ? {
1464
1503
  text: `ctx ${tokens(ctx.used)}/${tokens(ctx.limit)} (${pct}%)`,
@@ -1478,7 +1517,7 @@ function StatusBar({ status, width }: { status: StatusInfo; width: number }) {
1478
1517
  ]
1479
1518
  : []),
1480
1519
  ...(status.cache !== undefined
1481
- ? [{ text: `cache ${Math.round(status.cache * 100)}%`, dropAt: 7, dim: true }]
1520
+ ? [{ text: `cache ${Math.round(status.cache * 1000) / 10}%`, dropAt: 7, dim: true }]
1482
1521
  : []),
1483
1522
  ...(status.spent
1484
1523
  ? [
@@ -1500,7 +1539,27 @@ function StatusBar({ status, width }: { status: StatusInfo; width: number }) {
1500
1539
  dim: true,
1501
1540
  },
1502
1541
  ];
1503
- const shown = fitSegments(segments, width);
1542
+ return fitSegments(segments, width);
1543
+ }
1544
+
1545
+ /**
1546
+ * 状态栏里后台的事那一段占的列(从 0 数,含两端);没有这一段时是 undefined。
1547
+ * 照着 StatusBar 的画法算(左右各空一列、段落间是 " · "),点击的行是界面最后一行(App 里的 rows - 2):
1548
+ * 改了状态栏的位置或画法要跟着改,tui-ui 测试里点状态栏的那一条会发现
1549
+ */
1550
+ function jobsColumns(segments: Segment[]): [number, number] | undefined {
1551
+ let x = 1;
1552
+ for (const [i, s] of segments.entries()) {
1553
+ if (i) x += 3;
1554
+ const w = visibleWidth(s.text);
1555
+ if (s.jobs) return [x, x + w - 1];
1556
+ x += w;
1557
+ }
1558
+ return undefined;
1559
+ }
1560
+
1561
+ function StatusBar({ status, jobs, width }: { status: StatusInfo; jobs: JobInfo[]; width: number }) {
1562
+ const shown = statusSegments(status, jobs, width);
1504
1563
  return h(
1505
1564
  Box,
1506
1565
  { paddingX: 1 },
@@ -2433,6 +2492,112 @@ function SelectDialog({
2433
2492
  );
2434
2493
  }
2435
2494
 
2495
+ /** 还在运行的后台的事按种类计数,例如 "2 agents · 1 shell";没有时是空字符串 */
2496
+ export function runningJobs(jobs: readonly JobInfo[]): string {
2497
+ const counts = new Map<string, number>();
2498
+ for (const j of jobs) if (!j.done) counts.set(j.kind, (counts.get(j.kind) ?? 0) + 1);
2499
+ return [...counts].map(([kind, n]) => `${n} ${kind}${n > 1 ? "s" : ""}`).join(" · ");
2500
+ }
2501
+
2502
+ /** 查看一件后台的事时,输出只折最后这么多行 */
2503
+ const JOB_TAIL_LINES = 2000;
2504
+
2505
+ /**
2506
+ * 后台的事(ctrl+t):列表里选一件,enter 看它的输出(跟着最新的,PgUp/PgDn 翻看),x 停掉,esc 返回、关掉。
2507
+ * 正在看的那件被去掉了(子 Agent 交了报告)时回到列表
2508
+ */
2509
+ function JobsDialog({ dialog, jobs }: { dialog: Extract<Dialog, { kind: "jobs" }>; jobs: JobInfo[] }) {
2510
+ const selection = useContext(SelectionContext);
2511
+ const [getSelected, setSelected] = useLive(0);
2512
+ const [getViewing, setViewing] = useLive<number | undefined>(undefined);
2513
+ /** 看输出时离底部翻上去了多少行 */
2514
+ const [getBack, setBack] = useLive(0);
2515
+ const { rows, columns } = useScreenSize();
2516
+ const width = Math.max(10, columns - 4);
2517
+ const viewing = jobs.find((j) => j.id === getViewing());
2518
+ const selected = Math.min(getSelected(), Math.max(0, jobs.length - 1));
2519
+ const room = Math.max(3, rows - 14);
2520
+ // 输出折好行,只显示末尾 room 行(往上翻了 back 行)
2521
+ const lines = viewing ? wrap(viewing.output.replace(/\n+$/, "").split("\n").slice(-JOB_TAIL_LINES).join("\n"), width).map(visibleRow) : [];
2522
+ const maxBack = Math.max(0, lines.length - room);
2523
+ const back = Math.min(getBack(), maxBack);
2524
+ const scrolling = useRef({ maxBack, room });
2525
+ scrolling.current = { maxBack, room };
2526
+ useInput((input, key) => {
2527
+ if (key.ctrl && input === "c" && selection.active()) return selection.clear();
2528
+ const current = jobs.find((j) => j.id === getViewing());
2529
+ const target = current ?? jobs[Math.min(getSelected(), jobs.length - 1)];
2530
+ if (input === "x" && target && !target.done && target.stop) return target.stop();
2531
+ if (current) {
2532
+ const { maxBack, room } = scrolling.current;
2533
+ const by = (n: number) => setBack(Math.max(0, Math.min(maxBack, Math.min(getBack(), maxBack) + n)));
2534
+ if (key.pageUp) return by(room - 1);
2535
+ if (key.pageDown) return by(-(room - 1));
2536
+ if (key.upArrow || input === "k") return by(1);
2537
+ if (key.downArrow || input === "j") return by(-1);
2538
+ if (key.escape || key.leftArrow || (key.ctrl && input === "c")) {
2539
+ setBack(0);
2540
+ return setViewing(undefined);
2541
+ }
2542
+ return;
2543
+ }
2544
+ const n = jobs.length;
2545
+ if (key.upArrow || input === "k") return n && setSelected((Math.min(getSelected(), n - 1) - 1 + n) % n);
2546
+ 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
+ }
2551
+ if (key.escape || (key.ctrl && input === "c")) return dialog.resolve(undefined);
2552
+ });
2553
+ const mark = (j: JobInfo) => (j.done ? h(Text, { dimColor: true }, "○ ") : h(Text, { color: "green" }, "● "));
2554
+ 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;
2556
+ if (viewing) {
2557
+ const shown = lines.slice(lines.length - room - back, lines.length - back);
2558
+ return h(
2559
+ Box,
2560
+ frame,
2561
+ 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
+ lines.length > room + back ? h(Text, { dimColor: true }, ` ↑ ${lines.length - room - back} more lines`) : null,
2563
+ lines.length === 0 ? h(Text, { dimColor: true }, " (no output yet)") : null,
2564
+ shown.map((l, i) => h(Text, { key: i, wrap: "truncate-end" }, l || " ")),
2565
+ back > 0 ? h(Text, { dimColor: true }, ` ↓ ${back} more lines`) : null,
2566
+ h(Hint, {
2567
+ width,
2568
+ variants: [`PgUp/PgDn ↑↓ scroll${canStop(viewing) ? " · x stop" : ""} · esc back`, `↑↓${canStop(viewing) ? " · x" : ""} · esc`],
2569
+ }),
2570
+ );
2571
+ }
2572
+ const visible = roomFor(rows, VISIBLE);
2573
+ const start = around(selected, jobs.length, visible);
2574
+ return h(
2575
+ Box,
2576
+ frame,
2577
+ h(Text, { bold: true }, "Background tasks"),
2578
+ jobs.length === 0 ? h(Text, { dimColor: true }, "Nothing is running in the background.") : null,
2579
+ start > 0 ? h(Text, { dimColor: true }, ` ↑ ${start} more`) : null,
2580
+ jobs.slice(start, start + visible).map((j, k) => {
2581
+ const on = start + k === selected;
2582
+ return h(
2583
+ Text,
2584
+ { key: j.id, wrap: "truncate-end" },
2585
+ h(Text, { color: on ? "cyan" : undefined, bold: on }, on ? "❯ " : " "),
2586
+ mark(j),
2587
+ h(Text, { color: on ? "cyan" : undefined, bold: on }, `${j.kind} · ${j.title}`),
2588
+ j.status ? h(Text, { dimColor: true }, ` · ${j.status}`) : null,
2589
+ );
2590
+ }),
2591
+ start + visible < jobs.length ? h(Text, { dimColor: true }, ` ↓ ${jobs.length - start - visible} more`) : null,
2592
+ h(Hint, {
2593
+ width,
2594
+ variants: jobs.length
2595
+ ? [`↑↓ select · enter view output${canStop(jobs[selected]) ? " · x stop" : ""} · esc close`, `↑↓ · enter${canStop(jobs[selected]) ? " · x" : ""} · esc`]
2596
+ : ["esc close"],
2597
+ }),
2598
+ );
2599
+ }
2600
+
2436
2601
  function InputDialog({
2437
2602
  dialog,
2438
2603
  }: {
@@ -1,6 +1,6 @@
1
1
  import { definePlugin } from "@uncarved/jade-api";
2
2
  export const KEY_SPEC = /^(ctrl\+[a-z]|alt\+[a-z0-9]|shift\+tab)$/;
3
- export const RESERVED_KEYS = new Set([..."acdehijklmoruw"].map((c) => `ctrl+${c}`).concat("alt+f", "alt+b"));
3
+ export const RESERVED_KEYS = new Set([..."acdehijklmortuw"].map((c) => `ctrl+${c}`).concat("alt+f", "alt+b"));
4
4
  const registry = new Map;
5
5
  export default definePlugin({
6
6
  process(ctx) {