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/24 04:44:27 UTC
(maka) 03/20: refactor(cli): remove message fallback ownership
This is an automated email from the ASF dual-hosted git repository.
Astro-Han pushed a commit to branch fix/steering-durable-admission
in repository https://gitbox.apache.org/repos/asf/maka.git
commit 3b244b31fdd54df99d493f4613ea8399e631449c
Author: AstroHan <le...@outlook.com>
AuthorDate: Sun Aug 23 22:09:39 2026 +0800
refactor(cli): remove message fallback ownership
Generated-by: Maka
---
packages/cli/src/__tests__/pi-transcript.test.ts | 2 -
packages/cli/src/__tests__/pi-tui-runner.test.ts | 442 -----------------------
packages/cli/src/pi-transcript.ts | 27 +-
packages/cli/src/pi-tui-runner.ts | 194 +---------
packages/cli/src/runtime-host-session-driver.ts | 16 +-
packages/cli/src/session-driver.ts | 1 -
6 files changed, 22 insertions(+), 660 deletions(-)
diff --git a/packages/cli/src/__tests__/pi-transcript.test.ts b/packages/cli/src/__tests__/pi-transcript.test.ts
index b57e43775..53f450611 100644
--- a/packages/cli/src/__tests__/pi-transcript.test.ts
+++ b/packages/cli/src/__tests__/pi-transcript.test.ts
@@ -373,7 +373,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 +404,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');
});
diff --git a/packages/cli/src/__tests__/pi-tui-runner.test.ts b/packages/cli/src/__tests__/pi-tui-runner.test.ts
index 930513d66..c8f17a76a 100644
--- a/packages/cli/src/__tests__/pi-tui-runner.test.ts
+++ b/packages/cli/src/__tests__/pi-tui-runner.test.ts
@@ -2200,199 +2200,6 @@ 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 () => {
- const terminal = new FakeTerminal();
- // Every enqueue reports `fallback` — the runtime never has a live owner.
- const driver = new FallbackSteeringDriver();
- const run = runMakaPiTui({
- title: 'Maka',
- driver,
- cwd: '/repo',
- model: 'm',
- connectionSlug: 'c',
- permissionMode: 'bypass',
- terminal,
- });
-
- terminal.input('start the work');
- terminal.input('\r');
- await waitFor(() => terminal.progressStates.at(-1) === true);
-
- terminal.input('second thought');
- terminal.input('\r'); // steer → fallback → CLI-held pending
- terminal.input('and afterwards');
- terminal.input('\x1b\r'); // Alt+Enter → fallback → CLI-held pending
- await waitFor(() => {
- const screen = plainTerminalOutput(terminal.screenOutput());
- return (
- screen.includes('Steering: second thought') && screen.includes('Queued: and afterwards')
- );
- });
-
- // The old bounded poll gave up after ~2s of busy (about 20 attempts at the
- // 100ms retry cadence) and silently dropped the text. Waiting for the
- // driver to observe the retries crossing that budget — instead of guessing
- // elapsed time — proves the CLI is still retrying under any scheduler load.
- await waitForUpTo(() => driver.steerAttempts > 22 && driver.queueAttempts > 22, 30_000);
- const screen = plainTerminalOutput(terminal.screenOutput());
- assert.equal(screen.includes('Steering: second thought'), true);
- assert.equal(screen.includes('Queued: and afterwards'), true);
- assert.deepEqual(driver.prompts, ['start the work']);
-
- // The turn boundary flushes the undelivered texts into the next turn.
- driver.endTurn();
- await waitFor(() => driver.prompts.length === 2);
- assert.equal(driver.prompts[1], 'second thought\n\nand afterwards');
-
- await waitForUpTo(() => driver.parked, 1_000);
- driver.endTurn();
- await waitFor(() => terminal.progressStates.at(-1) === false);
- terminal.input('/exit');
- terminal.input('\r');
- await run;
- });
-
- test('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
- const run = runMakaPiTui({
- title: 'Maka',
- driver,
- cwd: '/repo',
- model: 'm',
- connectionSlug: 'c',
- permissionMode: 'bypass',
- terminal,
- });
-
- terminal.input('start the work');
- terminal.input('\r');
- await waitFor(() => terminal.progressStates.at(-1) === true);
-
- terminal.input('late owner');
- terminal.input('\r'); // steer → fallback, retried until it lands
- await waitForUpTo(() => driver.steered.includes('late owner'), 1_000);
- // Landed as a steer of the RUNNING turn — no fresh turn was opened.
- assert.deepEqual(driver.prompts, ['start the work']);
- await waitFor(() =>
- plainTerminalOutput(terminal.screenOutput()).includes('Steering: late owner'),
- );
-
- driver.endTurn();
- await waitFor(() => terminal.progressStates.at(-1) === false);
- // Nothing left to flush: the text was delivered mid-turn, not re-queued.
- assert.deepEqual(driver.prompts, ['start the work']);
- terminal.input('/exit');
- terminal.input('\r');
- await run;
- });
-
- test('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({
- title: 'Maka',
- driver,
- cwd: '/repo',
- model: 'm',
- connectionSlug: 'c',
- permissionMode: 'bypass',
- terminal,
- });
-
- terminal.input('start');
- terminal.input('\r');
- await waitFor(() => terminal.progressStates.at(-1) === true);
- await waitForUpTo(() => driver.parked, 1_000);
- terminal.input('late admission');
- terminal.input('\r');
- await waitFor(() => driver.steerCalls === 1);
-
- driver.endTurn();
- await waitFor(() => driver.completedTurns === 1);
- assert.deepEqual(driver.prompts, ['start']);
- driver.releaseAdmission({ kind: 'fallback' });
- await waitForUpTo(() => driver.prompts.length === 2, 1_000);
- assert.equal(driver.prompts[1], 'late admission');
-
- await waitForUpTo(() => driver.parked, 1_000);
- driver.endTurn();
- await waitFor(() => terminal.progressStates.at(-1) === false);
- terminal.input('/exit');
- terminal.input('\r');
- await run;
- });
-
- test('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({
- title: 'Maka',
- driver,
- cwd: '/repo',
- model: 'm',
- connectionSlug: 'c',
- permissionMode: 'bypass',
- terminal,
- });
-
- terminal.input('start');
- terminal.input('\r');
- await waitFor(() => terminal.progressStates.at(-1) === true);
- terminal.input('lands on retry');
- terminal.input('\r');
- await waitForUpTo(() => driver.steerCalls === 2, 1_000);
-
- driver.endTurn();
- driver.releaseRetry();
- await waitFor(() => terminal.progressStates.at(-1) === false);
- assert.deepEqual(driver.prompts, ['start']);
- assert.deepEqual(driver.delivered, ['lands on retry']);
-
- terminal.input('/exit');
- terminal.input('\r');
- await run;
- });
-
- test('interrupt refills CLI-held fallback text into the editor', async () => {
- const terminal = new FakeTerminal();
- const driver = new FallbackSteeringDriver();
- const run = runMakaPiTui({
- title: 'Maka',
- driver,
- cwd: '/repo',
- model: 'm',
- connectionSlug: 'c',
- permissionMode: 'bypass',
- terminal,
- });
-
- terminal.input('start the work');
- terminal.input('\r');
- await waitFor(() => terminal.progressStates.at(-1) === true);
-
- terminal.input('rescue me');
- terminal.input('\r'); // steer → fallback → CLI-held pending
- await waitFor(() =>
- plainTerminalOutput(terminal.screenOutput()).includes('Steering: rescue me'),
- );
-
- terminal.input('\x1b');
- terminal.input('\x1b'); // interrupt
- await waitFor(() => terminal.progressStates.at(-1) === false);
- // The CLI-held text comes back for re-editing; the pending bar clears.
- await waitFor(() => {
- const screen = plainTerminalOutput(terminal.screenOutput());
- return screen.includes('rescue me') && !screen.includes('Steering: rescue me');
- });
-
- terminal.input('\x03'); // clear the refilled draft
- terminal.input('/exit');
- terminal.input('\r');
- await run;
- });
-
test('input during the interrupt convergence window stays in the editor and opens no turn', async () => {
const terminal = new FakeTerminal();
const driver = new SlowStopDriver(); // stop() returns but the turn keeps running
@@ -2439,49 +2246,6 @@ 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 () => {
- const terminal = new FakeTerminal();
- const driver = new FallbackSteeringDriver(); // enqueues always fall back
- const run = runMakaPiTui({
- title: 'Maka',
- driver,
- cwd: '/repo',
- model: 'm',
- connectionSlug: 'c',
- permissionMode: 'bypass',
- terminal,
- });
-
- terminal.input('start the work');
- terminal.input('\r');
- await waitFor(() => terminal.progressStates.at(-1) === true);
-
- terminal.input('next thing');
- terminal.input('\x1b\r'); // Alt+Enter → fallback → CLI-held pending
- await waitFor(() =>
- plainTerminalOutput(terminal.screenOutput()).includes('Queued: next thing'),
- );
-
- // The turn ends as ABORTED on its own (not via the CLI interrupt path):
- // the boundary flush must not open a turn the user just stopped.
- driver.abortNextTurn = true;
- driver.endTurn();
- await waitFor(() => terminal.progressStates.at(-1) === false);
- // The undelivered text is an editable draft, not a queued line.
- await waitFor(() => {
- const screen = plainTerminalOutput(terminal.screenOutput());
- return screen.includes('next thing') && !screen.includes('Queued: next thing');
- });
-
- terminal.input('\x03'); // clear the preserved draft
- terminal.input('/exit');
- terminal.input('\r');
- await run;
- // Anchored after close: a wrongly-opened flush turn would have landed in
- // prompts by the time the TUI has fully shut down.
- assert.deepEqual(driver.prompts, ['start the work']);
- });
-
test('exits on the second Ctrl-C during a control command', async () => {
const terminal = new FakeTerminal();
const driver = new DeferredControlDriver();
@@ -6732,212 +6496,6 @@ class SteeringTurnDriver implements MakaSessionDriver {
* first N calls (configurable, default forever) while the turn parks until
* `endTurn()` — the begin-window shape behind review finding N2.
*/
-class FallbackSteeringDriver implements MakaSessionDriver {
- readonly prompts: string[] = [];
- readonly steered: string[] = [];
- readonly queuedMessages: string[] = [];
- stopCalls = 0;
- completedTurns = 0;
- /** Enqueue calls that report `fallback` before the owner "appears". */
- steerFallbacks = Number.POSITIVE_INFINITY;
- queueFallbacks = Number.POSITIVE_INFINITY;
- /** Total enqueue attempts, including rejected ones — the observable retry count. */
- steerAttempts = 0;
- queueAttempts = 0;
- private steering: string[] = [];
- private followup: string[] = [];
- private pendingEvents: SessionEvent[] = [];
- private wakeTurn: (() => void) | null = null;
- private turnOpen = false;
- private turnEnded = false;
- private eventSeq = 0;
-
- get parked(): boolean {
- return this.turnOpen && !this.turnEnded;
- }
-
- async listSessions(): Promise<SessionSummary[]> {
- return [];
- }
-
- preparePrompt(
- prompt: string,
- options: MakaPreparePromptOptions = {},
- ): Promise<MakaPreparedSessionTurn> {
- this.prompts.push(options.modelText ?? prompt);
- const turnId = options.turnId ?? `turn-${this.prompts.length}`;
- return Promise.resolve({
- sessionId: this.getSessionId(),
- turnId,
- events: this.promptEvents(turnId),
- });
- }
-
- async *compactSession(): AsyncIterable<never> {}
-
- // Same single-path contract as the runtime: queue contents reach the CLI
- // only through `queue_update` events on the turn stream.
- private emitQueueUpdate(): void {
- this.eventSeq += 1;
- this.pendingEvents.push({
- type: 'queue_update',
- id: `queue-update-${this.eventSeq}`,
- turnId: `turn-${this.prompts.length}`,
- ts: this.eventSeq,
- steering: [...this.steering],
- followup: [...this.followup],
- });
- this.wakeTurn?.();
- this.wakeTurn = null;
- }
-
- async *promptEvents(turnId: string): AsyncIterable<SessionEvent> {
- this.turnOpen = true;
- this.turnEnded = false;
- for (;;) {
- while (this.pendingEvents.length > 0) yield this.pendingEvents.shift()!;
- if (this.turnEnded) break;
- await new Promise<void>((resolve) => {
- this.wakeTurn = resolve;
- });
- }
- this.turnOpen = false;
- if (this.abortNextTurn) {
- this.abortNextTurn = false;
- yield {
- type: 'abort',
- id: `abort-${this.prompts.length}`,
- turnId,
- ts: 1,
- reason: 'user_stop',
- };
- yield {
- type: 'complete',
- id: `complete-${this.prompts.length}`,
- turnId,
- ts: 2,
- stopReason: 'user_stop',
- };
- this.completedTurns += 1;
- return;
- }
- yield {
- type: 'complete',
- id: `complete-${this.prompts.length}`,
- turnId,
- ts: 1,
- stopReason: 'end_turn',
- };
- this.completedTurns += 1;
- }
-
- /** Next endTurn() finishes the turn as aborted instead of end_turn. */
- abortNextTurn = false;
-
- async steer(text: string): Promise<QueueEnqueueOutcome> {
- this.steerAttempts += 1;
- if (this.steerFallbacks > 0) {
- this.steerFallbacks -= 1;
- return { kind: 'fallback' };
- }
- this.steered.push(text);
- this.steering.push(text);
- this.emitQueueUpdate();
- return { kind: 'queued' };
- }
-
- async queueMessage(text: string): Promise<QueueEnqueueOutcome> {
- this.queueAttempts += 1;
- if (this.queueFallbacks > 0) {
- this.queueFallbacks -= 1;
- return { kind: 'fallback' };
- }
- this.queuedMessages.push(text);
- this.followup.push(text);
- this.emitQueueUpdate();
- 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 = [];
- this.followup = [];
- this.emitQueueUpdate();
- return joined;
- }
-
- endTurn(): void {
- this.turnEnded = true;
- this.wakeTurn?.();
- this.wakeTurn = null;
- }
-
- async stop(): Promise<void> {
- this.stopCalls += 1;
- this.steering = [];
- this.followup = [];
- this.endTurn();
- }
-
- async respondToSandboxBoundary(_response: SandboxBoundaryResponse): Promise<void> {}
- async renameSession(): Promise<void> {}
- async setModel(): Promise<void> {}
- async setPermissionMode(): Promise<void> {}
- async setThinkingLevel(): Promise<void> {}
- async switchSession(sessionId: string): Promise<MakaSessionSwitchResult> {
- return switchResult(fakeSessionSummary(sessionId));
- }
- async listRewindTargets(): Promise<RewindTarget[]> {
- return [];
- }
- async rewindToTurn(): Promise<MakaSessionRewindResult> {
- throw new Error('rewind not supported in this fake');
- }
- startNewSession(): void {}
- getSessionId(): string {
- return 'session-1';
- }
-}
-
-class DeferredAdmissionDriver extends FallbackSteeringDriver {
- steerCalls = 0;
- readonly #admission = deferred<QueueEnqueueOutcome>();
-
- override async steer(_text: string): Promise<QueueEnqueueOutcome> {
- this.steerCalls += 1;
- return this.#admission.promise;
- }
-
- releaseAdmission(outcome: QueueEnqueueOutcome): void {
- this.#admission.resolve(outcome);
- }
-}
-
-class DeferredRetryDriver extends FallbackSteeringDriver {
- steerCalls = 0;
- readonly delivered: string[] = [];
- readonly #retry = deferred<void>();
-
- override async steer(text: string): Promise<QueueEnqueueOutcome> {
- this.steerCalls += 1;
- if (this.steerCalls === 1) return { kind: 'fallback' };
- await this.#retry.promise;
- this.delivered.push(text);
- return { kind: 'queued' };
- }
-
- releaseRetry(): void {
- this.#retry.resolve();
- }
-}
-
class SlowStopDriver implements MakaSessionDriver {
stopCalls = 0;
readonly prompts: string[] = [];
diff --git a/packages/cli/src/pi-transcript.ts b/packages/cli/src/pi-transcript.ts
index 730ecc207..883440988 100644
--- a/packages/cli/src/pi-transcript.ts
+++ b/packages/cli/src/pi-transcript.ts
@@ -112,7 +112,6 @@ export interface MakaPiTranscriptState {
* 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;
}
@@ -217,7 +216,6 @@ export function createMakaPiTranscriptState(): MakaPiTranscriptState {
usage: { costUsd: 0, cacheHitInput: 0, cacheMissInput: 0 },
steering: [],
followup: [],
- pendingFallback: [],
};
}
@@ -344,7 +342,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);
}
@@ -1453,33 +1450,15 @@ export function renderMakaPiPendingQueue(
width: number,
platform: NodeJS.Platform = process.platform,
): string[] {
- if (
- state.steering.length === 0 &&
- state.followup.length === 0 &&
- state.pendingFallback.length === 0
- ) {
- return [];
- }
+ 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 lines: string[] = [];
- for (const text of steering) {
+ for (const text of state.steering) {
lines.push(
fitLine(`${ansi.accent('Steering:')} ${ansi.dim(firstLinePreview(text))}`, safeWidth),
);
}
- for (const text of followup) {
+ for (const text of state.followup) {
lines.push(fitLine(`${ansi.dim('Queued:')} ${ansi.dim(firstLinePreview(text))}`, safeWidth));
}
lines.push(
diff --git a/packages/cli/src/pi-tui-runner.ts b/packages/cli/src/pi-tui-runner.ts
index 79c67bd6e..a533d7de3 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,
@@ -719,7 +719,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 +838,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,104 +889,8 @@ 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.
+ // Enter during a turn submits one Host-owned message. Runtime Host resolves
+ // the turn-boundary race atomically, so the TUI never owns a fallback copy.
const steerRunningTurn = (text: string) => {
if (!text.trim()) {
requestRender();
@@ -997,18 +899,13 @@ 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');
- else submitPrompt(text);
- return;
- }
- // Queued: the runtime's `queue_update` event refreshes the mirror.
+ .then(() => {
+ // The runtime's `queue_update` event refreshes the pending mirror.
requestRender();
})
.catch((error) => {
@@ -1038,18 +935,13 @@ 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');
- else submitPrompt(text);
- return;
- }
- // Queued: the runtime's `queue_update` event refreshes the mirror.
+ .then(() => {
+ // The runtime's `queue_update` event refreshes the pending mirror.
requestRender();
})
.catch((error) => {
@@ -1059,14 +951,12 @@ 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 the Host-owned pending queue 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);
};
@@ -1322,8 +1212,7 @@ 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
+ // it — accepted messages are already owned by the Host, and a
// failure notice would misreport the still-running Host Turn. Only
// release the slot and hand the freshly attached Turn its start;
// startPendingAttachedTurn no-ops until applySwitchResult has
@@ -1336,70 +1225,17 @@ 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.
+ // Runtime Host owns the accepted-message transition across Turn
+ // boundaries. The TUI only waits for its admission calls to settle.
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/runtime-host-session-driver.ts b/packages/cli/src/runtime-host-session-driver.ts
index 6b7cf0f2a..14d34279a 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', {
@@ -855,9 +849,8 @@ class RuntimeHostMakaSessionDriverImpl implements RuntimeHostMakaSessionDriver {
text: string,
placement: 'current_turn' | 'next_turn',
): Promise<QueueEnqueueOutcome> {
- const sessionId = this.#sessionId;
- if (!sessionId) return { kind: 'fallback' };
- const result = await this.#request('turn.message.submit', {
+ const sessionId = this.#requireSession('submit a message');
+ await this.#request('turn.message.submit', {
originHostEpoch: this.#connection.hostEpoch,
sessionId,
messageId: this.#newId(),
@@ -865,9 +858,8 @@ class RuntimeHostMakaSessionDriverImpl implements RuntimeHostMakaSessionDriver {
placement,
});
// A root Turn can settle between the local projection check and Host
- // admission. The Host has already started the message in that case, so it
- // must not be submitted again. Treat it as accepted; the subscription owns
- // projection of the successor Turn.
+ // admission. The Host atomically starts the message in that case; the
+ // subscription owns projection of the successor Turn.
return { kind: 'queued' };
}
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>;
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org