Official

settings

Built-in settings UI (JavaScript UI plugin).

The app opens the listing; nothing installs until an agent in your Plugins workspace has read the files and you enable the plugin. In a terminal: dvg install divergence/settings@0.2.6

Permissions in 0.2.6

  • Manage plugins plugins.manageOfficial onlyReloads and enables plugins. Only official plugins can have it.List, enable, disable and reload plugins, install updates, and quit to finish an update
  • Change app settings settings.writeHighChanges the app settings.Change the settings and the theme
  • Manage agents agents.manageHighEnables, disables and signs in agents, and changes their settings.Turn agents on and off, sign in to them and update them
  • Control chats chats.controlHighCreates chats, sends prompts and cancels runs.Add project folders, and open the first chat and the changes saved in the first-run guide
  • Read chats chats.readMediumReads your transcripts and chat lists.Hold an agent's update until its chats stop running
  • Read app settings settings.readLowReads the app settings.Show the settings, and the tools and rules of every plugin
  • Show panels ui.slotsAlways grantedShows views in the listed parts of the window.Draw settings, its list of sections in the sidebar's place, and the first-run guideSlots: centerleft

Files

upkeep.ts21.8 KB
// The update button at the foot of the sidebar: every enabled agent whose own
// program is behind, a new Divergence, new default plugins and the plugin
// updates the marketplace offers, in one place. An update never cuts off
// work: one asked for while its agent runs or has messages waiting to be
// sent (or, for the app, the plugins and a plugin that provides agents,
// while any chat does) waits and starts by itself once nothing is in its
// way. One installer runs at a time. A version can be skipped, and the
// whole list put off until tomorrow.
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Result from "effect/Result";
import * as Schedule from "effect/Schedule";
import * as Scope from "effect/Scope";
import * as Option from "effect/Option";
import * as Semaphore from "effect/Semaphore";
import * as Stream from "effect/Stream";
import * as z from "zod";
import { Host, Kernel, Notify, Services, Storage } from "divergence/effect";
import type { HostError } from "divergence/effect";
import type { AgentInfo, Chat, ChatStatus, InputSnapshot, UpdateStatus, ViewHandle } from "divergence";
import type { Terminal } from "../terminal/contract.ts";
import type { Market, PluginUpdate } from "../market/contract.ts";
import type { Chat as ChatService } from "../chat/contract.ts";

/// What the button of an item does: install it here, run its command in a
/// terminal, nothing (the user updates it the way they installed it), or
/// install the app and restart.
export type Action = "update" | "terminal" | "manual" | "restart";

export interface UpdateItem {
  /// The agent's id, `app`, `plugins`, or `plugin:<folder>` for a marketplace plugin.
  readonly id: string;
  readonly name: string;
  /// The agent's mark (inline SVG).
  readonly icon: string | null;
  readonly from: string | null;
  readonly to: string;
  readonly action: Action;
  readonly command: string | null;
  /// An agent's id; the app and the plugins wait for every chat.
  readonly agentId: string | null;
  /// Whether it waits for chats at all: a plugin that provides no agent
  /// cuts off no chat when it is replaced.
  readonly waits: boolean;
}

export type Job =
  | { readonly state: "waiting" }
  | { readonly state: "updating" }
  | { readonly state: "terminal" }
  | { readonly state: "failed"; readonly message: string };

export const Dismissals = z.object({
  /// The version skipped, by item id.
  skipped: z.record(z.string(), z.string()),
  /// The button stays away until then (epoch milliseconds).
  snoozedUntil: z.number().nullable(),
});
export type Dismissals = z.infer<typeof Dismissals>;

export const SNOOZE = 24 * 60 * 60 * 1000;
const STORAGE_KEY = "upkeep";
/// The host's busy mark while the downloaded app waits for every chat to
/// be idle before it answers `restart`.
export const RESTARTING = "restarting when every chat is idle";
const BUSY: ReadonlySet<ChatStatus> = new Set(["running", "waiting_approval", "waiting_question"]);

type Agent = AgentInfo & { readonly enabled: boolean };

/// Everything that is behind: agents first in the host's order, then the
/// default plugins, the marketplace's plugin updates, and the app last, so
/// Update all restarts only after everything else.
export function updateItems(
  agents: readonly Agent[],
  updates: UpdateStatus | null,
  plugins: readonly PluginUpdate[] = [],
  agentPlugins: ReadonlySet<string> = new Set(),
): UpdateItem[] {
  const out: UpdateItem[] = [];
  for (const agent of agents) {
    const m = agent.maintenance;
    if (!agent.enabled || !m?.latestVersion || m.latestVersion === m.installedVersion) continue;
    out.push({
      id: agent.id,
      name: agent.name,
      icon: agent.icon ?? null,
      from: m.installedVersion ?? null,
      to: m.latestVersion,
      action: m.canUpdate ? "update" : m.command ? "terminal" : "manual",
      command: m.command ?? null,
      agentId: agent.id,
      waits: true,
    });
  }
  if (updates?.enabled && updates.pluginUpdate)
    out.push({
      id: "plugins",
      name: "Default plugins",
      icon: null,
      from: updates.plugins ? `build ${updates.plugins.build}` : null,
      to: `build ${updates.pluginUpdate.build}`,
      action: "update",
      command: null,
      agentId: null,
      waits: true,
    });
  for (const plugin of plugins)
    out.push({
      id: `plugin:${plugin.folder}`,
      name: plugin.folder,
      icon: null,
      from: plugin.installed,
      to: plugin.latest,
      action: "update",
      command: null,
      agentId: null,
      waits: agentPlugins.has(plugin.folder),
    });
  if (updates?.enabled && updates.appUpdate)
    out.push({
      id: "app",
      name: "Divergence",
      icon: null,
      from: updates.appVersion,
      to: updates.appUpdate.version,
      action: "restart",
      command: null,
      agentId: null,
      waits: true,
    });
  return out;
}

/// The items the button lists: none while it is put off, and none skipped at
/// their version. An item with work under way always shows.
export function shownItems(
  items: readonly UpdateItem[],
  dismissals: Dismissals,
  jobs: Readonly<Record<string, Job>>,
  now: number,
): UpdateItem[] {
  const snoozed = dismissals.snoozedUntil !== null && now < dismissals.snoozedUntil;
  return items.filter((item) => jobs[item.id] || (!snoozed && dismissals.skipped[item.id] !== item.to));
}

/// Whether a chat's input holds a message that is still to be sent: one
/// held without a pause (the host pauses what a restart interrupted), or
/// one being handed to the agent.
export function holdsMessage(snapshot: InputSnapshot): boolean {
  return snapshot.inputs.some((input) => (input.state === "held" && !input.pauseReason) || input.state === "dispatching");
}

/// The chats an update would cut off: those running or with messages
/// waiting to be sent (`queued`), the agent's own for an agent, every one
/// for the app, the plugins and a plugin that provides agents, none for a
/// plugin that provides no agent.
export function blockers(item: UpdateItem, chats: Iterable<Chat>, queued: ReadonlySet<string>): Chat[] {
  if (!item.waits) return [];
  const out: Chat[] = [];
  for (const chat of chats) {
    if (!BUSY.has(chat.status) && !queued.has(chat.id)) continue;
    if (item.agentId === null || chat.agentId === item.agentId) out.push(chat);
  }
  return out;
}

export function blocked(item: UpdateItem, chats: Iterable<Chat>, queued: ReadonlySet<string> = new Set()): boolean {
  return blockers(item, chats, queued).length > 0;
}

/// What a waiting item waits for, by chat: "Updates when “Fix login”
/// finishes", "Updates when 2 running chats finish and “Docs” sends its
/// queued messages".
export function waitLine(item: UpdateItem, chats: readonly Chat[], queued: ReadonlySet<string>): string {
  const running = chats.filter((chat) => BUSY.has(chat.status));
  const holding = chats.filter((chat) => !BUSY.has(chat.status) && queued.has(chat.id));
  const parts: string[] = [];
  const [run] = running;
  if (run) parts.push(running.length === 1 ? `“${run.title}” finishes` : `${running.length} running chats finish`);
  const [hold] = holding;
  if (hold) parts.push(holding.length === 1 ? `“${hold.title}” sends its queued messages` : `${holding.length} chats send their queued messages`);
  if (parts.length) return `Updates when ${parts.join(" and ")}`;
  return item.agentId ? `Updates when ${item.name} is idle` : "Updates when every chat is idle";
}

/// Whether its button installs it here, so Update all takes it.
export const installsHere = (item: UpdateItem) => item.action === "update" || item.action === "restart";

/// "0.48.0 → 0.50.1", or the new version alone when the old one is unknown.
export function versionLine(item: UpdateItem): string {
  return item.from ? `${item.from} → ${item.to}` : item.to;
}

export interface UpkeepState {
  agents: readonly Agent[];
  updates: UpdateStatus | null;
  /// The marketplace's plugin updates, while the market plugin runs.
  plugins: readonly PluginUpdate[];
  /// The folders of the plugins that provide agents.
  agentPlugins: ReadonlySet<string>;
  chats: Map<string, Chat>;
  /// Chats whose input holds a message still to be sent.
  held: Set<string>;
  /// Unsent chats queued to start, while the chat plugin runs.
  drafts: ReadonlySet<string>;
  jobs: Record<string, Job>;
  dismissals: Dismissals;
  open: boolean;
}

/// Runs `then` in `scope` once `until` (epoch milliseconds) has passed, when it lies ahead.
function runAt(until: number | null, scope: Scope.Scope, then: () => void) {
  if (until === null || until <= Date.now()) return;
  Effect.runFork(Effect.forkIn(Effect.sleep(until - Date.now()).pipe(Effect.andThen(Effect.sync(then))), scope, { startImmediately: true }));
}

/// What an update follows besides the host's lists of agents, updates and
/// chats: the messages still to be sent (the host's inputs and the chat
/// plugin's queued chats), which hold updates back as runs do, and the
/// marketplace's plugin updates (the market plugin). `changed` runs after
/// each change: it redraws, forgets jobs caught up and starts what nothing
/// holds back any more.
const makeFollowers = Effect.fn("Upkeep.followers")(function* (state: UpkeepState, changed: () => Effect.Effect<void>) {
  const host = yield* Host;
  const services = yield* Services;
  const queued = (): ReadonlySet<string> => new Set([...state.held, ...state.drafts]);
  const blockersOf = (item: UpdateItem) => blockers(item, state.chats.values(), queued());
  const isBlocked = (item: UpdateItem) => blocked(item, state.chats.values(), queued());
  // A message queued behind a run that began before this plugin loaded:
  // later ones arrive with `inputs_changed`. One that waits in an idle
  // chat since a restart is paused, so it holds nothing up.
  const seedHeld = Effect.fn("Upkeep.seedHeld")(function* (chats: readonly Chat[]) {
    const busy = chats.filter((chat) => BUSY.has(chat.status));
    const snapshots = yield* Effect.all(busy.map((chat) => host.call("host/inputs.list", { chatId: chat.id })), { concurrency: "unbounded" });
    for (const snapshot of snapshots) if (holdsMessage(snapshot)) state.held.add(snapshot.chatId);
  });
  const inputsChanged = Effect.fn("Upkeep.inputsChanged")(function* (snapshot: InputSnapshot) {
    if (holdsMessage(snapshot)) state.held.add(snapshot.chatId);
    else state.held.delete(snapshot.chatId);
    yield* changed();
  });
  const setPlugins = Effect.fn("Upkeep.setPlugins")(function* (plugins: readonly PluginUpdate[]) {
    // Which of them provide agents decides whether they wait for chats.
    if (plugins.length) {
      const { plugins: installed } = yield* host.call("host/plugins.list", {});
      state.agentPlugins = new Set(
        installed.filter((plugin) => plugin.permissions.some((entry) => entry.permission === "agents.provide")).map((plugin) => plugin.name),
      );
    }
    state.plugins = plugins;
    yield* changed();
  });
  // A provider that is starting or reloading answers `Interrupted` for a
  // moment: the read is tried again, and its failure never ends the events.
  const firstRead = <A>(read: Effect.Effect<A, { readonly _tag: string }>) =>
    Stream.fromEffect(read.pipe(Effect.retry({ schedule: Schedule.spaced("500 millis"), times: 20, while: (error) => error._tag === "Interrupted" }))).pipe(
      Stream.ignore({ log: "Error" }),
    );
  // The marketplace's plugin updates and the queued chats come from the
  // market and chat plugins while they run: followed through their events
  // from before the first read (whose answer is as new as any event sent
  // before it), and empty while the plugin is away.
  const followServices = Effect.fn("Upkeep.followServices")(function* () {
    const market = services.when<typeof Market>("divergence/market").pipe(
      Stream.switchMap((client) =>
        Option.isNone(client)
          ? Stream.make([] as readonly PluginUpdate[])
          : Stream.merge(client.value.on("updatesChanged"), firstRead(client.value.updates({}))),
      ),
      Stream.runForEach((plugins) => setPlugins(plugins).pipe(Effect.ignore({ log: "Error", message: "settings: reading the plugin updates failed" }))),
    );
    const chat = services.when<typeof ChatService>("divergence/chat").pipe(
      Stream.switchMap((client) =>
        Option.isNone(client)
          ? Stream.make([] as readonly string[])
          : Stream.merge(client.value.on("queuedChanged"), firstRead(client.value.queued({}))),
      ),
      Stream.runForEach((drafts) =>
        Effect.suspend(() => {
          state.drafts = new Set(drafts);
          return changed();
        }),
      ),
    );
    yield* Effect.all([market, chat], { concurrency: "unbounded", discard: true });
  });
  return { queued, blockersOf, isBlocked, seedHeld, inputsChanged, followServices };
});

/// The work itself, by kind of update. After an agent's update the agent is
/// read again before its job goes, so the list never shows the old gap in
/// between; after the default plugins' update the status is read again.
const makeInstall = Effect.fn("Upkeep.makeInstall")(function* (loadAgents: () => Effect.Effect<void, HostError>, loadUpdates: () => Effect.Effect<void, HostError>) {
  const host = yield* Host;
  const kernel = yield* Kernel;
  const services = yield* Services;
  return Effect.fn("Upkeep.install")(function* (item: UpdateItem) {
    if (item.id === "app") {
      const { restart } = yield* host.call("host/updates.install_app", {});
      // The host answers once every chat is idle, and no run starts after.
      if (restart) yield* kernel.call("quit", {});
      return null;
    }
    if (item.id === "plugins") {
      const { report, chatId } = yield* host.call("host/updates.apply_plugins", {});
      yield* loadUpdates();
      if (chatId) return "An agent is merging the plugins you changed in the Plugins workspace.";
      const changed = report.updated.length + report.added.length + report.removed.length;
      return changed ? `Plugins updated (${changed} changed).` : null;
    }
    if (item.id.startsWith("plugin:")) {
      // The market replaces it, or opens the chat that merges it, and says which.
      const market = yield* services.client<typeof Market>("divergence/market");
      yield* market.update({ folder: item.name });
      return null;
    }
    yield* host.call("host/agents.update", { agentId: item.id });
    yield* loadAgents();
    return `${item.name} updated to ${item.to}.`;
  });
});

const makeUpkeep = Effect.fn("Upkeep.make")(function* () {
  const host = yield* Host;
  const notify = yield* Notify;
  const storage = yield* Storage;
  const services = yield* Services;
  const scope = yield* Scope.Scope;
  // Two installers at once can trip over each other (two global npm
  // installs into one prefix), and the app's restart must come last.
  const installer = yield* Semaphore.make(1);
  const state: UpkeepState = {
    agents: [],
    updates: null,
    plugins: [],
    agentPlugins: new Set(),
    chats: new Map(),
    held: new Set(),
    drafts: new Set(),
    jobs: {},
    dismissals: { skipped: {}, snoozedUntil: null },
    open: false,
  };
  const views: ViewHandle[] = [];
  // Told after every change whether anything shows: the sidebar's button is there only then.
  const watchers: ((any: boolean) => void)[] = [];
  const follow = yield* makeFollowers(state, () => changed());
  const { isBlocked } = follow;
  const items = () => updateItems(state.agents, state.updates, state.plugins, state.agentPlugins);
  const shown = () => shownItems(items(), state.dismissals, state.jobs, Date.now());
  // The list closes with its last item, so the next one does not open it.
  const redraw = () => {
    const any = shown().length > 0;
    if (state.open && !any) state.open = false;
    for (const watch of watchers) watch(any);
    for (const view of views) view.update();
  };

  const loadAgents = Effect.fn("Upkeep.loadAgents")(function* () {
    state.agents = (yield* host.call("host/agents.all", {})).agents;
    redraw();
  });
  const loadUpdates = Effect.fn("Upkeep.loadUpdates")(function* () {
    state.updates = yield* host.call("host/updates.status", {});
    redraw();
  });
  const load = Effect.fn("Upkeep.load")(function* () {
    const [agents, updates, chats, dismissals] = yield* Effect.all(
      [
        host.call("host/agents.all", {}),
        host.call("host/updates.status", {}),
        host.call("host/chats.list", {}),
        storage.get(STORAGE_KEY, Dismissals).pipe(Effect.catchTag("ParseFailed", () => Effect.succeed(undefined))),
      ],
      { concurrency: "unbounded" },
    );
    state.agents = agents.agents;
    state.updates = updates;
    state.chats = new Map(chats.chats.map((chat) => [chat.id, chat]));
    if (dismissals) state.dismissals = dismissals;
    redraw();
    yield* follow.seedHeld(chats.chats);
    // What a snooze hid shows again when the snooze ends.
    runAt(state.dismissals.snoozedUntil, scope, redraw);
  });

  const save = () => storage.set(STORAGE_KEY, state.dismissals);

  const install = yield* makeInstall(loadAgents, loadUpdates);

  const perform = Effect.fn("Upkeep.perform")(function* (item: UpdateItem) {
    state.jobs[item.id] = { state: "updating" };
    redraw();
    // A job queued behind another install looks at the runs again when its
    // turn comes (`undefined`): a chat may have started while it queued.
    const done = yield* installer
      .withPermits(1)(Effect.suspend(() => (isBlocked(item) ? Effect.succeed(undefined) : install(item))))
      .pipe(Effect.result);
    if (Result.isFailure(done)) {
      state.jobs[item.id] = { state: "failed", message: done.failure.message };
      yield* notify.error(`${item.name}: ${done.failure.message}`);
    } else if (done.success === undefined) {
      state.jobs[item.id] = { state: "waiting" };
    } else {
      delete state.jobs[item.id];
      if (done.success) yield* notify.info(done.success);
    }
    redraw();
  });

  const start = (item: UpdateItem) => Effect.forkIn(perform(item), scope, { startImmediately: true });

  const runInTerminal = Effect.fn("Upkeep.runInTerminal")(function* (item: UpdateItem) {
    if (!item.command) return;
    const terminal = yield* services.client<typeof Terminal>("divergence/terminal");
    const ran = yield* terminal.run({ command: item.command, title: `Update ${item.name}` }).pipe(Effect.result);
    if (Result.isFailure(ran)) return yield* notify.error(`Cannot open a terminal: ${ran.failure.message}`);
    state.jobs[item.id] = { state: "terminal" };
    state.open = false;
    redraw();
  });

  /// The item's button: at once when nothing would be cut off, else once
  /// the runs in its way end.
  const request = Effect.fn("Upkeep.request")(function* (item: UpdateItem) {
    if (item.action === "manual") return;
    if (item.action === "terminal") return yield* runInTerminal(item);
    if (isBlocked(item)) {
      state.jobs[item.id] = { state: "waiting" };
      redraw();
      return;
    }
    yield* start(item);
  });

  /// Every item one press installs, the app's restart included. The app
  /// comes last in the list and its wait covers every other item's, so the
  /// single installer reaches it only after the others.
  const requestAll = Effect.fn("Upkeep.requestAll")(function* () {
    for (const item of shown()) {
      const job = state.jobs[item.id];
      if (!installsHere(item) || job?.state === "updating" || job?.state === "waiting") continue;
      yield* request(item);
    }
  });

  const cancel = Effect.fn("Upkeep.cancel")(function* (item: UpdateItem) {
    if (state.jobs[item.id]?.state !== "updating") delete state.jobs[item.id];
    redraw();
  });

  const skip = Effect.fn("Upkeep.skip")(function* (item: UpdateItem) {
    state.dismissals = { ...state.dismissals, skipped: { ...state.dismissals.skipped, [item.id]: item.to } };
    delete state.jobs[item.id];
    redraw();
    yield* save();
  });

  const snooze = Effect.fn("Upkeep.snooze")(function* () {
    state.dismissals = { ...state.dismissals, snoozedUntil: Date.now() + SNOOZE };
    state.open = false;
    redraw();
    // What a snooze hid shows again when the snooze ends.
    runAt(state.dismissals.snoozedUntil, scope, redraw);
    yield* save();
  });

  const setOpen = (open: boolean) => {
    state.open = open;
    redraw();
  };

  // A chat that stopped running or sent its queued messages may free an
  // update that waits for it.
  const releaseWaiting = Effect.fn("Upkeep.releaseWaiting")(function* () {
    for (const item of items()) {
      if (state.jobs[item.id]?.state === "waiting" && !isBlocked(item)) yield* start(item);
    }
  });
  const chatChanged = Effect.fn("Upkeep.chatChanged")(function* (chat: Chat) {
    state.chats.set(chat.id, chat);
    yield* releaseWaiting();
  });
  const chatRemoved = Effect.fn("Upkeep.chatRemoved")(function* (chatId: string) {
    state.chats.delete(chatId);
    state.held.delete(chatId);
    yield* releaseWaiting();
  });
  // A job whose gap is gone (an update run in a terminal, a plugin updated
  // from the marketplace page) has nothing left to show.
  const forgetCaughtUp = () => {
    const behind = new Set(items().map((item) => item.id));
    for (const id of Object.keys(state.jobs)) if (!behind.has(id)) delete state.jobs[id];
    redraw();
  };
  const agentsChanged = Effect.fn("Upkeep.agentsChanged")(function* () {
    yield* loadAgents();
    forgetCaughtUp();
  });
  const changed = (): Effect.Effect<void> => Effect.suspend(() => (forgetCaughtUp(), releaseWaiting()));
  return {
    state,
    views,
    watchers,
    shown,
    ...follow,
    load,
    loadUpdates,
    request,
    requestAll,
    cancel,
    skip,
    snooze,
    setOpen,
    chatChanged,
    chatRemoved,
    agentsChanged,
  };
});

/// One owner of every update, so the button and Settings > Updates share its
/// jobs, its wait for runs and its single installer.
export class Upkeep extends Context.Service<Upkeep, Effect.Success<ReturnType<typeof makeUpkeep>>>()("settings/Upkeep") {
  static readonly layer = Layer.effect(Upkeep, makeUpkeep());
}

Versions

VersionPublishedPlugin APISizePermissionsStatus
0.2.8latestNov 21, 2026>=5 <668.5 KB7 permissionsListed
0.2.7Nov 18, 2026>=5 <668 KB7 permissionsListed
0.2.6Nov 16, 2026>=5 <666.3 KB7 permissionsListed
0.2.5Nov 11, 2026>=5 <663.6 KB7 permissionsListed
0.2.4Nov 9, 2026>=5 <661.6 KB7 permissionsListed
0.2.3Oct 27, 2026>=2 <446.8 KB7 permissionsListed

Reviews and comments

0 threads · 0 reviews

No comments yet.