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/26 14:58:11 UTC

(maka) 20/26: fix(cli): give Host admission a single ordered client stream

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 b567439ecb4fe3444765eb0b5d64aa26d3325eb2
Author: AstroHan <le...@outlook.com>
AuthorDate: Wed Aug 26 14:08:06 2026 +0800

    fix(cli): give Host admission a single ordered client stream
    
    Runtime Host decides what a Message becomes from the state it holds when the
    Message arrives, so arrival order is part of the meaning. Removing the TUI's
    submit hold left nothing enforcing it: every Enter started an independent
    `driver.submitMessage()`, and `#ensureSession()` had no single-flight, so two
    Enters on a fresh TUI could issue two `session.create` calls and leave the
    first Message in a Session the TUI no longer displays. On an existing Session
    the per-submit configuration read could still reorder Host arrival, and a
    `/model` typed after a Message could overtake it and change the Turn that
    Message opens.
    
    Serialize admission and configuration through one tail in the driver, and
    share one in-flight Session creation. The tail is deliberately not a gate on
    user input: the transient row still appears immediately, and Session identity
    changes stay off the tail so `/session` and `/new` remain the way out of a
    stuck admission, fenced by the existing generation assert instead.
    
    Generated-by: Claude Code
---
 .../__tests__/runtime-host-session-driver.test.ts  | 90 ++++++++++++++++++++++
 packages/cli/src/runtime-host-session-driver.ts    | 77 ++++++++++++++++--
 2 files changed, 161 insertions(+), 6 deletions(-)

diff --git a/packages/cli/src/__tests__/runtime-host-session-driver.test.ts b/packages/cli/src/__tests__/runtime-host-session-driver.test.ts
index 683634557..88aa5f1ae 100644
--- a/packages/cli/src/__tests__/runtime-host-session-driver.test.ts
+++ b/packages/cli/src/__tests__/runtime-host-session-driver.test.ts
@@ -1172,6 +1172,88 @@ describe('Runtime Host Maka Session driver', () => {
     });
   });
 
+  test('admits concurrent first messages into one Session in submission order', async () => {
+    // Two subscriptions so a driver that creates two Sessions fails on the
+    // claim rather than on missing fake infrastructure.
+    const connection = new FakeConnection([
+      new FakeSubscription(continuitySnapshot(), Promise.resolve([])),
+      new FakeSubscription(continuitySnapshot(), Promise.resolve([])),
+    ]);
+    const create = deferred<void>();
+    connection.heldOperations.set('session.create', create.promise);
+    let nextId = 0;
+    const driver = createRuntimeHostMakaSessionDriver({
+      connection: connection.value,
+      cwd: '/repo',
+      llmConnectionSlug: 'openai-main',
+      model: 'gpt-5',
+      newId: () => `session-${++nextId}`,
+    });
+
+    // Two Enters before the first round trip resolves. Nothing about the TUI
+    // holds the second one back, so the driver is what has to keep them from
+    // racing into two Sessions or reaching the Host out of order.
+    const first = driver.submitMessage!('first', {
+      messageId: 'message-1',
+      placement: 'current_turn',
+    });
+    const second = driver.submitMessage!('second', {
+      messageId: 'message-2',
+      placement: 'current_turn',
+    });
+    create.resolve();
+    await Promise.all([first, second]);
+
+    const creates = connection.requests.filter(({ operation }) => operation === 'session.create');
+    assert.equal(creates.length, 1);
+    const submits = connection.requests.filter(
+      ({ operation }) => operation === 'turn.message.submit',
+    );
+    assert.deepEqual(
+      submits.map(({ input }) => (input as OperationInput<'turn.message.submit'>).messageId),
+      ['message-1', 'message-2'],
+    );
+    assert.deepEqual(
+      new Set(
+        submits.map(({ input }) => (input as OperationInput<'turn.message.submit'>).sessionId),
+      ),
+      new Set(['session-1']),
+    );
+  });
+
+  test('keeps a configuration change from crossing a pending admission', async () => {
+    const subscription = new FakeSubscription(continuitySnapshot(), Promise.resolve([]));
+    const connection = new FakeConnection([subscription]);
+    const driver = createRuntimeHostMakaSessionDriver({
+      connection: connection.value,
+      cwd: '/tmp',
+      llmConnectionSlug: 'openai-main',
+      model: 'gpt-5',
+    });
+    await driver.switchSession('session-1');
+
+    const submit = deferred<void>();
+    connection.heldOperations.set('turn.message.submit', submit.promise);
+    const admitted = driver.submitMessage!('before the model change', {
+      messageId: 'message-1',
+      placement: 'current_turn',
+    });
+    // `/model` typed while the Message is still in flight. The Host must see
+    // it after the Message it was typed after, or the Turn that Message opens
+    // runs under a model the user had not chosen yet.
+    const changed = driver.setModel('gpt-5-codex');
+    submit.resolve();
+    await Promise.all([admitted, changed]);
+
+    const ordered = connection.requests
+      .map(({ operation }) => operation)
+      .filter(
+        (operation) =>
+          operation === 'turn.message.submit' || operation === 'session.configuration.update',
+      );
+    assert.deepEqual(ordered, ['turn.message.submit', 'session.configuration.update']);
+  });
+
   test('keeps an unknown message admission available for transcript reconciliation', async () => {
     const subscription = new FakeSubscription(continuitySnapshot(), Promise.resolve([]));
     const connection = new FakeConnection([subscription]);
@@ -1848,6 +1930,12 @@ class FakeConnection {
   /** Scripted goal.query results, shifted per call; defaults to null (no goal). */
   readonly goalQueryResults: Array<GoalProjection | null> = [];
   readonly messageSubmitOutcomes: Array<OperationOutput<'turn.message.submit'> | Error> = [];
+  /**
+   * Operations held open by a test. The request is recorded on entry and then
+   * waits, so a test can hold one round trip and observe what the driver does
+   * with a second call while the first is still in flight.
+   */
+  readonly heldOperations = new Map<string, Promise<void>>();
   readonly value: RuntimeHostMakaSessionDriverInput['connection'];
 
   constructor(
@@ -1874,6 +1962,8 @@ class FakeConnection {
     input: OperationInput<K>,
   ): Promise<OperationOutput<K>> {
     this.requests.push({ operation, input });
+    const held = this.heldOperations.get(operation);
+    if (held) await held;
     if (operation === 'session.workspace.relocate') {
       const workspace = (input as OperationInput<'session.workspace.relocate'>).workspace;
       if (workspace.kind !== 'host_path') throw new Error('Expected Host-path workspace');
diff --git a/packages/cli/src/runtime-host-session-driver.ts b/packages/cli/src/runtime-host-session-driver.ts
index 53143fa06..5ad8cd139 100644
--- a/packages/cli/src/runtime-host-session-driver.ts
+++ b/packages/cli/src/runtime-host-session-driver.ts
@@ -393,7 +393,14 @@ class RuntimeHostMakaSessionDriverImpl implements RuntimeHostMakaSessionDriver {
     yield* events;
   }
 
-  async submitMessage(
+  submitMessage(
+    text: string,
+    options: MakaSubmitMessageOptions,
+  ): Promise<OperationOutput<'turn.message.submit'> | undefined> {
+    return this.#admit(() => this.#submitMessage(text, options));
+  }
+
+  async #submitMessage(
     text: string,
     options: MakaSubmitMessageOptions,
   ): Promise<OperationOutput<'turn.message.submit'> | undefined> {
@@ -470,7 +477,11 @@ class RuntimeHostMakaSessionDriverImpl implements RuntimeHostMakaSessionDriver {
     if (pending) this.#channel?.publishInteractionAnswer(answered, pending);
   }
 
-  async setModel(model: string, connectionSlug?: string): Promise<void> {
+  setModel(model: string, connectionSlug?: string): Promise<void> {
+    return this.#admit(() => this.#setModel(model, connectionSlug));
+  }
+
+  async #setModel(model: string, connectionSlug?: string): Promise<void> {
     const nextConnection = connectionSlug ?? this.#llmConnectionSlug;
     if (this.#sessionId) {
       const session = await this.#updateConfiguration(this.#sessionId, {
@@ -485,7 +496,11 @@ class RuntimeHostMakaSessionDriverImpl implements RuntimeHostMakaSessionDriver {
     this.#thinkingLevel = undefined;
   }
 
-  async setThinkingLevel(level: ThinkingLevel | undefined): Promise<void> {
+  setThinkingLevel(level: ThinkingLevel | undefined): Promise<void> {
+    return this.#admit(() => this.#setThinkingLevel(level));
+  }
+
+  async #setThinkingLevel(level: ThinkingLevel | undefined): Promise<void> {
     if (this.#sessionId) {
       this.#adoptConfiguration(
         await this.#updateConfiguration(this.#sessionId, { thinkingLevel: level ?? null }),
@@ -495,7 +510,11 @@ class RuntimeHostMakaSessionDriverImpl implements RuntimeHostMakaSessionDriver {
     this.#thinkingLevel = level;
   }
 
-  async setPermissionMode(mode: PermissionMode): Promise<void> {
+  setPermissionMode(mode: PermissionMode): Promise<void> {
+    return this.#admit(() => this.#setPermissionMode(mode));
+  }
+
+  async #setPermissionMode(mode: PermissionMode): Promise<void> {
     if (this.#sessionId) {
       const session = await this.#updateConfiguration(this.#sessionId, { permissionMode: mode });
       this.#permissionMode = session.permissionMode;
@@ -508,7 +527,11 @@ class RuntimeHostMakaSessionDriverImpl implements RuntimeHostMakaSessionDriver {
     this.#permissionMode = mode;
   }
 
-  async setOrchestrationMode(mode: OrchestrationMode): Promise<void> {
+  setOrchestrationMode(mode: OrchestrationMode): Promise<void> {
+    return this.#admit(() => this.#setOrchestrationMode(mode));
+  }
+
+  async #setOrchestrationMode(mode: OrchestrationMode): Promise<void> {
     if (this.#sessionId) {
       this.#adoptConfiguration(
         await this.#updateConfiguration(this.#sessionId, { orchestrationMode: mode }),
@@ -990,9 +1013,51 @@ class RuntimeHostMakaSessionDriverImpl implements RuntimeHostMakaSessionDriver {
     }
   }
 
+  /**
+   * The ordered client → Host operation stream.
+   *
+   * Runtime Host decides what a Message becomes, and it decides from the state
+   * it holds when the Message arrives. That makes arrival order part of the
+   * meaning: two Enters typed before the first round trip resolves must not
+   * race into two Sessions, and a `/model` typed after a Message must not
+   * overtake it and change the Turn that Message opens.
+   *
+   * Session identity changes deliberately stay off this tail. `/session` and
+   * `/new` are how a user leaves a Session whose admission is stuck, so
+   * queueing them behind it would remove the only exit; `#assertCurrentSession`
+   * fences them instead, by failing an admission whose Session moved under it.
+   */
+  #admissionTail: Promise<unknown> = Promise.resolve();
+
+  #admit<T>(operation: () => Promise<T>): Promise<T> {
+    const admitted = this.#admissionTail.then(operation, operation);
+    // A failed operation must not poison the tail: the next Message is a new
+    // intent, not a retry of the one that failed.
+    this.#admissionTail = admitted.then(
+      () => undefined,
+      () => undefined,
+    );
+    return admitted;
+  }
+
+  #sessionCreation: Promise<string> | undefined;
+
+  /**
+   * One in-flight creation, shared. Reads outside the admission tail
+   * (`queryCancelledMessages`) can reach this concurrently with an admission,
+   * and a second `session.create` would leave the first Message in a Session
+   * the TUI has already stopped displaying.
+   */
   async #ensureSession(): Promise<string> {
     if (this.#sessionId) return this.#sessionId;
-    return (await this.#createSession(DEFAULT_SESSION_NAME)).id;
+    if (this.#sessionCreation) return this.#sessionCreation;
+    const creation = this.#createSession(DEFAULT_SESSION_NAME).then((session) => session.id);
+    this.#sessionCreation = creation;
+    try {
+      return await creation;
+    } finally {
+      if (this.#sessionCreation === creation) this.#sessionCreation = undefined;
+    }
   }
 
   async #createSession(name: string): Promise<SessionCatalogProjection> {


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org