@trans-ai/trans-code 0.10.2 → 0.10.4

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.
@@ -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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trans-ai/trans-code",
3
- "version": "0.10.2",
3
+ "version": "0.10.4",
4
4
  "description": "AI-powered multi-model coding CLI",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",
package/src/main.tsx CHANGED
@@ -13,7 +13,7 @@ function Banner({ modelId, cwd, envLabel }: { modelId: string; cwd: string; envL
13
13
  const models = getAvailableModels();
14
14
  const current = models.find(m => m.id === modelId);
15
15
 
16
- const logo = bannerLines('T R A N S C O D E · Multi-model Agent');
16
+ const logo = bannerLines('T R A N S C O D E · Multi-Model Agent');
17
17
 
18
18
  return (
19
19
  <Box flexDirection="column" marginBottom={1}>
@@ -48,6 +48,8 @@ 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';
52
+ import { createStreamThrottler } from './stream-throttle.js';
51
53
  import { historyRule } from './history-rule.js';
52
54
  import { renderDiff } from './diff-render.js';
53
55
  import { createTurnStats, recordCall, renderTurnLog, shouldCollapse, summaryLine } from './turn-summary.js';
@@ -167,6 +169,19 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
167
169
  });
168
170
  }, []);
169
171
 
172
+ // Busy-input queue: prompts typed while the agent works. Natural turn end
173
+ // auto-continues the head; cancel/error freezes (manual Enter resumes);
174
+ // Esc at idle clears. Ref mirror avoids stale closures in runChat's finally.
175
+ const [inputQueue, setInputQueue] = useState<string[]>([]);
176
+ const inputQueueRef = useRef<string[]>([]);
177
+ const applyQueue = useCallback((action: QueueAction) => {
178
+ const next = reduceQueue(inputQueueRef.current, action);
179
+ inputQueueRef.current = next.queue;
180
+ setInputQueue(next.queue);
181
+ return next;
182
+ }, []);
183
+ const handleSubmitRef = useRef<(raw: string) => Promise<void>>(async () => {});
184
+
170
185
  // ---- chat state ----
171
186
  const [busy, setBusy] = useState(false);
172
187
  const busyRef = useRef(false);
@@ -334,6 +349,21 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
334
349
  });
335
350
  }, []);
336
351
 
352
+ /**
353
+ * Frame-level coalescing for streaming output. Stock Ink re-renders
354
+ * synchronously per setState, so per-delta appends rewrite the whole
355
+ * history frame dozens of times per second — that is the flicker.
356
+ * Everything within a turn flows through here and is flushed at turn
357
+ * end (order preserved; ≤32ms latency, invisible).
358
+ */
359
+ const streamAppendRef = useRef<ReturnType<typeof createStreamThrottler> | null>(null);
360
+ if (streamAppendRef.current === null) {
361
+ streamAppendRef.current = createStreamThrottler(appendChatOutput, 32);
362
+ }
363
+ const streamAppend = (chunk: string): void => {
364
+ streamAppendRef.current?.push(chunk);
365
+ };
366
+
337
367
  /**
338
368
  * One shared compaction run for /resume and /compact: fast-model routing
339
369
  * (routing.compact → fallback current model) with the digest streamed
@@ -349,11 +379,13 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
349
379
  record,
350
380
  createModel(getRouting().compact ?? ctx.modelId).model,
351
381
  keepTurns,
352
- (delta) => appendChatOutput(delta),
382
+ (delta) => streamAppend(delta),
353
383
  );
384
+ streamAppendRef.current?.flush();
354
385
  appendChatOutput('\n\n');
355
386
  return outcome;
356
387
  } catch (error) {
388
+ streamAppendRef.current?.flush();
357
389
  appendChatOutput('\n\n');
358
390
  return {
359
391
  compressed: false,
@@ -448,6 +480,7 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
448
480
  appendChatOutput('[plan 模式:只读探索,产出方案,PLAN READY 后可让我执行]\n');
449
481
  }
450
482
 
483
+ let endedNaturally = false;
451
484
  try {
452
485
  const provider =
453
486
  process.env.TRANSCODE_MOCK === '1'
@@ -495,11 +528,11 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
495
528
  toolSession: toolSessionRef.current,
496
529
  onEvent: event => {
497
530
  if (event.type === 'text') {
498
- appendChatOutput(lastWasTool ? `\n${event.text}` : event.text);
531
+ streamAppend(lastWasTool ? `\n${event.text}` : event.text);
499
532
  turnAssistantText += event.text;
500
533
  lastWasTool = false;
501
534
  } else if (event.type === 'max_turns_reached') {
502
- appendChatOutput(
535
+ streamAppend(
503
536
  `\n⚠ 已达轮次上限(${event.maxTurns}),任务未完成。输入"继续"接着做,或调大 TRANSCODE_MAX_TURNS。`,
504
537
  );
505
538
  lastWasTool = true;
@@ -517,10 +550,10 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
517
550
  );
518
551
  if (event.diff) {
519
552
  // Edits and writes stay visible immediately — rare and important.
520
- appendChatOutput(`\n⚙ ${title} ${marker}\n${renderDiff(event.diff)}`);
553
+ streamAppend(`\n⚙ ${title} ${marker}\n${renderDiff(event.diff)}`);
521
554
  } else if (event.name === 'todo_write' || event.name === 'dispatch_agent') {
522
555
  // Progress state and sub-agent reports: show immediately.
523
- appendChatOutput(`\n${event.output}`);
556
+ streamAppend(`\n${event.output}`);
524
557
  } else {
525
558
  bufferedLines.push(`\n⚙ ${title} ${marker}`);
526
559
  }
@@ -534,10 +567,10 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
534
567
  // Collapsed detail is kept (hiddenLines) so ctrl+o can reveal it.
535
568
  if (shouldCollapse(stats)) {
536
569
  const line = summaryLine(stats);
537
- if (line) appendChatOutput(`\n${line}`);
570
+ if (line) streamAppend(`\n${line}`);
538
571
  attachHiddenLines(bufferedLines);
539
572
  } else {
540
- for (const line of bufferedLines) appendChatOutput(line);
573
+ for (const line of bufferedLines) streamAppend(line);
541
574
  }
542
575
 
543
576
  messagesRef.current = result.messages.filter(
@@ -588,23 +621,35 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
588
621
  persist();
589
622
  })();
590
623
  }
591
- if (controller.signal.aborted) appendChatOutput('\n(cancelled)');
624
+ if (controller.signal.aborted) {
625
+ streamAppend('\n(cancelled)');
626
+ } else {
627
+ endedNaturally = true;
628
+ }
592
629
  } catch (error) {
593
630
  const message = error instanceof Error ? error.message : String(error);
594
- appendChatOutput(`\n⚠ ${message}`);
631
+ streamAppend(`\n⚠ ${message}`);
595
632
  if (/api.?key/i.test(message)) {
596
- appendChatOutput(`\n(run "models" to switch model + set key, or export its env var)`);
633
+ streamAppend(`\n(run "models" to switch model + set key, or export its env var)`);
597
634
  }
598
635
  } finally {
636
+ // Drain any coalesced tail before busy resets and the queue continues.
637
+ streamAppendRef.current?.flush();
599
638
  setBusyBoth(false);
600
639
  abortRef.current = undefined;
601
640
  setLiveTool(null);
602
641
  // The agent may have created/removed files; rebuild @-completion list.
603
642
  setFileList(null);
604
643
  dragFlush();
644
+ // Queue continuation: only a naturally-ended turn auto-submits the
645
+ // next queued prompt; cancel and error freeze it (Enter resumes).
646
+ const queued = applyQueue(endedNaturally ? { type: 'turnEnded' } : { type: 'frozen' });
647
+ if (endedNaturally && queued.submit) {
648
+ void handleSubmitRef.current(queued.submit);
649
+ }
605
650
  }
606
651
  },
607
- [ctx.modelId, addHistory, appendChatOutput, askInTerminal, setBusyBoth, dragFlush],
652
+ [ctx.modelId, addHistory, appendChatOutput, askInTerminal, setBusyBoth, dragFlush, applyQueue],
608
653
  );
609
654
 
610
655
  const enterModelSelect = useCallback(() => {
@@ -1027,6 +1072,8 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
1027
1072
  setHistoryIndex(-1);
1028
1073
  setSavedInput('');
1029
1074
  }, [exit, ctx, phase, handleApiKey, addHistory, enterModelSelect, commitInput, dragFlush, runChat]);
1075
+ // Late-bound so runChat's finally can auto-continue queued prompts.
1076
+ handleSubmitRef.current = handleSubmit;
1030
1077
 
1031
1078
  useInput((ch, key) => {
1032
1079
  if (process.env.TRANSCODE_DEBUG_KEYS === '1') {
@@ -1066,6 +1113,11 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
1066
1113
  addHistory({ input: '', output: 'Cancelled.' });
1067
1114
  return;
1068
1115
  }
1116
+ if (inputQueueRef.current.length > 0) {
1117
+ applyQueue({ type: 'clear' });
1118
+ addHistory({ input: '', output: '(队列已清空)' });
1119
+ return;
1120
+ }
1069
1121
  exit();
1070
1122
  return;
1071
1123
  }
@@ -1273,7 +1325,21 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
1273
1325
  }
1274
1326
 
1275
1327
  if (key.return) {
1276
- if (busyRef.current) return; // still generating; Esc cancels
1328
+ if (busyRef.current) {
1329
+ // Still generating: queue the prompt; it submits when the turn ends
1330
+ // naturally (cancel/error freeze it — idle empty-Enter resumes).
1331
+ const trimmed = inputRef.current.trim();
1332
+ if (trimmed) {
1333
+ applyQueue({ type: 'enqueue', text: trimmed });
1334
+ commitInput('');
1335
+ }
1336
+ return;
1337
+ }
1338
+ if (shouldResumeQueue(phase, inputRef.current, inputQueueRef.current.length)) {
1339
+ const next = applyQueue({ type: 'submitNext' });
1340
+ if (next.submit) void handleSubmit(next.submit);
1341
+ return;
1342
+ }
1277
1343
  handleSubmit(inputRef.current);
1278
1344
  return;
1279
1345
  }
@@ -1476,6 +1542,16 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
1476
1542
 
1477
1543
  {phase !== 'model_select' && phase !== 'session_select' && (
1478
1544
  <Box flexDirection="column">
1545
+ {inputQueue.length > 0 && (
1546
+ <Box flexDirection="column" marginLeft={2}>
1547
+ {inputQueue.map((text, i) => (
1548
+ <Text key={i} color="gray" dimColor>⏎ {text}</Text>
1549
+ ))}
1550
+ {!busy && phase === 'idle' && (
1551
+ <Text color="gray" dimColor>(queued {inputQueue.length} — Enter 续发,Esc 清空)</Text>
1552
+ )}
1553
+ </Box>
1554
+ )}
1479
1555
  <Text color="gray" dimColor>{historyRule(stdout?.columns ?? 80)}</Text>
1480
1556
  <Box>
1481
1557
  <Text color={phase === 'idle' ? 'green' : 'yellow'}>{promptLabel}</Text>
@@ -3,7 +3,7 @@ import { bannerLines } from './banner.js';
3
3
 
4
4
  describe('bannerLines', () => {
5
5
  test('renders a closed rectangle with aligned sides', () => {
6
- const lines = bannerLines('T R A N S C O D E · Multi-model Agent').split('\n');
6
+ const lines = bannerLines('T R A N S C O D E · Multi-Model Agent').split('\n');
7
7
  expect(lines.length).toBe(3);
8
8
  expect(lines[0]!.startsWith('┌')).toBe(true);
9
9
  expect(lines[0]!.endsWith('┐')).toBe(true);
@@ -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
+ }
@@ -0,0 +1,76 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { createStreamThrottler } from './stream-throttle.js';
3
+
4
+ interface Harness {
5
+ push: (chunk: string) => void;
6
+ flush: () => void;
7
+ appended: string[];
8
+ tick: () => void;
9
+ pendingTimer: () => boolean;
10
+ }
11
+
12
+ function harness(intervalMs = 32): Harness {
13
+ const appended: string[] = [];
14
+ let timer: (() => void) | null = null;
15
+ const throttler = createStreamThrottler((text) => appended.push(text), intervalMs, {
16
+ setTimer: (fn) => {
17
+ timer = fn;
18
+ return 0;
19
+ },
20
+ clearTimer: () => {
21
+ timer = null;
22
+ },
23
+ });
24
+ return {
25
+ ...throttler,
26
+ appended,
27
+ tick: () => {
28
+ const fn = timer;
29
+ timer = null;
30
+ fn?.();
31
+ },
32
+ pendingTimer: () => timer !== null,
33
+ };
34
+ }
35
+
36
+ describe('createStreamThrottler', () => {
37
+ test('窗口内多个 delta 合并为一次追加(内容按序拼接)', () => {
38
+ const h = harness();
39
+ h.push('He');
40
+ h.push('llo ');
41
+ h.push('world');
42
+ expect(h.appended).toEqual([]);
43
+ h.tick();
44
+ expect(h.appended).toEqual(['Hello world']);
45
+ });
46
+
47
+ test('定时器窗口外的新 delta 开新窗口', () => {
48
+ const h = harness();
49
+ h.push('a');
50
+ h.tick();
51
+ h.push('b');
52
+ h.push('c');
53
+ h.tick();
54
+ expect(h.appended).toEqual(['a', 'bc']);
55
+ });
56
+
57
+ test('flush 立即排水并取消挂起的定时器;空缓冲 flush 无操作', () => {
58
+ const h = harness();
59
+ h.push('x');
60
+ h.push('y');
61
+ h.flush();
62
+ expect(h.appended).toEqual(['xy']);
63
+ expect(h.pendingTimer()).toBe(false);
64
+ h.flush();
65
+ expect(h.appended).toEqual(['xy']);
66
+ });
67
+
68
+ test('flush 后再 push 正常开新窗口', () => {
69
+ const h = harness();
70
+ h.push('1');
71
+ h.flush();
72
+ h.push('2');
73
+ h.tick();
74
+ expect(h.appended).toEqual(['1', '2']);
75
+ });
76
+ });
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Frame-level throttle for streaming output. Stock Ink re-renders
3
+ * synchronously on every setState — per-delta appends (dozens per second,
4
+ * each rewriting the whole history frame) are what makes the screen
5
+ * flicker. Coalescing deltas into one append per interval window cuts the
6
+ * render rate to frame level without changing output content or order.
7
+ */
8
+
9
+ export interface ThrottleTimers {
10
+ setTimer: (fn: () => void, ms: number) => unknown;
11
+ clearTimer: (handle: unknown) => void;
12
+ }
13
+
14
+ const REAL_TIMERS: ThrottleTimers = {
15
+ setTimer: (fn, ms) => setTimeout(fn, ms),
16
+ clearTimer: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
17
+ };
18
+
19
+ export function createStreamThrottler(
20
+ append: (text: string) => void,
21
+ intervalMs = 32,
22
+ timers: ThrottleTimers = REAL_TIMERS,
23
+ ): { push: (chunk: string) => void; flush: () => void } {
24
+ let buffer = '';
25
+ let pending: unknown = null;
26
+
27
+ const drain = (): void => {
28
+ if (pending !== null) {
29
+ timers.clearTimer(pending);
30
+ pending = null;
31
+ }
32
+ if (!buffer) return;
33
+ const text = buffer;
34
+ buffer = '';
35
+ append(text);
36
+ };
37
+
38
+ return {
39
+ push(chunk) {
40
+ buffer += chunk;
41
+ if (pending === null) {
42
+ pending = timers.setTimer(drain, intervalMs);
43
+ }
44
+ },
45
+ flush: drain,
46
+ };
47
+ }
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';
2
+ export const VERSION = '0.10.4';