Official

chat

Built-in chat 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/chat@0.2.7

Permissions in 0.2.7

  • Control chats chats.controlHighCreates chats, sends prompts and cancels runs.Send prompts, answer agent questions, and create, change, fork, revert, stop and group chats
  • Run other plugins' commands commands.runHighRuns commands of other plugins.Run the sidebar's New chat command from the title bar
  • Read chats chats.readMediumReads your transcripts and chat lists.Show workspaces, tasks, chats and transcripts, and follow them as agents work
  • Read files fs.readMediumReads files in the listed places.Suggest workspace files for @ mentionsPlaces: the open workspace
  • Show panels ui.slotsAlways grantedShows views in the listed parts of the window.Draw the chat grid, the title bar, and the Session panel with its rail buttonSlots: centertitlerailright

Files

composer-scheduler.test.ts78.9 KB
// Composer intent, structured capture, failure retention and truthful inline UI.
import assert from "node:assert/strict";
import test from "node:test";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import type { ComposerDraft, ContentBlock, HostMethods, KernelMethods } from "divergence";
import { DraftLedger, InputLedger, held, settledRun, withController } from "./testing.ts";
import {
  acceptPicked,
  onChange,
  onSubmit,
  pickerKey,
  send,
  submitDraft,
  queuePrompt,
  keepNewImages,
  attachFiles,
  changeAgent,
  onPasteFiles,
  takeBack,
} from "./composer.ts";
import { nodes, chat } from "./ui-for-tests.test.ts";
import { renderPending, renderLimit } from "./views/pending.tsx";
import { renderPane } from "./views/panes.tsx";
import { renderComposer } from "./views/composer.tsx";
import { renderSettings } from "./settings.tsx";
import { autoSend, policyOf } from "./scheduler-policy.ts";
import type { ChatView } from "./controller.ts";
import { HostCallFailed } from "divergence/effect";
import { unknownMethod } from "./scheduler.ts";

const image = { id: "image", name: "diagram.png", bytes: 100, mimeType: "image/png", width: 20, height: 20 };
for (const queue of [false, true]) {
  for (const text of ["Read README.md", ""]) {
    test(`external draft submission loads unopened content and preserves images (queue=${queue}, text=${!!text})`, async (ctx) => {
      const ledger = new DraftLedger();
      delete ledger.snapshots.c1.sessionId;
      const blocks: ContentBlock[] = [
        ...(text ? [{ type: "text" as const, text }] : []),
        { type: "image", data: "saved-image-bytes", mimeType: "image/png" },
      ];
      ledger.draft = { chatId: "c1", revision: 1, blocks };
      const call = ledger.call.bind(ledger);
      ledger.call = async (method, params) => {
        const chatId = (params as { chatId?: string }).chatId;
        if (method === "host/workspaces.list") return { workspaces: [] };
        if (method === "host/agents.all") return { agents: [] };
        if (method === "host/chats.prepare") return {};
        if (method === "host/security.pending") return { requests: [] };
        if (method === "host/drafts.get" && chatId === "other")
          return { chatId, revision: 0, blocks: [] };
        if (method === "host/chats.transcript" && chatId === "other")
          return { items: [], pendingApprovals: [], pendingQuestions: [], plan: null, usage: {}, running: true };
        return call(method, params);
      };
      await withController(ledger, (c) =>
        Effect.gen(function* () {
          delete c.state.composers.c1;
          delete c.state.chats.c1;
          ctx.mock.method(c.api.app, "state", () => ({ route: "chat", chatId: "other" }));
          c.state.chats.other = chat({ id: "other", status: "running", sessionId: "other-session" });
          yield* submitDraft(c, "c1", queue);
          assert.equal(c.api.app.state().chatId, "other");
          if (queue) {
            assert.deepEqual(c.state.chatQueue, [{ chatId: "c1" }]);
            assert.equal(c.composer("c1").text, text, "queued drafts remain editable");
            assert.deepEqual(ledger.draft.blocks, blocks);
            assert.deepEqual(ledger.deliveries, []);
            c.state.chats.other = { ...c.state.chats.other, status: "idle" };
            yield* c.pumpChatQueue();
          }
          assert.equal(c.composer("c1").text, "");
          assert.deepEqual(ledger.snapshots.c1.inputs[0].blocks, blocks);
          assert.equal(ledger.snapshots.c1.inputs[0].intent, "send");
          assert.equal(ledger.deliveries.length, 1);
          assert.deepEqual(c.state.chatQueue, []);
          assert.deepEqual(ledger.draft.blocks, []);
          assert.deepEqual(ledger.notices, []);
        }),
      );
    });
  }
}
test("a dropped path with a space goes as one whole file reference", async () => {
  const ledger = new InputLedger();
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      c.composer("c1").loading = false;
      yield* attachFiles(c, "c1", ["/Users/me/My Docs/spec.md"]);
      yield* send(c, "c1");
      assert.deepEqual(ledger.deliveries.map((d) => d.blocks), [[{ type: "file_ref", path: "/Users/me/My Docs/spec.md" }]]);
    }),
  );
});

test("a fresh draft that switches to an agent that cannot read images lets its image chips go, and says so", async () => {
  class UpdateLedger extends InputLedger {
    override async call(method: string, raw: unknown): Promise<unknown> {
      if (method !== "host/chats.update") return super.call(method, raw);
      const { chatId, agentId } = raw as { chatId: string; agentId: string };
      return chat({ id: chatId, agentId });
    }
  }
  const ledger = new UpdateLedger();
  delete ledger.snapshots.c1.sessionId;
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      c.state.chats.c1 = chat({ id: "c1" });
      c.state.agents.blind = { id: "blind", name: "Blind", capabilities: { images: false } };
      c.composer("c1").attachments = [image];
      yield* changeAgent(c, "c1", "blind");
      assert.equal(c.state.chats.c1.agentId, "blind");
      assert.deepEqual(c.composer("c1").attachments, []);
      assert.deepEqual(ledger.forgotten, ["image"]);
      assert.deepEqual(ledger.notices, ["Blind cannot read images"]);
    }),
  );
});

test("an external failed send retains the draft and an empty draft sends nothing", async () => {
  const ledger = new DraftLedger();
  ledger.draft = { chatId: "c1", revision: 1, blocks: [{ type: "text", text: "Keep this request" }] };
  ledger.rejectEnqueue = true;
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      yield* submitDraft(c, "c1", false);
      assert.equal(c.composer("c1").text, "Keep this request");
      assert.ok(ledger.notices.some((notice) => notice.includes("disk unavailable")));
      assert.deepEqual(ledger.deliveries, []);
      c.composer("c1").text = "";
      ledger.rejectEnqueue = false;
      yield* submitDraft(c, "c1", false);
      assert.deepEqual(ledger.deliveries, []);
      assert.deepEqual(ledger.snapshots.c1.inputs, []);
    }),
  );
});
// A started chat handed to another agent goes on in a new chat beside it
// (specs/tasks-and-splits/02): the new chat takes the prompt box's text and
// the screen; the original keeps its agent and its own chat state.
test("handing a started chat to another agent moves its prompt text to the new chat beside it", async () => {
  const ledger = new DraftLedger();
  const call = ledger.call.bind(ledger);
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      let asked: unknown;
      ledger.call = async (method, params) => {
        if (method === "host/chats.context_policy") return { provider: c.api.plugin, available: true };
        if (method === "host/chats.handoff") {
          asked = params;
          // The host moves the draft's text to the new chat and clears the original's.
          const text = ledger.draft.blocks;
          ledger.draft = { chatId: "c1", revision: ledger.draft.revision + 1, blocks: [] };
          return {
            chat: { ...c.state.chats.c1, id: "c2", agentId: "destination" },
            snapshot: { ...structuredClone(ledger.snapshots.c1), chatId: "c2" },
            draft: { chatId: "c2", revision: 1, blocks: text },
            recovered: false,
          };
        }
        if (method === "host/agents.list_options" || method === "host/chats.list_options") return { options: [] };
        if (method === "host/agents.commands") return { commands: [] };
        if (method === "host/agents.skills") return { skills: [] };
        return call(method, params);
      };
      c.composer("c1").text = "Carry this over";
      yield* changeAgent(c, "c1", "destination");
      assert.deepEqual(asked, { chatId: "c1", agentId: "destination", newChat: true });
      assert.equal(c.state.chats.c2?.agentId, "destination");
      assert.notEqual(c.state.chats.c1.agentId, "destination", "the original keeps its agent");
      assert.equal(c.composer("c2").text, "Carry this over");
      assert.equal(c.composer("c1").text, "");
    }),
  );
});

for (const failure of ["draft", "retirement"] as const)
  test(`restoring durable recovery survives ${failure} persistence failure and reload`, async () => {
    const ledger = new DraftLedger();
    ledger.draft = { chatId: "c1", revision: 5, blocks: [] };
    ledger.storage["draft-recoveries:c1"] = [{ id: "recovery", text: "Newer local typing", blocks: [] }];
    const call = ledger.call.bind(ledger);
    await withController(ledger, (c) =>
      Effect.gen(function* () {
        yield* c.drafts.load("c1");
        const actions: Effect.Effect<unknown, unknown>[] = [];
        const view: ChatView = {
          controller: c,
          ctx: {
            state: {},
            set: () => {},
            app: { route: "chat", chatId: "c1" },
            plugin: "chat",
            update() {},
            run: (effect) => {
              actions.push(effect as Effect.Effect<unknown, unknown>);
            },
          },
        };
        const restore = nodes(renderComposer(view, c.state.chats.c1)).find((node) => node.id === "recover-recovery");
        assert.ok(restore);
        restore.onClick();
        yield* Effect.all(actions);
        ledger.call = async (method, params) => {
          if (failure === "draft" && method === "host/drafts.update") throw new Error("draft storage unavailable");
          if (
            failure === "retirement" &&
            method === "host/storage.set" &&
            (params as { key: string }).key === "draft-recoveries:c1"
          ) {
            assert.deepEqual(
              ledger.draft.blocks,
              [{ type: "text", text: "Newer local typing" }],
              "the draft must be durable before retiring its recovery",
            );
            throw new Error("recovery storage unavailable");
          }
          return call(method, params);
        };
        yield* c.drafts.save("c1").pipe(Effect.result);
      }),
    );
    ledger.call = call;
    await withController(ledger, (c) =>
      Effect.gen(function* () {
        yield* c.drafts.load("c1");
        assert.ok(
          c.composer("c1").text === "Newer local typing" ||
            c.composer("c1").recovered?.some((draft) => draft.text === "Newer local typing"),
          "reload must retain at least one durable copy",
        );
        if (failure === "retirement") assert.equal(c.composer("c1").text, "Newer local typing");
      }),
    );
  });

test("lost enqueue reply retry never recaptures an already queued submission", async () => {
  const ledger = new InputLedger();
  let draft: ComposerDraft = { chatId: "c1", revision: 0, blocks: [] },
    lost = true;
  const call = ledger.call.bind(ledger);
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      ledger.call = async (method, raw) => {
        const p = raw as { revision: number; blocks: ContentBlock[]; id: string; intent: "queue" };
        if (method === "host/drafts.get") return structuredClone(draft);
        if (method === "host/drafts.update") {
          assert.equal(p.revision, draft.revision);
          draft = { ...draft, revision: draft.revision + 1, blocks: structuredClone(p.blocks) };
          return structuredClone(draft);
        }
        if (method === "host/drafts.enqueue") {
          if (ledger.snapshots.c1.inputs.some((i) => i.id === p.id))
            return { snapshot: structuredClone(ledger.snapshots.c1), draft: structuredClone(draft) };
          assert.equal(p.revision, draft.revision);
          const snapshot = await call("host/inputs.enqueue", {
            chatId: "c1",
            id: p.id,
            intent: p.intent,
            blocks: draft.blocks,
          });
          draft = { chatId: "c1", revision: draft.revision + 1, blocks: [] };
          c.drafts.observe(structuredClone(draft));
          if (lost) {
            lost = false;
            throw new Error("enqueue reply lost");
          }
          return { snapshot, draft: structuredClone(draft) };
        }
        return call(method, raw);
      };
      c.composer("c1").text = "Original request";
      yield* queuePrompt(c, "c1");
      assert.equal(c.composer("c1").text, "Original request");
      const id = c.composer("c1").submission!.id;
      yield* queuePrompt(c, "c1");
      yield* c.drafts.save("c1");
      assert.equal(c.composer("c1").text, "");
      assert.deepEqual(
        ledger.snapshots.c1.inputs.map((i) => i.id),
        [id],
      );
      assert.deepEqual(draft.blocks, [], "reload must not resurrect submitted text");
    }),
  );
});

test("draft mention round trips keep editable text and expand transferred instructions once", async (ctx) => {
  const ledger = new InputLedger();
  let draft: ComposerDraft = { chatId: "c1", revision: 0, blocks: [] };
  const call = ledger.call.bind(ledger);
  ledger.call = async (method, raw) => {
    if (method === "host/drafts.get") return structuredClone(draft);
    if (method === "host/drafts.update") {
      draft = {
        ...draft,
        revision: draft.revision + 1,
        blocks: structuredClone((raw as { blocks: ContentBlock[] }).blocks),
      };
      return structuredClone(draft);
    }
    return call(method, raw);
  };
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      ctx.mock.method(c.api.mentions, "list", () => [
        { plugin: "test", id: "reviewer", token: "reviewer", label: "Reviewer", prompt: "Use review agent for {part}" },
      ]);
      c.composer("c1").text = "@reviewer Inspect this";
      yield* c.drafts.save("c1");
      assert.deepEqual(draft.blocks, [{ type: "text", text: "@reviewer Inspect this" }]);
      c.drafts.apply(draft);
      assert.equal(c.composer("c1").text, "@reviewer Inspect this");
      const queued = [
        { type: "text", text: "@reviewer Inspect this" },
        { type: "text", text: "\n\nUse review agent for Inspect this" },
      ] satisfies ContentBlock[];
      c.drafts.apply({
        ...draft,
        revision: draft.revision + 1,
        inputId: "queue-head",
        blocks: queued,
        composition: { text: "@reviewer Inspect this", generated: [0, 1] },
      });
      assert.equal(c.composer("c1").text, "@reviewer Inspect this");
      // This fixture uses the old-host enqueue path but real composition expansion.
      c.drafts.available = false;
      yield* queuePrompt(c, "c1");
      assert.deepEqual(ledger.snapshots.c1.inputs[0].blocks, queued);
    }),
  );
});

for (const edit of ["@reviewer NEW TASK", "@tester NEW TASK", "NEW TASK"])
  test(`failed enqueue capture reload rebuilds derived mentions: ${edit}`, async (ctx) => {
    const ledger = new DraftLedger();
    const mentions = [
      { plugin: "test", id: "reviewer", token: "reviewer", label: "Reviewer", prompt: "Review {part}" },
      { plugin: "test", id: "tester", token: "tester", label: "Tester", prompt: "Test {part}" },
    ];
    ledger.rejectEnqueue = true;
    await withController(ledger, (c) =>
      Effect.gen(function* () {
        ctx.mock.method(c.api.mentions, "list", () => mentions);
        c.composer("c1").text = "@reviewer OLD TASK";
        yield* c.drafts.save("c1");
        yield* queuePrompt(c, "c1");
        assert.equal(ledger.draft.composition?.text, "@reviewer OLD TASK");
      }),
    );
    ledger.rejectEnqueue = false;
    await withController(ledger, (c) =>
      Effect.gen(function* () {
        ctx.mock.method(c.api.mentions, "list", () => mentions);
        yield* c.drafts.load("c1");
        assert.equal(c.composer("c1").text, "@reviewer OLD TASK");
        yield* onChange(c, "c1", edit);
        yield* queuePrompt(c, "c1");
        const expected = edit.startsWith("@reviewer")
          ? "\n\nReview NEW TASK"
          : edit.startsWith("@tester")
            ? "\n\nTest NEW TASK"
            : undefined;
        assert.deepEqual(ledger.snapshots.c1.inputs[0].blocks, [
          { type: "text", text: edit },
          ...(expected ? [{ type: "text", text: expected }] : []),
        ]);
      }),
    );
  });

for (const edit of [
  "@reviewer OLD TASK @src/old.ts",
  "@tester NEW TASK",
  "NEW TASK",
  "$inspect OLD TASK",
  "without skill",
])
  test(`queue draft round trip preserves opaque blocks and rebuilds only provenance: ${edit}`, async (ctx) => {
    const ledger = new DraftLedger();
    const opaque: ContentBlock[] = [
      { type: "text", text: "Opaque external instructions" },
      { type: "file_ref", path: "src/opaque.ts" },
      { type: "skill", name: "opaque", input: "unchanged" },
    ];
    await withController(ledger, (c) =>
      Effect.gen(function* () {
        ctx.mock.method(c.api.mentions, "list", () => [
          { plugin: "test", id: "reviewer", token: "reviewer", label: "Reviewer", prompt: "Review {part}" },
          { plugin: "test", id: "tester", token: "tester", label: "Tester", prompt: "Test {part}" },
        ]);
        c.composer("c1").skills = [{ name: "inspect" }];
        c.composer("c1").text =
          edit.includes("skill") || edit.startsWith("$") ? "$inspect OLD TASK" : "@reviewer OLD TASK @src/old.ts";
        c.composer("c1").carriedBlocks = opaque;
        yield* queuePrompt(c, "c1");
        const queued = ledger.snapshots.c1.inputs[0];
        assert.ok(queued.composition);
        const moved = yield* c.host.call("host/inputs.to_draft", {
          chatId: "c1",
          inputId: queued.id,
          revision: ledger.snapshots.c1.revision,
          draftRevision: ledger.draft.revision,
        });
        c.drafts.apply(moved.draft);
        assert.deepEqual(c.composer("c1").carriedBlocks, opaque);
        yield* onChange(c, "c1", edit);
        yield* queuePrompt(c, "c1");
        const blocks = ledger.snapshots.c1.inputs[0].blocks;
        assert.deepEqual(blocks.slice(-opaque.length), opaque);
        const derived = blocks.slice(0, -opaque.length);
        if (edit === "@reviewer OLD TASK @src/old.ts") assert.deepEqual(blocks, queued.blocks);
        else if (edit === "@tester NEW TASK")
          assert.deepEqual(derived, [
            { type: "text", text: edit },
            { type: "text", text: "\n\nTest NEW TASK" },
          ]);
        else if (edit.startsWith("$"))
          assert.deepEqual(derived, [{ type: "skill", name: "inspect", input: "OLD TASK" }]);
        else assert.deepEqual(derived, [{ type: "text", text: edit }]);
      }),
    );
  });

test("legacy opaque text/files/skills are never guessed to be generated", async () => {
  const ledger = new DraftLedger();
  const blocks: ContentBlock[] = [
    { type: "text", text: "Editable" },
    { type: "text", text: "Opaque" },
    { type: "file_ref", path: "old.ts" },
    { type: "skill", name: "external" },
  ];
  ledger.draft = { chatId: "c1", revision: 1, blocks };
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      yield* c.drafts.load("c1");
      yield* onChange(c, "c1", "Changed");
      yield* queuePrompt(c, "c1");
      assert.deepEqual(ledger.snapshots.c1.inputs[0].blocks, [{ type: "text", text: "Changed" }, ...blocks.slice(1)]);
    }),
  );
});

for (const newer of [false, true])
  test(`lost enqueue without a draft event retries once and retains newer typing (${newer})`, async () => {
    const ledger = new DraftLedger();
    ledger.lostEnqueueReply = true;
    await withController(ledger, (c) =>
      Effect.gen(function* () {
        const composer = c.composer("c1");
        composer.text = "Original request";
        ledger.beforeEnqueue = async () => {
          if (newer) {
            composer.text = "Newer draft";
            composer.editVersion = (composer.editVersion ?? 0) + 1;
          }
        };
        yield* queuePrompt(c, "c1");
        ledger.beforeEnqueue = undefined;
        const queued = ledger.snapshots.c1.inputs[0];
        assert.deepEqual(queued.blocks, [{ type: "text", text: "Original request" }]);
        assert.equal(ledger.draft.composition?.text, newer ? "Newer draft" : "Original request");
        if (newer) {
          assert.equal(composer.recovered?.[0].text, "Original request");
          // The idempotent retry branch submits the existing id without capture.
          const later = structuredClone(ledger.draft);
          yield* c.scheduler.enqueue("c1", queued.id, queued.blocks, "queue");
          assert.deepEqual(ledger.draft, later);
          assert.equal(composer.text, "Newer draft");
        } else yield* queuePrompt(c, "c1");
        assert.equal(ledger.snapshots.c1.inputs.length, 1);
        yield* c.drafts.save("c1");
        assert.deepEqual(ledger.draft.blocks, newer ? [{ type: "text", text: "Newer draft" }] : []);
        yield* c.scheduler.manualDispatch("c1", queued.id, ledger.snapshots.c1.revision);
        assert.equal(ledger.deliveries.length, 1);
        assert.equal(ledger.deliveries[0].inputId, queued.id);
      }),
    );
  });

test("held edit UI uses raw composition and regenerates tags without dropping opaque text", async (ctx) => {
  const ledger = new DraftLedger();
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      ctx.mock.method(c.api.mentions, "list", () => [
        { plugin: "test", id: "reviewer", token: "reviewer", label: "Reviewer", prompt: "Review {part}" },
        { plugin: "test", id: "tester", token: "tester", label: "Tester", prompt: "Test {part}" },
      ]);
      const composer = c.composer("c1");
      composer.text = "@reviewer OLD @src/old.ts";
      composer.carriedBlocks = [{ type: "text", text: "Opaque" }];
      yield* queuePrompt(c, "c1");
      const input = ledger.snapshots.c1.inputs[0];
      const actions: Effect.Effect<unknown, unknown>[] = [];
      const view: ChatView = {
        controller: c,
        ctx: {
          state: {},
          set: () => {},
          app: { route: "chat", chatId: "c1" },
          plugin: "chat",
          update() {},
          run: (effect) => {
            actions.push(effect as Effect.Effect<unknown, unknown>);
          },
        },
      };
      const rows = () => nodes(renderPending(view, c.state.chats.c1));
      rows()
        .find((node) => node.id === `edit-input-${input.id}`)
        ?.onClick();
      assert.equal(composer.pendingEdit?.text, "@reviewer OLD @src/old.ts");
      rows()
        .find((node) => node.id === `edit-pending-${input.id}`)
        ?.onChange({ value: "@tester NEW" });
      rows()
        .find((node) => node.id === `save-pending-${input.id}`)
        ?.onClick();
      yield* Effect.all(actions);
      assert.deepEqual(ledger.snapshots.c1.inputs[0].blocks, [
        { type: "text", text: "@tester NEW" },
        { type: "text", text: "\n\nTest NEW" },
        { type: "text", text: "Opaque" },
      ]);
      assert.equal(ledger.snapshots.c1.inputs[0].composition?.text, "@tester NEW");
    }),
  );
});

test("established agent switching requires the selected policy, not only draft support", async () => {
  for (const [provider, available, stockEnabled, permitted] of [
    ["stock", true, true, true],
    ["stock", true, false, false],
    ["custom", true, false, true],
    ["custom", false, true, false],
  ] as const) {
    const ledger = new InputLedger();
    ledger.settings.handoffEnabled = stockEnabled;
    await withController(ledger, (c) =>
      Effect.gen(function* () {
        c.drafts.available = true;
        c.contextPolicy = { provider: provider === "stock" ? c.api.plugin : "replacement", available };
        c.state.chats.c1 = { ...c.state.chats.c1, sessionId: undefined };
        c.transcript("c1").snapshot = { kind: "ready" };
        c.transcript("c1").items = [{ id: "existing", role: "assistant", text: "Historical response" }];
        c.state.agentList = [
          { id: "agent", name: "Agent" },
          { id: "other", name: "Other" },
        ];
        const view: ChatView = {
          controller: c,
          ctx: { state: {}, set: () => {}, app: { route: "chat", chatId: "c1" }, plugin: "chat", update() {}, run() {} },
        };
        const picker = nodes(renderPane(view, "c1")).find((node) => node.id === "agent-c1");
        assert.ok(picker);
        assert.equal(Boolean(picker.disabled), !permitted);
      }),
    );
  }
});

test("authoritative empty drafts suppress stale legacy unsent text in either startup ordering", async () => {
  for (const structuredFirst of [true, false]) {
    const ledger = new InputLedger();
    const call = ledger.call.bind(ledger);
    ledger.call = async (method, params) => {
      if (method === "host/drafts.get") return { chatId: "c1", revision: 7, blocks: [] };
      if (method === "host/storage.get" && (params as { key: string }).key === "unsent")
        return { value: { c1: "Already submitted before the crash" } };
      return call(method, params);
    };
    await withController(ledger, (c) =>
      Effect.gen(function* () {
        if (structuredFirst) yield* c.drafts.load("c1");
        yield* c.restoreUnsent();
        if (!structuredFirst) yield* c.drafts.load("c1");
        assert.equal(c.composer("c1").text, "");
      }),
    );
  }
});

test("draft and existing Send clear and show the captured prompt before any host acknowledgement", async () => {
  for (const draft of [true, false]) {
    const ledger = new InputLedger();
    await withController(ledger, (c) =>
      Effect.gen(function* () {
        c.state.chats.c1 = chat({ id: "c1", sessionId: draft ? undefined : "existing" });
        const transcript = c.transcript("c1");
        transcript.snapshot = { kind: "ready" };
        if (!draft) transcript.items = [{ id: "earlier", role: "assistant", text: "Previous answer" }];
        c.composer("c1").text = "Immediate outgoing message";
        const view: ChatView = {
          controller: c,
          ctx: { state: {}, set: () => {}, app: { route: "chat", chatId: "c1" }, plugin: "chat", update() {}, run() {} },
        };
        const frames: ReturnType<typeof nodes>[] = [];
        const inspect = () => {
          frames.push(nodes(renderPane(view, "c1")));
        };
        const call = ledger.call.bind(ledger);
        ledger.call = async (method, params) => {
          if (method === "host/inputs.list") inspect();
          return call(method, params);
        };
        ledger.beforeEnqueue = async () => inspect();
        ledger.afterClaim = async (snapshot) => {
          c.scheduler.receive(snapshot);
          inspect();
        };
        yield* send(c, "c1");
        assert.ok(frames.length >= 3);
        for (const tree of frames) {
          assert.equal(tree.find((node) => node.id === "prompt-c1")?.value, "", "composer clears before persistence");
          assert.equal(
            tree.filter((node) => node.text === "Immediate outgoing message").length,
            1,
            "one visible outgoing copy",
          );
          assert.ok(!tree.some((node) => node.type === "empty"), "no landing/loading gap after Send");
          if (!draft) assert.ok(tree.some((node) => node.text === "Previous answer"));
        }
      }),
    );
  }
});

test("Queue and Steer show one local pending card before acknowledgment, then hand it to the host", async () => {
  for (const intent of ["queue", "steer"] as const) {
    const ledger = new DraftLedger();
    ledger.mutate("c1", (snapshot) => {
      snapshot.running = true;
    });
    await withController(ledger, (c) =>
      Effect.gen(function* () {
        c.state.chats.c1 = { ...c.state.chats.c1, status: "running" };
        if (intent === "queue") delete c.scheduler.snapshots.c1;
        const composer = c.composer("c1");
        composer.text = "Keep the original file";
        composer.attachments = [image];
        const view: ChatView = {
          controller: c,
          ctx: { state: {}, set: () => {}, app: { route: "chat", chatId: "c1" }, plugin: "chat", update() {}, run() {} },
        };
        let initial: ReturnType<typeof nodes> = [];
        c.state.panes.c1 = {
          chatId: "c1",
          view: {
            id: 1,
            update() {
              if (!initial.length) initial = nodes(renderComposer(view, c.state.chats.c1));
            },
            remove() {},
          },
        };
        const entered = Promise.withResolvers<void>(),
          gate = Promise.withResolvers<void>();
        ledger.beforeEnqueue = async () => {
          entered.resolve();
          await gate.promise;
        };
        const submitting = yield* Effect.forkChild(intent === "queue" ? queuePrompt(c, "c1") : send(c, "c1"));
        yield* Effect.promise(() => entered.promise);
        try {
          assert.equal(initial.find((node) => node.id === "prompt-c1")?.value, "");
          assert.equal(initial.filter((node) => node.text === "Keep the original file").length, 1);
          assert.ok(initial.some((node) => node.text === (intent === "queue" ? "Queued" : "Steer")));
          assert.ok(initial.some((node) => node.text === "Saving"));
          assert.ok(initial.some((node) => node.text === "Image · image/png"));
          assert.ok(!initial.some((node) => node.text === "Submitting…"));
          assert.equal(
            ledger.snapshots.c1.inputs.length,
            0,
            "local presentation must not fabricate host acknowledgment",
          );
          const pending = nodes(renderPending(view, c.state.chats.c1));
          assert.ok(
            !pending.some((node) => node.type === "button"),
            "no revision-authorized actions before acknowledgment",
          );
        } finally {
          gate.resolve();
        }
        yield* Fiber.join(submitting);
        assert.equal(ledger.snapshots.c1.inputs.length, 1);
        assert.equal(ledger.snapshots.c1.inputs[0].intent, intent);
        assert.equal(composer.outgoing, undefined);
        const canonical = nodes(renderPending(view, c.state.chats.c1));
        assert.equal(canonical.filter((node) => node.text === "Keep the original file").length, 1);
        assert.ok(!canonical.some((node) => node.text === "Saving" || node.text?.endsWith("· saving")));
        assert.equal(ledger.deliveries.length, intent === "queue" ? 0 : 1);
      }),
    );
  }
});

test("a Steer appended to an existing reservation keeps one canonical card during delivery", async () => {
  const ledger = new InputLedger();
  ledger.mutate("c1", (snapshot) => {
    snapshot.running = true;
    snapshot.inputs = [held("reserved", { intent: "steer", blocks: [{ type: "text", text: "Keep alpha" }] })];
  });
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      c.state.chats.c1 = { ...c.state.chats.c1, status: "running" };
      c.composer("c1").text = "Also keep beta";
      const view: ChatView = {
        controller: c,
        ctx: { state: {}, set: () => {}, app: { route: "chat", chatId: "c1" }, plugin: "chat", update() {}, run() {} },
      };
      let during: ReturnType<typeof nodes> = [];
      ledger.afterClaim = async () => {
        during = nodes(renderComposer(view, c.state.chats.c1));
      };
      yield* send(c, "c1");
      assert.ok(during.some((node) => node.text === "Keep alpha\nAlso keep beta"));
      assert.ok(!during.some((node) => node.text === "Also keep beta" || node.text === "Saving"));
      assert.ok(!during.some((node) => node.text === "Submitting…"));
      assert.equal(ledger.deliveries.length, 1);
      assert.equal(ledger.deliveries[0].inputId, "reserved");
    }),
  );
});

test("a Steer still being delivered leaves the send button ready for the next prompt", async () => {
  const ledger = new InputLedger();
  ledger.mutate("c1", (snapshot) => {
    snapshot.running = true;
  });
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      c.state.chats.c1 = { ...c.state.chats.c1, status: "running" };
      const composer = c.composer("c1");
      composer.text = "Steer this way";
      const view: ChatView = {
        controller: c,
        ctx: { state: {}, set: () => {}, app: { route: "chat", chatId: "c1" }, plugin: "chat", update() {}, run() {} },
      };
      const claimed = Promise.withResolvers<void>(),
        gate = Promise.withResolvers<void>();
      ledger.afterClaim = async () => {
        claimed.resolve();
        await gate.promise;
      };
      const steering = yield* Effect.forkChild(send(c, "c1"));
      yield* Effect.promise(() => claimed.promise);
      try {
        composer.text = "And this too";
        const button = nodes(renderComposer(view, c.state.chats.c1)).find((node) => node.id === "send-c1");
        assert.equal(composer.submitting, false, "the acknowledged steer no longer holds the prompt box");
        assert.ok(button && !button.disabled, "typing again can send while the steer is delivered");
      } finally {
        gate.resolve();
      }
      yield* Fiber.join(steering);
      assert.equal(composer.text, "And this too");
    }),
  );
});

test("failed Queue withdraws its local card and recovers input before the host refresh completes", async () => {
  const ledger = new InputLedger();
  ledger.rejectEnqueue = true;
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      const composer = c.composer("c1");
      composer.text = "Recover queued text";
      composer.attachments = [image];
      const view: ChatView = {
        controller: c,
        ctx: { state: {}, set: () => {}, app: { route: "chat", chatId: "c1" }, plugin: "chat", update() {}, run() {} },
      };
      let latest: ReturnType<typeof nodes> = [];
      c.state.panes.c1 = {
        chatId: "c1",
        view: {
          id: 1,
          update() {
            latest = nodes(renderComposer(view, c.state.chats.c1));
          },
          remove() {},
        },
      };
      ledger.beforeEnqueue = () => Effect.runPromise(onChange(c, "c1", "Newer typing"));
      const entered = Promise.withResolvers<void>(),
        gate = Promise.withResolvers<void>();
      const call = ledger.call.bind(ledger);
      let reads = 0;
      ledger.call = async (method, params) => {
        if (method === "host/inputs.list" && ++reads === 2) {
          entered.resolve();
          await gate.promise;
        }
        return call(method, params);
      };
      const submitting = yield* Effect.forkChild(queuePrompt(c, "c1"));
      yield* Effect.promise(() => entered.promise);
      try {
        assert.equal(latest.find((node) => node.id === "prompt-c1")?.value, "Newer typing");
        assert.ok(ledger.notices.some((notice) => notice.includes("Input could not be submitted:")));
        assert.ok(
          !latest.some((node) => node.text?.includes("Input could not be submitted:")),
          "a toast, not chat text",
        );
        assert.ok(!latest.some((node) => node.text === "Queued · saving" || node.text === "Submitting…"));
        assert.equal(composer.outgoing, undefined);
        assert.equal(composer.recovered?.[0].text, "Recover queued text");
        assert.deepEqual(composer.recovered?.[0].attachments, [image]);
        assert.equal(ledger.snapshots.c1.inputs.length, 0);
      } finally {
        gate.resolve();
      }
      yield* Fiber.join(submitting);
      assert.deepEqual(ledger.forgotten, []);
    }),
  );
});

test("acknowledged Queue refreshes available controls before draft cleanup finishes", async () => {
  const ledger = new DraftLedger();
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      const composer = c.composer("c1");
      composer.text = "First queued request";
      const view: ChatView = {
        controller: c,
        ctx: { state: {}, set: () => {}, app: { route: "chat", chatId: "c1" }, plugin: "chat", update() {}, run() {} },
      };
      let latest: ReturnType<typeof nodes> = [];
      c.state.panes.c1 = {
        chatId: "c1",
        view: {
          id: 1,
          update() {
            latest = nodes(renderComposer(view, c.state.chats.c1));
          },
          remove() {},
        },
      };
      const entered = Promise.withResolvers<void>(),
        gate = Promise.withResolvers<void>();
      const call = ledger.call.bind(ledger);
      ledger.call = async (method, params) => {
        if (method === "host/drafts.update" && ledger.snapshots.c1.inputs.length) {
          entered.resolve();
          await gate.promise;
        }
        return call(method, params);
      };
      const submitting = yield* Effect.forkChild(queuePrompt(c, "c1"));
      yield* Effect.promise(() => entered.promise);
      try {
        assert.equal(composer.submitting, false);
        assert.equal(composer.outgoing, undefined);
        const queue = latest.find((node) => node.id === "queue-c1");
        assert.ok(queue && !queue.disabled, "the retained controls must not wait for cleanup");
        assert.equal(latest.filter((node) => node.text === "First queued request").length, 1);
        assert.ok(!latest.some((node) => node.text === "Queued · saving" || node.text === "Submitting…"));
      } finally {
        gate.resolve();
      }
      yield* Fiber.join(submitting);
    }),
  );
});

test("a fresh chat renders its composer while transcript hydration is outstanding", async () => {
  await withController(new InputLedger(), (c) =>
    Effect.sync(() => {
      c.state.chats.c1 = chat({ id: "c1", sessionId: undefined });
      const view: ChatView = {
        controller: c,
        ctx: { state: {}, set: () => {}, app: { route: "chat", chatId: "c1" }, plugin: "chat", update() {}, run() {} },
      };
      assert.ok(nodes(renderPane(view, "c1")).some((node) => node.id === "prompt-c1"));
      assert.equal(c.transcript("c1").snapshot.kind, "unread", "visible draft must not fabricate hydration completion");
    }),
  );
});

test("Alpha sends and non-prompt commands clear immediately without inventing a correlated user row", async () => {
  for (const alpha of [true, false]) {
    const ledger = new InputLedger();
    await withController(ledger, (c) =>
      Effect.gen(function* () {
        c.scheduler.available = !alpha;
        const text = alpha ? "Old host send" : "/no-prompt";
        c.composer("c1").text = text;
        c.transcript("c1").snapshot = { kind: "ready" };
        const view: ChatView = {
          controller: c,
          ctx: { state: {}, set: () => {}, app: { route: "chat", chatId: "c1" }, plugin: "chat", update() {}, run() {} },
        };
        let before: ReturnType<typeof nodes> | undefined;
        const call = ledger.call.bind(ledger);
        ledger.call = async (method, params) => {
          if (method === "host/chats.send") {
            before = nodes(renderPane(view, "c1"));
            return {};
          }
          return call(method, params);
        };
        ledger.beforeEnqueue = async () => {
          before = nodes(renderPane(view, "c1"));
        };
        yield* send(c, "c1");
        assert.ok(before);
        assert.equal(before.find((node) => node.id === "prompt-c1")?.value, "");
        assert.ok(before.some((node) => node.text === "Submitting…"));
        assert.ok(!before.some((node) => node.type === "markdown" && node.text === text));
        assert.equal(c.composer("c1").error, undefined);
        assert.equal(c.transcript("c1").items.length, 0);
      }),
    );
  }
});

test("secondary Enter and adjacent Queue hold structured image-only or mixed drafts while idle", async () => {
  const ledger = new InputLedger();
  ledger.files.add("src/main.ts");
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      c.composer("c1").attachments = [image];
      yield* onSubmit(c, "c1", { value: "", secondary: true, shift: false });
      assert.equal(ledger.deliveries.length, 0);
      assert.deepEqual(ledger.snapshots.c1.inputs[0].blocks, [
        { type: "image", mimeType: "image/png", data: "persisted-image-bytes" },
      ]);
      assert.equal(c.composer("c1").attachments.length, 0);
      c.composer("c1").text = "Read @src/main.ts";
      c.composer("c1").attachments = [image];
      yield* queuePrompt(c, "c1");
      assert.deepEqual(
        ledger.snapshots.c1.inputs[1].blocks.map((block) => block.type),
        ["text", "file_ref", "image"],
      );
      assert.equal(ledger.deliveries.length, 0);
    }),
  );
});

test("a restored image-only draft survives text edits, persists raw bytes and submits once", async () => {
  const ledger = new InputLedger();
  let draft: ComposerDraft = {
    chatId: "c1",
    revision: 4,
    inputId: "transferred-input",
    blocks: [{ type: "image", mimeType: "image/png", data: "original-image-bytes" }],
  };
  const call = ledger.call.bind(ledger);
  ledger.call = async (method, raw) => {
    const params = raw as {
      chatId: string;
      revision: number;
      blocks: ContentBlock[];
      id: string;
      intent: "send" | "queue" | "steer";
    };
    if (method === "host/drafts.get") return structuredClone(draft);
    if (method === "host/drafts.update") {
      assert.equal(params.revision, draft.revision);
      draft = { ...draft, revision: draft.revision + 1, blocks: structuredClone(params.blocks) };
      return structuredClone(draft);
    }
    if (method === "host/drafts.enqueue") {
      assert.equal(params.revision, draft.revision);
      const snapshot = await call("host/inputs.enqueue", {
        chatId: params.chatId,
        id: params.id,
        intent: params.intent,
        blocks: draft.blocks,
      });
      draft = { chatId: "c1", revision: draft.revision + 1, blocks: [] };
      return { snapshot, draft: structuredClone(draft) };
    }
    return call(method, raw);
  };
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      yield* c.drafts.load("c1");
      assert.equal(c.composer("c1").text, "");
      assert.deepEqual(c.composer("c1").carriedBlocks, draft.blocks);
      c.composer("c1").text = "Compare the asymmetrical diagram";
      c.composer("c1").editVersion!++;
      yield* c.drafts.save("c1");
      assert.deepEqual(draft.blocks, [
        { type: "text", text: "Compare the asymmetrical diagram" },
        { type: "image", mimeType: "image/png", data: "original-image-bytes" },
      ]);
      yield* send(c, "c1");
      assert.equal(ledger.deliveries.length, 1);
      assert.equal(ledger.deliveries[0].inputId, "transferred-input");
      assert.deepEqual(ledger.deliveries[0].blocks, [
        { type: "text", text: "Compare the asymmetrical diagram" },
        { type: "image", mimeType: "image/png", data: "original-image-bytes" },
      ]);
      assert.deepEqual(draft.blocks, []);
    }),
  );
});

test("draft notifications update a clean composer but never overwrite unsaved typing", async () => {
  await withController(new InputLedger(), (c) =>
    Effect.sync(() => {
      c.drafts.apply({ chatId: "c1", revision: 2, blocks: [{ type: "text", text: "Clean draft" }] });
      c.drafts.observe({ chatId: "c1", revision: 3, blocks: [{ type: "text", text: "Transferred queue" }] });
      assert.equal(c.composer("c1").text, "Transferred queue");
      c.composer("c1").text = "User typed after handoff began";
      c.composer("c1").editVersion!++;
      c.drafts.observe({ chatId: "c1", revision: 4, blocks: [{ type: "text", text: "Older host content" }] });
      assert.equal(c.composer("c1").text, "User typed after handoff began");
      assert.equal(c.drafts.snapshots.c1.revision, 4);
    }),
  );
});

test("keys typed while a chat's saved draft loads go after that draft instead of overwriting it", async () => {
  const ledger = new DraftLedger();
  ledger.draft = { chatId: "c1", revision: 1, blocks: [{ type: "text", text: "Earlier draft" }] };
  let release!: () => void;
  const answered = new Promise<void>((resolve) => (release = resolve));
  const call = ledger.call.bind(ledger);
  ledger.call = async (method, params) => {
    if (method === "host/drafts.get") await answered;
    return call(method, params);
  };
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      delete c.state.composers.c1;
      c.state.restored ??= {};
      yield* c.ensureComposer("c1");
      yield* onChange(c, "c1", "and more");
      release();
      yield* c.drafts.load("c1");
      assert.equal(c.composer("c1").text, "Earlier draft\n\nand more");
      assert.deepEqual(ledger.draft.blocks, [{ type: "text", text: "Earlier draft\n\nand more" }]);
    }),
  );
});

test("idle Queue after a prior success does not reuse that old release boundary", async () => {
  const ledger = new InputLedger();
  ledger.settled("c1", settledRun("old-success"));
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      c.composer("c1").text = "Hold, do not start";
      yield* queuePrompt(c, "c1");
      yield* c.scheduler.evaluate();
      assert.equal(ledger.deliveries.length, 0);
      assert.equal(ledger.snapshots.c1.inputs[0].state, "held");
    }),
  );
});

test("plain Enter accepts the selected picker, secondary bypasses it, and Shift never submits", async () => {
  const ledger = new InputLedger();
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      const composer = c.composer("c1");
      composer.text = "Inspect @src";
      composer.picker = { kind: "files", query: "src", start: 8, end: 12 };
      composer.files = ["src/first.ts", "src/selected.ts"];
      pickerKey(c, "c1", "down");
      yield* onSubmit(c, "c1", { value: composer.text, secondary: false, shift: false });
      assert.equal(composer.text, "Inspect @src/selected.ts ");
      assert.equal(ledger.snapshots.c1.inputs.length, 0);
      composer.text = "Inspect current draft";
      composer.picker = { kind: "files", query: "src", start: 8, end: 12, index: 1 };
      yield* onSubmit(c, "c1", { value: composer.text, secondary: true, shift: false });
      assert.deepEqual(ledger.snapshots.c1.inputs[0].blocks, [{ type: "text", text: "Inspect current draft" }]);
      composer.text = "line\nnext";
      yield* onSubmit(c, "c1", { value: composer.text, secondary: false, shift: true });
      assert.equal(composer.text, "line\nnext");
      assert.equal(ledger.snapshots.c1.inputs.length, 1);
    }),
  );
});

test("the slash picker lists a command once, Tab completes the highlighted one, Down then Enter runs it", async (ctx) => {
  const ledger = new InputLedger();
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      ctx.mock.method(c.api, "slashCommands", () => [
        { name: "clear", plugin: "chat", description: "New chat", inputHint: null },
      ]);
      const composer = c.composer("c1");
      // The host lists the plugins' commands after the agent's, and a
      // plugin's runs in place of the agent's of the same name.
      composer.commands = [
        { name: "clear", description: "New session" },
        { name: "compact", description: "Compact" },
        { name: "clear", description: "New chat (chat)", source: "plugin" },
      ];
      assert.deepEqual(
        c.matchingCommands(composer, "c").map((command) => `/${command.name} ${command.description}`),
        ["/compact Compact", "/clear New chat (chat)"],
      );
      const view: ChatView = {
        controller: c,
        ctx: { state: {}, set: () => {}, app: { route: "chat", chatId: "c1" }, plugin: "chat", update() {}, run() {} },
      };
      const prompt = () => nodes(renderPane(view, "c1")).find((node) => node.id === "prompt-c1");
      assert.deepEqual(prompt()?.keys, [], "the prompt keeps its keys while no picker is open");
      yield* onChange(c, "c1", "/c");
      // The prompt would act on these keys itself before the picker saw them.
      assert.deepEqual(prompt()?.keys, ["up", "down", "tab", "escape"]);
      pickerKey(c, "c1", "down");
      assert.equal(yield* acceptPicked(c, "c1", false), true);
      assert.equal(composer.text, "/clear ");
      assert.equal(ledger.snapshots.c1.inputs.length, 0, "Tab completes the command, it does not run it");
      yield* onChange(c, "c1", "/c");
      pickerKey(c, "c1", "down");
      yield* onSubmit(c, "c1", { value: "/c", secondary: false, shift: false });
      for (let tries = 0; !ledger.snapshots.c1.inputs.length && tries < 100; tries++) yield* Effect.sleep(5);
      assert.deepEqual(ledger.snapshots.c1.inputs[0]?.blocks, [{ type: "text", text: "/clear" }]);
    }),
  );
});

test("secondary Enter does not accept an incomplete slash command candidate", async () => {
  const ledger = new InputLedger();
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      const composer = c.composer("c1");
      composer.text = "/comp";
      composer.picker = { kind: "commands", query: "comp", start: 0, end: 5 };
      composer.commands = [{ name: "compact", description: "Compact" }];
      yield* onSubmit(c, "c1", { value: composer.text, secondary: true, shift: false });
      assert.equal(composer.text, "/comp");
      assert.equal(ledger.snapshots.c1.inputs.length, 0);
      assert.match(ledger.notices[0], /complete command/);
    }),
  );
});

test("active Enter steers supported agents, simulated copy explains interruption, unsupported Send never queues silently", async () => {
  for (const capability of ["native", "simulated", "unsupported"]) {
    const ledger = new InputLedger();
    ledger.mutate("c1", (snapshot) => {
      snapshot.running = true;
      snapshot.runId = "active";
    });
    await withController(ledger, (c) =>
      Effect.gen(function* () {
        c.state.chats.c1 = chat({ status: "waiting_approval" });
        c.state.agents.agent.capabilities =
          capability === "native" ? { steer: true } : capability === "simulated" ? { simulatedSteer: true } : {};
        c.composer("c1").text = "Do not touch beta";
        yield* onSubmit(c, "c1", { value: "Do not touch beta", secondary: false, shift: false });
        if (capability === "unsupported") {
          assert.equal(ledger.snapshots.c1.inputs.length, 0);
          assert.equal(c.composer("c1").text, "Do not touch beta");
          assert.match(ledger.notices[0], /does not support/);
        } else {
          assert.equal(ledger.snapshots.c1.inputs[0].intent, "steer");
          assert.equal(ledger.deliveries[0].inputId, ledger.snapshots.c1.inputs[0].id);
        }
      }),
    );
  }
});

test("attachment read and enqueue failures retain the full draft, images and a visible error; enqueue retry reuses id", async () => {
  for (const kind of ["attachment", "enqueue"]) {
    const ledger = new InputLedger();
    ledger.missingImage = kind === "attachment";
    ledger.rejectEnqueue = kind === "enqueue";
    await withController(ledger, (c) =>
      Effect.gen(function* () {
        const composer = c.composer("c1");
        composer.text = "Text plus image";
        composer.attachments = [image];
        yield* send(c, "c1");
        assert.equal(composer.text, "Text plus image");
        assert.equal(composer.attachments.length, 1);
        assert.equal(ledger.forgotten.length, 0);
        assert.equal(ledger.deliveries.length, 0);
        assert.ok(composer.error);
        const previous = composer.submission?.id;
        ledger.missingImage = false;
        ledger.rejectEnqueue = false;
        yield* send(c, "c1");
        assert.equal(ledger.snapshots.c1.inputs.length, 1);
        assert.equal(ledger.deliveries[0].blocks.length, 2);
        if (previous) assert.equal(ledger.deliveries[0].inputId, previous);
      }),
    );
  }
});

test("ambiguous provider failure leaves an unknown durable copy and no automatic replay", async () => {
  const ledger = new InputLedger();
  ledger.rejectDispatch = true;
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      c.composer("c1").text = "Keep this recoverable";
      c.composer("c1").attachments = [image];
      yield* send(c, "c1");
      assert.equal(c.composer("c1").text, "");
      assert.equal(ledger.snapshots.c1.inputs[0].state, "delivery_unknown");
      assert.equal(ledger.snapshots.c1.inputs[0].blocks.length, 2);
      assert.ok(c.composer("c1").error);
      assert.equal(c.scheduler.snapshots.c1.inputs[0].state, "delivery_unknown");
      for (let i = 0; i < 5; i++) yield* c.scheduler.evaluate();
      assert.equal(ledger.calls.filter((call) => call.method === "host/inputs.dispatch").length, 1);
    }),
  );
});

test("a pasted image the kernel refused is reported while the others attach", async () => {
  const ledger = new InputLedger();
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      yield* onPasteFiles(c, "c1", {
        images: [image],
        paths: [],
        refused: ["Pasted image is 20 MB; the limit is 16 MB"],
      });
      assert.deepEqual(c.composer("c1").attachments, [image]);
      assert.deepEqual(ledger.notices, ["Could not attach: Pasted image is 20 MB; the limit is 16 MB"]);
    }),
  );
});

test("typing during durable capture preserves the later draft and its attachments", async () => {
  const ledger = new InputLedger();
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      const composer = c.composer("c1");
      composer.text = "Original";
      composer.attachments = [image];
      const laterImage = { ...image, id: "later-image" };
      let before: { text: string; images: string[] } | undefined;
      ledger.beforeEnqueue = async () => {
        before = { text: composer.text, images: composer.attachments.map((image) => image.id) };
        await Effect.runPromise(onChange(c, "c1", "Later draft"));
        await Effect.runPromise(keepNewImages(c, "c1", [laterImage]));
      };
      yield* queuePrompt(c, "c1");
      assert.deepEqual(before, { text: "", images: [] });
      assert.equal(composer.text, "Later draft");
      assert.deepEqual(composer.attachments, [laterImage]);
      assert.deepEqual(ledger.forgotten, [image.id]);
      assert.deepEqual(ledger.snapshots.c1.inputs[0].blocks[0], { type: "text", text: "Original" });
    }),
  );
});

test("failed capture does not replace a later edit even when it was deleted back to empty", async () => {
  const ledger = new InputLedger();
  ledger.rejectEnqueue = true;
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      const composer = c.composer("c1");
      composer.text = "Recover original";
      composer.attachments = [image];
      ledger.beforeEnqueue = async () => {
        await Effect.runPromise(onChange(c, "c1", "Later draft"));
        await Effect.runPromise(onChange(c, "c1", ""));
      };
      yield* send(c, "c1");
      assert.equal(composer.text, "");
      assert.deepEqual(composer.attachments, []);
      assert.equal(composer.recovered?.[0].text, "Recover original");
      assert.deepEqual(composer.recovered?.[0].attachments, [image]);
      assert.deepEqual(ledger.forgotten, []);
      const recovered = composer.recovered?.[0];
      assert.ok(recovered);
      const submission = recovered.submission;
      composer.text = "Another failure";
      yield* send(c, "c1");
      assert.deepEqual(
        composer.recovered?.map((input) => input.text),
        ["Recover original", "Another failure"],
      );
      const view: ChatView = {
        controller: c,
        ctx: { state: {}, set: () => {}, app: { route: "chat", chatId: "c1" }, plugin: "chat", update() {}, run() {} },
      };
      const restore = nodes(renderPane(view, "c1")).find((node) => node.id === `recover-${submission.id}`);
      assert.ok(restore);
      restore.onClick();
      assert.equal(composer.text, "Recover original");
      assert.deepEqual(composer.attachments, [image]);
      assert.deepEqual(
        composer.recovered?.map((input) => input.text),
        ["Another failure"],
      );
      ledger.beforeEnqueue = undefined;
      ledger.rejectEnqueue = false;
      yield* send(c, "c1");
      assert.equal(ledger.deliveries.length, 1);
      assert.equal(ledger.deliveries[0].inputId, submission.id, "recovery retains the idempotency key");
    }),
  );
});

test("canonical pickup replaces the preview without duplicate text or fictional edit actions", async () => {
  const ledger = new InputLedger();
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      const composer = c.composer("c1");
      composer.text = "Correlated prompt";
      const transcript = c.transcript("c1");
      transcript.snapshot = { kind: "ready" };
      const view: ChatView = {
        controller: c,
        ctx: { state: {}, set: () => {}, app: { route: "chat", chatId: "c1" }, plugin: "chat", update() {}, run() {} },
      };
      const frames: ReturnType<typeof nodes>[] = [];
      ledger.beforeEnqueue = async () => {
        frames.push(nodes(renderPane(view, "c1")));
      };
      ledger.afterClaim = async (snapshot) => {
        c.scheduler.receive(snapshot);
        const input = snapshot.inputs[0];
        transcript.items.push({ id: input.id, role: "user", blocks: input.blocks });
        transcript.running = true;
        frames.push(nodes(renderPane(view, "c1")));
      };
      yield* send(c, "c1");
      for (const tree of frames) {
        assert.equal(tree.filter((node) => node.text === "Correlated prompt").length, 1);
        assert.ok(!tree.some((node) => node.id?.startsWith("edit-chat:")));
      }
      assert.equal(composer.outgoing, undefined);
      assert.equal(nodes(renderPane(view, "c1")).filter((node) => node.text === "Correlated prompt").length, 1);
    }),
  );
});

test("completed dispatch keeps its preview across an older in-flight read until a fresh snapshot takes ownership", async () => {
  const ledger = new InputLedger();
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      const composer = c.composer("c1");
      composer.text = "Bridge prompt";
      composer.attachments = [image];
      const old = Promise.withResolvers<HostMethods["host/chats.transcript"]["result"]>();
      const started = Promise.withResolvers<void>(),
        delivered = Promise.withResolvers<void>();
      const call = ledger.call.bind(ledger);
      let reads = 0;
      ledger.call = async (method, params) => {
        if (method === "host/chats.transcript" && ++reads === 1) {
          started.resolve();
          return old.promise;
        }
        const result = await call(method, params);
        if (method === "host/inputs.dispatch") {
          delivered.resolve();
          return ledger.consumed("c1", ledger.deliveries[0].inputId);
        }
        return result;
      };
      const hydration = yield* Effect.forkIn(c.loadTranscript("c1"), c.scope, { startImmediately: true });
      yield* Effect.promise(() => started.promise);
      const submitting = yield* Effect.forkIn(send(c, "c1"), c.scope, { startImmediately: true });
      yield* Effect.promise(() => delivered.promise);
      const view: ChatView = {
        controller: c,
        ctx: { state: {}, set: () => {}, app: { route: "chat", chatId: "c1" }, plugin: "chat", update() {}, run() {} },
      };
      const before = nodes(renderPane(view, "c1"));
      assert.equal(before.filter((node) => node.text === "Bridge prompt").length, 1);
      assert.equal(composer.text, "");
      assert.ok(composer.submitting);
      old.resolve({ items: [], pendingApprovals: [], pendingQuestions: [], plan: null, usage: {}, running: false });
      yield* Fiber.join(hydration);
      yield* Fiber.join(submitting);
      assert.equal(reads, 2, "the old read is not the post-dispatch barrier");
      assert.equal(composer.outgoing, undefined);
      assert.equal(nodes(renderPane(view, "c1")).filter((node) => node.text === "Bridge prompt").length, 1);
      assert.deepEqual(c.state.itemImages[ledger.deliveries[0].inputId], ["restored-image"]);
      assert.deepEqual(ledger.forgotten, [image.id], "the preview releases its hold after the transcript loads its own image");
      assert.deepEqual(ledger.notices, []);
    }),
  );
});

test("a post-delivery refresh failure reports a view error without restoring or dispatching again", async () => {
  const ledger = new InputLedger();
  const call = ledger.call.bind(ledger);
  ledger.call = async (method, params) => {
    if (method === "host/chats.transcript") throw new Error("transcript read unavailable");
    return call(method, params);
  };
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      c.composer("c1").text = "Already submitted";
      yield* send(c, "c1");
      assert.equal(ledger.deliveries.length, 1);
      assert.equal(c.composer("c1").text, "");
      assert.equal(c.composer("c1").recovered, undefined);
      assert.equal(c.composer("c1").error, "Input submitted; transcript refresh failed");
      assert.equal(c.composer("c1").submitting, false);
      assert.equal(c.composer("c1").outgoing, undefined);
      assert.ok(ledger.notices.some((notice) => notice === "Input submitted; transcript refresh failed"));
    }),
  );
});

test("a deferred non-prompt command executes only on explicit dispatch and never releases FIFO", async () => {
  const ledger = new InputLedger();
  ledger.settled("c1", settledRun("previous"));
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      c.composer("c1").text = "/no-prompt";
      yield* queuePrompt(c, "c1");
      c.composer("c1").text = "Held follow-up";
      yield* queuePrompt(c, "c1");
      assert.equal(ledger.deliveries.length, 0);
      const input = ledger.snapshots.c1.inputs[0];
      yield* c.scheduler.promote("c1", input.id, ledger.snapshots.c1.revision);
      yield* c.scheduler.evaluate();
      assert.equal(ledger.deliveries.length, 1);
      assert.equal(ledger.snapshots.c1.running, false);
      assert.equal(ledger.snapshots.c1.inputs[1].state, "held");
    }),
  );
});

test("unknown-method compatibility is positive-only; permission and transport failures cannot fall back", () => {
  assert.equal(
    unknownMethod(new HostCallFailed({ method: "host/inputs.list", code: -32601, message: "unknown" })),
    true,
  );
  assert.equal(
    unknownMethod(new HostCallFailed({ method: "host/inputs.enqueue", code: -32603, message: "transport lost" })),
    false,
  );
  assert.equal(unknownMethod({ _tag: "PermissionNotGranted", message: "unknown host method host/inputs.list" }), false);
});

test("native admitted/unknown rows show full steer text and no edit/remove; grace and settings share agent preference", async () => {
  const ledger = new InputLedger();
  ledger.mutate("c1", (snapshot) => {
    snapshot.inputs = [
      held("unknown", {
        intent: "steer",
        state: "delivery_unknown",
        blocks: [{ type: "text", text: "Inspect alpha\nDo not change beta" }],
      }),
      held("admitted", { intent: "steer", state: "native_admitted" }),
    ];
    snapshot.running = true;
    snapshot.runId = "active";
  });
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      const view: ChatView = {
        controller: c,
        ctx: { state: {}, set: () => {}, app: { route: "chat", chatId: "c1" }, plugin: "chat", update() {}, run() {} },
      };
      const rows = renderPending(view, c.state.chats.c1).flatMap((row) => nodes(row));
      assert.ok(rows.some((node) => node.text === "Inspect alpha\nDo not change beta"));
      assert.ok(!rows.some((node) => typeof node.id === "string" && /edit-input|remove-input|promote-/.test(node.id)));
      c.scheduler.activeLimits.c1 = {
        runId: "active",
        evidence: {
          availability: "blocked",
          source: "native",
          observedAt: "2026-10-04T12:00:00Z",
          reason: "Limit",
          identity: "account",
        },
      };
      assert.ok(
        nodes(renderLimit(view, c.state.chats.c1)).some(
          (node) => node.text === "Usage limit reported · still working / retrying",
        ),
      );
      assert.ok(nodes(renderLimit(view, c.state.chats.c1)).some((node) => node.text === "Reset time unavailable"));
      yield* c.scheduler.setAutoSend("agent", false);
      assert.equal(
        nodes(renderLimit(view, c.state.chats.c1)).find((node) => node.id === "auto-limit-c1")?.checked,
        false,
      );
      assert.equal(nodes(renderSettings(view)).find((node) => node.id === "auto-limit-agent-agent")?.checked, false);
    }),
  );
});

test("quick checkbox and settings handlers update the same global preference and repaint settings", async () => {
  const ledger = new InputLedger(["c1", "c2"]);
  for (const id of ["c1", "c2"])
    ledger.mutate(id, (snapshot) => {
      snapshot.inputs = [held(`next:${id}`, { chatId: id })];
      snapshot.policyState = {
        version: 1,
        generation: 1,
        wait: { runId: "limit", stoppedAt: "2026-10-04T12:00:00Z", reason: "Limit", status: "armed" },
      };
    });
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      const actions: Effect.Effect<unknown, unknown>[] = [];
      let settingsUpdates = 0;
      c.settingsView = {
        id: 10,
        update: () => {
          settingsUpdates++;
        },
        remove() {},
      };
      const view: ChatView = {
        controller: c,
        ctx: {
          state: {},
          set: () => {},
          app: { route: "chat", chatId: "c1" },
          plugin: "chat",
          update() {},
          run: (effect) => {
            // These local handlers use the controller's injected services, as
            // in ui-for-tests; none requires additional Effect environment.
            actions.push(effect as Effect.Effect<unknown, unknown>);
          },
        },
      };
      const quick = nodes(renderLimit(view, c.state.chats.c1)).find((node) => node.id === "auto-limit-c1");
      assert.ok(quick);
      // The local tree contains the boolean checkbox handler, not a text input.
      (quick.onChange as unknown as (event: { value: boolean }) => void)({ value: false });
      yield* Effect.all(actions.splice(0));
      assert.deepEqual(ledger.settings.autoSendAfterLimit, { agent: false });
      assert.equal(autoSend(c.scheduler.preferences, "agent"), false);
      assert.equal(
        nodes(renderLimit(view, c.state.chats.c2)).find((node) => node.id === "auto-limit-c2")?.checked,
        false,
      );
      assert.equal(nodes(renderSettings(view)).find((node) => node.id === "auto-limit-agent-agent")?.checked, false);
      assert.ok(settingsUpdates > 0, "retained settings view must repaint after preference application");
      const setting = nodes(renderSettings(view)).find((node) => node.id === "auto-limit-agent-agent");
      assert.ok(setting);
      (setting.onChange as unknown as (event: { value: boolean }) => void)({ value: true });
      yield* Effect.all(actions.splice(0));
      assert.deepEqual(ledger.settings.autoSendAfterLimit, { agent: true });
      assert.equal(
        nodes(renderLimit(view, c.state.chats.c1)).find((node) => node.id === "auto-limit-c1")?.checked,
        true,
      );
      assert.equal(ledger.deliveries.length, 0, "preferences alone cannot establish missing identity/reset evidence");
    }),
  );
});

test("held edit and explicit promotion handlers preserve every attachment and an unrelated draft", async () => {
  const ledger = new InputLedger();
  const attachments = [
    { type: "image", mimeType: "image/png", data: "image-bytes" },
    { type: "audio", mimeType: "audio/wav", data: "audio-bytes" },
    { type: "file_ref", path: "src/main.ts" },
    { type: "resource", path: "notes.md", text: "resource contents" },
    { type: "skill", name: "review", input: "inspect changes" },
  ] satisfies import("divergence").ContentBlock[];
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      const composer = c.composer("c1");
      composer.text = "Unrelated draft";
      composer.attachments = [image];
      yield* c.scheduler.enqueue("c1", "editable", [{ type: "text", text: "Original" }, ...attachments], "queue");
      const actions: Effect.Effect<unknown, unknown>[] = [];
      const view: ChatView = {
        controller: c,
        ctx: {
          state: {},
          set: () => {},
          app: { route: "chat", chatId: "c1" },
          plugin: "chat",
          update() {},
          run: (effect) => {
            // Held edit/promote call only the injected controller services.
            actions.push(effect as Effect.Effect<unknown, unknown>);
          },
        },
      };
      const rows = () => nodes(renderPending(view, c.state.chats.c1));
      rows()
        .find((node) => node.id === "edit-input-editable")
        ?.onClick();
      assert.ok(composer.pendingEdit);
      rows()
        .find((node) => node.id === "edit-pending-editable")
        ?.onChange({ value: "Edited held input" });
      rows()
        .find((node) => node.id === "save-pending-editable")
        ?.onClick();
      yield* Effect.all(actions.splice(0));
      assert.deepEqual(ledger.snapshots.c1.inputs[0].blocks, [
        { type: "text", text: "Edited held input" },
        ...attachments,
      ]);
      rows()
        .find((node) => node.id === "promote-editable")
        ?.onClick();
      yield* Effect.all(actions.splice(0));
      assert.equal(ledger.deliveries[0].inputId, "editable");
      assert.deepEqual(ledger.deliveries[0].blocks, [{ type: "text", text: "Edited held input" }, ...attachments]);
      assert.equal(composer.text, "Unrelated draft");
      assert.deepEqual(composer.attachments, [image]);
      assert.deepEqual(ledger.forgotten, []);
    }),
  );
});

const pendingView = (c: ChatView["controller"], actions: Effect.Effect<unknown, unknown>[]): ChatView => ({
  controller: c,
  ctx: {
    state: {},
    set: () => {},
    app: { route: "chat", chatId: "c1" },
    plugin: "chat",
    update() {},
    run: (effect) => {
      actions.push(effect as Effect.Effect<unknown, unknown>);
    },
  },
});

test("Save of a held edit goes through after the chat changed, and refuses each time once the prompt itself changed", async () => {
  const ledger = new InputLedger();
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      yield* c.scheduler.enqueue("c1", "held", [{ type: "text", text: "Original" }], "queue");
      const actions: Effect.Effect<unknown, unknown>[] = [];
      const rows = () => nodes(renderPending(pendingView(c, actions), c.state.chats.c1));
      const press = (id: string) => rows().find((node) => node.id === id)?.onClick();
      press("edit-input-held");
      rows().find((node) => node.id === "edit-pending-held")?.onChange({ value: "   " });
      assert.equal(rows().find((node) => node.id === "save-pending-held")?.disabled, true, "an empty edit cannot be saved");
      // The run's events move the chat on while the user types.
      c.scheduler.receive(ledger.mutate("c1", (snapshot) => void (snapshot.running = true)));
      rows().find((node) => node.id === "edit-pending-held")?.onChange({ value: "Edited" });
      press("save-pending-held");
      yield* Effect.all(actions.splice(0));
      assert.deepEqual(ledger.notices, []);
      assert.deepEqual(ledger.snapshots.c1.inputs[0].blocks, [{ type: "text", text: "Edited" }]);
      assert.equal(c.composer("c1").pendingEdit, undefined);
      // Edited elsewhere meanwhile: Save refuses, and says so on every press.
      press("edit-input-held");
      c.scheduler.receive(ledger.mutate("c1", (snapshot) => void (snapshot.inputs[0].revision = 2)));
      rows().find((node) => node.id === "edit-pending-held")?.onChange({ value: "Mine" });
      for (const _ of [1, 2]) {
        press("save-pending-held");
        yield* Effect.all(actions.splice(0));
      }
      const refused = "Pending input: this prompt changed while you edited it; cancel and edit it again";
      assert.deepEqual(ledger.notices, [refused, refused]);
      assert.deepEqual(ledger.snapshots.c1.inputs[0].blocks, [{ type: "text", text: "Edited" }]);
    }),
  );
});

test("an editor open on a held prompt that goes meanwhile gives the typed edit back", async () => {
  const ledger = new InputLedger();
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      yield* c.scheduler.enqueue("c1", "held", [{ type: "text", text: "Original" }], "queue");
      const actions: Effect.Effect<unknown, unknown>[] = [];
      const rows = () => nodes(renderPending(pendingView(c, actions), c.state.chats.c1));
      rows().find((node) => node.id === "edit-input-held")?.onClick();
      rows().find((node) => node.id === "edit-pending-held")?.onChange({ value: "Original, and more" });
      yield* c.scheduler.manualDispatch("c1", "held", ledger.snapshots.c1.revision);
      yield* Effect.yieldNow;
      assert.equal(c.composer("c1").pendingEdit, undefined);
      assert.equal(c.composer("c1").text, "Original, and more");
    }),
  );
});

test("a cancelled waiting prompt is saved as the draft when it goes back into the box", async () => {
  const ledger = new DraftLedger();
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      c.state.restored ??= {};
      yield* c.drafts.load("c1");
      yield* takeBack(c, "c1", { queue: false, text: "Bring me back", attachments: [], carriedBlocks: [] });
      yield* Effect.sleep("20 millis");
      assert.equal(c.composer("c1").text, "Bring me back");
      assert.deepEqual(ledger.draft.blocks, [{ type: "text", text: "Bring me back" }]);
    }),
  );
});

test("queued inputs reorder from the grip at their start, before or after the row they are dropped on", async () => {
  const ledger = new InputLedger();
  ledger.mutate("c1", (snapshot) => {
    snapshot.running = true;
    snapshot.runId = "active";
  });
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      for (const id of ["a", "b", "c"]) yield* c.scheduler.enqueue("c1", id, [{ type: "text", text: id }], "queue");
      const actions: Effect.Effect<unknown, unknown>[] = [];
      const view = pendingView(c, actions);
      const rows = () => nodes(renderPending(view, c.state.chats.c1));
      const order = () => ledger.snapshots.c1.inputs.map((input) => input.id);
      const drop = (target: number, dragged: string, zone: string) =>
        Effect.gen(function* () {
          const node = rows().filter((node) => node.drop)[target];
          (node.drop as { onDrop: (event: unknown) => void }).onDrop({ type: "queued-input:c1", data: dragged, zone });
          yield* Effect.all(actions.splice(0));
        });
      assert.deepEqual(
        rows().flatMap((node) => (node.drag ? [(node.drag as { data: string }).data] : [])),
        ["a", "b", "c"],
        "each queued row carries its grip",
      );
      yield* drop(0, "c", "before");
      assert.deepEqual(order(), ["c", "a", "b"]);
      yield* drop(2, "c", "after");
      assert.deepEqual(order(), ["a", "b", "c"]);
      yield* drop(1, "a", "into");
      assert.deepEqual(order(), ["b", "a", "c"], "an older kernel's drop takes the target's place");
      yield* drop(1, "a", "before");
      assert.deepEqual(order(), ["b", "a", "c"], "a drop where it already is moves nothing");
      assert.equal(ledger.deliveries.length, 0);
    }),
  );
});

test("a lone queued input has no grip to drag", async () => {
  const ledger = new InputLedger();
  ledger.mutate("c1", (snapshot) => {
    snapshot.running = true;
    snapshot.runId = "active";
  });
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      yield* c.scheduler.enqueue("c1", "only", [{ type: "text", text: "only" }], "queue");
      const rows = nodes(renderPending(pendingView(c, []), c.state.chats.c1));
      assert.ok(!rows.some((node) => node.drag || node.drop));
      assert.ok(rows.some((node) => node.id === "remove-input-only"));
    }),
  );
});

test("a steer the agent holds is cancelled through the agent, only when the agent can take it back", async () => {
  const ledger = new InputLedger();
  ledger.mutate("c1", (snapshot) => {
    snapshot.inputs = [held("sent", { intent: "steer", originalIntent: "steer", state: "native_admitted" })];
    snapshot.running = true;
    snapshot.runId = "active";
  });
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      c.state.transcripts.c1 = { ...c.state.transcripts.c1, items: [] } as typeof c.state.transcripts.c1;
      const actions: Effect.Effect<unknown, unknown>[] = [];
      const view = pendingView(c, actions);
      const cancel = () => nodes(renderPending(view, c.state.chats.c1)).find((node) => node.id === "withdraw-sent");
      assert.equal(cancel(), undefined, "no withdrawal without the agent's own operation");
      c.state.agents.agent.capabilities = { ...c.state.agents.agent.capabilities, withdraw: true };
      cancel()?.onClick();
      yield* Effect.all(actions.splice(0));
      assert.deepEqual(ledger.snapshots.c1.inputs, []);
      assert.deepEqual(renderPending(view, c.state.chats.c1), []);
    }),
  );
});

test("user enqueue wins if generated Continue reaches the host after the user's input", async (ctx) => {
  ctx.mock.method(Date, "now", () => Date.parse("2026-10-04T12:00:00Z"));
  const ledger = new InputLedger();
  ledger.settings.generateContinue = true;
  ledger.settled(
    "c1",
    settledRun("limit", {
      outcome: { status: "failed", message: "Limit" },
      usageLimit: {
        availability: "blocked",
        source: "native",
        observedAt: "2026-10-04T12:00:00Z",
        reason: "Limit",
        identity: "account",
        resetsAt: "2026-10-04T12:05:00Z",
      },
    }),
  );
  // An initialized previous policy lets this new settled interruption be handled.
  ledger.mutate("c1", (snapshot) => {
    snapshot.policyState = { version: 1, generation: 1 };
  });
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      ledger.beforeEnqueue = async () => {
        ledger.beforeEnqueue = undefined;
        await Effect.runPromise(
          c.scheduler.enqueue("c1", "user-wins", [{ type: "text", text: "User instruction" }], "queue"),
        );
      };
      yield* c.scheduler.updatePreferences();
      yield* c.scheduler.evaluate();
      assert.deepEqual(
        ledger.snapshots.c1.inputs.map((input) => input.id),
        ["user-wins"],
      );
      assert.equal(policyOf(ledger.snapshots.c1).wait?.generated, true);
      assert.equal(ledger.deliveries.length, 0);
    }),
  );
});

test("a restore leaves saying the files are back to the host, and names the ones the checkpoint did not cover, only once they are", async () => {
  for (const unknownPaths of [[], ["outside.txt"]]) {
    const ledger = new InputLedger();
    const restored: string[] = [];
    const call = ledger.call.bind(ledger);
    ledger.call = async (method, params) => {
      if (method === "host/chats.checkpoint_coverage") return { degraded: false, expired: false, unknownPaths };
      if (method === "host/chats.restore_checkpoint") {
        assert.deepEqual(ledger.notices, [], "nothing is said before the files are back");
        restored.push((params as { itemId: string }).itemId);
        return {};
      }
      return call(method, params);
    };
    await withController(ledger, (c) => c.revert("c1", "u1"));
    assert.deepEqual(restored, ["u1"]);
    // The host's own notice ("Restored N file(s).") says the files are back; the plugin adds only what it does not name.
    assert.deepEqual(
      ledger.notices,
      unknownPaths.length ? ["The checkpoint did not cover these files, which are left as they are: outside.txt"] : [],
    );
  }
});

test("a restored draft shows its images as attachments again, not as carried rows", async () => {
  const ledger = new DraftLedger();
  ledger.draft = {
    chatId: "c1",
    revision: 3,
    blocks: [
      { type: "text", text: "What is in this picture?" },
      { type: "image", mimeType: "image/png", data: "persisted-image-bytes" },
      { type: "file_ref", path: "notes.md" },
    ],
    composition: { text: "What is in this picture?", generated: [0] },
  };
  await withController(ledger, (c) =>
    Effect.gen(function* () {
      yield* c.drafts.load("c1");
      yield* Effect.yieldNow;
      const composer = c.composer("c1");
      assert.equal(composer.text, "What is in this picture?");
      assert.deepEqual(
        composer.attachments.map((image) => image.id),
        ["restored-image"],
      );
      assert.deepEqual(composer.carriedBlocks, [{ type: "file_ref", path: "notes.md" }]);
      // Saving again writes the same image back from the kernel's bytes.
      composer.editVersion = (composer.editVersion ?? 0) + 1;
      yield* c.drafts.save("c1");
      assert.deepEqual(
        ledger.draft.blocks.filter((block) => block.type === "image"),
        [{ type: "image", mimeType: "image/png", data: "persisted-image-bytes" }],
      );
    }),
  );
});

Versions

VersionPublishedPlugin APISizePermissionsStatus
0.2.9latestNov 21, 2026>=5 <6349 KB5 permissionsListed
0.2.8Nov 16, 2026>=5 <6348.6 KB5 permissionsListed
0.2.7Nov 11, 2026>=5 <6314.3 KB5 permissionsListed
0.2.6Nov 9, 2026>=5 <6306.2 KB5 permissionsListed
0.2.5Oct 27, 2026>=2 <4178.6 KB5 permissionsListed

Reviews and comments

0 threads · 0 reviews

No comments yet.