@trans-ai/trans-code 0.10.1 → 0.10.3
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.
- package/docs/superpowers/plans/2026-11-22-input-queue.md +113 -0
- package/docs/superpowers/specs/2026-11-22-input-queue-design.md +46 -0
- package/package.json +1 -1
- package/src/agent/loop.test.ts +78 -0
- package/src/agent/loop.ts +40 -5
- package/src/screens/REPL.tsx +90 -5
- package/src/screens/input-queue.test.ts +42 -0
- package/src/screens/input-queue.ts +46 -0
- package/src/screens/turn-summary.test.ts +23 -0
- package/src/screens/turn-summary.ts +16 -0
- package/src/version.ts +1 -1
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
# 忙时输入队列 Implementation Plan
|
|
2
|
+
|
|
3
|
+
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
|
4
|
+
|
|
5
|
+
**Goal:** agent 忙时用户可排队输入,回合自然结束自动逐条续发;取消/报错冻结,空回车续发,idle 单击 Esc 清空队列。
|
|
6
|
+
|
|
7
|
+
**Architecture:** 队列语义全部收进纯函数 reducer(`src/screens/input-queue.ts`,仿 turn-summary 抽离模式);REPL 只做三处接线——回车分支(入队/空回车续发)、runChat 收尾(自然结束 `turnEnded` / 取消与报错 `frozen`)、Esc 分支(清空)——加一段淡色队列渲染。
|
|
8
|
+
|
|
9
|
+
**Tech Stack:** TypeScript + Bun test(已有,零新依赖)。
|
|
10
|
+
|
|
11
|
+
**Spec:** `docs/superpowers/specs/2026-11-22-input-queue-design.md`
|
|
12
|
+
|
|
13
|
+
## Global Constraints
|
|
14
|
+
|
|
15
|
+
- 队列不持久化、不编辑单条;ACP 侧不动
|
|
16
|
+
- 入队认一切 busy(含 /compact、/resume 窗口);自动续发只挂聊天回合自然结束(end_turn/stalled/max_turns),`cancelled` 与 catch 报错一律 `frozen`
|
|
17
|
+
- Esc:idle 且队列非空 → 清空队列(不退出);队列空 → 原退出行为不变;busy → 原取消行为 + frozen
|
|
18
|
+
- 空白输入不入队;busy 时空回车无操作;idle 空回车且队列非空 → 续发一条
|
|
19
|
+
- 每任务收尾:`bun test` 全绿 + `bun run typecheck` 通过
|
|
20
|
+
|
|
21
|
+
## Review Focus
|
|
22
|
+
|
|
23
|
+
1. **空白输入 busy 回车** → 不入队(reducer 拒收空串)
|
|
24
|
+
2. **回合报错** → 冻结不续发,防止过期 key 连烧整条队列(REPL 接线的 catch 路径)
|
|
25
|
+
3. **Esc 语义矩阵**:busy=取消+冻结 / idle+队列=清空 / idle+空=退出(不再误退)
|
|
26
|
+
4. **取消或报错后队列滞留** → idle 空回车可逐条捞回
|
|
27
|
+
5. **/compact、/resume busy 窗口** → 可入队,流程结束不触发自动续发(只挂 runChat)
|
|
28
|
+
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
### Task 1: 队列 reducer `src/screens/input-queue.ts`
|
|
32
|
+
|
|
33
|
+
**Files:**
|
|
34
|
+
- Create: `src/screens/input-queue.ts`
|
|
35
|
+
- Test: `src/screens/input-queue.test.ts`
|
|
36
|
+
|
|
37
|
+
**Interfaces:**
|
|
38
|
+
|
|
39
|
+
```ts
|
|
40
|
+
export type QueueAction =
|
|
41
|
+
| { type: 'enqueue'; text: string }
|
|
42
|
+
| { type: 'turnEnded' } // 自然结束:shift 首条为 submit
|
|
43
|
+
| { type: 'frozen' } // 取消/报错:原样保留(冻结态由 REPL 侧呈现)
|
|
44
|
+
| { type: 'submitNext' } // idle 空回车:同 turnEnded
|
|
45
|
+
| { type: 'clear' };
|
|
46
|
+
export function reduceQueue(queue: string[], action: QueueAction): { queue: string[]; submit?: string };
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
- [ ] **Step 1: 写失败测试**
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
test('enqueue:入队尾部;空白(trim 后空)拒收')
|
|
53
|
+
test('turnEnded:shift 首条返回 submit 与剩余;空队列无 submit')
|
|
54
|
+
test('submitNext 与 turnEnded 同型')
|
|
55
|
+
test('frozen 原样返回;clear 清空')
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
- [ ] **Step 2: 跑测试确认失败**
|
|
59
|
+
|
|
60
|
+
Run: `bun test src/screens/input-queue.test.ts`
|
|
61
|
+
Expected: FAIL(模块不存在)
|
|
62
|
+
|
|
63
|
+
- [ ] **Step 3: 实现 reducer**(纯函数,不可变更新)
|
|
64
|
+
|
|
65
|
+
- [ ] **Step 4: 跑测试确认通过**
|
|
66
|
+
|
|
67
|
+
Run: `bun test src/screens/input-queue.test.ts`
|
|
68
|
+
Expected: PASS
|
|
69
|
+
|
|
70
|
+
- [ ] **Step 5: 提交**
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
git add src/screens/input-queue.ts src/screens/input-queue.test.ts
|
|
74
|
+
git commit -m "feat: input queue reducer with freeze and manual-resume semantics"
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
---
|
|
78
|
+
|
|
79
|
+
### Task 2: REPL 接线 + 队列渲染
|
|
80
|
+
|
|
81
|
+
**Files:**
|
|
82
|
+
- Modify: `src/screens/REPL.tsx`(回车分支、runChat 收尾、Esc 分支、渲染区)
|
|
83
|
+
- Test: 纯逻辑已由 Task 1 覆盖;本任务验证 = 全量回归 + typecheck
|
|
84
|
+
|
|
85
|
+
**Interfaces:**
|
|
86
|
+
- Consumes: Task 1 的 `reduceQueue`/`QueueAction`
|
|
87
|
+
- Produces: REPL 内部 `inputQueue` state + `dispatchQueue(action)` helper(不导出)
|
|
88
|
+
|
|
89
|
+
- [ ] **Step 1: 回车分支改造**(`key.return` 处)
|
|
90
|
+
|
|
91
|
+
原 `if (busyRef.current) return;` 改为:busy 且 trimmed 非空 → `enqueue` + `commitInput('')`;busy 且空 → 无操作;非 busy 且空且队列非空 → `submitNext`;非 busy 其余 → 原提交。同步在 `resolveSubmitInput` 门之前处理(空回车续发不能被闸门吞)。
|
|
92
|
+
|
|
93
|
+
- [ ] **Step 2: runChat 收尾挂续发**
|
|
94
|
+
|
|
95
|
+
`runChat` 内线程化 `endedNaturally`(stopReason 非 `cancelled` 且未抛错);`finally` 里 busy 复位后:自然结束 → `dispatchQueue({ type: 'turnEnded' })`,否则 `frozen`。dispatchQueue 收到 `submit` 时调 `handleSubmit(submit)`(注意重入:handleSubmit 会再次进入 runChat,队列 state 更新在前)。
|
|
96
|
+
|
|
97
|
+
- [ ] **Step 3: Esc 分支改造**
|
|
98
|
+
|
|
99
|
+
busy(现有取消路径不变,取消会经 runChat 的 cancelled → frozen);idle 且 `inputQueue.length > 0` → 清空 + 提示 `(队列已清空)` 并 return;idle 且空 → 原退出逻辑不动。
|
|
100
|
+
|
|
101
|
+
- [ ] **Step 4: 渲染**
|
|
102
|
+
|
|
103
|
+
输入框上方:`inputQueue.map(t => <Text color="gray" dimColor>⏎ {t}</Text>)`;队列非空且 !busy 时附提示行 `(queued N — Enter 续发,Esc 清空)`。
|
|
104
|
+
|
|
105
|
+
- [ ] **Step 5: 全量回归 + typecheck + 提交**
|
|
106
|
+
|
|
107
|
+
Run: `bun test && bun run typecheck`
|
|
108
|
+
Expected: PASS 全绿
|
|
109
|
+
|
|
110
|
+
```bash
|
|
111
|
+
git add src/screens/REPL.tsx
|
|
112
|
+
git commit -m "feat: queue prompts while busy, auto-continue after natural turn end"
|
|
113
|
+
```
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# 忙时输入队列(busy-input queue)— 设计
|
|
2
|
+
|
|
3
|
+
## 意图
|
|
4
|
+
|
|
5
|
+
agent 工作时用户可以继续打字并回车排队,回合结束后自动逐条接续——对齐 Claude Code 的"边生成边输入"。现状:忙时回车直接丢弃(`REPL.tsx` 的 `busyRef` 拦截),用户只能干等或 Esc 取消。
|
|
6
|
+
|
|
7
|
+
## 设计
|
|
8
|
+
|
|
9
|
+
**队列状态机**(纯函数 reducer,`src/screens/input-queue.ts`,可测):
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
export type QueueAction =
|
|
13
|
+
| { type: 'enqueue'; text: string } // busy 时回车入队
|
|
14
|
+
| { type: 'turnEnded' } // 聊天回合自然结束(end_turn/stalled/max_turns)→ 续发一条
|
|
15
|
+
| { type: 'frozen' } // Esc 取消或回合报错 → 队列冻结保留
|
|
16
|
+
| { type: 'submitNext' } // idle 空回车 → 续发一条(冻结后手动恢复)
|
|
17
|
+
| { type: 'clear' }; // idle 下 Esc 清空队列
|
|
18
|
+
export function reduceQueue(queue: string[], action: QueueAction): { queue: string[]; submit?: string };
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
**入队**:idle phase 且 busy 时回车 → trimmed 输入入队、清空输入框;非 busy 走现有提交路径不变。
|
|
22
|
+
|
|
23
|
+
**续发**:回合**自然结束**(end_turn / stalled / max_turns 等)→ 自动 shift 一条 `handleSubmit`;**Esc 取消或回合报错都不自动续发**(取消=改主意;报错=连烧整条队列没有意义),队列冻结并提示 `(queued N — Enter 续发,Esc 清空)`,idle 时空回车续发下一条。
|
|
24
|
+
|
|
25
|
+
**Esc 清空**:idle 且队列非空时,单击 Esc = 清空队列(对齐 mention/斜杠弹窗的 Esc 关闭惯例);队列空时 Esc 仍为退出程序——原有退出行为只在无队列时保留。
|
|
26
|
+
|
|
27
|
+
**busy 的口径**:入队认一切 busy(含 /compact、/resume 压缩窗口,此时打的字正是要排队的);自动续发只挂在**聊天回合**的自然结束上,压缩/恢复流程结束不触发(避免把 handleSubmit 插进恢复的渲染中缝),滞留条目由空回车或下一回合结束捞走。
|
|
28
|
+
|
|
29
|
+
**渲染**:输入框上方淡色列表,每条 `⏎ <text>`;队首不展示输入框重复。
|
|
30
|
+
|
|
31
|
+
**命令**:斜杠命令照常入队,续发时经正常 dispatch(本地执行,快)。
|
|
32
|
+
|
|
33
|
+
## 非目标
|
|
34
|
+
|
|
35
|
+
- 队列条目编辑/删除单条(入了队就是定稿)
|
|
36
|
+
- 队列持久化(重启丢弃)
|
|
37
|
+
- ACP 侧(宿主自己管理输入时序)
|
|
38
|
+
- 后台并行 agent 任务(那是 C,后续大版本)
|
|
39
|
+
|
|
40
|
+
## 备选(已否)
|
|
41
|
+
|
|
42
|
+
- 单条 pending(只存最新):CC 是多深度,排队多条是常态需求 — 已否
|
|
43
|
+
- Esc 取消后也自动续发:与"取消=改主意"语义冲突,取消瞬间续发用户来不及反应 — 已否
|
|
44
|
+
- 报错回合自动续发:持续性错误(过期 key/断网)会连烧整条队列 — 已否,冻结
|
|
45
|
+
- 双击 Esc(500ms 窗口)清空:计时窗口复杂且首按有误退风险;单击清空 + 空队列才退出更简、且对齐弹窗 Esc 惯例 — 已否
|
|
46
|
+
- 取消后把队首移回输入框可编辑:状态机复杂化,空回车续发已够用 — 已否
|
package/package.json
CHANGED
package/src/agent/loop.test.ts
CHANGED
|
@@ -690,3 +690,81 @@ describe('runAgentLoop', () => {
|
|
|
690
690
|
expect(wrapUp).toBeUndefined();
|
|
691
691
|
});
|
|
692
692
|
});
|
|
693
|
+
|
|
694
|
+
describe('context estimator sees tool-call args', () => {
|
|
695
|
+
test('estimateMessagesChars 计入 tool_calls 参数(巨型参数不再隐形)', async () => {
|
|
696
|
+
const { AIMessage } = await import('@langchain/core/messages');
|
|
697
|
+
const { estimateMessagesChars } = await import('./loop.js');
|
|
698
|
+
const messages = [
|
|
699
|
+
new AIMessage({
|
|
700
|
+
content: '写文件',
|
|
701
|
+
tool_calls: [
|
|
702
|
+
{ id: 'c1', name: 'write_file', args: { content: 'x'.repeat(250_000) } },
|
|
703
|
+
],
|
|
704
|
+
}),
|
|
705
|
+
];
|
|
706
|
+
expect(estimateMessagesChars(messages)).toBeGreaterThan(200_000);
|
|
707
|
+
});
|
|
708
|
+
});
|
|
709
|
+
|
|
710
|
+
describe('malformed tool-call breaker', () => {
|
|
711
|
+
test('isMalformedToolArgs:仅 _raw 键为真,正常/空参数为假', async () => {
|
|
712
|
+
const { isMalformedToolArgs } = await import('./loop.js');
|
|
713
|
+
expect(isMalformedToolArgs({ _raw: '{"broken": tru' })).toBe(true);
|
|
714
|
+
expect(isMalformedToolArgs({ path: 'a.ts' })).toBe(false);
|
|
715
|
+
expect(isMalformedToolArgs({})).toBe(false);
|
|
716
|
+
});
|
|
717
|
+
|
|
718
|
+
test('连续 3 次全格式错误 → 第 3 次拒绝执行并停轮(stalled),给出指引', async () => {
|
|
719
|
+
let executions = 0;
|
|
720
|
+
const countingTool: AgentTool = {
|
|
721
|
+
...fakeTool,
|
|
722
|
+
name: 'fake',
|
|
723
|
+
async execute() {
|
|
724
|
+
executions++;
|
|
725
|
+
return 'ok';
|
|
726
|
+
},
|
|
727
|
+
};
|
|
728
|
+
const events: Array<{ type: string; text?: string }> = [];
|
|
729
|
+
const result = await runAgentLoop({
|
|
730
|
+
model: scriptedModel([
|
|
731
|
+
{ tool: 'fake', args: '{"path": "a.ts", "content": "xxx' },
|
|
732
|
+
{ tool: 'fake', args: '{"path": "b.ts", "content": "yyy' },
|
|
733
|
+
{ tool: 'fake', args: '{"path": "c.ts", "content": "zzz' },
|
|
734
|
+
{ tool: 'fake', args: '{"path": "d.ts", "content": "www' },
|
|
735
|
+
]),
|
|
736
|
+
cwd: '/tmp',
|
|
737
|
+
messages: [],
|
|
738
|
+
systemPrompt: 'test',
|
|
739
|
+
tools: [countingTool],
|
|
740
|
+
onEvent: (event) => events.push(event as never),
|
|
741
|
+
});
|
|
742
|
+
|
|
743
|
+
expect(result.stopReason).toBe('stalled');
|
|
744
|
+
expect(executions).toBeLessThanOrEqual(2);
|
|
745
|
+
const guidance = events.find(
|
|
746
|
+
(event) => event.type === 'text' && JSON.stringify(event).includes('malformed'),
|
|
747
|
+
);
|
|
748
|
+
expect(guidance).toBeDefined();
|
|
749
|
+
});
|
|
750
|
+
|
|
751
|
+
test('格式错误后自愈(第 2 次正常)→ 计数归零不熔断', async () => {
|
|
752
|
+
const events: Array<{ type: string }> = [];
|
|
753
|
+
const result = await runAgentLoop({
|
|
754
|
+
model: scriptedModel([
|
|
755
|
+
{ tool: 'fake', args: '{"broken": tru' },
|
|
756
|
+
{ tool: 'fake', args: '{"a":1}' },
|
|
757
|
+
{ tool: 'fake', args: '{"a":2}' },
|
|
758
|
+
{ tool: 'fake', args: '{"a":3}' },
|
|
759
|
+
{ tool: 'fake', args: '{"a":4}' },
|
|
760
|
+
{ tool: 'text' as never, text: 'done' } as never,
|
|
761
|
+
]),
|
|
762
|
+
cwd: '/tmp',
|
|
763
|
+
messages: [],
|
|
764
|
+
systemPrompt: 'test',
|
|
765
|
+
tools: [fakeTool],
|
|
766
|
+
onEvent: (event) => events.push(event as never),
|
|
767
|
+
});
|
|
768
|
+
expect(result.stopReason).toBe('end_turn');
|
|
769
|
+
});
|
|
770
|
+
});
|
package/src/agent/loop.ts
CHANGED
|
@@ -249,13 +249,36 @@ async function runMockTurn(
|
|
|
249
249
|
|
|
250
250
|
const COMPACT_DEFAULT_CHARS = 200_000;
|
|
251
251
|
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
252
|
+
/**
|
|
253
|
+
* Char estimate for the in-turn compaction gate. MUST include tool-call
|
|
254
|
+
* arguments: a turn that repeatedly emits huge (possibly malformed) tool
|
|
255
|
+
* payloads grows history invisibly if only message content is counted —
|
|
256
|
+
* that blind spot once ballooned a session past the model's context window.
|
|
257
|
+
*/
|
|
258
|
+
export function estimateMessagesChars(messages: BaseMessage[]): number {
|
|
259
|
+
return messages.reduce((sum, message) => {
|
|
260
|
+
const toolCalls = (message as AIMessage).tool_calls ?? [];
|
|
261
|
+
const argsChars = toolCalls.reduce(
|
|
262
|
+
(n, call) => n + JSON.stringify(call.args ?? '').length,
|
|
263
|
+
0,
|
|
264
|
+
);
|
|
265
|
+
return sum + JSON.stringify(message.content ?? '').length + argsChars + 200;
|
|
266
|
+
}, 0);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** True when parseToolCalls fell back to {_raw}: the args were not valid JSON. */
|
|
270
|
+
export function isMalformedToolArgs(args: Record<string, unknown>): boolean {
|
|
271
|
+
return Object.keys(args).length === 1 && '_raw' in args;
|
|
257
272
|
}
|
|
258
273
|
|
|
274
|
+
/** Consecutive all-malformed turns tolerated before the breaker stops the loop. */
|
|
275
|
+
const MALFORMED_TOOL_CALL_BREAKER = 3;
|
|
276
|
+
|
|
277
|
+
const MALFORMED_GUIDANCE =
|
|
278
|
+
'Your last tool calls had malformed JSON arguments and were never executed. ' +
|
|
279
|
+
'Do NOT retry the same payload. Write the file in smaller sections, or use a ' +
|
|
280
|
+
'bash heredoc for large content, or reply describing what you are stuck on.';
|
|
281
|
+
|
|
259
282
|
/**
|
|
260
283
|
* Auto-compaction (Claude Code's autoCompact, ported): when the estimated
|
|
261
284
|
* conversation size exceeds the char budget, summarize the history with the
|
|
@@ -350,6 +373,7 @@ export async function runAgentLoop(
|
|
|
350
373
|
let stallNudged = false;
|
|
351
374
|
let callsAtStallNudge = 0;
|
|
352
375
|
let wrapUpNudged = false;
|
|
376
|
+
let malformedStrikes = 0;
|
|
353
377
|
|
|
354
378
|
for (let turn = 0; turn < maxTurns; turn++) {
|
|
355
379
|
if (options.signal?.aborted) return { stopReason: 'cancelled', messages };
|
|
@@ -399,6 +423,17 @@ export async function runAgentLoop(
|
|
|
399
423
|
return { stopReason: 'end_turn', messages };
|
|
400
424
|
}
|
|
401
425
|
|
|
426
|
+
// Malformed-args breaker: every call this turn unparsable → strike;
|
|
427
|
+
// a clean turn resets. The 3rd consecutive strike is refused (never
|
|
428
|
+
// executed) and stops the loop — retrying the same giant broken
|
|
429
|
+
// payload only balloons the context.
|
|
430
|
+
const allMalformed = toolCalls.every((call) => isMalformedToolArgs(call.args));
|
|
431
|
+
malformedStrikes = allMalformed ? malformedStrikes + 1 : 0;
|
|
432
|
+
if (malformedStrikes >= MALFORMED_TOOL_CALL_BREAKER) {
|
|
433
|
+
await options.onEvent({ type: 'text', text: `\n⚠ ${MALFORMED_GUIDANCE}\n` });
|
|
434
|
+
return { stopReason: 'stalled', messages };
|
|
435
|
+
}
|
|
436
|
+
|
|
402
437
|
for (const call of toolCalls) {
|
|
403
438
|
if (options.signal?.aborted) return { stopReason: 'cancelled', messages };
|
|
404
439
|
|
package/src/screens/REPL.tsx
CHANGED
|
@@ -48,15 +48,18 @@ import {
|
|
|
48
48
|
} from './slash-completion.js';
|
|
49
49
|
import { resolveSubmitInput } from './submit.js';
|
|
50
50
|
import { submitSearchApiKey } from './search-setup.js';
|
|
51
|
+
import { reduceQueue, shouldResumeQueue, type QueueAction } from './input-queue.js';
|
|
51
52
|
import { historyRule } from './history-rule.js';
|
|
52
53
|
import { renderDiff } from './diff-render.js';
|
|
53
|
-
import { createTurnStats, recordCall, shouldCollapse, summaryLine } from './turn-summary.js';
|
|
54
|
+
import { createTurnStats, recordCall, renderTurnLog, shouldCollapse, summaryLine } from './turn-summary.js';
|
|
54
55
|
import { buildSystemPrompt, INIT_PROMPT, loadProjectContext } from '../agent/system-prompt.js';
|
|
55
56
|
import { HumanMessage, SystemMessage, type BaseMessage } from '@langchain/core/messages';
|
|
56
57
|
|
|
57
58
|
interface HistoryEntry {
|
|
58
59
|
input: string;
|
|
59
60
|
output: string;
|
|
61
|
+
/** Tool-log detail hidden behind the collapse summary (ctrl+o reveals). */
|
|
62
|
+
hiddenLines?: string[];
|
|
60
63
|
}
|
|
61
64
|
|
|
62
65
|
type PromptPhase =
|
|
@@ -149,6 +152,35 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
149
152
|
setHistory(prev => [...prev, entry]);
|
|
150
153
|
}, []);
|
|
151
154
|
|
|
155
|
+
/** ctrl+o verbose view: collapsed turns show their hidden tool-log detail. */
|
|
156
|
+
const [verboseTools, setVerboseTools] = useState(false);
|
|
157
|
+
|
|
158
|
+
const attachHiddenLines = useCallback((lines: string[]) => {
|
|
159
|
+
setHistory(prev => {
|
|
160
|
+
if (prev.length === 0 || lines.length === 0) return prev;
|
|
161
|
+
const next = [...prev];
|
|
162
|
+
const last = next[next.length - 1];
|
|
163
|
+
next[next.length - 1] = {
|
|
164
|
+
...last,
|
|
165
|
+
hiddenLines: [...(last.hiddenLines ?? []), ...lines],
|
|
166
|
+
};
|
|
167
|
+
return next;
|
|
168
|
+
});
|
|
169
|
+
}, []);
|
|
170
|
+
|
|
171
|
+
// Busy-input queue: prompts typed while the agent works. Natural turn end
|
|
172
|
+
// auto-continues the head; cancel/error freezes (manual Enter resumes);
|
|
173
|
+
// Esc at idle clears. Ref mirror avoids stale closures in runChat's finally.
|
|
174
|
+
const [inputQueue, setInputQueue] = useState<string[]>([]);
|
|
175
|
+
const inputQueueRef = useRef<string[]>([]);
|
|
176
|
+
const applyQueue = useCallback((action: QueueAction) => {
|
|
177
|
+
const next = reduceQueue(inputQueueRef.current, action);
|
|
178
|
+
inputQueueRef.current = next.queue;
|
|
179
|
+
setInputQueue(next.queue);
|
|
180
|
+
return next;
|
|
181
|
+
}, []);
|
|
182
|
+
const handleSubmitRef = useRef<(raw: string) => Promise<void>>(async () => {});
|
|
183
|
+
|
|
152
184
|
// ---- chat state ----
|
|
153
185
|
const [busy, setBusy] = useState(false);
|
|
154
186
|
const busyRef = useRef(false);
|
|
@@ -430,6 +462,7 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
430
462
|
appendChatOutput('[plan 模式:只读探索,产出方案,PLAN READY 后可让我执行]\n');
|
|
431
463
|
}
|
|
432
464
|
|
|
465
|
+
let endedNaturally = false;
|
|
433
466
|
try {
|
|
434
467
|
const provider =
|
|
435
468
|
process.env.TRANSCODE_MOCK === '1'
|
|
@@ -513,9 +546,11 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
513
546
|
});
|
|
514
547
|
|
|
515
548
|
// Collapse long turns into one summary line; short turns stay expanded.
|
|
549
|
+
// Collapsed detail is kept (hiddenLines) so ctrl+o can reveal it.
|
|
516
550
|
if (shouldCollapse(stats)) {
|
|
517
551
|
const line = summaryLine(stats);
|
|
518
552
|
if (line) appendChatOutput(`\n${line}`);
|
|
553
|
+
attachHiddenLines(bufferedLines);
|
|
519
554
|
} else {
|
|
520
555
|
for (const line of bufferedLines) appendChatOutput(line);
|
|
521
556
|
}
|
|
@@ -568,7 +603,11 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
568
603
|
persist();
|
|
569
604
|
})();
|
|
570
605
|
}
|
|
571
|
-
if (controller.signal.aborted)
|
|
606
|
+
if (controller.signal.aborted) {
|
|
607
|
+
appendChatOutput('\n(cancelled)');
|
|
608
|
+
} else {
|
|
609
|
+
endedNaturally = true;
|
|
610
|
+
}
|
|
572
611
|
} catch (error) {
|
|
573
612
|
const message = error instanceof Error ? error.message : String(error);
|
|
574
613
|
appendChatOutput(`\n⚠ ${message}`);
|
|
@@ -582,9 +621,15 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
582
621
|
// The agent may have created/removed files; rebuild @-completion list.
|
|
583
622
|
setFileList(null);
|
|
584
623
|
dragFlush();
|
|
624
|
+
// Queue continuation: only a naturally-ended turn auto-submits the
|
|
625
|
+
// next queued prompt; cancel and error freeze it (Enter resumes).
|
|
626
|
+
const queued = applyQueue(endedNaturally ? { type: 'turnEnded' } : { type: 'frozen' });
|
|
627
|
+
if (endedNaturally && queued.submit) {
|
|
628
|
+
void handleSubmitRef.current(queued.submit);
|
|
629
|
+
}
|
|
585
630
|
}
|
|
586
631
|
},
|
|
587
|
-
[ctx.modelId, addHistory, appendChatOutput, askInTerminal, setBusyBoth, dragFlush],
|
|
632
|
+
[ctx.modelId, addHistory, appendChatOutput, askInTerminal, setBusyBoth, dragFlush, applyQueue],
|
|
588
633
|
);
|
|
589
634
|
|
|
590
635
|
const enterModelSelect = useCallback(() => {
|
|
@@ -1007,12 +1052,19 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
1007
1052
|
setHistoryIndex(-1);
|
|
1008
1053
|
setSavedInput('');
|
|
1009
1054
|
}, [exit, ctx, phase, handleApiKey, addHistory, enterModelSelect, commitInput, dragFlush, runChat]);
|
|
1055
|
+
// Late-bound so runChat's finally can auto-continue queued prompts.
|
|
1056
|
+
handleSubmitRef.current = handleSubmit;
|
|
1010
1057
|
|
|
1011
1058
|
useInput((ch, key) => {
|
|
1012
1059
|
if (process.env.TRANSCODE_DEBUG_KEYS === '1') {
|
|
1013
1060
|
// eslint-disable-next-line no-console
|
|
1014
1061
|
console.error(`CB ${JSON.stringify(ch)} ret=${key.return} esc=${key.escape}`);
|
|
1015
1062
|
}
|
|
1063
|
+
// ctrl+o: toggle verbose tool logs (expand/collapse every turn).
|
|
1064
|
+
if (key.ctrl && (ch === 'o' || ch === 'O')) {
|
|
1065
|
+
setVerboseTools(v => !v);
|
|
1066
|
+
return;
|
|
1067
|
+
}
|
|
1016
1068
|
// @-mention popup: Esc dismisses it instead of exiting the app.
|
|
1017
1069
|
if (key.escape && mentionActive && mentionCandidates.length > 0) {
|
|
1018
1070
|
setMentionDismissed(true);
|
|
@@ -1041,6 +1093,11 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
1041
1093
|
addHistory({ input: '', output: 'Cancelled.' });
|
|
1042
1094
|
return;
|
|
1043
1095
|
}
|
|
1096
|
+
if (inputQueueRef.current.length > 0) {
|
|
1097
|
+
applyQueue({ type: 'clear' });
|
|
1098
|
+
addHistory({ input: '', output: '(队列已清空)' });
|
|
1099
|
+
return;
|
|
1100
|
+
}
|
|
1044
1101
|
exit();
|
|
1045
1102
|
return;
|
|
1046
1103
|
}
|
|
@@ -1248,7 +1305,21 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
1248
1305
|
}
|
|
1249
1306
|
|
|
1250
1307
|
if (key.return) {
|
|
1251
|
-
if (busyRef.current)
|
|
1308
|
+
if (busyRef.current) {
|
|
1309
|
+
// Still generating: queue the prompt; it submits when the turn ends
|
|
1310
|
+
// naturally (cancel/error freeze it — idle empty-Enter resumes).
|
|
1311
|
+
const trimmed = inputRef.current.trim();
|
|
1312
|
+
if (trimmed) {
|
|
1313
|
+
applyQueue({ type: 'enqueue', text: trimmed });
|
|
1314
|
+
commitInput('');
|
|
1315
|
+
}
|
|
1316
|
+
return;
|
|
1317
|
+
}
|
|
1318
|
+
if (shouldResumeQueue(phase, inputRef.current, inputQueueRef.current.length)) {
|
|
1319
|
+
const next = applyQueue({ type: 'submitNext' });
|
|
1320
|
+
if (next.submit) void handleSubmit(next.submit);
|
|
1321
|
+
return;
|
|
1322
|
+
}
|
|
1252
1323
|
handleSubmit(inputRef.current);
|
|
1253
1324
|
return;
|
|
1254
1325
|
}
|
|
@@ -1339,7 +1410,11 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
1339
1410
|
)}
|
|
1340
1411
|
{entry.output && (
|
|
1341
1412
|
<Box marginLeft={2}>
|
|
1342
|
-
<Text>
|
|
1413
|
+
<Text>
|
|
1414
|
+
{entry.hiddenLines?.length
|
|
1415
|
+
? renderTurnLog(entry.output, entry.hiddenLines, verboseTools)
|
|
1416
|
+
: entry.output}
|
|
1417
|
+
</Text>
|
|
1343
1418
|
</Box>
|
|
1344
1419
|
)}
|
|
1345
1420
|
</Box>
|
|
@@ -1447,6 +1522,16 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
1447
1522
|
|
|
1448
1523
|
{phase !== 'model_select' && phase !== 'session_select' && (
|
|
1449
1524
|
<Box flexDirection="column">
|
|
1525
|
+
{inputQueue.length > 0 && (
|
|
1526
|
+
<Box flexDirection="column" marginLeft={2}>
|
|
1527
|
+
{inputQueue.map((text, i) => (
|
|
1528
|
+
<Text key={i} color="gray" dimColor>⏎ {text}</Text>
|
|
1529
|
+
))}
|
|
1530
|
+
{!busy && phase === 'idle' && (
|
|
1531
|
+
<Text color="gray" dimColor>(queued {inputQueue.length} — Enter 续发,Esc 清空)</Text>
|
|
1532
|
+
)}
|
|
1533
|
+
</Box>
|
|
1534
|
+
)}
|
|
1450
1535
|
<Text color="gray" dimColor>{historyRule(stdout?.columns ?? 80)}</Text>
|
|
1451
1536
|
<Box>
|
|
1452
1537
|
<Text color={phase === 'idle' ? 'green' : 'yellow'}>{promptLabel}</Text>
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { reduceQueue } from './input-queue.js';
|
|
3
|
+
|
|
4
|
+
describe('reduceQueue', () => {
|
|
5
|
+
test('enqueue:入队尾部;空白(trim 后空)拒收', () => {
|
|
6
|
+
expect(reduceQueue(['a'], { type: 'enqueue', text: 'b' })).toEqual({
|
|
7
|
+
queue: ['a', 'b'],
|
|
8
|
+
});
|
|
9
|
+
expect(reduceQueue(['a'], { type: 'enqueue', text: ' ' })).toEqual({ queue: ['a'] });
|
|
10
|
+
expect(reduceQueue([], { type: 'enqueue', text: '' })).toEqual({ queue: [] });
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
test('turnEnded:shift 首条返回 submit 与剩余;空队列无 submit', () => {
|
|
14
|
+
expect(reduceQueue(['a', 'b'], { type: 'turnEnded' })).toEqual({
|
|
15
|
+
queue: ['b'],
|
|
16
|
+
submit: 'a',
|
|
17
|
+
});
|
|
18
|
+
expect(reduceQueue([], { type: 'turnEnded' })).toEqual({ queue: [] });
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
test('submitNext 与 turnEnded 同型', () => {
|
|
22
|
+
expect(reduceQueue(['x'], { type: 'submitNext' })).toEqual({ queue: [], submit: 'x' });
|
|
23
|
+
expect(reduceQueue([], { type: 'submitNext' })).toEqual({ queue: [] });
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
test('frozen 原样返回;clear 清空', () => {
|
|
27
|
+
expect(reduceQueue(['a', 'b'], { type: 'frozen' })).toEqual({ queue: ['a', 'b'] });
|
|
28
|
+
expect(reduceQueue(['a'], { type: 'clear' })).toEqual({ queue: [] });
|
|
29
|
+
});
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
describe('shouldResumeQueue', () => {
|
|
33
|
+
test('仅 idle + 空输入 + 队列非空才续发;apikey 等 phase 的空回车不归队列', async () => {
|
|
34
|
+
const { shouldResumeQueue } = await import('./input-queue.js');
|
|
35
|
+
expect(shouldResumeQueue('idle', '', 2)).toBe(true);
|
|
36
|
+
expect(shouldResumeQueue('model_apikey', '', 2)).toBe(false);
|
|
37
|
+
expect(shouldResumeQueue('search_apikey', '', 2)).toBe(false);
|
|
38
|
+
expect(shouldResumeQueue('idle', ' ', 1)).toBe(true);
|
|
39
|
+
expect(shouldResumeQueue('idle', 'text', 1)).toBe(false);
|
|
40
|
+
expect(shouldResumeQueue('idle', '', 0)).toBe(false);
|
|
41
|
+
});
|
|
42
|
+
});
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Busy-input queue semantics, extracted as a pure reducer so the REPL only
|
|
3
|
+
* wires keys and rendering. Natural turn end (and the idle empty-Enter
|
|
4
|
+
* resume) shift the head as the next submit; cancel and error freeze the
|
|
5
|
+
* queue (nothing auto-fires); Esc at idle clears it.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export type QueueAction =
|
|
9
|
+
| { type: 'enqueue'; text: string }
|
|
10
|
+
| { type: 'turnEnded' }
|
|
11
|
+
| { type: 'frozen' }
|
|
12
|
+
| { type: 'submitNext' }
|
|
13
|
+
| { type: 'clear' };
|
|
14
|
+
|
|
15
|
+
export interface QueueState {
|
|
16
|
+
queue: string[];
|
|
17
|
+
submit?: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function reduceQueue(queue: string[], action: QueueAction): QueueState {
|
|
21
|
+
switch (action.type) {
|
|
22
|
+
case 'enqueue': {
|
|
23
|
+
const text = action.text.trim();
|
|
24
|
+
if (!text) return { queue };
|
|
25
|
+
return { queue: [...queue, text] };
|
|
26
|
+
}
|
|
27
|
+
case 'turnEnded':
|
|
28
|
+
case 'submitNext': {
|
|
29
|
+
if (queue.length === 0) return { queue };
|
|
30
|
+
return { queue: queue.slice(1), submit: queue[0] };
|
|
31
|
+
}
|
|
32
|
+
case 'frozen':
|
|
33
|
+
return { queue };
|
|
34
|
+
case 'clear':
|
|
35
|
+
return { queue: [] };
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Empty-Enter resumes the queue ONLY at the idle prompt: the apikey phases
|
|
41
|
+
* have their own empty-Enter contract ("reuse the saved key"), and routing
|
|
42
|
+
* their Enter to the queue would swallow a queued prompt as if it were a key.
|
|
43
|
+
*/
|
|
44
|
+
export function shouldResumeQueue(phase: string, raw: string, queueLength: number): boolean {
|
|
45
|
+
return phase === 'idle' && !raw.trim() && queueLength > 0;
|
|
46
|
+
}
|
|
@@ -39,3 +39,26 @@ describe('turn summary', () => {
|
|
|
39
39
|
expect(shouldCollapse(long)).toBe(true);
|
|
40
40
|
});
|
|
41
41
|
});
|
|
42
|
+
|
|
43
|
+
describe('renderTurnLog', () => {
|
|
44
|
+
test('折叠:summary + "… +N lines (ctrl+o to expand)",N 数实际行数', async () => {
|
|
45
|
+
const { renderTurnLog } = await import('./turn-summary.js');
|
|
46
|
+
const hidden = ['\n⚙ read_file a.ts ✓', '\n⚙ bash npm test ✓\nextra line', '\n⚙ grep foo ✓'];
|
|
47
|
+
expect(renderTurnLog('⚙ 3 tool calls · …', hidden, false)).toBe(
|
|
48
|
+
'⚙ 3 tool calls · …\n… +4 lines (ctrl+o to expand)',
|
|
49
|
+
);
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
test('展开:明细可见 + "(ctrl+o to collapse)" 提示', async () => {
|
|
53
|
+
const { renderTurnLog } = await import('./turn-summary.js');
|
|
54
|
+
const out = renderTurnLog('S', ['\n⚙ read_file a.ts ✓', '\n⚙ bash npm test ✓'], true);
|
|
55
|
+
expect(out).toContain('read_file a.ts');
|
|
56
|
+
expect(out).toContain('bash npm test');
|
|
57
|
+
expect(out).toContain('(ctrl+o to collapse)');
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
test('无明细时原样返回 summary', async () => {
|
|
61
|
+
const { renderTurnLog } = await import('./turn-summary.js');
|
|
62
|
+
expect(renderTurnLog('S', [], false)).toBe('S');
|
|
63
|
+
});
|
|
64
|
+
});
|
|
@@ -32,3 +32,19 @@ export function summaryLine(stats: TurnStats): string {
|
|
|
32
32
|
const markers = `${stats.ok}✓${stats.fail > 0 ? ` ${stats.fail}✗` : ''}`;
|
|
33
33
|
return `⚙ ${stats.calls} tool calls · ${parts.join(' ')} · ${markers}`;
|
|
34
34
|
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Render a collapsed turn's tool log. Non-verbose: the summary line plus a
|
|
38
|
+
* "… +N lines (ctrl+o to expand)" affordance; verbose (ctrl+o): the hidden
|
|
39
|
+
* detail lines become visible so nothing is permanently unreachable.
|
|
40
|
+
*/
|
|
41
|
+
export function renderTurnLog(summary: string, hiddenLines: string[], verbose: boolean): string {
|
|
42
|
+
if (hiddenLines.length === 0) return summary;
|
|
43
|
+
if (verbose) {
|
|
44
|
+
return `${summary}\n(ctrl+o to collapse)${hiddenLines.join('')}`;
|
|
45
|
+
}
|
|
46
|
+
const count = hiddenLines
|
|
47
|
+
.flatMap((line) => line.split('\n'))
|
|
48
|
+
.filter((line) => line.trim().length > 0).length;
|
|
49
|
+
return `${summary}\n… +${count} lines (ctrl+o to expand)`;
|
|
50
|
+
}
|
package/src/version.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// Auto-generated from package.json by scripts/sync-version.ts (npm version hook)
|
|
2
|
-
export const VERSION = '0.10.
|
|
2
|
+
export const VERSION = '0.10.3';
|