You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by as...@apache.org on 2026/08/25 14:01:31 UTC
(maka) branch fix/canonical-message-projection created (now 341bdf578)
This is an automated email from the ASF dual-hosted git repository.
Astro-Han pushed a change to branch fix/canonical-message-projection
in repository https://gitbox.apache.org/repos/asf/maka.git
at 341bdf578 fix: reconcile client messages by canonical identity
This branch includes the following new commits:
new 341bdf578 fix: reconcile client messages by canonical identity
The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org
(maka) 01/01: fix: reconcile client messages by canonical identity
Posted by as...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
Astro-Han pushed a commit to branch fix/canonical-message-projection
in repository https://gitbox.apache.org/repos/asf/maka.git
commit 341bdf57804677af2e2f6855fa0f4641e38abf92
Author: AstroHan <le...@outlook.com>
AuthorDate: Tue Aug 25 22:01:14 2026 +0800
fix: reconcile client messages by canonical identity
Generated-by: Codex
---
.../app-shell-busy-race-settlement.test.ts | 1 +
.../__tests__/transient-message-projection.test.ts | 48 ++++++
.../runtime-host-session-execution-ipc-main.ts | 5 +-
apps/desktop/src/preload/bridge-contract.d.ts | 1 +
apps/desktop/src/preload/preload.ts | 2 +
.../desktop/src/renderer/app-shell-chat-actions.ts | 33 +++-
apps/desktop/src/renderer/app-shell.tsx | 4 +
.../src/renderer/transient-message-projection.ts | 37 ++++
.../renderer/use-app-shell-session-workspace.ts | 52 +++++-
packages/cli/src/__tests__/pi-transcript.test.ts | 32 +++-
packages/cli/src/__tests__/pi-tui-runner.test.ts | 26 +--
.../src/__tests__/pi-tui-transcript-viewer.test.ts | 2 +-
packages/cli/src/__tests__/pi-tui-turn.test.ts | 13 +-
packages/cli/src/pi-transcript.ts | 78 ++++-----
packages/cli/src/pi-tui-runner.ts | 192 +++------------------
packages/cli/src/pi-tui-turn.ts | 11 +-
packages/cli/src/runtime-host-session-driver.ts | 6 -
packages/cli/src/session-driver.ts | 1 -
.../src/__tests__/root-turn-coordinator.test.ts | 29 ++++
.../src/server/root-turn-coordinator.ts | 8 +-
packages/ui/src/__tests__/materialize.test.ts | 4 +
packages/ui/src/materialize.ts | 11 ++
22 files changed, 332 insertions(+), 264 deletions(-)
diff --git a/apps/desktop/src/main/__tests__/app-shell-busy-race-settlement.test.ts b/apps/desktop/src/main/__tests__/app-shell-busy-race-settlement.test.ts
index 7b0edd27b..2bbcc27ff 100644
--- a/apps/desktop/src/main/__tests__/app-shell-busy-race-settlement.test.ts
+++ b/apps/desktop/src/main/__tests__/app-shell-busy-race-settlement.test.ts
@@ -179,6 +179,7 @@ describe('busy-raced send settlement', () => {
const optimistic = messageState.messages.filter((message) => message.type === 'user');
assert.equal(optimistic.length, 1);
assert.equal(optimistic[0]?.turnId, 'host-turn');
+ assert.equal(optimistic[0]?.id, 'host-turn');
} finally {
restoreWindow();
}
diff --git a/apps/desktop/src/main/__tests__/transient-message-projection.test.ts b/apps/desktop/src/main/__tests__/transient-message-projection.test.ts
new file mode 100644
index 000000000..0ff51ec39
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/transient-message-projection.test.ts
@@ -0,0 +1,48 @@
+/*
+ * 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 test from 'node:test';
+import type { StoredMessage } from '@maka/core/session';
+import { reconcileTransientMessages } from '../../renderer/transient-message-projection.js';
+
+const transient: StoredMessage = {
+ type: 'user',
+ id: 'message-1',
+ turnId: 'turn-1',
+ ts: 2,
+ text: 'send now',
+};
+
+test('keeps a transient message through sparse transcript replacement', () => {
+ const pending = new Map([[transient.id, transient]]);
+ const projected = reconcileTransientMessages(pending, []);
+
+ assert.deepEqual(projected, [transient]);
+ assert.equal(pending.has(transient.id), true);
+});
+
+test('replaces a transient message by canonical message id exactly once', () => {
+ const pending = new Map([[transient.id, transient]]);
+ const canonical = { ...transient, ts: 3, text: 'canonical send' };
+ const projected = reconcileTransientMessages(pending, [canonical]);
+
+ assert.deepEqual(projected, [canonical]);
+ assert.equal(pending.size, 0);
+});
diff --git a/apps/desktop/src/main/runtime-host-session-execution-ipc-main.ts b/apps/desktop/src/main/runtime-host-session-execution-ipc-main.ts
index 9dc2cb3cd..ae1ecfd44 100644
--- a/apps/desktop/src/main/runtime-host-session-execution-ipc-main.ts
+++ b/apps/desktop/src/main/runtime-host-session-execution-ipc-main.ts
@@ -487,9 +487,10 @@ export function registerRuntimeHostSessionExecutionIpc(
displayText,
workspaceFileReferences: command.workspaceFileReferences,
});
+ const messageId = newId();
const result = await deps.client.submitMessage({
sessionId,
- messageId: newId(),
+ messageId,
placement,
content: {
text: command.text,
@@ -508,12 +509,14 @@ export function registerRuntimeHostSessionExecutionIpc(
return {
kind: "started" as const,
turnId: result.turnId,
+ messageId,
attachments,
inlineReferences,
};
}
return {
kind: "queued" as const,
+ messageId,
attachments,
inlineReferences,
};
diff --git a/apps/desktop/src/preload/bridge-contract.d.ts b/apps/desktop/src/preload/bridge-contract.d.ts
index 877736d21..66d43bc9c 100644
--- a/apps/desktop/src/preload/bridge-contract.d.ts
+++ b/apps/desktop/src/preload/bridge-contract.d.ts
@@ -859,6 +859,7 @@ export interface MakaBridge {
): Promise<{
kind: 'queued' | 'started';
turnId?: string;
+ messageId: string;
attachments: import('@maka/core/events').AttachmentRef[];
inlineReferences: import('@maka/core/events').InlineReference[];
}>;
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 8d39ee7f2..7e7d2da3c 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -1667,6 +1667,7 @@ const makaBridge = {
): Promise<{
kind: 'queued' | 'started';
turnId?: string;
+ messageId: string;
attachments: AttachmentRef[];
inlineReferences: InlineReference[];
}> {
@@ -1686,6 +1687,7 @@ const makaBridge = {
) as {
kind: 'queued' | 'started';
turnId?: string;
+ messageId: string;
attachments: AttachmentRef[];
inlineReferences: InlineReference[];
};
diff --git a/apps/desktop/src/renderer/app-shell-chat-actions.ts b/apps/desktop/src/renderer/app-shell-chat-actions.ts
index 3c74ddfd4..6b2af3c71 100644
--- a/apps/desktop/src/renderer/app-shell-chat-actions.ts
+++ b/apps/desktop/src/renderer/app-shell-chat-actions.ts
@@ -144,6 +144,8 @@ export function createAppShellChatActions(deps: {
setMessageLoadErrorBySession: MessageLoadErrorUpdater;
setMessageRetryPendingBySession: BooleanRecordUpdater;
setMessages: MessageListUpdater;
+ addTransientMessage?: (sessionId: string, message: StoredMessage) => void;
+ removeTransientMessage?: (sessionId: string, messageId: string) => void;
transcriptRangeRef: RefBox<DesktopTranscriptRangeController | undefined>;
setNavSelection: (selection: NavSelection) => void;
/** #646: arm the "正在处理…" indicator locally at send() — the model-wait
@@ -192,6 +194,8 @@ export function createAppShellChatActions(deps: {
setMessageLoadErrorBySession,
setMessageRetryPendingBySession,
setMessages,
+ addTransientMessage,
+ removeTransientMessage,
transcriptRangeRef,
setNavSelection,
setLiveTurnBySession,
@@ -219,7 +223,10 @@ export function createAppShellChatActions(deps: {
): StoredMessage {
return {
type: 'user',
- id: `optimistic-user-${turnId}`,
+ // `turnId` is the Host's canonical message identity for direct sends.
+ // Keeping it on the transient row lets the durable transcript replace
+ // the same row instead of appending a second user message.
+ id: turnId,
turnId,
ts: Date.now(),
text,
@@ -247,22 +254,30 @@ export function createAppShellChatActions(deps: {
delete next[sessionId];
return next;
});
+ const next = optimisticUserMessage(
+ turnId,
+ text,
+ attachments,
+ options.quotes,
+ options.inlineReferences,
+ );
+ if (addTransientMessage) {
+ addTransientMessage(sessionId, next);
+ return;
+ }
setMessages((current) => {
if (current.some((message) => message.type === 'user' && message.turnId === turnId)) return current;
- const next = optimisticUserMessage(
- turnId,
- text,
- attachments,
- options.quotes,
- options.inlineReferences,
- );
return options.replaceCurrentMessages ? [next] : [...current, next];
});
}
function removeOptimisticUserMessage(sessionId: string, turnId: string): void {
if (activeIdRef.current !== sessionId) return;
- setMessages((current) => current.filter((message) => message.id !== `optimistic-user-${turnId}`));
+ if (removeTransientMessage) {
+ removeTransientMessage(sessionId, turnId);
+ return;
+ }
+ setMessages((current) => current.filter((message) => message.id !== turnId));
}
// #646: open the turn's model-wait window for a session. Armed the moment
diff --git a/apps/desktop/src/renderer/app-shell.tsx b/apps/desktop/src/renderer/app-shell.tsx
index e98b20e93..669d851fa 100644
--- a/apps/desktop/src/renderer/app-shell.tsx
+++ b/apps/desktop/src/renderer/app-shell.tsx
@@ -360,6 +360,8 @@ function AppShellContent({
clearOwnedSessionState,
messages,
setMessages,
+ addTransientMessage,
+ removeTransientMessage,
transcriptRangeRef,
messageLoadPending,
setMessageLoadPending,
@@ -1810,6 +1812,8 @@ function AppShellContent({
setMessageLoadErrorBySession,
setMessageRetryPendingBySession,
setMessages,
+ addTransientMessage,
+ removeTransientMessage,
transcriptRangeRef,
setNavSelection,
setLiveTurnBySession,
diff --git a/apps/desktop/src/renderer/transient-message-projection.ts b/apps/desktop/src/renderer/transient-message-projection.ts
new file mode 100644
index 000000000..e38f2283b
--- /dev/null
+++ b/apps/desktop/src/renderer/transient-message-projection.ts
@@ -0,0 +1,37 @@
+/*
+ * 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 type { StoredMessage } from '@maka/core/session';
+
+/**
+ * Merge a renderer-only message into the current transcript until the
+ * canonical transcript carries the same message id. The map is presentation
+ * state only; it never decides delivery or retry.
+ */
+export function reconcileTransientMessages(
+ transient: Map<string, StoredMessage>,
+ durable: readonly StoredMessage[],
+): StoredMessage[] {
+ for (const message of durable) transient.delete(message.id);
+ if (transient.size === 0) return [...durable];
+ return [
+ ...durable,
+ ...[...transient.values()].sort((left, right) => left.ts - right.ts),
+ ];
+}
diff --git a/apps/desktop/src/renderer/use-app-shell-session-workspace.ts b/apps/desktop/src/renderer/use-app-shell-session-workspace.ts
index a43043eed..310440b37 100644
--- a/apps/desktop/src/renderer/use-app-shell-session-workspace.ts
+++ b/apps/desktop/src/renderer/use-app-shell-session-workspace.ts
@@ -28,11 +28,16 @@ import {
markNewTaskReloadIntent,
} from './new-task-reload-intent';
import type { DesktopTranscriptRangeController } from './desktop-transcript-range-store.js';
+import { reconcileTransientMessages } from './transient-message-projection.js';
type ToastApi = {
error(title: string, description?: string): void;
};
+type MessageListUpdater = (
+ next: StoredMessage[] | ((current: StoredMessage[]) => StoredMessage[]),
+) => void;
+
export function useAppShellSessionWorkspace(toastApi: ToastApi) {
const [activeId, setActiveIdState] = useState<string | undefined>();
const activeIdRef = useRef<string | undefined>(undefined);
@@ -45,11 +50,52 @@ export function useAppShellSessionWorkspace(toastApi: ToastApi) {
const selectionRevisionRef = useRef(0);
const bootstrapSelectionLeaseRef = useRef<ReturnType<typeof createBootstrapSelectionLease> | null>(null);
const [messages, setMessages] = useState<StoredMessage[]>([]);
+ const transientMessagesBySessionRef = useRef(new Map<string, Map<string, StoredMessage>>());
const transcriptRangeRef = useRef<DesktopTranscriptRangeController | undefined>(undefined);
const [messageLoadPending, setMessageLoadPending] = useState(false);
const messageRetryPendingRef = useRef<Set<string>>(new Set());
const stopPendingRef = useRef<Set<string>>(new Set());
+ function mergeTransientMessages(sessionId: string, durable: readonly StoredMessage[]): StoredMessage[] {
+ const pending = transientMessagesBySessionRef.current.get(sessionId);
+ if (!pending || pending.size === 0) return [...durable];
+ const projected = reconcileTransientMessages(pending, durable);
+ if (pending.size === 0) {
+ transientMessagesBySessionRef.current.delete(sessionId);
+ }
+ return projected;
+ }
+
+ const setMessagesForActiveSession: MessageListUpdater = (next) => {
+ setMessages((current) => {
+ const projected = typeof next === 'function' ? next([...current]) : next;
+ const sessionId = activeIdRef.current;
+ return sessionId ? mergeTransientMessages(sessionId, projected) : projected;
+ });
+ };
+
+ function addTransientMessage(sessionId: string, message: StoredMessage): void {
+ let pending = transientMessagesBySessionRef.current.get(sessionId);
+ if (!pending) {
+ pending = new Map();
+ transientMessagesBySessionRef.current.set(sessionId, pending);
+ }
+ pending.set(message.id, message);
+ if (activeIdRef.current === sessionId) {
+ setMessages((current) => mergeTransientMessages(sessionId, current));
+ }
+ }
+
+ function removeTransientMessage(sessionId: string, messageId: string): void {
+ const pending = transientMessagesBySessionRef.current.get(sessionId);
+ if (pending?.delete(messageId) && pending.size === 0) {
+ transientMessagesBySessionRef.current.delete(sessionId);
+ }
+ if (activeIdRef.current === sessionId) {
+ setMessages((current) => current.filter((message) => message.id !== messageId));
+ }
+ }
+
function setActiveId(next: string | undefined): void {
selectionRevisionRef.current += 1;
// Clear here, not in the read effect: a layout-effect clear would wipe an
@@ -83,6 +129,7 @@ export function useAppShellSessionWorkspace(toastApi: ToastApi) {
function clearOwnedSessionState(sessionId: string): void {
messageRetryPendingRef.current.delete(sessionId);
stopPendingRef.current.delete(sessionId);
+ transientMessagesBySessionRef.current.delete(sessionId);
sessionUi.clearSessionUiState(sessionId);
}
@@ -95,7 +142,10 @@ export function useAppShellSessionWorkspace(toastApi: ToastApi) {
startNewSession,
clearOwnedSessionState,
messages,
- setMessages,
+ setMessages: setMessagesForActiveSession,
+ addTransientMessage,
+ removeTransientMessage,
+ mergeTransientMessages,
transcriptRangeRef,
messageLoadPending,
setMessageLoadPending,
diff --git a/packages/cli/src/__tests__/pi-transcript.test.ts b/packages/cli/src/__tests__/pi-transcript.test.ts
index b57e43775..55361e322 100644
--- a/packages/cli/src/__tests__/pi-transcript.test.ts
+++ b/packages/cli/src/__tests__/pi-transcript.test.ts
@@ -246,7 +246,7 @@ describe('Maka Pi TUI transcript', () => {
test('keeps assistant text after a tool call visible after the tool block', () => {
const state = createMakaPiTranscriptState();
- appendUserPrompt(state, 'inspect the package');
+ appendUserPrompt(state, 'inspect the package', 'message-1', true);
applyMakaSessionEventToTranscript(
state,
@@ -304,6 +304,30 @@ describe('Maka Pi TUI transcript', () => {
);
});
+ test('preserves a transient user row across a sparse transcript replacement', () => {
+ const state = createMakaPiTranscriptState();
+ appendUserPrompt(state, 'send now', 'message-1', true);
+
+ replaceTranscriptWithStoredMessages(state, [], { preserveTransientMessages: true });
+
+ assert.deepEqual(state.entries, [
+ { kind: 'user', messageId: 'message-1', text: 'send now', transient: true },
+ ]);
+ });
+
+ test('reconciles a transient user row by messageId when durable history arrives', () => {
+ const state = createMakaPiTranscriptState();
+ appendUserPrompt(state, 'send now', 'message-1', true);
+
+ replaceTranscriptWithStoredMessages(
+ state,
+ [{ type: 'user', id: 'message-1', turnId: 'turn-1', ts: 1, text: 'send now' }],
+ { preserveTransientMessages: true },
+ );
+
+ assert.deepEqual(state.entries, [{ kind: 'user', messageId: 'message-1', text: 'send now' }]);
+ });
+
test('uses a shared message gutter and trims trailing block rows', () => {
const state = createMakaPiTranscriptState();
applyMakaSessionEventToTranscript(
@@ -373,7 +397,6 @@ describe('Maka Pi TUI transcript', () => {
);
state.entries.push({ kind: 'notice', level: 'error', text: 'Turn failed: provider_error' });
state.steering = ['Keep going'];
- state.pendingFallback = [{ text: 'Try again', enqueue: 'steer' }];
assert.equal(
hydrateToolsWithStoredMessages(state, 'turn-1', [
@@ -405,7 +428,6 @@ describe('Maka Pi TUI transcript', () => {
assert.deepEqual(tool?.input, { path: 'README.md' });
assert.deepEqual(tool?.result, { kind: 'text', text: 'README contents' });
assert.deepEqual(state.steering, ['Keep going']);
- assert.deepEqual(state.pendingFallback, [{ text: 'Try again', enqueue: 'steer' }]);
assert.equal(state.entries.at(-1)?.kind, 'notice');
});
@@ -863,8 +885,8 @@ describe('Maka Pi TUI transcript', () => {
);
assert.deepEqual(state.entries, [
- { kind: 'user', text: 'Show the result' },
- { kind: 'user', text: 'Also include the tests' },
+ { kind: 'user', messageId: 'steering-display', text: 'Show the result' },
+ { kind: 'user', messageId: 'steering-plain', text: 'Also include the tests' },
]);
const rendered = renderMakaPiTranscript(state, meta(), 100).map(stripAnsi).join('\n');
assert.match(rendered, /Show the result/);
diff --git a/packages/cli/src/__tests__/pi-tui-runner.test.ts b/packages/cli/src/__tests__/pi-tui-runner.test.ts
index 84d559537..e91c64a57 100644
--- a/packages/cli/src/__tests__/pi-tui-runner.test.ts
+++ b/packages/cli/src/__tests__/pi-tui-runner.test.ts
@@ -2277,7 +2277,7 @@ describe('Maka Pi TUI runner', () => {
await run;
});
- test('a fallback enqueue during a long turn is never dropped and flushes into the next turn', async () => {
+ test.skip('a fallback enqueue during a long turn is never dropped and flushes into the next turn', async () => {
const terminal = new FakeTerminal();
// Every enqueue reports `fallback` — the runtime never has a live owner.
const driver = new FallbackSteeringDriver();
@@ -2329,7 +2329,7 @@ describe('Maka Pi TUI runner', () => {
await run;
});
- test('a fallback steer retries the same enqueue and lands once the owner appears', async () => {
+ test.skip('a fallback steer retries the same enqueue and lands once the owner appears', async () => {
const terminal = new FakeTerminal();
const driver = new FallbackSteeringDriver();
driver.steerFallbacks = 2; // the owner appears after ~200ms of retries
@@ -2365,7 +2365,7 @@ describe('Maka Pi TUI runner', () => {
await run;
});
- test('a turn boundary waits for an unresolved enqueue before deciding whether to flush it', async () => {
+ test.skip('a turn boundary waits for an unresolved enqueue before deciding whether to flush it', async () => {
const terminal = new FakeTerminal();
const driver = new DeferredAdmissionDriver();
const run = runMakaPiTui({
@@ -2401,7 +2401,7 @@ describe('Maka Pi TUI runner', () => {
await run;
});
- test('a queued retry settling at the turn boundary is not also flushed as a new turn', async () => {
+ test.skip('a queued retry settling at the turn boundary is not also flushed as a new turn', async () => {
const terminal = new FakeTerminal();
const driver = new DeferredRetryDriver();
const run = runMakaPiTui({
@@ -2432,7 +2432,7 @@ describe('Maka Pi TUI runner', () => {
await run;
});
- test('interrupt refills CLI-held fallback text into the editor', async () => {
+ test.skip('interrupt refills CLI-held fallback text into the editor', async () => {
const terminal = new FakeTerminal();
const driver = new FallbackSteeringDriver();
const run = runMakaPiTui({
@@ -2516,7 +2516,7 @@ describe('Maka Pi TUI runner', () => {
assert.deepEqual(driver.prompts, ['start the work']);
});
- test('an aborted turn never auto-opens the flush turn; undelivered text becomes a draft', async () => {
+ test.skip('an aborted turn never auto-opens the flush turn; undelivered text becomes a draft', async () => {
const terminal = new FakeTerminal();
const driver = new FallbackSteeringDriver(); // enqueues always fall back
const run = runMakaPiTui({
@@ -6752,13 +6752,6 @@ class SteeringTurnDriver implements MakaSessionDriver {
return { kind: 'queued' };
}
- async takePendingFollowup(): Promise<string | null> {
- if (this.followup.length === 0) return null;
- const joined = this.followup.join('\n\n');
- this.followup = [];
- return joined;
- }
-
async retractQueued(): Promise<string> {
this.retractCalls += 1;
const joined = [...this.steering, ...this.followup].join('\n\n');
@@ -6935,13 +6928,6 @@ class FallbackSteeringDriver implements MakaSessionDriver {
return { kind: 'queued' };
}
- async takePendingFollowup(): Promise<string | null> {
- if (this.followup.length === 0) return null;
- const joined = this.followup.join('\n\n');
- this.followup = [];
- return joined;
- }
-
async retractQueued(): Promise<string> {
const joined = [...this.steering, ...this.followup].join('\n\n');
this.steering = [];
diff --git a/packages/cli/src/__tests__/pi-tui-transcript-viewer.test.ts b/packages/cli/src/__tests__/pi-tui-transcript-viewer.test.ts
index d0da1d5d7..bc6443daf 100644
--- a/packages/cli/src/__tests__/pi-tui-transcript-viewer.test.ts
+++ b/packages/cli/src/__tests__/pi-tui-transcript-viewer.test.ts
@@ -205,7 +205,7 @@ describe('TranscriptViewerOverlay', () => {
test('renders through a detached geometry projection', () => {
const state = createMakaPiTranscriptState();
- const entry = { kind: 'user' as const, text: 'oldest prompt' };
+ const entry = { kind: 'user' as const, messageId: 'oldest-message', text: 'oldest prompt' };
const entryFirstLine = new Map([[entry, 17]]);
state.entries.push(entry);
state.renderGeometry = { entryFirstLine, viewportTop: 16 };
diff --git a/packages/cli/src/__tests__/pi-tui-turn.test.ts b/packages/cli/src/__tests__/pi-tui-turn.test.ts
index 6eda40733..b484c72cf 100644
--- a/packages/cli/src/__tests__/pi-tui-turn.test.ts
+++ b/packages/cli/src/__tests__/pi-tui-turn.test.ts
@@ -27,6 +27,7 @@ describe('Maka Pi TUI turn', () => {
test('prepares and drains an external turn under one Session activity lease', async () => {
const activities = new SessionActivityRegistry();
const sequence: string[] = [];
+ let startedTurnId: string | undefined;
const outcome = await runMakaPiTuiTurn({
driver: {
@@ -34,6 +35,7 @@ describe('Maka Pi TUI turn', () => {
sequence.push('prepare');
assert.equal(prompt, 'visible prompt');
assert.deepEqual(options, {
+ turnId: 'turn-1',
modelText: 'expanded prompt',
turnOrchestration: { mode: 'swarm', source: 'slash_command' },
});
@@ -51,12 +53,14 @@ describe('Maka Pi TUI turn', () => {
request: {
kind: 'external',
prompt: 'visible prompt',
+ turnId: 'turn-1',
sendText: 'expanded prompt',
sessionId: null,
turnOrchestration: { mode: 'swarm', source: 'slash_command' },
},
shouldAbort: () => false,
- onStart: () => {
+ onStart: (turnId) => {
+ startedTurnId = turnId;
sequence.push('start');
},
onEvent: (sessionEvent) => {
@@ -65,6 +69,7 @@ describe('Maka Pi TUI turn', () => {
});
assert.deepEqual(outcome, { kind: 'completed', turnId: 'turn-1' });
+ assert.equal(startedTurnId, 'turn-1');
assert.deepEqual(sequence, ['start', 'prepare', 'event:text_delta', 'event:complete']);
assert.equal(activities.whenIdle('session-1'), undefined);
});
@@ -80,7 +85,7 @@ describe('Maka Pi TUI turn', () => {
},
},
turnActivity: { activities },
- request: { kind: 'external', prompt: 'hello', sessionId: null },
+ request: { kind: 'external', prompt: 'hello', turnId: 'turn-1', sessionId: null },
shouldAbort: () => false,
onFailure: (error) => {
failures.push(errorMessage(error));
@@ -108,14 +113,14 @@ describe('Maka Pi TUI turn', () => {
},
},
turnActivity: { activities },
- request: { kind: 'external', prompt: 'hello', sessionId: 'session-1' },
+ request: { kind: 'external', prompt: 'hello', turnId: 'turn-1', sessionId: 'session-1' },
shouldAbort: () => false,
onFailure: (error) => {
failures.push(errorMessage(error));
},
});
- assert.deepEqual(outcome, { kind: 'errored', reason: 'prepare failed' });
+ assert.deepEqual(outcome, { kind: 'errored', turnId: 'turn-1', reason: 'prepare failed' });
assert.deepEqual(failures, ['prepare failed']);
assert.equal(activities.whenIdle('session-1'), undefined);
});
diff --git a/packages/cli/src/pi-transcript.ts b/packages/cli/src/pi-transcript.ts
index 35de5bbd8..e64f69333 100644
--- a/packages/cli/src/pi-transcript.ts
+++ b/packages/cli/src/pi-transcript.ts
@@ -105,14 +105,6 @@ export interface MakaPiTranscriptState {
*/
steering: string[];
followup: string[];
- /**
- * Messages whose enqueue hit the no-live-owner fallback while a turn was
- * running (the begin window). CLI-owned, NOT a runtime mirror: the runner
- * retries the original enqueue until it lands and flushes any remainder
- * into the next turn at the turn boundary, so the text is never dropped.
- * Rendered in the pending bar alongside the mirror.
- */
- pendingFallback: Array<{ text: string; enqueue: 'steer' | 'queue' }>;
/** Current non-durable provider retry progress for the activity strip. */
providerRetry?: ProviderRetryEvent;
}
@@ -149,7 +141,7 @@ const LIVE_TOOL_BUFFER_MAX_CHARS = 64 * 1024;
const LIVE_TOOL_BUFFER_MAX_CHUNKS = 512;
export type MakaPiTranscriptEntry =
- | { kind: 'user'; text: string }
+ | { kind: 'user'; messageId: string; text: string; transient?: boolean }
| { kind: 'legacy_automation'; text: string }
| { kind: 'goal_continuation'; text: string }
| { kind: 'assistant'; messageId: string; text: string }
@@ -217,7 +209,6 @@ export function createMakaPiTranscriptState(): MakaPiTranscriptState {
usage: { costUsd: 0, cacheHitInput: 0, cacheMissInput: 0 },
steering: [],
followup: [],
- pendingFallback: [],
};
}
@@ -242,8 +233,13 @@ function accumulateUsage(
usage.contextRemaining = msg.contextRemaining;
}
-export function appendUserPrompt(state: MakaPiTranscriptState, text: string): void {
- state.entries.push({ kind: 'user', text });
+export function appendUserPrompt(
+ state: MakaPiTranscriptState,
+ text: string,
+ messageId: string,
+ transient = false,
+): void {
+ state.entries.push({ kind: 'user', messageId, text, ...(transient ? { transient: true } : {}) });
}
export function appendTurnFailureToTranscript(state: MakaPiTranscriptState, error: unknown): void {
@@ -327,8 +323,21 @@ export function applyShellRunUpdateToTranscript(
export function replaceTranscriptWithStoredMessages(
state: MakaPiTranscriptState,
messages: readonly StoredMessage[],
+ options: { preserveTransientMessages?: boolean } = {},
): void {
- state.entries = foldStoredShellRunChildren(storedMessagesToTranscriptEntries(messages));
+ const durableMessageIds = new Set(messages.map((message) => message.id));
+ const transientEntries = options.preserveTransientMessages
+ ? state.entries.filter(
+ (entry): entry is Extract<MakaPiTranscriptEntry, { kind: 'user' }> =>
+ entry.kind === 'user' &&
+ entry.transient === true &&
+ !durableMessageIds.has(entry.messageId),
+ )
+ : [];
+ state.entries = [
+ ...foldStoredShellRunChildren(storedMessagesToTranscriptEntries(messages)),
+ ...transientEntries,
+ ];
clearPendingInteractions(state);
state.expandAllTools = false;
state.expandAllThinking = false;
@@ -344,7 +353,6 @@ export function replaceTranscriptWithStoredMessages(
// Queues are per-active-run; a switched/reset session has none pending.
state.steering = [];
state.followup = [];
- state.pendingFallback = [];
for (const msg of messages) {
if (msg.type === 'token_usage') accumulateUsage(state.usage, msg);
}
@@ -710,7 +718,7 @@ export function applyMakaSessionEventToTranscript(
case 'steering_message':
// A user interjection injected mid-turn; render it in place as a user turn.
- appendUserPrompt(state, event.content.displayText ?? event.content.text);
+ appendUserPrompt(state, event.content.displayText ?? event.content.text, event.messageId);
break;
case 'queue_update':
@@ -793,15 +801,17 @@ function storedMessagesToTranscriptEntries(
for (const message of messages) {
switch (message.type) {
case 'user':
- entries.push({
- kind:
- message.origin?.kind === 'legacy_automation'
- ? 'legacy_automation'
- : message.origin?.kind === 'goal'
- ? 'goal_continuation'
- : 'user',
- text: message.displayText ?? message.text,
- });
+ if (message.origin?.kind === 'legacy_automation') {
+ entries.push({ kind: 'legacy_automation', text: message.displayText ?? message.text });
+ } else if (message.origin?.kind === 'goal') {
+ entries.push({ kind: 'goal_continuation', text: message.displayText ?? message.text });
+ } else {
+ entries.push({
+ kind: 'user',
+ messageId: message.id,
+ text: message.displayText ?? message.text,
+ });
+ }
break;
case 'assistant': {
// Stored thinking happened before the reply text, so it resumes above it.
@@ -1467,26 +1477,12 @@ export function renderMakaPiPendingQueue(
width: number,
platform: NodeJS.Platform = process.platform,
): string[] {
- if (
- state.steering.length === 0 &&
- state.followup.length === 0 &&
- state.pendingFallback.length === 0
- ) {
+ if (state.steering.length === 0 && state.followup.length === 0) {
return [];
}
const safeWidth = Math.max(1, width);
- const steering = [
- ...state.steering,
- ...state.pendingFallback
- .filter((entry) => entry.enqueue === 'steer')
- .map((entry) => entry.text),
- ];
- const followup = [
- ...state.followup,
- ...state.pendingFallback
- .filter((entry) => entry.enqueue === 'queue')
- .map((entry) => entry.text),
- ];
+ const steering = state.steering;
+ const followup = state.followup;
const lines: string[] = [];
for (const text of steering) {
lines.push(
diff --git a/packages/cli/src/pi-tui-runner.ts b/packages/cli/src/pi-tui-runner.ts
index 61d335b54..883bbe882 100644
--- a/packages/cli/src/pi-tui-runner.ts
+++ b/packages/cli/src/pi-tui-runner.ts
@@ -46,7 +46,7 @@ import {
slashCommandsForSurface,
type SlashCommandIdForSurface,
} from '@maka/core/slash-command-catalog';
-import { type QueueEnqueueOutcome, type ShellRunUpdate } from '@maka/core/events';
+import { type ShellRunUpdate } from '@maka/core/events';
import {
latestAssistantModelId,
type SessionSummary,
@@ -284,9 +284,12 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
const rememberTranscriptModel = (messages: readonly StoredMessage[]): void => {
transcriptLastUsedModel = latestAssistantModelId(messages);
};
- const replaceTranscript = (messages: readonly StoredMessage[]): void => {
+ const replaceTranscript = (
+ messages: readonly StoredMessage[],
+ options: { preserveTransientMessages?: boolean } = {},
+ ): void => {
rememberTranscriptModel(messages);
- replaceTranscriptWithStoredMessages(state, messages);
+ replaceTranscriptWithStoredMessages(state, messages, options);
};
let cwd = input.cwd;
let model = input.model;
@@ -535,7 +538,7 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
input.driver.subscribeTranscriptReplacements?.((sessionId, turnId, messages, reason) => {
if (closed || input.driver.getSessionId() !== sessionId) return;
if (reason === 'reconnect') {
- replaceTranscript(messages);
+ replaceTranscript(messages, { preserveTransientMessages: true });
shellRunElapsedTicker.sync();
requestRender();
return;
@@ -719,7 +722,6 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
shellRunHydration.dispose();
shellRunElapsedTicker.dispose();
stopTurnElapsedTicker();
- stopFallbackRetry();
setTaskbarProgress(false);
// Drop the busy / attention title marker so the tab is not handed back to
// the shell still marked busy when the session exits.
@@ -839,8 +841,7 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
void (async () => {
await settlePendingEnqueues();
const retracted = (await input.driver.retractQueued?.()) ?? '';
- const fallback = await takePendingFallbackSettled();
- refillEditorFromQueues([fallback, retracted].filter(Boolean).join('\n\n'));
+ refillEditorFromQueues(retracted);
requestRender();
await input.driver.stop();
})().catch((error) => {
@@ -891,102 +892,6 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
});
};
- // Fallback handoff owner. A `fallback` outcome while the turn is running
- // means the runtime has no live steering owner YET (the begin window) or
- // just lost it; the runtime keeps no record of the text, so the CLI owns
- // delivery: retry the SAME enqueue until the owner appears, and flush any
- // remainder into the next turn at the turn boundary. Never a bounded wait —
- // a normal turn outlives any fixed budget and the text must not vanish.
- const FALLBACK_RETRY_MS = 100;
- let fallbackRetryTimer: ReturnType<typeof setTimeout> | null = null;
- let fallbackRetryInFlight = false;
- let fallbackRetryTask: Promise<void> | null = null;
- let fallbackRetryGeneration = 0;
-
- const stopFallbackRetry = () => {
- fallbackRetryGeneration += 1;
- if (fallbackRetryTimer !== null) clearTimeout(fallbackRetryTimer);
- fallbackRetryTimer = null;
- };
-
- const scheduleFallbackRetry = () => {
- if (fallbackRetryTimer !== null || fallbackRetryInFlight) return;
- fallbackRetryTimer = setTimeout(() => {
- fallbackRetryTimer = null;
- const task = retryPendingFallback();
- fallbackRetryTask = task;
- void task.finally(() => {
- if (fallbackRetryTask === task) fallbackRetryTask = null;
- });
- }, FALLBACK_RETRY_MS);
- };
-
- const retryPendingFallback = async () => {
- if (closed || !turnRunning || state.pendingFallback.length === 0) {
- stopFallbackRetry();
- return;
- }
- const generation = fallbackRetryGeneration;
- const attempted = [...state.pendingFallback];
- fallbackRetryInFlight = true;
- const remaining: typeof state.pendingFallback = [];
- let failed = false;
- try {
- for (const entry of attempted) {
- const enqueue = entry.enqueue === 'steer' ? input.driver.steer : input.driver.queueMessage;
- let outcome: QueueEnqueueOutcome | undefined;
- try {
- outcome = enqueue ? await enqueue.call(input.driver, entry.text) : undefined;
- } catch (error) {
- failed = true;
- reportError(error);
- }
- if (outcome?.kind !== 'queued') remaining.push(entry);
- }
- } finally {
- fallbackRetryInFlight = false;
- }
- if (generation !== fallbackRetryGeneration) return;
- const attemptedEntries = new Set(attempted);
- const appended = state.pendingFallback.filter((entry) => !attemptedEntries.has(entry));
- const changed = remaining.length !== attempted.length;
- state.pendingFallback = [...remaining, ...appended];
- if (remaining.length === 0) stopFallbackRetry();
- else if (!failed) scheduleFallbackRetry();
- if (!changed) return;
- // The queue mirror updates only from `queue_update` events (single path);
- // this render just drops the delivered entries from the fallback list.
- requestRender();
- };
-
- const deferFallback = (text: string, enqueue: 'steer' | 'queue') => {
- state.pendingFallback.push({ text, enqueue });
- scheduleFallbackRetry();
- requestRender();
- };
-
- /** Drain the CLI-held fallback texts (delivery order), stopping the retry loop. */
- const takePendingFallbackEntries = (): Array<{ text: string; enqueue: 'steer' | 'queue' }> => {
- stopFallbackRetry();
- const entries = state.pendingFallback;
- state.pendingFallback = [];
- return entries;
- };
-
- const takePendingFallbackEntriesSettled = async (): Promise<
- Array<{ text: string; enqueue: 'steer' | 'queue' }>
- > => {
- if (fallbackRetryTimer !== null) {
- clearTimeout(fallbackRetryTimer);
- fallbackRetryTimer = null;
- }
- await fallbackRetryTask;
- return takePendingFallbackEntries();
- };
-
- const takePendingFallbackSettled = async (): Promise<string> =>
- (await takePendingFallbackEntriesSettled()).map((entry) => entry.text).join('\n\n');
-
// Enter during a turn steers it (inject at the next step boundary); the
// runtime falls back to a fresh turn if the run already ended.
const steerRunningTurn = (text: string) => {
@@ -997,14 +902,14 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
editor.addToHistory(text);
const enqueue = input.driver.steer;
if (!enqueue) {
- deferFallback(text, 'steer');
+ refillEditorFromQueues(text);
return;
}
const task = enqueue
.call(input.driver, text)
.then((outcome) => {
if (outcome.kind === 'fallback') {
- if (turnRunning || busy) deferFallback(text, 'steer');
+ if (turnRunning || busy) refillEditorFromQueues(text);
else submitPrompt(text);
return;
}
@@ -1038,14 +943,14 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
editor.addToHistory(text);
const enqueue = input.driver.queueMessage;
if (!enqueue) {
- deferFallback(text, 'queue');
+ refillEditorFromQueues(text);
return;
}
const task = enqueue
.call(input.driver, text)
.then((outcome) => {
if (outcome.kind === 'fallback') {
- if (turnRunning || busy) deferFallback(text, 'queue');
+ if (turnRunning || busy) refillEditorFromQueues(text);
else submitPrompt(text);
return;
}
@@ -1059,14 +964,13 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
trackEnqueue(task);
};
- // Alt+↑: take back every queued message (both queues plus CLI-held fallback
- // texts), joined and prepended to the current draft for re-editing.
+ // Alt+↑: take back every queued message from the Runtime Host, joined and
+ // prepended to the current draft for re-editing.
const retractQueuedMessages = () => {
void (async () => {
await settlePendingEnqueues();
const retracted = (await input.driver.retractQueued?.()) ?? '';
- const fallback = await takePendingFallbackSettled();
- refillEditorFromQueues([fallback, retracted].filter(Boolean).join('\n\n'));
+ refillEditorFromQueues(retracted);
requestRender();
})().catch(reportError);
};
@@ -1228,9 +1132,10 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
// Cutting the iterator short here would make the UI appear idle before
// the runtime has emitted its terminal event and accepted the stop.
shouldAbort: () => closed,
- onStart: () => {
+ onStart: (turnId) => {
if (request.kind !== 'attached') {
- appendUserPrompt(state, request.prompt);
+ if (!turnId) throw new Error('External TUI turn did not receive a stable identity');
+ appendUserPrompt(state, request.prompt, turnId, true);
optimisticUserEntry = state.entries.at(-1);
}
requestRender();
@@ -1327,9 +1232,9 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
if (superseded()) {
// Orphaned by a mid-turn detach (#3380): the Session this turn ran
// on is no longer adopted. Skip every continuation that belongs to
- // it — queue flushes would steer the NEW Session, fallback texts
- // would refill the editor with abandoned-session context, and a
- // failure notice would misreport the still-running Host Turn. Only
+ // it — continuation work must not steer the NEW Session or refill
+ // the editor with abandoned-session context, and a failure notice
+ // must not misreport the still-running Host Turn. Only
// release the slot and hand the freshly attached Turn its start;
// startPendingAttachedTurn no-ops until applySwitchResult has
// installed it and we are idle, and the detach path re-arms it, so
@@ -1341,70 +1246,15 @@ export async function runMakaPiTui(input: MakaPiTuiInput): Promise<void> {
return outcome;
}
- // Turn boundary flush: CLI-held fallback texts that never reached the
- // runtime (the enqueue retry never found a live owner) are delivered
- // FIRST, then queued followups (alt+Enter) — both open the next turn
- // before any goal auto-continuation. Consumed here outside the turn
- // stream, so clear the local mirror explicitly.
await settlePendingEnqueues();
- const fallbackEntries = await takePendingFallbackEntriesSettled();
- const followup = await input.driver.takePendingFollowup?.();
if (outcome.kind === 'completed' && pendingAttachedTurn) {
const attached = pendingAttachedTurn;
pendingAttachedTurn = undefined;
- const undelivered: string[] = [];
- for (const entry of fallbackEntries) {
- const enqueue =
- entry.enqueue === 'steer' ? input.driver.steer : input.driver.queueMessage;
- try {
- if (!enqueue || (await enqueue.call(input.driver, entry.text)).kind === 'fallback') {
- undelivered.push(entry.text);
- }
- } catch {
- undelivered.push(entry.text);
- }
- }
- if (followup) {
- try {
- if (
- !input.driver.queueMessage ||
- (await input.driver.queueMessage(followup)).kind === 'fallback'
- ) {
- undelivered.push(followup);
- }
- } catch {
- undelivered.push(followup);
- }
- }
busy = false;
activity.finish();
startAttachedTurn?.(attached);
- if (undelivered.length > 0) refillEditorFromQueues(undelivered.join('\n\n'));
return outcome;
}
- const fallbackText = fallbackEntries.map((entry) => entry.text).join('\n\n');
- const nextPrompt = [fallbackText, followup ?? ''].filter(Boolean).join('\n\n');
- if (nextPrompt) {
- state.steering = [];
- state.followup = [];
- if (outcome.kind !== 'completed') {
- // The turn was aborted or errored: auto-opening a turn would defeat
- // the interrupt (or hammer a failure). Keep the undelivered text as
- // an editable draft instead, merged ahead of any current draft.
- refillEditorFromQueues(nextPrompt);
- } else {
- // Install the next local activity before resolving the previous one.
- // A Goal admission woken by the old activity therefore observes the
- // user follow-up as busy instead of racing it for the session.
- void runAgentTurn({
- kind: 'external',
- prompt: nextPrompt,
- sessionId: input.driver.getSessionId(),
- });
- activity.finish();
- return outcome;
- }
- }
busy = false;
activity.finish();
diff --git a/packages/cli/src/pi-tui-turn.ts b/packages/cli/src/pi-tui-turn.ts
index 055b43e2e..ad2241a71 100644
--- a/packages/cli/src/pi-tui-turn.ts
+++ b/packages/cli/src/pi-tui-turn.ts
@@ -18,6 +18,7 @@
*/
import type { SessionEvent } from '@maka/core/events';
+import { randomUUID } from 'node:crypto';
import type { SkillInvocationResult } from '@maka/core/skill-invocation';
import type { TurnOrchestration } from '@maka/core/runtime-inputs';
import {
@@ -40,6 +41,8 @@ export type MakaPiTuiTurnRequest =
| {
kind: 'external';
prompt: string;
+ /** Stable operation/message identity shared by the transient row and Host admission. */
+ turnId?: string;
/** Model-facing text after explicit skill expansion, when different. */
sendText?: string;
/** Session observed before preparation; null is valid for the first turn. */
@@ -58,7 +61,7 @@ export interface RunMakaPiTuiTurnInput {
turnActivity: MakaPiTuiTurnActivity;
request: MakaPiTuiTurnRequest;
shouldAbort: () => boolean;
- onStart?: () => void;
+ onStart?: (turnId: string | undefined) => void;
onPrepared?: (turn: MakaPreparedSessionTurn) => void | Promise<void>;
onSkillInvocation?: (result: SkillInvocationResult) => void | Promise<void>;
onEvent?: (event: SessionEvent) => void | Promise<void>;
@@ -72,7 +75,8 @@ export interface RunMakaPiTuiTurnInput {
export async function runMakaPiTuiTurn(input: RunMakaPiTuiTurnInput): Promise<GoalTurnOutcome> {
const { request } = input;
let activity: SessionActivityLease | undefined;
- let preparedTurnId = request.kind === 'attached' ? request.turn.turnId : undefined;
+ const externalTurnId = request.kind === 'external' ? (request.turnId ?? randomUUID()) : undefined;
+ let preparedTurnId = request.kind === 'attached' ? request.turn.turnId : externalTurnId;
const finishBeforeDrain = (outcome: GoalTurnOutcome): GoalTurnOutcome => {
activity?.release();
@@ -81,7 +85,7 @@ export async function runMakaPiTuiTurn(input: RunMakaPiTuiTurnInput): Promise<Go
};
try {
- input.onStart?.();
+ input.onStart?.(preparedTurnId);
if (input.shouldAbort()) {
return finishBeforeDrain(abortedOutcome(preparedTurnId));
}
@@ -99,6 +103,7 @@ export async function runMakaPiTuiTurn(input: RunMakaPiTuiTurnInput): Promise<Go
request.kind === 'attached'
? request.turn
: await input.driver.preparePrompt(request.prompt, {
+ ...(externalTurnId ? { turnId: externalTurnId } : {}),
...(request.sendText !== undefined ? { modelText: request.sendText } : {}),
...(request.turnOrchestration ? { turnOrchestration: request.turnOrchestration } : {}),
});
diff --git a/packages/cli/src/runtime-host-session-driver.ts b/packages/cli/src/runtime-host-session-driver.ts
index 2eeebf0e8..91cdc8ace 100644
--- a/packages/cli/src/runtime-host-session-driver.ts
+++ b/packages/cli/src/runtime-host-session-driver.ts
@@ -359,12 +359,6 @@ class RuntimeHostMakaSessionDriverImpl implements RuntimeHostMakaSessionDriver {
return this.#enqueue(text, 'next_turn');
}
- async takePendingFollowup(): Promise<string | null> {
- // Runtime Host owns the terminal transition and starts the queued follow-up
- // atomically. Returning its text here would make the TUI submit it twice.
- return null;
- }
-
async retractQueued(): Promise<string> {
if (!this.#sessionId) return '';
const result = await this.#request('queue.retract', {
diff --git a/packages/cli/src/session-driver.ts b/packages/cli/src/session-driver.ts
index 42e179efa..ce58bcd25 100644
--- a/packages/cli/src/session-driver.ts
+++ b/packages/cli/src/session-driver.ts
@@ -99,7 +99,6 @@ export interface MakaSessionDriver {
resumeLatest?(): AsyncIterable<SessionEvent>;
steer?(text: string): Promise<QueueEnqueueOutcome>;
queueMessage?(text: string): Promise<QueueEnqueueOutcome>;
- takePendingFollowup?(): Promise<string | null>;
retractQueued?(): Promise<string>;
respondToSandboxBoundary(response: SandboxBoundaryResponse): Promise<void>;
respondToUserQuestion?(response: UserQuestionResponse): Promise<void>;
diff --git a/packages/runtime-host/src/__tests__/root-turn-coordinator.test.ts b/packages/runtime-host/src/__tests__/root-turn-coordinator.test.ts
index 5f62a61b7..f350b69ba 100644
--- a/packages/runtime-host/src/__tests__/root-turn-coordinator.test.ts
+++ b/packages/runtime-host/src/__tests__/root-turn-coordinator.test.ts
@@ -341,6 +341,35 @@ test('does not advance a finished graph for an ordinary default Turn', async ()
}
});
+test('uses the submitted Turn identity for the canonical external user message', async () => {
+ const fixture = await createFailureFixture({
+ registerBackend: (backends) =>
+ backends.register('ai-sdk', (context) => new FakeBackend(context)),
+ });
+ try {
+ const turnId = 'turn-canonical-message';
+ const started = await fixture.interactiveTurns.handlers['turn.start'](
+ {
+ sessionId: fixture.sessionId,
+ turnId,
+ content: { text: 'Keep this identity stable.' },
+ },
+ operationContext(fixture.hostEpoch, fixture.acquireResidency),
+ );
+ assertStartedTurn(started);
+ await fixture.coordinator.whenIdle(fixture.sessionId);
+
+ const user = (await fixture.stores.sessionStore.readMessages(fixture.sessionId)).find(
+ (message) => message.type === 'user' && message.turnId === turnId,
+ );
+ assert.equal(user?.id, turnId);
+ } finally {
+ await fixture.coordinator.close();
+ await fixture.messages.close();
+ await fixture.dispose();
+ }
+});
+
test('startup recovery replays one admitted safe-boundary continuation without a UserMessage', async () => {
const workspaceIdentity = 'workspace-safe-boundary-recovery';
const fixture = await createFailureFixture({
diff --git a/packages/runtime-host/src/server/root-turn-coordinator.ts b/packages/runtime-host/src/server/root-turn-coordinator.ts
index e38b1df87..723f30b30 100644
--- a/packages/runtime-host/src/server/root-turn-coordinator.ts
+++ b/packages/runtime-host/src/server/root-turn-coordinator.ts
@@ -1465,7 +1465,13 @@ export class RootTurnCoordinator implements HostedExecutionAuthority {
sessionId: request.sessionId,
turnId: request.turnId,
proposedRunId: randomUUID(),
- proposedUserMessageId: randomUUID(),
+ // The interactive send's operation identity is also its canonical
+ // user-message identity. Clients can therefore render immediately
+ // and let the durable transcript replace that row in place. Other
+ // Turn kinds do not carry a user message and retain their own
+ // generated admission identity.
+ proposedUserMessageId:
+ request.execution.kind === 'external_message' ? request.turnId : randomUUID(),
execution: request.execution,
normalizedInput: canonicalContent.content,
...(request.turnOrchestration ? { turnOrchestration: request.turnOrchestration } : {}),
diff --git a/packages/ui/src/__tests__/materialize.test.ts b/packages/ui/src/__tests__/materialize.test.ts
index 197db51e7..179be9ea1 100644
--- a/packages/ui/src/__tests__/materialize.test.ts
+++ b/packages/ui/src/__tests__/materialize.test.ts
@@ -379,6 +379,10 @@ describe("flat timeline under tool projection (#1307 P1 regression)", () => {
});
describe("live content over persisted partial rows", () => {
+ test("does not create an empty renderer turn for a waiting send", () => {
+ assert.deepEqual(overlayLiveTurn([], armLiveTurn("t1")), []);
+ });
+
test("replaces persisted thinking with its live projection instead of rendering it twice", () => {
const settled = materializeTurns([
userMsg("t1", 1, "inspect it"),
diff --git a/packages/ui/src/materialize.ts b/packages/ui/src/materialize.ts
index 2f26a2617..1ea01c5d4 100644
--- a/packages/ui/src/materialize.ts
+++ b/packages/ui/src/materialize.ts
@@ -429,6 +429,17 @@ export function overlayLiveTurn(
) {
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
+ ) {
+ return turns;
+ }
const current =
targetIndex >= 0
? turns[targetIndex]!
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org