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.5

Permissions in 0.2.5

  • 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.Import an agent's own sessions as chats, 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.List the workspaces an agent's sessions can be imported into, and 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

service.test.ts54.2 KB
// The divergence/settings service: showShortcuts routes to settings and
// opens Keyboard Shortcuts searched for the command. Real activation
// against a fake host and kernel; calls go through the provided method.
import assert from "node:assert/strict";
import { test } from "node:test";
import type {
  Api,
  AppState,
  Chat,
  AppStatePatch,
  HostEvent,
  PluginSummary,
  RenderResult,
  SettingValue,
  SlotOptions,
  ViewContext,
  Workspace,
} from "divergence";
import { testLayer } from "divergence/effect/testing";
import activate from "./main.ts";
import { nodes } from "../sdk/ui-testing.ts";
import type { AgentEntry } from "./controller.ts";
import { APP_SECTIONS } from "./model.ts";
import manifest from "./plugin.json" with { type: "json" };

const tick = () => new Promise<void>((resolve) => setImmediate(resolve));
const stable = (value: unknown) =>
  JSON.stringify(value, (_key, item: unknown) => (typeof item === "function" ? "@handler" : item));

type ServiceImpl = Record<string, (params: never, ctx: unknown) => Promise<unknown>>;

function fakeApi(options: { progress?: unknown; agents?: AgentEntry[]; workspaces?: Workspace[]; plugins?: PluginSummary[]; autoImport?: boolean; sessions?: Record<string, string[]>; hasChats?: boolean; chats?: Chat[]; route?: string; onAgentUpdate?: (agentId: string) => void; updates?: unknown; tools?: unknown; disabledRules?: string[] } = {}) {
  let state: AppState = { route: options.route };
  let progress: unknown = "progress" in options ? options.progress : { done: true, step: 0, workspaceId: null };
  let agents = options.agents ?? [];
  const workspaces = options.workspaces ?? [];
  let plugins = options.plugins ?? [];
  const ownSettings: Record<string, SettingValue> = { autoImportChats: options.autoImport ?? false };
  const settingsListeners = new Set<(values: Record<string, SettingValue>) => unknown>();
  const importedChats: { id: string; sessionId: string; agentId: string; workspaceId: string }[] = [];
  let appearance = "system";
  let drafted = 0;
  let pickedPath: string | null = null;
  let failure: string | null = null;
  let waitFor: { method: string; promise: Promise<void> } | null = null;
  const appListeners = new Set<(state: AppState) => void>();
  const views: { render: (ctx: ViewContext<object>) => RenderResult; active: boolean }[] = [];
  const listeners = new Map<string, Set<(event: HostEvent) => unknown>>();
  const hostCalls: { method: string; params: unknown }[] = [];
  const kernelCalls: { method: string; params: unknown }[] = [];
  const notices: string[] = [];
  let dirty = true;
  const provided = new Map<string, ServiceImpl>();
  const emitted: { event: string; payload: unknown }[] = [];
  const registered = new Map<string, () => void>();
  const commands = {
    commands: [
      {
        id: "a.open",
        title: "Open",
        category: "A",
        plugin: "a",
        pluginTitle: "A",
        official: true,
        key: "cmd+x",
        defaultKey: "cmd+x",
        keys: ["cmd+x"],
        labels: ["⌘X"],
        source: "default",
        conflict: null,
        problem: null,
        kernel: false,
        enabled: true,
        registered: true,
      },
      {
        id: "b.close",
        title: "Close",
        category: "B",
        plugin: "b",
        pluginTitle: "B",
        official: false,
        key: null,
        defaultKey: "cmd-x",
        keys: [],
        labels: [],
        source: "none",
        conflict: { key: "cmd-x", label: "⌘X", with: "a.open", withTitle: "Open" },
        problem: null,
        kernel: false,
        enabled: true,
        registered: true,
      },
    ],
    errors: [],
  };
  // The kernel's recorder: a new recording answers the one that waits with no key.
  let recording: ((answer: unknown) => void) | null = null;
  const update = (patch: AppStatePatch) => {
    state = {
      ...state,
      ...patch,
      workspaceId: patch.workspaceId === null ? undefined : (patch.workspaceId ?? state.workspaceId),
      chatId: patch.chatId === null ? undefined : (patch.chatId ?? state.chatId),
      route: patch.route ?? state.route,
      shared: { ...state.shared, ...patch.shared },
    };
    dirty = true;
    for (const listener of appListeners) listener(state);
  };
  const hostCall = async (method: string, params: unknown) => {
    hostCalls.push({ method, params });
    if (waitFor?.method === method) await waitFor.promise;
    if (failure === method) throw new Error("Test service is unavailable");
    switch (method) {
      case "host/storage.get":
        return { value: progress };
      case "host/storage.set":
        progress = (params as { value: unknown }).value;
        return {};
      case "host/settings.get":
        return { appearance, tools: { mode: "code", disabled: [], disabledRules: options.disabledRules ?? [] } };
      case "host/settings.update":
        appearance = (params as { appearance: string }).appearance;
        return { appearance };
      case "host/agents.all":
        return { agents };
      case "host/agents.set_enabled": {
        const patch = params as { agentId: string; enabled: boolean };
        agents = agents.map((a) => a.id === patch.agentId ? { ...a, enabled: patch.enabled } : a);
        return {};
      }
      case "host/agents.authenticate":
        agents = agents.map((a) => a.id === (params as { agentId: string }).agentId ? { ...a, status: { state: "ready" } } : a);
        return {};
      case "host/agents.update":
        options.onAgentUpdate?.((params as { agentId: string }).agentId);
        return {};
      case "host/plugins.list":
        return { plugins };
      case "host/plugins.set_enabled": {
        const patch = params as { name: string; enabled: boolean };
        plugins = plugins.map((p) => p.name === patch.name ? { ...p, enabled: patch.enabled } : p);
        return {};
      }
      case "host/plugins.request_enable":
        return { requestId: "native-approval" };
      case "host/workspaces.list":
        return { workspaces };
      case "host/workspaces.remove": {
        const at = workspaces.findIndex((w) => w.id === (params as { workspaceId: string }).workspaceId);
        if (at >= 0) workspaces.splice(at, 1);
        return {};
      }
      case "host/drafts.get":
        return { chatId: (params as { chatId: string }).chatId, revision: 3, blocks: [] };
      case "host/drafts.update":
        return { ...(params as object) };
      case "host/plugins.set_setting":
        return { value: (params as { value: unknown }).value, requestId: null };
      case "host/workspaces.add": {
        const workspace = { id: "project", name: "Project", path: (params as { path: string }).path, position: workspaces.length };
        workspaces.push(workspace);
        return workspace;
      }
      case "host/chats.list":
        return { chats: [...(options.hasChats ? [{ id: "existing" }] : []), ...(options.chats ?? []), ...importedChats] };
      case "host/chats.import": {
        const { workspaceId, agentId } = params as { workspaceId: string; agentId: string };
        let imported = 0;
        for (const sessionId of options.sessions?.[`${workspaceId}/${agentId}`] ?? []) {
          if (importedChats.some((c) => c.sessionId === sessionId && c.agentId === agentId)) continue;
          importedChats.push({ id: `chat-${sessionId}`, sessionId, agentId, workspaceId });
          imported++;
        }
        return { imported };
      }
      case "host/chats.update": {
        const { chatId, archived } = params as { chatId: string; archived: boolean };
        const at = options.chats!.findIndex((c) => c.id === chatId);
        options.chats![at] = { ...options.chats![at]!, archived };
        return options.chats![at];
      }
      case "host/chats.delete":
        options.chats!.splice(options.chats!.findIndex((c) => c.id === (params as { chatId: string }).chatId), 1);
        return {};
      case "host/chats.create":
        // A titled chat is a change saved in the guide; the untitled one is the first chat.
        return { id: (params as { title?: string }).title ? `draft-${++drafted}` : "first", ...(params as object) };
      case "host/updates.status":
        return options.updates ?? {};
      case "host/updates.install_app":
        return { restart: true };
      case "host/tools.list":
        return options.tools ?? null;
      case "host/plugins.settings":
        return { name: "x", error: null, properties: [], notices: [] };
      default:
        throw new Error(`Unexpected host method ${method}`);
    }
  };
  const kernelCall = async (method: string, params: unknown) => {
    kernelCalls.push({ method, params });
    if (method === "commands") return commands;
    if (method === "keys.record") {
      recording?.({ key: null });
      return new Promise((resolve) => { recording = resolve; });
    }
    if (method === "themes") return { themes: [] };
    if (method === "settings_view") return { view: null };
    if (method === "theme") return {};
    if (method === "quit") return {};
    throw new Error(`Unexpected kernel method ${method}`);
  };
  const broker = testLayer();
  // This assertion describes a local fake; unused API methods fail rather than impersonating external replies.
  const api = new Proxy(
    {
      ...broker.api,
      plugin: "settings",
      id: "divergence/settings",
      services: {
        provide: async (def: { name: string }, impl: ServiceImpl) => {
          provided.set(def.name, impl);
          return {
            emit: (event: string, payload: unknown) => {
              emitted.push({ event, payload });
            },
            remove: () => {
              provided.delete(def.name);
            },
          };
        },
        get: (name: string) => {
          throw new Error(`no provider for ${name}`);
        },
        available: () => false,
        when: () => () => {},
      },
      host: { ...broker.api.host, call: hostCall, kernel: kernelCall },
      settings: {
        ...broker.api.settings,
        get: ((key?: string) => key === undefined ? ownSettings : ownSettings[key] ?? null) as Api["settings"]["get"],
        set: async (key: string, value: SettingValue) => {
          ownSettings[key] = value;
          for (const listener of settingsListeners) listener(ownSettings);
          return value;
        },
        onChange: (fn: (values: Record<string, SettingValue>) => unknown) => {
          settingsListeners.add(fn);
          return () => { settingsListeners.delete(fn); };
        },
      },
      app: {
        state: () => state,
        update,
        select: (chatId: string, workspaceId: string) => update({ chatId, workspaceId, route: "chat" }),
        route: (route: string) => update({ route }),
        onChange: (fn: (state: AppState) => void) => {
          appListeners.add(fn);
          return () => {
            appListeners.delete(fn);
          };
        },
      },
      views: { add: (key: string, definition: any) => {
        const { slot: slot, render: render } = definition;
        const options = { ...definition, key };
        const _options = options;
        void slot; void _options; void options;
        const view = { render, active: true };
        views.push(view);
        dirty = true;
        return {
          id: views.length,
          update: () => {
            dirty = true;
          },
          remove: () => {
            view.active = false;
          },
        };
      } },
      on: (name: string, fn: (event: HostEvent) => unknown) => {
        const subscribers = listeners.get(name) ?? new Set();
        listeners.set(name, subscribers);
        subscribers.add(fn);
        return () => {
          subscribers.delete(fn);
        };
      },
      command: (definition: { id: string; run: () => void }) => {
        registered.set(definition.id, definition.run);
        return { remove() { registered.delete(definition.id); } };
      },
      pickFolder: async () => ({ path: pickedPath }),
      notify: (message: string) => {
        notices.push(message);
      },
      focus: () => {},
    },
    {
      get(target, key, receiver) {
        if (Reflect.has(target, key)) return Reflect.get(target, key, receiver);
        throw new Error(`Unexpected API ${String(key)}`);
      },
    },
  ) as unknown as Api;
  const render = () =>
    views
      .filter((view) => view.active)
      .map((view) =>
        view.render({
          state: {},
          set: () => {},
          app: state,
          plugin: "settings",
          update: () => {
            dirty = true;
          },
        }),
      );
  let trees: RenderResult[] = [];
  const settle = async () => {
    for (let round = 0; round < 50; round++) {
      await tick();
      if (!dirty) {
        await tick();
        if (!dirty) return;
      }
      dirty = false;
      trees = render();
    }
    throw new Error("settings did not settle");
  };
  const ctx = { caller: { plugin: "test/client", id: "test/client" }, signal: AbortSignal.timeout(5000) };
  return {
    api,
    hostCalls,
    kernelCalls,
    notices,
    provided,
    settle,
    trees: () => stable(trees),
    state: () => state,
    progress: () => progress,
    settings: () => ({ ...ownSettings }),
    chats: () => importedChats,
    plugins: (next: PluginSummary[]) => { plugins = next; },
    route: (route: string) => update({ route }),
    node: (id: string) => {
      const node = nodes(trees).find((node) => node.id === id);
      assert.ok(node, `Missing control ${id}`);
      return node;
    },
    click: async (id: string) => {
      const node = nodes(trees).find((node) => node.id === id);
      assert.ok(node && typeof node.onClick === "function", `Missing action ${id}`);
      assert.ok(!node.disabled, `${id} is disabled`);
      node.onClick();
      await settle();
    },
    change: async (id: string, value: unknown) => {
      const node = nodes(trees).find((node) => node.id === id);
      assert.ok(node && typeof node.onChange === "function", `Missing input ${id}`);
      assert.ok(!node.disabled, `${id} is disabled`);
      node.onChange({ value });
      await settle();
    },
    press: async (id: string) => {
      const node = nodes(trees).find((node) => node.id === id);
      assert.ok(node && typeof node.onPress === "function", `Missing trigger ${id}`);
      node.onPress();
      await settle();
    },
    has: (id: string) => nodes(trees).some((node) => node.id === id),
    // What the plugin saved through its Storage service.
    stored: () => Object.fromEntries(broker.storage),
    pick: (path: string | null) => { pickedPath = path; },
    fail: (method: string | null) => { failure = method; },
    block: (method: string) => {
      const { promise, resolve } = Promise.withResolvers<void>();
      waitFor = { method, promise };
      return () => { waitFor = null; resolve(); };
    },
    emit: async (event: HostEvent) => {
      for (const fn of listeners.get(event.event) ?? []) fn(event);
      await settle();
    },
    agents: (next: AgentEntry[]) => { agents = next; },
    pressKey: async (key: string, label: string) => {
      const answer = recording;
      recording = null;
      answer?.({ key, label });
      await settle();
    },
    command: async (id: string) => { registered.get(id)?.(); await settle(); },
    callService: (method: string, params: unknown) =>
      provided.get("divergence/settings")?.[method]?.(params as never, ctx),
  };
}

test("showShortcuts routes to settings and searches Keyboard Shortcuts", async () => {
  const fake = fakeApi();
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    assert.ok(fake.provided.has("divergence/settings"));
    // The page loaded at activation, so Settings opens on its section at once.
    const loads = fake.kernelCalls.filter((call) => call.method === "commands").length;
    assert.equal(loads, 1);
    assert.deepEqual(await fake.callService("showShortcuts", { query: "assign-me" }), null);
    assert.equal(fake.state().route, "settings");
    assert.equal(fake.state().shared?.showShortcuts, undefined);
    await fake.settle();
    // The keys are read again for the request.
    assert.equal(fake.kernelCalls.filter((call) => call.method === "commands").length, loads + 1);
    assert.ok(fake.trees().includes("Keyboard Shortcuts"));
    assert.ok(fake.trees().includes("assign-me"));
    assert.ok(!fake.trees().includes("Loading settings"));
    assert.equal(fake.notices.length, 0);
  } finally {
    await dispose();
  }
});

test("Settings takes the sidebar's place and opens on its section without a loading state", async () => {
  const fake = fakeApi();
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    assert.ok(!fake.has("settings-sidebar") && !fake.has("settings-page"), "nothing draws off the route");
    fake.route("settings");
    await fake.settle();
    // Its list of sections, in the sidebar's place, and the open section.
    assert.ok(fake.has("settings-sidebar") && fake.has("nav-general") && fake.has("settings-back"));
    assert.ok(fake.has("settings-page") && fake.has("appearance"));
    assert.ok(!fake.trees().includes("Loading"));
    await fake.click("settings-back");
    assert.equal(fake.state().route, "chat");
    assert.ok(!fake.has("settings-sidebar") && !fake.has("settings-page"));
  } finally {
    await dispose();
  }
});

test("each of the app's sections has a command that opens Settings on it", async () => {
  const fake = fakeApi();
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    const declared = (manifest.contributes.commands as { id: string; title: string; category: string }[]);
    for (const section of APP_SECTIONS) {
      const id = `settings.${section.id}`;
      assert.ok(declared.some((command) => command.id === id && command.title === section.label && command.category === "Settings"), `${id} is declared`);
      fake.route("chat");
      await fake.settle();
      await fake.command(id);
      assert.equal(fake.state().route, "settings", `${id} opens Settings`);
      assert.equal(fake.node(`nav-${section.id}`).selected, true, `${id} opens ${section.label}`);
    }
    assert.equal(fake.notices.length, 0);
  } finally {
    await dispose();
  }
});

const pluginsWorkspace: Workspace = { id: "plugins", name: "Divergence", path: "/plugins", mark: "divergence", position: 0 };
const available: AgentEntry = { id: "test-agent", name: "Test Agent", enabled: true, status: { state: "ready" }, capabilities: { sessionList: true } };

const optionals: PluginSummary[] = ["files", "git", "terminal", "market", "visuals"].map((name) => ({
  name, id: `divergence/${name}`, version: "1.0.0", description: name, official: true, claimsOfficial: false,
  source: "official-bundle", enabled: true, state: "loaded", ui: true, sandboxed: null, permissions: [], pending: [], commands: 0,
}));

test("first-run guide teaches plugins, makes every choice real, and Start opens the first chat and the saved changes", async () => {
  const fake = fakeApi({ progress: null, agents: [available], workspaces: [pluginsWorkspace], plugins: optionals });
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    assert.equal(fake.state().route, "onboarding");
    assert.ok(fake.trees().includes("One window for every coding agent"));
    for (const plugin of ["sidebar", "chat", "files", "git", "terminal", "market", "settings", "themes"])
      assert.ok(fake.trees().includes(`"${plugin}"`), `the example window labels ${plugin}`);
    assert.equal((fake.progress() as { step: number }).step, 0);
    assert.equal(fake.node("onboarding-step-2").onClick, undefined, "later steps cannot be skipped to");
    await fake.click("onboarding-next");
    assert.ok(fake.trees().includes("Test Agent") && fake.trees().includes("First chat"));
    await fake.change("agent-test-agent", false);
    assert.equal(fake.node("agent-test-agent").checked, false);
    assert.equal(fake.node("onboarding-next").label, "Continue without an agent");
    await fake.change("agent-test-agent", true);
    await fake.click("onboarding-next");
    assert.ok(fake.trees().includes("Divergence’s own plugins"));
    fake.pick(null);
    await fake.click("onboarding-folder");
    assert.ok(!fake.hostCalls.some((c) => c.method === "host/workspaces.add"));
    fake.pick("/project");
    await fake.click("onboarding-folder");
    assert.ok(fake.trees().includes("/project"));
    assert.equal(fake.node("onboarding-next").label, "Continue");
    await fake.click("onboarding-next");
    await fake.change("onboarding-plugin-terminal", false);
    assert.ok(fake.hostCalls.some((c) => c.method === "host/plugins.set_enabled" && stable(c.params) === stable({ name: "terminal", enabled: false })));
    assert.ok(fake.trees().includes("terminal is off"), "the window loses what was switched off");
    await fake.click("onboarding-theme-vscode");
    assert.deepEqual(fake.hostCalls.find((c) => c.method === "host/plugins.set_setting")?.params, {
      name: "themes", key: "active", value: { light: "vscode-light", dark: "vscode-dark" },
    });
    await fake.change("onboarding-appearance", "dark");
    assert.ok(fake.kernelCalls.some((c) => c.method === "theme" && stable(c.params) === stable({ mode: "dark" })));
    await fake.change("onboarding-change", "Show a word count under the prompt");
    await fake.click("onboarding-save-change");
    assert.ok(fake.trees().includes("Waiting in Divergence for you to send it"));
    await fake.click("onboarding-next");
    assert.ok(fake.has("onboarding-visual-chart"), "a real reply with a chart");
    await fake.click("onboarding-visual-diagram");
    assert.ok(fake.has("onboarding-visual-diagram"));
    await fake.click("onboarding-next");
    assert.equal(fake.node("onboarding-next").label, "Start in Project");
    for (const line of ["Project, Divergence", "VS Code Modern, without Terminal", "1 change waiting in Divergence", "Test Agent starts the first chat"])
      assert.ok(fake.trees().includes(line), line);
    await fake.click("onboarding-next");
    assert.equal(fake.state().route, "chat");
    assert.equal(fake.state().workspaceId, "project");
    assert.equal(fake.state().chatId, "first");
    const created = fake.hostCalls.filter((c) => c.method === "host/chats.create").map((c) => c.params);
    assert.deepEqual(created, [
      { workspaceId: "plugins", agentId: "test-agent", title: "Show a word count under the prompt", inUse: [] },
      { workspaceId: "project", agentId: "test-agent", inUse: ["draft-1"] },
    ]);
    assert.deepEqual(fake.hostCalls.find((c) => c.method === "host/drafts.update")?.params, {
      chatId: "draft-1", revision: 3, blocks: [{ type: "text", text: "Show a word count under the prompt" }],
    });
    assert.deepEqual(fake.progress(), { done: true, step: 5, workspaceId: "project", firstAgent: "test-agent", saved: [] });
    assert.equal(fake.notices.length, 0);
  } finally { await dispose(); }
});

test("existing users and completed setup retain their route; the command reopens the guide", async () => {
  for (const options of [
    { progress: null, hasChats: true },
    { progress: null, workspaces: [{ id: "project", name: "Project", path: "/project", position: 0 }] },
    {},
    { progress: null, route: "market" },
  ]) {
    const fake = fakeApi(options);
    const dispose = activate(fake.api);
    try {
      await fake.settle();
      assert.notEqual(fake.state().route, "onboarding");
      await fake.command("settings.onboarding");
      assert.equal(fake.state().route, "onboarding");
      assert.ok(fake.trees().includes("One window for every coding agent"));
    } finally { await dispose(); }
  }
});

test("interrupted setup resumes its step from older progress, goes back, and Skip still opens a chat", async () => {
  const fake = fakeApi({ progress: { done: false, step: 2, workspaceId: "plugins", returning: true }, agents: [available], workspaces: [pluginsWorkspace] });
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    assert.equal(fake.state().route, "onboarding");
    assert.ok(fake.trees().includes("Add the folders you work in"));
    await fake.click("onboarding-back");
    assert.ok(fake.trees().includes("Choose your agents"));
    await fake.click("onboarding-step-0");
    assert.ok(fake.trees().includes("One window for every coding agent"));
    await fake.click("onboarding-skip");
    assert.equal(fake.state().route, "chat");
    assert.equal(fake.state().chatId, "first", "skipping never ends on an empty window");
    assert.equal((fake.progress() as { done: boolean }).done, true);
    assert.deepEqual(fake.hostCalls.find((c) => c.method === "host/chats.create")?.params, { workspaceId: "plugins", agentId: "test-agent", inUse: [] });
  } finally { await dispose(); }
});

test("agent setup shows starting, unavailable and sign-in states, guards duplicate requests, and recovers", async () => {
  const auth: AgentEntry = { ...available, status: { state: "auth_required", message: "Sign in to continue" }, authMethods: [{ id: "login", name: "Sign in" }] };
  const fake = fakeApi({ progress: { done: false, step: 1, workspaceId: null }, agents: [auth] });
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    assert.ok(fake.trees().includes("Sign in to continue"));
    fake.fail("host/agents.authenticate");
    await fake.click("auth-test-agent-login");
    assert.ok(fake.trees().includes("Test service is unavailable"));
    assert.equal(fake.node("onboarding-next").disabled, false);
    fake.fail(null);
    const release = fake.block("host/agents.authenticate");
    await fake.click("auth-test-agent-login");
    assert.equal(fake.node("auth-test-agent-login").loading, true);
    assert.equal(fake.node("onboarding-next").disabled, true);
    const handler = fake.node("auth-test-agent-login").onClick;
    if (typeof handler === "function") handler();
    await fake.settle();
    assert.equal(fake.hostCalls.filter((c) => c.method === "host/agents.authenticate").length, 2);
    release();
    await fake.settle();
    assert.ok(fake.trees().includes("Ready"));
    assert.ok(!fake.trees().includes("Test service is unavailable"));
    fake.agents([{ ...available, status: { state: "starting" } }]);
    await fake.emit({ event: "agents_changed" });
    assert.ok(fake.trees().includes("Checking…"));
    fake.agents([{ ...available, status: { state: "unavailable", message: "Install the agent first" } }]);
    await fake.emit({ event: "agents_changed" });
    assert.ok(fake.trees().includes("Install the agent first"));
    assert.equal(fake.node("onboarding-next").label, "Continue without an agent");
    for (let step = 1; step < 5; step++) await fake.click("onboarding-next");
    assert.equal(fake.node("onboarding-next").label, "Open Divergence");
    await fake.click("onboarding-next");
    assert.equal(fake.state().route, "chat");
    assert.ok(!fake.hostCalls.some((c) => c.method === "host/chats.create"));
  } finally { await dispose(); }
});

test("loading and completion failures remain on setup and can be retried without a false completion", async () => {
  const fake = fakeApi({ progress: { done: false, step: 5, workspaceId: "plugins" }, agents: [available], workspaces: [pluginsWorkspace] });
  fake.fail("host/settings.get");
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    assert.ok(fake.trees().includes("Test service is unavailable"));
    assert.equal(fake.node("onboarding-next").disabled, true);
    fake.fail(null);
    await fake.click("onboarding-retry");
    assert.equal(fake.node("onboarding-next").disabled, false);
    fake.fail("host/chats.create");
    await fake.click("onboarding-next");
    assert.equal(fake.state().route, "onboarding");
    assert.equal((fake.progress() as { done: boolean }).done, false);
    fake.fail("host/storage.set");
    const before = fake.hostCalls.length;
    await fake.click("onboarding-next");
    assert.equal(fake.state().route, "onboarding");
    assert.equal((fake.progress() as { done: boolean }).done, false);
    fake.fail(null);
    await fake.click("onboarding-next");
    assert.equal(fake.state().route, "chat");
    const made = fake.hostCalls.slice(before).filter((c) => c.method === "host/chats.create");
    assert.equal(made.length, 1, "Start again after a failed save opens the chat the first press made");
  } finally { await dispose(); }
});

const projectWorkspace: Workspace = { id: "project", name: "Project", path: "/project", position: 1 };

test("Projects lists every workspace with the Divergence one last, and the chosen one is where the first chat opens", async () => {
  const fake = fakeApi({ progress: { done: false, step: 2, workspaceId: "project" }, agents: [available], workspaces: [pluginsWorkspace, projectWorkspace] });
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    assert.ok(fake.trees().includes("/project") && fake.trees().includes("Divergence’s own plugins"));
    assert.ok(fake.has("onboarding-remove-project") && !fake.has("onboarding-remove-plugins"), "only a project folder can be removed");
    await fake.click("onboarding-project-plugins");
    assert.equal((fake.progress() as { workspaceId: string }).workspaceId, "plugins");
    await fake.click("onboarding-remove-project");
    assert.ok(fake.hostCalls.some((c) => c.method === "host/workspaces.remove" && stable(c.params) === stable({ workspaceId: "project" })));
    assert.ok(!fake.trees().includes("/project"));
    for (let i = 0; i < 3; i++) await fake.click("onboarding-next");
    assert.equal(fake.node("onboarding-next").label, "Start in Divergence");
    assert.ok(fake.trees().includes("Your first chat opens in Divergence with Test Agent."));
  } finally { await dispose(); }
});

test("auto-import is opt-in where folders are added, imports after a project is added, and can be disabled in General", async () => {
  const fake = fakeApi({ progress: { done: false, step: 2, workspaceId: null }, agents: [available], workspaces: [pluginsWorkspace], sessions: { "project/test-agent": ["outside-1", "outside-2"], "plugins/test-agent": ["plugin-session"] } });
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    assert.equal(fake.node("auto-import-chats").checked, false);
    await fake.change("auto-import-chats", true);
    assert.equal(fake.settings().autoImportChats, true);
    assert.deepEqual(fake.chats(), []);
    fake.pick("/project");
    await fake.click("onboarding-folder");
    assert.deepEqual(fake.chats().map((c) => [c.workspaceId, c.agentId, c.sessionId]), [
      ["project", "test-agent", "outside-1"], ["project", "test-agent", "outside-2"],
    ]);
    assert.ok(fake.trees().includes("Imported 2 chats."));
    await fake.emit({ event: "workspaces_changed" });
    assert.equal(fake.hostCalls.filter((c) => c.method === "host/chats.import").length, 1);
    fake.route("settings");
    await fake.settle();
    assert.equal(fake.node("auto-import-chats").checked, true);
    await fake.change("auto-import-chats", false);
    assert.equal(fake.settings().autoImportChats, false);
    fake.agents([available, { ...available, id: "another" }]);
    await fake.emit({ event: "agents_changed" });
    assert.equal(fake.hostCalls.filter((c) => c.method === "host/chats.import").length, 1);
  } finally { await dispose(); }
});

test("startup imports only ready history-listing agents, and later readiness/enabling imports each project once", async () => {
  const later: AgentEntry = { ...available, id: "later", name: "Later", status: { state: "starting" } };
  const disabled: AgentEntry = { ...available, id: "disabled", enabled: false };
  const noHistory: AgentEntry = { ...available, id: "no-history", capabilities: { sessionHistory: true, sessionList: false } };
  const workspaces = [pluginsWorkspace, projectWorkspace];
  const sessions = { "project/test-agent": ["first"], "project/later": ["second", "third"], "project/disabled": ["fourth"], "other/test-agent": ["fifth"] };
  const fake = fakeApi({ autoImport: true, agents: [available, later, disabled, noHistory], workspaces, sessions });
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    assert.deepEqual(fake.chats().map((c) => c.sessionId), ["first"]);
    fake.agents([available, { ...later, status: { state: "ready" } }, { ...disabled, enabled: true }, noHistory]);
    await fake.emit({ event: "agents_changed" });
    assert.deepEqual(fake.chats().map((c) => c.sessionId), ["first", "second", "third", "fourth"]);
    workspaces.push({ id: "other", name: "Other", path: "/other", position: 2 });
    await fake.emit({ event: "workspaces_changed" });
    assert.deepEqual(fake.chats().map((c) => c.sessionId), ["first", "second", "third", "fourth", "fifth"]);
    const imports = fake.hostCalls.filter((c) => c.method === "host/chats.import");
    await fake.emit({ event: "agents_changed" });
    await fake.emit({ event: "workspaces_changed" });
    assert.equal(fake.hostCalls.filter((c) => c.method === "host/chats.import").length, imports.length);
    assert.ok(!imports.some((c) => stable(c.params).includes("no-history") || stable(c.params).includes("plugins")));
  } finally { await dispose(); }
});

test("a slow import coalesces change events and disabling it prevents more work without deleting imported chats", async () => {
  const fake = fakeApi({ autoImport: true, route: "settings", agents: [available, { ...available, id: "other" }], workspaces: [projectWorkspace], sessions: { "project/test-agent": ["first"], "project/other": ["must-not-import"] } });
  const release = fake.block("host/chats.import");
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    assert.ok(fake.trees().includes("Importing existing chats"));
    await fake.emit({ event: "agents_changed" });
    await fake.emit({ event: "workspaces_changed" });
    await fake.change("auto-import-chats", false);
    release();
    await fake.settle();
    assert.deepEqual(fake.chats().map((c) => c.sessionId), ["first"]);
    assert.equal(fake.node("auto-import-chats").checked, false);
    assert.equal(fake.hostCalls.filter((c) => c.method === "host/chats.import").length, 1);
  } finally { release(); await dispose(); }
});

test("automatic import errors stay visible, can be retried, and survive leaving onboarding", async () => {
  const fake = fakeApi({ autoImport: true, route: "settings", agents: [available], workspaces: [projectWorkspace], sessions: { "project/test-agent": ["recoverable"] } });
  fake.fail("host/chats.import");
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    assert.ok(fake.trees().includes("Could not import Test Agent chats into Project"));
    assert.ok(fake.notices.some((n) => n.includes("Test service is unavailable")));
    assert.deepEqual(fake.chats(), []);
    fake.fail(null);
    await fake.click("auto-import-retry");
    assert.deepEqual(fake.chats().map((c) => c.sessionId), ["recoverable"]);
    assert.ok(!fake.trees().includes("Some chats could not be imported"));
    assert.ok(fake.trees().includes("Imported 1 chat."));
  } finally { await dispose(); }
});

// --- the update row in the sidebar ---------------------------------------------------

const behind = (id: string, name: string, maintenance: AgentEntry["maintenance"]): AgentEntry => ({
  id,
  name,
  description: "",
  capabilities: {},
  authMethods: [],
  status: { state: "ready" },
  enabled: true,
  maintenance,
});
const chat = (id: string, agentId: string, status: Chat["status"]) =>
  ({ id, agentId, workspaceId: "w", status, title: "", createdAt: "", updatedAt: "" }) as unknown as Chat;

test("an update asked for while its agent runs waits, then installs once the chat stops", async () => {
  const fake = fakeApi({
    agents: [behind("codex", "Codex", { installedVersion: "0.48.0", latestVersion: "0.50.1", manager: "npm", canUpdate: true })],
    chats: [chat("c1", "codex", "running")],
    onAgentUpdate: () => fake.agents([behind("codex", "Codex", { installedVersion: "0.50.1", manager: "npm", canUpdate: true })]),
  });
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    // The sidebar draws the published view above Settings.
    assert.equal(typeof fake.state().shared?.["sidebarItem.updates"], "number");
    assert.ok(fake.trees().includes("Update Codex"));
    await fake.click("sidebar-updates");
    assert.equal(fake.node("updates").open, true);
    assert.ok(fake.trees().includes("0.48.0 → 0.50.1"));
    // The button works at once; the install waits for the run.
    await fake.click("update-codex");
    assert.ok(!fake.hostCalls.some((call) => call.method === "host/agents.update"));
    assert.ok(fake.trees().includes("Updates when Codex is idle"));
    // Another agent's chat ending changes nothing.
    await fake.emit({ event: "chat_changed", chat: chat("c2", "claude", "idle") });
    assert.ok(!fake.hostCalls.some((call) => call.method === "host/agents.update"));
    await fake.emit({ event: "chat_changed", chat: chat("c1", "codex", "idle") });
    await fake.settle();
    assert.deepEqual(
      fake.hostCalls.filter((call) => call.method === "host/agents.update").map((call) => call.params),
      [{ agentId: "codex" }],
    );
    assert.ok(!fake.has("sidebar-updates"), "nothing is behind any more");
    assert.ok(fake.notices.includes("Codex updated to 0.50.1."));
    // The next update shows the row, closed.
    fake.agents([behind("codex", "Codex", { installedVersion: "0.50.1", latestVersion: "0.51.0", manager: "npm", canUpdate: true })]);
    await fake.emit({ event: "agents_changed" });
    assert.ok(fake.has("sidebar-updates"));
    assert.equal(fake.node("updates").open, false, "the list stays closed");
  } finally {
    await dispose();
  }
});

test("Settings > Agents disables Sign in, Update and the switch while a sign-in runs", async () => {
  const fake = fakeApi({
    route: "settings",
    agents: [
      {
        ...behind("codex", "Codex", { installedVersion: "0.48.0", latestVersion: "0.50.1", manager: "npm", canUpdate: true }),
        status: { state: "auth_required", message: "Sign in to continue" },
        authMethods: [{ id: "chatgpt", name: "Sign in with ChatGPT" }],
      },
    ],
  });
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    await fake.click("nav-agents");
    const signIn = fake.block("host/agents.authenticate");
    await fake.click("auth-codex-chatgpt");
    assert.equal(fake.node("auth-codex-chatgpt").loading, true);
    assert.equal(fake.node("auth-codex-chatgpt").disabled, true);
    assert.equal(fake.node("agent-codex").disabled, true);
    assert.equal(fake.node("update-codex").disabled, true);
    signIn();
    await fake.settle();
    assert.ok(fake.notices.includes("Codex: signed in."));
    assert.equal(fake.hostCalls.filter((call) => call.method === "host/agents.authenticate").length, 1);
  } finally {
    await dispose();
  }
});

test("Update in Settings > Agents waits for the agent's running chat, like the update row", async () => {
  const fake = fakeApi({
    route: "settings",
    agents: [behind("codex", "Codex", { installedVersion: "0.48.0", latestVersion: "0.50.1", manager: "npm", canUpdate: true })],
    chats: [chat("c1", "codex", "running")],
  });
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    await fake.click("nav-agents");
    await fake.click("update-codex");
    assert.ok(!fake.hostCalls.some((call) => call.method === "host/agents.update"));
    assert.ok(fake.trees().includes("Updates when Codex is idle."));
    assert.equal(fake.node("update-codex").disabled, true);
    await fake.emit({ event: "chat_changed", chat: chat("c1", "codex", "idle") });
    await fake.settle();
    assert.equal(fake.hostCalls.filter((call) => call.method === "host/agents.update").length, 1);
  } finally {
    await dispose();
  }
});

test("Install and restart in Settings > Updates waits for the running chats before it quits", async () => {
  const fake = fakeApi({
    route: "settings",
    chats: [chat("c1", "codex", "running")],
    updates: {
      enabled: true,
      appVersion: "1.0.0",
      appUpdate: { version: "1.1.0", releaseNotes: "" },
      plugins: null,
      pluginUpdate: null,
      lastChecked: null,
      checking: false,
      error: null,
      busy: null,
    },
  });
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    await fake.click("nav-updates");
    await fake.click("install-app");
    assert.ok(!fake.hostCalls.some((call) => call.method === "host/updates.install_app"));
    assert.ok(!fake.kernelCalls.some((call) => call.method === "quit"));
    assert.ok(fake.trees().includes("restarts when every chat is idle"));
    assert.equal(fake.node("install-app").disabled, true);
    await fake.emit({ event: "chat_changed", chat: chat("c1", "codex", "idle") });
    await fake.settle();
    assert.equal(fake.hostCalls.filter((call) => call.method === "host/updates.install_app").length, 1);
    assert.ok(fake.kernelCalls.some((call) => call.method === "quit"));
  } finally {
    await dispose();
  }
});

test("while the downloaded app waits for every chat, the row says it restarts when they are idle", async () => {
  const updates = { enabled: true, appVersion: "1.0.0", appUpdate: { version: "1.1.0", releaseNotes: "" }, pluginUpdate: null, busy: null as string | null };
  const fake = fakeApi({ updates });
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    await fake.click("sidebar-updates");
    const download = fake.block("host/updates.install_app");
    await fake.click("update-app");
    updates.busy = "restarting when every chat is idle";
    await fake.emit({ event: "updates_changed" });
    assert.ok(fake.trees().includes("Restarts when every chat is idle"));
    assert.ok(!fake.kernelCalls.some((call) => call.method === "quit"));
    download();
    await fake.settle();
    assert.equal(fake.hostCalls.filter((call) => call.method === "host/updates.install_app").length, 1);
    assert.ok(fake.kernelCalls.some((call) => call.method === "quit"));
  } finally {
    await dispose();
  }
});

test("an update queued behind another install waits for a chat that started meanwhile", async () => {
  const fake = fakeApi({
    agents: [behind("codex", "Codex", { installedVersion: "0.48.0", latestVersion: "0.50.1", manager: "npm", canUpdate: true })],
    updates: { enabled: true, appVersion: "1.0.0", appUpdate: { version: "1.1.0", releaseNotes: "" }, pluginUpdate: null },
  });
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    await fake.click("sidebar-updates");
    const install = fake.block("host/agents.update");
    await fake.click("update-codex");
    await fake.click("update-app");
    await fake.emit({ event: "chat_changed", chat: chat("c1", "claude", "running") });
    install();
    await fake.settle();
    assert.ok(!fake.hostCalls.some((call) => call.method === "host/updates.install_app"));
    assert.ok(fake.trees().includes("Updates when every chat is idle"));
    await fake.emit({ event: "chat_changed", chat: chat("c1", "claude", "idle") });
    await fake.settle();
    assert.equal(fake.hostCalls.filter((call) => call.method === "host/updates.install_app").length, 1);
  } finally {
    await dispose();
  }
});

test("pressing the update row opens the list and pressing it again closes it", async () => {
  const fake = fakeApi({
    agents: [behind("codex", "Codex", { installedVersion: "0.48.0", latestVersion: "0.50.1", manager: "npm", canUpdate: true })],
  });
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    assert.equal(fake.node("updates").open, false, "passing over the row opens nothing");
    await fake.click("sidebar-updates");
    assert.equal(fake.node("updates").open, true);
    await fake.click("sidebar-updates");
    assert.equal(fake.node("updates").open, false);
  } finally {
    await dispose();
  }
});

test("a skipped version stays away, a newer one comes back, and tomorrow puts off the row", async () => {
  const fake = fakeApi({
    agents: [behind("codex", "Codex", { installedVersion: "0.48.0", latestVersion: "0.50.1", manager: "npm", canUpdate: true })],
  });
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    await fake.click("sidebar-updates");
    await fake.click("update-skip-codex");
    assert.ok(!fake.has("sidebar-updates"));
    assert.deepEqual(fake.stored()["upkeep"], { skipped: { codex: "0.50.1" }, snoozedUntil: null });
    fake.agents([behind("codex", "Codex", { installedVersion: "0.48.0", latestVersion: "0.51.0", manager: "npm", canUpdate: true })]);
    await fake.emit({ event: "agents_changed" });
    assert.ok(fake.trees().includes("Update Codex"));
    await fake.click("sidebar-updates");
    await fake.click("updates-snooze");
    assert.ok(!fake.has("sidebar-updates"));
    const until = (fake.stored()["upkeep"] as { snoozedUntil: number }).snoozedUntil;
    assert.ok(until > Date.now() + 23 * 60 * 60 * 1000);
  } finally {
    await dispose();
  }
});

test("a host event whose handler fails is logged with its cause, not dropped", async () => {
  const fake = fakeApi();
  const logged: string[] = [];
  const methods = ["log", "info", "warn", "error", "debug"] as const;
  const originals = methods.map((name) => console[name]);
  for (const name of methods) console[name] = (...args: unknown[]) => void logged.push(args.map(String).join(" "));
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    fake.fail("host/updates.status");
    await fake.emit({ event: "updates_changed" });
    await fake.settle();
  } finally {
    methods.forEach((name, i) => (console[name] = originals[i] as (typeof console)[typeof name]));
    await dispose?.();
  }
  const line = logged.find((text) => text.includes("settings: handling updates_changed failed"));
  assert.ok(line, `nothing logged: ${JSON.stringify(logged)}`);
  assert.match(line, /Test service is unavailable/);
});

test("Archived Chats lists them by workspace, restores one, and deletes one only after asking", async () => {
  const archived = (id: string, workspaceId: string, day: number): Chat =>
    ({ ...chat(id, "codex", "idle"), title: id.toUpperCase(), workspaceId, archived: true, updatedAt: `2026-10-0${day}T00:00:00.000Z` }) as Chat;
  const live = { ...chat("live", "codex", "idle"), workspaceId: "w1", archived: false } as Chat;
  const chats = [archived("a", "w1", 1), archived("b", "w1", 2), archived("c", "w2", 3), live];
  const fake = fakeApi({
    route: "settings",
    agents: [{ id: "codex", name: "Codex", enabled: true }],
    workspaces: [
      { id: "w1", name: "Alpha", path: "/alpha", position: 0 },
      { id: "w2", name: "Beta", path: "/beta", position: 1 },
    ],
    chats,
  });
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    await fake.click("nav-archived");
    // Each workspace's chats, the most recently archived first; a chat that is not archived is not listed.
    const order = ["Alpha", "restore-b", "restore-a", "Beta", "restore-c"].map((mark) => fake.trees().indexOf(mark));
    assert.ok(order.every((at, n) => at > (order[n - 1] ?? -1)), `in order: ${order}`);
    assert.ok(!fake.has("restore-live"));
    assert.ok(fake.trees().includes("Codex · Archived"));

    await fake.click("restore-a");
    assert.deepEqual(fake.hostCalls.at(-1), { method: "host/chats.update", params: { chatId: "a", archived: false } });
    assert.ok(!fake.has("restore-a"));

    // Delete asks first; Cancel deletes nothing.
    await fake.click("delete-b");
    assert.ok(fake.trees().includes("Delete “B”? This cannot be undone."));
    await fake.click("delete-ask-cancel");
    assert.ok(!fake.has("delete-ask"));
    assert.ok(!fake.hostCalls.some((call) => call.method === "host/chats.delete"));
    await fake.click("delete-b");
    await fake.click("delete-ask-confirm");
    assert.deepEqual(fake.hostCalls.at(-1), { method: "host/chats.delete", params: { chatId: "b" } });
    assert.ok(!fake.has("delete-b") && !fake.has("delete-ask"));

    // A failure says so, and the chat stays listed.
    fake.fail("host/chats.update");
    await fake.click("restore-c");
    assert.deepEqual(fake.notices, ["Could not restore “C”: Test service is unavailable"]);
    assert.ok(fake.has("restore-c"));
    fake.fail(null);

    // A chat archived elsewhere joins the list, and one brought back elsewhere leaves it.
    await fake.emit({ event: "chat_changed", chat: { ...live, archived: true, updatedAt: "2026-10-05T00:00:00.000Z" } });
    assert.ok(fake.has("restore-live"));
    await fake.emit({ event: "chat_changed", chat: { ...archived("c", "w2", 3), archived: false } });
    assert.ok(!fake.has("restore-c"));
    assert.ok(fake.has("restore-live"));
  } finally {
    await dispose();
  }
});

test("Archived Chats says when there are none", async () => {
  const fake = fakeApi({ route: "settings", workspaces: [{ id: "w1", name: "Alpha", path: "/alpha", position: 0 }], chats: [] });
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    await fake.click("nav-archived");
    assert.ok(fake.trees().includes("No archived chats."));
  } finally {
    await dispose();
  }
});

// --- regressions from the settings scan ----------------------------------------

test("Assign… on a row that already records keeps the recorder, and the key shows as key caps", async () => {
  const fake = fakeApi({ route: "settings" });
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    await fake.click("nav-keys");
    await fake.click("assign-b-close");
    assert.ok(fake.trees().includes("Press the keys…"));
    // Assign… stays on screen while its row records; pressing it again starts over.
    await fake.click("assign-b-close");
    assert.ok(fake.trees().includes("Press the keys…"), "the recorder is still open");
    await fake.pressKey("shift-cmd-k", "⇧⌘K");
    assert.ok(fake.has("save-key-b-close"), "the key pressed after Assign… is recorded");
    assert.ok(fake.trees().includes("⇧⌘K") && !fake.trees().includes("shift-cmd-k"), "as key caps");
  } finally {
    await dispose();
  }
});

test("a first load that fails says why and loads again on Try again", async () => {
  const fake = fakeApi({ route: "settings" });
  fake.fail("host/settings.get");
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    assert.ok(fake.trees().includes("Settings could not load"));
    assert.ok(fake.trees().includes("Test service is unavailable"));
    fake.fail(null);
    await fake.click("settings-retry");
    assert.ok(fake.has("appearance") && !fake.has("settings-retry"));
  } finally {
    await dispose();
  }
});

test("Archived Chats says why a read failed and reads again on Try again", async () => {
  const fake = fakeApi({ route: "settings", workspaces: [{ id: "w1", name: "Alpha", path: "/alpha", position: 0 }], chats: [] });
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    fake.fail("host/chats.list");
    await fake.click("nav-archived");
    assert.ok(fake.trees().includes("Could not read the archived chats"));
    fake.fail(null);
    await fake.click("archived-retry");
    assert.ok(fake.trees().includes("No archived chats.") && !fake.has("archived-retry"));
  } finally {
    await dispose();
  }
});

test("Import sessions asks only the agents that can list their sessions now", async () => {
  const signedOut: AgentEntry = { ...available, id: "signed-out", name: "Signed Out", status: { state: "auth_required" } };
  const noList: AgentEntry = { ...available, id: "no-list", name: "No List", capabilities: { sessionList: false } };
  const fake = fakeApi({ route: "settings", agents: [available, signedOut, noList], workspaces: [projectWorkspace], sessions: { "project/test-agent": ["one"] } });
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    await fake.click("import-sessions");
    const asked = fake.hostCalls.filter((c) => c.method === "host/chats.import").map((c) => (c.params as { agentId: string }).agentId);
    assert.deepEqual(asked, ["test-agent"]);
    assert.deepEqual(fake.notices, ["Imported 1 sessions."]);
  } finally {
    await dispose();
  }
});

test("a refused agent switch says what failed in words", async () => {
  const fake = fakeApi({ route: "settings", agents: [available] });
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    await fake.click("nav-agents");
    fake.fail("host/agents.set_enabled");
    await fake.change("agent-test-agent", false);
    assert.deepEqual(fake.notices, ["Could not turn off Test Agent: Test service is unavailable"]);
    assert.equal(fake.node("agent-test-agent").checked, true);
  } finally {
    await dispose();
  }
});

test("Check now stays while an update is known, and a page before the first check says so", async () => {
  const fake = fakeApi({ route: "settings", updates: { enabled: true, appVersion: "1.0.0", lastChecked: null, appUpdate: { version: "1.1.0", releaseNotes: null } } });
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    await fake.click("nav-updates");
    assert.ok(fake.has("check-updates") && fake.has("install-app"));
    assert.ok(fake.trees().includes("Not checked yet.") && !fake.trees().includes("Checked never"));
  } finally {
    await dispose();
  }
});

test("each rule file has its own switch, and a plugin turned off before keeps its other files off", async () => {
  // Settings from before rules were switched per file turn the whole plugin off.
  const rule = (file: string) => ({ plugin: "style", file, text: `${file} text`, enabled: false });
  const fake = fakeApi({ route: "settings", disabledRules: ["style"], tools: { mode: "code", tools: [], rules: [rule("a.md"), rule("b.md")] } });
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    await fake.click("nav-tools");
    assert.ok(fake.has("rules-style-a.md") && fake.has("rules-style-b.md") && !fake.has("rules-style"));
    await fake.change("rules-style-a.md", true);
    const update = fake.hostCalls.findLast((c) => c.method === "host/settings.update")?.params as { tools: { disabledRules: string[] } };
    assert.deepEqual(update.tools.disabledRules, ["style/b.md"], "only the file turned on comes back on");
  } finally {
    await dispose();
  }
});

test("Start without a ready agent keeps the saved changes for the next run of the guide", async () => {
  const signedOut: AgentEntry = { ...available, status: { state: "auth_required" } };
  const fake = fakeApi({ progress: { done: false, step: 5, workspaceId: "plugins", saved: ["Show a word count"] }, agents: [signedOut], workspaces: [pluginsWorkspace] });
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    assert.ok(fake.trees().includes("1 change kept until an agent is ready"));
    await fake.click("onboarding-next");
    assert.equal(fake.state().route, "chat");
    assert.deepEqual((fake.progress() as { saved: string[] }).saved, ["Show a word count"]);
    assert.ok(fake.notices.some((n) => n.startsWith("Your saved change waits for a ready agent.")));
  } finally {
    await dispose();
  }
});

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.