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.5
Permissions in 0.2.5
Files
drafts.ts10.5 KB
// Host-owned structured drafts. Older Alpha hosts retain the text-only path.
import * as Effect from "effect/Effect";
import * as Semaphore from "effect/Semaphore";
import * as z from "zod";
import { parse } from "divergence/effect";
import type { ComposerDraft, ContentBlock, InputComposition } from "divergence";
import type { Controller } from "./controller.ts";
import type { Composer } from "./state.ts";
import { compositionFor, editableComposition, inputId } from "./composition.ts";
import { contentBlocks } from "./input-schema.ts";
import { unknownMethod } from "./scheduler.ts";
import { errorMessage } from "./data.ts";
const recoveries = z.array(z.object({ id: z.string(), text: z.string(), blocks: contentBlocks }));
const recoveryKey = (chatId: string) => `draft-recoveries:${chatId}`;
export class Drafts {
readonly snapshots: Record<string, ComposerDraft> = {};
readonly loading = new Set<string>();
available: boolean | undefined;
private readonly lanes: Record<string, Semaphore.Semaphore> = {};
private readonly saved: Record<string, number> = {};
private readonly initialized = new Set<string>();
readonly controller: Controller;
constructor(controller: Controller) {
this.controller = controller;
}
private lane(chatId: string) {
return (this.lanes[chatId] ??= Semaphore.makeUnsafe(1));
}
receive(draft: ComposerDraft) {
const before = this.snapshots[draft.chatId];
if (!before || before.revision <= draft.revision) this.snapshots[draft.chatId] = draft;
}
observe(draft: ComposerDraft) {
const previous = this.snapshots[draft.chatId];
const composer = this.controller.state.composers[draft.chatId];
if (previous && previous.revision >= draft.revision) return;
if (
composer &&
!composer.submitting &&
!composer.preparing &&
this.saved[draft.chatId] === (composer.editVersion ?? 0)
)
this.apply(draft);
else this.receive(draft);
}
apply(draft: ComposerDraft) {
if ((this.snapshots[draft.chatId]?.revision ?? 0) > draft.revision) return;
this.receive(draft);
const composer = this.controller.composer(draft.chatId);
const editable = editableComposition(draft);
composer.text = editable.text;
composer.carriedBlocks = editable.carriedBlocks;
composer.draftInputId = draft.inputId;
composer.attachments = [];
composer.editVersion = (composer.editVersion ?? 0) + 1;
this.saved[draft.chatId] = composer.editVersion;
this.controller.refresh(draft.chatId);
Effect.runFork(Effect.forkIn(this.holdImages(draft.chatId), this.controller.scope));
}
// A stored draft keeps its images as bytes. Handed to the kernel again they
// are attachments, drawn with the thumbnail they were attached with.
holdImages = Effect.fn("Drafts.holdImages")((chatId: string) =>
Effect.gen({ self: this }, function* () {
const composer = this.controller.composer(chatId),
carried = composer.carriedBlocks ?? [];
const images = carried.flatMap((block) =>
block.type === "image" && block.data ? [{ block, data: block.data }] : [],
);
if (!images.length) return;
const held = yield* Effect.all(
images.map(({ block, data }) =>
this.controller.kernel.call("attach_image", { data, name: `Image.${block.mimeType.split("/")[1]}` }),
),
{ concurrency: "unbounded" },
);
// Another draft was installed while the bytes were read: it has its own.
if (composer.carriedBlocks !== carried) {
for (const image of held) yield* this.controller.kernel.call("forget_image", { id: image.id });
return;
}
composer.attachments.push(...held);
composer.carriedBlocks = carried.filter((block) => !images.some((image) => image.block === block));
this.controller.refresh(chatId);
}).pipe(
Effect.catch((error) =>
this.controller.notify.warning(`Could not show an attached image: ${errorMessage(error)}`),
),
),
);
load = Effect.fn("Drafts.load")((chatId: string) =>
this.lane(chatId).withPermit(
Effect.gen({ self: this }, function* () {
if (this.available === false || this.initialized.has(chatId)) return;
this.loading.add(chatId);
yield* Effect.gen({ self: this }, function* () {
const draft = yield* this.controller.host.call("host/drafts.get", { chatId }).pipe(
Effect.catch((error) =>
unknownMethod(error)
? Effect.sync(() => {
this.available = false;
return undefined;
})
: Effect.fail(error),
),
);
if (!draft) return;
this.available = true;
this.receive(draft);
const composer = this.controller.composer(chatId);
const stored = (yield* this.controller.host.call("host/storage.get", { key: recoveryKey(chatId) })).value;
if (stored) {
const saved = yield* parse("recovered drafts", recoveries, stored);
for (const recovery of saved)
(composer.recovered ??= []).push({
text: recovery.text,
attachments: [],
carriedBlocks: recovery.blocks,
submission: { id: recovery.id, signature: "" },
durable: true,
});
}
if (!composer.submitting && !(composer.editVersion ?? 0) && (draft.revision > 0 || !composer.text))
this.apply(draft);
this.initialized.add(chatId);
}).pipe(
Effect.ensuring(
Effect.sync(() => {
this.loading.delete(chatId);
this.controller.refresh(chatId);
}),
),
);
}),
),
);
read = Effect.fn("Drafts.read")((chatId: string) =>
this.controller.host
.call("host/drafts.get", { chatId })
.pipe(Effect.tap((draft) => Effect.sync(() => this.receive(draft)))),
);
// A queue head committed by handoff is authoritative even when the reply is
// lost. Newer typing is a different draft, not a replacement for that head.
reconcileHandoff = Effect.fn("Drafts.reconcileHandoff")(
(before: ComposerDraft, version: number, draft: ComposerDraft) =>
Effect.gen({ self: this }, function* () {
this.receive(draft);
if (draft.revision <= before.revision || !draft.inputId || draft.inputId === before.inputId) return;
const composer = this.controller.composer(draft.chatId);
if (
(composer.editVersion ?? 0) !== version &&
(composer.text || composer.attachments.length || composer.carriedBlocks?.length)
) {
const recovery: NonNullable<Composer["recovered"]>[number] = {
text: "",
attachments: [],
carriedBlocks: [],
submission: { id: inputId(), signature: "" },
durable: true,
};
(composer.recovered ??= []).push(recovery);
let capturedVersion: number;
do {
capturedVersion = composer.editVersion ?? 0;
const captured = yield* compositionFor(
this.controller,
draft.chatId,
composer.text,
[...composer.attachments],
composer.carriedBlocks,
false,
);
Object.assign(recovery, editableComposition(captured));
yield* this.saveRecoveries(draft.chatId);
} while (capturedVersion !== (composer.editVersion ?? 0));
}
this.apply(draft);
}),
);
private saveRecoveries = Effect.fn("Drafts.saveRecoveries")((chatId: string) =>
this.controller.host.call("host/storage.set", {
key: recoveryKey(chatId),
value: (this.controller.composer(chatId).recovered ?? [])
.filter((draft) => draft.durable)
.map((draft) => ({ id: draft.submission.id, text: draft.text, blocks: draft.carriedBlocks ?? [] })),
}),
);
private write = Effect.fn("Drafts.write")(
(chatId: string, revision: number, blocks: readonly ContentBlock[], composition?: InputComposition) =>
Effect.gen({ self: this }, function* () {
const draft = yield* this.controller.host.call("host/drafts.update", {
chatId,
revision,
blocks,
composition,
});
this.receive(draft);
// Capture materializes send-time blocks without changing the local edit
// version. A failed enqueue must still write raw editable state back.
delete this.saved[chatId];
return draft;
}),
);
save = Effect.fn("Drafts.save")((chatId: string) =>
Effect.gen({ self: this }, function* () {
yield* this.load(chatId);
if (!this.available) return;
yield* this.lane(chatId).withPermit(
Effect.gen({ self: this }, function* () {
const composer = this.controller.composer(chatId),
version = composer.editVersion ?? 0;
if (composer.submitting) return;
// Earlier typing may still advance CAS and abort preparation. Once a
// transferred head is observed, only reconciliation may install it.
const draft = this.snapshots[chatId];
if (composer.preparing && draft?.inputId && draft.inputId !== composer.draftInputId) return;
if (this.saved[chatId] !== version) {
const revision = draft!.revision;
const { blocks, composition } = yield* compositionFor(
this.controller,
chatId,
composer.text,
composer.attachments,
composer.carriedBlocks,
false,
);
// Capture can await images while a handoff transfers ownership.
// Its notification must never upgrade this save's CAS authority.
yield* this.write(chatId, revision, blocks, composition);
this.saved[chatId] = version;
}
// A restored draft replaces its durable recovery only after the
// replacement is itself durable. Failure retains the recovery.
yield* this.saveRecoveries(chatId);
}),
);
}),
);
capture = Effect.fn("Drafts.capture")(
(chatId: string, blocks: readonly ContentBlock[], composition?: InputComposition) =>
Effect.gen({ self: this }, function* () {
yield* this.load(chatId);
if (!this.available) return undefined;
return yield* this.lane(chatId).withPermit(
Effect.gen({ self: this }, function* () {
return yield* this.write(chatId, this.snapshots[chatId]!.revision, blocks, composition);
}),
);
}),
);
}Versions
| Version | Published | Plugin API | Size | Permissions | Status |
|---|---|---|---|---|---|
| 0.2.9latest | Nov 21, 2026 | >=5 <6 | 349 KB | 5 permissions | Listed |
| 0.2.8 | Nov 16, 2026 | >=5 <6 | 348.6 KB | 5 permissions | Listed |
| 0.2.7 | Nov 11, 2026 | >=5 <6 | 314.3 KB | 5 permissions | Listed |
| 0.2.6 | Nov 9, 2026 | >=5 <6 | 306.2 KB | 5 permissions | Listed |
| 0.2.5 | Oct 27, 2026 | >=2 <4 | 178.6 KB | 5 permissions | Listed |
No comments yet.