Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -252,3 +252,51 @@ jobs:
name: oxidezap-${{ matrix.name }}
path: ${{ env.ASSET }}
if-no-files-found: error

plugins:
name: Plugin bundle
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
ref: ${{ inputs.ref }}
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
with:
toolchain: "1.100.0"
targets: wasm32-unknown-unknown
- name: Build installable plugins
env:
VERSION: ${{ inputs.version }}
run: |
set -euo pipefail
case "$VERSION" in
""|*[!a-zA-Z0-9._-]*|-*|.*) exit 1 ;;
esac
modules=()
for manifest in examples/*/Cargo.toml; do
plugin="${manifest%/Cargo.toml}"
if [ "$plugin" = examples/template ]; then continue; fi
module="$(cargo xtask plugin build "$plugin")"
modules+=("$module")
done
test "${#modules[@]}" -gt 0
mkdir -p dist/release
python3 - "dist/release/oxidezap-$VERSION-plugins.zip" "${modules[@]}" <<'PYTHON'
import sys
from pathlib import Path
from zipfile import ZIP_DEFLATED, ZipFile

modules = [Path(path) for path in sys.argv[2:]]
names = [module.name for module in modules]
if len(set(names)) != len(names):
raise SystemExit("Duplicate plugin module names")
with ZipFile(sys.argv[1], "w", compression=ZIP_DEFLATED) as archive:
for module in modules:
archive.write(module, module.name)
PYTHON
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: oxidezap-plugins
path: dist/release/oxidezap-${{ inputs.version }}-plugins.zip
if-no-files-found: error
13 changes: 9 additions & 4 deletions .github/workflows/nightly.yml
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ jobs:
that runs in place, adds its own menu entry and updates through
its `.zsync`. `OxideZap.AppImage --cli ...` runs the CLI.

`oxidezap-nightly-plugins.zip` contains optional `.wasm` plugins.
Unpack it and install the modules you want under Settings → Plugins.

The tarballs carry the execute bit. On macOS, clear the quarantine
flag before the first run:

Expand All @@ -83,10 +86,12 @@ jobs:
obtains the cross-origin isolation the window needs. `README.md`
inside says the rest.
NOTES
echo "" >> notes.md
echo "Built from [\`${GITHUB_SHA:0:7}\`](https://github.com/$GH_REPO/commit/$GITHUB_SHA) on $(date -u +"%Y-%m-%d %H:%M") UTC." >> notes.md
echo "" >> notes.md
echo "Verify download integrity with \`sha256sum -c --ignore-missing checksums.sha256\`." >> notes.md
{
echo ""
echo "Built from [\`${GITHUB_SHA:0:7}\`](https://github.com/$GH_REPO/commit/$GITHUB_SHA) on $(date -u +"%Y-%m-%d %H:%M") UTC."
echo ""
echo "Verify download integrity with \`sha256sum -c --ignore-missing checksums.sha256\`."
} >> notes.md
# Recreate rather than edit: `gh release edit` cannot move a tag, and
# a stale tag would leave the assets pointing at an older commit.
gh release delete nightly --yes --cleanup-tag || true
Expand Down
18 changes: 17 additions & 1 deletion .github/workflows/release-check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,5 +42,21 @@ jobs:
test -s "artifacts/oxidezap-$VERSION-linux-$arch.$suffix"
done
done
test "$(find artifacts -type f | wc -l)" -eq 12
python3 - "artifacts/oxidezap-$VERSION-plugins.zip" <<'PYTHON'
import sys
from pathlib import PurePosixPath
from zipfile import ZipFile

with ZipFile(sys.argv[1]) as archive:
names = archive.namelist()
assert names and len(set(names)) == len(names), names
for name in names:
path = PurePosixPath(name)
assert name == path.name and path.suffix == ".wasm", name
assert name != "template.wasm", name
with archive.open(name) as module:
assert module.read(8) == b"\0asm\x01\0\0\0", name
assert archive.testzip() is None
PYTHON
test "$(find artifacts -type f | wc -l)" -eq 13
(cd artifacts && sha256sum oxidezap-* > checksums.sha256 && sha256sum -c checksums.sha256)
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,9 @@ history, which is what the in-app "pair again" action does.

## Plugins

Releases include an optional `oxidezap-<version>-plugins.zip`. Unpack it and
install the `.wasm` modules you want under Settings → Plugins.

A plugin is a `.wasm` file dropped in `~/.local/share/oxidezap/plugins` — or,
in a page running its own session, added under Settings → Plugins, which keeps
it in the browser's own storage. Either way it runs inside the daemon — which
Expand Down
2 changes: 2 additions & 0 deletions crates/core/src/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ use serde::{Deserialize, Serialize};
pub enum PluginSlot {
/// Beside the conversation's name.
ChatHeader,
/// Tools shown beside the conversation composer.
Composer,
/// A section of the Settings screen.
Settings,
}
Expand Down
4 changes: 4 additions & 0 deletions crates/daemon/src/plugins/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -329,11 +329,15 @@ fn publishing_to(hub: &Arc<StateHub>) -> Sink {
/// the rest of the split. Everything a plugin can actually ask for is here,
/// written once on top of it.
struct Bridge {
hub: Arc<StateHub>,
commands: SessionCommands,
}

impl Commands for Bridge {
fn send_text(&self, jid: &str, text: &str, quoted: Option<&str>) -> Outcome {
if !self.hub.connection().is_connected() {
return Outcome::NoSession;
}
self.ask(Action::SendText(oxidezap_ipc::SendText {
jid: jid.to_owned(),
text: text.to_owned(),
Expand Down
23 changes: 11 additions & 12 deletions crates/daemon/src/plugins/native.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,12 @@ use crate::state::StateHub;
pub(super) async fn start(hub: &Arc<StateHub>, commands: SessionCommands) -> Arc<Plugins> {
let sink = publishing_to(hub);
let account_id = hub.account_id();
let fallback = (publishing_to(hub), commands.clone());
tokio::task::spawn_blocking(move || load(sink, commands, account_id))
let bridge = Arc::new(Bridge {
hub: hub.clone(),
commands,
});
let fallback = (publishing_to(hub), bridge.clone());
tokio::task::spawn_blocking(move || load(sink, bridge, account_id))
.await
.unwrap_or_else(|e| {
// With the daemon's own sink and bridge, not a discarding pair.
Expand All @@ -43,28 +47,23 @@ pub(super) async fn start(hub: &Arc<StateHub>, commands: SessionCommands) -> Arc
// and every command answering `NoSession` — while reporting the
// reload as having worked.
log::error!("the plugin loader did not finish: {e}");
let (sink, commands) = fallback;
Arc::new(Plugins::none(sink, Arc::new(Bridge { commands })))
let (sink, bridge) = fallback;
Arc::new(Plugins::none(sink, bridge))
})
}

/// The scan itself, on the blocking thread [`start`] put it on.
fn load(sink: Sink, commands: SessionCommands, account_id: AccountId) -> Arc<Plugins> {
fn load(sink: Sink, bridge: Arc<Bridge>, account_id: AccountId) -> Arc<Plugins> {
let Some(dir) = oxidezap_plugin_host::default_dir() else {
log::debug!("no per-user data directory, so no plugins");
return Arc::new(Plugins::none(sink, Arc::new(Bridge { commands })));
return Arc::new(Plugins::none(sink, bridge));
};
// Not the daemon's `state_dir`: that one prefers XDG_RUNTIME_DIR, which
// is cleared on logout, and a permission answer that does not survive a
// logout is a prompt asked forever. Scoped to this account: see
// `account_state_dir`.
let state_dir = account_state_dir(account_id);
Arc::new(Plugins::load(
&dir,
state_dir.as_deref(),
Arc::new(Bridge { commands }),
sink,
))
Arc::new(Plugins::load(&dir, state_dir.as_deref(), bridge, sink))
}

/// See [`super::reload`].
Expand Down
5 changes: 4 additions & 1 deletion crates/daemon/src/plugins/web.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,10 @@ pub(super) async fn start(hub: &Arc<StateHub>, commands: SessionCommands) -> Arc
Plugins::start(
modules,
Arc::new(Origin::storage_for_account(hub.account_id())),
Arc::new(Bridge { commands }),
Arc::new(Bridge {
hub: hub.clone(),
commands,
}),
sink,
)
.await,
Expand Down
118 changes: 94 additions & 24 deletions crates/gui/src/app/plugins_ctl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
//! which needs somewhere to hold what is being typed before anybody commits
//! it — and that is what this file is.

use std::collections::HashMap;
use indexmap::IndexMap;

use gpui::{App, AppContext as _, Context, Entity, Window};
use gpui_component::input::{InputEvent, InputState};
Expand Down Expand Up @@ -58,6 +58,7 @@ impl PluginField {
/// oversized setting would disconnect the window. A plugin setting is a
/// keyword or a sentence; anything of this size is a mistake either way.
const MAX_FIELD_BYTES: usize = 64 * 1024;
const MAX_INACTIVE_COMPOSER_FIELDS: usize = 64;

/// A field's address. Two plugins may both call a widget `keyword`, and one
/// plugin may draw the same id in two slots.
Expand All @@ -72,8 +73,8 @@ const MAX_FIELD_BYTES: usize = 64 * 1024;
/// selection when Enter is pressed, so a box shared across chats would take
/// what somebody typed in one and commit it carrying the other's JID — a
/// plugin storing or sending it for the wrong conversation. Switching chats
/// therefore drops what was half-typed in the old one, which is the honest
/// trade: the alternative is not a preserved draft, it is a misdirected one.
/// drops legacy header fields. Composer drafts stay keyed to their own chat
/// until the plugin removes the field, the account changes, or the cache fills.
///
/// Which is why the *same* answer `send_plugin_action` gives is taken here
/// rather than the selection itself: a Settings action carries no chat, so
Expand All @@ -83,7 +84,7 @@ const MAX_FIELD_BYTES: usize = 64 * 1024;
/// gone for a context it never had.
fn key(plugin: &str, slot: PluginSlot, chat: Option<&str>, id: &str) -> FieldKey {
let chat = match slot {
PluginSlot::ChatHeader => chat,
PluginSlot::ChatHeader | PluginSlot::Composer => chat,
Comment thread
jlucaso1 marked this conversation as resolved.
Resolved
PluginSlot::Settings => None,
};
FieldKey {
Expand Down Expand Up @@ -289,14 +290,39 @@ impl Plugins {
}
}

// Gone means gone: a plugin that stopped drawing a field has taken it
// back, and holding the entity would keep a subscription alive that
// fires into a widget nobody can see.
let live: std::collections::HashSet<FieldKey> = wanted
.iter()
.map(|f| key(&f.plugin, f.slot, chat, &f.id))
.collect();
self.fields.retain(|k, _| live.contains(k));
let composers: std::collections::HashSet<_> = wanted
.iter()
.filter(|f| f.slot == PluginSlot::Composer)
.map(|f| (f.plugin.as_str(), f.id.as_str()))
.collect();
let mut inactive = 0;
self.fields.retain(|key, field| {
if live.contains(key) {
return true;
}
if key.slot != PluginSlot::Composer
|| !composers.contains(&(key.plugin.as_str(), key.id.as_str()))
{
return false;
}
let typed = field.state.read(cx).value();
let keep = typed.len() <= MAX_FIELD_BYTES && typed.as_ref() != field.published;
inactive += usize::from(keep);
keep
});
let mut excess = inactive.saturating_sub(MAX_INACTIVE_COMPOSER_FIELDS);
self.fields.retain(|key, _| {
if excess == 0 || live.contains(key) {
true
} else {
excess -= 1;
false
}
});

// What is left is what has no box yet. The ones that do are brought
// up to date here, and only when the *plugin* moved them: a tree
Expand Down Expand Up @@ -378,7 +404,9 @@ impl WhatsAppApp {
// what it was. Clicking elsewhere, tabbing away and
// closing the screen all blur the box, and all of them
// now commit what is in it.
InputEvent::PressEnter { .. } | InputEvent::Blur => {
InputEvent::PressEnter { .. } | InputEvent::Blur
if commit_slot != PluginSlot::Composer =>
{
this.commit_plugin_field(&commit_plugin, commit_slot, &commit_id, cx);
}
_ => {}
Expand Down Expand Up @@ -704,6 +732,31 @@ impl WhatsAppApp {
cx.notify();
}

fn composer_form(&self, plugin: &str, chat: &str, cx: &App) -> Option<String> {
let surface = self
.plugins(cx)
.iter()
.find(|surface| surface.id == plugin)?;
let mut fields = Vec::new();
for node in surface.roots_in(PluginSlot::Composer) {
collect_fields(plugin, PluginSlot::Composer, node, &mut fields);
}
let mut values = std::collections::BTreeMap::new();
let limit = MAX_FIELD_BYTES.checked_sub(chat.len())?;
let mut remaining = limit;
for field in fields {
let value = self
.plugin_field(plugin, PluginSlot::Composer, &field.id, cx)?
.read(cx)
.value();
remaining = remaining.checked_sub(field.id.len() + value.len())?;
values.insert(field.id, value.to_string());
}
serde_json::to_string(&values)
.ok()
.filter(|value| value.len() <= limit)
}

/// Tell a plugin one of its widgets was used.
///
/// The open conversation goes along only for a slot that has one. A
Expand All @@ -721,9 +774,25 @@ impl WhatsAppApp {
cx: &mut Context<Self>,
) {
let chat = match slot {
PluginSlot::ChatHeader => self.selected_chat_jid(),
PluginSlot::ChatHeader | PluginSlot::Composer => self.selected_chat_jid(),
PluginSlot::Settings => None,
};
let value = if slot == PluginSlot::Composer && widget == PluginWidget::Button {
let Some(form) = chat
.as_deref()
.and_then(|chat| self.composer_form(plugin, chat, cx))
else {
self.notify_user(
crate::tr!(ComposerPluginFormUnavailable),
super::notices::Tone::Problem,
cx,
);
return;
};
Some(form)
} else {
value
};
if let Some(client) = self.client.as_ref() {
client.plugin_action(plugin, action, value, chat, slot, widget);
}
Expand Down Expand Up @@ -760,7 +829,7 @@ fn collect_fields(plugin: &str, slot: PluginSlot, node: &PluginNode, out: &mut V
}

/// The boxes, keyed by what names each one.
type PluginFields = HashMap<FieldKey, PluginField>;
type PluginFields = IndexMap<FieldKey, PluginField>;

#[cfg(test)]
mod tests {
Expand Down Expand Up @@ -819,27 +888,28 @@ mod tests {
}

/// A Settings field is one field whatever is selected, because the action
/// it commits carries no conversation. A header field is one per chat,
/// because the action it commits carries the open one.
/// it commits carries no conversation. Chat tools keep separate fields
/// for each conversation.
#[test]
fn only_a_header_field_belongs_to_a_conversation() {
fn chat_tools_fields_belong_to_a_conversation() {
let settings = |chat| key("autoreply", PluginSlot::Settings, chat, "keyword");
assert_eq!(settings(Some("a@s.whatsapp.net")), settings(None));
assert_eq!(
settings(Some("a@s.whatsapp.net")),
settings(Some("b@s.whatsapp.net"))
);

let header = |chat| key("autoreply", PluginSlot::ChatHeader, chat, "keyword");
assert_ne!(
header(Some("a@s.whatsapp.net")),
header(Some("b@s.whatsapp.net"))
);
assert_ne!(
header(Some("a@s.whatsapp.net")),
settings(Some("a@s.whatsapp.net")),
"and the same id in two slots is still two fields"
);
for slot in [PluginSlot::ChatHeader, PluginSlot::Composer] {
let chat_field = |chat| key("autoreply", slot, chat, "keyword");
assert_ne!(
chat_field(Some("a@s.whatsapp.net")),
chat_field(Some("b@s.whatsapp.net"))
);
assert_ne!(
chat_field(Some("a@s.whatsapp.net")),
settings(Some("a@s.whatsapp.net"))
);
}
}

/// The key used to be a formatted string with `/` between its parts. A
Expand Down
Loading
Loading