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
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,11 @@ GitHub stores the messages, every client polls it, and anything that can run a c
with new messages.
- **Updates**: the Windows app updates itself from GitHub releases (electron-updater); the Android and Mac apps
show a download link when a newer release is out (the Mac app is unsigned, so it can't install by itself).
- **Search**: the sidebar box finds messages too, in every chat; older messages load a page at a time
(`opencom search <text>` for agents).
- **Search**: the sidebar box finds messages too, in every chat; 🔍 in a chat searches that chat (↑ ↓ through
the matches); older messages load a page at a time. Aa matches case, .* reads a regex (`opencom search <text>
[--case] [--regex]` for agents).
- **Media and files**: a chat's details show its photos and videos in a grid and its other files in a list; a
photo opens full screen with "Show in chat".
- **Drafts**: what you typed and did not send stays in the chat, after a restart and on your other devices.
- **Edit and delete**: your own messages, for everyone; the old text stays visible under "edited", and a notice
at the end of the chat tells everyone (and every watching agent) to look again (`opencom edit` / `opencom delete`).
Expand Down
4 changes: 2 additions & 2 deletions app/android/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ android {
applicationId "com.egebulut.opencommunicate"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 42
versionName "0.9.8"
versionCode 43
versionName "0.9.9"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
aaptOptions {
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
Expand Down
2 changes: 1 addition & 1 deletion app/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@opencommunicate/app",
"private": true,
"version": "0.9.8",
"version": "0.9.9",
"type": "module",
"scripts": {
"dev": "vite",
Expand Down
223 changes: 196 additions & 27 deletions app/src/App.tsx

Large diffs are not rendered by default.

32 changes: 32 additions & 0 deletions app/src/i18n.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,22 @@ const en = {
searchOlder: "Search older messages",
allSearched: "All messages searched",
cantSearch: (e: string) => `Couldn't load older messages: ${e}`,
searchInChat: "Search in this chat",
matchCase: "Match case",
regex: "Regular expression",
badRegex: "Not a valid regex",
noMatches: "No matches",
olderMatch: "Older match",
newerMatch: "Newer match",
closeSearch: "Close search",
mediaAndFiles: "Media and files",
mediaTab: (n: number) => `Media · ${n}`,
filesTab: (n: number) => `Files · ${n}`,
noMedia: "No photos or videos in the messages loaded.",
noFiles: "No files in the messages loaded.",
olderMedia: "Look in older messages too",
allLoaded: "All messages loaded",
showInChat: "Show in chat",
everyone: "Everyone",
groups: "Groups",
newGroupButton: "+ New group",
Expand Down Expand Up @@ -542,6 +558,22 @@ const tr: typeof en = {
searchOlder: "Eski mesajlarda ara",
allSearched: "Tüm mesajlarda arandı",
cantSearch: (e) => `Eski mesajlar yüklenemedi: ${e}`,
searchInChat: "Bu sohbette ara",
matchCase: "Büyük/küçük harfe duyarlı",
regex: "Düzenli ifade (regex)",
badRegex: "Geçersiz regex",
noMatches: "Sonuç yok",
olderMatch: "Daha eski sonuç",
newerMatch: "Daha yeni sonuç",
closeSearch: "Aramayı kapat",
mediaAndFiles: "Medya ve dosyalar",
mediaTab: (n) => `Medya · ${n}`,
filesTab: (n) => `Dosyalar · ${n}`,
noMedia: "Yüklenen mesajlarda fotoğraf ya da video yok.",
noFiles: "Yüklenen mesajlarda dosya yok.",
olderMedia: "Eski mesajlara da bak",
allLoaded: "Tüm mesajlar yüklendi",
showInChat: "Sohbette göster",
everyone: "Herkes",
groups: "Gruplar",
newGroupButton: "+ Yeni grup",
Expand Down
31 changes: 31 additions & 0 deletions app/src/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -390,3 +390,34 @@ i.activity { display: inline-block; width: 9px; height: 9px; border-radius: 50%;
.saver-row:hover .tip, .tip-wrap:focus-within .tip { display: block; }
.news ul { margin: 6px 0 10px; padding-left: 20px; display: flex; flex-direction: column; gap: 6px; font-size: 14px; }
.news h3 { margin: 10px 0 0; font-size: 14px; }

/* search: Aa (match case) and .* (regex) beside a search box; the search bar of one chat */
.filter { display: flex; gap: 6px; align-items: center; }
.filter input { flex: 1; min-width: 0; }
.search-how { display: inline-flex; gap: 2px; flex: none; }
.search-how button { min-width: 32px; height: 32px; border-radius: 8px; font: 600 13px/1 ui-monospace, SFMono-Regular, Menlo, monospace; color: var(--muted); border: 1px solid transparent; }
.search-how button:hover { background: var(--sunken); }
.search-how button.on { color: var(--accent); border-color: var(--accent); background: color-mix(in srgb, var(--accent) 12%, transparent); }
.chat-search { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; padding: 6px 10px; border-bottom: 1px solid var(--line); background: var(--panel); }
.chat-search input { flex: 1 1 90px; min-width: 0; padding: 7px 10px; border-radius: 10px; font-size: 14px; }
.chat-search .count { min-width: 2.8em; text-align: center; white-space: nowrap; }
.chat-search .icon { width: 32px; height: 32px; font-size: 17px; }
.chat-search .older-in-chat, .chat-search .error { flex-basis: 100%; text-align: left; }
.chat-search .older-in-chat { flex: 0 0 auto; }
.item.found .msg { outline: 2px solid var(--accent); outline-offset: 1px; }
::highlight(search) { background-color: color-mix(in srgb, var(--accent) 30%, transparent); }
::highlight(search-here) { background-color: var(--accent); color: var(--accent-ink); }

/* the chat's media and files, in its details */
.gallery { display: grid; grid-template-columns: repeat(auto-fill, minmax(84px, 1fr)); gap: 4px; margin: 8px 0; }
.gallery .tile { position: relative; aspect-ratio: 1; padding: 0; border-radius: 8px; overflow: hidden; background: var(--sunken); display: grid; place-items: center; }
.gallery .tile img { width: 100%; height: 100%; object-fit: cover; }
.gallery .tile-name { font-size: 11px; padding: 4px; word-break: break-all; color: var(--muted); }
.gallery .tile-play { position: absolute; inset: auto 6px 6px auto; color: #fff; font-size: 13px; background: rgb(0 0 0 / .5); border-radius: 999px; padding: 2px 7px; }
.file-list { display: flex; flex-direction: column; gap: 2px; margin: 8px 0; }
.file-row { display: flex; align-items: center; gap: 6px; }
.file-body { flex: 1; min-width: 0; display: flex; flex-direction: column; align-items: flex-start; text-align: left; padding: 6px 8px; border-radius: 10px; }
.file-body:hover { background: var(--sunken); }
.file-body .row-label { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.lightbox video { max-width: 100%; max-height: 100%; border-radius: 8px; }
.lightbox-note { color: #fff; }
2 changes: 1 addition & 1 deletion cli/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@opencommunicate/cli",
"private": true,
"version": "0.9.8",
"version": "0.9.9",
"type": "module",
"bin": {
"opencom": "dist/opencom.mjs"
Expand Down
20 changes: 16 additions & 4 deletions cli/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ const DIR = () => process.env.OPENCOM_APPS || path.join(os.homedir(), ".opencomm

type App = { id: number; slug: string; pem: string; owner: string; installation?: number };
type Pending = { topic: string; at: string };
type Note = { kind?: string; code?: unknown };
type Note = { kind?: string; code?: unknown; url?: string };

const file = (owner: string, kind: "app" | "pending") => path.join(DIR(), `${owner.toLowerCase()}.${kind}.json`);
const load = <T>(p: string): T | null => { try { return JSON.parse(fs.readFileSync(p, "utf8")); } catch { return null; } };
Expand All @@ -38,6 +38,8 @@ const save = (p: string, v: object, flag = "w") => {
/** The app for a repository owner's agents on this computer, if it was made (and not turned off: OPENCOM_APP=off). */
export const appOf = (owner: string) => (process.env.OPENCOM_APP === "off" ? null : load<App>(file(owner, "app")));

const installUrl = (slug: string, topic: string) => `https://github.com/apps/${slug}/installations/new?state=${topic}`;

/** What the app signs its calls with: a JWT good for ten minutes. */
function jwt(app: App): string {
const part = (o: object) => Buffer.from(JSON.stringify(o)).toString("base64url");
Expand Down Expand Up @@ -87,7 +89,10 @@ export async function setUpStep(bus: Bus, me: Device, devices: Device[], say: (s
pending = { topic: crypto.randomBytes(16).toString("hex"), at: new Date().toISOString() };
try { save(pendingFile, pending, "wx"); } catch { return false; } // another agent here asked first
const link = `${APP_PAGE}?t=${pending.topic}&o=${encodeURIComponent(owner)}&r=${encodeURIComponent(name)}`;
const person = devices.find((d) => d.kind !== "agent" && d.login?.toLowerCase() === owner.toLowerCase());
// the owner's device seen last: an account can have old ones it no longer reads
const people = devices.filter((d) => d.kind !== "agent" && d.login?.toLowerCase() === owner.toLowerCase());
const seen = people.length > 1 ? await bus.presence().catch(() => ({} as Record<string, { lastSeen?: string }>)) : {};
const person = people.sort((a, b) => (seen[b.id]?.lastSeen ?? "").localeCompare(seen[a.id]?.lastSeen ?? ""))[0];
if (person) {
await bus.send(dmChannel(me.id, person.id), me, [
`This computer's agents can use a GitHub quota of their own and leave yours alone: open the link, tap **Create GitHub App**, then **Install** (the ${name} repository is all it needs).`,
Expand All @@ -106,14 +111,21 @@ export async function setUpStep(bus: Bus, me: Device, devices: Device[], say: (s
const d = await res.json();
if (d.owner?.login?.toLowerCase() !== owner.toLowerCase()) continue; // an app someone else made: not ours
save(file(owner, "app"), { id: d.id, slug: d.slug, pem: d.pem, owner });
await post(pending.topic, { kind: "install", url: `https://github.com/apps/${d.slug}/installations/new?state=${pending.topic}` });
say(`app: ${d.slug} made; waiting for it to be installed`);
await post(pending.topic, { kind: "install", url: installUrl(d.slug, pending.topic) });
return false;
}
return false;
}
const res = await asApp(app, `/repos/${owner}/${name}/installation`);
if (!res.ok) return false; // not installed yet
if (!res.ok) {
// not installed yet: the page waits for the install link; one lost on the way (the process stopped first) goes again
if (pending && !(await read<Note>(pending.topic, pending.at)).some((n) => n.kind === "install")) {
await post(pending.topic, { kind: "install", url: installUrl(app.slug, pending.topic) });
say(`app: ${app.slug}: the install link went to the page again`);
}
return false;
}
save(file(owner, "app"), { ...app, installation: (await res.json()).id });
fs.rmSync(pendingFile, { force: true });
say(`app: ${app.slug} installed; this computer's agents use its own GitHub quota now`);
Expand Down
16 changes: 10 additions & 6 deletions cli/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,11 @@ const USAGE = `opencom — chat over a private GitHub repository
opencom history <to> [-n 20] [--edits]
recent messages; yours end in ✓ sent, ✓✓ delivered or ✓✓ read;
an edited one says (edited), --edits lists what it said before
opencom search <text…> [--chat <to>] [-n 20]
opencom search <text…> [--chat <to>] [-n 20] [--case] [--regex]
messages (and attachment names) containing the text, newest first,
in all your chats or one; reads the whole history, so it takes a while
in all your chats or one; reads the whole history, so it takes a while.
Case-insensitive unless --case; --regex reads the text as a regular
expression (JavaScript's)
opencom edit <chat> <id> <text…> change the text of one of your messages; everyone gets a notice
("… edited a message: <new text>") at the end of the chat
opencom delete <chat> <id> delete one of your messages for everyone (text and files go;
Expand Down Expand Up @@ -184,7 +186,7 @@ const alive = (pid: number) => { try { process.kill(pid, 0); return true; } catc
const writeConfig = (c: Config) => { fs.mkdirSync(CONFIG_DIR, { recursive: true }); fs.writeFileSync(CONFIG, JSON.stringify(c, null, 2), { mode: 0o600 }); };

// flags that take no value, so "send ege --wait hi" still sends "hi"
const SWITCHES = new Set(["help", "wait", "json", "once", "to-me", "all", "edits", "off", "clear", "random", "reset", "install"]);
const SWITCHES = new Set(["help", "wait", "json", "once", "to-me", "all", "edits", "off", "clear", "random", "reset", "install", "case", "regex"]);
/** When a Claude Code session should load the guide (`opencom skill`). */
const SKILL_WHEN = "How to use OpenCommunicate (the opencom CLI and MCP server) to work with people and other agents through a chat: listening for messages, replying, asking with choices and waiting for the answer, permission prompts on a phone, status, sending and opening files and screenshots, Markdown tables, reactions, quotes, groups, and sparing the account's shared GitHub quota. Use it whenever a task involves opencom, an OpenCommunicate chat, or messaging a person or agent through one.";
function flags(args: string[]) {
Expand Down Expand Up @@ -514,11 +516,13 @@ async function main(argv: string[]) {
}
case "search": {
const text = rest.join(" ");
if (!text.trim()) throw new Error("Usage: opencom search <text…> [--chat <to>] [-n 20]");
if (!text.trim()) throw new Error("Usage: opencom search <text…> [--chat <to>] [-n 20] [--case] [--regex]");
const how = { caseSensitive: !!f.case, regex: !!f.regex };
try { searchMessages([], text, undefined, how); } catch (e) { throw new Error(`Not a regular expression: ${(e as Error).message}`); }
const { devices, groups } = await load();
const channels = f.chat ? [resolveTarget(f.chat[0], me, devices, groups)] : bus.channelsFor(me.id, devices, groups);
const { messages } = await bus.older(channels, new Set(), Infinity);
const found = searchMessages(messages, text).slice(0, Number(f.n?.[0] ?? 20));
const found = searchMessages(messages, text, undefined, how).slice(0, Number(f.n?.[0] ?? 20));
if (!found.length) console.log(`Nothing found for "${text}" in ${messages.length} messages.`);
for (const m of found.reverse()) console.log(`${line(m, me, devices, groups)} (id ${m.id})`);
return;
Expand Down Expand Up @@ -634,7 +638,7 @@ async function main(argv: string[]) {
const read = cfg.readReceipts !== false;
const sent = bus.markReceipts(me, Object.fromEntries(Object.entries(newest).map(([ch, id]) => [ch, read ? { read: id } : { delivered: id }])))
.catch((e) => console.error(`watch: receipts: ${(e as Error).message}`));
if (f.once) { await sent; return; }
if (f.once) { await sent; await appStep; return; } // a setup step under way finishes (a code traded and not kept is lost)
}
} catch (e) {
console.error(`watch: ${(e as Error).message}`);
Expand Down
2 changes: 1 addition & 1 deletion core/package.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{ "name": "@opencommunicate/core", "private": true, "version": "0.9.8", "type": "module", "main": "src/index.ts" }
{ "name": "@opencommunicate/core", "private": true, "version": "0.9.9", "type": "module", "main": "src/index.ts" }
38 changes: 33 additions & 5 deletions core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1306,14 +1306,42 @@ export function snippet(m: Pick<Message, "text" | "files" | "locked"> | undefine
return m.files?.length ? `📎 ${m.files[0].name}` : "";
}

/** How a search reads its text: as written (`caseSensitive`), and as a regular expression (`regex`). */
export type SearchOptions = { caseSensitive?: boolean; regex?: boolean };

/**
* Every place `query` matches in a text, [start, end): case-insensitive in `locale` unless `caseSensitive` (so
* Turkish İ/ı match; the places are then in the lowercased text, which a few letters make longer), as plain text
* unless `regex`. Empty matches are left out. Throws a SyntaxError for a regex that does not parse.
*/
export function searchMatches(query: string, locale?: string, o: SearchOptions = {}): (text: string) => [number, number][] {
if (o.regex) {
const re = new RegExp(query, o.caseSensitive ? "gu" : "giu");
return (text) => [...text.matchAll(re)].filter((m) => m[0]).map((m) => [m.index, m.index + m[0].length]);
}
const q = o.caseSensitive ? query : query.toLocaleLowerCase(locale);
return (text) => {
const t = o.caseSensitive ? text : text.toLocaleLowerCase(locale), out: [number, number][] = [];
for (let i = q ? t.indexOf(q) : -1; i >= 0; i = t.indexOf(q, i + q.length)) out.push([i, i + q.length]);
return out;
};
}

/** Where `query` first matches in a text (see searchMatches), or null. */
export function searchMatcher(query: string, locale?: string, o: SearchOptions = {}): (text: string) => [number, number] | null {
const all = searchMatches(query, locale, o);
return (text) => all(text)[0] ?? null;
}

/**
* Messages whose text or attachment names contain `query` (case-insensitive in `locale`, so Turkish İ/ı match),
* newest first. Notices and deleted messages are left out; an edited message matches by what it says now.
* Messages whose text or attachment names match `query` (see searchMatcher), newest first. Notices and deleted
* messages are left out; an edited message matches by what it says now. Throws for a regex that does not parse.
*/
export function searchMessages(list: Message[], query: string, locale?: string): Message[] {
const q = query.trim().toLocaleLowerCase(locale);
export function searchMessages(list: Message[], query: string, locale?: string, o: SearchOptions = {}): Message[] {
const q = query.trim();
if (!q) return [];
const has = (s?: string) => !!s && s.toLocaleLowerCase(locale).includes(q);
const match = searchMatcher(q, locale, o);
const has = (s?: string) => !!s && !!match(s);
return list.filter((m) => !m.system && !m.deleted && (has(m.text) || m.files?.some((f) => has(f.name)))).sort((a, b) => b.id.localeCompare(a.id));
}

Expand Down
18 changes: 17 additions & 1 deletion core/test/search.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// older() pages through what is not loaded yet, newest first.
import { test } from "node:test";
import assert from "node:assert/strict";
import { Bus, msgPath, newerVersion, searchMessages, snippet } from "../src/index.ts";
import { Bus, msgPath, newerVersion, searchMatcher, searchMatches, searchMessages, snippet } from "../src/index.ts";

test("newerVersion compares part by part as numbers", () => {
assert.equal(newerVersion("0.7.10", "0.7.9"), true);
Expand Down Expand Up @@ -32,6 +32,22 @@ test("Turkish case in tr-TR", () => {
assert.equal(searchMessages(list, "ısparta", "tr-TR").length, 1);
});

test("case-sensitive and regex searches, and where a match is", () => {
const list = [msg(1, "Deploy 0.9.8 to vercel"), msg(2, "deploy 0.9.9"), msg(3, "release v1.0")];
const texts = (q, o) => searchMessages(list, q, "en", o).map((m) => m.text);
assert.deepEqual(texts("Deploy", { caseSensitive: true }), ["Deploy 0.9.8 to vercel"]);
assert.deepEqual(texts("0\\.9\\.\\d", { regex: true }), ["deploy 0.9.9", "Deploy 0.9.8 to vercel"]);
assert.deepEqual(texts("^deploy", { regex: true, caseSensitive: true }), ["deploy 0.9.9"]);
assert.deepEqual(texts("0.9.8", {}), ["Deploy 0.9.8 to vercel"], "a dot is a dot without regex");
assert.deepEqual(texts("x*", { regex: true }), [], "a regex that only matches empty text matches nothing");
assert.throws(() => searchMessages(list, "(", "en", { regex: true }), SyntaxError);
assert.deepEqual(searchMatcher("VERCEL", "en")("Deploy to vercel"), [10, 16]);
assert.deepEqual(searchMatcher("v\\d", "en", { regex: true })("release v1.0"), [8, 10]);
assert.equal(searchMatcher("İstanbul", "tr-TR", { caseSensitive: true })("istanbul"), null);
assert.deepEqual(searchMatches("deploy", "en")("Deploy, then deploy again"), [[0, 6], [13, 19]]);
assert.deepEqual(searchMatches("\\d+", "en", { regex: true })("v0.9.10"), [[1, 2], [3, 4], [5, 7]]);
});

test("older() pages through what is not loaded, newest first", async () => {
const all = [1, 2, 3, 4, 5].map((i) => msg(i, `m${i}`));
const bus = new Bus({ repo: "x/y", token: "t" });
Expand Down
Loading
Loading