Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 28 additions & 4 deletions apps/desktop/src/renderer/settings/general-settings-page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,10 @@ export function GeneralSettingsPage(props: {
patch: Parameters<typeof window.maka.settings.update>[0],
): Promise<UpdateAppSettingsResult>;
onRefreshConnections(): Promise<void>;
connectionsReadGeneration: number;
getConnectionsReadGeneration(): number;
getRuntimeHostTargetRevision(): number;
runtimeHostGenerationKey: string;
onRetryRuntimeHost(): Promise<void>;
}) {
const host = useOptionalRuntimeHostSettingsTarget();
Expand Down Expand Up @@ -294,6 +298,7 @@ export function GeneralSettingsPage(props: {
</SettingsSection>
{showRuntimeHostDefaults ? (
<GeneralDefaultsCard
key={props.runtimeHostGenerationKey}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] The synchronous targetRevision fence below already covers the pre-unmount window, so this remount is no longer what keeps a superseded save from acting. Its remaining job is narrower: dropping a pending optimistic pick stranded in @maka/ui when a fenced save returns early and no read is ever accepted. That is worth keeping, but it is not written down, so the next reader will see two guards for one hazard and delete this one. One line of comment here naming what the remount still owns would prevent that.

connections={props.connections}
defaultSlug={props.defaultSlug}
connectionsBridge={props.connectionsBridge}
Expand All @@ -304,6 +309,9 @@ export function GeneralSettingsPage(props: {
settingsInteractive={runtimeHostSettingsInteractive}
showSettingsPlaceholder={showRuntimeHostSettingsPlaceholder}
onRefresh={props.onRefreshConnections}
connectionsReadGeneration={props.connectionsReadGeneration}
getConnectionsReadGeneration={props.getConnectionsReadGeneration}
getRuntimeHostTargetRevision={props.getRuntimeHostTargetRevision}
permissionMode={props.settings.chatDefaults.permissionMode}
thinkingLevel={props.settings.chatDefaults.thinkingLevel}
onUpdate={props.onUpdate}
Expand Down Expand Up @@ -500,6 +508,9 @@ function GeneralDefaultsCard(props: {
settingsInteractive: boolean;
showSettingsPlaceholder: boolean;
onRefresh(): Promise<void>;
connectionsReadGeneration: number;
getConnectionsReadGeneration(): number;
getRuntimeHostTargetRevision(): number;
permissionMode: ChatDefaultPermissionMode;
thinkingLevel?: ThinkingLevel;
onUpdate(
Expand Down Expand Up @@ -549,6 +560,14 @@ function GeneralDefaultsCard(props: {
if (!props.connectionsBridge || !props.connectionsInteractive) return;
const releaseSave = persistGuard.begin("default-model");
if (!releaseSave) return;
// Fence this save to the Host generation it started in, synchronously via
// the request authority (bumped by selectTarget on an epoch change before
// React renders) — not by relying on unmount, which the old continuation
// can outrun in the window between the authority's setState and commit.
const startTargetRevision = props.getRuntimeHostTargetRevision();
const isCurrentEpoch = () =>
mountedRef.current &&
props.getRuntimeHostTargetRevision() === startTargetRevision;
setSaving(true);
try {
const parsed = parseModelChoiceValue(nextValue);
Expand All @@ -560,20 +579,24 @@ function GeneralDefaultsCard(props: {
}
: null,
);
if (!mountedRef.current) return;
if (!isCurrentEpoch()) return;
await props.onRefresh();
} catch (error) {
if (mountedRef.current) {
if (isCurrentEpoch()) {
toast.error(
copy.saveDefaultModelFailed,
settingsActionErrorMessage(error, locale),
undefined,
host ? { profileId: host.profileId } : undefined,
);
}
// Re-throw so ModelPicker rolls back its optimistic pick to the persisted
// model — the trigger owns the optimistic value (@maka/ui), fed the
// connections read generation via props; this row adds no local state.
throw error;
} finally {
releaseSave();
if (mountedRef.current) setSaving(false);
if (isCurrentEpoch()) setSaving(false);
}
}

Expand Down Expand Up @@ -663,11 +686,12 @@ function GeneralDefaultsCard(props: {
<ModelPicker
groups={modelGroups}
value={selectedValue}
committedGeneration={props.connectionsReadGeneration}
getReadGeneration={props.getConnectionsReadGeneration}
leadingOption={{ value: "", label: copy.notSet }}
renderProviderMark={(type) => <ProviderBrandMark type={type} />}
ariaLabel={copy.defaultModel}
disabled={saving || !props.connectionsInteractive}
loading={saving}
triggerClassName="settingsModelPickerTrigger"
onValueChange={persistDefault}
/>
Expand Down
16 changes: 16 additions & 0 deletions apps/desktop/src/renderer/settings/settings-request-authority.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,22 @@ export function createSettingsRequestAuthority(
return ticket(key, connectionsReadGeneration);
},

// The latest connections read generation issued so far. A read barrier
// captured here right after a write is exceeded only by reads issued
// afterwards (the caller's post-write refresh), never by ones already in
// flight — see useOptimisticSelection.
currentConnectionsReadGeneration(): number {
return connectionsReadGeneration;
},

// The current target revision, bumped synchronously by selectTarget on any
// Host key/epoch change (before React renders). A save that captures this at
// start and re-checks it in its async continuation is fenced to its epoch
// synchronously — it does not depend on the card unmounting.
currentTargetRevision(): number {
return targetRevision;
},

acceptsConnectionsRead(candidate: SettingsRequestTicket): boolean {
return isCurrentTarget(candidate) &&
candidate.requestGeneration === connectionsReadGeneration;
Expand Down
7 changes: 7 additions & 0 deletions apps/desktop/src/renderer/settings/settings-snapshot-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,13 @@ import type {
export interface RuntimeHostConnectionsSnapshot {
readonly connections: ProjectedLlmConnection[];
readonly defaultSlug: string | null;
/**
* The connections read generation that produced this snapshot. Advances only
* on an accepted read, so the default-model row's optimistic pick clears
* strictly on a read issued after its write. Optional: a cache-restored
* snapshot from a prior session carries no live generation.
*/
readonly readGeneration?: number;
}

export interface SettingsSnapshotCache {
Expand Down
23 changes: 23 additions & 0 deletions apps/desktop/src/renderer/settings/settings-surface.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,10 @@ function SettingsSurfaceContent(
);
const connections = selectedConnections?.connections ?? [];
const defaultSlug = selectedConnections?.defaultSlug ?? null;
// Read generation of the shown snapshot (carried on the snapshot itself, so
// no extra state here); drives the default-model row's optimistic read
// barrier in @maka/ui ModelPicker.
const committedConnectionsReadGeneration = selectedConnections?.readGeneration ?? 0;
const sectionScope = settingsSectionScope(section);
const showsRuntimeHost = sectionScope !== 'client';
const requiresRuntimeHost = sectionScope === 'runtime-host';
Expand Down Expand Up @@ -577,6 +581,9 @@ function SettingsSurfaceContent(
const next = {
connections: snapshot.connections,
defaultSlug: snapshot.defaultConnection,
// The accepted read's generation, so the row's optimistic pick clears
// only on a read issued after its write (see @maka/ui ModelPicker).
readGeneration: ticket.requestGeneration,
};
snapshotCache.commitRuntimeHostConnectionsRead(key, next);
setRuntimeHostConnections(completeSettingsResourceLoad(key, next));
Expand Down Expand Up @@ -1018,6 +1025,14 @@ function SettingsSurfaceContent(
themePref={props.themePref}
themePalette={props.themePalette}
onRefreshConnections={reloadConnections}
connectionsReadGeneration={committedConnectionsReadGeneration}
getConnectionsReadGeneration={
runtimeHostRequestAuthority.currentConnectionsReadGeneration
}
getRuntimeHostTargetRevision={
runtimeHostRequestAuthority.currentTargetRevision
}
runtimeHostGenerationKey={`${selectedRuntimeHostKey ?? "client"}@${selectedRuntimeHostEpoch ?? "unversioned"}`}
onUpdateSettings={updateSettings}
onReloadSettings={reloadRuntimeHostSettings}
onReloadClientSettings={reloadClientSettings}
Expand Down Expand Up @@ -1075,6 +1090,10 @@ function SettingsPageBody(props: {
themePref: ThemePreference;
themePalette: ThemePalette;
onRefreshConnections(): Promise<void>;
connectionsReadGeneration: number;
getConnectionsReadGeneration(): number;
getRuntimeHostTargetRevision(): number;
runtimeHostGenerationKey: string;
onUpdateSettings(patch: Parameters<typeof window.maka.settings.update>[0]): Promise<UpdateAppSettingsResult>;
onReloadSettings(): Promise<void>;
onReloadClientSettings(): Promise<void>;
Expand Down Expand Up @@ -1156,6 +1175,10 @@ function SettingsPageBody(props: {
: undefined}
onUpdate={props.onUpdateSettings}
onRefreshConnections={props.onRefreshConnections}
connectionsReadGeneration={props.connectionsReadGeneration}
getConnectionsReadGeneration={props.getConnectionsReadGeneration}
getRuntimeHostTargetRevision={props.getRuntimeHostTargetRevision}
runtimeHostGenerationKey={props.runtimeHostGenerationKey}
onRetryRuntimeHost={props.onRetryRuntimeHost}
/>
);
Expand Down
9 changes: 7 additions & 2 deletions apps/desktop/stories/settings/settings-pages.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1899,12 +1899,17 @@ export const GeneralHostGenerationRevalidation: Story = {
isDefault: true,
});

// The default-model row now remounts on the new Host generation (retiring
// the old epoch's save/optimistic state), so re-query rather than reuse the
// pre-epoch element, which detaches on remount.
await waitForStoryCondition(
() => tone.matches(':disabled') && defaultModel.matches(':disabled'),
() =>
tone.matches(':disabled') &&
(canvas.queryByRole('button', { name: '默认模型' })?.matches(':disabled') ?? false),
'Previous Runtime Host generation remained writable',
);
await expect(tone).toBeDisabled();
await expect(defaultModel).toBeDisabled();
await expect(canvas.getByRole('button', { name: '默认模型' })).toBeDisabled();
await expect(
canvas.getByRole('switch', { name: '完成时发送系统通知' }),
).toBeEnabled();
Expand Down
181 changes: 181 additions & 0 deletions packages/ui/src/__tests__/use-optimistic-selection.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
/*
* 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.
*/

/**
* The default-model row (Settings › 通用 › 默认模型) drives Astryx's Selector on
* the synchronous `onChange` path so the trigger never spins. On that path the
* Selector's own optimistic value never advances, so the row supplies the
* "reflect the pick immediately" half of the fix — this hook.
*
* The clear signal is a monotonic read GENERATION captured at the pick (the
* write's start), and these pin why that ordering point is the correct one:
*
* - a read already IN FLIGHT at pick time (generation ≤ floor) can only carry
* the pre-write value, so it must NOT clear the pick;
* - a read issued AFTER the pick (generation > floor) — the row's own refresh
* OR a concurrent external write's read that lands mid-write — reports a
* newer authority and MUST clear the pick, even if the row's own explicit
* refresh never lands (the production-order regression).
*
* Also covered: convergence to this pick / an external write / the prior value
* restored (A→B→A), a refresh that lands nothing keeping the pick, and cancel.
*/

import assert from 'node:assert/strict';
import { afterEach, test } from 'node:test';
import { act } from 'react';
import { createRoot } from 'react-dom/client';
import { parseHTML } from 'linkedom';
import { useOptimisticSelection, type OptimisticSelection } from '../use-optimistic-selection.js';

const originalGlobals = {
document: globalThis.document,
window: globalThis.window,
Element: globalThis.Element,
HTMLElement: globalThis.HTMLElement,
Node: globalThis.Node,
};
const originalActEnvironment = (globalThis as typeof globalThis & {
IS_REACT_ACT_ENVIRONMENT?: boolean;
}).IS_REACT_ACT_ENVIRONMENT;

let mountedRoot: ReturnType<typeof createRoot> | undefined;

afterEach(async () => {
if (mountedRoot) await act(() => mountedRoot?.unmount());
mountedRoot = undefined;
Object.assign(globalThis, {
...originalGlobals,
IS_REACT_ACT_ENVIRONMENT: originalActEnvironment,
});
});

interface Harness {
render(authoritative: string, committedGeneration: number): Promise<void>;
begin(next: string, floor: number): Promise<void>;
cancel(): Promise<void>;
value(): string | null;
}

async function mount(): Promise<Harness> {
const { document, window } = parseHTML('<main id="root"></main>');
const root = document.querySelector<HTMLElement>('#root');
assert.ok(root);
Object.assign(globalThis, {
document,
window,
Element: window.Element,
HTMLElement: window.HTMLElement,
Node: window.Node,
IS_REACT_ACT_ENVIRONMENT: true,
});

const api: { current: OptimisticSelection | null } = { current: null };
function Probe({ authoritative, committedGeneration }: { authoritative: string; committedGeneration: number }) {
const selection = useOptimisticSelection(authoritative, committedGeneration);
api.current = selection;
return <span data-value={selection.value} />;
}

mountedRoot = createRoot(root);
const el = () => root.querySelector('span');
return {
async render(authoritative, committedGeneration) {
await act(() =>
mountedRoot?.render(<Probe authoritative={authoritative} committedGeneration={committedGeneration} />),
);
},
async begin(next, floor) {
await act(() => api.current?.begin(next, floor));
},
async cancel() {
await act(() => api.current?.cancel());
},
value: () => el()?.getAttribute('data-value') ?? null,
};
}

test('a pick shows immediately', async () => {
const h = await mount();
await h.render('A', 5);
assert.equal(h.value(), 'A');

// Picked at floor 5 (the read generation issued as of the pick).
await h.begin('B', 5);
assert.equal(h.value(), 'B');
});

test('an in-flight read from before the pick (generation ≤ floor) does not clear', async () => {
const h = await mount();
await h.render('A', 5);
await h.begin('B', 5);
// A read that was already in flight at pick time commits the pre-write value
// at its own generation (≤ floor). It must not clear the pick.
await h.render('A', 5);
assert.equal(h.value(), 'B');
});

test("the row's own refresh (generation past the floor) clears to this pick", async () => {
const h = await mount();
await h.render('A', 5);
await h.begin('B', 5);
await h.render('B', 6);
assert.equal(h.value(), 'B');
});

test('an after-the-pick read clears to authority even with no explicit refresh (ordering regression)', async () => {
const h = await mount();
await h.render('A', 5);
await h.begin('B', 5);
// A concurrent external write's read, issued after the pick, lands mid-write
// reporting C. It is > floor, so it clears the pick and settles on C — WITHOUT
// the row's own refresh ever running. Under the old "arm the floor after the
// refresh resolves" ordering this read was absorbed into the floor and, if the
// refresh then failed, C was masked by B forever.
await h.render('C', 6);
assert.equal(h.value(), 'C');
});

test('A→B→A: authority restored to the pre-pick value still clears the pick', async () => {
const h = await mount();
await h.render('A', 5);
await h.begin('B', 5);
await h.render('A', 6);
assert.equal(h.value(), 'A');
});

test('a refresh that lands no after-the-pick read keeps the pick (does not revert to stale)', async () => {
const h = await mount();
await h.render('A', 5);
await h.begin('B', 5);
// No read newer than the floor ever commits (refresh failed/invalidated). The
// write persisted B, so B must remain shown.
await h.render('A', 5);
assert.equal(h.value(), 'B');
});

test('cancel rolls back to the authoritative value (write threw)', async () => {
const h = await mount();
await h.render('A', 5);
await h.begin('B', 5);
assert.equal(h.value(), 'B');

await h.cancel();
assert.equal(h.value(), 'A');
});
Loading