Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
63512b75ce | ||
|
|
0fd348f158 | ||
|
|
aef7169173 | ||
|
|
712145582e | ||
|
|
1b26c5b42f | ||
|
|
3e13d02341 | ||
|
|
a5dbde1da7 | ||
|
|
51747c069f | ||
|
|
3f551e7352 | ||
|
|
fdd1e8a757 | ||
|
|
60022d8220 | ||
|
|
4837bf325e |
@@ -5,69 +5,104 @@
|
||||
<img src="docs/readme/lockup-dark.svg#gh-dark-mode-only" alt="Cobble" height="56">
|
||||
</h1>
|
||||
|
||||
A crew of small AI worker bots you host yourself (alpha).
|
||||
### A crew of small AI worker bots you host yourself
|
||||
|
||||

|
||||

|
||||
Not a chat box with a system prompt. A coordinator, a team of workers, and real
|
||||
Docker computers with a browser and a shell that they actually operate.
|
||||
|
||||
[](https://github.com/Moduletrace/cobble/actions/workflows/ci.yml)
|
||||
[](https://github.com/Moduletrace/cobble/stargazers)
|
||||
[](LICENSE)
|
||||
[](https://cobble.moduletrace.org)
|
||||
[](https://bun.sh)
|
||||
[](https://bun.sh)
|
||||
|
||||
```bash
|
||||
curl -fsSL https://url.moduletrace.com/cobble | sudo bash
|
||||
```
|
||||
|
||||
One command. One SQLite file. Your machine. No account, no per-seat pricing.
|
||||
|
||||
<br>
|
||||
|
||||
<!-- Demo GIF: shot list in docs/readme/DEMO.md. -->
|
||||
|
||||
<!--  -->
|
||||
|
||||

|
||||

|
||||
|
||||
[Website](https://cobble.moduletrace.org) · [Install](#install) · [Features](#features) · [Development](#development) · [Architecture](AGENTS.md)
|
||||
|
||||
</div>
|
||||
|
||||
> **Alpha.** Cobble is still in alpha: interfaces, database schema and
|
||||
> settings change between releases, and things break. Install it to try it
|
||||
> out and to tell us what is wrong, but keep your own backups (Settings >
|
||||
> Backups) and do not put it in front of work you cannot lose. Every release
|
||||
> is a real release: the installer updates an existing install in place and
|
||||
> keeps its data.
|
||||
---
|
||||
|
||||
Cobble is a self-hosted crew of small AI worker bots. You get a coordinator
|
||||
and a set of workers, each with its own job, models, memory and workspace.
|
||||
They talk to you in one chat, share workspaces, run routines on a schedule,
|
||||
and drive their own computers: lean Docker sandboxes with a real Chrome and
|
||||
a shell, which a bot can use and hand back to you when it needs help.
|
||||
> **Alpha.** Cobble is still in alpha. Interfaces, database schema and settings
|
||||
> change between releases, and things break. Install it to try it out and to
|
||||
> tell us what is wrong, but keep your own backups (Settings > Backups) and do
|
||||
> not put it in front of work you cannot lose. Every release is a real release:
|
||||
> the installer updates an existing install in place and keeps its data.
|
||||
|
||||
It is an install, not a SaaS. One SQLite database, one Docker container, and
|
||||
your data on your own machine.
|
||||
## The problem with one big assistant
|
||||
|
||||
**Why small workers instead of one big assistant**
|
||||
You give an agent a task. It works for forty turns. Somewhere in the middle it
|
||||
loses the thread, forgets what it already tried, or quietly stops and says it is
|
||||
done. You cannot see what it is doing, you cannot stop it cleanly, and the whole
|
||||
thing lives in someone else's cloud with your files in it.
|
||||
|
||||
- **A crew, not a chat.** Each worker has one job and only loads the context
|
||||
for it. A five-bot crew does five things in parallel, and each one stays
|
||||
cheap and focused.
|
||||
Cobble splits that agent into a crew and gives the crew a machine:
|
||||
|
||||
- **A crew, not a chat.** Each worker has one job and only loads the context for
|
||||
it. A five-bot crew does five things in parallel, and each one stays cheap
|
||||
and focused. The coordinator plans and delegates; the workers do the work.
|
||||
- **Bots you can see through.** The face on each stone is the status: idle,
|
||||
working, done, asleep, needs you. You read the whole crew at a glance
|
||||
instead of asking each one what it is doing.
|
||||
- **Real computers.** Workers run on your own sandboxed machines, with
|
||||
browser, terminal, files and desktop, not just a tool loop.
|
||||
working, done, asleep, needs you. You read the whole crew at a glance instead
|
||||
of asking each one what it is doing.
|
||||
- **Real computers.** Workers run on your own sandboxed Docker machines, with a
|
||||
real headful Chrome on a virtual screen, a shell, files and a desktop. Not
|
||||
just a tool loop that can call `curl`.
|
||||
- **A human in the loop that works.** When a bot hits a login wall or a captcha,
|
||||
it hands the live browser back to you mid-task. You act, you hand it back, and
|
||||
it continues from the same browser and the same files. No restart, no lost
|
||||
state.
|
||||
- **Yours.** Self-hosted, MIT, one SQLite file to back up, no account and no
|
||||
per-seat billing.
|
||||
per-seat billing. Your keys stay on your machine.
|
||||
|
||||
## Where Cobble fits
|
||||
|
||||
| | One big chat assistant | A hosted agent platform | Cobble |
|
||||
|---|---|---|---|
|
||||
| Runs on your hardware | No | No | Yes, one container plus one per computer |
|
||||
| Parallel work | Manually, one thread | Often | Yes, one worker per job |
|
||||
| Real browser and shell | No | Sometimes, headless | Yes, headful Chrome plus a shell, visible live |
|
||||
| Human takes over mid-task | Copy and paste | Rarely | Yes, live, same session |
|
||||
| Your data leaves the box | Yes | Yes | Only where you point it: your provider, the tools you give a bot |
|
||||
| Cost model | Per seat | Per seat plus usage | Your hardware, your API keys |
|
||||
| Licence | Proprietary | Proprietary | MIT |
|
||||
|
||||
If you want a single assistant that writes emails, a chat app is cheaper. If you
|
||||
want a team that ships work on machines you control, that is this.
|
||||
|
||||
## Features
|
||||
|
||||
| Area | What you get |
|
||||
| ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Crew | One coordinator and as many workers as you need, each with a name, a role, a hue and its own core instructions |
|
||||
| Rail | The coordinator, your recent workers and their latest sessions, then your workspaces, each row carrying its status line |
|
||||
| Chat | Markdown with @-mentions for bots and #-mentions for workspaces, replies and quotes, reactions, attachments, older messages on scroll, drafts kept locally |
|
||||
| Stop | Stop a bot from the thinking row or the header menu: its queued and running work stops at once, everywhere you chat with it, and it goes idle |
|
||||
| Header | The bot's model, provider and computer at a glance, one click from either, and its picture, instructions and settings on the avatar |
|
||||
| Workspaces | A shared home for a group of bots: shared context, per-workspace instructions and memory, a default computer, and a dashboard |
|
||||
| Memory | Each bot keeps core memory, memory about you, and workspace memory, and rewrites it as it works |
|
||||
| Routines | Cron schedules per bot, written in chat, that queue a task on its own |
|
||||
| Computers | Docker sandboxes with a real headful Chrome and a shell, shown live in the chat and handed back to you mid-task |
|
||||
| Files | Bots keep files on your data volume, search them by meaning, and attach the ones they make to a reply |
|
||||
| Models | OpenRouter, OpenAI, Anthropic, Gemini, DeepSeek, Groq, Mistral, xAI, Ollama or any OpenAI-compatible server, per bot and per harness |
|
||||
| Voice | Dictate into the composer, play any bot reply, with speech-to-text and text-to-speech models of your choice |
|
||||
| Tools | Install your own MCP servers and custom HTTP, script or prompt tools, and give them to bots or workspaces |
|
||||
| Skills | Write runbooks your bots follow. Each bot sees what a skill is for and reads the whole thing only when it needs it |
|
||||
| Knowledge | Knowledgebases of documents and notes, given to bots or workspaces: every reply starts from the passages that fit, searched by one embedding model |
|
||||
| App | Installable PWA with Web Push, dark mode, and a rail built for a phone |
|
||||
| Area | What you get |
|
||||
| --- | --- |
|
||||
| Crew | One coordinator and as many workers as you need, each with a name, a role, a hue and its own core instructions |
|
||||
| Rail | The coordinator, your recent workers and their latest sessions, then your workspaces, each row carrying its status line |
|
||||
| Chat | Markdown with @-mentions for bots and #-mentions for workspaces, replies and quotes, reactions, attachments, older messages on scroll, drafts kept locally |
|
||||
| Stop | Stop a bot from the thinking row or the header menu: its queued and running work stops at once, everywhere you chat with it, and it goes idle |
|
||||
| Header | The bot's model, provider and computer at a glance, one click from either, and its picture, instructions and settings on the avatar |
|
||||
| Workspaces | A shared home for a group of bots: shared context, per-workspace instructions and memory, a default computer, and a dashboard |
|
||||
| Memory | Each bot keeps core memory, memory about you, and workspace memory, and rewrites it as it works |
|
||||
| Routines | Cron schedules per bot, written in chat, that queue a task on its own |
|
||||
| Computers | Docker sandboxes with a real headful Chrome and a shell, shown live in the chat and handed back to you mid-task |
|
||||
| Files | Bots keep files on your data volume, find them by name or path, and attach the ones they make to a reply |
|
||||
| Models | OpenRouter, OpenAI, Anthropic, Gemini, DeepSeek, Groq, Mistral, xAI, Ollama or any OpenAI-compatible server, per bot and per harness |
|
||||
| Voice | Dictate into the composer, play any bot reply, with speech-to-text and text-to-speech models of your choice |
|
||||
| Tools | Install your own MCP servers and custom HTTP, script or prompt tools, and give them to bots or workspaces |
|
||||
| Skills | Write runbooks your bots follow. Each bot sees what a skill is for and reads the whole thing only when it needs it |
|
||||
| Knowledge | Knowledgebases of documents and notes, given to bots or workspaces: every reply starts from the passages that fit, searched by one embedding model |
|
||||
| App | Installable PWA with Web Push, dark mode, and a rail built for a phone |
|
||||
|
||||
## Screenshots
|
||||
|
||||
@@ -77,44 +112,72 @@ their instructions there, and its computers.
|
||||

|
||||

|
||||
|
||||
## How it fits together
|
||||
|
||||
```
|
||||
You ── chat ── Coordinator ── delegates ── Workers
|
||||
│ │
|
||||
├── Workspaces ──────────┤
|
||||
│ context, memory, bots │
|
||||
├── Routines ────────────┤
|
||||
│ cron schedules │
|
||||
└── Computers ───────────┘
|
||||
docker sandboxes:
|
||||
real Chrome, shell
|
||||
```
|
||||
|
||||
- **Coordinator** is yours alone. It plans, delegates to workers, and keeps the
|
||||
crew in order. It is the only bot that reaches every worker.
|
||||
- **Workers** are the crew. Each has a job, its own instructions and memory, and
|
||||
its own models if you want to tune cost per bot.
|
||||
- **Workspaces** group bots around a subject. Models, instructions, memory and
|
||||
the default computer resolve per workspace before per bot.
|
||||
- **Routines** are cron schedules that queue a task without you asking.
|
||||
- **Computers** are per-install Docker containers of Cobble's own image
|
||||
(`computer/`: Debian 13, Google Chrome on a virtual screen, Playwright MCP and
|
||||
a shell). Bots drive the browser and the shell, and you can watch the same
|
||||
browser live in the chat and take over.
|
||||
|
||||
Each conversation is split into sessions, so a long-running bot does not grow
|
||||
one endless thread: the bot names a session, summarizes it, and carries the
|
||||
summary into the next one.
|
||||
|
||||
## Install
|
||||
|
||||
On a Linux machine with Docker (the installer adds Docker when it is
|
||||
missing):
|
||||
On a Linux machine with Docker (the installer adds Docker when it is missing):
|
||||
|
||||
```bash
|
||||
curl -fsSL https://url.moduletrace.com/cobble | sudo bash
|
||||
```
|
||||
|
||||
The app serves plain HTTP on the port it prints, usually
|
||||
`http://<your-ip>:7227`. Put a reverse proxy or tunnel in front of it for
|
||||
HTTPS (see [HTTPS](#https)), then open the proxy's address and create the
|
||||
super admin account. The first signup also creates the coordinator and the
|
||||
main computer, which pulls the computer image in the background. Give it a
|
||||
few minutes.
|
||||
`http://<your-ip>:7227`. Put a reverse proxy or tunnel in front of it for HTTPS
|
||||
(see [HTTPS](#https)), then open the proxy's address and create the super admin
|
||||
account. The first signup also creates the coordinator and the main computer,
|
||||
which pulls the computer image in the background. Give it a few minutes.
|
||||
|
||||
Then open **Settings > Models**, add an OpenRouter key (or another provider)
|
||||
and wait for the model list to sync. This is what the bots think with.
|
||||
Then open **Settings > Models**, add an OpenRouter key (or another provider) and
|
||||
wait for the model list to sync. This is what the bots think with.
|
||||
|
||||
### Requirements
|
||||
|
||||
- Linux amd64 or arm64, with Docker. The installer installs Docker from
|
||||
get.docker.com when it is missing.
|
||||
- 2 CPU cores, 4 GB RAM and 20 GB free disk for the app plus one computer.
|
||||
Each computer is its own container with its own memory limit.
|
||||
- Docker Desktop on macOS works for development and small installs, but
|
||||
Linux is the supported host.
|
||||
- 2 CPU cores, 4 GB RAM and 20 GB free disk for the app plus one computer. Each
|
||||
computer is its own container with its own memory limit.
|
||||
- Docker Desktop on macOS works for development and small installs, but Linux is
|
||||
the supported host.
|
||||
- Port 7227, or another port with `--port`.
|
||||
- A reverse proxy or tunnel in front for HTTPS. The app itself serves plain
|
||||
HTTP and never handles certificates.
|
||||
- A reverse proxy or tunnel in front for HTTPS. The app itself serves plain HTTP
|
||||
and never handles certificates.
|
||||
|
||||
The installer binds to `0.0.0.0` so the app is reachable from your phone on
|
||||
the same network. Use `--bind 127.0.0.1` when a reverse proxy is the only
|
||||
thing that should reach it.
|
||||
The installer binds to `0.0.0.0` so the app is reachable from your phone on the
|
||||
same network. Use `--bind 127.0.0.1` when a reverse proxy is the only thing that
|
||||
should reach it.
|
||||
|
||||
The app container itself is limited to 1 CPU and 2 GB of memory, since the
|
||||
heavy work happens in the computers' own containers. Change that with
|
||||
`--cpus` and `--memory`; each computer keeps its own limits.
|
||||
The app container itself is limited to 1 CPU and 2 GB of memory, since the heavy
|
||||
work happens in the computers' own containers. Change that with `--cpus` and
|
||||
`--memory`; each computer keeps its own limits.
|
||||
|
||||
## HTTPS
|
||||
|
||||
@@ -127,21 +190,21 @@ point that at `http://<this machine>:7227`:
|
||||
`proxy_set_header X-Forwarded-Proto $scheme;`.
|
||||
- Pass `/ws` through as well as ordinary requests, including the upgrade.
|
||||
- Keep the address the browser used in `Host` (or send it as
|
||||
`X-Forwarded-Host`). Live updates and the computers' terminals only accept
|
||||
a websocket from the app's own address; Caddy and Cloudflare Tunnel keep
|
||||
it, and nginx needs `proxy_set_header Host $host;`.
|
||||
- Give the proxy a real certificate. Browsers treat plain HTTP as unsafe, so
|
||||
the installable app, offline support, Web Push notifications and voice
|
||||
recording stay off until the address is HTTPS.
|
||||
`X-Forwarded-Host`). Live updates and the computers' terminals only accept a
|
||||
websocket from the app's own address; Caddy and Cloudflare Tunnel keep it, and
|
||||
nginx needs `proxy_set_header Host $host;`.
|
||||
- Give the proxy a real certificate. Browsers treat plain HTTP as unsafe, so the
|
||||
installable app, offline support, Web Push notifications and voice recording
|
||||
stay off until the address is HTTPS.
|
||||
|
||||
Nothing on the machine needs a certificate installed: the browser only ever
|
||||
talks to the proxy. See the Help page in the app for the common proxy fixes.
|
||||
|
||||
## Update and uninstall
|
||||
|
||||
The same script is the updater. It keeps the database, media, computers'
|
||||
home directories and generated secrets, backs up the database before
|
||||
replacing the container, and does nothing when the image has not changed.
|
||||
The same script is the updater. It keeps the database, media, computers' home
|
||||
directories and generated secrets, backs up the database before replacing the
|
||||
container, and does nothing when the image has not changed.
|
||||
|
||||
```bash
|
||||
curl -fsSL https://url.moduletrace.com/cobble | sudo bash
|
||||
@@ -157,54 +220,24 @@ curl -fsSL https://url.moduletrace.com/cobble | sudo bash -s -- --uninstall --pu
|
||||
|
||||
### Options
|
||||
|
||||
| Option | Meaning |
|
||||
| --------------------- | ---------------------------------------------------------- |
|
||||
| `--home DIR` | Install directory, default `/opt/cobble` |
|
||||
| `--data-dir DIR` | Data directory mounted at `/data`, default `HOME/data` |
|
||||
| `--port PORT` | Host port, default `7227` |
|
||||
| `--bind ADDRESS` | Host address to publish on, default `0.0.0.0` |
|
||||
| `--cpus N` | CPU cores for the app container, default `1` |
|
||||
| `--memory MB` | Memory for the app container in MB, default `2048` |
|
||||
| `--image IMAGE` | Container image, default `ghcr.io/moduletrace/cobble` |
|
||||
| `--version TAG` | Image tag, default `latest` |
|
||||
| Option | Meaning |
|
||||
| --- | --- |
|
||||
| `--home DIR` | Install directory, default `/opt/cobble` |
|
||||
| `--data-dir DIR` | Data directory mounted at `/data`, default `HOME/data` |
|
||||
| `--port PORT` | Host port, default `7227` |
|
||||
| `--bind ADDRESS` | Host address to publish on, default `0.0.0.0` |
|
||||
| `--cpus N` | CPU cores for the app container, default `1` |
|
||||
| `--memory MB` | Memory for the app container in MB, default `2048` |
|
||||
| `--image IMAGE` | Container image, default `ghcr.io/moduletrace/cobble` |
|
||||
| `--version TAG` | Image tag, default `latest` |
|
||||
| `--extra-network NET` | Join another Docker network, for a tunnel or reverse proxy |
|
||||
| `--force` | Recreate the container even when it is current |
|
||||
| `--no-pull` | Use an image that is already on the machine |
|
||||
| `--skip-backup` | Update without a database backup |
|
||||
| `--no-docker-install` | Fail instead of installing Docker |
|
||||
| `--yes`, `-y` | Accept the defaults without asking |
|
||||
| `--uninstall` | Stop and remove the app container |
|
||||
| `--purge` | With `--uninstall`, also delete the data directory |
|
||||
|
||||
## How it fits together
|
||||
|
||||
```
|
||||
You ── chat ── Coordinator ── delegates ── Workers
|
||||
│ │
|
||||
├── Workspaces ────────────┤
|
||||
│ context, memory, bots │
|
||||
├── Routines ──────────────┤
|
||||
│ cron schedules │
|
||||
└── Computers ─────────────┘
|
||||
docker sandboxes:
|
||||
real Chrome, shell
|
||||
```
|
||||
|
||||
- **Coordinator** is yours alone. It plans, delegates to workers, and keeps
|
||||
the crew in order. It is the only bot that reaches every worker.
|
||||
- **Workers** are the crew. Each has a job, its own instructions and memory,
|
||||
and its own models if you want to tune cost per bot.
|
||||
- **Workspaces** group bots around a subject. Models, instructions, memory
|
||||
and the default computer resolve per workspace before per bot.
|
||||
- **Routines** are cron schedules that queue a task without you asking.
|
||||
- **Computers** are per-install Docker containers of Cobble's own image
|
||||
(`computer/`: Debian 13, Google Chrome on a virtual screen, Playwright MCP
|
||||
and a shell). Bots drive the browser and the shell, and you can watch the
|
||||
same browser live in the chat and take over.
|
||||
|
||||
Each conversation is split into sessions, so a long-running bot does not grow
|
||||
one endless thread: the bot names a session, summarizes it, and carries the
|
||||
summary into the next one.
|
||||
| `--force` | Recreate the container even when it is current |
|
||||
| `--no-pull` | Use an image that is already on the machine |
|
||||
| `--skip-backup` | Update without a database backup |
|
||||
| `--no-docker-install` | Fail instead of installing Docker |
|
||||
| `--yes`, `-y` | Accept the defaults without asking |
|
||||
| `--uninstall` | Stop and remove the app container |
|
||||
| `--purge` | With `--uninstall`, also delete the data directory |
|
||||
|
||||
## Data and settings
|
||||
|
||||
@@ -227,38 +260,37 @@ Everything that must survive an update lives under the install directory:
|
||||
|
||||
`.env` holds the port and the encryption keys. The keys encrypt sessions and
|
||||
settings, so keep a copy and do not rotate them without re-entering provider
|
||||
keys and other secrets. Provider keys, MCP servers, tools and app settings
|
||||
are managed in the app, not in `.env`.
|
||||
keys and other secrets. Provider keys, MCP servers, tools and app settings are
|
||||
managed in the app, not in `.env`.
|
||||
|
||||
Edit `.env` and run `docker restart cobble` to apply changes. The installer
|
||||
only appends missing values and keeps what is already there, apart from the
|
||||
port it manages.
|
||||
Edit `.env` and run `docker restart cobble` to apply changes. The installer only
|
||||
appends missing values and keeps what is already there, apart from the port it
|
||||
manages.
|
||||
|
||||
Settings > Backups makes two kinds of copy. Database snapshots (bun-sqlite's
|
||||
`backup` command) stay in `data/db/.backups` and can be restored from the
|
||||
app. Whole-data archives are a `tar.gz` of the entire `data/` directory,
|
||||
written to `backups-archives/` (mounted at `/backups-archives`, the
|
||||
`BACKUP_ARCHIVE_DIR` setting); every entry sits under one folder named after
|
||||
the archive, so extracting one by hand drops a single folder. Each group
|
||||
can create a copy, restore from one (a listed row, or a file uploaded from
|
||||
the button beside Create), download it and delete it; the newest five
|
||||
archives are kept.
|
||||
`backup` command) stay in `data/db/.backups` and can be restored from the app.
|
||||
Whole-data archives are a `tar.gz` of the entire `data/` directory, written to
|
||||
`backups-archives/` (mounted at `/backups-archives`, the `BACKUP_ARCHIVE_DIR`
|
||||
setting); every entry sits under one folder named after the archive, so
|
||||
extracting one by hand drops a single folder. Each group can create a copy,
|
||||
restore from one (a listed row, or a file uploaded from the button beside
|
||||
Create), download it and delete it; the newest five archives are kept.
|
||||
|
||||
The app container is started with the Docker socket mounted and
|
||||
`MAIN_SERVER=1`, so it can create computer containers and run cron, the
|
||||
queue and Web Push.
|
||||
`MAIN_SERVER=1`, so it can create computer containers and run cron, the queue
|
||||
and Web Push.
|
||||
|
||||
## Images
|
||||
|
||||
Every release publishes a multi-arch image to
|
||||
`ghcr.io/moduletrace/cobble`, which is what the installer pulls. Tags are
|
||||
`latest`, the release version, `major.minor` and the commit sha.
|
||||
Every release publishes a multi-arch image to `ghcr.io/moduletrace/cobble`,
|
||||
which is what the installer pulls. Tags are `latest`, the release version,
|
||||
`major.minor` and the commit sha.
|
||||
|
||||
The same image is copied into `git.tben.me/moduletrace/cobble` by
|
||||
`bun run mirror:gitea`, which runs after the build over the VPN (the Gitea
|
||||
registry is not on the public internet, so GitHub Actions cannot reach it).
|
||||
Install from Gitea with `--image git.tben.me/moduletrace/cobble`, or build
|
||||
from source with `docker build -t cobble:local .` and
|
||||
Install from Gitea with `--image git.tben.me/moduletrace/cobble`, or build from
|
||||
source with `docker build -t cobble:local .` and
|
||||
`--image cobble --version local --no-pull`.
|
||||
|
||||
A release is published from a clean `main` with the two scripts, which tag the
|
||||
@@ -291,32 +323,31 @@ Open `http://localhost:7227`. With no users, every page goes to
|
||||
SEED_SUPER_ADMIN_PASSWORD=... bun run seed
|
||||
```
|
||||
|
||||
The development server serves plain HTTP, the same as the container. To try
|
||||
the app from a phone, run a proxy or tunnel in front of it (see
|
||||
[HTTPS](#https)); the installed app, Web Push and voice need that secure
|
||||
context.
|
||||
The development server serves plain HTTP, the same as the container. To try the
|
||||
app from a phone, run a proxy or tunnel in front of it (see [HTTPS](#https)); the
|
||||
installed app, Web Push and voice need that secure context.
|
||||
|
||||
| Command | Purpose |
|
||||
| ---------------------- | ----------------------------------- |
|
||||
| `bun run dev` | Development server |
|
||||
| `bun run start` | Production server on the host |
|
||||
| `bun run typecheck` | Type-check |
|
||||
| `bun run test` | Run the test suite |
|
||||
| `bun run check:bundle` | Bundle budget after a build |
|
||||
| `bun run seed` | Create the super admin from the CLI |
|
||||
| `bun run seed:bots` | Add a sample crew |
|
||||
| `bun run db:schema` | Sync the schema and types |
|
||||
| `bun run gen:favicon` | Regenerate favicons and PWA assets |
|
||||
| Command | Purpose |
|
||||
| --- | --- |
|
||||
| `bun run dev` | Development server |
|
||||
| `bun run start` | Production server on the host |
|
||||
| `bun run typecheck` | Type-check |
|
||||
| `bun run test` | Run the test suite |
|
||||
| `bun run check:bundle` | Bundle budget after a build |
|
||||
| `bun run seed` | Create the super admin from the CLI |
|
||||
| `bun run seed:bots` | Add a sample crew |
|
||||
| `bun run db:schema` | Sync the schema and types |
|
||||
| `bun run gen:favicon` | Regenerate favicons and PWA assets |
|
||||
|
||||
Plain Node does not work: the app runs on Bun. The stack is Bun,
|
||||
[`@moduletrace/bunext`](https://github.com/Moduletrace/bunext) for
|
||||
filesystem routing, SQLite via
|
||||
[`@moduletrace/bun-sqlite`](https://github.com/Moduletrace/bun-sqlite),
|
||||
Tailwind CSS and the `@moduletrace/twui` component library. The model layer is
|
||||
one adapter over OpenAI-compatible APIs, so any compatible provider works.
|
||||
[`@moduletrace/bunext`](https://github.com/Moduletrace/bunext) for filesystem
|
||||
routing, SQLite via
|
||||
[`@moduletrace/bun-sqlite`](https://github.com/Moduletrace/bun-sqlite), Tailwind
|
||||
CSS and the `@moduletrace/twui` component library. The model layer is one
|
||||
adapter over OpenAI-compatible APIs, so any compatible provider works.
|
||||
|
||||
See [AGENTS.md](AGENTS.md) for the full architecture, routes, queue, harness
|
||||
and data model. CI runs type-check and tests on every push and pull request;
|
||||
See [AGENTS.md](AGENTS.md) for the full architecture, routes, queue, harness and
|
||||
data model. CI runs type-check and tests on every push and pull request;
|
||||
releases are built by GitHub Actions and pushed to both registries. See
|
||||
[RELEASING.md](RELEASING.md) for the release and launch checklist.
|
||||
|
||||
@@ -325,9 +356,24 @@ releases are built by GitHub Actions and pushed to both registries. See
|
||||
Issues and pull requests are welcome, in English, on either
|
||||
[GitHub](https://github.com/Moduletrace/cobble) or
|
||||
[Gitea](https://git.tben.me/Moduletrace/cobble). Run `bun run typecheck` and
|
||||
`bun run test` before opening a pull request, and read
|
||||
[AGENTS.md](AGENTS.md) first: it documents the conventions the code follows.
|
||||
`bun run test` before opening a pull request, and read [AGENTS.md](AGENTS.md)
|
||||
first: it documents the conventions the code follows.
|
||||
|
||||
Good first contributions right now: a worker role that ships as a one-click
|
||||
template, an MCP server integration that other people would install, a missing
|
||||
proxy recipe for the Help page, or a test around a bug you hit while installing.
|
||||
|
||||
## License
|
||||
|
||||
MIT. See [LICENSE](LICENSE).
|
||||
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
|
||||
**If Cobble saves you from stitching three tools together, star the repo.**
|
||||
It is the fastest way to help other people find it.
|
||||
|
||||
[](https://github.com/Moduletrace/cobble/stargazers)
|
||||
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
# Demo GIF
|
||||
|
||||
The demo recording is a placeholder. `README.md` carries the image line commented
|
||||
out, pointing at `docs/readme/demo.gif`, which does not exist yet.
|
||||
|
||||
## To go live
|
||||
|
||||
1. Record the loop below and save it as `docs/readme/demo.gif`, under 8 MB
|
||||
(GitHub renders anything bigger badly, and the point is that it plays
|
||||
instantly on the repo page).
|
||||
2. Uncomment the image line near the top of `README.md`.
|
||||
|
||||
## Shot list
|
||||
|
||||
Target 12 to 18 seconds, 960px wide, loop, no audio.
|
||||
|
||||
1. **0.0s** The rail. Coordinator at top, four workers below with different
|
||||
faces. Mouse hovers one, its status line reads "working".
|
||||
2. **2.5s** Cut to the chat. You type: "Check whether the staging site still
|
||||
returns 200 and open a PR if the footer link is broken." Send.
|
||||
3. **4.5s** The coordinator delegates. Two worker faces go to "working" in the
|
||||
rail at the same time.
|
||||
4. **6.5s** Cut to the live computer view. Chrome is open, the bot is scrolling
|
||||
the staging site. The cursor moves on its own. Terminal panel beside it shows
|
||||
curl output.
|
||||
5. **10.0s** The bot hits a login wall. Face flips to "needs you". Card appears
|
||||
asking to take over. You click, type the password, hand it back.
|
||||
6. **12.5s** The bot finishes. PR link appears in chat. Worker faces go to
|
||||
"done".
|
||||
7. **15.0s** Pull back to the rail. Whole crew idle, everything green, one line
|
||||
of summary text.
|
||||
|
||||
That sequence is the entire product in one loop: delegate, parallel work, a real
|
||||
browser, a human handoff, a shipped artifact. Do not replace it with a
|
||||
screenshot carousel.
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.27.6",
|
||||
"version": "0.27.10",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -2,6 +2,7 @@ import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS, BUN_SQLITE_COBBLE_CONNECTORS } from "@/db/types/db";
|
||||
import type { BotConnectorEntry, ConnectorAccountRecord, ConnectorRecord } from "@/src/types";
|
||||
import botConnectorsSql from "@/src/utils/bot-connectors-sql";
|
||||
import connectorAccountReachSql from "@/src/utils/connector-account-reach-sql";
|
||||
import attachConnectorAccountScopes from "./attach-connector-account-scopes";
|
||||
import parseConnectorAccountRow from "./parse-connector-account-row";
|
||||
import parseConnectorRow from "./parse-connector-row";
|
||||
@@ -18,10 +19,11 @@ type ConnectorRow = BUN_SQLITE_COBBLE_CONNECTORS & { connection_name?: string };
|
||||
/**
|
||||
* The connectors a conversation's bot can use for this user, with the
|
||||
* accounts that reach there: this user's own (whatever their status, so a
|
||||
* pending sign-in still shows), and any connected account given to this
|
||||
* bot, this workspace or every bot, named with its owner. Each app says
|
||||
* where it comes from: the install, this workspace, this user's own
|
||||
* attachment, or an account given here.
|
||||
* pending sign-in still shows), every connected account of a connector given
|
||||
* to this workspace, and any connected account given to this bot, this
|
||||
* workspace or every bot, named with its owner. Each app says where it comes
|
||||
* from: the install, this workspace, this user's own attachment, or an
|
||||
* account given here.
|
||||
*/
|
||||
export default async function grabBotConnectors({
|
||||
user_id,
|
||||
@@ -44,6 +46,7 @@ export default async function grabBotConnectors({
|
||||
const connection_names = new Map(found.map((row) => [Number(row.id), row.connection_name || ""]));
|
||||
const ids = connectors.map((connector) => connector.id);
|
||||
const placeholders = ids.map(() => "?").join(", ");
|
||||
const workspace_reach = connectorAccountReachSql({ workspace_id });
|
||||
|
||||
const [account_res, workspace_res, bot_res] = await Promise.all([
|
||||
BunSQLite.sql<AccountRow>({
|
||||
@@ -57,13 +60,18 @@ export default async function grabBotConnectors({
|
||||
a.all_bots = 1
|
||||
OR EXISTS (SELECT 1 FROM connector_account_bots ab WHERE ab.account_id = a.id AND ab.bot_id = ?)
|
||||
${workspace_id ? `OR EXISTS (SELECT 1 FROM connector_account_workspaces aw WHERE aw.account_id = a.id AND aw.workspace_id = ?)` : ""}
|
||||
${workspace_reach.sql}
|
||||
)
|
||||
)
|
||||
)
|
||||
ORDER BY a.id ASC`,
|
||||
values: workspace_id
|
||||
? [...ids, Number(user_id), Number(bot_id), Number(workspace_id)]
|
||||
: [...ids, Number(user_id), Number(bot_id)],
|
||||
values: [
|
||||
...ids,
|
||||
Number(user_id),
|
||||
Number(bot_id),
|
||||
...(workspace_id ? [Number(workspace_id)] : []),
|
||||
...workspace_reach.values,
|
||||
],
|
||||
}),
|
||||
BunSQLite.sql<{ connector_id: number }>({
|
||||
sql: `SELECT connector_id FROM workspace_connectors WHERE connector_id IN (${placeholders})`,
|
||||
|
||||
@@ -2,6 +2,7 @@ import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS, BUN_SQLITE_COBBLE_CONNECTORS } from "@/db/types/db";
|
||||
import type { ConnectorAccountRecord, ConnectorRecord } from "@/src/types";
|
||||
import botConnectorsSql from "@/src/utils/bot-connectors-sql";
|
||||
import connectorAccountReachSql from "@/src/utils/connector-account-reach-sql";
|
||||
import attachConnectorAccountScopes from "./attach-connector-account-scopes";
|
||||
import parseConnectorAccountRow from "./parse-connector-account-row";
|
||||
import parseConnectorRow from "./parse-connector-row";
|
||||
@@ -19,9 +20,10 @@ type Params = {
|
||||
export type RunConnector = {
|
||||
connector: ConnectorRecord;
|
||||
/**
|
||||
* The accounts the run may use for it: the user's own, and every one
|
||||
* given to this bot, this workspace or every bot. Empty means nothing
|
||||
* to call with: the card asks them to connect one.
|
||||
* The accounts the run may use for it: the user's own, every connected
|
||||
* account of a connector given to this workspace, and every one given to
|
||||
* this bot, this workspace or every bot. Empty means nothing to call
|
||||
* with: the card asks them to connect one.
|
||||
*/
|
||||
accounts: ConnectorAccountRecord[];
|
||||
};
|
||||
@@ -31,9 +33,9 @@ type AccountRow = BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS & { owner_name?: string }
|
||||
/**
|
||||
* The connectors one run reaches (`botConnectorsSql`) with the accounts it
|
||||
* may act through: its own user's, never another person's unless that
|
||||
* account was given to this bot, this workspace or every bot. A connector
|
||||
* reaches a run without any account; it only becomes callable once there is
|
||||
* one.
|
||||
* account was given to this bot, this workspace or every bot, or its app was
|
||||
* given to this workspace. A connector reaches a run without any account; it
|
||||
* only becomes callable once there is one.
|
||||
*/
|
||||
export default async function grabRunConnectors({ user_id, bot_id, workspace_id }: Params): Promise<RunConnector[]> {
|
||||
const found =
|
||||
@@ -47,6 +49,7 @@ export default async function grabRunConnectors({ user_id, bot_id, workspace_id
|
||||
|
||||
const connectors = found.map((row) => parseConnectorRow({ row }));
|
||||
const ids = connectors.map((connector) => connector.id);
|
||||
const workspace_reach = connectorAccountReachSql({ workspace_id });
|
||||
const rows =
|
||||
(
|
||||
await BunSQLite.sql<AccountRow>({
|
||||
@@ -60,9 +63,10 @@ export default async function grabRunConnectors({ user_id, bot_id, workspace_id
|
||||
OR a.all_bots = 1
|
||||
OR EXISTS (SELECT 1 FROM connector_account_bots b WHERE b.account_id = a.id AND b.bot_id = ?)
|
||||
OR EXISTS (SELECT 1 FROM connector_account_workspaces w WHERE w.account_id = a.id AND w.workspace_id = ?)
|
||||
${workspace_reach.sql}
|
||||
)
|
||||
ORDER BY a.id ASC`,
|
||||
values: [...ids, Number(user_id), Number(bot_id), Number(workspace_id || 0)],
|
||||
values: [...ids, Number(user_id), Number(bot_id), Number(workspace_id || 0), ...workspace_reach.values],
|
||||
})
|
||||
).payload || [];
|
||||
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import insertConnectorAccountSql from "@/src/functions/backend/db/connectors/insert-connector-account-sql";
|
||||
|
||||
function scratch() {
|
||||
const db = new Database(":memory:");
|
||||
|
||||
db.run(`CREATE TABLE connector_accounts (
|
||||
id INTEGER PRIMARY KEY,
|
||||
created_at INTEGER,
|
||||
updated_at INTEGER,
|
||||
connector_id INTEGER,
|
||||
user_id INTEGER,
|
||||
label TEXT,
|
||||
slug TEXT,
|
||||
provider_account_id TEXT,
|
||||
status TEXT,
|
||||
is_default INTEGER,
|
||||
connected_at INTEGER,
|
||||
last_checked_at INTEGER,
|
||||
last_error TEXT
|
||||
)`);
|
||||
|
||||
return db;
|
||||
}
|
||||
|
||||
function insert(db: Database, { label, slug }: { label: string; slug: string }) {
|
||||
const statement = insertConnectorAccountSql({
|
||||
now: 1000,
|
||||
connector_id: 1,
|
||||
user_id: 1,
|
||||
label,
|
||||
slug,
|
||||
provider_account_id: "ca_one",
|
||||
status: "connected",
|
||||
});
|
||||
|
||||
db.query(statement.sql).run(...statement.values);
|
||||
}
|
||||
|
||||
describe("insertConnectorAccountSql", () => {
|
||||
test("inserts the sign-in once", () => {
|
||||
const db = scratch();
|
||||
|
||||
insert(db, { label: "Ben", slug: "ben" });
|
||||
|
||||
const rows = db.query(`SELECT label, slug, status, is_default, last_error FROM connector_accounts`).all();
|
||||
|
||||
expect(rows).toEqual([{ label: "Ben", slug: "ben", status: "connected", is_default: 0, last_error: "" }]);
|
||||
});
|
||||
|
||||
test("keeps the row a second sync already wrote for the same account", () => {
|
||||
const db = scratch();
|
||||
|
||||
insert(db, { label: "Ben", slug: "ben" });
|
||||
insert(db, { label: "Ben again", slug: "ben-2" });
|
||||
|
||||
const rows = db.query(`SELECT label, slug FROM connector_accounts`).all();
|
||||
|
||||
expect(rows).toEqual([{ label: "Ben", slug: "ben" }]);
|
||||
});
|
||||
|
||||
test("adds a different account of the same app", () => {
|
||||
const db = scratch();
|
||||
|
||||
insert(db, { label: "Ben", slug: "ben" });
|
||||
|
||||
const statement = insertConnectorAccountSql({
|
||||
now: 1000,
|
||||
connector_id: 1,
|
||||
user_id: 1,
|
||||
label: "Ben work",
|
||||
slug: "ben-work",
|
||||
provider_account_id: "ca_two",
|
||||
status: "connected",
|
||||
});
|
||||
|
||||
db.query(statement.sql).run(...statement.values);
|
||||
|
||||
expect(db.query(`SELECT provider_account_id FROM connector_accounts ORDER BY id`).all()).toEqual([
|
||||
{ provider_account_id: "ca_one" },
|
||||
{ provider_account_id: "ca_two" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import type { ProviderAccountStatus } from "@/src/harness/connectors/connector-provider";
|
||||
|
||||
type Params = {
|
||||
now: number;
|
||||
connector_id: number;
|
||||
user_id: number;
|
||||
label: string;
|
||||
slug: string;
|
||||
provider_account_id: string;
|
||||
status: ProviderAccountStatus;
|
||||
};
|
||||
|
||||
/**
|
||||
* One row per provider account, even when two syncs (a poll beside the cron)
|
||||
* reach it at once: the statement itself refuses a second row, so neither can
|
||||
* insert the same sign-in twice.
|
||||
*/
|
||||
export default function insertConnectorAccountSql({
|
||||
now,
|
||||
connector_id,
|
||||
user_id,
|
||||
label,
|
||||
slug,
|
||||
provider_account_id,
|
||||
status,
|
||||
}: Params) {
|
||||
return {
|
||||
sql: `INSERT INTO connector_accounts
|
||||
(created_at, updated_at, connector_id, user_id, label, slug, provider_account_id, status, is_default, connected_at, last_checked_at, last_error)
|
||||
SELECT ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ''
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM connector_accounts WHERE connector_id = ? AND user_id = ? AND provider_account_id = ?
|
||||
)`,
|
||||
values: [
|
||||
now,
|
||||
now,
|
||||
connector_id,
|
||||
user_id,
|
||||
label,
|
||||
slug,
|
||||
provider_account_id,
|
||||
status,
|
||||
status == "connected" ? now : null,
|
||||
now,
|
||||
connector_id,
|
||||
user_id,
|
||||
provider_account_id,
|
||||
],
|
||||
};
|
||||
}
|
||||
@@ -2,42 +2,18 @@ import { describe, expect, test } from "bun:test";
|
||||
import shouldAdoptConnectorAccount from "@/src/functions/backend/db/connectors/should-adopt-connector-account";
|
||||
|
||||
describe("shouldAdoptConnectorAccount", () => {
|
||||
test("adopts a connected account into the app's free card", () => {
|
||||
expect(shouldAdoptConnectorAccount({ status: "connected", reconnect: false, claimed: false, free_slot: true })).toBe(
|
||||
true,
|
||||
);
|
||||
test("adopts a connected account its own sign-in made", () => {
|
||||
expect(shouldAdoptConnectorAccount({ status: "connected", reconnect: true, claimed: false })).toBe(true);
|
||||
expect(shouldAdoptConnectorAccount({ status: "connected", reconnect: false, claimed: true })).toBe(true);
|
||||
});
|
||||
|
||||
test("leaves a second connected account at the provider once the card is taken", () => {
|
||||
expect(shouldAdoptConnectorAccount({ status: "connected", reconnect: false, claimed: false, free_slot: false })).toBe(
|
||||
false,
|
||||
);
|
||||
test("leaves a connected account nothing here asked for at the provider", () => {
|
||||
expect(shouldAdoptConnectorAccount({ status: "connected", reconnect: false, claimed: false })).toBe(false);
|
||||
});
|
||||
|
||||
test("adopts a connected account a request here started, even with no free card", () => {
|
||||
expect(shouldAdoptConnectorAccount({ status: "connected", reconnect: false, claimed: true, free_slot: false })).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
test("adopts a pending account a request here started", () => {
|
||||
expect(shouldAdoptConnectorAccount({ status: "pending", reconnect: false, claimed: true, free_slot: false })).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
test("adopts a pending account that reconnects a row", () => {
|
||||
expect(shouldAdoptConnectorAccount({ status: "pending", reconnect: true, claimed: false, free_slot: false })).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
test("skips a pending account nothing here started", () => {
|
||||
expect(shouldAdoptConnectorAccount({ status: "pending", reconnect: false, claimed: false, free_slot: true })).toBe(
|
||||
false,
|
||||
);
|
||||
expect(shouldAdoptConnectorAccount({ status: "expired", reconnect: false, claimed: false, free_slot: true })).toBe(
|
||||
false,
|
||||
);
|
||||
test("leaves an unfinished sign-in alone until it connects", () => {
|
||||
expect(shouldAdoptConnectorAccount({ status: "pending", reconnect: true, claimed: false })).toBe(false);
|
||||
expect(shouldAdoptConnectorAccount({ status: "pending", reconnect: false, claimed: true })).toBe(false);
|
||||
expect(shouldAdoptConnectorAccount({ status: "expired", reconnect: false, claimed: false })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -6,23 +6,17 @@ type Params = {
|
||||
reconnect: boolean;
|
||||
/** A pending request here started this sign-in. */
|
||||
claimed: boolean;
|
||||
/**
|
||||
* Whether the app has no live account here yet: one card per app is
|
||||
* filled by the provider's account, and any other account arrives through
|
||||
* its own sign-in (claimed).
|
||||
*/
|
||||
free_slot: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether a provider account becomes a local row. One a request here started
|
||||
* (or is reconnecting) always does. A connected one the app doesn't know
|
||||
* gets the app's one free card, so leftovers from earlier sign-ins at the
|
||||
* provider can't pile up as four rows of the same mailbox; a second account
|
||||
* appears by signing in again, which claims its own row.
|
||||
* Whether a provider account becomes a local row: only one a request here
|
||||
* started or is reconnecting, and only once it is connected. One card per
|
||||
* sign-in, so an account the provider already held (a leftover from an earlier
|
||||
* attempt, or a sign-in made at the provider itself) never arrives as a second
|
||||
* card of the same mailbox. A sign-in that hasn't finished has no card either:
|
||||
* a link that connects under another id would leave a dead row beside the real
|
||||
* one.
|
||||
*/
|
||||
export default function shouldAdoptConnectorAccount({ status, reconnect, claimed, free_slot }: Params) {
|
||||
if (reconnect || claimed) return true;
|
||||
|
||||
return status == "connected" && free_slot;
|
||||
export default function shouldAdoptConnectorAccount({ status, reconnect, claimed }: Params) {
|
||||
return status == "connected" && (reconnect || claimed);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* The row an id-less reconnect replaces. The production fault this pins:
|
||||
* 0.27.6 fell back to the one dead row with the requested name, so a new
|
||||
* mailbox that arrived while a dead row existed took that row's label and
|
||||
* namespace. Only a pending request that names a row may hand it over.
|
||||
*/
|
||||
import { expect, test } from "bun:test";
|
||||
import { pendingReconnectRow } from "./sync-connector-accounts";
|
||||
|
||||
test("an id-less reconnect names the row its request does", () => {
|
||||
expect(pendingReconnectRow([{ account_id: 5, provider_account_id: "" }])).toBe(5);
|
||||
});
|
||||
|
||||
test("a reconnect the provider gave an id for is not an id-less one", () => {
|
||||
expect(pendingReconnectRow([{ account_id: 5, provider_account_id: "ca_new" }])).toBeNull();
|
||||
});
|
||||
|
||||
test("a plain sign-in (no row) and no request name nothing", () => {
|
||||
expect(pendingReconnectRow([])).toBeNull();
|
||||
expect(pendingReconnectRow([{ account_id: 0, provider_account_id: "" }])).toBeNull();
|
||||
});
|
||||
@@ -7,6 +7,7 @@ import connectorSlug from "@/src/utils/connector-slug";
|
||||
import grabConnector from "./grab-connector";
|
||||
import parseConnectorAccountRow from "./parse-connector-account-row";
|
||||
import shouldAdoptConnectorAccount from "./should-adopt-connector-account";
|
||||
import insertConnectorAccountSql from "./insert-connector-account-sql";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
@@ -20,15 +21,15 @@ type Params = {
|
||||
|
||||
/**
|
||||
* Reads the user's accounts for a connector at its provider and brings the
|
||||
* local rows in line: new sign-ins are added (the first connected one is the
|
||||
* default), ones the provider reports expired say so, and ones it no longer
|
||||
* lists are marked revoked without losing their label. Pending connect
|
||||
* requests are closed as soon as the account they made is connected.
|
||||
* local rows in line: the account a sign-in here made is added (the first
|
||||
* connected one is the default), ones the provider reports expired say so, and
|
||||
* ones it no longer lists are marked revoked without losing their label.
|
||||
* Pending connect requests are closed as soon as the account they made is
|
||||
* connected.
|
||||
*
|
||||
* One card per app unless the user signed in again: an account the provider
|
||||
* holds but no request here made fills the app's free card once and is left
|
||||
* at the provider after that, so a pile of earlier sign-ins cannot arrive as
|
||||
* four rows of the same mailbox.
|
||||
* One card per sign-in: an account no request here made is left at the
|
||||
* provider, so a leftover from an earlier attempt there cannot arrive as a
|
||||
* second card of the same mailbox beside the one its own sign-in made.
|
||||
*/
|
||||
export default async function syncConnectorAccounts({ user_id, connector_id, label }: Params) {
|
||||
const connector = await grabConnector({ connector_id });
|
||||
@@ -44,41 +45,54 @@ export default async function syncConnectorAccounts({ user_id, connector_id, lab
|
||||
|
||||
const requests = (
|
||||
await BunSQLite.sql<{ account_id: number; provider_account_id: string }>({
|
||||
sql: `SELECT account_id, provider_account_id FROM connector_requests WHERE connector_id = ? AND user_id = ? AND status = 'pending' AND provider_account_id != ''`,
|
||||
sql: `SELECT account_id, provider_account_id FROM connector_requests WHERE connector_id = ? AND user_id = ? AND status = 'pending'`,
|
||||
values: [connector.id, Number(user_id)],
|
||||
})
|
||||
).payload || [];
|
||||
const reconnect_for = new Map(
|
||||
requests.filter((row) => Number(row.account_id) != 0).map((row) => [String(row.provider_account_id), Number(row.account_id)]),
|
||||
requests
|
||||
.filter((row) => Number(row.account_id) != 0 && row.provider_account_id)
|
||||
// A row disconnected since is no target: that sign-in arrives as a new one.
|
||||
.filter((request) => local.some((account) => Number(account.id) == Number(request.account_id)))
|
||||
.map((row) => [String(row.provider_account_id), Number(row.account_id)]),
|
||||
);
|
||||
let reconnect_row = pendingReconnectRow(requests);
|
||||
// A row disconnected since is no target: that sign-in arrives as a new one.
|
||||
if (reconnect_row && !local.some((row) => Number(row.id) == reconnect_row)) reconnect_row = null;
|
||||
/**
|
||||
* A sign-in only becomes a row once it is connected, or while the request
|
||||
* that started it is still open. A pending account nothing here asked for
|
||||
* is an abandoned or replaced sign-in at the provider (Composio keeps one
|
||||
* A sign-in only becomes a row once it is connected, and only the account
|
||||
* its own request names. A pending account nothing here asked for is an
|
||||
* abandoned or replaced sign-in at the provider (Composio keeps one
|
||||
* `INITIALIZING` per abandoned link), and adopting it would put a second,
|
||||
* never connected account beside the one a reconnect replaced.
|
||||
*/
|
||||
const claimed = new Set(requests.map((row) => String(row.provider_account_id)));
|
||||
const claimed = new Set(requests.map((row) => String(row.provider_account_id || "")).filter(Boolean));
|
||||
/**
|
||||
* A new sign-in the provider named no account for: the first connected
|
||||
* account it didn't already have is that sign-in, once.
|
||||
*/
|
||||
let unclaimed_sign_in = requests.some((row) => Number(row.account_id) == 0 && !row.provider_account_id);
|
||||
|
||||
const seen = new Set(accounts.map((account) => account.provider_account_id));
|
||||
const now = Date.now();
|
||||
|
||||
/**
|
||||
* The app's one free card: a live row still listed by the provider holds
|
||||
* it. An account arriving without a sign-in here (an older attempt at
|
||||
* the provider) may fill it once, never pile up beside it.
|
||||
* A listing that names no account is the provider unable to answer, not
|
||||
* every account deleted there: revoking them all would put Reconnect on
|
||||
* cards that are fine.
|
||||
*/
|
||||
let free_slot = !local.some((row) => row.status == "connected" && seen.has(String(row.provider_account_id || "")));
|
||||
if (accounts.length) {
|
||||
for (const row of local) {
|
||||
if (seen.has(String(row.provider_account_id || ""))) continue;
|
||||
|
||||
for (const row of local) {
|
||||
if (seen.has(String(row.provider_account_id || ""))) continue;
|
||||
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE connector_accounts SET status = 'revoked', last_checked_at = ?, updated_at = ? WHERE id = ?`,
|
||||
values: [now, now, Number(row.id)],
|
||||
});
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE connector_accounts SET status = 'revoked', last_checked_at = ?, updated_at = ? WHERE id = ?`,
|
||||
values: [now, now, Number(row.id)],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let firstConnected: number | null = free_slot ? 0 : null;
|
||||
let firstConnected: number | null = local.some((row) => row.status == "connected") ? null : 0;
|
||||
|
||||
for (const account of accounts) {
|
||||
const provider_account_id = String(account.provider_account_id);
|
||||
@@ -87,9 +101,11 @@ export default async function syncConnectorAccounts({ user_id, connector_id, lab
|
||||
if (
|
||||
!shouldAdoptConnectorAccount({
|
||||
status: account.status,
|
||||
reconnect: Boolean(reconnect_id),
|
||||
claimed: claimed.has(provider_account_id),
|
||||
free_slot,
|
||||
reconnect: Boolean(reconnect_id) || Boolean(reconnect_row),
|
||||
claimed:
|
||||
claimed.has(provider_account_id) ||
|
||||
(unclaimed_sign_in &&
|
||||
!local.some((row) => String(row.provider_account_id || "") == provider_account_id)),
|
||||
})
|
||||
)
|
||||
continue;
|
||||
@@ -100,11 +116,11 @@ export default async function syncConnectorAccounts({ user_id, connector_id, lab
|
||||
account,
|
||||
fallback_label: label,
|
||||
reconnect_id,
|
||||
reconnect_row,
|
||||
});
|
||||
|
||||
if (account.status != "connected") continue;
|
||||
|
||||
if (free_slot) free_slot = false;
|
||||
reconnect_row = null;
|
||||
unclaimed_sign_in = false;
|
||||
|
||||
if (firstConnected === 0) {
|
||||
const created = (
|
||||
@@ -138,6 +154,12 @@ export default async function syncConnectorAccounts({ user_id, connector_id, lab
|
||||
return grabUserAccounts({ connector_id: connector.id, user_id: Number(user_id) });
|
||||
}
|
||||
|
||||
export function pendingReconnectRow(requests: Array<{ account_id: number; provider_account_id: string }>) {
|
||||
const named = requests.find((row) => Number(row.account_id) != 0 && !row.provider_account_id);
|
||||
|
||||
return Number(named?.account_id || 0) || null;
|
||||
}
|
||||
|
||||
type UpsertParams = {
|
||||
connector_id: number;
|
||||
user_id: number;
|
||||
@@ -148,9 +170,15 @@ type UpsertParams = {
|
||||
* sign-in takes its place instead of arriving as a second account.
|
||||
*/
|
||||
reconnect_id?: number;
|
||||
/**
|
||||
* That row when the provider gave the sign-in no id at all: the request
|
||||
* names it, so it's never guessed from a name or a sole dead row, which
|
||||
* would hand a new mailbox the dead one's label and namespace.
|
||||
*/
|
||||
reconnect_row?: number | null;
|
||||
};
|
||||
|
||||
async function upsertAccount({ connector_id, user_id, account, fallback_label, reconnect_id }: UpsertParams) {
|
||||
async function upsertAccount({ connector_id, user_id, account, fallback_label, reconnect_id, reconnect_row }: UpsertParams) {
|
||||
const now = Date.now();
|
||||
|
||||
if (reconnect_id) {
|
||||
@@ -200,42 +228,25 @@ async function upsertAccount({ connector_id, user_id, account, fallback_label, r
|
||||
}
|
||||
|
||||
/**
|
||||
* A reconnect the provider gave no id for still lands on the row it
|
||||
* replaces: one dead row with this account's name is that row, and a
|
||||
* second one with the same name would be the duplicate this prevents.
|
||||
* When the provider's name differs from the label the user chose, the one
|
||||
* dead row for this app is still the row a new sign-in takes over.
|
||||
* An id-less reconnect lands on the row it replaces, named by its request.
|
||||
* A row that is merely dead is not it: a new mailbox that arrives while
|
||||
* one dead row exists would otherwise take that row's name and namespace.
|
||||
* Only a connected account takes it, since an abandoned link at the
|
||||
* provider stays pending, and only once.
|
||||
*/
|
||||
const name = account.label || fallback_label || "";
|
||||
const named_dead = name
|
||||
? ((
|
||||
await BunSQLite.sql<BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS>({
|
||||
sql: `SELECT * FROM connector_accounts WHERE connector_id = ? AND user_id = ? AND status IN ('revoked', 'expired') AND lower(label) = lower(?) ORDER BY id ASC`,
|
||||
values: [connector_id, user_id, name],
|
||||
})
|
||||
).payload || [])
|
||||
: [];
|
||||
const dead = named_dead.length
|
||||
? named_dead
|
||||
: ((
|
||||
await BunSQLite.sql<BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS>({
|
||||
sql: `SELECT * FROM connector_accounts WHERE connector_id = ? AND user_id = ? AND status IN ('revoked', 'expired') ORDER BY id ASC`,
|
||||
values: [connector_id, user_id],
|
||||
})
|
||||
).payload || []);
|
||||
|
||||
if (dead.length == 1) {
|
||||
const row = dead[0]!;
|
||||
|
||||
if (reconnect_row) {
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE connector_accounts SET provider_account_id = ?, status = ?, connected_at = ?, last_checked_at = ?, last_error = '', updated_at = ? WHERE id = ?`,
|
||||
sql: `UPDATE connector_accounts SET provider_account_id = ?, status = ?, connected_at = ?, last_checked_at = ?, last_error = '', updated_at = ?
|
||||
WHERE id = ? AND connector_id = ? AND user_id = ?`,
|
||||
values: [
|
||||
account.provider_account_id,
|
||||
account.status,
|
||||
account.status == "connected" ? now : null,
|
||||
now,
|
||||
now,
|
||||
Number(row.id),
|
||||
reconnect_row,
|
||||
connector_id,
|
||||
user_id,
|
||||
],
|
||||
});
|
||||
|
||||
@@ -249,30 +260,24 @@ async function upsertAccount({ connector_id, user_id, account, fallback_label, r
|
||||
})
|
||||
).payload?.map((row) => row.slug) || [];
|
||||
|
||||
const display_name = name || "Account";
|
||||
const display_name = account.label || fallback_label || "Account";
|
||||
let slug = connectorSlug({ name: display_name, max: 12, fallback: "account" });
|
||||
|
||||
for (let index = 2; taken.includes(slug); index++) {
|
||||
slug = `${connectorSlug({ name: display_name, max: 8, fallback: "account" })}-${index}`;
|
||||
}
|
||||
|
||||
await BunSQLite.sql({
|
||||
sql: `INSERT INTO connector_accounts
|
||||
(created_at, updated_at, connector_id, user_id, label, slug, provider_account_id, status, is_default, connected_at, last_checked_at, last_error)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, '')`,
|
||||
values: [
|
||||
now,
|
||||
now,
|
||||
connector_id,
|
||||
user_id,
|
||||
display_name,
|
||||
slug,
|
||||
account.provider_account_id,
|
||||
account.status,
|
||||
account.status == "connected" ? now : null,
|
||||
now,
|
||||
],
|
||||
const { sql, values } = insertConnectorAccountSql({
|
||||
now,
|
||||
connector_id,
|
||||
user_id,
|
||||
label: display_name,
|
||||
slug,
|
||||
provider_account_id: account.provider_account_id,
|
||||
status: account.status,
|
||||
});
|
||||
|
||||
await BunSQLite.sql({ sql, values });
|
||||
}
|
||||
|
||||
type SettleParams = {
|
||||
@@ -303,7 +308,7 @@ async function settleRequests({ connector_id, user_id, provider_account_ids }: S
|
||||
WHERE a.connector_id = connector_requests.connector_id
|
||||
AND a.user_id = connector_requests.user_id
|
||||
AND a.status = 'connected'
|
||||
AND a.created_at >= connector_requests.created_at
|
||||
AND (a.created_at >= connector_requests.created_at OR a.id = connector_requests.account_id)
|
||||
))
|
||||
)`,
|
||||
values: [now, connector_id, user_id, now, ...provider_account_ids],
|
||||
|
||||
@@ -8,6 +8,14 @@ import type { ConnectorAccountRecord, ConnectorRecord } from "@/src/types";
|
||||
import connectorAccountGoneMessage from "./connector-account-gone";
|
||||
import type { ConnectorProvider } from "./connector-provider";
|
||||
|
||||
/**
|
||||
* When each account was last checked against the provider, per process: the
|
||||
* check is a listing of every account the user has, and a cached session is
|
||||
* used many times a minute.
|
||||
*/
|
||||
const accountChecks = new Map<string, number>();
|
||||
const AccountCheckEveryMs = 5 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* The endpoint one account's tools live at, cached in `connector_sessions`
|
||||
* because asking the provider costs a call and the session expires.
|
||||
@@ -54,8 +62,20 @@ async function readCachedHeaders({ headers }: { headers: string | null }): Promi
|
||||
* is not refused: the provider answers from whichever account it does have,
|
||||
* so a bot read a mailbox the user never chose. The row is marked revoked
|
||||
* (its card then offers Reconnect) and the call stops instead.
|
||||
*
|
||||
* The check lists every account the user has, so it is remembered per account
|
||||
* for `AccountCheckEveryMs`: a cached session is checked too, at that pace
|
||||
* rather than on every tool call.
|
||||
*/
|
||||
async function assertAccountStillThere({ connector, provider, user_id, account, now }: Params & { now: number }) {
|
||||
const key = `${connector.id}:${account.provider_account_id}`;
|
||||
|
||||
if (now - (accountChecks.get(key) || 0) < AccountCheckEveryMs) return;
|
||||
|
||||
if (accountChecks.size > 1000) accountChecks.clear();
|
||||
|
||||
accountChecks.set(key, now);
|
||||
|
||||
let accounts: Awaited<ReturnType<ConnectorProvider["accounts"]>>;
|
||||
|
||||
try {
|
||||
@@ -92,6 +112,9 @@ export default async function ensureConnectorEndpoint({
|
||||
account,
|
||||
}: Params): Promise<ConnectorEndpointResult> {
|
||||
const now = Date.now();
|
||||
|
||||
await assertAccountStillThere({ connector, provider, user_id, account, now });
|
||||
|
||||
const cached = (
|
||||
await BunSQLite.sql<BUN_SQLITE_COBBLE_CONNECTOR_SESSIONS>({
|
||||
sql: `SELECT * FROM connector_sessions WHERE connector_id = ? AND user_id = ? AND provider_account_id = ? LIMIT 1`,
|
||||
@@ -113,8 +136,6 @@ export default async function ensureConnectorEndpoint({
|
||||
}
|
||||
}
|
||||
|
||||
await assertAccountStillThere({ connector, provider, user_id, account, now });
|
||||
|
||||
const tools = connector.tools
|
||||
.map((tool) => tool.name)
|
||||
.filter((name) => !connector.excluded_tools.includes(name));
|
||||
|
||||
@@ -156,6 +156,7 @@ describe("composioConnectorProvider", () => {
|
||||
const session = calls.find((call) => call.url.pathname.endsWith("/tool_router/session"))!;
|
||||
|
||||
expect(session.body.multi_account).toEqual({ enable: true, max_accounts_per_toolkit: 5 });
|
||||
expect(session.body.auth_configs).toEqual({ gmail: "ac_1" });
|
||||
|
||||
const link = calls.find((call) => call.url.pathname.endsWith("/tool_router/session/trs_1/link"))!;
|
||||
|
||||
@@ -190,8 +191,69 @@ describe("composioConnectorProvider", () => {
|
||||
expect(made.body.use_composio_managed_auth).toBe(true);
|
||||
});
|
||||
|
||||
test("makes a custom sign-in setup for a toolkit Composio manages no credentials for", async () => {
|
||||
const { fetchImpl, calls } = stub({
|
||||
answer: ({ url, method }) => {
|
||||
if (url.pathname.endsWith("/toolkits/gitea")) {
|
||||
return { body: { composio_managed_auth_schemes: [], auth_config_details: [{ mode: "API_KEY" }] } };
|
||||
}
|
||||
if (url.pathname.endsWith("/tool_router/session")) return { status: 201, body: { session_id: "trs_1" } };
|
||||
if (url.pathname.endsWith("/link")) {
|
||||
return { status: 201, body: { redirect_url: "https://connect/gitea" } };
|
||||
}
|
||||
if (!url.pathname.endsWith("/auth_configs")) return { body: {} };
|
||||
|
||||
return method == "POST" ? { status: 201, body: { auth_config: { id: "ac_gitea" } } } : { body: { items: [] } };
|
||||
},
|
||||
});
|
||||
|
||||
const started = await composioConnectorProvider({ key: "k", fetchImpl }).startConnect({
|
||||
app: "gitea",
|
||||
user_id: 4,
|
||||
label: "Self-hosted",
|
||||
});
|
||||
|
||||
expect(started.auth_config_id).toBe("ac_gitea");
|
||||
|
||||
const made = calls.find((call) => call.url.pathname.endsWith("/auth_configs") && call.method == "POST")!;
|
||||
|
||||
expect(made.body).toEqual({
|
||||
toolkit: { slug: "gitea" },
|
||||
auth_config: { type: "use_custom_auth", authScheme: "API_KEY" },
|
||||
});
|
||||
|
||||
const session = calls.find((call) => call.url.pathname.endsWith("/tool_router/session"))!;
|
||||
|
||||
expect(session.body.auth_configs).toEqual({ gitea: "ac_gitea" });
|
||||
});
|
||||
|
||||
test("reuses a sign-in setup the toolkit can use, whatever its scheme", async () => {
|
||||
const { fetchImpl, calls } = stub({
|
||||
answer: ({ url }) => {
|
||||
if (url.pathname.endsWith("/toolkits/gitea")) {
|
||||
return { body: { composio_managed_auth_schemes: [], auth_config_details: [{ mode: "API_KEY" }] } };
|
||||
}
|
||||
if (url.pathname.endsWith("/tool_router/session")) return { status: 201, body: { session_id: "trs_1" } };
|
||||
if (url.pathname.endsWith("/link")) {
|
||||
return { status: 201, body: { redirect_url: "https://connect/gitea" } };
|
||||
}
|
||||
|
||||
return { body: { items: [{ id: "ac_dash", auth_scheme: "API_KEY" }] } };
|
||||
},
|
||||
});
|
||||
|
||||
const started = await composioConnectorProvider({ key: "k", fetchImpl }).startConnect({
|
||||
app: "gitea",
|
||||
user_id: 4,
|
||||
label: "Work",
|
||||
});
|
||||
|
||||
expect(started.auth_config_id).toBe("ac_dash");
|
||||
expect(calls.some((call) => call.url.pathname.endsWith("/auth_configs") && call.method == "POST")).toBe(false);
|
||||
});
|
||||
|
||||
test("maps account statuses and keeps the provider's id", async () => {
|
||||
const { fetchImpl } = stub({
|
||||
const { fetchImpl, calls } = stub({
|
||||
answer: () => ({
|
||||
body: {
|
||||
items: [
|
||||
@@ -208,6 +270,9 @@ describe("composioConnectorProvider", () => {
|
||||
{ provider_account_id: "ca_1", status: "connected", label: "work@x" },
|
||||
{ provider_account_id: "ca_2", status: "expired", label: undefined },
|
||||
]);
|
||||
expect(calls[0]!.url.searchParams.get("toolkit_slugs")).toBe("gmail");
|
||||
expect(calls[0]!.url.searchParams.get("user_ids")).toBe("cobble-user-4");
|
||||
expect(calls[0]!.url.searchParams.get("user_id")).toBeNull();
|
||||
});
|
||||
|
||||
test("executes one tool with the account named in the call", async () => {
|
||||
|
||||
@@ -128,29 +128,76 @@ export default function composioConnectorProvider({ key, base_url, fetchImpl }:
|
||||
return items;
|
||||
}
|
||||
|
||||
/**
|
||||
* How a toolkit can be signed in: the schemes Composio manages itself and
|
||||
* every scheme it accepts. Empty when the toolkit can't be read, which
|
||||
* leaves the managed OAuth setup that every OAuth app has.
|
||||
*/
|
||||
async function toolkitAuthMethods({ app }: { app: string }): Promise<{ managed: string[]; schemes: string[] }> {
|
||||
try {
|
||||
const toolkit = await request<any>({
|
||||
path: `/toolkits/${encodeURIComponent(app)}`,
|
||||
what: `the ${app} sign-in methods`,
|
||||
});
|
||||
|
||||
return {
|
||||
managed: (toolkit.composio_managed_auth_schemes || []).map((scheme: string) =>
|
||||
String(scheme).toUpperCase(),
|
||||
),
|
||||
schemes: (toolkit.auth_config_details || [])
|
||||
.map((detail: any) => String(detail.mode || "").toUpperCase())
|
||||
.filter(Boolean),
|
||||
};
|
||||
} catch {
|
||||
return { managed: [], schemes: [] };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The sign-in setup a link belongs to. Composio wants an auth config on
|
||||
* every link, and makes a managed one for a toolkit that has none yet,
|
||||
* so a fresh install can connect an app without visiting its dashboard.
|
||||
* A toolkit Composio manages no credentials for (Gitea, whose key and
|
||||
* instance URL are the user's own) gets a custom setup of its own scheme
|
||||
* instead, which the hosted sign-in page fills in.
|
||||
*/
|
||||
async function authConfigFor({ app, auth_config_id }: { app: string; auth_config_id?: string | null }) {
|
||||
if (auth_config_id) return auth_config_id;
|
||||
|
||||
const existing = await listAllPages<any>({
|
||||
path: "/auth_configs",
|
||||
query: { toolkit_slug: app },
|
||||
what: `the ${app} sign-in setups`,
|
||||
});
|
||||
const usable = existing.find((item) => item.auth_scheme == "OAUTH2") || existing[0];
|
||||
const [existing, methods] = await Promise.all([
|
||||
listAllPages<any>({
|
||||
path: "/auth_configs",
|
||||
query: { toolkit_slug: app },
|
||||
what: `the ${app} sign-in setups`,
|
||||
}),
|
||||
toolkitAuthMethods({ app }),
|
||||
]);
|
||||
const usable = (item: any) =>
|
||||
!methods.schemes.length || methods.schemes.includes(String(item.auth_scheme || "").toUpperCase());
|
||||
const reusable =
|
||||
existing.find((item) => usable(item) && String(item.auth_scheme).toUpperCase() == "OAUTH2") ||
|
||||
existing.find(usable);
|
||||
|
||||
if (usable?.id) return String(usable.id);
|
||||
if (reusable?.id) return String(reusable.id);
|
||||
|
||||
// Nothing known about the toolkit means an OAuth app that Composio
|
||||
// manages, as before.
|
||||
const managed = !methods.schemes.length || methods.managed.length > 0;
|
||||
|
||||
try {
|
||||
const created = await request<any>({
|
||||
path: "/auth_configs",
|
||||
method: "POST",
|
||||
what: `a sign-in setup for ${app}`,
|
||||
body: { toolkit: { slug: app }, auth_scheme: "OAUTH2", use_composio_managed_auth: true },
|
||||
body: managed
|
||||
? {
|
||||
toolkit: { slug: app },
|
||||
auth_scheme: methods.managed.includes("OAUTH2")
|
||||
? "OAUTH2"
|
||||
: methods.managed[0] || "OAUTH2",
|
||||
use_composio_managed_auth: true,
|
||||
}
|
||||
: { toolkit: { slug: app }, auth_config: { type: "use_custom_auth", authScheme: methods.schemes[0] } },
|
||||
});
|
||||
const id = created.auth_config?.id || created.id;
|
||||
|
||||
@@ -246,6 +293,9 @@ export default function composioConnectorProvider({ key, base_url, fetchImpl }:
|
||||
body: {
|
||||
user_id: `cobble-user-${user_id}`,
|
||||
toolkits: { enable: [app] },
|
||||
// The link names no auth config, so the session is what
|
||||
// pins the setup a toolkit with several of them uses.
|
||||
auth_configs: { [app]: config },
|
||||
multi_account: { enable: true, max_accounts_per_toolkit: MaxAccountsPerToolkit },
|
||||
},
|
||||
});
|
||||
@@ -280,7 +330,11 @@ export default function composioConnectorProvider({ key, base_url, fetchImpl }:
|
||||
async accounts({ app, user_id }) {
|
||||
const items = await listAllPages<any>({
|
||||
path: "/connected_accounts",
|
||||
query: { user_id: `cobble-user-${user_id}`, toolkit_slug: app },
|
||||
// The listing filters on the plural names only: `toolkit_slug`
|
||||
// and `user_id` are ignored and answer with the whole
|
||||
// project's accounts, which is how one user's sync took over
|
||||
// another's account.
|
||||
query: { user_ids: `cobble-user-${user_id}`, toolkit_slugs: app },
|
||||
what: `the ${app} accounts`,
|
||||
});
|
||||
|
||||
|
||||
@@ -3,11 +3,11 @@ import type { APIResponseObject } from "@moduletrace/bunext/types";
|
||||
import type { BotIdRequest } from "@/src/schemas/bot-schema";
|
||||
|
||||
/**
|
||||
* A bot's core instructions, for its edit form.
|
||||
* A bot's core instructions and memory, for its panel.
|
||||
*/
|
||||
export default async function fetchBotInstructions({ bot_id }: BotIdRequest) {
|
||||
return await fetchApi<BotIdRequest, APIResponseObject<{ system_prompt: string }>>(
|
||||
return await fetchApi<BotIdRequest, APIResponseObject<{ system_prompt: string; memory: string }>>(
|
||||
`/api/admin/bots/bot-instructions`,
|
||||
{ method: "POST", body: { bot_id } },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -4,23 +4,25 @@ import fetchBotInstructions from "../(functions)/fetch-bot-instructions";
|
||||
type Params = {
|
||||
bot_id: number;
|
||||
/**
|
||||
* Loads each time this turns true (the edit form opens), so the form
|
||||
* starts from what was last saved.
|
||||
* Loads each time this turns true (the panel opens), so its forms start
|
||||
* from what was last saved.
|
||||
*/
|
||||
enabled: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* The bot's core instructions for its edit form, loaded when it opens:
|
||||
* page props leave them out of every bot row.
|
||||
* The bot's core instructions and memory for its panel, loaded when it
|
||||
* opens: page props leave them out of every bot row.
|
||||
*/
|
||||
export default function useBotInstructions({ bot_id, enabled }: Params) {
|
||||
const [system_prompt, setSystemPrompt] = useState<string>();
|
||||
const [memory, setMemory] = useState<string>();
|
||||
const [error, setError] = useState<string>();
|
||||
|
||||
useEffect(() => {
|
||||
/** Cleared on close, so the next open never shows an old copy. */
|
||||
setSystemPrompt(undefined);
|
||||
setMemory(undefined);
|
||||
setError(undefined);
|
||||
|
||||
if (!enabled || !bot_id) return;
|
||||
@@ -33,6 +35,7 @@ export default function useBotInstructions({ bot_id, enabled }: Params) {
|
||||
|
||||
if (res.success && res.singleRes) {
|
||||
setSystemPrompt(res.singleRes.system_prompt);
|
||||
setMemory(res.singleRes.memory);
|
||||
} else {
|
||||
setError(res.msg || "Couldn't load the instructions.");
|
||||
}
|
||||
@@ -46,5 +49,5 @@ export default function useBotInstructions({ bot_id, enabled }: Params) {
|
||||
};
|
||||
}, [enabled, bot_id]);
|
||||
|
||||
return { system_prompt, error };
|
||||
}
|
||||
return { system_prompt, memory, error };
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import { useState } from "react";
|
||||
import Form from "@moduletrace/twui/form/Form";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import CodeEditor from "@/src/components/general/code-editor";
|
||||
import postAdminApi from "@/src/layouts/bots/(functions)/post-admin-api";
|
||||
import AddFormActions from "@/src/layouts/bots/(partials)/add-form-actions";
|
||||
|
||||
type Props = {
|
||||
bot_id: number;
|
||||
bot_name: string;
|
||||
/**
|
||||
* Its core memory, from the panel's read.
|
||||
*/
|
||||
memory: string;
|
||||
/**
|
||||
* Where the conversation is, so its memory there is edited beside it.
|
||||
*/
|
||||
workspace_id?: number | null;
|
||||
workspace_name?: string | null;
|
||||
workspace_memory?: string;
|
||||
onCancel?: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* The bot panel's memory tab: what it keeps in mind everywhere, and (in a
|
||||
* workspace) what it keeps in mind there. Both are markdown, replaced whole;
|
||||
* the bot's memory of each person stays its own.
|
||||
*/
|
||||
export default function BotMemoryForm({
|
||||
bot_id,
|
||||
bot_name,
|
||||
memory,
|
||||
workspace_id,
|
||||
workspace_name,
|
||||
workspace_memory = "",
|
||||
onCancel,
|
||||
}: Props) {
|
||||
const [core, setCore] = useState(memory);
|
||||
const [here, setHere] = useState(workspace_memory);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [saved, setSaved] = useState(false);
|
||||
const [error, setError] = useState<string>();
|
||||
|
||||
const submit = async () => {
|
||||
if (loading) return;
|
||||
if (!window.confirm(`Save ${bot_name}'s memory?`)) return;
|
||||
|
||||
setLoading(true);
|
||||
setError(undefined);
|
||||
setSaved(false);
|
||||
|
||||
try {
|
||||
const coreRes = await postAdminApi({
|
||||
path: "bots/update-bot-memory",
|
||||
body: { bot_id, memory: core },
|
||||
});
|
||||
|
||||
if (!coreRes.success) {
|
||||
setError(coreRes.msg || "Couldn't save its memory.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (workspace_id) {
|
||||
const hereRes = await postAdminApi({
|
||||
path: "workspaces/update-bot",
|
||||
body: { workspace_id, bot_id, memory: here },
|
||||
});
|
||||
|
||||
if (!hereRes.success) {
|
||||
setError(
|
||||
`Saved its memory everywhere, but not in ${workspace_name || "this workspace"}: ${hereRes.msg || "the save failed"}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
setSaved(true);
|
||||
} catch {
|
||||
setError("Couldn't save its memory.");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Form onSubmit={submit} className="w-full gap-4! items-stretch">
|
||||
<CodeEditor
|
||||
title="Memory"
|
||||
content={memory}
|
||||
mode="markdown"
|
||||
placeholder="What it should keep in mind wherever it works..."
|
||||
info={`What ${bot_name} keeps in mind everywhere it works, for everyone. Markdown, replaced whole.`}
|
||||
className="h-52"
|
||||
onChange={(value) => {
|
||||
setCore(value);
|
||||
setSaved(false);
|
||||
}}
|
||||
/>
|
||||
|
||||
{workspace_id ? (
|
||||
<CodeEditor
|
||||
title={`Memory in ${workspace_name || "this workspace"}`}
|
||||
content={workspace_memory}
|
||||
mode="markdown"
|
||||
placeholder="What it should keep in mind here..."
|
||||
info={`What ${bot_name} keeps in mind while it works here, for everyone in this workspace.`}
|
||||
className="h-40"
|
||||
onChange={(value) => {
|
||||
setHere(value);
|
||||
setSaved(false);
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<AddFormActions
|
||||
submit_label="Save"
|
||||
loading={loading}
|
||||
error={error}
|
||||
notice={saved ? "Saved." : undefined}
|
||||
onCancel={onCancel}
|
||||
/>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
type Props = {
|
||||
title: string;
|
||||
/**
|
||||
* One line under the title, saying what the section is.
|
||||
*/
|
||||
description: string;
|
||||
children?: ReactNode;
|
||||
};
|
||||
|
||||
/**
|
||||
* One labelled part of the bot panel's tools tab: what it is, then its
|
||||
* list.
|
||||
*/
|
||||
export default function BotPanelSection({ title, description, children }: Props) {
|
||||
return (
|
||||
<Stack className="w-full gap-1! items-stretch pb-4 border-0 border-b border-solid border-hairline last:border-b-0 last:pb-0">
|
||||
<Span className="text-[13px] leading-[18px] font-bold text-ink">{title}</Span>
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">{description}</Span>
|
||||
{children}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useContext, useEffect } from "react";
|
||||
import { useContext, useEffect, useState } from "react";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import H2 from "@moduletrace/twui/layout/H2";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
@@ -10,19 +10,29 @@ import Loading from "@moduletrace/twui/elements/Loading";
|
||||
import { X } from "lucide-react";
|
||||
import SidePanel from "@/src/components/general/side-panel";
|
||||
import BotAvatar from "@/src/components/general/bot-avatar";
|
||||
import TabButton from "@/src/components/general/tab-button";
|
||||
import type { BotFace } from "@/src/dict/bot-dict";
|
||||
import botStoneProps from "@/src/utils/bot-stone-props";
|
||||
import { BotPanelOpenEvent } from "@/src/utils/bot-panel-open-event";
|
||||
import type { BotWithLastMessage } from "@/src/types";
|
||||
import type { BUN_SQLITE_COBBLE_WORKSPACES } from "@/db/types/db";
|
||||
import BotForm from "@/src/layouts/bots/(partials)/bot-form";
|
||||
import { AppContext } from "@/src/pages/__root";
|
||||
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
|
||||
import useTopModalEscape from "@/src/hooks/use-top-modal-escape";
|
||||
import useBotInstructions from "../(hooks)/use-bot-instructions";
|
||||
import useWorkspaceBotInstructions from "../(hooks)/use-workspace-bot-instructions";
|
||||
import BotMemoryForm from "./bot-memory-form";
|
||||
import BotPanelTrigger from "./bot-panel-trigger";
|
||||
import BotToolsTab from "./bot-tools-tab";
|
||||
|
||||
type Props = {
|
||||
bot: BotWithLastMessage;
|
||||
/**
|
||||
* The workspace the conversation is in, so its memory and instructions
|
||||
* there are edited too.
|
||||
*/
|
||||
workspace?: BUN_SQLITE_COBBLE_WORKSPACES | null;
|
||||
/**
|
||||
* The header owns it, since the avatar and the name both open the panel.
|
||||
*/
|
||||
@@ -31,22 +41,37 @@ type Props = {
|
||||
on_close: () => void;
|
||||
};
|
||||
|
||||
type PanelTab = "settings" | "memory" | "tools";
|
||||
|
||||
/**
|
||||
* The bot's profile (picture, name, job, colour, instructions) to edit,
|
||||
* sliding in from the right over the conversation, for super admins and
|
||||
* admins. The avatar and the name beside it open it, and so does a swipe from
|
||||
* the right on a phone (`BotPanelOpenEvent`, sent by the layout, so a page
|
||||
* without a conversation has nobody listening). The instructions load when
|
||||
* it opens, and Escape, the backdrop or the X closes it.
|
||||
* The bot's profile (picture, name, job, colour, instructions), its memory
|
||||
* and what it works with (computer, tools, knowledgebases) to edit, sliding
|
||||
* in from the right over the conversation, for super admins and admins. The
|
||||
* avatar and the name beside it open it, and so does a swipe from the right
|
||||
* on a phone (`BotPanelOpenEvent`, sent by the layout, so a page without a
|
||||
* conversation has nobody listening). The tab's data loads when it opens,
|
||||
* and Escape, the backdrop or the X closes it.
|
||||
*/
|
||||
export default function BotPanel({ bot, open, on_open, on_close }: Props) {
|
||||
export default function BotPanel({ bot, workspace, open, on_open, on_close }: Props) {
|
||||
const { pageProps } = useContext(AppContext);
|
||||
const name = bot.name || "This bot";
|
||||
const can_edit = canManageCrew({ user_types: pageProps?.user_types });
|
||||
const { system_prompt, error } = useBotInstructions({
|
||||
const [tab, setTab] = useState<PanelTab>("settings");
|
||||
const workspace_id = Number(workspace?.id) || 0;
|
||||
const { system_prompt, memory, error } = useBotInstructions({
|
||||
bot_id: Number(bot.id) || 0,
|
||||
enabled: open && can_edit,
|
||||
});
|
||||
const workspace_instructions = useWorkspaceBotInstructions({
|
||||
workspace_id,
|
||||
bot_id: Number(bot.id) || 0,
|
||||
enabled: open && can_edit && Boolean(workspace_id) && tab == "memory",
|
||||
});
|
||||
const memory_ready =
|
||||
system_prompt != undefined &&
|
||||
memory != undefined &&
|
||||
(!workspace_id || Boolean(workspace_instructions.instructions));
|
||||
const loaded_error = error || workspace_instructions.error;
|
||||
|
||||
useTopModalEscape({ onClose: on_close, enabled: open });
|
||||
|
||||
@@ -101,26 +126,74 @@ export default function BotPanel({ bot, open, on_open, on_close }: Props) {
|
||||
<X size={18} aria-hidden />
|
||||
</Button>
|
||||
</Row>
|
||||
<Row
|
||||
role="tablist"
|
||||
aria-label={`Edit ${name}`}
|
||||
className="shrink-0 gap-1! flex-nowrap items-center px-3 py-2 border-0 border-b border-solid border-hairline"
|
||||
>
|
||||
<TabButton title="Settings" active={tab == "settings"} onPick={() => setTab("settings")} />
|
||||
<TabButton title="Memory" active={tab == "memory"} onPick={() => setTab("memory")} />
|
||||
<TabButton title="Tools" active={tab == "tools"} onPick={() => setTab("tools")} />
|
||||
</Row>
|
||||
<Stack className="grow min-h-0 overflow-y-auto gap-1! items-stretch px-4 pt-4 pb-6">
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
{bot.kind == "coordinator"
|
||||
? "The coordinator keeps its name. Give it a picture, or change its core instructions."
|
||||
: `${name}'s core instructions apply everywhere. What it does in one workspace is under Instructions here in the menu of its conversation there.`}
|
||||
</Span>
|
||||
{!open ? null : system_prompt != undefined ? (
|
||||
<BotForm
|
||||
bot={{ ...bot, system_prompt }}
|
||||
onCancel={on_close}
|
||||
{open && tab == "settings" ? (
|
||||
<>
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
{bot.kind == "coordinator"
|
||||
? "The coordinator keeps its name. Give it a picture, or change its core instructions."
|
||||
: `${name}'s core instructions apply everywhere. What it does in one workspace is under Instructions here in the menu of its conversation there.`}
|
||||
</Span>
|
||||
{system_prompt != undefined ? (
|
||||
<BotForm
|
||||
bot={{ ...bot, system_prompt }}
|
||||
onCancel={on_close}
|
||||
/>
|
||||
) : loaded_error ? (
|
||||
<Span className="py-6 text-[13px] leading-[18px] text-ink-secondary">
|
||||
{loaded_error}
|
||||
</Span>
|
||||
) : (
|
||||
<Stack className="w-full py-10 items-center">
|
||||
<Loading />
|
||||
</Stack>
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
{open && tab == "memory" ? (
|
||||
memory_ready ? (
|
||||
<>
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
{`What ${name} keeps in mind, and can add to itself as it works.`}
|
||||
</Span>
|
||||
<BotMemoryForm
|
||||
bot_id={Number(bot.id) || 0}
|
||||
bot_name={name}
|
||||
memory={memory || ""}
|
||||
workspace_id={workspace_id || undefined}
|
||||
workspace_name={workspace?.name}
|
||||
workspace_memory={workspace_instructions.instructions?.memory || ""}
|
||||
onCancel={on_close}
|
||||
/>
|
||||
</>
|
||||
) : loaded_error ? (
|
||||
<Span className="py-6 text-[13px] leading-[18px] text-ink-secondary">
|
||||
{loaded_error}
|
||||
</Span>
|
||||
) : (
|
||||
<Stack className="w-full py-10 items-center">
|
||||
<Loading />
|
||||
</Stack>
|
||||
)
|
||||
) : null}
|
||||
{open && tab == "tools" ? (
|
||||
<BotToolsTab
|
||||
bot={bot}
|
||||
workspace_id={workspace_id || null}
|
||||
initial={pageProps?.bot_extensions}
|
||||
has_browsers={Boolean(pageProps?.has_browsers)}
|
||||
open={open && tab == "tools"}
|
||||
/>
|
||||
) : error ? (
|
||||
<Span className="py-6 text-[13px] leading-[18px] text-ink-secondary">
|
||||
{error}
|
||||
</Span>
|
||||
) : (
|
||||
<Stack className="w-full py-10 items-center">
|
||||
<Loading />
|
||||
</Stack>
|
||||
)}
|
||||
) : null}
|
||||
</Stack>
|
||||
</SidePanel>
|
||||
</>
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
import { useContext } from "react";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import useExtensions from "@/src/hooks/use-extensions";
|
||||
import type {
|
||||
BotExtensionsPayload,
|
||||
BotWithLastMessage,
|
||||
} from "@/src/types";
|
||||
import { BotComputersContext } from "../(data)/bot-computers-context";
|
||||
import {
|
||||
composerKnowledgebasesCopy,
|
||||
composerToolsCopy,
|
||||
} from "../(data)/composer-extensions-copy";
|
||||
import BotComputerOption from "./bot-computer-option";
|
||||
import BotPanelSection from "./bot-panel-section";
|
||||
import ComposerBrowserButton from "./composer-browser-button";
|
||||
import ComposerConnectorsSection from "./composer-connectors-section";
|
||||
import ComposerExtensionsList from "./composer-extensions-list";
|
||||
|
||||
type Props = {
|
||||
bot: BotWithLastMessage;
|
||||
workspace_id?: number | null;
|
||||
initial?: BotExtensionsPayload | null;
|
||||
/**
|
||||
* Whether the user has a browser of their own; without one there is
|
||||
* nothing to pick.
|
||||
*/
|
||||
has_browsers?: boolean;
|
||||
/**
|
||||
* Whether the tab is on show, so its connectors are read then and its
|
||||
* computer switches show.
|
||||
*/
|
||||
open: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* The bot panel's third tab: where it works and what it can use there - its
|
||||
* computer, the MCP servers, tools and skills it was given (the apps its
|
||||
* connectors reach for you among them), its knowledgebases, and which of
|
||||
* your browsers it acts as you in.
|
||||
*/
|
||||
export default function BotToolsTab({ bot, workspace_id, initial, has_browsers, open }: Props) {
|
||||
const bot_name = bot.name || "this bot";
|
||||
const extensions = useExtensions({
|
||||
owner: { bot_id: bot.id || 0, workspace_id },
|
||||
owner_name: bot_name,
|
||||
initial,
|
||||
});
|
||||
const { computers, switching_id, error: computer_error, switchComputer, openComputer } =
|
||||
useContext(BotComputersContext);
|
||||
|
||||
const is_knowledge = (item: { kind: string }) => item.kind == "knowledgebase";
|
||||
const tools = {
|
||||
attached: extensions.attached.filter((item) => !is_knowledge(item)),
|
||||
addable: extensions.addable.filter((item) => !is_knowledge(item)),
|
||||
};
|
||||
const knowledge = {
|
||||
attached: extensions.attached.filter(is_knowledge),
|
||||
addable: extensions.addable.filter(is_knowledge),
|
||||
};
|
||||
const tools_copy = composerToolsCopy({ bot_name });
|
||||
const knowledge_copy = composerKnowledgebasesCopy({ bot_name });
|
||||
|
||||
return (
|
||||
<Stack className="w-full gap-4! items-stretch">
|
||||
<BotPanelSection
|
||||
title="Computer"
|
||||
description={`A computer is a sandbox ${bot_name} works in: a shell, a browser and files of its own. Its tasks run on the checked one. Open one to use it yourself.`}
|
||||
>
|
||||
{computers.length ? (
|
||||
<Stack
|
||||
role="radiogroup"
|
||||
aria-label={`${bot_name}'s computers`}
|
||||
className="w-full mt-2 py-1 gap-0! items-stretch rounded-default border border-solid border-hairline bg-surface"
|
||||
>
|
||||
{computers.map((computer, index) => (
|
||||
<BotComputerOption
|
||||
key={computer.id}
|
||||
computer={computer}
|
||||
current={index == 0}
|
||||
onPick={async () => {
|
||||
await switchComputer({ computer_id: computer.id || 0 });
|
||||
}}
|
||||
onOpen={() => {
|
||||
openComputer({ computer_id: computer.id || 0 });
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</Stack>
|
||||
) : (
|
||||
<Span className="mt-2 text-[13px] leading-[18px] text-ink-secondary">
|
||||
{`No computer is set up for ${bot_name} yet.`}
|
||||
</Span>
|
||||
)}
|
||||
{switching_id ? (
|
||||
<Span className="mt-2 text-[13px] leading-[18px] text-ink-secondary">
|
||||
Switching its computer. The tasks it has open finish where they are.
|
||||
</Span>
|
||||
) : null}
|
||||
{computer_error ? (
|
||||
<Span role="alert" className="mt-2 text-[13px] leading-[18px] text-ink-secondary">
|
||||
{computer_error}
|
||||
</Span>
|
||||
) : null}
|
||||
</BotPanelSection>
|
||||
|
||||
<BotPanelSection title="Tools" description={tools_copy.some}>
|
||||
<ComposerExtensionsList
|
||||
id="panel-add-extension"
|
||||
label={tools_copy.title}
|
||||
items={tools.attached}
|
||||
addable={tools.addable}
|
||||
can_manage={extensions.can_manage}
|
||||
busy={extensions.busy}
|
||||
empty={tools_copy.none}
|
||||
add_hint={tools_copy.add_hint}
|
||||
add_noun={tools_copy.add_noun}
|
||||
onAdd={extensions.add}
|
||||
onRemove={extensions.remove}
|
||||
/>
|
||||
<ComposerConnectorsSection
|
||||
bot_id={bot.id || 0}
|
||||
workspace_id={workspace_id}
|
||||
open={open}
|
||||
/>
|
||||
{has_browsers ? (
|
||||
<Stack className="w-full mt-4 gap-2! items-start">
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
{`Which of your browsers ${bot_name} acts as you in.`}
|
||||
</Span>
|
||||
<ComposerBrowserButton
|
||||
bot_id={bot.id || 0}
|
||||
bot_name={bot_name}
|
||||
workspace_id={workspace_id}
|
||||
/>
|
||||
</Stack>
|
||||
) : null}
|
||||
</BotPanelSection>
|
||||
|
||||
<BotPanelSection title="Knowledgebases" description={knowledge_copy.some}>
|
||||
<ComposerExtensionsList
|
||||
id="panel-add-knowledgebase"
|
||||
label={knowledge_copy.title}
|
||||
items={knowledge.attached}
|
||||
addable={knowledge.addable}
|
||||
can_manage={extensions.can_manage}
|
||||
busy={extensions.busy}
|
||||
empty={knowledge_copy.none}
|
||||
add_hint={knowledge_copy.add_hint}
|
||||
add_noun={knowledge_copy.add_noun}
|
||||
onAdd={extensions.add}
|
||||
onRemove={extensions.remove}
|
||||
/>
|
||||
</BotPanelSection>
|
||||
|
||||
{extensions.status?.error ? (
|
||||
<Span role="alert" className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
{extensions.status.msg}
|
||||
</Span>
|
||||
) : null}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import ExtensionAddSelect from "@/src/components/general/extension-add-select";
|
||||
import type {
|
||||
BotExtension,
|
||||
BotExtensionKind,
|
||||
BotExtensionsPayload,
|
||||
} from "@/src/types";
|
||||
import ComposerToolRow from "./composer-tool-row";
|
||||
|
||||
type Props = {
|
||||
/**
|
||||
* The add picker's element id, unique on the page.
|
||||
*/
|
||||
id: string;
|
||||
/**
|
||||
* What the list is, for screen readers.
|
||||
*/
|
||||
label: string;
|
||||
items: BotExtension[];
|
||||
addable: BotExtensionsPayload["addable"];
|
||||
can_manage: boolean;
|
||||
/**
|
||||
* The extension being changed, as `kind:id`.
|
||||
*/
|
||||
busy?: string;
|
||||
/**
|
||||
* Said instead of the list when it holds nothing.
|
||||
*/
|
||||
empty?: string;
|
||||
add_hint: string;
|
||||
add_noun: string;
|
||||
onAdd: (params: { kind: BotExtensionKind; id: number }) => Promise<boolean>;
|
||||
onRemove: (params: {
|
||||
kind: BotExtensionKind;
|
||||
id: number;
|
||||
name: string;
|
||||
}) => Promise<boolean>;
|
||||
};
|
||||
|
||||
/**
|
||||
* What a bot can use here as a list, then the picker for more: shared by
|
||||
* the composer's modals and the bot panel's tools tab. Super admins and
|
||||
* admins take away any it was given (even one every bot started with); a
|
||||
* workspace's own stay.
|
||||
*/
|
||||
export default function ComposerExtensionsList({
|
||||
id,
|
||||
label,
|
||||
items,
|
||||
addable,
|
||||
can_manage,
|
||||
busy,
|
||||
empty,
|
||||
add_hint,
|
||||
add_noun,
|
||||
onAdd,
|
||||
onRemove,
|
||||
}: Props) {
|
||||
return (
|
||||
<>
|
||||
{items.length ? (
|
||||
<Stack
|
||||
aria-label={label}
|
||||
className="w-full mt-4 py-1 gap-0! items-stretch rounded-default border border-solid border-hairline bg-surface"
|
||||
>
|
||||
{items.map((item) => (
|
||||
<ComposerToolRow
|
||||
key={`${item.kind}:${item.id}`}
|
||||
item={item}
|
||||
busy={busy == `${item.kind}:${item.id}`}
|
||||
onRemove={
|
||||
can_manage && item.source == "bot"
|
||||
? () =>
|
||||
onRemove({
|
||||
kind: item.kind,
|
||||
id: item.id,
|
||||
name: item.name,
|
||||
})
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</Stack>
|
||||
) : empty ? (
|
||||
<Span className="mt-4 text-[13px] leading-[18px] text-ink-secondary">{empty}</Span>
|
||||
) : null}
|
||||
|
||||
{can_manage && addable.length ? (
|
||||
<Stack className="w-full mt-4 gap-2! items-stretch">
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">{add_hint}</Span>
|
||||
<ExtensionAddSelect
|
||||
id={id}
|
||||
noun={add_noun}
|
||||
addable={addable}
|
||||
loading={Boolean(busy)}
|
||||
onAdd={onAdd}
|
||||
/>
|
||||
</Stack>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -7,7 +7,6 @@ import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { CircleAlert, type LucideIcon } from "lucide-react";
|
||||
import ExtensionAddSelect from "@/src/components/general/extension-add-select";
|
||||
import type {
|
||||
BotExtension,
|
||||
BotExtensionKind,
|
||||
@@ -15,7 +14,7 @@ import type {
|
||||
ConnectorAppIcon,
|
||||
} from "@/src/types";
|
||||
import ComposerConnectorsSection from "./composer-connectors-section";
|
||||
import ComposerToolRow from "./composer-tool-row";
|
||||
import ComposerExtensionsList from "./composer-extensions-list";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
/**
|
||||
@@ -168,45 +167,18 @@ export default function ComposerToolsModal({
|
||||
</Span>
|
||||
</Stack>
|
||||
|
||||
{count ? (
|
||||
<Stack
|
||||
aria-label={copy.title}
|
||||
className="w-full mt-4 py-1 gap-0! items-stretch rounded-default border border-solid border-hairline bg-surface"
|
||||
>
|
||||
{attached.map((item) => (
|
||||
<ComposerToolRow
|
||||
key={`${item.kind}:${item.id}`}
|
||||
item={item}
|
||||
busy={busy == `${item.kind}:${item.id}`}
|
||||
onRemove={
|
||||
can_manage && item.source == "bot"
|
||||
? () =>
|
||||
onRemove({
|
||||
kind: item.kind,
|
||||
id: item.id,
|
||||
name: item.name,
|
||||
})
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</Stack>
|
||||
) : null}
|
||||
|
||||
{can_manage && addable.length ? (
|
||||
<Stack className="w-full mt-4 gap-2! items-stretch">
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
{copy.add_hint}
|
||||
</Span>
|
||||
<ExtensionAddSelect
|
||||
id={copy.id}
|
||||
noun={copy.add_noun}
|
||||
addable={addable}
|
||||
loading={Boolean(busy)}
|
||||
onAdd={onAdd}
|
||||
/>
|
||||
</Stack>
|
||||
) : null}
|
||||
<ComposerExtensionsList
|
||||
id={copy.id}
|
||||
label={copy.title}
|
||||
items={attached}
|
||||
addable={addable}
|
||||
can_manage={can_manage}
|
||||
busy={busy}
|
||||
add_hint={copy.add_hint}
|
||||
add_noun={copy.add_noun}
|
||||
onAdd={onAdd}
|
||||
onRemove={onRemove}
|
||||
/>
|
||||
|
||||
{connectors ? (
|
||||
<ComposerConnectorsSection
|
||||
|
||||
@@ -108,6 +108,7 @@ export default function ConversationHeader({
|
||||
{is_workspace ? <BackButton /> : null}
|
||||
<BotPanel
|
||||
bot={bot}
|
||||
workspace={workspace}
|
||||
open={bot_panel_open}
|
||||
on_open={open_bot_panel}
|
||||
on_close={close_bot_panel}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import isCrewMessage from "@/src/utils/is-crew-message";
|
||||
import { lazy, Suspense, useContext, useEffect, useMemo, useRef, useState } from "react";
|
||||
import awaitsReply from "../(utils)/awaits-reply";
|
||||
import planMarksReplyDue from "../(utils)/plan-marks-reply-due";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import type { BotMessageReactionEmoji } from "@/src/dict/bot-dict";
|
||||
import type {
|
||||
@@ -336,7 +337,19 @@ export default function Conversation() {
|
||||
on_open_jobs: () => setOpenReplyJobs(1),
|
||||
});
|
||||
|
||||
useSessionPlan({ session_id, on_change: setSessionPlan });
|
||||
/**
|
||||
* An active plan has a step reply on its way, queued by the app with no
|
||||
* user message before it: mark it due here so the thinking row stands at
|
||||
* once instead of waiting for the run's first step push.
|
||||
*/
|
||||
useSessionPlan({
|
||||
session_id,
|
||||
on_change: (plan) => {
|
||||
setSessionPlan(plan);
|
||||
|
||||
if (planMarksReplyDue({ plan })) setOpenReplyJobs(1);
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* The thread's pull-to-reload: the page's crew read again (the layout
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import type { BotPlanView } from "@/src/types";
|
||||
import planMarksReplyDue from "./plan-marks-reply-due";
|
||||
|
||||
const plan = (status: BotPlanView["status"]) => ({ id: 7, status }) as BotPlanView;
|
||||
|
||||
describe("planMarksReplyDue", () => {
|
||||
test("a plan that started has a step reply on its way", () => {
|
||||
expect(planMarksReplyDue({ plan: plan("active") })).toBe(true);
|
||||
});
|
||||
|
||||
test("approving is what starts it: one waiting for the user does not", () => {
|
||||
expect(planMarksReplyDue({ plan: plan("planned") })).toBe(false);
|
||||
});
|
||||
|
||||
test("a plan stopped between steps has nothing on its way", () => {
|
||||
expect(planMarksReplyDue({ plan: plan("paused") })).toBe(false);
|
||||
expect(planMarksReplyDue({ plan: plan("done") })).toBe(false);
|
||||
expect(planMarksReplyDue({ plan: plan("cancelled") })).toBe(false);
|
||||
});
|
||||
|
||||
test("no plan in the conversation at all is no reply", () => {
|
||||
expect(planMarksReplyDue({ plan: null })).toBe(false);
|
||||
expect(planMarksReplyDue({})).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { BotPlanView } from "@/src/types";
|
||||
|
||||
type Params = {
|
||||
plan?: BotPlanView | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether this plan change means a reply is on its way in its conversation.
|
||||
* An active plan is one the app advances by itself: approving it, picking it
|
||||
* back up or finishing a step queues the next step with no user message
|
||||
* before it, so the thread must show the thinking row at once instead of
|
||||
* waiting for the run's first step push.
|
||||
*/
|
||||
export default function planMarksReplyDue({ plan }: Params) {
|
||||
return plan?.status == "active";
|
||||
}
|
||||
@@ -107,7 +107,7 @@ export default function ConnectorAccessModal({
|
||||
setOpen={(next) => !next && onCancel()}
|
||||
title={`Who gets ${connector.name}`}
|
||||
description={
|
||||
"A bot picked here is yours: it reaches the connector only in your runs there. A workspace reaches everyone working in it; every bot reaches the whole install."
|
||||
"A bot picked here is yours: it reaches the connector only in your runs there, with your own accounts. A workspace reaches everyone working in it, with every account connected for this connector. Every bot reaches the whole install, each user with their own accounts."
|
||||
}
|
||||
>
|
||||
<Form
|
||||
|
||||
@@ -80,7 +80,7 @@ export default function ConnectorConnectionModal({ connection, onSaved, onCancel
|
||||
description={
|
||||
connection
|
||||
? "Renaming keeps its apps. A new key lists them again."
|
||||
: "Each connection is one provider account with its own key, so a work account and a personal one live side by side. Once saved, every app that key holds is listed here: give one to every bot, a workspace or your own runs, and each person signs in to their own account for it."
|
||||
: "Each connection is one provider account with its own key, so a work account and a personal one live side by side. Once saved, every app that key holds is listed here: give one to every bot, a workspace or your own runs, and a workspace's apps use every account connected for them, whoever connected them."
|
||||
}
|
||||
>
|
||||
<Form className="w-full gap-4! items-stretch pt-4" onSubmit={submit}>
|
||||
|
||||
@@ -75,7 +75,7 @@ export default function ConnectorAppsSection() {
|
||||
return (
|
||||
<SettingsShell
|
||||
title={connection.name}
|
||||
description={`The apps ${connection.name} offers. Give one to every bot, to a workspace, or to your own runs on a bot; each person then signs in to their own account for it.`}
|
||||
description={`The apps ${connection.name} offers. Give one to every bot, to a workspace, or to your own runs on a bot; a workspace uses every account connected for that app, whoever connected it.`}
|
||||
>
|
||||
<Row className="w-full items-center gap-2!">
|
||||
<Link href="/admin/settings/connectors" className="text-sm">
|
||||
|
||||
@@ -46,7 +46,7 @@ export default function ConnectorsSettingsSection() {
|
||||
return (
|
||||
<SettingsGroup
|
||||
title="Connectors"
|
||||
description="Connect a paradigm once and every app it offers is listed under it. Open a connection to search its apps and give one to every bot, to a workspace, or to your own runs on a bot; each person then signs in to their own account for it."
|
||||
description="Connect a paradigm once and every app it offers is listed under it. Open a connection to search its apps and give one to every bot, to a workspace, or to your own runs on a bot; a workspace uses every account connected for that app, whoever connected it."
|
||||
>
|
||||
<SettingsList is_empty={!connections.length} empty="No connectors yet">
|
||||
{connections.map((connection) => (
|
||||
|
||||
@@ -11,12 +11,12 @@ import type {
|
||||
} from "@moduletrace/bunext/types";
|
||||
|
||||
/**
|
||||
* A bot's core instructions, for its edit form in the conversation, which
|
||||
* loads them when it opens (page props leave them out). For super admins
|
||||
* and admins; only the super admin reaches the coordinator.
|
||||
* A bot's core instructions and memory, for its panel in the conversation,
|
||||
* which loads them when it opens (page props leave them out). For super
|
||||
* admins and admins; only the super admin reaches the coordinator.
|
||||
*/
|
||||
export const handler: BunextAPIRouteHandler<
|
||||
APIResponseObject<{ system_prompt: string }>
|
||||
APIResponseObject<{ system_prompt: string; memory: string }>
|
||||
> = async ({ req, body }) => {
|
||||
try {
|
||||
if (req.method != "POST") {
|
||||
@@ -40,7 +40,7 @@ export const handler: BunextAPIRouteHandler<
|
||||
throw new AppError(`Bot not found.`);
|
||||
}
|
||||
|
||||
return { success: true, singleRes: { system_prompt: bot.system_prompt || "" } };
|
||||
return { success: true, singleRes: { system_prompt: bot.system_prompt || "", memory: bot.memory || "" } };
|
||||
} catch (error: unknown) {
|
||||
return { success: false, msg: safeErrorMessage({ error }) };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import userAuth from "@/src/functions/backend/auth/user-auth";
|
||||
import updateBotMemory from "@/src/functions/backend/db/bots/update-bot-memory";
|
||||
import logEvent, { grabRequestIP } from "@/src/functions/backend/logger";
|
||||
import { UpdateBotMemoryRequestSchema } from "@/src/schemas/bot-schema";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import parseWithSchema from "@/src/utils/parse-with-schema";
|
||||
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
|
||||
import isReadOnlyUser from "@/src/utils/rbac/is-read-only-user";
|
||||
import safeErrorMessage from "@/src/utils/safe-error-message";
|
||||
import type {
|
||||
APIResponseObject,
|
||||
BunextAPIRouteHandler,
|
||||
} from "@moduletrace/bunext/types";
|
||||
|
||||
/**
|
||||
* Replaces a bot's core memory from its panel (the memory tab), for super
|
||||
* admins and admins. Its memory of each user and its memory in a workspace
|
||||
* are separate rows.
|
||||
*/
|
||||
export const handler: BunextAPIRouteHandler<APIResponseObject> = async ({ req, body }) => {
|
||||
try {
|
||||
if (req.method != "POST") {
|
||||
throw new AppError(`Method not allowed`);
|
||||
}
|
||||
|
||||
const { user, user_types } = await userAuth({ req });
|
||||
|
||||
if (!user?.logged_in_status || !user.id) {
|
||||
return { success: false, msg: `Unauthorized`, logoutUser: true };
|
||||
}
|
||||
|
||||
if (isReadOnlyUser({ user_types: user_types || [] })) {
|
||||
throw new AppError(`This user can only read records.`);
|
||||
}
|
||||
|
||||
if (!canManageCrew({ user_types })) {
|
||||
throw new AppError(`Only an admin can edit a bot.`);
|
||||
}
|
||||
|
||||
const { bot_id, memory } = parseWithSchema({
|
||||
schema: UpdateBotMemoryRequestSchema,
|
||||
data: body,
|
||||
});
|
||||
|
||||
await updateBotMemory({ user_id: user.id, bot_id, memory });
|
||||
|
||||
await logEvent({
|
||||
title: "Bot memory changed",
|
||||
category: "system",
|
||||
user_id: user.id,
|
||||
plain_text: `User #${user.id} edited bot #${bot_id}'s memory.`,
|
||||
metadata: { bot_id },
|
||||
ip_address: grabRequestIP(req),
|
||||
});
|
||||
|
||||
return { success: true, msg: `Saved.` };
|
||||
} catch (error: unknown) {
|
||||
return { success: false, msg: safeErrorMessage({ error }) };
|
||||
}
|
||||
};
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { MessageDetailsRequestSchema } from "./bot-schema";
|
||||
import { MessageDetailsRequestSchema, UpdateBotMemoryRequestSchema } from "./bot-schema";
|
||||
|
||||
describe("MessageDetailsRequestSchema", () => {
|
||||
test("asks for the modal's calls by default", () => {
|
||||
@@ -21,3 +21,21 @@ describe("MessageDetailsRequestSchema", () => {
|
||||
expect(MessageDetailsRequestSchema.safeParse({}).success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("UpdateBotMemoryRequestSchema", () => {
|
||||
test("takes the whole new memory", () => {
|
||||
expect(UpdateBotMemoryRequestSchema.parse({ bot_id: "3", memory: "It writes short." })).toEqual({
|
||||
bot_id: 3,
|
||||
memory: "It writes short.",
|
||||
});
|
||||
});
|
||||
|
||||
test("allows clearing it", () => {
|
||||
expect(UpdateBotMemoryRequestSchema.parse({ bot_id: 3, memory: "" }).memory).toBe("");
|
||||
});
|
||||
|
||||
test("refuses a bot or a memory that isn't there", () => {
|
||||
expect(UpdateBotMemoryRequestSchema.safeParse({ bot_id: 3 }).success).toBe(false);
|
||||
expect(UpdateBotMemoryRequestSchema.safeParse({ bot_id: 0, memory: "x" }).success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -234,6 +234,19 @@ export const UpdateBotRequestSchema = CreateBotRequestSchema.omit({ workspace_id
|
||||
|
||||
export type UpdateBotRequest = z.infer<typeof UpdateBotRequestSchema>;
|
||||
|
||||
/**
|
||||
* The bot's core memory, edited from its panel: the whole new text.
|
||||
*/
|
||||
export const UpdateBotMemoryRequestSchema = z.object({
|
||||
bot_id: z.coerce.number().int().positive("Pick a bot"),
|
||||
memory: z
|
||||
.string()
|
||||
.trim()
|
||||
.max(AppData.PromptMaxLength, `Keep memory under ${AppData.PromptMaxLength} characters`),
|
||||
});
|
||||
|
||||
export type UpdateBotMemoryRequest = z.infer<typeof UpdateBotMemoryRequestSchema>;
|
||||
|
||||
export const UploadBotAttachmentRequestSchema = z.object({
|
||||
/**
|
||||
* The file as a base64 data URL.
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { UpdateWorkspaceBotRequestSchema } from "./workspace-schema";
|
||||
|
||||
describe("UpdateWorkspaceBotRequestSchema", () => {
|
||||
test("leaves the fields it wasn't given alone", () => {
|
||||
const parsed = UpdateWorkspaceBotRequestSchema.parse({ workspace_id: "2", bot_id: "5", memory: "Short here." });
|
||||
|
||||
expect(parsed).toEqual({ workspace_id: 2, bot_id: 5, memory: "Short here." });
|
||||
expect("system_prompt" in parsed).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -32,9 +32,13 @@ export const WorkspaceBotRequestSchema = z.object({
|
||||
|
||||
export type WorkspaceBotRequest = z.infer<typeof WorkspaceBotRequestSchema>;
|
||||
|
||||
/**
|
||||
* Either one alone: the bot panel's memory tab saves the workspace memory
|
||||
* without rewriting the instructions here, and vice versa.
|
||||
*/
|
||||
export const UpdateWorkspaceBotRequestSchema = WorkspaceBotRequestSchema.extend({
|
||||
system_prompt: Prompt.default(""),
|
||||
memory: Prompt.default(""),
|
||||
system_prompt: Prompt.optional(),
|
||||
memory: Prompt.optional(),
|
||||
});
|
||||
|
||||
export type UpdateWorkspaceBotRequest = z.infer<typeof UpdateWorkspaceBotRequestSchema>;
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import connectorAccountReachSql from "./connector-account-reach-sql";
|
||||
|
||||
describe("connectorAccountReachSql", () => {
|
||||
test("a connector given to a workspace hands every connected account of it to that workspace", () => {
|
||||
const { sql, values } = connectorAccountReachSql({ workspace_id: 4 });
|
||||
|
||||
expect(sql).toContain("SELECT 1 FROM workspace_connectors wc");
|
||||
expect(sql).toContain("wc.connector_id = a.connector_id");
|
||||
expect(sql).toContain("wc.workspace_id = ?");
|
||||
expect(values).toEqual([4]);
|
||||
});
|
||||
|
||||
test("the global scope brings no accounts, only the workspace grant does", () => {
|
||||
expect(connectorAccountReachSql({ workspace_id: 4 }).sql).not.toContain("all_bots");
|
||||
});
|
||||
|
||||
test("a run outside a workspace gets no clause", () => {
|
||||
expect(connectorAccountReachSql({})).toEqual({ sql: "", values: [] });
|
||||
expect(connectorAccountReachSql({ workspace_id: null })).toEqual({ sql: "", values: [] });
|
||||
expect(connectorAccountReachSql({ workspace_id: 0 })).toEqual({ sql: "", values: [] });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
type Params = {
|
||||
workspace_id?: number | string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The extra account clause a workspace brings: a connector given to a
|
||||
* workspace reaches everyone working in it, so every connected account of
|
||||
* that connector does too, whoever connected it. Empty outside a workspace,
|
||||
* and the global scope brings no accounts (only the workspace grant does).
|
||||
*/
|
||||
export default function connectorAccountReachSql({ workspace_id }: Params): { sql: string; values: number[] } {
|
||||
if (!workspace_id) return { sql: "", values: [] };
|
||||
|
||||
return {
|
||||
sql: `OR EXISTS (SELECT 1 FROM workspace_connectors wc WHERE wc.connector_id = a.connector_id AND wc.workspace_id = ?)`,
|
||||
values: [Number(workspace_id)],
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user