Multiplayer agent harness for work.
Synchronize runtime-default prompts across multiview panes (#1130)
Joshua France61f6f9fc5d75
diff --git a/plugins/web-ui/src/composer.ts b/plugins/web-ui/src/composer.tsindex 78f33f4e5..5318dd2f1 100644--- a/plugins/web-ui/src/composer.ts+++ b/plugins/web-ui/src/composer.ts@@ -1,3 +1,4 @@+import { getRuntimeConfig, loadRuntimeConfig, saveRuntimeConfig, subscribeRuntimeConfig } from "./runtime-config-store";import type { Agent, AgentMessage } from "@earendil-works/pi-agent-core";import type { Attachment } from "@earendil-works/pi-web-ui";import { FolderDropError, folderToZipFile, isFolderReadError, splitDropItems, type DropEntryLike } from "./folder-drop";@@ -22,7 +23,6 @@ import {api,ApiError,approvalBlocksComposer,- fetchRuntimeConfig,latestTranscriptSeq,MAX_ATTACHMENT_BYTES,MAX_FILES_PER_MESSAGE,@@ -31,7 +31,6 @@ import {PENDING_APPROVAL_REASON,queueTurn,tooManyFilesNote,- updateRuntimeConfig,uploadAttachments,userSendMessage,verifySteerDelivered,@@ -40,13 +39,11 @@ import {type CoreAttachment,type PendingApproval,type QueuedRun,- type RuntimeConfig,} from "./core-bridge";import { errMessage, swallow } from "../../chassis/src/errors";import { fieldSelect, icon } from "./ui";import {EFFORT_LEVELS,- applyRuntimeOptions,defaultEffortForModel,defaultModelValue,effortLabel,@@ -60,7 +57,7 @@ import {type ModelOption,type ModelOptionValue,} from "./model-options";-import { modelSupportsFastMode, setFastModeModelIds } from "./pi-models";+import { modelSupportsFastMode } from "./pi-models";import type { ComposerSurface, ConvCtx } from "./conv-types";import { bumpSessionActivity, dropPendingSession, renderList } from "./sessions";import { appState } from "./shell";@@ -91,8 +88,6 @@ function groupMenuOptions(options: ComposerMenuOption[]): Array<{ label: string;const LEGACY_MODEL_STORAGE_KEY = "web-ui:model";const THREAD_PICKS_STORAGE_KEY = "web-ui:model-picks";const THREAD_PICKS_CAP = 50;-const FAST_MODE_STORAGE_KEY = "web-ui:fast-mode";-const EFFORT_STORAGE_KEY = "web-ui:effort";const MENU_SEARCH_THRESHOLD = 8;function loadThreadPicks(): Map<string, ModelOptionValue> {@@ -111,12 +106,6 @@ function loadThreadPicks(): Map<string, ModelOptionValue> {}let threadModelPicks = loadThreadPicks();-let seededRuntime: { scopeId: string | null; config: RuntimeConfig } | null = null;--export function seedRuntimeConfig(scopeId: string | null, config: RuntimeConfig): void {- seededRuntime = { scopeId: runtimeScopeKey(scopeId), config };-}-function runtimeScopeKey(scopeId: string | null): string | null {if (scopeId) return scopeId;const user = appState.me?.user;@@ -148,27 +137,6 @@ function modelOptionFor(value: ModelOptionValue, scopeKey?: string | null): Modereturn getModelOptions(scopeKey).find((option) => option.value === value);}-function loadStoredFastMode(): boolean | undefined {- try {- const stored = localStorage.getItem(FAST_MODE_STORAGE_KEY);- if (stored === "0") return false;- if (stored === "1") return true;- } catch {- void 0;- }- return undefined;-}--function loadStoredEffort(fallback: EffortLevel): EffortLevel {- try {- const stored = localStorage.getItem(EFFORT_STORAGE_KEY);- if (stored && EFFORT_LEVELS.some((option) => option.value === stored)) return stored as EffortLevel;- } catch {- void 0;- }- return fallback;-}-function persistPreference(key: string, value: string): void {try {localStorage.setItem(key, value);@@ -223,8 +191,11 @@ export function resyncModelSelection(): void {}export function createComposerSurface(ctx: ConvCtx): ComposerSurface {- let activeRuntimeConfig: RuntimeConfig | null = null;let runtimeRequest = 0;+ let runtimeIdentity = "";+ let unsubscribeRuntime: (() => void) | undefined;+ let effortOverride: EffortLevel | undefined;+ let fastModeOverride: boolean | undefined;function isUnsentNewChat(): boolean {return (@@ -253,8 +224,22 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {openMenu: null as ComposerMenu | null,menuQuery: "",slashDismissed: false,- effortLevel: loadStoredEffort(defaultEffortForModel(modelOptionFor(defaultModelValue())?.model)),- fastMode: loadStoredFastMode(),+ get effortLevel(): EffortLevel {+ return (+ effortOverride ??+ (getRuntimeConfig(scopeKey())?.effective.effortLevel as EffortLevel | undefined) ??+ defaultEffortForModel(currentModelOption()?.model)+ );+ },+ set effortLevel(value: EffortLevel) {+ effortOverride = value;+ },+ get fastMode(): boolean | undefined {+ return fastModeOverride ?? getRuntimeConfig(scopeKey())?.effective.fastMode === true;+ },+ set fastMode(value: boolean | undefined) {+ fastModeOverride = value;+ },pasteView: null as { id: string; text: string; initial: string; dirty: boolean } | null,};@@ -282,9 +267,8 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {let skillsLoading = false;let slashActiveIndex = 0;let fastModeCharging = false;- let orgFastModeDefault = false;function effectiveFastMode(): boolean {- return composerState.fastMode ?? orgFastModeDefault;+ return composerState.fastMode === true;}let fastModeChargeTimer: ReturnType<typeof setTimeout> | null = null;@@ -309,45 +293,32 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {return modelOptionFor(picked ?? defaultModelValue(scopeKey()), scopeKey());}- async function refreshRuntimeSelection(scopeId: string | null, agent?: Agent): Promise<void> {+ async function refreshRuntimeSelection(scopeId: string | null, agent?: Agent, refresh = false): Promise<void> {const request = ++runtimeRequest;- const scopeKey = runtimeScopeKey(scopeId);- const seeded = scopeKey !== null && seededRuntime?.scopeId === scopeKey ? seededRuntime.config : null;- if (seeded) {- seededRuntime = null;- applySelectedRuntime(seeded, agent);- return;+ const key = runtimeScopeKey(scopeId);+ const identity = `${key}:${ctx.chat.state.threadRef}`;+ if (identity !== runtimeIdentity) {+ effortOverride = undefined;+ fastModeOverride = undefined;+ runtimeIdentity = identity;}- activeRuntimeConfig = null;+ unsubscribeRuntime?.();+ unsubscribeRuntime =+ key === null+ ? undefined+ : subscribeRuntimeConfig(key, () => {+ if (key !== scopeKey()) return;+ syncRuntimeSelection(ctx.chat.state.agent ?? undefined);+ });composerState.error = "";- ctx.chat.drawActiveChat(agent);- const config = await fetchRuntimeConfig(scopeId);+ syncRuntimeSelection(agent);+ const config = key === null ? null : await loadRuntimeConfig(key, refresh);if (request !== runtimeRequest) return;- if (!config) {- applyRuntimeOptions(scopeKey, [], {}, { harnessId: "", modelId: "" });- composerState.error = "Could not load runtime settings.";- ctx.chat.drawActiveChat(agent);- return;- }- applySelectedRuntime(config, agent);+ if (!config) composerState.error = "Could not load runtime settings.";+ syncRuntimeSelection(agent);}- function applySelectedRuntime(config: RuntimeConfig, agent?: Agent): void {- activeRuntimeConfig = config;- composerState.error = "";- setFastModeModelIds(scopeKey(), config.fastModeModelIds);- orgFastModeDefault = config.interactiveFastMode === true;- applyRuntimeOptions(- scopeKey(),- config.approvedHarnesses,- config.modelsByHarness,- config.effective,- config.modelCatalog,- );- composerState.effortLevel =- (config.effective.effortLevel as EffortLevel | undefined) ?? defaultEffortForModel(currentModelOption()?.model);- composerState.fastMode =- config.effective.fastMode === true && modelSupportsFastMode(scopeKey(), config.effective.modelId);+ function syncRuntimeSelection(agent?: Agent): void {if (agent && (!ctx.chat.state.threadRef || !threadModelPicks.has(ctx.chat.state.threadRef)))if (currentModelOption()) agent.state.model = currentModelOption()!.model;ctx.chat.drawActiveChat(agent);@@ -366,20 +337,20 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {agent: Agent,): Promise<void> {const request = ++runtimeRequest;- const scopeId = ctx.chat.state.scopeId;+ const scopeId = scopeKey();+ if (!scopeId) return;+ composerState.error = "";try {- const config = await updateRuntimeConfig(scopeId, change);- if (request !== runtimeRequest || scopeId !== ctx.chat.state.scopeId) return;- seededRuntime = null;- applySelectedRuntime(config, agent);+ await saveRuntimeConfig(scopeId, change);} catch (e) {- if (request !== runtimeRequest || scopeId !== ctx.chat.state.scopeId) return;+ if (request !== runtimeRequest || scopeId !== scopeKey()) return;composerState.error = errMessage(e, "Could not update the scope default.");+ ctx.chat.drawActiveChat(agent);}- ctx.chat.drawActiveChat(agent);}function composerForm(agent: Agent, header: TemplateResult | typeof nothing = nothing): TemplateResult {+ const activeRuntimeConfig = getRuntimeConfig(scopeKey());const selectedModel = currentModelOption();if (!selectedModel) {const selected =@@ -410,7 +381,7 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {},})}</label>- <button type="button" @click=${() => void refreshRuntimeSelection(ctx.chat.state.scopeId, agent)}>+ <button type="button" @click=${() => void refreshRuntimeSelection(ctx.chat.state.scopeId, agent, true)}>Refresh models</button></div>`;@@ -446,7 +417,7 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {composerNotice = composerState.error? html`<div class="composer-error">${composerState.error}- <button type="button" @click=${() => void refreshRuntimeSelection(ctx.chat.state.scopeId, agent)}>+ <button type="button" @click=${() => void refreshRuntimeSelection(ctx.chat.state.scopeId, agent, true)}>Retry</button></div>`@@ -522,9 +493,9 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {? html`<div class="runtime-upgrade"><span>The org now recommends- ${modelOptionFor(`${activeRuntimeConfig.orgDefault.harnessId}:${activeRuntimeConfig.orgDefault.modelId}`)?.harnessLabel ?? activeRuntimeConfig.orgDefault.harnessId}+ ${modelOptionFor(`${activeRuntimeConfig.orgDefault.harnessId}:${activeRuntimeConfig.orgDefault.modelId}`, scopeKey())?.harnessLabel ?? activeRuntimeConfig.orgDefault.harnessId}·- ${modelOptionFor(`${activeRuntimeConfig.orgDefault.harnessId}:${activeRuntimeConfig.orgDefault.modelId}`)?.buttonLabel ?? activeRuntimeConfig.orgDefault.modelId}.</span+ ${modelOptionFor(`${activeRuntimeConfig.orgDefault.harnessId}:${activeRuntimeConfig.orgDefault.modelId}`, scopeKey())?.buttonLabel ?? activeRuntimeConfig.orgDefault.modelId}.</span><buttontype="button"@@ -1245,7 +1216,7 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {return (Boolean(composerState.draft.trim() || composerState.attachments.length) &&!composerState.processingFiles &&- activeRuntimeConfig !== null &&+ getRuntimeConfig(scopeKey()) !== null &&ctx.chat.state.resolvingApprovals.size === 0 &&!ctx.chat.hasUnresolvedApproval());@@ -1509,7 +1480,7 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {async function sendPrompt(agent: Agent): Promise<void> {if (!currentModelOption()) return;if (composerState.processingFiles) return;- if (!activeRuntimeConfig) return;+ if (!getRuntimeConfig(scopeKey())) return;if (composerState.pasteView) closePasteView(agent);if (ctx.chat.state.resolvingApprovals.size > 0) return;if (ctx.chat.hasUnresolvedApproval()) return;@@ -1809,7 +1780,6 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {agent.state.model = option.model;if (composerState.effortLevel === previousDefaultEffort) {composerState.effortLevel = defaultEffortForModel(option.model);- persistPreference(EFFORT_STORAGE_KEY, composerState.effortLevel);}if (composerState.openMenu !== "settings") composerState.openMenu = null;ctx.chat.drawActiveChat(agent);@@ -1824,7 +1794,6 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {function selectEffort(level: EffortLevel, agent: Agent): void {composerState.effortLevel = level;- persistPreference(EFFORT_STORAGE_KEY, level);if (composerState.openMenu !== "settings") composerState.openMenu = null;ctx.chat.drawActiveChat(agent);}@@ -1833,7 +1802,6 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {if (ctx.chat.hasUnresolvedApproval() || ctx.chat.state.resolvingApprovals.size > 0) return;if (!modelSupportsFastMode(scopeKey(), currentModelOption()?.model.id)) return;composerState.fastMode = !effectiveFastMode();- persistPreference(FAST_MODE_STORAGE_KEY, composerState.fastMode ? "1" : "0");if (fastModeChargeTimer) {clearTimeout(fastModeChargeTimer);fastModeChargeTimer = null;@@ -1900,6 +1868,8 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {}function dispose(): void {+ unsubscribeRuntime?.();+ ++runtimeRequest;autosizeObserver?.disconnect();autosizeObserver = null;autosizedTa = null;diff --git a/plugins/web-ui/src/context-model.ts b/plugins/web-ui/src/context-model.tsindex d8bce4735..9a0314555 100644--- a/plugins/web-ui/src/context-model.ts+++ b/plugins/web-ui/src/context-model.ts@@ -1,5 +1,6 @@import { html, nothing, type TemplateResult } from "lit";-import { fetchRuntimeConfig, updateRuntimeConfig, type RuntimeConfig } from "./core-bridge";+import type { RuntimeConfig } from "./core-bridge";+import { getRuntimeConfig, loadRuntimeConfig, saveRuntimeConfig, subscribeRuntimeConfig } from "./runtime-config-store";import {EFFORT_LEVELS,effortLabel,@@ -19,22 +20,26 @@ export const contextModelState = {saving: false,pending: null as string | null,pendingEffort: null as string | null,- config: null as RuntimeConfig | null,+ get config(): RuntimeConfig | null {+ return getRuntimeConfig(contextModelState.scope);+ },notice: "",noticeKind: "" as "" | "saved" | "error",};let loadSeq = 0;+let unsubscribeRuntime: (() => void) | undefined;let redraw: () => void = () => {};export function resetContextModel(): void {loadSeq += 1;+ unsubscribeRuntime?.();+ unsubscribeRuntime = undefined;contextModelState.scope = null;contextModelState.loading = false;contextModelState.saving = false;contextModelState.pending = null;contextModelState.pendingEffort = null;- contextModelState.config = null;contextModelState.notice = "";contextModelState.noticeKind = "";}@@ -46,9 +51,12 @@ export async function loadContextModel(scopeId: string, onChange: () => void): Pconst seq = ++loadSeq;contextModelState.scope = scopeId;contextModelState.loading = true;- const config = await fetchRuntimeConfig(scopeId);+ unsubscribeRuntime = subscribeRuntimeConfig(scopeId, () => {+ contextModelState.loading = false;+ redraw();+ });+ const config = await loadRuntimeConfig(scopeId);if (seq !== loadSeq) return;- contextModelState.config = config;contextModelState.loading = false;if (!config) {contextModelState.notice = "Couldn't load this project's model.";@@ -101,7 +109,7 @@ async function choose(scope: string, value: string, effort?: string): Promise<votry {const sep = value.indexOf(":");const harnessId = value.slice(0, sep);- const config = await updateRuntimeConfig(+ const config = await saveRuntimeConfig(scope,value === INHERIT? { inherit: true }@@ -112,7 +120,6 @@ async function choose(scope: string, value: string, effort?: string): Promise<vo},);if (seq !== loadSeq) return;- contextModelState.config = config;const effortNote = config.scopeOverride?.effortLevel? ` · ${effortLabel(config.scopeOverride.effortLevel as EffortLevel)} effort`: "";diff --git a/plugins/web-ui/src/conv-types.ts b/plugins/web-ui/src/conv-types.tsindex f5b4a87c6..8709c30c6 100644--- a/plugins/web-ui/src/conv-types.ts+++ b/plugins/web-ui/src/conv-types.ts@@ -128,7 +128,7 @@ export interface ComposerSurface {resizeComposer(): void;currentModelOption(): ModelOption | undefined;carryModelPick(fromThreadRef: string | null, toThreadRef: string): void;- refreshRuntimeSelection(scopeId: string | null, agent?: Agent): Promise<void>;+ refreshRuntimeSelection(scopeId: string | null, agent?: Agent, refresh?: boolean): Promise<void>;onDragEnter(e: DragEvent): void;onDragOver(e: DragEvent): void;onDragLeave(e: DragEvent): void;diff --git a/plugins/web-ui/src/core-bridge.ts b/plugins/web-ui/src/core-bridge.tsindex 758df7258..8e73349d0 100644--- a/plugins/web-ui/src/core-bridge.ts+++ b/plugins/web-ui/src/core-bridge.ts@@ -8,7 +8,7 @@ import { errMessage, swallow } from "../../chassis/src/errors.ts";import { userFacingFailureText } from "../../chassis/src/failure-copy.ts";import { groupDmText } from "./group-dm-label.ts";import { base64ToBytes } from "./paste-text.ts";-import { defaultEffortForModel, harnessSupportsEffort } from "./model-options.ts";+import { defaultEffortForModel, harnessSupportsEffort } from "./runtime-capabilities.ts";import { SIGNIN_REQUIRED_EVENT, signinRedirect } from "./signin-return.ts";const BASE_URL = ((import.meta as unknown as { env?: { BASE_URL?: string } }).env?.BASE_URL ?? "/").replace(/\/$/, "");diff --git a/plugins/web-ui/src/model-options.ts b/plugins/web-ui/src/model-options.tsindex 042dc097c..9cc5af159 100644--- a/plugins/web-ui/src/model-options.ts+++ b/plugins/web-ui/src/model-options.ts@@ -1,3 +1,5 @@+import { getRuntimeConfig } from "./runtime-config-store.ts";+import type { RuntimeConfig } from "./core-bridge.ts";import type { Api, Model } from "@earendil-works/pi-ai";import { getBaseModel, type ModelMetadata } from "./pi-models.ts";@@ -93,12 +95,20 @@ interface RuntimeOptions {}const FALLBACK: RuntimeOptions = { options: [], defaultValue: null };-const byScope = new Map<string, RuntimeOptions>();-let lastApplied: RuntimeOptions = FALLBACK;+const derived = new WeakMap<RuntimeConfig, RuntimeOptions>();function runtimeFor(scopeKey?: string | null): RuntimeOptions {- if (scopeKey === undefined) return lastApplied;- return (scopeKey !== null ? byScope.get(scopeKey) : undefined) ?? FALLBACK;+ const config = getRuntimeConfig(scopeKey);+ if (!config) return FALLBACK;+ let options = derived.get(config);+ if (!options) {+ options = {+ options: runtimeModelOptions(config.approvedHarnesses, config.modelsByHarness, config.modelCatalog),+ defaultValue: `${config.effective.harnessId}:${config.effective.modelId}`,+ };+ derived.set(config, options);+ }+ return options;}export function getModelOptions(scopeKey?: string | null): ModelOption[] {@@ -126,19 +136,6 @@ export function runtimeModelOptions();}-export function applyRuntimeOptions(- scopeKey: string | null,- approvedHarnesses: readonly string[],- modelsByHarness: Readonly<Record<string, readonly string[]>>,- effective: { harnessId: string; modelId: string },- catalog: Readonly<Record<string, ModelMetadata>> = {},-): void {- const options = runtimeModelOptions(approvedHarnesses, modelsByHarness, catalog);- const applied = { options, defaultValue: `${effective.harnessId}:${effective.modelId}` };- lastApplied = applied;- if (scopeKey !== null) byScope.set(scopeKey, applied);-}-export function defaultModelValue(scopeKey?: string | null): ModelOptionValue {return runtimeFor(scopeKey).defaultValue ?? "";}@@ -148,35 +145,12 @@ export function transcriptModel(scopeKey?: string | null): Model<Api> | undefinereturn options.find((o) => o.value === defaultValue)?.model;}-export type EffortLevel = "low" | "medium" | "high" | "xhigh" | "max" | "ultracode" | "auto";--export const EFFORT_LEVELS: Array<{ value: EffortLevel; label: string }> = [- { value: "auto", label: "Auto" },- { value: "low", label: "Low" },- { value: "medium", label: "Medium" },- { value: "high", label: "High" },- { value: "xhigh", label: "XHigh" },- { value: "max", label: "Max" },- { value: "ultracode", label: "Ultracode" },-];--export function effortLabel(level: EffortLevel): string {- return EFFORT_LEVELS.find((option) => option.value === level)?.label ?? level;-}--export function harnessSupportsEffort(harnessId: string): boolean {- return harnessId === "pi" || harnessId === "codex" || harnessId === "claude";-}--export function harnessSupportsFastMode(harnessId: string): boolean {- return harnessId === "pi" || harnessId === "claude";-}--export function harnessSupportsSteer(harnessId: string): boolean {- return harnessId === "pi" || harnessId === "claude" || harnessId === "codex" || harnessId === "opencode";-}--export function defaultEffortForModel(model: Model<Api> | undefined): EffortLevel {- const provider = String(model?.provider ?? model?.api ?? "").toLowerCase();- return provider.includes("anthropic") ? "low" : "auto";-}+export {+ EFFORT_LEVELS,+ defaultEffortForModel,+ effortLabel,+ harnessSupportsEffort,+ harnessSupportsFastMode,+ harnessSupportsSteer,+ type EffortLevel,+} from "./runtime-capabilities.ts";diff --git a/plugins/web-ui/src/pi-models.ts b/plugins/web-ui/src/pi-models.tsindex 6f48dab22..8d383ae99 100644--- a/plugins/web-ui/src/pi-models.ts+++ b/plugins/web-ui/src/pi-models.ts@@ -1,3 +1,4 @@+import { getRuntimeConfig } from "./runtime-config-store.ts";import type { Api, Model } from "@earendil-works/pi-ai";export type ModelMetadata = Pick<@@ -14,15 +15,6 @@ export function getBaseModel(id: string, metadata?: ModelMetadata): Model<Api> {return { ...structuredClone(metadata), baseUrl: "" };}-const fastModeByScope = new Map<string, Set<string>>();-let lastFastModeIds = new Set<string>();--export function setFastModeModelIds(scopeKey: string | null, ids: readonly string[] | undefined): void {- lastFastModeIds = new Set(ids ?? []);- if (scopeKey !== null) fastModeByScope.set(scopeKey, lastFastModeIds);-}-export function modelSupportsFastMode(scopeKey: string | null, modelId: string | undefined): boolean {- const ids = (scopeKey !== null ? fastModeByScope.get(scopeKey) : undefined) ?? lastFastModeIds;- return !!modelId && ids.has(modelId);+ return !!modelId && (getRuntimeConfig(scopeKey)?.fastModeModelIds?.includes(modelId) ?? false);}diff --git a/plugins/web-ui/src/runtime-capabilities.ts b/plugins/web-ui/src/runtime-capabilities.tsnew file mode 100644index 000000000..d6fd026dd--- /dev/null+++ b/plugins/web-ui/src/runtime-capabilities.ts@@ -0,0 +1,34 @@+import type { Api, Model } from "@earendil-works/pi-ai";++export type EffortLevel = "low" | "medium" | "high" | "xhigh" | "max" | "ultracode" | "auto";++export const EFFORT_LEVELS: Array<{ value: EffortLevel; label: string }> = [+ { value: "auto", label: "Auto" },+ { value: "low", label: "Low" },+ { value: "medium", label: "Medium" },+ { value: "high", label: "High" },+ { value: "xhigh", label: "XHigh" },+ { value: "max", label: "Max" },+ { value: "ultracode", label: "Ultracode" },+];++export function effortLabel(level: EffortLevel): string {+ return EFFORT_LEVELS.find((option) => option.value === level)?.label ?? level;+}++export function harnessSupportsEffort(harnessId: string): boolean {+ return harnessId === "pi" || harnessId === "codex" || harnessId === "claude";+}++export function harnessSupportsFastMode(harnessId: string): boolean {+ return harnessId === "pi" || harnessId === "claude";+}++export function harnessSupportsSteer(harnessId: string): boolean {+ return harnessId === "pi" || harnessId === "claude" || harnessId === "codex" || harnessId === "opencode";+}++export function defaultEffortForModel(model: Model<Api> | undefined): EffortLevel {+ const provider = String(model?.provider ?? model?.api ?? "").toLowerCase();+ return provider.includes("anthropic") ? "low" : "auto";+}diff --git a/plugins/web-ui/src/runtime-config-store.ts b/plugins/web-ui/src/runtime-config-store.tsnew file mode 100644index 000000000..52c234590--- /dev/null+++ b/plugins/web-ui/src/runtime-config-store.ts@@ -0,0 +1,105 @@+import { fetchRuntimeConfig, updateRuntimeConfig, type RuntimeConfig } from "./core-bridge.ts";+import { swallow } from "../../chassis/src/errors.ts";++type Change = Parameters<typeof updateRuntimeConfig>[1];+type Entry = {+ config: RuntimeConfig | null;+ generation: number;+ fetchedAt: number;+ load: Promise<RuntimeConfig | null> | null;+ write: Promise<void> | null;+ listeners: Set<() => void>;+};+// Reuse boot/multiview reads briefly; returning to a view still revalidates server policy.+const FRESH_MS = 30_000;+const entries = new Map<string, Entry>();+let bootScope: string | null = null;++function entryFor(scopeId: string): Entry {+ let entry = entries.get(scopeId);+ if (!entry) {+ entry = { config: null, generation: 0, fetchedAt: 0, load: null, write: null, listeners: new Set() };+ entries.set(scopeId, entry);+ }+ return entry;+}++export function getRuntimeConfig(scopeId: string | null = bootScope): RuntimeConfig | null {+ return scopeId === null ? null : (entries.get(scopeId)?.config ?? null);+}++function publish(scopeId: string, entry: Entry, config: RuntimeConfig): void {+ if (config.scopeId !== scopeId) throw new Error("Runtime configuration scope mismatch");+ entry.config = config;+ entry.fetchedAt = Date.now();+ for (const listener of entry.listeners) {+ try {+ listener();+ } catch (e) {+ swallow("web-ui: runtime config listener", e);+ }+ }+}++/** Boot hydration is shared by every pane, not consumed by the first mount. */+export function seedRuntimeConfig(scopeId: string, config: RuntimeConfig): void {+ const entry = entryFor(scopeId);+ bootScope = scopeId;+ if (entry.config || entry.write) return;+ ++entry.generation;+ publish(scopeId, entry, config);+}++export function subscribeRuntimeConfig(scopeId: string, listener: () => void): () => void {+ const entry = entryFor(scopeId);+ entry.listeners.add(listener);+ return () => {+ entry.listeners.delete(listener);+ };+}++export async function loadRuntimeConfig(scopeId: string, refresh = false): Promise<RuntimeConfig | null> {+ const entry = entryFor(scopeId);+ // Reads started during a save must not race ahead of that save on the server.+ while (entry.write) await entry.write;+ if (!refresh && entry.config && Date.now() - entry.fetchedAt < FRESH_MS) return entry.config;+ if (entry.load) return entry.load;+ const generation = entry.generation;+ const load = fetchRuntimeConfig(scopeId).then(async (config) => {+ if (generation !== entry.generation) {+ while (entry.write) await entry.write;+ return entry.config;+ }+ if (config) publish(scopeId, entry, config);+ return config;+ });+ entry.load = load;+ try {+ return await load;+ } finally {+ if (entry.load === load) entry.load = null;+ }+}++export async function saveRuntimeConfig(scopeId: string, change: Change): Promise<RuntimeConfig> {+ const entry = entryFor(scopeId);+ // Serialize writes per scope so both the server and every view see the same order.+ // Invalidate old reads at enqueue time, including when the save ultimately fails.+ ++entry.generation;+ entry.load = null;+ const save = (entry.write ?? Promise.resolve()).then(async () => {+ const config = await updateRuntimeConfig(scopeId, change);+ publish(scopeId, entry, config);+ return config;+ });+ const settled = save.then(+ () => {},+ () => {},+ );+ entry.write = settled;+ try {+ return await save;+ } finally {+ if (entry.write === settled) entry.write = null;+ }+}diff --git a/plugins/web-ui/src/shell.ts b/plugins/web-ui/src/shell.tsindex f1afa6fdd..8295cd2f6 100644--- a/plugins/web-ui/src/shell.ts+++ b/plugins/web-ui/src/shell.ts@@ -34,12 +34,12 @@ import {webFetch,withBase,} from "./core-bridge";-import { applyRuntimeOptions } from "./model-options";+import { seedRuntimeConfig } from "./runtime-config-store";import { errMessage, swallow } from "../../chassis/src/errors";import { brandMark, brandName, icon } from "./ui";import { PHONE_MAX_WIDTH, trackVisualViewport } from "./viewport";import { markConnectorConnected } from "./chat";-import { clearSkillsCache, resyncModelSelection, seedRuntimeConfig } from "./composer";+import { clearSkillsCache, resyncModelSelection } from "./composer";import { ensureDeliveryStream, mainConversation, onExitCanvas } from "./conversations";import { clearAllDrafts, saveDraft, storedDraft } from "./drafts";import { deepLinkPath, isPlainLeftClick, parseDeepLink, UI_BASE } from "./deep-link";@@ -998,13 +998,6 @@ export async function boot(): Promise<void> {const runtimeConfig =prefetchedConfig?.scopeId === personalScope ? prefetchedConfig : await fetchRuntimeConfig(personalScope);if (runtimeConfig) {- applyRuntimeOptions(- personalScope,- runtimeConfig.approvedHarnesses,- runtimeConfig.modelsByHarness,- runtimeConfig.effective,- runtimeConfig.modelCatalog,- );seedRuntimeConfig(personalScope, runtimeConfig);}resyncModelSelection();diff --git a/plugins/web-ui/test/approval-handoff.test.ts b/plugins/web-ui/test/approval-handoff.test.tsindex accc965d4..315715ef9 100644--- a/plugins/web-ui/test/approval-handoff.test.ts+++ b/plugins/web-ui/test/approval-handoff.test.ts@@ -110,7 +110,7 @@ test("approval handoff unlocks queue and steer without losing pending decisions"const { createConversation } = await vite.ssrLoadModule("/src/conversations.ts");const { entriesToMessages, attachPendingApprovals } = await vite.ssrLoadModule("/src/core-bridge.ts");const { transcriptModel } = await vite.ssrLoadModule("/src/model-options.ts");- const { seedRuntimeConfig } = await vite.ssrLoadModule("/src/composer.ts");+ const { seedRuntimeConfig } = await vite.ssrLoadModule("/src/runtime-config-store.ts");seedRuntimeConfig(row.scopeId, await (await fetch("/api/runtime-config")).json());appState.me = { user: "owner", org: "test" };appState.currentView = "chats";@@ -273,7 +273,7 @@ test("approval handoff unlocks queue and steer without losing pending decisions"selectedModelId = "deleted-overlay";modelDeleted = true;mount();- await chat.composer.refreshRuntimeSelection(row.scopeId, chat.state.agent!);+ await chat.composer.refreshRuntimeSelection(row.scopeId, chat.state.agent!, true);await until(() => !!host.querySelector('select[aria-label="Replacement model"]'));assert.equal(chat.composer.currentModelOption(), undefined);assert.match(host.textContent ?? "", /deleted-overlay/);diff --git a/plugins/web-ui/test/composer-source.test.ts b/plugins/web-ui/test/composer-source.test.tsindex 625cf42b6..276e5409e 100644--- a/plugins/web-ui/test/composer-source.test.ts+++ b/plugins/web-ui/test/composer-source.test.ts@@ -82,6 +82,6 @@ test("a steer whose run already ended is recovered, never silently dropped", ()test("scope runtime defaults include effort and fast mode", () => {assert.match(composer, /effortLevel: composerState\.effortLevel/);assert.match(composer, /fastMode: fastOn/);- assert.match(composer, /config\.effective\.effortLevel/);- assert.match(composer, /config\.effective\.fastMode === true/);+ assert.match(composer, /getRuntimeConfig\(scopeKey\(\)\)\?\.effective\.effortLevel/);+ assert.match(composer, /getRuntimeConfig\(scopeKey\(\)\)\?\.effective\.fastMode === true/);});diff --git a/plugins/web-ui/test/context-model-source.test.ts b/plugins/web-ui/test/context-model-source.test.tsindex 9bb0ebd92..908321930 100644--- a/plugins/web-ui/test/context-model-source.test.ts+++ b/plugins/web-ui/test/context-model-source.test.ts@@ -7,7 +7,7 @@ const contexts = readFileSync(new URL("../src/contexts.ts", import.meta.url), "uconst css = readFileSync(new URL("../src/shell.css", import.meta.url), "utf8");test("the scope's model panel writes through the same endpoint the composer's default does", () => {- assert.match(panel, /updateRuntimeConfig\(\s*scope,/);+ assert.match(panel, /saveRuntimeConfig\(\s*scope,/);assert.match(panel, /\{ inherit: true \}/);assert.match(panel, /harnessId,\n\s+modelId: value\.slice\(sep \+ 1\)/);assert.doesNotMatch(panel, /applyRuntimeOptions/);diff --git a/plugins/web-ui/test/model-options.test.ts b/plugins/web-ui/test/model-options.test.tsindex 8a433471a..58fbe06be 100644--- a/plugins/web-ui/test/model-options.test.ts+++ b/plugins/web-ui/test/model-options.test.ts@@ -1,8 +1,8 @@+import { applyRuntimeOptions } from "./runtime-fixture.ts";import { test } from "node:test";import assert from "node:assert/strict";import { readFileSync } from "node:fs";import {- applyRuntimeOptions,defaultModelValue,getModelOptions,getHarnessOptions,@@ -15,8 +15,8 @@ import { metadata } from "./model-metadata.ts";const catalog = { future: metadata("future", "Future API Model"), custom: metadata("custom", "Custom", "gateway") };-test("server metadata controls picker labels, geometry, price, order and effective selection", () => {- applyRuntimeOptions(+test("server metadata controls picker labels, geometry, price, order and effective selection", async () => {+ await applyRuntimeOptions("scope:a",["pi", "mock"],{ pi: ["custom", "future", "custom"], mock: ["future"] },@@ -35,7 +35,7 @@ test("server metadata controls picker labels, geometry, price, order and effectiassert.equal(model.model.baseUrl, "");});-test("empty, unknown, missing-metadata and unapproved lists stay empty", () => {+test("empty, unknown, missing-metadata and unapproved lists stay empty", async () => {for (const options of [runtimeModelOptions([], { pi: ["future"] }, catalog),runtimeModelOptions(["pi"], { pi: [] }, catalog),@@ -43,22 +43,28 @@ test("empty, unknown, missing-metadata and unapproved lists stay empty", () => {runtimeModelOptions(["pi"], { pi: ["unknown"] }, catalog),])assert.deepEqual(options, []);- applyRuntimeOptions("scope:empty", ["pi"], { pi: [] }, { harnessId: "pi", modelId: "future" }, catalog);+ await applyRuntimeOptions("scope:empty", ["pi"], { pi: [] }, { harnessId: "pi", modelId: "future" }, catalog);assert.deepEqual(getModelOptions("scope:empty"), []);assert.equal(defaultModelValue("scope:empty"), "pi:future");assert.equal(transcriptModel("scope:empty"), undefined);assert.deepEqual(getHarnessOptions("scope:empty"), []);});-test("scopes retain independent choices and an unloaded scope does not borrow another policy", () => {- applyRuntimeOptions("scope:a", ["pi"], { pi: ["future"] }, { harnessId: "pi", modelId: "future" }, catalog);- applyRuntimeOptions("scope:b", ["mock"], { mock: ["custom"] }, { harnessId: "mock", modelId: "custom" }, catalog);+test("scopes retain independent choices and an unloaded scope does not borrow another policy", async () => {+ await applyRuntimeOptions("scope:a", ["pi"], { pi: ["future"] }, { harnessId: "pi", modelId: "future" }, catalog);+ await applyRuntimeOptions(+ "scope:b",+ ["mock"],+ { mock: ["custom"] },+ { harnessId: "mock", modelId: "custom" },+ catalog,+ );assert.equal(defaultModelValue("scope:a"), "pi:future");assert.equal(defaultModelValue("scope:b"), "mock:custom");assert.deepEqual(getModelOptions("scope:new"), []);});-test("OpenRouter and custom provider metadata retains provider grouping", () => {+test("OpenRouter and custom provider metadata retains provider grouping", async () => {const models = { "vendor/new": metadata("vendor/new", "Vendor: New", "openrouter"), custom: catalog.custom };const options = runtimeModelOptions(["pi"], { pi: Object.keys(models) }, models);assert.deepEqual(@@ -67,29 +73,41 @@ test("OpenRouter and custom provider metadata retains provider grouping", () =>);});-test("picker has no model IDs, clone templates or runtime SDK model registry imports", () => {+test("picker has no model IDs, clone templates or runtime SDK model registry imports", async () => {const source = ["pi-models.ts", "model-options.ts"].map((file) => readFileSync(new URL(`../src/${file}`, import.meta.url), "utf8")).join("\n");assert.doesNotMatch(source, /MODEL_CATALOG|CLONE_TEMPLATES|gpt-5|claude-opus|openrouter\/auto|import \{ getModel/);});-test("harness controls retain their supported surfaces", () => {+test("harness controls retain their supported surfaces", async () => {assert.equal(harnessSupportsEffort("pi"), true);assert.equal(harnessSupportsEffort("opencode"), false);assert.equal(harnessSupportsFastMode("claude"), true);assert.equal(harnessSupportsFastMode("codex"), false);});-test("deleted selection retains identity and transcript rendering does not borrow a replacement", () => {- applyRuntimeOptions("scope:deleted", ["pi"], { pi: ["custom"] }, { harnessId: "pi", modelId: "future" }, catalog);+test("deleted selection retains identity and transcript rendering does not borrow a replacement", async () => {+ await applyRuntimeOptions(+ "scope:deleted",+ ["pi"],+ { pi: ["custom"] },+ { harnessId: "pi", modelId: "future" },+ catalog,+ );assert.equal(defaultModelValue("scope:deleted"), "pi:future");assert.equal(transcriptModel("scope:deleted"), undefined);assert.deepEqual(getModelOptions("scope:deleted").map((model) => model.value),["pi:custom"],);- applyRuntimeOptions("scope:deleted", ["pi"], { pi: ["custom"] }, { harnessId: "pi", modelId: "custom" }, catalog);+ await applyRuntimeOptions(+ "scope:deleted",+ ["pi"],+ { pi: ["custom"] },+ { harnessId: "pi", modelId: "custom" },+ catalog,+ );assert.equal(defaultModelValue("scope:deleted"), "pi:custom");assert.equal(transcriptModel("scope:deleted")?.id, "custom");});diff --git a/plugins/web-ui/test/new-chat-placement.test.ts b/plugins/web-ui/test/new-chat-placement.test.tsindex bfad7ac52..5f8a1bf98 100644--- a/plugins/web-ui/test/new-chat-placement.test.ts+++ b/plugins/web-ui/test/new-chat-placement.test.ts@@ -41,6 +41,7 @@ async function withCanvas(run: (canvas: Canvas) => void | Promise<void>, stacked},fetch: async () =>Response.json({+ scopeId: "personal:tester",approvedHarnesses: ["pi"],modelsByHarness: { pi: [] },modelCatalog: {},diff --git a/plugins/web-ui/test/openrouter-turn.test.ts b/plugins/web-ui/test/openrouter-turn.test.tsindex ef888fef9..9515e1558 100644--- a/plugins/web-ui/test/openrouter-turn.test.ts+++ b/plugins/web-ui/test/openrouter-turn.test.ts@@ -1,10 +1,11 @@+import { applyRuntimeOptions } from "./runtime-fixture.ts";import { metadata } from "./model-metadata.ts";import assert from "node:assert/strict";import { afterEach, test } from "node:test";import type { Agent } from "@earendil-works/pi-agent-core";import type { Context } from "@earendil-works/pi-ai";import { makeOpenerStreamFn } from "../src/core-bridge.ts";-import { applyRuntimeOptions, getModelOptions } from "../src/model-options.ts";+import { getModelOptions } from "../src/model-options.ts";const realFetch = globalThis.fetch;@@ -13,7 +14,7 @@ afterEach(() => {});test("a web turn submits the fetched OpenRouter model selected by runtime config", async () => {- applyRuntimeOptions(+ await applyRuntimeOptions(null,["pi"],{ pi: ["anthropic/claude-sonnet-4.5"] },diff --git a/plugins/web-ui/test/pi-models.test.ts b/plugins/web-ui/test/pi-models.test.tsindex 905ba996a..66189bccc 100644--- a/plugins/web-ui/test/pi-models.test.ts+++ b/plugins/web-ui/test/pi-models.test.ts@@ -1,6 +1,8 @@+import { loadRuntimeConfig } from "../src/runtime-config-store.ts";+import { runtimeConfig } from "./runtime-fixture.ts";import { test } from "node:test";import assert from "node:assert/strict";-import { getBaseModel, modelSupportsFastMode, setFastModeModelIds } from "../src/pi-models.ts";+import { getBaseModel, modelSupportsFastMode } from "../src/pi-models.ts";import { metadata } from "./model-metadata.ts";test("models require server metadata even when the browser SDK knows their id", () => {@@ -18,9 +20,16 @@ test("browser model preserves safe server geometry and does not share mutable meassert.equal(model.baseUrl, "");});-test("fast mode support follows server updates", () => {- setFastModeModelIds("scope", ["future"]);- assert.equal(modelSupportsFastMode("scope", "future"), true);- setFastModeModelIds("scope", []);- assert.equal(modelSupportsFastMode("scope", "future"), false);+test("fast mode support follows shared server updates without borrowing another scope", async () => {+ const original = globalThis.fetch;+ try {+ for (const ids of [["future"], []]) {+ globalThis.fetch = async () => Response.json(runtimeConfig("scope", { fastModeModelIds: ids }));+ await loadRuntimeConfig("scope", true);+ assert.equal(modelSupportsFastMode("scope", "future"), ids.length > 0);+ assert.equal(modelSupportsFastMode("unknown", "future"), false);+ }+ } finally {+ globalThis.fetch = original;+ }});diff --git a/plugins/web-ui/test/post-reply-recovery.test.ts b/plugins/web-ui/test/post-reply-recovery.test.tsindex 9c91d5cef..4db634173 100644--- a/plugins/web-ui/test/post-reply-recovery.test.ts+++ b/plugins/web-ui/test/post-reply-recovery.test.ts@@ -132,7 +132,7 @@ test("post replies remain visible in new and continuing conversations", async (tawait vite.ssrLoadModule("/src/conversations.ts");const { entriesToMessages } = await vite.ssrLoadModule("/src/core-bridge.ts");const { transcriptModel } = await vite.ssrLoadModule("/src/model-options.ts");- const { seedRuntimeConfig } = await vite.ssrLoadModule("/src/composer.ts");+ const { seedRuntimeConfig } = await vite.ssrLoadModule("/src/runtime-config-store.ts");seedRuntimeConfig(row.scopeId, await (await fetch("/api/runtime-config")).json());appState.me = { user: "owner", org: "test" };appState.currentView = "chats";diff --git a/plugins/web-ui/test/runtime-config-handoff.test.ts b/plugins/web-ui/test/runtime-config-handoff.test.tsindex c209061c9..0ac08af02 100644--- a/plugins/web-ui/test/runtime-config-handoff.test.ts+++ b/plugins/web-ui/test/runtime-config-handoff.test.ts@@ -14,28 +14,10 @@ test("boot hands its runtime config to the composer instead of dropping it", ()assert.ok(fetchAt > 0 && seedAt > fetchAt, "boot must seed the config it just fetched");});-test("the first mount in the seeded scope renders from it — no blanking, no second fetch", () => {- const fn = composer.slice(- composer.indexOf("async function refreshRuntimeSelection"),- composer.indexOf("function applySelectedRuntime"),- );- assert.ok(fn, "refreshRuntimeSelection not found");- const seedRead = fn.indexOf("seededRuntime?.scopeId === scopeKey");- const blank = fn.indexOf("activeRuntimeConfig = null");- const fetchCall = fn.indexOf("await fetchRuntimeConfig(scopeId)");- assert.ok(seedRead > 0, "the seeded config must be consulted");- assert.ok(seedRead < blank, "consult the seed BEFORE blanking the composer");- assert.ok(seedRead < fetchCall, "consult the seed BEFORE refetching");- assert.match(fn, /if \(seeded\) \{\s*seededRuntime = null;\s*applySelectedRuntime\(seeded, agent\);\s*return;\s*\}/);- assert.match(fn, /seededRuntime\?\.scopeId === scopeKey \? seededRuntime\.config : null/);- assert.match(fn, /const scopeKey = runtimeScopeKey\(scopeId\);/);- assert.match(fn, /seededRuntime = null;/, "later refreshes must read current server metadata");- const change = composer.slice(composer.indexOf("async function changeScopeRuntime"));- assert.match(- change.slice(0, change.indexOf("\n }")),- /seededRuntime = null;/,- "scope updates also retire any remaining boot seed",- );+test("composers read the shared boot snapshot without consuming or copying it", () => {+ assert.match(composer, /const activeRuntimeConfig = getRuntimeConfig\(scopeKey\(\)\);/);+ assert.match(composer, /await loadRuntimeConfig\(key, refresh\)/);+ assert.doesNotMatch(composer, /seededRuntime|applyRuntimeOptions|let activeRuntimeConfig/);});test("a still-loading composer is not painted as a failure", () => {@@ -69,6 +51,4 @@ test("a personal mount passing null still matches the seeded personal scope", ()assert.ok(resolver, "runtimeScopeKey not found");assert.match(resolver, /if \(scopeId\) return scopeId;/, "a named scope is used as-is");assert.match(resolver, /return user \? `personal:\$\{user\}` : null;/, "null resolves to the personal scope");- assert.match(composer, /seededRuntime = \{ scopeId: runtimeScopeKey\(scopeId\), config \};/);- assert.match(composer, /scopeKey !== null && seededRuntime\?\.scopeId === scopeKey/);});diff --git a/plugins/web-ui/test/runtime-config-sync.test.ts b/plugins/web-ui/test/runtime-config-sync.test.tsnew file mode 100644index 000000000..6e0bf4841--- /dev/null+++ b/plugins/web-ui/test/runtime-config-sync.test.ts@@ -0,0 +1,178 @@+import assert from "node:assert/strict";+import { afterEach, test } from "node:test";+import {+ getRuntimeConfig,+ loadRuntimeConfig,+ saveRuntimeConfig,+ seedRuntimeConfig,+ subscribeRuntimeConfig,+} from "../src/runtime-config-store.ts";+import { runtimeConfig } from "./runtime-fixture.ts";+import { defaultModelValue } from "../src/model-options.ts";++const realFetch = globalThis.fetch;+afterEach(() => {+ globalThis.fetch = realFetch;+});+function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((done) => {+ resolve = done;+ });+ return { promise, resolve };+}++for (const [i, change] of [{ inherit: true }, { keep: true }, { harnessId: "pi", modelId: "new-model" }].entries()) {+ test(`successful runtime saves update one shared snapshot for every view: ${JSON.stringify(change)}`, async () => {+ const scope = `scope:save-${i}`;+ const config = runtimeConfig(scope, { upgradeAvailable: false });+ let first = 0;+ let second = 0;+ let other = 0;+ const stop = subscribeRuntimeConfig(scope, () => {+ first++;+ assert.equal(getRuntimeConfig(scope)?.upgradeAvailable, false);+ });+ const stop2 = subscribeRuntimeConfig(scope, () => {+ second++;+ });+ const stopOther = subscribeRuntimeConfig("scope:other", () => {+ other++;+ });+ globalThis.fetch = async () => Response.json(config);+ try {+ assert.deepEqual(await saveRuntimeConfig(scope, change), config);+ assert.deepEqual([first, second, other], [1, 1, 0]);+ assert.deepEqual(getRuntimeConfig(scope), config);+ stop2();+ await saveRuntimeConfig(scope, change);+ assert.deepEqual([first, second, other], [2, 1, 0]);+ } finally {+ stop();+ stop2();+ stopOther();+ }+ });+}++test("boot hydration and derived options are shared, not consumed by a pane", async () => {+ const config = runtimeConfig("scope:boot");+ seedRuntimeConfig(config.scopeId, config);+ globalThis.fetch = async () => {+ throw new Error("unexpected fetch");+ };+ assert.equal(await loadRuntimeConfig(config.scopeId), config);+ assert.equal(await loadRuntimeConfig(config.scopeId), config);+ assert.equal(defaultModelValue(config.scopeId), "pi:model");+ assert.equal(getRuntimeConfig("scope:unknown"), null);+});++test("concurrent loads share one request, and explicit refresh publishes to all views", async () => {+ const scope = "scope:load";+ const response = deferred<Response>();+ let requests = 0;+ let changes = 0;+ const stop = subscribeRuntimeConfig(scope, () => {+ changes++;+ });+ globalThis.fetch = async () => {+ requests++;+ return response.promise;+ };+ try {+ const first = loadRuntimeConfig(scope);+ const second = loadRuntimeConfig(scope);+ response.resolve(Response.json(runtimeConfig(scope)));+ assert.equal(await first, await second);+ assert.equal(requests, 1);+ assert.equal(changes, 1);+ globalThis.fetch = async () => Response.json(runtimeConfig(scope, { upgradeAvailable: false }));+ await loadRuntimeConfig(scope, true);+ assert.equal(changes, 2);+ assert.equal(getRuntimeConfig(scope)?.upgradeAvailable, false);+ } finally {+ stop();+ }+});++test("an old GET cannot restore a prompt after a successful save", async () => {+ const scope = "scope:stale";+ const response = deferred<Response>();+ globalThis.fetch = async (_input, init) =>+ init?.method === "PUT" ? Response.json(runtimeConfig(scope, { upgradeAvailable: false })) : response.promise;+ const pending = loadRuntimeConfig(scope);+ await saveRuntimeConfig(scope, { keep: true });+ response.resolve(Response.json(runtimeConfig(scope)));+ assert.equal((await pending)?.upgradeAvailable, false);+ assert.equal(getRuntimeConfig(scope)?.upgradeAvailable, false);+});++test("writes serialize per scope; reads during a save wait, and another scope is independent", async () => {+ const scope = "scope:ordering";+ const first = deferred<Response>();+ const calls: string[] = [];+ globalThis.fetch = async (_input, init) => {+ assert.equal(init?.method, "PUT", "no GET may run ahead of pending saves");+ const { scopeId, modelId } = JSON.parse(String(init.body));+ calls.push(modelId);+ if (modelId === "first") return first.promise;+ return Response.json(runtimeConfig(scopeId, { effective: { harnessId: "pi", modelId } }));+ };+ const save1 = saveRuntimeConfig(scope, { modelId: "first" });+ const save2 = saveRuntimeConfig(scope, { modelId: "second" });+ const read = loadRuntimeConfig(scope);+ await saveRuntimeConfig("scope:independent", { modelId: "other" });+ assert.deepEqual(calls, ["first", "other"]);+ first.resolve(Response.json(runtimeConfig(scope, { effective: { harnessId: "pi", modelId: "first" } })));+ await Promise.all([save1, save2]);+ assert.equal((await read)?.effective.modelId, "second");+ assert.equal(getRuntimeConfig(scope)?.effective.modelId, "second");+});++test("failed saves keep the last good snapshot and do not poison the write queue", async () => {+ const scope = "scope:failure";+ const config = runtimeConfig(scope);+ seedRuntimeConfig(scope, config);+ let calls = 0;+ let changes = 0;+ const stop = subscribeRuntimeConfig(scope, () => {+ changes++;+ });+ globalThis.fetch = async () =>+ ++calls === 1+ ? Response.json({ error: "save failed" }, { status: 500 })+ : Response.json(runtimeConfig(scope, { upgradeAvailable: false }));+ try {+ await assert.rejects(saveRuntimeConfig(scope, { inherit: true }), /save failed/);+ assert.equal(getRuntimeConfig(scope), config);+ assert.equal(changes, 0);+ await saveRuntimeConfig(scope, { keep: true });+ assert.equal(changes, 1);+ } finally {+ stop();+ }+});++test("bad scope responses never update or notify the requested scope", async () => {+ globalThis.fetch = async () => Response.json(runtimeConfig("scope:wrong"));+ await assert.rejects(loadRuntimeConfig("scope:expected"), /scope mismatch/);+ assert.equal(getRuntimeConfig("scope:expected"), null);+});++test("cached configuration is revalidated when returning to a view after the freshness window", async () => {+ const scope = "scope:revalidate";+ seedRuntimeConfig(scope, runtimeConfig(scope));+ const now = Date.now;+ Date.now = () => now() + 60_000;+ let calls = 0;+ globalThis.fetch = async () => {+ calls++;+ return Response.json(runtimeConfig(scope, { upgradeAvailable: false }));+ };+ try {+ assert.equal((await loadRuntimeConfig(scope))?.upgradeAvailable, false);+ assert.equal(calls, 1);+ } finally {+ Date.now = now;+ }+});diff --git a/plugins/web-ui/test/runtime-config-views.test.ts b/plugins/web-ui/test/runtime-config-views.test.tsnew file mode 100644index 000000000..59b73212f--- /dev/null+++ b/plugins/web-ui/test/runtime-config-views.test.ts@@ -0,0 +1,150 @@+import assert from "node:assert/strict";+import { test } from "node:test";+import { JSDOM } from "jsdom";+import { createServer } from "vite";+import type { Agent } from "@earendil-works/pi-agent-core";+import type { ConvCtx, ComposerSurface } from "../src/conv-types.ts";+import { runtimeConfig } from "./runtime-fixture.ts";++test("runtime defaults are shared while pane choices and editor drafts remain local", async () => {+ const dom = new JSDOM('<!doctype html><div id="app"></div><main id="main"></main>', {+ url: "http://localhost/",+ });+ Object.defineProperty(dom.window, "matchMedia", {+ value: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }),+ });+ const globals = {+ window: dom.window,+ document: dom.window.document,+ location: dom.window.location,+ history: dom.window.history,+ localStorage: dom.window.localStorage,+ navigator: dom.window.navigator,+ HTMLElement: dom.window.HTMLElement,+ customElements: dom.window.customElements,+ Node: dom.window.Node,+ Event: dom.window.Event,+ InputEvent: dom.window.InputEvent,+ KeyboardEvent: dom.window.KeyboardEvent,+ requestAnimationFrame: (callback: FrameRequestCallback) => setTimeout(() => callback(Date.now()), 0),+ cancelAnimationFrame: clearTimeout,+ getComputedStyle: dom.window.getComputedStyle.bind(dom.window),+ EventSource: undefined,+ };+ for (const [key, value] of Object.entries(globals))+ Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });++ const originalFetch = globalThis.fetch;+ const configs = new Map(+ ["personal:owner", "channel:other"].map((scope) => [scope, runtimeConfig(scope, { fastModeModelIds: ["model"] })]),+ );+ let fail = false;+ let gets = 0;+ globalThis.fetch = async (input, init) => {+ const scope = new URL(String(input), "http://localhost").searchParams.get("scopeId") ?? "personal:owner";+ if (init?.method === "PUT") {+ const change = JSON.parse(String(init.body));+ if (fail) return Response.json({ error: "save failed" }, { status: 500 });+ const config = {+ ...configs.get(change.scopeId)!,+ upgradeAvailable: false,+ effective: { harnessId: "pi", modelId: "model", effortLevel: "high", fastMode: true },+ };+ configs.set(change.scopeId, config);+ return Response.json(config);+ }+ gets++;+ return Response.json(configs.get(scope));+ };+ const vite = await createServer({ server: { middlewareMode: true, hmr: false }, appType: "custom" });+ const panes: Array<{ composer: ComposerSurface; ctx: ConvCtx; agent: Agent; host: HTMLElement }> = [];+ let resetPanel: (() => void) | undefined;+ try {+ await vite.ssrLoadModule("/src/shell.ts");+ const { appState } = await vite.ssrLoadModule("/src/shell-state.ts");+ const { createComposerSurface } = await vite.ssrLoadModule("/src/composer.ts");+ const { saveRuntimeConfig, loadRuntimeConfig, seedRuntimeConfig } =+ await vite.ssrLoadModule("/src/runtime-config-store.ts");+ const { loadContextModel, resetContextModel, contextModelState } =+ await vite.ssrLoadModule("/src/context-model.ts");+ const { render } = await vite.ssrLoadModule("lit");+ resetPanel = resetContextModel;+ appState.me = { user: "owner", org: "test" };+ seedRuntimeConfig("personal:owner", configs.get("personal:owner"));+ for (const [i, scopeId] of [null, "personal:owner", "channel:other"].entries()) {+ const host = document.createElement("section");+ document.body.append(host);+ const agent = { state: { messages: [] } } as unknown as Agent;+ const ctx = {+ pane: true,+ container: () => host,+ visible: () => true,+ density: () => "full",+ chat: {+ state: { scopeId, threadRef: `thread-${i}`, sessionId: `session-${i}`, agent, resolvingApprovals: new Set() },+ activePendingApprovals: () => [],+ hasUnresolvedApproval: () => false,+ drawActiveChat: () => render(composer.composerForm(agent), host),+ },+ } as unknown as ConvCtx;+ const composer = createComposerSurface(ctx) as ComposerSurface;+ await composer.refreshRuntimeSelection(scopeId, agent);+ panes.push({ composer, ctx, agent, host });+ }+ await loadContextModel("personal:owner", () => {});+ assert.equal(gets, 1, "boot data hydrates both personal panes and settings without another fetch");+ panes[1]!.composer.state.effortLevel = "auto"; // Explicitly equal to the old default is still a choice.+ panes[1]!.composer.state.fastMode = false;+ panes[1]!.composer.state.draft = "keep my message";+ contextModelState.pending = "pi:pending-model";+ contextModelState.pendingEffort = "low";+ await saveRuntimeConfig("personal:owner", { inherit: true });+ assert.deepEqual(+ panes.map(({ host }) => host.querySelectorAll(".runtime-upgrade").length),+ [0, 0, 1],+ );+ assert.equal(panes[0]!.composer.state.effortLevel, "high", "untouched pane follows new defaults");+ assert.equal(panes[0]!.composer.state.fastMode, true);+ assert.equal(panes[1]!.composer.state.effortLevel, "auto", "explicit effort survives even if equal to old default");+ assert.equal(panes[1]!.composer.state.fastMode, false, "explicit off survives a new fast default");+ assert.equal(panes[1]!.composer.state.draft, "keep my message");+ assert.equal(contextModelState.config.upgradeAvailable, false);+ assert.equal(contextModelState.pending, "pi:pending-model");+ assert.equal(contextModelState.pendingEffort, "low");+ fail = true;+ await assert.rejects(saveRuntimeConfig("personal:owner", { keep: true }), /save failed/);+ assert.equal(panes[1]!.composer.state.effortLevel, "auto");+ fail = false;+ const stale = contextModelState.config;+ resetContextModel();+ await loadContextModel("channel:other", () => {});+ await saveRuntimeConfig("personal:owner", { keep: true });+ assert.equal(contextModelState.config.scopeId, "channel:other");+ assert.notEqual(contextModelState.config, stale);+ const sibling = panes[1]!;+ sibling.ctx.chat.state.scopeId = "channel:other";+ sibling.ctx.chat.state.threadRef = "thread-new";+ await sibling.composer.refreshRuntimeSelection("channel:other", sibling.agent);+ assert.equal(sibling.composer.state.effortLevel, "auto");+ assert.equal(sibling.composer.state.fastMode, false);+ await saveRuntimeConfig("personal:owner", { keep: true });+ assert.ok(sibling.host.querySelector(".runtime-upgrade"), "navigated pane ignores former scope");+ sibling.composer.dispose();+ const html = sibling.host.innerHTML;+ await saveRuntimeConfig("channel:other", { keep: true });+ assert.equal(sibling.host.innerHTML, html, "disposed pane does not redraw");+ // A server refresh uses the same publishing path as a local save.+ configs.set(+ "personal:owner",+ runtimeConfig("personal:owner", { effective: { harnessId: "pi", modelId: "model", effortLevel: "low" } }),+ );+ await loadRuntimeConfig("personal:owner", true);+ assert.equal(panes[0]!.composer.state.effortLevel, "low");+ } finally {+ resetPanel?.();+ for (const { composer } of panes) composer.dispose();+ await vite.close();+ globalThis.fetch = originalFetch;+ dom.window.close();+ }+});diff --git a/plugins/web-ui/test/runtime-fixture.ts b/plugins/web-ui/test/runtime-fixture.tsnew file mode 100644index 000000000..074a2d920--- /dev/null+++ b/plugins/web-ui/test/runtime-fixture.ts@@ -0,0 +1,40 @@+import { loadRuntimeConfig, seedRuntimeConfig } from "../src/runtime-config-store.ts";+import type { RuntimeConfig } from "../src/core-bridge.ts";+import { metadata } from "./model-metadata.ts";++export function runtimeConfig(scopeId: string, changes: Partial<RuntimeConfig> = {}): RuntimeConfig {+ return {+ scopeId,+ approvedHarnesses: ["pi"],+ modelsByHarness: { pi: ["model"] },+ modelCatalog: { model: metadata("model") },+ orgDefault: { harnessId: "pi", modelId: "model", revision: 2 },+ scopeOverride: { harnessId: "pi", modelId: "model", orgRevision: 1 },+ effective: { harnessId: "pi", modelId: "model" },+ upgradeAvailable: true,+ ...changes,+ };+}++export async function applyRuntimeOptions(+ scopeId: string | null,+ approvedHarnesses: RuntimeConfig["approvedHarnesses"],+ modelsByHarness: RuntimeConfig["modelsByHarness"],+ effective: RuntimeConfig["effective"],+ modelCatalog: RuntimeConfig["modelCatalog"],+): Promise<void> {+ const config = runtimeConfig(scopeId ?? "personal:test", {+ approvedHarnesses,+ modelsByHarness,+ effective,+ modelCatalog,+ });+ const original = globalThis.fetch;+ globalThis.fetch = async () => Response.json(config);+ try {+ seedRuntimeConfig(config.scopeId, config);+ await loadRuntimeConfig(config.scopeId, true);+ } finally {+ globalThis.fetch = original;+ }+}