Merge branch 'master' into ep/feed

This commit is contained in:
sh-agents committed 2026-11-12 08:29:06 +00:00
commit d2e445237c
34 files changed
+1164 -252

No files matched your search

+1
View File
@@ -42,6 +42,7 @@ on:
- "website/test/**"
- "website/package.json"
- "packages/simplex-chat-mcp/**"
- "apps/simplex-support-bot/**"
types: [opened, synchronize, reopened, ready_for_review]
workflow_dispatch:
inputs:
+1 -1
View File
@@ -612,6 +612,7 @@ final class ChatModel: ObservableObject {
} else {
addChat_(chat, at: 0)
}
ChatTagsModel.shared.addPresetChatTags(chat.chatInfo, chat.chatStats)
popChatCollector.throttlePopChat(chat.chatInfo.id, currentPosition: 0)
}
@@ -656,7 +657,6 @@ final class ChatModel: ObservableObject {
updateChatInfo(cInfo)
} else if addMissing {
addChat(Chat(chatInfo: cInfo, chatItems: []))
ChatTagsModel.shared.addPresetChatTags(cInfo, ChatStats())
}
}
@@ -65,7 +65,7 @@ struct CIFeaturePreferenceView: View {
func allowFeatureToContact(_ contact: Contact, _ feature: ChatFeature, param: Int? = nil) {
Task {
do {
let prefs = contactUserPreferencesToPreferences(contact.mergedPreferences).setAllowed(feature, param: param)
let prefs = contact.userPreferences.setAllowed(feature, param: param)
if let toContact = try await apiSetContactPrefs(contactId: contact.contactId, preferences: prefs) {
await MainActor.run {
ChatModel.shared.updateContact(toContact)
@@ -282,7 +282,7 @@ struct ListItem: Hashable {
// using meta.hashValue instead of parts takes much more time so better to use partial meta here
func genHash(_ prevRevealed: Bool, _ nextRevealed: Bool) -> String {
"\(item.meta.itemId) \(item.meta.updatedAt.hashValue) \(item.meta.itemEdited) \(item.meta.itemDeleted?.hashValue ?? 0) \(item.meta.itemTimed?.hashValue ?? 0) \(item.meta.itemStatus.hashValue) \(item.meta.sentViaProxy ?? false) \(item.mergeCategory?.hashValue ?? 0) \(chatDirHash(item.chatDir)) \(item.reactions.hashValue) \(item.meta.isRcvNew) \(item.text.hash) \(item.file?.hashValue ?? 0) \(item.quotedItem?.itemId ?? 0) \(unreadBefore) \(prevItem?.id ?? 0) \(chatDirHash(prevItem?.chatDir)) \(prevItem?.mergeCategory?.hashValue ?? 0) \(prevRevealed) \(nextItem?.id ?? 0) \(chatDirHash(nextItem?.chatDir)) \(nextItem?.mergeCategory?.hashValue ?? 0) \(nextItem?.reactions.isEmpty ?? true) \(nextItem?.isOneLine ?? false) \(nextRevealed)"
"\(item.meta.itemId) \(item.meta.updatedAt.hashValue) \(item.meta.itemEdited) \(item.meta.isLive) \(item.meta.itemDeleted?.hashValue ?? 0) \(item.meta.itemTimed?.hashValue ?? 0) \(item.meta.itemStatus.hashValue) \(item.meta.sentViaProxy ?? false) \(item.mergeCategory?.hashValue ?? 0) \(chatDirHash(item.chatDir)) \(item.reactions.hashValue) \(item.meta.isRcvNew) \(item.text.hash) \(item.file?.hashValue ?? 0) \(item.quotedItem?.itemId ?? 0) \(unreadBefore) \(prevItem?.id ?? 0) \(chatDirHash(prevItem?.chatDir)) \(prevItem?.mergeCategory?.hashValue ?? 0) \(prevRevealed) \(nextItem?.id ?? 0) \(chatDirHash(nextItem?.chatDir)) \(nextItem?.mergeCategory?.hashValue ?? 0) \(nextItem?.reactions.isEmpty ?? true) \(nextItem?.isOneLine ?? false) \(nextRevealed)"
}
}
@@ -37,7 +37,7 @@ struct ChatPreviewView: View {
}
.padding(.leading, 4)
let chatTs = if let cItem {
let chatTs = if let cItem, cItem.content != .chatBanner {
cItem.meta.itemTs
} else {
chat.chatInfo.chatTs
-12
View File
@@ -960,18 +960,6 @@ public func fullPreferencesToPreferences(_ fullPreferences: FullPreferences) ->
)
}
public func contactUserPreferencesToPreferences(_ contactUserPreferences: ContactUserPreferences) -> Preferences {
Preferences(
timedMessages: contactUserPreferences.timedMessages.userPreference.preference,
fullDelete: contactUserPreferences.fullDelete.userPreference.preference,
reactions: contactUserPreferences.reactions.userPreference.preference,
voice: contactUserPreferences.voice.userPreference.preference,
files: contactUserPreferences.files.userPreference.preference,
calls: contactUserPreferences.calls.userPreference.preference,
commands: contactUserPreferences.commands
)
}
public protocol Preference: Codable, Equatable, Hashable {
var allow: FeatureAllowed { get set }
}
@@ -458,6 +458,9 @@ object ChatModel {
suspend fun addChat(chat: Chat) {
chats.add(index = 0, chat)
if (secondaryContextFilter == null) {
addPresetChatTags(chat.chatInfo, chat.chatStats)
}
popChatCollector.throttlePopChat(chat.remoteHostId, chat.id, currentPosition = 0)
}
@@ -519,7 +522,6 @@ object ChatModel {
updateChatInfo(rhId, cInfo)
} else if (addMissing) {
addChat(Chat(remoteHostId = rhId, chatInfo = cInfo, chatItems = arrayListOf()))
addPresetChatTags(cInfo, Chat.ChatStats())
}
}
@@ -2681,7 +2681,7 @@ object ChatController {
}
suspend fun allowFeatureToContact(rh: Long?, contact: Contact, feature: ChatFeature, param: Int? = null) {
val prefs = contact.mergedPreferences.toPreferences().setAllowed(feature, param = param)
val prefs = contact.userPreferences.setAllowed(feature, param = param)
val toContact = apiSetContactPrefs(rh, contact.contactId, prefs)
if (toContact != null) {
withContext(Dispatchers.Main) {
@@ -5939,16 +5939,6 @@ data class ContactUserPreferences(
val calls: ContactUserPreference,
val commands: List<ChatBotCommand>?,
) {
fun toPreferences(): ChatPreferences = ChatPreferences(
timedMessages = timedMessages.userPreference.pref,
fullDelete = fullDelete.userPreference.pref,
reactions = reactions.userPreference.pref,
voice = voice.userPreference.pref,
files = files.userPreference.pref,
calls = calls.userPreference.pref,
commands = commands,
)
companion object {
val sampleData = ContactUserPreferences(
timedMessages = ContactUserPreferenceTimed(
@@ -415,7 +415,7 @@ fun ChatPreviewView(
chatPreviewTitle()
}
Spacer(Modifier.width(8.sp.toDp()))
val ts = getTimestampText(chat.chatItems.lastOrNull()?.meta?.itemTs ?: chat.chatInfo.chatTs)
val ts = getTimestampText(chat.chatItems.lastOrNull()?.takeIf { it.content !is CIContent.ChatBanner }?.meta?.itemTs ?: chat.chatInfo.chatTs)
ChatListTimestampView(ts)
}
Row(Modifier.heightIn(min = 46.sp.toDp()).fillMaxWidth()) {
@@ -295,7 +295,7 @@ fun UserPicker(
{
ModalManager.start.showCustomModal(keyboardCoversBar = false) { close ->
val search = rememberSaveable { mutableStateOf("") }
val profileHidden = rememberSaveable { mutableStateOf(false) }
val profileHidden = remember { stateGetOrPut("profileHidden") { false } }
val authorized = remember { stateGetOrPut("authorized") { false } }
ModalView(
{ close() },
+104 -3
View File
@@ -5,7 +5,7 @@ A business-address bot that triages incoming support chats, optionally runs them
## Prerequisites
- Node.js v18 or newer (v24 tested)
- `GROK_API_KEY` env var (xAI) — optional; the bot runs without it
- an xAI API key in `GROK_API_KEY` or in `grok.api_key` of the config file — optional; the bot runs without it
- For the PostgreSQL backend: Linux x86_64, `libpq5` installed on the host, and a reachable PostgreSQL server
## Install & build
@@ -44,6 +44,7 @@ Run `npm start -- --help` for the auto-generated reference. Summary:
| Flag | Backend | Required | Default | Description |
|---|---|---|---|---|
| `--config` | both | no | | TOML file with option values and message texts, see [Config file](#config-file) |
| `--team-group` | both | yes | — | team group display name |
| `--state-file` | both | no | `./data/state.json` | path to bot state JSON |
| `--db` | both | no | `sqlite` | `sqlite` or `postgres` |
@@ -55,16 +56,115 @@ Run `npm start -- --help` for the auto-generated reference. Summary:
| `--timezone` | both | no | `UTC` | IANA zone for weekend detection |
| `--complete-hours` | both | no | `3` | auto-complete chats after N hours idle (`0` disables) |
| `--card-flush-seconds` | both | no | `300` | debounce card state writes |
| `--context-file` | both | required with `GROK_API_KEY` | | text file with Grok system context |
| `--queue-size` | both | no | core default, `1024` | internal queue size of the chat core, as the CLI's `-q`/`--queue-size` |
| `--context-file` | both | required with a Grok API key | | text file with Grok system context |
| `--dry-run` | both | no | | check config, database and state, then exit |
| `--allow-migrations` | both | no | | with `--dry-run`: apply pending migrations instead of reporting them |
| `--allow-down-migrations` | both | no | | with `--dry-run`: roll back migrations that this build does not have |
| `-h` / `--help` | both | no | | show usage and exit |
## Config file
`--config config.toml` reads option values and message texts from a TOML file, as [config.toml.example](../../scripts/support-bot/config/config.toml.example) shows. A list is joined with commas. An option given on the command line takes precedence over the file. `--dry-run`, `--allow-migrations` and `--allow-down-migrations` are command-line only. `grok.api_key` is file-only, so that the key is not visible in the process list; `GROK_API_KEY` takes precedence over it. The file holds the `pg_conn` password and the Grok key, so keep it readable only by the user that runs the bot.
| Key | Option |
|---|---|
| `bot.team_group` | `--team-group` |
| `bot.auto_add_team_members` | `--auto-add-team-members` |
| `bot.state_file` | `--state-file` |
| `bot.timezone` | `--timezone` |
| `bot.complete_hours` | `--complete-hours` |
| `bot.card_flush_seconds` | `--card-flush-seconds` |
| `bot.queue_size` | `--queue-size` |
| `database.type` | `--db` |
| `database.pg_conn` | `--pg-conn` |
| `database.pg_schema` | `--pg-schema` |
| `database.sqlite_file_prefix` | `--sqlite-file-prefix` |
| `database.sqlite_key` | `--sqlite-key` |
| `grok.context_file` | `--context-file` |
| `grok.api_key` | `GROK_API_KEY` |
A message left out of `[messages]` keeps its built-in text. `{hours}` is replaced with 24 on weekdays and 48 at weekends in `bot.timezone`. The welcome message is updated in the bot address on the next start.
| Message | Sent when |
|---|---|
| `welcome` | a customer connects to the business address |
| `queue` | a customer's first message is queued for the team, and after `grok_unavailable` when `/grok` was the first message |
| `queue_grok` | appended to `queue` after an empty line when Grok is enabled |
| `grok_activated` | Grok joins after `/grok` |
| `team_added` | team members are added after `/team` |
| `team_added_grok` | appended to `team_added` on a new line when Grok is in the chat |
| `team_already_invited` | `/team` is sent again while a team member is in the chat |
| `team_locked` | `/grok` is sent after a team member wrote in the chat |
| `no_team_members` | `/team` is sent with no team members configured |
| `no_team_members_grok` | the same, when Grok is enabled |
| `grok_inviting` | Grok is being invited |
| `grok_unavailable` | Grok cannot be invited, does not join within 2 minutes, or its first answer fails |
| `grok_error` | Grok's answer to a later message fails |
| `grok_no_history` | Grok joined but could not read earlier messages |
## Environment variables
| Var | Purpose |
|---|---|
| `GROK_API_KEY` | xAI API key; enables Grok replies |
| `GROK_API_KEY` | xAI API key; enables Grok replies; takes precedence over `grok.api_key` of the config file |
| `SIMPLEX_LIBS_DIR` | directory with a local libsimplex build for the `--db` backend, instead of the downloaded one |
| `SIMPLEX_ADDON_PATH` | locally built Node.js add-on (`simplex.node`), instead of the downloaded one |
| `NODE_OPTIONS` | `--max-old-space-size=8192` on a bot with many chats: single API responses outgrow the default heap |
## Docker
`scripts/support-bot/Dockerfile` builds the bot on the PostgreSQL backend with one of two library sources, selected by `LIBS`:
| `LIBS` | libsimplex, Node.js add-on and npm packages | Build time |
|---|---|---|
| `release` (default) | the versions pinned by package-lock.json, downloaded and checked by SHA-256 at build time | minutes |
| `source` | built from this checkout | hours on a cold cabal cache |
```bash
cd scripts/support-bot
cp config/config.toml.example config/config.toml
docker compose up --build
LIBS=source docker compose build
```
`scripts/support-bot/config` is mounted at `/etc/support-bot` and holds `config.toml`, with `database.pg_conn` and `grok.api_key`, and the Grok context file; the bot runs as uid 1000, which must be able to read them. Other arguments are passed after the service name, for example `docker compose run --rm support-bot --config /etc/support-bot/config.toml --dry-run`.
## Dry run
`--dry-run` opens the database, checks what the next start would do, and exits. It does not start chat, so nothing is sent to the network, and pending migrations are reported, not applied.
```bash
npm start -- --dry-run --team-group "Support Team" --db postgres --pg-conn "postgres://user:pass@host/db" \
-a 3:alice --context-file ./data/grok-context.yaml
```
```
ok database postgres opened, schema up to date
ok active user: 1:Ask SimpleX Team
ok team group 1: Support Team
FAIL team member 3:alice has display name "bob", the bot would exit
```
A pending migration stops the checks:
```
FAIL database: pending 2 migration(s): 20261019_chat_layout, 20261021_badge_subscriptions; a real start would apply them, --allow-migrations applies them now
```
With `--allow-migrations`, the migrations are applied first and the checks run after them. Run it against a restored copy of the database unless the migration is intended, and with the bot stopped.
A database migrated by a newer build also stops the checks, since the bot refuses to start on it:
```
FAIL database: database is newer than this build, to roll back 1 migration(s): 20260905_feeds; a real start would refuse, --allow-down-migrations rolls them back
```
With `--allow-down-migrations`, those migrations are rolled back with the down SQL that the newer build stored in the database, and the checks run after it. The core rolls back only when this build's migrations are a prefix of the database's; a database whose migrations diverge from this build's is reported as a migration state error and is not changed. Rolling back deletes the data of the removed migrations, so take a backup first.
A line is `ok`, `FAIL` or `?`. `?` marks an id absent from the chat previews: with chat stopped, only chats that were used are listed, so the bot verifies such ids at startup.
The exit code is 0 when no line is `FAIL`, 1 otherwise. The checks cover the database connection and migrations, the persisted team group, Grok user and Grok contact, the `--auto-add-team-members` ids and names, and the `--context-file`.
## Local development against unreleased lib changes
@@ -87,3 +187,4 @@ export SIMPLEX_ADDON_PATH=../../packages/simplex-chat-nodejs/build/Release/simpl
- **`--pg-conn is required with --db postgres`** — pass a connection string, or use `--db sqlite`.
- **`libpq5` errors at startup** — install `libpq5` on the host (`apt install libpq5` on Debian/Ubuntu).
- **`ENOENT: no such file or directory, open './data/state.json'`** — the parent directory of `--state-file` must exist; `mkdir -p data` before starting.
- **`JavaScript heap out of memory`** — a response outgrew the default heap; restart with `NODE_OPTIONS=--max-old-space-size=8192`.
+310 -15
View File
@@ -1,4 +1,4 @@
import {describe, test, expect, beforeEach, vi} from "vitest"
import {describe, test, expect, beforeEach, afterEach, vi} from "vitest"
import {mkdtempSync, writeFileSync} from "fs"
import {tmpdir} from "os"
import {join} from "path"
@@ -8,7 +8,8 @@ import {CardManager} from "./src/cards.js"
import {parseConfig} from "./src/config.js"
import {GrokApiClient} from "./src/grok.js"
import {loadGrokContext} from "./src/context.js"
import {welcomeMessage, queueMessage, grokActivatedMessage, teamLockedMessage, teamAlreadyInvitedMessage} from "./src/messages.js"
import {dryRun, migrationPlan} from "./src/dryRun.js"
import {defaultMessages, queueMessage, teamAddedMessage, noTeamMembersMessage} from "./src/messages.js"
// Silence console output during tests
vi.spyOn(console, "log").mockImplementation(() => {})
@@ -272,6 +273,7 @@ function makeConfig(overrides: Partial<any> = {}) {
cardFlushSeconds: 300,
grokApiKey: "test-key",
grokContactId: GROK_CONTACT_ID as number | null,
messages: defaultMessages,
...overrides,
}
}
@@ -669,7 +671,7 @@ describe("/grok Activation", () => {
await joinPromise
await bot.flush()
expectMemberAdded(CUSTOMER_GROUP_ID, GROK_CONTACT_ID)
expectSentToGroup(CUSTOMER_GROUP_ID, grokActivatedMessage)
expectSentToGroup(CUSTOMER_GROUP_ID, defaultMessages.grokActivated)
})
test("/grok as first message → WELCOME→GROK directly, no queue message", async () => {
@@ -677,7 +679,7 @@ describe("/grok Activation", () => {
await bot.onNewChatItems(customerMessage("/grok"))
await joinPromise
await bot.flush()
expectSentToGroup(CUSTOMER_GROUP_ID, grokActivatedMessage)
expectSentToGroup(CUSTOMER_GROUP_ID, defaultMessages.grokActivated)
expectNotSentToGroup(CUSTOMER_GROUP_ID, "The team will reply to your message")
expect(chat.sentTo(TEAM_GROUP_ID).length).toBeGreaterThan(0)
})
@@ -685,7 +687,7 @@ describe("/grok Activation", () => {
test("/grok in TEAM → rejected with teamLockedMessage", async () => {
await reachTeam()
await bot.onNewChatItems(customerMessage("/grok"))
expectSentToGroup(CUSTOMER_GROUP_ID, teamLockedMessage)
expectSentToGroup(CUSTOMER_GROUP_ID, defaultMessages.teamLocked)
})
test("/grok when grokContactId is null → grokUnavailableMessage", async () => {
@@ -963,7 +965,7 @@ describe("/team Activation", () => {
addBotMessage("We will reply within 24 hours.")
chat.members.set(CUSTOMER_GROUP_ID, [makeTeamMember(TEAM_MEMBER_1_ID, "Alice")])
await bot.onNewChatItems(customerMessage("/team"))
expectSentToGroup(CUSTOMER_GROUP_ID, teamAlreadyInvitedMessage)
expectSentToGroup(CUSTOMER_GROUP_ID, defaultMessages.teamAlreadyInvited)
})
test("/team with no team members → noTeamMembersMessage", async () => {
@@ -997,7 +999,7 @@ describe("One-Way Gate", () => {
test("/grok after gate → teamLockedMessage", async () => {
await reachTeam()
await bot.onNewChatItems(customerMessage("/grok"))
expectSentToGroup(CUSTOMER_GROUP_ID, teamLockedMessage)
expectSentToGroup(CUSTOMER_GROUP_ID, defaultMessages.teamLocked)
})
test("customer text in TEAM → card update scheduled, no bot reply", async () => {
@@ -1568,7 +1570,7 @@ describe("Error Handling", () => {
// Only the "Inviting Grok" message is sent — no activated/unavailable result
expect(chat.sent.length).toBe(sentBefore + 1)
expectSentToGroup(CUSTOMER_GROUP_ID, "Inviting Grok")
expectNotSentToGroup(CUSTOMER_GROUP_ID, grokActivatedMessage)
expectNotSentToGroup(CUSTOMER_GROUP_ID, defaultMessages.grokActivated)
expectNotSentToGroup(CUSTOMER_GROUP_ID, "temporarily unavailable")
})
@@ -1758,7 +1760,7 @@ describe("Grok Join Flow", () => {
await bot.flush()
expect(chat.joined).toContain(GROK_LOCAL_GROUP_ID)
expectSentToGroup(CUSTOMER_GROUP_ID, grokActivatedMessage)
expectSentToGroup(CUSTOMER_GROUP_ID, defaultMessages.grokActivated)
})
test("per-message responses suppressed during activateGrok initial response", async () => {
@@ -1906,7 +1908,7 @@ describe("End-to-End Flows", () => {
await joinPromise
await bot.flush()
expectSentToGroup(CUSTOMER_GROUP_ID, grokActivatedMessage)
expectSentToGroup(CUSTOMER_GROUP_ID, defaultMessages.grokActivated)
expectNotSentToGroup(CUSTOMER_GROUP_ID, "The team will reply to your message")
expect(chat.sentTo(TEAM_GROUP_ID).length).toBeGreaterThan(0)
})
@@ -1938,22 +1940,39 @@ describe("End-to-End Flows", () => {
describe("Message Templates", () => {
test("welcomeMessage is a non-empty string", () => {
expect(typeof welcomeMessage).toBe("string")
expect(welcomeMessage.length).toBeGreaterThan(0)
expect(typeof defaultMessages.welcome).toBe("string")
expect(defaultMessages.welcome.length).toBeGreaterThan(0)
})
test("grokActivatedMessage mentions chatting with Grok", () => {
expect(grokActivatedMessage).toContain("chatting with Grok")
expect(defaultMessages.grokActivated).toContain("chatting with Grok")
})
test("teamLockedMessage tells customer the team will handle the conversation", () => {
expect(teamLockedMessage).toContain("team")
expect(defaultMessages.teamLocked).toContain("team")
})
test("queueMessage mentions hours", () => {
const msg = queueMessage("UTC", true)
const msg = queueMessage(defaultMessages, "UTC", true)
expect(msg).toContain("hours")
})
test("queueMessage replaces every {hours} with 24 or 48 and appends the Grok part only with Grok", () => {
const messages = {...defaultMessages, queue: "Reply in {hours}h, not later than {hours}h.", queueGrok: "Try /grok."}
expect(queueMessage(messages, "UTC", false)).toMatch(/^Reply in (24|48)h, not later than (24|48)h\.$/)
expect(queueMessage(messages, "UTC", true)).toMatch(/^Reply in (24|48)h, not later than (24|48)h\.\n\nTry \/grok\.$/)
})
test("teamAddedMessage appends the Grok line on a new line only when Grok is present", () => {
const messages = {...defaultMessages, teamAdded: "Within {hours}h.", teamAddedGrok: "Grok helps."}
expect(teamAddedMessage(messages, "UTC", false)).toMatch(/^Within (24|48)h\.$/)
expect(teamAddedMessage(messages, "UTC", true)).toMatch(/^Within (24|48)h\.\nGrok helps\.$/)
})
test("noTeamMembersMessage selects the text by Grok availability", () => {
expect(noTeamMembersMessage(defaultMessages, true)).toBe(defaultMessages.noTeamMembersGrok)
expect(noTeamMembersMessage(defaultMessages, false)).toBe(defaultMessages.noTeamMembers)
})
})
describe("State persistence in customData", () => {
@@ -2452,6 +2471,161 @@ describe("parseConfig Validation", () => {
expect(cfg.db).toEqual({type: "sqlite", filePrefix: "./data/simplex", encryptionKey: "secret"})
})
test("--dry-run and --allow-migrations default to false and parse when given", () => {
expect(parseConfig(baseArgs).dryRun).toBe(false)
expect(parseConfig(baseArgs).allowMigrations).toBe(false)
const cfg = parseConfig([...baseArgs, "--dry-run", "--allow-migrations"])
expect(cfg.dryRun).toBe(true)
expect(cfg.allowMigrations).toBe(true)
})
test("--allow-migrations without --dry-run → throws", () => {
expect(() => parseConfig([...baseArgs, "--allow-migrations"]))
.toThrow(/--allow-migrations requires --dry-run/)
})
test("--queue-size is unset by default, so the core default applies", () => {
expect(parseConfig(baseArgs).queueSize).toBeUndefined()
})
test("--queue-size parses a positive integer", () => {
expect(parseConfig([...baseArgs, "--queue-size", "65536"]).queueSize).toBe(65536)
})
test("--queue-size 0 or non-numeric → throws, as the core rejects 0", () => {
expect(() => parseConfig([...baseArgs, "--queue-size", "0"]))
.toThrow(/--queue-size must be a positive integer, got "0"/)
expect(() => parseConfig([...baseArgs, "--queue-size", "big"]))
.toThrow(/--queue-size must be a positive integer, got "big"/)
})
test("--allow-down-migrations defaults to false, parses with --dry-run, throws without it", () => {
expect(parseConfig(baseArgs).allowDownMigrations).toBe(false)
expect(parseConfig([...baseArgs, "--dry-run", "--allow-down-migrations"]).allowDownMigrations).toBe(true)
expect(() => parseConfig([...baseArgs, "--allow-down-migrations"]))
.toThrow(/--allow-down-migrations requires --dry-run/)
})
describe("--config TOML file", () => {
const configFile = (toml: string): string => {
const path = join(mkdtempSync(join(tmpdir(), "support-bot-config-")), "bot.toml")
writeFileSync(path, toml)
return path
}
test("option values and messages are read; missing messages keep the defaults", () => {
const path = configFile([
`[bot]`,
`team_group = "SimpleX Support Team"`,
`auto_add_team_members = ["1:Alice", "2:Bob"]`,
`complete_hours = 0`,
`queue_size = 65536`,
`[database]`,
`type = "postgres"`,
`pg_conn = "postgres://localhost/db"`,
`[messages]`,
`welcome = """`,
`Hello!`,
``,
`Ask anything."""`,
`team_added_grok = "Grok helps."`,
].join("\n"))
const cfg = parseConfig(["--config", path])
expect(cfg.teamGroup).toEqual({id: 0, name: "SimpleX Support Team"})
expect(cfg.teamMembers).toEqual([{id: 1, name: "Alice"}, {id: 2, name: "Bob"}])
expect(cfg.completeHours).toBe(0)
expect(cfg.queueSize).toBe(65536)
expect(cfg.db).toEqual({type: "postgres", connectionString: "postgres://localhost/db"})
expect(cfg.messages.welcome).toBe("Hello!\n\nAsk anything.")
expect(cfg.messages.teamAddedGrok).toBe("Grok helps.")
expect(cfg.messages.queue).toBe(defaultMessages.queue)
})
test("command-line options take precedence over the file, given before or after --config", () => {
const path = configFile(`[bot]\nteam_group = "From file"\ntimezone = "Europe/London"`)
expect(parseConfig(["--team-group", "From CLI", "--config", path]).teamGroup.name).toBe("From CLI")
expect(parseConfig([`--config=${path}`, "--team-group", "From CLI"]).timezone).toBe("Europe/London")
})
test("without --config → default messages", () => {
expect(parseConfig(baseArgs).messages).toEqual(defaultMessages)
})
test("values are validated as on the command line", () => {
expect(() => parseConfig(["--config", configFile(`[bot]\nteam_group = "T"\ncomplete_hours = -1`)]))
.toThrow(/--complete-hours must be a non-negative integer, got "-1"/)
expect(() => parseConfig(["--config", configFile(`[bot]\nteam_group = "T"\n[database]\ntype = "mysql"`)]))
.toThrow(/Allowed choices are sqlite, postgres/)
expect(() => parseConfig(["--config", configFile(`[bot]\nteam_group = "T"\n[database]\ntype = "sqlite"\npg_conn = "c"`)]))
.toThrow(/--pg-conn and --pg-schema require --db postgres/)
})
test("unknown sections and keys, top-level keys and non-scalar values → throw", () => {
expect(() => parseConfig(["--config", configFile(`[server]\nport = 1`)]))
.toThrow(/unknown section \[server\], known sections: bot, database, grok, messages/)
expect(() => parseConfig(["--config", configFile(`team_group = "T"`)]))
.toThrow(/unknown section \[team_group\]/)
expect(() => parseConfig(["--config", configFile(`[bot]\nteam_grup = "T"`)]))
.toThrow(/unknown key bot.team_grup, known keys: team_group, auto_add_team_members,/)
expect(() => parseConfig(["--config", configFile(`[bot]\ndry_run = true`)]))
.toThrow(/unknown key bot.dry_run/)
expect(() => parseConfig(["--config", configFile(`[bot]\nteam_group = true`)]))
.toThrow(/bot.team_group must be a string, a number or a list of strings/)
expect(() => parseConfig(["--config", configFile(`bot = "T"`)]))
.toThrow(/\[bot\] must be a section/)
})
test("unknown or non-string messages → throw", () => {
expect(() => parseConfig(["--config", configFile(`[bot]\nteam_group = "T"\n[messages]\nteamAdded = "Hi"`)]))
.toThrow(/unknown message teamAdded, known messages: welcome, queue, queue_grok, grok_activated, team_added,/)
expect(() => parseConfig(["--config", configFile(`[bot]\nteam_group = "T"\n[messages]\nwelcome = 1`)]))
.toThrow(/message welcome must be a string/)
expect(() => parseConfig(["--config", configFile(`messages = "Hi"\n[bot]\nteam_group = "T"`)]))
.toThrow(/\[messages\] must be a section/)
})
describe("grok.api_key", () => {
const savedKey = process.env.GROK_API_KEY
beforeEach(() => { delete process.env.GROK_API_KEY })
afterEach(() => {
if (savedKey === undefined) delete process.env.GROK_API_KEY
else process.env.GROK_API_KEY = savedKey
})
const withKey = () => configFile(`[bot]\nteam_group = "T"\n[grok]\ncontext_file = "ctx.yaml"\napi_key = "file-key"`)
test("is read from the file", () => {
expect(parseConfig(["--config", withKey()]).grokApiKey).toBe("file-key")
})
test("GROK_API_KEY takes precedence; an empty GROK_API_KEY does not", () => {
process.env.GROK_API_KEY = "env-key"
expect(parseConfig(["--config", withKey()]).grokApiKey).toBe("env-key")
process.env.GROK_API_KEY = ""
expect(parseConfig(["--config", withKey()]).grokApiKey).toBe("file-key")
})
test("requires a context file", () => {
expect(() => parseConfig(["--config", configFile(`[bot]\nteam_group = "T"\n[grok]\napi_key = "file-key"`)]))
.toThrow(/A Grok API key is set but --context-file is not provided/)
})
test("must be a non-empty string", () => {
expect(() => parseConfig(["--config", configFile(`[bot]\nteam_group = "T"\n[grok]\napi_key = ""`)]))
.toThrow(/grok.api_key must be a non-empty string/)
expect(() => parseConfig(["--config", configFile(`[bot]\nteam_group = "T"\n[grok]\napi_key = 1`)]))
.toThrow(/grok.api_key must be a non-empty string/)
})
test("absent from file and environment → Grok disabled", () => {
expect(parseConfig(["--config", configFile(`[bot]\nteam_group = "T"`)]).grokApiKey).toBeNull()
})
})
test("malformed TOML → throws", () => {
expect(() => parseConfig(["--config", configFile(`[bot]\nteam_group = "unclosed`)])).toThrow()
})
})
test("unknown flag → parseArgs throws", () => {
expect(() => parseConfig([...baseArgs, "--team-gropu", "typo"]))
.toThrow()
@@ -2688,3 +2862,124 @@ describe("loadGrokContext", () => {
expect(() => loadGrokContext(join(dir, "does-not-exist.yaml"))).toThrow()
})
})
describe("Dry Run", () => {
const directChat = (contactId: number, displayName: string) => ({
chatInfo: {type: "direct", contact: {contactId, profile: {displayName}}},
})
const groupChat = (groupId: number, displayName: string) => ({
chatInfo: {type: "group", groupInfo: {groupId, groupProfile: {displayName}}},
})
function mkChat(chats: unknown[], users: number[] = [1]) {
return {
apiGetActiveUser: async () => ({userId: 1, profile: {displayName: "Ask SimpleX Team"}}),
apiListUsers: async () => users.map(userId => ({user: {userId, profile: {displayName: `user${userId}`}}})),
apiGetChats: async (_userId: number, _pagination: unknown, query?: {type: string; search?: string}) =>
query?.type === "search"
? chats.filter((c: any) =>
(c.chatInfo.contact?.profile.displayName ?? c.chatInfo.groupInfo?.groupProfile.displayName) === query.search)
: chats,
} as any
}
const config = (over: object = {}) =>
({
teamGroup: {id: 0, name: "Support Team"},
teamMembers: [],
contextFile: null,
...over,
}) as any
test("all ids resolve → passes", async () => {
const chat = mkChat([groupChat(1, "Support Team"), directChat(3, "alice")])
const ok = await dryRun(chat, config({teamMembers: [{id: 3, name: "alice"}]}), {teamGroupId: 1})
expect(ok).toBe(true)
})
test("no team group in state → reports it would be created, passes", async () => {
const chat = mkChat([])
expect(await dryRun(chat, config(), {})).toBe(true)
})
test("team group id not in chat previews → reported, passes", async () => {
const chat = mkChat([groupChat(7, "Support Team")])
expect(await dryRun(chat, config(), {teamGroupId: 1})).toBe(true)
})
test("team member id not in chat previews → reported, passes", async () => {
const chat = mkChat([groupChat(1, "Support Team")])
expect(await dryRun(chat, config({teamMembers: [{id: 3, name: "alice"}]}), {teamGroupId: 1})).toBe(true)
})
test("team member found by id after a rename → fails", async () => {
const chat = mkChat([groupChat(1, "Support Team"), directChat(3, "alice")])
expect(await dryRun(chat, config({teamMembers: [{id: 3, name: "bob"}]}), {teamGroupId: 1})).toBe(false)
})
test("persisted Grok user missing → fails", async () => {
const chat = mkChat([groupChat(1, "Support Team")], [1])
expect(await dryRun(chat, config(), {teamGroupId: 1, grokUserId: 2})).toBe(false)
})
test("persisted Grok user present → passes", async () => {
const chat = mkChat([groupChat(1, "Support Team")], [1, 2])
expect(await dryRun(chat, config(), {teamGroupId: 1, grokUserId: 2})).toBe(true)
})
test("no active user → fails", async () => {
const chat = {...mkChat([]), apiGetActiveUser: async () => undefined}
expect(await dryRun(chat, config(), {})).toBe(false)
})
test("malformed context file → fails", async () => {
const dir = mkdtempSync(join(tmpdir(), "support-bot-dryrun-"))
const path = join(dir, "ctx.yaml")
writeFileSync(path, "- role: user\n message: [unclosed\n")
const chat = mkChat([groupChat(1, "Support Team")])
expect(await dryRun(chat, config({contextFile: path}), {teamGroupId: 1})).toBe(false)
})
describe("migrationPlan", () => {
const allow = (allowMigrations: boolean, allowDownMigrations: boolean) => ({allowMigrations, allowDownMigrations})
const upgrade = {type: "upgrade" as const, names: ["20261019_chat_layout", "20261021_badge_subscriptions"]}
const downgrade = {type: "downgrade" as const, names: ["20260905_feeds"]}
test("current schema → opens without migrating", () => {
expect(migrationPlan({type: "current"}, allow(false, false)))
.toEqual({ok: true, confirm: "error", result: "schema up to date"})
})
test("pending up migrations → fail without --allow-migrations, YesUp with it", () => {
expect(migrationPlan(upgrade, allow(false, true))).toEqual({
ok: false,
reason: "pending 2 migration(s): 20261019_chat_layout, 20261021_badge_subscriptions; a real start would apply them, --allow-migrations applies them now",
})
expect(migrationPlan(upgrade, allow(true, false))).toEqual({
ok: true,
confirm: "yesUp",
result: "applied 2 migration(s): 20261019_chat_layout, 20261021_badge_subscriptions",
})
})
test("down migrations → fail without --allow-down-migrations, YesUpDown with it", () => {
expect(migrationPlan(downgrade, allow(true, false))).toEqual({
ok: false,
reason: "database is newer than this build, to roll back 1 migration(s): 20260905_feeds; a real start would refuse, --allow-down-migrations rolls them back",
})
expect(migrationPlan(downgrade, allow(false, true)))
.toEqual({ok: true, confirm: "yesUpDown", result: "rolled back 1 migration(s): 20260905_feeds"})
})
test("probe failure → fails with its text whatever is allowed", () => {
expect(migrationPlan({type: "failed", text: "connection refused"}, allow(true, true)))
.toEqual({ok: false, reason: "connection refused"})
})
})
test("missing context file → reported, passes", async () => {
const chat = mkChat([groupChat(1, "Support Team")])
const cfg = config({contextFile: join(tmpdir(), "no-such-context.txt")})
expect(await dryRun(chat, cfg, {teamGroupId: 1})).toBe(true)
})
})
+37 -125
View File
@@ -9,10 +9,11 @@
"version": "0.1.0",
"license": "AGPL-3.0",
"dependencies": {
"@simplex-chat/types": "^0.6.0",
"@simplex-chat/types": "^7.1.0-beta.9.1",
"async-mutex": "^0.5.0",
"commander": "^14.0.3",
"simplex-chat": "^6.5.1",
"simplex-chat": "^7.1.0-beta.10.2",
"smol-toml": "^1.9.1",
"yaml": "^2.8.4"
},
"devDependencies": {
@@ -783,9 +784,9 @@
]
},
"node_modules/@simplex-chat/types": {
"version": "0.6.0",
"resolved": "https://registry.npmjs.org/@simplex-chat/types/-/types-0.6.0.tgz",
"integrity": "sha512-QVYvaRsS6TnS+IROjNkekZYvhvy8QoA8vKCuGe9E6lplXDVutJo9tdDOSWS9NDdtwxT1wRZ29zN4xEZEEG/NHw==",
"version": "7.1.0-beta.9.1",
"resolved": "https://registry.npmjs.org/@simplex-chat/types/-/types-7.1.0-beta.9.1.tgz",
"integrity": "sha512-bK/x3D1mX9xDH8i2bl6mCBSBUTim52IYvq54FSLMjJ6ttLnSyrWskJKGF7xRTOCotiFI6+Gz6JmV7ekFaEi/fw==",
"license": "AGPL-3.0",
"dependencies": {
"typescript": "^5.9.2"
@@ -809,22 +810,12 @@
"version": "22.19.17",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.17.tgz",
"integrity": "sha512-wGdMcf+vPYM6jikpS/qhg6WiqSV/OhG+jeeHT/KlVqxYfD40iYJf9/AE1uQxVWFvU7MipKRkRv8NSHiCGgPr8Q==",
"devOptional": true,
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
}
},
"node_modules/@types/yauzl": {
"version": "2.10.3",
"resolved": "https://registry.npmjs.org/@types/yauzl/-/yauzl-2.10.3.tgz",
"integrity": "sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q==",
"license": "MIT",
"optional": true,
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@vitest/expect": {
"version": "1.6.1",
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-1.6.1.tgz",
@@ -957,15 +948,6 @@
"tslib": "^2.4.0"
}
},
"node_modules/buffer-crc32": {
"version": "0.2.13",
"resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz",
"integrity": "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==",
"license": "MIT",
"engines": {
"node": "*"
}
},
"node_modules/cac": {
"version": "6.7.14",
"resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz",
@@ -1043,6 +1025,7 @@
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
"dev": true,
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
@@ -1079,15 +1062,6 @@
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
}
},
"node_modules/end-of-stream": {
"version": "1.4.5",
"resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",
"integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==",
"license": "MIT",
"dependencies": {
"once": "^1.4.0"
}
},
"node_modules/esbuild": {
"version": "0.21.5",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz",
@@ -1174,41 +1148,12 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/extract-zip": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/extract-zip/-/extract-zip-2.0.1.tgz",
"integrity": "sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg==",
"license": "BSD-2-Clause",
"dependencies": {
"debug": "^4.1.1",
"get-stream": "^5.1.0",
"yauzl": "^2.10.0"
},
"bin": {
"extract-zip": "cli.js"
},
"engines": {
"node": ">= 10.17.0"
},
"optionalDependencies": {
"@types/yauzl": "^2.9.1"
}
},
"node_modules/fast-deep-equal": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
"license": "MIT"
},
"node_modules/fd-slicer": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.1.0.tgz",
"integrity": "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g==",
"license": "MIT",
"dependencies": {
"pend": "~1.2.0"
}
},
"node_modules/fsevents": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
@@ -1234,21 +1179,6 @@
"node": "*"
}
},
"node_modules/get-stream": {
"version": "5.2.0",
"resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz",
"integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==",
"license": "MIT",
"dependencies": {
"pump": "^3.0.0"
},
"engines": {
"node": ">=8"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/human-signals": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/human-signals/-/human-signals-5.0.0.tgz",
@@ -1367,6 +1297,7 @@
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"dev": true,
"license": "MIT"
},
"node_modules/nanoid": {
@@ -1388,15 +1319,6 @@
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
}
},
"node_modules/node-addon-api": {
"version": "8.7.0",
"resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.7.0.tgz",
"integrity": "sha512-9MdFxmkKaOYVTV+XVRG8ArDwwQ77XIgIPyKASB1k3JPq3M8fGQQQE3YpMOrKm6g//Ktx8ivZr8xo1Qmtqub+GA==",
"license": "MIT",
"engines": {
"node": "^18 || ^20 || >= 21"
}
},
"node_modules/npm-run-path": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-5.3.0.tgz",
@@ -1426,15 +1348,6 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/once": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
"integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
"license": "ISC",
"dependencies": {
"wrappy": "1"
}
},
"node_modules/onetime": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/onetime/-/onetime-6.0.0.tgz",
@@ -1570,16 +1483,6 @@
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
}
},
"node_modules/pump": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz",
"integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==",
"license": "MIT",
"dependencies": {
"end-of-stream": "^1.1.0",
"once": "^1.3.1"
}
},
"node_modules/react-is": {
"version": "18.3.1",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz",
@@ -1676,16 +1579,29 @@
}
},
"node_modules/simplex-chat": {
"version": "6.5.1",
"resolved": "https://registry.npmjs.org/simplex-chat/-/simplex-chat-6.5.1.tgz",
"integrity": "sha512-1cv91iMCqtP+9R1PQM3NKazocoUInKT2/06pIOuzORD5/VzulR6cMZnEQmaT02Jz+8FVkEKTsaAIJfVP6/tJmw==",
"hasInstallScript": true,
"version": "7.1.0-beta.10.2",
"resolved": "https://registry.npmjs.org/simplex-chat/-/simplex-chat-7.1.0-beta.10.2.tgz",
"integrity": "sha512-P3ONgfa7msuLC0/eK/Id0AUhnB7v7jzhOXgawgWDYHHqg/ZvYQPOrT0Y7wT3c2JNReg6kAdsn7YoioEk24SY3A==",
"license": "AGPL-3.0",
"dependencies": {
"@simplex-chat/types": "^0.6.0",
"extract-zip": "^2.0.1",
"@simplex-chat/types": "^7.1.0-beta.9.1",
"fast-deep-equal": "^3.1.3",
"node-addon-api": "^8.5.0"
"yauzl": "^3.4.0"
},
"bin": {
"simplex-chat": "dist/cli.js"
}
},
"node_modules/smol-toml": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.9.1.tgz",
"integrity": "sha512-j7WyPdf0CJoutMzMoPLF/bVXHtKZIT9Rb4eGeEbWw8X2t5oirjPgpL+OpaENZrILYaXqYwnVH+qgUwVbl+pUJQ==",
"license": "BSD-3-Clause",
"engines": {
"node": ">= 18"
},
"funding": {
"url": "https://github.com/sponsors/cyyynthia"
}
},
"node_modules/source-map-js": {
@@ -1805,7 +1721,7 @@
"version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
"devOptional": true,
"dev": true,
"license": "MIT"
},
"node_modules/vite": {
@@ -1990,12 +1906,6 @@
"node": ">=8"
}
},
"node_modules/wrappy": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
"license": "ISC"
},
"node_modules/yaml": {
"version": "2.8.4",
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.4.tgz",
@@ -2012,13 +1922,15 @@
}
},
"node_modules/yauzl": {
"version": "2.10.0",
"resolved": "https://registry.npmjs.org/yauzl/-/yauzl-2.10.0.tgz",
"integrity": "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==",
"version": "3.4.0",
"resolved": "https://registry.npmjs.org/yauzl/-/yauzl-3.4.0.tgz",
"integrity": "sha512-jIH9yLR9wqr0wOS0TpBvo/g/2UgZH5qePVbjgRliiF0BYvOZyaBknKsF+x9Iht0O6sqgnB93rCICdOZFecJuDw==",
"license": "MIT",
"dependencies": {
"buffer-crc32": "~0.2.3",
"fd-slicer": "~1.1.0"
"pend": "~1.2.0"
},
"engines": {
"node": ">=12"
}
},
"node_modules/yocto-queue": {
+5 -3
View File
@@ -5,13 +5,15 @@
"main": "dist/index.js",
"scripts": {
"build": "tsc",
"start": "node dist/index.js"
"start": "node dist/index.js",
"test": "vitest run"
},
"dependencies": {
"@simplex-chat/types": "^0.7.0",
"@simplex-chat/types": "^7.1.0-beta.9.1",
"async-mutex": "^0.5.0",
"commander": "^14.0.3",
"simplex-chat": "^6.5.2",
"simplex-chat": "^7.1.0-beta.10.2",
"smol-toml": "^1.9.1",
"yaml": "^2.8.4"
},
"devDependencies": {
+19 -23
View File
@@ -3,11 +3,7 @@ import {T, CEvt} from "@simplex-chat/types"
import {Config} from "./config.js"
import {GrokMessage, GrokApiClient} from "./grok.js"
import {CardManager, ConversationState} from "./cards.js"
import {
queueMessage, grokInvitingMessage, grokActivatedMessage, teamAddedMessage,
teamAlreadyInvitedMessage, teamLockedMessage, noTeamMembersMessage,
grokUnavailableMessage, grokErrorMessage, grokNoHistoryMessage,
} from "./messages.js"
import {queueMessage, teamAddedMessage, noTeamMembersMessage} from "./messages.js"
import {profileMutex, log, logError, getGroupInfo} from "./util.js"
// Collects the keyword of every "command" entry in the bot's registered
@@ -156,7 +152,7 @@ export class SupportBot {
}
private async withGrokProfile<R>(fn: () => Promise<R>): Promise<R> {
if (this.grokUserId === null) throw new Error("Grok is disabled (no GROK_API_KEY)")
if (this.grokUserId === null) throw new Error("Grok is disabled (no Grok API key)")
const grokUserId = this.grokUserId
return profileMutex.runExclusive(async () => {
await this.chat.apiSetActiveUser(grokUserId)
@@ -496,7 +492,7 @@ export class SupportBot {
// First regular message → QUEUE
if (text) {
await this.cards.mergeCustomData(groupId, {state: "QUEUE"})
await this.sendToGroup(groupId, queueMessage(this.config.timezone, this.grokEnabled))
await this.sendToGroup(groupId, queueMessage(this.config.messages, this.config.timezone, this.grokEnabled))
await this.cards.createCard(groupId, groupInfo)
}
break
@@ -542,7 +538,7 @@ export class SupportBot {
case "TEAM":
if (cmd?.keyword === "grok") {
await this.sendToGroup(groupId, teamLockedMessage)
await this.sendToGroup(groupId, this.config.messages.teamLocked)
} else if (cmd?.keyword === "team") {
// Team still present → "already invited"; team all left → silent re-add
await this.activateTeam(groupId)
@@ -619,7 +615,7 @@ export class SupportBot {
logError(`Grok per-message error for grokGroup ${grokGroupId}`, err)
try {
await this.withGrokProfile(() =>
this.chat.apiSendTextMessage([T.ChatType.Group, grokGroupId], grokErrorMessage)
this.chat.apiSendTextMessage([T.ChatType.Group, grokGroupId], this.config.messages.grokError)
)
} catch {}
}
@@ -643,8 +639,8 @@ export class SupportBot {
}
if (this.config.grokContactId === null) {
await revertStateOnFail()
await this.sendToGroup(groupId, grokUnavailableMessage)
if (opts.sendQueueOnFail) await this.sendToGroup(groupId, queueMessage(this.config.timezone, this.grokEnabled))
await this.sendToGroup(groupId, this.config.messages.grokUnavailable)
if (opts.sendQueueOnFail) await this.sendToGroup(groupId, queueMessage(this.config.messages, this.config.timezone, this.grokEnabled))
this.cards.scheduleUpdate(groupId)
return
}
@@ -663,7 +659,7 @@ export class SupportBot {
// any later and onGrokNewChatItems can fire a duplicate per-message reply.
this.grokInitialResponsePending.add(groupId)
try {
await this.sendToGroup(groupId, grokInvitingMessage)
await this.sendToGroup(groupId, this.config.messages.grokInviting)
let member: T.GroupMember
try {
@@ -679,8 +675,8 @@ export class SupportBot {
}
logError(`Failed to invite Grok to group ${groupId}`, err)
await revertStateOnFail()
await this.sendToGroup(groupId, grokUnavailableMessage)
if (opts.sendQueueOnFail) await this.sendToGroup(groupId, queueMessage(this.config.timezone, this.grokEnabled))
await this.sendToGroup(groupId, this.config.messages.grokUnavailable)
if (opts.sendQueueOnFail) await this.sendToGroup(groupId, queueMessage(this.config.messages, this.config.timezone, this.grokEnabled))
this.cards.scheduleUpdate(groupId)
return
}
@@ -705,19 +701,19 @@ export class SupportBot {
} catch {}
this.cleanupGrokMaps(groupId)
await revertStateOnFail()
await this.sendToGroup(groupId, grokUnavailableMessage)
if (opts.sendQueueOnFail) await this.sendToGroup(groupId, queueMessage(this.config.timezone, this.grokEnabled))
await this.sendToGroup(groupId, this.config.messages.grokUnavailable)
if (opts.sendQueueOnFail) await this.sendToGroup(groupId, queueMessage(this.config.messages, this.config.timezone, this.grokEnabled))
this.cards.scheduleUpdate(groupId)
return
}
await this.sendToGroup(groupId, grokActivatedMessage)
await this.sendToGroup(groupId, this.config.messages.grokActivated)
// Grok joined — send initial response based on customer's accumulated messages
try {
const grokLocalGId = this.grokGroupMap.get(groupId)
if (grokLocalGId === undefined) {
await this.sendToGroup(groupId, grokUnavailableMessage)
await this.sendToGroup(groupId, this.config.messages.grokUnavailable)
return
}
@@ -739,7 +735,7 @@ export class SupportBot {
if (customerMessages.length === 0) {
await this.withGrokProfile(() =>
this.chat.apiSendTextMessage([T.ChatType.Group, grokLocalGId], grokNoHistoryMessage)
this.chat.apiSendTextMessage([T.ChatType.Group, grokLocalGId], this.config.messages.grokNoHistory)
)
return
}
@@ -755,7 +751,7 @@ export class SupportBot {
if (response.includes("/team")) await this.activateTeam(groupId)
} catch (err) {
logError(`Grok initial response failed for group ${groupId}`, err)
await this.sendToGroup(groupId, grokUnavailableMessage)
await this.sendToGroup(groupId, this.config.messages.grokUnavailable)
}
} finally {
this.grokInitialResponsePending.delete(groupId)
@@ -766,7 +762,7 @@ export class SupportBot {
private async activateTeam(groupId: number): Promise<void> {
if (this.config.teamMembers.length === 0) {
await this.sendToGroup(groupId, noTeamMembersMessage(this.grokEnabled))
await this.sendToGroup(groupId, noTeamMembersMessage(this.config.messages, this.grokEnabled))
return
}
@@ -775,7 +771,7 @@ export class SupportBot {
if (alreadyActivated) {
const {teamMembers} = await this.cards.getGroupComposition(groupId)
if (teamMembers.length > 0) {
await this.sendToGroup(groupId, teamAlreadyInvitedMessage)
await this.sendToGroup(groupId, this.config.messages.teamAlreadyInvited)
return
}
// Team previously activated but all team members have since left —
@@ -803,7 +799,7 @@ export class SupportBot {
}
const {grokMember} = await this.cards.getGroupComposition(groupId)
await this.sendToGroup(groupId, teamAddedMessage(this.config.timezone, !!grokMember))
await this.sendToGroup(groupId, teamAddedMessage(this.config.messages, this.config.timezone, !!grokMember))
}
// --- Team group commands ---
+134 -5
View File
@@ -1,5 +1,8 @@
import {readFileSync} from "fs"
import {Command, Option} from "commander"
import {parse as parseToml} from "smol-toml"
import {api} from "simplex-chat"
import {Messages, defaultMessages} from "./messages.js"
export interface IdName {
id: number
@@ -15,8 +18,13 @@ export interface Config {
timezone: string
completeHours: number
cardFlushSeconds: number
queueSize: number | undefined
contextFile: string | null
dryRun: boolean
allowMigrations: boolean
allowDownMigrations: boolean
grokApiKey: string | null
messages: Messages
}
export function parseIdName(s: string): IdName {
@@ -37,10 +45,21 @@ function parseNonNegativeInt(flag: string) {
}
}
function parsePositiveInt(flag: string) {
return (raw: string): number => {
const n = parseInt(raw, 10)
if (!Number.isFinite(n) || n < 1) {
throw new Error(`${flag} must be a positive integer, got "${raw}"`)
}
return n
}
}
function buildCommand(): Command {
return new Command()
.name("simplex-chat-support-bot")
.description("business-address triage bot")
.option("--config <path>", "TOML file with option values and message texts; command-line options take precedence")
.requiredOption("--team-group <name>", "team group display name")
.option("--state-file <path>", "state JSON path", "./data/state.json")
.addOption(new Option("--db <backend>", "database backend").choices(["sqlite", "postgres"]).default("sqlite"))
@@ -52,8 +71,12 @@ function buildCommand(): Command {
.option("--timezone <iana>", "IANA timezone for weekend detection", "UTC")
.option("--complete-hours <n>", "auto-complete chats after N hours idle (0 disables)", parseNonNegativeInt("--complete-hours"), 3)
.option("--card-flush-seconds <n>", "debounce card state writes", parseNonNegativeInt("--card-flush-seconds"), 300)
.option("--context-file <path>", "text file with Grok system context (required if GROK_API_KEY set)")
.addHelpText("after", "\nEnvironment:\n GROK_API_KEY xAI API key — enables Grok replies\n SIMPLEX_LIBS_DIR local libsimplex build for the --db backend\n SIMPLEX_ADDON_PATH locally built Node.js add-on\n")
.option("--queue-size <n>", "internal queue size of the chat core, as the CLI's --queue-size (core default: 1024)", parsePositiveInt("--queue-size"))
.option("--context-file <path>", "text file with Grok system context (required with a Grok API key)")
.option("--dry-run", "check config, database and state, then exit without starting chat")
.option("--allow-migrations", "with --dry-run: apply pending migrations instead of reporting them")
.option("--allow-down-migrations", "with --dry-run: roll back migrations that this build does not have")
.addHelpText("after", "\nEnvironment:\n GROK_API_KEY xAI API key — enables Grok replies, takes precedence over grok.api_key in --config\n SIMPLEX_LIBS_DIR local libsimplex build for the --db backend\n SIMPLEX_ADDON_PATH locally built Node.js add-on\n")
}
interface RawOpts {
@@ -68,13 +91,111 @@ interface RawOpts {
timezone: string
completeHours: number
cardFlushSeconds: number
queueSize?: number
contextFile?: string
dryRun?: boolean
allowMigrations?: boolean
allowDownMigrations?: boolean
}
interface ConfigFile {
args: string[]
messages: Messages
grokApiKey: string | null
}
function configFilePath(args: string[]): string | undefined {
const i = args.indexOf("--config")
if (i >= 0) return args[i + 1]
return args.find(arg => arg.startsWith("--config="))?.slice("--config=".length)
}
const configFlags = new Map(
Object.entries({
bot: {
team_group: "--team-group",
auto_add_team_members: "--auto-add-team-members",
state_file: "--state-file",
timezone: "--timezone",
complete_hours: "--complete-hours",
card_flush_seconds: "--card-flush-seconds",
queue_size: "--queue-size",
},
database: {
type: "--db",
pg_conn: "--pg-conn",
pg_schema: "--pg-schema",
sqlite_file_prefix: "--sqlite-file-prefix",
sqlite_key: "--sqlite-key",
},
grok: {
context_file: "--context-file",
},
}).map(([section, flags]): [string, Map<string, string>] => [section, new Map(Object.entries(flags))])
)
function readConfigFile(path: string): ConfigFile {
const {messages = {}, grok = {}, ...sections} = parseToml(readFileSync(path, "utf-8"))
const {api_key, ...grokOptions} = configTable(path, "grok", grok)
return {
args: Object.entries({...sections, grok: grokOptions}).flatMap(([section, options]) => configSectionArgs(path, section, options)),
messages: configMessages(path, configTable(path, "messages", messages)),
grokApiKey: configGrokApiKey(path, api_key),
}
}
function configGrokApiKey(path: string, value: unknown): string | null {
if (value === undefined) return null
if (typeof value !== "string" || value === "") throw new Error(`${path}: grok.api_key must be a non-empty string`)
return value
}
function configTable(path: string, section: string, value: unknown): Record<string, unknown> {
if (typeof value !== "object" || value === null || Array.isArray(value)) {
throw new Error(`${path}: [${section}] must be a section`)
}
return value as Record<string, unknown>
}
function configSectionArgs(path: string, section: string, options: unknown): string[] {
const flags = configFlags.get(section)
if (!flags) {
throw new Error(`${path}: unknown section [${section}], known sections: ${[...configFlags.keys(), "messages"].join(", ")}`)
}
return Object.entries(configTable(path, section, options)).map(([key, value]) => {
const flag = flags.get(key)
if (!flag) throw new Error(`${path}: unknown key ${section}.${key}, known keys: ${[...flags.keys()].join(", ")}`)
return configOptionArg(path, `${section}.${key}`, flag, value)
})
}
function configOptionArg(path: string, name: string, flag: string, value: unknown): string {
if (typeof value === "string" || typeof value === "number") return `${flag}=${value}`
if (Array.isArray(value) && value.every(v => typeof v === "string")) return `${flag}=${value.join(",")}`
throw new Error(`${path}: ${name} must be a string, a number or a list of strings`)
}
const messageKeys = new Map(
(Object.keys(defaultMessages) as (keyof Messages)[]).map(field => [field.replace(/[A-Z]/g, c => `_${c.toLowerCase()}`), field])
)
function configMessages(path: string, table: Record<string, unknown>): Messages {
const messages = {...defaultMessages}
for (const [key, value] of Object.entries(table)) {
const field = messageKeys.get(key)
if (!field) throw new Error(`${path}: unknown message ${key}, known messages: ${[...messageKeys.keys()].join(", ")}`)
if (typeof value !== "string") throw new Error(`${path}: message ${key} must be a string`)
messages[field] = value
}
return messages
}
export function parseConfig(args: string[]): Config {
const cmd = buildCommand().exitOverride()
const configFile = configFilePath(args)
const file: ConfigFile = configFile ? readConfigFile(configFile) : {args: [], messages: defaultMessages, grokApiKey: null}
try {
cmd.parse(args, {from: "user"})
cmd.parse([...file.args, ...args], {from: "user"})
} catch (err) {
const code = (err as {code?: string}).code
if (code === "commander.helpDisplayed" || code === "commander.version") process.exit(0)
@@ -83,7 +204,7 @@ export function parseConfig(args: string[]): Config {
const opts = cmd.opts<RawOpts>()
const given = (option: keyof RawOpts) => cmd.getOptionValueSource(option) === "cli"
const grokApiKey = process.env.GROK_API_KEY || null
const grokApiKey = process.env.GROK_API_KEY || file.grokApiKey
let db: api.DbConfig
if (opts.db === "sqlite") {
@@ -99,6 +220,9 @@ export function parseConfig(args: string[]): Config {
: {type: "postgres", connectionString: opts.pgConn}
}
if (opts.allowMigrations && !opts.dryRun) throw new Error("--allow-migrations requires --dry-run")
if (opts.allowDownMigrations && !opts.dryRun) throw new Error("--allow-down-migrations requires --dry-run")
const teamGroup: IdName = {id: 0, name: opts.teamGroup}
const teamMembersRaw = opts.autoAddTeamMembers ?? ""
@@ -114,7 +238,7 @@ export function parseConfig(args: string[]): Config {
const contextFile = opts.contextFile ?? null
if (grokApiKey && !contextFile) {
throw new Error("GROK_API_KEY is set but --context-file is not provided. Grok requires a context file.")
throw new Error("A Grok API key is set but --context-file is not provided. Grok requires a context file.")
}
return {
@@ -126,7 +250,12 @@ export function parseConfig(args: string[]): Config {
timezone: opts.timezone,
completeHours: opts.completeHours,
cardFlushSeconds: opts.cardFlushSeconds,
queueSize: opts.queueSize,
contextFile,
dryRun: opts.dryRun ?? false,
allowMigrations: opts.allowMigrations ?? false,
allowDownMigrations: opts.allowDownMigrations ?? false,
grokApiKey,
messages: file.messages,
}
}
+151
View File
@@ -0,0 +1,151 @@
import {api, core} from "simplex-chat"
import {T} from "@simplex-chat/types"
import {Config, IdName} from "./config.js"
import {loadGrokContext} from "./context.js"
export interface DryRunState {
teamGroupId?: number
grokContactId?: number
grokUserId?: number
}
export type DbProbe =
| {type: "current"}
| {type: "upgrade"; names: string[]}
| {type: "downgrade"; names: string[]}
| {type: "failed"; text: string}
export type MigrationPlan =
| {ok: true; confirm: core.MigrationConfirmation; result: string}
| {ok: false; reason: string}
export function migrationPlan(probe: DbProbe, config: Pick<Config, "allowMigrations" | "allowDownMigrations">): MigrationPlan {
switch (probe.type) {
case "current":
return {ok: true, confirm: core.MigrationConfirmation.Error, result: "schema up to date"}
case "upgrade": {
const list = `${probe.names.length} migration(s): ${probe.names.join(", ")}`
return config.allowMigrations
? {ok: true, confirm: core.MigrationConfirmation.YesUp, result: `applied ${list}`}
: {ok: false, reason: `pending ${list}; a real start would apply them, --allow-migrations applies them now`}
}
case "downgrade": {
const list = `${probe.names.length} migration(s): ${probe.names.join(", ")}`
return config.allowDownMigrations
? {ok: true, confirm: core.MigrationConfirmation.YesUpDown, result: `rolled back ${list}`}
: {ok: false, reason: `database is newer than this build, to roll back ${list}; a real start would refuse, --allow-down-migrations rolls them back`}
}
case "failed":
return {ok: false, reason: probe.text}
}
}
const SEARCH_LIMIT = 100
const LISTING_LIMIT = 1000
const GROK_PROFILE_NAME = "Grok"
type Check = (ok: boolean, msg: string) => void
type Unverified = (msg: string) => void
export async function dryRun(chat: api.ChatApi, config: Config, state: DryRunState): Promise<boolean> {
const results: boolean[] = []
const check: Check = (ok, msg) => {
results.push(ok)
console.log(`${ok ? "ok " : "FAIL"} ${msg}`)
}
const unverified: Unverified = msg => console.log(`? ${msg}`)
if (config.contextFile) {
try {
const context = loadGrokContext(config.contextFile)
check(true, `Grok context: ${context.length} message(s) from ${config.contextFile}`)
} catch (err) {
const e = err as NodeJS.ErrnoException
const missing = e.code === "ENOENT"
check(missing, `Grok context ${config.contextFile}: ${missing ? "not found, would start without it" : e.message}`)
}
}
const user = await chat.apiGetActiveUser()
if (!user) {
check(false, "no active user in database, the bot would create one")
return false
}
check(true, `active user: ${user.userId}:${user.profile.displayName}`)
if (state.grokUserId !== undefined) {
const users = await chat.apiListUsers()
const found = users.find(u => u.user.userId === state.grokUserId)
check(!!found, `Grok user ${state.grokUserId}: ${found ? found.user.profile.displayName : "missing, the bot would exit"}`)
}
if (state.teamGroupId === undefined) {
check(true, `no team group in state, "${config.teamGroup.name}" would be created`)
} else {
const group = await findGroup(chat, user.userId, config.teamGroup.name, state.teamGroupId)
if (!group) {
unverified(`team group ${state.teamGroupId} not in chat previews, the bot verifies it at startup`)
} else {
check(true, `team group ${state.teamGroupId}: ${group.groupProfile.displayName}`)
if (group.groupProfile.displayName !== config.teamGroup.name) {
check(true, `team group name differs from --team-group, profile would be updated to "${config.teamGroup.name}"`)
}
}
}
if (state.grokContactId !== undefined) {
const contact = await findContact(chat, user.userId, GROK_PROFILE_NAME, state.grokContactId)
if (contact) check(true, `Grok contact ${state.grokContactId}: ${contact.profile.displayName}`)
else unverified(`Grok contact ${state.grokContactId} not in chat previews, the bot verifies it at startup`)
}
await checkTeamMembers(chat, user.userId, config.teamMembers, check, unverified)
return results.every(Boolean)
}
async function checkTeamMembers(
chat: api.ChatApi,
userId: number,
members: IdName[],
check: Check,
unverified: Unverified
): Promise<void> {
for (const {id, name} of members) {
const contact = await findContact(chat, userId, name, id)
if (!contact) {
unverified(`team member ${id}:${name} not in chat previews, the bot verifies it at startup`)
} else {
const match = contact.profile.displayName === name
check(match, `team member ${id}:${name}${match ? "" : ` has display name "${contact.profile.displayName}", the bot would exit`}`)
}
}
}
async function findGroup(chat: api.ChatApi, userId: number, search: string, groupId: number): Promise<T.GroupInfo | undefined> {
const group = (chats: T.AChat[]): T.GroupInfo | undefined => {
for (const {chatInfo} of chats) {
if (chatInfo.type === "group" && chatInfo.groupInfo.groupId === groupId) return chatInfo.groupInfo
}
return undefined
}
return group(await searchChats(chat, userId, search)) ?? group(await recentChats(chat, userId))
}
async function findContact(chat: api.ChatApi, userId: number, search: string, contactId: number): Promise<T.Contact | undefined> {
const contact = (chats: T.AChat[]): T.Contact | undefined => {
for (const {chatInfo} of chats) {
if (chatInfo.type === "direct" && chatInfo.contact.contactId === contactId) return chatInfo.contact
}
return undefined
}
return contact(await searchChats(chat, userId, search)) ?? contact(await recentChats(chat, userId))
}
function searchChats(chat: api.ChatApi, userId: number, search: string): Promise<T.AChat[]> {
return chat.apiGetChats(userId, {type: "last", count: SEARCH_LIMIT}, {type: "search", search})
}
function recentChats(chat: api.ChatApi, userId: number): Promise<T.AChat[]> {
return chat.apiGetChats(userId, {type: "last", count: LISTING_LIMIT})
}
+64 -6
View File
@@ -1,11 +1,11 @@
import {readFileSync, writeFileSync, existsSync} from "fs"
import {api, bot, util} from "simplex-chat"
import {api, bot, core, util} from "simplex-chat"
import {T} from "@simplex-chat/types"
import {parseConfig} from "./config.js"
import {Config, parseConfig} from "./config.js"
import {SupportBot} from "./bot.js"
import {DbProbe, dryRun, migrationPlan} from "./dryRun.js"
import {GrokApiClient, GrokMessage} from "./grok.js"
import {loadGrokContext} from "./context.js"
import {welcomeMessage} from "./messages.js"
import {profileMutex, log, logError, getGroupInfo, getContact} from "./util.js"
interface BotState {
@@ -35,11 +35,15 @@ async function main(): Promise<void> {
completeHours: config.completeHours,
})
const grokEnabled = config.grokApiKey !== null
if (!grokEnabled) log("No GROK_API_KEY provided, disabling Grok support")
if (!grokEnabled) log("No Grok API key in GROK_API_KEY or grok.api_key, disabling Grok support")
const stateFilePath = config.stateFile
const state = readState(stateFilePath)
if (config.dryRun) {
process.exit((await runDryRun(config, state)) ? 0 : 1)
}
// Forward-reference for event handlers during init
let supportBot: SupportBot | undefined
@@ -91,12 +95,12 @@ async function main(): Promise<void> {
log("Initializing main bot...")
const [chat, mainUser, mainAddress] = await bot.run({
profile: {displayName: "Ask SimpleX Team", fullName: "", image: supportImage},
dbOpts: config.db,
dbOpts: {...config.db, queueSize: config.queueSize},
options: {
addressSettings: {
businessAddress: true,
autoAccept: true,
welcomeMessage,
welcomeMessage: config.messages.welcome,
},
commands: desiredCommands,
useBotProfile: true,
@@ -370,6 +374,60 @@ async function main(): Promise<void> {
process.on("SIGTERM", () => shutdown("SIGTERM"))
}
async function runDryRun(config: Config, state: BotState): Promise<boolean> {
const plan = migrationPlan(await probeDatabase(config.db), config)
if (!plan.ok) {
console.log(`FAIL database: ${plan.reason}`)
return false
}
let chat: api.ChatApi
try {
chat = await api.ChatApi.init(config.db, plan.confirm)
} catch (err) {
console.log(`FAIL database: ${migrationErrorText(err)}`)
return false
}
console.log(`ok database ${config.db.type} opened, ${plan.result}`)
try {
return await dryRun(chat, config, state)
} finally {
await chat.close()
}
}
async function probeDatabase(db: api.DbConfig): Promise<DbProbe> {
try {
const chat = await api.ChatApi.init(db, core.MigrationConfirmation.Error)
await chat.close()
return {type: "current"}
} catch (err) {
const dbErr = (err as core.ChatInitError).dbMigrationError
if (dbErr?.type === "errorMigration") {
const me = dbErr.migrationError
if (me.type === "upgrade") return {type: "upgrade", names: me.upMigrations.map(m => m.upName)}
if (me.type === "downgrade") return {type: "downgrade", names: me.downMigrations}
}
return {type: "failed", text: migrationErrorText(err)}
}
}
function migrationErrorText(err: unknown): string {
const e = err as core.ChatInitError
const dbErr = e.dbMigrationError
if (dbErr?.type === "errorMigration") {
const me = dbErr.migrationError
switch (me.type) {
case "upgrade":
return `${me.upMigrations.length} migration(s) pending: ${me.upMigrations.map(m => m.upName).join(", ")}`
case "downgrade":
return `database is newer than this build, it would refuse to start; migrations to roll back: ${me.downMigrations.join(", ")}`
default:
return `migration state error: ${JSON.stringify(me)}`
}
}
return e.message
}
main().catch(err => {
logError("Fatal error", err)
process.exit(1)
+46 -33
View File
@@ -1,46 +1,59 @@
import {isWeekend} from "./util.js"
export const welcomeMessage = `Hello! This is a **SimpleX team** support bot - not an AI.
export interface Messages {
welcome: string
queue: string
queueGrok: string
grokActivated: string
teamAdded: string
teamAddedGrok: string
teamAlreadyInvited: string
teamLocked: string
noTeamMembers: string
noTeamMembersGrok: string
grokInviting: string
grokUnavailable: string
grokError: string
grokNoHistory: string
}
export const defaultMessages: Messages = {
welcome: `Hello! This is a **SimpleX team** support bot - not an AI.
Discover public groups: [simplex.chat/directory](https://simplex.chat/directory)
Join the livestream about SimpleX roadmap and equity crowdfunding: [simplex.chat/livestream](https://simplex.chat/livestream) (September 15, at 17:00 UTC)`
Join the livestream about SimpleX roadmap and equity crowdfunding: [simplex.chat/livestream](https://simplex.chat/livestream) (September 15, at 17:00 UTC)`,
queue: "The team will reply to your message within {hours} hours.",
queueGrok: `If your question is about SimpleX, click /grok for an **instant Grok answer**.
export function queueMessage(timezone: string, grokEnabled: boolean): string {
const hours = isWeekend(timezone) ? "48" : "24"
const base = `The team will reply to your message within ${hours} hours.`
if (!grokEnabled) return base
return `${base}
If your question is about SimpleX, click /grok for an **instant Grok answer**.
Send /team to switch back.`
Send /team to switch back.`,
grokActivated: "**You are now chatting with Grok** - use any language.",
teamAdded: "We will reply within {hours} hours.",
teamAddedGrok: "Grok will be answering your questions until then.",
teamAlreadyInvited: "A team member was invited to this conversation and will reply when available.",
teamLocked: "Only the team will now receive your messages.",
noTeamMembers: "No team members are available yet. Please try again later.",
noTeamMembersGrok: "No team members are available yet. Please try again later or click /grok.",
grokInviting: "Inviting Grok, please wait...",
grokUnavailable: "Grok is temporarily unavailable. Please try again later or send /team for a human team member.",
grokError: "Sorry, I couldn't process that. Please try again or send /team for a human team member.",
grokNoHistory: "I just joined but couldn't see your earlier messages. Could you repeat your question?",
}
export const grokActivatedMessage = `**You are now chatting with Grok** - use any language.`
export function teamAddedMessage(timezone: string, grokPresent: boolean): string {
const hours = isWeekend(timezone) ? "48" : "24"
const base = `We will reply within ${hours} hours.`
if (!grokPresent) return base
return `${base}
Grok will be answering your questions until then.`
function withReplyHours(text: string, timezone: string): string {
return text.replaceAll("{hours}", isWeekend(timezone) ? "48" : "24")
}
export const teamAlreadyInvitedMessage = "A team member was invited to this conversation and will reply when available."
export const teamLockedMessage = "Only the team will now receive your messages."
export function noTeamMembersMessage(grokEnabled: boolean): string {
return grokEnabled
? "No team members are available yet. Please try again later or click /grok."
: "No team members are available yet. Please try again later."
export function queueMessage(messages: Messages, timezone: string, grokEnabled: boolean): string {
const base = withReplyHours(messages.queue, timezone)
return grokEnabled ? `${base}\n\n${messages.queueGrok}` : base
}
export const grokInvitingMessage = "Inviting Grok, please wait..."
export function teamAddedMessage(messages: Messages, timezone: string, grokPresent: boolean): string {
const base = withReplyHours(messages.teamAdded, timezone)
return grokPresent ? `${base}\n${messages.teamAddedGrok}` : base
}
export const grokUnavailableMessage = "Grok is temporarily unavailable. Please try again later or send /team for a human team member."
export const grokErrorMessage = "Sorry, I couldn't process that. Please try again or send /team for a human team member."
export const grokNoHistoryMessage = "I just joined but couldn't see your earlier messages. Could you repeat your question?"
export function noTeamMembersMessage(messages: Messages, grokEnabled: boolean): string {
return grokEnabled ? messages.noTeamMembersGrok : messages.noTeamMembers
}
@@ -31,6 +31,6 @@ class ChatAPIError extends Error {
module.exports = {
api: {ChatApi: {}},
bot: {},
core: {ChatAPIError},
core: {ChatAPIError, MigrationConfirmation: {YesUp: "yesUp", YesUpDown: "yesUpDown", Console: "console", Error: "error"}},
util: {ciContentText, ciBotCommand, contactAddressStr},
}
+2 -2
View File
@@ -4,8 +4,8 @@
"declaration": true,
"forceConsistentCasingInFileNames": true,
"lib": ["ES2022"],
"module": "Node16",
"moduleResolution": "Node16",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"noFallthroughCasesInSwitch": true,
"noImplicitAny": true,
"noImplicitReturns": true,
+25
View File
@@ -0,0 +1,25 @@
# SimpleX Names Conditions of Use
You accept these Conditions of Use of SimpleX Names ("Names Conditions") by registering, receiving or extending a name in the .simplex namespace.
**SimpleX names**. A name is a record controlled by your key. The record can contain links to addresses in the SimpleX Network. "Community names" are marked in the registry as referring to specific communities, usually cities or territories.
**Registry**. The .simplex names registry is a set of contracts on the Ethereum blockchain. Name registrations, records, subnames and controlling addresses are stored in immutable contracts. Other contracts may be updated during a stabilization period, expected to last 12 to 24 months from the first registration.
**What the registry allows**.
- Changing the record of the name, creating subnames and transferring control of the name require your key.
- A name is registered for the period stored in the registry and can be extended until 90 days after that period ends, at the price set at the time of extension. Once the period ends, control of the name cannot be transferred.
**You agree**:
- not to use a name you control for fraud, to impersonate people or organizations, to store links to illegal content, or to knowingly infringe the rights of others, including trademarks;
- to use a community name you control to benefit that community, not as the brand of one person or business.
You are responsible for the names you control, their records and subnames. A name gives you no rights to the word itself, or to any word marks or other intellectual property.
**Your key**. Keep your key safe. If you lose your key, nobody can recover the key or control of the name, and nobody can reverse a transfer made with the key.
**Public information**. Everything in the registry is public with its history, including controlling addresses and acceptances of these Names Conditions.
**Changes to the conditions**. New versions of these Names Conditions are recorded in the registry. Each version applies to registrations, transfers and extensions made after it is recorded. A version that does not reduce your rights applies at once.
@@ -4,7 +4,7 @@ This TypeScript library provides auto-generated types for bots API: commands and
It is used in [simplex-chat](https://www.npmjs.com/package/simplex-chat) Node.js library.
SimpleX Chat core: 7.1.0.18
SimpleX Chat core: 7.1.3.0
[API reference](https://github.com/simplex-chat/simplex-chat/tree/stable/bots).
@@ -1,7 +1,7 @@
{
"name": "@simplex-chat/types",
"version": "7.1.0-beta.9.1",
"simplexChatCore": "7.1.0.18",
"version": "7.1.3",
"simplexChatCore": "7.1.3.0",
"description": "TypeScript types for SimpleX Chat bot libraries",
"main": "dist/index.js",
"types": "dist/index.d.ts",
+7 -1
View File
@@ -146,6 +146,13 @@ The reduced build runs one Linux job, build-linux (ubuntu-22.04 x86_64), for eve
- before a publication: the package with its published dependencies, type-checked and unit tested in job `publish` of build.yml (docs/contributing/RELEASES.md, "MCP server release").
- Local: `scripts/ci/scope-tests.sh mcp`.
#### support-bot
- Globs: apps/simplex-support-bot/**.
- CI, in build-linux: `scope-tests.sh support-bot` (step "Test changed scopes"): `npm ci`, `npm run build` and `npm test`, with the published `simplex-chat` and `@simplex-chat/types` of package-lock.json.
- The Docker image (scripts/support-bot/Dockerfile) is not built in CI.
- Local: `scripts/ci/scope-tests.sh support-bot`.
#### Scopes lacking CI tests
| Scope | Paths | CI |
@@ -155,7 +162,6 @@ The reduced build runs one Linux job, build-linux (ubuntu-22.04 x86_64), for eve
| ts-client | packages/simplex-chat-client/typescript/** | - |
| webrtc | packages/simplex-chat-webrtc/** | - |
| calculator-bot | apps/simplex-calculator-bot/** | - |
| support-bot | apps/simplex-support-bot/** | - |
| support-bot-light | apps/simplex-support-bot-light/** | - |
| prices | scripts/prices/** | - |
| nft | eth/nft/** | - |
+1
View File
@@ -90,6 +90,7 @@ SCOPE_CHANGES = {
"packages/simplex-chat-nodejs/**",
"packages/simplex-chat-client/types/typescript/**",
],
"support-bot": ["apps/simplex-support-bot/**"],
}
CABAL_FILE = "simplex-chat.cabal"
CABAL_VERSION = re.compile(r"^(version:\s*)(\S+)", re.M)
+4 -1
View File
@@ -25,8 +25,11 @@ case "${1:-}" in
npm test
npm run test:e2e
;;
support-bot)
(cd apps/simplex-support-bot && npm ci --no-audit --no-fund && npm run build && npm test)
;;
*)
echo "usage: $0 badge-web | ci-scripts | website | mcp" >&2
echo "usage: $0 badge-web | ci-scripts | website | mcp | support-bot" >&2
exit 1
;;
esac
+4
View File
@@ -527,6 +527,10 @@ class ChangesTest(GitRepoTest):
self.assertEqual(self.builds("packages/simplex-chat-nodejs/src/api.ts"), {"packages"})
self.assertEqual(self.values["scopes"], "mcp")
def test_support_bot_change_tests_its_scope(self):
self.assertEqual(self.builds("apps/simplex-support-bot/src/bot.ts"), set())
self.assertEqual(self.values["scopes"], "support-bot")
class PackageStateTest(GitRepoTest):
def setUp(self):
+4
View File
@@ -0,0 +1,4 @@
data/
.env
config/*
!config/config.toml.example
+153
View File
@@ -0,0 +1,153 @@
# syntax=docker/dockerfile:1
# release: libsimplex, the add-on and the npm packages pinned by package-lock.json
# source: all of them built from this checkout
ARG LIBS=release
ARG BACKEND=postgres
# The runtime glibc must be the same or newer.
ARG UBUNTU_LIBS=22.04
ARG GHC=9.6.3
ARG CABAL=3.10.2.0
ARG NODE=24
# --------------------------------------------------------------------------- #
# libsimplex from source
# --------------------------------------------------------------------------- #
FROM ubuntu:${UBUNTU_LIBS} AS libsimplex-source
ARG GHC
ARG CABAL
ARG BACKEND
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y --no-install-recommends \
build-essential ca-certificates curl git libgmp3-dev libnuma-dev \
libpq-dev libsqlite3-dev libssl-dev llvm patchelf pkg-config zlib1g-dev && \
rm -rf /var/lib/apt/lists/*
ENV BOOTSTRAP_HASKELL_NONINTERACTIVE=1 \
BOOTSTRAP_HASKELL_GHC_VERSION=${GHC} \
BOOTSTRAP_HASKELL_CABAL_VERSION=${CABAL} \
BOOTSTRAP_HASKELL_INSTALL_NO_STACK=true \
BOOTSTRAP_HASKELL_INSTALL_NO_STACK_HOOK=true
RUN curl --proto '=https' --tlsv1.2 -sSf https://get-ghcup.haskell.org | sh
ENV PATH="/root/.ghcup/bin:/root/.cabal/bin:$PATH"
ENV CABAL_DIR=/root/.cabal
WORKDIR /src
COPY cabal.project simplex-chat.cabal README.md PRIVACY.md ./
COPY scripts/cabal.project.local.linux ./cabal.project.local
# The build script checks the export lists in these.
COPY libsimplex.dll.def flake.nix ./
COPY scripts/desktop ./scripts/desktop
COPY src ./src
# Other versions' build trees are removed: the script's simplex-chat-* glob
# fails with "cd: too many arguments" when the cache holds more than one.
RUN --mount=type=cache,target=/root/.cabal \
--mount=type=cache,target=/src/dist-newstyle \
set -eu; \
ver=$(sed -n 's/^version: *//p' simplex-chat.cabal | tr -d '[:space:]'); \
build_dir=dist-newstyle/build/$(uname -m)-linux/ghc-${GHC}/simplex-chat-$ver/build; \
find dist-newstyle/build -maxdepth 3 -type d -name 'simplex-chat-*' \
! -path "*/simplex-chat-$ver" -exec rm -rf {} + 2>/dev/null || true; \
cabal update; \
SKIP_VLC=1 scripts/desktop/build-lib-linux.sh "${BACKEND}"; \
mkdir -p /libs; \
cp "$build_dir"/libsimplex.so "$build_dir"/deps/* /libs/
# --------------------------------------------------------------------------- #
# libs-source: libsimplex, the add-on and the npm packages from this checkout
# --------------------------------------------------------------------------- #
FROM node:${NODE}-bookworm-slim AS libs-source
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y --no-install-recommends \
build-essential python3 && \
rm -rf /var/lib/apt/lists/*
COPY --from=libsimplex-source /libs /opt/simplex/libs
WORKDIR /src
COPY packages/simplex-chat-client/types/typescript packages/simplex-chat-client/types/typescript
RUN cd packages/simplex-chat-client/types/typescript && \
npm install --no-audit --no-fund && \
npx tsc && \
mkdir -p /opt/simplex/packages && \
npm pack --pack-destination /opt/simplex/packages
COPY packages/simplex-chat-nodejs packages/simplex-chat-nodejs
RUN cd packages/simplex-chat-nodejs && \
npm install --no-audit --no-fund && \
npm install --no-save --no-audit --no-fund /opt/simplex/packages/*.tgz && \
npx node-gyp rebuild && \
npx tsc && \
cp src/simplex.* dist/ && \
cp build/Release/simplex.node /opt/simplex/simplex.node && \
npm pack --pack-destination /opt/simplex/packages
# --------------------------------------------------------------------------- #
# libs-release: libsimplex and the add-on pinned by the published simplex-chat
# --------------------------------------------------------------------------- #
FROM node:${NODE}-bookworm-slim AS libs-release
ARG BACKEND
WORKDIR /src/apps/simplex-support-bot
COPY apps/simplex-support-bot/package.json apps/simplex-support-bot/package-lock.json ./
RUN npm ci --no-audit --no-fund && \
XDG_CACHE_HOME=/tmp/cache npx simplex-chat install --backend "${BACKEND}" && \
mkdir -p /opt/simplex/packages && \
cp -r "$(dirname "$(find /tmp/cache -name libsimplex.so)")" /opt/simplex/libs && \
cp "$(find /tmp/cache -name '*.node')" /opt/simplex/simplex.node
FROM libs-${LIBS} AS libs
# --------------------------------------------------------------------------- #
# build
# --------------------------------------------------------------------------- #
FROM node:${NODE}-bookworm-slim AS build
COPY --from=libs /opt/simplex /opt/simplex
WORKDIR /src/apps/simplex-support-bot
COPY apps/simplex-support-bot/package.json apps/simplex-support-bot/package-lock.json ./
RUN npm ci --no-audit --no-fund && \
find /opt/simplex/packages -name '*.tgz' -print0 | \
xargs -0 -r npm install --no-save --no-audit --no-fund
COPY apps/simplex-support-bot ./
RUN npm run build && npm test
# --------------------------------------------------------------------------- #
# runtime
# --------------------------------------------------------------------------- #
FROM node:${NODE}-bookworm-slim AS runtime
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates dumb-init libffi8 libgmp10 libnuma1 libpq5 libssl3 zlib1g && \
rm -rf /var/lib/apt/lists/*
# A named volume takes this ownership; a bind mount must be owned by uid 1000.
RUN mkdir -p /data && chown node:node /data && chmod 0700 /data
COPY --from=libs /opt/simplex/libs /opt/simplex/libs
COPY --from=libs /opt/simplex/simplex.node /opt/simplex/simplex.node
COPY --from=build --chown=node:node /src/apps/simplex-support-bot /src/apps/simplex-support-bot
# The library loads these instead of downloading libsimplex and the add-on at startup.
ENV SIMPLEX_LIBS_DIR=/opt/simplex/libs \
SIMPLEX_ADDON_PATH=/opt/simplex/simplex.node
USER node
WORKDIR /src/apps/simplex-support-bot
ENV NODE_ENV=production
# Single API responses grow with the number of chats.
ENV NODE_OPTIONS=--max-old-space-size=8192
# node as PID 1 ignores SIGTERM, and the bot deletes the team group invite link on SIGTERM.
ENTRYPOINT ["dumb-init", "--", "node", "dist/index.js"]
CMD ["--config", "/etc/support-bot/config.toml"]
@@ -0,0 +1,22 @@
*
!cabal.project
!simplex-chat.cabal
!README.md
!PRIVACY.md
!libsimplex.dll.def
!flake.nix
!src
!scripts/cabal.project.local.linux
!scripts/desktop
!packages/simplex-chat-client
!packages/simplex-chat-nodejs
!apps/simplex-support-bot
**/node_modules
**/dist
**/build
**/libs
**/data
**/.env
**/.npmrc
+25
View File
@@ -0,0 +1,25 @@
# network_mode: host makes 127.0.0.1 reach PostgreSQL on the host.
#
# cp config/config.toml.example config/config.toml
# docker compose up --build
# LIBS=source docker compose build
services:
support-bot:
image: simplex-support-bot:latest
build:
context: ../..
dockerfile: scripts/support-bot/Dockerfile
args:
LIBS: ${LIBS:-release}
network_mode: host
restart: on-failure:5
environment:
GROK_API_KEY: ${GROK_API_KEY:-}
volumes:
- support-bot-data:/data
- ./config:/etc/support-bot:ro
stop_grace_period: 30s
volumes:
support-bot-data:
@@ -0,0 +1,31 @@
# Copy to config.toml. Each key sets the command-line option named next to it;
# an option given on the command line takes precedence.
[bot]
team_group = "SimpleX Support Team" # --team-group
auto_add_team_members = ["1:Alice"] # --auto-add-team-members
state_file = "/data/state.json" # --state-file
timezone = "UTC" # --timezone
# complete_hours = 3 # --complete-hours
# card_flush_seconds = 300 # --card-flush-seconds
# queue_size = 65536 # --queue-size, core default 1024
[database]
type = "postgres" # --db
pg_conn = "postgres://simplex@127.0.0.1/simplex_support_bot" # --pg-conn
# pg_schema = "simplex_v1" # --pg-schema
[grok]
context_file = "/etc/support-bot/grok-context.yaml" # --context-file
# Enables Grok replies; GROK_API_KEY takes precedence.
# api_key = "xai-..."
# A message left out keeps its built-in text.
# {hours} is 24 on weekdays and 48 at weekends in bot.timezone.
[messages]
welcome = """
Hello! This is a *SimpleX team* support bot - not an AI.
Discover public groups: [simplex.chat/directory](https://simplex.chat/directory)
Please ask any questions about SimpleX Chat."""
queue = "The team will reply to your message within {hours} hours."
+1 -1
View File
@@ -5,7 +5,7 @@ cabal-version: 1.12
-- see: https://github.com/sol/hpack
name: simplex-chat
version: 7.1.2.0
version: 7.1.3.0
category: Web, System, Services, Cryptography
homepage: https://github.com/simplex-chat/simplex-chat#readme
author: simplex.chat