You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by li...@apache.org on 2026/10/18 10:00:25 UTC

(maka) 01/01: fix(desktop): wait for in-flight session settings before sending

This is an automated email from the ASF dual-hosted git repository.

liugddx pushed a commit to branch fix/plan-mode-submit-race
in repository https://gitbox.apache.org/repos/asf/maka.git

commit a89d92a8c0be2446e11a0565a77c84832fed18c5
Author: liugddx <li...@gmail.com>
AuthorDate: Sun Oct 18 17:42:00 2026 +0800

    fix(desktop): wait for in-flight session settings before sending
    
    The Composer shows a Plan, model, permission or orchestration change as soon
    as it is requested, but the Host admits the next root turn under the
    committed value. Sending right after enabling Plan therefore started an
    ordinary Agent turn while the Composer said Plan.
    
    Session Settings now exposes settled(sessionId), which waits for every
    in-flight write for that Session and reports whether they all committed. It
    reaches the Conversation send path through a small application contract
    published by SessionSettingsProvider, so app-shell does not grow. A send into
    an existing Session waits for it; if a write failed, the existing rollback and
    error toast apply and the draft is kept instead of submitting.
    
    Fixes #4695
    
    Generated-by: Claude Code
    Co-Authored-By: Claude Opus 5.5 <no...@anthropic.com>
---
 .../app-shell-plan-mode-submit-race.test.ts        | 125 +++++++++++++++++++++
 .../main/__tests__/session-setting-intent.test.ts  |  73 ++++++++++++
 .../session-settings-provider-scope.test.ts        |  46 +++++++-
 .../contracts/session-settings-settlement.ts       |  40 +++++++
 .../conversation/controller/chat-actions.ts        |  19 ++++
 .../controller/use-composer-submission.ts          |   3 +
 .../renderer/features/session-settings/README.md   |   5 +
 .../controller/session-settings-bridge.ts          |   2 +
 .../controller/use-session-settings-controller.ts  |   1 +
 .../model/session-settings-contract.ts             |   6 +
 .../ui/session-settings-provider.tsx               |   8 +-
 packages/ui/src/session-setting-intent.ts          |  25 ++++-
 12 files changed, 350 insertions(+), 3 deletions(-)

diff --git a/apps/desktop/src/main/__tests__/app-shell-plan-mode-submit-race.test.ts b/apps/desktop/src/main/__tests__/app-shell-plan-mode-submit-race.test.ts
new file mode 100644
index 0000000000..f0f865584a
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/app-shell-plan-mode-submit-race.test.ts
@@ -0,0 +1,125 @@
+/*
+ * 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.
+ */
+/**
+ * #4695: the Composer shows a Plan (or other setting) change as soon as it is
+ * requested, while the Host admits a turn under the committed value. A send
+ * into an existing Session must wait for that write, and must not submit at
+ * all when it did not commit.
+ */
+
+import { strict as assert } from 'node:assert';
+import { describe, it } from 'node:test';
+
+import type { TransientUserMessageProjection } from '@maka/ui';
+import { createChatActions } from '../../renderer/features/conversation/testing.js';
+
+import {
+  createActionsDeps,
+  EMPTY_SKILL_INVOCATION,
+  installWindow,
+} from './app-shell-chat-actions-fixture.js';
+
+function deferred<T>() {
+  let resolve!: (value: T) => void;
+  const promise = new Promise<T>((next) => {
+    resolve = next;
+  });
+  return { promise, resolve };
+}
+
+async function flush() {
+  for (let index = 0; index < 5; index += 1) await Promise.resolve();
+}
+
+describe('#4695 send waits for in-flight session settings', () => {
+  it('submits only after a delayed Plan write commits', async () => {
+    const settings = deferred<boolean>();
+    const submitted: string[] = [];
+    const restoreWindow = installWindow({ sessions: {
+      submitMessage: async (sessionId: string) => {
+        submitted.push(sessionId);
+        return { ok: true, disposition: 'turn_started', attachments: [], inlineReferences: [], skillInvocation: EMPTY_SKILL_INVOCATION };
+      },
+    } });
+    try {
+      const awaited: string[] = [];
+      const actions = createChatActions({
+        ...createActionsDeps(), activeIdRef: { current: 'session-a' },
+        awaitSessionSettings: (sessionId) => {
+          awaited.push(sessionId);
+          return settings.promise;
+        },
+      });
+      const sending = actions.send('start by submitting a plan');
+      await flush();
+      assert.deepEqual(awaited, ['session-a']);
+      assert.deepEqual(submitted, [], 'the turn must not be admitted before Plan commits');
+
+      settings.resolve(true);
+      assert.equal(await sending, true);
+      assert.deepEqual(submitted, ['session-a']);
+    } finally { restoreWindow(); }
+  });
+
+  it('keeps the draft and submits nothing when the setting write fails', async () => {
+    const transient = new Map<string, TransientUserMessageProjection>();
+    let submitCount = 0;
+    const restoreWindow = installWindow({ sessions: {
+      submitMessage: async () => {
+        submitCount += 1;
+        return { ok: true, disposition: 'turn_started', attachments: [], inlineReferences: [], skillInvocation: EMPTY_SKILL_INVOCATION };
+      },
+    } });
+    try {
+      const actions = createChatActions({
+        ...createActionsDeps(), activeIdRef: { current: 'session-a' },
+        awaitSessionSettings: async () => false,
+        addTransientMessage: (_sessionId, message) => transient.set(message.id, message),
+      });
+      assert.equal(await actions.send('start by submitting a plan'), false);
+      assert.equal(submitCount, 0);
+      assert.equal(transient.size, 0, 'no optimistic row for a send that never left');
+    } finally { restoreWindow(); }
+  });
+
+  it('drops the send when the user leaves the Session while the write is in flight', async () => {
+    const settings = deferred<boolean>();
+    let submitCount = 0;
+    let ownerActive = true;
+    const restoreWindow = installWindow({ sessions: {
+      submitMessage: async () => {
+        submitCount += 1;
+        return { ok: true, disposition: 'turn_started', attachments: [], inlineReferences: [], skillInvocation: EMPTY_SKILL_INVOCATION };
+      },
+    } });
+    try {
+      const actions = createChatActions({
+        ...createActionsDeps(), activeIdRef: { current: 'session-a' },
+        awaitSessionSettings: () => settings.promise,
+        isShellSurfaceOwnerActive: () => ownerActive,
+      });
+      const sending = actions.send('start by submitting a plan');
+      await flush();
+      ownerActive = false;
+      settings.resolve(true);
+      assert.equal(await sending, false);
+      assert.equal(submitCount, 0);
+    } finally { restoreWindow(); }
+  });
+});
diff --git a/apps/desktop/src/main/__tests__/session-setting-intent.test.ts b/apps/desktop/src/main/__tests__/session-setting-intent.test.ts
index f0318518d0..5c541d2548 100644
--- a/apps/desktop/src/main/__tests__/session-setting-intent.test.ts
+++ b/apps/desktop/src/main/__tests__/session-setting-intent.test.ts
@@ -162,6 +162,79 @@ test('rapid requests share the worker and settle only after the latest value com
   assert.equal(await latest, true);
 });
 
+function mountLatestIntentHarness(write: (sessionId: string, value: string) => Promise<boolean>) {
+  const { document, window } = parseHTML('<div id="root"></div>');
+  Object.assign(globalThis, {
+    document,
+    window,
+    HTMLElement: window.HTMLElement,
+    Node: window.Node,
+    IS_REACT_ACT_ENVIRONMENT: true,
+  });
+  const container = document.querySelector('#root');
+  assert.ok(container);
+  const root = createRoot(container);
+  mountedRoot = root;
+  const handle: { controller?: SessionSettingIntentController<string> } = {};
+  return {
+    handle,
+    render: () => act(async () => {
+      root.render(createElement(LatestIntentHarness, {
+        capture: (next) => {
+          handle.controller = next;
+        },
+        write,
+      }));
+    }),
+  };
+}
+
+test('#4695: settled waits for an in-flight write and reports its commit', async () => {
+  const write = deferred<boolean>();
+  const mounted = mountLatestIntentHarness(() => write.promise);
+  await mounted.render();
+  const controller = () => mounted.handle.controller!;
+
+  assert.equal(await controller().settled('session-1'), true, 'nothing pending settles at once');
+
+  await act(async () => {
+    void controller().request('setting', 'session-1', 'plan');
+  });
+  let settled: boolean | undefined;
+  const waiting = controller().settled('session-1').then((value) => {
+    settled = value;
+  });
+  // Another Session's pending write must not hold this Session's submission.
+  assert.equal(await controller().settled('session-2'), true);
+  await Promise.resolve();
+  assert.equal(settled, undefined, 'a send must not proceed while the write is in flight');
+
+  await act(async () => {
+    write.resolve(true);
+    await waiting;
+  });
+  assert.equal(settled, true);
+});
+
+test('#4695: settled reports false when the in-flight write does not commit', async () => {
+  const write = deferred<boolean>();
+  const mounted = mountLatestIntentHarness(() => write.promise);
+  await mounted.render();
+  const controller = () => mounted.handle.controller!;
+
+  await act(async () => {
+    void controller().request('setting', 'session-1', 'plan');
+  });
+  const waiting = controller().settled('session-1');
+  await act(async () => {
+    write.resolve(false);
+    await waiting;
+  });
+  assert.equal(await waiting, false);
+  // The failed intent is retired, so a later send is not blocked forever.
+  assert.equal(await controller().settled('session-1'), true);
+});
+
 function Harness({
   catalog,
   catalogValue,
diff --git a/apps/desktop/src/main/__tests__/session-settings-provider-scope.test.ts b/apps/desktop/src/main/__tests__/session-settings-provider-scope.test.ts
index f88eab679d..b519d7fb7b 100644
--- a/apps/desktop/src/main/__tests__/session-settings-provider-scope.test.ts
+++ b/apps/desktop/src/main/__tests__/session-settings-provider-scope.test.ts
@@ -29,6 +29,10 @@ import {
 } from '../../renderer/features/session-settings/index.js';
 import type { DesktopSessionSummary } from '../../shared/desktop-session-projection.js';
 import { createSessionCatalogController } from '../../renderer/application/contracts/session-catalog/session-catalog-state.js';
+import {
+  useSessionSettingsSettlement,
+  type SessionSettingsSettlement,
+} from '../../renderer/application/contracts/session-settings-settlement.js';
 
 const model = { llmConnectionId: 'connection', llmConnectionSlug: 'openai', model: 'next' };
 const session = (id: string) => ({ id, revision: 1, permissionMode: 'ask', ...model } as DesktopSessionSummary);
@@ -72,7 +76,8 @@ async function mount(options: {
   let frameRenders = 0;
   const errors: unknown[] = [];
   const service = options.services ?? services();
-  function Frame() { frameRenders += 1; return null; }
+  let settlement: SessionSettingsSettlement | undefined;
+  function Frame() { frameRenders += 1; settlement = useSessionSettingsSettlement(); return null; }
   function Shell() {
     renders += 1;
     snapshot = useSessionSettingIntent(selected);
@@ -107,6 +112,7 @@ async function mount(options: {
     current: () => snapshot,
     renders: () => renders,
     frameRenders: () => frameRenders,
+    settlement: () => settlement,
     select: async (id: string | undefined) => {
       selected = id;
       owner = { sessionId: selected };
@@ -302,3 +308,41 @@ test('Plan discard remains bound to the requested Session while the user switche
   assert.equal(h.current().overlay.planMode, undefined);
   await act(() => h.root.unmount());
 });
+
+test('#4695: the provider lets a submission wait for an in-flight Plan write', async () => {
+  const write = deferred<DesktopSessionSummary>();
+  const h = await mount({ services: services({ setCollaborationMode: () => write.promise }) });
+  const settlement = h.settlement();
+  assert.ok(settlement, 'Session Settings must publish its settlement to the subtree');
+  assert.equal(await settlement.settled('a'), true, 'nothing pending');
+
+  let planWrite!: Promise<boolean>;
+  await act(() => { planWrite = h.current().commands.setPlanMode('a', true); });
+  assert.equal(h.current().overlay.planMode, true, 'the Composer already shows Plan');
+  let settled: boolean | undefined;
+  const waiting = settlement.settled('a').then((value) => { settled = value; });
+  await act(async () => { await Promise.resolve(); });
+  assert.equal(settled, undefined, 'a send must wait while Plan is still committing');
+
+  await act(async () => {
+    write.resolve({ ...session('a'), collaborationMode: 'plan', revision: 2 });
+    await planWrite;
+    await waiting;
+  });
+  assert.equal(settled, true);
+  assert.equal(h.settlement(), settlement, 'the settlement port is stable across renders');
+  await act(() => h.root.unmount());
+});
+
+test('#4695: a failed Plan write settles false and rolls the control back', async () => {
+  const write = deferred<DesktopSessionSummary>();
+  const h = await mount({ services: services({ setCollaborationMode: () => write.promise }) });
+  await act(() => { void h.current().commands.setPlanMode('a', true); });
+  const waiting = h.settlement()!.settled('a');
+  let result = true;
+  await act(async () => { write.reject(new Error('Host unavailable')); result = await waiting; });
+  assert.equal(result, false);
+  assert.equal(h.current().overlay.planMode, undefined);
+  assert.deepEqual(h.errors, [['a', 'failed', 'failed']]);
+  await act(() => h.root.unmount());
+});
diff --git a/apps/desktop/src/renderer/application/contracts/session-settings-settlement.ts b/apps/desktop/src/renderer/application/contracts/session-settings-settlement.ts
new file mode 100644
index 0000000000..177954cb47
--- /dev/null
+++ b/apps/desktop/src/renderer/application/contracts/session-settings-settlement.ts
@@ -0,0 +1,40 @@
+/*
+ * 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 { createContext, useContext } from 'react';
+
+/**
+ * Lets a submission wait for the selected Session's in-flight setting writes
+ * (Plan, model, permission, orchestration) without depending on the Session
+ * Settings feature. The Composer shows a change as soon as it is requested,
+ * while the Host admits a turn under the committed value (#4695).
+ */
+export interface SessionSettingsSettlement {
+  /** True when every pending write committed (or none was pending). */
+  settled(sessionId: string): Promise<boolean>;
+}
+
+const SessionSettingsSettlementContext = createContext<SessionSettingsSettlement | undefined>(undefined);
+
+export const SessionSettingsSettlementProvider = SessionSettingsSettlementContext.Provider;
+
+/** Undefined outside a Session Settings owner, where no write can be pending. */
+export function useSessionSettingsSettlement(): SessionSettingsSettlement | undefined {
+  return useContext(SessionSettingsSettlementContext);
+}
diff --git a/apps/desktop/src/renderer/features/conversation/controller/chat-actions.ts b/apps/desktop/src/renderer/features/conversation/controller/chat-actions.ts
index 0e9c49e781..55368feb21 100644
--- a/apps/desktop/src/renderer/features/conversation/controller/chat-actions.ts
+++ b/apps/desktop/src/renderer/features/conversation/controller/chat-actions.ts
@@ -116,6 +116,11 @@ export function createChatActions<Owner extends ComposerSurfaceOwner>(deps: {
   captureComposerImportOwner: () => Owner;
   captureSelection: () => () => boolean;
   checkTaskSubmissionReadiness: () => Promise<boolean>;
+  /**
+   * Waits for the Session's in-flight setting writes; false when one did not
+   * commit. Omitted only by tests that do not exercise mode changes.
+   */
+  awaitSessionSettings?: (sessionId: string) => Promise<boolean>;
   isNewChatSendSurfaceActive: (owner: Owner) => boolean;
   /** The shell's one answer to "is this owner still the surface the user is
    *  looking at". Both halves matter — the section AND the session id — which
@@ -176,6 +181,7 @@ export function createChatActions<Owner extends ComposerSurfaceOwner>(deps: {
     captureComposerImportOwner,
     captureSelection,
     checkTaskSubmissionReadiness,
+    awaitSessionSettings,
     isNewChatSendSurfaceActive,
     isShellSurfaceOwnerActive,
     refreshSessions,
@@ -277,6 +283,19 @@ export function createChatActions<Owner extends ComposerSurfaceOwner>(deps: {
     ) {
       return false;
     }
+    // #4695: the Composer shows a Plan (or model, permission, orchestration)
+    // change as soon as it is requested, but the Host only admits the turn
+    // under the committed value. Wait for the write so the turn runs in the
+    // mode the user sees; if it failed, the write path has already rolled the
+    // control back and reported why, so keep the draft instead of sending.
+    if (initialSessionId && awaitSessionSettings) {
+      if (
+        !(await awaitSessionSettings(initialSessionId)) || !selectionIsCurrent() ||
+        !isShellSurfaceOwnerActive(sendOwner)
+      ) {
+        return false;
+      }
+    }
     let optimisticSessionId: string | undefined;
     const messageId = crypto.randomUUID();
     // #1433: the composer creates the session BEFORE it sends, so a first
diff --git a/apps/desktop/src/renderer/features/conversation/controller/use-composer-submission.ts b/apps/desktop/src/renderer/features/conversation/controller/use-composer-submission.ts
index 1b7435865d..fbfaaae25b 100644
--- a/apps/desktop/src/renderer/features/conversation/controller/use-composer-submission.ts
+++ b/apps/desktop/src/renderer/features/conversation/controller/use-composer-submission.ts
@@ -25,6 +25,7 @@ import { activeHostTurn } from '../../../application/contracts/session-execution
 import { getDesktopConversationCopy } from '../../../application/contracts/conversation-copy.js';
 import { parseDesktopSlashCommand } from '../../../application/contracts/desktop-slash-command.js';
 import { catalogWatchedRowsUsable } from '../../../application/contracts/session-catalog/catalog-row-watch.js';
+import { useSessionSettingsSettlement } from '../../../application/contracts/session-settings-settlement.js';
 import { useStableActions } from '../../../application/contracts/use-stable-actions.js';
 import { getShellCopy, localizedShellErrorMessage } from '../../../locales/shell-copy.js';
 import type {
@@ -69,6 +70,7 @@ export function useComposerSubmission<Owner extends ComposerSurfaceOwner>(input:
   const services = useComposerSubmissionServices();
   const { workspace, commands } = useConversationOwner();
   const queue = useConversationQueueCommands();
+  const sessionSettings = useSessionSettingsSettlement();
   const composerRef = queue.composer;
   const uiLocale = useUiLocale();
   const toastApi = useToast();
@@ -109,6 +111,7 @@ export function useComposerSubmission<Owner extends ComposerSurfaceOwner>(input:
     captureSelection: commands.captureSelection,
     checkTaskSubmissionReadiness: async () =>
       !sharedSessionActive && (!!activeIdRef.current || !!newTask.target),
+    awaitSessionSettings: sessionSettings?.settled,
     isNewChatSendSurfaceActive: shell.isNewChatOwnerActive,
     isShellSurfaceOwnerActive: shell.isOwnerActive,
     refreshSessions: shell.refreshSessions,
diff --git a/apps/desktop/src/renderer/features/session-settings/README.md b/apps/desktop/src/renderer/features/session-settings/README.md
index c91178f002..e3f2c4ba07 100644
--- a/apps/desktop/src/renderer/features/session-settings/README.md
+++ b/apps/desktop/src/renderer/features/session-settings/README.md
@@ -70,6 +70,11 @@ a new-task change does not replace the Session overlay it returns.
   Session, even if navigation changes meanwhile. The Runtime leaves Plan as
   part of abandoning; orchestration is preserved.
 - Failed writes retain the existing rollback and active-Session error behavior.
+- `settled(sessionId)` waits for the Session's in-flight writes on every
+  channel and reports whether they committed. The provider publishes it through
+  `application/contracts/session-settings-settlement.ts`, so a send into an
+  existing Session runs under the mode the Composer shows, or keeps its draft
+  when a write failed (#4695).
 
 `index.ts` exports the owner and the shell read; `testing.ts` exposes the
 controller and Plan policy to tests. `controllerOwners` enforces the production
diff --git a/apps/desktop/src/renderer/features/session-settings/controller/session-settings-bridge.ts b/apps/desktop/src/renderer/features/session-settings/controller/session-settings-bridge.ts
index 8ba7f23476..312cc0375e 100644
--- a/apps/desktop/src/renderer/features/session-settings/controller/session-settings-bridge.ts
+++ b/apps/desktop/src/renderer/features/session-settings/controller/session-settings-bridge.ts
@@ -46,6 +46,8 @@ export function createSessionSettingsBridge() {
   };
   const commands: SessionSettingsCommands = {
     clear: (id) => controller?.clear(id),
+    // Without a controller no write can be in flight.
+    settled: (id) => controller?.settled(id) ?? Promise.resolve(true),
     setSessionModel: (id, model) => controller?.setSessionModel(id, model) ?? Promise.resolve(false),
     setSessionThinkingLevel: (id, level) => controller?.setSessionThinkingLevel(id, level) ?? Promise.resolve(false),
     setSessionExecutor: (id, target) => controller?.setSessionExecutor(id, target) ?? Promise.resolve(false),
diff --git a/apps/desktop/src/renderer/features/session-settings/controller/use-session-settings-controller.ts b/apps/desktop/src/renderer/features/session-settings/controller/use-session-settings-controller.ts
index c9fe4d2724..1f2560d31f 100644
--- a/apps/desktop/src/renderer/features/session-settings/controller/use-session-settings-controller.ts
+++ b/apps/desktop/src/renderer/features/session-settings/controller/use-session-settings-controller.ts
@@ -135,6 +135,7 @@ export function useSessionSettingsController<Owner extends { sessionId?: string
 
   return {
     clear: intent.clear,
+    settled: intent.settled,
     overlays: intent.overlayByChannel,
     newTask,
     setSessionModel: (sessionId: string, modelTarget: SessionModelTarget) =>
diff --git a/apps/desktop/src/renderer/features/session-settings/model/session-settings-contract.ts b/apps/desktop/src/renderer/features/session-settings/model/session-settings-contract.ts
index 0ae2fcd44a..38ddfa6777 100644
--- a/apps/desktop/src/renderer/features/session-settings/model/session-settings-contract.ts
+++ b/apps/desktop/src/renderer/features/session-settings/model/session-settings-contract.ts
@@ -71,6 +71,12 @@ export interface SessionSettingsInput<Owner extends { sessionId?: string }> {
 
 export interface SessionSettingsCommands {
   clear(sessionId: string): void;
+  /**
+   * Waits for the Session's in-flight setting writes. True when they all
+   * committed (or none was pending); false when one failed or was abandoned,
+   * so the caller must not act on the overlay the user saw.
+   */
+  settled(sessionId: string): Promise<boolean>;
   setSessionModel(sessionId: string, model: SessionModelTarget): Promise<boolean>;
   setSessionThinkingLevel(sessionId: string, level: ThinkingLevel | null): Promise<boolean>;
   setSessionExecutor(
diff --git a/apps/desktop/src/renderer/features/session-settings/ui/session-settings-provider.tsx b/apps/desktop/src/renderer/features/session-settings/ui/session-settings-provider.tsx
index 310c7e638a..2530f01f7a 100644
--- a/apps/desktop/src/renderer/features/session-settings/ui/session-settings-provider.tsx
+++ b/apps/desktop/src/renderer/features/session-settings/ui/session-settings-provider.tsx
@@ -18,6 +18,7 @@
  */
 
 import { useLayoutEffect, type ReactNode } from 'react';
+import { SessionSettingsSettlementProvider } from '../../../application/contracts/session-settings-settlement.js';
 import { useSessionSettingsController } from '../controller/use-session-settings-controller.js';
 import type { SessionSettingsBridge } from '../controller/session-settings-bridge.js';
 import type { SessionSettingsInput } from '../model/session-settings-contract.js';
@@ -31,5 +32,10 @@ export function SessionSettingsProvider<Owner extends { sessionId?: string }>(pr
   const controller = useSessionSettingsController(props.input);
   useLayoutEffect(() => props.bridge.publish(controller), [props.bridge, controller]);
   useLayoutEffect(() => () => props.bridge.disconnect(), [props.bridge]);
-  return props.children;
+  // The bridge's commands are stable, so this value never re-renders consumers.
+  return (
+    <SessionSettingsSettlementProvider value={props.bridge.commands}>
+      {props.children}
+    </SessionSettingsSettlementProvider>
+  );
 }
diff --git a/packages/ui/src/session-setting-intent.ts b/packages/ui/src/session-setting-intent.ts
index 0b14e4960b..7ae20737ec 100644
--- a/packages/ui/src/session-setting-intent.ts
+++ b/packages/ui/src/session-setting-intent.ts
@@ -84,6 +84,13 @@ export interface SessionSettingIntentController<Values extends object> {
     value: Values[Channel],
   ): Promise<boolean>;
   clear(sessionId: string): void;
+  /**
+   * Resolves once no write for `sessionId` is in flight on any channel: true
+   * when every write that was pending committed, false when one failed, was
+   * cleared or the owner unmounted. A submission that must run under the mode
+   * the user sees awaits this instead of reading an optimistic overlay.
+   */
+  settled(sessionId: string): Promise<boolean>;
 }
 
 type AnyIntent = SettingIntent<unknown>;
@@ -308,5 +315,21 @@ export function useSessionSettingIntent<Values extends object>(
     }
   }, [setOverlay]);
 
-  return { overlayByChannel, request, clear };
+  const settled = useCallback(async (sessionId: string): Promise<boolean> => {
+    let succeeded = true;
+    // A write can start while an earlier one is awaited, so re-read until idle.
+    for (;;) {
+      if (!mountedRef.current) return false;
+      const pending: Promise<boolean>[] = [];
+      for (const intents of intentsRef.current.values()) {
+        const intent = intents.get(sessionId);
+        if (intent?.inFlight) pending.push(intent.completion);
+      }
+      if (pending.length === 0) return succeeded && mountedRef.current;
+      const results = await Promise.all(pending);
+      if (results.includes(false)) succeeded = false;
+    }
+  }, []);
+
+  return { overlayByChannel, request, clear, settled };
 }


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