You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by wy...@apache.org on 2026/09/22 21:09:48 UTC
(maka) branch feat/runtime-host-rust updated: fix(chat): preserve steering boundaries and use platform send shortcuts
This is an automated email from the ASF dual-hosted git repository.
M4n5ter pushed a commit to branch feat/runtime-host-rust
in repository https://gitbox.apache.org/repos/asf/maka.git
The following commit(s) were added to refs/heads/feat/runtime-host-rust by this push:
new 5d41db7fb3 fix(chat): preserve steering boundaries and use platform send shortcuts
5d41db7fb3 is described below
commit 5d41db7fb333ba2e5072240f57b604b053deb714
Author: Wang <m4...@gmail.com>
AuthorDate: Wed Sep 23 05:09:42 2026 +0800
fix(chat): preserve steering boundaries and use platform send shortcuts
Generated-by: Codex
---
apps/desktop/e2e/side-chat-followups.spec.ts | 4 +-
apps/desktop/e2e/streaming-remount.spec.ts | 4 +-
apps/desktop/e2e/workhub-layout.spec.ts | 5 +-
.../main/__tests__/workhub-send-visibility.test.ts | 2 +-
apps/desktop/src/renderer/locales/shell-copy.ts | 9 +-
docs/desktop-message-queue.md | 3 +-
docs/rust-parity.md | 5 +-
docs/rust-parity.zh-CN.md | 5 +-
docs/side-conversation.md | 4 +-
.../src/__tests__/chat-turn-steering-order.test.ts | 280 ++++++++++++++++++++-
.../ui/src/__tests__/composer-shortcuts.test.tsx | 193 ++++++++++++++
.../ui/src/__tests__/live-turn-projection.test.ts | 8 +-
packages/ui/src/composer-message-queue.tsx | 3 +-
packages/ui/src/composer.tsx | 14 +-
packages/ui/src/conversation-copy.ts | 8 +-
packages/ui/src/live-turn-projection.ts | 231 +++++++++++------
packages/ui/src/materialize.ts | 83 +++---
packages/ui/src/transcript-projection.ts | 58 +++++
packages/workhub/src/locales/workhub-live-copy.ts | 6 +-
19 files changed, 774 insertions(+), 151 deletions(-)
diff --git a/apps/desktop/e2e/side-chat-followups.spec.ts b/apps/desktop/e2e/side-chat-followups.spec.ts
index e87dbcc598..a89356a522 100644
--- a/apps/desktop/e2e/side-chat-followups.spec.ts
+++ b/apps/desktop/e2e/side-chat-followups.spec.ts
@@ -131,7 +131,7 @@ test('Side Chat follow-ups survive queue actions, Host handoffs and reconnect',
await sideComposer.fill('steer the current response');
await awaitSendReady(companion);
- await sideComposer.press('Shift+Enter');
+ await sideComposer.press('ControlOrMeta+Enter');
await expect(companion).toContainText('Acknowledged steering: steer the current response');
await expect(queued.locator('.maka-composer-queue-text')).toHaveText([
'second follow-up', 'edited first follow-up',
@@ -163,7 +163,7 @@ test('Side Chat follow-ups survive queue actions, Host handoffs and reconnect',
await page.screenshot({ path: testInfo.outputPath('side-chat-queue.png'), fullPage: true });
await sideComposer.fill('release the held response');
await awaitSendReady(companion);
- await sideComposer.press('Shift+Enter');
+ await sideComposer.press('ControlOrMeta+Enter');
await expect(companion).toContainText('Acknowledged steering: release the held response');
await expect(companion).toContainText('Fake backend received: successor one', { timeout: 20_000 });
await expect(companion).toContainText('Fake backend received: successor two', { timeout: 20_000 });
diff --git a/apps/desktop/e2e/streaming-remount.spec.ts b/apps/desktop/e2e/streaming-remount.spec.ts
index 03cc72b8aa..bfdb7c510f 100644
--- a/apps/desktop/e2e/streaming-remount.spec.ts
+++ b/apps/desktop/e2e/streaming-remount.spec.ts
@@ -45,10 +45,10 @@ function sessionRow(sidebar: Locator, sessionId: string): Locator {
}
async function steerActiveTurn(composer: Locator, text: string): Promise<void> {
- // Mid-turn steering is Shift+Enter: the one Send stays Send, and the shifted
+ // Mid-turn steering is Cmd/Ctrl+Enter: Send stays Send, and the modified
// submit hands the draft to the active Turn once.
await composer.fill(text);
- await composer.press('Shift+Enter');
+ await composer.press('ControlOrMeta+Enter');
}
test('ordinary Enter queues on an already-running Session before observation recovers', async ({ window: page }) => {
diff --git a/apps/desktop/e2e/workhub-layout.spec.ts b/apps/desktop/e2e/workhub-layout.spec.ts
index b8264fd3e9..59aa4e7b49 100644
--- a/apps/desktop/e2e/workhub-layout.spec.ts
+++ b/apps/desktop/e2e/workhub-layout.spec.ts
@@ -456,7 +456,8 @@ test('WorkHub keeps the submitted prompt visible while its agent is still runnin
await expect(shortcuts).toHaveCount(1);
await shortcuts.hover();
const shortcutHint = workhub.getByRole('tooltip');
- await expect(shortcutHint).toHaveText('Shift+Enter:转向(Steering)\nEnter:下一轮(Follow-up)');
+ const steerModifier = process.platform === 'darwin' ? 'Cmd' : 'Ctrl';
+ await expect(shortcutHint).toHaveText(`${steerModifier}+Enter:转向(Steering)\nEnter:下一轮(Follow-up)\nShift+Enter:换行`);
await expect.poll(() => shortcutHint.evaluate((element) => {
const bounds = element.getBoundingClientRect();
return bounds.left >= 0 && bounds.right <= innerWidth && bounds.top >= 0 && bounds.bottom <= innerHeight;
@@ -468,7 +469,7 @@ test('WorkHub keeps the submitted prompt visible while its agent is still runnin
await expect(workhub.locator('.maka-bubble-streaming')).toContainText('Fake backend waiting');
await workhub.locator(COMPOSER_INPUT).fill('立即调整方向,保持当前任务');
await awaitSendReady(workhub);
- await workhub.locator(COMPOSER_INPUT).press('Shift+Enter');
+ await workhub.locator(COMPOSER_INPUT).press('ControlOrMeta+Enter');
await expect(workhub.locator('.maka-bubble-streaming')).toContainText('Acknowledged steering: 立即调整方向,保持当前任务');
const steered = workhub.locator('.maka-user-message').filter({ hasText: '立即调整方向,保持当前任务' });
await expect(steered).toHaveCount(1);
diff --git a/apps/desktop/src/main/__tests__/workhub-send-visibility.test.ts b/apps/desktop/src/main/__tests__/workhub-send-visibility.test.ts
index 0ba6c8eaef..8c88566475 100644
--- a/apps/desktop/src/main/__tests__/workhub-send-visibility.test.ts
+++ b/apps/desktop/src/main/__tests__/workhub-send-visibility.test.ts
@@ -383,7 +383,7 @@ test('uncertain steering retains its identity across Turn completion and rejecti
await act(async () => { assert.equal(await h.controller.send('change direction', [], 'steer'), false); });
const messageId = h.steers[1]![1];
await act(async () => { assert.equal(await h.controller.send('change direction', []), false); });
- assert.match(h.controller.error!, /Shift\+Enter/);
+ assert.match(h.controller.error!, /Cmd\/Ctrl\+Enter/);
assert.equal(h.steers.length, 2, 'Enter cannot silently replay uncertain steering or duplicate it');
for (const [text, attachments] of [
['edited direction', []],
diff --git a/apps/desktop/src/renderer/locales/shell-copy.ts b/apps/desktop/src/renderer/locales/shell-copy.ts
index 19e7971d98..023946cf19 100644
--- a/apps/desktop/src/renderer/locales/shell-copy.ts
+++ b/apps/desktop/src/renderer/locales/shell-copy.ts
@@ -1113,7 +1113,8 @@ const SHELL_COPY_BY_LOCALE = {
{
heading: 'Composer 输入',
rows: [
- { keys: ['Enter'], description: '发送消息' },
+ { keys: ['Enter'], description: '发送消息(运行中加入下一轮队列)' },
+ { keys: ['⌘', 'Enter'], description: '模型运行中调整方向(Steer)' },
{ keys: ['Shift', 'Enter'], description: '插入换行' },
{ keys: ['Alt', 'Enter'], description: '插入换行(备用)' },
],
@@ -1615,7 +1616,8 @@ const SHELL_COPY_BY_LOCALE = {
{
heading: 'Composer 輸入',
rows: [
- { keys: ['Enter'], description: '傳送訊息' },
+ { keys: ['Enter'], description: '傳送訊息(執行中加入下一輪佇列)' },
+ { keys: ['⌘', 'Enter'], description: '模型執行中調整方向(Steer)' },
{ keys: ['Shift', 'Enter'], description: '插入換行' },
{ keys: ['Alt', 'Enter'], description: '插入換行(備用)' },
],
@@ -2123,7 +2125,8 @@ const SHELL_COPY_BY_LOCALE = {
{
heading: 'Composer',
rows: [
- { keys: ['Enter'], description: 'Send the message' },
+ { keys: ['Enter'], description: 'Send the message (queue next turn while running)' },
+ { keys: ['⌘', 'Enter'], description: 'Steer the running turn' },
{ keys: ['Shift', 'Enter'], description: 'Insert a line break' },
{
keys: ['Alt', 'Enter'],
diff --git a/docs/desktop-message-queue.md b/docs/desktop-message-queue.md
index 2fc30d8722..025118b3a3 100644
--- a/docs/desktop-message-queue.md
+++ b/docs/desktop-message-queue.md
@@ -33,7 +33,8 @@ Runtime Host already owns the durable message semantics:
## Desktop Behavior
- While a turn is active, a composer submit queues a follow-up. There is no mode switch: Send is always Send.
-- `Shift+Enter` steers the draft into the active turn once.
+- `Cmd+Enter` on macOS (`Ctrl+Enter` on Windows/Linux) steers the draft into the active turn once; while idle it sends normally.
+- `Shift+Enter` and `Alt+Enter` always insert a line break, including during an active turn.
- Queued messages render in a pending plate above the composer card, in send order (first at the top). Per entry the plate offers:
- drag the hover grip to reorder the follow-up queue,
- promote (立即发送) to steer the entry into the active turn,
diff --git a/docs/rust-parity.md b/docs/rust-parity.md
index ff0aa6d21b..533a156ddb 100644
--- a/docs/rust-parity.md
+++ b/docs/rust-parity.md
@@ -87,9 +87,8 @@ implementations; wire adapters may retain existing client vocabulary.
| --- | --- | --- |
| Plan | State and durable receipts are complete: revision/abandonment, version and replan-source checks, frozen submissions, progress/interruption/resume/cancellation, exact retries and fixed-watermark history pages. Tools, Behavior, Remote/Desktop and live execution observation remain unwired. Non-Agent collaboration mode still fails admission. | **Plugin + Host.** The plugin owns workflow and records through public storage. Approving a plan grants no sandbox permissions; Host retains [...]
| Goal | Query/arm/control, continuation, termination, budget and recovery semantics. | **Plugin + Host.** Goal policy owns subsequent submissions; Host enforces admitted hard limits and records usage. Retiring the plugin must close future submission admission. |
-| Deep research | Research workflow, query/progress, results and recovery. | **Plugin.** Reuse Graph/Swarm, Web, bounded model calls and reliable submission. Do not build another generic orchestration engine. |
| Daily review / recap | Daily-review query/mutate, scheduled review and `session.recap.generate`. | **Plugin + Host.** Summarization/selection/output in plugins; reuse Scheduler and authorized history/model services. Host retains any canonical Session metadata commit. |
-| External agents | Setup start/query/cancel; execution adapters, configuration, auth, conversation identity, adapter-specific attachments/interactions/resume/fork; Command Code GO execution. | **Plugin + Host.** Implement concrete CLI/ACP adapters as Executor plugins over owned processes/HTTP. Generic Executor support is not a shipped adapter. Host owns authorization, cancellation and canonical external-event recording. |
+| External agents | Setup start/query/cancel; execution adapters, configuration, auth, conversation identity, adapter-specific attachments/interactions/resume/fork. | **Plugin + Host.** Implement concrete CLI/ACP adapters as Executor plugins over owned processes/HTTP. Generic Executor support is not a shipped adapter. Host owns authorization, cancellation and canonical external-event recording. |
| Usage / Pricing | Usage queries, revision-consistent screens/activity pages, pricing query/mutate and valuation. | **Plugin + Host.** Reports, price policy and rebuildable projections may be an Insights domain; Host records usage independently of plugin availability and provides consistent reads. Missing usage must not become zero. |
| Background health | BackgroundTaskHealth process and endpoint checks. | **Plugin + Host.** Health interpretation and Tool in a plugin; Host exposes authorized resource observations and bounded probes. A stored PID is not resource ownership. |
| Session lineage | Branch/revision create/abandon, regeneration. Ordinary resume/startup recovery exist. | **Host.** One transactional lineage and workspace authority; plugins may request changes through commands, not reproduce them in private storage. |
@@ -137,7 +136,7 @@ it does not reinterpret uncertain work using current policy or defaults.
the same scoped contracts as external plugins. Maintain Rust/JS parity as new consumers appear.
2. **External acceptance:** the JS workflow fixture exercises UI consent, durable background work,
exact receipts, disable/reactivation and revocation across Host restart.
-3. **Missing business domains:** complete Plan/Goal and research/review;
+3. **Missing business domains:** complete Plan/Goal and review;
finish external adapters and Insights/health. Reuse the domain boundaries rather than first
implementing new business logic in Host and moving it later.
4. **Remaining core parity:** complete Session lifecycle/lineage/transfer, policy, access/collaboration,
diff --git a/docs/rust-parity.zh-CN.md b/docs/rust-parity.zh-CN.md
index f4d6fae01b..f0675251a2 100644
--- a/docs/rust-parity.zh-CN.md
+++ b/docs/rust-parity.zh-CN.md
@@ -77,9 +77,8 @@ runtime 契约不能反向依赖插件实现,协议适配层可以保留现有
| --- | --- | --- |
| Plan | 状态与持久回执层完成:修订/放弃、版本与重规划来源检查、冻结提交、进度/中断/恢复/取消、精确重试及固定水位历史分页。工具、Behavior、Remote/Desktop 和实际执行观察尚未接入,非 Agent collaboration mode 仍拒绝准入。 | **插件 + Host。** 插件通过公共存储拥有流程与记录;审批计划不授予沙箱权限,Host 保留授权和 Turn 准入。没有 Host 回执只表示待准入,不能标记正在执行。 |
| Goal | 查询、arm、控制、续跑、终止、预算与恢复语义。 | **插件 + Host。** Goal 决定后续提交;Host 执行已准入的硬限制并记录用量。插件退休后不能继续提交。 |
-| Deep research | 研究流程、进度查询、结果与恢复。 | **插件。** 复用 Graph/Swarm、Web、有界模型调用及可靠提交,不新增通用编排引擎。 |
| Daily review/recap | daily-review 查询/修改、定时复盘、`session.recap.generate`。 | **插件 + Host。** 选择、总结及输出由插件负责,复用 Scheduler 和授权历史/模型服务;规范 Session 元数据的提交仍归 Host。 |
-| 外部 agent | setup start/query/cancel;具体执行适配、配置、鉴权、对话身份,以及附件/交互/resume/fork;Command Code GO 执行。 | **插件 + Host。** CLI/ACP 适配作为 Executor 插件,使用受管理进程/HTTP。已有 Executor 框架不等于已有具体 adapter。Host 负责授权、取消和外部事件落盘。 |
+| 外部 agent | setup start/query/cancel;具体执行适配、配置、鉴权、对话身份,以及附件/交互/resume/fork。 | **插件 + Host。** CLI/ACP 适配作为 Executor 插件,使用受管理进程/HTTP。已有 Executor 框架不等于已有具体 adapter。Host 负责授权、取消和外部事件落盘。 |
| Usage/Pricing | Usage 查询、一致版本视图及活动分页,Pricing 查询/修改和估价。 | **插件 + Host。** 报表、价格策略和可重建投影可归 Insights 领域;Host 不依赖插件存活来记录用量,并提供一致快照。缺失用量不能视为零。 |
| 后台健康 | BackgroundTaskHealth 的进程和端点检查。 | **插件 + Host。** 插件解释健康状态并提供工具;Host 提供授权资源观察和有界探测。保存 PID 不等于拥有进程。 |
| Session 谱系 | branch、revision create/abandon、regenerate;普通 resume 和启动恢复已有。 | **Host。** 谱系及工作区只有一个事务权威;插件可以请求命令,不能在私有存储中重做。 |
@@ -121,7 +120,7 @@ TS 的 LLM adapter 注册服务于插件模型调用,本身不等于主 Sessio
1. **公共 API 消费者已迁移:**Skills、默认助手、Scheduler、Graph、WorkHub 与外部插件使用同等受限契约;新增消费者时维持 Rust/JS 对等。
2. **外部验收:**JS workflow fixture 覆盖 UI 授权、持久后台工作、精确回执、停用/恢复以及跨 Host 重启的授权撤销。
-3. **缺失业务领域:**完成 Plan/Goal 和研究/复盘;完成外部 adapter、Insights/健康。复用领域边界,不先在 Host 写新业务再搬一次。
+3. **缺失业务领域:**完成 Plan/Goal 和复盘;完成外部 adapter、Insights/健康。复用领域边界,不先在 Host 写新业务再搬一次。
4. **其余核心等价:**完成 Session 生命周期/谱系/迁入迁出、policy、接入/协作、Peer Mesh、provider 和诊断。前面消费者所需的核心命令前置到对应阶段,核心工作不等待全部插件或商店。首批领域验证边界后评估 Code Mode/工具装配迁移,不将其作为功能等价的前提。
每个领域按“真实消费者及不变量 → 最小类型化 API 与消费者一起实现 → 验证生命周期和失败行为 → 删除旧 Host 业务路径”推进。
diff --git a/docs/side-conversation.md b/docs/side-conversation.md
index 71e0f426e4..e046f3ab2e 100644
--- a/docs/side-conversation.md
+++ b/docs/side-conversation.md
@@ -51,7 +51,7 @@ The generic side-conversation entry extends that foundation:
actions may use the inherited permission profile, and the permission can be
changed from the side Composer;
- while a side turn is running, Enter queues a follow-up for the next turn and
- Shift+Enter steers the active turn at its next model step; both appear
+ Cmd/Ctrl+Enter steers the active turn at its next model step; both appear
immediately, while Stop remains available;
- the side Composer shares `/` Skill discovery, `@` file references, files,
quotes, and draft ownership with the main Composer;
@@ -307,7 +307,7 @@ Maka now has the first usable slice of the same architecture:
quote queues;
- the same Composer shell as the main conversation, including a functional
attachment menu, Skill and file mentions, inherited permission menu,
- Enter-to-queue / Shift+Enter-to-Steer routing, and Host-backed queue controls;
+ Enter-to-queue / Cmd/Ctrl+Enter-to-Steer routing, and Host-backed queue controls;
- the same answer metadata surface for Copy, Info, and Regenerate, with Branch
withheld because it would navigate outside the temporary side-tab lifecycle;
- no content-area close action: Side Chat lifetime belongs exclusively to tab
diff --git a/packages/ui/src/__tests__/chat-turn-steering-order.test.ts b/packages/ui/src/__tests__/chat-turn-steering-order.test.ts
index f4a2f6e25c..6eb2d3ea59 100644
--- a/packages/ui/src/__tests__/chat-turn-steering-order.test.ts
+++ b/packages/ui/src/__tests__/chat-turn-steering-order.test.ts
@@ -24,13 +24,15 @@ import { renderToStaticMarkup } from 'react-dom/server';
import { parseHTML } from 'linkedom';
import { TurnView } from '../chat-turn.js';
import { LocaleProvider } from '../locale-context.js';
-import { materializeTurns, type TurnViewModel } from '../materialize.js';
+import { foldTimeline } from '../timeline-fold.js';
+import { materializeTurns, overlayLiveTurn, type TurnTimelineItem, type TurnViewModel } from '../materialize.js';
import { createTranscriptProjection } from '../transcript-projection.js';
import { ChatView } from '../chat-view.js';
import { Composer } from '../composer.js';
import { renderTranscriptMarkup } from './transcript-test-dom.js';
import { ChatSurfaceLayout } from '../chat-surface-layout.js';
-import { armLiveTurn } from '../live-turn-projection.js';
+import { armLiveTurn, type LiveTurnProjection } from '../live-turn-projection.js';
+import { reconcileLiveTurnBuffer } from '../live-turn-buffer.js';
import { applyLiveTurnEvent } from './live-turn-zh.js';
import type { SessionSummary, StoredMessage } from '@maka/core/session';
@@ -125,3 +127,277 @@ test('holds steering above the composer while old output continues, then renders
assert.deepEqual(timeline(), ['old answer continues', pending.text, 'reply to new instruction']);
assert.equal(text.split(pending.text).length - 1, 1);
});
+
+const timelineOrder = (timeline: readonly TurnTimelineItem[]): string[] =>
+ timeline.map((item) =>
+ item.kind === 'user'
+ ? `user:${item.message.text}`
+ : item.kind === 'tools'
+ ? `tools:${item.items.map((tool) => tool.toolUseId).join('+')}`
+ : `${item.kind}:${item.text}`,
+ );
+
+test('keeps post-steering work below the steering row even when it continues the same step', () => {
+ let live: LiveTurnProjection | undefined = applyLiveTurnEvent(armLiveTurn('turn-1'), {
+ type: 'thinking_delta', id: 'e1', turnId: 'turn-1', messageId: 'm1', ts: 1, text: 'pre-steer reasoning',
+ });
+ live = applyLiveTurnEvent(live, {
+ type: 'tool_start', id: 'e2', turnId: 'turn-1', stepId: 'm1', toolUseId: 'tool-1', toolName: 'Read', args: {}, ts: 2,
+ });
+ live = applyLiveTurnEvent(live, {
+ type: 'steering_message', id: 'steer-event', turnId: 'turn-1', messageId: 'steer-1', ts: 3, content: { text: 'steer' },
+ });
+ // A late result for a row that already exists updates that row in place; it
+ // does not claim the steering because its position was fixed at tool_start.
+ live = applyLiveTurnEvent(live, {
+ type: 'tool_result', id: 'e3', turnId: 'turn-1', toolUseId: 'tool-1', isError: false, ts: 4,
+ content: { kind: 'text', text: 'done' },
+ });
+ // While the steering awaits its boundary it must already render as one.
+ assert.deepEqual(timelineOrder(overlayLiveTurn([], live, 'en')[0]!.timeline), [
+ 'thinking:pre-steer reasoning', 'tools:tool-1', 'user:steer',
+ ]);
+ live = applyLiveTurnEvent(live, {
+ type: 'thinking_delta', id: 'e4', turnId: 'turn-1', messageId: 'm1', ts: 5, text: 'post-steer reasoning',
+ });
+ live = applyLiveTurnEvent(live, {
+ type: 'tool_start', id: 'e5', turnId: 'turn-1', stepId: 'm1', toolUseId: 'tool-2', toolName: 'Shell', args: {}, ts: 6,
+ });
+ live = applyLiveTurnEvent(live, {
+ type: 'text_delta', id: 'e6', turnId: 'turn-1', messageId: 'm1', ts: 7, text: 'answer continues',
+ });
+
+ const timeline = overlayLiveTurn([], live, 'en')[0]!.timeline;
+ assert.deepEqual(timelineOrder(timeline), [
+ 'thinking:pre-steer reasoning',
+ 'tools:tool-1',
+ 'user:steer',
+ 'thinking:post-steer reasoning',
+ 'tools:tool-2',
+ 'text:answer continues',
+ ]);
+ const folded = foldTimeline(timeline).entries.map((entry) =>
+ entry.kind === 'processing'
+ ? `fold:${entry.children.map((child) => child.kind).join('+')}`
+ : entry.kind === 'user'
+ ? `user:${entry.message.text}`
+ : `text:${entry.text}`,
+ );
+ assert.deepEqual(folded, [
+ 'fold:thinking+tools',
+ 'user:steer',
+ 'fold:thinking+tools',
+ 'text:answer continues',
+ ]);
+});
+
+test('anchors a persisted steering row ahead of live work the stream seeded after it', () => {
+ const settled = materializeTurns([
+ { type: 'user', id: 'original', turnId: 't1', ts: 1, text: 'request' },
+ { type: 'user', id: 'steer-1', turnId: 't1', ts: 3, text: 'steer', steeringEventId: 'steer-event' },
+ ], 'en');
+ const live = applyLiveTurnEvent(armLiveTurn('t1'), {
+ type: 'thinking_delta', id: 'e1', turnId: 't1', messageId: 'm2', ts: 5, text: 'in-flight after the steer',
+ });
+
+ const [overlaid] = overlayLiveTurn(settled, live, 'en');
+ assert.deepEqual(timelineOrder(overlaid!.timeline), [
+ 'user:steer',
+ 'thinking:in-flight after the steer',
+ ]);
+});
+
+test('keeps pre-steering content in place when its completion lands after the boundary', () => {
+ let live: LiveTurnProjection | undefined = applyLiveTurnEvent(armLiveTurn('turn-1'), {
+ type: 'text_delta', id: 'e1', turnId: 'turn-1', messageId: 'm1', ts: 1, text: 'answer before',
+ });
+ live = applyLiveTurnEvent(live, {
+ type: 'steering_message', id: 'steer-event', turnId: 'turn-1', messageId: 'steer-1', ts: 2, content: { text: 'steer' },
+ });
+ live = applyLiveTurnEvent(live, {
+ type: 'text_complete', id: 'e2', turnId: 'turn-1', messageId: 'm1', ts: 3, text: 'answer before',
+ });
+
+ assert.deepEqual(timelineOrder(overlayLiveTurn([], live, 'en')[0]!.timeline), [
+ 'text:answer before',
+ 'user:steer',
+ ]);
+});
+
+test('splits a completion across the boundary instead of duplicating the sealed portion', () => {
+ let live: LiveTurnProjection | undefined = applyLiveTurnEvent(armLiveTurn('turn-1'), {
+ type: 'thinking_delta', id: 'e1', turnId: 'turn-1', messageId: 'm1', ts: 1, text: 'pre-',
+ });
+ live = applyLiveTurnEvent(live, {
+ type: 'steering_message', id: 'steer-event', turnId: 'turn-1', messageId: 'steer-1', ts: 2, content: { text: 'steer' },
+ });
+ live = applyLiveTurnEvent(live, {
+ type: 'thinking_delta', id: 'e2', turnId: 'turn-1', messageId: 'm1', ts: 3, text: 'post',
+ });
+ live = applyLiveTurnEvent(live, {
+ type: 'thinking_complete', id: 'e3', turnId: 'turn-1', messageId: 'm1', ts: 4, text: 'pre-post',
+ });
+
+ assert.deepEqual(timelineOrder(overlayLiveTurn([], live, 'en')[0]!.timeline), [
+ 'thinking:pre-',
+ 'user:steer',
+ 'thinking:post',
+ ]);
+});
+
+test('keeps confirmed slice positions after releasing the live buffer, but never retains changed facts', () => {
+ const projection = createTranscriptProjection();
+ let live: LiveTurnProjection | undefined = applyLiveTurnEvent(armLiveTurn('turn'), {
+ type: 'text_delta', id: 'delta-1', turnId: 'turn', messageId: 'answer', ts: 1, text: 'before',
+ });
+ live = applyLiveTurnEvent(live, {
+ type: 'steering_message', id: 'steering', turnId: 'turn', messageId: 'instruction', ts: 2, content: { text: 'steer' },
+ });
+ live = applyLiveTurnEvent(live, {
+ type: 'text_delta', id: 'delta-2', turnId: 'turn', messageId: 'answer', ts: 3, text: 'after',
+ });
+ live = applyLiveTurnEvent(live, {
+ type: 'text_complete', id: 'text-end', turnId: 'turn', messageId: 'answer', ts: 4, text: 'beforeafter',
+ });
+ const expected = ['text:before', 'user:steer', 'text:after'];
+ assert.deepEqual(timelineOrder(projection.project({ locale: 'en', messages: [], liveTurns: [live] })[0]!.timeline), expected);
+ const messages: StoredMessage[] = [
+ { type: 'user', id: 'root', turnId: 'turn', ts: 0, text: 'question' },
+ { type: 'user', id: 'instruction', turnId: 'turn', ts: 2, text: 'steer', steeringEventId: 'steering' },
+ { type: 'assistant', id: 'answer', turnId: 'turn', ts: 4, text: 'beforeafter', modelId: 'test' },
+ { type: 'turn_state', id: 'end', turnId: 'turn', ts: 5, status: 'completed' },
+ ];
+ const buffer = reconcileLiveTurnBuffer([live], messages);
+ assert.equal(buffer, undefined);
+ const settled = projection.project({ locale: 'en', messages, liveTurns: buffer });
+ assert.deepEqual(timelineOrder(settled[0]!.timeline), expected);
+ assert.ok(settled[0]!.timeline.every((item) => !('live' in item) || !item.live));
+ assert.equal(projection.project({ locale: 'en', messages: structuredClone(messages) }), settled);
+ const corrected = structuredClone(messages);
+ (corrected[2] as Extract<StoredMessage, { type: 'assistant' }>).text = 'corrected';
+ assert.deepEqual(timelineOrder(projection.project({ locale: 'en', messages: corrected })[0]!.timeline), ['user:steer', 'text:corrected']);
+ assert.deepEqual(projection.project({ sessionId: 'another', locale: 'en', messages: [] }), []);
+});
+
+test('steering does not reset whole-stream text processing', () => {
+ for (const kind of ['text', 'thinking'] as const) {
+ let live: LiveTurnProjection | undefined = applyLiveTurnEvent(armLiveTurn('turn'), {
+ type: `${kind}_delta`, id: 'prefix', turnId: 'turn', messageId: 'm', ts: 1, text: 'Authorization: Bearer secret-prefix',
+ });
+ live = applyLiveTurnEvent(live, {
+ type: 'steering_message', id: 'steering', turnId: 'turn', messageId: 'instruction', ts: 2, content: { text: 'steer' },
+ });
+ live = applyLiveTurnEvent(live, {
+ type: kind === 'text' ? 'thinking_delta' : 'text_delta', id: 'interleaved', turnId: 'turn', messageId: 'm', ts: 3, text: 'other content',
+ });
+ live = applyLiveTurnEvent(live, {
+ type: `${kind}_delta`, id: 'suffix', turnId: 'turn', messageId: 'm', ts: 4, text: '-SECRET_SUFFIX tail',
+ });
+ const displayed = () => live!.steps.map((step) => step[kind]?.text ?? '').join('');
+ assert.equal(displayed(), 'Authorization: Bearer <redacted> tail');
+ live = applyLiveTurnEvent(live, {
+ type: `${kind}_complete`, id: 'end', turnId: 'turn', messageId: 'm', ts: 5, text: 'Authorization: Bearer secret-prefix-SECRET_SUFFIX tail',
+ });
+ assert.equal(displayed(), 'Authorization: Bearer <redacted> tail');
+ }
+});
+
+test('lands a divergent completion whole instead of slicing at the delta offset', () => {
+ // thinking_complete may carry a provider summary that replaces the streamed
+ // deltas outright — the accumulated delta length is not a safe cut point.
+ let live: LiveTurnProjection | undefined = applyLiveTurnEvent(armLiveTurn('turn-1'), {
+ type: 'thinking_delta', id: 'e1', turnId: 'turn-1', messageId: 'm1', ts: 1, text: 'AAAA',
+ });
+ live = applyLiveTurnEvent(live, {
+ type: 'steering_message', id: 's1', turnId: 'turn-1', messageId: 'steer-1', ts: 2, content: { text: 'steer' },
+ });
+ live = applyLiveTurnEvent(live, {
+ type: 'thinking_delta', id: 'e2', turnId: 'turn-1', messageId: 'm1', ts: 3, text: 'BBBB',
+ });
+ live = applyLiveTurnEvent(live, {
+ type: 'thinking_complete', id: 'e3', turnId: 'turn-1', messageId: 'm1', ts: 4, text: 'Short summary.',
+ });
+
+ assert.deepEqual(timelineOrder(overlayLiveTurn([], live, 'en')[0]!.timeline), [
+ 'thinking:AAAA',
+ 'user:steer',
+ 'thinking:Short summary.',
+ ]);
+});
+
+test('lands a completion shorter than the delta offset whole', () => {
+ let live: LiveTurnProjection | undefined = applyLiveTurnEvent(armLiveTurn('turn-1'), {
+ type: 'thinking_delta', id: 'e1', turnId: 'turn-1', messageId: 'm1', ts: 1, text: 'AAAA',
+ });
+ live = applyLiveTurnEvent(live, {
+ type: 'steering_message', id: 's1', turnId: 'turn-1', messageId: 'steer-1', ts: 2, content: { text: 'steer' },
+ });
+ live = applyLiveTurnEvent(live, {
+ type: 'thinking_delta', id: 'e2', turnId: 'turn-1', messageId: 'm1', ts: 3, text: 'BBBB',
+ });
+ live = applyLiveTurnEvent(live, {
+ type: 'thinking_complete', id: 'e3', turnId: 'turn-1', messageId: 'm1', ts: 4, text: 'ABC',
+ });
+
+ assert.deepEqual(timelineOrder(overlayLiveTurn([], live, 'en')[0]!.timeline), [
+ 'thinking:AAAA',
+ 'user:steer',
+ 'thinking:ABC',
+ ]);
+});
+
+test('keeps consecutive steering rows in arrival order', () => {
+ let live: LiveTurnProjection | undefined = applyLiveTurnEvent(armLiveTurn('turn-1'), {
+ type: 'text_delta', id: 'e1', turnId: 'turn-1', messageId: 'm1', ts: 1, text: 'before',
+ });
+ live = applyLiveTurnEvent(live, {
+ type: 'steering_message', id: 's1', turnId: 'turn-1', messageId: 'steer-1', ts: 2, content: { text: 'one' },
+ });
+ live = applyLiveTurnEvent(live, {
+ type: 'steering_message', id: 's2', turnId: 'turn-1', messageId: 'steer-2', ts: 3, content: { text: 'two' },
+ });
+ live = applyLiveTurnEvent(live, {
+ type: 'text_delta', id: 'e2', turnId: 'turn-1', messageId: 'm2', ts: 4, text: 'after',
+ });
+
+ assert.deepEqual(timelineOrder(overlayLiveTurn([], live, 'en')[0]!.timeline), [
+ 'text:before',
+ 'user:one',
+ 'user:two',
+ 'text:after',
+ ]);
+});
+
+test('renders a repeated steering event once', () => {
+ let live: LiveTurnProjection | undefined = applyLiveTurnEvent(armLiveTurn('turn-1'), {
+ type: 'steering_message', id: 's1', turnId: 'turn-1', messageId: 'steer-1', ts: 1, content: { text: 'steer' },
+ });
+ live = applyLiveTurnEvent(live, {
+ type: 'steering_message', id: 's1-echo', turnId: 'turn-1', messageId: 'steer-1', ts: 2, content: { text: 'steer' },
+ });
+
+ assert.deepEqual(timelineOrder(overlayLiveTurn([], live, 'en')[0]!.timeline), ['user:steer']);
+});
+
+test('trails a settled steering that carries no ts behind live work', () => {
+ const turn: TurnViewModel = {
+ turnId: 't1',
+ status: 'running',
+ tools: [],
+ notes: [],
+ startedAt: 1,
+ timeline: [
+ { kind: 'text', text: 'persisted answer', messageId: 'm1', ts: 1 },
+ { kind: 'user', message: { id: 'steer-1', role: 'user', text: 'steer' }, messageId: 'steer-1', steeringEventId: 'steer-event' },
+ ],
+ };
+ const live = applyLiveTurnEvent(armLiveTurn('t1'), {
+ type: 'text_delta', id: 'e1', turnId: 't1', messageId: 'm2', ts: 5, text: 'in-flight',
+ });
+
+ assert.deepEqual(timelineOrder(overlayLiveTurn([turn], live, 'en')[0]!.timeline), [
+ 'text:persisted answer',
+ 'text:in-flight',
+ 'user:steer',
+ ]);
+});
diff --git a/packages/ui/src/__tests__/composer-shortcuts.test.tsx b/packages/ui/src/__tests__/composer-shortcuts.test.tsx
new file mode 100644
index 0000000000..9008379eb8
--- /dev/null
+++ b/packages/ui/src/__tests__/composer-shortcuts.test.tsx
@@ -0,0 +1,193 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import assert from 'node:assert/strict';
+import { afterEach, test } from 'node:test';
+import { act, createRef } from 'react';
+import { createRoot } from 'react-dom/client';
+import { renderToStaticMarkup } from 'react-dom/server';
+import { parseHTML } from 'linkedom';
+import { Composer, type ComposerHandle, type ComposerSendMetadata } from '../composer.js';
+import { LocaleProvider } from '../locale-context.js';
+import { getConversationCopy } from '../conversation-copy.js';
+import { PlatformShortcutText } from '../platform-shortcut-text.js';
+
+const originalNavigator = Object.getOwnPropertyDescriptor(globalThis, 'navigator');
+const originalGlobals = {
+ document: globalThis.document,
+ window: globalThis.window,
+ KeyboardEvent: globalThis.KeyboardEvent,
+ Node: globalThis.Node,
+ HTMLElement: globalThis.HTMLElement,
+ IS_REACT_ACT_ENVIRONMENT: (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT,
+};
+let cleanup: (() => Promise<void>) | undefined;
+
+afterEach(async () => {
+ await cleanup?.();
+ cleanup = undefined;
+ Object.assign(globalThis, originalGlobals);
+ if (originalNavigator) Object.defineProperty(globalThis, 'navigator', originalNavigator);
+ else Reflect.deleteProperty(globalThis, 'navigator');
+});
+
+async function harness(platform = 'MacIntel', streaming = true, overrides: Partial<Parameters<typeof Composer>[0]> = {}) {
+ const { document, window } = parseHTML('<div id="root"></div>');
+ window.getComputedStyle = () => ({ direction: 'ltr', writingMode: 'horizontal-tb', getPropertyValue: () => '' }) as unknown as CSSStyleDeclaration;
+ window.getSelection = () => null;
+ document.getSelection = () => null;
+ const setAttribute = window.Element.prototype.setAttribute;
+ window.Element.prototype.setAttribute = function normalized(name: string, value: string) {
+ return setAttribute.call(this, name === 'contentEditable' ? 'contenteditable' : name, value);
+ };
+ class KeyEvent extends window.Event {
+ constructor(type: string, init: KeyboardEventInit = {}) {
+ super(type, init);
+ Object.assign(this, { key: 'Enter', code: 'Enter', shiftKey: false, altKey: false, ctrlKey: false, metaKey: false, isComposing: false }, init);
+ }
+ }
+ const lineBreaks: string[] = [];
+ document.execCommand = (command: string) => { lineBreaks.push(command); return true; };
+ Object.defineProperty(globalThis, 'navigator', { configurable: true, value: { platform } });
+ Object.assign(globalThis, { document, window, KeyboardEvent: KeyEvent, Node: window.Node, HTMLElement: window.HTMLElement, IS_REACT_ACT_ENVIRONMENT: true });
+ const root = createRoot(document.querySelector('#root')!);
+ const ref = createRef<ComposerHandle>();
+ const sends: { text: string; metadata?: ComposerSendMetadata }[] = [];
+ cleanup = async () => {
+ await act(() => root.unmount());
+ window.Element.prototype.setAttribute = setAttribute;
+ };
+ await act(() => root.render(
+ <LocaleProvider locale="en">
+ <Composer ref={ref} streaming={streaming} onSend={(text, metadata) => { sends.push({ text, metadata }); }} onStop={() => undefined} {...overrides} />
+ </LocaleProvider>,
+ ));
+ const editor = document.querySelector<HTMLElement>('[contenteditable="true"]')!;
+ assert.ok(editor);
+ return {
+ sends, lineBreaks, editor, ref,
+ async draft(text = 'adjust the current task') { await act(() => ref.current!.setText(text)); },
+ async press(init: KeyboardEventInit = {}) {
+ const event = new KeyEvent('keydown', { bubbles: true, cancelable: true, ...init });
+ await act(async () => { editor.dispatchEvent(event); await Promise.resolve(); });
+ return event;
+ },
+ async submit() {
+ await act(async () => {
+ document.querySelector('form')!.dispatchEvent(new window.Event('submit', { bubbles: true, cancelable: true }));
+ await Promise.resolve();
+ });
+ },
+ };
+}
+
+for (const [platform, modifier, otherModifier] of [
+ ['MacIntel', 'metaKey', 'ctrlKey'],
+ ['Win32', 'ctrlKey', 'metaKey'],
+ ['Linux x86_64', 'ctrlKey', 'metaKey'],
+] as const) {
+ for (const streaming of [false, true]) {
+ test(`${platform}: primary Enter ${streaming ? 'steers once without changing later sends' : 'sends normally when idle'}`, async () => {
+ const h = await harness(platform, streaming);
+ await h.draft();
+ await h.press({ [modifier]: true });
+ assert.deepEqual(h.sends, [{ text: 'adjust the current task', metadata: streaming ? { followUpMode: 'steer' } : undefined }]);
+ assert.equal(h.ref.current!.getText(), '');
+ await h.draft('next task');
+ await h.press();
+ assert.deepEqual(h.sends[1], { text: 'next task', metadata: undefined });
+ await h.draft('button send');
+ await h.submit();
+ assert.deepEqual(h.sends[2], { text: 'button send', metadata: undefined });
+ });
+ for (const newlineModifier of ['shiftKey', 'altKey'] as const) {
+ test(`${platform}: ${newlineModifier}+Enter inserts a line break while ${streaming ? 'running' : 'idle'}, including with the primary modifier`, async () => {
+ const h = await harness(platform, streaming);
+ await h.draft();
+ await h.press({ [newlineModifier]: true });
+ await h.press({ [newlineModifier]: true, [modifier]: true });
+ assert.deepEqual(h.sends, []);
+ assert.deepEqual(h.lineBreaks, ['insertLineBreak', 'insertLineBreak']);
+ assert.equal(h.ref.current!.getText(), 'adjust the current task');
+ });
+ }
+ }
+ test(`${platform}: the other platform modifier does not select steering`, async () => {
+ const h = await harness(platform);
+ await h.draft();
+ await h.press({ [otherModifier]: true });
+ assert.deepEqual(h.sends, [{ text: 'adjust the current task', metadata: undefined }]);
+ });
+ test(`${platform}: composing and empty drafts never send through the steering shortcut`, async () => {
+ const h = await harness(platform);
+ await h.press({ [modifier]: true });
+ assert.deepEqual(h.sends, []);
+ await h.draft();
+ await h.press({ [modifier]: true, isComposing: true });
+ assert.deepEqual(h.sends, []);
+ assert.equal(h.ref.current!.getText(), 'adjust the current task');
+ });
+ test(`${platform}: an open mention menu retains Enter before steering`, async () => {
+ const h = await harness(platform);
+ await h.draft();
+ h.editor.setAttribute('aria-expanded', 'true');
+ await h.press({ [modifier]: true });
+ assert.deepEqual(h.sends, []);
+ assert.equal(h.ref.current!.getText(), 'adjust the current task');
+ });
+}
+
+test('steering retains a refused draft', async () => {
+ const h = await harness('MacIntel', true, { onSend: () => false });
+ await h.draft();
+ await h.press({ metaKey: true });
+ assert.equal(h.ref.current!.getText(), 'adjust the current task');
+});
+
+test('a blocked composer cannot steer', async () => {
+ const h = await harness('MacIntel', true, { sendBlocked: true });
+ await h.draft();
+ await h.press({ metaKey: true });
+ assert.deepEqual(h.sends, []);
+ assert.equal(h.ref.current!.getText(), 'adjust the current task');
+});
+
+test('steering supports staged context and coalesces repeated keys while admission is pending', async () => {
+ let finish!: (accepted: boolean) => void;
+ const calls: (ComposerSendMetadata | undefined)[] = [];
+ const h = await harness('MacIntel', true, {
+ pendingQuotes: [{ text: 'quoted context', sourceTurnId: 'turn-1' }],
+ onSend: (_text, metadata) => { calls.push(metadata); return new Promise<boolean>((resolve) => { finish = resolve; }); },
+ });
+ await h.press({ metaKey: true });
+ await h.press({ metaKey: true });
+ assert.deepEqual(calls, [{ followUpMode: 'steer' }]);
+ await act(async () => finish(true));
+});
+
+for (const locale of ['en', 'zh-CN', 'zh-TW'] as const) {
+ for (const [platform, modifier] of [['MacIntel', 'Cmd'], ['Win32', 'Ctrl']] as const) {
+ test(`${locale}: queue help renders ${modifier}+Enter on ${platform}`, () => {
+ Object.defineProperty(globalThis, 'navigator', { configurable: true, value: { platform } });
+ const markup = renderToStaticMarkup(<PlatformShortcutText {...getConversationCopy(locale).composer.queueShortcuts} />);
+ assert.ok(markup.startsWith(`${modifier}+Enter`));
+ assert.ok(markup.includes('Shift+Enter'));
+ });
+ }
+}
diff --git a/packages/ui/src/__tests__/live-turn-projection.test.ts b/packages/ui/src/__tests__/live-turn-projection.test.ts
index 39b37fc1b0..dd971a1bc4 100644
--- a/packages/ui/src/__tests__/live-turn-projection.test.ts
+++ b/packages/ui/src/__tests__/live-turn-projection.test.ts
@@ -282,6 +282,7 @@ describe('applyLiveTurnEvent', () => {
text: '完整思考',
truncated: false,
complete: true,
+ sourceEndOffset: 4,
});
});
@@ -710,13 +711,14 @@ describe('reconcileTerminalLiveTurn', () => {
it('keeps terminal live steering until the terminal transcript catches up', () => {
const message = { id: 'steer-1', content: { text: 'change direction' }, ts: 2 };
+ const boundary = { stepId: 'steering:steer-1', tools: [], steering: message };
const withSteering: LiveTurnProjection = {
...toolOnly,
- steps: [{ ...toolOnly.steps[0]!, leadingSteering: [message] }],
+ steps: [...toolOnly.steps, boundary],
};
assert.equal(reconcileTerminalLiveTurn(withSteering, []), withSteering);
- const steeringOnly = { ...withSteering, steps: [] };
+ const steeringOnly = { ...toolOnly, steps: [boundary] };
assert.equal(reconcileTerminalLiveTurn(steeringOnly, []), steeringOnly);
assert.deepEqual(reconcileTerminalLiveTurn(withSteering, [{
type: 'turn_state', id: 'state-1', turnId: 'turn-1', ts: 3,
@@ -735,7 +737,7 @@ describe('reconcileTerminalLiveTurn', () => {
});
assert.equal(aborted?.terminal, true);
- assert.deepEqual(aborted?.pendingSteering, [message]);
+ assert.deepEqual(aborted?.steps[0]?.steering, message);
});
it('retains interrupted live output until a persisted result covers it', () => {
diff --git a/packages/ui/src/composer-message-queue.tsx b/packages/ui/src/composer-message-queue.tsx
index 08f0db5df8..123017f537 100644
--- a/packages/ui/src/composer-message-queue.tsx
+++ b/packages/ui/src/composer-message-queue.tsx
@@ -25,6 +25,7 @@ import { List, ListItem } from '@astryxdesign/core/List';
import type { ConversationCopy } from './conversation-copy.js';
import { Check, GripVertical, HelpCircle, ICON_SIZE, Trash2, X } from './icons.js';
import { useMountedRef } from './use-mounted-ref.js';
+import { PlatformShortcutText } from './platform-shortcut-text.js';
type ComposerQueueEntry = Omit<MessageQueueEntryProjection, 'state'> & {
state: MessageQueueEntryProjection['state'] | 'local';
@@ -150,7 +151,7 @@ export const ComposerMessageQueue = memo(function ComposerMessageQueue(
{groups.map((group, index) => <section key={group.placement} data-queue-placement={group.placement}>
<div className="maka-composer-queue-status">
<span>{group.placement === 'current_turn' ? copy.steeringPending : copy.followupPending}</span>
- {index === 0 && <Tooltip alignment="end" content={<span style={{ whiteSpace: 'pre-line' }}>{copy.queueShortcuts}</span>}>
+ {index === 0 && <Tooltip alignment="end" content={<span style={{ whiteSpace: 'pre-line' }}><PlatformShortcutText {...copy.queueShortcuts} /></span>}>
<IconButton variant="ghost" size="sm" type="button" label={copy.queueShortcutsLabel}
icon={<HelpCircle size={ICON_SIZE.control} aria-hidden="true" />} />
</Tooltip>}
diff --git a/packages/ui/src/composer.tsx b/packages/ui/src/composer.tsx
index 021b57e994..c0c9c98001 100644
--- a/packages/ui/src/composer.tsx
+++ b/packages/ui/src/composer.tsx
@@ -34,6 +34,7 @@ import {
} from 'react';
import type { LucideIcon } from './icons.js';
import { useMountedRef } from './use-mounted-ref.js';
+import { isAppleShortcutPlatform } from './utils.js';
import {
ICON_SIZE,
ArrowUp,
@@ -1342,7 +1343,7 @@ export const Composer = forwardRef<
function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
// Mid-turn the host queues the draft as a follow-up by default; only
- // Shift+Enter (see onInputKeyDown) steers it into the active Turn.
+ // Cmd/Ctrl+Enter (see onInputKeyDown) steers it into the active Turn.
void sendCurrent();
}
@@ -1405,15 +1406,18 @@ export const Composer = forwardRef<
if (handleArrowKey(event)) return;
}
if (event.key !== 'Enter') return;
- // Alt+Enter always inserts a line break. During a running turn, Shift+Enter
- // steers this one draft into the active Turn; plain Enter queues it.
- if (event.altKey || (event.shiftKey && !props.streaming)) {
+ // Shift+Enter and Alt+Enter always insert a line break. The platform
+ // primary modifier steers this one draft mid-turn; plain Enter queues it.
+ if (event.altKey || event.shiftKey) {
event.preventDefault();
document.execCommand('insertLineBreak');
return;
}
event.preventDefault();
- void sendCurrent(props.streaming && event.shiftKey ? 'steer' : undefined);
+ const primaryModifier = isAppleShortcutPlatform(navigator.platform)
+ ? event.metaKey
+ : event.ctrlKey;
+ void sendCurrent(props.streaming && primaryModifier ? 'steer' : undefined);
}
function onInputChange(next: string) {
diff --git a/packages/ui/src/conversation-copy.ts b/packages/ui/src/conversation-copy.ts
index 26ad0136a8..3d57e00e62 100644
--- a/packages/ui/src/conversation-copy.ts
+++ b/packages/ui/src/conversation-copy.ts
@@ -98,7 +98,7 @@ export interface ConversationCopy {
steeringPending: string;
followupPending: string;
queueShortcutsLabel: string;
- queueShortcuts: string;
+ queueShortcuts: { apple: string; other: string };
promoteQueuedEntry: string;
editQueuedEntry: string;
saveQueuedEntry: string;
@@ -436,7 +436,7 @@ const CONVERSATION_COPY = {
steeringPending: '调整方向 · 等待整批生效',
followupPending: '下一轮 · 每轮一条',
queueShortcutsLabel: '发送快捷键',
- queueShortcuts: 'Shift+Enter:转向(Steering)\nEnter:下一轮(Follow-up)',
+ queueShortcuts: { apple: 'Cmd+Enter:转向(Steering)\nEnter:下一轮(Follow-up)\nShift+Enter:换行', other: 'Ctrl+Enter:转向(Steering)\nEnter:下一轮(Follow-up)\nShift+Enter:换行' },
promoteQueuedEntry: '调整方向', editQueuedEntry: '编辑', saveQueuedEntry: '保存', cancelQueuedEntryEdit: '取消编辑', deleteQueuedEntry: '删除', reorderQueuedEntry: '拖动排序',
stopLabel: '停止', stopping: '停止中…',
streaming: 'Maka 正在回答…', processing: 'Maka 正在处理…', continuing: 'Maka 继续中…',
@@ -568,7 +568,7 @@ const CONVERSATION_COPY = {
steeringPending: '調整方向 · 等待整批生效',
followupPending: '下一輪 · 每輪一條',
queueShortcutsLabel: '傳送快速鍵',
- queueShortcuts: 'Shift+Enter:轉向(Steering)\nEnter:下一輪(Follow-up)',
+ queueShortcuts: { apple: 'Cmd+Enter:轉向(Steering)\nEnter:下一輪(Follow-up)\nShift+Enter:換行', other: 'Ctrl+Enter:轉向(Steering)\nEnter:下一輪(Follow-up)\nShift+Enter:換行' },
promoteQueuedEntry: '調整方向', editQueuedEntry: '編輯', saveQueuedEntry: '儲存', cancelQueuedEntryEdit: '取消編輯', deleteQueuedEntry: '刪除', reorderQueuedEntry: '拖動排序',
stopLabel: '停止', stopping: '停止中…',
streaming: 'Maka 正在回答…', processing: 'Maka 正在處理…', continuing: 'Maka 繼續中…',
@@ -700,7 +700,7 @@ const CONVERSATION_COPY = {
steeringPending: 'Steering · Applied together',
followupPending: 'Follow-up · One per turn',
queueShortcutsLabel: 'Send shortcuts',
- queueShortcuts: 'Shift+Enter: Steering\nEnter: Follow-up',
+ queueShortcuts: { apple: 'Cmd+Enter: Steering\nEnter: Follow-up\nShift+Enter: New line', other: 'Ctrl+Enter: Steering\nEnter: Follow-up\nShift+Enter: New line' },
promoteQueuedEntry: 'Steer', editQueuedEntry: 'Edit', saveQueuedEntry: 'Save', cancelQueuedEntryEdit: 'Cancel editing', deleteQueuedEntry: 'Delete', reorderQueuedEntry: 'Drag to reorder',
stopLabel: 'Stop', stopping: 'Stopping…',
streaming: 'Maka is responding…', processing: 'Maka is working…', continuing: 'Maka is continuing…',
diff --git a/packages/ui/src/live-turn-projection.ts b/packages/ui/src/live-turn-projection.ts
index fbf1b1ef08..cfbe42262b 100644
--- a/packages/ui/src/live-turn-projection.ts
+++ b/packages/ui/src/live-turn-projection.ts
@@ -63,9 +63,22 @@ export interface LiveThinkingProjection {
export interface LiveTurnStepProjection {
stepId: string;
+ /** Event ts of the first word that opened this step or slice. */
+ startedAt?: number;
contentOrder?: LiveTurnStepContentKind[];
- /** Steering drained immediately before this provider step began. */
- leadingSteering?: LiveSteeringProjection[];
+ /**
+ * A steering boundary slice: the steering row is emitted at this position
+ * and the slice holds no content. Content events never resolve to it
+ * (`steering:`-prefixed stepIds collide with no real stepId).
+ */
+ steering?: LiveSteeringProjection;
+ /**
+ * A steering boundary can split a step mid-flight; the continuation slice
+ * keeps the same durable stepId. Replayed deltas trim against the earlier
+ * slice's source length through these baselines instead of re-appending it.
+ */
+ continuedThinkingEndOffset?: number;
+ continuedTextEndOffset?: number;
thinking?: LiveThinkingProjection;
text?: LiveTextProjection;
tools: ToolActivityItem[];
@@ -103,8 +116,6 @@ export interface LiveTurnProjection {
/** Event ts of the first authority word about this Turn, so a Turn the
* transcript has not reached yet still has a stable start. */
startedAt?: number;
- /** Steering acknowledged after the current content and awaiting its next provider step. */
- pendingSteering?: LiveSteeringProjection[];
/**
* Set by `armLiveTurn` and cleared by the first word the authority says about
* this turn (any event carrying the same turnId).
@@ -219,14 +230,21 @@ function projectLiveTurnEvent(
if (liveSteeringMessages(prior).some((message) => message.id === event.messageId)) {
return confirmed(prior);
}
+ // A steering's position is fixed by stream order: it becomes a boundary
+ // slice immediately instead of parking until a later event claims it.
return {
...confirmed(prior),
- pendingSteering: [
- ...(prior.pendingSteering ?? []),
+ steps: [
+ ...prior.steps,
{
- id: event.messageId,
- content: structuredClone(event.content),
- ts: event.ts,
+ stepId: `steering:${event.messageId}`,
+ startedAt: event.ts,
+ tools: [],
+ steering: {
+ id: event.messageId,
+ content: structuredClone(event.content),
+ ts: event.ts,
+ },
},
],
};
@@ -296,33 +314,53 @@ function projectLiveTurnEvent(
: event.type === 'tool_start'
? event.stepId ?? existingToolStep?.stepId ?? `tool:${event.toolUseId}`
: existingToolStep?.stepId ?? `tool:${event.toolUseId}`;
- const stepIndex = prior.steps.findIndex((step) => step.stepId === stepId);
- const isNewStep = stepIndex < 0;
- const claimsPendingSteering = isNewStep
- && existingToolStep === undefined
- && (prior.pendingSteering?.length ?? 0) > 0;
- const step: LiveTurnStepProjection = isNewStep
+ // A steering boundary freezes the positions before it: same-stepId deltas
+ // arriving after one continue the step in a fresh slice, so a stepId can
+ // repeat across the array. Completions and events for an existing tool row
+ // are updates to a row whose position is already fixed — they resolve to
+ // the row's last slice wherever it sits, on either side of a boundary.
+ const boundaryIndex = prior.steps.findLastIndex((candidate) => candidate.steering !== undefined);
+ const sameStepIndex = prior.steps.findLastIndex((candidate) => candidate.stepId === stepId);
+ const stepIndex = existingToolStep === undefined
+ ? event.type === 'thinking_complete' || event.type === 'text_complete'
+ ? sameStepIndex
+ : sameStepIndex > boundaryIndex ? sameStepIndex : -1
+ : event.type !== 'tool_start'
+ || event.stepId === undefined
+ || event.stepId === existingToolStep.stepId
+ ? prior.steps.indexOf(existingToolStep)
+ : sameStepIndex;
+ const continuedFrom = stepIndex < 0 && sameStepIndex >= 0 ? prior.steps[sameStepIndex]! : undefined;
+ const continuedThinkingEnd = continuedFrom?.thinking?.sourceEndOffset ?? continuedFrom?.continuedThinkingEndOffset;
+ const continuedTextEnd = continuedFrom?.text?.sourceEndOffset ?? continuedFrom?.continuedTextEndOffset;
+ const step: LiveTurnStepProjection = stepIndex < 0
? {
stepId,
+ startedAt: event.ts,
tools: [],
- ...(claimsPendingSteering
- ? { leadingSteering: prior.pendingSteering }
- : {}),
+ ...(continuedThinkingEnd === undefined
+ ? {}
+ : { continuedThinkingEndOffset: continuedThinkingEnd }),
+ ...(continuedTextEnd === undefined
+ ? {}
+ : { continuedTextEndOffset: continuedTextEnd }),
}
: prior.steps[stepIndex]!;
let nextStep: LiveTurnStepProjection;
+ let replacedKind: 'thinking' | 'text' | undefined;
if (event.type === 'thinking_delta') {
- const delta = replaySafeDelta(step.thinking?.sourceEndOffset, event);
- const applied = applyThinkingDelta(step.thinking?.text ?? '', delta.text, {
+ const delta = replaySafeDelta(step.thinking?.sourceEndOffset ?? step.continuedThinkingEndOffset, event);
+ const prefix = renderedPrefix(prior, step, 'thinking');
+ const redactionState = prior.steps.findLast((candidate) => candidate.stepId === stepId && candidate.thinking)?.thinking?.redactionState;
+ const applied = applyThinkingDelta(prefix + (step.thinking?.text ?? ''), delta.text, {
locale,
- ...(step.thinking?.redactionState === undefined
- ? {}
- : { redactionState: step.thinking.redactionState }),
+ ...(redactionState === undefined ? {} : { redactionState }),
});
+ if (!applied.text.startsWith(prefix)) replacedKind = 'thinking';
nextStep = {
...step,
thinking: {
- text: applied.text,
+ text: completionRemainder(prior, step, 'thinking', applied.text),
truncated: (step.thinking?.truncated ?? false) || applied.truncated,
complete: false,
...(delta.sourceEndOffset === undefined
@@ -335,29 +373,31 @@ function projectLiveTurnEvent(
};
} else if (event.type === 'thinking_complete') {
const applied = applyThinkingComplete(event.text, { locale });
+ if (applied.redacted && !applied.text.startsWith(renderedPrefix(prior, step, 'thinking'))) replacedKind = 'thinking';
nextStep = {
...step,
thinking: {
- text: applied.text,
+ text: completionRemainder(prior, step, 'thinking', applied.text),
truncated: applied.truncated,
complete: true,
- ...(step.thinking?.sourceEndOffset === undefined
+ ...((step.thinking?.sourceEndOffset ?? step.continuedThinkingEndOffset) === undefined
? {}
: { sourceEndOffset: event.text.length }),
},
};
} else if (event.type === 'text_delta') {
- const delta = replaySafeDelta(step.text?.sourceEndOffset, event);
- const applied = applyAssistantDelta(step.text?.text ?? '', delta.text, {
+ const delta = replaySafeDelta(step.text?.sourceEndOffset ?? step.continuedTextEndOffset, event);
+ const prefix = renderedPrefix(prior, step, 'text');
+ const redactionState = prior.steps.findLast((candidate) => candidate.stepId === stepId && candidate.text)?.text?.redactionState;
+ const applied = applyAssistantDelta(prefix + (step.text?.text ?? ''), delta.text, {
locale,
- ...(step.text?.redactionState === undefined
- ? {}
- : { redactionState: step.text.redactionState }),
+ ...(redactionState === undefined ? {} : { redactionState }),
});
+ if (!applied.text.startsWith(prefix)) replacedKind = 'text';
nextStep = {
...step,
text: {
- text: applied.text,
+ text: completionRemainder(prior, step, 'text', applied.text),
truncated: (step.text?.truncated ?? false) || applied.truncated,
complete: false,
...(delta.sourceEndOffset === undefined
@@ -370,14 +410,15 @@ function projectLiveTurnEvent(
};
} else if (event.type === 'text_complete') {
const applied = applyAssistantComplete(event.text, { locale });
+ if (applied.redacted && !applied.text.startsWith(renderedPrefix(prior, step, 'text'))) replacedKind = 'text';
nextStep = {
...step,
text: {
...(event.interrupted ? { interrupted: true } : {}),
- text: applied.text,
+ text: completionRemainder(prior, step, 'text', applied.text),
truncated: applied.truncated,
complete: true,
- ...(step.text?.sourceEndOffset === undefined
+ ...((step.text?.sourceEndOffset ?? step.continuedTextEndOffset) === undefined
? {}
: { sourceEndOffset: event.text.length }),
},
@@ -496,7 +537,7 @@ function projectLiveTurnEvent(
};
let steps: LiveTurnStepProjection[];
if (existingToolStep && existingToolStep.stepId !== stepId && !messageEvent) {
- const sourceIndex = prior.steps.findIndex((candidate) => candidate.stepId === existingToolStep.stepId);
+ const sourceIndex = prior.steps.indexOf(existingToolStep);
const sourceWithoutTool = {
...existingToolStep,
tools: existingToolStep.tools.filter((tool) => tool.toolUseId !== event.toolUseId),
@@ -507,7 +548,7 @@ function projectLiveTurnEvent(
const sourceIsEmpty = !sourceWithoutTool.thinking
&& !sourceWithoutTool.text
&& sourceWithoutTool.tools.length === 0
- && (sourceWithoutTool.leadingSteering?.length ?? 0) === 0;
+ && sourceWithoutTool.steering === undefined;
steps = [];
for (let index = 0; index < prior.steps.length; index += 1) {
const candidate = prior.steps[index]!;
@@ -526,18 +567,65 @@ function projectLiveTurnEvent(
? prior.steps.map((candidate, index) => index === stepIndex ? nextStep : candidate)
: [...prior.steps, nextStep];
}
- const { pendingSteering: _pendingSteering, ...withoutPendingSteering } = priorWithoutRetry;
- return {
- ...(claimsPendingSteering ? withoutPendingSteering : priorWithoutRetry),
- steps,
- };
+ // A whole-stream transformation may revise a previously displayed prefix.
+ // Never leave an obsolete fragment beside the corrected projection.
+ if (replacedKind !== undefined) {
+ const kind = replacedKind;
+ steps = steps.map((candidate) => {
+ if (candidate === nextStep || candidate.stepId !== stepId) return candidate;
+ const { [kind]: _replaced, ...rest } = candidate;
+ return rest;
+ });
+ }
+ // A completion finalizes the message across every slice it occupies: an
+ // earlier slice keeps the portion it rendered — marked complete — so a
+ // steering boundary never relocates pre-steering content into the full text
+ // a later slice finalizes.
+ const finalizedKind = event.type === 'thinking_complete'
+ ? 'thinking'
+ : event.type === 'text_complete' ? 'text' : undefined;
+ if (finalizedKind !== undefined) {
+ steps = steps.map((candidate) =>
+ candidate !== nextStep
+ && candidate.stepId === stepId
+ && candidate[finalizedKind] !== undefined
+ ? { ...candidate, [finalizedKind]: { ...candidate[finalizedKind]!, complete: true } }
+ : candidate);
+ }
+ return { ...priorWithoutRetry, steps };
}
function liveSteeringMessages(current: LiveTurnProjection): LiveSteeringProjection[] {
- return [
- ...(current.pendingSteering ?? []),
- ...current.steps.flatMap((step) => step.leadingSteering ?? []),
- ];
+ return current.steps.flatMap((step) => (step.steering ? [step.steering] : []));
+}
+
+/**
+ * A completion's full text shares the delta stream's coordinates only when it
+ * extends the already-rendered prefix — a provider summary replaces the
+ * streamed text outright (`reasoningSummaryText` adoption), so a bare offset
+ * would cut real content. Trim only on a verified prefix; otherwise land the
+ * payload whole.
+ */
+function completionRemainder(
+ prior: LiveTurnProjection,
+ step: LiveTurnStepProjection,
+ kind: 'thinking' | 'text',
+ fullText: string,
+): string {
+ const prefix = renderedPrefix(prior, step, kind);
+ return fullText.startsWith(prefix) ? fullText.slice(prefix.length) : fullText;
+}
+
+function renderedPrefix(
+ prior: LiveTurnProjection,
+ step: LiveTurnStepProjection,
+ kind: 'thinking' | 'text',
+): string {
+ const rendered = prior.steps.flatMap((candidate) =>
+ candidate !== step && candidate.stepId === step.stepId && candidate[kind]
+ ? [candidate[kind]!.text]
+ : []);
+ return rendered.join('');
}
function replaySafeDelta(
@@ -547,9 +635,7 @@ function replaySafeDelta(
if (event.startOffset === undefined) {
return {
text: event.text,
- ...(currentEndOffset === undefined
- ? {}
- : { sourceEndOffset: currentEndOffset + event.text.length }),
+ sourceEndOffset: (currentEndOffset ?? 0) + event.text.length,
};
}
const endOffset = event.startOffset + event.text.length;
@@ -567,28 +653,30 @@ function replaySafeDelta(
* Streaming display handoff: drop the committed text/thinking slots for `stepId`.
* Tools that still carry live stream evidence (outputChunks) stay — empty
* shell_run durable results do not cover them, and co-located Shell+answer
- * steps must not lose pre-handoff output when the answer settles.
+ * steps must not lose pre-handoff output when the answer settles. `stepId`
+ * can match multiple slices once a steering boundary split the step;
+ * steering boundary slices carry their own namespaced id and never match.
*/
export function settleLiveTurnStep(
current: LiveTurnProjection,
stepId: string,
): LiveTurnProjection | undefined {
- const stepIndex = current.steps.findIndex((step) => step.stepId === stepId);
- if (stepIndex < 0) return current;
- const step = current.steps[stepIndex]!;
- const retainedTools = step.tools.filter((tool) => (tool.outputChunks?.length ?? 0) > 0);
- const steps = retainedTools.length > 0
- ? current.steps.map((candidate, index) => (
- index === stepIndex
- ? {
- stepId: candidate.stepId,
- tools: retainedTools,
- contentOrder: ['tools' as const],
- }
- : candidate
- ))
- : current.steps.filter((candidate) => candidate.stepId !== stepId);
- if (steps.length === current.steps.length && retainedTools.length === 0) return current;
+ let found = false;
+ const steps = current.steps.flatMap((step) => {
+ if (step.stepId !== stepId) return [step];
+ found = true;
+ const retainedTools = step.tools.filter((tool) => (tool.outputChunks?.length ?? 0) > 0);
+ if (retainedTools.length === 0) {
+ return [];
+ }
+ return [{
+ stepId,
+ tools: retainedTools,
+ ...(retainedTools.length > 0 ? { contentOrder: ['tools' as const] } : {}),
+ ...(step.startedAt !== undefined ? { startedAt: step.startedAt } : {}),
+ }];
+ });
+ if (!found) return current;
if (steps.length === 0 && current.terminal) return undefined;
return { ...current, steps };
}
@@ -655,6 +743,9 @@ export function reconcileTerminalLiveTurn(
const toolCallIds = new Set(turnMessages.flatMap((message) => message.type === 'tool_call' ? [message.id] : []));
const toolResultIds = new Set(turnMessages.flatMap((message) => message.type === 'tool_result' ? [message.toolUseId] : []));
let steps = projection.steps.filter((step) => {
+ // Steering boundary slices hold no durable-comparable content; the
+ // overlay dedupes against the persisted user row by id.
+ if (step.steering !== undefined) return true;
if (step.text?.text.length) return true;
if (step.thinking && !assistantIds.has(step.stepId)) return true;
const toolsCovered = step.tools.every((tool) => {
@@ -676,11 +767,7 @@ export function reconcileTerminalLiveTurn(
&& transcriptReachedTerminal
&& liveSteeringMessages(projection).length > 0;
if (steeringSettled) {
- steps = steps.map((step) => {
- if (!step.leadingSteering) return step;
- const { leadingSteering: _leadingSteering, ...withoutSteering } = step;
- return withoutSteering;
- });
+ steps = steps.filter((step) => step.steering === undefined);
}
if (
steps.length === 0
@@ -692,7 +779,5 @@ export function reconcileTerminalLiveTurn(
)
) return undefined;
if (steps.length === projection.steps.length && !steeringSettled) return projection;
- if (!steeringSettled) return { ...projection, steps };
- const { pendingSteering: _pendingSteering, ...withoutSteering } = projection;
- return { ...withoutSteering, steps };
+ return { ...projection, steps };
}
diff --git a/packages/ui/src/materialize.ts b/packages/ui/src/materialize.ts
index d6270a29f6..f156322de8 100644
--- a/packages/ui/src/materialize.ts
+++ b/packages/ui/src/materialize.ts
@@ -504,22 +504,14 @@ export function overlayLiveTurn(
} satisfies TurnViewModel,
];
}
- if (
- targetIndex >= 0
- && liveTurn.steps.length === 0
- && (liveTurn.pendingSteering?.length ?? 0) === 0
- ) {
+ if (targetIndex >= 0 && liveTurn.steps.length === 0) {
return turns;
}
// A send arm is only a presentation claim that the next message may still
// arrive. It is not a Turn record and must not manufacture one while the
// canonical transcript is catching up. A real live step (or steering
// message) is sufficient evidence to project a missing external Turn.
- if (
- targetIndex < 0
- && liveTurn.steps.length === 0
- && (liveTurn.pendingSteering?.length ?? 0) === 0
- ) {
+ if (targetIndex < 0 && liveTurn.steps.length === 0) {
return turns;
}
const current =
@@ -555,22 +547,20 @@ export function overlayLiveTurn(
}
}
const liveTimeline: TurnTimelineItem[] = [];
- const emittedSteeringIds = new Set<string>();
- const appendLiveSteering = (
- messages: readonly LiveSteeringProjection[],
- ): void => {
- for (const message of messages) {
- if (emittedSteeringIds.has(message.id)) continue;
- emittedSteeringIds.add(message.id);
- liveTimeline.push({
- kind: "user",
- message: chatItemFromContent(message.id, message.ts, message.content),
- messageId: message.id,
- });
- }
+ const liveItemTs: number[] = [];
+ const pushLive = (item: TurnTimelineItem, ts: number | undefined): void => {
+ liveTimeline.push(item);
+ liveItemTs.push(ts ?? 0);
+ };
+ const appendLiveSteering = (message: LiveSteeringProjection): void => {
+ pushLive({
+ kind: "user",
+ message: chatItemFromContent(message.id, message.ts, message.content),
+ messageId: message.id,
+ }, message.ts);
};
for (const step of liveTurn.steps) {
- appendLiveSteering(step.leadingSteering ?? []);
+ if (step.steering !== undefined) appendLiveSteering(step.steering);
const contentOrder = step.contentOrder ?? [
...(step.thinking ? ["thinking" as const] : []),
...(step.text ? ["text" as const] : []),
@@ -578,15 +568,15 @@ export function overlayLiveTurn(
];
for (const kind of contentOrder) {
if (kind === "thinking" && step.thinking?.text) {
- liveTimeline.push({
+ pushLive({
kind: "thinking",
text: step.thinking.text,
messageId: step.stepId,
live: step.thinking.complete !== true,
truncated: step.thinking.truncated,
- });
+ }, step.startedAt);
} else if (kind === "text" && step.text && (step.text.text || step.text.interrupted)) {
- liveTimeline.push({
+ pushLive({
kind: "text",
text: step.text.text,
...(step.text.interrupted ? { interrupted: true } : {}),
@@ -594,36 +584,48 @@ export function overlayLiveTurn(
live: true,
complete: step.text.complete,
truncated: step.text.truncated,
- });
+ }, step.startedAt);
} else if (kind === "tools") {
const stepTools = step.tools.flatMap((tool) => {
const projected = toolByUseId.get(tool.toolUseId);
return projected ? [projected] : [];
});
if (stepTools.length > 0)
- liveTimeline.push({ kind: "tools", items: stepTools });
+ pushLive({ kind: "tools", items: stepTools }, step.startedAt);
}
}
}
- appendLiveSteering(liveTurn.pendingSteering ?? []);
// Shared entries are handoff points: replace them in place while preserving
// live production order. Appending all live content after settled rows moved
// an earlier answer (and its steering anchor) behind later persisted steps.
- const liveEntries = flattenTimelineTools(liveTimeline);
- const liveIndex = new Map(liveEntries.map((item, index) => [timelineItemKey(item), index]));
+ const liveEntries = liveTimeline.flatMap((item, index) =>
+ flattenTimelineTools([item]).map((entry) => ({ entry, ts: liveItemTs[index]! })));
+ const lastSettledContentIndex = current.timeline.findLastIndex((item) => item.kind !== 'user');
+ const liveKeys = new Set(liveEntries.map(({ entry }) => timelineItemKey(entry)));
+ // A steering the live stream missed is position-ambiguous once it sits at
+ // the settled tail; splice it into the live order where its own ts falls
+ // instead of blindly trailing content that followed it. Missing ts sorts
+ // conservatively on both sides: a live entry without one keeps the deferred
+ // steering behind it, and a settled steering without one trails the live
+ // order rather than leaping ahead of known content.
+ const deferredSettled = new Set<number>();
+ for (const [index, item] of current.timeline.entries()) {
+ if (item.kind !== 'user' || item.steeringEventId === undefined
+ || index <= lastSettledContentIndex || liveKeys.has(timelineItemKey(item))) continue;
+ deferredSettled.add(index);
+ const ts = item.message.ts ?? Number.MAX_SAFE_INTEGER;
+ const at = liveEntries.findIndex((entry) => entry.ts > ts);
+ if (at < 0) liveEntries.push({ entry: item, ts });
+ else liveEntries.splice(at, 0, { entry: item, ts });
+ }
+ const liveIndex = new Map(liveEntries.map(({ entry }, index) => [timelineItemKey(entry), index]));
const timeline: TurnTimelineItem[] = [];
let nextLive = 0;
const appendLiveThrough = (index: number) => {
- while (nextLive <= index) timeline.push(liveEntries[nextLive++]!);
+ while (nextLive <= index) timeline.push(liveEntries[nextLive++]!.entry);
};
- const lastSettledContentIndex = current.timeline.findLastIndex((item) => item.kind !== 'user');
- const deferredSteering: TurnTimelineItem[] = [];
for (const [index, item] of current.timeline.entries()) {
- if (item.kind === 'user' && item.steeringEventId !== undefined
- && !liveIndex.has(timelineItemKey(item)) && index > lastSettledContentIndex) {
- deferredSteering.push(item);
- continue;
- }
+ if (deferredSettled.has(index)) continue;
for (const entry of flattenTimelineTools([item])) {
const key = timelineItemKey(entry);
const livePosition = liveIndex.get(key);
@@ -632,7 +634,6 @@ export function overlayLiveTurn(
}
}
appendLiveThrough(liveEntries.length - 1);
- timeline.push(...deferredSteering);
const mergedTimeline = mergeAdjacentTimeline(timeline);
const next = {
...current,
diff --git a/packages/ui/src/transcript-projection.ts b/packages/ui/src/transcript-projection.ts
index 267c6972a8..57f91479a4 100644
--- a/packages/ui/src/transcript-projection.ts
+++ b/packages/ui/src/transcript-projection.ts
@@ -218,6 +218,10 @@ export function reconcileTurnIdentities(
const previousById = new Map(previous.map((turn) => [turn.turnId, turn]));
const reconciled = next.map((turn) => {
const prior = previousById.get(turn.turnId);
+ if (prior) {
+ const timeline = retainSteeringLayout(prior.timeline, turn.timeline);
+ if (timeline !== turn.timeline) turn = { ...turn, timeline };
+ }
if (!prior || valuesEqual(prior, turn)) return prior ?? turn;
// The turn moved, but usually only its tail did: hand the previous
// timeline entry back for every item whose value did not change, so the
@@ -229,6 +233,60 @@ export function reconcileTurnIdentities(
: reconciled;
}
+/**
+ * The durable assistant row contains full text, not live slice offsets.
+ * Keep an already displayed split only while its entire span is still covered
+ * by identical canonical text and confirmed steering rows. This uses the
+ * existing visible transcript cache; live buffers can retire normally.
+ */
+function retainSteeringLayout(
+ previous: TurnTimelineItem[],
+ next: TurnTimelineItem[],
+): TurnTimelineItem[] {
+ const positions = new Map<string, number[]>();
+ previous.forEach((item, index) => {
+ if (item.kind !== 'text' && item.kind !== 'thinking') return;
+ const key = timelineItemKey(item);
+ const indices = positions.get(key) ?? [];
+ indices.push(index);
+ positions.set(key, indices);
+ });
+ const splitPositions = [...positions.values()].filter((indices) => indices.length > 1).flat();
+ if (splitPositions.length === 0) return next;
+ const span = previous.slice(Math.min(...splitPositions), Math.max(...splitPositions) + 1);
+ if (!span.some((item) => item.kind === 'user')) return next;
+ const keys = new Set(span.map(timelineItemKey));
+ const matches = next.flatMap((item, index) => keys.has(timelineItemKey(item)) ? [index] : []);
+ // New, missing or repeated facts invalidate this layout instead of being hidden.
+ if (matches.length !== keys.size) return next;
+ const first = matches[0]!;
+ const last = matches.at(-1)!;
+ if (last - first + 1 !== keys.size) return next;
+ const current = new Map(next.slice(first, last + 1).map((item) => [timelineItemKey(item), item]));
+ if (current.size !== keys.size) return next;
+ for (const key of keys) {
+ const item = current.get(key);
+ const fragments = span.filter((part) => timelineItemKey(part) === key);
+ if (!item) return next;
+ if (item.kind === 'text' || item.kind === 'thinking') {
+ if (item.live || fragments.some((part) => part.kind !== item.kind)
+ || fragments.map((part) => 'text' in part ? part.text : '').join('') !== item.text) return next;
+ } else if (item.kind === 'user') {
+ if (item.steeringEventId === undefined || fragments.length !== 1 || fragments[0]?.kind !== 'user'
+ || fragments[0].message.text !== item.message.text) return next;
+ } else if (fragments.length !== 1) {
+ return next;
+ }
+ }
+ const retained = span.map((fragment): TurnTimelineItem => {
+ const item = current.get(timelineItemKey(fragment))!;
+ return (item.kind === 'text' || item.kind === 'thinking') && 'text' in fragment
+ ? { ...item, text: fragment.text }
+ : item;
+ });
+ return [...next.slice(0, first), ...retained, ...next.slice(last + 1)];
+}
+
/**
* Keep the previous object for every timeline item whose projected value is
* unchanged. `overlayLiveTurn` rebuilds a live turn's whole timeline from its
diff --git a/packages/workhub/src/locales/workhub-live-copy.ts b/packages/workhub/src/locales/workhub-live-copy.ts
index d888d65c22..25a14f379e 100644
--- a/packages/workhub/src/locales/workhub-live-copy.ts
+++ b/packages/workhub/src/locales/workhub-live-copy.ts
@@ -32,7 +32,7 @@ export const workHubLiveCopy = {
reviewAttachments: 'Please review the attachments.',
sendFailed: 'Could not send',
retrySteering:
- 'Retry the original text and attachments with Shift+Enter to resolve the previous submission first.',
+ 'Retry the original text and attachments with Cmd/Ctrl+Enter to resolve the previous submission first.',
retryFollowup:
'Retry the original text and attachments with Enter to resolve the previous submission first.',
sendUnknown: 'The Host has not confirmed this message. Retry checks the same submission.',
@@ -82,7 +82,7 @@ export const workHubLiveCopy = {
attachmentUploadFailed: '附件上传失败',
reviewAttachments: '请查看附件。',
sendFailed: '发送失败',
- retrySteering: '请先保留原文和附件,用 Shift+Enter 重试并确认上次提交结果。',
+ retrySteering: '请先保留原文和附件,用 Cmd/Ctrl+Enter 重试并确认上次提交结果。',
retryFollowup: '请先保留原文和附件,用 Enter 重试并确认上次提交结果。',
sendUnknown: 'Host 尚未确认这条消息。重试会核对原提交。',
sendNotAdmitted: 'Host 在接收这条消息前已重启,可以重试发送。',
@@ -131,7 +131,7 @@ export const workHubLiveCopy = {
attachmentUploadFailed: '附件上傳失敗',
reviewAttachments: '請查看附件。',
sendFailed: '傳送失敗',
- retrySteering: '請先保留原文和附件,用 Shift+Enter 重試並確認上次提交結果。',
+ retrySteering: '請先保留原文和附件,用 Cmd/Ctrl+Enter 重試並確認上次提交結果。',
retryFollowup: '請先保留原文和附件,用 Enter 重試並確認上次提交結果。',
sendUnknown: 'Host 尚未確認這則訊息。重試會核對原提交。',
sendNotAdmitted: 'Host 在接收這則訊息前已重新啟動,可以重試傳送。',
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org