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/19 02:17:16 UTC
(maka) branch main updated: fix(desktop): wait for in-flight session settings before sending (#6150)
This is an automated email from the ASF dual-hosted git repository.
liugddx pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/maka.git
The following commit(s) were added to refs/heads/main by this push:
new 39615e2834 fix(desktop): wait for in-flight session settings before sending (#6150)
39615e2834 is described below
commit 39615e2834ee60de2b8b30ce40389b3f76100f22
Author: Guangdong Liu <li...@gmail.com>
AuthorDate: Mon Oct 19 10:17:11 2026 +0800
fix(desktop): wait for in-flight session settings before sending (#6150)
---
.../app-shell-plan-mode-submit-race.test.ts | 125 ++++++++++++++
.../__tests__/app-shell-revision-resend.test.ts | 106 ++++++++++++
.../main/__tests__/composer-staging-owner.test.ts | 60 ++++++-
.../main/__tests__/session-setting-intent.test.ts | 190 +++++++++++++++++++++
.../session-settings-provider-scope.test.ts | 46 ++++-
.../contracts/session-settings-settlement.ts | 52 ++++++
.../conversation/controller/chat-actions.ts | 19 +++
.../conversation/controller/composer-submit.ts | 50 +++++-
.../controller/use-composer-submission.ts | 12 ++
.../features/conversation/ui/staged-composer.tsx | 31 +++-
.../renderer/features/session-settings/README.md | 10 ++
.../controller/session-settings-bridge.ts | 6 +
.../controller/use-session-settings-controller.ts | 2 +
.../model/session-settings-contract.ts | 12 ++
.../ui/session-settings-provider.tsx | 8 +-
packages/ui/src/session-setting-intent.ts | 83 ++++++++-
16 files changed, 795 insertions(+), 17 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__/app-shell-revision-resend.test.ts b/apps/desktop/src/main/__tests__/app-shell-revision-resend.test.ts
index 15f6e483ed..8141a42ba1 100644
--- a/apps/desktop/src/main/__tests__/app-shell-revision-resend.test.ts
+++ b/apps/desktop/src/main/__tests__/app-shell-revision-resend.test.ts
@@ -239,6 +239,7 @@ async function mountRevisionWorld(): Promise<RevisionWorld> {
let pendingSend: Promise<boolean | void> | undefined;
const sendPendingFlags: boolean[] = [];
const ports: RevisionSendPorts<TurnRevisionDraft> = {
+ captureSubmitSurface: () => () => true,
shellCopy: {
sideChatUnavailableTitle: '',
sideChatUnavailableDescription: '',
@@ -477,3 +478,108 @@ test('submit releases attachment ownership when sending throws', async () => {
world.restoreWindow();
}
});
+
+// #4695 review: an edit-and-resend copies the source Session's settings, so
+// the Plan write the user saw at submit must settle before that copy.
+for (const outcome of [true, false]) {
+ test(`#4695: a revision waits for the submit's setting writes before copying (${outcome ? 'committed' : 'failed'})`, async () => {
+ const world = await mountRevisionWorld();
+ try {
+ const events: string[] = [];
+ let settle!: (ok: boolean) => void;
+ // One attempt: every read of it sees the same result.
+ const attempt = new Promise<boolean>((resolve) => { settle = resolve; });
+ const settlement = { settled: () => attempt };
+ const onSend = createRevisionAwareOnSend({
+ ...world.ports,
+ revisionDraftRef: { current: { draftSessionId: SESSION_1, sourceSessionId: SESSION_1 } as never },
+ activeIdRef: { current: SESSION_1 },
+ prepareRevisionSend: async () => { events.push('copy'); return true; },
+ setNewTaskSendPending: () => {},
+ send: async () => { events.push('send'); return true; },
+ });
+ const sent = onSend('edited message', undefined, undefined, settlement);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ assert.deepEqual(events, [], 'nothing may copy or send while the Plan write is pending');
+ settle(outcome);
+ const result = await sent;
+ if (outcome) {
+ assert.notEqual(result, false);
+ assert.deepEqual(events, ['copy', 'send']);
+ } else {
+ assert.equal(result, false, 'a failed setting write keeps the draft');
+ assert.deepEqual(events, [], 'no copy is made from a failed Plan attempt');
+ }
+ } finally {
+ world.restoreWindow();
+ }
+ });
+}
+
+// #4695 review round 2: navigation keeps the Session id, so the wait must
+// re-check the surface and selection captured before it.
+test('#4695: a submit that navigates away while settings settle sends nothing', async () => {
+ const world = await mountRevisionWorld();
+ try {
+ let onSurface = true;
+ let captured = 0;
+ let settle!: (ok: boolean) => void;
+ const outcome = new Promise<boolean>((resolve) => { settle = resolve; });
+ const settlement = { settled: () => outcome };
+ const sends: string[] = [];
+ const onSend = createRevisionAwareOnSend({
+ ...world.ports,
+ activeIdRef: { current: SESSION_1 },
+ captureSubmitSurface: () => { captured += 1; return () => onSurface; },
+ setNewTaskSendPending: () => {},
+ send: async (text) => { sends.push(text); return true; },
+ });
+ const sent = onSend('start by submitting a plan', undefined, undefined, settlement);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ assert.equal(captured, 1, 'the surface is captured before the wait');
+ onSurface = false; // e.g. Extensions: same Session id, different surface
+ settle(true);
+ assert.equal(await sent, false);
+ assert.deepEqual(sends, []);
+ } finally {
+ world.restoreWindow();
+ }
+});
+
+test('#4695: a source write that fails while the revision copy is prepared stops the send', async () => {
+ const world = await mountRevisionWorld();
+ try {
+ const events: string[] = [];
+ const outcomes = [true, false];
+ const settlement = { settled: async () => outcomes.shift() ?? false };
+ const onSend = createRevisionAwareOnSend({
+ ...world.ports,
+ revisionDraftRef: { current: { draftSessionId: SESSION_1, sourceSessionId: SESSION_1 } as never },
+ activeIdRef: { current: SESSION_1 },
+ prepareRevisionSend: async () => { events.push('copy'); return true; },
+ setNewTaskSendPending: () => {},
+ send: async () => { events.push('send'); return true; },
+ });
+ assert.equal(await onSend('edited message', undefined, undefined, settlement), false);
+ assert.deepEqual(events, ['copy'], 'the prepared child is kept for an explicit retry, but nothing is sent');
+ } finally {
+ world.restoreWindow();
+ }
+});
+
+test('#4695: local slash commands do not wait on setting writes', async () => {
+ const world = await mountRevisionWorld();
+ try {
+ const settlement = { settled: () => new Promise<boolean>(() => {}) };
+ const onSend = createRevisionAwareOnSend({
+ ...world.ports,
+ activeIdRef: { current: SESSION_1 },
+ setNewTaskSendPending: () => {},
+ getActiveOrchestrationMode: () => 'default',
+ send: async () => assert.fail('/swarm status must not send'),
+ });
+ assert.equal(await onSend('/swarm status', undefined, undefined, settlement), true);
+ } finally {
+ world.restoreWindow();
+ }
+});
diff --git a/apps/desktop/src/main/__tests__/composer-staging-owner.test.ts b/apps/desktop/src/main/__tests__/composer-staging-owner.test.ts
index 2d954deb3f..39443cbff8 100644
--- a/apps/desktop/src/main/__tests__/composer-staging-owner.test.ts
+++ b/apps/desktop/src/main/__tests__/composer-staging-owner.test.ts
@@ -46,6 +46,11 @@ import { renderTranscriptMarkup } from './transcript-test-dom.js';
import { createSessionCatalogController, SessionCatalogContext } from '../../renderer/application/contracts/session-catalog/session-catalog-state.js';
import type { DesktopSessionSummary } from '../../shared/desktop-session-projection.js';
import type { DesktopLocalMessageDraft } from '../../shared/session-local-contract.js';
+import {
+ SessionSettingsSettlementProvider,
+ type SessionSendSettlement,
+ type SessionSettingsSettlement,
+} from '../../renderer/application/contracts/session-settings-settlement.js';
const saved = Object.fromEntries([
'window', 'document', 'Element', 'HTMLBRElement', 'sessionStorage', 'HTMLElement', 'HTMLIFrameElement', 'Event', 'Node', 'CSS',
@@ -80,8 +85,14 @@ const recoverySession = (id: string): DesktopSessionSummary => ({
});
async function mount(options: {
- onSend?: (text: string, metadata?: ComposerSendMetadata, staging?: ComposerStagingSubmission) => Promise<boolean | void>;
+ onSend?: (
+ text: string,
+ metadata?: ComposerSendMetadata,
+ staging?: ComposerStagingSubmission,
+ settlement?: SessionSendSettlement,
+ ) => Promise<boolean | void>;
waitForSessionReference?: () => Promise<boolean>;
+ sessionSettings?: SessionSettingsSettlement;
releaseRecoveryAttachments?: (ids: readonly string[]) => Promise<void>;
} = {}) {
const { window, document } = parseHTML('<html><body><div id="root"></div></body></html>');
@@ -158,9 +169,12 @@ async function mount(options: {
children: createElement(LocaleProvider, { locale: 'en', children:
createElement(ComposerStagingFixture, { commands, draftKey, directoryHostId: hostId, conversationServices, children:
createElement(PlanServicesProvider, { services: planServices, children:
- createElement(PlanProvider, { session: undefined, children: createElement(Fragment, null,
- createElement(StagingProbe), createElement(Frame, { draftKey, visible }),
- ) }),
+ createElement(PlanProvider, { session: undefined, children: createElement(SessionSettingsSettlementProvider, {
+ value: options.sessionSettings,
+ children: createElement(Fragment, null,
+ createElement(StagingProbe), createElement(Frame, { draftKey, visible }),
+ ),
+ }) }),
}),
}),
}),
@@ -228,6 +242,7 @@ test('StagedComposer keeps the submitted recovery attachment while waiting for S
});
const submissions: Array<{ sources: unknown[]; replaces?: string }> = [];
onSend = createRevisionAwareOnSend({
+ captureSubmitSurface: () => () => true,
shellCopy: {
sideChatUnavailableTitle: '', sideChatUnavailableDescription: '',
sideChatContextPendingTitle: '', sideChatContextPendingDescription: '',
@@ -649,6 +664,7 @@ for (const accepted of [true, false]) {
const sendResult = new Promise<boolean>((done) => { resolve = done; });
let sentQuotes: readonly { text: string; comment?: string }[] | undefined;
const ports: RevisionSendPorts<{ sourceSessionId: string; draftSessionId: string }> = {
+ captureSubmitSurface: () => () => true,
shellCopy: {
sideChatUnavailableTitle: '', sideChatUnavailableDescription: '',
sideChatContextPendingTitle: '', sideChatContextPendingDescription: '',
@@ -868,3 +884,39 @@ test('Desktop backs the attachment port with the bridge reader; AppShell no long
const shell = readFileSync(fileURLToPath(new URL('../../../src/renderer/app-shell.tsx', import.meta.url)), 'utf8');
assert.deepEqual(shell.split('\n').filter((line) => /\battachments\s*\.\s*readBytes\b|\bonReadAttachmentBytes\b/.test(line)), []);
});
+
+test('#4695 review: StagedComposer begins the setting settlement at submit, before Session references load', async () => {
+ const events: string[] = [];
+ let finishReference!: (ready: boolean) => void;
+ const reference = new Promise<boolean>((resolve) => { finishReference = resolve; });
+ const begun: SessionSendSettlement[] = [];
+ const received: Array<SessionSendSettlement | undefined> = [];
+ const view = await mount({
+ waitForSessionReference: () => { events.push('wait-reference'); return reference; },
+ sessionSettings: {
+ settled: async () => true,
+ beginSettlement: (sessionId) => {
+ events.push(`begin:${sessionId}`);
+ const settlement = { settled: async () => false, release: () => { events.push('release'); } };
+ begun.push(settlement);
+ return settlement;
+ },
+ },
+ onSend: async (_text, _metadata, _staging, settlement) => {
+ events.push('send');
+ received.push(settlement);
+ return false;
+ },
+ });
+ await act(() => { view.composer.current!.appendDraft('draft-a', 'start by submitting a plan', []); });
+ await act(() => {
+ const form = view.container.querySelector('form');
+ assert.ok(form);
+ form.dispatchEvent(new window.Event('submit', { bubbles: true, cancelable: true }));
+ });
+ // A Plan write that fails while the reference loads lands inside this attempt.
+ assert.deepEqual(events, ['begin:draft-a', 'wait-reference']);
+ await act(async () => { finishReference(true); await Promise.resolve(); });
+ assert.deepEqual(events, ['begin:draft-a', 'wait-reference', 'send', 'release']);
+ assert.equal(received[0], begun[0], 'the submit\'s own settlement reaches onSend');
+});
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..76c1970450 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,196 @@ 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);
+});
+
+type TwoChannelController = ReturnType<typeof useSessionSettingIntent<{ plan: string; orchestration: string }>>;
+
+function mountTwoChannels() {
+ 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 writes = { plan: [] as Array<ReturnType<typeof deferred<boolean>>>, orchestration: [] as Array<ReturnType<typeof deferred<boolean>>> };
+ const handle: { controller?: TwoChannelController } = {};
+ function TwoChannelHarness() {
+ const writer = (channel: 'plan' | 'orchestration') => () => {
+ const result = deferred<boolean>();
+ writes[channel].push(result);
+ return result.promise;
+ };
+ handle.controller = useSessionSettingIntent<{ plan: string; orchestration: string }>({
+ catalog: { revision: () => 0, subscribeChanged: () => () => {} },
+ refreshCatalog: async () => {},
+ channels: {
+ plan: { write: writer('plan'), onWriteError: () => {} },
+ orchestration: { write: writer('orchestration'), onWriteError: () => {} },
+ },
+ });
+ return null;
+ }
+ return {
+ root,
+ writes,
+ controller: () => handle.controller!,
+ render: () => act(async () => { root.render(createElement(TwoChannelHarness)); }),
+ };
+}
+
+test('#4695 review: a write that starts and fails while a send waits still stops it', async () => {
+ const h = mountTwoChannels();
+ await h.render();
+ await act(async () => { void h.controller().request('orchestration', 'session-1', 'swarm'); });
+ const waiting = h.controller().settled('session-1');
+ // Plan is requested while the send waits on orchestration, and fails first.
+ await act(async () => { void h.controller().request('plan', 'session-1', 'plan'); });
+ await act(async () => { h.writes.plan[0]!.resolve(false); await Promise.resolve(); });
+ await act(async () => { h.writes.orchestration[0]!.resolve(true); });
+ assert.equal(await waiting, false);
+});
+
+test('#4695 review: a settlement begun at submit sees a failure that lands before it is awaited', async () => {
+ const h = mountTwoChannels();
+ await h.render();
+ await act(async () => { void h.controller().request('plan', 'session-1', 'plan'); });
+ const settlement = h.controller().beginSettlement('session-1');
+ // The Composer is still loading a Session reference when Plan fails.
+ await act(async () => { h.writes.plan[0]!.resolve(false); await Promise.resolve(); });
+ assert.equal(await settlement.settled(), false);
+ settlement.release();
+ // The attempt is over: a later explicit retry is not blocked by it.
+ assert.equal(await h.controller().settled('session-1'), true);
+});
+
+test('#4695 review: a released settlement ignores later writes', async () => {
+ const h = mountTwoChannels();
+ await h.render();
+ const settlement = h.controller().beginSettlement('session-1');
+ settlement.release();
+ await act(async () => { void h.controller().request('plan', 'session-1', 'plan'); });
+ await act(async () => { h.writes.plan[0]!.resolve(false); await Promise.resolve(); });
+ assert.equal(await settlement.settled(), true);
+});
+
+test('#4695 review: a write that throws settles false and does not block a retry', async () => {
+ 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;
+ let fail!: (error: Error) => void;
+ const write = new Promise<boolean>((_resolve, reject) => { fail = reject; });
+ const mounted = { controller: undefined as SessionSettingIntentController<string> | undefined };
+ await act(async () => {
+ root.render(createElement(LatestIntentHarness, {
+ capture: (next) => { mounted.controller = next; },
+ write: () => write,
+ }));
+ });
+ await act(async () => { void mounted.controller!.request('setting', 'session-1', 'plan'); });
+ const waiting = mounted.controller!.settled('session-1');
+ await act(async () => { fail(new Error('Host unavailable')); await waiting.catch(() => {}); });
+ assert.equal(await waiting, false);
+ assert.equal(await mounted.controller!.settled('session-1'), true);
+});
+
+for (const ending of ['rejected', 'cleared', 'unmounted'] as const) {
+ test(`#4695 review: settled resolves false, without hanging, when the write is ${ending} mid-wait`, async () => {
+ const h = mountTwoChannels();
+ await h.render();
+ await act(async () => { void h.controller().request('plan', 'session-1', 'plan'); });
+ const controller = h.controller();
+ const waiting = controller.settled('session-1');
+ await act(async () => {
+ if (ending === 'rejected') h.writes.plan[0]!.resolve(false);
+ if (ending === 'cleared') controller.clear('session-1');
+ if (ending === 'unmounted') h.root.unmount();
+ });
+ assert.equal(await waiting, false);
+ if (ending === 'unmounted') mountedRoot = undefined;
+ else assert.equal(await h.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..87b7cf9073
--- /dev/null
+++ b/apps/desktop/src/renderer/application/contracts/session-settings-settlement.ts
@@ -0,0 +1,52 @@
+/*
+ * 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>;
+ /**
+ * Starts observing one submission attempt at the user's submit, so writes
+ * that fail while it prepares (reference loading, revision copy) still
+ * stop it. The caller must `release()` it when the attempt ends.
+ */
+ beginSettlement(sessionId: string): SessionSendSettlement;
+}
+
+/** One submission attempt's view of its Session's setting writes. */
+export interface SessionSendSettlement {
+ settled(): Promise<boolean>;
+ release(): void;
+}
+
+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 97b644f077..392a671876 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/composer-submit.ts b/apps/desktop/src/renderer/features/conversation/controller/composer-submit.ts
index 0b3f88c928..e66e52f4b3 100644
--- a/apps/desktop/src/renderer/features/conversation/controller/composer-submit.ts
+++ b/apps/desktop/src/renderer/features/conversation/controller/composer-submit.ts
@@ -41,6 +41,12 @@ export type ComposerSlashCommand =
| { kind: 'graph'; command: ParsedGraphCommand }
| { kind: 'swarm'; command: ParsedSwarmCommand };
+/** Whether a submit starts a turn, which the Host runs under the Session's settings. */
+function startsTurn(command: ComposerSlashCommand | null): boolean {
+ if (!command) return true;
+ return (command.kind === 'swarm' || command.kind === 'graph') && command.command.kind === 'run_once';
+}
+
export interface RevisionDraftIdentity {
sourceSessionId: string;
draftSessionId: string;
@@ -79,6 +85,18 @@ export interface RevisionSendShellCopy {
* tests must call it rather than re-implementing its ordering.
*/
export interface RevisionSendPorts<TDraft extends RevisionDraftIdentity> {
+ /**
+ * #4695: the Session's setting writes observed since the user's submit.
+ * Settled before a revision copies the Session or the send starts.
+ */
+ sendSettlement?: { settled(): Promise<boolean> };
+ /**
+ * Captures the surface and selection this submit came from; the returned
+ * check says whether the user is still on it. Navigation keeps the Session
+ * id, so the id alone cannot answer that (#1433). Required so the
+ * production wiring cannot be dropped silently.
+ */
+ captureSubmitSurface: () => () => boolean;
shellCopy: RevisionSendShellCopy;
toastApi: {
info(title: string, description?: string): void;
@@ -172,14 +190,23 @@ export function createStagedFollowUp(ports: {
*/
export function createRevisionAwareOnSend<TDraft extends RevisionDraftIdentity>(
ports: RevisionAwareOnSendPorts<TDraft>,
-): (text: string, metadata?: ComposerSendMetadata, captured?: ComposerStagingSubmission) => Promise<boolean | void> {
- return (text, metadata, captured) => {
+): (
+ text: string,
+ metadata?: ComposerSendMetadata,
+ captured?: ComposerStagingSubmission,
+ settlement?: { settled(): Promise<boolean> },
+) => Promise<boolean | void> {
+ return (text, metadata, captured, settlement) => {
const staging = captured ?? ports.captureStaging();
return composerSend({
pending: staging.submittableAttachments,
retainAttachments: staging.retainAttachments,
setPending: ports.setNewTaskSendPending,
- send: (value, context) => revisionAwareSend({ ...ports, captureStaging: () => staging }, value, context),
+ send: (value, context) => revisionAwareSend({
+ ...ports,
+ captureStaging: () => staging,
+ ...(settlement ? { sendSettlement: settlement } : {}),
+ }, value, context),
})(text, metadata);
};
}
@@ -220,6 +247,20 @@ export async function revisionAwareSend<TDraft extends RevisionDraftIdentity>(
if (queued) delete ports.retractedWorkspaceReferencesRef.current[sessionId];
return queued;
}
+ // #4695: settle before a revision copies the source Session's settings and
+ // before the send reads them; a failed write keeps the draft. Only a submit
+ // that starts a turn runs under those settings, so local commands skip it.
+ const settlement = startsTurn(slashCommand) ? ports.sendSettlement : undefined;
+ if (settlement) {
+ const surfaceIsCurrent = ports.captureSubmitSurface();
+ if (
+ !(await settlement.settled()) ||
+ ports.activeIdRef.current !== sessionId ||
+ !surfaceIsCurrent()
+ ) {
+ return false;
+ }
+ }
if (revisionSend && revision) {
const actionCopy = ports.revisionUnavailableCopy;
if (slashCommand) {
@@ -229,6 +270,9 @@ export async function revisionAwareSend<TDraft extends RevisionDraftIdentity>(
// The attachments / mixed-context refusals live inside the revision
// lifecycle (prepareRevisionSend), which toasts and stops the send.
if (!(await ports.prepareRevisionSend(text))) return false;
+ // A source write can still fail while the copy is prepared. The child
+ // stays prepared, so an explicit retry sends into it like any refusal.
+ if (settlement && !(await settlement.settled())) return false;
}
if (slashCommand?.kind === 'compact') {
const compactSessionId = ports.activeIdRef.current;
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..f1610cf430 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,
@@ -166,6 +169,15 @@ export function useComposerSubmission<Owner extends ComposerSurfaceOwner>(input:
captureStaging: staging.captureSubmission,
prepareRevisionSend: revision.prepareRevisionSend,
send: chat.send,
+ // The same owner and selection checks `chat.send` applies, captured before
+ // the submit waits on setting writes.
+ captureSubmitSurface: () => {
+ const owner = shell.captureOwner();
+ const selectionIsCurrent = commands.captureSelection();
+ const hadSession = Boolean(activeIdRef.current);
+ return () => selectionIsCurrent() &&
+ (hadSession ? shell.isOwnerActive(owner) : shell.isNewChatOwnerActive(owner));
+ },
completeRevisionCopyAttempt: completeTurnRevisionCopyAttempt,
parseSlashCommand: parseDesktopSlashCommand,
mergeWorkspaceReferences,
diff --git a/apps/desktop/src/renderer/features/conversation/ui/staged-composer.tsx b/apps/desktop/src/renderer/features/conversation/ui/staged-composer.tsx
index 5de2369ab5..780f4b011d 100644
--- a/apps/desktop/src/renderer/features/conversation/ui/staged-composer.tsx
+++ b/apps/desktop/src/renderer/features/conversation/ui/staged-composer.tsx
@@ -17,8 +17,12 @@
* under the License.
*/
-import type { ComponentProps } from 'react';
+import { useRef, type ComponentProps } from 'react';
import { Composer, type ComposerSendMetadata } from '@maka/ui';
+import {
+ useSessionSettingsSettlement,
+ type SessionSendSettlement,
+} from '../../../application/contracts/session-settings-settlement.js';
import type { ComposerStagingSubmission } from '../model/composer-staging-contract.js';
import { captureComposerStaging } from '../controller/capture-composer-staging.js';
import { useComposerStaging } from './composer-staging-context.js';
@@ -32,16 +36,35 @@ export type ComposerStagingProp =
export function StagedComposer({
stagingEnabled, canStageContext, contextPickEnabled, directoryPickerEnabled, ...props
}: Omit<ComponentProps<typeof Composer>, ComposerStagingProp | 'onSend'> & {
- readonly onSend: (text: string, metadata?: ComposerSendMetadata, staging?: ComposerStagingSubmission) => boolean | void | Promise<boolean | void>;
+ readonly onSend: (
+ text: string,
+ metadata?: ComposerSendMetadata,
+ staging?: ComposerStagingSubmission,
+ settlement?: SessionSendSettlement,
+ ) => boolean | void | Promise<boolean | void>;
readonly stagingEnabled: boolean;
readonly canStageContext: boolean;
readonly contextPickEnabled: boolean;
readonly directoryPickerEnabled: boolean;
}) {
const staging = useComposerStaging();
+ const sessionSettings = useSessionSettingsSettlement();
+ // #4695: the attempt starts at the user's submit, before the Composer waits
+ // on Session references or the send prepares a revision, so a setting write
+ // that fails in between still stops this send.
+ const settlementRef = useRef<SessionSendSettlement | undefined>(undefined);
return <Composer {...props} onSend={(text, metadata) =>
- props.onSend(text, metadata, captureComposerStaging(staging, staging.draftKey))} {...(stagingEnabled ? {
- retainSendContext: () => staging.retainAttachments(staging.submittableAttachments),
+ props.onSend(text, metadata, captureComposerStaging(staging, staging.draftKey), settlementRef.current)} {...(stagingEnabled ? {
+ retainSendContext: () => {
+ const releaseAttachments = staging.retainAttachments(staging.submittableAttachments);
+ const settlement = props.draftKey ? sessionSettings?.beginSettlement(props.draftKey) : undefined;
+ settlementRef.current = settlement;
+ return () => {
+ releaseAttachments();
+ settlement?.release();
+ if (settlementRef.current === settlement) settlementRef.current = undefined;
+ };
+ },
pendingAttachments: staging.pendingAttachments,
onRemoveAttachment: staging.removeAttachment,
onPickAttachments: contextPickEnabled ? staging.pickAttachments : undefined,
diff --git a/apps/desktop/src/renderer/features/session-settings/README.md b/apps/desktop/src/renderer/features/session-settings/README.md
index c91178f002..ddee10e9df 100644
--- a/apps/desktop/src/renderer/features/session-settings/README.md
+++ b/apps/desktop/src/renderer/features/session-settings/README.md
@@ -70,6 +70,16 @@ 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.
+- `beginSettlement(sessionId)` observes one submission attempt: the Session's
+ writes in flight when the user submits and every write requested before the
+ attempt is released, so a write that starts and fails mid-wait still counts.
+ `StagedComposer` begins it at submit, before Session references load. A
+ submit that starts a turn settles it before an edit-and-resend copies the
+ Session and again after the copy, and re-checks the surface and selection it
+ was submitted from, since navigation keeps the Session id. A failed write
+ keeps the draft; local slash commands do not wait. `settled(sessionId)` is the begin-await-release
+ shorthand the send path keeps as a fallback. The provider publishes both
+ through `application/contracts/session-settings-settlement.ts` (#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..648733a05d 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
@@ -29,6 +29,9 @@ export interface SessionSettingsReadState {
readonly newTask: NewTaskSettings;
}
+/** Without a controller no write can be in flight or start. */
+const SETTLED = Object.freeze({ settled: () => Promise.resolve(true), release: () => {} });
+
const EMPTY_STATE: SessionSettingsReadState = {
overlays: { modelConfiguration: {}, permissionMode: {}, planMode: {}, orchestrationMode: {} },
newTask: { planMode: false, orchestrationMode: 'default' },
@@ -46,6 +49,9 @@ 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),
+ beginSettlement: (id) => controller?.beginSettlement(id) ?? SETTLED,
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..4311a2715b 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,8 @@ export function useSessionSettingsController<Owner extends { sessionId?: string
return {
clear: intent.clear,
+ settled: intent.settled,
+ beginSettlement: intent.beginSettlement,
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..cb8365a6b7 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
@@ -21,6 +21,7 @@ import type { OrchestrationMode } from '@maka/core/orchestration';
import type { PermissionMode } from '@maka/core/permission';
import type { ThinkingLevel } from '@maka/core/model-thinking';
import type { ChatDefaultPermissionMode } from '@maka/core/settings';
+import type { SessionSettingSettlement } from '@maka/ui';
import type { SessionCatalogController } from '../../../application/contracts/session-catalog/session-catalog-state.js';
import type { SessionModelConfigurationIntent, SessionModelTarget } from '../session-model-configuration-intent.js';
@@ -71,6 +72,17 @@ 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>;
+ /**
+ * Observes the Session's setting writes for one submission attempt, from
+ * the moment the user submits until `release()`; see `settled` for results.
+ */
+ beginSettlement(sessionId: string): SessionSettingSettlement;
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..4167ba4c1c 100644
--- a/packages/ui/src/session-setting-intent.ts
+++ b/packages/ui/src/session-setting-intent.ts
@@ -84,6 +84,30 @@ export interface SessionSettingIntentController<Values extends object> {
value: Values[Channel],
): Promise<boolean>;
clear(sessionId: string): void;
+ /**
+ * Starts observing `sessionId`'s setting writes for one submission attempt:
+ * every write in flight now and every write requested before `release()`.
+ * Begin it when the user submits, before any other await, so a write that
+ * fails while the submission prepares is still attributed to it.
+ */
+ beginSettlement(sessionId: string): SessionSettingSettlement;
+ /** `beginSettlement`, awaited and released in one call. */
+ settled(sessionId: string): Promise<boolean>;
+}
+
+export interface SessionSettingSettlement {
+ /**
+ * Resolves once every observed write has finished: true when all of them
+ * committed (or there were none), false when any failed, was cleared, or the
+ * owner unmounted. Writes requested while this waits are awaited too.
+ */
+ settled(): Promise<boolean>;
+ /** Stops observing; later writes no longer affect this attempt. */
+ release(): void;
+}
+
+interface SettlementObserver {
+ readonly completions: Promise<boolean>[];
}
type AnyIntent = SettingIntent<unknown>;
@@ -122,6 +146,7 @@ export function useSessionSettingIntent<Values extends object>(
const optionsRef = useRef(options);
optionsRef.current = options;
const intentsRef = useRef(new Map<keyof Values, Map<string, AnyIntent>>());
+ const observersRef = useRef(new Map<string, Set<SettlementObserver>>());
const mountedRef = useRef(false);
const [overlayByChannel, setOverlayByChannel] = useState<
SessionSettingIntentOverlays<Values>
@@ -206,6 +231,14 @@ export function useSessionSettingIntent<Values extends object>(
};
}, []);
+ /** Attributes a write's outcome to every settlement observing its Session. */
+ const observe = useCallback((sessionId: string, completion: Promise<boolean>) => {
+ for (const observer of observersRef.current.get(sessionId) ?? []) {
+ observer.completions.push(completion);
+ }
+ return completion;
+ }, []);
+
const request = useCallback(<Channel extends keyof Values>(
channel: Channel,
sessionId: string,
@@ -226,7 +259,7 @@ export function useSessionSettingIntent<Values extends object>(
}
existing.desired = value;
setOverlay(channel, sessionId, value);
- if (existing.inFlight) return existing.completion;
+ if (existing.inFlight) return observe(sessionId, existing.completion);
}
const intent = createIntent(value, existing);
@@ -296,8 +329,8 @@ export function useSessionSettingIntent<Values extends object>(
}
})();
- return intent.completion;
- }, [isEqual, reconcile, setOverlay]);
+ return observe(sessionId, intent.completion);
+ }, [isEqual, observe, reconcile, setOverlay]);
const clear = useCallback((sessionId: string): void => {
for (const [channel, intents] of intentsRef.current) {
@@ -308,5 +341,47 @@ export function useSessionSettingIntent<Values extends object>(
}
}, [setOverlay]);
- return { overlayByChannel, request, clear };
+ const beginSettlement = useCallback((sessionId: string): SessionSettingSettlement => {
+ const observer: SettlementObserver = { completions: [] };
+ for (const intents of intentsRef.current.values()) {
+ const intent = intents.get(sessionId);
+ if (intent?.inFlight) observer.completions.push(intent.completion);
+ }
+ let observers = observersRef.current.get(sessionId);
+ if (!observers) {
+ observers = new Set();
+ observersRef.current.set(sessionId, observers);
+ }
+ observers.add(observer);
+ const release = () => {
+ const current = observersRef.current.get(sessionId);
+ current?.delete(observer);
+ if (current?.size === 0) observersRef.current.delete(sessionId);
+ };
+ return {
+ async settled() {
+ let succeeded = true;
+ // A write requested while earlier ones are awaited joins the list, and
+ // its outcome counts even if it finished before this loop saw it.
+ for (let awaited = 0; awaited < observer.completions.length;) {
+ const batch = observer.completions.slice(awaited);
+ awaited += batch.length;
+ if ((await Promise.all(batch)).includes(false)) succeeded = false;
+ }
+ return succeeded && mountedRef.current;
+ },
+ release,
+ };
+ }, []);
+
+ const settled = useCallback(async (sessionId: string): Promise<boolean> => {
+ const settlement = beginSettlement(sessionId);
+ try {
+ return await settlement.settled();
+ } finally {
+ settlement.release();
+ }
+ }, [beginSettlement]);
+
+ return { overlayByChannel, request, clear, beginSettlement, settled };
}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org