Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
000d6158ae | ||
|
|
bb1586001a | ||
|
|
56463d5147 | ||
|
|
1ebaa165bd | ||
|
|
55899d9cab | ||
|
|
0d2e6c73a7 | ||
|
|
3067b88ecc | ||
|
|
c6e9c82ae5 | ||
|
|
3787b55ca5 | ||
|
|
1f16f5dd44 | ||
|
|
e7cfb3dbd9 | ||
|
|
b21e74307e | ||
|
|
aebf253226 | ||
|
|
b7f354cd12 | ||
|
|
5f93ad815e | ||
|
|
39945c5e99 | ||
|
|
9be4ee4225 | ||
|
|
8c20c3d3a6 | ||
|
|
9b97fb8c32 | ||
|
|
cef9f28dfd |
@@ -0,0 +1,48 @@
|
|||||||
|
# Plugin development instructions
|
||||||
|
|
||||||
|
Instructions for opencode agents working on the Paarrot plugin system in this repo.
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
- Plugin host: `overlay/src/app/utils/pluginHost.ts`. Electron uses `window.electron.plugins`, Android uses the Capacitor `PluginStorage` plugin, web returns null.
|
||||||
|
- Native Android host: `android/app/src/main/java/com/paarrot/app/PluginStoragePlugin.kt` (download zip, unzip with zip-slip guard, list, uninstall, readPluginCode). Registered in `MainActivity.java`.
|
||||||
|
- Loader: `cinny/src/app/features/settings/plugins/PluginLoader.tsx`, mounted in `ClientRoot.tsx`. It evaluates `index.js` with `new Function` for CommonJS and falls back to a data-URL import for ESM.
|
||||||
|
- Registry and marketplace: `PluginAPI.ts` persists both to `localStorage`. Enabled state survives restarts. Plugins load at app start, so enabling a plugin requires an app restart.
|
||||||
|
|
||||||
|
## Plugin context contract
|
||||||
|
|
||||||
|
- `createPluginContext` from `@paarrot/plugin-manager` provides: `commands`, `messages`, `ui`, `settings`, `themes`, `events`, `timers`, `log`, `warn`, `error`.
|
||||||
|
- `PluginLoader` adds compat fields on top: `matrixClient`, `matrix`, `React`, `lucide`. Plugins destructure these directly (for example `const { Link } = ctx.lucide`), so a missing field throws at `onLoad` and the plugin never runs. Keep the compat fields in sync between `cinny` and `overlay`. A missing `lucide` caused silent plugin failure on mobile, fixed in commit `1f16f5d`.
|
||||||
|
|
||||||
|
## UI locations
|
||||||
|
|
||||||
|
- Valid `UILocation` values: `room-header`, `message-actions`, `user-menu`, `room-menu`, `composer-actions`, `channel-list`, `direct-messages`, `home-section`, `search-notification-section`, `text-composer-toolbar`, `sidebar-actions`.
|
||||||
|
- Button slots render at all screen sizes. Nav-only locations (`channel-list`, `direct-messages`, `home-section`, `sidebar-actions`) have no surface in the single-column mobile UI, so plugins that only register there are invisible on phones.
|
||||||
|
|
||||||
|
## Mobile quirks
|
||||||
|
|
||||||
|
- Capacitor injects plugins on `Capacitor.Plugins` after the bridge is ready, and `registerPlugin` is often missing on Android. The `waitForBridge` fallback pattern in `overlay/src/app/utils/backgroundSync.ts` is the reference.
|
||||||
|
- No CSP is configured in `capacitor.config.json`, so `new Function` and data-URL imports work. Adding CSP would break plugin evaluation.
|
||||||
|
- WebView console logs reach logcat under the tag `Capacitor/Console`.
|
||||||
|
|
||||||
|
## Debugging on device
|
||||||
|
|
||||||
|
- Wireless adb: `adb connect <ip>:<port>`. The `adb tcpip` port persists until reboot, then resets to 5555. Android 11+ wireless debugging randomizes the port per reboot by design. Pinning needs root (`persist.adb.tcp.port`).
|
||||||
|
- Plugin files: `adb shell run-as com.paarrot.app cat files/plugins/<id>/index.js` works on debuggable builds.
|
||||||
|
- Enabled state: localStorage lives in `app_webview/Local Storage/leveldb`. Search for `plugin-manager:installed-plugins`.
|
||||||
|
- Live eval: the WebView devtools socket is `@webview_devtools_remote_<pid>`. Forward with `adb forward tcp:9222 localsocket:webview_devtools_remote_<pid>`. The socket may refuse HTTP and WebSocket requests from non-localhost hosts.
|
||||||
|
- To trigger plugin load logs: force-stop, start, then `logcat -d | grep PluginLoader`.
|
||||||
|
- Hotpatching the installed copy with `run-as` plus an app restart tests plugin changes without reinstalling.
|
||||||
|
|
||||||
|
## Marketplace
|
||||||
|
|
||||||
|
- Directory: `Paarrot/Plugin-Directory`. Entries are static JSON files. The `version` field is a manual snapshot and is never synced from the plugin repo.
|
||||||
|
- Updates go through PRs. `validate-pr.yml` validates and auto-merges. `update-index.yml` regenerates `index.json` from committed entries only.
|
||||||
|
- A plugin repo needs `index.js` and `plugin-metadata.json`. The directory `downloadUrl` is the GitHub archive zip.
|
||||||
|
- Bump the version in both the plugin repo metadata and the directory entry when shipping changes.
|
||||||
|
|
||||||
|
## Repo conventions
|
||||||
|
|
||||||
|
- Edit `overlay/` files, not `cinny` directly. `scripts/apply-overlay.mjs` layers the overlay onto the cinny submodule before every Android build.
|
||||||
|
- `android/gradlew` is not executable. Run it as `sh gradlew`.
|
||||||
|
- Use `scripts/push.sh` for commits. It skips the cinny submodule pointer and `gradlew`.
|
||||||
@@ -377,12 +377,50 @@ class MatrixSyncService : Service() {
|
|||||||
val isMessageLike =
|
val isMessageLike =
|
||||||
eventType == "m.room.message" ||
|
eventType == "m.room.message" ||
|
||||||
eventType == "m.room.encrypted" ||
|
eventType == "m.room.encrypted" ||
|
||||||
eventType == "m.sticker"
|
eventType == "m.sticker" ||
|
||||||
|
eventType == "m.reaction"
|
||||||
if (!isMessageLike) continue
|
if (!isMessageLike) continue
|
||||||
if (sender.isNotBlank() && sender == myUserId) continue
|
if (sender.isNotBlank() && sender == myUserId) continue
|
||||||
if (eventId.isNotBlank() && !shownEventIds.add(eventId)) continue
|
if (eventId.isNotBlank() && !shownEventIds.add(eventId)) continue
|
||||||
|
|
||||||
val content = event.optJSONObject("content") ?: JSONObject()
|
val content = event.optJSONObject("content") ?: JSONObject()
|
||||||
|
|
||||||
|
// Reactions have no media, so use the emoji as the icon and quote the
|
||||||
|
// reacted-to message as the body.
|
||||||
|
if (eventType == "m.reaction") {
|
||||||
|
val relates = content.optJSONObject("m.relates_to")
|
||||||
|
val key = relates?.optString("key").orEmpty()
|
||||||
|
if (key.isBlank()) continue
|
||||||
|
val parentEventId = relates?.optString("event_id").orEmpty()
|
||||||
|
val snippet =
|
||||||
|
if (parentEventId.isNotBlank())
|
||||||
|
fetchEventBodySnippet(homeserver, token, roomId, parentEventId)
|
||||||
|
else ""
|
||||||
|
val reactionBody =
|
||||||
|
if (snippet.isNotBlank()) "reacted with $key to \"$snippet\""
|
||||||
|
else "reacted with $key"
|
||||||
|
|
||||||
|
val profile = try {
|
||||||
|
resolveProfile(sender, homeserver, token)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "profile fetch failed: ${e.message}")
|
||||||
|
UserProfile(sender.substringAfter("@").substringBefore(":").ifBlank { "Someone" }, null)
|
||||||
|
}
|
||||||
|
|
||||||
|
Log.i(TAG, "notify room=$roomId type=$eventType sender=$sender")
|
||||||
|
showMessageNotification(
|
||||||
|
nm,
|
||||||
|
roomId,
|
||||||
|
profile.displayName,
|
||||||
|
reactionBody,
|
||||||
|
renderEmojiBitmap(key),
|
||||||
|
null,
|
||||||
|
resolveGroupInfo(roomId, notifyCtx),
|
||||||
|
)
|
||||||
|
notifiedForRoom = true
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
val encrypted = eventType == "m.room.encrypted"
|
val encrypted = eventType == "m.room.encrypted"
|
||||||
val msgtype = content.optString("msgtype")
|
val msgtype = content.optString("msgtype")
|
||||||
val rawBody = content.optString("body")
|
val rawBody = content.optString("body")
|
||||||
@@ -587,6 +625,25 @@ class MatrixSyncService : Service() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Fetch the body of the event a reaction points at, as a short single-line snippet. */
|
||||||
|
private fun fetchEventBodySnippet(
|
||||||
|
homeserver: String,
|
||||||
|
token: String,
|
||||||
|
roomId: String,
|
||||||
|
eventId: String,
|
||||||
|
maxLength: Int = 60,
|
||||||
|
): String {
|
||||||
|
val obj = fetchJson(
|
||||||
|
"$homeserver/_matrix/client/v3/rooms/${urlEncode(roomId)}/event/${urlEncode(eventId)}",
|
||||||
|
token,
|
||||||
|
) ?: return ""
|
||||||
|
val content = obj.optJSONObject("content") ?: return ""
|
||||||
|
val rawBody = content.optString("body")
|
||||||
|
if (rawBody.isBlank()) return ""
|
||||||
|
val trimmed = rawBody.replace(Regex("\\s+"), " ").trim()
|
||||||
|
return if (trimmed.length > maxLength) trimmed.substring(0, maxLength) + "…" else trimmed
|
||||||
|
}
|
||||||
|
|
||||||
private fun resolveProfile(mxid: String, homeserver: String, token: String): UserProfile {
|
private fun resolveProfile(mxid: String, homeserver: String, token: String): UserProfile {
|
||||||
val cachedName = displayNameCache[mxid]
|
val cachedName = displayNameCache[mxid]
|
||||||
if (cachedName != null) return UserProfile(cachedName, avatarCache[mxid])
|
if (cachedName != null) return UserProfile(cachedName, avatarCache[mxid])
|
||||||
@@ -1164,6 +1221,25 @@ class MatrixSyncService : Service() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Render a reaction emoji to a bitmap so it can be used as the notification icon. */
|
||||||
|
fun renderEmojiBitmap(emoji: String): Bitmap? {
|
||||||
|
return try {
|
||||||
|
val size = 128
|
||||||
|
val bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)
|
||||||
|
val canvas = Canvas(bitmap)
|
||||||
|
val paint = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||||
|
paint.textSize = size * 0.7f
|
||||||
|
paint.textAlign = Paint.Align.CENTER
|
||||||
|
val fontMetrics = paint.fontMetrics
|
||||||
|
val y = size / 2f - (fontMetrics.ascent + fontMetrics.descent) / 2f
|
||||||
|
canvas.drawText(emoji, size / 2f, y, paint)
|
||||||
|
bitmap
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "Failed to render emoji icon: ${e.message}")
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** Crop a bitmap into a circle for the notification avatar slot. */
|
/** Crop a bitmap into a circle for the notification avatar slot. */
|
||||||
fun toCircularBitmap(bitmap: Bitmap): Bitmap {
|
fun toCircularBitmap(bitmap: Bitmap): Bitmap {
|
||||||
val size = minOf(bitmap.width, bitmap.height)
|
val size = minOf(bitmap.width, bitmap.height)
|
||||||
|
|||||||
+1
-1
Submodule cinny updated: fabbbc40af...b294bb0c06
@@ -1,5 +1,6 @@
|
|||||||
import React, { useEffect } from 'react';
|
import React, { useEffect } from 'react';
|
||||||
import { MatrixClient } from 'matrix-js-sdk';
|
import { MatrixClient } from 'matrix-js-sdk';
|
||||||
|
import * as lucide from 'lucide-react';
|
||||||
import { Plugin, createPluginContext } from '@paarrot/plugin-manager';
|
import { Plugin, createPluginContext } from '@paarrot/plugin-manager';
|
||||||
import { pluginMarketplaceManager, pluginRegistry } from './PluginAPI';
|
import { pluginMarketplaceManager, pluginRegistry } from './PluginAPI';
|
||||||
import { sendNotification } from '../../../utils/tauri';
|
import { sendNotification } from '../../../utils/tauri';
|
||||||
@@ -80,6 +81,7 @@ export function PluginLoader({ matrixClient, children }: PluginLoaderProps) {
|
|||||||
matrixClient.off(eventType as any, handler as any),
|
matrixClient.off(eventType as any, handler as any),
|
||||||
},
|
},
|
||||||
React,
|
React,
|
||||||
|
lucide,
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log('[PluginLoader] compatContext.React:', !!compatContext.React);
|
console.log('[PluginLoader] compatContext.React:', !!compatContext.React);
|
||||||
|
|||||||
@@ -104,14 +104,52 @@ async function waitForEventDecryption(mx: MatrixClient, mEvent: MatrixEvent) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Short, single-line snippet of an event's body for use inside a notification. */
|
||||||
|
function eventBodySnippet(mEvent: MatrixEvent, maxLength = 60): string {
|
||||||
|
const content = mEvent.getClearContent() ?? mEvent.getContent();
|
||||||
|
const rawBody = typeof content.body === 'string' ? content.body : '';
|
||||||
|
if (!rawBody) return '';
|
||||||
|
const trimmed = rawBody.replace(/\s+/g, ' ').trim();
|
||||||
|
return trimmed.length > maxLength ? `${trimmed.slice(0, maxLength)}…` : trimmed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Render a reaction emoji to a PNG base64 string so it can be used as the notification icon. */
|
||||||
|
async function renderEmojiToBase64(emoji: string): Promise<string | undefined> {
|
||||||
|
try {
|
||||||
|
const size = 128;
|
||||||
|
const canvas = document.createElement('canvas');
|
||||||
|
canvas.width = size;
|
||||||
|
canvas.height = size;
|
||||||
|
const ctx = canvas.getContext('2d');
|
||||||
|
if (!ctx) return undefined;
|
||||||
|
|
||||||
|
ctx.font = `${Math.floor(size * 0.7)}px "Apple Color Emoji","Segoe UI Emoji","Noto Color Emoji",sans-serif`;
|
||||||
|
ctx.textBaseline = 'middle';
|
||||||
|
ctx.textAlign = 'center';
|
||||||
|
ctx.fillText(emoji, size / 2, size / 2);
|
||||||
|
|
||||||
|
const dataUrl = canvas.toDataURL('image/png');
|
||||||
|
return dataUrl.split(',')[1];
|
||||||
|
} catch (err) {
|
||||||
|
console.warn('[Notifications] Failed to render emoji icon:', err);
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** Build a human-readable notification body from (possibly decrypted) event content. */
|
/** Build a human-readable notification body from (possibly decrypted) event content. */
|
||||||
function notificationBodyFromEvent(mEvent: MatrixEvent): string | undefined {
|
function notificationBodyFromEvent(mx: MatrixClient, mEvent: MatrixEvent): string | undefined {
|
||||||
const content = mEvent.getClearContent() ?? mEvent.getContent();
|
const content = mEvent.getClearContent() ?? mEvent.getContent();
|
||||||
const eventType = mEvent.getType();
|
const eventType = mEvent.getType();
|
||||||
|
|
||||||
if (eventType === 'm.reaction') {
|
if (eventType === 'm.reaction') {
|
||||||
const reactionKey = content['m.relates_to']?.key;
|
const relates = content['m.relates_to'];
|
||||||
return reactionKey ? `reacted with ${reactionKey}` : 'reacted to a message';
|
const reactionKey = relates?.key;
|
||||||
|
const parent = relates?.event_id ? mx.getCachedEventById(relates.event_id) : undefined;
|
||||||
|
const snippet = parent ? eventBodySnippet(parent) : '';
|
||||||
|
|
||||||
|
if (reactionKey && snippet) return `reacted with ${reactionKey} to "${snippet}"`;
|
||||||
|
if (reactionKey) return `reacted with ${reactionKey}`;
|
||||||
|
return 'reacted to a message';
|
||||||
}
|
}
|
||||||
|
|
||||||
if (eventType === 'm.room.encrypted' || mEvent.isDecryptionFailure()) {
|
if (eventType === 'm.room.encrypted' || mEvent.isDecryptionFailure()) {
|
||||||
@@ -684,12 +722,26 @@ function MessageNotifications() {
|
|||||||
: Promise.resolve(undefined),
|
: Promise.resolve(undefined),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const messageBody = notificationBodyFromEvent(mEvent);
|
// Reactions have no media, so render the reaction emoji as the notification icon.
|
||||||
|
let finalIconBase64 = iconBase64;
|
||||||
|
let finalRoomAvatar = roomAvatar;
|
||||||
|
if (mEvent.getType() === 'm.reaction') {
|
||||||
|
const emoji = (mEvent.getClearContent() ?? mEvent.getContent())['m.relates_to']?.key;
|
||||||
|
if (emoji) {
|
||||||
|
const emojiBase64 = await renderEmojiToBase64(emoji);
|
||||||
|
if (emojiBase64) {
|
||||||
|
finalIconBase64 = emojiBase64;
|
||||||
|
finalRoomAvatar = `data:image/png;base64,${emojiBase64}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const messageBody = notificationBodyFromEvent(mx, mEvent);
|
||||||
|
|
||||||
notify({
|
notify({
|
||||||
roomName: room.name ?? 'Unknown',
|
roomName: room.name ?? 'Unknown',
|
||||||
roomAvatar,
|
roomAvatar: finalRoomAvatar,
|
||||||
iconBase64,
|
iconBase64: finalIconBase64,
|
||||||
bigPictureBase64,
|
bigPictureBase64,
|
||||||
username,
|
username,
|
||||||
messageBody,
|
messageBody,
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "paarrot",
|
"name": "paarrot",
|
||||||
"version": "4.11.180",
|
"version": "4.11.190",
|
||||||
"description": "Paarrot - A Matrix client based on Cinny",
|
"description": "Paarrot - A Matrix client based on Cinny",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=18.0.0"
|
"node": ">=18.0.0"
|
||||||
|
|||||||
@@ -33,7 +33,8 @@ if (cinnyStatus.trim()) {
|
|||||||
// Ensure android/ junction is excluded from the cinny git view — otherwise
|
// Ensure android/ junction is excluded from the cinny git view — otherwise
|
||||||
// `git stash -u` would traverse the junction into the root android/ directory
|
// `git stash -u` would traverse the junction into the root android/ directory
|
||||||
// and delete files there when the stash is created.
|
// and delete files there when the stash is created.
|
||||||
const cinnyExclude = join(CINNY, '.git', 'info', 'exclude');
|
const gitDir = resolve(CINNY, execSync('git rev-parse --git-dir', { cwd: CINNY, encoding: 'utf8' }).trim());
|
||||||
|
const cinnyExclude = join(gitDir, 'info', 'exclude');
|
||||||
const excludeContent = existsSync(cinnyExclude) ? readFileSync(cinnyExclude, 'utf8') : '';
|
const excludeContent = existsSync(cinnyExclude) ? readFileSync(cinnyExclude, 'utf8') : '';
|
||||||
if (!excludeContent.includes('android/')) {
|
if (!excludeContent.includes('android/')) {
|
||||||
writeFileSync(cinnyExclude, excludeContent + (excludeContent.endsWith('\n') || !excludeContent ? '' : '\n') + 'android/\n', 'utf8');
|
writeFileSync(cinnyExclude, excludeContent + (excludeContent.endsWith('\n') || !excludeContent ? '' : '\n') + 'android/\n', 'utf8');
|
||||||
|
|||||||
Reference in New Issue
Block a user