Compare commits

..
Author SHA1 Message Date
Matchy d399c82f51 fix(server): keep plugin entries other writers put in config.json (#11501)
The daemon owns plugin source entries and `paseo reload` does not pick up
edits to `plugins`, so its in-memory copy goes stale when config.json is
edited while it runs. Every plugin operation (install, enable, disable,
update, remove) then wrote that whole stale map back to disk. A hand-added
entry was silently deleted by the next operation on any other plugin, and
an entry removed by hand was written back. Local directory plugins hit
this most, since they are the ones people add by editing config.json.

Persisting a plugins patch now applies only the entries that changed
relative to the in-memory copy onto the plugins read from disk. Reload
still ignores plugin edits; they now survive until the next restart loads
them, as docs/plugins.md describes.

Verified with new DaemonConfigStore tests covering a hand-added entry, a
hand-removed entry, and removing one plugin while another sits on disk;
all three failed before the change.
2026-11-30 19:42:40 +00:00
SunicemanandShane Su 9a520f0adc Keep attached plugin slash commands out of the agent conversation (#11483)
Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>
2026-11-30 17:12:44 +00:00
20 changed files with 196 additions and 152 deletions
@@ -1,5 +1,11 @@
import { expect, test, type Page } from "../support/fixtures";
import { composerLocator, expectComposerVisible, submitMessage } from "../support/helpers/composer";
import { withDirectoryPlugin } from "../support/helpers/plugin-timeline";
import {
attachImageFromMenu,
composerLocator,
expectComposerVisible,
submitMessage,
} from "../support/helpers/composer";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import {
expectSessionRowArchived,
@@ -140,6 +146,47 @@ async function waitForReplacementAgentId(page: Page, oldAgentId: string): Promis
}
test.describe("Client slash commands", () => {
test("keeps the draft when a typed plugin slash command has an attachment", async ({ page }) => {
test.setTimeout(90_000);
await withDirectoryPlugin({
pluginId: "attachment-slash-e2e",
source: `
export default function contribute(client) {
client.addSlashCommand({name:"picture", description:"Review an attached picture", argumentHint:"<question>", context:"agent",
onSubmit(){throw new Error("Plugin handler unexpectedly received this command");}});
return () => {};
}`,
run: async () => {
await withOpenReadyMockAgent(page, { title: "Attached slash command" }, async () => {
const input = composerLocator(page);
await input.fill("/pict");
await expect(
page.getByText("Review an attached picture", { exact: true }).first(),
).toBeVisible();
await input.fill("");
await attachImageFromMenu(page, {
name: "picture.png",
mimeType: "image/png",
buffer: Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",
"base64",
),
});
await input.fill("/picture what is this?");
await input.press("Enter");
await expect(
page.getByRole("alert").filter({ hasText: "Remove attachments to run /picture." }),
).toBeVisible();
await expect(input).toHaveValue("/picture what is this?");
await expect(page.getByTestId("composer-image-attachment-pill")).toBeVisible();
await expect(
page.getByTestId("user-message").filter({ hasText: "/picture what is this?" }),
).toHaveCount(0);
});
},
});
});
test("slash quit archives the active agent and removes its tab", async ({ page }) => {
await withOpenReadyMockAgent(page, { title: "Slash quit e2e" }, async ({ agentId, title }) => {
await runClientSlashCommand(page, "/quit");
@@ -52,28 +52,17 @@ async function exitSelection(page: Page) {
}
/**
* Walks the sidebar selection click matrix on four rows: Cmd/Ctrl+click (and Cmd/Ctrl+Shift+click)
* from normal mode navigates instead of entering select mode, Shift+click enters select mode on the
* clicked row alone, Cmd/Ctrl+click and plain clicks toggle while select mode is active, and
* Shift+click extends, shrinks, and flips a range from the anchor.
* Walks the Finder click matrix on four rows, starting with the first row open: a modifier click
* from normal mode selects only the clicked row, Cmd/Ctrl+click toggles, Shift+click extends and
* shrinks a range from the anchor, and plain clicks keep toggling while select mode is on.
*/
async function exerciseClickMatrix(page: Page, rows: readonly Locator[]) {
const [first, second, third, fourth] = rows;
await first.click();
await expect(first).toHaveAttribute("aria-selected", "true");
// Cmd/Ctrl+click and Cmd/Ctrl+Shift+click outside select mode navigate normally.
await third.click({ modifiers: [MOD] });
await expect(third).toHaveAttribute("aria-selected", "true");
await expect(page.getByTestId("workspace-selection-toast")).toHaveCount(0);
await first.click({ modifiers: [MOD, "Shift"] });
await expect(first).toHaveAttribute("aria-selected", "true");
await expect(page.getByTestId("workspace-selection-toast")).toHaveCount(0);
const openWorkspaceUrl = page.url();
// Shift+click enters select mode on the clicked row alone; Cmd/Ctrl+click and plain clicks toggle.
await third.click({ modifiers: ["Shift"] });
await third.click({ modifiers: [MOD] });
await expectSelectedCount(page, 1);
await expectChecked(rows, [false, false, true, false]);
@@ -113,7 +102,7 @@ test.describe("sidebar workspace selection clicks", () => {
seeded = null;
});
test("Shift+click enters select mode while Cmd/Ctrl+click navigates in project grouping", async ({
test("Cmd/Ctrl+click and Shift+click select like Finder in project grouping", async ({
page,
}) => {
seeded = await seedProjectWithWorkspaces(4);
@@ -122,9 +111,7 @@ test.describe("sidebar workspace selection clicks", () => {
await exerciseClickMatrix(page, await rowsInSidebarOrder(page, seeded.workspaceIds));
});
test("Shift+click enters select mode while Cmd/Ctrl+click navigates in status grouping", async ({
page,
}) => {
test("Cmd/Ctrl+click and Shift+click select like Finder in status grouping", async ({ page }) => {
seeded = await seedProjectWithWorkspaces(4);
await gotoAppShell(page);
await waitForSidebarHydration(page);
+19 -7
View File
@@ -1671,7 +1671,16 @@ function ComposerContentImpl({
);
const runPluginClientSlashCommand = useCallback(
(resolved: { command: (typeof pluginClientSlashCommands)[number]; args: string }): boolean => {
(
resolved: { command: (typeof pluginClientSlashCommands)[number]; args: string },
hasAttachments: boolean,
) => {
if (hasAttachments) {
setSendError(
t("composer.errors.removePluginCommandAttachments", { command: resolved.command.name }),
);
return;
}
if (blurOnSubmit) messageInputRef.current?.blur();
clearDraft("sent");
replaceUserInput("");
@@ -1686,9 +1695,8 @@ function ComposerContentImpl({
toastErrorRef.current(error instanceof Error ? error.message : String(error));
},
});
return true;
},
[blurOnSubmit, clearDraft, replaceUserInput, resetSuppression, setSelectedAttachments],
[blurOnSubmit, clearDraft, replaceUserInput, resetSuppression, setSelectedAttachments, t],
);
const { pickImages } = useImageAttachmentPicker();
@@ -1988,10 +1996,12 @@ function ComposerContentImpl({
}
const pluginSlashCommand = resolvePluginClientSlashCommand({
text: payload.text,
hasAttachments: outgoingAttachments.length > 0,
commands: pluginClientSlashCommands,
});
if (pluginSlashCommand && runPluginClientSlashCommand(pluginSlashCommand)) return;
if (pluginSlashCommand) {
runPluginClientSlashCommand(pluginSlashCommand, outgoingAttachments.length > 0);
return;
}
if (blurOnSubmit) {
messageInputRef.current?.blur();
@@ -2261,10 +2271,12 @@ function ComposerContentImpl({
}
const pluginSlashCommand = resolvePluginClientSlashCommand({
text: payload.text,
hasAttachments: outgoingAttachments.length > 0,
commands: pluginClientSlashCommands,
});
if (pluginSlashCommand && runPluginClientSlashCommand(pluginSlashCommand)) return;
if (pluginSlashCommand) {
runPluginClientSlashCommand(pluginSlashCommand, outgoingAttachments.length > 0);
return;
}
queueMessage(payload.text, outgoingAttachments);
},
[
+1
View File
@@ -195,6 +195,7 @@ export const ar: TranslationResources = {
removeReview: "إزالة مرفق المراجعة",
},
errors: {
removePluginCommandAttachments: "أزل المرفقات لتشغيل الأمر /{{command}}.",
failedToSend: "فشل في إرسال الرسالة",
failedToCreateAgent: "فشل في إنشاء الوكيل",
noHostSelected: "لم يتم تحديد مضيف",
+1
View File
@@ -193,6 +193,7 @@ export const en = {
removeReview: "Remove review attachment",
},
errors: {
removePluginCommandAttachments: "Remove attachments to run /{{command}}.",
failedToSend: "Failed to send message",
failedToCreateAgent: "Failed to create agent",
noHostSelected: "No host selected",
+1
View File
@@ -196,6 +196,7 @@ export const es: TranslationResources = {
removeReview: "Eliminar archivo adjunto de reseña",
},
errors: {
removePluginCommandAttachments: "Quita los archivos adjuntos para ejecutar /{{command}}.",
failedToSend: "No se pudo enviar el mensaje",
failedToCreateAgent: "No se pudo crear el agente",
noHostSelected: "Ningún anfitrión seleccionado",
+1
View File
@@ -197,6 +197,7 @@ export const fr: TranslationResources = {
removeReview: "Retirer la revue jointe",
},
errors: {
removePluginCommandAttachments: "Retirez les pièces jointes pour exécuter /{{command}}.",
failedToSend: "Impossible d’envoyer le message",
failedToCreateAgent: "Impossible de créer l’agent",
noHostSelected: "Aucun hôte sélectionné",
+1
View File
@@ -196,6 +196,7 @@ export const ja: TranslationResources = {
removeReview: "レビュー添付ファイルを削除",
},
errors: {
removePluginCommandAttachments: "/{{command}} を実行するには添付ファイルを削除してください。",
failedToSend: "メッセージの送信に失敗しました",
failedToCreateAgent: "エージェントの作成に失敗しました",
noHostSelected: "ホストが選択されていません",
+1
View File
@@ -195,6 +195,7 @@ export const ko: TranslationResources = {
removeReview: "리뷰 첨부 제거",
},
errors: {
removePluginCommandAttachments: "/{{command}} 명령을 실행하려면 첨부 파일을 제거하세요.",
failedToSend: "메시지를 보내지 못했습니다",
failedToCreateAgent: "에이전트를 생성하지 못했습니다",
noHostSelected: "선택된 호스트가 없습니다",
+1
View File
@@ -196,6 +196,7 @@ export const ptBR: TranslationResources = {
removeReview: "Remover anexo de revisão",
},
errors: {
removePluginCommandAttachments: "Remova os anexos para executar /{{command}}.",
failedToSend: "Falha ao enviar mensagem",
failedToCreateAgent: "Falha ao criar agente",
noHostSelected: "Nenhum host selecionado",
+1
View File
@@ -196,6 +196,7 @@ export const ru: TranslationResources = {
removeReview: "Удалить вложение проверки",
},
errors: {
removePluginCommandAttachments: "Чтобы выполнить /{{command}}, удалите вложения.",
failedToSend: "Не удалось отправить сообщение",
failedToCreateAgent: "Не удалось создать агента.",
noHostSelected: "Хост не выбран",
+1
View File
@@ -195,6 +195,7 @@ export const zhCN: TranslationResources = {
removeReview: "移除 review 附件",
},
errors: {
removePluginCommandAttachments: "请先移除附件,再运行 /{{command}}。",
failedToSend: "发送消息失败",
failedToCreateAgent: "创建 Agent 失败",
noHostSelected: "未选择 Host",
@@ -93,54 +93,19 @@ export function readPressModifiers(
context: PressModifierContext = { isMac: getShortcutOs() === "mac", held: heldModifiers },
): PressModifiers {
const modKey: HeldModifierKey = context.isMac ? "Meta" : "Control";
const trustEventFlags = !isTouchPressEvent(event);
return {
shift: resolveModifierFlag(event, "shiftKey", "Shift", trustEventFlags, context.held),
mod: resolveModifierFlag(event, MODIFIER_FLAGS[modKey], modKey, trustEventFlags, context.held),
shift: hasPressFlag(event, "shiftKey") || context.held.isDown("Shift"),
mod: hasPressFlag(event, MODIFIER_FLAGS[modKey]) || context.held.isDown(modKey),
};
}
function resolveModifierFlag(
event: unknown,
flag: "shiftKey" | "metaKey" | "ctrlKey",
heldKey: HeldModifierKey,
trustEventFlags: boolean,
held: Pick<HeldModifierTracker, "isDown">,
): boolean {
const eventFlag = readPressFlag(event, flag);
if (trustEventFlags && eventFlag !== undefined) {
return eventFlag;
}
return eventFlag === true || held.isDown(heldKey);
}
function readPressFlag(
event: unknown,
flag: "shiftKey" | "metaKey" | "ctrlKey",
): boolean | undefined {
if (typeof event !== "object" || event === null) return undefined;
const direct = Reflect.get(event, flag);
if (typeof direct === "boolean") return direct;
const nativeEvent = Reflect.get(event, "nativeEvent");
if (typeof nativeEvent !== "object" || nativeEvent === null) return undefined;
const nativeFlag = Reflect.get(nativeEvent, flag);
return typeof nativeFlag === "boolean" ? nativeFlag : undefined;
}
function isTouchPressEvent(event: unknown): boolean {
function hasPressFlag(event: unknown, flag: "shiftKey" | "metaKey" | "ctrlKey"): boolean {
if (typeof event !== "object" || event === null) return false;
return isTouchEventRecord(event) || isTouchEventRecord(Reflect.get(event, "nativeEvent"));
}
function isTouchEventRecord(record: unknown): boolean {
if (typeof record !== "object" || record === null) return false;
if (Reflect.get(record, "pointerType") === "touch") return true;
const type = Reflect.get(record, "type");
if (typeof type === "string" && type.startsWith("touch")) return true;
const sourceCapabilities = Reflect.get(record, "sourceCapabilities");
if (Reflect.get(event, flag) === true) return true;
const nativeEvent = Reflect.get(event, "nativeEvent");
return (
typeof sourceCapabilities === "object" &&
sourceCapabilities !== null &&
Reflect.get(sourceCapabilities, "firesTouchEvents") === true
typeof nativeEvent === "object" &&
nativeEvent !== null &&
Reflect.get(nativeEvent, flag) === true
);
}
@@ -407,45 +407,6 @@ describe("press modifiers", () => {
mod: false,
});
});
it("trusts explicit boolean flags on non-touch pointer events over stale held keys", async () => {
const { createHeldModifierTracker, readPressModifiers } =
await import("./internal/press-modifiers");
const held = createHeldModifierTracker();
// Simulate a missed key-up (e.g. OS overlay or native menu swallowing release).
held.handleKeyDown(modifierKey("Shift", "ShiftLeft", { shiftKey: true }));
held.handleKeyDown(modifierKey("Meta", "MetaLeft", { shiftKey: true, metaKey: true }));
const mouseClick = {
nativeEvent: { shiftKey: false, metaKey: false, ctrlKey: false, pointerType: "mouse" },
};
expect(readPressModifiers(mouseClick, { isMac: true, held })).toEqual({
shift: false,
mod: false,
});
// Touch-synthesized clicks on web may report false modifier flags while a hardware key is held.
const touchPointerClick = {
nativeEvent: { shiftKey: false, metaKey: false, ctrlKey: false, pointerType: "touch" },
};
expect(readPressModifiers(touchPointerClick, { isMac: true, held })).toEqual({
shift: true,
mod: true,
});
const touchCapabilityClick = {
nativeEvent: {
shiftKey: false,
metaKey: false,
ctrlKey: false,
sourceCapabilities: { firesTouchEvents: true },
},
};
expect(readPressModifiers(touchCapabilityClick, { isMac: true, held })).toEqual({
shift: true,
mod: true,
});
});
});
describe("non-TextInput native focus registration", () => {
@@ -33,14 +33,12 @@ describe("plugin client slash commands", () => {
expect(
resolvePluginClientSlashCommand({
text: " /review foo bar ",
hasAttachments: false,
commands: [command],
}),
).toEqual({ command, args: "foo bar" });
expect(
resolvePluginClientSlashCommand({
text: "/review foo",
hasAttachments: true,
text: "/another-command foo",
commands: [command],
}),
).toBeNull();
@@ -47,10 +47,8 @@ export function mergeSlashCommandSources<
export function resolvePluginClientSlashCommand<Command extends SlashCommandDescriptor>(input: {
text: string;
hasAttachments: boolean;
commands: readonly Command[];
}): { command: Command; args: string } | null {
if (input.hasAttachments) return null;
const match = /^\/([^\s]+)(?:\s+([\s\S]*))?$/.exec(input.text.trim());
if (!match) return null;
const command = input.commands.find((candidate) => candidate.name === match[1]);
@@ -218,24 +218,14 @@ async function slowClick(element: HTMLElement) {
const MOD_KEY = getShortcutOs() === "mac" ? "Meta" : "Control";
describe("sidebar workspace row presses", () => {
it("navigates on Cmd/Ctrl+click and Cmd/Ctrl+Shift+click outside select mode, and toggles with Cmd/Ctrl+click once active", async () => {
it("enters select mode on the Cmd/Ctrl+clicked row alone and toggles rows without navigating", async () => {
mountHost(["a", "b", "c", "d"].map(makeEntry));
await userEvent.click(row("a"));
expect(navigatedKeys).toEqual(["srv:a"]);
expect(useSidebarSelectionStore.getState().active).toBe(false);
// Cmd/Ctrl+click (and Cmd/Ctrl+Shift+click) must not enter select mode from idle.
await userEvent.click(row("c"), { modifiers: [MOD_KEY] });
expect(useSidebarSelectionStore.getState().active).toBe(false);
expect(navigatedKeys).toEqual(["srv:a", "srv:c"]);
await userEvent.click(row("d"), { modifiers: [MOD_KEY, "Shift"] });
expect(useSidebarSelectionStore.getState().active).toBe(false);
expect(navigatedKeys).toEqual(["srv:a", "srv:c", "srv:d"]);
// Once select mode is entered (e.g. via Shift+click), Cmd/Ctrl+click and plain clicks toggle.
await userEvent.click(row("c"), { modifiers: ["Shift"] });
expect(selectedIds()).toEqual(["c"]);
await userEvent.click(row("b"), { modifiers: [MOD_KEY] });
@@ -248,38 +238,31 @@ describe("sidebar workspace row presses", () => {
// Plain clicks keep toggling while select mode is on.
await userEvent.click(row("a"));
expect(selectedIds()).toEqual(["a", "b", "d"]);
expect(navigatedKeys).toEqual(["srv:a", "srv:c", "srv:d"]);
expect(navigatedKeys).toEqual(["srv:a"]);
});
it("selects on the first Shift+click or select-mode click after an earlier gesture ended as a long press", async () => {
mountHost(["a", "b", "c"].map(makeEntry));
it("selects on the first modifier or select-mode click after an earlier gesture ended as a long press", async () => {
mountHost(["a", "b"].map(makeEntry));
// A scroll, swipe, drag, or long-press menu leaves the flag set without firing onPress.
// Ctrl+click on Windows/Linux gets no press-in on web, so nothing clears it first.
markGestureCanceled("a");
await userEvent.click(row("a"), { modifiers: ["Shift"] });
await userEvent.click(row("a"), { modifiers: [MOD_KEY] });
expect(selectedIds()).toEqual(["a"]);
markGestureCanceled("b");
await userEvent.click(row("b"), { modifiers: [MOD_KEY] });
await userEvent.click(row("b"));
expect(selectedIds()).toEqual(["a", "b"]);
markGestureCanceled("c");
await userEvent.click(row("c"));
expect(selectedIds()).toEqual(["a", "b", "c"]);
});
it("opens a row on a slow click and still selects it on the next Shift+click and Cmd/Ctrl+click", async () => {
it("opens a row on a slow click and still selects it on the next Cmd/Ctrl+click", async () => {
mountHost(["a", "b"].map(makeEntry));
await act(() => slowClick(row("a")));
expect(navigatedKeys).toEqual(["srv:a"]);
await userEvent.click(row("a"), { modifiers: ["Shift"] });
await userEvent.click(row("a"), { modifiers: [MOD_KEY] });
expect(selectedIds()).toEqual(["a"]);
await userEvent.click(row("b"), { modifiers: [MOD_KEY] });
expect(selectedIds()).toEqual(["a", "b"]);
});
it("enters select mode on the Shift+clicked row alone, then extends and shrinks the range", async () => {
@@ -12,12 +12,10 @@ interface WorkspaceSelectionPressInput {
}
/**
* Routes a sidebar workspace row press between navigation and select mode:
* - Outside select mode, Shift+click (without Cmd/Ctrl) enters select mode on the clicked row
* alone; plain clicks and Cmd/Ctrl+clicks navigate normally so shortcut rollover and Cmd-held
* badge peeks never trigger bulk selection.
* - Inside select mode, Shift+click selects a Finder-style range from the anchor, and plain clicks
* or Cmd/Ctrl+clicks toggle one row without navigating.
* Routes a sidebar workspace row press between navigation and select mode, Finder-style:
* Shift+click selects a range, Cmd+click (Ctrl+click off macOS) toggles one row, and either one
* enters select mode on the clicked row alone. In select mode every press selects, so touch and
* mouse users can keep tapping without a modifier.
*
* Selecting presses never consult the row's long-press flag. They never arm the long-press
* gesture, a native long press already cancels the press, and react-native-web gives Ctrl+click
@@ -32,7 +30,7 @@ export function useWorkspaceSelectionPress({
(event: GestureResponderEvent) => {
const modifiers = readPressModifiers(event);
const store = useSidebarSelectionStore.getState();
if (!store.active && (!modifiers.shift || modifiers.mod)) {
if (!store.active && !modifiers.shift && !modifiers.mod) {
onNavigate();
return;
}
@@ -45,14 +43,12 @@ export function useWorkspaceSelectionPress({
const handlePressIn = useCallback(
(event: GestureResponderEvent) => {
const modifiers = readPressModifiers(event);
const isSelectionMode = useSidebarSelectionStore.getState().active;
const entersSelection = !isSelectionMode && modifiers.shift && !modifiers.mod;
if (entersSelection || (isSelectionMode && (modifiers.shift || modifiers.mod))) {
if (modifiers.shift || modifiers.mod) {
// Keep the browser from extending a text selection or starting a drag on modifier clicks.
event.preventDefault?.();
return;
}
if (!isSelectionMode) {
if (!useSidebarSelectionStore.getState().active) {
onPressIn?.(event);
}
},
@@ -1548,6 +1548,64 @@ describe("DaemonConfigStore reload", () => {
});
});
describe("plugin entries edited in config.json while the daemon runs", () => {
const other = { source: "directory", path: "/other", enabled: true } as const;
const local = { source: "directory", path: "/local", enabled: true } as const;
function disableOther(store: DaemonConfigStore) {
return store.patch((current) => ({
plugins: { ...current.plugins, other: { ...current.plugins.other!, enabled: false } },
}));
}
function removeOther(store: DaemonConfigStore) {
return store.patch((current) => {
const { other: _removed, ...rest } = current.plugins;
return { plugins: rest };
});
}
test("keeps a hand-added entry on disk when another plugin changes", async () => {
const { paseoHome, store, persisted } = createReloadableStore({
initialPersisted: { version: 1, plugins: { other } },
});
writeConfig(paseoHome, { ...persisted, plugins: { other, local } });
await disableOther(store);
expect(loadPersistedConfig(paseoHome).plugins).toEqual({
other: { ...other, enabled: false },
local,
});
expect(store.get().plugins).toEqual({ other: { ...other, enabled: false } });
});
test("does not write back an entry removed by hand when another plugin changes", async () => {
const { paseoHome, store, persisted } = createReloadableStore({
initialPersisted: { version: 1, plugins: { other, local } },
});
writeConfig(paseoHome, { ...persisted, plugins: { other } });
await disableOther(store);
expect(loadPersistedConfig(paseoHome).plugins).toEqual({
other: { ...other, enabled: false },
});
});
test("removing a plugin deletes only that entry from disk", async () => {
const { paseoHome, store, persisted } = createReloadableStore({
initialPersisted: { version: 1, plugins: { other } },
});
writeConfig(paseoHome, { ...persisted, plugins: { other, local } });
await removeOther(store);
expect(loadPersistedConfig(paseoHome).plugins).toEqual({ local });
expect(store.get().plugins).toEqual({});
});
});
test("serializes overlapping patches before committing their combined state", async () => {
const { paseoHome, store } = createReloadableStore();
const first = store.patch({ appendSystemPrompt: "first" });
@@ -1012,6 +1012,7 @@ export class DaemonConfigStore {
patch,
removeProviders,
persistRelayEnabled: this.relayEnabledMutable,
pluginsBeforePatch: this.current.plugins ?? {},
});
const nextPersisted = merge(persisted);
const knownNext = merge(this.lastKnownPersisted);
@@ -1025,8 +1026,9 @@ function mergeMutablePatchIntoPersistedConfig(params: {
patch: Omit<SupportedMutableConfigPatch, "removeProviders">;
removeProviders: readonly string[];
persistRelayEnabled: boolean;
pluginsBeforePatch: PluginSources;
}): PersistedConfig {
const { persisted, patch, removeProviders, persistRelayEnabled } = params;
const { persisted, patch, removeProviders, persistRelayEnabled, pluginsBeforePatch } = params;
const daemon = mergeMutableDaemonPatch(persisted.daemon, patch, persistRelayEnabled);
const agents = mergeMutableAgentPatch(persisted.agents, patch, removeProviders);
const withSpeech = patch.features
@@ -1035,12 +1037,40 @@ function mergeMutablePatchIntoPersistedConfig(params: {
return {
...withSpeech,
...(patch.pluginsEnabled !== undefined ? { pluginsEnabled: patch.pluginsEnabled } : {}),
...(patch.plugins !== undefined ? { plugins: patch.plugins } : {}),
...(patch.plugins !== undefined
? {
plugins: applyChangedPluginEntries({
persisted: persisted.plugins,
before: pluginsBeforePatch,
after: patch.plugins,
}),
}
: {}),
...(daemon ? { daemon } : { daemon: undefined }),
...(agents ? { agents } : { agents: undefined }),
} as PersistedConfig;
}
type PluginSources = NonNullable<MutableDaemonConfig["plugins"]>;
// The daemon never reloads plugin entries from config.json, so its copy can be stale. Writing only
// the entries this patch changed keeps entries other writers put on disk until the next restart.
function applyChangedPluginEntries(params: {
persisted: PersistedConfig["plugins"];
before: PluginSources;
after: PluginSources;
}): PluginSources {
const { persisted, before, after } = params;
const next: PluginSources = { ...persisted };
for (const [pluginId, source] of Object.entries(after)) {
if (!isEqualValue(before[pluginId], source)) next[pluginId] = source;
}
for (const pluginId of Object.keys(before)) {
if (!(pluginId in after)) delete next[pluginId];
}
return next;
}
function mergeMutableAgentPatch(
persistedAgents: PersistedConfig["agents"],
patch: Omit<SupportedMutableConfigPatch, "removeProviders">,