mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-03 05:36:08 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
072160adb6 | ||
|
|
79cc380d50 |
@@ -1,6 +1,7 @@
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { mergeCreateAgentSelectionPreferences } from "@/create-agent-preferences/preferences";
|
||||
import { applyLiveAgentConfig } from "@/composer/agent-mutations";
|
||||
import { useFormPreferences } from "@/hooks/use-form-preferences";
|
||||
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
@@ -171,22 +172,22 @@ export function useAgentProfilePicker(
|
||||
return;
|
||||
}
|
||||
persistSelection(reconciled);
|
||||
if (!client) {
|
||||
if (!client || !serverId) {
|
||||
return;
|
||||
}
|
||||
void client
|
||||
.applyAgentConfig(
|
||||
target.agentId,
|
||||
toAgentConfigApply(reconciled),
|
||||
target.currentProvider ? { expectedProvider: target.currentProvider } : undefined,
|
||||
)
|
||||
void applyLiveAgentConfig({
|
||||
serverId,
|
||||
agentId: target.agentId,
|
||||
config: toAgentConfigApply(reconciled),
|
||||
expectedProvider: target.currentProvider ?? undefined,
|
||||
})
|
||||
.then((notice) => showProviderNoticeToast(toast, notice))
|
||||
.catch((error) => {
|
||||
console.warn("[useAgentProfilePicker] applyAgentConfig failed", error);
|
||||
toast.error(toErrorMessage(error));
|
||||
});
|
||||
},
|
||||
[applicableProfiles, client, persistSelection, target, toast],
|
||||
[applicableProfiles, client, persistSelection, serverId, target, toast],
|
||||
);
|
||||
|
||||
return useMemo(
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Pressable, Text, View, type LayoutChangeEvent } from "react-native";
|
||||
import { Gesture, GestureDetector } from "react-native-gesture-handler";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
@@ -54,6 +54,22 @@ export function SteppedSlider<T extends string>({
|
||||
const travelWidthRef = useRef(0);
|
||||
const [scrubIndex, setScrubIndex] = useState<number | null>(null);
|
||||
const scrubIndexRef = useRef<number | null>(null);
|
||||
const suppressNextTapRef = useRef(false);
|
||||
const suppressTapTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
// Keep latest callbacks and options off `panGesture`'s deps so a re-render mid-drag never
|
||||
// recreates the Gesture.Pan instance and cancels the active scrub.
|
||||
const latestRef = useRef({ options, value, onValueChange, onPreviewChange });
|
||||
latestRef.current = { options, value, onValueChange, onPreviewChange };
|
||||
|
||||
const clearSuppressNextTap = useCallback(() => {
|
||||
if (suppressTapTimerRef.current !== null) {
|
||||
clearTimeout(suppressTapTimerRef.current);
|
||||
suppressTapTimerRef.current = null;
|
||||
}
|
||||
suppressNextTapRef.current = false;
|
||||
}, []);
|
||||
|
||||
useEffect(() => clearSuppressNextTap, [clearSuppressNextTap]);
|
||||
|
||||
const selectedIndex = Math.max(
|
||||
0,
|
||||
@@ -66,51 +82,62 @@ export function SteppedSlider<T extends string>({
|
||||
travelWidthRef.current = event.nativeEvent.layout.width;
|
||||
}, []);
|
||||
|
||||
const updateScrubFromX = useCallback(
|
||||
(x: number) => {
|
||||
const nextIndex = resolveSliderIndexFromX(
|
||||
x - TRAVEL_EDGE,
|
||||
travelWidthRef.current,
|
||||
options.length,
|
||||
);
|
||||
if (nextIndex === scrubIndexRef.current) return;
|
||||
scrubIndexRef.current = nextIndex;
|
||||
setScrubIndex(nextIndex);
|
||||
const option = options[nextIndex];
|
||||
if (option) {
|
||||
onPreviewChange?.(option.value);
|
||||
triggerSelectionHaptic();
|
||||
}
|
||||
},
|
||||
[onPreviewChange, options],
|
||||
);
|
||||
const updateScrubFromX = useCallback((x: number) => {
|
||||
const { options: currentOptions, onPreviewChange: notifyPreview } = latestRef.current;
|
||||
const nextIndex = resolveSliderIndexFromX(
|
||||
x - TRAVEL_EDGE,
|
||||
travelWidthRef.current,
|
||||
currentOptions.length,
|
||||
);
|
||||
if (nextIndex === scrubIndexRef.current) return;
|
||||
scrubIndexRef.current = nextIndex;
|
||||
setScrubIndex(nextIndex);
|
||||
const option = currentOptions[nextIndex];
|
||||
if (option) {
|
||||
notifyPreview?.(option.value);
|
||||
triggerSelectionHaptic();
|
||||
}
|
||||
}, []);
|
||||
|
||||
const commitScrub = useCallback(() => {
|
||||
const finalIndex = scrubIndexRef.current;
|
||||
scrubIndexRef.current = null;
|
||||
setScrubIndex(null);
|
||||
onPreviewChange?.(null);
|
||||
const {
|
||||
options: currentOptions,
|
||||
value: currentValue,
|
||||
onValueChange: notifyChange,
|
||||
onPreviewChange: notifyPreview,
|
||||
} = latestRef.current;
|
||||
notifyPreview?.(null);
|
||||
if (finalIndex === null) return;
|
||||
const option = options[finalIndex];
|
||||
if (option && option.value !== value) {
|
||||
onValueChange(option.value);
|
||||
const option = currentOptions[finalIndex];
|
||||
if (option && option.value !== currentValue) {
|
||||
notifyChange(option.value);
|
||||
}
|
||||
}, [onPreviewChange, onValueChange, options, value]);
|
||||
}, []);
|
||||
|
||||
const cancelScrub = useCallback(() => {
|
||||
if (scrubIndexRef.current === null) return;
|
||||
scrubIndexRef.current = null;
|
||||
setScrubIndex(null);
|
||||
onPreviewChange?.(null);
|
||||
}, [onPreviewChange]);
|
||||
latestRef.current.onPreviewChange?.(null);
|
||||
}, []);
|
||||
|
||||
const canScrub = !disabled && options.length > 1;
|
||||
const panGesture = useMemo(
|
||||
() =>
|
||||
Gesture.Pan()
|
||||
.enabled(!disabled && options.length > 1)
|
||||
.enabled(canScrub)
|
||||
.activeOffsetX([-6, 6])
|
||||
.failOffsetY([-12, 12])
|
||||
.runOnJS(true)
|
||||
.onBegin((event) => {
|
||||
.onBegin(() => {
|
||||
clearSuppressNextTap();
|
||||
})
|
||||
// Start scrubbing only after horizontal intent wins over vertical scroll and tap.
|
||||
.onStart((event) => {
|
||||
suppressNextTapRef.current = true;
|
||||
updateScrubFromX(event.x);
|
||||
})
|
||||
.onUpdate((event) => {
|
||||
@@ -121,17 +148,29 @@ export function SteppedSlider<T extends string>({
|
||||
})
|
||||
.onFinalize((_, success) => {
|
||||
if (!success) cancelScrub();
|
||||
if (suppressNextTapRef.current) {
|
||||
// Defer past the click/onPress synthesized from the same pointerup (a microtask drains
|
||||
// between pointerup and click on web).
|
||||
suppressTapTimerRef.current = setTimeout(() => {
|
||||
suppressTapTimerRef.current = null;
|
||||
suppressNextTapRef.current = false;
|
||||
}, 0);
|
||||
}
|
||||
}),
|
||||
[cancelScrub, commitScrub, disabled, options.length, updateScrubFromX],
|
||||
[canScrub, cancelScrub, clearSuppressNextTap, commitScrub, updateScrubFromX],
|
||||
);
|
||||
|
||||
const handleSelectOption = useCallback(
|
||||
(optionValue: T) => {
|
||||
if (suppressNextTapRef.current) {
|
||||
clearSuppressNextTap();
|
||||
return;
|
||||
}
|
||||
if (disabled || optionValue === value) return;
|
||||
triggerSelectionHaptic();
|
||||
onValueChange(optionValue);
|
||||
},
|
||||
[disabled, onValueChange, value],
|
||||
[clearSuppressNextTap, disabled, onValueChange, value],
|
||||
);
|
||||
|
||||
const containerStyle = useMemo(() => [styles.container, disabled && styles.disabled], [disabled]);
|
||||
@@ -165,7 +204,7 @@ export function SteppedSlider<T extends string>({
|
||||
filled={index < activeIndex}
|
||||
/>
|
||||
))}
|
||||
<View style={thumbStyle} />
|
||||
<View style={thumbStyle} testID={testID ? `${testID}-thumb` : undefined} />
|
||||
</View>
|
||||
</View>
|
||||
<View style={styles.hitRow}>
|
||||
|
||||
@@ -8,6 +8,12 @@ import {
|
||||
resolveAgentModelSelection,
|
||||
resolveProviderSnapshotEntry,
|
||||
} from "@/composer/agent-controls/utils";
|
||||
import {
|
||||
setLiveAgentMode,
|
||||
setLiveAgentModel,
|
||||
setLiveAgentOptions,
|
||||
setLiveAgentThinkingOption,
|
||||
} from "@/composer/agent-mutations";
|
||||
import type { ComposerFocusOptions, ComposerModel, ComposerState } from "@/composer/model";
|
||||
import { filterSelectableModels } from "@/provider-selection/model-catalog";
|
||||
import { buildDraftStoreKey } from "@/stores/draft-keys";
|
||||
@@ -332,16 +338,16 @@ export function createAgentComposer(
|
||||
throw new Error("A running agent cannot change provider.");
|
||||
},
|
||||
async setModel(modelId) {
|
||||
await client().setAgentModel(agentId, modelId);
|
||||
await setLiveAgentModel({ serverId, agentId, modelId });
|
||||
},
|
||||
async setMode(modeId) {
|
||||
await client().setAgentMode(agentId, modeId);
|
||||
await setLiveAgentMode({ serverId, agentId, modeId });
|
||||
},
|
||||
async setThinking(thinkingOptionId) {
|
||||
await client().setAgentThinkingOption(agentId, thinkingOptionId);
|
||||
await setLiveAgentThinkingOption({ serverId, agentId, thinkingOptionId });
|
||||
},
|
||||
async setOptions(patch) {
|
||||
await client().setAgentOptions(agentId, patch);
|
||||
await setLiveAgentOptions({ serverId, agentId, patch });
|
||||
},
|
||||
async setMetadata(patch) {
|
||||
await client().setAgentMetadata(agentId, patch);
|
||||
|
||||
@@ -31,6 +31,11 @@ import {
|
||||
useStagedProviderSwitch,
|
||||
useStagedProviderSwitchStore,
|
||||
} from "@/composer/provider-switch";
|
||||
import {
|
||||
setLiveAgentModel,
|
||||
setLiveAgentOptions,
|
||||
setLiveAgentThinkingOption,
|
||||
} from "@/composer/agent-mutations";
|
||||
import { resolveProviderDefinition } from "@/utils/provider-definitions";
|
||||
import { mergeProviderPreferences, useFormPreferences } from "@/hooks/use-form-preferences";
|
||||
import {
|
||||
@@ -377,8 +382,6 @@ type AgentControlsSlice = {
|
||||
controls: AgentOptionControl[] | undefined;
|
||||
runtimeThinkingOptionId: string | null;
|
||||
thinkingOptionId: string | null | undefined;
|
||||
lastUsage: unknown;
|
||||
metadata: Record<string, JsonValue> | undefined;
|
||||
} | null;
|
||||
|
||||
function selectAgentControlsSlice(
|
||||
@@ -399,8 +402,6 @@ function selectAgentControlsSlice(
|
||||
controls: currentAgent.controls,
|
||||
runtimeThinkingOptionId: currentAgent.runtimeInfo?.thinkingOptionId ?? null,
|
||||
thinkingOptionId: currentAgent.thinkingOptionId,
|
||||
lastUsage: currentAgent.lastUsage,
|
||||
metadata: currentAgent.metadata,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1304,29 +1305,35 @@ export const AgentControls = memo(function AgentControls({
|
||||
);
|
||||
|
||||
const applyLiveModel = useCallback(
|
||||
async (modelId: string) => {
|
||||
(modelId: string) => {
|
||||
if (!client || !agentProvider) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await client.setAgentModel(agentId, modelId, { expectedProvider: agentProvider });
|
||||
await updatePreferences((current) =>
|
||||
const persistModel = () =>
|
||||
updatePreferences((current) =>
|
||||
mergeProviderPreferences({
|
||||
preferences: current,
|
||||
provider: agentProvider,
|
||||
updates: { model: modelId },
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
console.warn("[AgentControls] setAgentModel or persist preference failed", error);
|
||||
toast.error(toErrorMessage(error));
|
||||
}
|
||||
void setLiveAgentModel({
|
||||
serverId,
|
||||
agentId,
|
||||
modelId,
|
||||
expectedProvider: agentProvider,
|
||||
})
|
||||
.then((applied) => (applied ? persistModel() : undefined))
|
||||
.catch((error) => {
|
||||
console.warn("[AgentControls] setAgentModel or persist preference failed", error);
|
||||
toast.error(toErrorMessage(error));
|
||||
});
|
||||
},
|
||||
[agentId, agentProvider, client, toast, updatePreferences],
|
||||
[agentId, agentProvider, client, serverId, toast, updatePreferences],
|
||||
);
|
||||
|
||||
const handleSelectModel = useCallback(
|
||||
async (modelId: string) => {
|
||||
(modelId: string) => {
|
||||
if (activeStagedSwitch) {
|
||||
const nextModel = models?.find((candidate) => candidate.id === modelId);
|
||||
const preferredThinking =
|
||||
@@ -1345,7 +1352,7 @@ export const AgentControls = memo(function AgentControls({
|
||||
}));
|
||||
return;
|
||||
}
|
||||
await applyLiveModel(modelId);
|
||||
applyLiveModel(modelId);
|
||||
},
|
||||
[
|
||||
activeStagedSwitch,
|
||||
@@ -1364,7 +1371,7 @@ export const AgentControls = memo(function AgentControls({
|
||||
clearStagedProviderSwitch(serverId, agentId);
|
||||
const liveModelId = agent?.runtimeModelId ?? agent?.model ?? null;
|
||||
if (modelId && modelId !== liveModelId) {
|
||||
void applyLiveModel(modelId);
|
||||
applyLiveModel(modelId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -1399,7 +1406,7 @@ export const AgentControls = memo(function AgentControls({
|
||||
handleSelectProviderAndModel(provider, modelId);
|
||||
return;
|
||||
}
|
||||
void handleSelectModel(modelId);
|
||||
handleSelectModel(modelId);
|
||||
},
|
||||
[handleSelectModel, handleSelectProviderAndModel, supportsProviderSwitching],
|
||||
);
|
||||
@@ -1503,8 +1510,12 @@ export const AgentControls = memo(function AgentControls({
|
||||
console.warn("[AgentControls] persist thinking preference failed", error);
|
||||
});
|
||||
}
|
||||
void client
|
||||
.setAgentThinkingOption(agentId, thinkingOptionId, { expectedProvider: agentProvider })
|
||||
void setLiveAgentThinkingOption({
|
||||
serverId,
|
||||
agentId,
|
||||
thinkingOptionId,
|
||||
expectedProvider: agentProvider,
|
||||
})
|
||||
.then((notice) => showProviderNoticeToast(toast, notice))
|
||||
.catch((error) => {
|
||||
console.warn("[AgentControls] setAgentThinkingOption failed", error);
|
||||
@@ -1549,8 +1560,13 @@ export const AgentControls = memo(function AgentControls({
|
||||
).catch((error) => {
|
||||
console.warn("[AgentControls] persist option preference failed", error);
|
||||
});
|
||||
void client
|
||||
.setAgentOptions(agentId, { [key]: value }, { expectedProvider: agentProvider })
|
||||
void setLiveAgentOptions({
|
||||
serverId,
|
||||
agentId,
|
||||
patch: { [key]: value },
|
||||
expectedProvider: agentProvider,
|
||||
})
|
||||
.then((notice) => showProviderNoticeToast(toast, notice))
|
||||
.catch((error) => {
|
||||
console.warn("[AgentControls] setAgentOptions failed", error);
|
||||
toast.error(toErrorMessage(error));
|
||||
|
||||
@@ -0,0 +1,491 @@
|
||||
import React, { useCallback, useMemo } from "react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { GestureHandlerRootView } from "react-native-gesture-handler";
|
||||
import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { cdp } from "vitest/browser";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import type {
|
||||
AgentOptionControl,
|
||||
AgentProviderNotice,
|
||||
ProviderOptions,
|
||||
} from "@getpaseo/protocol/agent-types";
|
||||
import type { ToastApi } from "@/components/toast-host";
|
||||
import { ToastApiProvider } from "@/contexts/toast-api-context";
|
||||
import { useSessionStore, type Agent } from "@/stores/session-store";
|
||||
import {
|
||||
clearLiveAgentMutationsForServer,
|
||||
setLiveAgentOptions,
|
||||
setLiveAgentThinkingOption,
|
||||
} from "@/composer/agent-mutations";
|
||||
import { useAgentControlItems } from "./control-items";
|
||||
import { resolveComposerControlPresentation } from "./layout";
|
||||
import { useLiveAgentModeControl } from "./mode-control";
|
||||
import { AgentSheetHome, type AgentSheetControls } from "./sheet-home";
|
||||
|
||||
const SERVER_ID = "srv-live-settings";
|
||||
const AGENT_ID = "agent-1";
|
||||
const SHEET_FRAME_STYLE = { width: 390, height: 640, display: "flex" } as const;
|
||||
const GESTURE_ROOT_STYLE = { flex: 1 } as const;
|
||||
const PRESENTATION = resolveComposerControlPresentation("compact");
|
||||
const ignoreOpenSelect = () => undefined;
|
||||
|
||||
const THINKING_OPTIONS = [
|
||||
{ id: "off", label: "Off" },
|
||||
{ id: "low", label: "Low" },
|
||||
{ id: "medium", label: "Medium" },
|
||||
{ id: "high", label: "High" },
|
||||
{ id: "max", label: "Max" },
|
||||
] as const;
|
||||
|
||||
const CONTROLS: AgentOptionControl[] = [
|
||||
{ type: "toggle", key: "fast_mode", label: "Fast", defaultValue: false },
|
||||
{
|
||||
type: "select",
|
||||
key: "service_tier",
|
||||
label: "Speed",
|
||||
defaultValue: "default",
|
||||
choices: [
|
||||
{ value: "default", label: "Normal" },
|
||||
{ value: "fast", label: "Fast" },
|
||||
{ value: "flex", label: "Flex" },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
function deferred<T = AgentProviderNotice | null>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (error: unknown) => void;
|
||||
const promise = new Promise<T>((res, rej) => {
|
||||
resolve = res;
|
||||
reject = rej;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
function nextPaint(): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
requestAnimationFrame(() => resolve());
|
||||
});
|
||||
}
|
||||
|
||||
function createAgent(): Agent {
|
||||
const now = new Date("2026-12-01T12:00:00.000Z");
|
||||
return {
|
||||
serverId: SERVER_ID,
|
||||
id: AGENT_ID,
|
||||
provider: "claude",
|
||||
status: "running",
|
||||
turn: { phase: "open", turnId: "t1", startedAt: now, cancellationRequestId: null },
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
lastUserMessageAt: now,
|
||||
lastActivityAt: now,
|
||||
capabilities: {
|
||||
supportsStreaming: true,
|
||||
supportsSessionPersistence: true,
|
||||
supportsDynamicModes: true,
|
||||
supportsMcpServers: false,
|
||||
supportsReasoningStream: true,
|
||||
supportsToolInvocations: true,
|
||||
},
|
||||
currentModeId: "default",
|
||||
availableModes: [
|
||||
{ id: "default", label: "Default" },
|
||||
{ id: "plan", label: "Plan" },
|
||||
],
|
||||
pendingPermissions: [],
|
||||
persistence: null,
|
||||
title: "Running agent",
|
||||
cwd: "/repo",
|
||||
workspaceId: "ws-1",
|
||||
model: "claude-sonnet-4",
|
||||
thinkingOptionId: "low",
|
||||
runtimeInfo: {
|
||||
provider: "claude",
|
||||
sessionId: "s1",
|
||||
model: "claude-sonnet-4",
|
||||
modeId: "default",
|
||||
thinkingOptionId: "low",
|
||||
},
|
||||
options: { fast_mode: false, service_tier: "default" },
|
||||
controls: CONTROLS,
|
||||
parentAgentId: null,
|
||||
labels: {},
|
||||
};
|
||||
}
|
||||
|
||||
function pushServerUpdate(patch: Partial<Agent>): void {
|
||||
useSessionStore.getState().setAgents(SERVER_ID, (current) => {
|
||||
const existing = current.get(AGENT_ID);
|
||||
return existing ? new Map(current).set(AGENT_ID, { ...existing, ...patch }) : current;
|
||||
});
|
||||
}
|
||||
|
||||
function setupSession() {
|
||||
const calls: Array<{
|
||||
kind: string;
|
||||
value: unknown;
|
||||
gate: ReturnType<typeof deferred<AgentProviderNotice | null>>;
|
||||
}> = [];
|
||||
const record = (kind: string) => (_id: string, value: unknown) => {
|
||||
const gate = deferred<AgentProviderNotice | null>();
|
||||
calls.push({ kind, value, gate });
|
||||
return gate.promise;
|
||||
};
|
||||
const client = {
|
||||
setAgentThinkingOption: vi.fn(record("thinking")),
|
||||
setAgentMode: vi.fn(record("mode")),
|
||||
setAgentOptions: vi.fn(record("options")),
|
||||
setAgentModel: vi.fn(async () => undefined),
|
||||
applyAgentConfig: vi.fn(async () => null),
|
||||
};
|
||||
const store = useSessionStore.getState();
|
||||
store.initializeSession(SERVER_ID, client as unknown as DaemonClient);
|
||||
store.setAgents(SERVER_ID, new Map([[AGENT_ID, createAgent()]]));
|
||||
return calls;
|
||||
}
|
||||
|
||||
// Reads strictly from session-store — zero overlay merging in the view.
|
||||
function LiveSheet({ toast }: { toast: ToastApi }) {
|
||||
const agent = useSessionStore((state) => state.sessions[SERVER_ID]?.agents.get(AGENT_ID) ?? null);
|
||||
const modeControl = useLiveAgentModeControl(SERVER_ID, AGENT_ID);
|
||||
|
||||
const onSelectThinking = useCallback(
|
||||
(thinkingOptionId: string) => {
|
||||
void setLiveAgentThinkingOption({
|
||||
serverId: SERVER_ID,
|
||||
agentId: AGENT_ID,
|
||||
thinkingOptionId,
|
||||
expectedProvider: "claude",
|
||||
}).catch((error: unknown) => {
|
||||
toast.error(error instanceof Error ? error.message : String(error));
|
||||
});
|
||||
},
|
||||
[toast],
|
||||
);
|
||||
|
||||
const onSetOption = useCallback(
|
||||
(key: string, value: unknown) => {
|
||||
void setLiveAgentOptions({
|
||||
serverId: SERVER_ID,
|
||||
agentId: AGENT_ID,
|
||||
patch: { [key]: value },
|
||||
expectedProvider: "claude",
|
||||
}).catch((error: unknown) => {
|
||||
toast.error(error instanceof Error ? error.message : String(error));
|
||||
});
|
||||
},
|
||||
[toast],
|
||||
);
|
||||
|
||||
const selectedThinkingId =
|
||||
agent?.runtimeInfo?.thinkingOptionId ?? agent?.thinkingOptionId ?? undefined;
|
||||
const thinking = useMemo(
|
||||
() => ({
|
||||
options: THINKING_OPTIONS,
|
||||
selectedId: selectedThinkingId,
|
||||
onSelect: onSelectThinking,
|
||||
displayLabel:
|
||||
THINKING_OPTIONS.find((option) => option.id === selectedThinkingId)?.label ?? "Low",
|
||||
}),
|
||||
[onSelectThinking, selectedThinkingId],
|
||||
);
|
||||
const optionControls = useMemo(
|
||||
() => ({ controls: agent?.controls ?? [], options: agent?.options ?? {}, onSetOption }),
|
||||
[agent?.controls, agent?.options, onSetOption],
|
||||
);
|
||||
const items = useAgentControlItems({
|
||||
surface: "sheet",
|
||||
presentation: PRESENTATION,
|
||||
thinking,
|
||||
optionControls,
|
||||
});
|
||||
const controls = useMemo<AgentSheetControls>(
|
||||
() => ({ thinkingItems: items.thinking, featureItems: items.features, modeControl }),
|
||||
[items.features, items.thinking, modeControl],
|
||||
);
|
||||
|
||||
return (
|
||||
<div style={SHEET_FRAME_STYLE}>
|
||||
<AgentSheetHome
|
||||
controls={controls}
|
||||
disabled={false}
|
||||
topCard={null}
|
||||
onOpenSelect={ignoreOpenSelect}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function createToast() {
|
||||
return { error: vi.fn(), info: vi.fn() } as unknown as ToastApi & {
|
||||
error: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
}
|
||||
|
||||
function renderSheet() {
|
||||
const toast = createToast();
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
render(
|
||||
<GestureHandlerRootView style={GESTURE_ROOT_STYLE}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ToastApiProvider api={toast}>
|
||||
<LiveSheet toast={toast} />
|
||||
</ToastApiProvider>
|
||||
</QueryClientProvider>
|
||||
</GestureHandlerRootView>,
|
||||
);
|
||||
return toast;
|
||||
}
|
||||
|
||||
beforeEach(() => vi.stubGlobal("React", React));
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
clearLiveAgentMutationsForServer(SERVER_ID);
|
||||
useSessionStore.getState().clearSession(SERVER_ID);
|
||||
});
|
||||
|
||||
describe("live agent settings sheet (browser geometry & races)", () => {
|
||||
it("holds the slider thumb at exact pixel coordinates across in-flight ticks and late sync", async () => {
|
||||
const calls = setupSession();
|
||||
renderSheet();
|
||||
await nextPaint();
|
||||
|
||||
const slider = screen.getByTestId("agent-controls-thinking");
|
||||
const thumb = screen.getByTestId("agent-controls-thinking-thumb");
|
||||
const initialLeft = Math.round(thumb.getBoundingClientRect().left);
|
||||
|
||||
fireEvent.click(screen.getByTestId("agent-controls-thinking-high"));
|
||||
await nextPaint();
|
||||
const targetLeft = Math.round(thumb.getBoundingClientRect().left);
|
||||
expect(targetLeft).toBeGreaterThan(initialLeft);
|
||||
expect(getComputedStyle(slider).opacity).toBe("1");
|
||||
|
||||
// Running agent emits unrelated usage tick with old thinkingOptionId ("low").
|
||||
act(() => pushServerUpdate({ lastUsage: { inputTokens: 2000, outputTokens: 500 } }));
|
||||
await nextPaint();
|
||||
expect(Math.round(thumb.getBoundingClientRect().left)).toBe(targetLeft);
|
||||
|
||||
// RPC resolves before confirming agent_update arrives (old daemon timing).
|
||||
await act(async () => {
|
||||
calls[0].gate.resolve(null);
|
||||
await Promise.resolve();
|
||||
});
|
||||
await nextPaint();
|
||||
expect(Math.round(thumb.getBoundingClientRect().left)).toBe(targetLeft);
|
||||
|
||||
// Confirming agent_update lands -> exact same pixel.
|
||||
act(() =>
|
||||
pushServerUpdate({
|
||||
thinkingOptionId: "high",
|
||||
runtimeInfo: {
|
||||
provider: "claude",
|
||||
sessionId: "s1",
|
||||
model: "claude-sonnet-4",
|
||||
modeId: "default",
|
||||
thinkingOptionId: "high",
|
||||
},
|
||||
}),
|
||||
);
|
||||
await nextPaint();
|
||||
expect(Math.round(thumb.getBoundingClientRect().left)).toBe(targetLeft);
|
||||
});
|
||||
|
||||
it("coalesces rapid taps without snapping backwards and rolls back on error", async () => {
|
||||
const calls = setupSession();
|
||||
const toast = renderSheet();
|
||||
await nextPaint();
|
||||
|
||||
const thumb = screen.getByTestId("agent-controls-thinking-thumb");
|
||||
const lowLeft = Math.round(thumb.getBoundingClientRect().left);
|
||||
|
||||
fireEvent.click(screen.getByTestId("agent-controls-thinking-medium"));
|
||||
fireEvent.click(screen.getByTestId("agent-controls-thinking-high"));
|
||||
fireEvent.click(screen.getByTestId("agent-controls-thinking-max"));
|
||||
await nextPaint();
|
||||
|
||||
const maxLeft = Math.round(thumb.getBoundingClientRect().left);
|
||||
expect(maxLeft).toBeGreaterThan(lowLeft);
|
||||
expect(calls.map((c) => c.value)).toEqual(["medium"]);
|
||||
|
||||
await act(async () => {
|
||||
pushServerUpdate({
|
||||
thinkingOptionId: "medium",
|
||||
runtimeInfo: {
|
||||
provider: "claude",
|
||||
sessionId: "s1",
|
||||
model: "claude-sonnet-4",
|
||||
modeId: "default",
|
||||
thinkingOptionId: "medium",
|
||||
},
|
||||
});
|
||||
calls[0].gate.resolve(null);
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
});
|
||||
await nextPaint();
|
||||
expect(Math.round(thumb.getBoundingClientRect().left)).toBe(maxLeft);
|
||||
expect(calls.map((c) => c.value)).toEqual(["medium", "max"]);
|
||||
|
||||
await act(async () => {
|
||||
calls[1].gate.reject(new Error("Max effort unavailable"));
|
||||
await Promise.resolve();
|
||||
});
|
||||
await nextPaint();
|
||||
|
||||
const rolledBackLeft = Math.round(thumb.getBoundingClientRect().left);
|
||||
expect(rolledBackLeft).toBeGreaterThan(lowLeft);
|
||||
expect(rolledBackLeft).toBeLessThan(maxLeft);
|
||||
expect(toast.error).toHaveBeenCalledWith("Max effort unavailable");
|
||||
});
|
||||
|
||||
it("updates switch, pills, and mode optimistically through session-store", async () => {
|
||||
const calls = setupSession();
|
||||
renderSheet();
|
||||
await nextPaint();
|
||||
|
||||
const fastSwitch = screen.getByRole("switch", { name: "Fast" });
|
||||
const flexPill = screen.getByTestId("agent-feature-service_tier-flex");
|
||||
const planRow = screen.getByTestId("mode-option-plan");
|
||||
|
||||
fireEvent.click(fastSwitch);
|
||||
expect(fastSwitch.getAttribute("aria-checked")).toBe("true");
|
||||
fireEvent.click(fastSwitch);
|
||||
expect(fastSwitch.getAttribute("aria-checked")).toBe("false");
|
||||
fireEvent.click(flexPill);
|
||||
expect(flexPill.getAttribute("aria-selected")).toBe("true");
|
||||
fireEvent.click(planRow);
|
||||
expect(planRow.getAttribute("aria-checked")).toBe("true");
|
||||
|
||||
// Unrelated update does not revert any field.
|
||||
act(() => pushServerUpdate({ lastUsage: { inputTokens: 3000, outputTokens: 800 } }));
|
||||
expect(fastSwitch.getAttribute("aria-checked")).toBe("false");
|
||||
expect(flexPill.getAttribute("aria-selected")).toBe("true");
|
||||
expect(planRow.getAttribute("aria-checked")).toBe("true");
|
||||
expect(calls.map((c) => [c.kind, c.value] as [string, ProviderOptions | string])).toEqual([
|
||||
["options", { fast_mode: true }],
|
||||
]);
|
||||
});
|
||||
|
||||
it("completes a horizontal drag across stops during live usage ticks, accepts a tap after, and ignores vertical drags", async () => {
|
||||
const calls = setupSession();
|
||||
renderSheet();
|
||||
await nextPaint();
|
||||
|
||||
const thumb = screen.getByTestId("agent-controls-thinking-thumb");
|
||||
const lowStop = screen.getByTestId("agent-controls-thinking-low");
|
||||
const highStop = screen.getByTestId("agent-controls-thinking-high");
|
||||
const mediumStop = screen.getByTestId("agent-controls-thinking-medium");
|
||||
const frameRect = window.frameElement?.getBoundingClientRect();
|
||||
const scaleX = frameRect ? frameRect.width / window.innerWidth : 1;
|
||||
const scaleY = frameRect ? frameRect.height / window.innerHeight : 1;
|
||||
const toViewport = (x: number, y: number) => ({
|
||||
x: Math.round((frameRect?.left ?? 0) + x * scaleX),
|
||||
y: Math.round((frameRect?.top ?? 0) + y * scaleY),
|
||||
});
|
||||
const lowRect = lowStop.getBoundingClientRect();
|
||||
const highRect = highStop.getBoundingClientRect();
|
||||
const start = toViewport(lowRect.left + lowRect.width / 2, lowRect.top + lowRect.height / 2);
|
||||
const end = toViewport(highRect.left + highRect.width / 2, highRect.top + highRect.height / 2);
|
||||
const initialLeft = Math.round(thumb.getBoundingClientRect().left);
|
||||
const browserCdp = cdp();
|
||||
|
||||
// Pointer-down alone (before horizontal intent wins) must not jump the thumb.
|
||||
await browserCdp.send("Input.dispatchMouseEvent", {
|
||||
type: "mousePressed",
|
||||
x: start.x,
|
||||
y: start.y,
|
||||
button: "left",
|
||||
buttons: 1,
|
||||
clickCount: 1,
|
||||
});
|
||||
await nextPaint();
|
||||
expect(Math.round(thumb.getBoundingClientRect().left)).toBe(initialLeft);
|
||||
|
||||
// Drag past activeOffsetX across stops while running-agent usage ticks arrive mid-drag.
|
||||
await browserCdp.send("Input.dispatchMouseEvent", {
|
||||
type: "mouseMoved",
|
||||
x: start.x + 24,
|
||||
y: start.y,
|
||||
button: "left",
|
||||
buttons: 1,
|
||||
});
|
||||
act(() => pushServerUpdate({ lastUsage: { inputTokens: 5000, outputTokens: 1200 } }));
|
||||
await browserCdp.send("Input.dispatchMouseEvent", {
|
||||
type: "mouseMoved",
|
||||
x: end.x,
|
||||
y: end.y,
|
||||
button: "left",
|
||||
buttons: 1,
|
||||
});
|
||||
await nextPaint();
|
||||
const draggedLeft = Math.round(thumb.getBoundingClientRect().left);
|
||||
expect(draggedLeft).toBeGreaterThan(initialLeft);
|
||||
|
||||
// Release commits exactly one write ("high") and holds the thumb position without snapping back.
|
||||
await browserCdp.send("Input.dispatchMouseEvent", {
|
||||
type: "mouseReleased",
|
||||
x: end.x,
|
||||
y: end.y,
|
||||
button: "left",
|
||||
buttons: 0,
|
||||
clickCount: 1,
|
||||
});
|
||||
await nextPaint();
|
||||
expect(Math.round(thumb.getBoundingClientRect().left)).toBe(draggedLeft);
|
||||
expect(calls.map((c) => [c.kind, c.value])).toEqual([["thinking", "high"]]);
|
||||
|
||||
// A vertical drag starting on the slider fails pan and sends no write.
|
||||
await browserCdp.send("Input.dispatchMouseEvent", {
|
||||
type: "mousePressed",
|
||||
x: end.x,
|
||||
y: end.y,
|
||||
button: "left",
|
||||
buttons: 1,
|
||||
clickCount: 1,
|
||||
});
|
||||
await browserCdp.send("Input.dispatchMouseEvent", {
|
||||
type: "mouseMoved",
|
||||
x: end.x,
|
||||
y: end.y + 24,
|
||||
button: "left",
|
||||
buttons: 1,
|
||||
});
|
||||
await browserCdp.send("Input.dispatchMouseEvent", {
|
||||
type: "mouseReleased",
|
||||
x: end.x,
|
||||
y: end.y + 24,
|
||||
button: "left",
|
||||
buttons: 0,
|
||||
clickCount: 1,
|
||||
});
|
||||
await nextPaint();
|
||||
expect(Math.round(thumb.getBoundingClientRect().left)).toBe(draggedLeft);
|
||||
expect(calls).toHaveLength(1);
|
||||
|
||||
// A plain tap after the drag still selects immediately.
|
||||
const medRect = mediumStop.getBoundingClientRect();
|
||||
const med = toViewport(medRect.left + medRect.width / 2, medRect.top + medRect.height / 2);
|
||||
await browserCdp.send("Input.dispatchMouseEvent", {
|
||||
type: "mousePressed",
|
||||
x: med.x,
|
||||
y: med.y,
|
||||
button: "left",
|
||||
buttons: 1,
|
||||
clickCount: 1,
|
||||
});
|
||||
await browserCdp.send("Input.dispatchMouseEvent", {
|
||||
type: "mouseReleased",
|
||||
x: med.x,
|
||||
y: med.y,
|
||||
button: "left",
|
||||
buttons: 0,
|
||||
clickCount: 1,
|
||||
});
|
||||
await nextPaint();
|
||||
const mediumLeft = Math.round(thumb.getBoundingClientRect().left);
|
||||
expect(mediumLeft).toBeGreaterThan(initialLeft);
|
||||
expect(mediumLeft).toBeLessThan(draggedLeft);
|
||||
});
|
||||
});
|
||||
@@ -17,6 +17,7 @@ import { resolveNextAgentModeId } from "@/composer/agent-controls/mode";
|
||||
import { useComposerKeyboardScope } from "@/composer/keyboard-scope";
|
||||
import { useComposerControlLayout } from "@/composer/agent-controls/layout-context";
|
||||
import { AgentControlTrigger } from "@/composer/agent-controls/control";
|
||||
import { setLiveAgentMode } from "@/composer/agent-mutations";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
|
||||
import { mergeProviderPreferences, useFormPreferences } from "@/hooks/use-form-preferences";
|
||||
@@ -295,15 +296,19 @@ export function useLiveAgentModeControl(
|
||||
).catch((error) => {
|
||||
console.warn("[AgentModeControl] persist mode preference failed", error);
|
||||
});
|
||||
void client
|
||||
.setAgentMode(agentId, modeId, { expectedProvider: slice.provider })
|
||||
void setLiveAgentMode({
|
||||
serverId,
|
||||
agentId,
|
||||
modeId,
|
||||
expectedProvider: slice.provider,
|
||||
})
|
||||
.then((notice) => showProviderNoticeToast(toast, notice))
|
||||
.catch((error) => {
|
||||
console.warn("[AgentModeControl] setAgentMode failed", error);
|
||||
toast.error(toErrorMessage(error));
|
||||
});
|
||||
},
|
||||
[agentId, client, slice?.provider, toast, updatePreferences],
|
||||
[agentId, client, serverId, slice?.provider, toast, updatePreferences],
|
||||
);
|
||||
|
||||
return useMemo(() => {
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
import equal from "fast-deep-equal";
|
||||
import type {
|
||||
AgentProvider,
|
||||
AgentProviderNotice,
|
||||
ProviderOptions,
|
||||
} from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentConfigApply } from "@getpaseo/protocol/messages";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import { createEntityMutationQueue, type EntitySlotPatch } from "@/runtime/entity-mutation-queue";
|
||||
import { getSessionAgentBase, useSessionStore, type Agent } from "@/stores/session-store";
|
||||
|
||||
interface AgentTarget {
|
||||
serverId: string;
|
||||
agentId: string;
|
||||
expectedProvider?: AgentProvider;
|
||||
}
|
||||
|
||||
const KEY_SEP = "\0";
|
||||
const clientIds = new WeakMap<DaemonClient, number>();
|
||||
let nextClientId = 0;
|
||||
|
||||
function entityKey(serverId: string, agentId: string): string {
|
||||
return `${serverId}${KEY_SEP}${agentId}`;
|
||||
}
|
||||
|
||||
function splitEntityKey(key: string): { serverId: string; agentId: string } {
|
||||
const sep = key.indexOf(KEY_SEP);
|
||||
return { serverId: key.slice(0, sep), agentId: key.slice(sep + 1) };
|
||||
}
|
||||
|
||||
function getClientId(client: DaemonClient): number {
|
||||
let id = clientIds.get(client);
|
||||
if (id === undefined) {
|
||||
id = ++nextClientId;
|
||||
clientIds.set(client, id);
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
const queue = createEntityMutationQueue<Agent>({
|
||||
setOverlay(key, apply) {
|
||||
const { serverId, agentId } = splitEntityKey(key);
|
||||
useSessionStore.getState().setAgentOverlay(serverId, agentId, apply);
|
||||
},
|
||||
getBase(key) {
|
||||
const { serverId, agentId } = splitEntityKey(key);
|
||||
const agent = getSessionAgentBase(serverId, agentId);
|
||||
return agent && agent.archivedAt == null ? agent : null;
|
||||
},
|
||||
subscribeBase(listener) {
|
||||
return useSessionStore.subscribe(listener);
|
||||
},
|
||||
getEpoch(key) {
|
||||
const { serverId, agentId } = splitEntityKey(key);
|
||||
const session = useSessionStore.getState().sessions[serverId];
|
||||
const agent = getSessionAgentBase(serverId, agentId);
|
||||
if (!session?.client || !agent || agent.archivedAt != null) return null;
|
||||
return `${getClientId(session.client)}:${agent.provider}`;
|
||||
},
|
||||
});
|
||||
|
||||
function requireClient(serverId: string): DaemonClient | null {
|
||||
return useSessionStore.getState().sessions[serverId]?.client ?? null;
|
||||
}
|
||||
|
||||
function hostNotConnected(): Promise<never> {
|
||||
return Promise.reject(new Error("The host is not connected."));
|
||||
}
|
||||
|
||||
function providerGuard(expectedProvider?: AgentProvider) {
|
||||
return expectedProvider ? { expectedProvider } : undefined;
|
||||
}
|
||||
|
||||
function modelPatch(modelId: string | null, baseBefore: Agent | null): EntitySlotPatch<Agent> {
|
||||
const beforeModel = baseBefore?.runtimeInfo?.model ?? baseBefore?.model ?? null;
|
||||
return {
|
||||
slot: "model",
|
||||
apply: (agent) => ({
|
||||
...agent,
|
||||
model: modelId,
|
||||
...(agent.runtimeInfo ? { runtimeInfo: { ...agent.runtimeInfo, model: modelId } } : {}),
|
||||
}),
|
||||
isSynced: (base) => {
|
||||
const actual = base.runtimeInfo?.model ?? base.model ?? null;
|
||||
if (modelId === null) return actual === null && base.model === null;
|
||||
return (
|
||||
base.runtimeInfo?.model === modelId || base.model === modelId || actual !== beforeModel
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function modePatch(modeId: string): EntitySlotPatch<Agent> {
|
||||
return {
|
||||
slot: "mode",
|
||||
apply: (agent) => ({
|
||||
...agent,
|
||||
currentModeId: modeId,
|
||||
...(agent.runtimeInfo ? { runtimeInfo: { ...agent.runtimeInfo, modeId } } : {}),
|
||||
}),
|
||||
isSynced: (base) => base.currentModeId === modeId || base.runtimeInfo?.modeId === modeId,
|
||||
};
|
||||
}
|
||||
|
||||
function thinkingPatch(thinkingOptionId: string | null): EntitySlotPatch<Agent> {
|
||||
return {
|
||||
slot: "thinking",
|
||||
apply: (agent) => ({
|
||||
...agent,
|
||||
thinkingOptionId,
|
||||
...(agent.runtimeInfo ? { runtimeInfo: { ...agent.runtimeInfo, thinkingOptionId } } : {}),
|
||||
}),
|
||||
isSynced: (base) => {
|
||||
const actual = base.runtimeInfo?.thinkingOptionId ?? base.thinkingOptionId ?? null;
|
||||
if (thinkingOptionId === null || thinkingOptionId === "default") {
|
||||
return actual === null || actual === "default";
|
||||
}
|
||||
return (
|
||||
base.runtimeInfo?.thinkingOptionId === thinkingOptionId ||
|
||||
base.thinkingOptionId === thinkingOptionId
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function optionPatch(key: string, value: unknown): EntitySlotPatch<Agent> {
|
||||
return {
|
||||
slot: `option:${key}`,
|
||||
apply: (agent) => {
|
||||
const options: ProviderOptions = { ...agent.options };
|
||||
if (value === null) delete options[key];
|
||||
else options[key] = value;
|
||||
return { ...agent, options };
|
||||
},
|
||||
isSynced: (base) => {
|
||||
const actual = base.options?.[key];
|
||||
return value === null ? actual === undefined || actual === null : equal(actual, value);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function setLiveAgentModel(
|
||||
input: AgentTarget & { modelId: string | null },
|
||||
): Promise<boolean> {
|
||||
const client = requireClient(input.serverId);
|
||||
if (!client) return hostNotConnected();
|
||||
const baseBefore = getSessionAgentBase(input.serverId, input.agentId);
|
||||
const outcome = await queue.write({
|
||||
entityKey: entityKey(input.serverId, input.agentId),
|
||||
patches: [modelPatch(input.modelId, baseBefore)],
|
||||
barrier: true,
|
||||
send: () =>
|
||||
client.setAgentModel(input.agentId, input.modelId, providerGuard(input.expectedProvider)),
|
||||
});
|
||||
return outcome.status === "applied";
|
||||
}
|
||||
|
||||
export async function setLiveAgentMode(
|
||||
input: AgentTarget & { modeId: string },
|
||||
): Promise<AgentProviderNotice | null> {
|
||||
const client = requireClient(input.serverId);
|
||||
if (!client) return hostNotConnected();
|
||||
const outcome = await queue.write({
|
||||
entityKey: entityKey(input.serverId, input.agentId),
|
||||
patches: [modePatch(input.modeId)],
|
||||
send: () =>
|
||||
client.setAgentMode(input.agentId, input.modeId, providerGuard(input.expectedProvider)),
|
||||
});
|
||||
return outcome.status === "applied" ? outcome.result : null;
|
||||
}
|
||||
|
||||
export async function setLiveAgentThinkingOption(
|
||||
input: AgentTarget & { thinkingOptionId: string | null },
|
||||
): Promise<AgentProviderNotice | null> {
|
||||
const client = requireClient(input.serverId);
|
||||
if (!client) return hostNotConnected();
|
||||
const outcome = await queue.write({
|
||||
entityKey: entityKey(input.serverId, input.agentId),
|
||||
patches: [thinkingPatch(input.thinkingOptionId)],
|
||||
send: () =>
|
||||
client.setAgentThinkingOption(
|
||||
input.agentId,
|
||||
input.thinkingOptionId,
|
||||
providerGuard(input.expectedProvider),
|
||||
),
|
||||
});
|
||||
return outcome.status === "applied" ? outcome.result : null;
|
||||
}
|
||||
|
||||
export async function setLiveAgentOptions(
|
||||
input: AgentTarget & { patch: ProviderOptions },
|
||||
): Promise<AgentProviderNotice | null> {
|
||||
const entries = Object.entries(input.patch);
|
||||
if (entries.length === 0) return null;
|
||||
const client = requireClient(input.serverId);
|
||||
if (!client) return hostNotConnected();
|
||||
const outcome = await queue.write({
|
||||
entityKey: entityKey(input.serverId, input.agentId),
|
||||
patches: entries.map(([key, value]) => optionPatch(key, value)),
|
||||
send: () =>
|
||||
client.setAgentOptions(input.agentId, input.patch, providerGuard(input.expectedProvider)),
|
||||
});
|
||||
return outcome.status === "applied" ? outcome.result : null;
|
||||
}
|
||||
|
||||
export async function applyLiveAgentConfig(
|
||||
input: AgentTarget & { config: AgentConfigApply },
|
||||
): Promise<AgentProviderNotice | null> {
|
||||
const client = requireClient(input.serverId);
|
||||
if (!client) return hostNotConnected();
|
||||
const baseBefore = getSessionAgentBase(input.serverId, input.agentId);
|
||||
const patches: EntitySlotPatch<Agent>[] = [];
|
||||
if (input.config.modelId !== undefined)
|
||||
patches.push(modelPatch(input.config.modelId, baseBefore));
|
||||
if (input.config.modeId !== undefined) patches.push(modePatch(input.config.modeId));
|
||||
if (input.config.thinkingOptionId !== undefined) {
|
||||
patches.push(thinkingPatch(input.config.thinkingOptionId));
|
||||
}
|
||||
const mergedOptions = { ...input.config.featureValues, ...input.config.options };
|
||||
for (const [key, value] of Object.entries(mergedOptions)) {
|
||||
patches.push(optionPatch(key, value));
|
||||
}
|
||||
const outcome = await queue.write({
|
||||
entityKey: entityKey(input.serverId, input.agentId),
|
||||
patches,
|
||||
barrier: true,
|
||||
send: () =>
|
||||
client.applyAgentConfig(input.agentId, input.config, providerGuard(input.expectedProvider)),
|
||||
});
|
||||
return outcome.status === "applied" ? outcome.result : null;
|
||||
}
|
||||
|
||||
export function clearLiveAgentMutationsForServer(serverId: string): void {
|
||||
queue.clearPrefix(`${serverId}${KEY_SEP}`);
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { createEntityMutationQueue } from "./entity-mutation-queue";
|
||||
|
||||
interface Item {
|
||||
model: string;
|
||||
thinking: string;
|
||||
fast: boolean;
|
||||
ticks: number;
|
||||
}
|
||||
|
||||
function deferred<T = void>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (error: unknown) => void;
|
||||
const promise = new Promise<T>((res, rej) => {
|
||||
resolve = res;
|
||||
reject = rej;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
function createHarness(
|
||||
initial: Item = { model: "sonnet", thinking: "low", fast: false, ticks: 0 },
|
||||
) {
|
||||
let base: Item | null = initial;
|
||||
let epoch: string | null = "c1:claude";
|
||||
let overlay: ((item: Item) => Item) | null = null;
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
const queue = createEntityMutationQueue<Item>({
|
||||
setOverlay: (_key, next) => {
|
||||
overlay = next;
|
||||
},
|
||||
getBase: () => base,
|
||||
subscribeBase: (fn) => {
|
||||
listeners.add(fn);
|
||||
return () => listeners.delete(fn);
|
||||
},
|
||||
getEpoch: () => epoch,
|
||||
syncTimeoutMs: 500,
|
||||
});
|
||||
|
||||
const read = () => (base && overlay ? overlay(base) : base);
|
||||
const pushBase = (patch: Partial<Item>) => {
|
||||
if (!base) return;
|
||||
base = { ...base, ...patch };
|
||||
for (const fn of listeners) fn();
|
||||
};
|
||||
const setEpoch = (next: string | null) => {
|
||||
epoch = next;
|
||||
for (const fn of listeners) fn();
|
||||
};
|
||||
|
||||
return { queue, read, pushBase, setEpoch };
|
||||
}
|
||||
|
||||
beforeEach(() => vi.useFakeTimers());
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
describe("createEntityMutationQueue", () => {
|
||||
it("projects immediately, survives unrelated base updates, and waits for late sync", async () => {
|
||||
const h = createHarness();
|
||||
const rpc = deferred<string>();
|
||||
|
||||
const write = h.queue.write({
|
||||
entityKey: "e1",
|
||||
patches: [
|
||||
{
|
||||
slot: "thinking",
|
||||
apply: (item) => ({ ...item, thinking: "high" }),
|
||||
isSynced: (item) => item.thinking === "high",
|
||||
},
|
||||
],
|
||||
send: () => rpc.promise,
|
||||
});
|
||||
|
||||
expect(h.read()?.thinking).toBe("high");
|
||||
|
||||
// Unrelated tick leaves optimistic field intact while updating live fields.
|
||||
h.pushBase({ ticks: 1 });
|
||||
expect(h.read()).toEqual({ model: "sonnet", thinking: "high", fast: false, ticks: 1 });
|
||||
|
||||
// RPC resolves before base catches up (old server) -> stays projected.
|
||||
rpc.resolve("next-turn");
|
||||
await expect(write).resolves.toEqual({ status: "applied", result: "next-turn" });
|
||||
expect(h.read()?.thinking).toBe("high");
|
||||
|
||||
// Confirming base update clears the overlay cleanly.
|
||||
h.pushBase({ thinking: "high" });
|
||||
expect(h.read()?.thinking).toBe("high");
|
||||
});
|
||||
|
||||
it("coalesces rapid same-slot writes and suppresses superseded results and errors", async () => {
|
||||
const h = createHarness();
|
||||
const sent: Array<{ value: string; gate: ReturnType<typeof deferred<string>> }> = [];
|
||||
const writeThinking = (value: string) =>
|
||||
h.queue.write({
|
||||
entityKey: "e1",
|
||||
patches: [
|
||||
{
|
||||
slot: "thinking",
|
||||
apply: (item) => ({ ...item, thinking: value }),
|
||||
isSynced: (item) => item.thinking === value,
|
||||
},
|
||||
],
|
||||
send: () => {
|
||||
const gate = deferred<string>();
|
||||
sent.push({ value, gate });
|
||||
return gate.promise;
|
||||
},
|
||||
});
|
||||
|
||||
const p1 = writeThinking("medium");
|
||||
const p2 = writeThinking("high");
|
||||
const p3 = writeThinking("max");
|
||||
|
||||
expect(sent.map((s) => s.value)).toEqual(["medium"]);
|
||||
expect(h.read()?.thinking).toBe("max");
|
||||
await expect(p2).resolves.toEqual({ status: "superseded" });
|
||||
|
||||
// Even if first write fails, user already moved to "max" -> no rollback, no error.
|
||||
sent[0].gate.reject(new Error("stale"));
|
||||
await expect(p1).resolves.toEqual({ status: "superseded" });
|
||||
await Promise.resolve();
|
||||
expect(h.read()?.thinking).toBe("max");
|
||||
|
||||
// Only "max" runs next ("high" was coalesced away).
|
||||
expect(sent.map((s) => s.value)).toEqual(["medium", "max"]);
|
||||
h.pushBase({ thinking: "max" });
|
||||
sent[1].gate.resolve("ok");
|
||||
await expect(p3).resolves.toEqual({ status: "applied", result: "ok" });
|
||||
expect(h.read()?.thinking).toBe("max");
|
||||
});
|
||||
|
||||
it("respects barrier ordering and rolls back on failure of the latest write", async () => {
|
||||
const h = createHarness();
|
||||
const sent: Array<{ op: string; gate: ReturnType<typeof deferred<void>> }> = [];
|
||||
const send = (op: string) => () => {
|
||||
const gate = deferred<void>();
|
||||
sent.push({ op, gate });
|
||||
return gate.promise;
|
||||
};
|
||||
|
||||
const pModel = h.queue.write({
|
||||
entityKey: "e1",
|
||||
barrier: true,
|
||||
patches: [{ slot: "model", apply: (i) => ({ ...i, model: "opus" }) }],
|
||||
send: send("model:opus"),
|
||||
});
|
||||
const pLow = h.queue.write({
|
||||
entityKey: "e1",
|
||||
patches: [{ slot: "thinking", apply: (i) => ({ ...i, thinking: "high" }) }],
|
||||
send: send("thinking:high"),
|
||||
});
|
||||
const pMax = h.queue.write({
|
||||
entityKey: "e1",
|
||||
patches: [{ slot: "thinking", apply: (i) => ({ ...i, thinking: "max" }) }],
|
||||
send: send("thinking:max"),
|
||||
});
|
||||
|
||||
expect(h.read()).toMatchObject({ model: "opus", thinking: "max" });
|
||||
expect(sent.map((s) => s.op)).toEqual(["model:opus"]);
|
||||
await expect(pLow).resolves.toEqual({ status: "superseded" });
|
||||
|
||||
h.pushBase({ model: "opus" });
|
||||
sent[0].gate.resolve();
|
||||
await pModel;
|
||||
await Promise.resolve();
|
||||
|
||||
expect(sent.map((s) => s.op)).toEqual(["model:opus", "thinking:max"]);
|
||||
sent[1].gate.reject(new Error("rejected"));
|
||||
await expect(pMax).rejects.toThrow("rejected");
|
||||
expect(h.read()).toMatchObject({ model: "opus", thinking: "low" });
|
||||
});
|
||||
|
||||
it("clears awaiting-sync on timeout and drops work when epoch changes", async () => {
|
||||
const h = createHarness();
|
||||
const rpc = deferred();
|
||||
|
||||
const p1 = h.queue.write({
|
||||
entityKey: "e1",
|
||||
patches: [
|
||||
{
|
||||
slot: "thinking",
|
||||
apply: (i) => ({ ...i, thinking: "max" }),
|
||||
isSynced: (i) => i.thinking === "max",
|
||||
},
|
||||
],
|
||||
send: () => rpc.promise,
|
||||
});
|
||||
rpc.resolve();
|
||||
await p1;
|
||||
expect(h.read()?.thinking).toBe("max");
|
||||
|
||||
vi.advanceTimersByTime(500);
|
||||
expect(h.read()?.thinking).toBe("low");
|
||||
|
||||
const rpc2 = deferred();
|
||||
const p2 = h.queue.write({
|
||||
entityKey: "e1",
|
||||
patches: [{ slot: "thinking", apply: (i) => ({ ...i, thinking: "high" }) }],
|
||||
send: () => rpc2.promise,
|
||||
});
|
||||
expect(h.read()?.thinking).toBe("high");
|
||||
|
||||
h.setEpoch("c1:codex");
|
||||
expect(h.read()?.thinking).toBe("low");
|
||||
rpc2.resolve();
|
||||
await expect(p2).resolves.toEqual({ status: "superseded" });
|
||||
});
|
||||
|
||||
it("completes empty-patch writes on an idle queue (e.g. system-prompt-only profile apply)", async () => {
|
||||
const h = createHarness();
|
||||
const ok = deferred<string>();
|
||||
const pOk = h.queue.write({
|
||||
entityKey: "e1",
|
||||
patches: [],
|
||||
barrier: true,
|
||||
send: () => ok.promise,
|
||||
});
|
||||
ok.resolve("done");
|
||||
await expect(pOk).resolves.toEqual({ status: "applied", result: "done" });
|
||||
|
||||
const bad = deferred<string>();
|
||||
const pBad = h.queue.write({
|
||||
entityKey: "e1",
|
||||
patches: [],
|
||||
barrier: true,
|
||||
send: () => bad.promise,
|
||||
});
|
||||
bad.reject(new Error("boom"));
|
||||
await expect(pBad).rejects.toThrow("boom");
|
||||
});
|
||||
|
||||
it("marks a failed barrier write as superseded when a newer write replaced its slot", async () => {
|
||||
const h = createHarness();
|
||||
const first = deferred<void>();
|
||||
const second = deferred<void>();
|
||||
|
||||
const pB = h.queue.write({
|
||||
entityKey: "e1",
|
||||
barrier: true,
|
||||
patches: [{ slot: "model", apply: (i) => ({ ...i, model: "model-b" }) }],
|
||||
send: () => first.promise,
|
||||
});
|
||||
const pC = h.queue.write({
|
||||
entityKey: "e1",
|
||||
barrier: true,
|
||||
patches: [{ slot: "model", apply: (i) => ({ ...i, model: "model-c" }) }],
|
||||
send: () => second.promise,
|
||||
});
|
||||
|
||||
first.reject(new Error("b failed"));
|
||||
await expect(pB).resolves.toEqual({ status: "superseded" });
|
||||
|
||||
second.reject(new Error("c failed"));
|
||||
await expect(pC).rejects.toThrow("c failed");
|
||||
expect(h.read()?.model).toBe("sonnet");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,303 @@
|
||||
export interface EntitySlotPatch<TEntity> {
|
||||
/** Coalescing slot key (e.g. `"thinking"`, `"option:fast_mode"`). */
|
||||
slot: string;
|
||||
/** Projects this slot's optimistic state onto a base entity snapshot. */
|
||||
apply: (entity: TEntity) => TEntity;
|
||||
/**
|
||||
* Returns true once the remote base reflects this slot. When provided and still false after
|
||||
* `send()` resolves, the slot stays overlaid until the base catches up or `syncTimeoutMs` elapses.
|
||||
*/
|
||||
isSynced?: (base: TEntity) => boolean;
|
||||
}
|
||||
|
||||
export interface EntityWrite<TEntity, TResult> {
|
||||
/** Entity owning the serialized mutation queue (e.g. `${serverId}:${agentId}`). */
|
||||
entityKey: string;
|
||||
/**
|
||||
* Optimistic slot patches owned by this write. A single-slot non-barrier write coalesces with
|
||||
* the latest queued write for the same slot unless a barrier write sits between them.
|
||||
*/
|
||||
patches: readonly EntitySlotPatch<TEntity>[];
|
||||
/** Stops later writes from coalescing ahead of this write (e.g. model change or config bundle). */
|
||||
barrier?: boolean;
|
||||
/** Sends the write to the remote owner. */
|
||||
send: () => Promise<TResult>;
|
||||
}
|
||||
|
||||
export interface EntityOverlayAdapter<TEntity> {
|
||||
setOverlay: (entityKey: string, apply: ((base: TEntity) => TEntity) | null) => void;
|
||||
getBase: (entityKey: string) => TEntity | null;
|
||||
subscribeBase?: (listener: () => void) => () => void;
|
||||
/** Optional identity token (e.g. `client` + `provider`); changing it drops stale pending work. */
|
||||
getEpoch?: (entityKey: string) => unknown;
|
||||
syncTimeoutMs?: number;
|
||||
}
|
||||
|
||||
export type EntityWriteOutcome<TResult> =
|
||||
| { status: "applied"; result: TResult }
|
||||
| { status: "superseded" };
|
||||
|
||||
export interface EntityMutationQueue<TEntity> {
|
||||
write: <TResult>(input: EntityWrite<TEntity, TResult>) => Promise<EntityWriteOutcome<TResult>>;
|
||||
clearEntity: (entityKey: string) => void;
|
||||
clearPrefix: (prefix: string) => void;
|
||||
}
|
||||
|
||||
interface SlotState<TEntity> {
|
||||
version: number;
|
||||
apply: (entity: TEntity) => TEntity;
|
||||
phase: "pending" | "awaiting-sync";
|
||||
isSynced?: (base: TEntity) => boolean;
|
||||
timer?: ReturnType<typeof setTimeout>;
|
||||
}
|
||||
|
||||
interface QueuedWrite<TEntity> {
|
||||
patches: readonly EntitySlotPatch<TEntity>[];
|
||||
versions: readonly number[];
|
||||
barrier: boolean;
|
||||
send: () => Promise<unknown>;
|
||||
resolve: (outcome: EntityWriteOutcome<unknown>) => void;
|
||||
reject: (error: unknown) => void;
|
||||
}
|
||||
|
||||
interface EntityQueueState<TEntity> {
|
||||
epoch: unknown;
|
||||
slots: Map<string, SlotState<TEntity>>;
|
||||
queue: Array<QueuedWrite<TEntity>>;
|
||||
running: boolean;
|
||||
}
|
||||
|
||||
const DEFAULT_SYNC_TIMEOUT_MS = 1000;
|
||||
|
||||
/**
|
||||
* Serialized, coalescing optimistic write queue for any replicated entity. Keeps pending patches
|
||||
* projected on top of incoming remote updates, skips superseded intermediate writes, and rolls
|
||||
* back cleanly when the latest write fails.
|
||||
*/
|
||||
export function createEntityMutationQueue<TEntity>(
|
||||
adapter: EntityOverlayAdapter<TEntity>,
|
||||
): EntityMutationQueue<TEntity> {
|
||||
const syncTimeoutMs = adapter.syncTimeoutMs ?? DEFAULT_SYNC_TIMEOUT_MS;
|
||||
const entities = new Map<string, EntityQueueState<TEntity>>();
|
||||
let nextVersion = 0;
|
||||
let stopWatchingBase: (() => void) | null = null;
|
||||
|
||||
function clearTimer(slot: SlotState<TEntity> | undefined): void {
|
||||
if (slot?.timer !== undefined) {
|
||||
clearTimeout(slot.timer);
|
||||
slot.timer = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function syncWatcher(): void {
|
||||
if (!adapter.subscribeBase) return;
|
||||
if (entities.size > 0) {
|
||||
stopWatchingBase ??= adapter.subscribeBase(reconcile);
|
||||
} else if (stopWatchingBase) {
|
||||
stopWatchingBase();
|
||||
stopWatchingBase = null;
|
||||
}
|
||||
}
|
||||
|
||||
function publish(entityKey: string): void {
|
||||
const entry = entities.get(entityKey);
|
||||
if (!entry || entry.slots.size === 0) {
|
||||
adapter.setOverlay(entityKey, null);
|
||||
if (entry && !entry.running && entry.queue.length === 0) entities.delete(entityKey);
|
||||
syncWatcher();
|
||||
return;
|
||||
}
|
||||
const ordered = Array.from(entry.slots.values()).sort((a, b) => a.version - b.version);
|
||||
const apply = (base: TEntity) => ordered.reduce((acc, slot) => slot.apply(acc), base);
|
||||
adapter.setOverlay(entityKey, apply);
|
||||
syncWatcher();
|
||||
}
|
||||
|
||||
function dropEntity(entityKey: string): void {
|
||||
const entry = entities.get(entityKey);
|
||||
if (!entry) return;
|
||||
for (const slot of entry.slots.values()) clearTimer(slot);
|
||||
entry.slots.clear();
|
||||
for (const queued of entry.queue) queued.resolve({ status: "superseded" });
|
||||
entry.queue.length = 0;
|
||||
entities.delete(entityKey);
|
||||
adapter.setOverlay(entityKey, null);
|
||||
syncWatcher();
|
||||
}
|
||||
|
||||
function reconcile(): void {
|
||||
for (const [entityKey, entry] of Array.from(entities.entries())) {
|
||||
const base = adapter.getBase(entityKey);
|
||||
const epoch = adapter.getEpoch?.(entityKey);
|
||||
if (!base || !Object.is(epoch, entry.epoch)) {
|
||||
dropEntity(entityKey);
|
||||
continue;
|
||||
}
|
||||
let changed = false;
|
||||
for (const [slotKey, slot] of Array.from(entry.slots.entries())) {
|
||||
if (slot.phase !== "awaiting-sync") continue;
|
||||
if (slot.isSynced && !slot.isSynced(base)) continue;
|
||||
clearTimer(slot);
|
||||
entry.slots.delete(slotKey);
|
||||
changed = true;
|
||||
}
|
||||
if (changed) publish(entityKey);
|
||||
}
|
||||
}
|
||||
|
||||
function settleSuccess(
|
||||
entityKey: string,
|
||||
entry: EntityQueueState<TEntity>,
|
||||
slotKey: string,
|
||||
version: number,
|
||||
isSynced: ((base: TEntity) => boolean) | undefined,
|
||||
): void {
|
||||
const slot = entry.slots.get(slotKey);
|
||||
if (!slot || slot.version !== version) return;
|
||||
const base = adapter.getBase(entityKey);
|
||||
if (!base || !isSynced || isSynced(base)) {
|
||||
clearTimer(slot);
|
||||
entry.slots.delete(slotKey);
|
||||
return;
|
||||
}
|
||||
slot.phase = "awaiting-sync";
|
||||
slot.isSynced = isSynced;
|
||||
clearTimer(slot);
|
||||
slot.timer = setTimeout(() => {
|
||||
const currentEntry = entities.get(entityKey);
|
||||
const currentSlot = currentEntry?.slots.get(slotKey);
|
||||
if (!currentEntry || !currentSlot || currentSlot.version !== version) return;
|
||||
currentSlot.timer = undefined;
|
||||
currentEntry.slots.delete(slotKey);
|
||||
publish(entityKey);
|
||||
}, syncTimeoutMs);
|
||||
}
|
||||
|
||||
function settleFailure(entry: EntityQueueState<TEntity>, slotKey: string, version: number): void {
|
||||
const slot = entry.slots.get(slotKey);
|
||||
if (!slot || slot.version !== version) return;
|
||||
clearTimer(slot);
|
||||
entry.slots.delete(slotKey);
|
||||
}
|
||||
|
||||
function hasCurrentSlot(entry: EntityQueueState<TEntity>, item: QueuedWrite<TEntity>): boolean {
|
||||
if (item.patches.length === 0) return true;
|
||||
return item.patches.some(
|
||||
(patch, index) => entry.slots.get(patch.slot)?.version === item.versions[index],
|
||||
);
|
||||
}
|
||||
|
||||
function enqueue(entry: EntityQueueState<TEntity>, item: QueuedWrite<TEntity>): void {
|
||||
if (item.patches.length === 1 && !item.barrier) {
|
||||
const targetSlot = item.patches[0].slot;
|
||||
for (let i = entry.queue.length - 1; i >= 0; i -= 1) {
|
||||
const existing = entry.queue[i];
|
||||
if (
|
||||
existing.patches.length === 1 &&
|
||||
existing.patches[0].slot === targetSlot &&
|
||||
!existing.barrier
|
||||
) {
|
||||
existing.resolve({ status: "superseded" });
|
||||
entry.queue[i] = item;
|
||||
return;
|
||||
}
|
||||
if (existing.barrier || existing.patches.some((patch) => patch.slot === targetSlot)) break;
|
||||
}
|
||||
}
|
||||
entry.queue.push(item);
|
||||
}
|
||||
|
||||
async function runOne(
|
||||
entityKey: string,
|
||||
entry: EntityQueueState<TEntity>,
|
||||
item: QueuedWrite<TEntity>,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const result = await item.send();
|
||||
if (entities.get(entityKey) !== entry) {
|
||||
item.resolve({ status: "superseded" });
|
||||
return;
|
||||
}
|
||||
const current = hasCurrentSlot(entry, item);
|
||||
for (let i = 0; i < item.patches.length; i += 1) {
|
||||
const patch = item.patches[i];
|
||||
settleSuccess(entityKey, entry, patch.slot, item.versions[i], patch.isSynced);
|
||||
}
|
||||
publish(entityKey);
|
||||
item.resolve(current ? { status: "applied", result } : { status: "superseded" });
|
||||
} catch (error) {
|
||||
if (entities.get(entityKey) !== entry) {
|
||||
item.resolve({ status: "superseded" });
|
||||
return;
|
||||
}
|
||||
const current = hasCurrentSlot(entry, item);
|
||||
for (let i = 0; i < item.patches.length; i += 1) {
|
||||
settleFailure(entry, item.patches[i].slot, item.versions[i]);
|
||||
}
|
||||
publish(entityKey);
|
||||
if (current) item.reject(error);
|
||||
else item.resolve({ status: "superseded" });
|
||||
}
|
||||
}
|
||||
|
||||
function startIfIdle(entityKey: string, entry: EntityQueueState<TEntity>): void {
|
||||
if (entry.running) return;
|
||||
entry.running = true;
|
||||
void (async () => {
|
||||
try {
|
||||
while (entities.get(entityKey) === entry && entry.queue.length > 0) {
|
||||
await runOne(entityKey, entry, entry.queue.shift()!);
|
||||
}
|
||||
} finally {
|
||||
entry.running = false;
|
||||
if (entities.get(entityKey) === entry) {
|
||||
if (entry.queue.length > 0) startIfIdle(entityKey, entry);
|
||||
else publish(entityKey);
|
||||
}
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
return {
|
||||
write<TResult>(input: EntityWrite<TEntity, TResult>): Promise<EntityWriteOutcome<TResult>> {
|
||||
const epoch = adapter.getEpoch?.(input.entityKey);
|
||||
let entry = entities.get(input.entityKey);
|
||||
if (entry && !Object.is(entry.epoch, epoch)) {
|
||||
dropEntity(input.entityKey);
|
||||
entry = undefined;
|
||||
}
|
||||
if (!entry) {
|
||||
entry = { epoch, slots: new Map(), queue: [], running: false };
|
||||
entities.set(input.entityKey, entry);
|
||||
}
|
||||
|
||||
const versions = input.patches.map((patch) => {
|
||||
const version = ++nextVersion;
|
||||
clearTimer(entry.slots.get(patch.slot));
|
||||
entry.slots.set(patch.slot, { version, apply: patch.apply, phase: "pending" });
|
||||
return version;
|
||||
});
|
||||
|
||||
return new Promise<EntityWriteOutcome<TResult>>((resolve, reject) => {
|
||||
enqueue(entry, {
|
||||
patches: input.patches,
|
||||
versions,
|
||||
barrier: input.barrier === true,
|
||||
send: input.send,
|
||||
resolve: resolve as (outcome: EntityWriteOutcome<unknown>) => void,
|
||||
reject,
|
||||
});
|
||||
publish(input.entityKey);
|
||||
startIfIdle(input.entityKey, entry);
|
||||
});
|
||||
},
|
||||
|
||||
clearEntity: dropEntity,
|
||||
|
||||
clearPrefix(prefix: string): void {
|
||||
for (const entityKey of Array.from(entities.keys())) {
|
||||
if (entityKey.startsWith(prefix)) dropEntity(entityKey);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -888,3 +888,35 @@ describe("removeWorkspace", () => {
|
||||
expect(after.workspaces).toBe(before.workspaces);
|
||||
});
|
||||
});
|
||||
|
||||
describe("setAgentOverlay", () => {
|
||||
it("rolls back cleanly when an overlaid agent moves from agentDetails to agents mid-write", () => {
|
||||
const store = useSessionStore.getState();
|
||||
initializeTestSession();
|
||||
const initial = { ...createTestAgent("agent-1"), thinkingOptionId: "low" };
|
||||
store.setAgentDetails("test-server", new Map([["agent-1", initial]]));
|
||||
|
||||
// User edits thinking while the agent is only in agentDetails.
|
||||
store.setAgentOverlay("test-server", "agent-1", (agent) => ({
|
||||
...agent,
|
||||
thinkingOptionId: "high",
|
||||
}));
|
||||
expect(
|
||||
useSessionStore.getState().sessions["test-server"]?.agentDetails.get("agent-1")
|
||||
?.thinkingOptionId,
|
||||
).toBe("high");
|
||||
|
||||
// Directory accept promotes the agent into `agents`, then clears `agentDetails`.
|
||||
store.setAgents("test-server", new Map([["agent-1", initial]]));
|
||||
store.setAgentDetails("test-server", new Map());
|
||||
expect(
|
||||
useSessionStore.getState().sessions["test-server"]?.agents.get("agent-1")?.thinkingOptionId,
|
||||
).toBe("high");
|
||||
|
||||
// Write fails -> clearing the overlay rolls `agents` back to the daemon value ("low").
|
||||
store.setAgentOverlay("test-server", "agent-1", null);
|
||||
expect(
|
||||
useSessionStore.getState().sessions["test-server"]?.agents.get("agent-1")?.thinkingOptionId,
|
||||
).toBe("low");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -117,6 +117,8 @@ export interface Agent {
|
||||
projectPlacement?: ProjectPlacementPayload | null;
|
||||
}
|
||||
|
||||
export type AgentOverlay = (agent: Agent) => Agent;
|
||||
|
||||
export interface WorkspaceDescriptor {
|
||||
parentWorkspaceId?: string;
|
||||
createdAt: Date | null;
|
||||
@@ -260,6 +262,108 @@ function preserveMapIdentity<Key, Value>(
|
||||
return changed ? next : existing;
|
||||
}
|
||||
|
||||
function preserveAgentFieldIdentity(previous: Agent | undefined, incoming: Agent): Agent {
|
||||
if (!previous || previous === incoming) return incoming;
|
||||
const next = { ...incoming };
|
||||
let changed = Object.keys(previous).length !== Object.keys(next).length;
|
||||
for (const key of Object.keys(next) as (keyof Agent)[]) {
|
||||
if (next[key] === previous[key]) continue;
|
||||
if (key in previous && equal(next[key], previous[key])) {
|
||||
Object.assign(next, { [key]: previous[key] });
|
||||
} else {
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
return changed ? next : previous;
|
||||
}
|
||||
|
||||
function buildServerBaseView(
|
||||
current: Map<string, Agent>,
|
||||
bases: Map<string, Agent>,
|
||||
): Map<string, Agent> {
|
||||
let baseView = current;
|
||||
let copied = false;
|
||||
for (const [id, base] of bases) {
|
||||
if (!current.has(id)) continue;
|
||||
if (!copied) {
|
||||
baseView = new Map(current);
|
||||
copied = true;
|
||||
}
|
||||
baseView.set(id, base);
|
||||
}
|
||||
return baseView;
|
||||
}
|
||||
|
||||
function shouldDropOverlay(
|
||||
serverAgent: Agent | undefined,
|
||||
oldBase: Agent | undefined,
|
||||
): serverAgent is undefined {
|
||||
if (!serverAgent) return true;
|
||||
if (serverAgent.archivedAt != null) return true;
|
||||
return oldBase !== undefined && serverAgent.provider !== oldBase.provider;
|
||||
}
|
||||
|
||||
function projectAgentMapWithOverlays(input: {
|
||||
current: Map<string, Agent>;
|
||||
otherMap: Map<string, Agent>;
|
||||
updater: Map<string, Agent> | ((prev: Map<string, Agent>) => Map<string, Agent>);
|
||||
overlays: Map<string, AgentOverlay>;
|
||||
bases: Map<string, Agent>;
|
||||
}): {
|
||||
agents: Map<string, Agent>;
|
||||
overlays: Map<string, AgentOverlay>;
|
||||
bases: Map<string, Agent>;
|
||||
} | null {
|
||||
if (input.overlays.size === 0) {
|
||||
const next = typeof input.updater === "function" ? input.updater(input.current) : input.updater;
|
||||
return next === input.current
|
||||
? null
|
||||
: { agents: next, overlays: input.overlays, bases: input.bases };
|
||||
}
|
||||
|
||||
const baseView =
|
||||
typeof input.updater === "function"
|
||||
? buildServerBaseView(input.current, input.bases)
|
||||
: input.current;
|
||||
const rawNext = typeof input.updater === "function" ? input.updater(baseView) : input.updater;
|
||||
if (rawNext === baseView) return null;
|
||||
|
||||
const nextAgents = new Map(rawNext);
|
||||
let nextOverlays = input.overlays;
|
||||
let nextBases = input.bases;
|
||||
for (const [id, overlay] of input.overlays) {
|
||||
const serverAgent = rawNext.get(id);
|
||||
const oldBase = input.bases.get(id);
|
||||
if (shouldDropOverlay(serverAgent, oldBase)) {
|
||||
// Keep the session overlay when this map dropped the id because it lives in the other map
|
||||
// (for example, `agentDetails` clearing after `agents` accepted the directory delta).
|
||||
if (!serverAgent && input.otherMap.has(id)) continue;
|
||||
if (oldBase && !input.current.has(id)) continue;
|
||||
if (nextOverlays === input.overlays) nextOverlays = new Map(input.overlays);
|
||||
if (nextBases === input.bases) nextBases = new Map(input.bases);
|
||||
nextOverlays.delete(id);
|
||||
nextBases.delete(id);
|
||||
continue;
|
||||
}
|
||||
if (nextBases === input.bases) nextBases = new Map(input.bases);
|
||||
nextBases.set(id, serverAgent);
|
||||
nextAgents.set(id, preserveAgentFieldIdentity(input.current.get(id), overlay(serverAgent)));
|
||||
}
|
||||
return { agents: nextAgents, overlays: nextOverlays, bases: nextBases };
|
||||
}
|
||||
|
||||
/** Reads the un-overlaid remote snapshot of an agent (used by optimistic mutation queues). */
|
||||
export function getSessionAgentBase(serverId: string, agentId: string): Agent | null {
|
||||
const session = useSessionStore.getState().sessions[serverId];
|
||||
if (!session) return null;
|
||||
return (
|
||||
session.agentOverlayBases.get(agentId) ??
|
||||
session.agents.get(agentId) ??
|
||||
session.agentDetails.get(agentId) ??
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
export type ExplorerEntryKind = "file" | "directory";
|
||||
|
||||
export interface ExplorerEntry {
|
||||
@@ -557,6 +661,10 @@ export interface SessionState {
|
||||
agents: Map<string, Agent>;
|
||||
workspaceAgentActivity: Map<string, WorkspaceAgentActivity>;
|
||||
agentDetails: Map<string, Agent>;
|
||||
// Pending optimistic projections layered onto `agents` / `agentDetails`.
|
||||
// `agentOverlayBases` keeps the un-overlaid remote snapshot only for overlaid ids.
|
||||
agentOverlays: Map<string, AgentOverlay>;
|
||||
agentOverlayBases: Map<string, Agent>;
|
||||
workspaces: Map<string, WorkspaceDescriptor>;
|
||||
// All active project descriptors, keyed by host-local projectId.
|
||||
projects: Map<string, ProjectDescriptor>;
|
||||
@@ -713,6 +821,7 @@ interface SessionStoreActions {
|
||||
serverId: string,
|
||||
agents: Map<string, Agent> | ((prev: Map<string, Agent>) => Map<string, Agent>),
|
||||
) => void;
|
||||
setAgentOverlay: (serverId: string, agentId: string, overlay: AgentOverlay | null) => void;
|
||||
setWorkspaces: (
|
||||
serverId: string,
|
||||
workspaces:
|
||||
@@ -806,6 +915,8 @@ function createInitialSessionState(
|
||||
agents: new Map(),
|
||||
workspaceAgentActivity: new Map(),
|
||||
agentDetails: new Map(),
|
||||
agentOverlays: new Map(),
|
||||
agentOverlayBases: new Map(),
|
||||
workspaces: new Map(),
|
||||
projects: new Map(),
|
||||
restoringWorkspaces: new Map(),
|
||||
@@ -1712,8 +1823,14 @@ export const useSessionStore = create<SessionStore>()(
|
||||
if (!session) {
|
||||
return prev;
|
||||
}
|
||||
const nextAgents = typeof agents === "function" ? agents(session.agents) : agents;
|
||||
if (session.agents === nextAgents) {
|
||||
const projected = projectAgentMapWithOverlays({
|
||||
current: session.agents,
|
||||
otherMap: session.agentDetails,
|
||||
updater: agents,
|
||||
overlays: session.agentOverlays,
|
||||
bases: session.agentOverlayBases,
|
||||
});
|
||||
if (!projected) {
|
||||
return prev;
|
||||
}
|
||||
return {
|
||||
@@ -1722,9 +1839,11 @@ export const useSessionStore = create<SessionStore>()(
|
||||
...prev.sessions,
|
||||
[serverId]: {
|
||||
...session,
|
||||
agents: nextAgents,
|
||||
agents: projected.agents,
|
||||
agentOverlays: projected.overlays,
|
||||
agentOverlayBases: projected.bases,
|
||||
workspaceAgentActivity: buildWorkspaceAgentActivityIndex(
|
||||
nextAgents,
|
||||
projected.agents,
|
||||
session.workspaceAgentActivity,
|
||||
),
|
||||
},
|
||||
@@ -1739,15 +1858,92 @@ export const useSessionStore = create<SessionStore>()(
|
||||
if (!session) {
|
||||
return prev;
|
||||
}
|
||||
const nextAgents = typeof agents === "function" ? agents(session.agentDetails) : agents;
|
||||
if (session.agentDetails === nextAgents) {
|
||||
const projected = projectAgentMapWithOverlays({
|
||||
current: session.agentDetails,
|
||||
otherMap: session.agents,
|
||||
updater: agents,
|
||||
overlays: session.agentOverlays,
|
||||
bases: session.agentOverlayBases,
|
||||
});
|
||||
if (!projected) {
|
||||
return prev;
|
||||
}
|
||||
return {
|
||||
...prev,
|
||||
sessions: {
|
||||
...prev.sessions,
|
||||
[serverId]: { ...session, agentDetails: nextAgents },
|
||||
[serverId]: {
|
||||
...session,
|
||||
agentDetails: projected.agents,
|
||||
agentOverlays: projected.overlays,
|
||||
agentOverlayBases: projected.bases,
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
setAgentOverlay: (serverId, agentId, overlay) => {
|
||||
set((prev) => {
|
||||
const session = prev.sessions[serverId];
|
||||
if (!session) return prev;
|
||||
const inAgents = session.agents.has(agentId);
|
||||
const inDetails = !inAgents && session.agentDetails.has(agentId);
|
||||
if (!inAgents && !inDetails) {
|
||||
if (!session.agentOverlays.has(agentId) && !session.agentOverlayBases.has(agentId)) {
|
||||
return prev;
|
||||
}
|
||||
const agentOverlays = new Map(session.agentOverlays);
|
||||
const agentOverlayBases = new Map(session.agentOverlayBases);
|
||||
agentOverlays.delete(agentId);
|
||||
agentOverlayBases.delete(agentId);
|
||||
return {
|
||||
...prev,
|
||||
sessions: {
|
||||
...prev.sessions,
|
||||
[serverId]: { ...session, agentOverlays, agentOverlayBases },
|
||||
},
|
||||
};
|
||||
}
|
||||
const targetMap = inAgents ? session.agents : session.agentDetails;
|
||||
const currentProjected = targetMap.get(agentId)!;
|
||||
const base = session.agentOverlayBases.get(agentId) ?? currentProjected;
|
||||
const agentOverlays = new Map(session.agentOverlays);
|
||||
const agentOverlayBases = new Map(session.agentOverlayBases);
|
||||
let nextAgent: Agent;
|
||||
if (overlay === null) {
|
||||
if (!agentOverlays.has(agentId) && !agentOverlayBases.has(agentId)) return prev;
|
||||
agentOverlays.delete(agentId);
|
||||
agentOverlayBases.delete(agentId);
|
||||
nextAgent = preserveAgentFieldIdentity(currentProjected, base);
|
||||
} else {
|
||||
agentOverlays.set(agentId, overlay);
|
||||
agentOverlayBases.set(agentId, base);
|
||||
nextAgent = preserveAgentFieldIdentity(currentProjected, overlay(base));
|
||||
}
|
||||
const nextMap =
|
||||
nextAgent === currentProjected ? targetMap : new Map(targetMap).set(agentId, nextAgent);
|
||||
return {
|
||||
...prev,
|
||||
sessions: {
|
||||
...prev.sessions,
|
||||
[serverId]: {
|
||||
...session,
|
||||
agentOverlays,
|
||||
agentOverlayBases,
|
||||
...(inAgents
|
||||
? {
|
||||
agents: nextMap,
|
||||
workspaceAgentActivity:
|
||||
nextMap === session.agents
|
||||
? session.workspaceAgentActivity
|
||||
: buildWorkspaceAgentActivityIndex(
|
||||
nextMap,
|
||||
session.workspaceAgentActivity,
|
||||
),
|
||||
}
|
||||
: { agentDetails: nextMap }),
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
@@ -1281,6 +1281,11 @@ export class Session {
|
||||
this.agentConfigSession = new AgentConfigSession({
|
||||
host: {
|
||||
emit: (msg) => this.emit(msg),
|
||||
runAfterAgentUpdates: (agentId, action) =>
|
||||
this.agentUpdates.runAfterUpdates(agentId, () => {
|
||||
if (this.isCleanedUp) return;
|
||||
action();
|
||||
}),
|
||||
},
|
||||
operations: {
|
||||
ensureLoaded: async (agentId, mutationOptions) => {
|
||||
|
||||
@@ -6,7 +6,8 @@ import {
|
||||
type AgentConfigSessionHost,
|
||||
} from "./agent-config-session.js";
|
||||
import type { AgentProviderNotice } from "../../agent/agent-sdk-types.js";
|
||||
import type { SessionOutboundMessage } from "../../messages.js";
|
||||
import type { SessionInboundMessage, SessionOutboundMessage } from "../../messages.js";
|
||||
import { SessionDelivery } from "../owned-subscriptions/index.js";
|
||||
|
||||
class FakeAgentConfigOperations implements AgentConfigOperations {
|
||||
readonly loadedAgentIds: string[] = [];
|
||||
@@ -456,4 +457,57 @@ describe("AgentConfigSession", () => {
|
||||
payload: { requestId: "req-1", agentId: "agent-1", accepted: false, error: "apply boom" },
|
||||
});
|
||||
});
|
||||
|
||||
test("keeps SessionDelivery request active until queued live agent updates flush before replying", async () => {
|
||||
const delivered: Array<SessionOutboundMessage["type"]> = [];
|
||||
const socket = {};
|
||||
const delivery = new SessionDelivery((_source, message) => {
|
||||
delivered.push(message.type);
|
||||
});
|
||||
delivery.attach(socket, true);
|
||||
|
||||
let releaseAgentUpdate!: () => void;
|
||||
const pendingAgentUpdate = new Promise<void>((resolve) => {
|
||||
releaseAgentUpdate = resolve;
|
||||
});
|
||||
const operations = new FakeAgentConfigOperations();
|
||||
const subsystem = new AgentConfigSession({
|
||||
host: {
|
||||
emit: (msg) => {
|
||||
delivery.reply(msg);
|
||||
},
|
||||
runAfterAgentUpdates: async (_agentId, action) => {
|
||||
await pendingAgentUpdate;
|
||||
action();
|
||||
},
|
||||
},
|
||||
operations,
|
||||
logger: pino({ level: "silent" }),
|
||||
});
|
||||
|
||||
const request: Extract<SessionInboundMessage, { type: "set_agent_thinking_request" }> = {
|
||||
type: "set_agent_thinking_request",
|
||||
agentId: "agent-1",
|
||||
thinkingOptionId: "high",
|
||||
requestId: "req-1",
|
||||
};
|
||||
let settled = false;
|
||||
const runRequest = () => subsystem.handleSetAgentThinkingRequest(request);
|
||||
const pendingRequest = delivery.request(socket, request, runRequest).finally(() => {
|
||||
settled = true;
|
||||
});
|
||||
|
||||
// Wait for ensureLoaded + setThinking to reach runAfterAgentUpdates.
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
expect(settled).toBe(false);
|
||||
expect(delivered).toEqual([]);
|
||||
|
||||
// Emit the queued agent_update, then let the deferred reply run while the request is still active.
|
||||
delivered.push("agent_update");
|
||||
releaseAgentUpdate();
|
||||
await pendingRequest;
|
||||
|
||||
expect(settled).toBe(true);
|
||||
expect(delivered).toEqual(["agent_update", "set_agent_thinking_response"]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -18,6 +18,8 @@ type AgentActionResponsePayload = Extract<
|
||||
|
||||
export interface AgentConfigSessionHost {
|
||||
emit(msg: SessionOutboundMessage): void;
|
||||
/** Runs after any queued live `agent_update` for `agentId` has been emitted on the socket. */
|
||||
runAfterAgentUpdates?(agentId: string, action: () => void): void | Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -234,6 +236,14 @@ export class AgentConfigSession {
|
||||
return notice;
|
||||
}
|
||||
|
||||
private async emitAfterAgentUpdates(agentId: string, action: () => void): Promise<void> {
|
||||
if (this.host.runAfterAgentUpdates) {
|
||||
await this.host.runAfterAgentUpdates(agentId, action);
|
||||
return;
|
||||
}
|
||||
action();
|
||||
}
|
||||
|
||||
private async applyConfigChange(change: ConfigChange): Promise<void> {
|
||||
const { agentId, requestId, options, logLabel, logFields, failureText, run, emitResponse } =
|
||||
change;
|
||||
@@ -243,23 +253,27 @@ export class AgentConfigSession {
|
||||
await this.operations.ensureLoaded(agentId, options);
|
||||
const notice = await run();
|
||||
this.logger.info(logFields, `session: ${logLabel} success`);
|
||||
emitResponse({ requestId, agentId, accepted: true, error: null, notice });
|
||||
await this.emitAfterAgentUpdates(agentId, () => {
|
||||
emitResponse({ requestId, agentId, accepted: true, error: null, notice });
|
||||
});
|
||||
} catch (error) {
|
||||
this.logger.error({ err: error, ...logFields }, `session: ${logLabel} error`);
|
||||
this.host.emit({
|
||||
type: "activity_log",
|
||||
payload: {
|
||||
id: uuidv4(),
|
||||
timestamp: new Date(),
|
||||
type: "error",
|
||||
content: `${failureText}: ${getErrorMessage(error)}`,
|
||||
},
|
||||
});
|
||||
emitResponse({
|
||||
requestId,
|
||||
agentId,
|
||||
accepted: false,
|
||||
error: getErrorMessageOr(error, failureText),
|
||||
await this.emitAfterAgentUpdates(agentId, () => {
|
||||
this.host.emit({
|
||||
type: "activity_log",
|
||||
payload: {
|
||||
id: uuidv4(),
|
||||
timestamp: new Date(),
|
||||
type: "error",
|
||||
content: `${failureText}: ${getErrorMessage(error)}`,
|
||||
},
|
||||
});
|
||||
emitResponse({
|
||||
requestId,
|
||||
agentId,
|
||||
accepted: false,
|
||||
error: getErrorMessageOr(error, failureText),
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,7 +67,7 @@ export interface AgentUpdatesService {
|
||||
* order with queued `agent_update` frames for that agent. Runs synchronously when nothing is
|
||||
* queued for the agent, and never waits on workspace broadcasts.
|
||||
*/
|
||||
runAfterUpdates(agentId: string, action: () => void): void;
|
||||
runAfterUpdates(agentId: string, action: () => void): Promise<void>;
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
@@ -444,12 +444,12 @@ export function createAgentUpdatesService(deps: AgentUpdatesServiceDeps): AgentU
|
||||
}
|
||||
}
|
||||
|
||||
function runAfterUpdates(agentId: string, action: () => void): void {
|
||||
function runAfterUpdates(agentId: string, action: () => void): Promise<void> {
|
||||
if (!liveAgentUpdateTails.has(agentId)) {
|
||||
action();
|
||||
return;
|
||||
return Promise.resolve();
|
||||
}
|
||||
void enqueueAgentUpdate(agentId, action);
|
||||
return enqueueAgentUpdate(agentId, action);
|
||||
}
|
||||
|
||||
function dispose(): void {
|
||||
|
||||
Reference in New Issue
Block a user