mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-20 02:46:54 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4b62c31f29 | ||
|
|
2208d4e0e0 | ||
|
|
df7f4c3c2d | ||
|
|
12323e1416 | ||
|
|
2edc5e1071 | ||
|
|
2162ed9ebe | ||
|
|
6acebb73ec | ||
|
|
7a1d6c0ab5 | ||
|
|
d16e31c0e5 | ||
|
|
d9a8b6a191 | ||
|
|
5ec4cd7fcd | ||
|
|
a7925e3c79 | ||
|
|
472b420620 | ||
|
|
8f55ba1d37 | ||
|
|
7b1428bf51 | ||
|
|
d5b3b1868e | ||
|
|
49f3fc0be5 | ||
|
|
59e641ccb3 | ||
|
|
1d9268b224 | ||
|
|
470a4bd6f7 | ||
|
|
8801d59b2e | ||
|
|
6a20e06982 | ||
|
|
b17abce2c2 | ||
|
|
f67e334016 | ||
|
|
c1de66520e | ||
|
|
37e086d822 | ||
|
|
d21f8ca8de | ||
|
|
6af4e7c2ec | ||
|
|
1f2bdc8c9e | ||
|
|
4c0fd29b7f | ||
|
|
ffef67be8f | ||
|
|
4d100bf542 | ||
|
|
8a75d015a1 | ||
|
|
f806272c06 | ||
|
|
4935eeff28 | ||
|
|
eed0264b9c | ||
|
|
dd82daf65c | ||
|
|
55d9596835 | ||
|
|
cb1c1c502b | ||
|
|
6d4f62d6f6 | ||
|
|
43808216e6 | ||
|
|
f66bb7af73 | ||
|
|
ae86d56a7d | ||
|
|
1cee103b1c | ||
|
|
3c3b6880e4 | ||
|
|
0b84402c83 | ||
|
|
61a61abc7c | ||
|
|
fc878775c2 | ||
|
|
7acf736300 | ||
|
|
9d50301a43 | ||
|
|
7f185ca23c | ||
|
|
94582c9001 | ||
|
|
41b73feeab | ||
|
|
96493a5493 | ||
|
|
93c593545d | ||
|
|
11758c23c0 | ||
|
|
1cd94a77c6 | ||
|
|
5ad3fdbf69 | ||
|
|
851ae49c84 | ||
|
|
82aee9a291 | ||
|
|
1b5cbf936a | ||
|
|
1daeaf51ef | ||
|
|
49ef48a74a | ||
|
|
a680fccb12 | ||
|
|
e67552d8bd | ||
|
|
8080acfb2e | ||
|
|
dbd30a815f | ||
|
|
442568de00 | ||
|
|
d15fc5c6be | ||
|
|
aa6d5ed626 |
@@ -22,9 +22,9 @@ jobs:
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v1
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: latest
|
||||
bun-version: 1.3.14
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install
|
||||
@@ -76,9 +76,9 @@ jobs:
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v1
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: latest
|
||||
bun-version: 1.3.14
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install
|
||||
@@ -118,9 +118,9 @@ jobs:
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v1
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: latest
|
||||
bun-version: 1.3.14
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install
|
||||
@@ -152,9 +152,9 @@ jobs:
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v1
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: latest
|
||||
bun-version: 1.3.14
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install
|
||||
|
||||
@@ -36,7 +36,7 @@ jobs:
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: latest
|
||||
bun-version: 1.3.14
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
|
||||
@@ -54,5 +54,6 @@ jobs:
|
||||
platforms: linux/amd64,linux/arm64
|
||||
context: .
|
||||
push: true
|
||||
provenance: false
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
|
||||
@@ -11,6 +11,7 @@ data/
|
||||
*.db
|
||||
*.diff
|
||||
*.orig
|
||||
code_quality.md
|
||||
.agents
|
||||
|
||||
# Playwright
|
||||
|
||||
+8
-2
@@ -1,6 +1,6 @@
|
||||
#syntax=docker/dockerfile:1.7-labs
|
||||
# Stage 1: Builder
|
||||
FROM oven/bun:1 AS builder
|
||||
FROM oven/bun:1.3.14 AS builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
@@ -8,6 +8,7 @@ WORKDIR /app
|
||||
COPY package.json bun.lock ./
|
||||
COPY --parents packages/*/package.json ./
|
||||
COPY --parents apps/*/package.json ./
|
||||
COPY patches/ ./patches/
|
||||
|
||||
# Install dependencies (including devDependencies for build tools)
|
||||
RUN bun install --frozen-lockfile
|
||||
@@ -24,7 +25,7 @@ RUN bun run build.ts
|
||||
RUN bun run scripts/extract-runtime-deps.ts
|
||||
|
||||
# Stage 2: Runner
|
||||
FROM oven/bun:1 AS runner
|
||||
FROM oven/bun:1.3.14 AS runner
|
||||
|
||||
# Install ffmpeg/ffprobe
|
||||
COPY --from=mwader/static-ffmpeg:8.1 /ffmpeg /usr/local/bin/
|
||||
@@ -79,6 +80,11 @@ USER root
|
||||
COPY scripts/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
|
||||
RUN chmod +x /usr/local/bin/docker-entrypoint.sh
|
||||
|
||||
# Expose "bun index.js" as "shumai" CLI command (and alias "shuami")
|
||||
RUN printf '#!/bin/sh\nexec bun /app/index.js "$@"\n' > /usr/local/bin/shumai \
|
||||
&& chmod +x /usr/local/bin/shumai \
|
||||
&& ln -s /usr/local/bin/shumai /usr/local/bin/shuami
|
||||
|
||||
ENTRYPOINT ["docker-entrypoint.sh"]
|
||||
|
||||
# Default command: run migrations and start API server
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a target="_blank" href="https://shumai.one/">Website</a> | <a target="_blank" href="https://docs.shumai.one/introduction">Docs</a> | <a target="_blank" href="https://staging.shumai.one">Demo</a> | <a target="_blank" href="https://discord.gg/sUzhujK6DD">Discord</a> | <a target="_blank" href="README_CN.md">中文</a>
|
||||
<a target="_blank" href="https://shumai.one/">Website</a> | <a target="_blank" href="https://docs.shumai.one/getting-started/overview">Docs</a> | <a target="_blank" href="https://staging.shumai.one">Demo</a> | <a target="_blank" href="https://discord.gg/sUzhujK6DD">Discord</a> | <a target="_blank" href="README_CN.md">中文</a>
|
||||
</p>
|
||||
|
||||

|
||||
@@ -26,15 +26,18 @@ Shumai is an open-source Frame.io alternative built for creative teams to collab
|
||||
* **Custom Asset Metadata**: Define dynamic metadata fields tailored to your production pipeline.
|
||||
* **Share Link Watermarking**: Protect shared media with customizable text and image watermarks, and save watermark as reusable templates.
|
||||
* **Wide File Format Support**: Preview common creative file formats, including images (with PSD support), videos, audio, and documents, while allowing any file type to be uploaded and stored.
|
||||
* **Office & Document PDF Proxying via Gotenberg**: Convert Word, PowerPoint, Excel, Markdown, HTML, and CSV documents to high-quality PDF proxies for in-browser previewing using [Gotenberg](https://docs.shumai.one/using-shumai/gotenberg).
|
||||
|
||||
But Shumai goes beyond being a Frame.io alternative. With modern models like GPT-Image-2 and Seedance 2.5, AI can already handle a surprising amount of creative work. That means you can create or update videos and images from a simple prompt without having to jump back into Photoshop, Premiere or Houdini. That is why Shumai includes a powerful agent system:
|
||||
|
||||
* **Agent as a Team Member**: Mention a context-aware AI agent with `@mentions` directly in asset comments, just like a real teammate.
|
||||
* **Agent as a One-to-One Assistant**: Chat privately with the agent and ask it to help with tasks.
|
||||
* **Custom Skills & Tools**: Extend the agent by registering custom scripts, tools, and automation skills.
|
||||
* **Model Context Protocol (MCP)**: Connect agents to external tools and APIs through remote MCP servers, with OAuth authentication and per-agent MCP access.
|
||||
* **Isolated Sandbox Execution**: Run agent-submitted scripts safely in a sandboxed environment.
|
||||
* **AI Metadata Autofill**: Automatically fill in custom metadata for new assets.
|
||||
* **Semantic Search**: Find assets by visual or conceptual meaning using vector embeddings (Gemini Embedding 2).
|
||||
* **Resource Quotas**: Set usage limits on AI tokens, costs, and tool execution per member, role, or team-wide, with real-time tracking.
|
||||
|
||||
Here is a short demo video showing what the Shumai agent can do:
|
||||
|
||||
@@ -42,6 +45,12 @@ Here is a short demo video showing what the Shumai agent can do:
|
||||
|
||||
https://github.com/user-attachments/assets/1186067a-72c0-41b9-836f-987438f2332a
|
||||
|
||||
Shumai also brings project management into the creative workflow. A built-in Kanban board helps teams organize tasks, track progress, and collaborate in one place.
|
||||
|
||||
The ultimate goal is an **agentic Kanban**, where agents and team members can work together on tasks. This is still a **work in progress**: you can already create tasks for AI agents, but agents cannot act on those tasks yet.
|
||||
|
||||
<img width="2880" height="2160" alt="localhost_3000_teams_01M0HQR3EEBS0B46K4FK39X2C8_kanban(1080p-2) (1)" src="https://github.com/user-attachments/assets/cd0648d0-c69a-4398-958b-8d15a33378b0" />
|
||||
|
||||
|
||||
|
||||
> [!NOTE]
|
||||
@@ -244,11 +253,14 @@ BETTER_AUTH_SECRET=ySxs7DxzHDZBbeeHNPEwBuspYwipBqz5Gk5XdBjNhWw=
|
||||
STORAGE_BACKEND=local
|
||||
SHUMAI_SERVER_PORT=3000
|
||||
AWS_ENDPOINT_URL_S3=http://localhost:3000
|
||||
# Optional: base URL for MCP OAuth redirects (defaults to BETTER_AUTH_URL)
|
||||
MCP_OAUTH_REDIRECT_BASE_URL=http://localhost:3000
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> `SHUMAI_SERVER_PORT` sets the port the server starts on, while `AWS_ENDPOINT_URL_S3` is used by the browser to build file upload URLs.
|
||||
> If deploying on a remote server (e.g. `http://123.456.7.8`) with a mapped port (e.g. `12345:3000` in docker-compose), set `AWS_ENDPOINT_URL_S3` to `http://123.456.7.8:12345`.
|
||||
> `MCP_OAUTH_REDIRECT_BASE_URL` is only needed when MCP servers use OAuth: the authorization redirect URI defaults to `{BETTER_AUTH_URL}/api/mcp/oauth/callback`; set it to an externally reachable URL if the app is served behind a proxy.
|
||||
|
||||
#### Step 6: Run Shumai
|
||||
|
||||
|
||||
+11
-1
@@ -9,7 +9,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a target="_blank" href="https://shumai.one/">官方网站</a> | <a target="_blank" href="https://docs.shumai.one/introduction">文档</a> | <a target="_blank" href="https://staging.shumai.one">在线演示</a> | <a target="_blank" href="README.md">English</a>
|
||||
<a target="_blank" href="https://shumai.one/">官方网站</a> | <a target="_blank" href="https://docs.shumai.one/getting-started/overview">文档</a> | <a target="_blank" href="https://staging.shumai.one">在线演示</a> | <a target="_blank" href="README.md">English</a>
|
||||
</p>
|
||||
</p>
|
||||
|
||||
@@ -27,20 +27,30 @@ Shumai 是一个开源的 Frame.io 替代方案,专为创意团队打造,让
|
||||
* **自定义素材元数据**:可以按你的制作流程,自由定义动态元数据字段。
|
||||
* **分享链接水印**:通过可自定义的文字和图片水印保护共享媒体,并将水印配置保存为模板以便重复使用。
|
||||
* **丰富的文件格式支持**:支持预览常见创意文件格式,包括图片(支持 PSD)、视频、音频和文档,同时可上传和存储任意类型的文件。
|
||||
* **基于 Gotenberg 的文档 PDF 转码代理**:通过集成 [Gotenberg](https://docs.shumai.one/using-shumai/gotenberg) 支持将 Word、PowerPoint、Excel、Markdown、HTML 和 CSV 文档高质量转换为 PDF 代理文件进行在线预览。
|
||||
|
||||
但 Shumai 不仅仅只满足于 Frame.io 的开源替代。随着 GPT-Image-2、Seedance 2.5 这类强大模型的问世,AI已经生成产品级的图片/视频。很多时候,你只要给一句提示词,就能直接生成或修改图片和视频,而不用再打开 Photoshop、Premiere 或者 Houdini。也正因为这样,Shumai 才把 AI Agent 做成了核心能力:
|
||||
|
||||
* **Agent 就像团队成员**:你可以在素材评论区里直接用 `@` 提到 AI Agent,像拉一个真实同事进来一起看稿一样。
|
||||
* **Agent 也能当你的私聊助手**:你可以单独和它聊天,让它帮你查东西、做任务。
|
||||
* **自定义技能和工具**:你可以给 Agent 接上自己的脚本、工具和自动化能力。
|
||||
* **Model Context Protocol (MCP) 支持**:通过远程 MCP 服务端为 Agent 接入外部工具与 API,支持 OAuth 鉴权与按 Agent 独立分配访问权限。
|
||||
* **沙箱隔离执行**:Agent 生成的脚本会在隔离环境里运行,更安全。
|
||||
* **AI 自动补全元数据**:新素材上传后,系统可以自动帮你补一些元数据。
|
||||
* **语义搜索**:支持按画面内容或语义找素材,底层用的是向量 embedding(Gemini Embedding 2)。
|
||||
* **资源配额**:支持按成员、角色或全团队对 AI Token、成本和工具调用设置使用上限与实时用量监控。
|
||||
|
||||
下面是一个简短的 demo 视频,展示了 Shumai Agent 能做什么:
|
||||
|
||||
https://github.com/user-attachments/assets/1186067a-72c0-41b9-836f-987438f2332a
|
||||
|
||||
Shumai 也将项目管理融入了创意工作流程。 内置的看板可以帮助团队整理任务以及跟踪进度。
|
||||
|
||||
最终目标是打造一个 Agentic看板,让 Agent 和团队成员能够围绕同一个目标协同工作。目前这一功能仍在开发中: 你已经可以在看板中为 Agent 创建任务,但 Agent 目前还无法自动执行这些任务。
|
||||
|
||||
<img width="2880" height="2160" alt="localhost_3000_teams_01M0HQR3EEBS0B46K4FK39X2C8_kanban(1080p-2) (1)" src="https://github.com/user-attachments/assets/29ff1db1-2d65-4e3c-b467-754b777b406f" />
|
||||
|
||||
|
||||
> [!NOTE]
|
||||
> **媒体处理与存储机制:** 上传媒体文件后,Shumai 始终会保留并存储原始文件。请注意,系统中显示的文件大小为原始文件的大小,不包含转码后生成的代理文件大小。无论图片还是视频,都会额外生成一张 300p 的 WebP 封面图,作为文件列表中的预览图。此外:
|
||||
>
|
||||
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
# Security Policy
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
Please report security vulnerabilities **privately**. Do not open a public issue,
|
||||
pull request or Discord message for a suspected vulnerability, as that discloses it
|
||||
to everyone before a fix exists.
|
||||
|
||||
Use **[GitHub private vulnerability reporting](https://github.com/shumaiOne/shumai/security/advisories/new)**
|
||||
(the "Report a vulnerability" button on the Security tab). If that is unavailable,
|
||||
contact the maintainer directly rather than in a public channel.
|
||||
|
||||
Please include:
|
||||
|
||||
- What the issue is, and the impact you believe it has
|
||||
- The version or commit you tested (`git rev-parse HEAD`, or the image digest)
|
||||
- Steps to reproduce, ideally minimal
|
||||
- Your deployment shape: storage backend, whether the agent feature is enabled,
|
||||
and whether the instance is internet-reachable
|
||||
|
||||
## Supported Versions
|
||||
|
||||
Shumai is pre-1.0 and moves quickly. Security fixes are made against the **latest
|
||||
release**. Users are encouraged to track releases rather than pin indefinitely.
|
||||
|
||||
## Scope
|
||||
|
||||
**In scope** — the application, its API, the shipped Docker images, and the
|
||||
deployment manifests under `docker-compose/`.
|
||||
|
||||
Deployment manifests are explicitly in scope. A default that is unsafe when
|
||||
followed as documented is a real finding, because the documented quickstart is what
|
||||
most operators actually run.
|
||||
|
||||
**Out of scope**
|
||||
|
||||
- Vulnerabilities in third-party dependencies, unless Shumai's use of them is what
|
||||
creates the exposure. Report those upstream.
|
||||
- Findings that require an already-compromised host or database.
|
||||
- Configurations that deviate from the documented deployment.
|
||||
|
||||
## Operator guidance
|
||||
|
||||
Shumai is self-hosted, so several controls belong to the operator rather than to the
|
||||
project:
|
||||
|
||||
- **Set `BETTER_AUTH_SECRET` per deployment.** It signs sessions and, in local
|
||||
storage mode, upload URLs. Never reuse a value from documentation or an example.
|
||||
- **Do not expose the instance to the public internet without a reverse proxy**
|
||||
terminating TLS and applying your own access policy.
|
||||
- **Do not publish the database port.** Set a real database password.
|
||||
- **Treat the agent feature as a code-execution surface.** If you enable it, run it
|
||||
where a compromise is survivable, and review the sandbox network policy.
|
||||
|
||||
## Disclosure
|
||||
|
||||
Please allow a reasonable period for a fix before public disclosure. The maintainer
|
||||
will acknowledge reports and keep reporters informed of progress.
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/agent-app",
|
||||
"version": "0.3.4",
|
||||
"version": "0.4.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/cli",
|
||||
"version": "0.3.4",
|
||||
"version": "0.4.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/transcode-app",
|
||||
"version": "0.3.4",
|
||||
"version": "0.4.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -56,6 +56,8 @@ apps/web/e2e/
|
||||
|---|---|
|
||||
| Sign up as the first user and become the team owner | `tests/auth/signup.spec.ts` |
|
||||
| Log in with existing credentials | `tests/auth/login.spec.ts` |
|
||||
| Show error when accessing reset-password page without token | `tests/auth/reset-password.spec.ts` |
|
||||
| Reset password with valid token and allow logging in with new password | `tests/auth/reset-password.spec.ts` |
|
||||
|
||||
### team
|
||||
| Test | File |
|
||||
@@ -63,12 +65,13 @@ apps/web/e2e/
|
||||
| Owner invites a member via invite link and the invitee joins | `tests/team/invite-member.spec.ts` |
|
||||
| Owner removes a member via the members dialog; the membership is deleted from the DB | `tests/team/remove-member.spec.ts` |
|
||||
| Owner changes a team member role in the members dialog and permissions update | `tests/team/change-member-role.spec.ts` |
|
||||
| Owner manages resource quotas in settings and resets usage from the dashboard | `tests/team/quotas-settings.spec.ts` |
|
||||
|
||||
### project
|
||||
| Test | File |
|
||||
|---|---|
|
||||
| Owner creates a project with a cover image | `tests/project/create-project.spec.ts` |
|
||||
| Owner uploads a file via the "Upload File" context menu action | `tests/project/upload-file.spec.ts` |
|
||||
| Owner uploads a file or an unsupported file via the "Upload File" context menu action | `tests/project/upload-file.spec.ts` |
|
||||
| Owner deletes a file, finds it in recently deleted, and restores it | `tests/project/delete-restore.spec.ts` |
|
||||
| Owner creates a share link from a file context menu and lands on the share page | `tests/project/create-share-link.spec.ts` |
|
||||
| Owner protects a share with a password; guests must enter it to view | `tests/project/share-password.spec.ts` |
|
||||
@@ -80,12 +83,17 @@ apps/web/e2e/
|
||||
| Owner drags a file into a folder and a folder into another folder | `tests/project/move-folder-file.spec.ts` |
|
||||
| Owner drags a file onto a file to create a version stack | `tests/project/version-stack-create.spec.ts` |
|
||||
| Owner drags a file onto a version stack to add a new version | `tests/project/version-stack-add-version.spec.ts` |
|
||||
| Owner manages version stack: removes version from 3-version stack | `tests/project/version-stack-manage.spec.ts` |
|
||||
| Owner removes version from 2-version stack which dissolves into standalone files | `tests/project/version-stack-manage.spec.ts` |
|
||||
| Dissolving a shared version stack renders the remaining standalone file name on the share page | `tests/project/version-stack-manage.spec.ts` |
|
||||
| Moving a shared file into a shared version stack leaves only 1 stack card on the share page | `tests/project/version-stack-manage.spec.ts` |
|
||||
| Owner searches the file list by an English name keyword | `tests/project/search-file-list.spec.ts` |
|
||||
| Owner searches the file list by Chinese, Japanese, and Korean name keywords | `tests/project/search-file-list.spec.ts` |
|
||||
| Owner searches the file list with a keyword and a filter condition | `tests/project/search-file-list.spec.ts` |
|
||||
| Owner saves a search result as a collection | `tests/project/save-search-collection.spec.ts` |
|
||||
| Image share with watermark + download disabled: no download buttons on public list/detail pages, watermarked proxy served, download-url rejected | `tests/project/share-watermark-no-download.spec.ts` |
|
||||
| Video share with watermark + download disabled: no download buttons on public list/detail pages, watermarked proxy served, download-url rejected | `tests/project/share-watermark-no-download.spec.ts` |
|
||||
| Owner views a file and it appears in recents | `tests/project/recents.spec.ts` |
|
||||
|
||||
### file
|
||||
| Test | File |
|
||||
|
||||
+16
-11
@@ -21,19 +21,23 @@ const currentDir = path.dirname(fileURLToPath(import.meta.url))
|
||||
const envPath = path.resolve(currentDir, '.env.e2e')
|
||||
const fixturesDir = path.resolve(currentDir, '../../../packages/e2e/fixtures')
|
||||
|
||||
// Load E2E environment variables if present
|
||||
if (fs.existsSync(envPath)) {
|
||||
const content = fs.readFileSync(envPath, 'utf8')
|
||||
content.split('\n').forEach((line) => {
|
||||
const parts = line.split('=')
|
||||
if (parts.length >= 2) {
|
||||
const key = parts[0].trim()
|
||||
const value = parts.slice(1).join('=').trim()
|
||||
process.env[key] = value
|
||||
}
|
||||
})
|
||||
function loadEnv() {
|
||||
if (fs.existsSync(envPath)) {
|
||||
const content = fs.readFileSync(envPath, 'utf8')
|
||||
content.split('\n').forEach((line) => {
|
||||
const parts = line.split('=')
|
||||
if (parts.length >= 2) {
|
||||
const key = parts[0].trim()
|
||||
const value = parts.slice(1).join('=').trim()
|
||||
process.env[key] = value
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Load E2E environment variables if present
|
||||
loadEnv()
|
||||
|
||||
export interface OwnerFixture {
|
||||
/** Page opened in a browser context logged in as the team owner. */
|
||||
page: Page
|
||||
@@ -104,6 +108,7 @@ export const test = base.extend<{
|
||||
prisma: [
|
||||
// eslint-disable-next-line no-empty-pattern
|
||||
async ({}, use) => {
|
||||
loadEnv()
|
||||
const connectionString = process.env.DATABASE_URL
|
||||
const pool = new Pool({ connectionString })
|
||||
const adapter = new PrismaPg(pool)
|
||||
|
||||
@@ -7,15 +7,16 @@ interface CreateShareResponse {
|
||||
}
|
||||
|
||||
/**
|
||||
* Locates a file/folder card by its name. File names are rendered as
|
||||
* `EditableText` inputs (not text nodes), so `getByText` does not match them.
|
||||
* The returned locator points at the card wrapper div (right-clickable to open
|
||||
* the card context menu).
|
||||
* Locates a file/folder card by its name. Matches both read-only text nodes
|
||||
* and active EditableText inputs. The returned locator points at the card
|
||||
* wrapper div (right-clickable to open the card context menu).
|
||||
*/
|
||||
export function fileCard(page: Page, name: string): Locator {
|
||||
return page
|
||||
.locator('div.group')
|
||||
.filter({ has: page.locator(`input[value="${name}"]`) })
|
||||
.filter({
|
||||
has: page.locator(`input[value="${name}"]`).or(page.getByText(name, { exact: true })),
|
||||
})
|
||||
.first()
|
||||
}
|
||||
|
||||
|
||||
@@ -32,4 +32,7 @@ async function start() {
|
||||
await import('../src/index.ts')
|
||||
}
|
||||
|
||||
start().catch(console.error)
|
||||
start().catch((err) => {
|
||||
console.error('Failed to start E2E server:', err)
|
||||
process.exit(1)
|
||||
})
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { expect, test } from '../../fixtures'
|
||||
import { apiSignup, E2E_PASSWORD, uniqueEmail } from '../../helpers/auth'
|
||||
import { loginViaUi } from '../../helpers/ui'
|
||||
|
||||
test('should show error when accessing reset-password page without token', async ({ page }) => {
|
||||
await page.goto('/reset-password')
|
||||
await expect(page.getByText('Invalid or missing reset token.')).toBeVisible()
|
||||
await expect(page.getByRole('button', { name: 'Go to Login' })).toBeVisible()
|
||||
})
|
||||
|
||||
test('should reset password with valid token and allow logging in with new password', async ({
|
||||
page,
|
||||
request,
|
||||
prisma,
|
||||
}) => {
|
||||
const email = uniqueEmail('reset-pw')
|
||||
const oldPassword = E2E_PASSWORD
|
||||
const newPassword = 'newSecretPassword123'
|
||||
|
||||
// 1. Seed user
|
||||
await apiSignup(request, email, oldPassword)
|
||||
|
||||
// 2. Request password reset via API
|
||||
const resetRes = await request.post('/api/auth/request-password-reset', {
|
||||
data: {
|
||||
email,
|
||||
redirectTo: '/reset-password',
|
||||
},
|
||||
})
|
||||
expect(resetRes.ok()).toBe(true)
|
||||
|
||||
// Retrieve the generated verification token from DB
|
||||
const verification = await prisma.verification.findFirst({
|
||||
where: {
|
||||
identifier: { startsWith: 'reset-password:' },
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
})
|
||||
expect(verification).not.toBeNull()
|
||||
const token = verification!.identifier.replace('reset-password:', '')
|
||||
|
||||
// 3. Open reset password page with token
|
||||
await page.goto(`/reset-password?token=${token}`)
|
||||
|
||||
// 4. Fill in new password and confirmation
|
||||
await page.locator('input#password').fill(newPassword)
|
||||
await page.locator('input#confirmPassword').fill(newPassword)
|
||||
|
||||
// 5. Submit form
|
||||
await page.getByRole('button', { name: 'Reset Password' }).click()
|
||||
|
||||
// 6. Verify success state
|
||||
await expect(page.getByText('Password reset successfully!')).toBeVisible()
|
||||
|
||||
// 7. Click Go to Login
|
||||
await page.getByRole('button', { name: 'Go to Login' }).click()
|
||||
await expect(page).toHaveURL('/login')
|
||||
|
||||
// 8. Log in with the new password
|
||||
await loginViaUi(page, email, newPassword)
|
||||
await expect(page).toHaveURL(/\/teams\/[^/]+/)
|
||||
await expect(page.getByRole('heading', { name: 'Projects' })).toBeVisible()
|
||||
})
|
||||
@@ -40,8 +40,8 @@ test('owner should create a project with a cover image', async ({ owner, prisma
|
||||
await expect(page).toHaveURL(/\/projects\/[^/]+/)
|
||||
await expect(page.locator(`text=${projectName}`).first()).toBeVisible()
|
||||
|
||||
// Back on the dashboard the new project card is visible with its cover
|
||||
await page.click('button[aria-label="Dashboard"]')
|
||||
// Back on the home page the new project card is visible with its cover
|
||||
await page.click('button[aria-label="Home"]')
|
||||
await expect(page).toHaveURL(/\/teams\/[^/]+/)
|
||||
await expect(page.locator(`img[alt="${projectName}"]`)).toBeVisible()
|
||||
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { expect, test } from '../../fixtures'
|
||||
import { fileCard } from '../../helpers/files'
|
||||
|
||||
test('owner views a file and it appears in recents', async ({ file }) => {
|
||||
const { page, projectId, fileName, fileId } = file
|
||||
|
||||
// Open the file details page to record view
|
||||
await page.goto(`/projects/${projectId}/files/${fileId}`)
|
||||
await expect(page.getByText(fileName).first()).toBeVisible()
|
||||
|
||||
// Navigate to Recents page via sidebar or direct URL
|
||||
await page.goto(`/projects/${projectId}`)
|
||||
await page.getByText('Recently Viewed').first().click()
|
||||
await expect(page).toHaveURL(new RegExp(`/projects/${projectId}/recents`))
|
||||
|
||||
// The viewed file should be visible in recents
|
||||
const card = fileCard(page, fileName)
|
||||
await expect(card).toBeVisible()
|
||||
|
||||
// Toolbar should show hint text instead of action buttons
|
||||
await expect(
|
||||
page.getByText('This page displays the 100 most recent files you viewed in this project.'),
|
||||
).toBeVisible()
|
||||
await expect(page.getByRole('button', { name: 'Field' })).not.toBeVisible()
|
||||
await expect(page.getByRole('button', { name: 'Search' })).not.toBeVisible()
|
||||
await expect(page.getByText('AGENTS.md')).not.toBeVisible()
|
||||
|
||||
// Right-clicking the file should NOT show the context menu
|
||||
await card.click({ button: 'right' })
|
||||
await expect(page.getByRole('menuitem', { name: 'Delete' })).not.toBeVisible()
|
||||
await expect(page.getByRole('menuitem', { name: 'Download' })).not.toBeVisible()
|
||||
|
||||
// The per-item overflow menu must also be unavailable on the read-only Recents page.
|
||||
await expect(card.getByRole('button')).toHaveCount(0)
|
||||
})
|
||||
@@ -47,3 +47,39 @@ test('owner uploads a file via the "Upload File" context menu action', async ({
|
||||
const projectRow = await prisma.project.findUnique({ where: { id: projectId } })
|
||||
expect(asset!.parentId).toBe(projectRow?.rootFolderId)
|
||||
})
|
||||
|
||||
test('owner uploads an unsupported file via context menu action', async ({ project, prisma }) => {
|
||||
const { page, projectId } = project
|
||||
const fileName = `e2e-upload-${Date.now()}.bin`
|
||||
const binBuffer = Buffer.from([0x00, 0x01, 0x02, 0x03])
|
||||
|
||||
await page.goto(`/projects/${projectId}`)
|
||||
await expect(page.getByText('This folder is empty')).toBeVisible()
|
||||
|
||||
await page.getByText('This folder is empty').click({ button: 'right' })
|
||||
const [fileChooser] = await Promise.all([
|
||||
page.waitForEvent('filechooser'),
|
||||
page.getByRole('menuitem', { name: 'Upload File' }).click(),
|
||||
])
|
||||
await fileChooser.setFiles({
|
||||
name: fileName,
|
||||
mimeType: 'application/octet-stream',
|
||||
buffer: binBuffer,
|
||||
})
|
||||
|
||||
const card = fileCard(page, fileName)
|
||||
await expect(card).toBeVisible()
|
||||
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
const asset = await prisma.asset.findFirst({ where: { name: fileName } })
|
||||
return asset?.status
|
||||
},
|
||||
{ timeout: 30_000 },
|
||||
)
|
||||
.toBe('processed')
|
||||
|
||||
// Verify that the file card shows the generic file icon and is not stuck in uploading state
|
||||
await expect(card.locator('svg.lucide-file')).toBeVisible({ timeout: 10_000 })
|
||||
})
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
import { expect, test } from '../../fixtures'
|
||||
import { seedFile } from '../../helpers/assets'
|
||||
import { dragCard } from '../../helpers/dnd'
|
||||
import { apiAddAssetsToShare, apiCreateShare, fileCard } from '../../helpers/files'
|
||||
|
||||
test('owner manages versions: removes a version from a 3-version stack', async ({
|
||||
project,
|
||||
prisma,
|
||||
}) => {
|
||||
const { page, projectId, rootFolderId } = project
|
||||
|
||||
const fileA = await seedFile(prisma, projectId, rootFolderId, `e2e-mng-a-${Date.now()}`)
|
||||
const fileB = await seedFile(prisma, projectId, rootFolderId, `e2e-mng-b-${Date.now()}`)
|
||||
const fileC = await seedFile(prisma, projectId, rootFolderId, `e2e-mng-c-${Date.now()}`)
|
||||
|
||||
await page.goto(`/projects/${projectId}`)
|
||||
await expect(fileCard(page, fileA.name)).toBeVisible()
|
||||
await expect(fileCard(page, fileB.name)).toBeVisible()
|
||||
await expect(fileCard(page, fileC.name)).toBeVisible()
|
||||
|
||||
// 1. Create a 3-version stack: B on A -> stack (v2), then C on stack -> stack (v3)
|
||||
await dragCard(page, fileCard(page, fileB.name), fileCard(page, fileA.name))
|
||||
await expect(page.getByText('v2', { exact: true })).toBeVisible()
|
||||
|
||||
await dragCard(page, fileCard(page, fileC.name), fileCard(page, fileB.name))
|
||||
await expect(page.getByText('v3', { exact: true })).toBeVisible()
|
||||
|
||||
const stack = await prisma.asset.findFirstOrThrow({
|
||||
where: { projectId, parentId: rootFolderId, type: 'version_stack' },
|
||||
})
|
||||
expect(stack.fileCount).toBe(3)
|
||||
|
||||
// 2. Navigate to file viewer for the stack
|
||||
await page.goto(`/projects/${projectId}/files/${stack.id}`)
|
||||
|
||||
// 3. Open breadcrumb menu and click "Manage versions..."
|
||||
// Click on the asset name / badge dropdown trigger
|
||||
await page.getByRole('button', { name: new RegExp(fileC.name) }).click()
|
||||
// Hover or click on Versions sub-menu trigger
|
||||
await page.getByRole('menuitem', { name: 'Versions', exact: true }).hover()
|
||||
// Click "Manage versions..."
|
||||
await page.getByRole('button', { name: /manage versions$/i }).click()
|
||||
|
||||
// 4. Verify Manage versions dialog is visible with all 3 versions
|
||||
const dialog = page.getByRole('dialog')
|
||||
await expect(dialog).toBeVisible()
|
||||
await expect(dialog.getByText('Manage versions')).toBeVisible()
|
||||
await expect(dialog.getByText(fileA.name)).toBeVisible()
|
||||
await expect(dialog.getByText(fileB.name)).toBeVisible()
|
||||
await expect(dialog.getByText(fileC.name)).toBeVisible()
|
||||
|
||||
// 5. Remove fileB from stack: hover its row and click Remove from stack
|
||||
const rowB = dialog.locator('div.group', { hasText: fileB.name })
|
||||
await rowB.hover()
|
||||
const moreButton = rowB.getByRole('button', { name: 'More options' })
|
||||
await moreButton.click()
|
||||
await page.getByRole('menuitem', { name: /remove from stack/i }).click()
|
||||
|
||||
// 6. Verify toast and that fileB is removed from dialog
|
||||
await expect(page.getByText(/version removed from stack/i)).toBeVisible()
|
||||
await expect(dialog.getByText(fileB.name)).not.toBeVisible()
|
||||
await expect(dialog.getByText(fileA.name)).toBeVisible()
|
||||
await expect(dialog.getByText(fileC.name)).toBeVisible()
|
||||
|
||||
// DB: stack now has 2 versions (fileA and fileC), and fileB is standalone in root folder
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const s = await prisma.asset.findUnique({ where: { id: stack.id } })
|
||||
return s?.fileCount
|
||||
})
|
||||
.toBe(2)
|
||||
|
||||
const updatedFileB = await prisma.asset.findUnique({ where: { id: fileB.id } })
|
||||
expect(updatedFileB?.parentId).toBe(rootFolderId)
|
||||
})
|
||||
|
||||
test('owner removes version from 2-version stack dissolving the stack into standalone files', async ({
|
||||
project,
|
||||
prisma,
|
||||
}) => {
|
||||
const { page, projectId, rootFolderId } = project
|
||||
|
||||
const fileA = await seedFile(prisma, projectId, rootFolderId, `e2e-dis-a-${Date.now()}`)
|
||||
const fileB = await seedFile(prisma, projectId, rootFolderId, `e2e-dis-b-${Date.now()}`)
|
||||
|
||||
await page.goto(`/projects/${projectId}`)
|
||||
await dragCard(page, fileCard(page, fileB.name), fileCard(page, fileA.name))
|
||||
await expect(page.getByText('v2', { exact: true })).toBeVisible()
|
||||
|
||||
const stack = await prisma.asset.findFirstOrThrow({
|
||||
where: { projectId, parentId: rootFolderId, type: 'version_stack' },
|
||||
})
|
||||
|
||||
// Open file view
|
||||
await page.goto(`/projects/${projectId}/files/${stack.id}`)
|
||||
|
||||
// Open breadcrumb menu and click "Manage versions..."
|
||||
await page.getByRole('button', { name: new RegExp(fileB.name) }).click()
|
||||
await page.getByRole('menuitem', { name: 'Versions', exact: true }).hover()
|
||||
await page.getByRole('button', { name: /manage versions$/i }).click()
|
||||
|
||||
const dialog = page.getByRole('dialog')
|
||||
await expect(dialog).toBeVisible()
|
||||
|
||||
// Remove fileB -> stack dissolves -> only fileA remains
|
||||
const rowB = dialog.locator('div.group', { hasText: fileB.name })
|
||||
await rowB.hover()
|
||||
const moreButton = rowB.getByRole('button', { name: 'More options' })
|
||||
await moreButton.click()
|
||||
await page.getByRole('menuitem', { name: /remove from stack/i }).click()
|
||||
|
||||
// Dialog should close automatically when stack dissolves
|
||||
await expect(dialog).not.toBeVisible()
|
||||
|
||||
// DB: stack asset is deleted
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const s = await prisma.asset.findUnique({ where: { id: stack.id } })
|
||||
return s === null
|
||||
})
|
||||
.toBe(true)
|
||||
|
||||
// Both fileA and fileB are now standalone files in rootFolder
|
||||
const updatedFileA = await prisma.asset.findUnique({ where: { id: fileA.id } })
|
||||
const updatedFileB = await prisma.asset.findUnique({ where: { id: fileB.id } })
|
||||
expect(updatedFileA?.parentId).toBe(rootFolderId)
|
||||
expect(updatedFileB?.parentId).toBe(rootFolderId)
|
||||
})
|
||||
|
||||
test('dissolving a shared version stack renders the remaining standalone file name on the share page', async ({
|
||||
project,
|
||||
prisma,
|
||||
}) => {
|
||||
const { page, projectId, rootFolderId } = project
|
||||
|
||||
const fileA = await seedFile(prisma, projectId, rootFolderId, `e2e-shd-a-${Date.now()}`)
|
||||
const fileB = await seedFile(prisma, projectId, rootFolderId, `e2e-shd-b-${Date.now()}`)
|
||||
|
||||
await page.goto(`/projects/${projectId}`)
|
||||
await dragCard(page, fileCard(page, fileB.name), fileCard(page, fileA.name))
|
||||
await expect(page.getByText('v2', { exact: true })).toBeVisible()
|
||||
|
||||
const stack = await prisma.asset.findFirstOrThrow({
|
||||
where: { projectId, parentId: rootFolderId, type: 'version_stack' },
|
||||
})
|
||||
|
||||
// Share the version stack
|
||||
await fileCard(page, fileB.name).click({ button: 'right' })
|
||||
await page.getByRole('menuitem', { name: 'Create Share Link' }).click()
|
||||
const toast = page.locator('[data-sonner-toast]').filter({ hasText: 'Share link created' })
|
||||
await expect(toast).toBeVisible()
|
||||
|
||||
const share = await prisma.shareLink.findFirstOrThrow({
|
||||
where: { projectId },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
})
|
||||
|
||||
// Open file viewer for the stack
|
||||
await page.goto(`/projects/${projectId}/files/${stack.id}`)
|
||||
|
||||
// Open breadcrumb menu and click "Manage versions"
|
||||
await page.getByRole('button', { name: new RegExp(fileB.name) }).click()
|
||||
await page.getByRole('menuitem', { name: 'Versions', exact: true }).hover()
|
||||
await page.getByRole('button', { name: /manage versions$/i }).click()
|
||||
|
||||
const dialog = page.getByRole('dialog')
|
||||
await expect(dialog).toBeVisible()
|
||||
|
||||
// Remove fileB -> stack dissolves -> only fileA remains
|
||||
const rowB = dialog.locator('div.group', { hasText: fileB.name })
|
||||
await rowB.hover()
|
||||
const moreButton = rowB.getByRole('button', { name: 'More options' })
|
||||
await moreButton.click()
|
||||
await page.getByRole('menuitem', { name: /remove from stack/i }).click()
|
||||
|
||||
await expect(dialog).not.toBeVisible()
|
||||
|
||||
// Navigate to public share page: verify fileA is displayed with its non-empty name
|
||||
await page.goto(`/share/${share.id}`)
|
||||
await expect(fileCard(page, fileA.name)).toBeVisible()
|
||||
await expect(fileCard(page, fileB.name)).not.toBeVisible()
|
||||
})
|
||||
|
||||
test('moving a shared file into a shared version stack leaves only 1 stack card on the share page', async ({
|
||||
project,
|
||||
prisma,
|
||||
}) => {
|
||||
const { page, projectId, rootFolderId } = project
|
||||
|
||||
const fileA = await seedFile(prisma, projectId, rootFolderId, `e2e-mvsh-a-${Date.now()}`)
|
||||
const fileB = await seedFile(prisma, projectId, rootFolderId, `e2e-mvsh-b-${Date.now()}`)
|
||||
const fileC = await seedFile(prisma, projectId, rootFolderId, `e2e-mvsh-c-${Date.now()}`)
|
||||
|
||||
await page.goto(`/projects/${projectId}`)
|
||||
|
||||
// 1. Create a version stack from file B and file A (stack has v2, displays file B)
|
||||
await dragCard(page, fileCard(page, fileB.name), fileCard(page, fileA.name))
|
||||
await expect(page.getByText('v2', { exact: true })).toBeVisible()
|
||||
|
||||
const stack = await prisma.asset.findFirstOrThrow({
|
||||
where: { projectId, parentId: rootFolderId, type: 'version_stack' },
|
||||
})
|
||||
|
||||
// 2. Create a share link and add both stack AB and file C to it
|
||||
const share = await apiCreateShare(project.context.request, projectId, `Test Share ${Date.now()}`)
|
||||
await apiAddAssetsToShare(project.context.request, share.id, [stack.id, fileC.id])
|
||||
|
||||
// Verify initial share page has both stack and file C
|
||||
await page.goto(`/share/${share.id}`)
|
||||
await expect(fileCard(page, fileB.name)).toBeVisible()
|
||||
await expect(fileCard(page, fileC.name)).toBeVisible()
|
||||
|
||||
// 3. In project page, drop file C onto stack card (displays file B)
|
||||
await page.goto(`/projects/${projectId}`)
|
||||
await dragCard(page, fileCard(page, fileC.name), fileCard(page, fileB.name))
|
||||
await expect(page.getByText('v3', { exact: true })).toBeVisible()
|
||||
|
||||
// 4. Return to public share page: now only 1 card exists (the stack showing file C with v3)
|
||||
await page.goto(`/share/${share.id}`)
|
||||
await expect(page.getByText('v3', { exact: true })).toBeVisible()
|
||||
await expect(fileCard(page, fileC.name)).toBeVisible()
|
||||
await expect(fileCard(page, fileB.name)).not.toBeVisible()
|
||||
|
||||
// DB: share rootFolder fileCount is 1 and exactly 1 symlink exists
|
||||
const symlinks = await prisma.asset.findMany({
|
||||
where: { parentId: share.rootFolderId, type: 'symlink' },
|
||||
})
|
||||
expect(symlinks).toHaveLength(1)
|
||||
expect(symlinks[0].targetId).toBe(stack.id)
|
||||
|
||||
const updatedShareRoot = await prisma.asset.findUnique({ where: { id: share.rootFolderId } })
|
||||
expect(updatedShareRoot?.fileCount).toBe(1)
|
||||
})
|
||||
@@ -0,0 +1,121 @@
|
||||
import { expect, test } from '../../fixtures'
|
||||
|
||||
test('owner manages resource quotas in settings and resets usage from the dashboard', async ({
|
||||
owner,
|
||||
prisma,
|
||||
}) => {
|
||||
const { page, teamId, email } = owner
|
||||
|
||||
// 1. Navigate to team settings
|
||||
await page.goto(`/teams/${teamId}/settings`)
|
||||
|
||||
// 2. Click the Quotas sidebar tab
|
||||
await page.getByRole('button', { name: /Quotas|配额/i }).click()
|
||||
|
||||
// 3. Verify Quotas settings card is displayed with empty state
|
||||
await expect(page.getByRole('heading', { name: /^(Resource Quotas|资源配额)$/i })).toBeVisible()
|
||||
await expect(page.getByText(/No resource quotas configured|暂未配置资源配额/i)).toBeVisible()
|
||||
|
||||
// 4. Open Create Quota Dialog
|
||||
await page
|
||||
.getByRole('button', { name: /Add Quota|添加配额/i })
|
||||
.first()
|
||||
.click()
|
||||
await expect(page.getByText(/Create Quota Rule|创建配额规则/i)).toBeVisible()
|
||||
|
||||
// 5. Fill and submit new quota rule
|
||||
await page.fill('#quota-limit', '50000')
|
||||
await page.getByRole('button', { name: /^(Create|创建)$/i }).click()
|
||||
|
||||
// 6. Verify quota rule card appears in the list
|
||||
await expect(page.getByText(/50,000 tokens|50000 tokens/i)).toBeVisible()
|
||||
await expect(page.getByText(/Each Member|每个成员/i)).toBeVisible()
|
||||
|
||||
// Verify in database
|
||||
const createdRule = await prisma.quotaRule.findFirst({
|
||||
where: { teamId, limit: 50000 },
|
||||
})
|
||||
expect(createdRule).not.toBeNull()
|
||||
expect(createdRule?.enabled).toBe(true)
|
||||
|
||||
// 7. Usage is now monitored from the dashboard, not the settings rule card.
|
||||
await expect(page.getByRole('button', { name: /View Usage|查看使用量/i })).not.toBeVisible()
|
||||
|
||||
// 8. Toggle quota rule switch
|
||||
await page.getByRole('switch').click()
|
||||
await expect(page.getByRole('switch')).not.toBeChecked()
|
||||
const disabledRule = await prisma.quotaRule.findFirst({
|
||||
where: { id: createdRule?.id },
|
||||
})
|
||||
expect(disabledRule?.enabled).toBe(false)
|
||||
|
||||
// Toggle back on
|
||||
await page.getByRole('switch').click()
|
||||
await expect(page.getByRole('switch')).toBeChecked()
|
||||
|
||||
// 9. Open Edit Dialog by clicking the quota card
|
||||
await page.getByText(/50,000 tokens|50000 tokens/i).click()
|
||||
await expect(page.getByText(/Edit Quota Rule|编辑配额规则/i)).toBeVisible()
|
||||
await expect(page.getByRole('button', { name: /Each Member|每个成员/i })).toBeDisabled()
|
||||
await expect(page.locator('#quota-resource')).toBeDisabled()
|
||||
|
||||
// 10. Update limit
|
||||
await page.fill('#quota-limit', '75000')
|
||||
await page.getByRole('button', { name: /^(Save|保存)$/i }).click()
|
||||
|
||||
// Verify updated limit in UI and DB
|
||||
await expect(page.getByText(/75,000 tokens|75000 tokens/i)).toBeVisible()
|
||||
const updatedRule = await prisma.quotaRule.findFirst({
|
||||
where: { id: createdRule?.id },
|
||||
})
|
||||
expect(updatedRule?.limit).toBe(75000)
|
||||
|
||||
// 11. Verify quota usage and reset it from the dashboard
|
||||
const ownerUser = await prisma.user.findUnique({ where: { email } })
|
||||
expect(ownerUser).not.toBeNull()
|
||||
await prisma.quotaRecord.create({
|
||||
data: {
|
||||
ruleId: createdRule?.id as string,
|
||||
teamId,
|
||||
userId: ownerUser?.id,
|
||||
periodStart: new Date(),
|
||||
periodEnd: new Date(Date.now() + 24 * 60 * 60 * 1000),
|
||||
consumed: 100,
|
||||
},
|
||||
})
|
||||
await page.goto(`/teams/${teamId}/dashboard`)
|
||||
await page.getByRole('button', { name: /Quotas|配额/i }).click()
|
||||
await expect(
|
||||
page.getByText(/Monitor live quota usage|在仪表盘中监控实时配额使用情况/),
|
||||
).toBeVisible()
|
||||
|
||||
const quotaRuleButton = page.getByRole('button', { name: /Expand quota rule|展开配额规则/i })
|
||||
await quotaRuleButton.click()
|
||||
await expect(page.getByText(/^100 \/ 75,000 tokens$|^100 \/ 75000 tokens$/i)).toBeVisible()
|
||||
await page.getByRole('button', { name: /Reset Usage|重置使用量/i }).click()
|
||||
await expect(page.getByRole('alertdialog')).toBeVisible()
|
||||
await page.getByRole('button', { name: /Confirm|确认/i }).click()
|
||||
await expect(page.getByText(/^0 \/ 75,000 tokens$|^0 \/ 75000 tokens$/i)).toBeVisible()
|
||||
|
||||
const resetRecord = await prisma.quotaRecord.findFirst({
|
||||
where: { ruleId: createdRule?.id, userId: ownerUser?.id },
|
||||
})
|
||||
expect(resetRecord?.consumed).toBe(0)
|
||||
|
||||
// 12. Delete quota rule from settings
|
||||
await page.goto(`/teams/${teamId}/settings`)
|
||||
await page.getByRole('button', { name: /Quotas|配额/i }).click()
|
||||
await page.getByRole('button', { name: 'Quota actions' }).first().click()
|
||||
await page.getByRole('menuitem', { name: /Delete|删除/i }).click()
|
||||
await page
|
||||
.getByRole('button', { name: /Delete|删除/i })
|
||||
.last()
|
||||
.click()
|
||||
|
||||
// Verify empty state returns
|
||||
await expect(page.getByText(/No resource quotas configured|暂未配置资源配额/i)).toBeVisible()
|
||||
const deletedRule = await prisma.quotaRule.findFirst({
|
||||
where: { id: createdRule?.id },
|
||||
})
|
||||
expect(deletedRule).toBeNull()
|
||||
})
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/web-app",
|
||||
"version": "0.3.4",
|
||||
"version": "0.4.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
|
||||
@@ -13,12 +13,37 @@ import { initTranscodeWorkflows } from '@shumai/transcode'
|
||||
import { workflowService } from '@shumai/workflow-core'
|
||||
|
||||
import { handleDaemonCommands } from '@shumai/core/src/utils/daemon'
|
||||
import { authService } from '@shumai/core/src/auth/auth'
|
||||
|
||||
if (process.argv.includes('--check')) {
|
||||
console.log('✅ Web app evaluated successfully!')
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const cliArgs = process.argv.slice(2)
|
||||
const resetCmdIndex = cliArgs.findIndex(
|
||||
(arg) => arg === 'reset-password' || arg === 'reset-passowrd',
|
||||
)
|
||||
|
||||
if (resetCmdIndex !== -1) {
|
||||
const email = cliArgs[resetCmdIndex + 1]
|
||||
if (!email || email.startsWith('-')) {
|
||||
console.error('Error: Please provide a valid email address.')
|
||||
console.error('Usage: shumai reset-password <email>')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
try {
|
||||
const link = await authService.generatePasswordResetLink(email)
|
||||
console.log(link)
|
||||
process.exit(0)
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : 'Unknown error'
|
||||
console.error(`Error: ${message}`)
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
async function run() {
|
||||
// Initialize workflows and activities for local executor mode
|
||||
initAgentWorkflows()
|
||||
|
||||
@@ -33,7 +33,7 @@
|
||||
},
|
||||
"apps/agent": {
|
||||
"name": "@shumai/agent-app",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.7",
|
||||
"bin": {
|
||||
"shumai-agent": "./src/index.ts",
|
||||
},
|
||||
@@ -45,7 +45,7 @@
|
||||
},
|
||||
"apps/cli": {
|
||||
"name": "@shumai/cli",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.7",
|
||||
"bin": {
|
||||
"shumai-cli": "./src/index.ts",
|
||||
},
|
||||
@@ -60,7 +60,7 @@
|
||||
},
|
||||
"apps/transcode": {
|
||||
"name": "@shumai/transcode-app",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.7",
|
||||
"bin": {
|
||||
"shumai-transcode": "./src/index.ts",
|
||||
},
|
||||
@@ -72,7 +72,7 @@
|
||||
},
|
||||
"apps/web": {
|
||||
"name": "@shumai/web-app",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.7",
|
||||
"dependencies": {
|
||||
"@shumai/agent": "workspace:*",
|
||||
"@shumai/api": "workspace:*",
|
||||
@@ -92,7 +92,7 @@
|
||||
},
|
||||
"packages/agent": {
|
||||
"name": "@shumai/agent",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.7",
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sandbox-runtime": "0.0.66",
|
||||
"@earendil-works/pi-agent-core": "0.82.1",
|
||||
@@ -102,12 +102,12 @@
|
||||
"@shumai/db": "workspace:*",
|
||||
"@shumai/dtos": "workspace:*",
|
||||
"@shumai/workflow-core": "workspace:*",
|
||||
"@sinclair/typebox": "0.34.49",
|
||||
"@temporalio/activity": "1.17.2",
|
||||
"@temporalio/worker": "1.17.2",
|
||||
"@temporalio/workflow": "1.17.2",
|
||||
"adm-zip": "0.5.17",
|
||||
"jittered-fractional-indexing": "1.0.1",
|
||||
"typebox": "1.1.38",
|
||||
"ulid": "3.0.2",
|
||||
"zod": "4.4.3",
|
||||
},
|
||||
@@ -117,7 +117,7 @@
|
||||
},
|
||||
"packages/api": {
|
||||
"name": "@shumai/api",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.7",
|
||||
"dependencies": {
|
||||
"@hono/zod-validator": "0.7.6",
|
||||
"@shumai/core": "workspace:*",
|
||||
@@ -131,10 +131,11 @@
|
||||
},
|
||||
"packages/core": {
|
||||
"name": "@shumai/core",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.7",
|
||||
"dependencies": {
|
||||
"@earendil-works/pi-agent-core": "0.82.1",
|
||||
"@earendil-works/pi-ai": "0.82.1",
|
||||
"@modelcontextprotocol/client": "2.0.0",
|
||||
"@shumai/db": "workspace:*",
|
||||
"@shumai/dtos": "workspace:*",
|
||||
"@sinclair/typebox": "0.34.49",
|
||||
@@ -151,11 +152,13 @@
|
||||
"pino": "10.3.1",
|
||||
"sharp": "0.34.5",
|
||||
"tweetnacl": "1.0.3",
|
||||
"typebox": "1.1.38",
|
||||
"ulid": "3.0.2",
|
||||
"yaml": "2.9.0",
|
||||
"zod": "4.4.3",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@modelcontextprotocol/server": "2.0.0",
|
||||
"@types/adm-zip": "0.5.8",
|
||||
"@types/extract-zip": "2.0.3",
|
||||
"@types/pdfkit": "0.17.6",
|
||||
@@ -163,7 +166,7 @@
|
||||
},
|
||||
"packages/db": {
|
||||
"name": "@shumai/db",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.7",
|
||||
"dependencies": {
|
||||
"@earendil-works/pi-agent-core": "0.82.1",
|
||||
"@prisma/adapter-pg": "7.8.0",
|
||||
@@ -179,7 +182,7 @@
|
||||
},
|
||||
"packages/dtos": {
|
||||
"name": "@shumai/dtos",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.7",
|
||||
"dependencies": {
|
||||
"@earendil-works/pi-agent-core": "0.82.1",
|
||||
"zod": "4.4.3",
|
||||
@@ -187,7 +190,7 @@
|
||||
},
|
||||
"packages/e2e": {
|
||||
"name": "@shumai/e2e",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.7",
|
||||
"dependencies": {
|
||||
"@earendil-works/pi-agent-core": "0.82.1",
|
||||
"@google/genai": "1.52.0",
|
||||
@@ -202,11 +205,11 @@
|
||||
},
|
||||
"packages/tableprinter": {
|
||||
"name": "@shumai/tableprinter",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.7",
|
||||
},
|
||||
"packages/transcode": {
|
||||
"name": "@shumai/transcode",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.7",
|
||||
"dependencies": {
|
||||
"@shumai/core": "workspace:*",
|
||||
"@shumai/db": "workspace:*",
|
||||
@@ -220,7 +223,7 @@
|
||||
},
|
||||
"packages/webui": {
|
||||
"name": "@shumai/webui",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.7",
|
||||
"dependencies": {
|
||||
"@base-ui/react": "1.5.0",
|
||||
"@dnd-kit/abstract": "0.4.0",
|
||||
@@ -318,7 +321,7 @@
|
||||
},
|
||||
"packages/workflow-core": {
|
||||
"name": "@shumai/workflow-core",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.7",
|
||||
"dependencies": {
|
||||
"@shumai/core": "workspace:*",
|
||||
"@shumai/db": "workspace:*",
|
||||
@@ -330,6 +333,9 @@
|
||||
},
|
||||
},
|
||||
},
|
||||
"patchedDependencies": {
|
||||
"@earendil-works/pi-ai@0.82.1": "patches/@earendil-works%2Fpi-ai@0.82.1.patch",
|
||||
},
|
||||
"packages": {
|
||||
"@alloc/quick-lru": ["@alloc/quick-lru@5.2.0", "", {}, "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw=="],
|
||||
|
||||
@@ -735,6 +741,12 @@
|
||||
|
||||
"@mistralai/mistralai": ["@mistralai/mistralai@2.2.6", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.40.0", "ws": "^8.18.0", "zod": "^3.25.0 || ^4.0.0", "zod-to-json-schema": "^3.25.0" }, "peerDependencies": { "@opentelemetry/api": "^1.9.0" }, "optionalPeers": ["@opentelemetry/api"] }, "sha512-W8pX7zHxjJvMIpw8JMxeJEleapXX0Q9NPszdNzqkM3MIEoIGPObdodujj+WHteXEvGfaP/AMwlNyRfEzSY6dQQ=="],
|
||||
|
||||
"@modelcontextprotocol/client": ["@modelcontextprotocol/client@2.0.0", "", { "dependencies": { "@modelcontextprotocol/core": "2.0.0", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "jose": "^6.1.3", "pkce-challenge": "^5.0.0", "zod": "^4.2.0" } }, "sha512-8f1OghQ2rjzIOfqgUCP+8GiUWqRs89njoWLNqAe8kWmDePv3s1fZXseej+QXemssEuuOvLLmLO/kqM3IQHtISw=="],
|
||||
|
||||
"@modelcontextprotocol/core": ["@modelcontextprotocol/core@2.0.0", "", { "dependencies": { "zod": "^4.2.0" } }, "sha512-pJCEwGG7Lfr/+PQp9ZTwKXNeO5wzbfKL7H3MYpCorM4oFBoQrdjnBgEoqG+RjhsvS1FKrDbKux+M1HhlnGWqcA=="],
|
||||
|
||||
"@modelcontextprotocol/server": ["@modelcontextprotocol/server@2.0.0", "", { "dependencies": { "@modelcontextprotocol/core": "2.0.0", "zod": "^4.2.0" } }, "sha512-YhHWdHfpFMQfd0prsEnxKeS3Qz3ytIGmsS0sth4KDjnacIT7hxk6hXHkJ9KysxlkvTM+WZAtQbbcUhdoP4Hvtw=="],
|
||||
|
||||
"@napi-rs/canvas": ["@napi-rs/canvas@1.0.2", "", { "optionalDependencies": { "@napi-rs/canvas-android-arm64": "1.0.2", "@napi-rs/canvas-darwin-arm64": "1.0.2", "@napi-rs/canvas-darwin-x64": "1.0.2", "@napi-rs/canvas-linux-arm-gnueabihf": "1.0.2", "@napi-rs/canvas-linux-arm64-gnu": "1.0.2", "@napi-rs/canvas-linux-arm64-musl": "1.0.2", "@napi-rs/canvas-linux-riscv64-gnu": "1.0.2", "@napi-rs/canvas-linux-x64-gnu": "1.0.2", "@napi-rs/canvas-linux-x64-musl": "1.0.2", "@napi-rs/canvas-win32-arm64-msvc": "1.0.2", "@napi-rs/canvas-win32-x64-msvc": "1.0.2" } }, "sha512-EYEqlMYaCbpZDz+IgDH5xp9MTd3ui4dmGqbQYryhMLnSRxrhHKq5KQWHHKxFUcEP4Hp8/BWgvqXocX4j7iSbOQ=="],
|
||||
|
||||
"@napi-rs/canvas-android-arm64": ["@napi-rs/canvas-android-arm64@1.0.2", "", { "os": "android", "cpu": "arm64" }, "sha512-IMXKVQod0ol4vt3gmClUfXz4JAgHYESGPCUqmH3lQxBoL0K/2greJaQE1HVBVxWWFKfLc4OLZVdxg7kXVyXv+g=="],
|
||||
@@ -1761,6 +1773,10 @@
|
||||
|
||||
"events-universal": ["events-universal@1.0.1", "", { "dependencies": { "bare-events": "^2.7.0" } }, "sha512-LUd5euvbMLpwOF8m6ivPCbhQeSiYVNb8Vs0fQ8QjXo0JTkEHpz8pxdQf0gStltaPpw0Cca8b39KxvK9cfKRiAw=="],
|
||||
|
||||
"eventsource": ["eventsource@3.0.7", "", { "dependencies": { "eventsource-parser": "^3.0.1" } }, "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA=="],
|
||||
|
||||
"eventsource-parser": ["eventsource-parser@3.1.0", "", {}, "sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg=="],
|
||||
|
||||
"expect-type": ["expect-type@1.3.0", "", {}, "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA=="],
|
||||
|
||||
"exsolve": ["exsolve@1.0.8", "", {}, "sha512-LmDxfWXwcTArk8fUEnOfSZpHOJ6zOMUJKOtFLFqJLoKJetuQG874Uc7/Kki7zFLzYybmZhp1M7+98pfMqeX8yA=="],
|
||||
@@ -2329,6 +2345,8 @@
|
||||
|
||||
"pino-std-serializers": ["pino-std-serializers@7.1.0", "", {}, "sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw=="],
|
||||
|
||||
"pkce-challenge": ["pkce-challenge@5.0.1", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],
|
||||
|
||||
"pkcs7": ["pkcs7@1.0.4", "", { "dependencies": { "@babel/runtime": "^7.5.5" }, "bin": { "pkcs7": "bin/cli.js" } }, "sha512-afRERtHn54AlwaF2/+LFszyAANTCggGilmcmILUzEjvs3XgFZT+xE6+QWQcAGmu4xajy+Xtj7acLOPdx5/eXWQ=="],
|
||||
|
||||
"pkg-types": ["pkg-types@2.3.1", "", { "dependencies": { "confbox": "^0.2.4", "exsolve": "^1.0.8", "pathe": "^2.0.3" } }, "sha512-y+ichcgc2LrADuhLNAx8DFjVfgz91pRxfZdI3UDhxHvcVEZsenLO+7XaU5vOp0u/7V/wZ+plyuQxtrDlZJ+yeg=="],
|
||||
|
||||
+10
-3
@@ -34,7 +34,8 @@
|
||||
"using-shumai/notifications",
|
||||
"using-shumai/metadata",
|
||||
"using-shumai/collections",
|
||||
"using-shumai/share-links"
|
||||
"using-shumai/share-links",
|
||||
"using-shumai/gotenberg"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -42,14 +43,20 @@
|
||||
"pages": [
|
||||
"using-shumai/agent-providers",
|
||||
"using-shumai/agents",
|
||||
"using-shumai/agents-md",
|
||||
"using-shumai/agent-skills",
|
||||
"using-shumai/agent-tools",
|
||||
"using-shumai/mcp-servers",
|
||||
"using-shumai/agent-sandbox"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Media Transcoding Settings",
|
||||
"pages": ["using-shumai/transcode-settings"]
|
||||
"group": "Team Settings",
|
||||
"pages": [
|
||||
"using-shumai/transcode-settings",
|
||||
"using-shumai/quotas-settings",
|
||||
"using-shumai/password-reset"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Configuration",
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 309 KiB After Width: | Height: | Size: 131 KiB |
@@ -25,7 +25,7 @@ To protect your workspace environments and sensitive data, the sandbox enforces
|
||||
|
||||
## Domain Whitelisting
|
||||
|
||||
By default, sandboxed scripts cannot make network requests to the internet. Team Owners must explicitly authorize external APIs by managing domain access:
|
||||
By default, Network Sandbox is **disabled** (allowing all outbound network requests). Team Owners can toggle Network Sandbox **ON** in Sandbox Settings to enforce strict domain whitelisting:
|
||||
|
||||
### Allowed Domains
|
||||
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
---
|
||||
title: AGENTS.md Context & Instructions
|
||||
description: Provide hierarchical, folder-specific instructions and context to AI agents.
|
||||
---
|
||||
|
||||
In addition to global agent system prompts and skills, Shumai allows you to define project-level and folder-level instructions using **`AGENTS.md`**.
|
||||
|
||||
When an AI agent (such as a Chat Agent or Autofill Agent) operates within a project or folder, Shumai automatically loads the corresponding `AGENTS.md` files to provide context, operational rules, and project-specific knowledge.
|
||||
|
||||
---
|
||||
|
||||
## Hierarchical Traversal & Inheritance
|
||||
|
||||
Shumai uses a hierarchical context model for `AGENTS.md`:
|
||||
|
||||
- **Upward Traversal**: When an agent works on a file or folder, Shumai traverses the folder tree upwards from the current folder all the way to the **project root level**.
|
||||
- **Combined Context**: All `AGENTS.md` files found along this path are loaded into the agent's context in order (from the project root down to the current folder).
|
||||
- **Layered Rules**: This lets you define broad, project-wide rules and guidelines at the project root `AGENTS.md`, while adding specific rules, vocabulary, or autofill hints in nested subfolder `AGENTS.md` files.
|
||||
|
||||
---
|
||||
|
||||
## What to Include in AGENTS.md
|
||||
|
||||
You can use `AGENTS.md` to define any instructions you want the agent to follow when working in that folder or project:
|
||||
|
||||
- **Project & Folder Overview**: Describe what assets are stored in the folder and how they relate to the broader project.
|
||||
- **Agent Behavioral Rules**: Specify guardrails, tone, required formats, or things the agent should and shouldn't do when answering queries or leaving comments.
|
||||
- **Terminology & Domain Knowledge**: Define specialized vocabulary, acronyms, brand naming conventions, or project-specific jargon.
|
||||
- **Metadata & Autofill Instructions**: Guide the **Autofill Agent** on how to summarize assets, generate tags, or populate specific custom metadata fields for files in this folder.
|
||||
|
||||
---
|
||||
|
||||
## Accessing and Editing AGENTS.md
|
||||
|
||||
### Opening the Editor
|
||||
|
||||
To view or edit `AGENTS.md`:
|
||||
|
||||
1. Open any project or folder in the Shumai web application.
|
||||
2. Click the **`AGENTS.md`** button in the top navigation toolbar, or right-click any folder in the file browser and choose **AGENTS.md**.
|
||||
3. A dedicated WYSIWYG Markdown editor opens with full formatting support (headings, lists, code blocks, bold/italics, and links).
|
||||
|
||||
### Auto-Save
|
||||
|
||||
As you make changes in the editor, Shumai automatically saves your edits in the background with visual save status indicators (`Saving...`, `Saved`).
|
||||
|
||||
---
|
||||
|
||||
## Permissions & Read-Only Mode
|
||||
|
||||
- **Viewing**: All team members who have read access to the project can view `AGENTS.md`.
|
||||
- **Editing**: **Only Team Owners** are permitted to create, edit, or delete `AGENTS.md` files.
|
||||
- **Read-Only State**: Non-owner members will see a clear read-only indicator in the toolbar explaining that only team owners can edit instructions for the file.
|
||||
@@ -0,0 +1,82 @@
|
||||
---
|
||||
title: Document PDF Conversion with Gotenberg
|
||||
description: Convert Office documents, HTML, Markdown, CSV, and TXT files into high-fidelity PDF proxies for in-browser previewing.
|
||||
---
|
||||
|
||||
Office documents, HTML pages, Markdown files, spreadsheets, and plain-text files cannot be rendered natively in web browsers. Shumai uses [Gotenberg](https://gotenberg.dev), an open-source, Docker powered conversion API — to turn these files into PDF proxy assets for seamless in-browser previewing.
|
||||
|
||||
Gotenberg performs the conversion using:
|
||||
|
||||
- **LibreOffice** for Office documents, spreadsheets, and plain text.
|
||||
- **Headless Chromium** for HTML and Markdown files.
|
||||
|
||||
---
|
||||
|
||||
## Supported File Types
|
||||
|
||||
When Gotenberg is configured, Shumai automatically generates a PDF proxy for the following uploads:
|
||||
|
||||
| Category | Extensions | Converter |
|
||||
| ------------------ | ---------------------- | ----------- |
|
||||
| Word | `.doc`, `.docx` | LibreOffice |
|
||||
| Excel | `.xls`, `.xlsx` | LibreOffice |
|
||||
| PowerPoint | `.ppt`, `.pptx` | LibreOffice |
|
||||
| OpenDocument | `.odt`, `.ods`, `.odp` | LibreOffice |
|
||||
| Rich Text | `.rtf` | LibreOffice |
|
||||
| HTML | `.html`, `.htm` | Chromium |
|
||||
| Markdown | `.md`, `.markdown` | Chromium |
|
||||
| Spreadsheets / CSV | `.csv` | LibreOffice |
|
||||
| Plain text | `.txt` | LibreOffice |
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
|
||||
Gotenberg support is opt-in and controlled by the following environment variables on the machine running the transcode workers:
|
||||
|
||||
| Variable | Required | Description |
|
||||
| ------------------------------- | --------------- | ---------------------------------------------------------------- |
|
||||
| `GOTENBERG_URL` | Yes (to enable) | Base URL of the Gotenberg service, e.g. `http://gotenberg:3000`. |
|
||||
| `GOTENBERG_BASIC_AUTH_USERNAME` | No | Username when Basic Authentication is enabled on Gotenberg. |
|
||||
| `GOTENBERG_BASIC_AUTH_PASSWORD` | No | Password when Basic Authentication is enabled on Gotenberg. |
|
||||
|
||||
### Docker Quickstart
|
||||
|
||||
You can start a Gotenberg container with a single command:
|
||||
|
||||
```bash
|
||||
docker run -d --name gotenberg -p 3000:3000 gotenberg/gotenberg:8
|
||||
```
|
||||
|
||||
If you wish to enable Basic Authentication:
|
||||
|
||||
```bash
|
||||
docker run -d --name gotenberg -p 3000:3000 gotenberg/gotenberg:8 gotenberg --gotenberg-basic-auth-username=admin --gotenberg-basic-auth-password=secret
|
||||
```
|
||||
|
||||
### Docker Compose Setup
|
||||
|
||||
Add a Gotenberg service to your `docker-compose.yaml`:
|
||||
|
||||
```yaml
|
||||
gotenberg:
|
||||
image: gotenberg/gotenberg:8
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- '3000:3000'
|
||||
```
|
||||
|
||||
Then point Shumai at it:
|
||||
|
||||
```bash
|
||||
GOTENBERG_URL=http://localhost:3000
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Behavior Without Gotenberg
|
||||
|
||||
If Gotenberg is not configured or unreachable, Shumai degrades gracefully:
|
||||
|
||||
- **Office documents and HTML**: the upload completes as `processed` without a PDF proxy.
|
||||
- **CSV, Markdown, and TXT**: a lightweight built-in PDF generator produces the proxy instead, with reduced fidelity.
|
||||
@@ -0,0 +1,115 @@
|
||||
---
|
||||
title: MCP Servers
|
||||
description: Connect your agents to external tools and APIs using Model Context Protocol.
|
||||
---
|
||||
|
||||
Model Context Protocol (MCP) is an open standard that enables AI models to safely interface with external tools, microservices, and APIs. In Shumai, you can register remote MCP servers using standard HTTP transports (`Streamable HTTP` or `SSE`) and assign them to your AI agents.
|
||||
|
||||
---
|
||||
|
||||
## How MCP Works in Shumai
|
||||
|
||||
Rather than overloading model context windows with dozens of complex parameter schemas, Shumai connects to MCP servers efficiently:
|
||||
|
||||
- **Automatic Discovery & Metadata Caching**: When you add an MCP server, Shumai records it in your team's settings and connects to the endpoint to discover available tools, server-reported usage instructions, and description metadata. Discovery runs when you refresh the server, complete an OAuth flow, or the first time an agent calls one of its tools. These schemas are cached in your database for fast retrieval.
|
||||
- **Context-Efficient Proxy Tool (`mcp`)**: Assigned MCP servers are multiplexed through a single unified `mcp` proxy tool injected into your Chat Agents. The agent can dynamically inspect server status, search tools, view parameter schemas, and invoke functions as needed without wasting LLM tokens.
|
||||
- **Direct Tools Option**: For high-frequency actions, you can optionally configure specific tools as **Direct Tools** to expose them directly to the agent as top-level LLM functions alongside the `mcp` proxy.
|
||||
|
||||
---
|
||||
|
||||
## Adding an MCP Server
|
||||
|
||||
To register a new MCP server in Shumai:
|
||||
|
||||
1. Navigate to **Team Settings** and click the **MCP** tab.
|
||||
2. Click **Add MCP Server**.
|
||||
3. In the dialog box, enter your **Server Endpoint URL** (e.g. `https://mcp.example.com/sse` or `http://localhost:8080/mcp`).
|
||||
4. Click **Create**.
|
||||
|
||||
> **Note:** Only the **Server Endpoint URL** is required. Shumai derives a placeholder server name from the URL immediately; the server's actual name, status, instructions, and tool inventory are discovered the first time the server is connected (via the Refresh button in the edit dialog or the first tool call by an agent).
|
||||
|
||||
### Optional Server Configuration
|
||||
|
||||
After creating a server (the create dialog only requires a URL), open its edit dialog to configure advanced settings:
|
||||
|
||||
- **Transport**: Choose between `Streamable HTTP` (default) or `Server-Sent Events (SSE)`.
|
||||
- **Auth Strategy**: Select `Auto-detect` (default), `None`, `Bearer Token`, or `OAuth 2.0`.
|
||||
- **Minimum Permission Role**: Set the minimum team role required to invoke tools on this server (`Reviewer`, `Editor`, or `Owner`).
|
||||
- **Direct Tools**: Specify a list of tool names that should be exposed directly to agents as native LLM tools.
|
||||
|
||||
---
|
||||
|
||||
## Understanding Tool Configuration
|
||||
|
||||
In the server's edit dialog, the **Tools** section lists every discovered tool with a three-state toggle (plus **All Off** / **All Proxy** / **All Direct** bulk actions):
|
||||
|
||||
- **Off**: The tool is excluded and completely invisible to agents — it cannot be listed, searched, or called through the proxy, nor registered as a direct tool. Use this to hide noisy or dangerous tools.
|
||||
- **Proxy** (default): The tool is available through the single `mcp` proxy tool.
|
||||
- **Direct**: The tool is exposed to agents as a native top-level function with a `{server}_{tool}` prefixed name.
|
||||
|
||||
### The `mcp` Proxy Tool
|
||||
|
||||
The `mcp` proxy tool is a single function injected into an agent's context that multiplexes every MCP server assigned to that agent. Instead of loading each tool's full parameter schema up front, the agent interacts with servers on demand:
|
||||
|
||||
- `mcp({})` — connection and auth status of all assigned servers
|
||||
- `mcp({ server: "name" })` — list a server's tools
|
||||
- `mcp({ search: "query" })` — search for tools across servers (schemas included by default)
|
||||
- `mcp({ describe: "tool" })` — view one tool's full parameter schema
|
||||
- `mcp({ instructions: "name" })` — view a server's usage instructions
|
||||
- `mcp({ server: "name", tool: "tool_name", args: {...} })` — call a tool (pass either the `{server}_{tool}` prefixed name or the original name)
|
||||
- `mcp({ action: "auth-start", server: "name" })` — start OAuth for a server
|
||||
|
||||
Because only one compact tool (plus a short server/tool listing) occupies the context window, the proxy keeps token usage low even when a server exposes dozens of tools. The trade-off is an extra discovery round trip: the agent typically lists or searches tools first, then calls them.
|
||||
|
||||
### Direct Tools
|
||||
|
||||
Direct tools flip the trade-off in the other direction. A tool configured as **Direct** is registered as a native top-level function (e.g. `tavily_mcp_tavily_search`) that the agent can invoke immediately, exactly like any built-in tool.
|
||||
|
||||
Why use direct tools:
|
||||
|
||||
- **Faster, more reliable calls** for high-frequency actions: the full parameter schema is always in the context window, so the agent can call the tool in a single step without first discovering it through the proxy.
|
||||
- **Better tool discovery**: the model sees the tool and its description up front and is more likely to reach for it at the right moment.
|
||||
|
||||
The cost: every direct tool permanently consumes context tokens for its schema, so reserve **Direct** for frequently used or critical tools and keep large MCP servers on **Proxy** to avoid unnecessary context overhead. Direct tools are still subject to the same role-based permission checks as proxy calls, and the `mcp` proxy tool remains available for discovery, auth, and status.
|
||||
|
||||
---
|
||||
|
||||
## Authentication Modes
|
||||
|
||||
Shumai supports several authentication strategies for securing access to MCP endpoints:
|
||||
|
||||
### 1. No Auth (`none`)
|
||||
|
||||
Used for public or local MCP servers that do not require credentials.
|
||||
|
||||
### 2. Bearer Token (`bearer`)
|
||||
|
||||
Provide a static API token or key. Shumai attaches this token in the `Authorization: Bearer <token>` header for all transport requests.
|
||||
|
||||
### 3. OAuth 2.0 (`oauth`)
|
||||
|
||||
For MCP endpoints protected by OAuth identity providers:
|
||||
|
||||
- **Authorization Code + PKCE**: Click **Connect** on the server card in Team Settings. Shumai opens a secure OAuth popup window directing you to the identity provider. After approving permissions, the browser automatically redirects back to Shumai, completes token exchange, and refreshes server tools.
|
||||
- **Client Credentials**: Provide a `Client ID` and `Client Secret` for automated server-to-server token acquisition.
|
||||
|
||||
---
|
||||
|
||||
## Assigning MCP Servers to Agents
|
||||
|
||||
By default, newly added MCP servers are **not assigned to any agent**. To give an agent access to an MCP server:
|
||||
|
||||
1. Navigate to **Team Settings** > **Agents**.
|
||||
2. Click on the target agent to open its configuration dialog.
|
||||
3. Scroll down to the **MCP Servers** section.
|
||||
4. Toggle the switch next to the MCP server(s) you want to authorize for this agent.
|
||||
5. Click **Save Changes**.
|
||||
|
||||
---
|
||||
|
||||
## Role-Based Access Control
|
||||
|
||||
Each MCP server has a **Minimum Required Role** setting (`Reviewer`, `Editor`, or `Owner`):
|
||||
|
||||
- When an agent attempts to call a tool on an MCP server, Shumai verifies the role of the user interacting with the agent.
|
||||
- If the user's role does not meet the minimum requirement, tool execution is blocked with a permission error message, preventing unauthorized actions.
|
||||
@@ -0,0 +1,60 @@
|
||||
---
|
||||
title: Password Reset
|
||||
description: How administrators generate secure password reset links for team members.
|
||||
---
|
||||
|
||||
Because Shumai does not require an external email delivery service (SMTP) to be configured for standard self-hosted deployments, password resets are initiated securely by an administrator using the Shumai CLI.
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
When a user forgets their password, an administrator can generate a one-time password reset link directly from the command line.
|
||||
|
||||
- **Link Expiration**: The generated password reset link is valid for **1 hour** (`3600 seconds`).
|
||||
- **One-Time Use**: Once used, the token is permanently invalidated.
|
||||
- **Session Revocation**: When a user resets their password, all existing active sessions for that account are automatically revoked across all devices.
|
||||
- **Latest Link Validity**: Generating a new reset link for a user immediately supersedes any previously generated pending links.
|
||||
|
||||
---
|
||||
|
||||
## Generating a Password Reset Link
|
||||
|
||||
### Running on Local Host / Server
|
||||
|
||||
Run the `reset-password` subcommand from your Shumai installation directory:
|
||||
|
||||
```bash
|
||||
shumai reset-password <user-email>
|
||||
```
|
||||
|
||||
_(Alternatively, `bun apps/web/src/index.ts reset-password <user-email>`)_
|
||||
|
||||
**Example Output:**
|
||||
|
||||
```text
|
||||
http://localhost:3000/reset-password?token=bb3xg4uO3cwN0FQv4cgUK6Hh
|
||||
```
|
||||
|
||||
### Running inside Docker
|
||||
|
||||
If Shumai is running inside a Docker container, execute the command using `docker exec`:
|
||||
|
||||
```bash
|
||||
docker exec -it <container-name-or-id> shumai reset-password <user-email>
|
||||
```
|
||||
|
||||
> [!TIP]
|
||||
> Both `shumai` and the common alias `shuami` (e.g. `shuami reset-password <user-email>`) are supported.
|
||||
|
||||
> [!NOTE]
|
||||
> For remote servers or production deployments, ensure `BETTER_AUTH_URL` is set in your environment (e.g., `BETTER_AUTH_URL=https://shumai.example.com`) so the CLI generates the reset link with your public domain instead of `localhost`.
|
||||
|
||||
---
|
||||
|
||||
## Member Reset Experience
|
||||
|
||||
1. The administrator sends the generated URL to the team member via their preferred secure communication channel.
|
||||
2. The user opens the link in their browser.
|
||||
3. The user inputs their **New Password** and **Confirm Password** (minimum 3 characters).
|
||||
4. Upon clicking **Reset Password**, the password is securely updated, all previous active sessions are invalidated, and the user is redirected to `/login` to sign in.
|
||||
@@ -0,0 +1,121 @@
|
||||
---
|
||||
title: Resource Quotas
|
||||
description: Configure team resource quotas, monitor live usage, and reset quota windows from the dashboard.
|
||||
---
|
||||
|
||||
AI workflows and media processing tools can consume significant compute and API credits. Shumai provides a **Resource Quotas** system that allows Team Owners to set granular rate limits, govern budgets, and monitor real-time usage across team members and roles.
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Resource Quotas allow you to define maximum usage limits across specific time windows (e.g., hourly, daily, or weekly). When a member or team reaches their assigned quota, further actions for that resource are safely blocked until the quota period resets.
|
||||
|
||||
Quota configuration and usage monitoring are separate parts of the team experience:
|
||||
|
||||
- To create and manage quota rules, open **Team Settings** and navigate to the **Quotas** tab.
|
||||
- To monitor live usage, open the **Team Dashboard** and select **Quotas** under the **TEAM** section.
|
||||
|
||||
The quota dashboard is available to Team Owners.
|
||||
|
||||
---
|
||||
|
||||
## Scope Modes
|
||||
|
||||
When creating or editing a quota rule, you can define how the limit is applied:
|
||||
|
||||
### 1. Each Member
|
||||
|
||||
- **Behavior**: Every member in the scope receives their own independent limit. Usage by one member does not affect the remaining quota of others.
|
||||
- **Optional Role Filter**: You can restrict the quota to members with a specific role (e.g. only **Editors** or **Reviewers**), or apply it to the entire team.
|
||||
- **Use Case**: Give each editor a daily budget of 100,000 tokens.
|
||||
|
||||
### 2. All Members (Shared Pool)
|
||||
|
||||
- **Behavior**: The quota limit is shared as a collective pool across all matching members. Every member's consumption draws from the same total.
|
||||
- **Optional Role Filter**: Apply the shared pool to all team members or restrict it to a specific role.
|
||||
- **Use Case**: Cap the total team spending on AI models to $50 per day.
|
||||
|
||||
### 3. Selected Members
|
||||
|
||||
- **Behavior**: Assign individual limits to specific chosen team members.
|
||||
- **Use Case**: Grant higher limits to senior artists or technical directors while keeping standard limits for others.
|
||||
|
||||
---
|
||||
|
||||
## Supported Resource Types
|
||||
|
||||
Shumai supports quota enforcement across multiple layers of the AI and agent architecture:
|
||||
|
||||
| Resource Type | Description | Target Specification |
|
||||
| :-------------------------- | :-------------------------------------------------------------------------------------- | :----------------------------------- |
|
||||
| **Total Tokens** | Total LLM input and output tokens consumed in chat, comments, and autofill. | Team, Role, or Members |
|
||||
| **AI Cost ($)** | Dollar expenditure accrued from AI model providers. | Team, Role, or Members |
|
||||
| **MCP Server Calls** | Number of tool invocations directed to a connected Model Context Protocol (MCP) server. | Target MCP Server ID |
|
||||
| **Sandboxed Bash Commands** | Shell commands executed by the agent inside the isolated sandbox. | Wildcard pattern (e.g. `npm *`, `*`) |
|
||||
| **Agent Tool Calls** | Calls to specific native tools (e.g. `analyze_image`, `screenshot`, `create_file`). | Tool name |
|
||||
|
||||
### Bash Command Wildcard Matching
|
||||
|
||||
For sandboxed bash execution, you can restrict specific command patterns using wildcards (`*` and `?`):
|
||||
|
||||
- `*`: Matches any bash command execution.
|
||||
- `npm *`: Matches any npm command (e.g., `npm install`, `npm test`).
|
||||
- `git commit*`: Matches git commit invocations.
|
||||
|
||||
---
|
||||
|
||||
## Time Periods & Rollover
|
||||
|
||||
Quotas can be configured with the following reset periods:
|
||||
|
||||
- **1 Hour** (`1hour`)
|
||||
- **5 Hours** (`5hour`)
|
||||
- **1 Day** (`1day`)
|
||||
- **7 Days** (`7day`)
|
||||
|
||||
### Lazy Reset Mechanism
|
||||
|
||||
Shumai tracks usage windows automatically. When a period window expires, the system resets the quota upon the member's next request, seamlessly starting a fresh window without requiring background maintenance tasks.
|
||||
|
||||
---
|
||||
|
||||
## Monitoring Live Usage
|
||||
|
||||
Team Owners can inspect live consumption from the team dashboard:
|
||||
|
||||
1. Open the **Team Dashboard**.
|
||||
2. Select **Quotas** under the **TEAM** section.
|
||||
3. Quota rules are shown as first-level collapsible entries.
|
||||
4. Expand a rule to view its usage records.
|
||||
|
||||
Each usage record displays:
|
||||
|
||||
- **Consumption Status**: Progress bar showing consumed units versus the total limit.
|
||||
- **Remaining Allowance**: Percentage and numerical amount remaining.
|
||||
- **Refresh Countdown**: Remaining time until the active window resets (e.g., _"Refreshes in 45m"_).
|
||||
- **Target**: The team shared pool, role pool, or individual member associated with the record.
|
||||
- **Member Search**: For member-scoped rules, search the usage records by member name or email.
|
||||
|
||||
Usage records are loaded when a rule is expanded and refresh automatically while the rule is open.
|
||||
|
||||
### Manually Resetting a Usage Record
|
||||
|
||||
Each usage record includes a **Reset Usage** action. After confirming the action:
|
||||
|
||||
- Consumption is set to zero.
|
||||
- The quota period starts immediately.
|
||||
- The period ends after the configured quota duration.
|
||||
- For example, resetting a one-day quota at 10:00 starts a new window from 10:00 until 10:00 the following day.
|
||||
|
||||
A reset can also initialize a zero-consumption record for a member or shared pool that has not received usage yet. Resets are recorded in the team audit log.
|
||||
|
||||
---
|
||||
|
||||
## Managing Quota Rules
|
||||
|
||||
- **Enable / Disable**: Toggle the switch on any quota card in Team Settings to temporarily pause or resume enforcement without deleting the rule.
|
||||
- **Edit Rules**: Click any quota card in Team Settings to update limits, change reset periods, or adjust member selections.
|
||||
- **Delete Rules**: Open the card action menu (`⋮`) in Team Settings and select **Delete** to remove the quota rule.
|
||||
|
||||
Quota usage is monitored and reset from the Team Dashboard rather than from the settings rule cards.
|
||||
+4
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "shumai",
|
||||
"version": "0.3.4",
|
||||
"version": "0.4.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"repository": {
|
||||
@@ -65,5 +65,8 @@
|
||||
"typescript-eslint": "8.60.1",
|
||||
"vite-tsconfig-paths": "6.1.1",
|
||||
"vitest": "4.1.8"
|
||||
},
|
||||
"patchedDependencies": {
|
||||
"@earendil-works/pi-ai@0.82.1": "patches/@earendil-works%2Fpi-ai@0.82.1.patch"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/agent",
|
||||
"version": "0.3.4",
|
||||
"version": "0.4.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
@@ -14,12 +14,12 @@
|
||||
"@shumai/db": "workspace:*",
|
||||
"@shumai/dtos": "workspace:*",
|
||||
"@shumai/workflow-core": "workspace:*",
|
||||
"@sinclair/typebox": "0.34.49",
|
||||
"@temporalio/activity": "1.17.2",
|
||||
"@temporalio/worker": "1.17.2",
|
||||
"@temporalio/workflow": "1.17.2",
|
||||
"adm-zip": "0.5.17",
|
||||
"jittered-fractional-indexing": "1.0.1",
|
||||
"typebox": "1.1.38",
|
||||
"ulid": "3.0.2",
|
||||
"zod": "4.4.3"
|
||||
},
|
||||
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
updateCommentActivity,
|
||||
getAgentChatContextActivity,
|
||||
getAgentAutofillContextActivity,
|
||||
getAssetAutofillContextActivity,
|
||||
getAssetActivity,
|
||||
getCommentActivity,
|
||||
getProjectAutofillFieldsActivity,
|
||||
@@ -19,6 +18,7 @@ import {
|
||||
generateSessionNameActivity,
|
||||
type GenerateSessionNameParams,
|
||||
getUserTeamInfoActivity,
|
||||
formatProjectContextPrompt,
|
||||
} from './agent'
|
||||
import * as piAgent from '../index'
|
||||
import { type AgentHarness, type Session } from '@earendil-works/pi-agent-core'
|
||||
@@ -460,58 +460,7 @@ describe('Agent Activities', () => {
|
||||
expect(res.usage.inputTokens).toBe(5)
|
||||
})
|
||||
|
||||
it('should include agentContext in the autofill prompt when provided', async () => {
|
||||
const mockHarness = {
|
||||
subscribe: vi.fn(),
|
||||
prompt: vi.fn().mockResolvedValue({
|
||||
content: [{ type: 'text', text: 'Captured' }],
|
||||
usage: { input: 5, output: 5 },
|
||||
}),
|
||||
}
|
||||
const mockSession = {
|
||||
getEntries: vi.fn().mockResolvedValue([]),
|
||||
getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }),
|
||||
}
|
||||
|
||||
vi.mocked(piAgent.createAgentSession).mockImplementation(async (config: unknown) => {
|
||||
const params = config as {
|
||||
customTools: Array<{
|
||||
name: string
|
||||
execute: (id: string, args: Record<string, unknown>) => Promise<unknown>
|
||||
}>
|
||||
}
|
||||
const tool = params.customTools.find((t) => t.name === 'autofill_metadata')
|
||||
if (tool) {
|
||||
await tool.execute('1', { f1: 'val' })
|
||||
}
|
||||
return {
|
||||
session: mockSession as unknown as Session<DatabaseSessionMetadata>,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Mock AgentHarness instance for activity test
|
||||
harness: mockHarness as unknown as AgentHarness<any, any, any, any>,
|
||||
}
|
||||
})
|
||||
|
||||
const context = {
|
||||
agent: { id: 'b1', provider: { name: 'google' }, modelRef: { modelId: 'gemini' } },
|
||||
dbProviders: [],
|
||||
teamSkills: [],
|
||||
allowedDomains: [],
|
||||
} as unknown as AgentExecutionContext
|
||||
|
||||
await autofillAiActivity({
|
||||
teamId: 't1',
|
||||
images: [],
|
||||
fields: [{ id: 'f1', config: { name: 'F1', type: 'text' } }],
|
||||
context,
|
||||
agentContext: 'Generated using gemini',
|
||||
})
|
||||
|
||||
const capturedPrompt = mockHarness.prompt.mock.calls[0]?.[0] ?? ''
|
||||
expect(capturedPrompt).toContain('Generated using gemini')
|
||||
expect(capturedPrompt).toContain('<context>')
|
||||
})
|
||||
|
||||
it('should not include agentContext in the autofill prompt when absent', async () => {
|
||||
it('should use the base autofill prompt without any creation-context injection', async () => {
|
||||
const mockHarness = {
|
||||
subscribe: vi.fn(),
|
||||
prompt: vi.fn().mockResolvedValue({
|
||||
@@ -557,6 +506,7 @@ describe('Agent Activities', () => {
|
||||
})
|
||||
|
||||
const capturedPrompt = mockHarness.prompt.mock.calls[0]?.[0] ?? ''
|
||||
expect(capturedPrompt).toContain('Analyze the provided images and extract metadata.')
|
||||
expect(capturedPrompt).not.toContain('<context>')
|
||||
})
|
||||
})
|
||||
@@ -564,6 +514,11 @@ describe('Agent Activities', () => {
|
||||
describe('Agent Database Activities Integration', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
// Space out comment creations: ULID ids have 1ms timestamp granularity, so
|
||||
// back-to-back creates landing in the same millisecond sort by random suffix
|
||||
// and can break the id-ordered DAG spine in initializeAgentSessionActivity.
|
||||
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
|
||||
|
||||
let team: Team
|
||||
let user: User
|
||||
let project: Project
|
||||
@@ -621,6 +576,7 @@ describe('Agent Database Activities Integration', () => {
|
||||
},
|
||||
})
|
||||
|
||||
await sleep(2)
|
||||
// Create second comment that user responds with, triggering session initialization
|
||||
const userComment = await prisma.assetComment.create({
|
||||
data: {
|
||||
@@ -668,11 +624,13 @@ describe('Agent Database Activities Integration', () => {
|
||||
const mainComment1 = await prisma.assetComment.create({
|
||||
data: { assetId: asset.id, message: 'Main Comment 1', creatorId: user.id },
|
||||
})
|
||||
await sleep(2)
|
||||
const mainComment2 = await prisma.assetComment.create({
|
||||
data: { assetId: asset.id, message: 'Main Comment 2', creatorId: user.id },
|
||||
})
|
||||
|
||||
// 2. Thread reply under mainComment1
|
||||
await sleep(2)
|
||||
const threadReply1 = await prisma.assetComment.create({
|
||||
data: {
|
||||
assetId: asset.id,
|
||||
@@ -781,10 +739,12 @@ describe('Agent Database Activities Integration', () => {
|
||||
const msg1 = await prisma.assetComment.create({
|
||||
data: { assetId: asset.id, message: 'msg1', creatorId: user.id },
|
||||
})
|
||||
await sleep(2)
|
||||
// msg2 (top level)
|
||||
const msg2 = await prisma.assetComment.create({
|
||||
data: { assetId: asset.id, message: 'msg2', creatorId: user.id },
|
||||
})
|
||||
await sleep(2)
|
||||
// msg3 (top level asking agent)
|
||||
const msg3 = await prisma.assetComment.create({
|
||||
data: { assetId: asset.id, message: '[ask agent] msg3', creatorId: user.id },
|
||||
@@ -799,6 +759,7 @@ describe('Agent Database Activities Integration', () => {
|
||||
})
|
||||
|
||||
// agent response msg4
|
||||
await sleep(2)
|
||||
const msg4 = await prisma.assetComment.create({
|
||||
data: {
|
||||
assetId: asset.id,
|
||||
@@ -810,6 +771,7 @@ describe('Agent Database Activities Integration', () => {
|
||||
})
|
||||
|
||||
// msg5 (top level asking agent)
|
||||
await sleep(2)
|
||||
const msg5 = await prisma.assetComment.create({
|
||||
data: { assetId: asset.id, message: '[ask agent] msg5', creatorId: user.id },
|
||||
})
|
||||
@@ -833,6 +795,7 @@ describe('Agent Database Activities Integration', () => {
|
||||
expect(session3Id).not.toBe(session5Id)
|
||||
|
||||
// msg7 (reply to msg3 asking agent again)
|
||||
await sleep(2)
|
||||
const msg7 = await prisma.assetComment.create({
|
||||
data: {
|
||||
assetId: asset.id,
|
||||
@@ -881,10 +844,12 @@ describe('Agent Database Activities Integration', () => {
|
||||
const msg1 = await prisma.assetComment.create({
|
||||
data: { assetId: asset.id, message: 'msg1', creatorId: user.id },
|
||||
})
|
||||
await sleep(2)
|
||||
// msg2 (top level)
|
||||
const msg2 = await prisma.assetComment.create({
|
||||
data: { assetId: asset.id, message: 'msg2', creatorId: user.id },
|
||||
})
|
||||
await sleep(2)
|
||||
// msg3 (top level asking agent)
|
||||
const msg3 = await prisma.assetComment.create({
|
||||
data: { assetId: asset.id, message: '<@shumai-x1> what did i say', creatorId: user.id },
|
||||
@@ -919,10 +884,12 @@ describe('Agent Database Activities Integration', () => {
|
||||
const msg1 = await prisma.assetComment.create({
|
||||
data: { assetId: asset.id, message: 'msg1', creatorId: user.id },
|
||||
})
|
||||
await sleep(2)
|
||||
// msg2 (top level)
|
||||
const msg2 = await prisma.assetComment.create({
|
||||
data: { assetId: asset.id, message: 'msg2', creatorId: user.id },
|
||||
})
|
||||
await sleep(2)
|
||||
// msg3 (top level asking agent)
|
||||
const msg3 = await prisma.assetComment.create({
|
||||
data: { assetId: asset.id, message: '<@shumai-x1> what did i say', creatorId: user.id },
|
||||
@@ -1089,6 +1056,24 @@ describe('Agent Database Activities Integration', () => {
|
||||
},
|
||||
})
|
||||
|
||||
// Create two team skills, only one of which is enabled for the agent
|
||||
const enabledSkill = await prisma.skill.create({
|
||||
data: {
|
||||
name: 'Enabled Chat Skill',
|
||||
assetId: 'asset-enabled',
|
||||
hash: 'enabled-hash',
|
||||
teamId: team.id,
|
||||
},
|
||||
})
|
||||
const disabledSkill = await prisma.skill.create({
|
||||
data: {
|
||||
name: 'Disabled Chat Skill',
|
||||
assetId: 'asset-disabled',
|
||||
hash: 'disabled-hash',
|
||||
teamId: team.id,
|
||||
},
|
||||
})
|
||||
|
||||
const agent = await prisma.agent.create({
|
||||
data: {
|
||||
id: agentUser.id,
|
||||
@@ -1100,6 +1085,9 @@ describe('Agent Database Activities Integration', () => {
|
||||
provider: 'openai',
|
||||
model: 'gpt-4',
|
||||
},
|
||||
skills: {
|
||||
create: [{ skillId: enabledSkill.id }],
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
@@ -1110,6 +1098,59 @@ describe('Agent Database Activities Integration', () => {
|
||||
|
||||
expect(chatCtx.agent.id).toBe(agent.id)
|
||||
expect(chatCtx.dbProviders[0].name).toBe('openai')
|
||||
// Only the enabled skill must be advertised, and disabled team skills excluded
|
||||
expect(chatCtx.teamSkills.map((s) => s.id)).toEqual([enabledSkill.id])
|
||||
expect(chatCtx.enabledSkillIds).toEqual([enabledSkill.id])
|
||||
expect(chatCtx.teamSkills.map((s) => s.id)).not.toContain(disabledSkill.id)
|
||||
|
||||
// Test permission enforcement in getAgentChatContextActivity
|
||||
// Create owner-only agent
|
||||
const ownerAgentUser = await prisma.user.create({
|
||||
data: { name: 'Owner Bot', email: `ownerbot-${Date.now()}@shumai.ai`, type: 'agent' },
|
||||
})
|
||||
const ownerAgent = await prisma.agent.create({
|
||||
data: {
|
||||
id: ownerAgentUser.id,
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
permission: 'owner',
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
config: { provider: 'openai', model: 'gpt-4' },
|
||||
},
|
||||
})
|
||||
|
||||
// Create owner and reviewer members
|
||||
const ownerUser = await prisma.user.create({
|
||||
data: { name: 'Owner User', email: `owner-${Date.now()}@shumai.ai` },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: ownerUser.id, role: 'owner' },
|
||||
})
|
||||
|
||||
const reviewerUser = await prisma.user.create({
|
||||
data: { name: 'Reviewer User', email: `reviewer-${Date.now()}@shumai.ai` },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: reviewerUser.id, role: 'reviewer' },
|
||||
})
|
||||
|
||||
// Owner should succeed
|
||||
const ownerCtx = await getAgentChatContextActivity({
|
||||
teamId: team.id,
|
||||
agentId: ownerAgent.id,
|
||||
userId: ownerUser.id,
|
||||
})
|
||||
expect(ownerCtx.agent.id).toBe(ownerAgent.id)
|
||||
|
||||
// Reviewer should fail with non-retryable ApplicationFailure
|
||||
await expect(
|
||||
getAgentChatContextActivity({
|
||||
teamId: team.id,
|
||||
agentId: ownerAgent.id,
|
||||
userId: reviewerUser.id,
|
||||
}),
|
||||
).rejects.toThrow('Permission denied')
|
||||
|
||||
// Create User for autofill agent
|
||||
const autofillUser = await prisma.user.create({
|
||||
@@ -1132,6 +1173,9 @@ describe('Agent Database Activities Integration', () => {
|
||||
provider: 'openai',
|
||||
model: 'gpt-4',
|
||||
},
|
||||
skills: {
|
||||
create: [{ skillId: enabledSkill.id }],
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
@@ -1140,6 +1184,77 @@ describe('Agent Database Activities Integration', () => {
|
||||
})
|
||||
|
||||
expect(autofillCtx.agent.id).toBe(autofillAgent.id)
|
||||
// Only the enabled skill must be advertised for the autofill agent as well
|
||||
expect(autofillCtx.teamSkills.map((s) => s.id)).toEqual([enabledSkill.id])
|
||||
expect(autofillCtx.enabledSkillIds).toEqual([enabledSkill.id])
|
||||
expect(autofillCtx.teamSkills.map((s) => s.id)).not.toContain(disabledSkill.id)
|
||||
})
|
||||
|
||||
it('should return an empty enabled skill list when the agent has no skills enabled', async () => {
|
||||
const provider = await prisma.provider.create({
|
||||
data: {
|
||||
teamId: team.id,
|
||||
name: 'openai-noskill',
|
||||
config: {
|
||||
api: 'openai-completions',
|
||||
apiKey: 'mock-key',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const model = await prisma.model.create({
|
||||
data: {
|
||||
providerId: provider.id,
|
||||
modelId: 'gpt-4',
|
||||
name: 'GPT 4',
|
||||
config: {
|
||||
reasoning: false,
|
||||
input: ['text'],
|
||||
contextWindow: 8192,
|
||||
maxTokens: 2048,
|
||||
cost: { input: 0.01, output: 0.03, cacheRead: 0, cacheWrite: 0 },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.skill.create({
|
||||
data: {
|
||||
name: 'Team Wide Skill',
|
||||
assetId: 'asset-team',
|
||||
hash: 'team-hash',
|
||||
teamId: team.id,
|
||||
},
|
||||
})
|
||||
|
||||
const agentUser = await prisma.user.create({
|
||||
data: {
|
||||
name: 'No Skill Agent User',
|
||||
email: 'noskillagent@shumai.ai',
|
||||
type: 'agent',
|
||||
},
|
||||
})
|
||||
const agent = await prisma.agent.create({
|
||||
data: {
|
||||
id: agentUser.id,
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
config: {
|
||||
provider: 'openai-noskill',
|
||||
model: 'gpt-4',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const chatCtx = await getAgentChatContextActivity({
|
||||
teamId: team.id,
|
||||
agentId: agent.id,
|
||||
})
|
||||
|
||||
// Team-wide skill exists but is not enabled for this agent
|
||||
expect(chatCtx.teamSkills).toEqual([])
|
||||
expect(chatCtx.enabledSkillIds).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1243,8 +1358,7 @@ describe('Agent Database Activities Integration', () => {
|
||||
key: 'field_key_1',
|
||||
scope: 'TEAM',
|
||||
teamId: team.id,
|
||||
aiAutofill: true,
|
||||
config: { name: 'Title Extractor', type: 'text' },
|
||||
config: { name: 'Title Extractor', type: 'text', autofillSource: 'CONTENT' },
|
||||
},
|
||||
})
|
||||
|
||||
@@ -1264,37 +1378,6 @@ describe('Agent Database Activities Integration', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('getAssetAutofillContextActivity', () => {
|
||||
it('should return the stored autofill context for an asset', async () => {
|
||||
const withContext = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'ctx.png',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
autofillContext: 'Generated using gemini',
|
||||
},
|
||||
})
|
||||
|
||||
const ctx = await getAssetAutofillContextActivity(withContext.id)
|
||||
expect(ctx).toBe('Generated using gemini')
|
||||
})
|
||||
|
||||
it('should return null when the asset has no autofill context', async () => {
|
||||
const noContext = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'plain.png',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
},
|
||||
})
|
||||
|
||||
const ctx = await getAssetAutofillContextActivity(noContext.id)
|
||||
expect(ctx).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('executeAgentToolActivity', () => {
|
||||
beforeEach(() => {
|
||||
vi.spyOn(authzService, 'hasPermission').mockResolvedValue()
|
||||
@@ -1342,6 +1425,54 @@ describe('Agent Database Activities Integration', () => {
|
||||
expect(res.assets.length).toBe(1)
|
||||
expect(res.pageInfo.cursor).toBeDefined()
|
||||
})
|
||||
|
||||
it('should resolve version_stack name and size from top child version when container name is empty', async () => {
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'WorkspaceFolder',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
},
|
||||
})
|
||||
|
||||
const versionStack = await prisma.asset.create({
|
||||
data: {
|
||||
name: '',
|
||||
type: AssetType.version_stack,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
parentId: folder.id,
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.asset.create({
|
||||
data: {
|
||||
name: 'banana_ghost.txt',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
parentId: versionStack.id,
|
||||
sizeByte: 622960,
|
||||
sortIndex: '0|i00000:',
|
||||
},
|
||||
})
|
||||
|
||||
const res = await executeAgentToolActivity({
|
||||
taskId: 'task-1',
|
||||
toolName: 'list_assets',
|
||||
args: { parent: folder.id, page: 1, pageSize: 10 },
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
const stackItem = res.assets.find(
|
||||
(a: { id: string; name: string; size: number; type: string }) => a.id === versionStack.id,
|
||||
)
|
||||
expect(stackItem).toBeDefined()
|
||||
expect(stackItem?.name).toBe('banana_ghost.txt')
|
||||
expect(stackItem?.size).toBe(622960)
|
||||
expect(stackItem?.type).toBe('version_stack')
|
||||
})
|
||||
})
|
||||
|
||||
describe('create_folder', () => {
|
||||
@@ -1406,7 +1537,17 @@ describe('Agent Database Activities Integration', () => {
|
||||
expect(uploadService.triggerPostUploadWorkflows).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should persist autofillContext on the created file when context is provided', async () => {
|
||||
it('should persist metadata on the created file when metadata map is provided', async () => {
|
||||
await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'prompt',
|
||||
scope: 'PROJECT',
|
||||
projectId: project.id,
|
||||
teamId: team.id,
|
||||
config: { name: 'Prompt', type: 'text', autofillSource: 'CREATION_CONTEXT' },
|
||||
},
|
||||
})
|
||||
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'WorkspaceFolder',
|
||||
@@ -1427,16 +1568,46 @@ describe('Agent Database Activities Integration', () => {
|
||||
name: 'ctx.txt',
|
||||
size: 100,
|
||||
contentType: 'text/plain',
|
||||
context: 'Generated using gemini',
|
||||
metadata: { prompt: 'Generated using gemini' },
|
||||
},
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
const created = await prisma.asset.findUnique({ where: { id: res.id } })
|
||||
expect(created?.autofillContext).toBe('Generated using gemini')
|
||||
const val = await prisma.assetMetadataValue.findFirst({
|
||||
where: { assetId: res.id, fieldKey: 'prompt' },
|
||||
})
|
||||
expect(val?.stringValue).toBe('Generated using gemini')
|
||||
})
|
||||
|
||||
it('should not set autofillContext when context is not provided', async () => {
|
||||
it('should persist select and selectMulti metadata with dynamic newOption', async () => {
|
||||
const selectField = await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'provider',
|
||||
scope: 'PROJECT',
|
||||
project: { connect: { id: project.id } },
|
||||
config: {
|
||||
name: 'Provider',
|
||||
type: 'select',
|
||||
autofillSource: 'CREATION_CONTEXT',
|
||||
select: { options: [{ id: 'openai', displayName: 'OpenAI', color: '#f43f5e' }] },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const multiField = await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'tags',
|
||||
scope: 'PROJECT',
|
||||
project: { connect: { id: project.id } },
|
||||
config: {
|
||||
name: 'Tags',
|
||||
type: 'selectMulti',
|
||||
autofillSource: 'CREATION_CONTEXT',
|
||||
selectMulti: { options: [{ id: 'tag1', displayName: 'Tag 1', color: '#3b82f6' }] },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'WorkspaceFolder',
|
||||
@@ -1453,16 +1624,80 @@ describe('Agent Database Activities Integration', () => {
|
||||
toolName: 'create_file',
|
||||
args: {
|
||||
parent: folder.id,
|
||||
s3Key: 'uploads/plain.txt',
|
||||
name: 'plain.txt',
|
||||
s3Key: 'uploads/new_opt.txt',
|
||||
name: 'new_opt.txt',
|
||||
size: 100,
|
||||
contentType: 'text/plain',
|
||||
metadata: {
|
||||
provider: { newOption: { value: 'Kling' } },
|
||||
tags: ['tag1', { newOption: { value: 'Tag 2' } }],
|
||||
},
|
||||
},
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
const created = await prisma.asset.findUnique({ where: { id: res.id } })
|
||||
expect(created?.autofillContext).toBeNull()
|
||||
// Verify select field
|
||||
const providerVal = await prisma.assetMetadataValue.findFirst({
|
||||
where: { assetId: res.id, fieldKey: selectField.key },
|
||||
})
|
||||
expect(providerVal?.stringValue).toBe('kling')
|
||||
|
||||
// Verify select field config was updated with new option
|
||||
const updatedSelectField = await prisma.metadataField.findUnique({
|
||||
where: { key: selectField.key },
|
||||
})
|
||||
const selectOpts =
|
||||
(updatedSelectField?.config as PrismaJson.FieldConfig)?.select?.options || []
|
||||
expect(selectOpts.some((o) => o.displayName === 'Kling' && o.id === 'kling')).toBe(true)
|
||||
|
||||
// Verify selectMulti field
|
||||
const tagsVal = await prisma.assetMetadataValue.findFirst({
|
||||
where: { assetId: res.id, fieldKey: multiField.key },
|
||||
})
|
||||
expect(tagsVal?.jsonValue).toEqual(['tag1', 'tag-2'])
|
||||
|
||||
// Verify selectMulti field config was updated with new option
|
||||
const updatedMultiField = await prisma.metadataField.findUnique({
|
||||
where: { key: multiField.key },
|
||||
})
|
||||
const multiOpts =
|
||||
(updatedMultiField?.config as PrismaJson.FieldConfig)?.selectMulti?.options || []
|
||||
expect(multiOpts.some((o) => o.displayName === 'Tag 2' && o.id === 'tag-2')).toBe(true)
|
||||
})
|
||||
|
||||
it('should reject metadata with keys that are not valid in this project', async () => {
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'WorkspaceFolder',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
fileCount: 0,
|
||||
sizeByte: 0,
|
||||
},
|
||||
})
|
||||
|
||||
await expect(
|
||||
executeAgentToolActivity({
|
||||
taskId: 'task-1',
|
||||
toolName: 'create_file',
|
||||
args: {
|
||||
parent: folder.id,
|
||||
s3Key: 'uploads/ctx.txt',
|
||||
name: 'ctx.txt',
|
||||
size: 100,
|
||||
contentType: 'text/plain',
|
||||
metadata: { prompt: 'ok', unknownKey: 'not allowed' },
|
||||
},
|
||||
userId: user.id,
|
||||
}),
|
||||
).rejects.toThrow(/not valid in this project/)
|
||||
|
||||
// No metadata value should have been written for the unknown key
|
||||
const val = await prisma.assetMetadataValue.findFirst({
|
||||
where: { fieldKey: 'unknownKey' },
|
||||
})
|
||||
expect(val).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1573,7 +1808,17 @@ describe('Agent Database Activities Integration', () => {
|
||||
expect(Number(updatedStack?.sizeByte)).toBe(350)
|
||||
})
|
||||
|
||||
it('should persist autofillContext when creating a new version stack', async () => {
|
||||
it('should persist metadata on the created version when metadata map is provided', async () => {
|
||||
await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'prompt',
|
||||
scope: 'PROJECT',
|
||||
projectId: project.id,
|
||||
teamId: team.id,
|
||||
config: { name: 'Prompt', type: 'text', autofillSource: 'CREATION_CONTEXT' },
|
||||
},
|
||||
})
|
||||
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'WorkspaceFolder',
|
||||
@@ -1605,45 +1850,51 @@ describe('Agent Database Activities Integration', () => {
|
||||
name: 'v2.txt',
|
||||
size: 300,
|
||||
contentType: 'text/plain',
|
||||
context: 'Generated using seedance',
|
||||
metadata: { prompt: 'Generated using seedance' },
|
||||
},
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
const created = await prisma.asset.findUnique({ where: { id: res.id } })
|
||||
expect(created?.autofillContext).toBe('Generated using seedance')
|
||||
const val = await prisma.assetMetadataValue.findFirst({
|
||||
where: { assetId: res.id, fieldKey: 'prompt' },
|
||||
})
|
||||
expect(val?.stringValue).toBe('Generated using seedance')
|
||||
})
|
||||
|
||||
it('should persist autofillContext when adding to an existing version stack', async () => {
|
||||
it('should persist select and selectMulti newOption metadata in create_version', async () => {
|
||||
const selectField = await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'versionProvider',
|
||||
scope: 'PROJECT',
|
||||
project: { connect: { id: project.id } },
|
||||
config: {
|
||||
name: 'Version Provider',
|
||||
type: 'select',
|
||||
autofillSource: 'CREATION_CONTEXT',
|
||||
select: { options: [{ id: 'openai', displayName: 'OpenAI', color: '#f43f5e' }] },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'WorkspaceFolder',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
},
|
||||
})
|
||||
|
||||
const stack = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'VersionStack',
|
||||
type: AssetType.version_stack,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
parentId: folder.id,
|
||||
fileCount: 1,
|
||||
sizeByte: 100,
|
||||
sizeByte: 200,
|
||||
},
|
||||
})
|
||||
|
||||
const existingFileVersion = await prisma.asset.create({
|
||||
const fileAsset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'v1.txt',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
parentId: stack.id,
|
||||
sizeByte: 100,
|
||||
parentId: folder.id,
|
||||
sizeByte: 200,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -1651,137 +1902,28 @@ describe('Agent Database Activities Integration', () => {
|
||||
taskId: 'task-1',
|
||||
toolName: 'create_version',
|
||||
args: {
|
||||
parent: existingFileVersion.id,
|
||||
parent: fileAsset.id,
|
||||
s3Key: 'uploads/v2.txt',
|
||||
name: 'v2.txt',
|
||||
size: 250,
|
||||
size: 300,
|
||||
contentType: 'text/plain',
|
||||
context: 'Generated using sora2',
|
||||
},
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
const created = await prisma.asset.findUnique({ where: { id: res.id } })
|
||||
expect(created?.autofillContext).toBe('Generated using sora2')
|
||||
})
|
||||
})
|
||||
|
||||
describe('list_autofill_fields', () => {
|
||||
it('should return only aiAutofill fields with their options', async () => {
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'WorkspaceFolder',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'source',
|
||||
scope: 'PROJECT',
|
||||
projectId: project.id,
|
||||
teamId: team.id,
|
||||
aiAutofill: true,
|
||||
config: {
|
||||
name: 'Source',
|
||||
type: 'select',
|
||||
select: {
|
||||
options: [
|
||||
{ id: 'gemini', displayName: 'Gemini', color: '#ffffff' },
|
||||
{ id: 'seedance', displayName: 'Seedance', color: '#ffffff' },
|
||||
],
|
||||
},
|
||||
metadata: {
|
||||
versionProvider: { newOption: { value: 'Midjourney' } },
|
||||
},
|
||||
description: 'Generation source',
|
||||
},
|
||||
})
|
||||
await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'title',
|
||||
scope: 'PROJECT',
|
||||
projectId: project.id,
|
||||
teamId: team.id,
|
||||
aiAutofill: true,
|
||||
config: { name: 'Title', type: 'text' },
|
||||
},
|
||||
})
|
||||
await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'manual_notes',
|
||||
scope: 'PROJECT',
|
||||
projectId: project.id,
|
||||
teamId: team.id,
|
||||
aiAutofill: false,
|
||||
config: { name: 'Manual Notes', type: 'text' },
|
||||
},
|
||||
})
|
||||
|
||||
const res = await executeAgentToolActivity({
|
||||
taskId: 'task-1',
|
||||
toolName: 'list_autofill_fields',
|
||||
args: { parent: folder.id },
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
expect(res.fields).toHaveLength(2)
|
||||
const source = res.fields.find((f: { name: string }) => f.name === 'Source')
|
||||
expect(source?.name).toBe('Source')
|
||||
expect(source?.type).toBe('select')
|
||||
expect(source?.description).toBe('Generation source')
|
||||
expect(source?.options).toEqual([{ displayName: 'Gemini' }, { displayName: 'Seedance' }])
|
||||
expect(res.fields.find((f: { name: string }) => f.name === 'Manual Notes')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('should resolve the project through the ancestor chain', async () => {
|
||||
const rootFolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'Root',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
},
|
||||
const val = await prisma.assetMetadataValue.findFirst({
|
||||
where: { assetId: res.id, fieldKey: selectField.key },
|
||||
})
|
||||
const subFolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'Sub',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
parentId: rootFolder.id,
|
||||
},
|
||||
expect(val?.stringValue).toBe('midjourney')
|
||||
|
||||
const updatedField = await prisma.metadataField.findUnique({
|
||||
where: { key: selectField.key },
|
||||
})
|
||||
|
||||
await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'title_2',
|
||||
scope: 'PROJECT',
|
||||
projectId: project.id,
|
||||
teamId: team.id,
|
||||
aiAutofill: true,
|
||||
config: { name: 'Title 2', type: 'text' },
|
||||
},
|
||||
})
|
||||
|
||||
const res = await executeAgentToolActivity({
|
||||
taskId: 'task-1',
|
||||
toolName: 'list_autofill_fields',
|
||||
args: { parent: subFolder.id },
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
expect(res.fields.length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('should fail when parent is missing', async () => {
|
||||
await expect(
|
||||
executeAgentToolActivity({
|
||||
taskId: 'task-1',
|
||||
toolName: 'list_autofill_fields',
|
||||
args: {},
|
||||
userId: user.id,
|
||||
}),
|
||||
).rejects.toThrow('parent parameter is required')
|
||||
const opts = (updatedField?.config as PrismaJson.FieldConfig)?.select?.options || []
|
||||
expect(opts.some((o) => o.displayName === 'Midjourney' && o.id === 'midjourney')).toBe(true)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1966,4 +2108,113 @@ describe('Agent Database Activities Integration', () => {
|
||||
expect(piAgent.createAgentSession).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Nested AGENTS.md prompt injection', () => {
|
||||
it('formatProjectContextPrompt formats context files into XML project_context block', () => {
|
||||
expect(formatProjectContextPrompt([])).toBe('')
|
||||
|
||||
const formatted = formatProjectContextPrompt([
|
||||
{ path: '/AGENTS.md', content: 'Root rules' },
|
||||
{ path: '/subfolder/AGENTS.md', content: 'Subfolder rules' },
|
||||
])
|
||||
|
||||
expect(formatted).toBe(
|
||||
'\n\n<project_context>\n\nProject-specific instructions and guidelines:\n\n<project_instructions path="/AGENTS.md">\nRoot rules\n</project_instructions>\n\n<project_instructions path="/subfolder/AGENTS.md">\nSubfolder rules\n</project_instructions>\n\n</project_context>',
|
||||
)
|
||||
})
|
||||
|
||||
it('agentChatActivity injects nested AGENTS.md instructions into systemPrompt', async () => {
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'User_Chat_Md', email: `chat-md-${Date.now()}@example.com` },
|
||||
})
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Team_Chat_Md_' + Date.now() },
|
||||
})
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Project_Chat_Md', teamId: team.id },
|
||||
})
|
||||
const rootFolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'Root',
|
||||
type: AssetType.root,
|
||||
projectId: project.id,
|
||||
status: AssetStatus.uploaded,
|
||||
},
|
||||
})
|
||||
await prisma.assetAgentMd.create({
|
||||
data: {
|
||||
assetId: rootFolder.id,
|
||||
content: '# Root Policy',
|
||||
},
|
||||
})
|
||||
const subfolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'subfolder',
|
||||
type: AssetType.folder,
|
||||
parentId: rootFolder.id,
|
||||
projectId: project.id,
|
||||
status: AssetStatus.uploaded,
|
||||
},
|
||||
})
|
||||
await prisma.assetAgentMd.create({
|
||||
data: {
|
||||
assetId: subfolder.id,
|
||||
content: '# Subfolder Policy',
|
||||
},
|
||||
})
|
||||
|
||||
const mockHarness = {
|
||||
subscribe: vi.fn(),
|
||||
prompt: vi.fn().mockResolvedValue({
|
||||
content: [{ type: 'text', text: 'Chat reply' }],
|
||||
usage: { input: 10, output: 20 },
|
||||
}),
|
||||
}
|
||||
const mockSession = {
|
||||
getEntries: vi.fn().mockResolvedValue([]),
|
||||
getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }),
|
||||
}
|
||||
|
||||
vi.mocked(piAgent.createAgentSession).mockResolvedValue({
|
||||
session: mockSession as unknown as Session<DatabaseSessionMetadata>,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Mock AgentHarness instance for activity test
|
||||
harness: mockHarness as unknown as AgentHarness<any, any, any, any>,
|
||||
})
|
||||
|
||||
const context = {
|
||||
agent: { id: 'agent-1', provider: { name: 'google' }, modelRef: { modelId: 'gemini' } },
|
||||
dbProviders: [],
|
||||
teamSkills: [],
|
||||
allowedDomains: [],
|
||||
} as unknown as AgentExecutionContext
|
||||
|
||||
await agentChatActivity({
|
||||
teamId: team.id,
|
||||
agentId: 'agent-1',
|
||||
message: 'Hello',
|
||||
imageUrls: [],
|
||||
projectId: project.id,
|
||||
folderId: subfolder.id,
|
||||
assetId: subfolder.id,
|
||||
sessionId: 'mock-session-id',
|
||||
userId: user.id,
|
||||
context,
|
||||
})
|
||||
|
||||
expect(piAgent.createAgentSession).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
systemPrompt: expect.stringContaining('<project_context>'),
|
||||
}),
|
||||
)
|
||||
|
||||
const lastCall = vi.mocked(piAgent.createAgentSession).mock.calls.at(-1)
|
||||
const systemPromptArg = lastCall?.[0].systemPrompt as string
|
||||
expect(systemPromptArg).toContain(
|
||||
'<project_instructions path="/AGENTS.md">\n# Root Policy\n</project_instructions>',
|
||||
)
|
||||
expect(systemPromptArg).toContain(
|
||||
'<project_instructions path="/subfolder/AGENTS.md">\n# Subfolder Policy\n</project_instructions>',
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -5,13 +5,20 @@ import {
|
||||
} from '@earendil-works/pi-agent-core'
|
||||
import { type ImageContent } from '@earendil-works/pi-ai'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import {
|
||||
authzService,
|
||||
Permission,
|
||||
ResourceType,
|
||||
resolveEffectiveRole,
|
||||
} from '@shumai/core/src/authz/authz'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { mcpService } from '@shumai/core/src/mcp/mcp-service'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { encodeCursor, paginateQuery } from '@shumai/core/src/pagination'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { uploadService } from '@shumai/core/src/upload/upload'
|
||||
import { VersionStackService } from '@shumai/core/src/versionStack/versionStack'
|
||||
import { getAgentRequiredLevel, getRoleLevel } from '@shumai/core/src/agent/permissions'
|
||||
import { AssetType, prisma, Prisma, type Skill } from '@shumai/db'
|
||||
import { registerLocalCancelHandler, unregisterLocalCancelHandler } from '@shumai/workflow-core'
|
||||
import { ApplicationFailure, Context } from '@temporalio/activity'
|
||||
@@ -26,6 +33,7 @@ import {
|
||||
} from '../index'
|
||||
|
||||
import { aiUsageService } from '@shumai/core/src/ai-usage/ai-usage'
|
||||
import { quotaService, QuotaExceededError } from '@shumai/core/src/quota/quota-service'
|
||||
import { UpdateAssetMetadataRequest } from '@shumai/dtos'
|
||||
|
||||
export interface Usage {
|
||||
@@ -41,6 +49,11 @@ export type AgentWithProviderAndModel = Prisma.AgentGetPayload<{
|
||||
include: {
|
||||
provider: true
|
||||
modelRef: true
|
||||
skills: {
|
||||
include: {
|
||||
skill: true
|
||||
}
|
||||
}
|
||||
}
|
||||
}>
|
||||
|
||||
@@ -54,9 +67,23 @@ export interface AgentExecutionContext {
|
||||
agent: AgentWithProviderAndModel
|
||||
dbProviders: DbProviderWithModels[]
|
||||
teamSkills: Skill[]
|
||||
mcpServers: Prisma.McpServerGetPayload<Record<string, never>>[]
|
||||
enabledSkillIds: string[]
|
||||
allowedDomains: string[]
|
||||
}
|
||||
|
||||
export function formatProjectContextPrompt(
|
||||
contextFiles: Array<{ path: string; content: string }>,
|
||||
): string {
|
||||
if (contextFiles.length === 0) return ''
|
||||
let prompt = '\n\n<project_context>\n\nProject-specific instructions and guidelines:\n\n'
|
||||
for (const { path: filePath, content } of contextFiles) {
|
||||
prompt += `<project_instructions path="${filePath}">\n${content}\n</project_instructions>\n\n`
|
||||
}
|
||||
prompt += '</project_context>'
|
||||
return prompt
|
||||
}
|
||||
|
||||
async function executeAgentPrompt(params: {
|
||||
taskId?: string
|
||||
teamId: string
|
||||
@@ -66,12 +93,14 @@ async function executeAgentPrompt(params: {
|
||||
agentsInstruction: string
|
||||
sessionId?: string
|
||||
userId?: string
|
||||
projectId?: string
|
||||
assetId?: string
|
||||
userCommentId?: string | null
|
||||
tools?: AgentTool[]
|
||||
context: AgentExecutionContext
|
||||
attachedAssets?: Array<{ id: string; name: string; type: string }>
|
||||
}): Promise<{ text: string; usage: Usage; sessionId: string }> {
|
||||
const { agent, dbProviders, teamSkills, allowedDomains } = params.context
|
||||
const { agent, dbProviders, teamSkills, enabledSkillIds, allowedDomains } = params.context
|
||||
|
||||
if (!agent.provider) {
|
||||
throw ApplicationFailure.create({
|
||||
@@ -96,7 +125,7 @@ shumai has its own cloud file system. If a user asks you to perform file system
|
||||
|
||||
If you need to create files in the local filesystem (for example, a temporary file for uploading), only the '.pi' folder in the current directory has write permissions. Do NOT attempt to create files in any other directories.
|
||||
|
||||
When creating a file or version, first use 'list_autofill_fields' to inspect the project's AI-autofillable metadata fields. If relevant metadata depends on information unavailable from the file content (for example, the AI model or prompt used to generate the asset), include a context in the 'context' field of 'create_file' or 'create_version'. Keep the context short and only include information relevant to those fields.`
|
||||
When creating a file or version, you may attach metadata (for example, the AI model or prompt used to generate the asset). The allowed field keys and value types are declared directly in the 'metadata' parameter of the 'create_file' and 'create_version' tools.`
|
||||
|
||||
if (agent.soul) {
|
||||
systemPrompt = `${systemPrompt}\n\nAgent Personality and Core Instructions:\n${agent.soul}`
|
||||
@@ -105,6 +134,40 @@ When creating a file or version, first use 'list_autofill_fields' to inspect the
|
||||
// Note: params.agentsInstruction is no longer appended to systemPrompt here.
|
||||
// Instead, it is persisted as a custom message session entry in the conversation history below.
|
||||
|
||||
let targetAssetId = params.assetId
|
||||
if (!targetAssetId) {
|
||||
if (params.userCommentId) {
|
||||
const comment = await prisma.assetComment.findUnique({
|
||||
where: { id: params.userCommentId },
|
||||
select: { assetId: true },
|
||||
})
|
||||
if (comment?.assetId) {
|
||||
targetAssetId = comment.assetId
|
||||
}
|
||||
} else if (params.taskId) {
|
||||
const task = await prisma.workflowTask.findUnique({
|
||||
where: { id: params.taskId },
|
||||
select: { assetId: true },
|
||||
})
|
||||
if (task?.assetId) {
|
||||
targetAssetId = task.assetId
|
||||
}
|
||||
} else if (params.projectId) {
|
||||
const project = await prisma.project.findUnique({
|
||||
where: { id: params.projectId },
|
||||
select: { rootFolderId: true },
|
||||
})
|
||||
if (project?.rootFolderId) {
|
||||
targetAssetId = project.rootFolderId
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const contextFiles = targetAssetId ? await assetService.getNestedAgentsMd(targetAssetId) : []
|
||||
if (contextFiles.length > 0) {
|
||||
systemPrompt += formatProjectContextPrompt(contextFiles)
|
||||
}
|
||||
|
||||
const modelConfig = agent.modelRef?.config
|
||||
if (modelConfig?.input) {
|
||||
systemPrompt += `\n\nYour current model supports the following input types: ${modelConfig.input.join(', ')}.`
|
||||
@@ -113,6 +176,18 @@ When creating a file or version, first use 'list_autofill_fields' to inspect the
|
||||
const agentConfig = agent.config as PrismaJson.AgentConfig | null | undefined
|
||||
const thinkingLevel = agentConfig?.thinkingLevel || 'off'
|
||||
|
||||
// MCP tools are only wired to chat agents (D6); autofill/embedding/naming
|
||||
// sessions never receive MCP tools even if a server is assigned.
|
||||
const mcpTools =
|
||||
agent.type === 'chat'
|
||||
? await mcpService.buildAgentTools(
|
||||
params.agentId,
|
||||
params.teamId,
|
||||
params.userId,
|
||||
params.projectId,
|
||||
)
|
||||
: []
|
||||
|
||||
const { session, harness } = await createAgentSession({
|
||||
teamId: params.teamId,
|
||||
agentId: params.agentId,
|
||||
@@ -125,11 +200,13 @@ When creating a file or version, first use 'list_autofill_fields' to inspect the
|
||||
name: s.name,
|
||||
description: s.description,
|
||||
})),
|
||||
enabledSkillIds,
|
||||
allowedDomains,
|
||||
sessionId: params.sessionId,
|
||||
userId: params.userId,
|
||||
projectId: params.projectId,
|
||||
userCommentId: params.userCommentId,
|
||||
customTools: params.tools || [],
|
||||
customTools: [...(params.tools || []), ...mcpTools],
|
||||
providers: dbProviders.map((p) => ({
|
||||
name: p.name,
|
||||
config: p.config,
|
||||
@@ -221,6 +298,39 @@ When creating a file or version, first use 'list_autofill_fields' to inspect the
|
||||
let grandTotalTokens = 0
|
||||
let totalCost = 0
|
||||
|
||||
const effectiveRole = params.userId
|
||||
? await resolveEffectiveRole(params.teamId, params.projectId, params.userId)
|
||||
: undefined
|
||||
|
||||
try {
|
||||
await quotaService.checkQuota(
|
||||
{
|
||||
teamId: params.teamId,
|
||||
userId: params.userId,
|
||||
role: effectiveRole,
|
||||
resource: 'agent_total_tokens',
|
||||
},
|
||||
0,
|
||||
)
|
||||
await quotaService.checkQuota(
|
||||
{
|
||||
teamId: params.teamId,
|
||||
userId: params.userId,
|
||||
role: effectiveRole,
|
||||
resource: 'agent_cost',
|
||||
},
|
||||
0,
|
||||
)
|
||||
} catch (err) {
|
||||
if (err instanceof QuotaExceededError) {
|
||||
throw ApplicationFailure.create({
|
||||
message: err.message,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
throw err
|
||||
}
|
||||
|
||||
harness.subscribe(async (event) => {
|
||||
if (event.type === 'message_end' && event.message.role === 'assistant') {
|
||||
const assistantMsg = event.message
|
||||
@@ -251,6 +361,29 @@ When creating a file or version, first use 'list_autofill_fields' to inspect the
|
||||
} catch (err) {
|
||||
logger.error({ err }, 'Failed to record AI usage')
|
||||
}
|
||||
|
||||
try {
|
||||
await quotaService.consumeQuota(
|
||||
{
|
||||
teamId: params.teamId,
|
||||
userId: params.userId,
|
||||
role: effectiveRole,
|
||||
resource: 'agent_total_tokens',
|
||||
},
|
||||
totalTokens,
|
||||
)
|
||||
await quotaService.consumeQuota(
|
||||
{
|
||||
teamId: params.teamId,
|
||||
userId: params.userId,
|
||||
role: effectiveRole,
|
||||
resource: 'agent_cost',
|
||||
},
|
||||
cost,
|
||||
)
|
||||
} catch (err) {
|
||||
logger.error({ err }, 'Failed to record quota usage for AI call')
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -263,6 +396,29 @@ When creating a file or version, first use 'list_autofill_fields' to inspect the
|
||||
totalCacheReadTokens = assistantMessage.usage.cacheRead || 0
|
||||
grandTotalTokens = assistantMessage.usage.totalTokens || totalInputTokens + totalOutputTokens
|
||||
totalCost = assistantMessage.usage.cost?.total || 0
|
||||
|
||||
try {
|
||||
await quotaService.consumeQuota(
|
||||
{
|
||||
teamId: params.teamId,
|
||||
userId: params.userId,
|
||||
role: effectiveRole,
|
||||
resource: 'agent_total_tokens',
|
||||
},
|
||||
grandTotalTokens,
|
||||
)
|
||||
await quotaService.consumeQuota(
|
||||
{
|
||||
teamId: params.teamId,
|
||||
userId: params.userId,
|
||||
role: effectiveRole,
|
||||
resource: 'agent_cost',
|
||||
},
|
||||
totalCost,
|
||||
)
|
||||
} catch (err) {
|
||||
logger.error({ err }, 'Failed to record fallback quota usage for AI call')
|
||||
}
|
||||
}
|
||||
|
||||
const sessionEntries = await session.getEntries()
|
||||
@@ -331,6 +487,7 @@ export interface AgentChatParams {
|
||||
imageUrls: string[]
|
||||
projectId: string
|
||||
folderId: string
|
||||
assetId?: string
|
||||
agentsInstruction?: string
|
||||
sessionId: string
|
||||
userId?: string
|
||||
@@ -395,6 +552,8 @@ export async function agentChatActivity(params: AgentChatParams) {
|
||||
agentsInstruction: params.agentsInstruction || '',
|
||||
sessionId,
|
||||
userId: params.userId,
|
||||
projectId: params.projectId,
|
||||
assetId: params.assetId || params.folderId,
|
||||
userCommentId: params.userCommentId,
|
||||
context: params.context,
|
||||
attachedAssets: params.attachedAssets,
|
||||
@@ -406,17 +565,12 @@ export interface AutofillAiParams {
|
||||
images: string[]
|
||||
fields: AutofillField[]
|
||||
context: AgentExecutionContext
|
||||
agentContext?: string
|
||||
assetId?: string
|
||||
projectId?: string
|
||||
}
|
||||
|
||||
export async function autofillAiActivity(params: AutofillAiParams) {
|
||||
let prompt = 'Analyze the provided images and extract metadata.'
|
||||
if (params.agentContext && params.agentContext.trim()) {
|
||||
prompt +=
|
||||
'\n\nAdditional context about this file, provided during creation:\n' +
|
||||
`<context>\n${params.agentContext.trim()}\n</context>\n` +
|
||||
'Use this context to inform your answers, especially for fields that cannot be determined from the images alone (e.g. generation model/source).'
|
||||
}
|
||||
const prompt = 'Analyze the provided images and extract metadata.'
|
||||
const toolSchema = fieldsToTypeBoxSchema(params.fields)
|
||||
let capturedData: Record<string, unknown> | null = null
|
||||
|
||||
@@ -446,6 +600,8 @@ export async function autofillAiActivity(params: AutofillAiParams) {
|
||||
agentsInstruction: '',
|
||||
sessionId: undefined,
|
||||
userId: undefined,
|
||||
projectId: params.projectId,
|
||||
assetId: params.assetId,
|
||||
tools: [autofillTool],
|
||||
context: params.context,
|
||||
})
|
||||
@@ -821,6 +977,8 @@ export async function updateCommentActivity(params: {
|
||||
export async function getAgentChatContextActivity(params: {
|
||||
teamId: string
|
||||
agentId: string
|
||||
userId?: string
|
||||
projectId?: string
|
||||
}): Promise<AgentExecutionContext> {
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: params.teamId },
|
||||
@@ -834,6 +992,11 @@ export async function getAgentChatContextActivity(params: {
|
||||
include: {
|
||||
provider: true,
|
||||
modelRef: true,
|
||||
skills: {
|
||||
include: {
|
||||
skill: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
if (!agent) {
|
||||
@@ -843,6 +1006,18 @@ export async function getAgentChatContextActivity(params: {
|
||||
})
|
||||
}
|
||||
|
||||
if (params.userId) {
|
||||
const effectiveRole = await resolveEffectiveRole(params.teamId, params.projectId, params.userId)
|
||||
const userLevel = getRoleLevel(effectiveRole)
|
||||
const requiredLevel = getAgentRequiredLevel(agent.permission)
|
||||
if (userLevel < requiredLevel) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Permission denied: Insufficient role to use agent "${params.agentId}". Minimum required role is "${agent.permission}".`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (!agent.provider) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'agent has no provider configured',
|
||||
@@ -864,20 +1039,41 @@ export async function getAgentChatContextActivity(params: {
|
||||
include: { models: true },
|
||||
})
|
||||
|
||||
// Fetch team skills
|
||||
const teamSkills = await prisma.skill.findMany({
|
||||
where: { teamId: params.teamId },
|
||||
// Only advertise skills that are explicitly enabled for this agent (agent_skills)
|
||||
// AND permitted for the requesting user's effective role. Disabled or
|
||||
// un-permitted skills must not be listed in the system prompt nor loadable
|
||||
// via read_skill (read_skill keeps its own permission check as a backstop).
|
||||
const enabledSkills = (agent.skills ?? []).map((as) => as.skill)
|
||||
let permittedSkills = enabledSkills
|
||||
if (params.userId) {
|
||||
const effectiveRole = await resolveEffectiveRole(params.teamId, params.projectId, params.userId)
|
||||
if (!effectiveRole) {
|
||||
permittedSkills = []
|
||||
} else {
|
||||
const userLevel = getRoleLevel(effectiveRole)
|
||||
permittedSkills = enabledSkills.filter((s) => (getRoleLevel(s.permission) || 1) <= userLevel)
|
||||
}
|
||||
}
|
||||
const enabledSkillIds = permittedSkills.map((s) => s.id)
|
||||
|
||||
// Fetch the agent's assigned MCP servers
|
||||
const assignments = await prisma.agentMcpServer.findMany({
|
||||
where: { agentId: params.agentId },
|
||||
include: { mcpServer: true },
|
||||
})
|
||||
const mcpServers = assignments.map((a) => a.mcpServer)
|
||||
|
||||
const sandbox = await prisma.sandbox.findUnique({
|
||||
where: { teamId: params.teamId },
|
||||
})
|
||||
const allowedDomains = sandbox?.allowedDomains || []
|
||||
const allowedDomains = sandbox?.networkSandboxEnabled ? sandbox.allowedDomains : ['*']
|
||||
|
||||
return {
|
||||
agent,
|
||||
dbProviders,
|
||||
teamSkills,
|
||||
teamSkills: permittedSkills,
|
||||
mcpServers,
|
||||
enabledSkillIds,
|
||||
allowedDomains,
|
||||
}
|
||||
}
|
||||
@@ -912,6 +1108,11 @@ export async function getAgentAutofillContextActivity(params: {
|
||||
include: {
|
||||
provider: true,
|
||||
modelRef: true,
|
||||
skills: {
|
||||
include: {
|
||||
skill: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
if (!agentWithDetails) {
|
||||
@@ -938,20 +1139,25 @@ export async function getAgentAutofillContextActivity(params: {
|
||||
include: { models: true },
|
||||
})
|
||||
|
||||
// Fetch team skills
|
||||
const teamSkills = await prisma.skill.findMany({
|
||||
where: { teamId: params.teamId },
|
||||
})
|
||||
// Only advertise skills that are explicitly enabled for this agent (agent_skills).
|
||||
// Disabled skills must not be listed in the system prompt nor loadable via read_skill.
|
||||
const enabledSkills = (agentWithDetails.skills ?? []).map((as) => as.skill)
|
||||
const enabledSkillIds = enabledSkills.map((s) => s.id)
|
||||
|
||||
// Autofill agents currently do not use MCP tools.
|
||||
const mcpServers: Prisma.McpServerGetPayload<Record<string, never>>[] = []
|
||||
|
||||
const sandbox = await prisma.sandbox.findUnique({
|
||||
where: { teamId: params.teamId },
|
||||
})
|
||||
const allowedDomains = sandbox?.allowedDomains || []
|
||||
const allowedDomains = sandbox?.networkSandboxEnabled ? sandbox.allowedDomains : ['*']
|
||||
|
||||
return {
|
||||
agent: agentWithDetails,
|
||||
dbProviders,
|
||||
teamSkills,
|
||||
teamSkills: enabledSkills,
|
||||
mcpServers,
|
||||
enabledSkillIds,
|
||||
allowedDomains,
|
||||
}
|
||||
}
|
||||
@@ -1003,15 +1209,7 @@ export async function getCommentActivity(commentId: string) {
|
||||
|
||||
export async function getProjectAutofillFieldsActivity(projectId: string) {
|
||||
const fields = await metadataService.listProjectFields('', projectId)
|
||||
return fields.filter((f) => f.field.aiAutofill).map((f) => f.field)
|
||||
}
|
||||
|
||||
export async function getAssetAutofillContextActivity(assetId: string): Promise<string | null> {
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: assetId },
|
||||
select: { autofillContext: true },
|
||||
})
|
||||
return asset?.autofillContext ?? null
|
||||
return fields.filter((f) => f.field.config?.autofillSource === 'CONTENT').map((f) => f.field)
|
||||
}
|
||||
|
||||
export async function updateAssetMetadataActivity(params: {
|
||||
@@ -1060,7 +1258,37 @@ export interface ExecuteAgentToolParams {
|
||||
userId?: string
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
/**
|
||||
* Validates that every metadata key provided by the agent is a defined
|
||||
* CREATION_CONTEXT field of the project. Unknown keys are rejected with a
|
||||
* non-retryable failure so Temporal does not retry expected validation errors.
|
||||
*/
|
||||
async function validateCreationContextMetadata(
|
||||
userId: string,
|
||||
projectId: string,
|
||||
metadata: Record<string, unknown> | undefined,
|
||||
): Promise<void> {
|
||||
if (!metadata || Object.keys(metadata).length === 0) return
|
||||
|
||||
const fields = await metadataService.listProjectFields(userId, projectId)
|
||||
const allowedKeys = new Set(
|
||||
fields
|
||||
.filter((f) => f.field.config?.autofillSource === 'CREATION_CONTEXT')
|
||||
.map((f) => f.field.key),
|
||||
)
|
||||
const invalidKeys = Object.keys(metadata).filter((key) => !allowedKeys.has(key))
|
||||
if (invalidKeys.length > 0) {
|
||||
throw ApplicationFailure.create({
|
||||
message:
|
||||
`metadata contains keys that are not valid in this project: ${invalidKeys.join(', ')}. ` +
|
||||
"The valid metadata fields are fixed to the current conversation's project. " +
|
||||
'If the target folder or file belongs to a different project, call the tool WITHOUT the metadata parameter.',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Activity return type is a union of tool result shapes
|
||||
export async function executeAgentToolActivity(params: ExecuteAgentToolParams): Promise<any> {
|
||||
const { toolName, args, userId } = params
|
||||
if (!userId) {
|
||||
@@ -1134,13 +1362,35 @@ export async function executeAgentToolActivity(params: ExecuteAgentToolParams):
|
||||
{ first: limit, after },
|
||||
)
|
||||
|
||||
const stackIds = assets.filter((a) => a.type === AssetType.version_stack).map((a) => a.id)
|
||||
|
||||
const latestVersionsMap = new Map<string, Prisma.AssetGetPayload<Record<string, never>>>()
|
||||
|
||||
if (stackIds.length > 0) {
|
||||
const versions = await prisma.asset.findMany({
|
||||
where: { parentId: { in: stackIds }, isDeleted: false },
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
})
|
||||
for (const v of versions) {
|
||||
if (!latestVersionsMap.has(v.parentId!)) {
|
||||
latestVersionsMap.set(v.parentId!, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// return asset id, asset name, asset type, asset size (sizeByte or size)
|
||||
const results = assets.map((a) => ({
|
||||
id: a.id,
|
||||
name: a.name,
|
||||
type: a.type,
|
||||
size: Number(a.sizeByte),
|
||||
}))
|
||||
const results = assets.map((a) => {
|
||||
const latestVersion = latestVersionsMap.get(a.id)
|
||||
return {
|
||||
id: a.id,
|
||||
name: a.type === AssetType.version_stack ? (latestVersion?.name ?? a.name) : a.name,
|
||||
type: a.type,
|
||||
size:
|
||||
a.type === AssetType.version_stack && latestVersion
|
||||
? Number(latestVersion.sizeByte)
|
||||
: Number(a.sizeByte),
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
assets: results,
|
||||
@@ -1187,7 +1437,10 @@ export async function executeAgentToolActivity(params: ExecuteAgentToolParams):
|
||||
const name = args.name as string
|
||||
const fileSize = args.size as number
|
||||
const mimeType = args.contentType as string
|
||||
const context = typeof args.context === 'string' ? args.context : undefined
|
||||
const metadata =
|
||||
typeof args.metadata === 'object' && args.metadata !== null
|
||||
? (args.metadata as Record<string, unknown>)
|
||||
: undefined
|
||||
if (!parent || !s3Key || !name || fileSize === undefined || !mimeType) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'parent, s3Key, name, size, and contentType parameters are required',
|
||||
@@ -1221,6 +1474,9 @@ export async function executeAgentToolActivity(params: ExecuteAgentToolParams):
|
||||
})
|
||||
}
|
||||
|
||||
// Validate that any provided metadata keys are defined CREATION_CONTEXT fields
|
||||
await validateCreationContextMetadata(userId, parentAsset.projectId, metadata)
|
||||
|
||||
// Create asset via assetService
|
||||
const newFile = await assetService.createAsset({
|
||||
name,
|
||||
@@ -1237,12 +1493,14 @@ export async function executeAgentToolActivity(params: ExecuteAgentToolParams):
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await assetService.updateAncestorsSize(tx as any, parent, fileSize)
|
||||
|
||||
// Persist autofill context provided by the agent (used by the autofill workflow)
|
||||
if (context) {
|
||||
await tx.asset.update({
|
||||
where: { id: newFile.id },
|
||||
data: { autofillContext: context },
|
||||
})
|
||||
// Persist creation context metadata provided by the agent
|
||||
if (metadata) {
|
||||
const metadataUpdates = Object.entries(metadata)
|
||||
.filter(([, value]) => value !== null)
|
||||
.map(([key, value]) => ({ key, value }))
|
||||
if (metadataUpdates.length > 0) {
|
||||
await metadataService.updateAssetMetadataInTx(tx, newFile.id, metadataUpdates)
|
||||
}
|
||||
}
|
||||
|
||||
// Trigger post-upload transcode and AI workflows
|
||||
@@ -1268,7 +1526,10 @@ export async function executeAgentToolActivity(params: ExecuteAgentToolParams):
|
||||
const name = args.name as string
|
||||
const fileSize = args.size as number
|
||||
const mimeType = args.contentType as string
|
||||
const context = typeof args.context === 'string' ? args.context : undefined
|
||||
const metadata =
|
||||
typeof args.metadata === 'object' && args.metadata !== null
|
||||
? (args.metadata as Record<string, unknown>)
|
||||
: undefined
|
||||
if (!parent || !s3Key || !name || fileSize === undefined || !mimeType) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'parent, s3Key, name, size, and contentType parameters are required',
|
||||
@@ -1294,6 +1555,9 @@ export async function executeAgentToolActivity(params: ExecuteAgentToolParams):
|
||||
})
|
||||
}
|
||||
|
||||
// Validate that any provided metadata keys are defined CREATION_CONTEXT fields
|
||||
await validateCreationContextMetadata(userId, parentFile.projectId, metadata)
|
||||
|
||||
// Authz check: verify Edit permission on the parent file (resource ID is parent file id)
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
@@ -1333,12 +1597,14 @@ export async function executeAgentToolActivity(params: ExecuteAgentToolParams):
|
||||
where: { id: newFile.id },
|
||||
data: { sortIndex: newSortIndex },
|
||||
})
|
||||
// Persist autofill context provided by the agent (used by the autofill workflow)
|
||||
if (context) {
|
||||
await tx.asset.update({
|
||||
where: { id: newFile.id },
|
||||
data: { autofillContext: context },
|
||||
})
|
||||
// Persist creation context metadata provided by the agent
|
||||
if (metadata) {
|
||||
const metadataUpdates = Object.entries(metadata)
|
||||
.filter(([, value]) => value !== null)
|
||||
.map(([key, value]) => ({ key, value }))
|
||||
if (metadataUpdates.length > 0) {
|
||||
await metadataService.updateAssetMetadataInTx(tx, newFile.id, metadataUpdates)
|
||||
}
|
||||
}
|
||||
// Increment stack's size (fileCount is incremented by createAsset already)
|
||||
const updatedStack = await tx.asset.update({
|
||||
@@ -1398,12 +1664,14 @@ export async function executeAgentToolActivity(params: ExecuteAgentToolParams):
|
||||
projectId: parentFile.projectId!,
|
||||
creatorId: userId,
|
||||
})
|
||||
// Persist autofill context provided by the agent (used by the autofill workflow)
|
||||
if (context) {
|
||||
await tx.asset.update({
|
||||
where: { id: newFile.id },
|
||||
data: { autofillContext: context },
|
||||
})
|
||||
// Persist creation context metadata provided by the agent
|
||||
if (metadata) {
|
||||
const metadataUpdates = Object.entries(metadata)
|
||||
.filter(([, value]) => value !== null)
|
||||
.map(([key, value]) => ({ key, value }))
|
||||
if (metadataUpdates.length > 0) {
|
||||
await metadataService.updateAssetMetadataInTx(tx, newFile.id, metadataUpdates)
|
||||
}
|
||||
}
|
||||
// Update ancestors' size (add size of the new file version)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
@@ -1427,49 +1695,6 @@ export async function executeAgentToolActivity(params: ExecuteAgentToolParams):
|
||||
}
|
||||
}
|
||||
|
||||
case 'list_autofill_fields': {
|
||||
const parent = args.parent
|
||||
if (!parent) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'parent parameter is required',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
// Authz check
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: parent,
|
||||
})
|
||||
|
||||
// Resolve projectId from the parent asset (climb ancestor chain if needed)
|
||||
const projectId = await resolveAssetProjectId(parent)
|
||||
if (!projectId) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Could not resolve project for parent: ${parent}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const fields = await metadataService.listProjectFields(userId, projectId)
|
||||
const autofillFields = fields
|
||||
.filter((f) => f.field.aiAutofill)
|
||||
.map((f) => ({
|
||||
name: f.field.config?.name,
|
||||
type: f.field.config?.type,
|
||||
description: f.field.description,
|
||||
options: (
|
||||
f.field.config?.select?.options ??
|
||||
f.field.config?.selectMulti?.options ??
|
||||
[]
|
||||
).map((o) => ({ displayName: o.displayName })),
|
||||
}))
|
||||
|
||||
return { fields: autofillFields }
|
||||
}
|
||||
|
||||
default:
|
||||
throw ApplicationFailure.create({
|
||||
message: `Unsupported tool name: ${toolName}`,
|
||||
@@ -1478,21 +1703,6 @@ export async function executeAgentToolActivity(params: ExecuteAgentToolParams):
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveAssetProjectId(assetId: string): Promise<string | null> {
|
||||
let currentId: string | null = assetId
|
||||
while (currentId) {
|
||||
/* prettier-ignore */
|
||||
const assetNode = (await prisma.asset.findUnique({
|
||||
where: { id: currentId },
|
||||
select: { id: true, projectId: true, parentId: true },
|
||||
})) as { id: string; projectId: string | null; parentId: string | null } | null
|
||||
if (!assetNode) break
|
||||
if (assetNode.projectId) return assetNode.projectId
|
||||
currentId = assetNode.parentId
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export interface GenerateSessionNameParams {
|
||||
teamId: string
|
||||
agentId: string
|
||||
|
||||
@@ -8,8 +8,11 @@ import {
|
||||
} from './index'
|
||||
import { createSandboxedBashTool } from './tools/sandboxed-bash'
|
||||
import { SandboxManager, type SandboxAskCallback } from '@anthropic-ai/sandbox-runtime'
|
||||
import { quotaService } from '@shumai/core/src/quota/quota-service'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { type TSchema } from 'typebox'
|
||||
import { Value } from 'typebox/value'
|
||||
import * as path from 'path'
|
||||
import * as childProcess from 'node:child_process'
|
||||
import * as fs from 'fs'
|
||||
@@ -89,10 +92,16 @@ describe('Sandbox Network isolation integration', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
it('should register callback that pushes blocked hosts to database and propagates to bash tool', async () => {
|
||||
// 1. Create a team
|
||||
// 1. Create a team and enabled sandbox
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Test Sandbox Team' },
|
||||
})
|
||||
await prisma.sandbox.create({
|
||||
data: {
|
||||
teamId: team.id,
|
||||
networkSandboxEnabled: true,
|
||||
},
|
||||
})
|
||||
|
||||
// Ensure agent user and agent exist in database to avoid foreign key violation
|
||||
await prisma.user.create({
|
||||
@@ -198,6 +207,12 @@ describe('Sandbox Network isolation integration', () => {
|
||||
const team2 = await prisma.team.create({
|
||||
data: { name: 'Team 2' },
|
||||
})
|
||||
await prisma.sandbox.create({
|
||||
data: { teamId: team1.id, networkSandboxEnabled: true },
|
||||
})
|
||||
await prisma.sandbox.create({
|
||||
data: { teamId: team2.id, networkSandboxEnabled: true },
|
||||
})
|
||||
|
||||
// Ensure agent user and agents exist in database
|
||||
await prisma.user.create({
|
||||
@@ -290,6 +305,64 @@ describe('Sandbox Network isolation integration', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('should bypass domain blocking and pending domain recording when networkSandboxEnabled is false', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Disabled Sandbox Team' },
|
||||
})
|
||||
await prisma.sandbox.create({
|
||||
data: { teamId: team.id, networkSandboxEnabled: false },
|
||||
})
|
||||
|
||||
await prisma.user.create({
|
||||
data: {
|
||||
id: 'agent-disabled',
|
||||
name: 'Ai Agent Disabled',
|
||||
email: 'disabled@shumai.ai',
|
||||
type: 'agent',
|
||||
},
|
||||
})
|
||||
await prisma.agent.create({
|
||||
data: {
|
||||
id: 'agent-disabled',
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
config: { provider: 'openai', model: 'gpt-4' },
|
||||
},
|
||||
})
|
||||
|
||||
const initializeSpy = vi.spyOn(SandboxManager, 'initialize').mockResolvedValue()
|
||||
vi.spyOn(SandboxManager, 'wrapWithSandbox').mockImplementation(async (cmd) => cmd)
|
||||
|
||||
await createAgentSession({
|
||||
teamId: team.id,
|
||||
agentId: 'agent-disabled',
|
||||
providerName: 'google',
|
||||
modelId: 'gemini',
|
||||
systemPrompt: 'prompt',
|
||||
teamSkills: [],
|
||||
allowedDomains: ['*'],
|
||||
providers: mockProviders,
|
||||
})
|
||||
|
||||
expect(initializeSpy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
network: expect.objectContaining({
|
||||
allowedDomains: ['*'],
|
||||
}),
|
||||
}),
|
||||
expect.any(Function),
|
||||
)
|
||||
|
||||
const callback = initializeSpy.mock.calls[0][1]
|
||||
const res = await callback!({ host: 'any-external-domain.com', port: 443 })
|
||||
expect(res).toBe(true)
|
||||
|
||||
const sandbox = await prisma.sandbox.findUnique({
|
||||
where: { teamId: team.id },
|
||||
})
|
||||
expect(sandbox?.pendingDomains).toEqual([])
|
||||
})
|
||||
|
||||
it('should pass thinkingLevel to AgentHarness and default to off', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Test Team' },
|
||||
@@ -813,3 +886,374 @@ describe('createAgentSession bash restriction for non-owner users', () => {
|
||||
expect(prompt).not.toContain('# Restricted User Context')
|
||||
})
|
||||
})
|
||||
|
||||
describe('createAgentSession typed metadata schema', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
async function setupSessionWithProject(opts: { withCreationFields: boolean }) {
|
||||
const team = await prisma.team.create({ data: { name: 'Typed Metadata Team' } })
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Typed Metadata Project', teamId: team.id },
|
||||
})
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'Typed Metadata User', email: 'typed-metadata@shumai.ai' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: user.id, role: 'owner' },
|
||||
})
|
||||
await prisma.user.create({
|
||||
data: {
|
||||
id: 'typed-metadata-agent',
|
||||
name: 'Ai Agent Typed Metadata',
|
||||
email: 'typed-metadata-agent@shumai.ai',
|
||||
type: 'agent',
|
||||
},
|
||||
})
|
||||
await prisma.agent.create({
|
||||
data: {
|
||||
id: 'typed-metadata-agent',
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
config: { provider: 'google', model: 'gemini' },
|
||||
},
|
||||
})
|
||||
|
||||
if (opts.withCreationFields) {
|
||||
await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'prompt',
|
||||
scope: 'PROJECT',
|
||||
projectId: project.id,
|
||||
teamId: team.id,
|
||||
config: { name: 'Prompt', type: 'text', autofillSource: 'CREATION_CONTEXT' },
|
||||
},
|
||||
})
|
||||
await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'source',
|
||||
scope: 'PROJECT',
|
||||
projectId: project.id,
|
||||
teamId: team.id,
|
||||
config: {
|
||||
name: 'Source',
|
||||
type: 'select',
|
||||
autofillSource: 'CREATION_CONTEXT',
|
||||
select: {
|
||||
options: [{ id: 'gemini', displayName: 'Gemini', color: '#ffffff' }],
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'manualNotes',
|
||||
scope: 'PROJECT',
|
||||
projectId: project.id,
|
||||
teamId: team.id,
|
||||
config: { name: 'Manual Notes', type: 'text', autofillSource: 'NONE' },
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const initializeSpy = vi.spyOn(SandboxManager, 'initialize').mockResolvedValue()
|
||||
try {
|
||||
const { harness } = await createAgentSession({
|
||||
teamId: team.id,
|
||||
agentId: 'typed-metadata-agent',
|
||||
providerName: 'google',
|
||||
modelId: 'gemini',
|
||||
systemPrompt: 'prompt',
|
||||
teamSkills: [],
|
||||
allowedDomains: [],
|
||||
providers: mockProviders,
|
||||
userId: user.id,
|
||||
projectId: project.id,
|
||||
})
|
||||
return { harness }
|
||||
} finally {
|
||||
initializeSpy.mockRestore()
|
||||
}
|
||||
}
|
||||
|
||||
it('should build create_file/create_version with the project CREATION_CONTEXT fields', async () => {
|
||||
const { harness } = await setupSessionWithProject({ withCreationFields: true })
|
||||
const tools = harness.getTools()
|
||||
|
||||
expect(tools.some((t) => t.name === 'list_autofill_fields')).toBe(false)
|
||||
|
||||
const createFile = tools.find((t) => t.name === 'create_file')
|
||||
const createVersion = tools.find((t) => t.name === 'create_version')
|
||||
expect(createFile).toBeDefined()
|
||||
expect(createVersion).toBeDefined()
|
||||
|
||||
const checkFile = (args: Record<string, unknown>) =>
|
||||
Value.Check(createFile!.parameters as unknown as TSchema, {
|
||||
parent: 'f1',
|
||||
path: '/tmp/x.md',
|
||||
data: null,
|
||||
...args,
|
||||
})
|
||||
const checkVersion = (args: Record<string, unknown>) =>
|
||||
Value.Check(createVersion!.parameters as unknown as TSchema, {
|
||||
parent: 'f1',
|
||||
path: '/tmp/x.md',
|
||||
...args,
|
||||
})
|
||||
|
||||
for (const check of [checkFile, checkVersion]) {
|
||||
// Declared CREATION_CONTEXT fields (all-required, nullable) validate; other keys do not
|
||||
expect(check({ metadata: { prompt: 'hello', source: null } })).toBe(true)
|
||||
expect(check({ metadata: { prompt: null, source: 'gemini' } })).toBe(true)
|
||||
expect(check({ metadata: null })).toBe(true)
|
||||
expect(check({ metadata: { prompt: null, source: null, manualNotes: 'no' } })).toBe(false)
|
||||
expect(check({ metadata: { prompt: null, source: null, bogus: 1 } })).toBe(false)
|
||||
expect(check({ metadata: { prompt: 'hello' } })).toBe(false)
|
||||
}
|
||||
})
|
||||
|
||||
it('should omit the metadata parameter when the project has no CREATION_CONTEXT fields', async () => {
|
||||
const { harness } = await setupSessionWithProject({ withCreationFields: false })
|
||||
const createFile = harness.getTools().find((t) => t.name === 'create_file')
|
||||
const createVersion = harness.getTools().find((t) => t.name === 'create_version')
|
||||
expect(createFile).toBeDefined()
|
||||
expect(createVersion).toBeDefined()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- inspecting the runtime schema shape of the dynamically-built tool
|
||||
const fileProps = (createFile!.parameters as any).properties
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- inspecting the runtime schema shape of the dynamically-built tool
|
||||
const versionProps = (createVersion!.parameters as any).properties
|
||||
expect('metadata' in fileProps).toBe(false)
|
||||
expect('metadata' in versionProps).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('createAgentSession enabled skill filtering', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('should only advertise and allow reading skills enabled for the agent', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Skill Filter Team' } })
|
||||
|
||||
const enabledSkill = await prisma.skill.create({
|
||||
data: {
|
||||
name: 'Enabled Skill',
|
||||
assetId: 'asset-enabled',
|
||||
hash: 'enabled-hash',
|
||||
teamId: team.id,
|
||||
},
|
||||
})
|
||||
const disabledSkill = await prisma.skill.create({
|
||||
data: {
|
||||
name: 'Disabled Skill',
|
||||
assetId: 'asset-disabled',
|
||||
hash: 'disabled-hash',
|
||||
teamId: team.id,
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.user.create({
|
||||
data: {
|
||||
id: 'skill-filter-agent',
|
||||
name: 'Ai Agent Skill Filter',
|
||||
email: 'skill-filter-agent@shumai.ai',
|
||||
type: 'agent',
|
||||
},
|
||||
})
|
||||
await prisma.agent.create({
|
||||
data: {
|
||||
id: 'skill-filter-agent',
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
config: { provider: 'google', model: 'gemini' },
|
||||
skills: {
|
||||
create: [{ skillId: enabledSkill.id }],
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const initializeSpy = vi.spyOn(SandboxManager, 'initialize').mockResolvedValue()
|
||||
try {
|
||||
const { harness } = await createAgentSession({
|
||||
teamId: team.id,
|
||||
agentId: 'skill-filter-agent',
|
||||
providerName: 'google',
|
||||
modelId: 'gemini',
|
||||
systemPrompt: 'prompt',
|
||||
teamSkills: [{ id: enabledSkill.id, name: enabledSkill.name }],
|
||||
enabledSkillIds: [enabledSkill.id],
|
||||
allowedDomains: [],
|
||||
providers: mockProviders,
|
||||
})
|
||||
|
||||
// The disabled skill must not be advertised in the available skills list
|
||||
// @ts-expect-error accessing private property for verification
|
||||
const prompt = await harness.systemPrompt()
|
||||
expect(prompt).toContain(enabledSkill.id)
|
||||
expect(prompt).not.toContain(disabledSkill.id)
|
||||
|
||||
// read_skill must reject the disabled skill id
|
||||
const readSkillTool = harness.getTools().find((t) => t.name === 'read_skill')
|
||||
expect(readSkillTool).toBeDefined()
|
||||
|
||||
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs readFileSync which has complex overloaded signatures
|
||||
vi.spyOn(fs, 'readFileSync').mockImplementation((p: any) => {
|
||||
if (p.toString().endsWith('.hash')) return 'enabled-hash'
|
||||
if (p.toString().endsWith('SKILL.md')) return '# Enabled Skill'
|
||||
return ''
|
||||
})
|
||||
|
||||
await expect(
|
||||
readSkillTool!.execute('1', { skillId: disabledSkill.id }, undefined, undefined, undefined),
|
||||
).rejects.toThrow('not enabled for this agent')
|
||||
|
||||
const result = await readSkillTool!.execute(
|
||||
'1',
|
||||
{ skillId: enabledSkill.id },
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
expect((result.content[0] as any).text).toBe('# Enabled Skill')
|
||||
} finally {
|
||||
initializeSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('should reject all read_skill calls when no skills are enabled for the agent', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Skill None Team' } })
|
||||
const skill = await prisma.skill.create({
|
||||
data: { name: 'Unassigned Skill', assetId: 'asset-none', hash: 'none-hash', teamId: team.id },
|
||||
})
|
||||
|
||||
await prisma.user.create({
|
||||
data: {
|
||||
id: 'skill-none-agent',
|
||||
name: 'Ai Agent Skill None',
|
||||
email: 'skill-none-agent@shumai.ai',
|
||||
type: 'agent',
|
||||
},
|
||||
})
|
||||
await prisma.agent.create({
|
||||
data: {
|
||||
id: 'skill-none-agent',
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
config: { provider: 'google', model: 'gemini' },
|
||||
},
|
||||
})
|
||||
|
||||
const initializeSpy = vi.spyOn(SandboxManager, 'initialize').mockResolvedValue()
|
||||
try {
|
||||
const { harness } = await createAgentSession({
|
||||
teamId: team.id,
|
||||
agentId: 'skill-none-agent',
|
||||
providerName: 'google',
|
||||
modelId: 'gemini',
|
||||
systemPrompt: 'prompt',
|
||||
teamSkills: [],
|
||||
enabledSkillIds: [],
|
||||
allowedDomains: [],
|
||||
providers: mockProviders,
|
||||
})
|
||||
|
||||
const readSkillTool = harness.getTools().find((t) => t.name === 'read_skill')
|
||||
expect(readSkillTool).toBeDefined()
|
||||
|
||||
await expect(
|
||||
readSkillTool!.execute('1', { skillId: skill.id }, undefined, undefined, undefined),
|
||||
).rejects.toThrow('not enabled for this agent')
|
||||
} finally {
|
||||
initializeSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('enforces agent tool call count quota on tool execution', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Tool Quota Enforcement Team' } })
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'Member User', email: 'member-tool-quota@shumai.ai', password: 'pw' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: user.id, role: 'editor' },
|
||||
})
|
||||
await prisma.user.create({
|
||||
data: {
|
||||
id: 'tool-quota-agent',
|
||||
name: 'Tool Quota Agent',
|
||||
email: 'tool-quota-agent@shumai.ai',
|
||||
type: 'agent',
|
||||
},
|
||||
})
|
||||
await prisma.agent.create({
|
||||
data: {
|
||||
id: 'tool-quota-agent',
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
config: { provider: 'google', model: 'gemini' },
|
||||
},
|
||||
})
|
||||
|
||||
await quotaService.createRule(team.id, {
|
||||
scopeMode: 'all_members',
|
||||
resource: 'agent_tool_call_count',
|
||||
resourceData: { name: 'read_thread' },
|
||||
limit: 1,
|
||||
period: '1hour',
|
||||
enabled: true,
|
||||
})
|
||||
|
||||
const initializeSpy = vi.spyOn(SandboxManager, 'initialize').mockResolvedValue()
|
||||
try {
|
||||
const { harness } = await createAgentSession({
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
agentId: 'tool-quota-agent',
|
||||
providerName: 'google',
|
||||
modelId: 'gemini',
|
||||
systemPrompt: 'prompt',
|
||||
teamSkills: [],
|
||||
enabledSkillIds: [],
|
||||
allowedDomains: [],
|
||||
providers: mockProviders,
|
||||
})
|
||||
|
||||
const readThreadTool = harness.getTools().find((t) => t.name === 'read_thread')
|
||||
expect(readThreadTool).toBeDefined()
|
||||
|
||||
// First call executes and consumes quota
|
||||
const res1 = await readThreadTool!.execute(
|
||||
'call-1',
|
||||
{ threadId: 'non-existent' },
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
)
|
||||
expect(res1).toBeDefined()
|
||||
|
||||
// Second call exceeds quota and returns error
|
||||
const res2 = await readThreadTool!.execute(
|
||||
'call-2',
|
||||
{ threadId: 'non-existent' },
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
)
|
||||
expect(res2).toBeDefined()
|
||||
const textContent = res2.content[0]
|
||||
if (textContent && textContent.type === 'text') {
|
||||
expect(textContent.text).toContain('Quota exceeded')
|
||||
} else {
|
||||
expect.unreachable('Expected text content')
|
||||
}
|
||||
} finally {
|
||||
initializeSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
+162
-52
@@ -9,15 +9,18 @@ import type { Api, Model } from '@earendil-works/pi-ai'
|
||||
import { createModels, InMemoryCredentialStore } from '@earendil-works/pi-ai'
|
||||
import { builtinProviders } from '@earendil-works/pi-ai/providers/all'
|
||||
import { agentService } from '@shumai/core/src/agent/agent'
|
||||
import { prisma, type TeamMemberRole } from '@shumai/db'
|
||||
import { Type, type TSchema } from '@sinclair/typebox'
|
||||
import { resolveEffectiveRole } from '@shumai/core/src/authz/authz'
|
||||
import { quotaService, QuotaExceededError } from '@shumai/core/src/quota/quota-service'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { Type, type TSchema } from 'typebox'
|
||||
import * as fs from 'fs'
|
||||
import * as os from 'os'
|
||||
import * as path from 'path'
|
||||
import { DatabaseSessionStorage } from './database-session-storage'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { createAnalyzeImageTool } from './tools/analyze-image'
|
||||
import { createCreateFileTool } from './tools/create-file'
|
||||
import { createListAutofillFieldsTool } from './tools/list-autofill-fields'
|
||||
import { createCreateFolderTool } from './tools/create-folder'
|
||||
import { createCreateVersionTool } from './tools/create-version'
|
||||
import { createDownloadAssetTool } from './tools/download-asset'
|
||||
@@ -98,9 +101,11 @@ export interface CreateAgentSessionParams {
|
||||
modelId: string
|
||||
systemPrompt: string
|
||||
teamSkills: Array<{ id: string; name: string; description?: string | null }>
|
||||
enabledSkillIds?: string[]
|
||||
allowedDomains: string[]
|
||||
sessionId?: string
|
||||
userId?: string
|
||||
projectId?: string
|
||||
userCommentId?: string | null
|
||||
customTools?: AgentTool[]
|
||||
thinkingLevel?: string
|
||||
@@ -110,18 +115,6 @@ export interface CreateAgentSessionParams {
|
||||
baseDelayMs?: number
|
||||
}
|
||||
|
||||
async function resolveTeamMemberRole(
|
||||
teamId: string,
|
||||
userId?: string,
|
||||
): Promise<TeamMemberRole | undefined> {
|
||||
if (!userId) return undefined
|
||||
const member = await prisma.teamMember.findUnique({
|
||||
where: { teamIdUserId: { teamId, userId } },
|
||||
select: { role: true },
|
||||
})
|
||||
return member?.role
|
||||
}
|
||||
|
||||
/**
|
||||
* Security instructions appended to the system prompt when the requesting user is not a team
|
||||
* owner (i.e. editor/reviewer). These complement the hard enforcement in the bash tool itself
|
||||
@@ -145,9 +138,11 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
modelId,
|
||||
systemPrompt,
|
||||
teamSkills,
|
||||
enabledSkillIds,
|
||||
allowedDomains,
|
||||
sessionId,
|
||||
userId,
|
||||
projectId,
|
||||
userCommentId: passedUserCommentId,
|
||||
customTools = [],
|
||||
thinkingLevel,
|
||||
@@ -181,11 +176,17 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
blockedHost: '',
|
||||
}
|
||||
|
||||
const role = userId ? await resolveEffectiveRole(teamId, projectId, userId) : undefined
|
||||
const isOwner = !userId || role === 'owner'
|
||||
const restricted = !isOwner
|
||||
const sandboxAskCallback = async ({ host }: { host: string; port?: number }) => {
|
||||
try {
|
||||
const sandbox = await prisma.sandbox.findUnique({
|
||||
where: { teamId },
|
||||
})
|
||||
if (sandbox && !sandbox.networkSandboxEnabled) {
|
||||
return true
|
||||
}
|
||||
const pendingDomains = sandbox?.pendingDomains || []
|
||||
if (!pendingDomains.includes(host)) {
|
||||
await prisma.sandbox.upsert({
|
||||
@@ -210,6 +211,54 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
return false
|
||||
}
|
||||
|
||||
const wrapToolWithQuota = (tool: AgentTool): AgentTool => {
|
||||
const originalExecute = tool.execute
|
||||
return {
|
||||
...tool,
|
||||
execute: async (toolCallId, args, signal, onUpdate) => {
|
||||
try {
|
||||
await quotaService.checkQuota(
|
||||
{
|
||||
teamId,
|
||||
userId,
|
||||
role,
|
||||
resource: 'agent_tool_call_count',
|
||||
resourceData: { name: tool.name, toolName: tool.name },
|
||||
},
|
||||
1,
|
||||
)
|
||||
} catch (err) {
|
||||
if (err instanceof QuotaExceededError) {
|
||||
return {
|
||||
content: [{ type: 'text', text: `Quota exceeded: ${err.message}` }],
|
||||
details: { error: err.message },
|
||||
}
|
||||
}
|
||||
throw err
|
||||
}
|
||||
|
||||
const result = await originalExecute(toolCallId, args, signal, onUpdate)
|
||||
|
||||
try {
|
||||
await quotaService.consumeQuota(
|
||||
{
|
||||
teamId,
|
||||
userId,
|
||||
role,
|
||||
resource: 'agent_tool_call_count',
|
||||
resourceData: { name: tool.name, toolName: tool.name },
|
||||
},
|
||||
1,
|
||||
)
|
||||
} catch (err) {
|
||||
logger.error({ err }, 'Failed to record quota usage for agent tool call')
|
||||
}
|
||||
|
||||
return result
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// SandboxManager.initialize is a global operation that applies to the entire process.
|
||||
// We reset it first to ensure any previous process-global SOCKS/HTTP proxy servers
|
||||
// and callbacks are cleaned up, allowing the new callback and allowedDomains to take effect.
|
||||
@@ -235,13 +284,6 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
Object.assign(skillEnvs, envs)
|
||||
}
|
||||
|
||||
// Resolve the requesting user's team role to enforce owner-only bash privileges.
|
||||
// A user who is not a member of the team is treated as restricted (fail-closed),
|
||||
// while flows without a user context (e.g. autofill) remain unrestricted.
|
||||
const role = await resolveTeamMemberRole(teamId, userId)
|
||||
const isOwner = !userId || role === 'owner'
|
||||
const restricted = !isOwner
|
||||
|
||||
// Restore env variables from previously loaded skills in this session
|
||||
let skillLoadedInSession = false
|
||||
if (sessionId) {
|
||||
@@ -287,6 +329,9 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
const deniedTools = agentConfig?.deniedTools || []
|
||||
|
||||
const sandboxedBash = createSandboxedBashTool(process.cwd(), skillEnvs, {
|
||||
teamId,
|
||||
userId,
|
||||
role,
|
||||
getBlockedHost: () => sandboxState.blockedHost,
|
||||
clearBlockedHost: () => {
|
||||
sandboxState.blockedHost = ''
|
||||
@@ -307,28 +352,34 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
bashInjected = true
|
||||
// Pass the full post-update tool list as activeToolNames: setTools only updates the
|
||||
// registry otherwise, and the model would never see the bash tool on the next turn.
|
||||
const next = [...harness.getTools(), sandboxedBash]
|
||||
const next = [...harness.getTools(), wrapToolWithQuota(sandboxedBash)]
|
||||
await harness.setTools(
|
||||
next,
|
||||
next.map((t) => t.name),
|
||||
)
|
||||
}
|
||||
const readSkill = createReadSkillTool(userId, onEnvsAdded, restricted ? onSkillLoaded : undefined)
|
||||
const readSkill = createReadSkillTool(
|
||||
userId,
|
||||
onEnvsAdded,
|
||||
restricted ? onSkillLoaded : undefined,
|
||||
enabledSkillIds,
|
||||
projectId,
|
||||
)
|
||||
|
||||
const systemTools: AgentTool[] = []
|
||||
if (userId) {
|
||||
const metadataSchema = await buildProjectMetadataSchema(projectId)
|
||||
systemTools.push(
|
||||
createListAssetsTool(userId),
|
||||
createCreateFolderTool(userId),
|
||||
createCreateFileTool(userId),
|
||||
createCreateVersionTool(userId),
|
||||
createCreateFileTool(userId, metadataSchema),
|
||||
createCreateVersionTool(userId, metadataSchema),
|
||||
createDownloadAssetTool(userId),
|
||||
createListAutofillFieldsTool(userId),
|
||||
)
|
||||
}
|
||||
|
||||
const readThread = createReadThreadTool()
|
||||
const allTools = [
|
||||
const rawTools = [
|
||||
...mediaTools,
|
||||
readSkill,
|
||||
readThread,
|
||||
@@ -336,6 +387,7 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
...systemTools,
|
||||
...customTools,
|
||||
]
|
||||
const allTools = rawTools.map((tool) => wrapToolWithQuota(tool))
|
||||
const enabledTools = disableTools
|
||||
? []
|
||||
: allTools.filter((tool) => !deniedTools.includes(tool.name))
|
||||
@@ -403,58 +455,116 @@ export interface AutofillField {
|
||||
}
|
||||
|
||||
export function fieldsToTypeBoxSchema(fields: AutofillField[]) {
|
||||
const newOptionSchema = Type.Object(
|
||||
{
|
||||
newOption: Type.Object(
|
||||
{
|
||||
value: Type.String({
|
||||
minLength: 1,
|
||||
description:
|
||||
'The new option display name/value to create and select if none of the existing options match.',
|
||||
}),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
)
|
||||
|
||||
const properties: Record<string, TSchema> = {}
|
||||
for (const f of fields) {
|
||||
let schema: TSchema
|
||||
const fieldName = f.config.name
|
||||
const fieldDesc = f.description || fieldName
|
||||
const baseDescription = `The field '${fieldName}' represents ${fieldDesc}.`
|
||||
switch (f.config.type) {
|
||||
case 'text':
|
||||
case 'longText':
|
||||
schema = Type.String()
|
||||
schema = Type.String({ description: baseDescription })
|
||||
break
|
||||
case 'number':
|
||||
case 'rating':
|
||||
schema = Type.Number()
|
||||
schema = Type.Number({ description: baseDescription })
|
||||
break
|
||||
case 'toggle':
|
||||
schema = Type.Boolean()
|
||||
schema = Type.Boolean({ description: baseDescription })
|
||||
break
|
||||
case 'select': {
|
||||
const options = f.config.select?.options || []
|
||||
schema = Type.String({
|
||||
enum: options.map((o) => o.id),
|
||||
})
|
||||
const description =
|
||||
options.length > 0
|
||||
? `${baseDescription}\nSelect one existing option ID or provide {"newOption": {"value": "..."}} to create a new option.\n\nAvailable options:\n${options.map((o) => `- ${o.displayName} => ${o.id}`).join('\n')}`
|
||||
: `${baseDescription}\nProvide {"newOption": {"value": "..."}} with the desired option name.`
|
||||
if (options.length > 0) {
|
||||
const optionLines = options.map((o) => `- ${o.displayName} => ${o.id}`).join('\n')
|
||||
schema.description = `The field '${fieldName}' represents ${fieldDesc}.\nSelect one option and return the option ID as the value.\n\nAvailable options:\n${optionLines}`
|
||||
schema = Type.Union(
|
||||
[
|
||||
Type.String({
|
||||
enum: options.map((o) => o.id),
|
||||
}),
|
||||
newOptionSchema,
|
||||
],
|
||||
{ description },
|
||||
)
|
||||
} else {
|
||||
schema = Type.Object(newOptionSchema.properties, {
|
||||
additionalProperties: false,
|
||||
description,
|
||||
})
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'selectMulti': {
|
||||
const options = f.config.selectMulti?.options || []
|
||||
schema = Type.Array(
|
||||
Type.String({
|
||||
enum: options.map((o) => o.id),
|
||||
}),
|
||||
)
|
||||
if (options.length > 0) {
|
||||
const optionLines = options.map((o) => `- ${o.displayName} => ${o.id}`).join('\n')
|
||||
schema.description = `The field '${fieldName}' represents ${fieldDesc}.\nSelect applicable options and return the option IDs as the value.\n\nAvailable options:\n${optionLines}`
|
||||
}
|
||||
const description =
|
||||
options.length > 0
|
||||
? `${baseDescription}\nSelect applicable option IDs or provide {"newOption": {"value": "..."}} objects for new options (e.g. ["opt1", {"newOption": {"value": "new_name"}}]).\n\nAvailable options:\n${options.map((o) => `- ${o.displayName} => ${o.id}`).join('\n')}`
|
||||
: `${baseDescription}\nProvide an array of {"newOption": {"value": "..."}} objects for new options.`
|
||||
const itemSchema =
|
||||
options.length > 0
|
||||
? Type.Union([
|
||||
Type.String({
|
||||
enum: options.map((o) => o.id),
|
||||
}),
|
||||
newOptionSchema,
|
||||
])
|
||||
: newOptionSchema
|
||||
schema = Type.Array(itemSchema, { description })
|
||||
break
|
||||
}
|
||||
default:
|
||||
schema = Type.String()
|
||||
schema = Type.String({ description: baseDescription })
|
||||
}
|
||||
|
||||
if (!schema.description) {
|
||||
schema.description = `The field '${fieldName}' represents ${fieldDesc}.`
|
||||
}
|
||||
properties[f.id] = schema
|
||||
// Every field is required but nullable: the agent must return each field key,
|
||||
// using `null` for values it does not know. Nulls are skipped when persisting.
|
||||
// This matches the OpenAI structured-outputs strict-mode convention (all
|
||||
// properties required, optionality expressed via `null`).
|
||||
properties[f.id] = Type.Union([schema, Type.Null()])
|
||||
}
|
||||
|
||||
return Type.Object(properties)
|
||||
return Type.Object(properties, { additionalProperties: false })
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the strict, all-optional metadata schema for the project's CREATION_CONTEXT
|
||||
* fields (the same field set the agent may attach when creating files/versions).
|
||||
* Returns undefined when no project is known or the project defines no fields, in
|
||||
* which case the `metadata` parameter is omitted from the tools entirely.
|
||||
*/
|
||||
async function buildProjectMetadataSchema(projectId?: string): Promise<TSchema | undefined> {
|
||||
if (!projectId) return undefined
|
||||
const fields = await metadataService.listProjectFields('', projectId)
|
||||
const creationFields: AutofillField[] = []
|
||||
for (const f of fields) {
|
||||
const config = f.field.config
|
||||
if (!config || config.autofillSource !== 'CREATION_CONTEXT') continue
|
||||
creationFields.push({
|
||||
id: f.field.key,
|
||||
config,
|
||||
description: f.field.description,
|
||||
})
|
||||
}
|
||||
if (creationFields.length === 0) return undefined
|
||||
return fieldsToTypeBoxSchema(creationFields)
|
||||
}
|
||||
|
||||
function escapeXml(str: string): string {
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { validateToolArguments } from '@earendil-works/pi-ai'
|
||||
import { createCreateFileTool } from './tools/create-file'
|
||||
import { fieldsToTypeBoxSchema } from './index'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { executeAgentToolWorkflow } from './tools/utils'
|
||||
|
||||
vi.mock('@shumai/core/src/s3/s3', () => ({
|
||||
s3Service: {
|
||||
uploadFileToKey: vi.fn(),
|
||||
putObject: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('./tools/utils', () => ({
|
||||
executeAgentToolWorkflow: vi.fn().mockResolvedValue({ id: 'file-1', name: 'test', type: 'file' }),
|
||||
}))
|
||||
|
||||
/**
|
||||
* Reproduce: pi-ai <= 0.82.1 runs its lenient coercion on typebox v1 schemas and
|
||||
* converts `null` in a `[string, null]` union into `""` (see
|
||||
* coerceWithUnionSchema in @earendil-works/pi-ai/dist/utils/validation.js).
|
||||
*
|
||||
* When the agent calls create_file with `path: null, data: {...}`, the harness
|
||||
* validates first: the `null` path becomes `""`, so the tool's
|
||||
* assertExactlyOneSource believes BOTH path and data were provided and throws
|
||||
* "Provide exactly one of ..." even though the call is valid.
|
||||
*
|
||||
* Fixed upstream in pi-ai 0.84.0 (#7328): values that already match a union arm
|
||||
* are preserved before coercion. This test should pass once @earendil-works/pi-ai
|
||||
* is upgraded to >= 0.84.0.
|
||||
*/
|
||||
describe('reproduce null coercion in harness tool validation', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('keeps path: null when data is provided (no false "exactly one" error)', async () => {
|
||||
const tool = createCreateFileTool('user-1')
|
||||
|
||||
const validated = validateToolArguments(
|
||||
{
|
||||
name: 'create_file',
|
||||
description: '',
|
||||
parameters: tool.parameters,
|
||||
} as Parameters<typeof validateToolArguments>[0],
|
||||
{
|
||||
type: 'toolCall',
|
||||
id: 'call-1',
|
||||
name: 'create_file',
|
||||
arguments: {
|
||||
parent: '01KYKNP52YERGJ6Q4GTPF5FRQF',
|
||||
path: null,
|
||||
data: { name: 'random_text.txt', content: 'hello' },
|
||||
},
|
||||
} as Parameters<typeof validateToolArguments>[1],
|
||||
) as { path?: unknown; data?: unknown }
|
||||
|
||||
// The `null` path must survive validation untouched; coercion to "" makes
|
||||
// the tool think both path and data were provided.
|
||||
expect(validated.path).toBeNull()
|
||||
expect(validated.data).toEqual({ name: 'random_text.txt', content: 'hello' })
|
||||
|
||||
// execute must accept the valid call (data-only) without throwing
|
||||
const result = await tool.execute('call-1', validated as never)
|
||||
expect(result.details).toEqual({ id: 'file-1', name: 'test', type: 'file' })
|
||||
expect(s3Service.putObject).toHaveBeenCalledTimes(1)
|
||||
expect(executeAgentToolWorkflow).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('keeps null metadata values (the "unknown" sentinel) through validation', () => {
|
||||
const tool = createCreateFileTool(
|
||||
'user-1',
|
||||
fieldsToTypeBoxSchema([{ id: 'prompt', config: { name: 'Prompt', type: 'text' } }]),
|
||||
)
|
||||
const validated = validateToolArguments(
|
||||
{
|
||||
name: 'create_file',
|
||||
description: '',
|
||||
parameters: tool.parameters,
|
||||
} as Parameters<typeof validateToolArguments>[0],
|
||||
{
|
||||
type: 'toolCall',
|
||||
id: 'call-1',
|
||||
name: 'create_file',
|
||||
arguments: {
|
||||
parent: 'folder-1',
|
||||
path: null,
|
||||
data: { name: 'a.md', content: 'x' },
|
||||
metadata: { prompt: null },
|
||||
},
|
||||
} as Parameters<typeof validateToolArguments>[1],
|
||||
) as { metadata?: Record<string, unknown> }
|
||||
|
||||
expect(validated.metadata).toEqual({ prompt: null })
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,22 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { type TSchema } from 'typebox'
|
||||
import { Value } from 'typebox/value'
|
||||
import { fieldsToTypeBoxSchema, type AutofillField } from './index'
|
||||
|
||||
interface AnyOfFieldSchema {
|
||||
type?: string
|
||||
enum?: string[]
|
||||
const?: string
|
||||
description?: string
|
||||
items?: { enum?: string[]; type?: string }
|
||||
anyOf?: AnyOfFieldSchema[]
|
||||
}
|
||||
|
||||
function propsOf(schema: TSchema): Record<string, { anyOf?: AnyOfFieldSchema[] }> {
|
||||
return (schema as unknown as { properties: Record<string, { anyOf?: AnyOfFieldSchema[] }> })
|
||||
.properties
|
||||
}
|
||||
|
||||
describe('fieldsToTypeBoxSchema', () => {
|
||||
it('converts text fields', () => {
|
||||
const fields: AutofillField[] = [
|
||||
@@ -8,10 +24,12 @@ describe('fieldsToTypeBoxSchema', () => {
|
||||
{ id: 'f2', config: { name: 'Desc', type: 'longText' } },
|
||||
]
|
||||
const schema = fieldsToTypeBoxSchema(fields)
|
||||
expect(schema.properties.f1.type).toBe('string')
|
||||
expect(schema.properties.f1.description).toBe("The field 'Title' represents The title.")
|
||||
expect(schema.properties.f2.type).toBe('string')
|
||||
expect(schema.properties.f2.description).toBe("The field 'Desc' represents Desc.")
|
||||
const props = propsOf(schema)
|
||||
expect(props.f1.anyOf![0].type).toBe('string')
|
||||
expect(props.f1.anyOf![1].type).toBe('null')
|
||||
expect(props.f1.anyOf![0].description).toBe("The field 'Title' represents The title.")
|
||||
expect(props.f2.anyOf![0].type).toBe('string')
|
||||
expect(props.f2.anyOf![0].description).toBe("The field 'Desc' represents Desc.")
|
||||
})
|
||||
|
||||
it('converts numeric fields', () => {
|
||||
@@ -20,17 +38,18 @@ describe('fieldsToTypeBoxSchema', () => {
|
||||
{ id: 'f2', config: { name: 'Rating', type: 'rating' } },
|
||||
]
|
||||
const schema = fieldsToTypeBoxSchema(fields)
|
||||
expect(schema.properties.f1.type).toBe('number')
|
||||
expect(schema.properties.f2.type).toBe('number')
|
||||
const props = propsOf(schema)
|
||||
expect(props.f1.anyOf![0].type).toBe('number')
|
||||
expect(props.f2.anyOf![0].type).toBe('number')
|
||||
})
|
||||
|
||||
it('converts toggle fields', () => {
|
||||
const fields: AutofillField[] = [{ id: 'f1', config: { name: 'Active', type: 'toggle' } }]
|
||||
const schema = fieldsToTypeBoxSchema(fields)
|
||||
expect(schema.properties.f1.type).toBe('boolean')
|
||||
expect(propsOf(schema).f1.anyOf![0].type).toBe('boolean')
|
||||
})
|
||||
|
||||
it('converts select fields with enums and option descriptions', () => {
|
||||
it('converts select fields with enums, newOption support and option descriptions', () => {
|
||||
const fields: AutofillField[] = [
|
||||
{
|
||||
id: 'f1',
|
||||
@@ -48,14 +67,41 @@ describe('fieldsToTypeBoxSchema', () => {
|
||||
},
|
||||
]
|
||||
const schema = fieldsToTypeBoxSchema(fields)
|
||||
expect(schema.properties.f1.type).toBe('string')
|
||||
expect(schema.properties.f1.enum).toEqual(['opt1', 'opt2'])
|
||||
expect(schema.properties.f1.description).toBe(
|
||||
"The field 'Species' represents Species of animal.\nSelect one option and return the option ID as the value.\n\nAvailable options:\n- Option 1 => opt1\n- Option 2 => opt2",
|
||||
const selectSchema = propsOf(schema).f1.anyOf![0]
|
||||
expect(selectSchema.anyOf![0].type).toBe('string')
|
||||
expect(selectSchema.anyOf![0].enum).toEqual(['opt1', 'opt2'])
|
||||
expect(selectSchema.anyOf![1].type).toBe('object')
|
||||
expect(selectSchema.description).toBe(
|
||||
'The field \'Species\' represents Species of animal.\nSelect one existing option ID or provide {"newOption": {"value": "..."}} to create a new option.\n\nAvailable options:\n- Option 1 => opt1\n- Option 2 => opt2',
|
||||
)
|
||||
// Declared option IDs, newOption objects, and null are valid
|
||||
expect(Value.Check(schema, { f1: 'opt1' })).toBe(true)
|
||||
expect(Value.Check(schema, { f1: 'opt2' })).toBe(true)
|
||||
expect(Value.Check(schema, { f1: { newOption: { value: 'kling' } } })).toBe(true)
|
||||
expect(Value.Check(schema, { f1: null })).toBe(true)
|
||||
// Arbitrary strings or invalid objects are rejected
|
||||
expect(Value.Check(schema, { f1: 'not-an-option' })).toBe(false)
|
||||
expect(Value.Check(schema, { f1: { newOption: { foo: 'bar' } } })).toBe(false)
|
||||
})
|
||||
|
||||
it('converts selectMulti fields with array enums and option descriptions', () => {
|
||||
it('converts select fields with empty options to newOption schema only', () => {
|
||||
const fields: AutofillField[] = [
|
||||
{
|
||||
id: 'f1',
|
||||
config: {
|
||||
name: 'Provider',
|
||||
type: 'select',
|
||||
select: { options: [] },
|
||||
},
|
||||
},
|
||||
]
|
||||
const schema = fieldsToTypeBoxSchema(fields)
|
||||
expect(Value.Check(schema, { f1: { newOption: { value: 'kling' } } })).toBe(true)
|
||||
expect(Value.Check(schema, { f1: null })).toBe(true)
|
||||
expect(Value.Check(schema, { f1: 'any-string' })).toBe(false)
|
||||
})
|
||||
|
||||
it('converts selectMulti fields with array enums, newOption support and option descriptions', () => {
|
||||
const fields: AutofillField[] = [
|
||||
{
|
||||
id: 'f1',
|
||||
@@ -72,11 +118,35 @@ describe('fieldsToTypeBoxSchema', () => {
|
||||
},
|
||||
]
|
||||
const schema = fieldsToTypeBoxSchema(fields)
|
||||
expect(schema.properties.f1.type).toBe('array')
|
||||
expect(schema.properties.f1.items.enum).toEqual(['opt1', 'opt2'])
|
||||
expect(schema.properties.f1.description).toBe(
|
||||
"The field 'Tags' represents Tags.\nSelect applicable options and return the option IDs as the value.\n\nAvailable options:\n- Tag 1 => opt1\n- Tag 2 => opt2",
|
||||
const selectMultiSchema = propsOf(schema).f1.anyOf![0]
|
||||
expect(selectMultiSchema.type).toBe('array')
|
||||
expect(selectMultiSchema.description).toBe(
|
||||
'The field \'Tags\' represents Tags.\nSelect applicable option IDs or provide {"newOption": {"value": "..."}} objects for new options (e.g. ["opt1", {"newOption": {"value": "new_name"}}]).\n\nAvailable options:\n- Tag 1 => opt1\n- Tag 2 => opt2',
|
||||
)
|
||||
expect(Value.Check(schema, { f1: ['opt1', 'opt2'] })).toBe(true)
|
||||
expect(Value.Check(schema, { f1: [{ newOption: { value: 'Tag 3' } }] })).toBe(true)
|
||||
expect(Value.Check(schema, { f1: ['opt1', { newOption: { value: 'Tag 3' } }] })).toBe(true)
|
||||
expect(Value.Check(schema, { f1: null })).toBe(true)
|
||||
expect(Value.Check(schema, { f1: ['opt1', 'bad'] })).toBe(false)
|
||||
expect(Value.Check(schema, { f1: ['opt1', { newOption: { bad: 'value' } }] })).toBe(false)
|
||||
})
|
||||
|
||||
it('converts selectMulti fields with empty options to array of newOption schema', () => {
|
||||
const fields: AutofillField[] = [
|
||||
{
|
||||
id: 'f1',
|
||||
config: {
|
||||
name: 'Tags',
|
||||
type: 'selectMulti',
|
||||
selectMulti: { options: [] },
|
||||
},
|
||||
},
|
||||
]
|
||||
const schema = fieldsToTypeBoxSchema(fields)
|
||||
expect(Value.Check(schema, { f1: [{ newOption: { value: 'Tag 1' } }] })).toBe(true)
|
||||
expect(Value.Check(schema, { f1: [] })).toBe(true)
|
||||
expect(Value.Check(schema, { f1: null })).toBe(true)
|
||||
expect(Value.Check(schema, { f1: ['tag1'] })).toBe(false)
|
||||
})
|
||||
|
||||
it('defaults to string for unknown types', () => {
|
||||
@@ -85,6 +155,22 @@ describe('fieldsToTypeBoxSchema', () => {
|
||||
{ id: 'f1', config: { name: 'Unknown', type: 'invalid' } },
|
||||
]
|
||||
const schema = fieldsToTypeBoxSchema(fields)
|
||||
expect(schema.properties.f1.type).toBe('string')
|
||||
expect(propsOf(schema).f1.anyOf![0].type).toBe('string')
|
||||
})
|
||||
|
||||
it('marks every property required (nullable) and rejects unknown keys', () => {
|
||||
const fields: AutofillField[] = [
|
||||
{ id: 'f1', config: { name: 'Title', type: 'text' } },
|
||||
{ id: 'f2', config: { name: 'Rating', type: 'rating' } },
|
||||
]
|
||||
const schema = fieldsToTypeBoxSchema(fields)
|
||||
const props = propsOf(schema)
|
||||
// typebox v1 objects are strict by default: unknown keys are rejected
|
||||
expect(props.f1.anyOf![0].type).toBe('string')
|
||||
expect(props.f1.anyOf![1].type).toBe('null')
|
||||
expect(Value.Check(schema, { f1: 'x', f2: null })).toBe(true)
|
||||
expect(Value.Check(schema, { f1: null, f2: 3 })).toBe(true)
|
||||
expect(Value.Check(schema, { f1: 'x' })).toBe(false)
|
||||
expect(Value.Check(schema, { f1: 'x', f2: null, extra: 1 })).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Type } from '@sinclair/typebox'
|
||||
import { Type } from 'typebox'
|
||||
import { type AgentTool } from '@earendil-works/pi-agent-core'
|
||||
import { type ImageContent } from '@earendil-works/pi-ai'
|
||||
import { prisma, WorkflowTaskType, WorkflowTaskStatus, type User } from '@shumai/db'
|
||||
@@ -36,7 +36,7 @@ export function createAnalyzeImageTool(
|
||||
id: assetId,
|
||||
})
|
||||
|
||||
const asset = await prisma.asset.findUnique({
|
||||
let asset = await prisma.asset.findUnique({
|
||||
where: { id: assetId },
|
||||
include: { storageKey: true },
|
||||
})
|
||||
@@ -45,6 +45,17 @@ export function createAnalyzeImageTool(
|
||||
throw new Error(`Asset with ID ${assetId} not found.`)
|
||||
}
|
||||
|
||||
if (asset.type === 'version_stack') {
|
||||
const latestVersion = await prisma.asset.findFirst({
|
||||
where: { parentId: asset.id, isDeleted: false },
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
include: { storageKey: true },
|
||||
})
|
||||
if (latestVersion) {
|
||||
asset = latestVersion
|
||||
}
|
||||
}
|
||||
|
||||
// Get default media key
|
||||
let mediaKey = asset.storageKey?.key
|
||||
if (asset.media) {
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { createCreateFileTool } from './create-file'
|
||||
import { fieldsToTypeBoxSchema } from '../index'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { executeAgentToolWorkflow } from './utils'
|
||||
import { Value } from 'typebox/value'
|
||||
import * as fs from 'fs'
|
||||
import * as os from 'os'
|
||||
import * as path from 'path'
|
||||
@@ -44,7 +46,7 @@ describe('createCreateFileTool', () => {
|
||||
const filePath = createTempFile('# Hello from disk', 'create-file-test.md')
|
||||
|
||||
const tool = createCreateFileTool('user-1')
|
||||
const result = await tool.execute('call-1', { parent: 'folder-1', path: filePath })
|
||||
const result = await tool.execute('call-1', { parent: 'folder-1', path: filePath, data: null })
|
||||
|
||||
expect(s3Service.uploadFileToKey).toHaveBeenCalledTimes(1)
|
||||
expect(s3Service.putObject).not.toHaveBeenCalled()
|
||||
@@ -70,37 +72,93 @@ describe('createCreateFileTool', () => {
|
||||
expect(result.details).toEqual({ id: 'file-1', name: 'test', type: 'file' })
|
||||
})
|
||||
|
||||
it('should forward the optional context to the agent tool workflow when provided', async () => {
|
||||
const filePath = createTempFile('# Hello from disk', 'create-file-context.md')
|
||||
it('should forward the metadata to the agent tool workflow when provided', async () => {
|
||||
const filePath = createTempFile('# Hello from disk', 'create-file-metadata.md')
|
||||
const metadataSchema = fieldsToTypeBoxSchema([
|
||||
{ id: 'prompt', config: { name: 'Prompt', type: 'text' } },
|
||||
])
|
||||
|
||||
const tool = createCreateFileTool('user-1')
|
||||
const tool = createCreateFileTool('user-1', metadataSchema)
|
||||
await tool.execute('call-1', {
|
||||
parent: 'folder-1',
|
||||
path: filePath,
|
||||
context: 'Generated using gemini',
|
||||
data: null,
|
||||
metadata: { prompt: 'Generated using gemini' },
|
||||
})
|
||||
|
||||
expect(executeAgentToolWorkflow).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
args: expect.objectContaining({ context: 'Generated using gemini' }),
|
||||
args: expect.objectContaining({ metadata: { prompt: 'Generated using gemini' } }),
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should not include context in args when not provided', async () => {
|
||||
const filePath = createTempFile('# Hello from disk', 'create-file-no-context.md')
|
||||
it('should forward select and selectMulti newOption metadata', async () => {
|
||||
const filePath = createTempFile('# Hello from disk', 'create-file-new-option.md')
|
||||
const metadataSchema = fieldsToTypeBoxSchema([
|
||||
{
|
||||
id: 'provider',
|
||||
config: {
|
||||
name: 'Provider',
|
||||
type: 'select',
|
||||
select: { options: [{ id: 'openai', displayName: 'OpenAI', color: '#f43f5e' }] },
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'tags',
|
||||
config: {
|
||||
name: 'Tags',
|
||||
type: 'selectMulti',
|
||||
selectMulti: { options: [{ id: 'tag1', displayName: 'Tag 1', color: '#3b82f6' }] },
|
||||
},
|
||||
},
|
||||
])
|
||||
|
||||
const tool = createCreateFileTool('user-1')
|
||||
await tool.execute('call-1', { parent: 'folder-1', path: filePath })
|
||||
const tool = createCreateFileTool('user-1', metadataSchema)
|
||||
await tool.execute('call-1', {
|
||||
parent: 'folder-1',
|
||||
path: filePath,
|
||||
data: null,
|
||||
metadata: {
|
||||
provider: { newOption: { value: 'Kling' } },
|
||||
tags: ['tag1', { newOption: { value: 'Tag 2' } }],
|
||||
},
|
||||
})
|
||||
|
||||
expect(executeAgentToolWorkflow).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
args: expect.objectContaining({
|
||||
metadata: {
|
||||
provider: { newOption: { value: 'Kling' } },
|
||||
tags: ['tag1', { newOption: { value: 'Tag 2' } }],
|
||||
},
|
||||
}),
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should not include metadata in args when metadata is null', async () => {
|
||||
const filePath = createTempFile('# Hello from disk', 'create-file-no-metadata.md')
|
||||
const metadataSchema = fieldsToTypeBoxSchema([
|
||||
{ id: 'prompt', config: { name: 'Prompt', type: 'text' } },
|
||||
])
|
||||
|
||||
const tool = createCreateFileTool('user-1', metadataSchema)
|
||||
await tool.execute('call-1', {
|
||||
parent: 'folder-1',
|
||||
path: filePath,
|
||||
data: null,
|
||||
metadata: null,
|
||||
})
|
||||
|
||||
const callArgs = vi.mocked(executeAgentToolWorkflow).mock.calls[0][0].args
|
||||
expect(callArgs).not.toHaveProperty('context')
|
||||
expect(callArgs).not.toHaveProperty('metadata')
|
||||
})
|
||||
|
||||
it('should throw when the local file does not exist', async () => {
|
||||
const tool = createCreateFileTool('user-1')
|
||||
await expect(
|
||||
tool.execute('call-1', { parent: 'folder-1', path: '/nonexistent/file.md' }),
|
||||
tool.execute('call-1', { parent: 'folder-1', path: '/nonexistent/file.md', data: null }),
|
||||
).rejects.toThrow('Local file not found at path: /nonexistent/file.md')
|
||||
expect(s3Service.uploadFileToKey).not.toHaveBeenCalled()
|
||||
expect(executeAgentToolWorkflow).not.toHaveBeenCalled()
|
||||
@@ -110,6 +168,7 @@ describe('createCreateFileTool', () => {
|
||||
const tool = createCreateFileTool('user-1')
|
||||
const result = await tool.execute('call-1', {
|
||||
parent: 'folder-1',
|
||||
path: null,
|
||||
data: { name: 'notes.md', content: '# Notes\n\nHello' },
|
||||
})
|
||||
|
||||
@@ -145,6 +204,7 @@ describe('createCreateFileTool', () => {
|
||||
const tool = createCreateFileTool('user-1')
|
||||
await tool.execute('call-1', {
|
||||
parent: 'folder-1',
|
||||
path: null,
|
||||
data: { name: 'script.ts', content: 'const x = 1' },
|
||||
})
|
||||
|
||||
@@ -162,6 +222,7 @@ describe('createCreateFileTool', () => {
|
||||
const tool = createCreateFileTool('user-1')
|
||||
await tool.execute('call-1', {
|
||||
parent: 'folder-1',
|
||||
path: null,
|
||||
data: { name: 'my/notes.md', content: 'hello' },
|
||||
})
|
||||
|
||||
@@ -183,9 +244,9 @@ describe('createCreateFileTool', () => {
|
||||
|
||||
it('should throw when neither "path" nor "data" is provided', async () => {
|
||||
const tool = createCreateFileTool('user-1')
|
||||
await expect(tool.execute('call-1', { parent: 'folder-1' })).rejects.toThrow(
|
||||
'Provide exactly one of "path" (a local file) or "data" (name and content).',
|
||||
)
|
||||
await expect(
|
||||
tool.execute('call-1', { parent: 'folder-1', path: null, data: null }),
|
||||
).rejects.toThrow('Provide exactly one of "path" (a local file) or "data" (name and content).')
|
||||
})
|
||||
|
||||
it('should throw when both "path" and "data" are provided', async () => {
|
||||
@@ -201,4 +262,58 @@ describe('createCreateFileTool', () => {
|
||||
expect(s3Service.putObject).not.toHaveBeenCalled()
|
||||
expect(executeAgentToolWorkflow).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should expose a strict, all-required (nullable) metadata schema when fields are provided', () => {
|
||||
const metadataSchema = fieldsToTypeBoxSchema([
|
||||
{ id: 'prompt', config: { name: 'Prompt', type: 'text' } },
|
||||
{
|
||||
id: 'source',
|
||||
config: {
|
||||
name: 'Source',
|
||||
type: 'select',
|
||||
select: { options: [{ id: 'gemini', displayName: 'Gemini', color: '#ffffff' }] },
|
||||
},
|
||||
},
|
||||
{ id: 'rating', config: { name: 'Rating', type: 'rating' } },
|
||||
])
|
||||
|
||||
const tool = createCreateFileTool('user-1', metadataSchema)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- inspecting the runtime schema shape of the dynamically-built tool
|
||||
const meta = (tool.parameters as any).properties.metadata
|
||||
// `metadata` is a nullable union: [strict object, null]
|
||||
const metaObject = meta.anyOf[0]
|
||||
|
||||
expect(meta).toBeDefined()
|
||||
expect(metaObject.required).toEqual(['prompt', 'source', 'rating'])
|
||||
expect(metaObject.additionalProperties).toBe(false)
|
||||
expect(metaObject.properties.prompt.anyOf[0].type).toBe('string')
|
||||
expect(metaObject.properties.prompt.anyOf[1].type).toBe('null')
|
||||
expect(metaObject.properties.source.anyOf[0].anyOf[0].enum).toEqual(['gemini'])
|
||||
expect(metaObject.properties.rating.anyOf[0].type).toBe('number')
|
||||
|
||||
// Every field must be present (use null when unknown); unknown keys and bad enums are rejected
|
||||
expect(Value.Check(meta, { prompt: 'hello', source: 'gemini', rating: 5 })).toBe(true)
|
||||
expect(
|
||||
Value.Check(meta, {
|
||||
prompt: 'hello',
|
||||
source: { newOption: { value: 'kling' } },
|
||||
rating: 5,
|
||||
}),
|
||||
).toBe(true)
|
||||
expect(Value.Check(meta, { prompt: null, source: null, rating: null })).toBe(true)
|
||||
expect(Value.Check(meta, { prompt: 'hello', source: null, rating: null })).toBe(true)
|
||||
expect(Value.Check(meta, { prompt: 'hello' })).toBe(false)
|
||||
expect(
|
||||
Value.Check(meta, { prompt: 'hello', source: 'gemini', rating: 5, unknownKey: 'x' }),
|
||||
).toBe(false)
|
||||
expect(Value.Check(meta, { prompt: 'hello', source: 'not-an-option', rating: null })).toBe(
|
||||
false,
|
||||
)
|
||||
})
|
||||
|
||||
it('should omit the metadata parameter when no schema is provided', () => {
|
||||
const tool = createCreateFileTool('user-1')
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- inspecting the runtime schema shape of the dynamically-built tool
|
||||
expect((tool.parameters as any).properties.metadata).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -2,69 +2,78 @@ import { type AgentTool } from '@earendil-works/pi-agent-core'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { getFileMimeType, readFileMimeType } from '@shumai/core/src/utils/file-mime'
|
||||
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
|
||||
import { Type } from '@sinclair/typebox'
|
||||
import { Type, type TSchema } from 'typebox'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { ulid } from 'ulid'
|
||||
import { executeAgentToolWorkflow } from './utils'
|
||||
|
||||
const createFileSchema = Type.Object({
|
||||
parent: Type.String({
|
||||
description: 'The parent folder ID under which to create the file. This parameter is required.',
|
||||
}),
|
||||
path: Type.Optional(
|
||||
Type.String({
|
||||
description:
|
||||
'The absolute or relative local path to an existing file on disk. Provide either this or "data", but not both.',
|
||||
}),
|
||||
),
|
||||
data: Type.Optional(
|
||||
Type.Object({
|
||||
name: Type.String({
|
||||
minLength: 1,
|
||||
description:
|
||||
'The desired name for the new file, including its extension (e.g. "notes.md").',
|
||||
}),
|
||||
content: Type.String({
|
||||
description: 'The full content of the file as a plain string.',
|
||||
}),
|
||||
}),
|
||||
),
|
||||
context: Type.Optional(
|
||||
Type.String({
|
||||
description:
|
||||
'Optional context passed to the AI metadata autofill workflow for fields that cannot be inferred from file content alone ' +
|
||||
'(e.g. the model or prompt used to generate the asset). ' +
|
||||
'Use list_autofill_fields first to check which fields can be autofilled. ' +
|
||||
'Keep the context short and only include information relevant to those fields.',
|
||||
}),
|
||||
),
|
||||
})
|
||||
interface CreateFileToolParams {
|
||||
parent: string
|
||||
path: string | null
|
||||
data: { name: string; content: string } | null
|
||||
metadata?: Record<string, unknown> | null
|
||||
}
|
||||
|
||||
function assertExactlyOneSource(params: {
|
||||
path?: string
|
||||
data?: { name: string; content: string }
|
||||
}) {
|
||||
const hasPath = params.path !== undefined
|
||||
const hasData = params.data !== undefined
|
||||
function assertExactlyOneSource(params: CreateFileToolParams) {
|
||||
const hasPath = params.path !== null
|
||||
const hasData = params.data !== null
|
||||
if (hasPath === hasData) {
|
||||
throw new Error('Provide exactly one of "path" (a local file) or "data" (name and content).')
|
||||
}
|
||||
return hasPath ? params.path! : params.data!
|
||||
}
|
||||
|
||||
export function createCreateFileTool(userId: string): AgentTool<typeof createFileSchema> {
|
||||
return {
|
||||
export function createCreateFileTool(userId: string, metadataSchema?: TSchema): AgentTool {
|
||||
const createFileSchema = Type.Object(
|
||||
{
|
||||
parent: Type.String({
|
||||
description:
|
||||
'The parent folder ID under which to create the file. This parameter is required.',
|
||||
}),
|
||||
path: Type.Union([
|
||||
Type.String({
|
||||
description:
|
||||
'The absolute or relative local path to an existing file on disk. Provide a value here OR in "data", but not both. Use null if you are providing "data".',
|
||||
}),
|
||||
Type.Null(),
|
||||
]),
|
||||
data: Type.Union([
|
||||
Type.Object(
|
||||
{
|
||||
name: Type.String({
|
||||
minLength: 1,
|
||||
description:
|
||||
'The desired name for the new file, including its extension (e.g. "notes.md").',
|
||||
}),
|
||||
content: Type.String({
|
||||
description: 'The full content of the file as a plain string.',
|
||||
}),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
Type.Null(),
|
||||
]),
|
||||
...(metadataSchema ? { metadata: Type.Union([metadataSchema, Type.Null()]) } : {}),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
)
|
||||
|
||||
const tool: AgentTool = {
|
||||
name: 'create_file',
|
||||
label: 'Create File',
|
||||
description:
|
||||
'Create a new file under a folder. You MUST choose exactly ONE creation method: ' +
|
||||
'(1) provide "path" to upload an existing local file, OR ' +
|
||||
'(2) provide "data" with name and content to create a new text file. ' +
|
||||
'Never provide both "path" and "data" together. Never omit both.',
|
||||
'Set the unused parameter to null. ' +
|
||||
'The optional "metadata" parameter accepts only the CREATION_CONTEXT fields declared in its schema; never invent field keys, and use null for fields you do not know.',
|
||||
parameters: createFileSchema,
|
||||
execute: async (_toolCallId, params) => {
|
||||
const source = assertExactlyOneSource(params)
|
||||
// The harness validates tool args against `createFileSchema` before calling
|
||||
// execute, so `params` is guaranteed to match this shape.
|
||||
const p = params as CreateFileToolParams
|
||||
const source = assertExactlyOneSource(p)
|
||||
|
||||
let name: string
|
||||
let size: number
|
||||
@@ -99,15 +108,15 @@ export function createCreateFileTool(userId: string): AgentTool<typeof createFil
|
||||
const result = await executeAgentToolWorkflow({
|
||||
toolName: 'create_file',
|
||||
args: {
|
||||
parent: params.parent,
|
||||
parent: p.parent,
|
||||
s3Key,
|
||||
name,
|
||||
size,
|
||||
contentType: mimeType,
|
||||
...(params.context ? { context: params.context } : {}),
|
||||
...(p.metadata ? { metadata: p.metadata } : {}),
|
||||
},
|
||||
userId,
|
||||
assetId: params.parent,
|
||||
assetId: p.parent,
|
||||
})
|
||||
return {
|
||||
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
|
||||
@@ -115,4 +124,5 @@ export function createCreateFileTool(userId: string): AgentTool<typeof createFil
|
||||
}
|
||||
},
|
||||
}
|
||||
return tool
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Type } from '@sinclair/typebox'
|
||||
import { Type } from 'typebox'
|
||||
import { type AgentTool } from '@earendil-works/pi-agent-core'
|
||||
import { executeAgentToolWorkflow } from './utils'
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { createCreateVersionTool } from './create-version'
|
||||
import { fieldsToTypeBoxSchema } from '../index'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { executeAgentToolWorkflow } from './utils'
|
||||
import { Value } from 'typebox/value'
|
||||
import * as fs from 'fs'
|
||||
import * as os from 'os'
|
||||
import * as path from 'path'
|
||||
@@ -67,31 +69,80 @@ describe('createCreateVersionTool', () => {
|
||||
expect(result.details).toEqual({ id: 'file-1', name: 'v2', type: 'file' })
|
||||
})
|
||||
|
||||
it('should forward the optional context to the agent tool workflow when provided', async () => {
|
||||
const filePath = createTempFile('# Hello from disk', 'create-version-context.md')
|
||||
it('should forward the metadata to the agent tool workflow when provided', async () => {
|
||||
const filePath = createTempFile('# Hello from disk', 'create-version-metadata.md')
|
||||
const metadataSchema = fieldsToTypeBoxSchema([
|
||||
{ id: 'prompt', config: { name: 'Prompt', type: 'text' } },
|
||||
])
|
||||
|
||||
const tool = createCreateVersionTool('user-1')
|
||||
const tool = createCreateVersionTool('user-1', metadataSchema)
|
||||
await tool.execute('call-1', {
|
||||
parent: 'file-1',
|
||||
path: filePath,
|
||||
context: 'Generated using gemini',
|
||||
metadata: { prompt: 'Generated using gemini' },
|
||||
})
|
||||
|
||||
expect(executeAgentToolWorkflow).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
args: expect.objectContaining({ context: 'Generated using gemini' }),
|
||||
args: expect.objectContaining({ metadata: { prompt: 'Generated using gemini' } }),
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should not include context in args when not provided', async () => {
|
||||
const filePath = createTempFile('# Hello from disk', 'create-version-no-context.md')
|
||||
it('should forward select and selectMulti newOption metadata', async () => {
|
||||
const filePath = createTempFile('# Hello from disk', 'create-version-new-option.md')
|
||||
const metadataSchema = fieldsToTypeBoxSchema([
|
||||
{
|
||||
id: 'provider',
|
||||
config: {
|
||||
name: 'Provider',
|
||||
type: 'select',
|
||||
select: { options: [{ id: 'openai', displayName: 'OpenAI', color: '#f43f5e' }] },
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'tags',
|
||||
config: {
|
||||
name: 'Tags',
|
||||
type: 'selectMulti',
|
||||
selectMulti: { options: [{ id: 'tag1', displayName: 'Tag 1', color: '#3b82f6' }] },
|
||||
},
|
||||
},
|
||||
])
|
||||
|
||||
const tool = createCreateVersionTool('user-1')
|
||||
await tool.execute('call-1', { parent: 'file-1', path: filePath })
|
||||
const tool = createCreateVersionTool('user-1', metadataSchema)
|
||||
await tool.execute('call-1', {
|
||||
parent: 'file-1',
|
||||
path: filePath,
|
||||
metadata: {
|
||||
provider: { newOption: { value: 'Kling' } },
|
||||
tags: ['tag1', { newOption: { value: 'Tag 2' } }],
|
||||
},
|
||||
})
|
||||
|
||||
expect(executeAgentToolWorkflow).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
args: expect.objectContaining({
|
||||
metadata: {
|
||||
provider: { newOption: { value: 'Kling' } },
|
||||
tags: ['tag1', { newOption: { value: 'Tag 2' } }],
|
||||
},
|
||||
}),
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should not include metadata in args when metadata is null', async () => {
|
||||
const filePath = createTempFile('# Hello from disk', 'create-version-no-metadata.md')
|
||||
const metadataSchema = fieldsToTypeBoxSchema([
|
||||
{ id: 'prompt', config: { name: 'Prompt', type: 'text' } },
|
||||
])
|
||||
|
||||
const tool = createCreateVersionTool('user-1', metadataSchema)
|
||||
await tool.execute('call-1', { parent: 'file-1', path: filePath, metadata: null })
|
||||
|
||||
const callArgs = vi.mocked(executeAgentToolWorkflow).mock.calls[0][0].args
|
||||
expect(callArgs).not.toHaveProperty('context')
|
||||
expect(callArgs).not.toHaveProperty('metadata')
|
||||
})
|
||||
|
||||
it('should throw when the local file does not exist', async () => {
|
||||
@@ -102,4 +153,34 @@ describe('createCreateVersionTool', () => {
|
||||
expect(s3Service.uploadFileToKey).not.toHaveBeenCalled()
|
||||
expect(executeAgentToolWorkflow).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should expose a strict, all-required (nullable) metadata schema when fields are provided', () => {
|
||||
const metadataSchema = fieldsToTypeBoxSchema([
|
||||
{ id: 'prompt', config: { name: 'Prompt', type: 'text' } },
|
||||
{ id: 'toggle', config: { name: 'Active', type: 'toggle' } },
|
||||
])
|
||||
|
||||
const tool = createCreateVersionTool('user-1', metadataSchema)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- inspecting the runtime schema shape of the dynamically-built tool
|
||||
const meta = (tool.parameters as any).properties.metadata
|
||||
// `metadata` is a nullable union: [strict object, null]
|
||||
const metaObject = meta.anyOf[0]
|
||||
|
||||
expect(meta).toBeDefined()
|
||||
expect(metaObject.required).toEqual(['prompt', 'toggle'])
|
||||
expect(metaObject.additionalProperties).toBe(false)
|
||||
expect(metaObject.properties.prompt.anyOf[0].type).toBe('string')
|
||||
expect(metaObject.properties.prompt.anyOf[1].type).toBe('null')
|
||||
expect(metaObject.properties.toggle.anyOf[0].type).toBe('boolean')
|
||||
|
||||
expect(Value.Check(meta, { prompt: 'p', toggle: true })).toBe(true)
|
||||
expect(Value.Check(meta, { prompt: null, toggle: null })).toBe(true)
|
||||
expect(Value.Check(meta, { prompt: 'p', toggle: null, unknownKey: 'x' })).toBe(false)
|
||||
})
|
||||
|
||||
it('should omit the metadata parameter when no schema is provided', () => {
|
||||
const tool = createCreateVersionTool('user-1')
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- inspecting the runtime schema shape of the dynamically-built tool
|
||||
expect((tool.parameters as any).properties.metadata).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Type } from '@sinclair/typebox'
|
||||
import { Type, type TSchema } from 'typebox'
|
||||
import { type AgentTool } from '@earendil-works/pi-agent-core'
|
||||
import { executeAgentToolWorkflow } from './utils'
|
||||
import * as fs from 'fs'
|
||||
@@ -8,36 +8,42 @@ import { readFileMimeType } from '@shumai/core/src/utils/file-mime'
|
||||
import { ulid } from 'ulid'
|
||||
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
|
||||
|
||||
const createVersionSchema = Type.Object({
|
||||
parent: Type.String({
|
||||
description:
|
||||
'The parent file ID for which to create a new version. This parameter is required.',
|
||||
}),
|
||||
path: Type.String({
|
||||
description:
|
||||
'The absolute or relative local path to the file on disk. This parameter is required.',
|
||||
}),
|
||||
context: Type.Optional(
|
||||
Type.String({
|
||||
description:
|
||||
'Optional context passed to the AI metadata autofill workflow for fields that cannot be inferred from file content alone ' +
|
||||
'(e.g. the model or prompt used to generate the asset). ' +
|
||||
'Use list_autofill_fields first to check which fields can be autofilled. ' +
|
||||
'Keep the context short and only include information relevant to those fields.',
|
||||
}),
|
||||
),
|
||||
})
|
||||
interface CreateVersionToolParams {
|
||||
parent: string
|
||||
path: string
|
||||
metadata?: Record<string, unknown> | null
|
||||
}
|
||||
|
||||
export function createCreateVersionTool(userId: string): AgentTool<typeof createVersionSchema> {
|
||||
return {
|
||||
export function createCreateVersionTool(userId: string, metadataSchema?: TSchema): AgentTool {
|
||||
const createVersionSchema = Type.Object(
|
||||
{
|
||||
parent: Type.String({
|
||||
description:
|
||||
'The parent file ID for which to create a new version. This parameter is required.',
|
||||
}),
|
||||
path: Type.String({
|
||||
description:
|
||||
'The absolute or relative local path to the file on disk. This parameter is required.',
|
||||
}),
|
||||
...(metadataSchema ? { metadata: Type.Union([metadataSchema, Type.Null()]) } : {}),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
)
|
||||
|
||||
const tool: AgentTool = {
|
||||
name: 'create_version',
|
||||
label: 'Create Version',
|
||||
description: 'Create a new version of an existing file from a local file path.',
|
||||
description:
|
||||
'Create a new version of an existing file from a local file path. ' +
|
||||
'The optional "metadata" parameter accepts only the CREATION_CONTEXT fields declared in its schema; never invent field keys, and use null for fields you do not know.',
|
||||
parameters: createVersionSchema,
|
||||
execute: async (_toolCallId, params) => {
|
||||
const absolutePath = path.resolve(process.cwd(), params.path)
|
||||
// The harness validates tool args against `createVersionSchema` before calling
|
||||
// execute, so `params` is guaranteed to match this shape.
|
||||
const p = params as CreateVersionToolParams
|
||||
const absolutePath = path.resolve(process.cwd(), p.path)
|
||||
if (!fs.existsSync(absolutePath)) {
|
||||
throw new Error(`Local file not found at path: ${params.path}`)
|
||||
throw new Error(`Local file not found at path: ${p.path}`)
|
||||
}
|
||||
|
||||
const fileSize = fs.statSync(absolutePath).size
|
||||
@@ -50,15 +56,15 @@ export function createCreateVersionTool(userId: string): AgentTool<typeof create
|
||||
const result = await executeAgentToolWorkflow({
|
||||
toolName: 'create_version',
|
||||
args: {
|
||||
parent: params.parent,
|
||||
parent: p.parent,
|
||||
s3Key,
|
||||
name: path.basename(absolutePath),
|
||||
size: fileSize,
|
||||
contentType: mimeType,
|
||||
...(params.context ? { context: params.context } : {}),
|
||||
...(p.metadata ? { metadata: p.metadata } : {}),
|
||||
},
|
||||
userId,
|
||||
assetId: params.parent,
|
||||
assetId: p.parent,
|
||||
})
|
||||
return {
|
||||
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
|
||||
@@ -66,4 +72,5 @@ export function createCreateVersionTool(userId: string): AgentTool<typeof create
|
||||
}
|
||||
},
|
||||
}
|
||||
return tool
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ vi.mock('@shumai/db', async (importOriginal) => {
|
||||
prisma: {
|
||||
asset: {
|
||||
findUnique: vi.fn(),
|
||||
findFirst: vi.fn(),
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -166,4 +167,48 @@ describe('downloadAssetTool', () => {
|
||||
expect(fs.existsSync(expectedPath)).toBe(true)
|
||||
expect(result.details.contentType).toBe('text/markdown')
|
||||
})
|
||||
|
||||
it('should resolve version_stack asset to its latest version file', async () => {
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue()
|
||||
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
|
||||
id: 'stack-1',
|
||||
name: '',
|
||||
type: 'version_stack',
|
||||
storageKey: null,
|
||||
media: null,
|
||||
} as unknown as Asset)
|
||||
|
||||
vi.mocked(prisma.asset.findFirst).mockResolvedValue({
|
||||
id: 'file-ver-2',
|
||||
name: 'banana_pig.png',
|
||||
type: 'file',
|
||||
storageKey: { key: 'raw/banana_pig.png' },
|
||||
media: {
|
||||
proxyType: 'image',
|
||||
imageTranscodes: [{ key: 'proxy/banana_pig.webp' }],
|
||||
},
|
||||
} as unknown as Asset)
|
||||
|
||||
vi.mocked(s3Service.getObject).mockResolvedValue({
|
||||
buffer: Buffer.from('fake-version-bytes'),
|
||||
contentType: 'image/webp',
|
||||
} as unknown as { buffer: Buffer; contentType: string })
|
||||
|
||||
const tool = createDownloadAssetTool('user-1')
|
||||
const result = await tool.execute('call-1', { assetId: 'stack-1' })
|
||||
|
||||
expect(prisma.asset.findFirst).toHaveBeenCalledWith({
|
||||
where: { parentId: 'stack-1', isDeleted: false },
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
include: { storageKey: true },
|
||||
})
|
||||
|
||||
expect(s3Service.getObject).toHaveBeenCalledWith('shumai', 'proxy/banana_pig.webp')
|
||||
|
||||
const expectedPath = path.join(piDir, 'file-ver-2_banana_pig.png')
|
||||
createdFiles.push(expectedPath)
|
||||
|
||||
expect(fs.existsSync(expectedPath)).toBe(true)
|
||||
expect(result.details.name).toBe('banana_pig.png')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Type } from '@sinclair/typebox'
|
||||
import { Type } from 'typebox'
|
||||
import { type AgentTool } from '@earendil-works/pi-agent-core'
|
||||
import { prisma, type User } from '@shumai/db'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
@@ -35,7 +35,7 @@ export function createDownloadAssetTool(userId: string): AgentTool<typeof downlo
|
||||
id: assetId,
|
||||
})
|
||||
|
||||
const asset = await prisma.asset.findUnique({
|
||||
let asset = await prisma.asset.findUnique({
|
||||
where: { id: assetId },
|
||||
include: { storageKey: true },
|
||||
})
|
||||
@@ -44,6 +44,17 @@ export function createDownloadAssetTool(userId: string): AgentTool<typeof downlo
|
||||
throw new Error(`Asset with ID ${assetId} not found.`)
|
||||
}
|
||||
|
||||
if (asset.type === 'version_stack') {
|
||||
const latestVersion = await prisma.asset.findFirst({
|
||||
where: { parentId: asset.id, isDeleted: false },
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
include: { storageKey: true },
|
||||
})
|
||||
if (latestVersion) {
|
||||
asset = latestVersion
|
||||
}
|
||||
}
|
||||
|
||||
let mediaKey = asset.storageKey?.key
|
||||
|
||||
if (asset.media) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Type } from '@sinclair/typebox'
|
||||
import { Type } from 'typebox'
|
||||
import { type AgentTool } from '@earendil-works/pi-agent-core'
|
||||
import { executeAgentToolWorkflow } from './utils'
|
||||
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createListAutofillFieldsTool } from './list-autofill-fields'
|
||||
import { executeAgentToolWorkflow } from './utils'
|
||||
|
||||
vi.mock('./utils', () => ({
|
||||
executeAgentToolWorkflow: vi.fn().mockResolvedValue({
|
||||
fields: [{ name: 'Source', type: 'select', options: [{ displayName: 'Gemini' }] }],
|
||||
}),
|
||||
}))
|
||||
|
||||
describe('createListAutofillFieldsTool', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should list autofill fields for the parent folder via the agent tool workflow', async () => {
|
||||
const tool = createListAutofillFieldsTool('user-1')
|
||||
const result = await tool.execute('call-1', { parent: 'folder-1' })
|
||||
|
||||
expect(executeAgentToolWorkflow).toHaveBeenCalledWith({
|
||||
toolName: 'list_autofill_fields',
|
||||
args: { parent: 'folder-1' },
|
||||
userId: 'user-1',
|
||||
assetId: 'folder-1',
|
||||
})
|
||||
|
||||
expect(result.details).toEqual({
|
||||
fields: [{ name: 'Source', type: 'select', options: [{ displayName: 'Gemini' }] }],
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,35 +0,0 @@
|
||||
import { Type } from '@sinclair/typebox'
|
||||
import { type AgentTool } from '@earendil-works/pi-agent-core'
|
||||
import { executeAgentToolWorkflow } from './utils'
|
||||
|
||||
const listAutofillFieldsSchema = Type.Object({
|
||||
parent: Type.String({
|
||||
description:
|
||||
'The parent folder ID whose project autofillable metadata fields to list. This parameter is required.',
|
||||
}),
|
||||
})
|
||||
|
||||
export function createListAutofillFieldsTool(
|
||||
userId: string,
|
||||
): AgentTool<typeof listAutofillFieldsSchema> {
|
||||
return {
|
||||
name: 'list_autofill_fields',
|
||||
label: 'List Autofill Fields',
|
||||
description:
|
||||
'List the AI-autofillable metadata fields defined for the project of a parent folder, including their types and available options. ' +
|
||||
'Use this before creating a file or version so you can pass relevant context (e.g. the model or prompt used to generate the asset) to create_file/create_version.',
|
||||
parameters: listAutofillFieldsSchema,
|
||||
execute: async (_toolCallId, params) => {
|
||||
const result = await executeAgentToolWorkflow({
|
||||
toolName: 'list_autofill_fields',
|
||||
args: params,
|
||||
userId,
|
||||
assetId: params.parent,
|
||||
})
|
||||
return {
|
||||
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
|
||||
details: result,
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Type } from '@sinclair/typebox'
|
||||
import { Type } from 'typebox'
|
||||
import { type AgentTool } from '@earendil-works/pi-agent-core'
|
||||
import { type ImageContent } from '@earendil-works/pi-ai'
|
||||
import { prisma, WorkflowTaskType, WorkflowTaskStatus, type User } from '@shumai/db'
|
||||
@@ -56,7 +56,7 @@ export function createReadPdfPagesTool(
|
||||
id: targetAssetId,
|
||||
})
|
||||
|
||||
const asset = await prisma.asset.findUnique({
|
||||
let asset = await prisma.asset.findUnique({
|
||||
where: { id: targetAssetId },
|
||||
})
|
||||
|
||||
@@ -64,6 +64,16 @@ export function createReadPdfPagesTool(
|
||||
throw new Error(`Asset with ID ${targetAssetId} not found.`)
|
||||
}
|
||||
|
||||
if (asset.type === 'version_stack') {
|
||||
const latestVersion = await prisma.asset.findFirst({
|
||||
where: { parentId: asset.id, isDeleted: false },
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
})
|
||||
if (latestVersion) {
|
||||
asset = latestVersion
|
||||
}
|
||||
}
|
||||
|
||||
const proxyType = (asset.media as PrismaJson.MediaInfo | null)?.proxyType
|
||||
if (proxyType !== 'pdf') {
|
||||
throw new Error(`Asset ${targetAssetId} is not a PDF or document.`)
|
||||
|
||||
@@ -307,6 +307,77 @@ describe('readSkillTool', () => {
|
||||
reviewerTool.execute('1', { skillId: ownerSkill.id }, undefined, undefined),
|
||||
).rejects.toThrow('Permission denied')
|
||||
})
|
||||
|
||||
it('uses the effective project role for skill permission checks', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Project Skill Team' } })
|
||||
const project = await prisma.project.create({ data: { name: 'Skill Proj', teamId: team.id } })
|
||||
const editorSkill = await prisma.skill.create({
|
||||
data: {
|
||||
name: 'Editor Project Skill',
|
||||
assetId: 'asset1',
|
||||
hash: 'proj-editor-hash',
|
||||
teamId: team.id,
|
||||
permission: 'editor',
|
||||
},
|
||||
})
|
||||
|
||||
// Team editor demoted to project reviewer: denied inside the project
|
||||
const demoted = await prisma.user.create({
|
||||
data: { name: 'Demoted Skill', email: 'dem-skill@test.com' },
|
||||
})
|
||||
const demotedTm = await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: demoted.id, role: 'editor', scope: 'team' },
|
||||
})
|
||||
await prisma.projectMember.create({
|
||||
data: { projectId: project.id, teamMemberId: demotedTm.id, role: 'reviewer' },
|
||||
})
|
||||
|
||||
const demotedTool = createReadSkillTool(
|
||||
demoted.id,
|
||||
() => {},
|
||||
undefined,
|
||||
undefined,
|
||||
project.id,
|
||||
)
|
||||
await expect(
|
||||
demotedTool.execute('1', { skillId: editorSkill.id }, undefined, undefined),
|
||||
).rejects.toThrow('Permission denied')
|
||||
|
||||
// Project-scoped member invited as editor: allowed
|
||||
const projEditor = await prisma.user.create({
|
||||
data: { name: 'PE Skill', email: 'pe-skill@test.com' },
|
||||
})
|
||||
const projEditorTm = await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: projEditor.id, role: 'reviewer', scope: 'project' },
|
||||
})
|
||||
await prisma.projectMember.create({
|
||||
data: { projectId: project.id, teamMemberId: projEditorTm.id, role: 'editor' },
|
||||
})
|
||||
|
||||
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs calls
|
||||
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
|
||||
if (path.toString().endsWith('.hash')) return 'proj-editor-hash'
|
||||
if (path.toString().endsWith('SKILL.md')) return '# Editor Project Skill Content'
|
||||
return ''
|
||||
})
|
||||
|
||||
const projEditorTool = createReadSkillTool(
|
||||
projEditor.id,
|
||||
() => {},
|
||||
undefined,
|
||||
undefined,
|
||||
project.id,
|
||||
)
|
||||
const result = await projEditorTool.execute(
|
||||
'1',
|
||||
{ skillId: editorSkill.id },
|
||||
undefined,
|
||||
undefined,
|
||||
)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
expect((result.content[0] as any).text).toBe('# Editor Project Skill Content')
|
||||
})
|
||||
})
|
||||
|
||||
describe('onSkillLoaded callback', () => {
|
||||
@@ -363,4 +434,75 @@ describe('readSkillTool', () => {
|
||||
expect(onSkillLoaded).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('enabled skills enforcement', () => {
|
||||
it('should reject loading a skill that is not enabled for the agent', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Enabled Filter Team' } })
|
||||
const skill = await prisma.skill.create({
|
||||
data: {
|
||||
name: 'Disabled For Agent Skill',
|
||||
assetId: 'asset1',
|
||||
hash: 'disabled-agent-hash',
|
||||
teamId: team.id,
|
||||
},
|
||||
})
|
||||
|
||||
const readSkillTool = createReadSkillTool(undefined, () => {}, undefined, [
|
||||
'some-other-enabled-skill',
|
||||
])
|
||||
await expect(
|
||||
readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined),
|
||||
).rejects.toThrow('not enabled for this agent')
|
||||
})
|
||||
|
||||
it('should allow loading a skill that is enabled for the agent', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Enabled Allow Team' } })
|
||||
const skill = await prisma.skill.create({
|
||||
data: {
|
||||
name: 'Enabled For Agent Skill',
|
||||
assetId: 'asset1',
|
||||
hash: 'enabled-agent-hash',
|
||||
teamId: team.id,
|
||||
},
|
||||
})
|
||||
|
||||
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs readFileSync which has complex overloaded signatures
|
||||
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
|
||||
if (path.toString().endsWith('.hash')) return 'enabled-agent-hash'
|
||||
if (path.toString().endsWith('SKILL.md')) return '# Enabled For Agent Skill'
|
||||
return ''
|
||||
})
|
||||
|
||||
const readSkillTool = createReadSkillTool(undefined, () => {}, undefined, [skill.id])
|
||||
const result = await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
expect((result.content[0] as any).text).toBe('# Enabled For Agent Skill')
|
||||
})
|
||||
|
||||
it('should allow loading any skill when enabledSkillIds is not provided (backward compatibility)', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'No Filter Team' } })
|
||||
const skill = await prisma.skill.create({
|
||||
data: {
|
||||
name: 'No Filter Skill',
|
||||
assetId: 'asset1',
|
||||
hash: 'no-filter-hash',
|
||||
teamId: team.id,
|
||||
},
|
||||
})
|
||||
|
||||
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs readFileSync which has complex overloaded signatures
|
||||
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
|
||||
if (path.toString().endsWith('.hash')) return 'no-filter-hash'
|
||||
if (path.toString().endsWith('SKILL.md')) return '# No Filter Skill'
|
||||
return ''
|
||||
})
|
||||
|
||||
const readSkillTool = createReadSkillTool(undefined, () => {})
|
||||
const result = await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
expect((result.content[0] as any).text).toBe('# No Filter Skill')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
import { Type } from '@sinclair/typebox'
|
||||
import { Type } from 'typebox'
|
||||
import { type AgentTool } from '@earendil-works/pi-agent-core'
|
||||
import { agentService } from '@shumai/core/src/agent/agent'
|
||||
import { resolveEffectiveRole } from '@shumai/core/src/authz/authz'
|
||||
|
||||
const readSkillSchema = Type.Object({
|
||||
skillId: Type.String({ description: 'The ID of the skill to read' }),
|
||||
@@ -17,6 +18,8 @@ export const createReadSkillTool = (
|
||||
userId: string | undefined,
|
||||
onEnvsAdded: (envs: Record<string, string>) => void,
|
||||
onSkillLoaded?: () => Promise<void> | void,
|
||||
enabledSkillIds?: string[],
|
||||
projectId?: string,
|
||||
): AgentTool<typeof readSkillSchema, { skillId: string }> => ({
|
||||
name: 'read_skill',
|
||||
label: 'Read Agent Skill',
|
||||
@@ -31,18 +34,21 @@ export const createReadSkillTool = (
|
||||
throw new Error(`Skill with ID ${params.skillId} not found.`)
|
||||
}
|
||||
|
||||
// Skills disabled for this agent must not be loadable, even if the model
|
||||
// somehow knows their ID (e.g. from earlier conversation history).
|
||||
if (enabledSkillIds && !enabledSkillIds.includes(params.skillId)) {
|
||||
throw new Error(`Skill with ID ${params.skillId} is not enabled for this agent.`)
|
||||
}
|
||||
|
||||
const requiredLevel = ROLE_HIERARCHY[skill.permission] || 1
|
||||
const effectiveRole = userId
|
||||
? await resolveEffectiveRole(skill.teamId, projectId, userId)
|
||||
: null
|
||||
|
||||
if (userId) {
|
||||
const member = await prisma.teamMember.findUnique({
|
||||
where: {
|
||||
teamIdUserId: {
|
||||
teamId: skill.teamId,
|
||||
userId,
|
||||
},
|
||||
},
|
||||
})
|
||||
const userLevel = member ? ROLE_HIERARCHY[member.role] || 0 : 0
|
||||
// Resolve the user's effective role for the project context (project
|
||||
// override wins; project-scoped members without project access are denied).
|
||||
const userLevel = effectiveRole ? ROLE_HIERARCHY[effectiveRole] || 0 : 0
|
||||
if (userLevel < requiredLevel) {
|
||||
throw new Error(
|
||||
`Permission denied: Insufficient role to load skill "${skill.name}". Minimum required role is "${skill.permission}".`,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
import { Type } from '@sinclair/typebox'
|
||||
import { Type } from 'typebox'
|
||||
import { type AgentTool } from '@earendil-works/pi-agent-core'
|
||||
|
||||
const readThreadSchema = Type.Object({
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { SandboxManager } from '@anthropic-ai/sandbox-runtime'
|
||||
import { type AgentTool, type AgentToolResult } from '@earendil-works/pi-agent-core'
|
||||
import { Type } from '@sinclair/typebox'
|
||||
import { Type } from 'typebox'
|
||||
import { spawn } from 'node:child_process'
|
||||
import { OutputAccumulator } from '../utils/output-accumulator'
|
||||
import {
|
||||
@@ -10,6 +10,8 @@ import {
|
||||
formatSize,
|
||||
type TruncationResult,
|
||||
} from '../utils/truncate'
|
||||
import { quotaService } from '@shumai/core/src/quota/quota-service'
|
||||
import type { TeamMemberRole } from '@shumai/db'
|
||||
|
||||
const BashSource = Type.String({
|
||||
enum: ['user', 'skill'],
|
||||
@@ -33,6 +35,9 @@ export interface BashDetails {
|
||||
}
|
||||
|
||||
export interface SandboxedBashOptions {
|
||||
teamId?: string
|
||||
userId?: string
|
||||
role?: TeamMemberRole | null
|
||||
getBlockedHost?: () => string
|
||||
clearBlockedHost?: () => void
|
||||
/**
|
||||
@@ -66,6 +71,18 @@ export const createSandboxedBashTool = (
|
||||
'Only commands required by a loaded skill (source="skill") can be executed.',
|
||||
)
|
||||
}
|
||||
if (options?.teamId) {
|
||||
await quotaService.checkQuota(
|
||||
{
|
||||
teamId: options.teamId,
|
||||
userId: options.userId,
|
||||
role: options.role,
|
||||
resource: 'agent_bash_call_count',
|
||||
resourceData: { command },
|
||||
},
|
||||
1,
|
||||
)
|
||||
}
|
||||
options?.clearBlockedHost?.()
|
||||
const wrappedCommand = await SandboxManager.wrapWithSandbox(command)
|
||||
|
||||
@@ -219,6 +236,23 @@ export const createSandboxedBashTool = (
|
||||
const snapshot = await finishOutput()
|
||||
const { text: outputText, details: truncationDetails } = formatOutput(snapshot)
|
||||
|
||||
if (options?.teamId) {
|
||||
try {
|
||||
await quotaService.consumeQuota(
|
||||
{
|
||||
teamId: options.teamId,
|
||||
userId: options.userId,
|
||||
role: options.role,
|
||||
resource: 'agent_bash_call_count',
|
||||
resourceData: { command },
|
||||
},
|
||||
1,
|
||||
)
|
||||
} catch (err) {
|
||||
logger.error({ err }, 'Failed to record quota usage for bash command')
|
||||
}
|
||||
}
|
||||
|
||||
if (signal?.aborted) {
|
||||
logger.error({ command, outputText }, 'Sandboxed bash command aborted')
|
||||
reject(new Error(appendStatus(outputText, 'Command aborted')))
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Type } from '@sinclair/typebox'
|
||||
import { Type } from 'typebox'
|
||||
import { type AgentTool } from '@earendil-works/pi-agent-core'
|
||||
import { type ImageContent } from '@earendil-works/pi-ai'
|
||||
import { prisma, WorkflowTaskType, WorkflowTaskStatus, type User } from '@shumai/db'
|
||||
|
||||
@@ -64,6 +64,7 @@ describe('Agent Autofill Workflow', () => {
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' })
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'a1',
|
||||
projectId: 'p1',
|
||||
storageKey: { key: 'asset-key' },
|
||||
project: { id: 'p1', teamId: 't1' },
|
||||
mediaType: 'image/png',
|
||||
@@ -78,7 +79,6 @@ describe('Agent Autofill Workflow', () => {
|
||||
{ key: 'title', config: { name: 'Title', type: 'text' }, description: 'The title' },
|
||||
])
|
||||
mockActivities.getAgentAutofillContextActivity.mockResolvedValue({ agent: { id: 'b1' } })
|
||||
mockActivities.getAssetAutofillContextActivity.mockResolvedValue('Generated using gemini')
|
||||
mockActivities.autofillAiActivity.mockResolvedValue({
|
||||
text: '{"title":"Extracted Title"}',
|
||||
sessionId: 'session-123',
|
||||
@@ -118,6 +118,9 @@ describe('Agent Autofill Workflow', () => {
|
||||
status: 'processing',
|
||||
})
|
||||
|
||||
// Verify asset fetched
|
||||
expect(mockActivities.getAssetActivity).toHaveBeenCalledWith('a1')
|
||||
|
||||
// Verify placeholder comment created
|
||||
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
|
||||
assetId: 'a1',
|
||||
@@ -140,11 +143,12 @@ describe('Agent Autofill Workflow', () => {
|
||||
expect(mockActivities.getAgentAutofillContextActivity).toHaveBeenCalledWith({
|
||||
teamId: 't1',
|
||||
})
|
||||
expect(mockActivities.getAssetAutofillContextActivity).toHaveBeenCalledWith('a1')
|
||||
|
||||
// Verify AI autofill called with mapped fields
|
||||
expect(mockActivities.autofillAiActivity).toHaveBeenCalledWith({
|
||||
teamId: 't1',
|
||||
assetId: 'a1',
|
||||
projectId: 'p1',
|
||||
images: ['/tmp/test-dir/1.webp'],
|
||||
fields: [
|
||||
{
|
||||
@@ -154,7 +158,6 @@ describe('Agent Autofill Workflow', () => {
|
||||
},
|
||||
],
|
||||
context: { agent: { id: 'b1' } },
|
||||
agentContext: 'Generated using gemini',
|
||||
})
|
||||
|
||||
// Verify task usage update
|
||||
@@ -195,42 +198,6 @@ describe('Agent Autofill Workflow', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('should run autofill without agentContext when the asset has no context', async () => {
|
||||
mockActivities.getAssetAutofillContextActivity.mockResolvedValue(null)
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'ai_metadata_autofill',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
payload: {
|
||||
projectId: 'p1',
|
||||
agent: { sessionId: 's1', agentId: 'agent-1' },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await agentAutofillMedia(task)
|
||||
|
||||
expect(mockActivities.getAssetAutofillContextActivity).toHaveBeenCalledWith('a1')
|
||||
expect(mockActivities.autofillAiActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
teamId: 't1',
|
||||
images: ['/tmp/test-dir/1.webp'],
|
||||
fields: [
|
||||
{
|
||||
id: 'title',
|
||||
config: { name: 'Title', type: 'text' },
|
||||
description: 'The title',
|
||||
},
|
||||
],
|
||||
context: { agent: { id: 'b1' } },
|
||||
}),
|
||||
)
|
||||
const aiCallArgs = mockActivities.autofillAiActivity.mock.calls[0][0]
|
||||
expect(aiCallArgs).not.toHaveProperty('agentContext')
|
||||
})
|
||||
|
||||
it('should complete early if no image files could be extracted', async () => {
|
||||
mockActivities.extractAiMetadataActivity.mockResolvedValue([])
|
||||
|
||||
|
||||
@@ -15,7 +15,6 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
extractAiMetadataActivity,
|
||||
getProjectAutofillFieldsActivity,
|
||||
getAgentAutofillContextActivity,
|
||||
getAssetAutofillContextActivity,
|
||||
autofillAiActivity,
|
||||
updateTaskUsageActivity,
|
||||
updateAssetMetadataActivity,
|
||||
@@ -132,17 +131,12 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
teamId,
|
||||
})
|
||||
|
||||
// 3c. Fetch Agent-Provided Autofill Context (from create_file/create_version)
|
||||
const agentContext = await executeActivity(
|
||||
agentWorkerQueue,
|
||||
getAssetAutofillContextActivity,
|
||||
asset.id,
|
||||
)
|
||||
|
||||
// 4. Call AI Service
|
||||
const aiResult = await executeActivity(agentWorkerQueue, autofillAiActivity, {
|
||||
teamId,
|
||||
images: generatedFiles,
|
||||
assetId: asset.id,
|
||||
projectId: asset.projectId ?? undefined,
|
||||
fields: fields.map(
|
||||
(f: { key: string; config: Record<string, unknown>; description?: string | null }) => ({
|
||||
id: f.key,
|
||||
@@ -151,7 +145,6 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
}),
|
||||
),
|
||||
context,
|
||||
...(agentContext ? { agentContext } : {}),
|
||||
})
|
||||
|
||||
if (aiResult.usage) {
|
||||
@@ -166,10 +159,12 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
|
||||
// 6. Update Asset Metadata
|
||||
const result = JSON.parse(aiResult.text)
|
||||
const metadataUpdates = Object.entries(result).map(([key, value]) => ({
|
||||
key,
|
||||
value,
|
||||
}))
|
||||
const metadataUpdates = Object.entries(result)
|
||||
.filter(([, value]) => value !== null)
|
||||
.map(([key, value]) => ({
|
||||
key,
|
||||
value,
|
||||
}))
|
||||
|
||||
if (metadataUpdates.length > 0) {
|
||||
await executeActivity(agentWorkerQueue, updateAssetMetadataActivity, {
|
||||
|
||||
@@ -118,6 +118,15 @@ describe('Agent Chat Workflow', () => {
|
||||
// Verify comment context fetched
|
||||
expect(mockActivities.getCommentActivity).toHaveBeenCalledWith('c1')
|
||||
|
||||
// Verify agent context fetched with the project context forwarded
|
||||
// (required for project-aware role enforcement in the activity)
|
||||
expect(mockActivities.getAgentChatContextActivity).toHaveBeenCalledWith({
|
||||
teamId: 't1',
|
||||
agentId: 'b1',
|
||||
userId: undefined,
|
||||
projectId: 'p1',
|
||||
})
|
||||
|
||||
// Verify placeholder comment created
|
||||
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
|
||||
assetId: 'a1',
|
||||
@@ -150,6 +159,7 @@ describe('Agent Chat Workflow', () => {
|
||||
agentsInstruction: expectedInstruction1,
|
||||
sessionId: 'session-123',
|
||||
folderId: 'parent-folder-id',
|
||||
assetId: 'a1',
|
||||
}),
|
||||
)
|
||||
|
||||
|
||||
@@ -114,6 +114,8 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
const context = await executeActivity(agentWorkerQueue, getAgentChatContextActivity, {
|
||||
teamId,
|
||||
agentId: agentId,
|
||||
userId: payload.agent?.userId,
|
||||
projectId: payload.projectId,
|
||||
})
|
||||
|
||||
const pathContext = await executeActivity(
|
||||
@@ -202,6 +204,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
imageUrls: attachmentImageUrls,
|
||||
projectId: payload.projectId,
|
||||
folderId,
|
||||
assetId: asset.id,
|
||||
agentsInstruction: instruction,
|
||||
sessionId,
|
||||
userId: payload.agent?.userId,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/api",
|
||||
"version": "0.3.4",
|
||||
"version": "0.4.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import { agentService } from '@shumai/core/src/agent/agent'
|
||||
import { authzService } from '@shumai/core/src/authz/authz'
|
||||
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
|
||||
import type { AgentInfo } from '@shumai/dtos'
|
||||
import app from './agent'
|
||||
|
||||
vi.mock('@shumai/core/src/agent/agent')
|
||||
@@ -12,6 +14,24 @@ vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
|
||||
},
|
||||
}))
|
||||
|
||||
/**
|
||||
* Shape of the agent rows returned by the (mocked) service methods. Mirrors
|
||||
* the real AgentInfoSource consumed by AgentService.toAgentInfo.
|
||||
*/
|
||||
interface MockAgentRow {
|
||||
id: string
|
||||
user: { name: string; image?: string | null }
|
||||
type: string
|
||||
enabled?: boolean
|
||||
permission?: string
|
||||
providerId?: string | null
|
||||
modelId?: string | null
|
||||
soul?: string | null
|
||||
config?: { thinkingLevel?: string; systemPrompt?: string; deniedTools?: string[] }
|
||||
skills?: Array<{ id: string; skillId: string; skill?: { id: string; name: string } }>
|
||||
mcpServers?: Array<{ mcpServerId: string }>
|
||||
}
|
||||
|
||||
describe('Agent API', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
@@ -20,6 +40,32 @@ describe('Agent API', () => {
|
||||
id: 'agent1',
|
||||
teamId: 'team1',
|
||||
} as unknown as Awaited<ReturnType<typeof agentService.getAgent>>)
|
||||
|
||||
// The route delegates AgentInfo mapping to the service; replicate the real
|
||||
// mapping so response assertions keep working.
|
||||
vi.mocked(agentService.toAgentInfo).mockImplementation(async (agent) => {
|
||||
const config = agent.config as MockAgentRow['config']
|
||||
return {
|
||||
id: agent.id,
|
||||
name: agent.user.name,
|
||||
type: agent.type,
|
||||
enabled: agent.enabled ?? true,
|
||||
permission: agent.permission ?? 'reviewer',
|
||||
avatar: agent.user.image || undefined,
|
||||
providerId: agent.providerId || undefined,
|
||||
modelId: agent.modelId || undefined,
|
||||
thinkingLevel: config?.thinkingLevel || 'off',
|
||||
systemPrompt: config?.systemPrompt,
|
||||
soul: agent.soul || undefined,
|
||||
skills: (agent.skills || []).map((s) => ({
|
||||
id: s.id,
|
||||
skillId: s.skillId,
|
||||
skill: s.skill,
|
||||
})),
|
||||
mcpServerIds: (agent.mcpServers || []).map((m) => m.mcpServerId),
|
||||
deniedTools: config?.deniedTools || [],
|
||||
} as unknown as AgentInfo
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /teams/:teamId/agents', () => {
|
||||
@@ -183,6 +229,63 @@ describe('Agent API', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('PATCH /agents/:agentId/permission', () => {
|
||||
it('updates agent permission when user is admin', async () => {
|
||||
const mockAgent = {
|
||||
id: 'agent1',
|
||||
teamId: 'team1',
|
||||
user: { name: 'Bot 1', image: 'avatar1' },
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
permission: 'owner',
|
||||
config: {
|
||||
provider: 'prov1',
|
||||
model: 'model1',
|
||||
},
|
||||
skills: [],
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(agentService.updateAgentPermission).mockResolvedValue(mockAgent as any)
|
||||
|
||||
const res = await app.request('/agents/agent1/permission', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ permission: 'owner' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.permission).toBe('owner')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: undefined,
|
||||
permission: 'Admin',
|
||||
type: 'agent',
|
||||
id: 'agent1',
|
||||
})
|
||||
expect(agentService.updateAgentPermission).toHaveBeenCalledWith('agent1', 'owner')
|
||||
expect(auditLogService.logAction).toHaveBeenCalledWith({
|
||||
action: 'agent_update',
|
||||
teamId: 'team1',
|
||||
userId: undefined,
|
||||
itemId: 'agent1',
|
||||
})
|
||||
})
|
||||
|
||||
it('denies access when user is not admin', async () => {
|
||||
vi.mocked(authzService.hasPermission).mockRejectedValue(
|
||||
new HTTPException(403, { message: 'Forbidden' }),
|
||||
)
|
||||
|
||||
const res = await app.request('/agents/agent1/permission', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ permission: 'owner' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /agent-sessions/:sessionId/entries', () => {
|
||||
it('returns entries of agent session if user is admin', async () => {
|
||||
const mockEntries = [
|
||||
@@ -258,4 +361,53 @@ describe('Agent API', () => {
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /projects/:projectId/chat-agents', () => {
|
||||
it('returns project-scoped chat agents for the user', async () => {
|
||||
const mockAgents = [
|
||||
{
|
||||
id: 'agent1',
|
||||
name: 'Chat Bot',
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
permission: 'reviewer',
|
||||
skills: [],
|
||||
mcpServerIds: [],
|
||||
deniedTools: [],
|
||||
},
|
||||
]
|
||||
vi.mocked(agentService.listProjectChatAgents).mockResolvedValue(
|
||||
mockAgents as unknown as Awaited<ReturnType<typeof agentService.listProjectChatAgents>>,
|
||||
)
|
||||
|
||||
const res = await app.request('/projects/project1/chat-agents', {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data).toHaveLength(1)
|
||||
expect(data[0].name).toBe('Chat Bot')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: undefined,
|
||||
permission: 'Read',
|
||||
type: 'project',
|
||||
id: 'project1',
|
||||
})
|
||||
expect(agentService.listProjectChatAgents).toHaveBeenCalledWith('project1', undefined)
|
||||
})
|
||||
|
||||
it('denies access when the user has no project access', async () => {
|
||||
vi.mocked(authzService.hasPermission).mockRejectedValue(
|
||||
new HTTPException(403, { message: 'Forbidden' }),
|
||||
)
|
||||
|
||||
const res = await app.request('/projects/project1/chat-agents', {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(agentService.listProjectChatAgents).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
+48
-62
@@ -2,13 +2,12 @@ import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { agentService } from '@shumai/core/src/agent/agent'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { getAvatarUrl } from '@shumai/core/src/user/avatar'
|
||||
import {
|
||||
createAgentRequestSchema,
|
||||
updateAgentRequestSchema,
|
||||
updateAgentPermissionRequestSchema,
|
||||
paginationParamsSchema,
|
||||
AgentInfo,
|
||||
AgentType,
|
||||
AuditAction,
|
||||
} from '@shumai/dtos'
|
||||
|
||||
@@ -29,34 +28,28 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const agents = await agentService.listAgents({ teamId })
|
||||
const agents = await agentService.listAgents({ teamId, userId: userReq?.id })
|
||||
|
||||
const res: AgentInfo[] = await Promise.all(
|
||||
agents.map(async (agent) => {
|
||||
const config = agent.config as unknown as PrismaJson.AgentConfig
|
||||
return {
|
||||
id: agent.id,
|
||||
name: agent.user.name,
|
||||
type: agent.type as AgentType,
|
||||
enabled: agent.enabled,
|
||||
avatar: (await getAvatarUrl(agent.user.image)) || undefined,
|
||||
providerId: agent.providerId || undefined,
|
||||
modelId: agent.modelId || undefined,
|
||||
thinkingLevel: config.thinkingLevel || 'off',
|
||||
systemPrompt: config.systemPrompt,
|
||||
soul: agent.soul || undefined,
|
||||
skills: agent.skills.map((s) => ({
|
||||
id: s.id,
|
||||
skillId: s.skillId,
|
||||
skill: s.skill,
|
||||
})),
|
||||
deniedTools: config.deniedTools || [],
|
||||
}
|
||||
}),
|
||||
agents.map((agent) => agentService.toAgentInfo(agent)),
|
||||
)
|
||||
|
||||
return c.json(res, 200)
|
||||
})
|
||||
.get('/projects/:projectId/chat-agents', async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const userReq = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user: userReq,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const agents = await agentService.listProjectChatAgents(projectId, userReq?.id)
|
||||
return c.json(agents, 200)
|
||||
})
|
||||
.post('/teams/:teamId/agents', zValidator('json', createAgentRequestSchema), async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const userReq = c.get('user')
|
||||
@@ -76,25 +69,7 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
|
||||
if (!agent) throw new Error('failed to create agent')
|
||||
|
||||
const config = agent.config as unknown as PrismaJson.AgentConfig
|
||||
const info: AgentInfo = {
|
||||
id: agent.id,
|
||||
name: agent.user.name,
|
||||
type: agent.type as AgentType,
|
||||
enabled: agent.enabled,
|
||||
avatar: (await getAvatarUrl(agent.user.image)) || undefined,
|
||||
providerId: agent.providerId || undefined,
|
||||
modelId: agent.modelId || undefined,
|
||||
thinkingLevel: config.thinkingLevel || 'off',
|
||||
systemPrompt: config.systemPrompt,
|
||||
soul: agent.soul || undefined,
|
||||
skills: agent.skills.map((s) => ({
|
||||
id: s.id,
|
||||
skillId: s.skillId,
|
||||
skill: s.skill,
|
||||
})),
|
||||
deniedTools: config.deniedTools || [],
|
||||
}
|
||||
const info = await agentService.toAgentInfo(agent)
|
||||
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.agent_create,
|
||||
@@ -129,28 +104,39 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
itemId: agent.id,
|
||||
})
|
||||
|
||||
const config = agent.config as unknown as PrismaJson.AgentConfig
|
||||
const info: AgentInfo = {
|
||||
id: agent.id,
|
||||
name: agent.user.name,
|
||||
type: agent.type as AgentType,
|
||||
enabled: agent.enabled,
|
||||
avatar: (await getAvatarUrl(agent.user.image)) || undefined,
|
||||
providerId: agent.providerId || undefined,
|
||||
modelId: agent.modelId || undefined,
|
||||
thinkingLevel: config.thinkingLevel || 'off',
|
||||
systemPrompt: config.systemPrompt,
|
||||
soul: agent.soul || undefined,
|
||||
skills: agent.skills.map((s) => ({
|
||||
id: s.id,
|
||||
skillId: s.skillId,
|
||||
skill: s.skill,
|
||||
})),
|
||||
deniedTools: config.deniedTools || [],
|
||||
}
|
||||
const info = await agentService.toAgentInfo(agent)
|
||||
|
||||
return c.json(info, 200)
|
||||
})
|
||||
.patch(
|
||||
'/agents/:agentId/permission',
|
||||
zValidator('json', updateAgentPermissionRequestSchema),
|
||||
async (c) => {
|
||||
const agentId = c.req.param('agentId')
|
||||
const userReq = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user: userReq,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Agent,
|
||||
id: agentId,
|
||||
})
|
||||
|
||||
const agent = await agentService.updateAgentPermission(agentId, req.permission)
|
||||
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.agent_update,
|
||||
teamId: agent.teamId,
|
||||
userId: userReq?.id,
|
||||
itemId: agent.id,
|
||||
})
|
||||
|
||||
const info = await agentService.toAgentInfo(agent)
|
||||
|
||||
return c.json(info, 200)
|
||||
},
|
||||
)
|
||||
.delete('/agents/:agentId', async (c) => {
|
||||
const agentId = c.req.param('agentId')
|
||||
const userReq = c.get('user')
|
||||
|
||||
@@ -188,6 +188,46 @@ describe('folder api', () => {
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
expect(assetService.listChildren).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
assetType: 'folder',
|
||||
})
|
||||
})
|
||||
|
||||
it('GET /folders/:folderId/children forwards pagination parameters', async () => {
|
||||
vi.mocked(assetService.listChildren).mockResolvedValue({
|
||||
data: [
|
||||
{
|
||||
id: 'child-id-2',
|
||||
name: 'child-folder-2',
|
||||
sizeByte: 0,
|
||||
fileCount: 0,
|
||||
type: 'folder',
|
||||
status: 'active',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
],
|
||||
pageInfo: { total: 30, cursor: 'cursorNextToken' },
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request(
|
||||
'/folders/test-id/children?assetType=folder&first=20&after=cursorToken123&prefix=sub',
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.data).toHaveLength(1)
|
||||
expect(json.pageInfo.cursor).toBe('cursorNextToken')
|
||||
|
||||
expect(assetService.listChildren).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
assetType: 'folder',
|
||||
first: 20,
|
||||
after: 'cursorToken123',
|
||||
prefix: 'sub',
|
||||
})
|
||||
})
|
||||
|
||||
it('DELETE /folders', async () => {
|
||||
@@ -310,4 +350,59 @@ describe('folder api', () => {
|
||||
beforeIndex: 'index-1',
|
||||
})
|
||||
})
|
||||
|
||||
it('GET /folders/:folderId/agentsmd', async () => {
|
||||
vi.spyOn(assetService, 'getAgentsMd').mockResolvedValue('# Folder Guidelines')
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/folders/test-id/agentsmd')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.content).toBe('# Folder Guidelines')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
expect(assetService.getAgentsMd).toHaveBeenCalledWith('test-id')
|
||||
})
|
||||
|
||||
it('PATCH /folders/:folderId/agentsmd', async () => {
|
||||
vi.spyOn(assetService, 'updateAgentsMd').mockResolvedValue({ content: '# Updated Guidelines' })
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/folders/test-id/agentsmd', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ content: '# Updated Guidelines' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.content).toBe('# Updated Guidelines')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
expect(assetService.updateAgentsMd).toHaveBeenCalledWith('test-id', '# Updated Guidelines')
|
||||
})
|
||||
|
||||
it('PATCH /folders/:folderId/agentsmd rejects oversized content', async () => {
|
||||
const mockUpdate = vi.spyOn(assetService, 'updateAgentsMd').mockResolvedValue({ content: '' })
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/folders/test-id/agentsmd', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ content: 'x'.repeat(100_001) }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
expect(mockUpdate).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
updateFolderRequestSchema,
|
||||
deleteFoldersRequestSchema,
|
||||
restoreFoldersRequestSchema,
|
||||
updateAgentsMdRequestSchema,
|
||||
} from '@shumai/dtos'
|
||||
import { listChildrenRequestSchema, updateAssetOrderRequestSchema, AuditAction } from '@shumai/dtos'
|
||||
import { searchRequestSchema } from '@shumai/dtos'
|
||||
@@ -119,12 +120,8 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
})
|
||||
|
||||
const resp = await assetService.listChildren({
|
||||
...req,
|
||||
assetId: folderId,
|
||||
assetType: req.assetType,
|
||||
projectId: req.projectId,
|
||||
showDeleted: req.showDeleted,
|
||||
sort: req.sort,
|
||||
order: req.order,
|
||||
})
|
||||
return c.json(resp)
|
||||
})
|
||||
@@ -189,5 +186,48 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const result = await searchService.search(folderId, req)
|
||||
return c.json(result)
|
||||
})
|
||||
.get('/folders/:folderId/agentsmd', async (c) => {
|
||||
const folderId = c.req.param('folderId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: folderId,
|
||||
})
|
||||
|
||||
const content = await assetService.getAgentsMd(folderId)
|
||||
return c.json({ content })
|
||||
})
|
||||
.patch(
|
||||
'/folders/:folderId/agentsmd',
|
||||
zValidator('json', updateAgentsMdRequestSchema),
|
||||
async (c) => {
|
||||
const folderId = c.req.param('folderId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Asset,
|
||||
id: folderId,
|
||||
})
|
||||
|
||||
const res = await assetService.updateAgentsMd(folderId, req.content)
|
||||
|
||||
const ctx = await assetService.getAssetContext(folderId)
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.folder_update,
|
||||
teamId: ctx.teamId,
|
||||
userId: user.id,
|
||||
projectId: ctx.projectId,
|
||||
itemId: folderId,
|
||||
})
|
||||
|
||||
return c.json(res)
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
|
||||
@@ -9,6 +9,7 @@ import fileRoute from './file'
|
||||
import folderRoute from './folder'
|
||||
import inviteRoute from './invite'
|
||||
import metadataRoute from './metadata'
|
||||
import mcpRoute, { mcpOauthCallbackRoute } from './mcp'
|
||||
import { authMiddleware } from './middleware/auth'
|
||||
import { tokenAuthMiddleware } from './middleware/tokenAuth'
|
||||
import notificationRoute from './notification'
|
||||
@@ -20,9 +21,11 @@ import s3Route from './s3'
|
||||
import shareRoute from './share'
|
||||
import skillRoute from './skill'
|
||||
import watermarkTemplateRoute from './watermark-template'
|
||||
import quotaRoute from './quota'
|
||||
import teamRoute from './team'
|
||||
import uploadRoute, { localUploadRoute } from './upload'
|
||||
import versionStackRoute from './versionStack'
|
||||
import kanbanRoute from './kanban'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
@@ -34,6 +37,7 @@ const apiRoute = new Hono<{ Variables: { user: User } }>()
|
||||
.route('/', publicInviteRoute)
|
||||
.route('/', publicShareRoute)
|
||||
.route('/', localUploadRoute)
|
||||
.route('/', mcpOauthCallbackRoute)
|
||||
|
||||
// Selected routes supporting API token authentication
|
||||
.use('/projects', tokenAuthMiddleware)
|
||||
@@ -61,7 +65,10 @@ const apiRoute = new Hono<{ Variables: { user: User } }>()
|
||||
.route('/', uploadRoute)
|
||||
.route('/', shareRoute)
|
||||
.route('/', skillRoute)
|
||||
.route('/', mcpRoute)
|
||||
.route('/', watermarkTemplateRoute)
|
||||
.route('/', quotaRoute)
|
||||
.route('/', kanbanRoute)
|
||||
|
||||
app.route('/files', s3Route)
|
||||
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { Hono } from 'hono'
|
||||
import { kanbanService } from '@shumai/core/src/kanban/kanban'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
|
||||
import {
|
||||
authzService,
|
||||
Permission,
|
||||
ResourceType,
|
||||
resolveEffectiveRole,
|
||||
} from '@shumai/core/src/authz/authz'
|
||||
import { createKanbanCommentSchema, postAttachmentRequestSchema, AuditAction } from '@shumai/dtos'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.post(
|
||||
'/teams/:teamId/kanban/attachments',
|
||||
zValidator('json', postAttachmentRequestSchema),
|
||||
async (c) => {
|
||||
const { teamId } = c.req.param()
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const attachment = await kanbanService.createAttachment(teamId, req)
|
||||
return c.json(attachment)
|
||||
},
|
||||
)
|
||||
.post(
|
||||
'/teams/:teamId/kanban/tasks/:taskId/comments',
|
||||
zValidator('json', createKanbanCommentSchema),
|
||||
async (c) => {
|
||||
const { teamId, taskId } = c.req.param()
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.KanbanTask,
|
||||
id: taskId,
|
||||
})
|
||||
|
||||
const comment = await kanbanService.addComment(taskId, user.id, req.body, req.attachments)
|
||||
const task = await kanbanService.getTask(taskId)
|
||||
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.kanban_comment_create,
|
||||
teamId,
|
||||
userId: user.id,
|
||||
projectId: task.projectId ?? undefined,
|
||||
itemId: comment.id,
|
||||
})
|
||||
|
||||
notificationService.notifyKanbanTaskEvent({
|
||||
type: 'kanban_task_comment_created',
|
||||
teamId,
|
||||
projectId: task.projectId,
|
||||
creatorId: user.id,
|
||||
kanbanTaskId: taskId,
|
||||
stakeholderIds: [task.creator?.id, task.assignee?.id, task.reporter?.id],
|
||||
commentMessage: req.body,
|
||||
})
|
||||
|
||||
return c.json(comment)
|
||||
},
|
||||
)
|
||||
.get('/teams/:teamId/kanban/tasks/:taskId/comments', async (c) => {
|
||||
const { taskId } = c.req.param()
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.KanbanTask,
|
||||
id: taskId,
|
||||
})
|
||||
|
||||
const comments = await kanbanService.listComments(taskId)
|
||||
return c.json({ data: comments })
|
||||
})
|
||||
.delete('/teams/:teamId/kanban/tasks/:taskId/comments/:commentId', async (c) => {
|
||||
const { teamId, taskId, commentId } = c.req.param()
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.KanbanTask,
|
||||
id: taskId,
|
||||
})
|
||||
|
||||
const userRole = await resolveEffectiveRole(teamId, undefined, user.id)
|
||||
const task = await kanbanService.getTask(taskId)
|
||||
await kanbanService.deleteComment(taskId, commentId, user.id, userRole)
|
||||
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.kanban_comment_delete,
|
||||
teamId,
|
||||
userId: user.id,
|
||||
projectId: task.projectId ?? undefined,
|
||||
itemId: commentId,
|
||||
})
|
||||
|
||||
return c.json({ success: true })
|
||||
})
|
||||
.get('/teams/:teamId/kanban/tasks/:taskId/events', async (c) => {
|
||||
const { taskId } = c.req.param()
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.KanbanTask,
|
||||
id: taskId,
|
||||
})
|
||||
|
||||
const events = await kanbanService.listEvents(taskId)
|
||||
return c.json({ data: events })
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,131 @@
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { Hono } from 'hono'
|
||||
import { kanbanService } from '@shumai/core/src/kanban/kanban'
|
||||
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
|
||||
import {
|
||||
authzService,
|
||||
Permission,
|
||||
ResourceType,
|
||||
resolveEffectiveRole,
|
||||
} from '@shumai/core/src/authz/authz'
|
||||
import {
|
||||
createKanbanGoalSchema,
|
||||
updateKanbanGoalSchema,
|
||||
listKanbanGoalsRequestSchema,
|
||||
AuditAction,
|
||||
} from '@shumai/dtos'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.post('/teams/:teamId/kanban/goals', zValidator('json', createKanbanGoalSchema), async (c) => {
|
||||
const { teamId } = c.req.param()
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const role = await resolveEffectiveRole(teamId, undefined, user.id)
|
||||
const goal = await kanbanService.createGoal(teamId, req, user.id, role)
|
||||
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.kanban_goal_create,
|
||||
teamId,
|
||||
userId: user.id,
|
||||
itemId: goal.id,
|
||||
})
|
||||
|
||||
return c.json(goal)
|
||||
})
|
||||
.get(
|
||||
'/teams/:teamId/kanban/goals',
|
||||
zValidator('query', listKanbanGoalsRequestSchema),
|
||||
async (c) => {
|
||||
const { teamId } = c.req.param()
|
||||
const req = c.req.valid('query')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const goals = await kanbanService.listGoals(teamId, req)
|
||||
return c.json({ data: goals })
|
||||
},
|
||||
)
|
||||
.get('/teams/:teamId/kanban/goals/:goalId', async (c) => {
|
||||
const { goalId } = c.req.param()
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.KanbanGoal,
|
||||
id: goalId,
|
||||
})
|
||||
|
||||
const goal = await kanbanService.getGoal(goalId)
|
||||
return c.json(goal)
|
||||
})
|
||||
.patch(
|
||||
'/teams/:teamId/kanban/goals/:goalId',
|
||||
zValidator('json', updateKanbanGoalSchema),
|
||||
async (c) => {
|
||||
const { teamId, goalId } = c.req.param()
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.KanbanGoal,
|
||||
id: goalId,
|
||||
})
|
||||
|
||||
const role = await resolveEffectiveRole(teamId, undefined, user.id)
|
||||
const goal = await kanbanService.updateGoal(goalId, req, role)
|
||||
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.kanban_goal_update,
|
||||
teamId,
|
||||
userId: user.id,
|
||||
itemId: goalId,
|
||||
})
|
||||
|
||||
return c.json(goal)
|
||||
},
|
||||
)
|
||||
.delete('/teams/:teamId/kanban/goals/:goalId', async (c) => {
|
||||
const { teamId, goalId } = c.req.param()
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.KanbanGoal,
|
||||
id: goalId,
|
||||
})
|
||||
|
||||
const role = await resolveEffectiveRole(teamId, undefined, user.id)
|
||||
await kanbanService.deleteGoal(goalId, role)
|
||||
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.kanban_goal_delete,
|
||||
teamId,
|
||||
userId: user.id,
|
||||
itemId: goalId,
|
||||
})
|
||||
|
||||
return c.json({ ok: true })
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
import goalsRoute from './goals'
|
||||
import tasksRoute from './tasks'
|
||||
import commentsRoute from './comments'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const kanbanRoute = new Hono<{ Variables: { user: User } }>()
|
||||
.route('/', goalsRoute)
|
||||
.route('/', tasksRoute)
|
||||
.route('/', commentsRoute)
|
||||
|
||||
export default kanbanRoute
|
||||
@@ -0,0 +1,689 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { Hono, type Context, type Next } from 'hono'
|
||||
import { kanbanService } from '@shumai/core/src/kanban/kanban'
|
||||
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
import { KanbanTaskStatus, KanbanTaskPriority } from '@shumai/db/enums'
|
||||
import kanbanRoute from './index'
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
resolveEffectiveRole: vi.fn().mockResolvedValue('owner'),
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
ResourceType: {
|
||||
Team: 'team',
|
||||
Project: 'project',
|
||||
KanbanGoal: 'kanbanGoal',
|
||||
KanbanTask: 'kanbanTask',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
|
||||
auditLogService: {
|
||||
logAction: vi.fn().mockResolvedValue({}),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/notification/notification', () => ({
|
||||
notificationService: {
|
||||
notifyKanbanTaskEvent: vi.fn().mockResolvedValue(undefined),
|
||||
create: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('Kanban API Routes', () => {
|
||||
const teamId = 'team-1'
|
||||
const taskId = 'task-1'
|
||||
const goalId = 'goal-1'
|
||||
|
||||
const authMiddleware = async (c: Context, next: Next) => {
|
||||
c.set('user', { id: 'user-1', name: 'Test User' })
|
||||
await next()
|
||||
}
|
||||
|
||||
let app: Hono
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(auditLogService.logAction).mockResolvedValue({} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(notificationService.notifyKanbanTaskEvent).mockResolvedValue(undefined as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
app = new Hono()
|
||||
app.use('*', authMiddleware)
|
||||
app.route('/', kanbanRoute)
|
||||
})
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Goals Endpoints
|
||||
// --------------------------------------------------------------------------
|
||||
describe('Goals Endpoints', () => {
|
||||
it('POST /teams/:teamId/kanban/goals', async () => {
|
||||
const mockCreate = vi.spyOn(kanbanService, 'createGoal').mockResolvedValue({
|
||||
id: goalId,
|
||||
title: 'New Goal',
|
||||
description: 'Goal description',
|
||||
teamId,
|
||||
creatorId: 'user-1',
|
||||
taskCount: 0,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const res = await app.request(`/teams/${teamId}/kanban/goals`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ title: 'New Goal', description: 'Goal description' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.id).toBe(goalId)
|
||||
expect(mockCreate).toHaveBeenCalledWith(
|
||||
teamId,
|
||||
{ title: 'New Goal', description: 'Goal description' },
|
||||
'user-1',
|
||||
'owner',
|
||||
)
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/kanban/goals', async () => {
|
||||
const mockList = vi.spyOn(kanbanService, 'listGoals').mockResolvedValue([
|
||||
{
|
||||
id: goalId,
|
||||
title: 'Goal 1',
|
||||
teamId,
|
||||
creatorId: 'user-1',
|
||||
taskCount: 0,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
])
|
||||
|
||||
const res = await app.request(`/teams/${teamId}/kanban/goals`)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.data).toHaveLength(1)
|
||||
expect(mockList).toHaveBeenCalledWith(teamId, expect.any(Object))
|
||||
})
|
||||
|
||||
it('PATCH /teams/:teamId/kanban/goals/:goalId', async () => {
|
||||
const mockUpdate = vi.spyOn(kanbanService, 'updateGoal').mockResolvedValue({
|
||||
id: goalId,
|
||||
title: 'Updated Goal',
|
||||
teamId,
|
||||
creatorId: 'user-1',
|
||||
taskCount: 0,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const res = await app.request(`/teams/${teamId}/kanban/goals/${goalId}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ title: 'Updated Goal' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.title).toBe('Updated Goal')
|
||||
expect(mockUpdate).toHaveBeenCalledWith(goalId, { title: 'Updated Goal' }, 'owner')
|
||||
})
|
||||
|
||||
it('DELETE /teams/:teamId/kanban/goals/:goalId', async () => {
|
||||
const mockDelete = vi.spyOn(kanbanService, 'deleteGoal').mockResolvedValue(undefined)
|
||||
|
||||
const res = await app.request(`/teams/${teamId}/kanban/goals/${goalId}`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.ok).toBe(true)
|
||||
expect(mockDelete).toHaveBeenCalledWith(goalId, 'owner')
|
||||
})
|
||||
})
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Tasks Endpoints
|
||||
// --------------------------------------------------------------------------
|
||||
describe('Tasks Endpoints', () => {
|
||||
it('POST /teams/:teamId/kanban/tasks', async () => {
|
||||
const mockCreate = vi.spyOn(kanbanService, 'createTask').mockResolvedValue({
|
||||
id: taskId,
|
||||
title: 'New Task',
|
||||
isAgentTask: false,
|
||||
status: KanbanTaskStatus.READY,
|
||||
priority: KanbanTaskPriority.MEDIUM,
|
||||
teamId,
|
||||
creator: { id: 'user-1', name: 'User 1' },
|
||||
commentCount: 0,
|
||||
dependencyCount: 0,
|
||||
dependentCount: 0,
|
||||
assetCount: 0,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const res = await app.request(`/teams/${teamId}/kanban/tasks`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ title: 'New Task', isAgentTask: false }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.id).toBe(taskId)
|
||||
expect(mockCreate).toHaveBeenCalledWith(teamId, expect.any(Object), 'user-1', 'owner')
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/kanban/tasks (with isAgentTask and goal filters)', async () => {
|
||||
const mockList = vi.spyOn(kanbanService, 'listTasks').mockResolvedValue({
|
||||
data: [
|
||||
{
|
||||
id: taskId,
|
||||
title: 'Task 1',
|
||||
isAgentTask: false,
|
||||
status: KanbanTaskStatus.READY,
|
||||
priority: KanbanTaskPriority.MEDIUM,
|
||||
teamId,
|
||||
creator: { id: 'user-1', name: 'User 1' },
|
||||
commentCount: 0,
|
||||
dependencyCount: 0,
|
||||
dependentCount: 0,
|
||||
assetCount: 0,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
],
|
||||
pageInfo: { total: 1 },
|
||||
})
|
||||
|
||||
const res = await app.request(
|
||||
`/teams/${teamId}/kanban/tasks?isAgentTask=false&status=READY&goalId=goal-1`,
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.data).toHaveLength(1)
|
||||
expect(mockList).toHaveBeenCalledWith(
|
||||
teamId,
|
||||
expect.objectContaining({
|
||||
isAgentTask: false,
|
||||
status: 'READY',
|
||||
goalId: 'goal-1',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/kanban/tasks/:taskId', async () => {
|
||||
const mockGet = vi.spyOn(kanbanService, 'getTask').mockResolvedValue({
|
||||
id: taskId,
|
||||
title: 'Task 1',
|
||||
isAgentTask: false,
|
||||
status: KanbanTaskStatus.READY,
|
||||
priority: KanbanTaskPriority.MEDIUM,
|
||||
teamId,
|
||||
creator: { id: 'user-1', name: 'User 1' },
|
||||
dependencies: [],
|
||||
dependents: [],
|
||||
assets: [],
|
||||
comments: [],
|
||||
events: [],
|
||||
commentCount: 0,
|
||||
dependencyCount: 0,
|
||||
dependentCount: 0,
|
||||
assetCount: 0,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const res = await app.request(`/teams/${teamId}/kanban/tasks/${taskId}`)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.id).toBe(taskId)
|
||||
expect(mockGet).toHaveBeenCalledWith(taskId)
|
||||
})
|
||||
|
||||
it('PATCH /teams/:teamId/kanban/tasks/:taskId', async () => {
|
||||
vi.spyOn(kanbanService, 'getTask').mockResolvedValue({
|
||||
id: taskId,
|
||||
title: 'Old Task Title',
|
||||
isAgentTask: false,
|
||||
status: KanbanTaskStatus.READY,
|
||||
priority: KanbanTaskPriority.MEDIUM,
|
||||
teamId,
|
||||
creator: { id: 'user-1', name: 'User 1' },
|
||||
dependencies: [],
|
||||
dependents: [],
|
||||
assets: [],
|
||||
comments: [],
|
||||
events: [],
|
||||
commentCount: 0,
|
||||
dependencyCount: 0,
|
||||
dependentCount: 0,
|
||||
assetCount: 0,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
const mockUpdate = vi.spyOn(kanbanService, 'updateTask').mockResolvedValue({
|
||||
id: taskId,
|
||||
title: 'Updated Task Title',
|
||||
isAgentTask: false,
|
||||
status: KanbanTaskStatus.READY,
|
||||
priority: KanbanTaskPriority.HIGH,
|
||||
teamId,
|
||||
creator: { id: 'user-1', name: 'User 1' },
|
||||
commentCount: 0,
|
||||
dependencyCount: 0,
|
||||
dependentCount: 0,
|
||||
assetCount: 0,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const res = await app.request(`/teams/${teamId}/kanban/tasks/${taskId}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ priority: 'HIGH', status: 'DONE', reason: 'All done' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(mockUpdate).toHaveBeenCalledWith(
|
||||
taskId,
|
||||
{ priority: 'HIGH', status: 'DONE', reason: 'All done' },
|
||||
'user-1',
|
||||
'owner',
|
||||
)
|
||||
})
|
||||
|
||||
it('PATCH /teams/:teamId/kanban/tasks/:taskId with beforeIndex and afterIndex', async () => {
|
||||
vi.spyOn(kanbanService, 'getTask').mockResolvedValue({
|
||||
id: taskId,
|
||||
title: 'Task 1',
|
||||
isAgentTask: false,
|
||||
status: KanbanTaskStatus.READY,
|
||||
priority: KanbanTaskPriority.MEDIUM,
|
||||
sortIndex: 'a0V',
|
||||
teamId,
|
||||
creator: { id: 'user-1', name: 'User 1' },
|
||||
dependencies: [],
|
||||
dependents: [],
|
||||
assets: [],
|
||||
comments: [],
|
||||
events: [],
|
||||
commentCount: 0,
|
||||
dependencyCount: 0,
|
||||
dependentCount: 0,
|
||||
assetCount: 0,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
const mockUpdate = vi.spyOn(kanbanService, 'updateTask').mockResolvedValue({
|
||||
id: taskId,
|
||||
title: 'Task 1',
|
||||
isAgentTask: false,
|
||||
status: KanbanTaskStatus.READY,
|
||||
priority: KanbanTaskPriority.MEDIUM,
|
||||
sortIndex: 'a0V',
|
||||
teamId,
|
||||
creator: { id: 'user-1', name: 'User 1' },
|
||||
commentCount: 0,
|
||||
dependencyCount: 0,
|
||||
dependentCount: 0,
|
||||
assetCount: 0,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const res = await app.request(`/teams/${teamId}/kanban/tasks/${taskId}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ status: 'READY', beforeIndex: 'a1', afterIndex: 'a0' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(mockUpdate).toHaveBeenCalledWith(
|
||||
taskId,
|
||||
{ status: 'READY', beforeIndex: 'a1', afterIndex: 'a0' },
|
||||
'user-1',
|
||||
'owner',
|
||||
)
|
||||
})
|
||||
|
||||
it('PATCH /teams/:teamId/kanban/tasks/:taskId with fromStatus for CAS', async () => {
|
||||
vi.spyOn(kanbanService, 'getTask').mockResolvedValue({
|
||||
id: taskId,
|
||||
title: 'Task 1',
|
||||
isAgentTask: false,
|
||||
status: KanbanTaskStatus.TODO,
|
||||
priority: KanbanTaskPriority.MEDIUM,
|
||||
teamId,
|
||||
creator: { id: 'user-1', name: 'User 1' },
|
||||
dependencies: [],
|
||||
dependents: [],
|
||||
assets: [],
|
||||
comments: [],
|
||||
events: [],
|
||||
commentCount: 0,
|
||||
dependencyCount: 0,
|
||||
dependentCount: 0,
|
||||
assetCount: 0,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
const mockUpdate = vi.spyOn(kanbanService, 'updateTask').mockResolvedValue({
|
||||
id: taskId,
|
||||
title: 'Task 1',
|
||||
isAgentTask: false,
|
||||
status: KanbanTaskStatus.IN_PROGRESS,
|
||||
priority: KanbanTaskPriority.MEDIUM,
|
||||
teamId,
|
||||
creator: { id: 'user-1', name: 'User 1' },
|
||||
commentCount: 0,
|
||||
dependencyCount: 0,
|
||||
dependentCount: 0,
|
||||
assetCount: 0,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const res = await app.request(`/teams/${teamId}/kanban/tasks/${taskId}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ fromStatus: 'TODO', status: 'IN_PROGRESS' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(mockUpdate).toHaveBeenCalledWith(
|
||||
taskId,
|
||||
{ fromStatus: 'TODO', status: 'IN_PROGRESS' },
|
||||
'user-1',
|
||||
'owner',
|
||||
)
|
||||
})
|
||||
|
||||
it('DELETE /teams/:teamId/kanban/tasks/:taskId', async () => {
|
||||
vi.spyOn(kanbanService, 'getTask').mockResolvedValue({
|
||||
id: taskId,
|
||||
title: 'Task to delete',
|
||||
isAgentTask: false,
|
||||
status: KanbanTaskStatus.READY,
|
||||
priority: KanbanTaskPriority.MEDIUM,
|
||||
teamId,
|
||||
creator: { id: 'user-1', name: 'User 1' },
|
||||
dependencies: [],
|
||||
dependents: [],
|
||||
assets: [],
|
||||
comments: [],
|
||||
events: [],
|
||||
commentCount: 0,
|
||||
dependencyCount: 0,
|
||||
dependentCount: 0,
|
||||
assetCount: 0,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
const mockDelete = vi.spyOn(kanbanService, 'deleteTask').mockResolvedValue({
|
||||
id: taskId,
|
||||
title: 'Task to delete',
|
||||
isAgentTask: false,
|
||||
status: KanbanTaskStatus.READY,
|
||||
priority: KanbanTaskPriority.MEDIUM,
|
||||
teamId,
|
||||
creator: { id: 'user-1', name: 'User 1' },
|
||||
commentCount: 0,
|
||||
dependencyCount: 0,
|
||||
dependentCount: 0,
|
||||
assetCount: 0,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const res = await app.request(`/teams/${teamId}/kanban/tasks/${taskId}`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.success).toBe(true)
|
||||
expect(mockDelete).toHaveBeenCalledWith(taskId, 'user-1', 'owner')
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/kanban/tasks/:taskId/assets', async () => {
|
||||
const mockListTaskAssets = vi.spyOn(kanbanService, 'listTaskAssets').mockResolvedValue([
|
||||
{
|
||||
id: 'asset-1',
|
||||
name: 'Video.mp4',
|
||||
type: 'file',
|
||||
proxyType: 'video',
|
||||
thumbnailUrl: 'http://example.com/thumb.jpg',
|
||||
path: '/Project/Video.mp4',
|
||||
creator: { id: 'user-1', name: 'User 1' },
|
||||
createdAt: new Date().toISOString(),
|
||||
},
|
||||
])
|
||||
|
||||
const res = await app.request(`/teams/${teamId}/kanban/tasks/${taskId}/assets`)
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json).toHaveLength(1)
|
||||
expect(json[0].name).toBe('Video.mp4')
|
||||
expect(mockListTaskAssets).toHaveBeenCalledWith(taskId)
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/kanban/tasks/:taskId/assets', async () => {
|
||||
const mockLinkAssets = vi.spyOn(kanbanService, 'linkAssets').mockResolvedValue(undefined)
|
||||
|
||||
const res = await app.request(`/teams/${teamId}/kanban/tasks/${taskId}/assets`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ assetIds: ['asset-1', 'asset-2'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.success).toBe(true)
|
||||
expect(mockLinkAssets).toHaveBeenCalledWith(teamId, taskId, ['asset-1', 'asset-2'])
|
||||
})
|
||||
|
||||
it('DELETE /teams/:teamId/kanban/tasks/:taskId/assets/:assetId', async () => {
|
||||
const mockUnlinkAsset = vi.spyOn(kanbanService, 'unlinkAsset').mockResolvedValue(undefined)
|
||||
|
||||
const res = await app.request(`/teams/${teamId}/kanban/tasks/${taskId}/assets/asset-1`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.success).toBe(true)
|
||||
expect(mockUnlinkAsset).toHaveBeenCalledWith(teamId, taskId, 'asset-1')
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/kanban/assets/:assetId/tasks', async () => {
|
||||
const mockListTasksForAsset = vi.spyOn(kanbanService, 'listTasksForAsset').mockResolvedValue([
|
||||
{
|
||||
id: taskId,
|
||||
title: 'Task linked to asset',
|
||||
isAgentTask: false,
|
||||
status: KanbanTaskStatus.READY,
|
||||
priority: KanbanTaskPriority.MEDIUM,
|
||||
teamId,
|
||||
creator: { id: 'user-1', name: 'User 1' },
|
||||
commentCount: 0,
|
||||
dependencyCount: 0,
|
||||
dependentCount: 0,
|
||||
assetCount: 1,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
])
|
||||
|
||||
const res = await app.request(`/teams/${teamId}/kanban/assets/asset-1/tasks`)
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.total).toBe(1)
|
||||
expect(json.data).toHaveLength(1)
|
||||
expect(mockListTasksForAsset).toHaveBeenCalledWith(teamId, 'asset-1')
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/kanban/assets/:assetId/tasks', async () => {
|
||||
const mockLinkAsset = vi.spyOn(kanbanService, 'linkAsset').mockResolvedValue(undefined)
|
||||
|
||||
const res = await app.request(`/teams/${teamId}/kanban/assets/asset-1/tasks`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ taskId }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.success).toBe(true)
|
||||
expect(mockLinkAsset).toHaveBeenCalledWith(teamId, taskId, 'asset-1')
|
||||
})
|
||||
|
||||
it('DELETE /teams/:teamId/kanban/assets/:assetId/tasks/:taskId', async () => {
|
||||
const mockUnlinkAsset = vi.spyOn(kanbanService, 'unlinkAsset').mockResolvedValue(undefined)
|
||||
|
||||
const res = await app.request(`/teams/${teamId}/kanban/assets/asset-1/tasks/${taskId}`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.success).toBe(true)
|
||||
expect(mockUnlinkAsset).toHaveBeenCalledWith(teamId, taskId, 'asset-1')
|
||||
})
|
||||
})
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Comments, Attachments & Events
|
||||
// --------------------------------------------------------------------------
|
||||
describe('Comments, Attachments and Events Endpoints', () => {
|
||||
it('POST /teams/:teamId/kanban/attachments', async () => {
|
||||
const mockAttachment = vi.spyOn(kanbanService, 'createAttachment').mockResolvedValue({
|
||||
id: 'att-1',
|
||||
name: 'test.png',
|
||||
key: 'kanban/attachments/test.png',
|
||||
sizeByte: 1024,
|
||||
uploadUrl: 'http://s3/upload',
|
||||
proxyType: 'image',
|
||||
})
|
||||
|
||||
const res = await app.request(`/teams/${teamId}/kanban/attachments`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ fileName: 'test.png', size: 1024, contentType: 'image/png' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.id).toBe('att-1')
|
||||
expect(mockAttachment).toHaveBeenCalledWith(teamId, {
|
||||
fileName: 'test.png',
|
||||
size: 1024,
|
||||
contentType: 'image/png',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/kanban/tasks/:taskId/comments', async () => {
|
||||
const mockAdd = vi.spyOn(kanbanService, 'addComment').mockResolvedValue({
|
||||
id: 'c-1',
|
||||
taskId,
|
||||
author: { id: 'user-1', name: 'User 1' },
|
||||
body: 'Here is a note',
|
||||
attachments: [],
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const res = await app.request(`/teams/${teamId}/kanban/tasks/${taskId}/comments`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
body: 'Here is a note',
|
||||
attachments: [
|
||||
{
|
||||
id: 'att-1',
|
||||
name: 'test.png',
|
||||
key: 'key-1',
|
||||
sizeByte: 1024,
|
||||
proxyType: 'image',
|
||||
},
|
||||
],
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(mockAdd).toHaveBeenCalledWith(taskId, 'user-1', 'Here is a note', [
|
||||
{
|
||||
id: 'att-1',
|
||||
name: 'test.png',
|
||||
key: 'key-1',
|
||||
sizeByte: 1024,
|
||||
proxyType: 'image',
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
it('DELETE /teams/:teamId/kanban/tasks/:taskId/comments/:commentId', async () => {
|
||||
const mockDelete = vi.spyOn(kanbanService, 'deleteComment').mockResolvedValue()
|
||||
|
||||
const res = await app.request(`/teams/${teamId}/kanban/tasks/${taskId}/comments/c-1`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.success).toBe(true)
|
||||
expect(mockDelete).toHaveBeenCalledWith(taskId, 'c-1', 'user-1', 'owner')
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/kanban/tasks/:taskId/comments', async () => {
|
||||
const mockList = vi.spyOn(kanbanService, 'listComments').mockResolvedValue([
|
||||
{
|
||||
id: 'c-1',
|
||||
taskId,
|
||||
author: { id: 'user-1', name: 'User 1' },
|
||||
body: 'Note',
|
||||
attachments: [],
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
])
|
||||
|
||||
const res = await app.request(`/teams/${teamId}/kanban/tasks/${taskId}/comments`)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.data).toHaveLength(1)
|
||||
expect(mockList).toHaveBeenCalledWith(taskId)
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/kanban/tasks/:taskId/events', async () => {
|
||||
const mockEvents = vi.spyOn(kanbanService, 'listEvents').mockResolvedValue([
|
||||
{
|
||||
id: 'e-1',
|
||||
taskId,
|
||||
actor: { id: 'user-1', name: 'User 1' },
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
type: 'CREATED' as any,
|
||||
createdAt: new Date().toISOString(),
|
||||
},
|
||||
])
|
||||
|
||||
const res = await app.request(`/teams/${teamId}/kanban/tasks/${taskId}/events`)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.data).toHaveLength(1)
|
||||
expect(mockEvents).toHaveBeenCalledWith(taskId)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,331 @@
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { Hono } from 'hono'
|
||||
import { kanbanService } from '@shumai/core/src/kanban/kanban'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
|
||||
import {
|
||||
authzService,
|
||||
Permission,
|
||||
ResourceType,
|
||||
resolveEffectiveRole,
|
||||
} from '@shumai/core/src/authz/authz'
|
||||
import {
|
||||
createKanbanTaskSchema,
|
||||
updateKanbanTaskSchema,
|
||||
listKanbanTasksRequestSchema,
|
||||
linkTaskAssetsSchema,
|
||||
linkAssetToTaskSchema,
|
||||
AuditAction,
|
||||
} from '@shumai/dtos'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.post('/teams/:teamId/kanban/tasks', zValidator('json', createKanbanTaskSchema), async (c) => {
|
||||
const { teamId } = c.req.param()
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const role = await resolveEffectiveRole(teamId, undefined, user.id)
|
||||
if (!role) {
|
||||
throw new HTTPException(403, { message: 'User is not a member of the team' })
|
||||
}
|
||||
|
||||
const task = await kanbanService.createTask(teamId, req, user.id, role)
|
||||
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.kanban_task_create,
|
||||
teamId,
|
||||
userId: user.id,
|
||||
projectId: task.projectId ?? undefined,
|
||||
itemId: task.id,
|
||||
})
|
||||
|
||||
if (req.assigneeId && req.assigneeId !== user.id) {
|
||||
notificationService.notifyKanbanTaskEvent({
|
||||
type: 'kanban_task_assigned',
|
||||
teamId,
|
||||
projectId: task.projectId,
|
||||
creatorId: user.id,
|
||||
kanbanTaskId: task.id,
|
||||
targetUserId: req.assigneeId,
|
||||
})
|
||||
}
|
||||
|
||||
if (req.reporterId && req.reporterId !== user.id && req.reporterId !== req.assigneeId) {
|
||||
notificationService.notifyKanbanTaskEvent({
|
||||
type: 'kanban_task_created',
|
||||
teamId,
|
||||
projectId: task.projectId,
|
||||
creatorId: user.id,
|
||||
kanbanTaskId: task.id,
|
||||
targetUserId: req.reporterId,
|
||||
})
|
||||
}
|
||||
|
||||
return c.json(task)
|
||||
})
|
||||
.get(
|
||||
'/teams/:teamId/kanban/tasks',
|
||||
zValidator('query', listKanbanTasksRequestSchema),
|
||||
async (c) => {
|
||||
const { teamId } = c.req.param()
|
||||
const req = c.req.valid('query')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const result = await kanbanService.listTasks(teamId, req)
|
||||
return c.json(result)
|
||||
},
|
||||
)
|
||||
.get('/teams/:teamId/kanban/tasks/:taskId', async (c) => {
|
||||
const { taskId } = c.req.param()
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.KanbanTask,
|
||||
id: taskId,
|
||||
})
|
||||
|
||||
const task = await kanbanService.getTask(taskId)
|
||||
return c.json(task)
|
||||
})
|
||||
.patch(
|
||||
'/teams/:teamId/kanban/tasks/:taskId',
|
||||
zValidator('json', updateKanbanTaskSchema),
|
||||
async (c) => {
|
||||
const { teamId, taskId } = c.req.param()
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.KanbanTask,
|
||||
id: taskId,
|
||||
})
|
||||
|
||||
const existing = await kanbanService.getTask(taskId)
|
||||
const role = await resolveEffectiveRole(teamId, existing.projectId ?? undefined, user.id)
|
||||
const task = await kanbanService.updateTask(taskId, req, user.id, role)
|
||||
|
||||
const hasMeaningfulChanges =
|
||||
req.title !== undefined ||
|
||||
req.description !== undefined ||
|
||||
req.priority !== undefined ||
|
||||
req.startDate !== undefined ||
|
||||
req.dueDate !== undefined ||
|
||||
req.goalId !== undefined ||
|
||||
req.assigneeId !== undefined ||
|
||||
req.reporterId !== undefined ||
|
||||
req.targetFolderId !== undefined ||
|
||||
(req.status !== undefined && req.status !== existing.status)
|
||||
|
||||
if (hasMeaningfulChanges) {
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.kanban_task_update,
|
||||
teamId,
|
||||
userId: user.id,
|
||||
projectId: task.projectId ?? undefined,
|
||||
itemId: task.id,
|
||||
})
|
||||
}
|
||||
|
||||
if (req.status !== undefined && req.status !== existing.status) {
|
||||
notificationService.notifyKanbanTaskEvent({
|
||||
type: 'kanban_task_status_updated',
|
||||
teamId,
|
||||
projectId: task.projectId,
|
||||
creatorId: user.id,
|
||||
kanbanTaskId: task.id,
|
||||
stakeholderIds: [task.creator?.id, task.assignee?.id, task.reporter?.id],
|
||||
})
|
||||
}
|
||||
|
||||
if (
|
||||
req.assigneeId !== undefined &&
|
||||
req.assigneeId !== existing.assignee?.id &&
|
||||
req.assigneeId !== null &&
|
||||
req.assigneeId !== user.id
|
||||
) {
|
||||
notificationService.notifyKanbanTaskEvent({
|
||||
type: 'kanban_task_assigned',
|
||||
teamId,
|
||||
projectId: task.projectId,
|
||||
creatorId: user.id,
|
||||
kanbanTaskId: task.id,
|
||||
targetUserId: req.assigneeId,
|
||||
})
|
||||
}
|
||||
|
||||
const hasOtherDetailsChanged =
|
||||
req.title !== undefined ||
|
||||
req.description !== undefined ||
|
||||
req.priority !== undefined ||
|
||||
req.startDate !== undefined ||
|
||||
req.dueDate !== undefined ||
|
||||
req.goalId !== undefined ||
|
||||
req.reporterId !== undefined ||
|
||||
req.targetFolderId !== undefined
|
||||
|
||||
if (hasOtherDetailsChanged && req.status === undefined) {
|
||||
notificationService.notifyKanbanTaskEvent({
|
||||
type: 'kanban_task_updated',
|
||||
teamId,
|
||||
projectId: task.projectId,
|
||||
creatorId: user.id,
|
||||
kanbanTaskId: task.id,
|
||||
stakeholderIds: [task.creator?.id, task.assignee?.id, task.reporter?.id],
|
||||
})
|
||||
}
|
||||
|
||||
return c.json(task)
|
||||
},
|
||||
)
|
||||
.delete('/teams/:teamId/kanban/tasks/:taskId', async (c) => {
|
||||
const { teamId, taskId } = c.req.param()
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.KanbanTask,
|
||||
id: taskId,
|
||||
})
|
||||
|
||||
const existing = await kanbanService.getTask(taskId)
|
||||
const role = await resolveEffectiveRole(teamId, existing.projectId ?? undefined, user.id)
|
||||
|
||||
notificationService.notifyKanbanTaskEvent({
|
||||
type: 'kanban_task_deleted',
|
||||
teamId,
|
||||
projectId: existing.projectId,
|
||||
creatorId: user.id,
|
||||
kanbanTaskId: taskId,
|
||||
stakeholderIds: [existing.creator?.id, existing.assignee?.id, existing.reporter?.id],
|
||||
})
|
||||
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.kanban_task_delete,
|
||||
teamId,
|
||||
userId: user.id,
|
||||
projectId: existing.projectId ?? undefined,
|
||||
itemId: taskId,
|
||||
})
|
||||
|
||||
await kanbanService.deleteTask(taskId, user.id, role)
|
||||
return c.json({ success: true })
|
||||
})
|
||||
.get('/teams/:teamId/kanban/tasks/:taskId/assets', async (c) => {
|
||||
const { taskId } = c.req.param()
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.KanbanTask,
|
||||
id: taskId,
|
||||
})
|
||||
|
||||
const assets = await kanbanService.listTaskAssets(taskId)
|
||||
return c.json(assets)
|
||||
})
|
||||
.post(
|
||||
'/teams/:teamId/kanban/tasks/:taskId/assets',
|
||||
zValidator('json', linkTaskAssetsSchema),
|
||||
async (c) => {
|
||||
const { teamId, taskId } = c.req.param()
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.KanbanTask,
|
||||
id: taskId,
|
||||
})
|
||||
|
||||
await kanbanService.linkAssets(teamId, taskId, req.assetIds)
|
||||
return c.json({ success: true })
|
||||
},
|
||||
)
|
||||
.delete('/teams/:teamId/kanban/tasks/:taskId/assets/:assetId', async (c) => {
|
||||
const { teamId, taskId, assetId } = c.req.param()
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.KanbanTask,
|
||||
id: taskId,
|
||||
})
|
||||
|
||||
await kanbanService.unlinkAsset(teamId, taskId, assetId)
|
||||
return c.json({ success: true })
|
||||
})
|
||||
.get('/teams/:teamId/kanban/assets/:assetId/tasks', async (c) => {
|
||||
const { teamId, assetId } = c.req.param()
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const tasks = await kanbanService.listTasksForAsset(teamId, assetId)
|
||||
return c.json({ data: tasks, total: tasks.length })
|
||||
})
|
||||
.post(
|
||||
'/teams/:teamId/kanban/assets/:assetId/tasks',
|
||||
zValidator('json', linkAssetToTaskSchema),
|
||||
async (c) => {
|
||||
const { teamId, assetId } = c.req.param()
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.KanbanTask,
|
||||
id: req.taskId,
|
||||
})
|
||||
|
||||
await kanbanService.linkAsset(teamId, req.taskId, assetId)
|
||||
return c.json({ success: true })
|
||||
},
|
||||
)
|
||||
.delete('/teams/:teamId/kanban/assets/:assetId/tasks/:taskId', async (c) => {
|
||||
const { teamId, assetId, taskId } = c.req.param()
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.KanbanTask,
|
||||
id: taskId,
|
||||
})
|
||||
|
||||
await kanbanService.unlinkAsset(teamId, taskId, assetId)
|
||||
return c.json({ success: true })
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,351 @@
|
||||
import { describe, expect, test, vi, beforeEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import mcpRoute, { mcpOauthCallbackRoute } from './mcp'
|
||||
import { mcpService } from '@shumai/core/src/mcp/mcp-service'
|
||||
import { authMiddleware } from './middleware/auth'
|
||||
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
|
||||
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
|
||||
|
||||
vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
|
||||
auditLogService: {
|
||||
logAction: vi.fn().mockResolvedValue({}),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/mcp/mcp-service', () => ({
|
||||
mcpService: {
|
||||
listServers: vi.fn(),
|
||||
createServer: vi.fn(),
|
||||
getServer: vi.fn(),
|
||||
getServerRecord: vi.fn(),
|
||||
updateServer: vi.fn(),
|
||||
updateServerPermission: vi.fn(),
|
||||
deleteServer: vi.fn(),
|
||||
refreshServer: vi.fn(),
|
||||
startAuth: vi.fn(),
|
||||
completeAuth: vi.fn(),
|
||||
getAuthStatus: vi.fn(),
|
||||
removeAuth: vi.fn(),
|
||||
testServer: vi.fn(),
|
||||
handleOauthCallback: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('./middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
c.set('user', { id: 'user1', name: 'Test User' } as any)
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
ResourceType: {
|
||||
Team: 'team',
|
||||
McpServer: 'mcpServer',
|
||||
},
|
||||
}))
|
||||
|
||||
import type { McpServerInfo } from '@shumai/dtos'
|
||||
|
||||
const serverInfo: McpServerInfo = {
|
||||
id: 'server1',
|
||||
name: 'github',
|
||||
description: 'GitHub MCP server',
|
||||
instructions: 'Always use the sandbox API and respect rate limits.',
|
||||
url: 'https://mcp.example.com/github',
|
||||
transport: 'streamable_http',
|
||||
authType: 'bearer',
|
||||
permission: 'reviewer',
|
||||
status: 'not_connected',
|
||||
toolCount: 0,
|
||||
hasCredential: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
|
||||
describe('MCP API', () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', mcpRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
// Clear call history so per-test call assertions are isolated.
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
vi.mocked(mcpService.listServers).mockResolvedValue([serverInfo])
|
||||
vi.mocked(mcpService.getServer).mockResolvedValue(serverInfo)
|
||||
vi.mocked(mcpService.getServerRecord).mockResolvedValue({
|
||||
...serverInfo,
|
||||
lastError: null,
|
||||
lastConnectedAt: null,
|
||||
teamId: 'team1',
|
||||
tools: [],
|
||||
credential: null,
|
||||
config: null,
|
||||
authConfig: { type: 'bearer', bearerToken: 'secret' },
|
||||
} as never)
|
||||
})
|
||||
|
||||
test('lists servers with Admin permission on the team', async () => {
|
||||
const res = await app.request('/teams/team1/mcp/servers')
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ servers: [serverInfo] })
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: 'team1',
|
||||
})
|
||||
})
|
||||
|
||||
test('includes server instructions in list and get responses', async () => {
|
||||
const list = await app.request('/teams/team1/mcp/servers')
|
||||
expect((await list.json()).servers[0].instructions).toBe(
|
||||
'Always use the sandbox API and respect rate limits.',
|
||||
)
|
||||
|
||||
const got = await app.request('/mcp/servers/server1')
|
||||
expect((await got.json()).instructions).toBe(
|
||||
'Always use the sandbox API and respect rate limits.',
|
||||
)
|
||||
})
|
||||
|
||||
test('creates a server and audits it', async () => {
|
||||
vi.mocked(mcpService.createServer).mockResolvedValue(serverInfo)
|
||||
const res = await app.request('/teams/team1/mcp/servers', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ url: 'https://mcp.example.com/github' }),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual(serverInfo)
|
||||
expect(auditLogService.logAction).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ action: 'mcp_server_create', teamId: 'team1' }),
|
||||
)
|
||||
})
|
||||
|
||||
test('rejects a server with an invalid URL', async () => {
|
||||
const res = await app.request('/teams/team1/mcp/servers', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ url: 'not-a-url' }),
|
||||
})
|
||||
expect(res.status).toBe(400)
|
||||
expect(mcpService.createServer).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('gets a single server with Admin on the McpServer resource', async () => {
|
||||
const res = await app.request('/mcp/servers/server1')
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual(serverInfo)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.McpServer,
|
||||
id: 'server1',
|
||||
})
|
||||
})
|
||||
|
||||
test('returns 404 when the server is missing', async () => {
|
||||
vi.mocked(mcpService.getServer).mockResolvedValue(null)
|
||||
const res = await app.request('/mcp/servers/missing')
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
test('updates a server and audits it', async () => {
|
||||
vi.mocked(mcpService.updateServer).mockResolvedValue({
|
||||
...serverInfo,
|
||||
transport: 'sse',
|
||||
})
|
||||
const res = await app.request('/mcp/servers/server1', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ transport: 'sse' }),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ ...serverInfo, transport: 'sse' })
|
||||
expect(auditLogService.logAction).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ action: 'mcp_server_update', itemId: 'server1' }),
|
||||
)
|
||||
})
|
||||
|
||||
test('updates the permission via the dedicated route', async () => {
|
||||
vi.mocked(mcpService.updateServerPermission).mockResolvedValue({
|
||||
...serverInfo,
|
||||
permission: 'editor',
|
||||
})
|
||||
const res = await app.request('/mcp/servers/server1/permission', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ permission: 'editor' }),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ ...serverInfo, permission: 'editor' })
|
||||
expect(mcpService.updateServerPermission).toHaveBeenCalledWith('server1', 'editor')
|
||||
})
|
||||
|
||||
test('rejects an invalid permission value', async () => {
|
||||
const res = await app.request('/mcp/servers/server1/permission', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ permission: 'superadmin' }),
|
||||
})
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
test('deletes a server and audits it', async () => {
|
||||
const res = await app.request('/mcp/servers/server1', { method: 'DELETE' })
|
||||
expect(res.status).toBe(204)
|
||||
expect(auditLogService.logAction).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ action: 'mcp_server_delete', itemId: 'server1' }),
|
||||
)
|
||||
})
|
||||
|
||||
test('refreshes a server and returns the updated record', async () => {
|
||||
vi.mocked(mcpService.refreshServer).mockResolvedValue({
|
||||
...serverInfo,
|
||||
status: 'connected',
|
||||
toolCount: 3,
|
||||
instructions: 'Always use the sandbox API and respect rate limits.',
|
||||
})
|
||||
const res = await app.request('/mcp/servers/server1/refresh', { method: 'POST' })
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({
|
||||
...serverInfo,
|
||||
status: 'connected',
|
||||
toolCount: 3,
|
||||
instructions: 'Always use the sandbox API and respect rate limits.',
|
||||
})
|
||||
})
|
||||
|
||||
test('refresh failure returns 502 with the error message', async () => {
|
||||
vi.mocked(mcpService.refreshServer).mockRejectedValue(new Error('boom'))
|
||||
const res = await app.request('/mcp/servers/server1/refresh', { method: 'POST' })
|
||||
expect(res.status).toBe(502)
|
||||
expect(await res.json()).toEqual({ error: 'boom' })
|
||||
})
|
||||
|
||||
test('lists cached tools', async () => {
|
||||
vi.mocked(mcpService.getServerRecord).mockResolvedValue({
|
||||
...serverInfo,
|
||||
lastError: null,
|
||||
lastConnectedAt: null,
|
||||
teamId: 'team1',
|
||||
tools: [{ name: 'echo' }],
|
||||
credential: null,
|
||||
config: null,
|
||||
authConfig: null,
|
||||
} as never)
|
||||
const res = await app.request('/mcp/servers/server1/tools')
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ tools: [{ name: 'echo' }] })
|
||||
})
|
||||
|
||||
test('starts OAuth auth', async () => {
|
||||
vi.mocked(mcpService.startAuth).mockResolvedValue({
|
||||
authorizationUrl: 'https://auth.example.com/authorize',
|
||||
})
|
||||
const res = await app.request('/mcp/servers/server1/auth/start', { method: 'POST' })
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({
|
||||
authorizationUrl: 'https://auth.example.com/authorize',
|
||||
status: 'in_progress',
|
||||
})
|
||||
})
|
||||
|
||||
test('completes OAuth auth', async () => {
|
||||
vi.mocked(mcpService.completeAuth).mockResolvedValue('authenticated')
|
||||
const res = await app.request('/mcp/servers/server1/auth/complete', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ code: 'auth-code', iss: 'https://issuer.example.com' }),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ status: 'authenticated' })
|
||||
expect(mcpService.completeAuth).toHaveBeenCalledWith('server1', {
|
||||
code: 'auth-code',
|
||||
iss: 'https://issuer.example.com',
|
||||
})
|
||||
})
|
||||
|
||||
test('reports auth status', async () => {
|
||||
vi.mocked(mcpService.getAuthStatus).mockResolvedValue('not_authenticated')
|
||||
const res = await app.request('/mcp/servers/server1/auth/status')
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ status: 'not_authenticated' })
|
||||
})
|
||||
|
||||
test('removes auth', async () => {
|
||||
const res = await app.request('/mcp/servers/server1/auth', { method: 'DELETE' })
|
||||
expect(res.status).toBe(204)
|
||||
expect(mcpService.removeAuth).toHaveBeenCalledWith('server1')
|
||||
})
|
||||
|
||||
test('tests the server connection', async () => {
|
||||
vi.mocked(mcpService.testServer).mockResolvedValue({ ok: true, toolCount: 3 })
|
||||
const res = await app.request('/mcp/servers/server1/test', { method: 'POST' })
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ ok: true, toolCount: 3 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('MCP OAuth callback route', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
test('completes a valid callback and renders an HTML page', async () => {
|
||||
vi.mocked(mcpService.handleOauthCallback).mockResolvedValue({ ok: true })
|
||||
const res = await mcpOauthCallbackRoute.request(
|
||||
'/mcp/oauth/callback?code=abc&state=xyz&iss=https%3A%2F%2Fissuer.example.com',
|
||||
)
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('content-type')).toContain('text/html')
|
||||
expect(mcpService.handleOauthCallback).toHaveBeenCalledWith(
|
||||
'abc',
|
||||
'xyz',
|
||||
'https://issuer.example.com',
|
||||
)
|
||||
const body = await res.text()
|
||||
expect(body).toContain('postMessage')
|
||||
expect(body).toContain('"ok":true')
|
||||
})
|
||||
|
||||
test('rejects a callback missing code or state', async () => {
|
||||
const res = await mcpOauthCallbackRoute.request('/mcp/oauth/callback?code=abc')
|
||||
expect(res.status).toBe(400)
|
||||
expect(mcpService.handleOauthCallback).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('surfaces callback failures in the HTML page', async () => {
|
||||
vi.mocked(mcpService.handleOauthCallback).mockResolvedValue({
|
||||
ok: false,
|
||||
message: 'Invalid or expired OAuth state',
|
||||
})
|
||||
const res = await mcpOauthCallbackRoute.request('/mcp/oauth/callback?code=abc&state=bad')
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.text()
|
||||
expect(body).toContain('"ok":false')
|
||||
expect(body).toContain('Invalid or expired OAuth state')
|
||||
})
|
||||
|
||||
test('accepts POST callbacks (form-encoded)', async () => {
|
||||
vi.mocked(mcpService.handleOauthCallback).mockResolvedValue({ ok: true })
|
||||
const res = await mcpOauthCallbackRoute.request('/mcp/oauth/callback', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: 'code=abc&state=xyz',
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
expect(mcpService.handleOauthCallback).toHaveBeenCalledWith('abc', 'xyz', undefined)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,356 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { mcpService } from '@shumai/core/src/mcp/mcp-service'
|
||||
import {
|
||||
createMcpServerRequestSchema,
|
||||
updateMcpServerRequestSchema,
|
||||
updateMcpServerPermissionRequestSchema,
|
||||
mcpAuthCompleteRequestSchema,
|
||||
AuditAction,
|
||||
} from '@shumai/dtos'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.get('/teams/:teamId/mcp/servers', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const servers = await mcpService.listServers(teamId)
|
||||
return c.json({ servers })
|
||||
})
|
||||
.post(
|
||||
'/teams/:teamId/mcp/servers',
|
||||
zValidator('json', createMcpServerRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const server = await mcpService.createServer(teamId, req)
|
||||
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.mcp_server_create,
|
||||
teamId,
|
||||
userId: user?.id,
|
||||
itemId: server.id,
|
||||
})
|
||||
|
||||
return c.json(server)
|
||||
},
|
||||
)
|
||||
.get('/mcp/servers/:id', async (c) => {
|
||||
const user = c.get('user')
|
||||
const id = c.req.param('id')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.McpServer,
|
||||
id,
|
||||
})
|
||||
|
||||
const server = await mcpService.getServer(id)
|
||||
if (!server) return c.json({ error: 'MCP server not found' }, 404)
|
||||
return c.json(server)
|
||||
})
|
||||
.patch('/mcp/servers/:id', zValidator('json', updateMcpServerRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const id = c.req.param('id')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.McpServer,
|
||||
id,
|
||||
})
|
||||
|
||||
const existing = await mcpService.getServerRecord(id)
|
||||
if (!existing) return c.json({ error: 'MCP server not found' }, 404)
|
||||
|
||||
const server = await mcpService.updateServer(id, req)
|
||||
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.mcp_server_update,
|
||||
teamId: existing.teamId,
|
||||
userId: user?.id,
|
||||
itemId: id,
|
||||
})
|
||||
|
||||
return c.json(server)
|
||||
})
|
||||
.patch(
|
||||
'/mcp/servers/:id/permission',
|
||||
zValidator('json', updateMcpServerPermissionRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const id = c.req.param('id')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.McpServer,
|
||||
id,
|
||||
})
|
||||
|
||||
const existing = await mcpService.getServerRecord(id)
|
||||
if (!existing) return c.json({ error: 'MCP server not found' }, 404)
|
||||
|
||||
const server = await mcpService.updateServerPermission(id, req.permission)
|
||||
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.mcp_server_update,
|
||||
teamId: existing.teamId,
|
||||
userId: user?.id,
|
||||
itemId: id,
|
||||
})
|
||||
|
||||
return c.json(server)
|
||||
},
|
||||
)
|
||||
.delete('/mcp/servers/:id', async (c) => {
|
||||
const user = c.get('user')
|
||||
const id = c.req.param('id')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.McpServer,
|
||||
id,
|
||||
})
|
||||
|
||||
const existing = await mcpService.getServerRecord(id)
|
||||
|
||||
await mcpService.deleteServer(id)
|
||||
|
||||
if (existing) {
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.mcp_server_delete,
|
||||
teamId: existing.teamId,
|
||||
userId: user?.id,
|
||||
itemId: id,
|
||||
})
|
||||
}
|
||||
|
||||
return new Response(null, { status: 204 })
|
||||
})
|
||||
.post('/mcp/servers/:id/refresh', async (c) => {
|
||||
const user = c.get('user')
|
||||
const id = c.req.param('id')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.McpServer,
|
||||
id,
|
||||
})
|
||||
|
||||
try {
|
||||
const server = await mcpService.refreshServer(id)
|
||||
return c.json(server)
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
return c.json({ error: message }, 502)
|
||||
}
|
||||
})
|
||||
.get('/mcp/servers/:id/tools', async (c) => {
|
||||
const user = c.get('user')
|
||||
const id = c.req.param('id')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.McpServer,
|
||||
id,
|
||||
})
|
||||
|
||||
const server = await mcpService.getServer(id)
|
||||
if (!server) return c.json({ error: 'MCP server not found' }, 404)
|
||||
const record = await mcpService.getServerRecord(id)
|
||||
return c.json({ tools: record?.tools ?? [] })
|
||||
})
|
||||
.post('/mcp/servers/:id/auth/start', async (c) => {
|
||||
const user = c.get('user')
|
||||
const id = c.req.param('id')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.McpServer,
|
||||
id,
|
||||
})
|
||||
|
||||
try {
|
||||
const result = await mcpService.startAuth(id)
|
||||
if (result.alreadyAuthenticated) {
|
||||
return c.json({ status: 'authenticated' })
|
||||
}
|
||||
return c.json({ authorizationUrl: result.authorizationUrl, status: 'in_progress' })
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
return c.json({ error: message }, 502)
|
||||
}
|
||||
})
|
||||
.post(
|
||||
'/mcp/servers/:id/auth/complete',
|
||||
zValidator('json', mcpAuthCompleteRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const id = c.req.param('id')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.McpServer,
|
||||
id,
|
||||
})
|
||||
|
||||
try {
|
||||
const status = await mcpService.completeAuth(id, { code: req.code, iss: req.iss })
|
||||
return c.json({ status })
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
return c.json({ error: message }, 502)
|
||||
}
|
||||
},
|
||||
)
|
||||
.get('/mcp/servers/:id/auth/status', async (c) => {
|
||||
const user = c.get('user')
|
||||
const id = c.req.param('id')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.McpServer,
|
||||
id,
|
||||
})
|
||||
|
||||
try {
|
||||
const status = await mcpService.getAuthStatus(id)
|
||||
return c.json({ status })
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
return c.json({ error: message }, 404)
|
||||
}
|
||||
})
|
||||
.delete('/mcp/servers/:id/auth', async (c) => {
|
||||
const user = c.get('user')
|
||||
const id = c.req.param('id')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.McpServer,
|
||||
id,
|
||||
})
|
||||
|
||||
await mcpService.removeAuth(id)
|
||||
return new Response(null, { status: 204 })
|
||||
})
|
||||
.post('/mcp/servers/:id/test', async (c) => {
|
||||
const user = c.get('user')
|
||||
const id = c.req.param('id')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.McpServer,
|
||||
id,
|
||||
})
|
||||
|
||||
const result = await mcpService.testServer(id)
|
||||
return c.json(result)
|
||||
})
|
||||
|
||||
export default route
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public OAuth callback route (mounted BEFORE authMiddleware in index.ts).
|
||||
// The OAuth provider redirects the user's browser here after approval.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function renderCallbackPage(payload: { ok: boolean; message?: string }): string {
|
||||
const escaped = JSON.stringify(payload).replace(/</g, '\\u003c')
|
||||
return `<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>MCP OAuth</title>
|
||||
</head>
|
||||
<body>
|
||||
<script>
|
||||
(function () {
|
||||
var payload = ${escaped};
|
||||
try {
|
||||
if (window.opener) {
|
||||
window.opener.postMessage({ source: 'shumai-mcp-oauth', payload: payload }, '*');
|
||||
}
|
||||
} catch (e) {
|
||||
/* ignore cross-origin postMessage failures */
|
||||
}
|
||||
setTimeout(function () {
|
||||
window.close();
|
||||
document.body.textContent = payload.ok ? 'Authentication complete. You can close this window.' : 'Authentication failed: ' + (payload.message || 'unknown error');
|
||||
}, 300);
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>`
|
||||
}
|
||||
|
||||
export const mcpOauthCallbackRoute = new Hono()
|
||||
.get('/mcp/oauth/callback', async (c) => {
|
||||
const code = c.req.query('code')
|
||||
const state = c.req.query('state')
|
||||
const iss = c.req.query('iss') || undefined
|
||||
|
||||
if (!code || !state) {
|
||||
return c.html(
|
||||
renderCallbackPage({ ok: false, message: 'Missing code or state parameter' }),
|
||||
400,
|
||||
)
|
||||
}
|
||||
|
||||
const result = await mcpService.handleOauthCallback(code, state, iss)
|
||||
return c.html(
|
||||
renderCallbackPage(result.ok ? { ok: true } : { ok: false, message: result.message }),
|
||||
)
|
||||
})
|
||||
.post('/mcp/oauth/callback', async (c) => {
|
||||
const body = await c.req.parseBody()
|
||||
const code = typeof body['code'] === 'string' ? body['code'] : undefined
|
||||
const state = typeof body['state'] === 'string' ? body['state'] : undefined
|
||||
const iss = typeof body['iss'] === 'string' ? body['iss'] : undefined
|
||||
|
||||
if (!code || !state) {
|
||||
return c.html(
|
||||
renderCallbackPage({ ok: false, message: 'Missing code or state parameter' }),
|
||||
400,
|
||||
)
|
||||
}
|
||||
|
||||
const result = await mcpService.handleOauthCallback(code, state, iss)
|
||||
return c.html(
|
||||
renderCallbackPage(result.ok ? { ok: true } : { ok: false, message: result.message }),
|
||||
)
|
||||
})
|
||||
@@ -46,10 +46,9 @@ describe('metadata api', () => {
|
||||
const mockField = {
|
||||
key: 'field1',
|
||||
scope: 'TEAM',
|
||||
config: { name: 'Test Field', type: 'text' },
|
||||
config: { name: 'Test Field', type: 'text', autofillSource: 'CONTENT' },
|
||||
readOnly: false,
|
||||
description: 'desc',
|
||||
aiAutofill: true,
|
||||
}
|
||||
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
@@ -62,7 +61,7 @@ describe('metadata api', () => {
|
||||
expect(json).toHaveLength(1)
|
||||
expect(json[0].id).toBe('field1')
|
||||
expect(json[0].config.name).toBe('Test Field')
|
||||
expect(json[0].aiAutofill).toBe(true)
|
||||
expect(json[0].config.autofillSource).toBe('CONTENT')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Read,
|
||||
@@ -75,10 +74,9 @@ describe('metadata api', () => {
|
||||
const mockField = {
|
||||
key: 'newfield',
|
||||
scope: 'TEAM',
|
||||
config: { name: 'New Field', type: 'text' },
|
||||
config: { name: 'New Field', type: 'text', autofillSource: 'CONTENT' },
|
||||
readOnly: false,
|
||||
description: 'desc',
|
||||
aiAutofill: true,
|
||||
}
|
||||
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
@@ -88,8 +86,7 @@ describe('metadata api', () => {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
config: { name: 'New Field', type: 'text' },
|
||||
aiAutofill: true,
|
||||
config: { name: 'New Field', type: 'text', autofillSource: 'CONTENT' },
|
||||
description: 'desc',
|
||||
}),
|
||||
})
|
||||
@@ -115,10 +112,9 @@ describe('metadata api', () => {
|
||||
const mockField = {
|
||||
key: 'field1',
|
||||
scope: 'PROJECT',
|
||||
config: { name: 'Project Field', type: 'text' },
|
||||
config: { name: 'Project Field', type: 'text', autofillSource: 'NONE' },
|
||||
readOnly: false,
|
||||
description: 'desc',
|
||||
aiAutofill: false,
|
||||
}
|
||||
|
||||
vi.mocked(metadataService.listProjectFields).mockResolvedValue([
|
||||
@@ -198,10 +194,9 @@ describe('metadata api', () => {
|
||||
const mockField = {
|
||||
key: 'f1',
|
||||
scope: 'TEAM',
|
||||
config: { name: 'Updated Field', type: 'text' },
|
||||
config: { name: 'Updated Field', type: 'text', autofillSource: 'CONTENT' },
|
||||
readOnly: false,
|
||||
description: 'desc',
|
||||
aiAutofill: true,
|
||||
teamId: 't1',
|
||||
}
|
||||
|
||||
@@ -214,8 +209,7 @@ describe('metadata api', () => {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
config: { name: 'Updated Field', type: 'text' },
|
||||
aiAutofill: true,
|
||||
config: { name: 'Updated Field', type: 'text', autofillSource: 'CONTENT' },
|
||||
description: 'desc',
|
||||
}),
|
||||
})
|
||||
|
||||
@@ -27,7 +27,6 @@ function toFieldInfo(
|
||||
readOnly: f.readOnly,
|
||||
visible: visible,
|
||||
description: f.description,
|
||||
aiAutofill: f.aiAutofill,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -31,6 +31,7 @@ describe('authMiddleware', () => {
|
||||
.get('/test', (c) => c.text('ok'))
|
||||
.post('/test', (c) => c.text('ok'))
|
||||
.post('/test/search', (c) => c.text('ok'))
|
||||
.post('/test/recents/view', (c) => c.text('ok'))
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks()
|
||||
@@ -81,6 +82,17 @@ describe('authMiddleware', () => {
|
||||
expect(await res.json()).toEqual({ error: 'System is in read-only mode' })
|
||||
})
|
||||
|
||||
it('allows POST /recents/view for reviewer', async () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(userService.getUserById).mockResolvedValue({ id: 'user1' } as any)
|
||||
vi.mocked(teamService.hasWritableRoleInAnyTeam).mockResolvedValue(false)
|
||||
|
||||
const res = await app.request('/test/recents/view', { method: 'POST' })
|
||||
expect(res.status).toBe(200)
|
||||
})
|
||||
|
||||
it('allows POST /search for reviewer', async () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any)
|
||||
|
||||
@@ -36,7 +36,9 @@ export const authMiddleware = createMiddleware<{
|
||||
if (process.env.SHUMAI_DEMO_MODE === '1') {
|
||||
const method = c.req.method.toUpperCase()
|
||||
const path = c.req.path
|
||||
if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(method) && !path.endsWith('/search')) {
|
||||
const isAllowedDemoWrite =
|
||||
method === 'POST' && (path.endsWith('/search') || path.endsWith('/recents/view'))
|
||||
if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(method) && !isAllowedDemoWrite) {
|
||||
const hasWritable = await teamService.hasWritableRoleInAnyTeam(user.id)
|
||||
|
||||
if (!hasWritable) {
|
||||
|
||||
@@ -150,6 +150,8 @@ describe('notification api', () => {
|
||||
yourUploads: true,
|
||||
otherUploads: false,
|
||||
statusUpdates: true,
|
||||
kanbanTasks: true,
|
||||
kanbanComments: true,
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
@@ -35,6 +35,7 @@ vi.mock('@shumai/core/src/project/project', () => ({
|
||||
},
|
||||
}))
|
||||
vi.mock('@shumai/core/src/asset/asset')
|
||||
|
||||
vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
|
||||
auditLogService: {
|
||||
logAction: vi.fn().mockResolvedValue({}),
|
||||
@@ -264,6 +265,75 @@ describe('project api', () => {
|
||||
expect(assetService.emptyTrash).toHaveBeenCalledWith('p1')
|
||||
})
|
||||
|
||||
it('GET /projects/:projectId/members', async () => {
|
||||
vi.mocked(projectService.listProjectMembers).mockResolvedValue([
|
||||
{
|
||||
id: 'user1',
|
||||
name: 'Test User',
|
||||
role: 'editor',
|
||||
type: 'human',
|
||||
},
|
||||
])
|
||||
|
||||
const res = await app.request('/projects/p1/members')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json).toEqual([
|
||||
{
|
||||
id: 'user1',
|
||||
name: 'Test User',
|
||||
role: 'editor',
|
||||
type: 'human',
|
||||
},
|
||||
])
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: 'p1',
|
||||
})
|
||||
expect(projectService.listProjectMembers).toHaveBeenCalledWith({
|
||||
projectId: 'p1',
|
||||
includeAgents: false,
|
||||
requesterUserId: 'user1',
|
||||
})
|
||||
})
|
||||
|
||||
it('GET /projects/:projectId/members?includeAgents=true', async () => {
|
||||
vi.mocked(projectService.listProjectMembers).mockResolvedValue([
|
||||
{
|
||||
id: 'user1',
|
||||
name: 'Test User',
|
||||
role: 'editor',
|
||||
type: 'human',
|
||||
},
|
||||
{
|
||||
id: 'agent1',
|
||||
name: 'Agent Bot',
|
||||
role: 'bot',
|
||||
type: 'agent',
|
||||
},
|
||||
])
|
||||
|
||||
const res = await app.request('/projects/p1/members?includeAgents=true')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json).toHaveLength(2)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: 'p1',
|
||||
})
|
||||
expect(projectService.listProjectMembers).toHaveBeenCalledWith({
|
||||
projectId: 'p1',
|
||||
includeAgents: true,
|
||||
requesterUserId: 'user1',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /projects/:projectId/members', async () => {
|
||||
vi.mocked(projectService.addProjectMember).mockResolvedValue(undefined)
|
||||
|
||||
@@ -341,4 +411,46 @@ describe('project api', () => {
|
||||
})
|
||||
expect(projectService.getUserProjects).toHaveBeenCalledWith('user1', 10)
|
||||
})
|
||||
|
||||
it('GET /projects/:projectId/recents', async () => {
|
||||
vi.mocked(assetService.listRecents).mockResolvedValue({
|
||||
data: [{ id: 'file1', name: 'video.mp4', type: 'file' }] as any, // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
pageInfo: { total: 1 },
|
||||
})
|
||||
|
||||
const res = await app.request('/projects/p1/recents?first=20')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.data).toHaveLength(1)
|
||||
expect(json.data[0].id).toBe('file1')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: 'p1',
|
||||
})
|
||||
expect(assetService.listRecents).toHaveBeenCalledWith('user1', 'p1', { first: 20 })
|
||||
})
|
||||
|
||||
it('POST /projects/:projectId/recents/view', async () => {
|
||||
vi.mocked(assetService.recordRecentView).mockResolvedValue(undefined)
|
||||
|
||||
const res = await app.request('/projects/p1/recents/view', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ assetId: 'file1' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.success).toBe(true)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: 'p1',
|
||||
})
|
||||
expect(assetService.recordRecentView).toHaveBeenCalledWith('user1', 'p1', 'file1')
|
||||
})
|
||||
})
|
||||
|
||||
+37
-15
@@ -11,6 +11,8 @@ import {
|
||||
recentlyDeletedRequestSchema,
|
||||
updateProjectMemberRoleRequestSchema,
|
||||
addProjectMemberRequestSchema,
|
||||
listRecentsRequestSchema,
|
||||
recordRecentViewRequestSchema,
|
||||
} from '@shumai/dtos'
|
||||
import { listMembersQuerySchema, paginationParamsSchema, AuditAction } from '@shumai/dtos'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
@@ -118,6 +120,40 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
return c.json(resp)
|
||||
},
|
||||
)
|
||||
.get('/projects/:projectId/recents', zValidator('query', listRecentsRequestSchema), async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const resp = await assetService.listRecents(user.id, projectId, req)
|
||||
return c.json(resp)
|
||||
})
|
||||
.post(
|
||||
'/projects/:projectId/recents/view',
|
||||
zValidator('json', recordRecentViewRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
await assetService.recordRecentView(user.id, projectId, req.assetId)
|
||||
return c.json({ success: true })
|
||||
},
|
||||
)
|
||||
.post('/projects/:projectId/empty-trash', async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
@@ -241,24 +277,10 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const members = await projectService.listProjectMembers({
|
||||
projectId,
|
||||
includeAgents: includeAgents,
|
||||
requesterUserId: user.id,
|
||||
})
|
||||
return c.json(members)
|
||||
})
|
||||
.get('/projects/:projectId/bots', async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
// STUB: AgentService is not migrated yet.
|
||||
return c.json([])
|
||||
})
|
||||
|
||||
.post(
|
||||
'/projects/:projectId/reparent',
|
||||
zValidator('json', reparentAssetsRequestSchema),
|
||||
|
||||
@@ -93,7 +93,6 @@ function toFieldInfo(
|
||||
readOnly: f.readOnly,
|
||||
visible: visible,
|
||||
description: f.description,
|
||||
aiAutofill: f.aiAutofill,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,311 @@
|
||||
import { describe, expect, test, vi, beforeEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import quotaRoute from './quota'
|
||||
import { quotaService } from '@shumai/core/src/quota/quota-service'
|
||||
import { authMiddleware } from './middleware/auth'
|
||||
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
|
||||
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
|
||||
import { AuditAction } from '@shumai/dtos'
|
||||
|
||||
vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
|
||||
auditLogService: {
|
||||
logAction: vi.fn().mockResolvedValue({}),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/quota/quota-service', () => ({
|
||||
quotaService: {
|
||||
listRules: vi.fn(),
|
||||
createRule: vi.fn(),
|
||||
getRule: vi.fn(),
|
||||
listRuleRecords: vi.fn(),
|
||||
resetRecord: vi.fn(),
|
||||
updateRule: vi.fn(),
|
||||
deleteRule: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('./middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
c.set('user', { id: 'user1', name: 'Test User' } as any)
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
ResourceType: {
|
||||
Team: 'team',
|
||||
QuotaRule: 'quotaRule',
|
||||
},
|
||||
}))
|
||||
|
||||
describe('Quota API', () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', quotaRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
describe('GET /teams/:teamId/quotas', () => {
|
||||
test('Success listing quota rules', async () => {
|
||||
const mockResult = {
|
||||
total: 1,
|
||||
rules: [
|
||||
{
|
||||
id: 'rule1',
|
||||
teamId: 'team1',
|
||||
scopeMode: 'all_members' as const,
|
||||
resource: 'agent_total_tokens' as const,
|
||||
limit: 50000,
|
||||
period: '1hour' as const,
|
||||
enabled: true,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
],
|
||||
}
|
||||
vi.spyOn(quotaService, 'listRules').mockResolvedValue(mockResult)
|
||||
|
||||
const res = await app.request('/teams/team1/quotas', {
|
||||
method: 'GET',
|
||||
headers: { Authorization: 'Bearer test' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual(mockResult)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Team,
|
||||
id: 'team1',
|
||||
permission: Permission.Admin,
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /teams/:teamId/quotas', () => {
|
||||
test('Success creating rule with audit log', async () => {
|
||||
const mockRule = {
|
||||
id: 'rule1',
|
||||
teamId: 'team1',
|
||||
scopeMode: 'all_members' as const,
|
||||
resource: 'agent_total_tokens' as const,
|
||||
limit: 100000,
|
||||
period: '1day' as const,
|
||||
enabled: true,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
vi.spyOn(quotaService, 'createRule').mockResolvedValue(mockRule)
|
||||
|
||||
const res = await app.request('/teams/team1/quotas', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: 'Bearer test',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
scopeMode: 'all_members',
|
||||
resource: 'agent_total_tokens',
|
||||
limit: 100000,
|
||||
period: '1day',
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(201)
|
||||
expect(await res.json()).toEqual(mockRule)
|
||||
expect(quotaService.createRule).toHaveBeenCalledWith('team1', {
|
||||
scopeMode: 'all_members',
|
||||
resource: 'agent_total_tokens',
|
||||
limit: 100000,
|
||||
period: '1day',
|
||||
enabled: true,
|
||||
})
|
||||
expect(auditLogService.logAction).toHaveBeenCalledWith({
|
||||
action: AuditAction.quota_rule_create,
|
||||
teamId: 'team1',
|
||||
userId: 'user1',
|
||||
itemId: 'rule1',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /teams/:teamId/quotas/:id', () => {
|
||||
test('Success fetching single rule', async () => {
|
||||
const mockRule = {
|
||||
id: 'rule1',
|
||||
teamId: 'team1',
|
||||
scopeMode: 'all_members' as const,
|
||||
resource: 'agent_cost' as const,
|
||||
limit: 50,
|
||||
period: '1day' as const,
|
||||
enabled: true,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
vi.spyOn(quotaService, 'getRule').mockResolvedValue(mockRule)
|
||||
|
||||
const res = await app.request('/teams/team1/quotas/rule1', {
|
||||
method: 'GET',
|
||||
headers: { Authorization: 'Bearer test' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual(mockRule)
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /teams/:teamId/quotas/:id/records', () => {
|
||||
test('Success listing records for a rule', async () => {
|
||||
const mockRecordsResult = {
|
||||
total: 1,
|
||||
records: [
|
||||
{
|
||||
id: 'rec1',
|
||||
ruleId: 'rule1',
|
||||
teamId: 'team1',
|
||||
userId: null,
|
||||
user: null,
|
||||
periodStart: null,
|
||||
periodEnd: null,
|
||||
consumed: 0,
|
||||
remaining: 50,
|
||||
percent: 0,
|
||||
isWindowActive: false,
|
||||
},
|
||||
],
|
||||
}
|
||||
vi.spyOn(quotaService, 'listRuleRecords').mockResolvedValue(mockRecordsResult)
|
||||
|
||||
const res = await app.request('/teams/team1/quotas/rule1/records', {
|
||||
method: 'GET',
|
||||
headers: { Authorization: 'Bearer test' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual(mockRecordsResult)
|
||||
expect(quotaService.listRuleRecords).toHaveBeenCalledWith('team1', 'rule1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /teams/:teamId/quotas/:id/records/reset', () => {
|
||||
test('Rejects a reset request without a userId', async () => {
|
||||
const res = await app.request('/teams/team1/quotas/rule1/records/reset', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: 'Bearer test',
|
||||
},
|
||||
body: JSON.stringify({}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
expect(quotaService.resetRecord).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('Success resetting a quota record with audit log', async () => {
|
||||
const mockRecord = {
|
||||
id: 'record1',
|
||||
ruleId: 'rule1',
|
||||
teamId: 'team1',
|
||||
userId: 'user2',
|
||||
user: null,
|
||||
periodStart: new Date().toISOString(),
|
||||
periodEnd: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
|
||||
consumed: 0,
|
||||
remaining: 100,
|
||||
percent: 0,
|
||||
isWindowActive: true,
|
||||
}
|
||||
vi.spyOn(quotaService, 'resetRecord').mockResolvedValue(mockRecord)
|
||||
|
||||
const res = await app.request('/teams/team1/quotas/rule1/records/reset', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: 'Bearer test',
|
||||
},
|
||||
body: JSON.stringify({ userId: 'user2' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual(mockRecord)
|
||||
expect(quotaService.resetRecord).toHaveBeenCalledWith('team1', 'rule1', 'user2')
|
||||
expect(auditLogService.logAction).toHaveBeenCalledWith({
|
||||
action: AuditAction.quota_record_reset,
|
||||
teamId: 'team1',
|
||||
userId: 'user1',
|
||||
itemId: 'record1',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('PUT /teams/:teamId/quotas/:id', () => {
|
||||
test('Success updating rule with audit log', async () => {
|
||||
const updatedRule = {
|
||||
id: 'rule1',
|
||||
teamId: 'team1',
|
||||
scopeMode: 'all_members' as const,
|
||||
resource: 'agent_cost' as const,
|
||||
limit: 100,
|
||||
period: '1day' as const,
|
||||
enabled: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
vi.spyOn(quotaService, 'updateRule').mockResolvedValue(updatedRule)
|
||||
|
||||
const res = await app.request('/teams/team1/quotas/rule1', {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: 'Bearer test',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
limit: 100,
|
||||
enabled: false,
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual(updatedRule)
|
||||
expect(auditLogService.logAction).toHaveBeenCalledWith({
|
||||
action: AuditAction.quota_rule_update,
|
||||
teamId: 'team1',
|
||||
userId: 'user1',
|
||||
itemId: 'rule1',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('DELETE /teams/:teamId/quotas/:id', () => {
|
||||
test('Success deleting rule with audit log', async () => {
|
||||
vi.spyOn(quotaService, 'deleteRule').mockResolvedValue(undefined)
|
||||
|
||||
const res = await app.request('/teams/team1/quotas/rule1', {
|
||||
method: 'DELETE',
|
||||
headers: { Authorization: 'Bearer test' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(quotaService.deleteRule).toHaveBeenCalledWith('team1', 'rule1')
|
||||
expect(auditLogService.logAction).toHaveBeenCalledWith({
|
||||
action: AuditAction.quota_rule_delete,
|
||||
teamId: 'team1',
|
||||
userId: 'user1',
|
||||
itemId: 'rule1',
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,152 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { quotaService } from '@shumai/core/src/quota/quota-service'
|
||||
import {
|
||||
createQuotaRuleRequestSchema,
|
||||
resetQuotaRecordRequestSchema,
|
||||
updateQuotaRuleRequestSchema,
|
||||
AuditAction,
|
||||
} from '@shumai/dtos'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.get('/teams/:teamId/quotas', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const data = await quotaService.listRules(teamId)
|
||||
return c.json(data)
|
||||
})
|
||||
.post('/teams/:teamId/quotas', zValidator('json', createQuotaRuleRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const rule = await quotaService.createRule(teamId, req)
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.quota_rule_create,
|
||||
teamId,
|
||||
userId: user?.id,
|
||||
itemId: rule.id,
|
||||
})
|
||||
return c.json(rule, 201)
|
||||
})
|
||||
.get('/teams/:teamId/quotas/:id', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const id = c.req.param('id')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const rule = await quotaService.getRule(teamId, id)
|
||||
return c.json(rule)
|
||||
})
|
||||
.get('/teams/:teamId/quotas/:id/records', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const id = c.req.param('id')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const data = await quotaService.listRuleRecords(teamId, id)
|
||||
return c.json(data)
|
||||
})
|
||||
.post(
|
||||
'/teams/:teamId/quotas/:id/records/reset',
|
||||
zValidator('json', resetQuotaRecordRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const id = c.req.param('id')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const record = await quotaService.resetRecord(teamId, id, req.userId)
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.quota_record_reset,
|
||||
teamId,
|
||||
userId: user?.id,
|
||||
itemId: record.id ?? id,
|
||||
})
|
||||
return c.json(record)
|
||||
},
|
||||
)
|
||||
.put('/teams/:teamId/quotas/:id', zValidator('json', updateQuotaRuleRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const id = c.req.param('id')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const rule = await quotaService.updateRule(teamId, id, req)
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.quota_rule_update,
|
||||
teamId,
|
||||
userId: user?.id,
|
||||
itemId: id,
|
||||
})
|
||||
return c.json(rule)
|
||||
})
|
||||
.delete('/teams/:teamId/quotas/:id', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const id = c.req.param('id')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
await quotaService.deleteRule(teamId, id)
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.quota_rule_delete,
|
||||
teamId,
|
||||
userId: user?.id,
|
||||
itemId: id,
|
||||
})
|
||||
return new Response(null, { status: 204 })
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -39,7 +39,7 @@ describe('S3 API', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('GET /files/* sets Content-Disposition: attachment only when download=1 query param is present', async () => {
|
||||
it('GET /files/* sets Content-Disposition with filename when download=1 & filename query params are present', async () => {
|
||||
// We need to capture the onFound callback from serveStatic options
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let onFoundCallback: ((path: string, c: any) => void) | undefined
|
||||
@@ -54,19 +54,36 @@ describe('S3 API', () => {
|
||||
const { default: route } = await import('./s3')
|
||||
const app = new Hono().route('/files', route)
|
||||
|
||||
await app.request('/files/b1/test.webp?download=1')
|
||||
await app.request('/files/b1/test.webp?download=1&filename=foo.png')
|
||||
|
||||
expect(onFoundCallback).toBeDefined()
|
||||
|
||||
// Test with download=1
|
||||
// Test with download=1 and filename
|
||||
const mockContextWithDownload = {
|
||||
req: { query: (key: string) => (key === 'download' ? '1' : undefined) },
|
||||
req: {
|
||||
query: (key: string) =>
|
||||
key === 'download' ? '1' : key === 'filename' ? 'foo.png' : undefined,
|
||||
},
|
||||
header: vi.fn(),
|
||||
}
|
||||
|
||||
if (onFoundCallback) {
|
||||
onFoundCallback('/files/b1/test.webp', mockContextWithDownload)
|
||||
expect(mockContextWithDownload.header).toHaveBeenCalledWith(
|
||||
'Content-Disposition',
|
||||
'attachment; filename="foo.png"; filename*=UTF-8\'\'foo.png',
|
||||
)
|
||||
}
|
||||
|
||||
// Test with download=1 but no filename
|
||||
const mockContextDownloadNoFilename = {
|
||||
req: { query: (key: string) => (key === 'download' ? '1' : undefined) },
|
||||
header: vi.fn(),
|
||||
}
|
||||
|
||||
if (onFoundCallback) {
|
||||
onFoundCallback('/files/b1/test.webp', mockContextDownloadNoFilename)
|
||||
expect(mockContextDownloadNoFilename.header).toHaveBeenCalledWith(
|
||||
'Content-Disposition',
|
||||
'attachment',
|
||||
)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Hono } from 'hono'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { buildContentDisposition, s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { serveStatic } from 'hono/bun'
|
||||
|
||||
const route = new Hono()
|
||||
@@ -10,7 +10,7 @@ const route = new Hono()
|
||||
rewriteRequestPath: (path) => path.replace(/^\/files\//, ''),
|
||||
onFound: (_path, c) => {
|
||||
if (c.req.query('download') === '1') {
|
||||
c.header('Content-Disposition', 'attachment')
|
||||
c.header('Content-Disposition', buildContentDisposition(c.req.query('filename')))
|
||||
}
|
||||
},
|
||||
}),
|
||||
|
||||
@@ -245,6 +245,21 @@ describe('team api', () => {
|
||||
expect(mockUpdateSettings).toHaveBeenCalledWith('t1', 'transcode.videoStrategy', 'all')
|
||||
})
|
||||
|
||||
it('PATCH /teams/:teamId/settings updates transcode.hardwareAcceleration', async () => {
|
||||
mockUpdateSettings.mockResolvedValue({ transcode: { hardwareAcceleration: 'auto' } })
|
||||
|
||||
const res = await app.request('/teams/t1/settings', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ key: 'transcode.hardwareAcceleration', value: 'auto' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.transcode.hardwareAcceleration).toBe('auto')
|
||||
expect(mockUpdateSettings).toHaveBeenCalledWith('t1', 'transcode.hardwareAcceleration', 'auto')
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/user-metadata returns all metadata for the user in the team', async () => {
|
||||
mockListUserMetadata.mockResolvedValue([
|
||||
{ key: 'key1', value: 'value1' },
|
||||
@@ -292,6 +307,7 @@ describe('team api', () => {
|
||||
|
||||
it('GET /teams/:teamId/sandbox returns sandbox settings', async () => {
|
||||
mockGetSandboxSettings.mockResolvedValue({
|
||||
networkSandboxEnabled: false,
|
||||
allowedDomains: ['example.com'],
|
||||
pendingDomains: ['pending.com'],
|
||||
})
|
||||
@@ -300,6 +316,7 @@ describe('team api', () => {
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.networkSandboxEnabled).toBe(false)
|
||||
expect(data.allowedDomains).toEqual(['example.com'])
|
||||
expect(data.pendingDomains).toEqual(['pending.com'])
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
@@ -314,6 +331,7 @@ describe('team api', () => {
|
||||
|
||||
it('PUT /teams/:teamId/sandbox updates sandbox settings', async () => {
|
||||
mockUpdateSandboxSettings.mockResolvedValue({
|
||||
networkSandboxEnabled: true,
|
||||
allowedDomains: ['new.com'],
|
||||
pendingDomains: ['new-pending.com'],
|
||||
})
|
||||
@@ -321,11 +339,16 @@ describe('team api', () => {
|
||||
const res = await app.request('/teams/t1/sandbox', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ allowedDomains: ['new.com'], pendingDomains: ['new-pending.com'] }),
|
||||
body: JSON.stringify({
|
||||
networkSandboxEnabled: true,
|
||||
allowedDomains: ['new.com'],
|
||||
pendingDomains: ['new-pending.com'],
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.networkSandboxEnabled).toBe(true)
|
||||
expect(data.allowedDomains).toEqual(['new.com'])
|
||||
expect(data.pendingDomains).toEqual(['new-pending.com'])
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
@@ -336,6 +359,7 @@ describe('team api', () => {
|
||||
}),
|
||||
)
|
||||
expect(mockUpdateSandboxSettings).toHaveBeenCalledWith('t1', {
|
||||
networkSandboxEnabled: true,
|
||||
allowedDomains: ['new.com'],
|
||||
pendingDomains: ['new-pending.com'],
|
||||
})
|
||||
|
||||
@@ -32,12 +32,14 @@ vi.mock('./middleware/auth', () => ({
|
||||
describe('versionStack api', () => {
|
||||
let mockCreateVersionStack: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockChangeStackFileVersion: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockRemoveVersionFromStack: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetAsset: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetStackVersions: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
beforeEach(() => {
|
||||
mockCreateVersionStack = vi.spyOn(versionStackService, 'createVersionStack')
|
||||
mockChangeStackFileVersion = vi.spyOn(versionStackService, 'changeStackFileVersion')
|
||||
mockRemoveVersionFromStack = vi.spyOn(versionStackService, 'removeVersionFromStack')
|
||||
mockGetAsset = vi.spyOn(assetService, 'getAsset')
|
||||
mockGetStackVersions = vi.spyOn(assetService, 'getStackVersions')
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
@@ -146,4 +148,30 @@ describe('versionStack api', () => {
|
||||
expect(mockGetStackVersions).toHaveBeenCalledWith('stack1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('DELETE /version_stacks/:stackId/versions/:versionId', () => {
|
||||
it('should remove version from stack and return 200', async () => {
|
||||
mockRemoveVersionFromStack.mockResolvedValue()
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', versionStackRoute)
|
||||
|
||||
const res = await app.request('/version_stacks/stack1/versions/v1', {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Asset,
|
||||
id: 'stack1',
|
||||
permission: Permission.Edit,
|
||||
}),
|
||||
)
|
||||
expect(mockRemoveVersionFromStack).toHaveBeenCalledWith({
|
||||
stackId: 'stack1',
|
||||
fileId: 'v1',
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -75,5 +75,24 @@ const route = app
|
||||
const versions = await assetService.getStackVersions(stackId)
|
||||
return c.json(versions)
|
||||
})
|
||||
.delete('/version_stacks/:stackId/versions/:versionId', async (c) => {
|
||||
const stackId = c.req.param('stackId')
|
||||
const versionId = c.req.param('versionId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: stackId,
|
||||
})
|
||||
|
||||
await versionStackService.removeVersionFromStack({
|
||||
stackId,
|
||||
fileId: versionId,
|
||||
})
|
||||
|
||||
return new Response(null, { status: 200 })
|
||||
})
|
||||
|
||||
export default route
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/core",
|
||||
"version": "0.3.4",
|
||||
"version": "0.4.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
@@ -8,6 +8,7 @@
|
||||
"dependencies": {
|
||||
"@earendil-works/pi-agent-core": "0.82.1",
|
||||
"@earendil-works/pi-ai": "0.82.1",
|
||||
"@modelcontextprotocol/client": "2.0.0",
|
||||
"@shumai/db": "workspace:*",
|
||||
"@shumai/dtos": "workspace:*",
|
||||
"@sinclair/typebox": "0.34.49",
|
||||
@@ -24,11 +25,13 @@
|
||||
"pino": "10.3.1",
|
||||
"sharp": "0.34.5",
|
||||
"tweetnacl": "1.0.3",
|
||||
"typebox": "1.1.38",
|
||||
"ulid": "3.0.2",
|
||||
"yaml": "2.9.0",
|
||||
"zod": "4.4.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@modelcontextprotocol/server": "2.0.0",
|
||||
"@types/adm-zip": "0.5.8",
|
||||
"@types/extract-zip": "2.0.3",
|
||||
"@types/pdfkit": "0.17.6"
|
||||
|
||||
@@ -421,4 +421,268 @@ describe('AgentService', () => {
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('agent permissions', () => {
|
||||
test('createAgent with custom permission and updateAgentPermission', async () => {
|
||||
const db = prisma
|
||||
const svc = new AgentService()
|
||||
const { team, provider, model } = await setupTestData(db)
|
||||
|
||||
const agent = await svc.createAgent({
|
||||
teamId: team.id,
|
||||
name: 'Owner Only Agent',
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
thinkingLevel: 'off',
|
||||
permission: 'owner',
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
})
|
||||
|
||||
expect(agent?.permission).toBe('owner')
|
||||
|
||||
const updated = await svc.updateAgentPermission(agent!.id, 'editor')
|
||||
expect(updated.permission).toBe('editor')
|
||||
|
||||
const updatedViaUpdateAgent = await svc.updateAgent({
|
||||
agentId: agent!.id,
|
||||
name: 'Owner Only Agent Updated',
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
thinkingLevel: 'off',
|
||||
permission: 'reviewer',
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
})
|
||||
expect(updatedViaUpdateAgent.permission).toBe('reviewer')
|
||||
})
|
||||
|
||||
test('listAgents filters chat agents by requester role when userId is provided', async () => {
|
||||
const db = prisma
|
||||
const svc = new AgentService()
|
||||
const { team, provider, model } = await setupTestData(db)
|
||||
|
||||
// Create 3 chat agents with different permissions
|
||||
const reviewerAgent = await svc.createAgent({
|
||||
teamId: team.id,
|
||||
name: 'All Users Agent',
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
thinkingLevel: 'off',
|
||||
permission: 'reviewer',
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
})
|
||||
|
||||
const editorAgent = await svc.createAgent({
|
||||
teamId: team.id,
|
||||
name: 'Editor Agent',
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
thinkingLevel: 'off',
|
||||
permission: 'editor',
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
})
|
||||
|
||||
const ownerAgent = await svc.createAgent({
|
||||
teamId: team.id,
|
||||
name: 'Owner Agent',
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
thinkingLevel: 'off',
|
||||
permission: 'owner',
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
})
|
||||
|
||||
// Create 3 test users with different roles in the team
|
||||
const reviewerUser = await db.user.create({
|
||||
data: { name: 'Reviewer User', email: 'rev@shumai.ai' },
|
||||
})
|
||||
await db.teamMember.create({
|
||||
data: { teamId: team.id, userId: reviewerUser.id, role: 'reviewer' },
|
||||
})
|
||||
|
||||
const editorUser = await db.user.create({
|
||||
data: { name: 'Editor User', email: 'ed@shumai.ai' },
|
||||
})
|
||||
await db.teamMember.create({
|
||||
data: { teamId: team.id, userId: editorUser.id, role: 'editor' },
|
||||
})
|
||||
|
||||
const ownerUser = await db.user.create({
|
||||
data: { name: 'Owner User', email: 'own@shumai.ai' },
|
||||
})
|
||||
await db.teamMember.create({
|
||||
data: { teamId: team.id, userId: ownerUser.id, role: 'owner' },
|
||||
})
|
||||
|
||||
// Reviewer should only see reviewerAgent
|
||||
const reviewerList = await svc.listAgents({ teamId: team.id, userId: reviewerUser.id })
|
||||
const reviewerAgentIds = reviewerList.map((a) => a.id)
|
||||
expect(reviewerAgentIds).toContain(reviewerAgent!.id)
|
||||
expect(reviewerAgentIds).not.toContain(editorAgent!.id)
|
||||
expect(reviewerAgentIds).not.toContain(ownerAgent!.id)
|
||||
|
||||
// Editor should see reviewerAgent and editorAgent
|
||||
const editorList = await svc.listAgents({ teamId: team.id, userId: editorUser.id })
|
||||
const editorAgentIds = editorList.map((a) => a.id)
|
||||
expect(editorAgentIds).toContain(reviewerAgent!.id)
|
||||
expect(editorAgentIds).toContain(editorAgent!.id)
|
||||
expect(editorAgentIds).not.toContain(ownerAgent!.id)
|
||||
|
||||
// Owner should see all agents
|
||||
const ownerList = await svc.listAgents({ teamId: team.id, userId: ownerUser.id })
|
||||
const ownerAgentIds = ownerList.map((a) => a.id)
|
||||
expect(ownerAgentIds).toContain(reviewerAgent!.id)
|
||||
expect(ownerAgentIds).toContain(editorAgent!.id)
|
||||
expect(ownerAgentIds).toContain(ownerAgent!.id)
|
||||
})
|
||||
|
||||
test('listProjectChatAgents filters by effective project role and chat/enabled only', async () => {
|
||||
const db = prisma
|
||||
const svc = new AgentService()
|
||||
const { team, provider, model } = await setupTestData(db)
|
||||
|
||||
const project = await db.project.create({
|
||||
data: { name: 'Proj Agents', teamId: team.id },
|
||||
})
|
||||
|
||||
// Two chat agents + one disabled chat agent + one embedding agent
|
||||
const reviewerAgent = await svc.createAgent({
|
||||
teamId: team.id,
|
||||
name: 'Reviewer Chat',
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
thinkingLevel: 'off',
|
||||
permission: 'reviewer',
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
})
|
||||
const editorAgent = await svc.createAgent({
|
||||
teamId: team.id,
|
||||
name: 'Editor Chat',
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
thinkingLevel: 'off',
|
||||
permission: 'editor',
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
})
|
||||
const disabledAgent = await svc.createAgent({
|
||||
teamId: team.id,
|
||||
name: 'Disabled Chat',
|
||||
type: 'chat',
|
||||
enabled: false,
|
||||
thinkingLevel: 'off',
|
||||
permission: 'reviewer',
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
})
|
||||
|
||||
// Team reviewer, promoted to project owner in this project
|
||||
const projectOwner = await db.user.create({
|
||||
data: { name: 'Proj Owner', email: 'projowner@shumai.ai' },
|
||||
})
|
||||
const projectOwnerTm = await db.teamMember.create({
|
||||
data: { teamId: team.id, userId: projectOwner.id, role: 'reviewer', scope: 'team' },
|
||||
})
|
||||
await db.projectMember.create({
|
||||
data: { projectId: project.id, teamMemberId: projectOwnerTm.id, role: 'owner' },
|
||||
})
|
||||
|
||||
const list = await svc.listProjectChatAgents(project.id, projectOwner.id)
|
||||
const ids = list.map((a) => a.id)
|
||||
expect(ids).toContain(reviewerAgent!.id)
|
||||
expect(ids).toContain(editorAgent!.id)
|
||||
expect(ids).not.toContain(disabledAgent!.id)
|
||||
expect(list.every((a) => a.type === 'chat')).toBe(true)
|
||||
expect(list.every((a) => a.enabled)).toBe(true)
|
||||
})
|
||||
|
||||
test('listProjectChatAgents restricts project-scoped members to their project role', async () => {
|
||||
const db = prisma
|
||||
const svc = new AgentService()
|
||||
const { team, provider, model } = await setupTestData(db)
|
||||
|
||||
const project = await db.project.create({
|
||||
data: { name: 'Proj Guest', teamId: team.id },
|
||||
})
|
||||
|
||||
const reviewerAgent = await svc.createAgent({
|
||||
teamId: team.id,
|
||||
name: 'Reviewer Chat',
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
thinkingLevel: 'off',
|
||||
permission: 'reviewer',
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
})
|
||||
const editorAgent = await svc.createAgent({
|
||||
teamId: team.id,
|
||||
name: 'Editor Chat',
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
thinkingLevel: 'off',
|
||||
permission: 'editor',
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
})
|
||||
|
||||
// Project-scoped member invited as reviewer in this project
|
||||
const guest = await db.user.create({
|
||||
data: { name: 'Guest', email: 'guest@shumai.ai' },
|
||||
})
|
||||
const guestTm = await db.teamMember.create({
|
||||
data: { teamId: team.id, userId: guest.id, role: 'reviewer', scope: 'project' },
|
||||
})
|
||||
await db.projectMember.create({
|
||||
data: { projectId: project.id, teamMemberId: guestTm.id, role: 'reviewer' },
|
||||
})
|
||||
|
||||
const ids = (await svc.listProjectChatAgents(project.id, guest.id)).map((a) => a.id)
|
||||
expect(ids).toContain(reviewerAgent!.id)
|
||||
expect(ids).not.toContain(editorAgent!.id)
|
||||
})
|
||||
|
||||
test('listProjectChatAgents returns empty for users outside the project', async () => {
|
||||
const db = prisma
|
||||
const svc = new AgentService()
|
||||
const { team, provider, model } = await setupTestData(db)
|
||||
|
||||
const project = await db.project.create({
|
||||
data: { name: 'Proj Closed', teamId: team.id },
|
||||
})
|
||||
const projectB = await db.project.create({
|
||||
data: { name: 'Proj Other', teamId: team.id },
|
||||
})
|
||||
|
||||
await svc.createAgent({
|
||||
teamId: team.id,
|
||||
name: 'Reviewer Chat',
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
thinkingLevel: 'off',
|
||||
permission: 'reviewer',
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
})
|
||||
|
||||
// Project-scoped member of projectB only
|
||||
const guest = await db.user.create({
|
||||
data: { name: 'Guest B', email: 'guestb@shumai.ai' },
|
||||
})
|
||||
const guestTm = await db.teamMember.create({
|
||||
data: { teamId: team.id, userId: guest.id, role: 'reviewer', scope: 'project' },
|
||||
})
|
||||
await db.projectMember.create({
|
||||
data: { projectId: projectB.id, teamMemberId: guestTm.id, role: 'reviewer' },
|
||||
})
|
||||
|
||||
const ids = (await svc.listProjectChatAgents(project.id, guest.id)).map((a) => a.id)
|
||||
expect(ids).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { prisma, type Prisma } from '@shumai/db'
|
||||
import { prisma, type Prisma, type TeamMemberRole } from '@shumai/db'
|
||||
import {
|
||||
CreateAgentParams,
|
||||
DeleteAgentParams,
|
||||
ListAgentsParams,
|
||||
UpdateAgentParams,
|
||||
AgentSessionInfo,
|
||||
AgentInfo,
|
||||
AgentType,
|
||||
} from '@shumai/dtos'
|
||||
import {
|
||||
paginateQuery,
|
||||
@@ -14,10 +16,35 @@ import {
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { getAvatarUrl } from '@shumai/core/src/user/avatar'
|
||||
import { resolveEffectiveRole } from '@shumai/core/src/authz/authz'
|
||||
import { getAllowedAgentRoles } from './permissions'
|
||||
import AdmZip from 'adm-zip'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
|
||||
const agentInclude = {
|
||||
user: true,
|
||||
provider: true,
|
||||
modelRef: true,
|
||||
skills: { include: { skill: true } },
|
||||
mcpServers: true,
|
||||
} satisfies Prisma.AgentInclude
|
||||
|
||||
/** Structural shape consumed by `toAgentInfo` (works with any standard include). */
|
||||
interface AgentInfoSource {
|
||||
id: string
|
||||
type: AgentType
|
||||
enabled: boolean
|
||||
permission: TeamMemberRole
|
||||
providerId: string | null
|
||||
modelId: string | null
|
||||
config: unknown
|
||||
soul: string | null
|
||||
user: { name: string; image: string | null }
|
||||
skills: Array<{ id: string; skillId: string; skill: { id: string; name: string } }>
|
||||
mcpServers: Array<{ mcpServerId: string }>
|
||||
}
|
||||
|
||||
function extractS3Key(urlOrKey?: string | null): string | null | undefined {
|
||||
if (!urlOrKey) return urlOrKey
|
||||
const match = urlOrKey.match(/files\/[A-Z0-9]{26}/)
|
||||
@@ -114,6 +141,7 @@ export class AgentService {
|
||||
name,
|
||||
type,
|
||||
enabled,
|
||||
permission,
|
||||
avatar,
|
||||
providerId,
|
||||
modelId,
|
||||
@@ -121,6 +149,7 @@ export class AgentService {
|
||||
systemPrompt,
|
||||
soul,
|
||||
skills,
|
||||
mcpServerIds,
|
||||
deniedTools,
|
||||
} = params
|
||||
|
||||
@@ -178,6 +207,7 @@ export class AgentService {
|
||||
teamId,
|
||||
type,
|
||||
enabled: enabled ?? true,
|
||||
permission: permission || 'reviewer',
|
||||
providerId: providerId || null,
|
||||
modelId: modelId || null,
|
||||
soul,
|
||||
@@ -189,6 +219,12 @@ export class AgentService {
|
||||
skillId,
|
||||
})) || [],
|
||||
},
|
||||
mcpServers: {
|
||||
create:
|
||||
mcpServerIds?.map((mcpServerId) => ({
|
||||
mcpServerId,
|
||||
})) || [],
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
@@ -202,7 +238,11 @@ export class AgentService {
|
||||
|
||||
return tx.agent.findUnique({
|
||||
where: { id: agent.id },
|
||||
include: { user: true, skills: { include: { skill: true } } },
|
||||
include: {
|
||||
user: true,
|
||||
skills: { include: { skill: true } },
|
||||
mcpServers: { include: { mcpServer: true } },
|
||||
},
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -213,6 +253,7 @@ export class AgentService {
|
||||
name,
|
||||
type,
|
||||
enabled,
|
||||
permission,
|
||||
avatar,
|
||||
providerId,
|
||||
modelId,
|
||||
@@ -220,6 +261,7 @@ export class AgentService {
|
||||
systemPrompt,
|
||||
soul,
|
||||
skills,
|
||||
mcpServerIds,
|
||||
deniedTools,
|
||||
} = params
|
||||
|
||||
@@ -278,11 +320,17 @@ export class AgentService {
|
||||
where: { agentId },
|
||||
})
|
||||
|
||||
// Update MCP server assignments: easier to delete all and recreate
|
||||
await tx.agentMcpServer.deleteMany({
|
||||
where: { agentId },
|
||||
})
|
||||
|
||||
return tx.agent.update({
|
||||
where: { id: agentId },
|
||||
data: {
|
||||
type,
|
||||
enabled: enabled ?? true,
|
||||
...(permission ? { permission } : {}),
|
||||
providerId: providerId || null,
|
||||
modelId: modelId || null,
|
||||
soul,
|
||||
@@ -294,12 +342,45 @@ export class AgentService {
|
||||
skillId,
|
||||
})) || [],
|
||||
},
|
||||
mcpServers: {
|
||||
create:
|
||||
mcpServerIds?.map((mcpServerId) => ({
|
||||
mcpServerId,
|
||||
})) || [],
|
||||
},
|
||||
},
|
||||
include: {
|
||||
user: true,
|
||||
skills: { include: { skill: true } },
|
||||
mcpServers: { include: { mcpServer: true } },
|
||||
},
|
||||
include: { user: true, skills: { include: { skill: true } } },
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async updateAgentPermission(agentId: string, permission: 'owner' | 'editor' | 'reviewer') {
|
||||
const existing = await this.prismaClient.agent.findUnique({
|
||||
where: { id: agentId },
|
||||
})
|
||||
if (!existing) throw new Error('agent not found')
|
||||
|
||||
return this.prismaClient.agent.update({
|
||||
where: { id: agentId },
|
||||
data: { permission },
|
||||
include: {
|
||||
user: true,
|
||||
provider: true,
|
||||
modelRef: true,
|
||||
skills: {
|
||||
include: {
|
||||
skill: true,
|
||||
},
|
||||
},
|
||||
mcpServers: true,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
async getAgent(params: { agentId: string }) {
|
||||
return this.prismaClient.agent.findUnique({
|
||||
where: { id: params.agentId },
|
||||
@@ -321,10 +402,96 @@ export class AgentService {
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Map an agent (with the standard relations include) to the AgentInfo DTO.
|
||||
* Shared by the team-level agent list and the project-scoped chat-agent list.
|
||||
*/
|
||||
async toAgentInfo(agent: AgentInfoSource): Promise<AgentInfo> {
|
||||
const config = agent.config as unknown as PrismaJson.AgentConfig
|
||||
return {
|
||||
id: agent.id,
|
||||
name: agent.user.name,
|
||||
type: agent.type as AgentType,
|
||||
enabled: agent.enabled,
|
||||
permission: agent.permission,
|
||||
avatar: (await getAvatarUrl(agent.user.image)) || undefined,
|
||||
providerId: agent.providerId || undefined,
|
||||
modelId: agent.modelId || undefined,
|
||||
thinkingLevel: config.thinkingLevel || 'off',
|
||||
systemPrompt: config.systemPrompt,
|
||||
soul: agent.soul || undefined,
|
||||
skills: agent.skills.map((s) => ({
|
||||
id: s.id,
|
||||
skillId: s.skillId,
|
||||
skill: s.skill,
|
||||
})),
|
||||
mcpServerIds: (agent.mcpServers || []).map((m) => m.mcpServerId),
|
||||
deniedTools: config.deniedTools || [],
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List the chat agents available to a user inside a specific project,
|
||||
* resolved against the user's effective project role (project override wins;
|
||||
* restricted users get an empty list). Used by the one-to-one chat selector.
|
||||
*/
|
||||
async listProjectChatAgents(projectId: string, userId: string): Promise<AgentInfo[]> {
|
||||
const project = await this.prismaClient.project.findUnique({
|
||||
where: { id: projectId },
|
||||
select: { teamId: true },
|
||||
})
|
||||
if (!project) return []
|
||||
|
||||
const effectiveRole = await resolveEffectiveRole(project.teamId, projectId, userId)
|
||||
if (!effectiveRole) return []
|
||||
|
||||
const allowedRoles = getAllowedAgentRoles(effectiveRole)
|
||||
|
||||
const agents = await this.prismaClient.agent.findMany({
|
||||
where: {
|
||||
teamId: project.teamId,
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
permission: { in: allowedRoles },
|
||||
},
|
||||
orderBy: { id: 'desc' },
|
||||
include: agentInclude,
|
||||
})
|
||||
|
||||
return Promise.all(agents.map((agent) => this.toAgentInfo(agent)))
|
||||
}
|
||||
|
||||
async listAgents(params: ListAgentsParams) {
|
||||
const allowedRoles = params.userId
|
||||
? getAllowedAgentRoles(
|
||||
(
|
||||
await this.prismaClient.teamMember.findUnique({
|
||||
where: {
|
||||
teamIdUserId: {
|
||||
teamId: params.teamId,
|
||||
userId: params.userId,
|
||||
},
|
||||
},
|
||||
select: { role: true },
|
||||
})
|
||||
)?.role,
|
||||
)
|
||||
: null
|
||||
|
||||
return this.prismaClient.agent.findMany({
|
||||
where: {
|
||||
teamId: params.teamId,
|
||||
...(allowedRoles
|
||||
? {
|
||||
OR: [
|
||||
{ type: { not: 'chat' } },
|
||||
{
|
||||
type: 'chat',
|
||||
permission: { in: allowedRoles },
|
||||
},
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
orderBy: {
|
||||
id: 'desc',
|
||||
@@ -338,6 +505,7 @@ export class AgentService {
|
||||
skill: true,
|
||||
},
|
||||
},
|
||||
mcpServers: true,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { getRoleLevel, getAgentRequiredLevel, getAllowedAgentRoles } from './permissions'
|
||||
|
||||
describe('agent permission helpers', () => {
|
||||
describe('getRoleLevel', () => {
|
||||
it('maps each role to its level', () => {
|
||||
expect(getRoleLevel('reviewer')).toBe(1)
|
||||
expect(getRoleLevel('editor')).toBe(2)
|
||||
expect(getRoleLevel('owner')).toBe(3)
|
||||
})
|
||||
|
||||
it('resolves missing roles to 0 (fail closed)', () => {
|
||||
expect(getRoleLevel(null)).toBe(0)
|
||||
expect(getRoleLevel(undefined)).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getAgentRequiredLevel', () => {
|
||||
it('maps each permission to its required level', () => {
|
||||
expect(getAgentRequiredLevel('reviewer')).toBe(1)
|
||||
expect(getAgentRequiredLevel('editor')).toBe(2)
|
||||
expect(getAgentRequiredLevel('owner')).toBe(3)
|
||||
})
|
||||
|
||||
it('defaults missing permissions to reviewer level (1)', () => {
|
||||
expect(getAgentRequiredLevel(null)).toBe(1)
|
||||
expect(getAgentRequiredLevel(undefined)).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getAllowedAgentRoles', () => {
|
||||
it('returns inclusive role sets per hierarchy', () => {
|
||||
expect(getAllowedAgentRoles('owner')).toEqual(['reviewer', 'editor', 'owner'])
|
||||
expect(getAllowedAgentRoles('editor')).toEqual(['reviewer', 'editor'])
|
||||
expect(getAllowedAgentRoles('reviewer')).toEqual(['reviewer'])
|
||||
})
|
||||
|
||||
it('defaults missing roles to reviewer only', () => {
|
||||
expect(getAllowedAgentRoles(null)).toEqual(['reviewer'])
|
||||
expect(getAllowedAgentRoles(undefined)).toEqual(['reviewer'])
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { TeamMemberRole } from '@shumai/db'
|
||||
|
||||
/**
|
||||
* Numeric levels for the team role hierarchy used by agent permissions.
|
||||
* The record is typed exhaustively over `TeamMemberRole`, so adding a new
|
||||
* role to the enum will fail compilation until it is handled here.
|
||||
*/
|
||||
const ROLE_LEVELS: Record<TeamMemberRole, number> = {
|
||||
reviewer: 1,
|
||||
editor: 2,
|
||||
owner: 3,
|
||||
}
|
||||
|
||||
/**
|
||||
* Numeric level of a team role for agent-permission comparisons.
|
||||
* Unknown or missing roles resolve to 0, which is below every agent
|
||||
* permission, so lookups fail closed.
|
||||
*/
|
||||
export function getRoleLevel(role: TeamMemberRole | null | undefined): number {
|
||||
if (!role) return 0
|
||||
return ROLE_LEVELS[role] ?? 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimum role level required to use an agent with the given permission.
|
||||
* Unknown or missing permissions resolve to 1 (reviewer), the most
|
||||
* permissive default.
|
||||
*/
|
||||
export function getAgentRequiredLevel(permission: TeamMemberRole | null | undefined): number {
|
||||
if (!permission) return 1
|
||||
return ROLE_LEVELS[permission] ?? 1
|
||||
}
|
||||
|
||||
/**
|
||||
* Roles allowed to use agents, following the inclusive role hierarchy:
|
||||
* owner sees owner+editor+reviewer agents, editor sees editor+reviewer,
|
||||
* reviewer (or any unknown/missing role) sees reviewer agents only.
|
||||
*/
|
||||
export function getAllowedAgentRoles(role: TeamMemberRole | null | undefined): TeamMemberRole[] {
|
||||
const level = getRoleLevel(role)
|
||||
if (level >= 3) return ['reviewer', 'editor', 'owner']
|
||||
if (level === 2) return ['reviewer', 'editor']
|
||||
return ['reviewer']
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -16,35 +16,41 @@ import {
|
||||
UpdateAssetNameRequest,
|
||||
UpdateAssetOrderRequest,
|
||||
AssetUserInfo,
|
||||
ListRecentsRequest,
|
||||
} from '@shumai/dtos'
|
||||
import { type Asset, AssetStatus, AssetType, Prisma, type StorageKey } from '@shumai/db'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { PaginatedData, paginateQuery, PaginationParams } from '@shumai/core/src/pagination'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { dedupeSymlinksToTarget } from './symlink'
|
||||
import { watermarkService } from '@shumai/core/src/watermark/watermark'
|
||||
import { generateKeyBetween } from 'jittered-fractional-indexing'
|
||||
import { getAvatarUrl } from '@shumai/core/src/user/avatar'
|
||||
import { getAgentRequiredLevel, getRoleLevel } from '@shumai/core/src/agent/permissions'
|
||||
import { resolveEffectiveRole } from '@shumai/core/src/authz/authz'
|
||||
|
||||
type AssetWithIncludes = Prisma.AssetGetPayload<{
|
||||
include: {
|
||||
creator: true
|
||||
metadataValues: true
|
||||
storageKey: true
|
||||
target: {
|
||||
include: {
|
||||
creator: true
|
||||
metadataValues: true
|
||||
storageKey: true
|
||||
children: {
|
||||
include: { creator: true; metadataValues: true; storageKey: true }
|
||||
}
|
||||
}
|
||||
}
|
||||
children: {
|
||||
include: { creator: true; metadataValues: true; storageKey: true }
|
||||
}
|
||||
}
|
||||
export const assetInclude = {
|
||||
creator: true,
|
||||
metadataValues: true,
|
||||
storageKey: true,
|
||||
target: {
|
||||
include: {
|
||||
creator: true,
|
||||
metadataValues: true,
|
||||
storageKey: true,
|
||||
children: {
|
||||
include: { creator: true, metadataValues: true, storageKey: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
children: {
|
||||
include: { creator: true, metadataValues: true, storageKey: true },
|
||||
},
|
||||
} as const
|
||||
|
||||
export type AssetWithIncludes = Prisma.AssetGetPayload<{
|
||||
include: typeof assetInclude
|
||||
}>
|
||||
|
||||
type CommentWithIncludes = Prisma.AssetCommentGetPayload<{
|
||||
@@ -160,6 +166,9 @@ export class AssetService {
|
||||
const count = await tx.asset.count({ where: { parentId: stack.id } })
|
||||
|
||||
if (count === 0) {
|
||||
await tx.asset.deleteMany({
|
||||
where: { targetId: stack.id, type: AssetType.symlink },
|
||||
})
|
||||
if (stack.parentId) {
|
||||
await tx.asset.update({
|
||||
where: { id: stack.parentId },
|
||||
@@ -174,9 +183,14 @@ export class AssetService {
|
||||
if (!lastChild) return
|
||||
if (!stack.parentId) throw new Error('Stack has no parent')
|
||||
|
||||
await tx.asset.updateMany({
|
||||
where: { targetId: stack.id, type: AssetType.symlink },
|
||||
data: { targetId: lastChild.id, name: lastChild.name },
|
||||
})
|
||||
|
||||
await tx.asset.update({
|
||||
where: { id: lastChild.id },
|
||||
data: { parentId: stack.parentId, sortIndex: null },
|
||||
data: { parentId: stack.parentId, sortIndex: stack.sortIndex },
|
||||
})
|
||||
await tx.asset.delete({ where: { id: stack.id } })
|
||||
}
|
||||
@@ -273,6 +287,14 @@ export class AssetService {
|
||||
firstSortIndex = newSortIndex
|
||||
}
|
||||
|
||||
if (newParent.type === AssetType.version_stack) {
|
||||
await dedupeSymlinksToTarget(tx, {
|
||||
targetIds: req.assetIds,
|
||||
newTargetId: newParent.id,
|
||||
name: '',
|
||||
})
|
||||
}
|
||||
|
||||
const oldParent = await tx.asset.findUnique({
|
||||
where: { id: oldParentId },
|
||||
})
|
||||
@@ -579,6 +601,12 @@ export class AssetService {
|
||||
},
|
||||
})
|
||||
|
||||
// Update existing symlinks pointing to destFile or sourceAsset
|
||||
await dedupeSymlinksToTarget(tx, {
|
||||
targetIds: [destFile.id, sourceAsset.id],
|
||||
newTargetId: stack.id,
|
||||
})
|
||||
|
||||
const oldParent = await tx.asset.findUnique({ where: { id: oldParentId } })
|
||||
if (oldParent) {
|
||||
await this.dissolveStackIfEmpty(tx, oldParent)
|
||||
@@ -604,10 +632,7 @@ export class AssetService {
|
||||
projectId: req.projectId,
|
||||
isDeleted: true,
|
||||
deletedAt: { gte: thirtyDaysAgo },
|
||||
OR: [
|
||||
{ type: { in: typesToQuery } },
|
||||
{ type: AssetType.symlink, target: { type: { in: typesToQuery } } },
|
||||
],
|
||||
type: { in: typesToQuery },
|
||||
}
|
||||
} else {
|
||||
if (!req.assetId) {
|
||||
@@ -626,7 +651,7 @@ export class AssetService {
|
||||
isDeleted: false,
|
||||
OR: [
|
||||
{ type: { in: typesToQuery } },
|
||||
{ type: AssetType.symlink, target: { type: { in: typesToQuery } } },
|
||||
{ type: AssetType.symlink, target: { isDeleted: false, type: { in: typesToQuery } } },
|
||||
],
|
||||
}
|
||||
}
|
||||
@@ -932,9 +957,42 @@ export class AssetService {
|
||||
}
|
||||
|
||||
async updateAssetName(req: UpdateAssetNameRequest): Promise<AssetInfo> {
|
||||
const asset = await this.prismaClient.asset.update({
|
||||
const existing = await this.prismaClient.asset.findUnique({
|
||||
where: { id: req.id },
|
||||
include: { target: true },
|
||||
})
|
||||
if (!existing) throw new Error('Asset not found')
|
||||
|
||||
let targetType = existing.type
|
||||
let targetId = existing.id
|
||||
|
||||
if (existing.type === AssetType.symlink && existing.target) {
|
||||
targetType = existing.target.type
|
||||
targetId = existing.target.id
|
||||
}
|
||||
|
||||
if (targetType === AssetType.version_stack) {
|
||||
const latestChild = await this.prismaClient.asset.findFirst({
|
||||
where: { parentId: targetId, isDeleted: false },
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
select: { id: true },
|
||||
})
|
||||
if (!latestChild) {
|
||||
throw new Error('No active version found in stack to rename')
|
||||
}
|
||||
await this.prismaClient.asset.update({
|
||||
where: { id: latestChild.id },
|
||||
data: { name: req.name },
|
||||
})
|
||||
} else {
|
||||
await this.prismaClient.asset.update({
|
||||
where: { id: req.id },
|
||||
data: { name: req.name },
|
||||
})
|
||||
}
|
||||
|
||||
const asset = await this.prismaClient.asset.findUnique({
|
||||
where: { id: req.id },
|
||||
data: { name: req.name },
|
||||
include: {
|
||||
creator: true,
|
||||
metadataValues: true,
|
||||
@@ -960,6 +1018,8 @@ export class AssetService {
|
||||
storageKey: true,
|
||||
},
|
||||
})
|
||||
if (!asset) throw new Error('Asset not found')
|
||||
|
||||
const infos = await this.toAssetInfos([asset as unknown as AssetWithIncludes])
|
||||
return infos[0]
|
||||
}
|
||||
@@ -1040,6 +1100,39 @@ export class AssetService {
|
||||
})
|
||||
}
|
||||
|
||||
const allDeletedIds = [a.id, ...descendantIds]
|
||||
const symlinks = await tx.asset.findMany({
|
||||
where: {
|
||||
targetId: { in: allDeletedIds },
|
||||
isDeleted: false,
|
||||
type: AssetType.symlink,
|
||||
},
|
||||
})
|
||||
|
||||
if (symlinks.length > 0) {
|
||||
await tx.asset.updateMany({
|
||||
where: { id: { in: symlinks.map((s) => s.id) } },
|
||||
data: {
|
||||
isDeleted: true,
|
||||
status: AssetStatus.trashed,
|
||||
deletedAt: new Date(),
|
||||
},
|
||||
})
|
||||
|
||||
const parentCounts = new Map<string, number>()
|
||||
for (const s of symlinks) {
|
||||
if (s.parentId) {
|
||||
parentCounts.set(s.parentId, (parentCounts.get(s.parentId) || 0) + 1)
|
||||
}
|
||||
}
|
||||
for (const [parentId, count] of parentCounts.entries()) {
|
||||
await tx.asset.update({
|
||||
where: { id: parentId },
|
||||
data: { fileCount: { decrement: count } },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
await tx.asset.update({
|
||||
where: { id: a.id },
|
||||
data: {
|
||||
@@ -1063,9 +1156,16 @@ export class AssetService {
|
||||
UNION ALL
|
||||
SELECT a.id FROM assets a
|
||||
INNER JOIN descendant d ON a.parent_id = d.id
|
||||
),
|
||||
all_purging_targets AS (
|
||||
SELECT id FROM descendant
|
||||
),
|
||||
all_affected_symlinks AS (
|
||||
SELECT s.id FROM assets s
|
||||
WHERE s.type = 'symlink' AND s.target_id IN (SELECT id FROM all_purging_targets)
|
||||
)
|
||||
UPDATE assets SET status = 'pending_purge', updated_at = NOW()
|
||||
WHERE id IN (SELECT id FROM descendant);
|
||||
WHERE id IN (SELECT id FROM all_purging_targets) OR id IN (SELECT id FROM all_affected_symlinks);
|
||||
`
|
||||
}
|
||||
|
||||
@@ -1251,6 +1351,39 @@ export class AssetService {
|
||||
})
|
||||
}
|
||||
|
||||
const allRestoredIds = [a.id, ...descendantIds]
|
||||
const symlinks = await tx.asset.findMany({
|
||||
where: {
|
||||
targetId: { in: allRestoredIds },
|
||||
isDeleted: true,
|
||||
type: AssetType.symlink,
|
||||
},
|
||||
})
|
||||
|
||||
if (symlinks.length > 0) {
|
||||
await tx.asset.updateMany({
|
||||
where: { id: { in: symlinks.map((s) => s.id) } },
|
||||
data: {
|
||||
isDeleted: false,
|
||||
status: AssetStatus.processed,
|
||||
deletedAt: null,
|
||||
},
|
||||
})
|
||||
|
||||
const parentCounts = new Map<string, number>()
|
||||
for (const s of symlinks) {
|
||||
if (s.parentId) {
|
||||
parentCounts.set(s.parentId, (parentCounts.get(s.parentId) || 0) + 1)
|
||||
}
|
||||
}
|
||||
for (const [parentId, count] of parentCounts.entries()) {
|
||||
await tx.asset.update({
|
||||
where: { id: parentId },
|
||||
data: { fileCount: { increment: count } },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
await tx.asset.update({
|
||||
where: { id: a.id },
|
||||
data: {
|
||||
@@ -1319,30 +1452,43 @@ export class AssetService {
|
||||
const mentionedAgentIds = new Set(botMentionMatches.map((match) => match[1]))
|
||||
const handledAgentIds = new Set<string>()
|
||||
|
||||
// Effective role for the project context (project override wins; project-
|
||||
// scoped members without project access resolve to null and are denied).
|
||||
const effectiveRole = a.project?.team
|
||||
? await resolveEffectiveRole(a.project.team.id, a.project.id, req.userId, tx)
|
||||
: null
|
||||
|
||||
const userLevel = getRoleLevel(effectiveRole)
|
||||
|
||||
if (parentComment && a.project) {
|
||||
const rootSessionId = parentComment.sessionId
|
||||
const isRootAgent = !!rootSessionId || parentComment.creator?.type === 'agent'
|
||||
const rootAgentId = parentComment.creatorId
|
||||
|
||||
if (isRootAgent && rootAgentId && mentionedAgentIds.has(rootAgentId)) {
|
||||
await tx.workflowTask.create({
|
||||
data: {
|
||||
assetId: a.id,
|
||||
type: 'chat',
|
||||
status: 'pending',
|
||||
teamId: a.project.team.id,
|
||||
projectId: a.project.id,
|
||||
payload: {
|
||||
const rootAgent = await tx.agent.findUnique({ where: { id: rootAgentId } })
|
||||
const requiredLevel = getAgentRequiredLevel(rootAgent?.permission)
|
||||
|
||||
if (userLevel >= requiredLevel) {
|
||||
await tx.workflowTask.create({
|
||||
data: {
|
||||
assetId: a.id,
|
||||
type: 'chat',
|
||||
status: 'pending',
|
||||
teamId: a.project.team.id,
|
||||
projectId: a.project.id,
|
||||
agent: {
|
||||
userCommentId: comment.id,
|
||||
agentId: rootAgentId,
|
||||
sessionId: rootSessionId || undefined,
|
||||
userId: req.userId,
|
||||
payload: {
|
||||
projectId: a.project.id,
|
||||
agent: {
|
||||
userCommentId: comment.id,
|
||||
agentId: rootAgentId,
|
||||
sessionId: rootSessionId || undefined,
|
||||
userId: req.userId,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
})
|
||||
}
|
||||
handledAgentIds.add(rootAgentId)
|
||||
}
|
||||
}
|
||||
@@ -1356,7 +1502,12 @@ export class AssetService {
|
||||
foundAgent = true
|
||||
} else {
|
||||
const agent = await tx.agent.findUnique({ where: { id: agentId } })
|
||||
if (agent) foundAgent = true
|
||||
if (agent) {
|
||||
const requiredLevel = getAgentRequiredLevel(agent.permission)
|
||||
if (userLevel >= requiredLevel) {
|
||||
foundAgent = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (foundAgent && a.project) {
|
||||
@@ -1545,7 +1696,7 @@ export class AssetService {
|
||||
return { data: infos, pageInfo }
|
||||
}
|
||||
|
||||
private async toAssetInfos(assets: AssetWithIncludes[]): Promise<AssetInfo[]> {
|
||||
async toAssetInfos(assets: AssetWithIncludes[]): Promise<AssetInfo[]> {
|
||||
const stackIds = new Set<string>()
|
||||
|
||||
for (const a of assets) {
|
||||
@@ -1592,6 +1743,15 @@ export class AssetService {
|
||||
}
|
||||
}
|
||||
|
||||
const agentMdRecords =
|
||||
assets.length > 0
|
||||
? await this.prismaClient.assetAgentMd.findMany({
|
||||
where: { assetId: { in: assets.map((a) => a.id) } },
|
||||
select: { assetId: true },
|
||||
})
|
||||
: []
|
||||
const hasAgentMdSet = new Set(agentMdRecords.map((r) => r.assetId))
|
||||
|
||||
const result: AssetInfo[] = []
|
||||
for (const a of assets) {
|
||||
let latestVersion:
|
||||
@@ -1620,6 +1780,7 @@ export class AssetService {
|
||||
id: v.id,
|
||||
name: v.name,
|
||||
previewUrl: preview?.thumbnailUrl || null,
|
||||
createdAt: v.createdAt.toISOString(),
|
||||
creator: v.creator
|
||||
? {
|
||||
id: v.creator.id,
|
||||
@@ -1735,9 +1896,12 @@ export class AssetService {
|
||||
result.push({
|
||||
id: a.id,
|
||||
name:
|
||||
a.type === AssetType.version_stack && (a.name === '' || !a.name)
|
||||
a.type === AssetType.version_stack ||
|
||||
(a.type === AssetType.symlink && a.target?.type === AssetType.version_stack)
|
||||
? latestVersion.name
|
||||
: a.name,
|
||||
: a.type === AssetType.symlink
|
||||
? a.name || latestVersion.name || a.target?.name || ''
|
||||
: a.name,
|
||||
sizeByte: Number(latestVersion.sizeByte),
|
||||
fileCount: latestVersion.fileCount,
|
||||
type: a.type,
|
||||
@@ -1753,6 +1917,7 @@ export class AssetService {
|
||||
creator,
|
||||
fieldValues,
|
||||
sortIndex: a.sortIndex,
|
||||
hasAgentsMd: hasAgentMdSet.has(a.id),
|
||||
media: media as unknown as AssetInfo['media'],
|
||||
versionStack,
|
||||
})
|
||||
@@ -1766,7 +1931,8 @@ export class AssetService {
|
||||
version: number
|
||||
name: string
|
||||
previewUrl: string | null
|
||||
creator: { id: string; name: string | null } | null
|
||||
createdAt: string
|
||||
creator: { id: string; name: string | null; image?: string | null } | null
|
||||
}>
|
||||
> {
|
||||
const versions = await this.prismaClient.asset.findMany({
|
||||
@@ -1787,6 +1953,7 @@ export class AssetService {
|
||||
version: versions.length - i,
|
||||
name: v.name,
|
||||
previewUrl: preview?.thumbnailUrl || null,
|
||||
createdAt: v.createdAt.toISOString(),
|
||||
creator: v.creator
|
||||
? {
|
||||
id: v.creator.id,
|
||||
@@ -1966,7 +2133,13 @@ export class AssetService {
|
||||
const key = file.storageKeyId ? storageKeyMap.get(file.storageKeyId) : null
|
||||
if (!key) return null
|
||||
|
||||
const url = await s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'GET', true)
|
||||
const url = await s3Service.presign(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
key,
|
||||
'GET',
|
||||
true,
|
||||
file.name,
|
||||
)
|
||||
|
||||
return {
|
||||
id: file.id,
|
||||
@@ -1988,7 +2161,7 @@ export class AssetService {
|
||||
const targetAssetId = await this.resolveLatestVersionId(assetId)
|
||||
const asset = await this.prismaClient.asset.findUnique({
|
||||
where: { id: targetAssetId },
|
||||
select: { id: true, parentId: true, storageKey: { select: { key: true } } },
|
||||
select: { id: true, name: true, parentId: true, storageKey: { select: { key: true } } },
|
||||
})
|
||||
|
||||
if (!asset?.storageKey?.key) {
|
||||
@@ -2022,10 +2195,16 @@ export class AssetService {
|
||||
throw new Error('Key does not belong to this asset')
|
||||
}
|
||||
|
||||
return s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'GET', true)
|
||||
return s3Service.presign(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
key,
|
||||
'GET',
|
||||
true,
|
||||
asset.name ?? undefined,
|
||||
)
|
||||
}
|
||||
|
||||
private async toPreviewInfo(asset: Asset | AssetWithIncludes): Promise<PreviewInfo | null> {
|
||||
async toPreviewInfo(asset: Asset | AssetWithIncludes): Promise<PreviewInfo | null> {
|
||||
if (!asset.media) return null
|
||||
|
||||
const proxyType = (asset.media?.proxyType || null) as 'image' | 'video' | 'audio' | 'pdf' | null
|
||||
@@ -2152,6 +2331,243 @@ export class AssetService {
|
||||
completionLastChangedBy,
|
||||
}
|
||||
}
|
||||
|
||||
async getAgentsMd(assetId: string): Promise<string | null> {
|
||||
const asset = await this.prismaClient.asset.findUnique({
|
||||
where: { id: assetId },
|
||||
select: { type: true },
|
||||
})
|
||||
if (!asset) throw new Error('Asset not found')
|
||||
if (asset.type !== AssetType.folder && asset.type !== AssetType.root) {
|
||||
throw new Error('AGENTS.md can only be stored on folders')
|
||||
}
|
||||
const record = await this.prismaClient.assetAgentMd.findUnique({
|
||||
where: { assetId },
|
||||
select: { content: true },
|
||||
})
|
||||
return record?.content ?? null
|
||||
}
|
||||
|
||||
async updateAgentsMd(assetId: string, content: string): Promise<{ content: string }> {
|
||||
const asset = await this.prismaClient.asset.findUnique({
|
||||
where: { id: assetId },
|
||||
select: { id: true, type: true },
|
||||
})
|
||||
if (!asset) throw new Error('Asset not found')
|
||||
if (asset.type !== AssetType.folder && asset.type !== AssetType.root) {
|
||||
throw new Error('AGENTS.md can only be stored on folders')
|
||||
}
|
||||
const trimmed = content.trim()
|
||||
if (trimmed.length === 0) {
|
||||
await this.prismaClient.assetAgentMd.deleteMany({
|
||||
where: { assetId },
|
||||
})
|
||||
return { content: '' }
|
||||
}
|
||||
const record = await this.prismaClient.assetAgentMd.upsert({
|
||||
where: { assetId },
|
||||
create: { assetId, content },
|
||||
update: { content },
|
||||
select: { content: true },
|
||||
})
|
||||
return { content: record.content }
|
||||
}
|
||||
|
||||
async getNestedAgentsMd(assetId: string): Promise<Array<{ path: string; content: string }>> {
|
||||
let currentId: string | null = assetId
|
||||
const nodes: Array<{
|
||||
id: string
|
||||
name: string
|
||||
type: AssetType
|
||||
parentId: string | null
|
||||
}> = []
|
||||
|
||||
while (currentId) {
|
||||
const node: {
|
||||
id: string
|
||||
name: string
|
||||
type: AssetType
|
||||
parentId: string | null
|
||||
} | null = await this.prismaClient.asset.findUnique({
|
||||
where: { id: currentId },
|
||||
select: { id: true, name: true, type: true, parentId: true },
|
||||
})
|
||||
if (!node) break
|
||||
nodes.unshift(node)
|
||||
currentId = node.parentId
|
||||
}
|
||||
|
||||
if (nodes.length === 0) return []
|
||||
|
||||
const agentMds = await this.prismaClient.assetAgentMd.findMany({
|
||||
where: { assetId: { in: nodes.map((n) => n.id) } },
|
||||
select: { assetId: true, content: true },
|
||||
})
|
||||
const agentMdMap = new Map(agentMds.map((m) => [m.assetId, m.content]))
|
||||
|
||||
const results: Array<{ path: string; content: string }> = []
|
||||
let currentFolderPath = ''
|
||||
|
||||
for (let i = 0; i < nodes.length; i++) {
|
||||
const node = nodes[i]
|
||||
let virtualPath: string
|
||||
|
||||
if (node.type === AssetType.root || i === 0) {
|
||||
currentFolderPath = ''
|
||||
virtualPath = '/AGENTS.md'
|
||||
} else {
|
||||
currentFolderPath = currentFolderPath
|
||||
? `${currentFolderPath}/${node.name}`
|
||||
: `/${node.name}`
|
||||
virtualPath = `${currentFolderPath}/AGENTS.md`
|
||||
}
|
||||
|
||||
const content = agentMdMap.get(node.id)
|
||||
if (content && content.trim().length > 0) {
|
||||
results.push({
|
||||
path: virtualPath,
|
||||
content: content.trim(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
/**
|
||||
* Record a file view by user in project.
|
||||
* If the asset is a child file in a version stack, resolves to the version stack.
|
||||
* Enforces a maximum cap of 100 recent file items per (userId, projectId).
|
||||
*/
|
||||
async recordRecentView(userId: string, projectId: string, assetId: string): Promise<void> {
|
||||
const asset = await this.prismaClient.asset.findFirst({
|
||||
where: { id: assetId, projectId },
|
||||
select: {
|
||||
id: true,
|
||||
type: true,
|
||||
parentId: true,
|
||||
isDeleted: true,
|
||||
target: { select: { type: true, projectId: true, isDeleted: true } },
|
||||
},
|
||||
})
|
||||
|
||||
if (!asset || asset.isDeleted) return
|
||||
|
||||
const isFileAsset =
|
||||
asset.type === AssetType.file ||
|
||||
asset.type === AssetType.version_stack ||
|
||||
(asset.type === AssetType.symlink &&
|
||||
asset.target !== null &&
|
||||
(asset.target.type === AssetType.file || asset.target.type === AssetType.version_stack) &&
|
||||
asset.target.projectId === projectId &&
|
||||
!asset.target.isDeleted)
|
||||
if (!isFileAsset) return
|
||||
|
||||
let targetAssetId = asset.id
|
||||
|
||||
// If it's a file inside a version stack, record the version stack instead
|
||||
if (asset.type === AssetType.file && asset.parentId) {
|
||||
const parent = await this.prismaClient.asset.findFirst({
|
||||
where: { id: asset.parentId, projectId, type: AssetType.version_stack, isDeleted: false },
|
||||
select: { id: true },
|
||||
})
|
||||
if (parent) {
|
||||
targetAssetId = parent.id
|
||||
}
|
||||
}
|
||||
|
||||
const now = new Date()
|
||||
|
||||
// Upsert into recent_file_items
|
||||
await this.prismaClient.recentFileItem.upsert({
|
||||
where: {
|
||||
userIdProjectIdAssetId: {
|
||||
userId,
|
||||
projectId,
|
||||
assetId: targetAssetId,
|
||||
},
|
||||
},
|
||||
update: {
|
||||
viewedAt: now,
|
||||
},
|
||||
create: {
|
||||
userId,
|
||||
projectId,
|
||||
assetId: targetAssetId,
|
||||
viewedAt: now,
|
||||
},
|
||||
})
|
||||
|
||||
// Prune if more than 100 items for this (userId, projectId)
|
||||
const count = await this.prismaClient.recentFileItem.count({
|
||||
where: { userId, projectId },
|
||||
})
|
||||
|
||||
if (count > 100) {
|
||||
const itemsToKeep = await this.prismaClient.recentFileItem.findMany({
|
||||
where: { userId, projectId },
|
||||
orderBy: [{ viewedAt: 'desc' }, { id: 'desc' }],
|
||||
take: 100,
|
||||
select: { id: true },
|
||||
})
|
||||
const keepIds = itemsToKeep.map((item) => item.id)
|
||||
|
||||
await this.prismaClient.recentFileItem.deleteMany({
|
||||
where: {
|
||||
userId,
|
||||
projectId,
|
||||
id: { notIn: keepIds },
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List recent files for user in project, paginated up to 100 total items.
|
||||
*/
|
||||
async listRecents(
|
||||
userId: string,
|
||||
projectId: string,
|
||||
req: ListRecentsRequest,
|
||||
): Promise<PaginatedData<AssetInfo[]>> {
|
||||
const where = {
|
||||
userId,
|
||||
projectId,
|
||||
asset: {
|
||||
isDeleted: false,
|
||||
projectId,
|
||||
},
|
||||
}
|
||||
|
||||
return paginateQuery(
|
||||
async (skip, take) => {
|
||||
if (skip >= 100) return []
|
||||
const effectiveTake = Math.min(take, 100 - skip)
|
||||
if (effectiveTake <= 0) return []
|
||||
|
||||
const recents = await this.prismaClient.recentFileItem.findMany({
|
||||
where,
|
||||
orderBy: [{ viewedAt: 'desc' }, { id: 'desc' }],
|
||||
skip,
|
||||
take: effectiveTake,
|
||||
include: {
|
||||
asset: {
|
||||
include: assetInclude,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const assets = recents.map((r) => r.asset).filter((a): a is AssetWithIncludes => !!a)
|
||||
|
||||
return await this.toAssetInfos(assets)
|
||||
},
|
||||
async () => {
|
||||
const total = await this.prismaClient.recentFileItem.count({ where })
|
||||
return Math.min(total, 100)
|
||||
},
|
||||
req,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export const assetService = new AssetService()
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { prisma, AssetType, AssetStatus } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { assetService } from './asset'
|
||||
import { projectService } from '../project/project'
|
||||
|
||||
describe('AssetService - Recently Viewed', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
async function setupProject() {
|
||||
const user1 = await prisma.user.create({
|
||||
data: { name: 'User 1', email: 'user1@example.com' },
|
||||
})
|
||||
const user2 = await prisma.user.create({
|
||||
data: { name: 'User 2', email: 'user2@example.com' },
|
||||
})
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
name: 'Test Team',
|
||||
settings: {
|
||||
transcode: { videoStrategy: 'best_match' },
|
||||
},
|
||||
sandbox: { create: {} },
|
||||
},
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: {
|
||||
teamId: team.id,
|
||||
userId: user1.id,
|
||||
role: 'owner',
|
||||
scope: 'team',
|
||||
},
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: {
|
||||
teamId: team.id,
|
||||
userId: user2.id,
|
||||
role: 'editor',
|
||||
scope: 'team',
|
||||
},
|
||||
})
|
||||
|
||||
const project = await projectService.createProject(user1, {
|
||||
name: 'Test Project',
|
||||
teamId: team.id,
|
||||
})
|
||||
|
||||
return { user1, user2, team, project }
|
||||
}
|
||||
|
||||
it('records recent file view and returns it in descending order', async () => {
|
||||
const { user1, project } = await setupProject()
|
||||
|
||||
const file1 = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'file1.mp4',
|
||||
type: AssetType.file,
|
||||
status: 'processed',
|
||||
projectId: project.id,
|
||||
parentId: project.rootFolder!,
|
||||
},
|
||||
})
|
||||
const file2 = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'file2.mp4',
|
||||
type: AssetType.file,
|
||||
status: 'processed',
|
||||
projectId: project.id,
|
||||
parentId: project.rootFolder!,
|
||||
},
|
||||
})
|
||||
|
||||
await assetService.recordRecentView(user1.id, project.id, file1.id)
|
||||
await assetService.recordRecentView(user1.id, project.id, file2.id)
|
||||
|
||||
const list = await assetService.listRecents(user1.id, project.id, {})
|
||||
expect(list.data.length).toBe(2)
|
||||
expect(list.data[0].id).toBe(file2.id)
|
||||
expect(list.data[1].id).toBe(file1.id)
|
||||
expect(list.pageInfo.total).toBe(2)
|
||||
})
|
||||
|
||||
it('updates viewedAt when viewing the same file again', async () => {
|
||||
const { user1, project } = await setupProject()
|
||||
|
||||
const file1 = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'file1.mp4',
|
||||
type: AssetType.file,
|
||||
status: 'processed',
|
||||
projectId: project.id,
|
||||
parentId: project.rootFolder!,
|
||||
},
|
||||
})
|
||||
const file2 = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'file2.mp4',
|
||||
type: AssetType.file,
|
||||
status: 'processed',
|
||||
projectId: project.id,
|
||||
parentId: project.rootFolder!,
|
||||
},
|
||||
})
|
||||
|
||||
await assetService.recordRecentView(user1.id, project.id, file1.id)
|
||||
await assetService.recordRecentView(user1.id, project.id, file2.id)
|
||||
// View file1 again
|
||||
await assetService.recordRecentView(user1.id, project.id, file1.id)
|
||||
|
||||
const list = await assetService.listRecents(user1.id, project.id, {})
|
||||
expect(list.data.length).toBe(2)
|
||||
expect(list.data[0].id).toBe(file1.id)
|
||||
expect(list.data[1].id).toBe(file2.id)
|
||||
})
|
||||
|
||||
it('records version stack when viewing a child version file', async () => {
|
||||
const { user1, project } = await setupProject()
|
||||
|
||||
const stack = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'version_stack',
|
||||
type: AssetType.version_stack,
|
||||
status: 'processed',
|
||||
projectId: project.id,
|
||||
parentId: project.rootFolder!,
|
||||
},
|
||||
})
|
||||
|
||||
const version1 = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'v1.mp4',
|
||||
type: AssetType.file,
|
||||
status: 'processed',
|
||||
projectId: project.id,
|
||||
parentId: stack.id,
|
||||
},
|
||||
})
|
||||
|
||||
await assetService.recordRecentView(user1.id, project.id, version1.id)
|
||||
|
||||
const list = await assetService.listRecents(user1.id, project.id, {})
|
||||
expect(list.data.length).toBe(1)
|
||||
expect(list.data[0].id).toBe(stack.id)
|
||||
expect(list.data[0].type).toBe(AssetType.version_stack)
|
||||
})
|
||||
|
||||
it('isolates recents per user', async () => {
|
||||
const { user1, user2, project } = await setupProject()
|
||||
|
||||
const file1 = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'file1.mp4',
|
||||
type: AssetType.file,
|
||||
status: 'processed',
|
||||
projectId: project.id,
|
||||
parentId: project.rootFolder!,
|
||||
},
|
||||
})
|
||||
|
||||
await assetService.recordRecentView(user1.id, project.id, file1.id)
|
||||
|
||||
const user1List = await assetService.listRecents(user1.id, project.id, {})
|
||||
const user2List = await assetService.listRecents(user2.id, project.id, {})
|
||||
|
||||
expect(user1List.data.length).toBe(1)
|
||||
expect(user2List.data.length).toBe(0)
|
||||
})
|
||||
|
||||
it('does not record assets from another project', async () => {
|
||||
const { user1, team, project } = await setupProject()
|
||||
const otherProject = await projectService.createProject(user1, {
|
||||
name: 'Other Project',
|
||||
teamId: team.id,
|
||||
})
|
||||
const foreignFile = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'foreign-file.mp4',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.processed,
|
||||
projectId: otherProject.id,
|
||||
parentId: otherProject.rootFolder!,
|
||||
},
|
||||
})
|
||||
|
||||
await assetService.recordRecentView(user1.id, project.id, foreignFile.id)
|
||||
|
||||
const list = await assetService.listRecents(user1.id, project.id, {})
|
||||
expect(list.data).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('does not record non-file assets', async () => {
|
||||
const { user1, project } = await setupProject()
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'folder',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.processed,
|
||||
projectId: project.id,
|
||||
parentId: project.rootFolder!,
|
||||
},
|
||||
})
|
||||
|
||||
await assetService.recordRecentView(user1.id, project.id, folder.id)
|
||||
|
||||
const list = await assetService.listRecents(user1.id, project.id, {})
|
||||
expect(list.data).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('does not return soft-deleted files in recents', async () => {
|
||||
const { user1, project } = await setupProject()
|
||||
|
||||
const file1 = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'file1.mp4',
|
||||
type: AssetType.file,
|
||||
status: 'processed',
|
||||
projectId: project.id,
|
||||
parentId: project.rootFolder!,
|
||||
},
|
||||
})
|
||||
|
||||
await assetService.recordRecentView(user1.id, project.id, file1.id)
|
||||
|
||||
// Soft delete file1
|
||||
await prisma.asset.update({
|
||||
where: { id: file1.id },
|
||||
data: { isDeleted: true, status: 'trashed' },
|
||||
})
|
||||
|
||||
const list = await assetService.listRecents(user1.id, project.id, {})
|
||||
expect(list.data.length).toBe(0)
|
||||
})
|
||||
|
||||
it('caps recents at 100 items per user/project', async () => {
|
||||
const { user1, project } = await setupProject()
|
||||
|
||||
// Batch create 105 assets
|
||||
const assetsData = Array.from({ length: 105 }, (_, i) => ({
|
||||
name: `file_${i}.mp4`,
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.processed,
|
||||
projectId: project.id,
|
||||
parentId: project.rootFolder!,
|
||||
}))
|
||||
await prisma.asset.createMany({ data: assetsData })
|
||||
const allAssets = await prisma.asset.findMany({
|
||||
where: { projectId: project.id, parentId: project.rootFolder! },
|
||||
orderBy: { id: 'asc' },
|
||||
})
|
||||
|
||||
// Seed 100 items in recentFileItem
|
||||
const baseDate = new Date('2026-01-01T00:00:00Z')
|
||||
await prisma.recentFileItem.createMany({
|
||||
data: allAssets.slice(0, 100).map((a, i) => ({
|
||||
userId: user1.id,
|
||||
projectId: project.id,
|
||||
assetId: a.id,
|
||||
viewedAt: new Date(baseDate.getTime() + i * 1000),
|
||||
})),
|
||||
})
|
||||
|
||||
// Now record view for the 101st asset to trigger pruning
|
||||
const newAsset = allAssets[100]
|
||||
await assetService.recordRecentView(user1.id, project.id, newAsset.id)
|
||||
|
||||
const count = await prisma.recentFileItem.count({
|
||||
where: { userId: user1.id, projectId: project.id },
|
||||
})
|
||||
expect(count).toBe(100)
|
||||
|
||||
const list = await assetService.listRecents(user1.id, project.id, { first: 100 })
|
||||
expect(list.data.length).toBe(100)
|
||||
// The most recently viewed file should be newAsset
|
||||
expect(list.data[0].id).toBe(newAsset.id)
|
||||
// The oldest file (allAssets[0]) should have been pruned
|
||||
expect(list.data.some((d) => d.id === allAssets[0].id)).toBe(false)
|
||||
}, 15000)
|
||||
})
|
||||
@@ -0,0 +1,249 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { AssetType } from '@shumai/db'
|
||||
import { dedupeSymlinksToTarget } from './symlink'
|
||||
|
||||
async function setupShareFolder(projectId: string, fileCount: number) {
|
||||
const shareRoot = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'share-root',
|
||||
type: AssetType.share_root,
|
||||
projectId,
|
||||
status: 'uploaded',
|
||||
fileCount,
|
||||
},
|
||||
})
|
||||
return shareRoot
|
||||
}
|
||||
|
||||
describe('dedupeSymlinksToTarget', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
async function setupProject() {
|
||||
const team = await prisma.team.create({ data: { name: 'Team ' + Date.now() } })
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Project ' + Date.now(), teamId: team.id },
|
||||
})
|
||||
const root = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'root',
|
||||
type: AssetType.folder,
|
||||
projectId: project.id,
|
||||
status: 'uploaded',
|
||||
},
|
||||
})
|
||||
const fileA = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'a.txt',
|
||||
type: AssetType.file,
|
||||
parentId: root.id,
|
||||
projectId: project.id,
|
||||
status: 'uploaded',
|
||||
sizeByte: 10,
|
||||
},
|
||||
})
|
||||
const fileB = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'b.txt',
|
||||
type: AssetType.file,
|
||||
parentId: root.id,
|
||||
projectId: project.id,
|
||||
status: 'uploaded',
|
||||
sizeByte: 20,
|
||||
},
|
||||
})
|
||||
return { project, root, fileA, fileB }
|
||||
}
|
||||
|
||||
it('repoints one symlink per parent and deletes duplicates, decrementing fileCount once', async () => {
|
||||
const { project, root, fileA, fileB } = await setupProject()
|
||||
const shareRoot = await setupShareFolder(project.id, 2)
|
||||
|
||||
const symA = await prisma.asset.create({
|
||||
data: {
|
||||
name: fileA.name,
|
||||
type: AssetType.symlink,
|
||||
parentId: shareRoot.id,
|
||||
targetId: fileA.id,
|
||||
projectId: project.id,
|
||||
status: 'uploaded',
|
||||
},
|
||||
})
|
||||
const symB = await prisma.asset.create({
|
||||
data: {
|
||||
name: fileB.name,
|
||||
type: AssetType.symlink,
|
||||
parentId: shareRoot.id,
|
||||
targetId: fileB.id,
|
||||
projectId: project.id,
|
||||
status: 'uploaded',
|
||||
},
|
||||
})
|
||||
|
||||
const stack = await prisma.asset.create({
|
||||
data: {
|
||||
name: '',
|
||||
type: AssetType.version_stack,
|
||||
parentId: root.id,
|
||||
projectId: project.id,
|
||||
status: 'uploaded',
|
||||
fileCount: 2,
|
||||
sizeByte: 30,
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.$transaction((tx) =>
|
||||
dedupeSymlinksToTarget(tx, { targetIds: [fileA.id, fileB.id], newTargetId: stack.id }),
|
||||
)
|
||||
|
||||
// First symlink repointed to the stack, second deleted
|
||||
const repointed = await prisma.asset.findUnique({ where: { id: symA.id } })
|
||||
expect(repointed?.targetId).toBe(stack.id)
|
||||
expect(await prisma.asset.findUnique({ where: { id: symB.id } })).toBeNull()
|
||||
|
||||
// fileCount decremented exactly once (2 -> 1)
|
||||
const updatedShareRoot = await prisma.asset.findUnique({ where: { id: shareRoot.id } })
|
||||
expect(updatedShareRoot?.fileCount).toBe(1)
|
||||
})
|
||||
|
||||
it('deletes a file symlink when the parent already shows the stack', async () => {
|
||||
const { project, root, fileA } = await setupProject()
|
||||
const shareRoot = await setupShareFolder(project.id, 2)
|
||||
|
||||
const stack = await prisma.asset.create({
|
||||
data: {
|
||||
name: '',
|
||||
type: AssetType.version_stack,
|
||||
parentId: root.id,
|
||||
projectId: project.id,
|
||||
status: 'uploaded',
|
||||
fileCount: 1,
|
||||
sizeByte: 10,
|
||||
},
|
||||
})
|
||||
// Share already contains a symlink to the stack
|
||||
const stackSymlink = await prisma.asset.create({
|
||||
data: {
|
||||
name: '',
|
||||
type: AssetType.symlink,
|
||||
parentId: shareRoot.id,
|
||||
targetId: stack.id,
|
||||
projectId: project.id,
|
||||
status: 'uploaded',
|
||||
},
|
||||
})
|
||||
// And a symlink to the file being moved into the stack
|
||||
const fileSymlink = await prisma.asset.create({
|
||||
data: {
|
||||
name: fileA.name,
|
||||
type: AssetType.symlink,
|
||||
parentId: shareRoot.id,
|
||||
targetId: fileA.id,
|
||||
projectId: project.id,
|
||||
status: 'uploaded',
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.$transaction((tx) =>
|
||||
dedupeSymlinksToTarget(tx, { targetIds: [fileA.id], newTargetId: stack.id }),
|
||||
)
|
||||
|
||||
// File symlink deleted, stack symlink untouched
|
||||
expect(await prisma.asset.findUnique({ where: { id: fileSymlink.id } })).toBeNull()
|
||||
const updatedStackSymlink = await prisma.asset.findUnique({ where: { id: stackSymlink.id } })
|
||||
expect(updatedStackSymlink?.targetId).toBe(stack.id)
|
||||
|
||||
// fileCount decremented once (2 -> 1)
|
||||
const updatedShareRoot = await prisma.asset.findUnique({ where: { id: shareRoot.id } })
|
||||
expect(updatedShareRoot?.fileCount).toBe(1)
|
||||
})
|
||||
|
||||
it('repoints symlinks in different share folders without changing fileCounts', async () => {
|
||||
const { project, root, fileA, fileB } = await setupProject()
|
||||
const share1 = await setupShareFolder(project.id, 1)
|
||||
const share2 = await setupShareFolder(project.id, 1)
|
||||
|
||||
const sym1 = await prisma.asset.create({
|
||||
data: {
|
||||
name: fileA.name,
|
||||
type: AssetType.symlink,
|
||||
parentId: share1.id,
|
||||
targetId: fileA.id,
|
||||
projectId: project.id,
|
||||
status: 'uploaded',
|
||||
},
|
||||
})
|
||||
const sym2 = await prisma.asset.create({
|
||||
data: {
|
||||
name: fileB.name,
|
||||
type: AssetType.symlink,
|
||||
parentId: share2.id,
|
||||
targetId: fileB.id,
|
||||
projectId: project.id,
|
||||
status: 'uploaded',
|
||||
},
|
||||
})
|
||||
|
||||
const stack = await prisma.asset.create({
|
||||
data: {
|
||||
name: '',
|
||||
type: AssetType.version_stack,
|
||||
parentId: root.id,
|
||||
projectId: project.id,
|
||||
status: 'uploaded',
|
||||
fileCount: 2,
|
||||
sizeByte: 30,
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.$transaction((tx) =>
|
||||
dedupeSymlinksToTarget(tx, { targetIds: [fileA.id, fileB.id], newTargetId: stack.id }),
|
||||
)
|
||||
|
||||
expect((await prisma.asset.findUnique({ where: { id: sym1.id } }))?.targetId).toBe(stack.id)
|
||||
expect((await prisma.asset.findUnique({ where: { id: sym2.id } }))?.targetId).toBe(stack.id)
|
||||
expect((await prisma.asset.findUnique({ where: { id: share1.id } }))?.fileCount).toBe(1)
|
||||
expect((await prisma.asset.findUnique({ where: { id: share2.id } }))?.fileCount).toBe(1)
|
||||
})
|
||||
|
||||
it('sets the provided name on repointed symlinks', async () => {
|
||||
const { project, root, fileA } = await setupProject()
|
||||
const shareRoot = await setupShareFolder(project.id, 1)
|
||||
|
||||
const sym = await prisma.asset.create({
|
||||
data: {
|
||||
name: fileA.name,
|
||||
type: AssetType.symlink,
|
||||
parentId: shareRoot.id,
|
||||
targetId: fileA.id,
|
||||
projectId: project.id,
|
||||
status: 'uploaded',
|
||||
},
|
||||
})
|
||||
|
||||
const stack = await prisma.asset.create({
|
||||
data: {
|
||||
name: '',
|
||||
type: AssetType.version_stack,
|
||||
parentId: root.id,
|
||||
projectId: project.id,
|
||||
status: 'uploaded',
|
||||
fileCount: 1,
|
||||
sizeByte: 10,
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.$transaction((tx) =>
|
||||
dedupeSymlinksToTarget(tx, {
|
||||
targetIds: [fileA.id],
|
||||
newTargetId: stack.id,
|
||||
name: '',
|
||||
}),
|
||||
)
|
||||
|
||||
const updatedSym = await prisma.asset.findUnique({ where: { id: sym.id } })
|
||||
expect(updatedSym?.targetId).toBe(stack.id)
|
||||
expect(updatedSym?.name).toBe('')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,59 @@
|
||||
import { Prisma } from '@shumai/db'
|
||||
import { AssetType } from '@shumai/db'
|
||||
|
||||
interface DedupeSymlinksParams {
|
||||
/** Files being merged into a version stack — symlinks pointing at them are the candidates. */
|
||||
targetIds: string[]
|
||||
/** The version stack the files are moving into. */
|
||||
newTargetId: string
|
||||
/** Optional name to set on repointed symlinks ('' for stacks — display name comes from the latest version). */
|
||||
name?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* When files are merged into a version stack, symlinks in share folders that
|
||||
* pointed at those files must either be repointed to the stack (one per parent)
|
||||
* or deleted as duplicates. Per parent folder: if the parent already shows the
|
||||
* stack (either before this call or after the first repoint), delete the
|
||||
* incoming symlink and decrement the parent's fileCount; otherwise repoint the
|
||||
* first symlink to the stack.
|
||||
*/
|
||||
export async function dedupeSymlinksToTarget(
|
||||
tx: Prisma.TransactionClient,
|
||||
{ targetIds, newTargetId, name }: DedupeSymlinksParams,
|
||||
): Promise<void> {
|
||||
const existingSymlinks = await tx.asset.findMany({
|
||||
where: { targetId: { in: targetIds }, type: AssetType.symlink },
|
||||
orderBy: { id: 'asc' },
|
||||
})
|
||||
if (existingSymlinks.length === 0) return
|
||||
|
||||
// Parents that already display the stack (or will after the first repoint).
|
||||
const stackSymlinkParents = new Set(
|
||||
(
|
||||
await tx.asset.findMany({
|
||||
where: { targetId: newTargetId, type: AssetType.symlink },
|
||||
select: { parentId: true },
|
||||
})
|
||||
)
|
||||
.map((s) => s.parentId)
|
||||
.filter((id): id is string => !!id),
|
||||
)
|
||||
|
||||
for (const symlink of existingSymlinks) {
|
||||
if (!symlink.parentId) continue
|
||||
if (stackSymlinkParents.has(symlink.parentId)) {
|
||||
await tx.asset.delete({ where: { id: symlink.id } })
|
||||
await tx.asset.update({
|
||||
where: { id: symlink.parentId },
|
||||
data: { fileCount: { decrement: 1 } },
|
||||
})
|
||||
} else {
|
||||
stackSymlinkParents.add(symlink.parentId)
|
||||
await tx.asset.update({
|
||||
where: { id: symlink.id },
|
||||
data: { targetId: newTargetId, ...(name !== undefined ? { name } : {}) },
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user