Skip to content

Examples

Each example on this page is a complete plugin. The comment at the top of each plugin lists the permissions that the plugin’s manifest must declare. To keep the code short, the examples display their messages in English only, whereas the plugins that ship with the app translate them with ctx.i18n.

This plugin prevents the deletion of any row that has the tag #keep.

The plugin registers a hook with ctx.hooks.shouldDelete. The app calls this hook once for every row that a change is about to delete, and passes it the row as it was before the change. The hook reads the tags of the row. If one of them is keep, the hook returns veto with a message: the deletion is refused, and the person sees the message. Otherwise, the hook returns allow, and the deletion proceeds.

The option onTimeout: 'veto' determines what happens when the hook throws an error or takes too long to answer: in that case, the deletion is refused. Without this option, a hook that fails would let the deletion go through.

// protect-tagged: refuses to delete any row that has the tag #keep. Permission: read.
import { allow, definePlugin, veto, type PluginContext } from '@tessera/plugin-sdk';
export default definePlugin({
onload(ctx: PluginContext) {
// The tags of a row, as the tags feature stores them.
const tags = ctx.facets.core.tags.tags;
// The app calls this hook for every row that a change deletes. If the hook fails or takes too long, the deletion is refused.
ctx.hooks.shouldDelete({ on: 'row', onTimeout: 'veto' }, delta => {
if (delta.kind !== 'deleted') {
return allow();
}
// The row as it was before the change.
const row = delta.value as { facets?: Record<string, unknown> };
const names = tags.of({ facets: row.facets ?? {} }) ?? [];
if (names.some(name => name.toLowerCase() === 'keep')) {
return veto('protected', 'Tagged #keep: it cannot be deleted');
}
return allow();
});
},
});

2. Asking for confirmation before a large change

Section titled “2. Asking for confirmation before a large change”

This plugin asks the person for confirmation when a single change would delete more than 30 rows, for example when they select a large part of an outline and press Delete.

The plugin registers a hook with ctx.hooks.shouldUpdate, which the app calls once for each change, before the change is applied. The hook counts the rows that the change deletes. When there are 30 or fewer, it returns allow. When there are more, it opens a confirmation dialog with ctx.ui.confirm and returns defer with the promise of the person’s answer. The app waits for that promise without blocking the screen. If the person confirms, the promise resolves to allow and the change is applied. If the person declines, the promise resolves to veto and the change is discarded.

Because the library may change while the dialog is open, the app checks the change again before applying it.

// confirm-mass-delete: asks the person to confirm a change that deletes more than 30 rows. Permissions: read, ui.
import { allow, defer, definePlugin, veto, type PluginContext } from '@tessera/plugin-sdk';
// The largest number of rows that a change may delete without asking.
const LIMIT = 30;
export default definePlugin({
onload(ctx: PluginContext) {
// The app calls this hook once for the whole change, before applying it.
ctx.hooks.shouldUpdate({}, proposal => {
// The number of rows that the change deletes.
const deleted = proposal.deltas.filter(d => d.kind === 'deleted' && d.ref.kind === 'row').length;
if (deleted <= LIMIT) {
return allow();
}
// The change waits for the answer, and the screen remains responsive in the meantime.
const answer = ctx.ui.confirm({ title: `Delete ${deleted} rows?`, message: 'This can be undone.' });
return defer(
answer.then(said => (said.confirmed ? allow() : veto('cancelled', 'Not deleted'))),
'Confirming',
);
});
},
});

3. Extra information on a row, menu items, a timer and a card with buttons

Section titled “3. Extra information on a row, menu items, a timer and a card with buttons”

A pomodoro is a period of 25 minutes spent on a single task. The pomodoro plugin attaches a 25-minute timer to a to-do, shows the time left on a card, and counts the pomodoros completed on each to-do. It ships with the app, and the code below is that plugin, with its messages in English only.

The plugin stores its data in two facets. A facet is a piece of data that a plugin attaches to a row, with a schema that describes its value and a merge kind that states how the values written on two devices are combined. The first facet is the number of pomodoros completed on the row. Its merge kind is counter, so if two devices each complete a pomodoro at the same moment, the row counts two. The second facet holds the timer that is running. It is declared with sync: false, so it stays on the device that started it. If it were synchronized, every device would ring when the time was up, and each of them would add a pomodoro.

The plugin adds four commands to the menu that opens when a row is right-clicked: start, pause, resume and cancel. A fifth command, finish, does not appear in any menu; the plugin runs it when the time is up. Each command has a can function, which states whether the command can be used on the selected row and, if it cannot, why. For example, pause can be used only while the timer is running. At any other time, the command palette shows the command as unavailable, with the reason “Not running”.

When the person starts a pomodoro, the start command writes the timer to the row, and the plugin watches that value with ctx.observe. While the timer runs, the plugin updates a card every second. The card shows the time left and has two buttons, Pause and Cancel, each of which runs one of the plugin’s commands. When the time is up, the finish command adds one to the counter and removes the timer, in a single change.

The plugin also adds a mark to the row with ctx.ui.decorate: 🍅 followed by the number of pomodoros, and ▶ or ⏸ while the row has a timer. The app calls the decoration function each time the row changes, and allows it 0.2 milliseconds to return the mark.

/* pomodoro: a 25-minute timer attached to a to-do.
To start a timer, right-click a to-do and choose "Start a pomodoro". A card then shows the time left, with buttons that pause
and cancel the timer. When the time is up, the counter of the to-do goes up by one, and the row shows a 🍅 with the count.
The example shows two facets (a counter that is synchronized, and a timer that stays on this device), commands in the menu of
a row, a mark on the row, a card with a progress bar, and how to watch a value.
Permissions: read, write:rows, ui, notifications, jobs. */
import { definePlugin, type PluginContext } from '@tessera/plugin-sdk';
// The length of a pomodoro, and the interval at which the card is updated.
const FULL_MS = 25 * 60 * 1000;
const TICK_MS = 1000;
// The timer of a row. While it runs, it ends at `endsAt`. While it is paused, `left` is the time that remains.
interface Timer {
readonly state: 'running' | 'paused';
readonly endsAt?: number;
readonly left: number;
}
// Formats a number of milliseconds as minutes and seconds, for example 24:59.
const clock = (ms: number): string => {
const seconds = Math.max(0, Math.ceil(ms / 1000));
const minutes = String(Math.floor(seconds / 60)).padStart(2, '0');
const rest = String(seconds % 60).padStart(2, '0');
return `${minutes}:${rest}`;
};
export default definePlugin({
onload(ctx: PluginContext) {
// The number of pomodoros completed on a row. Its merge kind is `counter`, so when two devices each complete
// a pomodoro at the same moment, both are counted.
const sessions = ctx.facets.define<number>({
key: 'com.example.pomodoro/sessions',
on: 'row',
merge: 'counter',
paths: ['.'],
alias: 'pomodoro',
schema: { type: 'integer', minimum: 0 },
});
// The timer of a row. It stays on the device that started it (`sync: false`). If it were synchronized, every device
// would ring when the time was up, and each of them would add a pomodoro.
const timer = ctx.facets.define<Timer>({
key: 'com.example.pomodoro/timer',
on: 'row',
merge: 'lww',
sync: false,
schema: {
type: 'object',
properties: {
state: { enum: ['running', 'paused'] },
endsAt: { type: 'integer' },
left: { type: 'integer', minimum: 0 },
},
required: ['state', 'left'],
},
});
// The rows that have a timer, whether it is running or paused. Only one timer can run at a time.
const timed = new Map<string, Timer>();
// The time that a timer has left to run.
const remaining = (t: Timer): number => {
if (t.state === 'running') {
return Math.max(0, (t.endsAt ?? 0) - ctx.clock.now());
}
return t.left;
};
// Every command of the plugin receives the id of a row, which the menu of the row supplies.
const arg = { type: 'object', properties: { id: { type: 'string' } }, required: ['id'] };
// Start: available on a to-do when no other timer is running.
const start = ctx.commands.register<{ id: string }>({
id: 'com.example.pomodoro/start',
title: 'Start a pomodoro',
icon: 'timer',
placements: ['row-menu'],
args: arg,
can: (state, _focus, args) => {
const row = args?.id ? state.row(args.id) : undefined;
if (!args?.id || !row) {
return { available: true };
}
if (row.marker !== 'task') {
return { available: false, reason: 'Only to-dos' };
}
if (timed.has(args.id)) {
return { available: false, reason: 'Already started' };
}
if (timed.size > 0) {
return { available: false, reason: 'Another pomodoro is running' };
}
return { available: true };
},
propose(state, args, draft) {
if (!state.row(args.id)) {
throw new Error(`There is no row ${args.id}`);
}
// The change writes the timer to the row. From then on, the plugin follows the value of the timer.
draft.facet(args.id, timer).set({ state: 'running', endsAt: ctx.clock.now() + FULL_MS, left: FULL_MS });
return draft;
},
});
// Pause: available while the timer is running.
const pause = ctx.commands.register<{ id: string }>({
id: 'com.example.pomodoro/pause',
title: 'Pause the pomodoro',
icon: 'pause',
placements: ['row-menu'],
args: arg,
can: (_state, _focus, args) => {
if (!args?.id || timed.get(args.id)?.state === 'running') {
return { available: true };
}
return { available: false, reason: 'Not running' };
},
propose(_state, args, draft) {
const t = timed.get(args.id);
if (t?.state !== 'running') {
throw new Error('The pomodoro is not running');
}
// A paused timer keeps the time that it has left to run.
draft.facet(args.id, timer).set({ state: 'paused', left: remaining(t) });
return draft;
},
});
// Resume: available while the timer is paused.
const resume = ctx.commands.register<{ id: string }>({
id: 'com.example.pomodoro/resume',
title: 'Resume the pomodoro',
icon: 'timer',
placements: ['row-menu'],
args: arg,
can: (_state, _focus, args) => {
if (!args?.id || timed.get(args.id)?.state === 'paused') {
return { available: true };
}
return { available: false, reason: 'Not paused' };
},
propose(_state, args, draft) {
const t = timed.get(args.id);
if (t?.state !== 'paused') {
throw new Error('The pomodoro is not paused');
}
draft.facet(args.id, timer).set({ state: 'running', endsAt: ctx.clock.now() + t.left, left: t.left });
return draft;
},
});
// Cancel: available while the row has a timer. It removes the timer without counting a pomodoro.
const cancel = ctx.commands.register<{ id: string }>({
id: 'com.example.pomodoro/cancel',
title: 'Cancel the pomodoro',
icon: 'close',
placements: ['row-menu'],
args: arg,
can: (_state, _focus, args) => {
if (!args?.id || timed.has(args.id)) {
return { available: true };
}
return { available: false, reason: 'No pomodoro' };
},
propose(_state, args, draft) {
draft.facet(args.id, timer).remove();
return draft;
},
});
// Finish: not shown in any menu. When the time is up, it adds one to the counter and removes the timer, in a single change.
const finish = ctx.commands.register<{ id: string }>({
id: 'com.example.pomodoro/finish',
title: 'Finish a pomodoro',
icon: 'timer',
args: arg,
can: (state, _focus, args) => {
const row = args?.id ? state.row(args.id) : undefined;
if (!row || row.marker === 'task') {
return { available: true };
}
return { available: false, reason: 'Only to-dos' };
},
propose(state, args, draft) {
const row = state.row(args.id);
if (!row) {
throw new Error(`There is no row ${args.id}`);
}
draft.facet(row.id, sessions).set((sessions.of(row) ?? 0) + 1);
draft.facet(row.id, timer).remove();
return draft;
},
});
// The mark on the row: 🍅 followed by the number of pomodoros, and ▶ or ⏸ while the row has a timer.
ctx.ui.decorate({ on: 'row', facets: [sessions, timer] }, row => {
const count = sessions.of(row);
const t = timer.of(row);
if (!count && !t) {
return undefined;
}
return {
...(count ? { badge: `🍅 ${count}` } : {}),
...(t ? { pill: t.state === 'running' ? '▶' : '⏸' } : {}),
};
});
// An event that the plugin sends each time a pomodoro is completed. Other plugins can subscribe to it.
const didFinish = ctx.notifications.declare<{ sessions: number }>('didFinish');
// The card of each timer: its text, a bar that fills as time passes, and two buttons.
const cards = new Map<string, ReturnType<PluginContext['ui']['alert']>>();
const show = (id: string, t: Timer): void => {
const title = ctx.state.row(id)?.title ?? '';
const paused = t.state === 'paused' ? 'paused ' : '';
const text = `${title} · ${paused}${clock(remaining(t))}`;
const progress = 1 - remaining(t) / FULL_MS;
// Each button runs a command of this plugin on this row.
const first = t.state === 'running'
? { id: 'pause', title: 'Pause', icon: 'pause', command: pause.id, args: { id } }
: { id: 'resume', title: 'Resume', icon: 'play', command: resume.id, args: { id } };
const actions = [
first,
{ id: 'cancel', title: 'Cancel', icon: 'close', command: cancel.id, args: { id } },
];
const card = cards.get(id);
if (card) {
card.update({ text, progress, actions });
} else {
cards.set(id, ctx.ui.alert({ id: `timer:${id}`, icon: 'timer', text, progress, actions }));
}
};
const hide = (id: string): void => {
cards.get(id)?.dispose();
cards.delete(id);
};
// A loop for each running timer. Every second, it reads the timer again, so that it notices a pause, a cancellation
// or a new start. When the time is up, it finishes the pomodoro.
const ticking = new Set<string>();
const tick = async (id: string): Promise<void> => {
if (ticking.has(id)) {
return;
}
ticking.add(id);
try {
for (;;) {
const t = timed.get(id);
if (t?.state !== 'running') {
return;
}
if (remaining(t) <= 0) {
const title = ctx.state.row(id)?.title ?? '';
await ctx.dispatch(finish.intent({ id }));
ctx.ui.notice({ text: `Pomodoro done: ${title}` });
return;
}
show(id, t);
await ctx.jobs.sleep(Math.min(TICK_MS, remaining(t)));
}
} finally {
ticking.delete(id);
}
};
// Called when the timer of a row changes, and when the plugin starts. The card and the loop are updated to match the timer.
const follow = (id: string): void => {
const row = ctx.state.row(id);
const t = row ? timer.of(row) : undefined;
if (!t) {
timed.delete(id);
hide(id);
return;
}
timed.set(id, t);
show(id, t);
if (t.state === 'running') {
void tick(id);
}
};
// Watches each row that has a counter or a timer. When the counter increases, the plugin sends the event. When the
// timer changes, the plugin follows it.
const watched = new Set<string>();
const watch = (id: string): void => {
if (watched.has(id)) {
return;
}
watched.add(id);
ctx.observe(sessions.on(id), { old: true, new: true }, ({ old, new: now }) => {
if ((now ?? 0) > (old ?? 0)) {
ctx.notifications.post(didFinish, id, { sessions: now ?? 0 });
}
});
ctx.observe(timer.on(id), { new: true }, () => follow(id));
};
// When the plugin starts, it watches the rows that already have a counter or a timer. A timer that was running when
// the app was closed continues, or finishes if its time has already passed.
for (const outline of ctx.state.outlines()) {
for (const row of ctx.state.outlineRows(outline.id)) {
if (sessions.of(row) !== undefined || timer.of(row) !== undefined) {
watch(row.id);
}
if (timer.of(row) !== undefined) {
follow(row.id);
}
}
}
// After that, the plugin watches each row that gains a counter or a timer through a change.
ctx.hooks.didUpdate({ topics: ['row.*'] }, change => {
for (const delta of change.deltas) {
if (delta.kind !== 'updated' || delta.ref.kind !== 'row' || !delta.fields.includes('facets')) {
continue;
}
const after = delta.after as { facets: Record<string, unknown> };
if (sessions.of(after) !== undefined || timer.of(after) !== undefined) {
watch(delta.ref.id);
follow(delta.ref.id);
}
}
});
},
});

4. Requesting another change after a change

Section titled “4. Requesting another change after a change”

This plugin archives an outline as soon as its last open to-do is completed.

The plugin registers a hook with ctx.hooks.didUpdate. The app calls this hook after a change has been applied, and passes it the change. A didUpdate hook cannot modify the change that has just been applied, but it can ask for further changes by returning followUps, a list of intents. An intent is a request for a change, which the app checks and applies in the same way as any other change. In this example, when a change has closed the last open to-do of an outline, the hook returns an intent that archives that outline.

The app runs each follow-up as a separate change and adds it to the undo step of the change that caused it, so a single undo reverses both the completion of the to-do and the archiving of the outline. Before running a follow-up, the app also checks that the plugin has the permission that the follow-up requires, which here is write:outlines.

// auto-archive: archives an outline when its last open to-do is completed. Permissions: read, write:outlines.
import { definePlugin, type PluginContext } from '@tessera/plugin-sdk';
export default definePlugin({
onload(ctx: PluginContext) {
// The state of a to-do, as the to-do feature stores it.
const status = ctx.facets.core.tasks.status;
// Whether a to-do is done or cancelled.
const closed = (entity: { readonly facets: Readonly<Record<string, unknown>> }): boolean => {
const state = status.of(entity)?.state ?? '';
return state === 'done' || state === 'cancelled';
};
// The app calls this hook after each change that touches rows.
ctx.hooks.didUpdate({ topics: ['row.*'] }, change => {
// The outlines in which this change closed a to-do.
const outlines = new Set<string>();
for (const delta of change.deltas) {
if (delta.kind !== 'updated' || delta.ref.kind !== 'row' || !delta.fields.includes('facets')) {
continue;
}
const wasOpen = !closed({ facets: (delta.before.facets ?? {}) as Record<string, unknown> });
const isDone = closed({ facets: (delta.after.facets ?? {}) as Record<string, unknown> });
if (wasOpen && isDone) {
const row = ctx.state.row(delta.ref.id);
if (row) {
outlines.add(row.outline);
}
}
}
// For each of those outlines whose to-dos are now all closed, a request to archive the outline.
const followUps = [...outlines].flatMap(id => {
const outline = ctx.state.outline(id);
if (!outline || outline.kind !== 'standard' || outline.archived) {
return [];
}
const todos = ctx.state.outlineRows(id).filter(row => status.of(row) !== undefined);
if (todos.length === 0 || !todos.every(closed)) {
return [];
}
return [ctx.outlines.modify.intent({ id, archived: true })];
});
// The app runs the requests as further changes, in the same undo step as this change, so a single undo reverses both.
return followUps.length > 0 ? { followUps } : undefined;
});
},
});

This plugin counts the words in the titles of the rows. Each time a change adds or removes words, the plugin sends an event that carries the new total. The plugin also subscribes to that event, and writes the total to the log when the person stops typing.

The example uses three functions of ctx.notifications:

  • ctx.notifications.declare declares a new event, here named didChange. The full name of the event begins with the id of the plugin. The type parameter describes the data that the event carries, which here is a number named total.
  • ctx.notifications.post sends the event to every subscriber.
  • ctx.notifications.subscribe registers a function that receives the event. The style idle delays the call until the person stops typing, and coalesce: 'onName' combines events with the same name that arrive in quick succession into a single call.

A plugin can also watch a single value instead of subscribing to an event. ctx.observe calls a function each time the value changes, and passes it the old value and the new one. The second block below shows how.

// word-count: counts the words in the titles of the rows, and writes the total to the log when the person stops typing.
// Permissions: read, notifications.
import { definePlugin, type Change, type PluginContext } from '@tessera/plugin-sdk';
// The number of words in a text.
const words = (text: unknown): number => {
if (typeof text !== 'string' || !text.trim()) {
return 0;
}
return text.trim().split(/\s+/).length;
};
// The number of words that a change added to the titles. The number is negative when the change removed words.
const wordsAdded = (change: Change): number => {
let added = 0;
for (const delta of change.deltas) {
if (delta.kind === 'moved' || delta.ref.kind !== 'row') {
continue;
}
if (delta.kind === 'created') {
added += words((delta.value as { title?: string }).title);
} else if (delta.kind === 'deleted') {
added -= words((delta.value as { title?: string }).title);
} else if (delta.kind === 'updated' && delta.fields.includes('title')) {
added += words(delta.after.title) - words(delta.before.title);
}
}
return added;
};
export default definePlugin({
onload(ctx: PluginContext) {
// The event, declared once. Its full name begins with the id of the plugin, and it carries { total }.
const didChange = ctx.notifications.declare<{ total: number }>('didChange');
// The number of words in the library when the plugin starts.
let total = 0;
for (const outline of ctx.state.outlines()) {
for (const row of ctx.state.outlineRows(outline.id)) {
total += words(row.title);
}
}
// After each change, the plugin updates the total and sends it with the event.
ctx.hooks.didUpdate({ topics: ['row.*'] }, change => {
const added = wordsAdded(change);
if (added !== 0) {
total += added;
ctx.notifications.post(didChange, undefined, { total });
}
});
// The app calls this function when the person stops typing. Several events sent in quick succession result in a single call.
ctx.notifications.subscribe(
{ topic: didChange },
{ style: 'idle', coalesce: 'onName' },
event => {
ctx.log('info', `${event.info?.total ?? total} words`);
},
);
},
});

The following code, placed inside onload, watches a single value, here a facet on one row:

// This watches the number of pomodoros on one row. `sessions` is the handle that ctx.facets.define returned, and `rowId`
// is the id of the row. A value that the app publishes, such as ctx.keys.net.sync, is watched in the same way.
ctx.observe(sessions.on(rowId), { old: true, new: true }, change => {
// The value before the change, and the value after it.
ctx.log('info', `${change.old ?? 0} → ${change.new ?? 0} pomodoros`);
});

This plugin adds an item to the menu that opens when the person types / in a note. The item turns the current line into a callout, which is a quoted line that begins with a bold “Note:”.

Features and plugins add items to this menu with the same call, ctx.ui.slashItem. The blocks that ship with the app, which are headings, quotes, dividers, tables and lists, are added in this way too.

An item has a title, a description and an icon, which the menu displays, and an apply function. When the person picks the item, the app calls apply with the text of the note, the position of the / and the position of the caret. The function returns the new text and the new position of the caret. It must not have any other effect, such as changing a row or displaying a message.

// callout: adds an item to the / menu of a note. Permission: ui.
import { definePlugin, type PluginContext } from '@tessera/plugin-sdk';
// The text that begins a callout line.
const MARK = '> **Note:** ';
export default definePlugin({
onload(ctx: PluginContext) {
ctx.ui.slashItem({
id: 'callout',
title: 'Callout',
desc: 'A highlighted note.',
icon: 'quote',
// The app passes the text of the note, the position of the / and the position of the caret. The function returns
// the new text and the new position of the caret, and has no other effect.
apply(text, start, caret) {
// The line that contains the /.
const lineStart = text.lastIndexOf('\n', start - 1) + 1;
const newline = text.indexOf('\n', caret);
const lineEnd = newline < 0 ? text.length : newline;
// The text of the line, without the / and what was typed after it.
const rest = (text.slice(lineStart, start) + text.slice(caret, lineEnd)).replace(/^> \*\*Note:\*\* /, '').trim();
const line = MARK + rest;
return {
text: text.slice(0, lineStart) + line + text.slice(lineEnd),
caret: lineStart + line.length,
};
},
});
},
});

Plugins draw panels and outline types with the components of ctx.ui, which are functions such as ctx.ui.stack, ctx.ui.text and ctx.ui.button. The following plugin adds a small panel to the sidebar, with a counter and a button that increases it:

// counter: a panel in the sidebar, drawn with the components of ctx.ui. Permission: ui.
import { definePlugin, type PluginContext } from '@tessera/plugin-sdk';
export default definePlugin({
onload(ctx: PluginContext) {
// The number that the panel displays. The plugin keeps it in a variable, and the app draws the panel again after a
// button is pressed.
let sessions = 0;
// An entry in the sidebar that opens the panel.
ctx.ui.sidebarEntry({ id: 'today', title: 'Today', icon: 'chart', panel: 'today' });
// The panel. Each component is a function of ctx.ui, so a misspelled property name is reported as a type error.
ctx.ui.panel({
id: 'today',
title: 'Today',
render: () => ctx.ui.stack({ axis: 'vertical', gap: 8 }, [
ctx.ui.text({ text: `Sessions: ${sessions}`, style: 'title' }),
ctx.ui.progress({ value: Math.min(100, sessions * 25), label: 'Goal: 4' }),
// A handler is a function. The arguments that it receives depend on the component.
ctx.ui.button({ title: 'Add a session', action: () => { sessions += 1; } }),
]),
});
},
});

This plugin displays a card while the library is being synchronized with the person’s other devices. The card has a progress bar that fills as the other devices receive the change. When the synchronization ends, the card shows “Synced” for a moment, then disappears. This plugin ships with the app.

The plugin takes its numbers from values that the app publishes, and it watches them with ctx.observe. While a synchronization is running, the app publishes ctx.keys.net.sync, a value of the form { active, done, total }, in which total is the number of connected devices and done is the number of those devices that already have the change.

The app also publishes a value for each device. ctx.keys.net.devices is the list of the ids of the devices, and ctx.keys.net.device(id) is the value for one device, of the form { name, connected, current, last, sent, received }:

  • name is the name of the device.
  • connected states whether a connection to the device is open.
  • current states whether the device has every change that this device has.
  • last is the time of the last synchronization between the two devices.
  • sent and received are the numbers of bytes sent to the device and received from it since the app started.

When a synchronization starts, the plugin records the values of sent and received for each device. While the synchronization runs and after it ends, the plugin subtracts the recorded values from the current ones, and shows the result in the detail line of the card, for example “Phone · ↑ 2.0 KB ↓ 1.5 MB”.

ctx.ui.alert displays a card at the top right of the screen, optionally with a progress bar. The object that it returns has two methods: update changes the card, for example to move the bar, and dispose removes it. The plugin needs the ui permission to display the card, and the jobs permission for ctx.jobs.sleep, which waits a moment before the card is removed.

/* sync-alert: displays a card with a progress bar while the library is being synchronized with the person's other devices.
The bar fills as the other devices receive the change. A line under the text names the devices involved, and shows how many
bytes were sent and received. When the synchronization ends, the card says "Synced" for a moment and then disappears.
The example shows how to watch values that the app publishes (`ctx.keys.net`), and how to display a card (`ctx.ui.alert`).
Permissions: read, ui, jobs. */
import { definePlugin, type PluginContext } from '@tessera/plugin-sdk';
// How long the card stays on screen with a full bar before it disappears.
const LINGER_MS = 700;
// What the app publishes about one device: its name, whether it is connected, and the numbers of bytes sent to it
// and received from it since the app started.
interface Peer {
readonly name: string | null;
readonly connected: boolean;
readonly sent: number;
readonly received: number;
}
// Formats a number of bytes in B, KB or MB.
const size = (bytes: number): string => {
if (bytes < 1024) {
return `${bytes} B`;
}
if (bytes < 1024 * 1024) {
return `${(bytes / 1024).toFixed(1)} KB`;
}
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
};
export default definePlugin({
onload(ctx: PluginContext) {
// The card, while it is on screen.
let card: ReturnType<PluginContext['ui']['alert']> | undefined;
// Increases each time the app publishes a new synchronization state. The card is removed only if no new state
// arrived while it was waiting to disappear.
let turn = 0;
// The phase that the card shows (a synchronization in progress, or a finished one whose card has not yet
// disappeared), and the progress of the bar.
let phase: 'syncing' | 'synced' | undefined;
let progress = 0;
// The devices, as the app last described them.
const peers = new Map<string, Peer>();
// The bytes that each device had sent and received when this synchronization began, so that the card shows only
// what was transferred during this synchronization.
const began = new Map<string, { sent: number; received: number }>();
// The devices that take part in this synchronization.
const involved = new Set<string>();
// The devices whose value the plugin is already watching.
const watching = new Set<string>();
// The line under the text: the devices involved, and the numbers of bytes sent and received.
const detail = (): string | undefined => {
if (involved.size === 0) {
return undefined;
}
const names = [...involved].map(id => peers.get(id)?.name || `Device ${id.slice(0, 6)}`);
let up = 0;
let down = 0;
for (const id of involved) {
const now = peers.get(id);
const was = began.get(id);
if (now) {
up += now.sent - (was?.sent ?? 0);
down += now.received - (was?.received ?? 0);
}
}
const moved = [up > 0 ? `↑ ${size(up)}` : '', down > 0 ? `↓ ${size(down)}` : ''].filter(Boolean).join(' ');
const who = names.length > 2 ? `${names.length} devices` : names.join(', ');
return moved ? `${who} · ${moved}` : who;
};
// The content of the card at this moment.
const patch = () => ({
text: phase === 'synced' ? 'Synced' : 'Syncing…',
detail: detail(),
progress,
});
// The app publishes each device under a separate key. When the value of a device changes, the plugin stores it and
// updates the card if the card is on screen.
const hear = (id: string, peer: Peer | undefined): void => {
if (peer) {
peers.set(id, peer);
if (phase === 'syncing' && peer.connected) {
involved.add(id);
}
} else {
peers.delete(id);
involved.delete(id);
}
// The app announces the end of a synchronization before the final byte counts of the devices arrive, so the card
// continues to be updated after it says "Synced".
if (card && phase) {
card.update(patch());
}
};
// The list of devices. The plugin starts watching the key of each new device.
ctx.observe(ctx.keys.net.devices, { new: true, initial: true }, change => {
for (const id of change.new ?? []) {
if (watching.has(id)) {
continue;
}
watching.add(id);
ctx.observe(ctx.keys.net.device(id), { new: true, initial: true }, one => hear(id, one.new));
}
});
// The app publishes the state of each synchronization under this key, as { active, done, total }.
ctx.observe(ctx.keys.net.sync, { new: true }, change => {
const sync = change.new;
const mine = ++turn;
// While a synchronization is running, the card shows it, and the bar shows the share of devices that have the change.
if (sync?.active) {
if (phase !== 'syncing') {
// A new synchronization: the plugin records how many bytes each device has sent and received so far, and
// which devices take part.
phase = 'syncing';
began.clear();
involved.clear();
for (const [id, peer] of peers) {
began.set(id, { sent: peer.sent, received: peer.received });
if (peer.connected) {
involved.add(id);
}
}
}
progress = sync.total > 0 ? sync.done / sync.total : 0;
if (card) {
card.update(patch());
} else {
const first = patch();
card = ctx.ui.alert({
id: 'sync',
icon: 'sync',
text: first.text,
...(first.detail ? { detail: first.detail } : {}),
progress,
});
}
return;
}
// The synchronization has finished: the card says so, remains on screen briefly, and then disappears, unless
// another synchronization has started in the meantime.
if (!card) {
return;
}
phase = 'synced';
progress = 1;
card.update(patch());
void ctx.jobs.sleep(LINGER_MS).then(() => {
if (mine !== turn) {
return;
}
card?.dispose();
card = undefined;
phase = undefined;
});
});
},
});

This plugin hides every row marked “later”, together with the rows under it.

ctx.query.hideRows registers a rule, which is a function that an outline calls to decide which rows to leave out. When the rule returns true for a row, the outline hides that row and all the rows under it.

By default, the outline calls the rule for every row that it contains, which is slow for an outline of tens of thousands of rows. To avoid this, the plugin can give the rule a narrow function, which uses the index of a facet to return the ids of the rows that might be hidden. The outline then calls the rule only for those rows, so the cost of opening part of an outline depends on the size of that part and not on the size of the whole outline. For the index to exist, the facet must declare paths, which lists the parts of its value that the app indexes.

ctx.query.filter registers a similar rule for searches and for lists such as Today. Its when function states whether the rule can hide anything in a given search. When when returns false, the app does not check any row.

// later: hides the rows marked "later", together with the rows under them. Permission: read.
import { definePlugin, type PluginContext } from '@tessera/plugin-sdk';
export default definePlugin({
onload(ctx: PluginContext) {
// The mark. `paths` asks the app to index the value, so that the rows marked "later" can be found without checking
// every row.
const later = ctx.facets.define<string>({
key: 'com.example.later/state',
on: 'row',
merge: 'lww',
paths: ['.'],
schema: { type: 'string', enum: ['later'] },
});
// In an outline, the rows marked "later" are hidden.
ctx.query.hideRows(row => later.of(row) === 'later', {
// The rows that might be hidden, taken from the index. Only these rows are checked, so an outline of 50,000 rows still
// opens quickly. Without `narrow`, the app would call the rule for every row of the outline.
narrow: lookup => lookup.index(later, '.')?.eq('later') ?? [],
});
// In searches and lists, such as Today and the counts, the rows marked "later" are left out.
ctx.query.filter(row => later.of(row) !== 'later', {
// `when` states whether the filter can hide anything. A search that includes archived outlines shows every row, so
// the filter does not apply to it.
when: (_view, options) => !options.archived,
});
},
});

This plugin encrypts an outline with a password. It ships with the app, and the code below is the plugin.

For each row of an encrypted outline, the plugin encrypts the title and the note together, with a key derived from the password through ctx.crypto. Only the encrypted text is saved, written to the log, synchronized and included in backups, and the row shows a lock symbol in place of its title and its note.

While the outline is unlocked, the plugin tells the page what each row says through ctx.rows.reveal, and nothing else reads the readable text. When the person types, the change passes through a shouldUpdate hook, in which the plugin replaces the readable text with encrypted text before the change is applied. Modifying a change in this way requires the amend:outside permission. As a result, the readable text is never written anywhere.

The key is kept in memory only, and it is erased when the outline is locked or the app is closed. The plugin asks for the password with ctx.ui.password. Deriving the key from the password takes about a second, so this work runs as a job (ctx.jobs) rather than inside the command. The lock shown next to the outline in the sidebar is added with ctx.ui.outlineIcon, and pressing it locks or unlocks the outline.

This version has the following limits.

  • The plugin encrypts titles and notes, but not facets such as tags, dates and the state of a to-do. These remain readable, because the features that use them read them from the saved row.
  • The structure of the tree remains readable, because synchronization needs it to merge changes.
  • Rows cannot be moved into or out of an encrypted outline.
  • A lost password cannot be recovered, and without it the encrypted text cannot be read.
/* vault: encrypts an outline with a password.
The title and the note of each row are saved, written to the log, synchronized and backed up only in encrypted form
(XChaCha20-Poly1305, with a key that scrypt derives from the password), and the row shows a lock in their place.
While the outline is unlocked, the key is kept in memory, and the page displays the readable text through `ctx.rows.reveal`,
which nothing else reads. What the person types is encrypted before the change is applied, so the readable text is never
written anywhere. The structure of the tree remains readable, because synchronization needs it to merge changes.
The example shows `ctx.crypto`, `ctx.rows.reveal`, a change that is modified before it is applied (`shouldUpdate`),
a password requested in a dialog, and jobs.
Permissions: read, write:rows, write:outlines, amend:outside, ui, jobs, crypto. */
import { allow, amend, definePlugin, veto, type ChangeDraft, type Delta, type PluginContext, type SealingKey, type VaultParams } from '@tessera/plugin-sdk';
// The text that the saved row shows in place of its title and its note.
const LOCK = '🔒';
// What an encrypted row contains: its title and its note, which are encrypted together.
interface Payload {
readonly title: string;
readonly note: string | null;
}
// What an encrypted outline stores: the parameters of its key, and a short text encrypted with the key, which is used
// to check whether a password is correct.
interface Vault {
readonly params: VaultParams;
readonly check: string;
}
// The fields of a row that the plugin reads.
interface RowLike {
readonly id: string;
readonly outline: string;
readonly facets: Readonly<Record<string, unknown>>;
}
export default definePlugin({
onload(ctx: PluginContext) {
// Stored on an encrypted outline: the parameters of its key, and the check text.
const vaultFacet = ctx.facets.define<Vault>({
key: 'tessera.vault/vault',
on: 'outline',
merge: 'lww',
schema: { type: 'object', properties: { params: { type: 'object' }, check: { type: 'string' } }, required: ['params', 'check'] },
});
// Stored on each row of an encrypted outline: the title and the note, encrypted.
const dataFacet = ctx.facets.define<string>({
key: 'tessera.vault/data',
on: 'row',
merge: 'lww',
schema: { type: 'string' },
});
// The keys of the outlines that are unlocked. They are kept in memory only, and they are forgotten when the outline
// is locked or the app is closed.
const keys = new Map<string, SealingKey>();
// A key created for an outline that is being encrypted, and not yet used.
const pending = new Map<string, { key: SealingKey; params: VaultParams }>();
// The outlines whose encryption is being removed. Text written in them during the removal is not encrypted again.
const removing = new Set<string>();
// The decrypted content of each row, kept so that a row is not decrypted again while it has not changed.
const opened = new Map<string, { sealed: string; payload: Payload }>();
// Whether an outline is encrypted.
const isVault = (outline: string): boolean => {
const found = ctx.state.outline(outline);
return !!found && vaultFacet.of(found) !== undefined && !removing.has(outline);
};
// The place that an encrypted text belongs to. An encrypted text that is copied to another row cannot be decrypted there.
const place = (id: string): string => `row:${id}`;
// The readable title and note of a row, when its outline is unlocked.
const open = (row: RowLike): Payload | undefined => {
const key = keys.get(row.outline);
const sealed = dataFacet.of(row as never);
if (!key || sealed === undefined) {
return undefined;
}
const hit = opened.get(row.id);
if (hit?.sealed === sealed) {
return hit.payload;
}
try {
const payload = JSON.parse(key.open(sealed, place(row.id))) as Payload;
opened.set(row.id, { sealed, payload });
return payload;
} catch {
return undefined;
}
};
// The page shows the readable text while the outline is unlocked, and the lock otherwise.
const reveal = ctx.rows.reveal(row => {
if (!isVault(row.outline) || dataFacet.of(row) === undefined) {
return undefined;
}
const payload = open(row);
return payload ? { title: payload.title, note: payload.note } : undefined;
});
// Called for every change before it is applied. Text that enters an encrypted outline is encrypted, and the change is
// refused when the text cannot be encrypted.
ctx.hooks.shouldUpdate({}, proposal => {
let changed = false;
const deltas: Delta[] = [];
for (const delta of proposal.deltas) {
const result = guard(delta);
if ('veto' in result) {
return result;
}
if (result.delta) {
changed = true;
}
deltas.push(result.delta ?? delta);
}
return changed ? amend<ChangeDraft>({ ...proposal, deltas }, 'sealed') : allow();
});
// Examines one part of a change, and either leaves it as it is, replaces it with an encrypted version, or refuses it.
function guard(delta: Delta): { delta?: Delta } | { veto: { code: string; message: string } } {
// A row cannot be moved into or out of an encrypted outline.
if (delta.kind === 'moved') {
const across = delta.from.outline !== delta.to.outline;
if (across && (isVault(delta.from.outline) || isVault(delta.to.outline))) {
return veto('vault', 'Rows cannot move into or out of an encrypted outline');
}
return {};
}
// A new row in an encrypted outline: its title and its note are encrypted, and the row shows the lock.
if (delta.kind === 'created' && delta.ref.kind === 'row') {
const value = delta.value as { id: string; outline: string; title: string; note: string | null; facets: Record<string, unknown> };
if (!isVault(value.outline) || dataFacet.of(value as never) !== undefined) {
return {};
}
const key = keys.get(value.outline);
if (!key) {
return veto('locked', 'This outline is locked: unlock it first');
}
const sealed = key.seal(JSON.stringify({ title: value.title, note: value.note }), place(value.id));
return { delta: { ...delta, value: { ...value, title: LOCK, note: LOCK, facets: { ...value.facets, [dataFacet.key]: sealed } } } };
}
// A row of an encrypted outline whose title or note changes: the new text is encrypted together with the rest.
if (delta.kind === 'updated' && delta.ref.kind === 'row') {
const row = ctx.state.row(delta.ref.id);
if (!row || !isVault(row.outline)) {
return {};
}
const writesTitle = delta.fields.includes('title') && delta.after.title !== LOCK;
const writesNote = delta.fields.includes('note') && delta.after.note !== LOCK;
if (!writesTitle && !writesNote) {
return {};
}
const key = keys.get(row.outline);
if (!key) {
return veto('locked', 'This outline is locked: unlock it first');
}
const was = open(row);
if (!was) {
return veto('vault', 'This row cannot be read with this password');
}
const next: Payload = {
title: writesTitle ? String(delta.after.title) : was.title,
note: writesNote ? (delta.after.note as string | null) : was.note,
};
// The title and the note are removed from the change, and the encrypted text is stored in their place.
const without = (side: Record<string, unknown>): Record<string, unknown> => {
const { title: _title, note: _note, ...others } = side;
return others;
};
const facets = (delta.after.facets as Record<string, unknown> | undefined) ?? row.facets;
return {
delta: {
...delta,
fields: [...new Set([...delta.fields.filter(f => f !== 'title' && f !== 'note'), 'facets'])],
before: { ...without(delta.before), facets: row.facets },
after: { ...without(delta.after), facets: { ...facets, [dataFacet.key]: key.seal(JSON.stringify(next), place(row.id)) } },
},
};
}
return {};
}
// Typing in a locked outline is stopped at the first key, and the person sees the reason.
ctx.editing.shouldChangeText({ topics: ['row.title', 'row.note'] }, change => {
const row = change.field.entity.kind === 'row' ? ctx.state.row(change.field.entity.id) : undefined;
if (row && isVault(row.outline) && !keys.has(row.outline)) {
return veto('locked', 'This outline is locked: unlock it first');
}
return allow();
});
// A lock next to each encrypted outline in the sidebar. While the outline is locked, the lock is closed, and pressing
// it unlocks the outline. While the outline is unlocked, the lock is open, and pressing it locks the outline.
const lights = new Map<string, ReturnType<PluginContext['ui']['outlineIcon']>>();
const light = (): void => {
const wanted = new Set<string>();
for (const outline of ctx.state.outlines()) {
if (vaultFacet.of(outline) === undefined || removing.has(outline.id)) {
continue;
}
wanted.add(outline.id);
const unlocked = keys.has(outline.id);
const shape = {
icon: unlocked ? 'unlock' : 'lock',
title: unlocked ? 'Lock outline' : 'Unlock outline…',
command: unlocked ? 'tessera.vault/lock' : 'tessera.vault/unlock',
args: { outline: outline.id },
};
const had = lights.get(outline.id);
if (had) {
had.update(shape);
} else {
lights.set(outline.id, ctx.ui.outlineIcon({ outline: outline.id, ...shape }));
}
}
for (const [id, handle] of lights) {
if (!wanted.has(id)) {
handle.dispose();
lights.delete(id);
}
}
};
light();
ctx.hooks.didUpdate({ topics: ['outline.*'] }, () => {
light();
});
// Every command in the menu of an outline receives the id of the outline.
const arg = { type: 'object', properties: { outline: { type: 'string' } }, required: ['outline'] };
const outlineOf = (state: { outline(id: string): unknown }, args: { outline: string } | undefined) =>
(args?.outline ? state.outline(args.outline) as { id: string; kind: string; facets: Record<string, unknown> } | undefined : undefined);
const vaultOf = (outline: string): Vault | undefined => {
const found = ctx.state.outline(outline);
return found ? vaultFacet.of(found) : undefined;
};
// Asks for the password and derives the key. This takes about a second, so it runs in a job rather than in the command.
const keyFor = async (outline: string, vault: Vault, title: string, action?: string): Promise<SealingKey | undefined> => {
const asked = await ctx.ui.password({ title, ...(action ? { action } : {}) });
if ('cancelled' in asked) {
return undefined;
}
const key = await ctx.crypto.deriveKey(asked.value, vault.params);
try {
key.open(vault.check, `outline:${outline}`);
} catch {
ctx.ui.notice({ text: 'The password is wrong', level: 'error' });
return undefined;
}
return key;
};
// Encrypt: asks for a new password twice, derives a key, and runs the command that encrypts every row.
ctx.commands.register<{ outline: string }>({
id: 'tessera.vault/encrypt',
title: 'Encrypt outline…',
icon: 'lock',
placements: ['outline-menu'],
args: arg,
discardable: true,
can: (state, _focus, args) => {
const outline = outlineOf(state, args);
if (!outline) {
return { available: true };
}
if (outline.kind === 'inbox') {
return { available: false, reason: 'The Inbox cannot be encrypted' };
}
if (vaultFacet.of(outline as never) !== undefined) {
return { available: false, reason: 'Already encrypted' };
}
return { available: true };
},
propose(_state, args, draft) {
void ctx.jobs.run(async () => {
const asked = await ctx.ui.password({
title: 'Encrypt outline',
message: 'The titles and notes of this outline will be locked with this password. If you lose it, nothing can bring them back.',
confirm: true,
action: 'Encrypt',
});
if ('cancelled' in asked) {
return;
}
const params = ctx.crypto.newParams();
const key = await ctx.crypto.deriveKey(asked.value, params);
pending.set(args.outline, { key, params });
keys.set(args.outline, key);
const outcome = await ctx.dispatch(seal.intent({ outline: args.outline }));
pending.delete(args.outline);
if (outcome.status !== 'committed') {
keys.delete(args.outline);
}
reveal.changed();
light();
});
return draft;
},
});
// The single change that encrypts the outline: it puts the lock in every row, stores the encrypted text of each row
// in a facet, and stores the check text on the outline.
const seal = ctx.commands.register<{ outline: string }>({
id: 'tessera.vault/seal',
title: 'Encrypt outline…',
args: arg,
discardable: false,
propose(state, args, draft) {
const made = pending.get(args.outline);
if (!made) {
throw new Error('There is no password to lock with');
}
for (const row of state.outlineRows(args.outline)) {
if (row.outline !== args.outline) {
continue;
}
draft.update(row.id, { title: LOCK, note: LOCK });
draft.facet(row.id, dataFacet).set(made.key.seal(JSON.stringify({ title: row.title, note: row.note }), place(row.id)));
}
draft.facet(args.outline, vaultFacet).set({ params: made.params, check: made.key.seal('tessera', `outline:${args.outline}`) });
return draft;
},
});
// Unlock: asks for the password and keeps the key in memory.
ctx.commands.register<{ outline: string }>({
id: 'tessera.vault/unlock',
title: 'Unlock outline…',
icon: 'unlock',
placements: ['outline-menu'],
args: arg,
discardable: true,
can: (state, _focus, args) => {
const outline = outlineOf(state, args);
if (!outline || args?.outline === undefined) {
return { available: true };
}
if (vaultFacet.of(outline as never) === undefined) {
return { available: false, reason: 'Not encrypted' };
}
return keys.has(args.outline) ? { available: false, reason: 'Not locked' } : { available: true };
},
propose(_state, args, draft) {
void ctx.jobs.run(async () => {
const vault = vaultOf(args.outline);
if (!vault) {
return;
}
const key = await keyFor(args.outline, vault, 'Unlock outline');
if (!key) {
return;
}
keys.set(args.outline, key);
reveal.changed();
light();
});
return draft;
},
});
// Lock: forgets the key and the decrypted content of every row of the outline.
ctx.commands.register<{ outline: string }>({
id: 'tessera.vault/lock',
title: 'Lock outline',
icon: 'lock',
placements: ['outline-menu'],
args: arg,
discardable: true,
can: (state, _focus, args) => {
const outline = outlineOf(state, args);
if (!outline || args?.outline === undefined) {
return { available: true };
}
if (vaultFacet.of(outline as never) === undefined) {
return { available: false, reason: 'Not encrypted' };
}
return keys.has(args.outline) ? { available: true } : { available: false, reason: 'Locked' };
},
propose(_state, args, draft) {
keys.delete(args.outline);
for (const id of [...opened.keys()]) {
if (ctx.state.row(id)?.outline === args.outline) {
opened.delete(id);
}
}
reveal.changed();
light();
return draft;
},
});
// The single change that removes the encryption: every row gets its readable text back.
const unseal = ctx.commands.register<{ outline: string }>({
id: 'tessera.vault/unseal',
title: 'Remove encryption…',
args: arg,
propose(state, args, draft) {
for (const row of state.outlineRows(args.outline)) {
if (row.outline !== args.outline) {
continue;
}
const payload = open(row);
if (!payload) {
throw new Error('This row cannot be read with this password');
}
draft.update(row.id, { title: payload.title, note: payload.note });
draft.facet(row.id, dataFacet).remove();
}
draft.facet(args.outline, vaultFacet).remove();
return draft;
},
});
// Remove encryption: asks for the password, then runs the change above.
ctx.commands.register<{ outline: string }>({
id: 'tessera.vault/decrypt',
title: 'Remove encryption…',
icon: 'unlock',
placements: ['outline-menu'],
args: arg,
discardable: true,
can: (state, _focus, args) => {
const outline = outlineOf(state, args);
if (!outline || args?.outline === undefined) {
return { available: true };
}
return vaultFacet.of(outline as never) === undefined ? { available: false, reason: 'Not encrypted' } : { available: true };
},
propose(_state, args, draft) {
void ctx.jobs.run(async () => {
const vault = vaultOf(args.outline);
if (!vault) {
return;
}
const key = await keyFor(args.outline, vault, 'Remove encryption', 'Remove');
if (!key) {
return;
}
keys.set(args.outline, key);
removing.add(args.outline);
try {
await ctx.dispatch(unseal.intent({ outline: args.outline }));
} finally {
removing.delete(args.outline);
}
if (vaultOf(args.outline) === undefined) {
keys.delete(args.outline);
opened.clear();
}
reveal.changed();
light();
});
return draft;
},
});
},
});

10. A letter that opens only when everyone agrees

Section titled “10. A letter that opens only when everyone agrees”

This example shows how a plugin can protect a note so that it can be read only after every person on a shared outline has agreed to open it. Some bank vaults work on the same principle: they need two employees, each holding a separate key, to open them. A family might use the plugin for an anniversary letter, or for emergency information such as passwords and account numbers that nobody should read alone.

The two-keys plugin, which ships with the app, implements this. Its full code is at the end of this section. The plugin adds commands to the menu of each row of a shared outline. They are not offered on the rows of other outlines.

When a person chooses Seal for everyone on this outline…, the plugin creates a new random key with ctx.crypto.newKey and uses it to encrypt the note. It then divides the key into as many parts as there are people on the outline, with ctx.crypto.split. The people on the outline are the person who seals the note and the friends that ctx.state.friends(outline) lists for that outline. The key can be rebuilt only from all the parts together, and any smaller set of parts reveals nothing about it.

Each part is then encrypted for the person it belongs to with ctx.crypto.sealTo, so that only that person’s devices can read it. The plugin stores the encrypted note and the encrypted parts in a facet of the row, and replaces the note with a lock symbol. As a result, the readable text of the note is never saved, written to the log or synchronized.

Sealing a note does not start a request to open it. Immediately after sealing, nobody has agreed and nobody is asked anything.

To open the letter, one of the people chooses Ask to open. The plugin decrypts that person’s part on their device with ctx.crypto.open, and writes it in readable form to a second facet of the row, which synchronization carries to everyone on the outline. The first part written to this facet identifies the person who asked.

While a request is pending, every other person who has not yet agreed sees an alert on each of their devices, created with ctx.ui.alert. The alert says who asked, for example “Bob wants to open “Anniversary letter””, shows how many people have agreed so far, and contains a button that agrees. The plugin does not send these alerts as messages. Instead, a didUpdate hook examines each row that a change touches, whether the change was made on this device or arrived through synchronization, and shows, updates or removes the alert according to what the row stores. Because the alert is derived from the stored row, it disappears when the person agrees, when the letter opens, when the letter is closed, or when the row is deleted.

Agreeing works in the same way as asking: the person’s part is decrypted and added to the second facet. People may agree in any order, and the row shows how many of them have agreed.

When the last part arrives, each device rebuilds the key from the parts with ctx.crypto.join and decrypts the letter. Nobody needs to press anything at this point. Until the last part arrives, nobody can read the letter, including the person who sealed it.

Whether the letter is open is decided only by what the row stores, so the letter remains open after the app is restarted, until someone closes it. The page displays the readable text through ctx.rows.reveal, and the text itself is never stored.

While the letter is open, anyone on the outline can edit it. The edit passes through a shouldUpdate hook, in which the plugin encrypts the new text with the same key and stores it in the facet, while the note itself keeps the lock symbol. Replacing part of a change before it is applied requires the amend:outside permission. While the letter is closed, the same hook refuses any change to the note.

While the letter is open, anyone on the outline can choose Close the letter. The plugin encrypts the letter again with a new key, divides that key into new parts for the same people, and removes the parts that had been given. Every device then shows the lock again, the parts given earlier no longer open anything, and nobody is asked to agree until someone asks to open the letter again.

If the person who closes the letter cannot encrypt a part for one of the other people, because that person is not one of their friends, the plugin only removes the parts that had been given. The letter is closed, but it keeps its previous key.

The plugin records each step in the audit trail of the outline with ctx.audit.record, which requires the audit:write permission. The trail shows who sealed the letter and for how many people, who asked to open it, who agreed and when, and who closed it. Each entry is signed by the device that wrote it, and the app adds the name of the plugin that recorded it.

To encrypt a part for a friend, the plugin needs the crypto:friends permission. A plugin that a person installs from a file may use this permission only if its manifest declares a publisher and the file is signed by that publisher. The two-keys plugin declares no publisher, which is allowed because it ships with the app and the app installs it directly. “Signing a plugin” in Manifest and permissions explains this rule.

This version has the following limits.

  • The people who hold a part are those who were on the outline when the letter was sealed. A person who joins the outline later holds no part. A person who leaves the outline still holds a part, and the letter cannot open without them.
  • A part that has been given can be read by everyone on the outline, because only they can read the outline’s document. A person on the outline could therefore write a wrong part in place of someone else’s. In that case the row says that the letter cannot be opened, until someone closes it and everyone agrees again.
  • If two people agree at the same moment on two different devices, synchronization keeps only one of the two agreements, and the other person has to agree again. The row shows how many people have agreed.
  • Only the note is sealed. The title remains readable, so that it can describe what the letter contains.
/* two-keys: a note on a shared outline that can be read only after everyone on the outline has agreed to open it.
How it works:
- Seal: the note is encrypted with a new random key. The key is divided into one part for each person on the outline.
All the parts are needed to rebuild the key, and any smaller set of parts reveals nothing about it. Each part is
encrypted for its person, and the row shows a lock in place of the note. Sealing does not start a request: nobody
has agreed, and nobody is asked anything.
- Ask to open: a person who holds a part asks to open the letter. Their part is decrypted on their device and written
to the row, where only the people on the outline can read it. The first part written identifies the person who asked.
- Alert: while a request is pending, each person who holds a part and has not yet agreed sees an alert on their
devices, with a button that agrees.
- Agree: each person agrees in the same way as the person who asked, in any order.
- Open: when the last part has been written, the letter is open for everyone on the outline, and it remains open after
a restart until someone closes it. Text typed in the letter while it is open is encrypted with the same key before
it is saved.
- Close: while the letter is open, anyone on the outline can close it. The letter is encrypted again with a new key
and new parts, and the parts that were given are removed, together with the request. Nobody is asked anything until
someone asks to open the letter again.
- Every step is recorded in the audit trail of the outline.
The readable text is never saved, written to the log or synchronized.
Permissions: read, write:rows, amend:outside, audit:write, ui, jobs, crypto, crypto:friends. */
import { allow, amend, definePlugin, veto, type ChangeDraft, type Delta, type Envelope, type PluginContext } from '@tessera/plugin-sdk';
// The text that the saved note shows in its place.
const LOCK = '🔒';
// The purpose under which each part is encrypted. An envelope that was encrypted for another purpose, or by another
// plugin, cannot be opened as a part.
const PART = 'two-keys/part';
// The sealed letter. `id` identifies this sealing, and changes each time the letter is sealed again. `letter` is the
// note, encrypted with the key. `parts` maps each person on the outline (the id of their group) to their part of the
// key, encrypted for them.
interface Sealed {
readonly id: string;
readonly letter: string;
readonly parts: Readonly<Record<string, Envelope>>;
}
// The parts given so far for the sealing `id`, and the person who asked to open the letter, who is the first person
// to have given their part. A part that has been given can be read by everyone on the outline, who are the people that
// the letter is for.
interface Agreed {
readonly id: string;
readonly parts: Readonly<Record<string, string>>;
readonly by?: string;
}
// The fields of a row that the plugin reads.
interface RowLike {
readonly id: string;
readonly title: string;
readonly outline: string;
readonly note: string | null;
readonly facets: Readonly<Record<string, unknown>>;
}
export default definePlugin({
onload(ctx: PluginContext) {
// The two facets of a sealed row: the letter, and the agreements.
const sealedFacet = ctx.facets.define<Sealed>({
key: 'tessera.two-keys/letter',
on: 'row',
merge: 'lww',
schema: { type: 'object', properties: { id: { type: 'string' }, letter: { type: 'string' }, parts: { type: 'object' } }, required: ['id', 'letter', 'parts'] },
});
const agreedFacet = ctx.facets.define<Agreed>({
key: 'tessera.two-keys/agreed',
on: 'row',
merge: 'lww',
schema: { type: 'object', properties: { id: { type: 'string' }, parts: { type: 'object' }, by: { type: 'string' } }, required: ['id', 'parts'] },
});
// ---- The state of the letter, read from the stored row. Only the stored row decides the state, so every device
// shows the same state.
const sealedOf = (row: RowLike): Sealed | undefined => sealedFacet.of(row as never);
// The parts given for the current sealing. Parts given for an earlier sealing are ignored.
const givenOf = (row: RowLike, sealed: Sealed): Readonly<Record<string, string>> => {
const agreed = agreedFacet.of(row as never);
return agreed && agreed.id === sealed.id ? agreed.parts : {};
};
// The person who asked to open the letter, while a request is pending.
const askerOf = (row: RowLike, sealed: Sealed): string | undefined => {
const agreed = agreedFacet.of(row as never);
if (!agreed || agreed.id !== sealed.id || Object.keys(agreed.parts).length === 0) {
return undefined;
}
return agreed.by ?? Object.keys(agreed.parts)[0];
};
// The people who hold a part, the number of people who have agreed, and whether everyone has agreed.
const holdersOf = (sealed: Sealed): string[] => Object.keys(sealed.parts);
const countOf = (row: RowLike, sealed: Sealed): number => holdersOf(sealed).filter(h => typeof givenOf(row, sealed)[h] === 'string').length;
const everyone = (row: RowLike, sealed: Sealed): boolean => countOf(row, sealed) === holdersOf(sealed).length;
// The place that an encrypted text belongs to. An encrypted text that is copied to another row cannot be decrypted there.
const place = (id: string): string => `row:${id}`;
// Whether a row belongs to a shared outline.
const shared = (row: RowLike): boolean => !!ctx.state.outline(row.outline)?.share;
// ---- The open letter
// The result of decrypting each row, kept in memory only: the encrypted text and the parts that were used, and the
// readable text, which is null when the parts do not decrypt the letter.
const opened = new Map<string, { readonly at: string; readonly text: string | null }>();
// The readable letter, once every part has been given. Undefined while the letter is closed, and null when the parts
// do not decrypt it.
const letterOf = (row: RowLike, sealed: Sealed): string | null | undefined => {
if (!everyone(row, sealed)) {
return undefined;
}
const given = givenOf(row, sealed);
const parts = holdersOf(sealed).map(h => given[h]!);
// A letter that is edited while it is open becomes a new encrypted text, so it has to be decrypted again.
const at = `${sealed.letter}|${parts.join(',')}`;
const hit = opened.get(row.id);
if (hit?.at === at) {
return hit.text;
}
let text: string | null;
try {
text = ctx.crypto.keyOf(ctx.crypto.join(parts)).open(sealed.letter, place(row.id));
} catch {
text = null;
}
opened.set(row.id, { at, text });
return text;
};
// The key of an open letter, rebuilt from the parts. Undefined while the letter is closed.
const keyOf = (row: RowLike, sealed: Sealed) => {
if (typeof letterOf(row, sealed) !== 'string') {
return undefined;
}
const given = givenOf(row, sealed);
return ctx.crypto.keyOf(ctx.crypto.join(holdersOf(sealed).map(h => given[h]!)));
};
// What the page shows in the note: the letter while it is open, and the number of agreements while it is closed.
ctx.rows.reveal(row => {
const sealed = sealedOf(row);
if (!sealed) {
return undefined;
}
const text = letterOf(row, sealed);
if (typeof text === 'string') {
return { note: text };
}
if (text === null) {
return { note: '🔒 This letter cannot be opened: a part given is not the right one. Close it, and agree again.' };
}
return { note: `🔒 Sealed with ${holdersOf(sealed).length} keys: ${countOf(row, sealed)} of ${holdersOf(sealed).length} agreed.` };
});
// ---- The note of a sealed row
// While the letter is open, typed text is encrypted before the change is applied: the note keeps the lock, and the
// letter stores the new text, encrypted with the same key. While the letter is closed, typing is refused.
ctx.hooks.shouldUpdate({}, proposal => {
let changed = false;
const deltas: Delta[] = [];
for (const delta of proposal.deltas as readonly Delta[]) {
const writesNote = delta.kind === 'updated' && delta.ref.kind === 'row' && delta.fields.includes('note') && delta.after.note !== LOCK;
const row = writesNote ? ctx.state.row(delta.ref.id) : undefined;
const sealed = row ? sealedOf(row) : undefined;
if (delta.kind !== 'updated' || !row || !sealed) {
deltas.push(delta);
continue;
}
const key = keyOf(row, sealed);
if (!key) {
return veto('sealed', 'The note of a sealed row cannot be changed');
}
// The note is removed from the change, and the letter, encrypted again with the new text, is stored in its place.
const text = typeof delta.after.note === 'string' ? delta.after.note : '';
const { note: _after, ...after } = delta.after as Record<string, unknown>;
const { note: _before, ...before } = delta.before as Record<string, unknown>;
const facets = (after.facets as Record<string, unknown> | undefined) ?? row.facets;
deltas.push({
...delta,
fields: [...new Set([...delta.fields.filter(f => f !== 'note'), 'facets'])],
before: { ...before, facets: row.facets },
after: { ...after, facets: { ...facets, [sealedFacet.key]: { ...sealed, letter: key.seal(text, place(row.id)) } } },
} as Delta);
changed = true;
}
return changed ? amend<ChangeDraft>({ ...proposal, deltas }, 'sealed') : allow();
});
// Typing in a closed letter is stopped at the first key, and the person sees the reason.
ctx.editing.shouldChangeText({ topics: ['row.note'] }, change => {
const row = change.field.entity.kind === 'row' ? ctx.state.row(change.field.entity.id) : undefined;
const sealed = row ? sealedOf(row) : undefined;
if (row && sealed && !keyOf(row, sealed)) {
return veto('sealed', 'The note of a sealed row cannot be changed');
}
return allow();
});
// ---- Helpers for the commands
// Every command in the menu of a row receives the id of the row.
const arg = { type: 'object', properties: { id: { type: 'string' } }, required: ['id'] };
const rowOf = (state: { row(id: string): RowLike | undefined }, args: { id: string } | undefined): RowLike | undefined =>
(args?.id ? state.row(args.id) : undefined);
// Shows a message at the bottom of the screen.
const told = (text: string, level: 'info' | 'error' = 'info'): void => {
ctx.ui.notice({ text, level });
};
// Records what was done in the audit trail of the outline. If the entry cannot be written, the action is not undone.
const trail = async (outline: string, text: string): Promise<void> => {
await ctx.audit.record(outline, text).catch(() => undefined);
};
// Seals a text for the given people: creates a new key, divides it into one part per person, and encrypts each part
// for its person. The part of the current person is encrypted for all of their devices.
const sealFor = async (text: string, rowId: string, holders: readonly string[], me: string): Promise<Sealed> => {
const key = ctx.crypto.newKey();
const cut = ctx.crypto.split(key, holders.length);
const parts: Record<string, Envelope> = {};
for (const [i, holder] of holders.entries()) {
const to = holder === me ? { me: true as const } : { friend: holder };
parts[holder] = await ctx.crypto.sealTo(to, cut[i]!, { purpose: PART });
}
return { id: ctx.crypto.newKey().slice(0, 16), letter: ctx.crypto.keyOf(key).seal(text, place(rowId)), parts };
};
// ---- 1. Seal
// Encrypting a part for each person takes a moment, so it runs in a job. The change itself is made by the command `commit`.
ctx.commands.register<{ id: string }>({
id: 'tessera.two-keys/seal',
title: 'Seal for everyone on this outline…',
icon: 'lock',
placements: ['row-menu'],
args: arg,
discardable: true,
can: (state, _focus, args) => {
const row = rowOf(state as never, args);
if (!row) {
return { available: true };
}
if (!shared(row)) {
return { available: false, reason: 'Only on a shared outline' };
}
// The command is also offered on a row without a note, so that choosing it tells the person what is missing.
return sealedOf(row) ? { available: false, reason: 'Already sealed' } : { available: true };
},
propose(_state, args, draft) {
void ctx.jobs.run(async () => {
const row = ctx.state.row(args.id);
if (!row || !shared(row)) {
return;
}
if (!row.note) {
told('This row has no note to seal', 'error');
return;
}
const me = ctx.state.viewer;
if (!me) {
told('Set up sync first: the keys belong to the people of the outline', 'error');
return;
}
// The parts go to the current person and to the friends who are on the shared outline.
const others = ctx.state.friends(row.outline).map(f => f.group).filter(g => g !== me);
if (others.length === 0) {
told('Nobody else is on this shared outline: the letter needs at least two people', 'error');
return;
}
const note = row.note;
const sealed = await sealFor(note, row.id, [me, ...others], me);
const outcome = await ctx.dispatch(commit.intent({ row: args.id, note, sealed }));
if (outcome.status !== 'committed') {
told('The row changed meanwhile: try again', 'error');
return;
}
told(`Sealed with ${others.length + 1} keys. It opens when everyone agrees.`);
await trail(row.outline, `Sealed "${row.title}" with ${others.length + 1} keys`);
});
return draft;
},
});
// The change that seals the note. The lock replaces the note and the encrypted letter is stored, in the same change,
// provided that the note has not changed in the meantime. Nobody has agreed yet, and nobody is asked.
const commit = ctx.commands.register<{ row: string; note: string; sealed: Sealed }>({
id: 'tessera.two-keys/commit',
title: 'Seal for everyone on this outline…',
discardable: false,
args: {
type: 'object',
properties: { row: { type: 'string' }, note: { type: 'string' }, sealed: { type: 'object' } },
required: ['row', 'note', 'sealed'],
},
propose(state, args, draft) {
const row = state.row(args.row);
if (!row || row.note !== args.note || sealedOf(row)) {
throw new Error('The row changed meanwhile: try again');
}
draft.update(args.row, { note: LOCK });
draft.facet(args.row, sealedFacet).set(args.sealed);
return draft;
},
});
// ---- 2. Ask to open, and 3. Agree
// What the current person can do with their part now: nothing (they hold no part, or have already given it), ask
// (nobody has asked yet), or agree (someone has asked).
const step = (row: RowLike, sealed: Sealed | undefined): { readonly can: 'ask' | 'agree' } | { readonly reason: string } => {
const me = ctx.state.viewer;
if (!sealed) {
return { reason: 'Not sealed' };
}
if (!me || !sealed.parts[me]) {
return { reason: 'You hold no key to this letter' };
}
if (typeof givenOf(row, sealed)[me] === 'string') {
return { reason: 'You already agreed' };
}
return { can: askerOf(row, sealed) ? 'agree' : 'ask' };
};
// Decrypts the part of the current person on this device and writes it to the row. The first part given is the request.
const giveMine = async (rowId: string): Promise<void> => {
const row = ctx.state.row(rowId);
const sealed = row ? sealedOf(row) : undefined;
const me = ctx.state.viewer;
if (!row || !sealed || !me || !sealed.parts[me]) {
return;
}
const mine = await ctx.crypto.open(sealed.parts[me], { purpose: PART });
if (!mine) {
told('You hold no key to this letter', 'error');
return;
}
const asking = !askerOf(row, sealed);
const outcome = await ctx.dispatch(give.intent({ row: rowId, id: sealed.id, holder: me, part: mine.text }));
if (outcome.status !== 'committed') {
told('The row changed meanwhile: try again', 'error');
return;
}
const now = ctx.state.row(rowId);
const n = holdersOf(sealed).length;
const k = now ? countOf(now, sealed) : n;
if (asking) {
told(`You asked to open it: ${k} of ${n}. The others are asked to agree.`);
await trail(row.outline, `Asked to open "${row.title}" (${k} of ${n})`);
} else if (k === n) {
told(`You agreed: ${k} of ${n}. The letter is open.`);
await trail(row.outline, `Agreed to open "${row.title}" (${k} of ${n}): it is open`);
} else {
told(`You agreed: ${k} of ${n}`);
await trail(row.outline, `Agreed to open "${row.title}" (${k} of ${n})`);
}
};
// Ask to open: available to a person who holds a part, while nobody has asked.
ctx.commands.register<{ id: string }>({
id: 'tessera.two-keys/ask',
title: 'Ask to open',
icon: 'unlock',
placements: ['row-menu'],
args: arg,
discardable: true,
can: (state, _focus, args) => {
const row = rowOf(state as never, args);
if (!row) {
return { available: true };
}
const now = step(row, sealedOf(row));
if (!('can' in now)) {
return { available: false, reason: now.reason };
}
return now.can === 'ask' ? { available: true } : { available: false, reason: 'Someone already asked to open it: agree to it' };
},
propose(_state, args, draft) {
void ctx.jobs.run(() => giveMine(args.id));
return draft;
},
});
// Agree to open: available to a person who holds a part and has not agreed, once someone has asked.
const agree = ctx.commands.register<{ id: string }>({
id: 'tessera.two-keys/agree',
title: 'Agree to open',
icon: 'unlock',
placements: ['row-menu'],
args: arg,
discardable: true,
can: (state, _focus, args) => {
const row = rowOf(state as never, args);
if (!row) {
return { available: true };
}
const now = step(row, sealedOf(row));
if (!('can' in now)) {
return { available: false, reason: now.reason };
}
return now.can === 'agree' ? { available: true } : { available: false, reason: 'Nobody asked to open it yet' };
},
propose(_state, args, draft) {
void ctx.jobs.run(() => giveMine(args.id));
return draft;
},
});
// The change that gives a part. It accepts only the part of the current person, and only for the current sealing.
// The first part given records who asked.
const give = ctx.commands.register<{ row: string; id: string; holder: string; part: string }>({
id: 'tessera.two-keys/give',
title: 'Agree to open',
discardable: false,
args: {
type: 'object',
properties: { row: { type: 'string' }, id: { type: 'string' }, holder: { type: 'string' }, part: { type: 'string' } },
required: ['row', 'id', 'holder', 'part'],
},
propose(state, args, draft) {
const row = state.row(args.row);
const sealed = row ? sealedOf(row) : undefined;
if (!row || !sealed || sealed.id !== args.id || args.holder !== ctx.state.viewer || !sealed.parts[args.holder]) {
throw new Error('The row changed meanwhile: try again');
}
draft.facet(args.row, agreedFacet).set({
id: sealed.id,
parts: { ...givenOf(row, sealed), [args.holder]: args.part },
by: askerOf(row, sealed) ?? args.holder,
});
return draft;
},
});
// ---- 4. Close
// Available to anyone on the outline while the letter is open. The letter is encrypted again with a new key and new
// parts, and the parts that were given are removed, together with the request. If a part cannot be encrypted for one
// of the people from this device, because that person is not a friend of the current person, the plugin only removes
// the parts that were given.
ctx.commands.register<{ id: string }>({
id: 'tessera.two-keys/close',
title: 'Close the letter',
icon: 'lock',
placements: ['row-menu'],
args: arg,
discardable: true,
can: (state, _focus, args) => {
const row = rowOf(state as never, args);
if (!row) {
return { available: true };
}
const sealed = sealedOf(row);
return sealed && letterOf(row, sealed) !== undefined ? { available: true } : { available: false, reason: 'The letter is not open' };
},
propose(_state, args, draft) {
void ctx.jobs.run(async () => {
const row = ctx.state.row(args.id);
const sealed = row ? sealedOf(row) : undefined;
const me = ctx.state.viewer;
const text = row && sealed ? letterOf(row, sealed) : undefined;
if (!row || !sealed || text === undefined || !me) {
return;
}
const again = typeof text === 'string' ? await sealFor(text, row.id, holdersOf(sealed), me).catch(() => undefined) : undefined;
const outcome = await ctx.dispatch(reseal.intent({ row: args.id, was: sealed.id, ...(again ? { sealed: again } : {}) }));
if (outcome.status !== 'committed') {
told('The row changed meanwhile: try again', 'error');
return;
}
told('Closed for everyone');
await trail(row.outline, `Closed "${row.title}" for everyone`);
});
return draft;
},
});
// The change that closes the letter: it stores the new sealing, when there is one, and removes the agreements.
const reseal = ctx.commands.register<{ row: string; was: string; sealed?: Sealed }>({
id: 'tessera.two-keys/reseal',
title: 'Close the letter',
discardable: false,
args: {
type: 'object',
properties: { row: { type: 'string' }, was: { type: 'string' }, sealed: { type: 'object' } },
required: ['row', 'was'],
},
propose(state, args, draft) {
const row = state.row(args.row);
const sealed = row ? sealedOf(row) : undefined;
if (!sealed || sealed.id !== args.was) {
throw new Error('The row changed meanwhile: try again');
}
if (args.sealed) {
draft.facet(args.row, sealedFacet).set(args.sealed);
}
draft.facet(args.row, agreedFacet).remove();
return draft;
},
});
// ---- The request, shown as an alert
// While a request is pending, each person who holds a part and has not agreed sees an alert on their devices: who
// wants to open the letter, how many people have agreed, and a button that agrees. The alert is derived from the
// stored row, so it reaches every person through synchronization, and it disappears when they agree, when the letter
// opens, when the letter is closed, or when the row is deleted.
const asking = new Map<string, ReturnType<PluginContext['ui']['alert']>>();
const ask = (rowId: string): void => {
const row = ctx.state.row(rowId);
const sealed = row ? sealedOf(row) : undefined;
const asker = row && sealed ? askerOf(row, sealed) : undefined;
const me = ctx.state.viewer;
const had = asking.get(rowId);
const asked = row && sealed && asker && me && sealed.parts[me] && typeof givenOf(row, sealed)[me] !== 'string';
if (!row || !sealed || !asked) {
had?.dispose();
asking.delete(rowId);
return;
}
const who = ctx.state.friends().find(f => f.group === asker)?.name ?? 'Someone';
const shape = {
text: `${who} wants to open “${row.title}”`,
detail: `${countOf(row, sealed)} of ${holdersOf(sealed).length} agreed. It opens when everyone agrees.`,
icon: 'lock',
actions: [{ id: 'agree', title: 'Agree to open', icon: 'unlock', command: agree.id, args: { id: rowId } }],
};
if (had) {
had.update(shape);
} else {
asking.set(rowId, ctx.ui.alert({ id: `agree:${rowId}`, ...shape }));
}
};
// When the plugin starts, it shows the pending requests for the letters on the shared outlines.
for (const outline of ctx.state.outlines()) {
if (!outline.share) {
continue;
}
for (const row of ctx.state.outlineRows(outline.id)) {
if (sealedOf(row)) {
ask(row.id);
}
}
}
// After that, it updates the alert of each row that a change touches, whether the change was made on this device or
// arrived through synchronization.
ctx.hooks.didUpdate({ on: 'row' }, change => {
for (const delta of change.deltas) {
if ('ref' in delta && delta.ref.kind === 'row') {
ask(delta.ref.id);
}
}
});
},
});