Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(entitlement): restrict agent invocation members, runtime member sharing and team Apps accounts by plan (MUL-9491) (#11035)
Multica Eve920e5231b785
diff --git a/apps/docs/content/docs/agents-create.fr.mdx b/apps/docs/content/docs/agents-create.fr.mdxindex b7ba7c99f4..314ad1f42a 100644--- a/apps/docs/content/docs/agents-create.fr.mdx+++ b/apps/docs/content/docs/agents-create.fr.mdx@@ -106,6 +106,8 @@ L'Accès détermine quels membres peuvent exécuter cet agent (l'assigner, l'@me+Sur Multica Cloud, **Personnes précises** est inclus dans Business. Avec Free et Pro, un agent qui a déjà une liste la conserve : on peut toujours en retirer des personnes ou passer à **Moi uniquement** ou **Tout l'espace de travail**, mais on ne peut plus ajouter personne ni donner une liste à un autre agent. Les espaces de travail auto-hébergés disposent de **Personnes précises**.+Seul le propriétaire de l'agent peut modifier l'Accès ; les administrateurs de l'espace de travail ne le peuvent pas. Les `owner` et `admin` de l'espace de travail peuvent gérer le reste de la configuration, mais ne peuvent pas se servir de leur rôle d'administrateur pour exécuter des agents auxquels ils n'ont pas accès.## Configuration après la créationdiff --git a/apps/docs/content/docs/agents-create.ja.mdx b/apps/docs/content/docs/agents-create.ja.mdxindex f1a590c20c..799d388baa 100644--- a/apps/docs/content/docs/agents-create.ja.mdx+++ b/apps/docs/content/docs/agents-create.ja.mdx@@ -106,6 +106,8 @@ Access は、どのメンバーがこのエージェントを実行(割り当+Multica Cloud では、**特定のメンバー**は Business に含まれます。Free と Pro では、すでにリストのあるエージェントはそのリストを保持し、メンバーの削除や**自分のみ**・**ワークスペース全体**への変更はできますが、新しいメンバーは追加できず、ほかのエージェントにリストを設定することもできません。セルフホストのワークスペースでは**特定のメンバー**を利用できます。+Access を変更できるのはエージェントの owner だけで、ワークスペースの管理者にもできません。ワークスペースの `owner` と `admin` はその他の構成を管理できますが、管理者の立場を使って、許可されていないエージェントを実行することはできません。## 作成後の設定項目diff --git a/apps/docs/content/docs/agents-create.ko.mdx b/apps/docs/content/docs/agents-create.ko.mdxindex 85b6767ae1..fce03b4c9d 100644--- a/apps/docs/content/docs/agents-create.ko.mdx+++ b/apps/docs/content/docs/agents-create.ko.mdx@@ -106,6 +106,8 @@ Access는 어떤 멤버가 이 에이전트를 실행할 수 있는지 결정합+Multica Cloud에서 **특정 멤버**는 Business에 포함됩니다. Free와 Pro에서는 이미 목록이 있는 에이전트는 목록을 유지하며 멤버 제거나 **나만**·**전체 워크스페이스**로의 변경은 할 수 있지만, 새 멤버를 추가하거나 다른 에이전트에 목록을 설정할 수는 없습니다. 셀프 호스팅 워크스페이스에서는 **특정 멤버**를 사용할 수 있습니다.+에이전트 owner만 Access를 수정할 수 있으며 워크스페이스 관리자도 수정할 수 없습니다. 워크스페이스 `owner`와 `admin`은 다른 설정을 관리할 수 있지만 관리자 권한으로 허가받지 않은 에이전트를 실행할 수는 없습니다.## 생성 후 설정 항목diff --git a/apps/docs/content/docs/agents-create.mdx b/apps/docs/content/docs/agents-create.mdxindex ce677f4737..54759be470 100644--- a/apps/docs/content/docs/agents-create.mdx+++ b/apps/docs/content/docs/agents-create.mdx@@ -106,6 +106,8 @@ Access decides which members can run this agent (assign, @-mention, or chat):+On Multica Cloud, **Specific people** is included in Business. On Free and Pro, an agent that already has a list keeps it, and people can still be removed or the agent switched to **Only me** or **Entire workspace**, but nobody new can be added and other agents cannot get a list. Self-hosted workspaces have **Specific people**.+Only the agent owner can change Access; workspace admins cannot. Workspace `owner`s and `admin`s can manage the rest of the configuration, but cannot use their admin role to run agents they aren't granted.## Configuration after creationdiff --git a/apps/docs/content/docs/agents-create.zh-Hant.mdx b/apps/docs/content/docs/agents-create.zh-Hant.mdxindex 55af12a661..0920170900 100644--- a/apps/docs/content/docs/agents-create.zh-Hant.mdx+++ b/apps/docs/content/docs/agents-create.zh-Hant.mdx@@ -106,6 +106,8 @@ Access 決定哪些成員可以執行這名 AI 代理(分配、@提及或對+在 Multica Cloud 上,Business 包含**指定成員**。Free 和 Pro 工作區中,已有名單的 AI 代理保留名單,仍然可以移除成員,或改成**僅自己**、**整個工作區**,但不能再新增成員,其他 AI 代理也不能設定名單。自行部署的工作區可以使用**指定成員**。+只有 AI 代理 owner 可以修改 Access,工作區管理員也不行。工作區 `owner` 和 `admin` 可以管理其他配置,但不能借管理員身份執行未授權的 AI 代理。## 建立後的配置項diff --git a/apps/docs/content/docs/agents-create.zh.mdx b/apps/docs/content/docs/agents-create.zh.mdxindex d6cc14df82..2b4afc467a 100644--- a/apps/docs/content/docs/agents-create.zh.mdx+++ b/apps/docs/content/docs/agents-create.zh.mdx@@ -106,6 +106,8 @@ Access 决定哪些成员可以运行这名智能体(分配、@提及或对话+在 Multica Cloud 上,Business 包含**指定成员**。Free 和 Pro 工作区里,已有名单的智能体保留名单,仍然可以移除成员,或改成**仅自己**、**整个工作区**,但不能再添加新成员,其他智能体也不能设置名单。自部署的工作区可以使用**指定成员**。+只有智能体 owner 可以修改 Access,工作区管理员也不行。工作区 `owner` 和 `admin` 可以管理其他配置,但不能借管理员身份运行未授权的智能体。## 创建后的配置项diff --git a/apps/docs/content/docs/cli.fr.mdx b/apps/docs/content/docs/cli.fr.mdxindex fc17d7295b..b04b9d7f0c 100644--- a/apps/docs/content/docs/cli.fr.mdx+++ b/apps/docs/content/docs/cli.fr.mdx@@ -292,7 +292,7 @@ multica agent update <agent-id> --mcp-config-file ./mcp.json- Les options `--custom-env` n'existent que sur `agent create`. Pour modifier les variables ensuite, utilisez `agent env set`, qui remplace l'ensemble ; les clés dont la valeur est `****` gardent leur valeur actuelle.- `agent update --mcp-config null` efface la configuration MCP.- `--custom-args` est un tableau JSON placé à la fin des arguments de lancement. Choisissez le modèle avec `--model` ; certains outils refusent un `--model` dans les arguments personnalisés.-- `--permission-mode` détermine qui peut invoquer l'agent : `private` pour le propriétaire seul, ou `public_to` avec `--public-to-workspace` ou `--public-to-member <user-id>`. `--visibility private|workspace` est l'ancienne forme, convertie en `--permission-mode` ; si les deux sont fournis, `--permission-mode` l'emporte.+- `--permission-mode` détermine qui peut invoquer l'agent : `private` pour le propriétaire seul, ou `public_to` avec `--public-to-workspace` ou `--public-to-member <user-id>`. `--visibility private|workspace` est l'ancienne forme, convertie en `--permission-mode` ; si les deux sont fournis, `--permission-mode` l'emporte. Sur Multica Cloud, les listes de membres sont incluses dans Business. Avec Free et Pro, quand la restriction est appliquée, `agent create` ou `agent update` qui donne une liste à un agent ou y ajoute quelqu'un est refusé avec `feature_locked` ; retirer des membres, réenregistrer la même liste et passer à `private` ou `--public-to-workspace` restent possibles.## Daemon et runtimesdiff --git a/apps/docs/content/docs/cli.ja.mdx b/apps/docs/content/docs/cli.ja.mdxindex 18b80dd15d..3dd830ef0c 100644--- a/apps/docs/content/docs/cli.ja.mdx+++ b/apps/docs/content/docs/cli.ja.mdx@@ -292,7 +292,7 @@ multica agent update <agent-id> --mcp-config-file ./mcp.json- `--custom-env` 系のフラグは `agent create` にしかありません。後から変えるときは `agent env set` を使います。これは全体を置き換え、値を `****` にしたキーは元の値を保ちます。- `agent update --mcp-config null` で MCP 設定を消去します。- `--custom-args` は JSON 配列で、起動引数の最後に置かれます。モデルは `--model` で選んでください。カスタム引数の中の `--model` を受け付けないツールもあります。-- エージェントを呼び出せる人は `--permission-mode` で決めます。`private` は所有者だけ、`public_to` は `--public-to-workspace` または `--public-to-member <user-id>` と組み合わせます。`--visibility private|workspace` は古い書き方で、`--permission-mode` に対応付けられます。両方を指定した場合は `--permission-mode` が優先されます。+- エージェントを呼び出せる人は `--permission-mode` で決めます。`private` は所有者だけ、`public_to` は `--public-to-workspace` または `--public-to-member <user-id>` と組み合わせます。`--visibility private|workspace` は古い書き方で、`--permission-mode` に対応付けられます。両方を指定した場合は `--permission-mode` が優先されます。Multica Cloud ではメンバーリストは Business に含まれます。Free と Pro で制限が有効な場合、`agent create` や `agent update` でリストを新しく設定したりメンバーを追加したりすると `feature_locked` で拒否されます。メンバーの削除、同じリストの再保存、`private` や `--public-to-workspace` への変更は引き続き行えます。## デーモンとランタイムdiff --git a/apps/docs/content/docs/cli.ko.mdx b/apps/docs/content/docs/cli.ko.mdxindex efa7edf059..a1cde85774 100644--- a/apps/docs/content/docs/cli.ko.mdx+++ b/apps/docs/content/docs/cli.ko.mdx@@ -292,7 +292,7 @@ multica agent update <agent-id> --mcp-config-file ./mcp.json- `--custom-env` 계열 플래그는 `agent create`에만 있습니다. 나중에 바꿀 때는 `agent env set`을 쓰며, 전체를 교체하고 값이 `****`인 키는 기존 값을 유지합니다.- `agent update --mcp-config null`은 MCP 설정을 지웁니다.- `--custom-args`는 JSON 배열이며 실행 인수의 맨 끝에 붙습니다. 모델은 `--model`로 고르세요. 사용자 지정 인수 안의 `--model`을 거부하는 도구도 있습니다.-- 에이전트를 호출할 수 있는 사람은 `--permission-mode`로 정합니다. `private`은 소유자만, `public_to`는 `--public-to-workspace` 또는 `--public-to-member <user-id>`와 함께 씁니다. `--visibility private|workspace`는 예전 방식이며 `--permission-mode`로 변환됩니다. 둘 다 지정하면 `--permission-mode`가 우선합니다.+- 에이전트를 호출할 수 있는 사람은 `--permission-mode`로 정합니다. `private`은 소유자만, `public_to`는 `--public-to-workspace` 또는 `--public-to-member <user-id>`와 함께 씁니다. `--visibility private|workspace`는 예전 방식이며 `--permission-mode`로 변환됩니다. 둘 다 지정하면 `--permission-mode`가 우선합니다. Multica Cloud에서 멤버 목록은 Business에 포함됩니다. Free와 Pro에서 제한이 적용되면 `agent create`나 `agent update`로 목록을 새로 설정하거나 멤버를 추가할 때 `feature_locked`로 거부됩니다. 멤버 제거, 같은 목록 다시 저장, `private` 또는 `--public-to-workspace`로의 변경은 계속 할 수 있습니다.## 데몬과 런타임diff --git a/apps/docs/content/docs/cli.mdx b/apps/docs/content/docs/cli.mdxindex f916269ec5..006881f47e 100644--- a/apps/docs/content/docs/cli.mdx+++ b/apps/docs/content/docs/cli.mdx@@ -292,7 +292,7 @@ multica agent update <agent-id> --mcp-config-file ./mcp.json- The `--custom-env` flags exist only on `agent create`. Change variables later with `agent env set`, which replaces the whole set; keys whose value is `****` keep their existing value.- `agent update --mcp-config null` clears the MCP configuration.- `--custom-args` is a JSON array placed at the end of the launch arguments. Choose the model with `--model`; some tools reject `--model` inside custom arguments.-- `--permission-mode` controls who can invoke the agent: `private` for the owner only, or `public_to` with `--public-to-workspace` or `--public-to-member <user-id>`. `--visibility private|workspace` is the older form and maps onto `--permission-mode`; when both are given, `--permission-mode` wins.+- `--permission-mode` controls who can invoke the agent: `private` for the owner only, or `public_to` with `--public-to-workspace` or `--public-to-member <user-id>`. `--visibility private|workspace` is the older form and maps onto `--permission-mode`; when both are given, `--permission-mode` wins. On Multica Cloud, member lists are included in Business. On Free and Pro with the restriction enforced, `agent create` or `agent update` that gives an agent a member list or adds someone to it is refused with `feature_locked`; removing members, re-saving the same list, and switching to `private` or `--public-to-workspace` still work.### Agent run historydiff --git a/apps/docs/content/docs/cli.zh-Hant.mdx b/apps/docs/content/docs/cli.zh-Hant.mdxindex 82a2bf09a3..c06bbf6dd9 100644--- a/apps/docs/content/docs/cli.zh-Hant.mdx+++ b/apps/docs/content/docs/cli.zh-Hant.mdx@@ -283,7 +283,7 @@ multica agent update <agent-id> --mcp-config-file ./mcp.json- `--custom-env` 系列只在 `agent create` 中可用。之後修改用 `agent env set`,它整體替換原有變數,值寫成 `****` 的鍵保留原值。- `agent update --mcp-config null` 清除 MCP 配置。- `--custom-args` 是 JSON 陣列,排在啟動引數的最後。選模型用 `--model`,部分工具會拒絕出現在自定義引數裡的 `--model`。-- 誰能呼叫 AI 代理用 `--permission-mode`:`private` 只有所有者,`public_to` 配合 `--public-to-workspace` 或 `--public-to-member <user-id>`。`--visibility private|workspace` 是舊寫法,會對映到 `--permission-mode`;兩者同時給出時以 `--permission-mode` 為準。+- 誰能呼叫 AI 代理用 `--permission-mode`:`private` 只有所有者,`public_to` 配合 `--public-to-workspace` 或 `--public-to-member <user-id>`。`--visibility private|workspace` 是舊寫法,會對映到 `--permission-mode`;兩者同時給出時以 `--permission-mode` 為準。在 Multica Cloud 上,Business 包含成員名單。Free 和 Pro 工作區開啟強制後,`agent create` 或 `agent update` 新建名單或往名單裡加人會以 `feature_locked` 拒絕;移除成員、原樣儲存名單、改成 `private` 或 `--public-to-workspace` 仍然可以。### AI 代理執行記錄diff --git a/apps/docs/content/docs/cli.zh.mdx b/apps/docs/content/docs/cli.zh.mdxindex c921b3bbbf..ba3e3486e1 100644--- a/apps/docs/content/docs/cli.zh.mdx+++ b/apps/docs/content/docs/cli.zh.mdx@@ -292,7 +292,7 @@ multica agent update <agent-id> --mcp-config-file ./mcp.json- `--custom-env` 系列只在 `agent create` 中可用。之后修改用 `agent env set`,它整体替换原有变量,值写成 `****` 的键保留原值。- `agent update --mcp-config null` 清除 MCP 配置。- `--custom-args` 是 JSON 数组,排在启动参数的最后。选模型用 `--model`,部分工具会拒绝出现在自定义参数里的 `--model`。-- 谁能调用智能体用 `--permission-mode`:`private` 只有所有者,`public_to` 配合 `--public-to-workspace` 或 `--public-to-member <user-id>`。`--visibility private|workspace` 是旧写法,会映射到 `--permission-mode`;两者同时给出时以 `--permission-mode` 为准。+- 谁能调用智能体用 `--permission-mode`:`private` 只有所有者,`public_to` 配合 `--public-to-workspace` 或 `--public-to-member <user-id>`。`--visibility private|workspace` 是旧写法,会映射到 `--permission-mode`;两者同时给出时以 `--permission-mode` 为准。在 Multica Cloud 上,Business 包含成员名单。Free 和 Pro 工作区开启强制后,`agent create` 或 `agent update` 新建名单或往名单里加人会以 `feature_locked` 拒绝;移除成员、原样保存名单、改成 `private` 或 `--public-to-workspace` 仍然可以。## 守护进程和运行时diff --git a/apps/docs/content/docs/daemon-runtimes.fr.mdx b/apps/docs/content/docs/daemon-runtimes.fr.mdxindex ef6379107d..018e5bf95d 100644--- a/apps/docs/content/docs/daemon-runtimes.fr.mdx+++ b/apps/docs/content/docs/daemon-runtimes.fr.mdx@@ -235,7 +235,7 @@ Un runtime local est **privé** par défaut : seul le propriétaire du runtime pSeul le propriétaire peut le rendre **public**. Les administrateurs de l'espace de travail peuvent renommer ou supprimer un runtime, mais le partager relève de la décision du propriétaire. Une fois le runtime public, les autres membres peuvent le sélectionner et acheminer les exécutions de leurs agents vers cet ordinateur ; les identifiants de connexion de l'outil de codage IA sous-jacent ne sont pas partagés.-Pour le partager seulement avec certaines personnes, ouvrez la page de détail du runtime, choisissez **Membres**, sélectionnez un ou plusieurs membres de l'espace de travail, puis cliquez sur **Enregistrer**. Ces membres peuvent sélectionner le runtime et y créer des agents. Seul le propriétaire peut modifier la liste, et y figurer ne donne pas le droit de renommer, supprimer ou administrer le runtime.+Pour le partager seulement avec certaines personnes, ouvrez la page de détail du runtime, choisissez **Membres**, sélectionnez un ou plusieurs membres de l'espace de travail, puis cliquez sur **Enregistrer**. Ces membres peuvent sélectionner le runtime et y créer des agents. Seul le propriétaire peut modifier la liste, et y figurer ne donne pas le droit de renommer, supprimer ou administrer le runtime. Sur Multica Cloud, le partage avec des membres choisis est inclus dans Business. Avec Free et Pro, une liste existante reste active et l'on peut toujours en retirer des membres ou rendre le runtime privé ou public, mais on ne peut plus ajouter personne. Les espaces de travail auto-hébergés peuvent partager avec des membres choisis.Lorsque le propriétaire retire des membres, restreint un runtime public à des membres spécifiques ou le rend à nouveau **privé**, Multica affiche d'abord les agents et les exécutions actives concernés, y compris les conversations de création d'agents avec Agent Builder. La confirmation dissocie les agents de ces autres membres, annule leurs exécutions en file d'attente, distribuées, en cours, en attente d'un répertoire local ou différées avec le motif `runtime_access_revoked`, et met en pause les automatisations actives assignées aux agents dissociés. Les agents et exécutions du propriétaire et des membres qui gardent l'accès ne sont pas affectés. Si le plan change, une nouvelle confirmation est nécessaire ; des modifications simultanées de la discussion peuvent nécessiter de réessayer. Pour reprendre le travail, associez l'agent à un runtime accessible, puis reprenez explicitement ses automatisations en pause.diff --git a/apps/docs/content/docs/daemon-runtimes.ja.mdx b/apps/docs/content/docs/daemon-runtimes.ja.mdxindex 1e82fa9528..36ff4b5e1f 100644--- a/apps/docs/content/docs/daemon-runtimes.ja.mdx+++ b/apps/docs/content/docs/daemon-runtimes.ja.mdx@@ -235,7 +235,7 @@ Codex のネイティブサブエージェントも既定でオフです。Multiランタイムを**公開**に変更できるのは所有者だけです。ワークスペースの管理者はランタイムの名前変更や削除はできますが、共有するかどうかは所有者が決めます。公開すると、ワークスペースの他のメンバーもこのランタイムを選び、エージェントの実行をこのコンピュータにルーティングできるようになります。基盤の AI コーディングツールのログイン認証情報は共有されません。-一部のメンバーにだけ共有するには、ランタイムの詳細で**メンバー**を選び、ワークスペースのメンバーを 1 人以上選んで**保存**します。選ばれたメンバーはこのランタイムを選択し、その上でエージェントを作成できます。リストを変更できるのは所有者だけで、リストに入っていても名前変更・削除・管理の権限は得られません。+一部のメンバーにだけ共有するには、ランタイムの詳細で**メンバー**を選び、ワークスペースのメンバーを 1 人以上選んで**保存**します。選ばれたメンバーはこのランタイムを選択し、その上でエージェントを作成できます。リストを変更できるのは所有者だけで、リストに入っていても名前変更・削除・管理の権限は得られません。Multica Cloud では、メンバーを指定した共有は Business に含まれます。Free と Pro では、既存のリストはそのまま有効で、メンバーの削除や非公開・公開への変更はできますが、新しいメンバーは追加できません。セルフホストのワークスペースではメンバーを指定して共有できます。所有者が共有メンバーを外したとき、公開ランタイムを指定メンバーに絞ったとき、または再び**プライベート**にしたとき、Multica はエージェントビルダーのセッションも含め、影響を受けるエージェントとアクティブな実行を表示します。確定すると、他メンバーの該当エージェントの接続を解除し、キュー中・配信済み・実行中・ローカルディレクトリ待ち・延期中の実行を `runtime_access_revoked` としてキャンセルします。これらのエージェントに割り当てられた有効なオートパイロットも一時停止します。所有者と、引き続きアクセスできるメンバーのエージェントと実行には影響しません。対象が変わった場合は再確認が必要で、同時にチャットが更新されている場合は再試行が必要になることがあります。作業を再開するには、利用可能なランタイムにエージェントを接続し、一時停止中のオートパイロットを手動で再開してください。diff --git a/apps/docs/content/docs/daemon-runtimes.ko.mdx b/apps/docs/content/docs/daemon-runtimes.ko.mdxindex a05d4b06e4..cf5590b8e9 100644--- a/apps/docs/content/docs/daemon-runtimes.ko.mdx+++ b/apps/docs/content/docs/daemon-runtimes.ko.mdx@@ -235,7 +235,7 @@ Codex 기본 하위 에이전트도 기본적으로 꺼져 있습니다. Multica**공개**로 바꿀 수 있는 사람은 런타임 owner뿐입니다. 워크스페이스 관리자는 런타임의 이름을 바꾸거나 삭제할 수 있지만, 공유 여부는 owner가 결정합니다. 공개하면 워크스페이스의 다른 멤버도 이 런타임을 선택해 에이전트 실행을 해당 컴퓨터로 라우팅할 수 있습니다. 기반 AI 코딩 도구의 로그인 자격 증명은 공유되지 않습니다.-일부 멤버에게만 공유하려면 런타임 상세에서 **멤버**를 고르고, 워크스페이스 멤버를 한 명 이상 선택한 뒤 **저장**합니다. 선택된 멤버는 이 런타임을 골라 에이전트를 만들 수 있습니다. 목록은 owner만 바꿀 수 있으며, 목록에 있다고 해서 런타임의 이름 변경·삭제·관리 권한이 생기지는 않습니다.+일부 멤버에게만 공유하려면 런타임 상세에서 **멤버**를 고르고, 워크스페이스 멤버를 한 명 이상 선택한 뒤 **저장**합니다. 선택된 멤버는 이 런타임을 골라 에이전트를 만들 수 있습니다. 목록은 owner만 바꿀 수 있으며, 목록에 있다고 해서 런타임의 이름 변경·삭제·관리 권한이 생기지는 않습니다. Multica Cloud에서 멤버를 지정한 공유는 Business에 포함됩니다. Free와 Pro에서는 기존 목록이 그대로 유지되며 멤버 제거나 비공개·공개 전환은 할 수 있지만 새 멤버는 추가할 수 없습니다. 셀프 호스팅 워크스페이스에서는 멤버를 지정해 공유할 수 있습니다.소유자가 공유 멤버를 빼거나, 공개 런타임을 지정 멤버로 좁히거나, 다시 **비공개**로 전환하면 Multica는 에이전트 빌더 세션을 포함하여 영향을 받는 에이전트와 활성 실행을 표시합니다. 확인하면 다른 멤버의 해당 에이전트 연결을 해제하고, 대기 중·배포됨·실행 중·로컬 디렉터리 대기·지연 중인 실행을 `runtime_access_revoked`로 취소합니다. 해당 에이전트에 할당된 활성 오토파일럿도 일시 중지합니다. 소유자와 계속 접근할 수 있는 멤버의 에이전트와 실행에는 영향을 주지 않습니다. 대상이 바뀌면 다시 확인해야 하며, 채팅이 동시에 변경되는 경우 재시도가 필요할 수 있습니다. 작업을 재개하려면 에이전트를 사용 가능한 런타임에 연결한 후 일시 중지된 오토파일럿을 직접 재개하세요.diff --git a/apps/docs/content/docs/daemon-runtimes.mdx b/apps/docs/content/docs/daemon-runtimes.mdxindex 6052008e8f..1d8c2904c6 100644--- a/apps/docs/content/docs/daemon-runtimes.mdx+++ b/apps/docs/content/docs/daemon-runtimes.mdx@@ -235,7 +235,7 @@ A local runtime is **private** by default: only the runtime owner can create ageOnly the owner can make it **public**. Workspace admins can rename or delete a runtime, but sharing one is the owner's decision. Once it is public, other workspace members can select this runtime and route their agents' runs to this computer; the underlying AI coding tool's login credentials are not shared.-To share it with selected people instead, open the runtime's detail page, choose **Members**, pick one or more workspace members, and **Save**. Those members can select the runtime and create agents on it. Only the owner can change the list, and being on it does not let anyone rename, delete, or administer the runtime.+To share it with selected people instead, open the runtime's detail page, choose **Members**, pick one or more workspace members, and **Save**. Those members can select the runtime and create agents on it. Only the owner can change the list, and being on it does not let anyone rename, delete, or administer the runtime. On Multica Cloud, sharing with selected members is included in Business. On Free and Pro, an existing list keeps working and members can still be removed or the runtime made private or public, but nobody new can be added. Self-hosted workspaces can share with selected members.When the owner removes members, narrows a public runtime to specific members, or makes it **private** again, Multica shows the affected agents and active runs, including Agent Builder sessions, before applying the change. Confirmation unbinds those teammates' agents, cancels their queued, dispatched, running, local-directory-waiting and deferred runs with `runtime_access_revoked`, and pauses active autopilots assigned to the unbound agents. Agents and runs belonging to the owner or to members who keep access are unaffected. A changed plan requires renewed confirmation; concurrent chat writes may require a retry. To resume work, bind the agent to an accessible runtime, then explicitly resume its paused autopilots.diff --git a/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx b/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdxindex aba22d0af5..efded4a689 100644--- a/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx+++ b/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx@@ -236,7 +236,7 @@ Codex 原生子 AI 代理同樣預設關閉:父執行緒結束時,Multica也只有所有者可以把它改為**公開**。管理員可以重新命名或刪除執行時,但要不要共享由所有者決定。公開後,工作區中的其他成員也可以選擇這條執行時,把 AI 代理的執行路由到這臺電腦;底層 AI 程式設計工具的登入憑據不會因此共享。-只想開放給部分成員時,在執行時詳情中選擇**指定成員**,勾選一位或多位工作區成員,然後**儲存**。這些成員可以選擇該執行時並在上面建立 AI 代理。只有所有者能修改名單;在名單上不代表可以重新命名、刪除或管理這條執行時。+只想開放給部分成員時,在執行時詳情中選擇**指定成員**,勾選一位或多位工作區成員,然後**儲存**。這些成員可以選擇該執行時並在上面建立 AI 代理。只有所有者能修改名單;在名單上不代表可以重新命名、刪除或管理這條執行時。在 Multica Cloud 上,Business 包含依指定成員共享。Free 和 Pro 工作區中,既有名單繼續生效,仍然可以移除成員、改為私有或公開,但不能再新增成員。自行部署的工作區可以依指定成員共享。所有者移除共享成員、把公開執行時改為指定成員,或重新設為**私有**時,Multica 會先展示受影響的 AI 代理和活動執行,包括 AI 代理構建會話。確認後會解綁其他成員的這些 AI 代理,以 `runtime_access_revoked` 取消其排隊中、已排程、執行中、等待本地目錄和延遲中的執行,並暫停分配給這些 AI 代理的已啟用自動化。所有者和仍有權限的成員,其 AI 代理與執行不受影響。影響範圍變化時需要重新確認;遇到併發聊天寫入時可能需要重試。恢復工作時,請先將 AI 代理繫結到可用的執行時,再手動恢復已暫停的自動化。diff --git a/apps/docs/content/docs/daemon-runtimes.zh.mdx b/apps/docs/content/docs/daemon-runtimes.zh.mdxindex 1078505663..8f82c3cfb0 100644--- a/apps/docs/content/docs/daemon-runtimes.zh.mdx+++ b/apps/docs/content/docs/daemon-runtimes.zh.mdx@@ -236,7 +236,7 @@ Codex 原生子智能体同样默认关闭:父线程结束时,Multica 就把也只有所有者可以把它改为**公开**。管理员可以重命名或删除运行时,但要不要共享由所有者决定。公开后,工作区中的其他成员也可以选择这条运行时,把智能体的执行路由到这台电脑;底层 AI 编程工具的登录凭据不会因此共享。-只想开放给部分成员时,在运行时详情中选择**指定成员**,勾选一位或多位工作区成员,然后**保存**。这些成员可以选择该运行时并在上面创建智能体。只有所有者能修改名单;在名单上不代表可以重命名、删除或管理这条运行时。+只想开放给部分成员时,在运行时详情中选择**指定成员**,勾选一位或多位工作区成员,然后**保存**。这些成员可以选择该运行时并在上面创建智能体。只有所有者能修改名单;在名单上不代表可以重命名、删除或管理这条运行时。在 Multica Cloud 上,Business 包含按指定成员共享。Free 和 Pro 工作区里,已有名单继续生效,仍然可以移除成员、改为私有或公开,但不能再添加新成员。自部署的工作区可以按指定成员共享。所有者移除共享成员、把公开运行时改为指定成员,或重新设为**私有**时,Multica 会先展示受影响的智能体和活动运行,包括智能体构建会话。确认后会解绑其他成员的这些智能体,以 `runtime_access_revoked` 取消其排队中、已调度、执行中、等待本地目录和延迟中的运行,并暂停分配给这些智能体的已启用自动化。所有者和仍有权限的成员,其智能体与运行不受影响。影响范围变化时需要重新确认;遇到并发聊天写入时可能需要重试。恢复工作时,请先将智能体绑定到可用的运行时,再手动恢复已暂停的自动化。diff --git a/packages/core/agents/draft.test.ts b/packages/core/agents/draft.test.tsindex 3ba99d01d8..9080763897 100644--- a/packages/core/agents/draft.test.ts+++ b/packages/core/agents/draft.test.ts@@ -102,6 +102,32 @@ describe("duplicate access", () => {}).permissionScope,).toBe("workspace");});++ it("starts the copy as Only me when the plan cannot add a member list", () => {+ const source = sourceAgent({+ permission_mode: "public_to",+ invocation_targets: [+ { target_type: "member", target_id: "member-1" },+ { target_type: "team", target_id: "team-1" },+ ],+ });+ const duplicate = buildDuplicateDraft(source, {+ runtimes: [CODEX_RUNTIME],+ currentUserId: "user-1",+ fallbackRuntimeId: "runtime-1",+ nameSuffix: " copy",+ canAddInvocationMembers: false,+ });+ expect(duplicate).toMatchObject({ permissionScope: "private", memberIds: new Set(), teamIds: new Set() });+ expect(buildInvocationTargets(duplicate)).toEqual([]);+ // Workspace-wide access is free, so it is copied either way.+ expect(+ deriveDuplicateAccess(+ { permission_mode: "public_to", invocation_targets: [{ target_type: "workspace", target_id: null }] },+ false,+ ).permissionScope,+ ).toBe("workspace");+ });});describe("agent conversation starters", () => {diff --git a/packages/core/agents/draft.ts b/packages/core/agents/draft.tsindex 448dd5c877..25cce5f24e 100644--- a/packages/core/agents/draft.ts+++ b/packages/core/agents/draft.ts@@ -125,6 +125,7 @@ export function buildInvocationTargets(export function deriveDuplicateAccess(agent: Pick<Agent, "permission_mode" | "invocation_targets">,+ canAddInvocationMembers = true,): Pick<AgentDraft, "permissionScope" | "memberIds" | "teamIds"> {if (agent.permission_mode !== "public_to") {return {@@ -149,7 +150,7 @@ export function deriveDuplicateAccess(const teamIds = targets.filter((target) => target.target_type === "team" && target.target_id).map((target) => target.target_id as string);- if (memberIds.length === 0 && teamIds.length === 0) {+ if ((memberIds.length === 0 && teamIds.length === 0) || !canAddInvocationMembers) {return {permissionScope: "private",memberIds: new Set(),@@ -181,6 +182,12 @@ export function buildDuplicateDraft(currentUserId: string | null;fallbackRuntimeId: string;nameSuffix: string;+ /**+ * False when the plan lacks `agent_invocation_members`: a member list on+ * the new agent would be refused, so the copy starts as "Only me".+ * Defaults to true.+ */+ canAddInvocationMembers?: boolean;},): AgentDraft {const keepsRuntime =@@ -205,7 +212,7 @@ export function buildDuplicateDraft(thinkingLevel: keepsRuntime ? source.thinking_level ?? "" : "",serviceTier: keepsRuntime ? source.service_tier ?? "" : "",skillIds: new Set(source.skills.map((skill) => skill.id)),- ...deriveDuplicateAccess(source),+ ...deriveDuplicateAccess(source, options.canAddInvocationMembers ?? true),};}diff --git a/packages/core/agents/effective-access.test.ts b/packages/core/agents/effective-access.test.tsindex 0ea1ca32b9..a595ba998b 100644--- a/packages/core/agents/effective-access.test.ts+++ b/packages/core/agents/effective-access.test.ts@@ -3,6 +3,7 @@ import type { AgentInvocationTarget } from "../types";import {effectiveAccessScope,isAccessChangeReady,+ usesInvocationMembers,} from "./effective-access";function ws(): AgentInvocationTarget {@@ -86,3 +87,14 @@ describe("isAccessChangeReady", () => {).toBe(false);});});++describe("usesInvocationMembers", () => {+ it("is true only for public_to with member or team targets and no workspace target", () => {+ expect(usesInvocationMembers("public_to", [member("u1")])).toBe(true);+ expect(usesInvocationMembers("public_to", [team("t1")])).toBe(true);+ expect(usesInvocationMembers("public_to", [ws(), member("u1")])).toBe(false);+ expect(usesInvocationMembers("public_to", [])).toBe(false);+ expect(usesInvocationMembers("public_to", undefined)).toBe(false);+ expect(usesInvocationMembers("private", [member("u1")])).toBe(false);+ });+});diff --git a/packages/core/agents/effective-access.ts b/packages/core/agents/effective-access.tsindex 6de8303f4e..2bbebe9b2b 100644--- a/packages/core/agents/effective-access.ts+++ b/packages/core/agents/effective-access.ts@@ -54,3 +54,18 @@ export function isAccessChangeReady(if (change.permission_mode === "private") return true;return change.invocation_targets.length > 0;}++/**+ * Whether the agent is invocable by specific members, the configuration the+ * `agent_invocation_members` paid feature covers: `public_to` with member or+ * team targets and no workspace target. Mirrors the server's gate.+ */+export function usesInvocationMembers(+ permissionMode: AgentPermissionMode | undefined | null,+ invocationTargets: readonly AgentInvocationTarget[] | undefined | null,+): boolean {+ return (+ effectiveAccessScope(permissionMode, invocationTargets) === "specific-people" &&+ (invocationTargets ?? []).some((t) => t.target_type === "member" || t.target_type === "team")+ );+}diff --git a/packages/core/billing/paid-features.test.tsx b/packages/core/billing/paid-features.test.tsxindex 50b495b21d..9935933ab9 100644--- a/packages/core/billing/paid-features.test.tsx+++ b/packages/core/billing/paid-features.test.tsx@@ -136,6 +136,58 @@ describe("WorkspaceFeaturesSchema", () => {features: { private_projects: "locked", future_feature: "available", broken: "available" },});expect(WorkspaceFeaturesSchema.parse({ features: [] })).toEqual({ features: {} });+ expect(WorkspaceFeaturesSchema.parse({ features: null })).toEqual({ features: {} });expect(WorkspaceFeaturesSchema.parse({})).toEqual({ features: {} });});++ it("reads the Business access and app features, and one malformed entry does not drop the others", () => {+ expect(+ WorkspaceFeaturesSchema.parse({+ features: {+ agent_invocation_members: { state: "locked" },+ runtime_member_sharing: { state: "available" },+ team_app_accounts: { state: "locked" },+ },+ }),+ ).toEqual({+ features: {+ agent_invocation_members: "locked",+ runtime_member_sharing: "available",+ team_app_accounts: "locked",+ },+ });+ expect(+ WorkspaceFeaturesSchema.parse({+ features: {+ agent_invocation_members: { state: "trialing" },+ runtime_member_sharing: null,+ team_app_accounts: { state: "locked" },+ private_projects: { state: 1 },+ },+ }),+ ).toEqual({+ features: {+ agent_invocation_members: "available",+ runtime_member_sharing: "available",+ team_app_accounts: "locked",+ private_projects: "available",+ },+ });+ });+});++describe("usePaidFeatureAccess for the Business access and app features", () => {+ it.each(["agent_invocation_members", "runtime_member_sharing", "team_app_accounts"] as const)(+ "resolves %s independently of the other features",+ async (feature) => {+ const { wrapper } = setup(async () => ({ features: { [feature]: "locked", private_projects: "available" } }));+ const existing = renderHook(() => usePaidFeatureAccess("ws-1", feature, { hasExistingConfig: true }), { wrapper });+ const fresh = renderHook(() => usePaidFeatureAccess("ws-1", feature, { hasExistingConfig: false }), { wrapper });+ const other = renderHook(() => usePaidFeatureAccess("ws-1", "private_projects", { hasExistingConfig: false }), { wrapper });+ await waitFor(() => expect(existing.result.current.state).toBe("read_only"));+ expect(existing.result.current).toMatchObject({ canAdd: false, canReduce: true });+ await waitFor(() => expect(fresh.result.current.state).toBe("unavailable"));+ await waitFor(() => expect(other.result.current.state).toBe("available"));+ },+ );});diff --git a/packages/core/types/billing.ts b/packages/core/types/billing.tsindex 37cb8eb3a0..531c7cb2a7 100644--- a/packages/core/types/billing.ts+++ b/packages/core/types/billing.ts@@ -445,7 +445,12 @@ export interface CreateWorkspaceSubscriptionPortalResponse {* can be reduced, but nothing can be added. The server enforces on every* write; this is only for rendering.*/-export type PaidFeature = "private_projects" | "guests";+export type PaidFeature =+ | "private_projects"+ | "guests"+ | "agent_invocation_members"+ | "runtime_member_sharing"+ | "team_app_accounts";export type WorkspaceFeatureState = "available" | "locked";diff --git a/packages/views/agents/components/agent-access-settings.test.tsx b/packages/views/agents/components/agent-access-settings.test.tsxnew file mode 100644index 0000000000..936952653e--- /dev/null+++ b/packages/views/agents/components/agent-access-settings.test.tsx@@ -0,0 +1,81 @@+// @vitest-environment jsdom++import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { cleanup, screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { setApiInstance } from "@multica/core/api";+import type { ApiClient } from "@multica/core/api/client";+import type { Agent, MemberWithUser, WorkspaceFeatureState } from "@multica/core/types";+import { renderWithI18n } from "../../test/i18n";+import { AgentAccessSettings } from "./agent-access-settings";++vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));+vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => null }));+vi.mock("@multica/core/paths", async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useWorkspacePaths: () => ({ settings: () => "/acme/settings" }),+}));+vi.mock("../../navigation", async (importOriginal) => ({+ ...(await importOriginal<object>()),+ AppLink: ({ href, children }: { href: string; children: React.ReactNode }) => <a href={href}>{children}</a>,+}));++const MEMBERS = [+ { user_id: "owner", name: "Owner", role: "owner" },+ { user_id: "u1", name: "Alice", role: "member" },+ { user_id: "u2", name: "Bob", role: "member" },+] as unknown as MemberWithUser[];++let feature: WorkspaceFeatureState;++function agent(overrides: Partial<Agent>): Agent {+ return {+ id: "a1",+ owner_id: "owner",+ visibility: "private",+ permission_mode: "private",+ invocation_targets: [],+ composio_toolkit_allowlist: [],+ ...overrides,+ } as Agent;+}++function renderSettings(value: Agent) {+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ return renderWithI18n(+ <QueryClientProvider client={qc}>+ <AgentAccessSettings agent={value} members={MEMBERS} currentUserId="owner" onUpdate={vi.fn()} />+ </QueryClientProvider>,+ );+}++describe("AgentAccessSettings plan access", () => {+ beforeEach(() => {+ feature = "available";+ setApiInstance({+ getWorkspaceFeatures: vi.fn(async () => ({ features: { agent_invocation_members: feature } })),+ } as unknown as ApiClient);+ });+ afterEach(cleanup);++ it("offers Specific people when the plan includes it", async () => {+ renderSettings(agent({}));+ await waitFor(() => expect(screen.getByRole("radio", { name: /^Specific people/i })).toBeEnabled());+ expect(screen.queryByText("View plans")).not.toBeInTheDocument();+ });++ it("marks a locked plan unavailable for an agent without a member list", async () => {+ feature = "locked";+ renderSettings(agent({ permission_mode: "public_to", invocation_targets: [{ target_type: "workspace", target_id: null }] }));+ expect(await screen.findByText("Not included in this workspace's plan.")).toBeInTheDocument();+ expect(screen.getByRole("radio", { name: /^Specific people/i })).toBeDisabled();+ });++ it("marks a locked plan read-only for an agent that already has members", async () => {+ feature = "locked";+ renderSettings(agent({ permission_mode: "public_to", invocation_targets: [{ target_type: "member", target_id: "u1" }] }));+ expect(await screen.findByText("Read-only. Upgrade to edit.")).toBeInTheDocument();+ expect(screen.getByRole("checkbox", { name: /Alice/i })).toBeChecked();+ expect(screen.queryByRole("checkbox", { name: /Bob/i })).not.toBeInTheDocument();+ });+});diff --git a/packages/views/agents/components/agent-access-settings.tsx b/packages/views/agents/components/agent-access-settings.tsxindex 766c04d50f..dd9d11fa2b 100644--- a/packages/views/agents/components/agent-access-settings.tsx+++ b/packages/views/agents/components/agent-access-settings.tsx@@ -1,6 +1,9 @@"use client";import type { Agent, MemberWithUser } from "@multica/core/types";+import { usesInvocationMembers } from "@multica/core/agents";+import { usePaidFeatureAccess } from "@multica/core/billing";+import { useWorkspaceId } from "@multica/core/hooks";import {SettingsCard,SettingsSection,@@ -22,6 +25,10 @@ export function AgentAccessSettings({onUpdate: (id: string, data: Record<string, unknown>) => Promise<void>;}) {const { t } = useT("agents");+ const wsId = useWorkspaceId();+ const membersAccess = usePaidFeatureAccess(wsId, "agent_invocation_members", {+ hasExistingConfig: usesInvocationMembers(agent.permission_mode, agent.invocation_targets),+ });return (<SettingsSection@@ -41,6 +48,7 @@ export function AgentAccessSettings({(agent.composio_toolkit_allowlist ?? []).length > 0}onDirtyChange={onDirtyChange}+ membersAccess={membersAccess}onChange={(next) => onUpdate(agent.id, next)}/></SettingsCard>diff --git a/packages/views/agents/components/agent-batch-toolbar.test.tsx b/packages/views/agents/components/agent-batch-toolbar.test.tsxindex 5282961b70..cd216f4008 100644--- a/packages/views/agents/components/agent-batch-toolbar.test.tsx+++ b/packages/views/agents/components/agent-batch-toolbar.test.tsx@@ -6,25 +6,42 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { I18nProvider } from "@multica/core/i18n/react";import enCommon from "../../locales/en/common.json";import enAgents from "../../locales/en/agents.json";+import enBilling from "../../locales/en/billing.json";+import { ApiError } from "@multica/core/api";+import type { MemberWithUser, WorkspaceFeatures } from "@multica/core/types";+import { toast } from "sonner";-const TEST_RESOURCES = { en: { common: enCommon, agents: enAgents } };+const TEST_RESOURCES = { en: { common: enCommon, agents: enAgents, billing: enBilling } };const updateAgentSpy = vi.hoisted(() =>vi.fn(async (_id: string, _patch: Record<string, unknown>) => ({})),);const archiveSpy = vi.hoisted(() => vi.fn(async () => ({})));const restoreSpy = vi.hoisted(() => vi.fn(async () => ({})));+const featuresSpy = vi.hoisted(() =>+ vi.fn(async (): Promise<WorkspaceFeatures> => ({ features: {} })),+);vi.mock("@multica/core/hooks", () => ({useWorkspaceId: () => "ws-1",}));-vi.mock("@multica/core/api", () => ({+vi.mock("@multica/core/api", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@multica/core/api")>()),api: {updateAgent: updateAgentSpy,archiveAgent: archiveSpy,restoreAgent: restoreSpy,+ getWorkspaceFeatures: featuresSpy,},}));+vi.mock("@multica/core/paths", async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useWorkspacePaths: () => ({ settings: () => "/acme/settings" }),+}));+vi.mock("../../navigation", async (importOriginal) => ({+ ...(await importOriginal<object>()),+ AppLink: ({ href, children }: { href: string; children: React.ReactNode }) => <a href={href}>{children}</a>,+}));vi.mock("../../common/actor-avatar", () => ({ActorAvatar: () => <div>avatar</div>,}));@@ -88,14 +105,14 @@ function makeRow(};}-function renderToolbar(rows: AgentListRow[]) {+function renderToolbar(rows: AgentListRow[], members: MemberWithUser[] = []) {const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });const ui = (nextRows: AgentListRow[]) => (<QueryClientProvider client={qc}><I18nProvider locale="en" resources={TEST_RESOURCES}><AgentBatchToolbarrows={nextRows}- members={[]}+ members={members}currentUserId="user-1"onClear={() => {}}/>@@ -109,9 +126,25 @@ function renderToolbar(rows: AgentListRow[]) {};}+const MEMBERS = [+ { user_id: "u-a", name: "Alice", role: "member" },+ { user_id: "u-b", name: "Bob", role: "member" },+ { user_id: "u-c", name: "Carol", role: "member" },+] as unknown as MemberWithUser[];++function specificPeople(...ids: string[]) {+ return {+ permission_mode: "public_to" as const,+ invocation_targets: ids.map((id) => ({ target_type: "member", target_id: id })),+ };+}+beforeEach(() => {updateAgentSpy.mockClear();updateAgentSpy.mockResolvedValue({});+ featuresSpy.mockReset();+ featuresSpy.mockResolvedValue({ features: {} });+ vi.mocked(toast.error).mockClear();});describe("AgentBatchToolbar — action order", () => {@@ -269,3 +302,95 @@ describe("AgentBatchToolbar — bulk Set access scope", () => {expect(updateAgentSpy).not.toHaveBeenCalled();});});++describe("AgentBatchToolbar — plan without member access (MUL-9491)", () => {+ it("offers Specific people when the plan includes it", async () => {+ featuresSpy.mockResolvedValue({ features: { agent_invocation_members: "available" } });+ renderToolbar([makeRow("a", "user-1")]);+ fireEvent.click(screen.getByRole("button", { name: "Set access scope" }));+ await waitFor(() => expect(screen.getByRole("radio", { name: /^Specific people/ })).toBeEnabled());+ expect(screen.queryByText("View plans")).not.toBeInTheDocument();+ });++ it("disables Specific people in bulk when a selected agent has no member list", async () => {+ featuresSpy.mockResolvedValue({ features: { agent_invocation_members: "locked" } });+ renderToolbar(+ [+ makeRow("a", "user-1", specificPeople("u-a", "u-b")),+ makeRow("b", "user-1", { permission_mode: "public_to", invocation_targets: [{ target_type: "workspace", target_id: null }] }),+ ],+ MEMBERS,+ );+ fireEvent.click(screen.getByRole("button", { name: "Set access scope" }));+ expect(await screen.findByText("Not included in this workspace's plan.")).toBeInTheDocument();+ expect(screen.getByRole("radio", { name: /^Specific people/ })).toBeDisabled();+ expect(screen.getByRole("radio", { name: /^Entire workspace/ })).toBeEnabled();+ expect(screen.getByRole("button", { name: enBilling.paid_feature.badge_label })).toBeInTheDocument();+ });++ it("lets a locked plan bulk-reduce agents that share the same people", async () => {+ featuresSpy.mockResolvedValue({ features: { agent_invocation_members: "locked" } });+ renderToolbar(+ [makeRow("a", "user-1", specificPeople("u-a", "u-b")), makeRow("b", "user-1", specificPeople("u-a", "u-b"))],+ MEMBERS,+ );+ fireEvent.click(screen.getByRole("button", { name: "Set access scope" }));+ await screen.findByText("Read-only. Upgrade to edit.");+ const members = screen.getByRole("radio", { name: /^Specific people/ });+ expect(members).toBeEnabled();+ fireEvent.click(members);+ expect(screen.getByRole("checkbox", { name: /Bob/ })).toBeInTheDocument();+ expect(screen.queryByRole("checkbox", { name: /Carol/ })).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("checkbox", { name: /Alice/ }));+ const apply = screen.getByRole("button", { name: "Apply" });+ await waitFor(() => expect(apply).toBeEnabled());+ fireEvent.click(apply);++ await waitFor(() => expect(updateAgentSpy).toHaveBeenCalledTimes(2));+ for (const id of ["a", "b"]) {+ expect(updateAgentSpy).toHaveBeenCalledWith(id, {+ permission_mode: "public_to",+ invocation_targets: [{ target_type: "member", target_id: "u-a" }],+ });+ }+ });++ it("offers only the people every selected agent already has", async () => {+ featuresSpy.mockResolvedValue({ features: { agent_invocation_members: "locked" } });+ renderToolbar(+ [makeRow("a", "user-1", specificPeople("u-a", "u-b")), makeRow("b", "user-1", specificPeople("u-a"))],+ MEMBERS,+ );+ fireEvent.click(screen.getByRole("button", { name: "Set access scope" }));+ await screen.findByText("Read-only. Upgrade to edit.");+ const members = screen.getByRole("radio", { name: /^Specific people/ });+ expect(members).toBeEnabled();+ fireEvent.click(members);+ expect(screen.getByRole("checkbox", { name: /Alice/ })).toBeInTheDocument();+ expect(screen.queryByRole("checkbox", { name: /Bob/ })).not.toBeInTheDocument();+ expect(screen.queryByRole("checkbox", { name: /Carol/ })).not.toBeInTheDocument();+ });++ it("explains a feature_locked refusal and refetches the plan", async () => {+ featuresSpy.mockResolvedValue({ features: { agent_invocation_members: "available" } });+ updateAgentSpy.mockImplementation(async (id: string) => {+ if (id === "b") {+ throw new ApiError("locked", 403, "Forbidden", { code: "feature_locked", feature: "agent_invocation_members" });+ }+ return {};+ });+ renderToolbar([makeRow("a", "user-1"), makeRow("b", "user-1")]);+ fireEvent.click(screen.getByRole("button", { name: "Set access scope" }));+ await waitFor(() => expect(featuresSpy).toHaveBeenCalledTimes(1));+ fireEvent.click(screen.getByRole("radio", { name: /Entire workspace/ }));+ const apply = screen.getByRole("button", { name: "Apply" });+ await waitFor(() => expect(apply).toBeEnabled());+ fireEvent.click(apply);++ await waitFor(() => expect(updateAgentSpy).toHaveBeenCalledTimes(2));+ await waitFor(() =>+ expect(toast.error).toHaveBeenCalledWith(enBilling.paid_feature.locked_error),+ );+ await waitFor(() => expect(featuresSpy).toHaveBeenCalledTimes(2));+ });+});diff --git a/packages/views/agents/components/agent-batch-toolbar.tsx b/packages/views/agents/components/agent-batch-toolbar.tsxindex 095c7b68b3..4521f1c1ce 100644--- a/packages/views/agents/components/agent-batch-toolbar.tsx+++ b/packages/views/agents/components/agent-batch-toolbar.tsx@@ -1,11 +1,17 @@"use client";-import { useCallback, useEffect, useState } from "react";+import { useCallback, useEffect, useMemo, useState } from "react";import { useQueryClient } from "@tanstack/react-query";import { toast } from "sonner";import type { MemberWithUser } from "@multica/core/types";import { api } from "@multica/core/api";+import { usesInvocationMembers } from "@multica/core/agents";import { useWorkspaceId } from "@multica/core/hooks";+import {+ isFeatureLockedError,+ refreshFeaturesOnLockedError,+ usePaidFeatureAccess,+} from "@multica/core/billing";import { workspaceKeys } from "@multica/core/workspace/queries";import { Button } from "@multica/ui/components/ui/button";import {@@ -18,6 +24,7 @@ import {} from "@multica/ui/components/ui/dialog";import { Archive, ArchiveRestore, Loader2 } from "@multica/ui/icons";import { useT } from "../../i18n";+import { usePaidFeatureErrorMessage } from "../../billing";import { CollectionBatchBar } from "../../layout/collection-list";import { AccessPicker, type AccessChange } from "./inspector/access-picker";import type { AgentListRow } from "./agents-page";@@ -50,6 +57,20 @@ export function AgentBatchToolbar({const [confirmAccess, setConfirmAccess] = useState(false);const [accessChange, setAccessChange] = useState<AccessChange | null>(null);const [busy, setBusy] = useState(false);+ const paidFeatureError = usePaidFeatureErrorMessage();+ const ownedRows = rows.filter((r) => r.isOwnedByMe);+ // A locked plan still lets every owned agent shrink its own member list. In+ // bulk that means picking only people all of them already have: any+ // non-empty subset of that intersection is a reduction for each agent.+ // Without a common person, a bulk member list would be new configuration+ // for some agent, so the option stays disabled.+ const sharedMembers = useMemo(+ () => sharedInvocationMembers(rows.filter((r) => r.isOwnedByMe)),+ [rows],+ );+ const membersAccess = usePaidFeatureAccess(wsId, "agent_invocation_members", {+ hasExistingConfig: sharedMembers.length > 0,+ });// Must be stable: AccessPicker lists this in the effect that notifies us, so// an inline callback would re-notify on every render we cause by storing the@@ -69,7 +90,6 @@ export function AgentBatchToolbar({}, []);const allManageable = rows.every((r) => r.canManage);- const ownedRows = rows.filter((r) => r.isOwnedByMe);const anyOwned = ownedRows.length > 0;const anyActive = rows.some((r) => !r.agent.archived_at);const anyArchived = rows.some((r) => !!r.agent.archived_at);@@ -119,12 +139,17 @@ export function AgentBatchToolbar({onClear();setBusy(false);if (failed > 0) {- const first = settled.find((s) => s.status === "rejected") as- | PromiseRejectedResult- | undefined;- if (first) {- toast.error(first.reason instanceof Error ? first.reason.message : String(first.reason));- }+ const reasons = settled.flatMap((s) =>+ s.status === "rejected" ? [s.reason as unknown] : [],+ );+ // A plan refusal explains the failure better than whichever error came+ // first, and means this client's view of the plan is stale.+ const locked = reasons.find(isFeatureLockedError);+ if (locked) refreshFeaturesOnLockedError(qc, wsId, locked);+ const first = locked ?? reasons[0];+ toast.error(+ paidFeatureError(first, first instanceof Error ? first.message : String(first)),+ );}return { succeeded, failed };};@@ -252,6 +277,8 @@ export function AgentBatchToolbar({ownerId={currentUserId}canEdithideFooter+ membersAccess={membersAccess}+ lockedMemberPool={sharedMembers}onReadyChange={handleAccessReadyChange}/><DialogFooter>@@ -286,3 +313,20 @@ export function AgentBatchToolbar({</>);}++/** The member targets every given agent already uses; empty when any of them+ * has no specific-people list. */+function sharedInvocationMembers(rows: AgentListRow[]): string[] {+ let shared: string[] | null = null;+ for (const { agent } of rows) {+ if (!usesInvocationMembers(agent.permission_mode, agent.invocation_targets)) return [];+ const ids = new Set(+ (agent.invocation_targets ?? []).flatMap((target) =>+ target.target_type === "member" && target.target_id ? [target.target_id] : [],+ ),+ );+ shared = (shared ?? Array.from(ids)).filter((id) => ids.has(id));+ if (shared.length === 0) return [];+ }+ return shared ?? [];+}diff --git a/packages/views/agents/components/agent-detail-page.test.tsx b/packages/views/agents/components/agent-detail-page.test.tsxindex 9b33d4231d..45ecf92a49 100644--- a/packages/views/agents/components/agent-detail-page.test.tsx+++ b/packages/views/agents/components/agent-detail-page.test.tsx@@ -14,6 +14,7 @@ import { ApiError } from "@multica/core/api";import type { Agent } from "@multica/core/types";import { I18nProvider } from "@multica/core/i18n/react";import { RESOURCES } from "../../locales";+import enBilling from "../../locales/en/billing.json";import {NavigationProvider,type NavigationAdapter,@@ -39,7 +40,9 @@ vi.mock("./agent-properties-panel", () => ({<span>model:{agent.model}</span><buttontype="button"- onClick={() => void onUpdate(agent.id, { model: "new-model" })}+ // The page rethrows a failed update for the caller; the real panel+ // handles it, so the stub swallows it.+ onClick={() => void onUpdate(agent.id, { model: "new-model" }).catch(() => {})}>update model</button>@@ -226,9 +229,11 @@ vi.mock("@multica/core/paths", () => ({vi.mock("@multica/core/api", () => {class ApiError extends Error {status: number;- constructor(message: string, status: number) {+ body: unknown;+ constructor(message: string, status: number, _statusText?: string, body?: unknown) {super(message);this.status = status;+ this.body = body;}}return {@@ -481,6 +486,23 @@ describe("AgentDetailPage direct-detail fallback", () => {).not.toBeInTheDocument();});+ it("rolls back and explains a feature_locked refusal, refetching the plan", async () => {+ mockUpdateAgent.mockRejectedValue(+ new ApiError("locked", 403, "Forbidden", { code: "feature_locked", feature: "agent_invocation_members" }),+ );+ const { queryClient } = renderPage();+ const invalidate = vi.spyOn(queryClient, "invalidateQueries");+ await screen.findByRole("button", { name: "Assign work" });++ fireEvent.click(screen.getByRole("button", { name: "update model" }));++ await waitFor(() =>+ expect(mockToastError).toHaveBeenCalledWith(enBilling.paid_feature.locked_error),+ );+ expect(invalidate).toHaveBeenCalledWith({ queryKey: ["workspace-features", "ws-1"] });+ expect(await screen.findByText("model:")).toBeInTheDocument();+ });+it("optimistically updates a detail-only cache entry", async () => {agentsRef.current = [];mockGetAgent.mockResolvedValue(baseAgent);diff --git a/packages/views/agents/components/agent-detail-page.tsx b/packages/views/agents/components/agent-detail-page.tsxindex d8566c0ad5..e45f398f5b 100644--- a/packages/views/agents/components/agent-detail-page.tsx+++ b/packages/views/agents/components/agent-detail-page.tsx@@ -29,6 +29,7 @@ import {import { api, ApiError } from "@multica/core/api";import { useAuthStore } from "@multica/core/auth";import { useWorkspaceId } from "@multica/core/hooks";+import { refreshFeaturesOnLockedError } from "@multica/core/billing";import { useModalStore } from "@multica/core/modals";import { useWorkspacePaths } from "@multica/core/paths";import {@@ -80,6 +81,7 @@ import {} from "../../layout/object-page";import { ActorAvatar } from "../../common/actor-avatar";import { useT } from "../../i18n";+import { usePaidFeatureErrorMessage } from "../../billing";import { availabilityConfig } from "../presence";import {AgentAdvancedSettings,@@ -121,6 +123,7 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {const paths = useWorkspacePaths();const navigation = useNavigation();const qc = useQueryClient();+ const paidFeatureError = usePaidFeatureErrorMessage();const currentUser = useAuthStore((s) => s.user);const {@@ -289,11 +292,12 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {);}void qc.invalidateQueries({ queryKey });- toast.error(e instanceof Error ? e.message : t(($) => $.detail.update_failed_toast));+ refreshFeaturesOnLockedError(qc, wsId, e);+ toast.error(paidFeatureError(e, e instanceof Error ? e.message : t(($) => $.detail.update_failed_toast)));throw e;}},- [qc, t, wsId],+ [paidFeatureError, qc, t, wsId],);const handleArchive = async (id: string) => {diff --git a/packages/views/agents/components/agents-page.test.tsx b/packages/views/agents/components/agents-page.test.tsxindex 29f188644a..4a3626563a 100644--- a/packages/views/agents/components/agents-page.test.tsx+++ b/packages/views/agents/components/agents-page.test.tsx@@ -71,6 +71,7 @@ vi.mock("@tanstack/react-query", () => ({return { data: [], isLoading: false, isPending: false, isSuccess: true };},useQueryClient: () => ({ invalidateQueries: vi.fn() }),+ queryOptions: <T,>(options: T) => options,}));// The list virtualizes; render every row so DOM order reflects sort order.diff --git a/packages/views/agents/components/inspector/access-picker.test.tsx b/packages/views/agents/components/inspector/access-picker.test.tsxindex 34196d5980..d47ec21ea9 100644--- a/packages/views/agents/components/inspector/access-picker.test.tsx+++ b/packages/views/agents/components/inspector/access-picker.test.tsx@@ -10,6 +10,7 @@ import { I18nProvider } from "@multica/core/i18n/react";import enCommon from "../../../locales/en/common.json";import enAgents from "../../../locales/en/agents.json";import enIssues from "../../../locales/en/issues.json";+import enBilling from "../../../locales/en/billing.json";import { AccessPicker } from "./access-picker";@@ -18,11 +19,21 @@ import { AccessPicker } from "./access-picker";vi.mock("../../../common/actor-avatar", () => ({ActorAvatar: () => null,}));+vi.mock("@multica/core/paths", async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useWorkspacePaths: () => ({ settings: () => "/acme/settings" }),+}));+vi.mock("../../../navigation", async (importOriginal) => ({+ ...(await importOriginal<object>()),+ AppLink: ({ href, children }: { href: string; children: React.ReactNode }) => <a href={href}>{children}</a>,+}));const TEST_RESOURCES = {- en: { common: enCommon, agents: enAgents, issues: enIssues },+ en: { common: enCommon, agents: enAgents, issues: enIssues, billing: enBilling },};+const BADGE = enBilling.paid_feature.badge_label;+const MEMBERS = [{ user_id: "u1", name: "Alice", role: "member" },{ user_id: "u2", name: "Bob", role: "member" },@@ -176,3 +187,88 @@ describe("AccessPicker owner-only editing (MUL-3963)", () => {expect(screen.getByTestId("access-readonly")).toBeInTheDocument();});});++describe("AccessPicker on a plan without member access (MUL-9491)", () => {+ beforeEach(() => cleanup());+ afterEach(() => cleanup());++ it("offers every member and no notice when the feature is available", () => {+ renderPicker({ membersAccess: { canAdd: true, state: "available" } });+ const members = screen.getByRole("radio", { name: /^Specific people/i });+ expect(members).toBeEnabled();+ fireEvent.click(members);+ expect(screen.getByRole("checkbox", { name: /Alice/i })).toBeInTheDocument();+ expect(screen.getByRole("checkbox", { name: /Bob/i })).toBeInTheDocument();+ expect(screen.queryByText("View plans")).not.toBeInTheDocument();+ expect(screen.queryByRole("button", { name: BADGE })).not.toBeInTheDocument();+ });++ it("disables Specific people for an agent without a member list", () => {+ renderPicker({ membersAccess: { canAdd: false, state: "unavailable" } });+ expect(screen.getByRole("radio", { name: /^Specific people/i })).toBeDisabled();+ expect(screen.getByRole("radio", { name: /^Entire workspace/i })).toBeEnabled();+ expect(screen.getByText("Not included in this workspace's plan.")).toBeInTheDocument();+ });++ it("puts a Business badge beside the locked option, outside its label", () => {+ renderPicker({ membersAccess: { canAdd: false, state: "unavailable" } });+ const badge = screen.getByRole("button", { name: BADGE });+ expect(badge).toBeEnabled();+ // A control inside the label would select the option it explains.+ expect(badge.closest("label")).toBeNull();+ });++ it("keeps an existing list removable but adds nobody, and requires Only me to drop the last person", () => {+ const { onChange } = renderPicker({+ permissionMode: "public_to",+ invocationTargets: [{ target_type: "member", target_id: "u1" }],+ membersAccess: { canAdd: false, state: "read_only" },+ });+ expect(screen.getByText("Read-only. Upgrade to edit.")).toBeInTheDocument();+ expect(screen.getByRole("button", { name: BADGE })).toBeInTheDocument();+ expect(screen.getByRole("radio", { name: /^Specific people/i })).toBeChecked();+ expect(screen.getByRole("checkbox", { name: /Alice/i })).toBeChecked();+ expect(screen.queryByRole("checkbox", { name: /Bob/i })).not.toBeInTheDocument();++ fireEvent.click(screen.getByRole("checkbox", { name: /Alice/i }));+ expect(screen.getByRole("alert")).toHaveTextContent("Select at least one person before saving.");+ expect(screen.getByRole("button", { name: "Save" })).toBeDisabled();++ fireEvent.click(screen.getByRole("radio", { name: /^Only me/i }));+ fireEvent.click(screen.getByRole("button", { name: "Save" }));+ expect(onChange).toHaveBeenCalledWith({ permission_mode: "private", invocation_targets: [] });+ });+});++describe("AccessPicker with a locked member pool (bulk edit, MUL-9491)", () => {+ afterEach(() => cleanup());++ it("offers only the pool's people while adding is locked", () => {+ renderPicker({+ membersAccess: { canAdd: false, state: "read_only" },+ lockedMemberPool: ["u1"],+ });+ const members = screen.getByRole("radio", { name: /^Specific people/i });+ expect(members).toBeEnabled();+ fireEvent.click(members);+ expect(screen.getByRole("checkbox", { name: /Alice/i })).not.toBeChecked();+ expect(screen.queryByRole("checkbox", { name: /Bob/i })).not.toBeInTheDocument();+ });++ it("disables Specific people when the pool is empty", () => {+ renderPicker({+ membersAccess: { canAdd: false, state: "unavailable" },+ lockedMemberPool: [],+ });+ expect(screen.getByRole("radio", { name: /^Specific people/i })).toBeDisabled();+ });++ it("ignores the pool when the plan includes the feature", () => {+ renderPicker({+ membersAccess: { canAdd: true, state: "available" },+ lockedMemberPool: [],+ });+ fireEvent.click(screen.getByRole("radio", { name: /^Specific people/i }));+ expect(screen.getByRole("checkbox", { name: /Bob/i })).toBeInTheDocument();+ });+});diff --git a/packages/views/agents/components/inspector/access-picker.tsx b/packages/views/agents/components/inspector/access-picker.tsxindex 53f8b9d200..186a7e79ba 100644--- a/packages/views/agents/components/inspector/access-picker.tsx+++ b/packages/views/agents/components/inspector/access-picker.tsx@@ -1,6 +1,6 @@"use client";-import { useEffect, useMemo, useRef, useState } from "react";+import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";import { Globe, Loader2, Lock, Users } from "@multica/ui/icons";import type {AgentInvocationTarget,@@ -10,9 +10,11 @@ import type {MemberWithUser,} from "@multica/core/types";import { effectiveAccessScope } from "@multica/core/agents";+import type { PaidFeatureAccess } from "@multica/core/billing";import { Button } from "@multica/ui/components/ui/button";import { Checkbox } from "@multica/ui/components/ui/checkbox";import { ActorAvatar } from "../../../common/actor-avatar";+import { PaidFeatureNotice, PaidFeatureUpgradeBadge } from "../../../billing";import { useT } from "../../../i18n";export type AccessChange = {@@ -51,6 +53,8 @@ export function AccessPicker({onReadyChange,onChange,hideFooter = false,+ membersAccess,+ lockedMemberPool,}: {permissionMode: AgentPermissionMode;invocationTargets: AgentInvocationTarget[] | undefined;@@ -69,6 +73,13 @@ export function AccessPicker({/** When true, suppress the bottom Save footer — the parent dialog owns* the apply trigger (e.g. the bulk "Set access scope" dialog). */hideFooter?: boolean;+ /** The plan's `agent_invocation_members` access for this agent (or, in+ * bulk, for agents that do not use it yet). Omitted means available. */+ membersAccess?: Pick<PaidFeatureAccess, "canAdd" | "state">;+ /** Who may be picked while adding members is locked, in place of this+ * agent's own list. Bulk edit passes the people every selected agent+ * already has, so any subset is a reduction for each of them. */+ lockedMemberPool?: string[];}) {const { t } = useT("agents");const { t: tc } = useT("common");@@ -127,9 +138,19 @@ export function AccessPicker({}}, [persistedScope, persistedMembers]);- const editableMembers = ownerId+ // Without the paid feature an agent keeps the people it already has: they+ // can be unchecked, but nobody new can be picked, and an agent without a+ // member list cannot get one.+ const canAddMembers = membersAccess?.canAdd ?? true;+ const lockedPool = lockedMemberPool ?? persistedMembers;+ const membersChoiceDisabled =+ !canAddMembers &&+ (lockedMemberPool ? lockedMemberPool.length === 0 : persistedScope !== "members");+ const editableMembers = (ownerId? members.filter((member) => member.user_id !== ownerId)- : members;+ : members+ ).filter((member) => canAddMembers || lockedPool.includes(member.user_id));+ const paidState = membersAccess?.state;const sameMembers =draftMembers.length === persistedMembers.length &&@@ -262,10 +283,22 @@ export function AccessPicker({title={t(($) => $.access.members_title)}description={t(($) => $.access.members_desc)}selected={draftScope === "members"}+ disabled={membersChoiceDisabled}onSelect={() => selectDraftScope("members")}+ trailing={+ paidState === "read_only" || paidState === "unavailable" ? (+ <PaidFeatureUpgradeBadge feature="agent_invocation_members" />+ ) : null+ }/></div>+ {paidState === "read_only" || paidState === "unavailable" ? (+ <div className="border-t border-surface-border px-4 py-3 sm:px-6">+ <PaidFeatureNotice state={paidState} />+ </div>+ ) : null}+{draftScope === "members" ? (<div className="border-t border-surface-border bg-muted/20 px-4 py-5 sm:px-6"><div>@@ -355,7 +388,9 @@ function AccessChoice({title,description,selected,+ disabled = false,onSelect,+ trailing,}: {name: string;value: string;@@ -363,27 +398,37 @@ function AccessChoice({title: string;description: string;selected: boolean;+ disabled?: boolean;onSelect: () => void;+ /** Rendered beside the label, not inside it, so a control here keeps its+ * own focus and accessible name and does not toggle the radio. */+ trailing?: ReactNode;}) {+ // Same tree with or without `trailing`: a badge appearing once the plan+ // loads must not remount (and unfocus) the radio.return (- <label className="flex min-h-16 cursor-pointer items-start gap-3 px-4 py-3.5 transition-colors hover:bg-surface-hover">- <input- type="radio"- name={name}- value={value}- checked={selected}- onChange={onSelect}- className="mt-2 size-4 shrink-0 accent-foreground"- />- <span className="mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground">- <Icon className="size-4" aria-hidden="true" />- </span>- <span className="min-w-0 flex-1">- <span className="block text-body font-medium">{title}</span>- <span className="mt-0.5 block text-caption leading-5 text-muted-foreground">- {description}+ <div className="flex items-start">+ <label className="flex min-h-16 flex-1 cursor-pointer items-start gap-3 px-4 py-3.5 transition-colors hover:bg-surface-hover has-disabled:cursor-default has-disabled:opacity-60 has-disabled:hover:bg-transparent">+ <input+ type="radio"+ name={name}+ value={value}+ checked={selected}+ disabled={disabled}+ onChange={onSelect}+ className="mt-2 size-4 shrink-0 accent-foreground"+ />+ <span className="mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground">+ <Icon className="size-4" aria-hidden="true" />+ </span>+ <span className="min-w-0 flex-1">+ <span className="block text-body font-medium">{title}</span>+ <span className="mt-0.5 block text-caption leading-5 text-muted-foreground">+ {description}+ </span></span>- </span>- </label>+ </label>+ {trailing ? <div className="shrink-0 py-4 pr-4">{trailing}</div> : null}+ </div>);}diff --git a/packages/views/agents/components/tabs/agent-apps-tab.test.tsx b/packages/views/agents/components/tabs/agent-apps-tab.test.tsxindex 9d50a4767d..1abdcdfbd6 100644--- a/packages/views/agents/components/tabs/agent-apps-tab.test.tsx+++ b/packages/views/agents/components/tabs/agent-apps-tab.test.tsx@@ -3,17 +3,24 @@ import type { ReactNode } from "react";import { cleanup, render, screen, waitFor, within } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { api } from "@multica/core/api";+import { api, ApiError } from "@multica/core/api";+import { toast } from "sonner";import { I18nProvider } from "@multica/core/i18n/react";import type { Agent, AgentApp, AppsOverview } from "@multica/core/types";import enCommon from "../../../locales/en/common.json";import enAgents from "../../../locales/en/agents.json";import enSettings from "../../../locales/en/settings.json";+import enBilling from "../../../locales/en/billing.json";import { AgentAppsTab } from "./agent-apps-tab";-vi.mock("@multica/core/api", () => ({ api: {- listAgentApps: vi.fn(), getAppsOverview: vi.fn(), listAppCatalog: vi.fn(), updateAgentApps: vi.fn(),-} }));+vi.mock("@multica/core/api", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@multica/core/api")>()),+ api: {+ listAgentApps: vi.fn(), getAppsOverview: vi.fn(), listAppCatalog: vi.fn(), updateAgentApps: vi.fn(),+ getWorkspaceFeatures: vi.fn(),+ },+}));+vi.mock("sonner", () => ({ toast: { error: vi.fn(), success: vi.fn() } }));vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));vi.mock("@multica/core/paths", () => ({ useWorkspacePaths: () => ({ settings: () => "/ws/settings" }) }));vi.mock("../../../navigation", () => ({@@ -43,6 +50,7 @@ beforeEach(() => {],});vi.mocked(api.updateAgentApps).mockImplementation(async (_id, body) => ({ apps: body.apps.map((app) => ({ ...app, agent_id: "a1" })) }));+ vi.mocked(api.getWorkspaceFeatures).mockResolvedValue({ features: {} });});afterEach(() => {@@ -54,7 +62,7 @@ function renderApps() {const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });return render(<QueryClientProvider client={queryClient}>- <I18nProvider locale="en" resources={{ en: { common: enCommon, agents: enAgents, settings: enSettings } }}>+ <I18nProvider locale="en" resources={{ en: { common: enCommon, agents: enAgents, settings: enSettings, billing: enBilling } }}><AgentAppsTab agent={{ id: "a1", permission_mode: "private" } as Agent} /></I18nProvider></QueryClientProvider>,@@ -256,3 +264,74 @@ describe("AgentAppsTab", () => {}));});});++describe("AgentAppsTab on a plan without team app accounts (MUL-9491)", () => {+ const lock = () => vi.mocked(api.getWorkspaceFeatures).mockResolvedValue({ features: { team_app_accounts: "locked" } });+ const dual = (slug: string) => {+ overview.team.push({ id: `team-${slug}`, toolkit_slug: slug, status: "active", connected_at: "", last_used_at: null });+ overview.personal.push({ id: `my-${slug}`, toolkit_slug: slug, status: "active", connected_at: "", last_used_at: null });+ };++ it("does not give an agent a team-only app and shows the upgrade notice", async () => {+ lock();+ const user = userEvent.setup();+ renderApps();+ expect(await screen.findByText("Not included in this workspace's plan.")).toBeVisible();+ const toggle = screen.getByRole("switch", { name: "Enable Notion" });+ expect(toggle).toHaveAttribute("aria-disabled", "true");+ await user.click(toggle);+ expect(api.updateAgentApps).not.toHaveBeenCalled();+ });++ it("enables a dual-account app on the triggerer's account and cannot move it to the team account", async () => {+ lock();+ dual("slack");+ const user = userEvent.setup();+ renderApps();+ await screen.findByText("Not included in this workspace's plan.");+ await user.click(screen.getByRole("switch", { name: "Enable Slack" }));+ await waitFor(() => expect(api.updateAgentApps).toHaveBeenCalledWith("a1", {+ apps: [+ { toolkit_slug: "gmail", account_scope: "personal", level: "read" },+ { toolkit_slug: "slack", account_scope: "personal", level: "write" },+ ],+ }));+ const sources = await screen.findByRole("radiogroup", { name: "Account for Slack" });+ const team = within(sources).getByRole("radio", { name: "Team account" });+ expect(team).toHaveAttribute("aria-disabled", "true");+ await user.click(team);+ expect(api.updateAgentApps).toHaveBeenCalledTimes(1);+ });++ it("keeps an existing team app: it can switch to the triggerer's account or be removed, but not be raised from read", async () => {+ lock();+ dual("gmail");+ vi.mocked(api.listAgentApps).mockResolvedValue({ apps: [{ agent_id: "a1", toolkit_slug: "gmail", account_scope: "team", level: "read" }] });+ const user = userEvent.setup();+ renderApps();+ // Once for the tab, once where "Allow all actions" would raise the level.+ expect(await screen.findAllByText("Read-only. Upgrade to edit.")).toHaveLength(2);+ expect(screen.queryByRole("button", { name: "Allow all actions" })).not.toBeInTheDocument();+ const sources = screen.getByRole("radiogroup", { name: "Account for Gmail" });+ expect(within(sources).getByRole("radio", { name: "Team account" })).toBeChecked();+ await user.click(within(sources).getByRole("radio", { name: "Triggerer's account" }));+ await waitFor(() => expect(api.updateAgentApps).toHaveBeenCalledWith("a1", {+ apps: [{ toolkit_slug: "gmail", account_scope: "personal", level: "read" }],+ }));+ await user.click(screen.getByRole("switch", { name: "Enable Gmail" }));+ await waitFor(() => expect(api.updateAgentApps).toHaveBeenLastCalledWith("a1", { apps: [] }));+ });++ it("explains a feature_locked refusal and refetches the plan", async () => {+ vi.mocked(api.updateAgentApps).mockRejectedValue(+ new ApiError("locked", 403, "Forbidden", { code: "feature_locked", feature: "team_app_accounts" }),+ );+ const user = userEvent.setup();+ renderApps();+ const toggle = await screen.findByRole("switch", { name: "Enable Notion" });+ await waitFor(() => expect(toggle).not.toHaveAttribute("aria-disabled", "true"));+ await user.click(toggle);+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith(enBilling.paid_feature.locked_error));+ await waitFor(() => expect(api.getWorkspaceFeatures).toHaveBeenCalledTimes(2));+ });+});diff --git a/packages/views/agents/components/tabs/agent-apps-tab.tsx b/packages/views/agents/components/tabs/agent-apps-tab.tsxindex f630868c5e..4c10555942 100644--- a/packages/views/agents/components/tabs/agent-apps-tab.tsx+++ b/packages/views/agents/components/tabs/agent-apps-tab.tsx@@ -1,7 +1,7 @@"use client";import { useMemo } from "react";-import { useQuery } from "@tanstack/react-query";+import { useQuery, useQueryClient } from "@tanstack/react-query";import { Radio } from "@base-ui/react/radio";import { RadioGroup } from "@base-ui/react/radio-group";import { toast } from "sonner";@@ -16,6 +16,7 @@ import {useRestoreAppAccess,} from "@multica/core/connected-apps";import { useWorkspacePaths } from "@multica/core/paths";+import { refreshFeaturesOnLockedError, usePaidFeatureAccess } from "@multica/core/billing";import { cn } from "@multica/ui/lib/utils";import type {Agent,@@ -26,6 +27,7 @@ import type {import { ComposioToolkitLogo } from "../../../common/composio-toolkit-logo";import { SavedAppRestriction } from "../../../common/saved-app-restriction";import { AppLink } from "../../../navigation";+import { PaidFeatureNotice, usePaidFeatureErrorMessage } from "../../../billing";import { useT } from "../../../i18n";import { ObjectSectionEmpty } from "../../../layout/object-page";@@ -43,6 +45,8 @@ export function AgentAppsTab({ agent }: { agent: Agent }) {const catalog = useQuery(appCatalogOptions(wsId));const update = useUpdateAgentApps(agent.id);const restore = useRestoreAppAccess();+ const qc = useQueryClient();+ const paidFeatureError = usePaidFeatureErrorMessage();const canManageTeam = overview.data?.can_manage ?? false;const apps = useMemo(() => appsQuery.data ?? [], [appsQuery.data]);@@ -57,6 +61,13 @@ export function AgentAppsTab({ agent }: { agent: Agent }) {for (const c of overview.data?.personal ?? []) if (c.status === "active") set.add(`personal:${c.toolkit_slug}`);return set;}, [overview.data]);+ // Without the paid feature the agent keeps its team-account apps: they can+ // be removed, switched to the triggerer's account or lowered to read, but+ // no app can move onto the team account and none can be raised from read.+ const teamAccess = usePaidFeatureAccess(wsId, "team_app_accounts", {+ hasExistingConfig: apps.some((a) => a.account_scope === "team"),+ });+ const canAddTeam = teamAccess.canAdd;const visibleSlugs = useMemo(() => {const slugs = new Set(apps.map((app) => app.toolkit_slug));for (const scope of SCOPES) {@@ -78,7 +89,12 @@ export function AgentAppsTab({ agent }: { agent: Agent }) {level: a.level,})),},- { onError: (e) => toast.error(e instanceof Error && e.message ? e.message : t(($) => $.tab_body.connected_apps.save_failed_toast)) },+ {+ onError: (e) => {+ refreshFeaturesOnLockedError(qc, wsId, e);+ toast.error(paidFeatureError(e, e instanceof Error && e.message ? e.message : t(($) => $.tab_body.connected_apps.save_failed_toast)));+ },+ },);};const patch = (slug: string, change: Partial<AgentApp>) =>@@ -110,6 +126,11 @@ export function AgentAppsTab({ agent }: { agent: Agent }) {? () => restore.mutateAsync({ catalog: true }) : undefined} />)}+ {canManageTeam && (teamAccess.state === "read_only" || teamAccess.state === "unavailable") &&+ (overview.data?.team ?? []).some((c) => c.status === "active") ? (+ <PaidFeatureNotice state={teamAccess.state} />+ ) : null}+{visibleSlugs.length === 0 ? (<ObjectSectionEmpty icon={Plug} description={t(($) => $.tab_body.connected_apps.empty)} />) : (@@ -121,12 +142,14 @@ export function AgentAppsTab({ agent }: { agent: Agent }) {const hasTeam = connected.has(`team:${slug}`);const hasPersonal = connected.has(`personal:${slug}`);const availableScopes = SCOPES.filter((scope) => connected.has(`${scope}:${slug}`));- const defaultScope: AppAccountScope = hasTeam && canManageTeam && (entry?.recommended_scope === "team" || !hasPersonal)+ const canUseTeam = canManageTeam && (canAddTeam || app?.account_scope === "team");+ const defaultScope: AppAccountScope = hasTeam && canManageTeam && canAddTeam && (entry?.recommended_scope === "team" || !hasPersonal)? "team" : "personal";const scope = app?.account_scope ?? defaultScope;const isConnected = connected.has(`${scope}:${slug}`);const lockedTeam = scope === "team" && !canManageTeam;- const canEnable = catalog.isSuccess && !!entry && entry.allowed !== false && (hasPersonal || (hasTeam && canManageTeam));+ const canEnable = catalog.isSuccess && !!entry && entry.allowed !== false && (hasPersonal || (hasTeam && canManageTeam && canAddTeam));+ const canRaiseLevel = scope !== "team" || canAddTeam;const AccountIcon = scope === "team" ? Users : User;const status =scope === "team"@@ -173,7 +196,7 @@ export function AgentAppsTab({ agent }: { agent: Agent }) {value={scope}disabled={update.isPending || lockedTeam || entry?.allowed === false}onValueChange={(value) => {- if ((value === "team" || value === "personal") && value !== scope && canManageTeam && entry?.allowed !== false && !update.isPending) patch(slug, { account_scope: value });+ if ((value === "team" || value === "personal") && value !== scope && canManageTeam && (value !== "team" || canUseTeam) && entry?.allowed !== false && !update.isPending) patch(slug, { account_scope: value });}}>{SCOPES.map((value) => (@@ -181,7 +204,7 @@ export function AgentAppsTab({ agent }: { agent: Agent }) {key={value}value={value}className="inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-[calc(var(--radius)-3px)] border border-transparent px-1.5 py-0.5 text-caption font-medium whitespace-nowrap text-muted-foreground transition-[color,background-color,border-color,box-shadow] hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring data-disabled:pointer-events-none data-disabled:opacity-50 data-checked:bg-background data-checked:text-foreground data-checked:shadow-sm dark:data-checked:bg-input/60"- disabled={value === "team" && !canManageTeam}+ disabled={value === "team" && !canUseTeam}title={!canManageTeam && value === "team" ? t(($) => $.tab_body.connected_apps.team_admin_only) : undefined}>{value === "team" && !canManageTeam && <Lock className="size-3" />}@@ -203,13 +226,20 @@ export function AgentAppsTab({ agent }: { agent: Agent }) {</div>{app?.level === "read" && (<div className="w-full">- <SavedAppRestriction kind="agent" onRestore={lockedTeam ? undefined : () => update.mutateAsync({- apps: apps.map((a) => ({- toolkit_slug: a.toolkit_slug,- account_scope: a.account_scope,- level: a.toolkit_slug === slug ? "write" : a.level,- })),- })} />+ <SavedAppRestriction+ kind="agent"+ restoreUnavailable={!lockedTeam && !canRaiseLevel ? <PaidFeatureNotice state="read_only" /> : undefined}+ onRestore={lockedTeam || !canRaiseLevel ? undefined : () => update.mutateAsync({+ apps: apps.map((a) => ({+ toolkit_slug: a.toolkit_slug,+ account_scope: a.account_scope,+ level: a.toolkit_slug === slug ? "write" : a.level,+ })),+ }).catch((e: unknown) => {+ refreshFeaturesOnLockedError(qc, wsId, e);+ throw e;+ })}+ /></div>)}{app && (overview.data?.[scope]?.some((c) => c.toolkit_slug === slug && c.actions_blocked === true)) && (diff --git a/packages/views/agents/create/agent-configuration-panel.test.tsx b/packages/views/agents/create/agent-configuration-panel.test.tsxnew file mode 100644index 0000000000..b8b9066a1b--- /dev/null+++ b/packages/views/agents/create/agent-configuration-panel.test.tsx@@ -0,0 +1,103 @@+// @vitest-environment jsdom++import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { cleanup, fireEvent, screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { setApiInstance } from "@multica/core/api";+import type { ApiClient } from "@multica/core/api/client";+import { EMPTY_AGENT_DRAFT, type AgentDraft } from "@multica/core/agents";+import type { MemberWithUser, WorkspaceFeatureState } from "@multica/core/types";+import { renderWithI18n } from "../../test/i18n";+import enBilling from "../../locales/en/billing.json";+import { AgentConfigurationPanel } from "./agent-configuration-panel";++vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));+vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => null }));+vi.mock("../../common/avatar-upload-control", () => ({ AvatarUploadControl: () => null }));+vi.mock("../components/runtime-picker", () => ({ RuntimePicker: () => null }));+vi.mock("../components/skill-multi-select", () => ({ SkillMultiSelect: () => null }));+vi.mock("@multica/core/paths", async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useWorkspacePaths: () => ({ settings: () => "/acme/settings" }),+}));+vi.mock("../../navigation", async (importOriginal) => ({+ ...(await importOriginal<object>()),+ AppLink: ({ href, children }: { href: string; children: React.ReactNode }) => <a href={href}>{children}</a>,+}));++const MEMBERS = [+ { user_id: "me", name: "Me" },+ { user_id: "u1", name: "Alice" },+ { user_id: "u2", name: "Bob" },+] as unknown as MemberWithUser[];++let feature: WorkspaceFeatureState;++function renderPanel(draft: Partial<AgentDraft> = {}) {+ const onChange = vi.fn();+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ renderWithI18n(+ <QueryClientProvider client={qc}>+ <AgentConfigurationPanel+ draft={{ ...EMPTY_AGENT_DRAFT, name: "New agent", ...draft }}+ onChange={onChange}+ runtimes={[]}+ runtimesLoading={false}+ members={MEMBERS}+ currentUserId="me"+ nameError={null}+ onNameChange={vi.fn()}+ />+ </QueryClientProvider>,+ );+ return { onChange };+}++const BADGE = enBilling.paid_feature.badge_label;++function membersOption() {+ return screen.getByRole("radio", { name: /Specific people/ });+}++describe("AgentConfigurationPanel member access (MUL-9491)", () => {+ beforeEach(() => {+ feature = "available";+ setApiInstance({+ getWorkspaceFeatures: vi.fn(async () => ({ features: { agent_invocation_members: feature } })),+ } as unknown as ApiClient);+ });+ afterEach(cleanup);++ it("offers Specific people when the plan includes it", async () => {+ const { onChange } = renderPanel();+ await waitFor(() => expect(membersOption()).toBeEnabled());+ fireEvent.click(membersOption());+ expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ permissionScope: "members" }));+ expect(screen.queryByText("View plans")).not.toBeInTheDocument();+ expect(screen.queryByRole("button", { name: BADGE })).not.toBeInTheDocument();+ });++ it("disables Specific people on a locked plan", async () => {+ feature = "locked";+ const { onChange } = renderPanel();+ expect(await screen.findByText("Not included in this workspace's plan.")).toBeInTheDocument();+ expect(membersOption()).toBeDisabled();+ fireEvent.click(membersOption());+ expect(onChange).not.toHaveBeenCalled();+ // The badge sits beside the option, not inside it.+ const badge = screen.getByRole("button", { name: BADGE });+ expect(badge).toBeEnabled();+ expect(membersOption()).not.toContainElement(badge);+ });++ it("lets a draft that already picked people drop them on a locked plan, but not add more", async () => {+ feature = "locked";+ renderPanel({ permissionScope: "members", memberIds: new Set(["u1"]) });+ await screen.findByText("Not included in this workspace's plan.");+ expect(membersOption()).toBeEnabled();+ const checkboxes = screen.getAllByRole("checkbox");+ // Alice (picked) can be unchecked; Bob cannot be added.+ expect(checkboxes[0]).not.toHaveAttribute("aria-disabled");+ expect(checkboxes[1]).toHaveAttribute("aria-disabled", "true");+ });+});diff --git a/packages/views/agents/create/agent-configuration-panel.tsx b/packages/views/agents/create/agent-configuration-panel.tsxindex a947ba08b3..d4c52e54fe 100644--- a/packages/views/agents/create/agent-configuration-panel.tsx+++ b/packages/views/agents/create/agent-configuration-panel.tsx@@ -12,12 +12,15 @@ import {type AgentPermissionScope,} from "@multica/core/agents";import { useConfigStore } from "@multica/core/config";+import { usePaidFeatureAccess } from "@multica/core/billing";+import { useWorkspaceId } from "@multica/core/hooks";import type { MemberWithUser, RuntimeDevice } from "@multica/core/types";import { Checkbox } from "@multica/ui/components/ui/checkbox";import { Input } from "@multica/ui/components/ui/input";import { Textarea } from "@multica/ui/components/ui/textarea";import { cn } from "@multica/ui/lib/utils";import { ActorAvatar } from "../../common/actor-avatar";+import { PaidFeatureNotice, PaidFeatureUpgradeBadge } from "../../billing";import { AvatarUploadControl } from "../../common/avatar-upload-control";import { useT } from "../../i18n";import {@@ -90,6 +93,14 @@ export function AgentConfigurationPanel({(member) => member.user_id !== currentUserId,);const runtimeLocked = runtimeSwitchPending || runtimeSwitchInFlight;+ // The agent does not exist yet, so a plan without member access makes the+ // option unavailable. A draft that already picked people (restored, or+ // seeded before the plan changed) can still drop them or switch away.+ const wsId = useWorkspaceId();+ const invocationMembers = usePaidFeatureAccess(wsId, "agent_invocation_members", {+ hasExistingConfig: false,+ });+ const canAddMembers = invocationMembers.canAdd;// The Qoder bridge refuses tasks from agents with skills or per-agent// config, so the fields that would produce them are not offered.const qoderRuntime = selectedRuntime?.provider === "qoder_cloud";@@ -291,41 +302,64 @@ export function AgentConfigurationPanel({role="radiogroup"aria-label={t(($) => $.creation_studio.sections.access)}>- {PERMISSION_SCOPES.map((scope) => (- <button- key={scope}- type="button"- role="radio"- aria-checked={draft.permissionScope === scope}- onClick={() => set("permissionScope", scope)}- className={cn(- "flex w-full items-start gap-3 rounded-md px-3 py-2.5 text-left transition-colors",- "hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",- draft.permissionScope === scope && "bg-muted",- )}- >- <span- className={cn(- "mt-1 flex size-3.5 shrink-0 items-center justify-center rounded-full border",- draft.permissionScope === scope && "border-primary",- )}- aria-hidden="true"- >- {draft.permissionScope === scope ? (- <span className="size-1.5 rounded-full bg-primary" />+ {PERMISSION_SCOPES.map((scope) => {+ // The badge is a sibling of the radio, not inside it, so it keeps+ // its own focus and name and never selects the option.+ const showBadge =+ scope === "members" && invocationMembers.state === "unavailable";+ return (+ <div key={scope} className="relative">+ <button+ type="button"+ role="radio"+ aria-checked={draft.permissionScope === scope}+ disabled={+ scope === "members" &&+ !canAddMembers &&+ draft.permissionScope !== "members"+ }+ onClick={() => set("permissionScope", scope)}+ className={cn(+ "flex w-full items-start gap-3 rounded-md px-3 py-2.5 text-left transition-colors",+ "hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ "disabled:cursor-default disabled:opacity-60 disabled:hover:bg-transparent",+ draft.permissionScope === scope && "bg-muted",+ showBadge && "pr-28",+ )}+ >+ <span+ className={cn(+ "mt-1 flex size-3.5 shrink-0 items-center justify-center rounded-full border",+ draft.permissionScope === scope && "border-primary",+ )}+ aria-hidden="true"+ >+ {draft.permissionScope === scope ? (+ <span className="size-1.5 rounded-full bg-primary" />+ ) : null}+ </span>+ <span className="min-w-0">+ <span className="block text-body font-medium">+ {t(($) => $.creation_studio.access[scope].title)}+ </span>+ <span className="mt-0.5 block text-caption leading-5 text-muted-foreground">+ {t(($) => $.creation_studio.access[scope].description)}+ </span>+ </span>+ </button>+ {showBadge ? (+ <PaidFeatureUpgradeBadge+ feature="agent_invocation_members"+ className="absolute top-3 right-3"+ />) : null}- </span>- <span className="min-w-0">- <span className="block text-body font-medium">- {t(($) => $.creation_studio.access[scope].title)}- </span>- <span className="mt-0.5 block text-caption leading-5 text-muted-foreground">- {t(($) => $.creation_studio.access[scope].description)}- </span>- </span>- </button>- ))}+ </div>+ );+ })}</div>+ {invocationMembers.state === "unavailable" ? (+ <PaidFeatureNotice state="unavailable" className="px-5 pb-3" />+ ) : null}{draft.permissionScope === "members" ? (<div className="max-h-48 overflow-y-auto p-2">{otherMembers.map((member) => {@@ -337,6 +371,7 @@ export function AgentConfigurationPanel({><Checkboxchecked={checked}+ disabled={!checked && !canAddMembers}onCheckedChange={(value) => {const next = new Set(draft.memberIds);if (value === true) next.add(member.user_id);diff --git a/packages/views/agents/create/manual-create-agent-page.tsx b/packages/views/agents/create/manual-create-agent-page.tsxindex 0da01a8758..5370a381ab 100644--- a/packages/views/agents/create/manual-create-agent-page.tsx+++ b/packages/views/agents/create/manual-create-agent-page.tsx@@ -9,6 +9,7 @@ import {toStoredAgentDraft,} from "@multica/core/agents";import { useWorkspaceId } from "@multica/core/hooks";+import { usePaidFeatureAccess } from "@multica/core/billing";import { useWorkspacePaths } from "@multica/core/paths";import { runtimeDisplayLabel } from "@multica/core/runtimes";import type { RuntimeDevice } from "@multica/core/types";@@ -70,6 +71,11 @@ export function ManualCreateAgentPage() {? agents.find((agent) => agent.id === duplicateId) ?? null: null;+ // A new agent has no member list yet, so a locked plan is "unavailable".+ const invocationMembers = usePaidFeatureAccess(wsId, "agent_invocation_members", {+ hasExistingConfig: false,+ });+// True when a duplicate had to fall back to another runtime, which drops the// source's model / thinking / speed. The notice explains the empty fields.const [duplicateRuntimeReset, setDuplicateRuntimeReset] = useState(false);@@ -89,6 +95,7 @@ export function ManualCreateAgentPage() {currentUserId: form.currentUserId,fallbackRuntimeId: form.usableRuntimes[0]?.id ?? "",nameSuffix: t(($) => $.create_dialog.duplicate_copy_suffix),+ canAddInvocationMembers: invocationMembers.isPending ? null : invocationMembers.canAdd,onSeed: (duplicated, runtimeReset) => {// Only the forced fallback gets the notice; a later manual runtime switch// is the user's own doing and needs no explanation.diff --git a/packages/views/agents/create/use-create-agent-submit.test.tsx b/packages/views/agents/create/use-create-agent-submit.test.tsxindex abb16ad144..b545d5c516 100644--- a/packages/views/agents/create/use-create-agent-submit.test.tsx+++ b/packages/views/agents/create/use-create-agent-submit.test.tsx@@ -9,6 +9,9 @@ import { I18nProvider } from "@multica/core/i18n/react";import type { Agent } from "@multica/core/types";import { workspaceKeys } from "@multica/core/workspace/queries";import enAgents from "../../locales/en/agents.json";+import enBilling from "../../locales/en/billing.json";+import { ApiError } from "@multica/core/api";+import { workspaceFeatureKeys } from "@multica/core/billing";const mockCreateAgent = vi.hoisted(() => vi.fn());const mockReplace = vi.hoisted(() => vi.fn());@@ -32,9 +35,11 @@ vi.mock("../../navigation", () => ({vi.mock("@multica/core/api", () => {class ApiError extends Error {status: number;- constructor(message: string, status: number) {+ body: unknown;+ constructor(message: string, status: number, _statusText?: string, body?: unknown) {super(message);this.status = status;+ this.body = body;}}return {@@ -80,7 +85,7 @@ const CREATED_AGENT: Agent = {function wrapper(queryClient: QueryClient) {return function TestWrapper({ children }: { children: ReactNode }) {return (- <I18nProvider locale="en" resources={{ en: { agents: enAgents } }}>+ <I18nProvider locale="en" resources={{ en: { agents: enAgents, billing: enBilling } }}><QueryClientProvider client={queryClient}>{children}</QueryClientProvider>@@ -148,3 +153,29 @@ describe("useCreateAgentSubmit cache handoff", () => {});});});++describe("useCreateAgentSubmit plan refusal", () => {+ it("shows the paid-feature message for feature_locked and refetches the plan", async () => {+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const invalidate = vi.spyOn(queryClient, "invalidateQueries");+ mockCreateAgent.mockRejectedValue(+ new ApiError("locked", 403, "Forbidden", { code: "feature_locked", feature: "agent_invocation_members" }),+ );+ const { result } = renderHook(+ () =>+ useCreateAgentSubmit({+ draft: { ...EMPTY_AGENT_DRAFT, name: "Shared", runtimeId: "runtime-1", permissionScope: "members", memberIds: new Set(["u2"]) },+ runtimeId: "runtime-1",+ squadId: null,+ }),+ { wrapper: wrapper(queryClient) },+ );+ await act(async () => {+ await result.current.create();+ });+ expect(result.current.formError).toBe(enBilling.paid_feature.locked_error);+ expect(result.current.nameError).toBeNull();+ expect(invalidate).toHaveBeenCalledWith({ queryKey: workspaceFeatureKeys.all("ws-1") });+ expect(mockReplace).not.toHaveBeenCalled();+ });+});diff --git a/packages/views/agents/create/use-create-agent-submit.ts b/packages/views/agents/create/use-create-agent-submit.tsindex e57b5117d5..c2c34fd21f 100644--- a/packages/views/agents/create/use-create-agent-submit.ts+++ b/packages/views/agents/create/use-create-agent-submit.ts@@ -6,6 +6,7 @@ import { toast } from "sonner";import { buildCreateAgentRequest, type AgentDraft } from "@multica/core/agents";import { api, ApiError } from "@multica/core/api";import { useWorkspaceId } from "@multica/core/hooks";+import { refreshFeaturesOnLockedError } from "@multica/core/billing";import { useWorkspacePaths } from "@multica/core/paths";import type { Agent } from "@multica/core/types";import {@@ -15,6 +16,7 @@ import {import { useNavigation } from "../../navigation";import { withSquadParam } from "./squad-param";import { useT } from "../../i18n";+import { usePaidFeatureErrorMessage } from "../../billing";interface AgentCreateErrors {nameError: string | null;@@ -58,6 +60,7 @@ export function useCreateAgentSubmit(options: {const paths = useWorkspacePaths();const navigation = useNavigation();const qc = useQueryClient();+ const paidFeatureError = usePaidFeatureErrorMessage();const [creating, setCreating] = useState(false);const [nameError, setNameError] = useState<string | null>(null);@@ -129,8 +132,11 @@ export function useCreateAgentSubmit(options: {t(($) => $.creation_studio.create_failed),t(($) => $.creation_studio.name_conflict),);+ refreshFeaturesOnLockedError(qc, wsId, error);setNameError(nextErrors.nameError);- setFormError(nextErrors.formError);+ setFormError(+ nextErrors.formError === null ? null : paidFeatureError(error, nextErrors.formError),+ );setCreating(false);}};diff --git a/packages/views/agents/create/use-duplicate-draft-seed.test.tsx b/packages/views/agents/create/use-duplicate-draft-seed.test.tsxindex f72d70f7ba..aa45f08b8b 100644--- a/packages/views/agents/create/use-duplicate-draft-seed.test.tsx+++ b/packages/views/agents/create/use-duplicate-draft-seed.test.tsx@@ -38,17 +38,26 @@ const SOURCE = {skills: [],} as unknown as Agent;-function setup(initial: { runtimesSettled: boolean; runtimes: RuntimeDevice[] }) {+type SeedProps = {+ runtimesSettled: boolean;+ runtimes: RuntimeDevice[];+ canAddInvocationMembers?: boolean | null;+ source?: Agent;+};++function setup(initial: SeedProps) {const onSeed = vi.fn<(draft: AgentDraft, runtimeReset: boolean) => void>();const view = renderHook(- (props: { runtimesSettled: boolean; runtimes: RuntimeDevice[] }) =>+ (props: SeedProps) =>useDuplicateDraftSeed({- source: SOURCE,+ source: props.source ?? SOURCE,runtimesSettled: props.runtimesSettled,runtimes: props.runtimes,currentUserId: "user-1",fallbackRuntimeId: props.runtimes[0]?.id ?? "",nameSuffix: " copy",+ canAddInvocationMembers:+ props.canAddInvocationMembers === undefined ? true : props.canAddInvocationMembers,onSeed,}),{ initialProps: initial },@@ -122,4 +131,47 @@ describe("useDuplicateDraftSeed", () => {expect(onSeed).toHaveBeenCalledTimes(1);expect(onSeed.mock.calls[0]![1]).toBe(true);});++ describe("member access on a locked plan", () => {+ const SHARED = {+ ...SOURCE,+ permission_mode: "public_to",+ invocation_targets: [{ target_type: "member", target_id: "user-2" }],+ } as unknown as Agent;++ it("waits for the plan, then copies a member list as Only me when it is locked", () => {+ const { onSeed, view } = setup({+ runtimesSettled: true,+ runtimes: [SOURCE_RUNTIME],+ source: SHARED,+ canAddInvocationMembers: null,+ });+ expect(onSeed).not.toHaveBeenCalled();++ view.rerender({+ runtimesSettled: true,+ runtimes: [SOURCE_RUNTIME],+ source: SHARED,+ canAddInvocationMembers: false,+ });+ expect(onSeed).toHaveBeenCalledTimes(1);+ expect(onSeed.mock.calls[0]![0]).toMatchObject({+ permissionScope: "private",+ memberIds: new Set(),+ });+ });++ it("copies the member list when the plan includes it", () => {+ const { onSeed } = setup({+ runtimesSettled: true,+ runtimes: [SOURCE_RUNTIME],+ source: SHARED,+ canAddInvocationMembers: true,+ });+ expect(onSeed.mock.calls[0]![0]).toMatchObject({+ permissionScope: "members",+ memberIds: new Set(["user-2"]),+ });+ });+ });});diff --git a/packages/views/agents/create/use-duplicate-draft-seed.ts b/packages/views/agents/create/use-duplicate-draft-seed.tsindex ed09680452..c3ec5d5297 100644--- a/packages/views/agents/create/use-duplicate-draft-seed.ts+++ b/packages/views/agents/create/use-duplicate-draft-seed.ts@@ -24,6 +24,7 @@ export function useDuplicateDraftSeed({currentUserId,fallbackRuntimeId,nameSuffix,+ canAddInvocationMembers,onSeed,}: {source: Agent | null;@@ -33,6 +34,9 @@ export function useDuplicateDraftSeed({currentUserId: string | null;fallbackRuntimeId: string;nameSuffix: string;+ /** Whether the plan allows a member list on a new agent; `null` while the+ * workspace's features are loading. A locked plan copies "Only me". */+ canAddInvocationMembers: boolean | null;onSeed: (draft: AgentDraft, runtimeReset: boolean) => void;}): void {const seededRef = useRef(false);@@ -42,16 +46,23 @@ export function useDuplicateDraftSeed({onSeedRef.current = onSeed;useEffect(() => {- if (seededRef.current || !source || !runtimesSettled) return;+ if (+ seededRef.current ||+ !source ||+ !runtimesSettled ||+ canAddInvocationMembers === null+ ) return;seededRef.current = true;const draft = buildDuplicateDraft(source, {runtimes,currentUserId,fallbackRuntimeId,nameSuffix,+ canAddInvocationMembers,});onSeedRef.current(draft, draft.runtimeId !== source.runtime_id);}, [+ canAddInvocationMembers,currentUserId,fallbackRuntimeId,nameSuffix,diff --git a/packages/views/billing/index.ts b/packages/views/billing/index.tsindex 069c936dff..ec6cdf4bfa 100644--- a/packages/views/billing/index.ts+++ b/packages/views/billing/index.ts@@ -1,5 +1,6 @@export { BillingReturnPage } from "./billing-return-page";export { PaidFeatureNotice, usePaidFeatureErrorMessage } from "./paid-feature-notice";+export { PaidFeatureUpgradeBadge, type UpgradeBadgeFeature } from "./paid-feature-upgrade-badge";export { TrialStatus } from "./trial-status";export { WorkspaceTrialNotices } from "./trial-notices";export {diff --git a/packages/views/billing/paid-feature-upgrade-badge.test.tsx b/packages/views/billing/paid-feature-upgrade-badge.test.tsxnew file mode 100644index 0000000000..d56ea6cf45--- /dev/null+++ b/packages/views/billing/paid-feature-upgrade-badge.test.tsx@@ -0,0 +1,82 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { cleanup, render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { I18nProvider } from "@multica/core/i18n/react";+import type { MemberRole } from "@multica/core/types";+import enBilling from "../locales/en/billing.json";+import { PaidFeatureUpgradeBadge, type UpgradeBadgeFeature } from "./paid-feature-upgrade-badge";++const member = vi.hoisted(() => ({ role: "member" as MemberRole | null }));++vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));+vi.mock("@multica/core/permissions", () => ({+ useCurrentMember: () => ({ userId: "user-1", role: member.role, member: null, isLoading: false }),+}));+vi.mock("@multica/core/paths", async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useWorkspacePaths: () => ({ settings: () => "/acme/settings" }),+}));+vi.mock("../navigation", async (importOriginal) => ({+ ...(await importOriginal<object>()),+ AppLink: ({ href, children, ...props }: React.ComponentProps<"a"> & { href: string }) => (+ <a href={href} {...props}>{children}</a>+ ),+}));++const card = enBilling.paid_feature.upgrade_card;++function renderBadge(feature: UpgradeBadgeFeature = "agent_invocation_members") {+ render(+ <I18nProvider locale="en" resources={{ en: { billing: enBilling } }}>+ <PaidFeatureUpgradeBadge feature={feature} />+ </I18nProvider>,+ );+ return screen.getByRole("button", { name: enBilling.paid_feature.badge_label });+}++afterEach(() => {+ cleanup();+ member.role = "member";+});++describe("PaidFeatureUpgradeBadge", () => {+ it("is a named button showing Business, with the card closed", () => {+ const badge = renderBadge();+ expect(badge).toHaveTextContent("Business");+ expect(screen.queryByText(card.agent_invocation_members.title)).not.toBeInTheDocument();+ });++ it("opens the card on click", async () => {+ const user = userEvent.setup();+ await user.click(renderBadge("runtime_member_sharing"));+ expect(await screen.findByText(card.runtime_member_sharing.title)).toBeVisible();+ expect(screen.getByText(card.runtime_member_sharing.description)).toBeVisible();+ });++ it.each(["{Enter}", " "])("opens the card from the keyboard (%s)", async (key) => {+ const user = userEvent.setup();+ const badge = renderBadge();+ badge.focus();+ expect(badge).toHaveFocus();+ await user.keyboard(key);+ expect(await screen.findByText(card.agent_invocation_members.title)).toBeVisible();+ expect(screen.getByText(card.agent_invocation_members.description)).toBeVisible();+ });++ it.each(["owner", "admin"] as const)("sends a workspace %s to Billing", async (role) => {+ member.role = role;+ const user = userEvent.setup();+ await user.click(renderBadge());+ const link = await screen.findByRole("link", { name: enBilling.paid_feature.upgrade_to_business });+ expect(link).toHaveAttribute("href", "/acme/settings?tab=billing");+ expect(screen.queryByText(enBilling.paid_feature.ask_admin)).not.toBeInTheDocument();+ });++ it("tells a member to ask an admin, without an upgrade action", async () => {+ member.role = "member";+ const user = userEvent.setup();+ await user.click(renderBadge());+ expect(await screen.findByText(enBilling.paid_feature.ask_admin)).toBeVisible();+ expect(screen.queryByRole("link")).not.toBeInTheDocument();+ });+});diff --git a/packages/views/billing/paid-feature-upgrade-badge.tsx b/packages/views/billing/paid-feature-upgrade-badge.tsxnew file mode 100644index 0000000000..41716d01fc--- /dev/null+++ b/packages/views/billing/paid-feature-upgrade-badge.tsx@@ -0,0 +1,89 @@+"use client";++import { Sparkles } from "@multica/ui/icons";+import type { PaidFeature } from "@multica/core/types";+import { useWorkspaceId } from "@multica/core/hooks";+import { useCurrentMember } from "@multica/core/permissions";+import { useWorkspacePaths } from "@multica/core/paths";+import { Badge } from "@multica/ui/components/ui/badge";+import { buttonVariants } from "@multica/ui/components/ui/button";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@multica/ui/components/ui/popover";+import { cn } from "@multica/ui/lib/utils";+import { AppLink } from "../navigation";+import { useT } from "../i18n";++/** Business features whose locked option sits in a picker next to free ones. */+export type UpgradeBadgeFeature = Extract<+ PaidFeature,+ "agent_invocation_members" | "runtime_member_sharing"+>;++/**+ * The "Business" badge beside a locked paid option (MUL-9416). It is its own+ * focusable button, never part of the option's label, and opens a card that+ * says what the feature is and how to get it: owners and admins go to+ * Billing, other members are told to ask an admin.+ */+export function PaidFeatureUpgradeBadge({+ feature,+ className,+}: {+ feature: UpgradeBadgeFeature;+ className?: string;+}) {+ const { t } = useT("billing");+ return (+ <Popover>+ <PopoverTrigger+ aria-label={t(($) => $.paid_feature.badge_label)}+ className={cn(+ "inline-flex h-5 shrink-0 items-center gap-1 rounded-md bg-brand/10 px-1.5 text-caption font-medium text-brand transition-colors hover:bg-brand/15 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ className,+ )}+ >+ <Sparkles className="size-3" aria-hidden="true" />+ {t(($) => $.paid_feature.business)}+ </PopoverTrigger>+ <PopoverContent align="end" className="w-72 gap-2 p-3">+ <UpgradeCard feature={feature} />+ </PopoverContent>+ </Popover>+ );+}++// Mounted only while the card is open, so the role lookup (auth store and+// member list) runs for people who look, not for every locked picker.+function UpgradeCard({ feature }: { feature: UpgradeBadgeFeature }) {+ const { t } = useT("billing");+ const wsId = useWorkspaceId();+ const paths = useWorkspacePaths();+ const { role } = useCurrentMember(wsId);+ const isManager = role === "owner" || role === "admin";+ return (+ <>+ <Badge variant="secondary">{t(($) => $.paid_feature.business)}</Badge>+ <p className="text-body font-medium">+ {t(($) => $.paid_feature.upgrade_card[feature].title)}+ </p>+ <p className="text-caption text-muted-foreground">+ {t(($) => $.paid_feature.upgrade_card[feature].description)}+ </p>+ {isManager ? (+ <AppLink+ href={`${paths.settings()}?tab=billing`}+ className={cn(buttonVariants({ size: "sm" }), "mt-1 self-start")}+ >+ {t(($) => $.paid_feature.upgrade_to_business)}+ </AppLink>+ ) : role !== null ? (+ <p className="text-caption text-muted-foreground">+ {t(($) => $.paid_feature.ask_admin)}+ </p>+ ) : null}+ </>+ );+}diff --git a/packages/views/common/app-requests.test.tsx b/packages/views/common/app-requests.test.tsxnew file mode 100644index 0000000000..e82c4c5899--- /dev/null+++ b/packages/views/common/app-requests.test.tsx@@ -0,0 +1,73 @@+import { afterEach, expect, it, vi } from "vitest";+import { cleanup, render, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { I18nProvider } from "@multica/core/i18n/react";+import { workspaceFeatureKeys } from "@multica/core/billing";+import { toast } from "sonner";+import enCommon from "../locales/en/common.json";+import enSettings from "../locales/en/settings.json";+import enBilling from "../locales/en/billing.json";+import { IssueAppRequests } from "./app-requests";++const nav = vi.hoisted(() => ({+ searchParams: new URLSearchParams(),+ pathname: "/acme/issues/MUL-1",+ hash: "",+ replace: vi.fn(),+}));++vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));+vi.mock("@multica/core/config", async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useFeatureEnabled: () => false,+}));+vi.mock("@multica/core/auth", () => ({+ useAuthStore: Object.assign(+ (select: (state: { user: { id: string } }) => unknown) => select({ user: { id: "user-1" } }),+ { getState: () => ({ user: { id: "user-1" } }) },+ ),+}));+vi.mock("../navigation", async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useNavigation: () => nav,+}));+vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++function renderCard() {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const invalidate = vi.spyOn(client, "invalidateQueries");+ render(+ <QueryClientProvider client={client}>+ <I18nProvider locale="en" resources={{ en: { common: enCommon, settings: enSettings, billing: enBilling } }}>+ <IssueAppRequests issueId="issue-1" />+ </I18nProvider>+ </QueryClientProvider>,+ );+ return { invalidate };+}++it("explains a connect the plan refused and refetches the plan", async () => {+ nav.searchParams = new URLSearchParams(+ "app_connect_error=gmail&app_connect_error_reason=feature_locked&keep=1",+ );+ const { invalidate } = renderCard();+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith(enBilling.paid_feature.locked_error));+ expect(toast.error).not.toHaveBeenCalledWith(enSettings.connected_apps.toast_connect_failed);+ expect(invalidate).toHaveBeenCalledWith({ queryKey: workspaceFeatureKeys.all("ws-1") });+ expect(nav.replace).toHaveBeenCalledWith("/acme/issues/MUL-1?keep=1");+});++it("keeps the generic retry message when an older server sends no reason", async () => {+ nav.searchParams = new URLSearchParams("app_connect_error=notion");+ renderCard();+ await waitFor(() =>+ expect(toast.error).toHaveBeenCalledWith(enSettings.connected_apps.toast_connect_failed),+ );+ expect(toast.error).not.toHaveBeenCalledWith(enBilling.paid_feature.locked_error);+ expect(nav.replace).toHaveBeenCalledWith("/acme/issues/MUL-1");+});diff --git a/packages/views/common/app-requests.tsx b/packages/views/common/app-requests.tsxindex 4921673272..7125e83e01 100644--- a/packages/views/common/app-requests.tsx+++ b/packages/views/common/app-requests.tsx@@ -14,6 +14,7 @@ import { useAuthStore } from "@multica/core/auth";import { useFeatureEnabled } from "@multica/core/config";import { COMPOSIO_MCP_APPS_FLAG } from "@multica/core/feature-flags";import { useWorkspaceId } from "@multica/core/hooks";+import { FEATURE_LOCKED_CODE, workspaceFeatureKeys } from "@multica/core/billing";import {chatAppRequestsOptions,connectedAppsKeys,@@ -28,6 +29,8 @@ import { isDesktopShell, openExternal } from "../platform";const CONNECTED_PARAM = "app_connected";const CONNECT_ERROR_PARAM = "app_connect_error";+// Set next to the error when the plan refused the account; older servers omit it.+const CONNECT_ERROR_REASON_PARAM = "app_connect_error_reason";let lastConnectReturn = "";/**@@ -38,11 +41,13 @@ let lastConnectReturn = "";*/function useConnectReturn() {const { t } = useT("settings");+ const { t: tBilling } = useT("billing");const navigation = useNavigation();const qc = useQueryClient();const wsId = useWorkspaceId();const connected = navigation.searchParams?.get(CONNECTED_PARAM) ?? null;const failed = navigation.searchParams?.get(CONNECT_ERROR_PARAM) ?? null;+ const failedReason = navigation.searchParams?.get(CONNECT_ERROR_REASON_PARAM) ?? null;useEffect(() => {const app = connected ?? failed;if (!app) return;@@ -53,12 +58,16 @@ function useConnectReturn() {if (connected) {toast.success(t(($) => $.connected_apps.request.connected_resumed, { app }));void qc.invalidateQueries({ queryKey: connectedAppsKeys.all(wsId) });+ } else if (failedReason === FEATURE_LOCKED_CODE) {+ toast.error(tBilling(($) => $.paid_feature.locked_error));+ void qc.invalidateQueries({ queryKey: workspaceFeatureKeys.all(wsId) });} else {toast.error(t(($) => $.connected_apps.toast_connect_failed));}const params = new URLSearchParams(navigation.searchParams);params.delete(CONNECTED_PARAM);params.delete(CONNECT_ERROR_PARAM);+ params.delete(CONNECT_ERROR_REASON_PARAM);const search = params.toString();navigation.replace(`${navigation.pathname}${search ? `?${search}` : ""}${navigation.hash}`);// eslint-disable-next-line react-hooks/exhaustive-depsdiff --git a/packages/views/common/saved-app-restriction.tsx b/packages/views/common/saved-app-restriction.tsxindex 38bace61c9..d11f247fa6 100644--- a/packages/views/common/saved-app-restriction.tsx+++ b/packages/views/common/saved-app-restriction.tsx@@ -1,6 +1,6 @@"use client";-import { useState } from "react";+import { useState, type ReactNode } from "react";import { toast } from "sonner";import { Button } from "@multica/ui/components/ui/button";import {@@ -10,9 +10,12 @@ import {import { useT } from "../i18n";/** A one-time recovery action, shown only while saved restrictions apply. */-export function SavedAppRestriction({ kind, onRestore }: {+export function SavedAppRestriction({ kind, onRestore, restoreUnavailable }: {kind: "account" | "agent" | "catalog";onRestore?: () => Promise<unknown>;+ /** Shown instead of the admin hint when the restore is withheld for another+ * reason, such as the workspace's plan. */+ restoreUnavailable?: ReactNode;}) {const { t } = useT("settings");const [open, setOpen] = useState(false);@@ -56,7 +59,7 @@ export function SavedAppRestriction({ kind, onRestore }: {</AlertDialogContent></AlertDialog></>- ) : <span className="text-muted-foreground">{t(($) => $.connected_apps.saved_access.admin_required)}</span>}+ ) : restoreUnavailable ?? <span className="text-muted-foreground">{t(($) => $.connected_apps.saved_access.admin_required)}</span>}</div>);}diff --git a/packages/views/locales/en/billing.json b/packages/views/locales/en/billing.jsonindex 660e9a806a..937757c411 100644--- a/packages/views/locales/en/billing.json+++ b/packages/views/locales/en/billing.json@@ -254,7 +254,22 @@"read_only": "Read-only. Upgrade to edit.","unavailable": "Not included in this workspace's plan.","view_plans": "View plans",- "locked_error": "This isn't included in the workspace's plan. Existing settings keep working; upgrade to add more."+ "locked_error": "This isn't included in the workspace's plan. Existing settings keep working; upgrade to add more.",+ "upgrade_to_add": "Upgrade to add",+ "business": "Business",+ "badge_label": "Business feature. Show details",+ "upgrade_to_business": "Upgrade to Business",+ "ask_admin": "Ask a workspace admin to upgrade to Business.",+ "upgrade_card": {+ "agent_invocation_members": {+ "title": "Letting specific people run an agent is a Business feature",+ "description": "\"Only me\" and \"Entire workspace\" stay available on every plan."+ },+ "runtime_member_sharing": {+ "title": "Sharing a runtime with specific members is a Business feature",+ "description": "\"Private\" and \"Public\" stay available on every plan."+ }+ }},"trial": {"status": {diff --git a/packages/views/locales/es/billing.json b/packages/views/locales/es/billing.jsonindex 9e2bfd824c..829be779ec 100644--- a/packages/views/locales/es/billing.json+++ b/packages/views/locales/es/billing.json@@ -254,7 +254,22 @@"read_only": "Solo lectura. Mejora el plan para editar.","unavailable": "No está incluido en el plan de este espacio de trabajo.","view_plans": "Ver planes",- "locked_error": "No está incluido en el plan del espacio de trabajo. La configuración existente sigue funcionando; mejora el plan para añadir más."+ "locked_error": "No está incluido en el plan del espacio de trabajo. La configuración existente sigue funcionando; mejora el plan para añadir más.",+ "upgrade_to_add": "Mejorar el plan",+ "business": "Business",+ "badge_label": "Función de Business. Ver detalles",+ "upgrade_to_business": "Pasar a Business",+ "ask_admin": "Pide a un administrador del espacio de trabajo que pase el plan a Business.",+ "upgrade_card": {+ "agent_invocation_members": {+ "title": "Permitir que personas concretas ejecuten un agente es una función de Business",+ "description": "\"Solo yo\" y \"Todo el espacio de trabajo\" siguen disponibles en todos los planes."+ },+ "runtime_member_sharing": {+ "title": "Compartir un runtime con miembros concretos es una función de Business",+ "description": "\"Privado\" y \"Público\" siguen disponibles en todos los planes."+ }+ }},"trial": {"status": {diff --git a/packages/views/locales/fr/billing.json b/packages/views/locales/fr/billing.jsonindex e44b7f4544..39b70d97bc 100644--- a/packages/views/locales/fr/billing.json+++ b/packages/views/locales/fr/billing.json@@ -254,7 +254,22 @@"read_only": "Lecture seule. Passez à un forfait supérieur pour modifier.","unavailable": "Non inclus dans le forfait de cet espace de travail.","view_plans": "Voir les forfaits",- "locked_error": "Non inclus dans le forfait de l'espace de travail. Les réglages existants restent actifs ; changez de forfait pour en ajouter."+ "locked_error": "Non inclus dans le forfait de l'espace de travail. Les réglages existants restent actifs ; changez de forfait pour en ajouter.",+ "upgrade_to_add": "Changer de forfait",+ "business": "Business",+ "badge_label": "Fonctionnalité Business. Voir les détails",+ "upgrade_to_business": "Passer à Business",+ "ask_admin": "Demandez à un administrateur de l'espace de travail de passer au forfait Business.",+ "upgrade_card": {+ "agent_invocation_members": {+ "title": "Autoriser des personnes précises à exécuter un agent est une fonctionnalité Business",+ "description": "\"Moi uniquement\" et \"Tout l'espace de travail\" restent disponibles dans tous les forfaits."+ },+ "runtime_member_sharing": {+ "title": "Partager un environnement avec des membres précis est une fonctionnalité Business",+ "description": "\"Privé\" et \"Public\" restent disponibles dans tous les forfaits."+ }+ }},"trial": {"status": {diff --git a/packages/views/locales/ja/billing.json b/packages/views/locales/ja/billing.jsonindex bf4fa87b10..858444602f 100644--- a/packages/views/locales/ja/billing.json+++ b/packages/views/locales/ja/billing.json@@ -248,7 +248,22 @@"read_only": "読み取り専用です。編集するにはアップグレードしてください。","unavailable": "このワークスペースのプランには含まれていません。","view_plans": "プランを見る",- "locked_error": "このワークスペースのプランには含まれていません。既存の設定はそのまま有効です。追加するにはアップグレードしてください。"+ "locked_error": "このワークスペースのプランには含まれていません。既存の設定はそのまま有効です。追加するにはアップグレードしてください。",+ "upgrade_to_add": "アップグレード",+ "business": "Business",+ "badge_label": "Business の機能。詳細を表示",+ "upgrade_to_business": "Business にアップグレード",+ "ask_admin": "Business へのアップグレードをワークスペースの管理者に依頼してください。",+ "upgrade_card": {+ "agent_invocation_members": {+ "title": "特定のメンバーにエージェントの実行を許可するのは Business の機能です",+ "description": "自分だけ、またはワークスペース全体に公開する設定は、どのプランでも使えます。"+ },+ "runtime_member_sharing": {+ "title": "ランタイムを特定のメンバーと共有するのは Business の機能です",+ "description": "\"非公開\" と \"公開\" は、どのプランでも使えます。"+ }+ }},"trial": {"status": {diff --git a/packages/views/locales/ko/billing.json b/packages/views/locales/ko/billing.jsonindex 57acfeb560..9ba9ea5aa1 100644--- a/packages/views/locales/ko/billing.json+++ b/packages/views/locales/ko/billing.json@@ -248,7 +248,22 @@"read_only": "읽기 전용입니다. 편집하려면 업그레이드하세요.","unavailable": "이 워크스페이스의 요금제에 포함되어 있지 않습니다.","view_plans": "요금제 보기",- "locked_error": "이 워크스페이스의 요금제에 포함되어 있지 않습니다. 기존 설정은 계속 적용되며, 추가하려면 업그레이드하세요."+ "locked_error": "이 워크스페이스의 요금제에 포함되어 있지 않습니다. 기존 설정은 계속 적용되며, 추가하려면 업그레이드하세요.",+ "upgrade_to_add": "업그레이드",+ "business": "Business",+ "badge_label": "Business 기능. 자세히 보기",+ "upgrade_to_business": "Business로 업그레이드",+ "ask_admin": "워크스페이스 관리자에게 Business로 업그레이드를 요청하세요.",+ "upgrade_card": {+ "agent_invocation_members": {+ "title": "특정 사용자에게 에이전트 실행을 허용하는 것은 Business 기능입니다",+ "description": "나만 사용하거나 워크스페이스 전체에 공개하는 설정은 모든 요금제에서 사용할 수 있습니다."+ },+ "runtime_member_sharing": {+ "title": "런타임을 특정 멤버와 공유하는 것은 Business 기능입니다",+ "description": "\"비공개\"와 \"공개\"는 모든 요금제에서 사용할 수 있습니다."+ }+ }},"trial": {"status": {diff --git a/packages/views/locales/ru/billing.json b/packages/views/locales/ru/billing.jsonindex b8c93bdd64..abc2a05c75 100644--- a/packages/views/locales/ru/billing.json+++ b/packages/views/locales/ru/billing.json@@ -266,7 +266,22 @@"read_only": "Только чтение. Чтобы редактировать, повысьте тариф.","unavailable": "Не входит в тариф этого рабочего пространства.","view_plans": "Посмотреть тарифы",- "locked_error": "Не входит в тариф рабочего пространства. Существующие настройки продолжают работать; чтобы добавить новые, повысьте тариф."+ "locked_error": "Не входит в тариф рабочего пространства. Существующие настройки продолжают работать; чтобы добавить новые, повысьте тариф.",+ "upgrade_to_add": "Повысить тариф",+ "business": "Business",+ "badge_label": "Функция тарифа Business. Подробнее",+ "upgrade_to_business": "Перейти на Business",+ "ask_admin": "Попросите администратора рабочего пространства перейти на тариф Business.",+ "upgrade_card": {+ "agent_invocation_members": {+ "title": "Разрешать запуск агента определённым людям можно только на тарифе Business",+ "description": "\"Только я\" и \"Всё рабочее пространство\" доступны на любом тарифе."+ },+ "runtime_member_sharing": {+ "title": "Открывать среду выполнения определённым участникам можно только на тарифе Business",+ "description": "\"Личная\" и \"Общая\" доступны на любом тарифе."+ }+ }},"trial": {"status": {diff --git a/packages/views/locales/zh-Hans/billing.json b/packages/views/locales/zh-Hans/billing.jsonindex 0b98e47257..0739b95031 100644--- a/packages/views/locales/zh-Hans/billing.json+++ b/packages/views/locales/zh-Hans/billing.json@@ -248,7 +248,22 @@"read_only": "只读,升级后可编辑","unavailable": "当前工作区的套餐不包含此功能。","view_plans": "查看套餐",- "locked_error": "当前工作区的套餐不包含此功能。已有设置继续生效,升级后可以新增。"+ "locked_error": "当前工作区的套餐不包含此功能。已有设置继续生效,升级后可以新增。",+ "upgrade_to_add": "升级套餐",+ "business": "Business",+ "badge_label": "Business 功能,查看详情",+ "upgrade_to_business": "升级到 Business",+ "ask_admin": "请联系工作区管理员升级到 Business。",+ "upgrade_card": {+ "agent_invocation_members": {+ "title": "允许指定成员运行智能体是 Business 功能",+ "description": "\"仅自己\"和\"整个工作区\"在所有套餐中都可以使用。"+ },+ "runtime_member_sharing": {+ "title": "与指定成员共享运行时是 Business 功能",+ "description": "\"私有\"和\"公开\"在所有套餐中都可以使用。"+ }+ }},"trial": {"status": {diff --git a/packages/views/locales/zh-Hant/billing.json b/packages/views/locales/zh-Hant/billing.jsonindex af1c36575f..3fec70126b 100644--- a/packages/views/locales/zh-Hant/billing.json+++ b/packages/views/locales/zh-Hant/billing.json@@ -248,7 +248,22 @@"read_only": "唯讀,升級後可編輯","unavailable": "目前工作區的套餐不包含此功能。","view_plans": "查看套餐",- "locked_error": "目前工作區的套餐不包含此功能。既有設定繼續生效,升級後可以新增。"+ "locked_error": "目前工作區的套餐不包含此功能。既有設定繼續生效,升級後可以新增。",+ "upgrade_to_add": "升級套餐",+ "business": "Business",+ "badge_label": "Business 功能,查看詳情",+ "upgrade_to_business": "升級到 Business",+ "ask_admin": "請聯絡工作區管理員升級到 Business。",+ "upgrade_card": {+ "agent_invocation_members": {+ "title": "允許指定成員執行 AI 代理是 Business 功能",+ "description": "\"僅自己\"和\"整個工作區\"在所有套餐中都可以使用。"+ },+ "runtime_member_sharing": {+ "title": "與指定成員共用執行時是 Business 功能",+ "description": "\"私有\"和\"公開\"在所有套餐中都可以使用。"+ }+ }},"trial": {"status": {diff --git a/packages/views/runtimes/components/runtime-access-editor.test.tsx b/packages/views/runtimes/components/runtime-access-editor.test.tsxnew file mode 100644index 0000000000..70daf98b72--- /dev/null+++ b/packages/views/runtimes/components/runtime-access-editor.test.tsx@@ -0,0 +1,117 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { cleanup, fireEvent, screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { ApiError } from "@multica/core/api";+import type { AgentRuntime, MemberWithUser, WorkspaceFeatures } from "@multica/core/types";+import { toast } from "sonner";+import enBilling from "../../locales/en/billing.json";+import { renderWithI18n } from "../../test/i18n";+import { RuntimeAccessEditor } from "./runtime-access-editor";++const api = vi.hoisted(() => ({+ listMembers: vi.fn(),+ updateRuntime: vi.fn(),+ getWorkspaceFeatures: vi.fn(),+}));+vi.mock("@multica/core/api", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@multica/core/api")>()),+ api,+}));+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));+vi.mock("sonner", () => ({ toast: { error: vi.fn(), success: vi.fn() } }));+vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => null }));+vi.mock("@multica/core/paths", async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useWorkspacePaths: () => ({ settings: () => "/acme/settings" }),+}));+vi.mock("../../navigation", async (importOriginal) => ({+ ...(await importOriginal<object>()),+ AppLink: ({ href, children }: { href: string; children: React.ReactNode }) => <a href={href}>{children}</a>,+}));++const MEMBERS = [+ { user_id: "owner", name: "Owner" },+ { user_id: "u1", name: "Alice" },+ { user_id: "u2", name: "Bob" },+] as unknown as MemberWithUser[];++function runtime(overrides: Partial<AgentRuntime> = {}): AgentRuntime {+ return {+ id: "runtime-1", workspace_id: "ws-1", name: "Local Runtime", custom_name: null,+ daemon_id: null, runtime_mode: "local", provider: "claude", launch_header: "", status: "online",+ device_info: "", metadata: {}, owner_id: "owner", visibility: "private", last_seen_at: null,+ created_at: "2026-09-05T00:00:00Z", updated_at: "2026-09-05T00:00:00Z",+ ...overrides,+ } as AgentRuntime;+}++function setFeature(state: "available" | "locked") {+ api.getWorkspaceFeatures.mockResolvedValue({ features: { runtime_member_sharing: state } } satisfies WorkspaceFeatures);+}++function renderEditor(value: AgentRuntime) {+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });+ return renderWithI18n(+ <QueryClientProvider client={qc}>+ <RuntimeAccessEditor runtime={value} />+ </QueryClientProvider>,+ );+}++const membersButton = () => screen.getByRole("button", { name: "Members" });+const BADGE = enBilling.paid_feature.badge_label;++describe("RuntimeAccessEditor member sharing (MUL-9491)", () => {+ beforeEach(() => {+ api.listMembers.mockResolvedValue(MEMBERS);+ api.updateRuntime.mockResolvedValue(runtime());+ setFeature("available");+ });+ afterEach(() => {+ cleanup();+ vi.clearAllMocks();+ });++ it("offers every member when the plan includes sharing", async () => {+ renderEditor(runtime());+ await waitFor(() => expect(membersButton()).toBeEnabled());+ fireEvent.click(membersButton());+ expect(await screen.findByRole("checkbox", { name: "Alice" })).toBeInTheDocument();+ expect(screen.getByRole("checkbox", { name: "Bob" })).toBeInTheDocument();+ expect(screen.queryByText("View plans")).not.toBeInTheDocument();+ expect(screen.queryByRole("button", { name: BADGE })).not.toBeInTheDocument();+ });++ it("disables Members for a runtime without a list on a locked plan", async () => {+ setFeature("locked");+ renderEditor(runtime({ visibility: "public" }));+ expect(await screen.findByText("Not included in this workspace's plan.")).toBeInTheDocument();+ expect(membersButton()).toBeDisabled();+ expect(screen.getByRole("button", { name: BADGE })).toBeEnabled();+ fireEvent.click(screen.getByRole("button", { name: "Private" }));+ await waitFor(() => expect(api.updateRuntime).toHaveBeenCalledWith("runtime-1", { visibility: "private", shared_with: [] }));+ });++ it("lets a locked plan remove members from an existing list but not add any", async () => {+ setFeature("locked");+ renderEditor(runtime({ shared_with: ["u1"] }));+ expect(await screen.findByText("Read-only. Upgrade to edit.")).toBeInTheDocument();+ expect(screen.getByRole("button", { name: BADGE })).toBeInTheDocument();+ fireEvent.click(membersButton());+ expect(await screen.findByRole("checkbox", { name: "Alice" })).toBeInTheDocument();+ expect(screen.queryByRole("checkbox", { name: "Bob" })).not.toBeInTheDocument();+ });++ it("explains a feature_locked refusal and refetches the plan", async () => {+ api.updateRuntime.mockRejectedValue(+ new ApiError("locked", 403, "Forbidden", { code: "feature_locked", feature: "runtime_member_sharing" }),+ );+ renderEditor(runtime());+ await waitFor(() => expect(membersButton()).toBeEnabled());+ fireEvent.click(membersButton());+ fireEvent.click(await screen.findByRole("checkbox", { name: "Bob" }));+ fireEvent.click(screen.getByRole("button", { name: "Save" }));+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith(enBilling.paid_feature.locked_error));+ await waitFor(() => expect(api.getWorkspaceFeatures).toHaveBeenCalledTimes(2));+ });+});diff --git a/packages/views/runtimes/components/runtime-access-editor.tsx b/packages/views/runtimes/components/runtime-access-editor.tsxindex 8a30552a22..ea726dc6a7 100644--- a/packages/views/runtimes/components/runtime-access-editor.tsx+++ b/packages/views/runtimes/components/runtime-access-editor.tsx@@ -3,11 +3,12 @@import { useMemo, useState, type ComponentProps } from "react";import { Globe, Lock, Users } from "@multica/ui/icons";import { toast } from "sonner";-import { useQuery } from "@tanstack/react-query";+import { useQuery, useQueryClient } from "@tanstack/react-query";import type { AgentRuntime } from "@multica/core/types";import { useWorkspaceId } from "@multica/core/hooks";import { memberListOptions } from "@multica/core/workspace/queries";import { useUpdateRuntime } from "@multica/core/runtimes/mutations";+import { refreshFeaturesOnLockedError, usePaidFeatureAccess } from "@multica/core/billing";import { Button } from "@multica/ui/components/ui/button";import { Checkbox } from "@multica/ui/components/ui/checkbox";import { Input } from "@multica/ui/components/ui/input";@@ -22,6 +23,11 @@ import {TooltipTrigger,} from "@multica/ui/components/ui/tooltip";import { ActorAvatar } from "../../common/actor-avatar";+import {+ PaidFeatureNotice,+ PaidFeatureUpgradeBadge,+ usePaidFeatureErrorMessage,+} from "../../billing";import { useT } from "../../i18n";import {RevokeRuntimeAccessDialog,@@ -71,8 +77,17 @@ export function RuntimeAccessEditor({ runtime }: { runtime: AgentRuntime }) {const wsId = useWorkspaceId();const { data: members = [] } = useQuery(memberListOptions(wsId));const updateRuntime = useUpdateRuntime(wsId);+ const qc = useQueryClient();+ const paidFeatureError = usePaidFeatureErrorMessage();const current = runtimeAccessScope(runtime);const persisted = useMemo(() => runtime.shared_with ?? [], [runtime.shared_with]);+ // Without the paid feature a runtime keeps the members it is shared with:+ // they can be removed and the runtime made private or public, but nobody+ // can be added, and a runtime without a list cannot get one.+ const memberSharing = usePaidFeatureAccess(wsId, "runtime_member_sharing", {+ hasExistingConfig: current === "members",+ });+ const membersDisabled = !memberSharing.canAdd && current !== "members";const [pickerOpen, setPickerOpen] = useState(false);const [revokePlan, setRevokePlan] = useState<RuntimeAccessRevocationPlan | null>(null);const [revokeOpen, setRevokeOpen] = useState(false);@@ -106,7 +121,8 @@ export function RuntimeAccessEditor({ runtime }: { runtime: AgentRuntime }) {setRevokeOpen(true);return;}- toast.error(err instanceof Error && err.message ? err.message : t(($) => $.detail.visibility_toast_failed));+ refreshFeaturesOnLockedError(qc, wsId, err);+ toast.error(paidFeatureError(err, err instanceof Error && err.message ? err.message : t(($) => $.detail.visibility_toast_failed)));},},);@@ -130,14 +146,16 @@ export function RuntimeAccessEditor({ runtime }: { runtime: AgentRuntime }) {}}/>))}- <Popover open={pickerOpen} onOpenChange={(open) => setPickerOpen(open && !disabled)}>+ <Popover open={pickerOpen} onOpenChange={(open) => setPickerOpen(open && !disabled && !membersDisabled)}><PopoverTrigger- render={<ScopeButton scope="members" active={current === "members"} disabled={disabled} />}+ render={<ScopeButton scope="members" active={current === "members"} disabled={disabled || membersDisabled} />}/><PopoverContent align="end" className="w-72 p-0">{pickerOpen ? (<MemberPicker- members={members.filter((member) => member.user_id !== runtime.owner_id)}+ members={members.filter((member) =>+ member.user_id !== runtime.owner_id &&+ (memberSharing.canAdd || persisted.includes(member.user_id)))}initial={persisted}saving={updateRuntime.isPending}onCancel={() => setPickerOpen(false)}@@ -169,6 +187,14 @@ export function RuntimeAccessEditor({ runtime }: { runtime: AgentRuntime }) {</span></button>) : null}+ {memberSharing.state === "read_only" || memberSharing.state === "unavailable" ? (+ // The badge sits with the notice, not in the scope switcher: the+ // properties column is too narrow for both without truncating labels.+ <div className="flex items-start justify-between gap-2">+ <PaidFeatureNotice state={memberSharing.state} />+ <PaidFeatureUpgradeBadge feature="runtime_member_sharing" className="shrink-0" />+ </div>+ ) : null}<RevokeRuntimeAccessDialog open={revokeOpen} onOpenChange={setRevokeOpen}runtime={runtime} wsId={wsId} initialPlan={revokePlan} sharedWith={revokeMembers} /></div>diff --git a/packages/views/settings/components/add-app-dialog.test.tsx b/packages/views/settings/components/add-app-dialog.test.tsxindex f1cfede1dc..7338636c4c 100644--- a/packages/views/settings/components/add-app-dialog.test.tsx+++ b/packages/views/settings/components/add-app-dialog.test.tsx@@ -1,14 +1,30 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { cleanup, render, screen, waitFor, within } from "@testing-library/react";import userEvent from "@testing-library/user-event";-import { api } from "@multica/core/api";+import { api, ApiError } from "@multica/core/api";+import type { PaidFeatureAccess } from "@multica/core/billing";+import { toast } from "sonner";+import enBilling from "../../locales/en/billing.json";import { I18nProvider } from "@multica/core/i18n/react";import type { AppAccountScope, AppsOverview } from "@multica/core/types";import enCommon from "../../locales/en/common.json";import enSettings from "../../locales/en/settings.json";import { AddAppDialog } from "./add-app-dialog";-vi.mock("@multica/core/api", () => ({ api: { connectApp: vi.fn() } }));+vi.mock("sonner", () => ({ toast: { error: vi.fn(), success: vi.fn() } }));+vi.mock("@multica/core/paths", async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useWorkspacePaths: () => ({ settings: () => "/acme/settings" }),+}));+vi.mock("../../navigation", async (importOriginal) => ({+ ...(await importOriginal<object>()),+ AppLink: ({ href, children, ...props }: React.ComponentProps<"a"> & { href: string }) => <a href={href} {...props}>{children}</a>,+}));++vi.mock("@multica/core/api", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@multica/core/api")>()),+ api: { connectApp: vi.fn() },+}));const overview: AppsOverview = {catalog_mode: "all", can_manage: true, agent_apps: [], personal: [],@@ -26,10 +42,15 @@ afterEach(() => {delete (window as { desktopAPI?: unknown }).desktopAPI;});-function renderDialog(scope: AppAccountScope, canManage = true) {- render(<I18nProvider locale="en" resources={{ en: { common: enCommon, settings: enSettings } }}>+function renderDialog(+ scope: AppAccountScope,+ canManage = true,+ extra: { overview?: AppsOverview; teamAccess?: Pick<PaidFeatureAccess, "canAdd" | "state">; onConnectError?: (e: unknown) => void } = {},+) {+ render(<I18nProvider locale="en" resources={{ en: { common: enCommon, settings: enSettings, billing: enBilling } }}><AddAppDialog open onOpenChange={vi.fn()} scope={scope} canManage={canManage}- overview={overview} catalog={catalog} catalogLoading={false} catalogError={false} />+ overview={extra.overview ?? overview} catalog={catalog} catalogLoading={false} catalogError={false}+ teamAccess={extra.teamAccess} onConnectError={extra.onConnectError} /></I18nProvider>);}@@ -91,3 +112,58 @@ describe("AddAppDialog", () => {expect(connect).toHaveTextContent("Connect");});});++describe("AddAppDialog on a plan without team app accounts (MUL-9491)", () => {+ const withExpiredSlack: AppsOverview = {+ ...overview,+ team: [...overview.team, { id: "team-slack", toolkit_slug: "slack", status: "expired", connected_at: "", last_used_at: null }],+ };+ const catalogWithSlack = [...catalog, { slug: "slack", name: "Slack", curated: true }];++ it("connects a new team app normally when the plan includes it", async () => {+ const user = userEvent.setup();+ renderDialog("team", true, { teamAccess: { canAdd: true, state: "available" } });+ expect(screen.queryByText("View plans")).not.toBeInTheDocument();+ await user.click(screen.getByRole("button", { name: "Connect" }));+ await waitFor(() => expect(api.connectApp).toHaveBeenCalledWith("team", "notion"));+ });++ it("replaces Connect with Upgrade to add for an app without a team account", async () => {+ const user = userEvent.setup();+ renderDialog("team", true, { teamAccess: { canAdd: false, state: "read_only" } });+ expect(screen.getByText("Read-only. Upgrade to edit.")).toBeVisible();+ const upgrade = screen.getByRole("link", { name: "Upgrade to add" });+ expect(upgrade).toHaveAttribute("href", "/acme/settings?tab=billing");+ expect(screen.queryByRole("button", { name: "Connect" })).not.toBeInTheDocument();+ await user.click(upgrade);+ expect(api.connectApp).not.toHaveBeenCalled();+ });++ it("still reconnects an app's existing team account", async () => {+ const user = userEvent.setup();+ render(<I18nProvider locale="en" resources={{ en: { common: enCommon, settings: enSettings, billing: enBilling } }}>+ <AddAppDialog open onOpenChange={vi.fn()} scope="team" canManage overview={withExpiredSlack}+ catalog={catalogWithSlack} catalogLoading={false} catalogError={false}+ teamAccess={{ canAdd: false, state: "read_only" }} />+ </I18nProvider>);+ await user.click(screen.getByRole("button", { name: "Reconnect" }));+ await waitFor(() => expect(api.connectApp).toHaveBeenCalledWith("team", "slack"));+ });++ it("does not gate personal accounts", () => {+ renderDialog("personal", true, { teamAccess: { canAdd: false, state: "unavailable" } });+ expect(screen.getAllByRole("button", { name: "Connect" })).toHaveLength(2);+ expect(screen.queryByText("View plans")).not.toBeInTheDocument();+ });++ it("explains a feature_locked refusal and reports it to the caller", async () => {+ const locked = new ApiError("locked", 403, "Forbidden", { code: "feature_locked", feature: "team_app_accounts" });+ vi.mocked(api.connectApp).mockRejectedValue(locked);+ const onConnectError = vi.fn();+ const user = userEvent.setup();+ renderDialog("team", true, { teamAccess: { canAdd: true, state: "available" }, onConnectError });+ await user.click(screen.getByRole("button", { name: "Connect" }));+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith(enBilling.paid_feature.locked_error));+ expect(onConnectError).toHaveBeenCalledWith(locked);+ });+});diff --git a/packages/views/settings/components/add-app-dialog.tsx b/packages/views/settings/components/add-app-dialog.tsxindex ce4c1b1242..e314d07517 100644--- a/packages/views/settings/components/add-app-dialog.tsx+++ b/packages/views/settings/components/add-app-dialog.tsx@@ -4,7 +4,7 @@ import { useMemo, useState } from "react";import { toast } from "sonner";import { Check, Loader2 } from "@multica/ui/icons";import { Badge } from "@multica/ui/components/ui/badge";-import { Button } from "@multica/ui/components/ui/button";+import { Button, buttonVariants } from "@multica/ui/components/ui/button";import {Dialog,DialogContent,@@ -14,9 +14,13 @@ import {} from "@multica/ui/components/ui/dialog";import { Input } from "@multica/ui/components/ui/input";import { api } from "@multica/core/api";+import type { PaidFeatureAccess } from "@multica/core/billing";+import { useWorkspacePaths } from "@multica/core/paths";import type { AppAccountScope, AppCatalogEntry, AppsOverview } from "@multica/core/types";import { ComposioToolkitLogo } from "../../common/composio-toolkit-logo";+import { PaidFeatureNotice, usePaidFeatureErrorMessage } from "../../billing";import { useT } from "../../i18n";+import { AppLink } from "../../navigation";import { isDesktopShell, openExternal } from "../../platform";/**@@ -32,6 +36,8 @@ export function AddAppDialog({catalog,catalogLoading,catalogError,+ teamAccess,+ onConnectError,}: {open: boolean;onOpenChange: (open: boolean) => void;@@ -41,8 +47,12 @@ export function AddAppDialog({catalog: AppCatalogEntry[];catalogLoading: boolean;catalogError: boolean;+ /** The plan's `team_app_accounts` access. Omitted means available. */+ teamAccess?: Pick<PaidFeatureAccess, "canAdd" | "state">;+ onConnectError?: (error: unknown) => void;}) {const { t } = useT("settings");+ const paidFeatureError = usePaidFeatureErrorMessage();const [query, setQuery] = useState("");const [connecting, setConnecting] = useState<string | null>(null);@@ -51,6 +61,14 @@ export function AddAppDialog({for (const c of overview[scope]) if (c.status === "active") set.add(c.toolkit_slug);return set;}, [overview, scope]);+ // A team account that already exists (active or expired) can always be+ // reauthorized; only a team account for a new app needs the paid feature.+ const existingTeam = useMemo(+ () => new Set(overview.team.filter((c) => c.status !== "revoked").map((c) => c.toolkit_slug)),+ [overview.team],+ );+ const canAddTeam = teamAccess?.canAdd ?? true;+ const teamState = scope === "team" ? teamAccess?.state : null;const filtered = useMemo(() => {const q = query.trim().toLowerCase();@@ -64,7 +82,7 @@ export function AddAppDialog({}, [catalog, query]);async function connect(app: AppCatalogEntry) {- if (connecting || (scope === "team" && !canManage)) return;+ if (connecting || (scope === "team" && (!canManage || (!canAddTeam && !existingTeam.has(app.slug))))) return;setConnecting(app.slug);try {const { redirect_url } = await api.connectApp(scope, app.slug);@@ -73,7 +91,8 @@ export function AddAppDialog({// browser and stays here, so the row must become clickable again.if (isDesktopShell()) setConnecting(null);} catch (e) {- toast.error(e instanceof Error && e.message ? e.message : t(($) => $.connected_apps.toast_failed));+ onConnectError?.(e);+ toast.error(paidFeatureError(e, e instanceof Error && e.message ? e.message : t(($) => $.connected_apps.toast_failed)));setConnecting(null);}}@@ -87,6 +106,10 @@ export function AddAppDialog({</span>);}+ const reconnect = scope === "team" && existingTeam.has(app.slug);+ if (scope === "team" && canManage && !canAddTeam && !reconnect) {+ return <UpgradeToAddLink />;+ }return (<Buttonsize="xs"@@ -95,7 +118,11 @@ export function AddAppDialog({onClick={() => connect(app)}>{connecting === app.slug && <Loader2 className="animate-spin" />}- {connecting === app.slug ? t(($) => $.connected_apps.add.connecting) : t(($) => $.connected_apps.add.connect)}+ {connecting === app.slug+ ? t(($) => $.connected_apps.add.connecting)+ : reconnect+ ? t(($) => $.connected_apps.reconnect)+ : t(($) => $.connected_apps.add.connect)}</Button>);};@@ -107,6 +134,9 @@ export function AddAppDialog({<DialogTitle>{scope === "team" ? t(($) => $.connected_apps.add.connect_team) : t(($) => $.connected_apps.add.connect_personal)}</DialogTitle><DialogDescription>{scope === "team" ? t(($) => $.connected_apps.add.team_description) : t(($) => $.connected_apps.add.personal_description)}</DialogDescription></DialogHeader>+ {canManage && (teamState === "read_only" || teamState === "unavailable") ? (+ <PaidFeatureNotice state={teamState} />+ ) : null}<InputautoFocusvalue={query}@@ -150,3 +180,14 @@ export function AddAppDialog({</Dialog>);}++/** Stands in for Connect where the plan cannot add a team account. */+function UpgradeToAddLink() {+ const { t } = useT("billing");+ const paths = useWorkspacePaths();+ return (+ <AppLink href={`${paths.settings()}?tab=billing`} className={buttonVariants({ size: "xs", variant: "outline" })}>+ {t(($) => $.paid_feature.upgrade_to_add)}+ </AppLink>+ );+}diff --git a/packages/views/settings/components/apps-settings.test.tsx b/packages/views/settings/components/apps-settings.test.tsxindex 2d906c1591..1c2cac5397 100644--- a/packages/views/settings/components/apps-settings.test.tsx+++ b/packages/views/settings/components/apps-settings.test.tsx@@ -3,18 +3,39 @@ import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-liimport userEvent from "@testing-library/user-event";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { api } from "@multica/core/api";+import { workspaceFeatureKeys } from "@multica/core/billing";import { I18nProvider } from "@multica/core/i18n/react";import type { AppsOverview } from "@multica/core/types";import enCommon from "../../locales/en/common.json";import enSettings from "../../locales/en/settings.json";+import enBilling from "../../locales/en/billing.json";+import { toast } from "sonner";import { AppsSettings } from "./apps-settings";-vi.mock("@multica/core/api", () => ({ api: {- getAppsOverview: vi.fn(), listAppCatalog: vi.fn(), updateAppSettings: vi.fn(), updateAppRules: vi.fn(),-} }));+const nav = vi.hoisted(() => ({+ searchParams: new URLSearchParams(),+ pathname: "/acme/settings",+ replace: vi.fn(),+}));++vi.mock("@multica/core/api", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@multica/core/api")>()),+ api: {+ getAppsOverview: vi.fn(), listAppCatalog: vi.fn(), updateAppSettings: vi.fn(), updateAppRules: vi.fn(),+ getWorkspaceFeatures: vi.fn(),+ },+}));+vi.mock("@multica/core/paths", async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useWorkspacePaths: () => ({ settings: () => "/acme/settings" }),+}));vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));+vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));vi.mock("@multica/core/workspace/hooks", () => ({ useActorName: () => ({ getActorName: () => "Admin" }) }));-vi.mock("../../navigation", () => ({ useNavigation: () => ({ searchParams: new URLSearchParams() }) }));+vi.mock("../../navigation", () => ({+ useNavigation: () => nav,+ AppLink: ({ href, children, ...props }: React.ComponentProps<"a"> & { href: string }) => <a href={href} {...props}>{children}</a>,+}));let overview: AppsOverview;beforeEach(() => {@@ -25,6 +46,7 @@ beforeEach(() => {};vi.mocked(api.getAppsOverview).mockImplementation(async () => overview);vi.mocked(api.listAppCatalog).mockResolvedValue({ catalog_mode: "custom", apps: [] });+ vi.mocked(api.getWorkspaceFeatures).mockResolvedValue({ features: {} });vi.mocked(api.updateAppSettings).mockImplementation(async () => {overview = { ...overview, catalog_mode: "all" };return { catalog_mode: "all", allowed_toolkits: [] };@@ -36,6 +58,7 @@ beforeEach(() => {});afterEach(() => {cleanup();+ nav.searchParams = new URLSearchParams();vi.clearAllMocks();delete (window as { desktopAPI?: unknown }).desktopAPI;});@@ -43,7 +66,7 @@ afterEach(() => {function renderSettings() {const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });render(<QueryClientProvider client={client}>- <I18nProvider locale="en" resources={{ en: { common: enCommon, settings: enSettings } }}>+ <I18nProvider locale="en" resources={{ en: { common: enCommon, settings: enSettings, billing: enBilling } }}><AppsSettings /></I18nProvider></QueryClientProvider>);@@ -119,3 +142,41 @@ it("does not reload on focus on the web, where the flow returns to this tab", asawait new Promise((resolve) => setTimeout(resolve, 20));expect(api.getAppsOverview).toHaveBeenCalledTimes(1);});++it("passes the plan's team account access to the connect dialog", async () => {+ vi.mocked(api.getWorkspaceFeatures).mockResolvedValue({ features: { team_app_accounts: "locked" } });+ vi.mocked(api.listAppCatalog).mockResolvedValue({ catalog_mode: "all", apps: [+ { slug: "gmail", name: "Gmail", curated: true },+ { slug: "notion", name: "Notion", curated: true },+ ] });+ overview.team = [{ id: "team-1", toolkit_slug: "gmail", status: "expired", connected_at: "", last_used_at: null }];+ const user = userEvent.setup();+ renderSettings();+ await waitFor(() => expect(api.getWorkspaceFeatures).toHaveBeenCalled());+ await user.click(await screen.findByRole("button", { name: "Connect team account" }));+ const dialog = screen.getByRole("dialog", { name: "Connect team account" });+ expect(await within(dialog).findByText("Read-only. Upgrade to edit.")).toBeVisible();+ expect(within(dialog).getByRole("button", { name: "Reconnect" })).toBeEnabled();+ expect(within(dialog).getByRole("link", { name: "Upgrade to add" })).toBeVisible();+});++it("explains a team connect refused by the plan and refetches the plan", async () => {+ nav.searchParams = new URLSearchParams(+ "tab=apps&error=composio_connect_failed&reason=feature_locked&scope=team",+ );+ const invalidate = vi.spyOn(QueryClient.prototype, "invalidateQueries");+ renderSettings();+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith(enBilling.paid_feature.locked_error));+ expect(toast.error).not.toHaveBeenCalledWith(enSettings.connected_apps.toast_connect_failed);+ expect(invalidate).toHaveBeenCalledWith({ queryKey: workspaceFeatureKeys.all("ws-1") });+ invalidate.mockRestore();+ expect(nav.replace).toHaveBeenCalledWith("/acme/settings?tab=apps");+});++it("keeps the generic retry message when an older server sends no reason", async () => {+ nav.searchParams = new URLSearchParams("tab=integrations&error=composio_connect_failed");+ renderSettings();+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith(enSettings.connected_apps.toast_connect_failed));+ expect(toast.error).not.toHaveBeenCalledWith(enBilling.paid_feature.locked_error);+ expect(nav.replace).toHaveBeenCalledWith("/acme/settings?tab=apps");+});diff --git a/packages/views/settings/components/apps-settings.tsx b/packages/views/settings/components/apps-settings.tsxindex ac42f5a24a..c9a1f2ab50 100644--- a/packages/views/settings/components/apps-settings.tsx+++ b/packages/views/settings/components/apps-settings.tsx@@ -17,6 +17,12 @@ import {} from "@multica/ui/components/ui/alert-dialog";import { api } from "@multica/core/api";import { useWorkspaceId } from "@multica/core/hooks";+import {+ FEATURE_LOCKED_CODE,+ refreshFeaturesOnLockedError,+ usePaidFeatureAccess,+ workspaceFeatureKeys,+} from "@multica/core/billing";import {appCatalogOptions,appsOverviewOptions,@@ -46,22 +52,30 @@ type AccountTarget = { scope: AppAccountScope; connection: AppConnection; name:* Which agents use each account is set on the agent. */export function AppsSettings() {const { t } = useT("settings");+ const { t: tBilling } = useT("billing");const wsId = useWorkspaceId();const qc = useQueryClient();const navigation = useNavigation();const overview = useQuery(appsOverviewOptions(wsId));const catalog = useQuery(appCatalogOptions(wsId));const restore = useRestoreAppAccess();+ // Without the paid feature existing team accounts keep working and can be+ // reauthorized or disconnected; only a team account for a new app is refused.+ const teamAccess = usePaidFeatureAccess(wsId, "team_app_accounts", {+ hasExistingConfig: (overview.data?.team ?? []).some((c) => c.status !== "revoked"),+ });const [addingScope, setAddingScope] = useState<AppAccountScope | null>(null);const [detail, setDetail] = useState<AccountTarget | null>(null);const [disconnecting, setDisconnecting] = useState<AccountTarget | null>(null);// The hosted connect flow returns with `?connected=<slug>` or- // `?error=composio_connect_failed`. Consume it once, then drop the params so- // a refresh does not toast again.+ // `?error=composio_connect_failed`, plus `reason=feature_locked` when the+ // plan refused a team account (older servers send no reason). Consume it+ // once, then drop the params so a refresh does not toast again.const connectedParam = navigation.searchParams.get("connected");const errorParam = navigation.searchParams.get("error");+ const reasonParam = navigation.searchParams.get("reason");const consumed = useRef<string | null>(null);useEffect(() => {const key = connectedParam@@ -74,12 +88,17 @@ export function AppsSettings() {if (connectedParam) {toast.success(t(($) => $.connected_apps.toast_connected));void qc.invalidateQueries({ queryKey: connectedAppsKeys.all(wsId) });+ } else if (reasonParam === FEATURE_LOCKED_CODE) {+ // This tab's view of the plan was stale: refetch so the page switches to+ // its locked state.+ toast.error(tBilling(($) => $.paid_feature.locked_error));+ void qc.invalidateQueries({ queryKey: workspaceFeatureKeys.all(wsId) });} else {toast.error(t(($) => $.connected_apps.toast_connect_failed));}const params = new URLSearchParams(navigation.searchParams);params.set("tab", "apps");- for (const k of ["integration", "connected", "error", "scope"]) params.delete(k);+ for (const k of ["integration", "connected", "error", "reason", "scope"]) params.delete(k);navigation.replace(`${navigation.pathname}?${params.toString()}`);// eslint-disable-next-line react-hooks/exhaustive-deps}, [connectedParam, errorParam]);@@ -199,6 +218,8 @@ export function AppsSettings() {catalog={catalog.data?.apps ?? []}catalogLoading={catalog.isLoading}catalogError={catalog.isError}+ teamAccess={teamAccess}+ onConnectError={(error) => refreshFeaturesOnLockedError(qc, wsId, error)}/>)}{detail && (diff --git a/packages/views/settings/components/billing-trial-section.tsx b/packages/views/settings/components/billing-trial-section.tsxindex 43f46d0256..ce60398641 100644--- a/packages/views/settings/components/billing-trial-section.tsx+++ b/packages/views/settings/components/billing-trial-section.tsx@@ -11,11 +11,14 @@ import type { IconComponent } from "@multica/ui/icons";import { useLocale, useT } from "../../i18n";import { SettingsCard, SettingsRow, SettingsSection } from "./settings-layout";-const TRIAL_FEATURE_ICONS: Record<PaidFeature, IconComponent> = {+// The paid features this section describes; not every paid feature has a+// trial summary.+type TrialFeature = Extract<PaidFeature, "private_projects" | "guests">;+const TRIAL_FEATURE_ICONS: Record<TrialFeature, IconComponent> = {private_projects: Lock,guests: Eye,};-const TRIAL_FEATURES = Object.keys(TRIAL_FEATURE_ICONS) as PaidFeature[];+const TRIAL_FEATURES = Object.keys(TRIAL_FEATURE_ICONS) as TrialFeature[];function formatDate(value: number, locale: string): string {return new Intl.DateTimeFormat(locale, { dateStyle: "medium" }).format(new Date(value));diff --git a/packages/views/settings/components/settings-navigation.test.ts b/packages/views/settings/components/settings-navigation.test.tsindex fa93c726f5..13de5355db 100644--- a/packages/views/settings/components/settings-navigation.test.ts+++ b/packages/views/settings/components/settings-navigation.test.ts@@ -67,6 +67,15 @@ describe("settings location", () => {},);+ it("lands a team connect refused by the plan on Connected apps", () => {+ expect(+ resolve("tab=apps&error=composio_connect_failed&reason=feature_locked&scope=team"),+ ).toEqual({ tab: "apps", section: null, integration: null });+ expect(+ resolve("tab=integrations&error=composio_connect_failed&reason=feature_locked").tab,+ ).toBe("apps");+ });+it("passes current pages and anchors through untouched", () => {expect(resolve("tab=code§ion=pr-sidebar")).toEqual({tab: "code",diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex b68fea1cab..655ccc3729 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1391,6 +1391,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busslog.Error("composio: service init failed; composio integration disabled", "error", serr)} else {h.Composio = svc+ // Team Apps accounts are a paid feature (MUL-9491): the+ // callback re-checks it right before writing an account.+ svc.SetTeamConnectGate(h.TeamAppConnectGate)// Connected Apps v2 (MUL-8516): runs reach their apps// through the Multica gateway, which holds the Composio// key and applies account rules and confirmations.diff --git a/server/internal/entitlement/README.md b/server/internal/entitlement/README.mdindex 136a8e92d7..3df5ab8ac4 100644--- a/server/internal/entitlement/README.md+++ b/server/internal/entitlement/README.md@@ -17,7 +17,7 @@ The client reads:- `schema_version`: only version 1 is accepted.- `policy_revision`: the effective-instruction generation, currently fixed at- `4` by Cloud and not deployment configuration. Cloud advances it when the+ `7` by Cloud and not deployment configuration. Cloud advances it when themeaning or set of actionable instructions changes, including additiveinstructions; `schema_version` changes only for incompatible wire parsing.- `subscription_version`: the workspace's monotonic subscription revision. A@@ -66,6 +66,11 @@ and the features keep their instructions. See [Member limit](#member-limit).`gates.storage_bytes` (revision 6) is optional the same way; see[Attachment storage limit](#attachment-storage-limit).+Revision 7 adds the `agent_invocation_members`, `runtime_member_sharing` and+`team_app_accounts` features. It is safe in either order: an older consumer+ignores features it does not know, and this consumer reads a policy without+one as that feature `off` with reason `feature_missing`.+Responses tolerate unknown JSON fields and gates for additive compatibility.Unknown schema/action, malformed fields, a missing `autopilot_runs` gate, HTTPfailures, and timeouts fail open.@@ -223,12 +228,18 @@ configured, including the access control it defines: a private project staysvisible only to its members after a downgrade. Each feature classifies its ownwrites; the handler entry point is `requireFeatureAddition`(`server/internal/handler/paid_feature.go`), called after the ordinary-permission checks, so a caller refused by those gets the ordinary error.+permission checks, so a caller refused by those gets the ordinary error. A+handler that can only tell whether its write adds while holding row locks+reads the decision first (`paidFeature`) and decides on the locked state, so+it never waits on Cloud under a lock.| Feature | Restricted additions | Always allowed || --- | --- | --- || `private_projects` | create a private project; make a project private; add someone who is not a member yet, directly or by making them the lead | remove members; make it workspace-visible; delete or archive; set the lead to an existing member, an agent or nobody; other fields; the owner's recovery join || `guests` | invite a guest; make a member a guest; share another project with a guest | remove a guest; narrow a guest's projects; make a guest a member; accept an invitation sent while the plan included guests |+| `agent_invocation_members` | create an agent that specific members may invoke (including duplicating one and the CLI `--public-to-member`); add someone to the list; switch from "only me" or "whole workspace" to specific members | remove someone; switch to "only me" or "whole workspace" (an emptied list is the whole workspace); re-save the same list; other fields; invoking the agent |+| `runtime_member_sharing` | add someone to a private runtime's `shared_with`, including switching from "only me" or public to specific members (decided on the locked runtime row) | remove someone; make it public or "only me"; re-save the same list; using the runtime |+| `team_app_accounts` | connect a team account for an app that has none, including after a disconnect (checked when the connect starts and again in the OAuth callback before the account is written); give an agent a team-account app or switch one from a personal account; raise an agent's level on a team account; set a team rule to a value that is neither its current value nor the default | reauthorize an app's existing team account; disconnect; remove an app from an agent; lower a level; restore default team rules (Allow all actions); personal accounts and rules; gateway calls, including existing `block` rules |A stale cached `enforce` is downgraded to `observe` with reason `stale` and`Downgraded` set, then to `off`, exactly like gates, so a Cloud outage admits additions rather thandiff --git a/server/internal/entitlement/feature_test.go b/server/internal/entitlement/feature_test.goindex c3d2f612c9..339c5a6c75 100644--- a/server/internal/entitlement/feature_test.go+++ b/server/internal/entitlement/feature_test.go@@ -56,6 +56,43 @@ func TestCloudFeatureActionsAreDeliveredUnchanged(t *testing.T) {}}+// Revision 7 adds three features. Each is read on its own: a policy from an+// older Cloud that lacks them leaves them off without touching the features+// it does carry.+func TestRevisionSevenFeaturesAreReadIndependently(t *testing.T) {+ server := httptest.NewServer(featurePolicyHandler(t, `{+ "private_projects":{"action":"observe"},+ "agent_invocation_members":{"action":"enforce"},+ "runtime_member_sharing":{"action":"observe"},+ "team_app_accounts":{"action":"off"}+ }`))+ defer server.Close()+ client := newTestClient(t, server.URL, nil)+ workspaceID := uuid.New()+ for name, want := range map[FeatureName]Action{+ FeaturePrivateProjects: ActionObserve,+ FeatureAgentInvocationMembers: ActionEnforce,+ FeatureRuntimeMemberSharing: ActionObserve,+ FeatureTeamAppAccounts: ActionOff,+ } {+ if got := client.Feature(context.Background(), workspaceID, name); got.Action != want || got.Reason != ReasonRefreshed && got.Reason != ReasonCacheFresh {+ t.Fatalf("%s = %+v, want %s", name, got, want)+ }+ }++ older := httptest.NewServer(featurePolicyHandler(t, `{"private_projects":{"action":"enforce"}}`))+ defer older.Close()+ client = newTestClient(t, older.URL, nil)+ for _, name := range []FeatureName{FeatureAgentInvocationMembers, FeatureRuntimeMemberSharing, FeatureTeamAppAccounts} {+ if got := client.Feature(context.Background(), workspaceID, name); got.Action != ActionOff || got.Reason != ReasonFeatureMissing {+ t.Fatalf("%s from an older policy = %+v, want off/feature_missing", name, got)+ }+ }+ if got := client.Feature(context.Background(), workspaceID, FeaturePrivateProjects); got.Action != ActionEnforce {+ t.Fatalf("private_projects = %+v, want enforce", got)+ }+}+// One feature that cannot be read falls back to off with a reason, and the// metered gate from the same response still enforces.func TestMalformedFeatureIsIsolatedFromGatesAndOtherFeatures(t *testing.T) {diff --git a/server/internal/entitlement/types.go b/server/internal/entitlement/types.goindex 054ae4d257..241434db32 100644--- a/server/internal/entitlement/types.go+++ b/server/internal/entitlement/types.go@@ -119,16 +119,33 @@ const (// FeatureGuests covers adding guests (MUL-9420): inviting one, making a// member a guest, and sharing more projects with a guest.FeatureGuests FeatureName = "guests"+ // FeatureAgentInvocationMembers covers letting specific members invoke an+ // agent: creating an agent with a member list, adding to the list, and+ // switching from "only me" or "whole workspace" to specific members.+ FeatureAgentInvocationMembers FeatureName = "agent_invocation_members"+ // FeatureRuntimeMemberSharing covers sharing a private runtime with+ // specific members: adding anyone to its shared_with list.+ FeatureRuntimeMemberSharing FeatureName = "runtime_member_sharing"+ // FeatureTeamAppAccounts covers team Apps accounts: connecting one for an+ // app that has none, giving an agent a team-account app or a higher level+ // on one, and custom team rules.+ FeatureTeamAppAccounts FeatureName = "team_app_accounts")// Features lists every paid feature this consumer understands.func Features() []FeatureName {- return []FeatureName{FeaturePrivateProjects, FeatureGuests}+ return []FeatureName{+ FeaturePrivateProjects,+ FeatureGuests,+ FeatureAgentInvocationMembers,+ FeatureRuntimeMemberSharing,+ FeatureTeamAppAccounts,+ }}func (n FeatureName) Valid() bool {switch n {- case FeaturePrivateProjects, FeatureGuests:+ case FeaturePrivateProjects, FeatureGuests, FeatureAgentInvocationMembers, FeatureRuntimeMemberSharing, FeatureTeamAppAccounts:return truedefault:return falsediff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex eae9f8f900..29b2e1e711 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -22,6 +22,7 @@ import ("github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/internal/attribution"+ "github.com/multica-ai/multica/server/internal/entitlement""github.com/multica-ai/multica/server/internal/logger"obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/projectaccess"@@ -1685,6 +1686,15 @@ func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {return}+ // Paid feature check after every permission and validation check, so a+ // caller who could not create this agent anyway gets the ordinary error.+ var invocationAdmission featureAdmission+ if agentInvocationMembersAdds(permissionModePrivate, nil, perm) {+ if invocationAdmission, ok = h.requireFeatureAddition(w, r, wsUUID, entitlement.FeatureAgentInvocationMembers, agentInvocationOpCreate); !ok {+ return+ }+ }+tx, err := h.TxStarter.Begin(r.Context())if err != nil {writeError(w, http.StatusInternalServerError, "failed to start agent create transaction")@@ -1771,6 +1781,7 @@ func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to commit agent create")return}+ invocationAdmission.admitted(r.Context())slog.Info("agent created", append(logger.RequestAttrs(r), "agent_id", uuidToString(created.ID), "name", created.Name, "workspace_id", workspaceID)...)if runtime.Status == "online" {@@ -2238,6 +2249,7 @@ func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) {_, hasTargets := rawFields["invocation_targets"]permissionTouched := hasPermissionMode || hasTargets || req.Visibility != nilreplacePermissionTargets := false+ invocationAddition := falsevar resolvedPerm resolvedPermissionif permissionTouched {isAgentOwner := uuidToString(existing.OwnerID) == requestUserID(r)@@ -2267,6 +2279,14 @@ func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) {replacePermissionTargets = trueparams.PermissionMode = pgtype.Text{String: perm.mode, Valid: true}params.Visibility = pgtype.Text{String: perm.legacyVisibility(), Valid: true}+ if agentPermissionNeedsCurrentTargets(perm) {+ current, err := h.Queries.ListAgentInvocationTargets(r.Context(), existing.ID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to load agent invocation targets")+ return+ }+ invocationAddition = agentInvocationMembersAdds(existing.PermissionMode, current, perm)+ }}}if req.Status != nil {@@ -2461,6 +2481,14 @@ func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) {}}+ // Paid feature check after every permission and validation check above.+ var invocationAdmission featureAdmission+ if invocationAddition {+ if invocationAdmission, ok = h.requireFeatureAddition(w, r, existing.WorkspaceID, entitlement.FeatureAgentInvocationMembers, agentInvocationOpAddMembers); !ok {+ return+ }+ }+// Only binding writes need this transaction. Hold the same runtime lock as// revocation until the new binding commits; a preflight-only check is stale// as soon as a public runtime becomes private.@@ -2622,6 +2650,7 @@ func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) {return}}+ invocationAdmission.admitted(r.Context())resp := h.agentToResponse(updated)if err := h.enrichAgentResponseWithTargets(r.Context(), &resp, updated.ID); err != nil {diff --git a/server/internal/handler/agent_invocation_feature.go b/server/internal/handler/agent_invocation_feature.gonew file mode 100644index 0000000000..04cc3ecdb0--- /dev/null+++ b/server/internal/handler/agent_invocation_feature.go@@ -0,0 +1,66 @@+package handler++import (+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// Paid feature agent_invocation_members (MUL-9491): letting specific members+// invoke an agent. "Only me" and "whole workspace" are free; a member list is+// the paid configuration. Team targets are not honored by the invoke check+// yet, so they count like members.+//+// Invocation itself (canInvokeAgent) never consults the feature: after a+// downgrade, members on an existing list keep invoking and everyone else is+// still refused.++const (+ agentInvocationOpCreate = "create"+ agentInvocationOpAddMembers = "add_members"+)++// agentInvocationMembersAdds reports whether moving an agent's invocation+// permission from (beforeMode, before) to after adds to the paid feature: the+// result is a member list (no workspace target) that names someone the+// current permission did not. Switching from "only me" or "whole workspace"+// to a member list is an addition; switching to "only me" or "whole+// workspace", removing people, and re-saving the same list are not. A create+// is the move from "only me" with no targets.+//+// An emptied list never reaches here as a member list: parsePermissionInput+// normalises an empty public_to to the workspace target, which is free.+func agentInvocationMembersAdds(beforeMode string, before []db.AgentInvocationTarget, after resolvedPermission) bool {+ if after.mode != permissionModePublicTo {+ return false+ }+ for _, t := range after.targets {+ if t.targetType == invocationTargetWorkspace {+ return false+ }+ }+ if len(after.targets) == 0 {+ return false+ }+ if beforeMode != permissionModePublicTo {+ return true+ }+ have := make(map[string]struct{}, len(before))+ for _, t := range before {+ if t.TargetType == invocationTargetWorkspace {+ // Everyone could invoke it; a member list is a new configuration.+ return true+ }+ have[t.TargetType+":"+uuidToString(t.TargetID)] = struct{}{}+ }+ for _, t := range after.targets {+ if _, ok := have[t.targetType+":"+uuidToString(t.targetID)]; !ok {+ return true+ }+ }+ return false+}++// agentPermissionNeedsCurrentTargets reports whether deciding the addition+// needs the agent's current targets: only a member-list result does.+func agentPermissionNeedsCurrentTargets(after resolvedPermission) bool {+ return agentInvocationMembersAdds(permissionModePrivate, nil, after)+}diff --git a/server/internal/handler/agent_invocation_feature_test.go b/server/internal/handler/agent_invocation_feature_test.gonew file mode 100644index 0000000000..9b0ec67d2a--- /dev/null+++ b/server/internal/handler/agent_invocation_feature_test.go@@ -0,0 +1,299 @@+package handler++import (+ "context"+ "net/http"+ "sort"+ "testing"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/internal/entitlement"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func memberTargets(ids ...string) []map[string]any {+ out := make([]map[string]any, 0, len(ids))+ for _, id := range ids {+ out = append(out, map[string]any{"target_type": "member", "target_id": id})+ }+ return out+}++func workspaceTarget() []map[string]any {+ return []map[string]any{{"target_type": "workspace", "target_id": testWorkspaceID}}+}++func createAgentWithAccessAs(t *testing.T, userID, runtimeID, name, mode string, targets []map[string]any) *testutil.Response {+ t.Helper()+ body := map[string]any{"name": name, "runtime_id": runtimeID, "permission_mode": mode}+ if targets != nil {+ body["invocation_targets"] = targets+ }+ t.Cleanup(func() {+ ctx := context.Background()+ testPool.Exec(ctx, `DELETE FROM agent_invocation_target WHERE agent_id IN (SELECT id FROM agent WHERE workspace_id = $1 AND name = $2)`, testWorkspaceID, name)+ testPool.Exec(ctx, `DELETE FROM agent WHERE workspace_id = $1 AND name = $2`, testWorkspaceID, name)+ })+ return testutil.Call(t, testHandler.CreateAgent, newRequestAs(userID, http.MethodPost, "/api/agents?workspace_id="+testWorkspaceID, body))+}++func agentCountByName(t *testing.T, name string) int {+ t.Helper()+ var n int+ if err := testPool.QueryRow(context.Background(), `SELECT count(*) FROM agent WHERE workspace_id = $1 AND name = $2`, testWorkspaceID, name).Scan(&n); err != nil {+ t.Fatalf("count agents: %v", err)+ }+ return n+}++func updateAgentAccessAs(t *testing.T, userID, agentID, mode string, targets []map[string]any) *testutil.Response {+ t.Helper()+ body := map[string]any{"permission_mode": mode}+ if targets != nil {+ body["invocation_targets"] = targets+ }+ req := withURLParam(newRequestAs(userID, http.MethodPut, "/api/agents/"+agentID, body), "id", agentID)+ return testutil.Call(t, testHandler.UpdateAgent, req)+}++// agentAccess is an agent's stored permission mode and sorted target keys.+func agentAccess(t *testing.T, agentID string) (string, []string) {+ t.Helper()+ ctx := context.Background()+ a, err := testHandler.Queries.GetAgent(ctx, parseUUID(agentID))+ if err != nil {+ t.Fatalf("load agent: %v", err)+ }+ rows, err := testHandler.Queries.ListAgentInvocationTargets(ctx, a.ID)+ if err != nil {+ t.Fatalf("load targets: %v", err)+ }+ keys := make([]string, 0, len(rows))+ for _, row := range rows {+ keys = append(keys, row.TargetType+":"+uuidToString(row.TargetID))+ }+ sort.Strings(keys)+ return a.PermissionMode, keys+}++func memberKeys(ids ...string) []string {+ keys := make([]string, 0, len(ids))+ for _, id := range ids {+ keys = append(keys, "member:"+id)+ }+ sort.Strings(keys)+ return keys+}++func wantAgentAccess(t *testing.T, agentID, wantMode string, wantKeys []string) {+ t.Helper()+ mode, keys := agentAccess(t, agentID)+ if mode != wantMode || len(keys) != len(wantKeys) {+ t.Fatalf("access = %s %v, want %s %v", mode, keys, wantMode, wantKeys)+ }+ for i := range keys {+ if keys[i] != wantKeys[i] {+ t.Fatalf("access = %s %v, want %s %v", mode, keys, wantMode, wantKeys)+ }+ }+}++// Creating an agent with a member list under each action: allowed when+// self-hosted, off or observed (observe records it), rejected under enforce+// without writing an agent.+func TestAgentInvocationMembersCreateUnderEachAction(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ member := createPermissionTestMember(t, "aim-create-"+uuid.NewString()[:8]+"@multica.test")+ runtimeID := handlerTestRuntimeID(t)+ for _, tc := range featureCases {+ t.Run(tc.name, func(t *testing.T) {+ usePaidFeatureOn(t, testHandler, entitlement.FeatureAgentInvocationMembers, tc.decision)+ name := "aim create " + tc.name + " " + uuid.NewString()[:8]+ resp := createAgentWithAccessAs(t, testUserID, runtimeID, name, "public_to", memberTargets(member))+ if tc.locked {+ wantFeatureLockedFor(t, resp, entitlement.FeatureAgentInvocationMembers)+ if n := agentCountByName(t, name); n != 0 {+ t.Fatalf("rejected create wrote %d agents", n)+ }+ wantAttempts(t, entitlement.FeatureAgentInvocationMembers, featureAttemptCounts{enforced: 1, lastOperation: "create"})+ return+ }+ resp.Want(http.StatusCreated)+ want := featureAttemptCounts{}+ if tc.observed > 0 {+ want = featureAttemptCounts{observed: 1, lastOperation: "create"}+ }+ wantAttempts(t, entitlement.FeatureAgentInvocationMembers, want)+ })+ }+}++// "Only me" and "whole workspace" are free: creating either is never+// restricted or recorded.+func TestAgentInvocationMembersFreeCreatesIgnoreFeature(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ usePaidFeatureOn(t, testHandler, entitlement.FeatureAgentInvocationMembers, enforced())+ runtimeID := handlerTestRuntimeID(t)+ createAgentWithAccessAs(t, testUserID, runtimeID, "aim free private "+uuid.NewString()[:8], "private", nil).Want(http.StatusCreated)+ createAgentWithAccessAs(t, testUserID, runtimeID, "aim free workspace "+uuid.NewString()[:8], "public_to", workspaceTarget()).Want(http.StatusCreated)+ // An empty public_to normalises to the whole workspace.+ createAgentWithAccessAs(t, testUserID, runtimeID, "aim free empty "+uuid.NewString()[:8], "public_to", []map[string]any{}).Want(http.StatusCreated)+ wantNoAttempts(t, entitlement.FeatureAgentInvocationMembers)+}++// After a downgrade an agent's member list keeps working exactly as+// configured. Removing people, switching to "only me" or "whole workspace",+// and re-saving are allowed; adding someone, or going back to a member list+// from "only me" or "whole workspace", is refused and leaves access unchanged.+func TestAgentInvocationMembersEnforcedKeepsExistingAndAllowsReductions(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ a := createPermissionTestMember(t, "aim-a-"+uuid.NewString()[:8]+"@multica.test")+ b := createPermissionTestMember(t, "aim-b-"+uuid.NewString()[:8]+"@multica.test")+ c := createPermissionTestMember(t, "aim-c-"+uuid.NewString()[:8]+"@multica.test")+ var created AgentResponse+ createAgentWithAccessAs(t, testUserID, handlerTestRuntimeID(t), "aim enforced "+uuid.NewString()[:8], "public_to", memberTargets(a, b)).+ Want(http.StatusCreated).JSON(&created)++ usePaidFeatureOn(t, testHandler, entitlement.FeatureAgentInvocationMembers, enforced())++ agentRow, err := testHandler.Queries.GetAgent(ctx, parseUUID(created.ID))+ if err != nil {+ t.Fatalf("load agent: %v", err)+ }+ for _, tc := range []struct {+ user string+ want bool+ }{{a, true}, {b, true}, {c, false}} {+ if got := testHandler.canInvokeAgent(ctx, agentRow, "member", tc.user, "", testWorkspaceID); got != tc.want {+ t.Fatalf("canInvokeAgent(%s) = %v under enforce, want %v", tc.user, got, tc.want)+ }+ }++ // Same list re-saved: allowed.+ updateAgentAccessAs(t, testUserID, created.ID, "public_to", memberTargets(b, a)).Want(http.StatusOK)+ // Adding someone: refused, unchanged.+ wantFeatureLockedFor(t, updateAgentAccessAs(t, testUserID, created.ID, "public_to", memberTargets(a, b, c)), entitlement.FeatureAgentInvocationMembers)+ wantAgentAccess(t, created.ID, "public_to", memberKeys(a, b))+ // Swapping someone out for someone new is still an addition.+ wantFeatureLockedFor(t, updateAgentAccessAs(t, testUserID, created.ID, "public_to", memberTargets(a, c)), entitlement.FeatureAgentInvocationMembers)+ // Removing someone: allowed.+ updateAgentAccessAs(t, testUserID, created.ID, "public_to", memberTargets(a)).Want(http.StatusOK)+ wantAgentAccess(t, created.ID, "public_to", memberKeys(a))+ // Whole workspace, then back to a member list: the second is an addition.+ updateAgentAccessAs(t, testUserID, created.ID, "public_to", workspaceTarget()).Want(http.StatusOK)+ wantFeatureLockedFor(t, updateAgentAccessAs(t, testUserID, created.ID, "public_to", memberTargets(a)), entitlement.FeatureAgentInvocationMembers)+ // Only me, then back to a member list: the second is an addition.+ updateAgentAccessAs(t, testUserID, created.ID, "private", nil).Want(http.StatusOK)+ wantFeatureLockedFor(t, updateAgentAccessAs(t, testUserID, created.ID, "public_to", memberTargets(a)), entitlement.FeatureAgentInvocationMembers)+ wantAgentAccess(t, created.ID, "private", []string{})+ // An emptied list is the whole workspace, which is free.+ updateAgentAccessAs(t, testUserID, created.ID, "public_to", []map[string]any{}).Want(http.StatusOK)+ wantAgentAccess(t, created.ID, "public_to", []string{"workspace:" + testWorkspaceID})++ wantAttempts(t, entitlement.FeatureAgentInvocationMembers, featureAttemptCounts{enforced: 4, lastOperation: "add_members"})+}++// An observed addition is admitted and recorded once, after the write.+func TestAgentInvocationMembersObservedUpdateIsRecorded(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ a := createPermissionTestMember(t, "aim-obs-a-"+uuid.NewString()[:8]+"@multica.test")+ b := createPermissionTestMember(t, "aim-obs-b-"+uuid.NewString()[:8]+"@multica.test")+ var created AgentResponse+ createAgentWithAccessAs(t, testUserID, handlerTestRuntimeID(t), "aim observe "+uuid.NewString()[:8], "public_to", memberTargets(a)).+ Want(http.StatusCreated).JSON(&created)+ usePaidFeatureOn(t, testHandler, entitlement.FeatureAgentInvocationMembers, observed())+ updateAgentAccessAs(t, testUserID, created.ID, "public_to", memberTargets(a, b)).Want(http.StatusOK)+ wantAgentAccess(t, created.ID, "public_to", memberKeys(a, b))+ // A reduction is not recorded.+ updateAgentAccessAs(t, testUserID, created.ID, "public_to", memberTargets(b)).Want(http.StatusOK)+ wantAttempts(t, entitlement.FeatureAgentInvocationMembers, featureAttemptCounts{observed: 1, lastOperation: "add_members"})+}++// The restriction runs after the ordinary permission checks: a caller who+// could not make the change gets the original 403 and nothing is recorded.+func TestAgentInvocationMembersPermissionChecksComeFirst(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ owner := createPermissionTestMember(t, "aim-owner-"+uuid.NewString()[:8]+"@multica.test")+ other := createPermissionTestMember(t, "aim-other-"+uuid.NewString()[:8]+"@multica.test")+ usePaidFeatureOn(t, testHandler, entitlement.FeatureAgentInvocationMembers, enforced())++ // A workspace admin who does not own the agent may not change its access.+ agentID := dbfx.Agent(t, "aim not mine "+uuid.NewString()[:8], handlerTestRuntimeID(t), testutil.Cols{+ "owner_id": owner, "permission_mode": "private", "visibility": "private",+ })+ wantPlainForbidden(t, updateAgentAccessAs(t, testUserID, agentID, "public_to", memberTargets(other)))++ // A private runtime the caller cannot use is refused before the feature.+ runtimeID := dbfx.Insert(t, "agent_runtime", testutil.Cols{+ "workspace_id": testWorkspaceID, "name": "aim private runtime " + uuid.NewString()[:8],+ "runtime_mode": "local", "provider": "claude", "status": "online", "device_info": "test",+ "metadata": testutil.Raw(`'{}'::jsonb`), "owner_id": owner, "visibility": "private",+ })+ wantPlainForbidden(t, createAgentWithAccessAs(t, other, runtimeID, "aim no runtime "+uuid.NewString()[:8], "public_to", memberTargets(owner)))++ wantNoAttempts(t, entitlement.FeatureAgentInvocationMembers)+}++func TestAgentInvocationMembersAddsClassification(t *testing.T) {+ ws := pgtype.UUID{Bytes: uuid.New(), Valid: true}+ a := pgtype.UUID{Bytes: uuid.New(), Valid: true}+ b := pgtype.UUID{Bytes: uuid.New(), Valid: true}+ team := pgtype.UUID{Bytes: uuid.New(), Valid: true}+ members := func(ids ...pgtype.UUID) resolvedPermission {+ p := resolvedPermission{mode: permissionModePublicTo}+ for _, id := range ids {+ p.targets = append(p.targets, targetSpec{targetType: invocationTargetMember, targetID: id})+ }+ return p+ }+ rows := func(specs ...targetSpec) []db.AgentInvocationTarget {+ out := make([]db.AgentInvocationTarget, 0, len(specs))+ for _, s := range specs {+ out = append(out, db.AgentInvocationTarget{TargetType: s.targetType, TargetID: s.targetID})+ }+ return out+ }+ workspace := targetSpec{targetType: invocationTargetWorkspace, targetID: ws}+ memberA := targetSpec{targetType: invocationTargetMember, targetID: a}+ memberB := targetSpec{targetType: invocationTargetMember, targetID: b}+ for _, tc := range []struct {+ name string+ beforeMode string+ before []db.AgentInvocationTarget+ after resolvedPermission+ want bool+ }{+ {"create private", permissionModePrivate, nil, resolvedPermission{mode: permissionModePrivate}, false},+ {"create workspace", permissionModePrivate, nil, resolvedPermission{mode: permissionModePublicTo, targets: []targetSpec{workspace}}, false},+ {"create members", permissionModePrivate, nil, members(a), true},+ {"create team", permissionModePrivate, nil, resolvedPermission{mode: permissionModePublicTo, targets: []targetSpec{{targetType: invocationTargetTeam, targetID: team}}}, true},+ {"workspace plus members is workspace", permissionModePrivate, nil, resolvedPermission{mode: permissionModePublicTo, targets: []targetSpec{memberA, workspace}}, false},+ {"same list", permissionModePublicTo, rows(memberA, memberB), members(b, a), false},+ {"remove", permissionModePublicTo, rows(memberA, memberB), members(a), false},+ {"add", permissionModePublicTo, rows(memberA), members(a, b), true},+ {"swap", permissionModePublicTo, rows(memberA), members(b), true},+ {"workspace to members", permissionModePublicTo, rows(workspace), members(a), true},+ {"workspace and member to the same member", permissionModePublicTo, rows(workspace, memberA), members(a), true},+ {"private to members", permissionModePrivate, nil, members(a), true},+ {"members to private", permissionModePublicTo, rows(memberA), resolvedPermission{mode: permissionModePrivate}, false},+ {"members to workspace", permissionModePublicTo, rows(memberA), resolvedPermission{mode: permissionModePublicTo, targets: []targetSpec{workspace}}, false},+ } {+ if got := agentInvocationMembersAdds(tc.beforeMode, tc.before, tc.after); got != tc.want {+ t.Errorf("%s: adds = %v, want %v", tc.name, got, tc.want)+ }+ }+}diff --git a/server/internal/handler/business_feature_test.go b/server/internal/handler/business_feature_test.gonew file mode 100644index 0000000000..cd9bf14584--- /dev/null+++ b/server/internal/handler/business_feature_test.go@@ -0,0 +1,109 @@+package handler++import (+ "context"+ "net/http"+ "strings"+ "testing"++ "github.com/google/uuid"++ "github.com/multica-ai/multica/server/internal/entitlement"+ "github.com/multica-ai/multica/server/internal/entitlement/entitlementtest"+ "github.com/multica-ai/multica/server/internal/testutil"+)++// Shared helpers for the Business paid features wired in MUL-9491:+// agent_invocation_members, runtime_member_sharing and team_app_accounts.++// usePaidFeatureOn points h at a stub that returns decision for feature in+// the test workspace (every other feature stays off), and clears the+// workspace's recorded attempts before and after. A nil decision leaves h+// without a provider, as on a self-hosted deployment.+func usePaidFeatureOn(t *testing.T, h *Handler, feature entitlement.FeatureName, decision *entitlement.FeatureDecision) {+ t.Helper()+ prior := h.Features+ if decision == nil {+ h.Features = nil+ } else {+ stub := entitlementtest.New()+ stub.SetFeature(uuid.MustParse(testWorkspaceID), feature, *decision)+ h.Features = stub+ }+ clearFeatureAttempts(t)+ t.Cleanup(func() {+ h.Features = prior+ clearFeatureAttempts(t)+ })+}++// featureCases is the matrix every feature runs an addition through:+// self-hosted (no provider), off, observe and enforce.+var featureCases = []struct {+ name string+ decision *entitlement.FeatureDecision+ locked bool+ observed int64+}{+ {"self-hosted", nil, false, 0},+ {"off", &entitlement.FeatureDecision{Action: entitlement.ActionOff, Reason: entitlement.ReasonRefreshed}, false, 0},+ {"observe", &entitlement.FeatureDecision{Action: entitlement.ActionObserve, Reason: entitlement.ReasonRefreshed, PolicyRevision: 7}, false, 1},+ {"enforce", &entitlement.FeatureDecision{Action: entitlement.ActionEnforce, Reason: entitlement.ReasonRefreshed, PolicyRevision: 7}, true, 0},+}++func enforced() *entitlement.FeatureDecision {+ return &entitlement.FeatureDecision{Action: entitlement.ActionEnforce, Reason: entitlement.ReasonRefreshed, PolicyRevision: 7}+}++func observed() *entitlement.FeatureDecision {+ return &entitlement.FeatureDecision{Action: entitlement.ActionObserve, Reason: entitlement.ReasonRefreshed, PolicyRevision: 7}+}++func featureAttemptsFor(t *testing.T, feature entitlement.FeatureName) featureAttemptCounts {+ t.Helper()+ var c featureAttemptCounts+ err := testPool.QueryRow(context.Background(), `+ SELECT COALESCE(SUM(observed_count), 0), COALESCE(SUM(degraded_count), 0), COALESCE(SUM(enforced_count), 0),+ COALESCE(MAX(last_operation), '')+ FROM entitlement_feature_attempt+ WHERE workspace_id = $1 AND feature = $2`, testWorkspaceID, string(feature),+ ).Scan(&c.observed, &c.degraded, &c.enforced, &c.lastOperation)+ if err != nil {+ t.Fatalf("read feature attempts: %v", err)+ }+ return c+}++func wantAttempts(t *testing.T, feature entitlement.FeatureName, want featureAttemptCounts) {+ t.Helper()+ if got := featureAttemptsFor(t, feature); got != want {+ t.Fatalf("%s attempts = %+v, want %+v", feature, got, want)+ }+}++func wantNoAttempts(t *testing.T, feature entitlement.FeatureName) {+ t.Helper()+ wantAttempts(t, feature, featureAttemptCounts{})+}++func wantFeatureLockedFor(t *testing.T, resp *testutil.Response, feature entitlement.FeatureName) {+ t.Helper()+ var body struct {+ Code string `json:"code"`+ Feature string `json:"feature"`+ }+ resp.Want(http.StatusForbidden).JSON(&body)+ if body.Code != "feature_locked" || body.Feature != string(feature) {+ t.Fatalf("locked body = %+v, want feature_locked/%s", body, feature)+ }+}++// wantPlainForbidden asserts the ordinary permission error, not the paid+// feature: the restriction runs after every permission check.+func wantPlainForbidden(t *testing.T, resp *testutil.Response) {+ t.Helper()+ resp.Want(http.StatusForbidden)+ if strings.Contains(resp.Text(), "feature_locked") {+ t.Fatalf("permission failure answered with the paid feature: %s", resp.Text())+ }+}diff --git a/server/internal/handler/connected_apps.go b/server/internal/handler/connected_apps.goindex c73f9e1ec7..f5139d2ddc 100644--- a/server/internal/handler/connected_apps.go+++ b/server/internal/handler/connected_apps.go@@ -14,6 +14,7 @@ import ("github.com/go-chi/chi/v5""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/connectedapps"+ "github.com/multica-ai/multica/server/internal/entitlement""github.com/multica-ai/multica/server/internal/integrations/composio""github.com/multica-ai/multica/server/internal/logger"db "github.com/multica-ai/multica/server/pkg/db/generated"@@ -360,6 +361,23 @@ func (h *Handler) ConnectTeamApp(w http.ResponseWriter, r *http.Request) {if !ok {return}+ // Reauthorizing the app's existing team account is always allowed. A new+ // one is an addition; an observed one is recorded by the callback once+ // the account is written (TeamAppConnectGate), so only rejections are+ // recorded here.+ if feature := h.paidFeature(r.Context(), workspaceID, entitlement.FeatureTeamAppAccounts); feature.active {+ reconnect, err := h.teamAppHasAccount(r.Context(), workspaceID, req.ToolkitSlug)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list team accounts")+ return+ }+ if !reconnect {+ if _, ok := feature.addition(r.Context(), teamAppOpConnect); !ok {+ writeFeatureLocked(w, entitlement.FeatureTeamAppAccounts)+ return+ }+ }+ }url, err := h.Composio.BeginTeamConnect(r.Context(), workspaceID, member.UserID, req.ToolkitSlug, req.ReturnTo)if err != nil {writeConnectError(w, r, err)@@ -607,10 +625,7 @@ func (h *Handler) UpdateAppRules(w http.ResponseWriter, r *http.Request) {return}var req struct {- Rules []struct {- ActionClass string `json:"action_class"`- Policy string `json:"policy"`- } `json:"rules"`+ Rules []appRuleInput `json:"rules"`}if err := json.NewDecoder(r.Body).Decode(&req); err != nil {writeError(w, http.StatusBadRequest, "invalid request body")@@ -622,6 +637,27 @@ func (h *Handler) UpdateAppRules(w http.ResponseWriter, r *http.Request) {return}}+ // Custom team rules are part of team_app_accounts; personal rules are not.+ var admission featureAdmission+ if scope == connectedapps.ScopeTeam {+ if feature := h.paidFeature(r.Context(), workspaceID, entitlement.FeatureTeamAppAccounts); feature.active {+ rows, err := h.Queries.ListAppActionRules(r.Context(), db.ListAppActionRulesParams{WorkspaceID: workspaceID, ToolkitSlug: slug, OwnerUserID: owner})+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list rules")+ return+ }+ current := make(map[string]string, len(rows))+ for _, row := range rows {+ current[row.ActionClass] = row.Policy+ }+ if teamRulesAdd(slug, current, req.Rules) {+ if admission, ok = feature.addition(r.Context(), teamAppOpChangeRules); !ok {+ writeFeatureLocked(w, entitlement.FeatureTeamAppAccounts)+ return+ }+ }+ }+ }tx, err := h.TxStarter.Begin(r.Context())if err != nil {writeError(w, http.StatusInternalServerError, "failed to save rules")@@ -642,6 +678,7 @@ func (h *Handler) UpdateAppRules(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to save rules")return}+ admission.admitted(r.Context())rules, err := h.rulesResponse(r.Context(), workspaceID, slug, owner)if err != nil {writeError(w, http.StatusInternalServerError, "failed to list rules")@@ -887,6 +924,7 @@ func (h *Handler) UpdateAgentApps(w http.ResponseWriter, r *http.Request) {seen := map[string]bool{}type want struct{ slug, scope, level string }var wants []want+ teamAddition := ""for _, app := range req.Apps {if app.Level == "" {app.Level = connectedapps.DefaultLevel(agent.PermissionMode)@@ -908,6 +946,9 @@ func (h *Handler) UpdateAgentApps(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusForbidden, "only workspace admins can give agents a team account")return}+ if op := agentTeamAppAdds(prev, had, app.AccountScope, app.Level); op != "" && teamAddition == "" {+ teamAddition = op+ }keep = append(keep, slug)wants = append(wants, want{slug, app.AccountScope, app.Level})}@@ -919,6 +960,12 @@ func (h *Handler) UpdateAgentApps(w http.ResponseWriter, r *http.Request) {}}}+ var admission featureAdmission+ if teamAddition != "" {+ if admission, ok = h.requireFeatureAddition(w, r, workspaceID, entitlement.FeatureTeamAppAccounts, teamAddition); !ok {+ return+ }+ }tx, err := h.TxStarter.Begin(ctx)if err != nil {writeError(w, http.StatusInternalServerError, "failed to save agent apps")@@ -947,6 +994,7 @@ func (h *Handler) UpdateAgentApps(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to save agent apps")return}+ admission.admitted(ctx)h.ListAgentApps(w, r)}diff --git a/server/internal/handler/integrations_composio.go b/server/internal/handler/integrations_composio.goindex c7b150e978..c6ce988c66 100644--- a/server/internal/handler/integrations_composio.go+++ b/server/internal/handler/integrations_composio.go@@ -120,10 +120,17 @@ func (h *Handler) ComposioCallback(w http.ResponseWriter, r *http.Request) {connectedAccountID := q.Get("connected_account_id")result, err := h.Composio.CompleteCallback(r.Context(), state, status, connectedAccountID)+ if errors.Is(err, composio.ErrTeamConnectRefused) {+ // The handshake was verified and only the workspace's plan refused+ // the account: say so, so the page offers the upgrade instead of a+ // retry that would fail the same way.+ http.Redirect(w, r, h.Composio.CallbackRedirectFailure(result, composio.CallbackFeatureLockedReason), http.StatusFound)+ return+ }if err != nil {- // Every failure (tampered/expired state, non-success status, write- // error) collapses to the generic failure redirect — we never tell the- // browser which check failed.+ // Every other failure (tampered/expired state, non-success status,+ // write error) collapses to the generic failure redirect — we never+ // tell the browser which check failed.http.Redirect(w, r, h.Composio.CallbackRedirect(result, false), http.StatusFound)return}diff --git a/server/internal/handler/paid_feature.go b/server/internal/handler/paid_feature.goindex 8ed81306b6..d999ab43c6 100644--- a/server/internal/handler/paid_feature.go+++ b/server/internal/handler/paid_feature.go@@ -55,26 +55,55 @@ func (a featureAdmission) admitted(ctx context.Context) {// rejection and answers 403 feature_locked; under observe it admits the// addition and returns an admission to record after the write commits.func (h *Handler) requireFeatureAddition(w http.ResponseWriter, r *http.Request, workspaceID pgtype.UUID, feature entitlement.FeatureName, operation string) (featureAdmission, bool) {+ admission, ok := h.paidFeature(r.Context(), workspaceID, feature).addition(r.Context(), operation)+ if !ok {+ writeFeatureLocked(w, feature)+ }+ return admission, ok+}++// paidFeature is one paid feature's decision for one workspace, read ahead of+// the write. A handler that decides whether its write adds only while holding+// row locks reads it first, so it never waits on Cloud under a lock, then+// calls addition on the locked state.+type paidFeature struct {+ attempts service.EntitlementFeatureAttempts+ attempt service.FeatureAttempt+ // active is false when the feature is off or there is no provider, as on+ // a self-hosted deployment: nothing is restricted or recorded.+ active bool+}++func (h *Handler) paidFeature(ctx context.Context, workspaceID pgtype.UUID, feature entitlement.FeatureName) paidFeature {if h.Features == nil || !workspaceID.Valid {- return featureAdmission{}, true+ return paidFeature{}}- decision := h.Features.Feature(r.Context(), uuid.UUID(workspaceID.Bytes), feature)+ decision := h.Features.Feature(ctx, uuid.UUID(workspaceID.Bytes), feature)if decision.Action == entitlement.ActionOff {- return featureAdmission{}, true+ return paidFeature{}}- attempts := service.EntitlementFeatureAttempts{Queries: h.Queries}- attempt := service.FeatureAttempt{- WorkspaceID: workspaceID,- Feature: feature,- Operation: operation,- Decision: decision,+ return paidFeature{+ attempts: service.EntitlementFeatureAttempts{Queries: h.Queries},+ attempt: service.FeatureAttempt{WorkspaceID: workspaceID, Feature: feature, Decision: decision},+ active: true,}- if decision.Restricted() {- attempts.Record(r.Context(), attempt)- writeFeatureLocked(w, feature)+}++// addition decides one write that adds to the feature. ok=false means the+// addition is rejected: the rejection is already recorded and the caller+// answers feature_locked. Otherwise the returned admission records an+// observed addition once the write commits.+func (f paidFeature) addition(ctx context.Context, operation string) (featureAdmission, bool) {+ if !f.active {+ return featureAdmission{}, true+ }+ attempt := f.attempt+ attempt.Operation = operation+ if attempt.Decision.Restricted() {+ f.attempts.Record(ctx, attempt)return featureAdmission{}, false}- return featureAdmission{attempts: attempts, attempt: attempt, record: true}, true+ return featureAdmission{attempts: f.attempts, attempt: attempt, record: true}, true}func writeFeatureLocked(w http.ResponseWriter, feature entitlement.FeatureName) {diff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.goindex 1a109dbaf7..e0de05e27e 100644--- a/server/internal/handler/runtime.go+++ b/server/internal/handler/runtime.go@@ -16,6 +16,7 @@ import ("github.com/jackc/pgx/v5/pgconn""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/agentconfig"+ "github.com/multica-ai/multica/server/internal/entitlement"obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/internal/util"@@ -568,12 +569,20 @@ func (h *Handler) UpdateAgentRuntime(w http.ResponseWriter, r *http.Request) {changed := falseif req.Visibility != nil || req.SharedWith != nil {- updated, plan, didChange, err := h.updateRuntimeAccessIfNoDependencies(r.Context(), rt, member, req)+ // Read the paid feature before the runtime row is locked; the addition+ // itself is decided against the locked row.+ var sharing paidFeature+ if runtimeShareRequestMayAdd(req) {+ sharing = h.paidFeature(r.Context(), rt.WorkspaceID, entitlement.FeatureRuntimeMemberSharing)+ }+ updated, plan, didChange, admission, err := h.updateRuntimeAccessIfNoDependencies(r.Context(), rt, member, req, sharing)if err != nil {if writeRuntimeRevocationBusy(w, err) {return}- if errors.Is(err, errRuntimeOwnerChanged) {+ if errors.Is(err, errRuntimeFeatureLocked) {+ writeFeatureLocked(w, entitlement.FeatureRuntimeMemberSharing)+ } else if errors.Is(err, errRuntimeOwnerChanged) {writeError(w, http.StatusForbidden, "only the runtime owner can change its visibility")} else if errors.Is(err, errRuntimeManagedByConnection) {writeJSON(w, http.StatusConflict, map[string]any{"error": "the Qoder runtime is always shared with the workspace", "code": "runtime_managed_by_connection"})@@ -589,6 +598,7 @@ func (h *Handler) UpdateAgentRuntime(w http.ResponseWriter, r *http.Request) {writeJSON(w, http.StatusConflict, h.runtimeWorkspaceAccessRevocationResponse(plan, "runtime_has_nonowner_dependents"))return}+ admission.admitted(r.Context())rt = updatedchanged = didChange}@@ -764,34 +774,45 @@ func (p runtimeWorkspaceAccessRevocationPlan) hasDependencies() bool {// A non-empty plan is deliberately returned without committing. The caller// turns it into the same confirmation response used by the disruptive path;// the confirmed endpoint will take a fresh locked snapshot before revoking.-func (h *Handler) updateRuntimeAccessIfNoDependencies(ctx context.Context, rt db.AgentRuntime, member db.Member, req UpdateAgentRuntimeRequest) (db.AgentRuntime, runtimeWorkspaceAccessRevocationPlan, bool, error) {+//+// sharing is runtime_member_sharing read before the lock. An addition is+// decided against the locked row, after the owner check; an admitted one is+// returned for the caller to record once committed.+func (h *Handler) updateRuntimeAccessIfNoDependencies(ctx context.Context, rt db.AgentRuntime, member db.Member, req UpdateAgentRuntimeRequest, sharing paidFeature) (db.AgentRuntime, runtimeWorkspaceAccessRevocationPlan, bool, featureAdmission, error) {tx, err := h.TxStarter.Begin(ctx)if err != nil {- return db.AgentRuntime{}, runtimeWorkspaceAccessRevocationPlan{}, false, fmt.Errorf("begin transaction: %w", err)+ return db.AgentRuntime{}, runtimeWorkspaceAccessRevocationPlan{}, false, featureAdmission{}, fmt.Errorf("begin transaction: %w", err)}defer tx.Rollback(ctx)qtx := h.Queries.WithTx(tx)lockedRuntime, err := qtx.LockAgentRuntimeForAccessChange(ctx, rt.ID)if err != nil {- return db.AgentRuntime{}, runtimeWorkspaceAccessRevocationPlan{}, false, fmt.Errorf("lock runtime: %w", err)+ return db.AgentRuntime{}, runtimeWorkspaceAccessRevocationPlan{}, false, featureAdmission{}, fmt.Errorf("lock runtime: %w", err)}next, err := resolveRuntimeAccess(ctx, qtx, lockedRuntime, req)if err != nil {- return db.AgentRuntime{}, runtimeWorkspaceAccessRevocationPlan{}, false, err+ return db.AgentRuntime{}, runtimeWorkspaceAccessRevocationPlan{}, false, featureAdmission{}, err}if sameRuntimeAccess(lockedRuntime, next) {- return lockedRuntime, runtimeWorkspaceAccessRevocationPlan{}, false, nil+ return lockedRuntime, runtimeWorkspaceAccessRevocationPlan{}, false, featureAdmission{}, nil}if !canSetRuntimeVisibility(member, lockedRuntime) {- return db.AgentRuntime{}, runtimeWorkspaceAccessRevocationPlan{}, false, errRuntimeOwnerChanged+ return db.AgentRuntime{}, runtimeWorkspaceAccessRevocationPlan{}, false, featureAdmission{}, errRuntimeOwnerChanged}managed, err := h.qoderManagesRuntime(ctx, lockedRuntime)if err != nil {- return db.AgentRuntime{}, runtimeWorkspaceAccessRevocationPlan{}, false, err+ return db.AgentRuntime{}, runtimeWorkspaceAccessRevocationPlan{}, false, featureAdmission{}, err}if managed {- return db.AgentRuntime{}, runtimeWorkspaceAccessRevocationPlan{}, false, errRuntimeManagedByConnection+ return db.AgentRuntime{}, runtimeWorkspaceAccessRevocationPlan{}, false, featureAdmission{}, errRuntimeManagedByConnection+ }+ var admission featureAdmission+ if runtimeMemberSharingAdds(lockedRuntime, next) {+ var ok bool+ if admission, ok = sharing.addition(ctx, runtimeSharingOpAddMembers); !ok {+ return db.AgentRuntime{}, runtimeWorkspaceAccessRevocationPlan{}, false, featureAdmission{}, errRuntimeFeatureLocked+ }}if runtimeAccessNarrows(lockedRuntime, next) {@@ -801,7 +822,7 @@ func (h *Handler) updateRuntimeAccessIfNoDependencies(ctx context.Context, rt dbSharedWith: next.SharedWith,})if err != nil {- return db.AgentRuntime{}, runtimeWorkspaceAccessRevocationPlan{}, false, fmt.Errorf("list non-owner agents: %w", err)+ return db.AgentRuntime{}, runtimeWorkspaceAccessRevocationPlan{}, false, featureAdmission{}, fmt.Errorf("list non-owner agents: %w", err)}tasks, err := qtx.ListNonOwnerActiveTasksByRuntime(ctx, db.ListNonOwnerActiveTasksByRuntimeParams{RuntimeID: lockedRuntime.ID,@@ -809,11 +830,11 @@ func (h *Handler) updateRuntimeAccessIfNoDependencies(ctx context.Context, rt dbSharedWith: next.SharedWith,})if err != nil {- return db.AgentRuntime{}, runtimeWorkspaceAccessRevocationPlan{}, false, fmt.Errorf("list non-owner tasks: %w", err)+ return db.AgentRuntime{}, runtimeWorkspaceAccessRevocationPlan{}, false, featureAdmission{}, fmt.Errorf("list non-owner tasks: %w", err)}plan := runtimeWorkspaceAccessRevocationPlan{Agents: agents, Tasks: tasks}if plan.hasDependencies() {- return lockedRuntime, plan, false, nil+ return lockedRuntime, plan, false, featureAdmission{}, nil}}@@ -823,12 +844,12 @@ func (h *Handler) updateRuntimeAccessIfNoDependencies(ctx context.Context, rt dbSharedWith: next.SharedWith,})if err != nil {- return db.AgentRuntime{}, runtimeWorkspaceAccessRevocationPlan{}, false, fmt.Errorf("update runtime visibility: %w", err)+ return db.AgentRuntime{}, runtimeWorkspaceAccessRevocationPlan{}, false, featureAdmission{}, fmt.Errorf("update runtime visibility: %w", err)}if err := tx.Commit(ctx); err != nil {- return db.AgentRuntime{}, runtimeWorkspaceAccessRevocationPlan{}, false, fmt.Errorf("commit transaction: %w", err)+ return db.AgentRuntime{}, runtimeWorkspaceAccessRevocationPlan{}, false, featureAdmission{}, fmt.Errorf("commit transaction: %w", err)}- return updated, runtimeWorkspaceAccessRevocationPlan{}, true, nil+ return updated, runtimeWorkspaceAccessRevocationPlan{}, true, admission, nil}// runtimeWorkspaceAccessRevocationResponse is returned for both the initial@@ -1151,6 +1172,13 @@ func (h *Handler) RevokeRuntimeWorkspaceAccess(w http.ResponseWriter, r *http.Rereturn}+ // Read the paid feature before the runtime row is locked; the addition+ // itself is decided against the locked row.+ var sharing paidFeature+ if len(sharedWithIDs) > 0 {+ sharing = h.paidFeature(r.Context(), rt.WorkspaceID, entitlement.FeatureRuntimeMemberSharing)+ }+tx, err := h.TxStarter.Begin(r.Context())if err != nil {writeError(w, http.StatusInternalServerError, "failed to start transaction")@@ -1193,6 +1221,13 @@ func (h *Handler) RevokeRuntimeWorkspaceAccess(w http.ResponseWriter, r *http.Re})return}+ var admission featureAdmission+ if runtimeMemberSharingAdds(lockedRuntime, next) {+ if admission, ok = sharing.addition(r.Context(), runtimeSharingOpAddMembers); !ok {+ writeFeatureLocked(w, entitlement.FeatureRuntimeMemberSharing)+ return+ }+ }plan, err := lockRuntimeRevocationPlan(r.Context(), qtx, next)if err != nil {@@ -1220,6 +1255,7 @@ func (h *Handler) RevokeRuntimeWorkspaceAccess(w http.ResponseWriter, r *http.RewriteError(w, http.StatusInternalServerError, "failed to commit runtime privacy change")return}+ admission.admitted(r.Context())h.PublishRuntimeTeardown(r.Context(), result, wsID, "member", uuidToString(member.UserID), "update", true)for _, taskID := range readyChats {diff --git a/server/internal/handler/runtime_sharing.go b/server/internal/handler/runtime_sharing.goindex d9e8feddae..d37634eec9 100644--- a/server/internal/handler/runtime_sharing.go+++ b/server/internal/handler/runtime_sharing.go@@ -18,6 +18,42 @@ var errRuntimeManagedByConnection = errors.New("runtime managed by connection")var errInvalidRuntimeShare = errors.New("invalid runtime sharing")+// errRuntimeFeatureLocked rejects an addition to runtime_member_sharing; the+// rejection is already recorded and the caller answers feature_locked.+var errRuntimeFeatureLocked = errors.New("runtime member sharing is not included in the plan")++const runtimeSharingOpAddMembers = "add_members"++// runtimeMemberSharingAdds reports whether moving a runtime's access from+// previous to next adds to the paid feature runtime_member_sharing (MUL-9491):+// next shares the private runtime with someone previous did not. Switching+// from "only me" or public to specific members is an addition; making it+// public, making it "only me", removing people, and re-saving the same list+// are not. Runtime claim and binding checks never consult the feature, so an+// existing list keeps working after a downgrade.+func runtimeMemberSharingAdds(previous, next db.AgentRuntime) bool {+ if next.Visibility != "private" {+ return false+ }+ var had []pgtype.UUID+ if previous.Visibility == "private" {+ had = previous.SharedWith+ }+ for _, id := range next.SharedWith {+ if id != next.OwnerID && !slices.Contains(had, id) {+ return true+ }+ }+ return false+}++// runtimeShareRequestMayAdd reports whether a request names any recipient, the+// only way it can add to runtime_member_sharing. Requests that cannot add skip+// reading the feature.+func runtimeShareRequestMayAdd(req UpdateAgentRuntimeRequest) bool {+ return len(req.sharedWithIDs) > 0+}+func parseRuntimeSharedWith(w http.ResponseWriter, raw []string) ([]pgtype.UUID, bool) {if len(raw) > 1000 {writeError(w, http.StatusBadRequest, "shared_with has too many members")diff --git a/server/internal/handler/runtime_sharing_feature_test.go b/server/internal/handler/runtime_sharing_feature_test.gonew file mode 100644index 0000000000..265f16a55a--- /dev/null+++ b/server/internal/handler/runtime_sharing_feature_test.go@@ -0,0 +1,199 @@+package handler++import (+ "context"+ "net/http"+ "testing"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/internal/entitlement"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func runtimeShare(t *testing.T, runtimeID string) (string, []string) {+ t.Helper()+ rt, err := testHandler.Queries.GetAgentRuntime(context.Background(), mustTestUUID(t, runtimeID))+ if err != nil {+ t.Fatalf("load runtime: %v", err)+ }+ return rt.Visibility, runtimeSharedWithStrings(rt.SharedWith)+}++func wantRuntimeShare(t *testing.T, runtimeID, visibility string, sharedWith ...string) {+ t.Helper()+ gotVisibility, got := runtimeShare(t, runtimeID)+ if gotVisibility != visibility || len(got) != len(sharedWith) {+ t.Fatalf("runtime access = %s %v, want %s %v", gotVisibility, got, visibility, sharedWith)+ }+ for _, id := range sharedWith {+ found := false+ for _, g := range got {+ found = found || g == id+ }+ if !found {+ t.Fatalf("runtime access = %s %v, want %s %v", gotVisibility, got, visibility, sharedWith)+ }+ }+}++// Sharing a private runtime with a member under each action.+func TestRuntimeMemberSharingAddUnderEachAction(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ for _, tc := range featureCases {+ t.Run(tc.name, func(t *testing.T) {+ rtID, ownerID, memberID := runtimeVisibilityFixture(t)+ usePaidFeatureOn(t, testHandler, entitlement.FeatureRuntimeMemberSharing, tc.decision)+ resp := runtimeSharingPatch(t, rtID, ownerID, map[string]any{"shared_with": []string{memberID}})+ if tc.locked {+ wantFeatureLockedFor(t, resp, entitlement.FeatureRuntimeMemberSharing)+ wantRuntimeShare(t, rtID, "private")+ wantAttempts(t, entitlement.FeatureRuntimeMemberSharing, featureAttemptCounts{enforced: 1, lastOperation: "add_members"})+ return+ }+ resp.Want(http.StatusOK)+ wantRuntimeShare(t, rtID, "private", memberID)+ want := featureAttemptCounts{}+ if tc.observed > 0 {+ want = featureAttemptCounts{observed: 1, lastOperation: "add_members"}+ }+ wantAttempts(t, entitlement.FeatureRuntimeMemberSharing, want)+ })+ }+}++// After a downgrade a runtime's member list keeps working; removing people,+// making it public or "only me", and re-saving are allowed; adding someone,+// or going from public back to specific members, is refused.+func TestRuntimeMemberSharingEnforcedKeepsExistingAndAllowsReductions(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ rtID, ownerID, memberID := runtimeVisibilityFixture(t)+ third := createPermissionTestMember(t, "rms-third-"+uuid.NewString()[:8]+"@multica.test")+ runtimeSharingPatch(t, rtID, ownerID, map[string]any{"shared_with": []string{memberID, testUserID}}).Want(http.StatusOK)++ usePaidFeatureOn(t, testHandler, entitlement.FeatureRuntimeMemberSharing, enforced())++ // The shared member can still create agents on it.+ // The revocation below unbinds the agent, so clean it up by owner.+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent WHERE owner_id = $1`, memberID) })+ testutil.Call(t, testHandler.CreateAgent, newRequestAs(memberID, http.MethodPost, "/api/agents", map[string]any{+ "name": "rms shared member " + uuid.NewString()[:8], "runtime_id": rtID,+ })).Want(http.StatusCreated)+ testutil.Call(t, testHandler.CreateAgent, newRequestAs(third, http.MethodPost, "/api/agents", map[string]any{+ "name": "rms outsider " + uuid.NewString()[:8], "runtime_id": rtID,+ })).Want(http.StatusForbidden)++ runtimeSharingPatch(t, rtID, ownerID, map[string]any{"shared_with": []string{testUserID, memberID}}).Want(http.StatusOK)+ wantFeatureLockedFor(t, runtimeSharingPatch(t, rtID, ownerID, map[string]any{"shared_with": []string{memberID, testUserID, third}}), entitlement.FeatureRuntimeMemberSharing)+ wantRuntimeShare(t, rtID, "private", memberID, testUserID)+ // testUserID has no agent on the runtime, so removing them needs no review.+ runtimeSharingPatch(t, rtID, ownerID, map[string]any{"shared_with": []string{memberID}}).Want(http.StatusOK)+ wantRuntimeShare(t, rtID, "private", memberID)+ runtimeSharingPatch(t, rtID, ownerID, map[string]any{"visibility": "public"}).Want(http.StatusOK)+ wantRuntimeShare(t, rtID, "public")+ // Public back to specific members: refused on both entry points.+ wantFeatureLockedFor(t, runtimeSharingPatch(t, rtID, ownerID, map[string]any{"visibility": "private", "shared_with": []string{memberID}}), entitlement.FeatureRuntimeMemberSharing)+ wantFeatureLockedFor(t, runtimePrivacyRequest(t, rtID, ownerID, map[string]any{+ "shared_with": []string{memberID}, "expected_nonowner_agent_ids": []string{}, "expected_task_ids": []string{},+ }), entitlement.FeatureRuntimeMemberSharing)+ wantRuntimeShare(t, rtID, "public")+ // Public to "only me" is a reduction (the member's agent is reviewed first).+ var plan struct {+ Agents []struct {+ ID string `json:"id"`+ } `json:"nonowner_agents"`+ }+ runtimeSharingPatch(t, rtID, ownerID, map[string]any{"visibility": "private"}).Want(http.StatusConflict).JSON(&plan)+ expected := []string{}+ for _, a := range plan.Agents {+ expected = append(expected, a.ID)+ }+ runtimePrivacyRequest(t, rtID, ownerID, map[string]any{+ "expected_nonowner_agent_ids": expected, "expected_task_ids": []string{},+ }).Want(http.StatusOK)+ wantRuntimeShare(t, rtID, "private")++ wantAttempts(t, entitlement.FeatureRuntimeMemberSharing, featureAttemptCounts{enforced: 3, lastOperation: "add_members"})+}++// Only the runtime owner may change sharing; anyone else gets the original+// error before the feature is consulted.+func TestRuntimeMemberSharingPermissionChecksComeFirst(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ rtID, _, memberID := runtimeVisibilityFixture(t)+ usePaidFeatureOn(t, testHandler, entitlement.FeatureRuntimeMemberSharing, enforced())+ // testUserID administers the workspace but does not own the runtime.+ wantPlainForbidden(t, runtimeSharingPatch(t, rtID, testUserID, map[string]any{"shared_with": []string{memberID}}))+ wantPlainForbidden(t, runtimePrivacyRequest(t, rtID, testUserID, map[string]any{+ "shared_with": []string{memberID}, "expected_nonowner_agent_ids": []string{}, "expected_task_ids": []string{},+ }))+ wantNoAttempts(t, entitlement.FeatureRuntimeMemberSharing)+}++func TestRuntimeMemberSharingAddsClassification(t *testing.T) {+ id := func() pgtype.UUID { return pgtype.UUID{Bytes: uuid.New(), Valid: true} }+ owner, a, b := id(), id(), id()+ rt := func(visibility string, shared ...pgtype.UUID) db.AgentRuntime {+ return db.AgentRuntime{OwnerID: owner, Visibility: visibility, SharedWith: shared}+ }+ for _, tc := range []struct {+ name string+ previous, next db.AgentRuntime+ want bool+ }{+ {"only me to members", rt("private"), rt("private", a), true},+ {"public to members", rt("public"), rt("private", a), true},+ {"add", rt("private", a), rt("private", a, b), true},+ {"swap", rt("private", a), rt("private", b), true},+ {"same", rt("private", a, b), rt("private", a, b), false},+ {"remove", rt("private", a, b), rt("private", a), false},+ {"to only me", rt("private", a), rt("private"), false},+ {"to public", rt("private", a), rt("public"), false},+ {"public to only me", rt("public"), rt("private"), false},+ } {+ if got := runtimeMemberSharingAdds(tc.previous, tc.next); got != tc.want {+ t.Errorf("%s: adds = %v, want %v", tc.name, got, tc.want)+ }+ }+}++// The addition is decided against the locked row, not the copy read before+// the transaction: a concurrent save that removed someone cannot be undone by+// a stale request putting them back while the feature is enforced.+func TestRuntimeMemberSharingDecidesOnLockedRow(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ rtID, ownerID, memberID := runtimeVisibilityFixture(t)+ runtimeSharingPatch(t, rtID, ownerID, map[string]any{"shared_with": []string{memberID}}).Want(http.StatusOK)+ stale, err := testHandler.Queries.GetAgentRuntime(context.Background(), mustTestUUID(t, rtID))+ if err != nil {+ t.Fatalf("load runtime: %v", err)+ }+ // Another save removes the member after this request read the runtime.+ runtimeSharingPatch(t, rtID, ownerID, map[string]any{"shared_with": []string{}}).Want(http.StatusOK)++ usePaidFeatureOn(t, testHandler, entitlement.FeatureRuntimeMemberSharing, enforced())+ owner, err := testHandler.Queries.GetMemberByUserAndWorkspace(context.Background(), db.GetMemberByUserAndWorkspaceParams{+ UserID: mustTestUUID(t, ownerID), WorkspaceID: mustTestUUID(t, testWorkspaceID),+ })+ if err != nil {+ t.Fatalf("load owner member: %v", err)+ }+ shared := []string{memberID}+ req := UpdateAgentRuntimeRequest{SharedWith: &shared, sharedWithIDs: []pgtype.UUID{mustTestUUID(t, memberID)}}+ sharing := testHandler.paidFeature(context.Background(), stale.WorkspaceID, entitlement.FeatureRuntimeMemberSharing)+ _, _, _, _, err = testHandler.updateRuntimeAccessIfNoDependencies(context.Background(), stale, owner, req, sharing)+ if err != errRuntimeFeatureLocked {+ t.Fatalf("stale re-add err = %v, want errRuntimeFeatureLocked", err)+ }+ wantRuntimeShare(t, rtID, "private")+}diff --git a/server/internal/handler/team_app_feature.go b/server/internal/handler/team_app_feature.gonew file mode 100644index 0000000000..1d38998aee--- /dev/null+++ b/server/internal/handler/team_app_feature.go@@ -0,0 +1,130 @@+package handler++import (+ "context"+ "log/slog"++ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/internal/connectedapps"+ "github.com/multica-ai/multica/server/internal/entitlement"+ composio "github.com/multica-ai/multica/server/internal/integrations/composio"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// Paid feature team_app_accounts (MUL-9491): team Apps accounts, their use+// by agents, and custom team rules.+//+// Additions: connecting a team account for an app that has none (including+// after a disconnect), giving an agent a team-account app or switching one+// from a personal account, raising an agent's level on a team account, and+// setting a team rule to a value that is neither its current value nor the+// default.+//+// Always allowed: reauthorizing an app's existing team account, disconnecting,+// removing an app from an agent, lowering a level, restoring default rules,+// and everything about personal accounts. The gateway (Decide) never consults+// the feature, so existing team accounts, agent apps and block rules keep+// working after a downgrade.++const (+ teamAppOpConnect = "connect_team_account"+ teamAppOpAgentApp = "add_agent_team_app"+ teamAppOpRaiseLevel = "raise_agent_team_level"+ teamAppOpChangeRules = "change_team_rules"+)++// teamAppHasAccount reports whether the workspace already has a team account+// for slug that is not revoked. Connecting again then reauthorizes it: a+// workspace keeps one team account per app, so the count never grows.+// Multica does not store the external identity, so switching to another+// external account on reauthorization is indistinguishable and allowed.+func (h *Handler) teamAppHasAccount(ctx context.Context, workspaceID pgtype.UUID, slug string) (bool, error) {+ rows, err := h.Queries.ListWorkspaceComposioConnections(ctx, workspaceID)+ if err != nil {+ return false, err+ }+ for _, row := range rows {+ if row.ToolkitSlug == slug {+ return true, nil+ }+ }+ return false, nil+}++// TeamAppConnectGate is the composio.TeamConnectGate for team_app_accounts.+// It runs when a completed handshake is about to write a team account, so a+// connect started before a downgrade, or one that raced another connect,+// cannot add an account the plan no longer includes. A refusal keeps the+// existing connection. An observed connect is recorded only after the write.+func (h *Handler) TeamAppConnectGate(ctx context.Context, workspaceID pgtype.UUID, slug string) (func(context.Context), error) {+ feature := h.paidFeature(ctx, workspaceID, entitlement.FeatureTeamAppAccounts)+ if !feature.active {+ return func(context.Context) {}, nil+ }+ reconnect, err := h.teamAppHasAccount(ctx, workspaceID, slug)+ if err != nil {+ // The restriction is commercial and fails open, like every other+ // entitlement failure.+ slog.Warn("team app connect gate: list team accounts failed; admitting", "error", err)+ return func(context.Context) {}, nil+ }+ if reconnect {+ return func(context.Context) {}, nil+ }+ admission, ok := feature.addition(ctx, teamAppOpConnect)+ if !ok {+ return nil, composio.ErrTeamConnectRefused+ }+ return admission.admitted, nil+}++// agentLevelRank orders agent levels by what they let the agent do. The+// gateway runs confirm_writes as write, so the two rank the same.+func agentLevelRank(level string) int {+ if level == connectedapps.LevelRead {+ return 0+ }+ return 1+}++// agentTeamAppAdds classifies one wanted agent app against the agent's+// current row for the same app. It returns the operation that adds to+// team_app_accounts, or "" when the change does not add: personal apps,+// unchanged team apps, and lowered levels.+func agentTeamAppAdds(prev db.AgentApp, had bool, scope, level string) string {+ if scope != connectedapps.ScopeTeam {+ return ""+ }+ if !had || prev.AccountScope != connectedapps.ScopeTeam {+ return teamAppOpAgentApp+ }+ if agentLevelRank(level) > agentLevelRank(prev.Level) {+ return teamAppOpRaiseLevel+ }+ return ""+}++// teamRulesAdd reports whether a team rules write sets any class to a value+// that is neither its current value (custom or default) nor the default.+// Same-value write-backs and restoring defaults (Allow all actions) are not+// additions.+func teamRulesAdd(slug string, current map[string]string, rules []appRuleInput) bool {+ for _, rule := range rules {+ def := connectedapps.DefaultPolicy(slug, rule.ActionClass)+ now, custom := current[rule.ActionClass]+ if !custom {+ now = def+ }+ if rule.Policy != now && rule.Policy != def {+ return true+ }+ }+ return false+}++// appRuleInput is one rule in a PUT /api/apps/rules body.+type appRuleInput struct {+ ActionClass string `json:"action_class"`+ Policy string `json:"policy"`+}diff --git a/server/internal/handler/team_app_feature_test.go b/server/internal/handler/team_app_feature_test.gonew file mode 100644index 0000000000..555f7f0813--- /dev/null+++ b/server/internal/handler/team_app_feature_test.go@@ -0,0 +1,437 @@+package handler++import (+ "context"+ "errors"+ "fmt"+ "net/http"+ "net/http/httptest"+ "net/url"+ "strings"+ "sync"+ "testing"+++ "github.com/multica-ai/multica/server/internal/connectedapps"+ "github.com/multica-ai/multica/server/internal/entitlement"+ composio "github.com/multica-ai/multica/server/internal/integrations/composio"+ "github.com/multica-ai/multica/server/internal/testutil"+ sdk "github.com/multica-ai/multica/server/pkg/composio"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func clearTeamAccounts(t *testing.T) {+ t.Helper()+ clear := func() {+ testPool.Exec(context.Background(), `DELETE FROM workspace_composio_connection WHERE workspace_id = $1`, testWorkspaceID)+ }+ clear()+ t.Cleanup(clear)+}++func seedTeamAccount(t *testing.T, slug, status string) string {+ t.Helper()+ return dbfx.Insert(t, "workspace_composio_connection", testutil.Cols{+ "workspace_id": testWorkspaceID, "toolkit_slug": slug, "auth_config_id": "ac_" + slug,+ "connected_account_id": fmt.Sprintf("ca_team_%s_%d", slug, testSeq.Add(1)),+ "composio_user_id": composio.TeamComposioUserID(parseUUID(testWorkspaceID)),+ "connected_by": testUserID, "status": status,+ })+}++func (f *appsFixture) connectTeam(t *testing.T, slug string) *testutil.Response {+ t.Helper()+ return testutil.Call(t, f.h.ConnectTeamApp, appsReqAs(t, testUserID, http.MethodPost, "/api/apps/team/connect", map[string]any{"toolkit_slug": slug}))+}++func (f *appsFixture) putTeamRules(t *testing.T, rules map[string]string) *testutil.Response {+ t.Helper()+ body := []map[string]string{}+ for class, policy := range rules {+ body = append(body, map[string]string{"action_class": class, "policy": policy})+ }+ return testutil.Call(t, f.h.UpdateAppRules, appsReqAs(t, testUserID, http.MethodPut, "/api/apps/rules?toolkit_slug=gmail&scope=team", map[string]any{"rules": body}))+}++func (f *appsFixture) putAgentAppsAs(t *testing.T, userID string, apps []map[string]string) *testutil.Response {+ t.Helper()+ req := appsReqAs(t, userID, http.MethodPut, "/api/agents/"+f.agentID+"/apps", map[string]any{"apps": apps})+ return testutil.Call(t, f.h.UpdateAgentApps, withURLParam(req, "id", f.agentID))+}++func agentApps(t *testing.T, agentID string) map[string]string {+ t.Helper()+ rows, err := testHandler.Queries.ListAgentApps(context.Background(), parseUUID(agentID))+ if err != nil {+ t.Fatalf("list agent apps: %v", err)+ }+ out := map[string]string{}+ for _, row := range rows {+ out[row.ToolkitSlug] = row.AccountScope + "/" + row.Level+ }+ return out+}++// Starting to connect a team account for an app that has none, under each+// action. An observed start is not recorded: the callback records it once+// the account is written.+func TestTeamAppAccountsConnectUnderEachAction(t *testing.T) {+ for _, tc := range featureCases {+ t.Run(tc.name, func(t *testing.T) {+ f := newAppsFixture(t)+ clearTeamAccounts(t)+ usePaidFeatureOn(t, f.h, entitlement.FeatureTeamAppAccounts, tc.decision)+ resp := f.connectTeam(t, "notion")+ if tc.locked {+ wantFeatureLockedFor(t, resp, entitlement.FeatureTeamAppAccounts)+ wantAttempts(t, entitlement.FeatureTeamAppAccounts, featureAttemptCounts{enforced: 1, lastOperation: "connect_team_account"})+ return+ }+ resp.Want(http.StatusOK)+ wantNoAttempts(t, entitlement.FeatureTeamAppAccounts)+ })+ }+}++// Reauthorizing an app's existing team account (active or expired) is always+// allowed, so a downgraded workspace can recover an expired account. After a+// disconnect the app has none, and connecting again is an addition.+func TestTeamAppAccountsEnforcedAllowsReauthorization(t *testing.T) {+ f := newAppsFixture(t)+ clearTeamAccounts(t)+ usePaidFeatureOn(t, f.h, entitlement.FeatureTeamAppAccounts, enforced())+ seedTeamAccount(t, "notion", "expired")+ f.connectTeam(t, "notion").Want(http.StatusOK)+ testPool.Exec(context.Background(), `UPDATE workspace_composio_connection SET status = 'revoked' WHERE workspace_id = $1`, testWorkspaceID)+ wantFeatureLockedFor(t, f.connectTeam(t, "notion"), entitlement.FeatureTeamAppAccounts)+ // Members still get the ordinary admin-only error first.+ wantPlainForbidden(t, testutil.Call(t, f.h.ConnectTeamApp, appsReqAs(t, f.member, http.MethodPost, "/api/apps/team/connect", map[string]any{"toolkit_slug": "notion"})))+ wantAttempts(t, entitlement.FeatureTeamAppAccounts, featureAttemptCounts{enforced: 1, lastOperation: "connect_team_account"})+}++// teamConnectSDK completes team handshakes: it remembers the callback URL+// (and so the signed state), reports every account as the workspace's team+// account under the notion auth config, and records upstream revocations.+type teamConnectSDK struct {+ appsFakeSDK+ mu sync.Mutex+ callbackURL string+ revoked []string+}++func (f *teamConnectSDK) CreateLink(_ context.Context, req sdk.CreateLinkRequest) (*sdk.CreateLinkResponse, error) {+ f.mu.Lock()+ f.callbackURL = req.CallbackURL+ f.mu.Unlock()+ return &sdk.CreateLinkResponse{RedirectURL: "https://composio.example/redirect"}, nil+}++func (f *teamConnectSDK) ListConnectedAccounts(_ context.Context, req sdk.ListConnectedAccountsRequest) (*sdk.ListConnectedAccountsResponse, error) {+ id := ""+ if len(req.ConnectedAccountIDs) > 0 {+ id = req.ConnectedAccountIDs[0]+ }+ return &sdk.ListConnectedAccountsResponse{Items: []sdk.ConnectedAccount{{+ ID: id, UserID: composio.TeamComposioUserID(parseUUID(testWorkspaceID)), AuthConfigID: "ac_notion",+ }}}, nil+}++func (f *teamConnectSDK) RevokeConnection(_ context.Context, id string) error {+ f.mu.Lock()+ f.revoked = append(f.revoked, id)+ f.mu.Unlock()+ return nil+}++func (f *teamConnectSDK) state(t *testing.T) string {+ t.Helper()+ f.mu.Lock()+ defer f.mu.Unlock()+ u, err := url.Parse(f.callbackURL)+ if err != nil {+ t.Fatalf("parse callback url: %v", err)+ }+ return u.Query().Get("state")+}++// newTeamConnectService wires a composio service with the paid feature gate+// into h, as the router does.+func newTeamConnectService(t *testing.T, h *Handler) (*composio.Service, *teamConnectSDK) {+ t.Helper()+ fake := &teamConnectSDK{}+ svc, err := composio.NewService(fake, h.Queries, composio.Config{+ StateSecret: []byte("team-connect-test-secret"), CallbackBaseURL: "https://multica.ai", FrontendBaseURL: "https://multica.ai",+ })+ if err != nil {+ t.Fatalf("composio.NewService: %v", err)+ }+ svc.SetTeamConnectGate(h.TeamAppConnectGate)+ return svc, fake+}++func teamAccountRows(t *testing.T) map[string]string {+ t.Helper()+ rows, err := testPool.Query(context.Background(), `SELECT connected_account_id, status FROM workspace_composio_connection WHERE workspace_id = $1 AND toolkit_slug = 'notion'`, testWorkspaceID)+ if err != nil {+ t.Fatalf("list team accounts: %v", err)+ }+ defer rows.Close()+ out := map[string]string{}+ for rows.Next() {+ var id, status string+ if err := rows.Scan(&id, &status); err != nil {+ t.Fatalf("scan: %v", err)+ }+ out[id] = status+ }+ return out+}++// The callback re-checks the feature right before writing a team account: a+// connect started before a downgrade cannot add an account, the refused+// account is revoked upstream and nothing is written, a reauthorization still+// replaces the existing account, and an observed connect is recorded once,+// after the write.+func TestTeamAppAccountsCallbackRechecksBeforeWriting(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ workspaceID := parseUUID(testWorkspaceID)+ h := *testHandler+ svc, fake := newTeamConnectService(t, &h)+ begin := func(t *testing.T) string {+ t.Helper()+ if _, err := svc.BeginTeamConnect(ctx, workspaceID, parseUUID(testUserID), "notion", ""); err != nil {+ t.Fatalf("BeginTeamConnect: %v", err)+ }+ return fake.state(t)+ }++ t.Run("refused", func(t *testing.T) {+ clearTeamAccounts(t)+ state := begin(t)+ usePaidFeatureOn(t, &h, entitlement.FeatureTeamAppAccounts, enforced())+ _, err := svc.CompleteCallback(ctx, state, "success", "ca_refused")+ if !errors.Is(err, composio.ErrTeamConnectRefused) {+ t.Fatalf("CompleteCallback err = %v, want ErrTeamConnectRefused", err)+ }+ if rows := teamAccountRows(t); len(rows) != 0 {+ t.Fatalf("refused connect wrote %v", rows)+ }+ if len(fake.revoked) == 0 || fake.revoked[len(fake.revoked)-1] != "ca_refused" {+ t.Fatalf("refused account not revoked upstream: %v", fake.revoked)+ }+ wantAttempts(t, entitlement.FeatureTeamAppAccounts, featureAttemptCounts{enforced: 1, lastOperation: "connect_team_account"})+ })++ // Over HTTP the refusal reaches the page as a plan refusal, so it can+ // show the upgrade prompt instead of asking for a retry (an older page+ // still sees the ordinary failure fields).+ t.Run("refused over HTTP", func(t *testing.T) {+ clearTeamAccounts(t)+ state := begin(t)+ usePaidFeatureOn(t, &h, entitlement.FeatureTeamAppAccounts, enforced())+ h.Composio = svc+ withComposioMCPAppsFlag(t, &h, true)+ q := url.Values{"state": {state}, "status": {"success"}, "connected_account_id": {"ca_refused_http"}}+ resp := testutil.Call(t, h.ComposioCallback, httptest.NewRequest(http.MethodGet, "/api/integrations/composio/callback?"+q.Encode(), nil)).Want(http.StatusFound)+ loc, err := url.Parse(resp.Header().Get("Location"))+ if err != nil {+ t.Fatalf("parse redirect: %v", err)+ }+ got := loc.Query()+ if got.Get("error") != "composio_connect_failed" || got.Get("reason") != "feature_locked" || got.Get("scope") != "team" {+ t.Fatalf("redirect = %s, want the failure with reason feature_locked", loc)+ }+ if rows := teamAccountRows(t); len(rows) != 0 {+ t.Fatalf("refused connect wrote %v", rows)+ }+ })++ t.Run("reauthorization", func(t *testing.T) {+ clearTeamAccounts(t)+ existing := seedTeamAccount(t, "notion", "expired")+ var existingAccount string+ dbfx.QueryRow(t, `SELECT connected_account_id FROM workspace_composio_connection WHERE id = $1`, existing).Scan(&existingAccount)+ state := begin(t)+ usePaidFeatureOn(t, &h, entitlement.FeatureTeamAppAccounts, enforced())+ if _, err := svc.CompleteCallback(ctx, state, "success", "ca_reauthorized"); err != nil {+ t.Fatalf("CompleteCallback: %v", err)+ }+ rows := teamAccountRows(t)+ if rows["ca_reauthorized"] != "active" || rows[existingAccount] != "revoked" {+ t.Fatalf("team accounts = %v, want the new one active and %s revoked", rows, existingAccount)+ }+ wantNoAttempts(t, entitlement.FeatureTeamAppAccounts)+ })++ t.Run("observed", func(t *testing.T) {+ clearTeamAccounts(t)+ state := begin(t)+ usePaidFeatureOn(t, &h, entitlement.FeatureTeamAppAccounts, observed())+ if _, err := svc.CompleteCallback(ctx, state, "success", "ca_observed"); err != nil {+ t.Fatalf("CompleteCallback: %v", err)+ }+ if rows := teamAccountRows(t); rows["ca_observed"] != "active" {+ t.Fatalf("team accounts = %v", rows)+ }+ wantAttempts(t, entitlement.FeatureTeamAppAccounts, featureAttemptCounts{observed: 1, lastOperation: "connect_team_account"})+ })++ t.Run("self-hosted", func(t *testing.T) {+ clearTeamAccounts(t)+ state := begin(t)+ usePaidFeatureOn(t, &h, entitlement.FeatureTeamAppAccounts, nil)+ if _, err := svc.CompleteCallback(ctx, state, "success", "ca_self_hosted"); err != nil {+ t.Fatalf("CompleteCallback: %v", err)+ }+ wantNoAttempts(t, entitlement.FeatureTeamAppAccounts)+ })+}++// Giving an agent a team-account app under each action.+func TestTeamAppAccountsAgentAppUnderEachAction(t *testing.T) {+ for _, tc := range featureCases {+ t.Run(tc.name, func(t *testing.T) {+ f := newAppsFixture(t)+ usePaidFeatureOn(t, f.h, entitlement.FeatureTeamAppAccounts, tc.decision)+ resp := f.putAgentAppsAs(t, testUserID, []map[string]string{{"toolkit_slug": "gmail", "account_scope": "team", "level": "read"}})+ if tc.locked {+ wantFeatureLockedFor(t, resp, entitlement.FeatureTeamAppAccounts)+ if apps := agentApps(t, f.agentID); len(apps) != 0 {+ t.Fatalf("rejected update wrote %v", apps)+ }+ wantAttempts(t, entitlement.FeatureTeamAppAccounts, featureAttemptCounts{enforced: 1, lastOperation: "add_agent_team_app"})+ return+ }+ resp.Want(http.StatusOK)+ want := featureAttemptCounts{}+ if tc.observed > 0 {+ want = featureAttemptCounts{observed: 1, lastOperation: "add_agent_team_app"}+ }+ wantAttempts(t, entitlement.FeatureTeamAppAccounts, want)+ })+ }+}++// After a downgrade an agent's team-account apps keep working and can be+// lowered or removed; switching a personal app to the team account and+// raising a level are refused. Personal apps are never restricted.+func TestTeamAppAccountsEnforcedAgentApps(t *testing.T) {+ f := newAppsFixture(t)+ put := func(apps ...map[string]string) *testutil.Response {+ t.Helper()+ return f.putAgentAppsAs(t, testUserID, apps)+ }+ app := func(slug, scope, level string) map[string]string {+ return map[string]string{"toolkit_slug": slug, "account_scope": scope, "level": level}+ }+ put(app("gmail", "team", "write"), app("notion", "personal", "read")).Want(http.StatusOK)++ usePaidFeatureOn(t, f.h, entitlement.FeatureTeamAppAccounts, enforced())++ put(app("gmail", "team", "write"), app("notion", "personal", "read")).Want(http.StatusOK)+ put(app("gmail", "team", "read"), app("notion", "personal", "write")).Want(http.StatusOK)+ wantFeatureLockedFor(t, put(app("gmail", "team", "write"), app("notion", "personal", "write")), entitlement.FeatureTeamAppAccounts)+ wantFeatureLockedFor(t, put(app("gmail", "team", "read"), app("notion", "team", "read")), entitlement.FeatureTeamAppAccounts)+ if apps := agentApps(t, f.agentID); apps["gmail"] != "team/read" || apps["notion"] != "personal/write" {+ t.Fatalf("agent apps = %v after refusals", apps)+ }+ put(app("notion", "personal", "write")).Want(http.StatusOK)+ if apps := agentApps(t, f.agentID); len(apps) != 1 || apps["notion"] != "personal/write" {+ t.Fatalf("agent apps = %v after removing the team app", apps)+ }+ // A member still gets the ordinary admin-only error first.+ wantPlainForbidden(t, f.putAgentAppsAs(t, f.member, []map[string]string{app("gmail", "team", "read")}))+ wantAttempts(t, entitlement.FeatureTeamAppAccounts, featureAttemptCounts{enforced: 2, lastOperation: "add_agent_team_app"})+}++// Custom team rules are part of the feature. After a downgrade, existing+// rules keep applying, a same-value write-back and restoring defaults (Allow+// all actions) are allowed, a new custom value is refused, and personal rules+// are never restricted.+func TestTeamAppAccountsEnforcedTeamRules(t *testing.T) {+ f := newAppsFixture(t)+ clearTeamAccounts(t)+ _, _, _, _ = f.executionAccount(t, "team")+ if w := f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "gmail", "account_scope": "team", "level": "write"}}); w.Code != http.StatusOK {+ t.Fatalf("attach team app: %d %s", w.Code, w.Body.String())+ }+ f.putTeamRules(t, map[string]string{"delete": "block"}).Want(http.StatusOK)++ usePaidFeatureOn(t, f.h, entitlement.FeatureTeamAppAccounts, enforced())++ // Existing configuration keeps working: the team account still runs and+ // the block rule still applies.+ token := f.token(t)+ if _, text, isErr := f.gateway(t, token, "apps_run_tool", map[string]any{"tool": "GMAIL_SEND_EMAIL", "arguments": map[string]any{}}); isErr {+ t.Fatalf("team account send under enforce: %s", text)+ }+ if _, text, isErr := f.gateway(t, token, "apps_run_tool", map[string]any{"tool": "GMAIL_DELETE_MESSAGE", "arguments": map[string]any{}}); !isErr || !strings.HasPrefix(text, "blocked") {+ t.Fatalf("existing block rule under enforce = %s", text)+ }++ f.putTeamRules(t, map[string]string{"delete": "block", "send": "allow"}).Want(http.StatusOK)+ wantFeatureLockedFor(t, f.putTeamRules(t, map[string]string{"send": "block"}), entitlement.FeatureTeamAppAccounts)+ wantFeatureLockedFor(t, f.putTeamRules(t, map[string]string{"delete": "confirm"}), entitlement.FeatureTeamAppAccounts)+ allowAll := map[string]string{}+ for _, class := range connectedapps.Classes {+ allowAll[class] = connectedapps.PolicyAllow+ }+ f.putTeamRules(t, allowAll).Want(http.StatusOK)+ testutil.Call(t, f.h.UpdateAppRules, appsReqAs(t, testUserID, http.MethodPut, "/api/apps/rules?toolkit_slug=gmail&scope=personal",+ map[string]any{"rules": []map[string]string{{"action_class": "send", "policy": "block"}}})).Want(http.StatusOK)+ // A member still gets the ordinary admin-only error first.+ wantPlainForbidden(t, testutil.Call(t, f.h.UpdateAppRules, appsReqAs(t, f.member, http.MethodPut, "/api/apps/rules?toolkit_slug=gmail&scope=team",+ map[string]any{"rules": []map[string]string{{"action_class": "send", "policy": "block"}}})))+ wantAttempts(t, entitlement.FeatureTeamAppAccounts, featureAttemptCounts{enforced: 2, lastOperation: "change_team_rules"})+}++func TestTeamAppAccountsClassification(t *testing.T) {+ team := func(level string) db.AgentApp {+ return db.AgentApp{AccountScope: connectedapps.ScopeTeam, Level: level}+ }+ personal := db.AgentApp{AccountScope: connectedapps.ScopePersonal, Level: connectedapps.LevelWrite}+ for _, tc := range []struct {+ name string+ prev db.AgentApp+ had bool+ scope string+ level string+ want string+ }{+ {"new personal", db.AgentApp{}, false, connectedapps.ScopePersonal, connectedapps.LevelWrite, ""},+ {"new team", db.AgentApp{}, false, connectedapps.ScopeTeam, connectedapps.LevelRead, teamAppOpAgentApp},+ {"personal to team", personal, true, connectedapps.ScopeTeam, connectedapps.LevelRead, teamAppOpAgentApp},+ {"team to personal", team(connectedapps.LevelWrite), true, connectedapps.ScopePersonal, connectedapps.LevelWrite, ""},+ {"same", team(connectedapps.LevelWrite), true, connectedapps.ScopeTeam, connectedapps.LevelWrite, ""},+ {"lower", team(connectedapps.LevelWrite), true, connectedapps.ScopeTeam, connectedapps.LevelRead, ""},+ {"raise", team(connectedapps.LevelRead), true, connectedapps.ScopeTeam, connectedapps.LevelWrite, teamAppOpRaiseLevel},+ {"raise to confirm_writes", team(connectedapps.LevelRead), true, connectedapps.ScopeTeam, connectedapps.LevelConfirmWrites, teamAppOpRaiseLevel},+ {"confirm_writes to write runs the same", team(connectedapps.LevelConfirmWrites), true, connectedapps.ScopeTeam, connectedapps.LevelWrite, ""},+ } {+ if got := agentTeamAppAdds(tc.prev, tc.had, tc.scope, tc.level); got != tc.want {+ t.Errorf("%s: op = %q, want %q", tc.name, got, tc.want)+ }+ }++ rule := func(class, policy string) appRuleInput { return appRuleInput{ActionClass: class, Policy: policy} }+ for _, tc := range []struct {+ name string+ current map[string]string+ rules []appRuleInput+ want bool+ }{+ {"default write-back", nil, []appRuleInput{rule("send", "allow")}, false},+ {"new custom", nil, []appRuleInput{rule("send", "block")}, true},+ {"same custom", map[string]string{"send": "block"}, []appRuleInput{rule("send", "block")}, false},+ {"restore default", map[string]string{"send": "block"}, []appRuleInput{rule("send", "allow")}, false},+ {"other custom value", map[string]string{"send": "block"}, []appRuleInput{rule("send", "confirm")}, true},+ } {+ if got := teamRulesAdd("gmail", tc.current, tc.rules); got != tc.want {+ t.Errorf("%s: adds = %v, want %v", tc.name, got, tc.want)+ }+ }+}+diff --git a/server/internal/integrations/composio/service.go b/server/internal/integrations/composio/service.goindex e59dbe689b..25382d36b3 100644--- a/server/internal/integrations/composio/service.go+++ b/server/internal/integrations/composio/service.go@@ -140,6 +140,9 @@ type Service struct {// connects for the same new app do not register two configs.authCreateMu sync.Mutextools toolCache+ // teamConnectGate decides whether a completed team handshake may write+ // its account; see SetTeamConnectGate.+ teamConnectGate TeamConnectGate}// NewService validates its inputs and returns a ready Service. It errors when a@@ -482,6 +485,21 @@ func (s *Service) CreateMCPSession(ctx context.Context, userID pgtype.UUID) (*MC// route and 404'd after the legacy rewrite. When FrontendBaseURL is unset it// returns a site-relative path.func (s *Service) CallbackRedirect(result CallbackResult, success bool) string {+ return s.callbackRedirect(result, success, "")+}++// CallbackFeatureLockedReason marks a failed connect the workspace's plan+// refused (ErrTeamConnectRefused), so the page can show the upgrade prompt+// instead of asking the user to retry. Clients that do not know the reason+// still see the ordinary failure.+const CallbackFeatureLockedReason = "feature_locked"++// CallbackRedirectFailure is the failure redirect carrying a reason.+func (s *Service) CallbackRedirectFailure(result CallbackResult, reason string) string {+ return s.callbackRedirect(result, false, reason)+}++func (s *Service) callbackRedirect(result CallbackResult, success bool, reason string) string {if result.ReturnTo != "" && SafeReturnPath(result.ReturnTo) {path, rawQuery, _ := strings.Cut(result.ReturnTo, "?")q, err := url.ParseQuery(rawQuery)@@ -492,6 +510,9 @@ func (s *Service) CallbackRedirect(result CallbackResult, success bool) string {q.Set("app_connected", result.ToolkitSlug)} else {q.Set("app_connect_error", result.ToolkitSlug)+ if reason != "" {+ q.Set("app_connect_error_reason", reason)+ }}return s.frontendURL + path + "?" + q.Encode()}@@ -501,6 +522,9 @@ func (s *Service) CallbackRedirect(result CallbackResult, success bool) string {q.Set("connected", result.ToolkitSlug)} else {q.Set("error", "composio_connect_failed")+ if reason != "" {+ q.Set("reason", reason)+ }}if result.Team() {q.Set("scope", "team")diff --git a/server/internal/integrations/composio/service_test.go b/server/internal/integrations/composio/service_test.goindex 50966bf2d9..9fa47cb22c 100644--- a/server/internal/integrations/composio/service_test.go+++ b/server/internal/integrations/composio/service_test.go@@ -707,6 +707,13 @@ func TestCallbackRedirect(t *testing.T) {}if got := svc.CallbackRedirect(CallbackResult{ToolkitSlug: "notion", WorkspaceID: "w"}, true); got != "https://multica.ai/settings?connected=notion&scope=team&tab=apps" {t.Errorf("team redirect = %q", got)+ } // A plan refusal keeps the ordinary failure fields, so older pages still+ // report a failure, and adds the reason for pages that show the upgrade.+ if got := svc.CallbackRedirectFailure(CallbackResult{ToolkitSlug: "notion", WorkspaceID: "w"}, CallbackFeatureLockedReason); got != "https://multica.ai/settings?error=composio_connect_failed&reason=feature_locked&scope=team&tab=apps" {+ t.Errorf("refused team redirect = %q", got)+ }+ if got := svc.CallbackRedirectFailure(CallbackResult{ToolkitSlug: "notion", ReturnTo: "/acme/issues/MUL-1"}, CallbackFeatureLockedReason); got != "https://multica.ai/acme/issues/MUL-1?app_connect_error=notion&app_connect_error_reason=feature_locked" {+ t.Errorf("refused return redirect = %q", got)}}diff --git a/server/internal/integrations/composio/team.go b/server/internal/integrations/composio/team.goindex 56fa50faa3..97fdfe511f 100644--- a/server/internal/integrations/composio/team.go+++ b/server/internal/integrations/composio/team.go@@ -15,6 +15,19 @@ import (db "github.com/multica-ai/multica/server/pkg/db/generated")+// ErrTeamConnectRefused is returned by a TeamConnectGate, and then by+// CompleteCallback, when the workspace may not add the team account.+var ErrTeamConnectRefused = errors.New("composio: team account not included in the workspace's plan")++// TeamConnectGate decides, when a completed handshake is about to write a team+// account, whether the workspace may add it. It returns ErrTeamConnectRefused+// to refuse, or admitted, which runs once the account is written. The handler+// supplies it; nil admits every account, as on a self-hosted deployment.+type TeamConnectGate func(ctx context.Context, workspaceID pgtype.UUID, toolkitSlug string) (admitted func(context.Context), err error)++// SetTeamConnectGate installs the gate. Call it before serving requests.+func (s *Service) SetTeamConnectGate(gate TeamConnectGate) { s.teamConnectGate = gate }+// ErrTeamAccountsUnavailable is returned when the configured SDK or store// cannot serve team accounts or tool execution (test fakes that predate them).var ErrTeamAccountsUnavailable = errors.New("composio: team accounts unavailable")@@ -136,6 +149,19 @@ func (s *Service) completeTeamCallback(ctx context.Context, claims stateClaims,if err := s.verifyAccountOwnership(ctx, connectedAccountID, claims.UserID, claims.AuthConfigID); err != nil {return err}+ admitted := func(context.Context) {}+ if s.teamConnectGate != nil {+ gateAdmitted, err := s.teamConnectGate(ctx, workspaceID, claims.ToolkitSlug)+ if err != nil {+ // Keep the existing connection and drop the account Composio just+ // created, so it holds no grant Multica does not track.+ if errors.Is(err, ErrTeamConnectRefused) {+ s.revokeUpstream(ctx, connectedAccountID)+ }+ return err+ }+ admitted = gateAdmitted+ }row, err := store.UpsertWorkspaceComposioConnection(ctx, db.UpsertWorkspaceComposioConnectionParams{WorkspaceID: workspaceID,ToolkitSlug: claims.ToolkitSlug,@@ -158,6 +184,7 @@ func (s *Service) completeTeamCallback(ctx context.Context, claims stateClaims,for _, old := range replaced {s.revokeUpstream(ctx, old.ConnectedAccountID)}+ admitted(ctx)return nil}