mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-20 04:59:26 +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 |
@@ -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
|
||||
|
||||
@@ -11,6 +11,7 @@ data/
|
||||
*.db
|
||||
*.diff
|
||||
*.orig
|
||||
code_quality.md
|
||||
.agents
|
||||
|
||||
# Playwright
|
||||
|
||||
+7
-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
|
||||
|
||||
@@ -25,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/
|
||||
@@ -80,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>
|
||||
|
||||

|
||||
@@ -37,6 +37,7 @@ But Shumai goes beyond being a Frame.io alternative. With modern models like GPT
|
||||
* **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:
|
||||
|
||||
@@ -44,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]
|
||||
|
||||
+9
-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>
|
||||
|
||||
@@ -38,11 +38,19 @@ Shumai 是一个开源的 Frame.io 替代方案,专为创意团队打造,让
|
||||
* **沙箱隔离执行**: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.8",
|
||||
"version": "0.4.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/cli",
|
||||
"version": "0.3.8",
|
||||
"version": "0.4.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/transcode-app",
|
||||
"version": "0.3.8",
|
||||
"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,6 +65,7 @@ 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 |
|
||||
@@ -90,6 +93,7 @@ apps/web/e2e/
|
||||
| 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)
|
||||
})
|
||||
@@ -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.8",
|
||||
"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()
|
||||
|
||||
+6
-2
@@ -51,8 +51,12 @@
|
||||
]
|
||||
},
|
||||
{
|
||||
"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 |
@@ -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.
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "shumai",
|
||||
"version": "0.3.8",
|
||||
"version": "0.4.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"repository": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/agent",
|
||||
"version": "0.3.8",
|
||||
"version": "0.4.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -514,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
|
||||
@@ -571,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: {
|
||||
@@ -618,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,
|
||||
@@ -731,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 },
|
||||
@@ -749,6 +759,7 @@ describe('Agent Database Activities Integration', () => {
|
||||
})
|
||||
|
||||
// agent response msg4
|
||||
await sleep(2)
|
||||
const msg4 = await prisma.assetComment.create({
|
||||
data: {
|
||||
assetId: asset.id,
|
||||
@@ -760,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 },
|
||||
})
|
||||
@@ -783,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,
|
||||
@@ -831,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 },
|
||||
@@ -869,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 },
|
||||
@@ -1086,6 +1103,55 @@ describe('Agent Database Activities Integration', () => {
|
||||
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({
|
||||
data: {
|
||||
|
||||
@@ -5,7 +5,12 @@ 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'
|
||||
@@ -13,6 +18,7 @@ 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'
|
||||
@@ -27,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 {
|
||||
@@ -173,7 +180,12 @@ When creating a file or version, you may attach metadata (for example, the AI mo
|
||||
// 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)
|
||||
? await mcpService.buildAgentTools(
|
||||
params.agentId,
|
||||
params.teamId,
|
||||
params.userId,
|
||||
params.projectId,
|
||||
)
|
||||
: []
|
||||
|
||||
const { session, harness } = await createAgentSession({
|
||||
@@ -286,6 +298,39 @@ When creating a file or version, you may attach metadata (for example, the AI mo
|
||||
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
|
||||
@@ -316,6 +361,29 @@ When creating a file or version, you may attach metadata (for example, the AI mo
|
||||
} 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')
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -328,6 +396,29 @@ When creating a file or version, you may attach metadata (for example, the AI mo
|
||||
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()
|
||||
@@ -886,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 },
|
||||
@@ -913,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',
|
||||
@@ -934,10 +1039,22 @@ export async function getAgentChatContextActivity(params: {
|
||||
include: { models: true },
|
||||
})
|
||||
|
||||
// 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.
|
||||
// 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)
|
||||
const enabledSkillIds = enabledSkills.map((s) => s.id)
|
||||
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({
|
||||
@@ -954,7 +1071,7 @@ export async function getAgentChatContextActivity(params: {
|
||||
return {
|
||||
agent,
|
||||
dbProviders,
|
||||
teamSkills: enabledSkills,
|
||||
teamSkills: permittedSkills,
|
||||
mcpServers,
|
||||
enabledSkillIds,
|
||||
allowedDomains,
|
||||
|
||||
@@ -8,6 +8,7 @@ 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'
|
||||
@@ -1173,4 +1174,86 @@ describe('createAgentSession enabled skill filtering', () => {
|
||||
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()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
+62
-22
@@ -9,7 +9,10 @@ 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 { 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'
|
||||
@@ -112,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
|
||||
@@ -185,6 +176,9 @@ 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({
|
||||
@@ -217,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.
|
||||
@@ -242,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) {
|
||||
@@ -294,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 = ''
|
||||
@@ -314,7 +352,7 @@ 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),
|
||||
@@ -325,6 +363,7 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
onEnvsAdded,
|
||||
restricted ? onSkillLoaded : undefined,
|
||||
enabledSkillIds,
|
||||
projectId,
|
||||
)
|
||||
|
||||
const systemTools: AgentTool[] = []
|
||||
@@ -340,7 +379,7 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
}
|
||||
|
||||
const readThread = createReadThreadTool()
|
||||
const allTools = [
|
||||
const rawTools = [
|
||||
...mediaTools,
|
||||
readSkill,
|
||||
readThread,
|
||||
@@ -348,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))
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { prisma } from '@shumai/db'
|
||||
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' }),
|
||||
@@ -18,6 +19,7 @@ export const createReadSkillTool = (
|
||||
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',
|
||||
@@ -39,17 +41,14 @@ export const createReadSkillTool = (
|
||||
}
|
||||
|
||||
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}".`,
|
||||
|
||||
@@ -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')))
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/api",
|
||||
"version": "0.3.8",
|
||||
"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
-65
@@ -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,35 +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,
|
||||
})),
|
||||
mcpServerIds: (agent.mcpServers || []).map((m) => m.mcpServerId),
|
||||
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')
|
||||
@@ -77,26 +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,
|
||||
})),
|
||||
mcpServerIds: (agent.mcpServers || []).map((m) => m.mcpServerId),
|
||||
deniedTools: config.deniedTools || [],
|
||||
}
|
||||
const info = await agentService.toAgentInfo(agent)
|
||||
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.agent_create,
|
||||
@@ -131,29 +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,
|
||||
})),
|
||||
mcpServerIds: (agent.mcpServers || []).map((m) => m.mcpServerId),
|
||||
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 () => {
|
||||
|
||||
@@ -120,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)
|
||||
})
|
||||
|
||||
@@ -21,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>>
|
||||
|
||||
@@ -65,6 +67,8 @@ const apiRoute = new Hono<{ Variables: { user: User } }>()
|
||||
.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
|
||||
@@ -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),
|
||||
|
||||
@@ -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
|
||||
@@ -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' },
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/core",
|
||||
"version": "0.3.8",
|
||||
"version": "0.4.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -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,
|
||||
@@ -179,6 +207,7 @@ export class AgentService {
|
||||
teamId,
|
||||
type,
|
||||
enabled: enabled ?? true,
|
||||
permission: permission || 'reviewer',
|
||||
providerId: providerId || null,
|
||||
modelId: modelId || null,
|
||||
soul,
|
||||
@@ -224,6 +253,7 @@ export class AgentService {
|
||||
name,
|
||||
type,
|
||||
enabled,
|
||||
permission,
|
||||
avatar,
|
||||
providerId,
|
||||
modelId,
|
||||
@@ -300,6 +330,7 @@ export class AgentService {
|
||||
data: {
|
||||
type,
|
||||
enabled: enabled ?? true,
|
||||
...(permission ? { permission } : {}),
|
||||
providerId: providerId || null,
|
||||
modelId: modelId || null,
|
||||
soul,
|
||||
@@ -327,6 +358,29 @@ export class AgentService {
|
||||
})
|
||||
}
|
||||
|
||||
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 },
|
||||
@@ -348,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',
|
||||
|
||||
@@ -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']
|
||||
}
|
||||
@@ -41,6 +41,13 @@ describe('AssetService', () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'TestTeam_Asset_' + Date.now() },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: {
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
role: 'owner',
|
||||
},
|
||||
})
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'TestProject_Asset', teamId: team.id },
|
||||
})
|
||||
@@ -734,15 +741,6 @@ describe('AssetService', () => {
|
||||
attachmentIds: [],
|
||||
})
|
||||
|
||||
// 2. Add user as a team member with owner role (team owner)
|
||||
await prisma.teamMember.create({
|
||||
data: {
|
||||
teamId: project.teamId,
|
||||
userId: user.id,
|
||||
role: 'owner',
|
||||
},
|
||||
})
|
||||
|
||||
// Create another user
|
||||
const otherUser = await prisma.user.create({
|
||||
data: {
|
||||
@@ -813,16 +811,7 @@ describe('AssetService', () => {
|
||||
it('deleteComment cleans up S3 attachment files and database records', async () => {
|
||||
const { user, project, assets } = await setupBasicAssets()
|
||||
|
||||
// 1. Add user as team owner
|
||||
await prisma.teamMember.create({
|
||||
data: {
|
||||
teamId: project.teamId,
|
||||
userId: user.id,
|
||||
role: 'owner',
|
||||
},
|
||||
})
|
||||
|
||||
// 2. Create StorageKey and Asset for attachment
|
||||
// 1. Create StorageKey and Asset for attachment
|
||||
const storageKey = await prisma.storageKey.create({
|
||||
data: {
|
||||
key: 'attachments/test-attachment-file.png',
|
||||
@@ -1245,6 +1234,152 @@ describe('AssetService', () => {
|
||||
expect(p3b?.agent?.userId).toBe(user.id)
|
||||
})
|
||||
|
||||
it('silently skips triggering agent workflow when comment creator lacks permission', async () => {
|
||||
const { project } = await setupBasicAssets()
|
||||
const file = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'perm-file',
|
||||
type: AssetType.file,
|
||||
projectId: project.id,
|
||||
status: 'uploaded',
|
||||
},
|
||||
})
|
||||
|
||||
// Create owner-only bot agent
|
||||
const ownerBotUser = await prisma.user.create({
|
||||
data: {
|
||||
name: 'Owner Bot Agent',
|
||||
type: 'agent',
|
||||
email: `owner-bot-${Date.now()}@shumai.ai`,
|
||||
},
|
||||
})
|
||||
const ownerAgent = await prisma.agent.create({
|
||||
data: {
|
||||
id: ownerBotUser.id,
|
||||
teamId: project.teamId,
|
||||
type: 'chat',
|
||||
permission: 'owner',
|
||||
config: { provider: 'p', model: 'm' },
|
||||
},
|
||||
})
|
||||
|
||||
// Create a reviewer user
|
||||
const reviewerUser = await prisma.user.create({
|
||||
data: {
|
||||
name: 'Reviewer Member',
|
||||
email: `rev-comment-${Date.now()}@shumai.ai`,
|
||||
password: 'pw',
|
||||
},
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: project.teamId, userId: reviewerUser.id, role: 'reviewer' },
|
||||
})
|
||||
|
||||
// Reviewer mentions owner-only agent
|
||||
const comment = await assetService.createComment({
|
||||
assetId: file.id,
|
||||
userId: reviewerUser.id,
|
||||
message: `Hello <@${ownerAgent.id}>`,
|
||||
attachmentIds: [],
|
||||
})
|
||||
|
||||
// Comment was saved successfully
|
||||
expect(comment.id).toBeDefined()
|
||||
|
||||
// But no workflow task was created for ownerAgent
|
||||
const tasks = await prisma.workflowTask.findMany({
|
||||
where: {
|
||||
assetId: file.id,
|
||||
payload: { path: ['agent', 'userCommentId'], equals: comment.id },
|
||||
},
|
||||
})
|
||||
expect(tasks.length).toBe(0)
|
||||
})
|
||||
|
||||
it('uses the effective project role for bot mention permission checks', async () => {
|
||||
const { project } = await setupBasicAssets()
|
||||
const file = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'perm-file-2',
|
||||
type: AssetType.file,
|
||||
projectId: project.id,
|
||||
status: 'uploaded',
|
||||
},
|
||||
})
|
||||
|
||||
// Editor-permission chat agent
|
||||
const editorBotUser = await prisma.user.create({
|
||||
data: {
|
||||
name: 'Editor Bot Agent',
|
||||
type: 'agent',
|
||||
email: `editor-bot-${Date.now()}@shumai.ai`,
|
||||
},
|
||||
})
|
||||
const editorAgent = await prisma.agent.create({
|
||||
data: {
|
||||
id: editorBotUser.id,
|
||||
teamId: project.teamId,
|
||||
type: 'chat',
|
||||
permission: 'editor',
|
||||
config: { provider: 'p', model: 'm' },
|
||||
},
|
||||
})
|
||||
|
||||
// Team editor, demoted to project reviewer in this project
|
||||
const demoted = await prisma.user.create({
|
||||
data: { name: 'Demoted Member', email: `dem-${Date.now()}@shumai.ai`, password: 'pw' },
|
||||
})
|
||||
const demotedTm = await prisma.teamMember.create({
|
||||
data: { teamId: project.teamId, userId: demoted.id, role: 'editor', scope: 'team' },
|
||||
})
|
||||
await prisma.projectMember.create({
|
||||
data: { projectId: project.id, teamMemberId: demotedTm.id, role: 'reviewer' },
|
||||
})
|
||||
|
||||
// Project-scoped member invited as editor
|
||||
const projEditor = await prisma.user.create({
|
||||
data: { name: 'Proj Editor', email: `pe-${Date.now()}@shumai.ai`, password: 'pw' },
|
||||
})
|
||||
const projEditorTm = await prisma.teamMember.create({
|
||||
data: { teamId: project.teamId, userId: projEditor.id, role: 'reviewer', scope: 'project' },
|
||||
})
|
||||
await prisma.projectMember.create({
|
||||
data: { projectId: project.id, teamMemberId: projEditorTm.id, role: 'editor' },
|
||||
})
|
||||
|
||||
// Demoted team editor (project reviewer) mentioning the editor agent: no workflow
|
||||
const demotedComment = await assetService.createComment({
|
||||
assetId: file.id,
|
||||
userId: demoted.id,
|
||||
message: `Hello <@${editorAgent.id}>`,
|
||||
attachmentIds: [],
|
||||
})
|
||||
const demotedTasks = await prisma.workflowTask.findMany({
|
||||
where: {
|
||||
assetId: file.id,
|
||||
payload: { path: ['agent', 'userCommentId'], equals: demotedComment.id },
|
||||
},
|
||||
})
|
||||
expect(demotedTasks.length).toBe(0)
|
||||
|
||||
// Project-scoped editor mentioning the editor agent: workflow created
|
||||
const peComment = await assetService.createComment({
|
||||
assetId: file.id,
|
||||
userId: projEditor.id,
|
||||
message: `Hello <@${editorAgent.id}>`,
|
||||
attachmentIds: [],
|
||||
})
|
||||
const peTasks = await prisma.workflowTask.findMany({
|
||||
where: {
|
||||
assetId: file.id,
|
||||
payload: { path: ['agent', 'userCommentId'], equals: peComment.id },
|
||||
},
|
||||
})
|
||||
expect(peTasks.length).toBe(1)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
expect((peTasks[0].payload as any)?.agent?.userId).toBe(projEditor.id)
|
||||
})
|
||||
|
||||
it('updates asset order correctly', async () => {
|
||||
const { user, project } = await setupBasicAssets()
|
||||
|
||||
@@ -1863,7 +1998,7 @@ describe('AssetService', () => {
|
||||
expect(await prisma.asset.findUnique({ where: { id: folderA.id } })).toBeNull()
|
||||
const remainingChildren = await prisma.asset.count({ where: { parentId: folderA.id } })
|
||||
expect(remainingChildren).toBe(0)
|
||||
})
|
||||
}, 20000)
|
||||
|
||||
it('should delete the entire directory prefix for assets with complex keys (e.g., files/ULID/raw)', async () => {
|
||||
const { project } = await setupBasicAssets()
|
||||
@@ -3440,5 +3575,133 @@ describe('AssetService — natural sort by name', () => {
|
||||
})
|
||||
expect(updatedFile.name).toBe('renamed.png')
|
||||
})
|
||||
|
||||
it('cascades soft-delete and restoration to symlinks and updates parent fileCount', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Test Team ' + Date.now() } })
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Test Project', teamId: team.id },
|
||||
})
|
||||
const rootFolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'Root',
|
||||
type: AssetType.folder,
|
||||
projectId: project.id,
|
||||
status: AssetStatus.uploaded,
|
||||
},
|
||||
})
|
||||
const shareRoot = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'Share Root',
|
||||
type: AssetType.share_root,
|
||||
projectId: project.id,
|
||||
status: AssetStatus.uploaded,
|
||||
fileCount: 0,
|
||||
},
|
||||
})
|
||||
|
||||
const file = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test-file.txt',
|
||||
type: AssetType.file,
|
||||
parentId: rootFolder.id,
|
||||
projectId: project.id,
|
||||
status: AssetStatus.uploaded,
|
||||
},
|
||||
})
|
||||
await prisma.asset.update({
|
||||
where: { id: rootFolder.id },
|
||||
data: { fileCount: 1 },
|
||||
})
|
||||
|
||||
const symlink = await prisma.asset.create({
|
||||
data: {
|
||||
name: file.name,
|
||||
type: AssetType.symlink,
|
||||
parentId: shareRoot.id,
|
||||
targetId: file.id,
|
||||
projectId: project.id,
|
||||
status: AssetStatus.uploaded,
|
||||
},
|
||||
})
|
||||
await prisma.asset.update({
|
||||
where: { id: shareRoot.id },
|
||||
data: { fileCount: 1 },
|
||||
})
|
||||
|
||||
// Soft delete the file
|
||||
await assetService.deleteAssets([file.id])
|
||||
|
||||
const deletedSymlink = await prisma.asset.findUnique({ where: { id: symlink.id } })
|
||||
expect(deletedSymlink?.isDeleted).toBe(true)
|
||||
expect(deletedSymlink?.status).toBe(AssetStatus.trashed)
|
||||
|
||||
const updatedShareRoot = await prisma.asset.findUnique({ where: { id: shareRoot.id } })
|
||||
expect(updatedShareRoot?.fileCount).toBe(0)
|
||||
|
||||
// Restore the file
|
||||
await assetService.restoreAssets([file.id])
|
||||
|
||||
const restoredSymlink = await prisma.asset.findUnique({ where: { id: symlink.id } })
|
||||
expect(restoredSymlink?.isDeleted).toBe(false)
|
||||
expect(restoredSymlink?.status).toBe(AssetStatus.processed)
|
||||
|
||||
const restoredShareRoot = await prisma.asset.findUnique({ where: { id: shareRoot.id } })
|
||||
expect(restoredShareRoot?.fileCount).toBe(1)
|
||||
})
|
||||
|
||||
it('cascades permanent purge to symlinks when emptying trash', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Test Team ' + Date.now() } })
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Test Project', teamId: team.id },
|
||||
})
|
||||
const rootFolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'Root',
|
||||
type: AssetType.folder,
|
||||
projectId: project.id,
|
||||
status: AssetStatus.uploaded,
|
||||
},
|
||||
})
|
||||
const shareRoot = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'Share Root',
|
||||
type: AssetType.share_root,
|
||||
projectId: project.id,
|
||||
status: AssetStatus.uploaded,
|
||||
fileCount: 0,
|
||||
},
|
||||
})
|
||||
|
||||
const file = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'file-to-purge.txt',
|
||||
type: AssetType.file,
|
||||
parentId: rootFolder.id,
|
||||
projectId: project.id,
|
||||
status: AssetStatus.uploaded,
|
||||
},
|
||||
})
|
||||
|
||||
const symlink = await prisma.asset.create({
|
||||
data: {
|
||||
name: file.name,
|
||||
type: AssetType.symlink,
|
||||
parentId: shareRoot.id,
|
||||
targetId: file.id,
|
||||
projectId: project.id,
|
||||
status: AssetStatus.uploaded,
|
||||
},
|
||||
})
|
||||
|
||||
// Soft delete then empty trash
|
||||
await assetService.deleteAssets([file.id])
|
||||
await assetService.emptyTrash(project.id)
|
||||
|
||||
const purgedFile = await prisma.asset.findUnique({ where: { id: file.id } })
|
||||
expect(purgedFile).toBeNull()
|
||||
|
||||
const purgedSymlink = await prisma.asset.findUnique({ where: { id: symlink.id } })
|
||||
expect(purgedSymlink).toBeNull()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -16,6 +16,7 @@ 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'
|
||||
@@ -26,26 +27,30 @@ 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<{
|
||||
@@ -627,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) {
|
||||
@@ -649,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 } } },
|
||||
],
|
||||
}
|
||||
}
|
||||
@@ -1098,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: {
|
||||
@@ -1121,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);
|
||||
`
|
||||
}
|
||||
|
||||
@@ -1309,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: {
|
||||
@@ -1377,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)
|
||||
}
|
||||
}
|
||||
@@ -1414,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) {
|
||||
@@ -1603,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) {
|
||||
@@ -2111,7 +2204,7 @@ export class AssetService {
|
||||
)
|
||||
}
|
||||
|
||||
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
|
||||
@@ -2340,6 +2433,141 @@ export class AssetService {
|
||||
|
||||
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)
|
||||
})
|
||||
@@ -24,6 +24,7 @@ export async function dedupeSymlinksToTarget(
|
||||
): Promise<void> {
|
||||
const existingSymlinks = await tx.asset.findMany({
|
||||
where: { targetId: { in: targetIds }, type: AssetType.symlink },
|
||||
orderBy: { id: 'asc' },
|
||||
})
|
||||
if (existingSymlinks.length === 0) return
|
||||
|
||||
|
||||
@@ -84,4 +84,36 @@ describe('AuditLogService', () => {
|
||||
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
|
||||
it('records kanban actions accurately', async () => {
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'Kanban User', email: 'kanban_user@example.com', password: 'password' },
|
||||
})
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Kanban Audit Team' },
|
||||
})
|
||||
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.kanban_task_create,
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
itemId: 'task-123',
|
||||
})
|
||||
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.kanban_goal_create,
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
itemId: 'goal-123',
|
||||
})
|
||||
|
||||
const result = await auditLogService.listAuditLogs({
|
||||
teamId: team.id,
|
||||
actions: [AuditAction.kanban_task_create, AuditAction.kanban_goal_create],
|
||||
})
|
||||
|
||||
expect(result.total).toBe(2)
|
||||
expect(result.nodes.map((n) => n.action)).toContain(AuditAction.kanban_task_create)
|
||||
expect(result.nodes.map((n) => n.action)).toContain(AuditAction.kanban_goal_create)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { auth } from './auth'
|
||||
import { auth, authService } from './auth'
|
||||
import { userMetadataService } from '../user-metadata/user-metadata'
|
||||
import { teamService } from '@shumai/core/src/team/team'
|
||||
|
||||
@@ -93,3 +93,214 @@ describe('Auth Signup Locale Hook', () => {
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('AuthService Password Reset', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.spyOn(teamService, 'getSignupInfo').mockResolvedValue({
|
||||
initialized: false,
|
||||
demoMode: false,
|
||||
userCount: 1,
|
||||
})
|
||||
})
|
||||
|
||||
it('should throw error when generating reset link for non-existent user', async () => {
|
||||
await expect(authService.generatePasswordResetLink('nonexistent@example.com')).rejects.toThrow(
|
||||
'User with email "nonexistent@example.com" not found',
|
||||
)
|
||||
})
|
||||
|
||||
it('should generate a valid reset link and invalidate previous pending tokens', async () => {
|
||||
const email = `reset-user-${Date.now()}@example.com`
|
||||
const signUpRes = await auth.api.signUpEmail({
|
||||
headers: new Headers(),
|
||||
body: {
|
||||
email,
|
||||
password: 'initialPassword123',
|
||||
name: 'Reset User',
|
||||
},
|
||||
})
|
||||
const userId = signUpRes.user.id
|
||||
|
||||
const firstLink = await authService.generatePasswordResetLink(email)
|
||||
expect(firstLink).toContain('/reset-password?token=')
|
||||
|
||||
const firstToken = new URL(firstLink).searchParams.get('token')!
|
||||
expect(firstToken).toBeTruthy()
|
||||
|
||||
// Check that verification record exists with identifier: reset-password:<token> and value: userId
|
||||
const firstVerification = await prisma.verification.findFirst({
|
||||
where: { identifier: `reset-password:${firstToken}` },
|
||||
})
|
||||
expect(firstVerification).not.toBeNull()
|
||||
expect(firstVerification?.value).toBe(userId)
|
||||
|
||||
// Generating a second link should produce a new token and invalidate the first token
|
||||
const secondLink = await authService.generatePasswordResetLink(email)
|
||||
const secondToken = new URL(secondLink).searchParams.get('token')!
|
||||
expect(secondToken).not.toBe(firstToken)
|
||||
|
||||
const newVerification = await prisma.verification.findFirst({
|
||||
where: { identifier: `reset-password:${secondToken}` },
|
||||
})
|
||||
expect(newVerification).not.toBeNull()
|
||||
expect(newVerification?.value).toBe(userId)
|
||||
|
||||
// The first token's verification record must have been deleted
|
||||
const oldVerification = await prisma.verification.findFirst({
|
||||
where: { identifier: `reset-password:${firstToken}` },
|
||||
})
|
||||
expect(oldVerification).toBeNull()
|
||||
|
||||
// First token must fail to reset password
|
||||
await expect(
|
||||
authService.resetPassword(firstToken, 'newPasswordFromFirstToken'),
|
||||
).rejects.toThrow()
|
||||
|
||||
// Second token must succeed
|
||||
const resetRes = await authService.resetPassword(secondToken, 'newPasswordFromSecondToken')
|
||||
expect(resetRes.success).toBe(true)
|
||||
})
|
||||
|
||||
it('should reset password with valid token and revoke active sessions', async () => {
|
||||
const email = `reset-valid-${Date.now()}@example.com`
|
||||
const signUpRes = await auth.api.signUpEmail({
|
||||
headers: new Headers(),
|
||||
body: {
|
||||
email,
|
||||
password: 'oldPassword123',
|
||||
name: 'Valid Reset User',
|
||||
},
|
||||
})
|
||||
|
||||
const userId = signUpRes.user.id
|
||||
|
||||
// Create an active session
|
||||
await prisma.session.create({
|
||||
data: {
|
||||
userId,
|
||||
token: `session-${Date.now()}`,
|
||||
expiresAt: new Date(Date.now() + 86400 * 1000),
|
||||
},
|
||||
})
|
||||
|
||||
const activeSessionsBefore = await prisma.session.findMany({
|
||||
where: { userId },
|
||||
})
|
||||
expect(activeSessionsBefore.length).toBeGreaterThan(0)
|
||||
|
||||
// Generate reset link
|
||||
const link = await authService.generatePasswordResetLink(email)
|
||||
const token = new URL(link).searchParams.get('token')!
|
||||
|
||||
// Reset password
|
||||
const result = await authService.resetPassword(token, 'newPassword456')
|
||||
expect(result.success).toBe(true)
|
||||
|
||||
// Verify active sessions are revoked
|
||||
const activeSessionsAfter = await prisma.session.findMany({
|
||||
where: { userId },
|
||||
})
|
||||
expect(activeSessionsAfter.length).toBe(0)
|
||||
|
||||
// Verify token was deleted
|
||||
const usedToken = await prisma.verification.findFirst({
|
||||
where: { identifier: `reset-password:${token}` },
|
||||
})
|
||||
expect(usedToken).toBeNull()
|
||||
|
||||
// Verify user password was updated to new password
|
||||
const account = await prisma.account.findFirst({
|
||||
where: { userId, providerId: 'credential' },
|
||||
})
|
||||
expect(account).toBeDefined()
|
||||
expect(account?.password).toBeTruthy()
|
||||
|
||||
const { verifyPassword } = await import('better-auth/crypto')
|
||||
const isNewValid = await verifyPassword({
|
||||
hash: account!.password!,
|
||||
password: 'newPassword456',
|
||||
})
|
||||
expect(isNewValid).toBe(true)
|
||||
|
||||
const isOldValid = await verifyPassword({
|
||||
hash: account!.password!,
|
||||
password: 'oldPassword123',
|
||||
})
|
||||
expect(isOldValid).toBe(false)
|
||||
})
|
||||
|
||||
it('should reject expired or invalid token', async () => {
|
||||
const email = `reset-expired-${Date.now()}@example.com`
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
email,
|
||||
name: 'Expired User',
|
||||
},
|
||||
})
|
||||
|
||||
// Create expired token fixture with identifier: reset-password:<token> and value: userId
|
||||
const token = 'expired-token-123'
|
||||
await prisma.verification.create({
|
||||
data: {
|
||||
identifier: `reset-password:${token}`,
|
||||
value: user.id,
|
||||
expiresAt: new Date(Date.now() - 1000), // Expired 1 second ago
|
||||
},
|
||||
})
|
||||
|
||||
await expect(authService.resetPassword(token, 'newPassword123')).rejects.toThrow()
|
||||
|
||||
// Non-existent token
|
||||
await expect(
|
||||
authService.resetPassword('non-existent-token', 'newPassword123'),
|
||||
).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('should handle concurrent link generation for different users without crosstalk', async () => {
|
||||
const emailA = `concurrent-a-${Date.now()}@example.com`
|
||||
const emailB = `concurrent-b-${Date.now()}@example.com`
|
||||
|
||||
const [resA, resB] = await Promise.all([
|
||||
auth.api.signUpEmail({
|
||||
headers: new Headers(),
|
||||
body: { email: emailA, password: 'passwordA123', name: 'User A' },
|
||||
}),
|
||||
auth.api.signUpEmail({
|
||||
headers: new Headers(),
|
||||
body: { email: emailB, password: 'passwordB123', name: 'User B' },
|
||||
}),
|
||||
])
|
||||
|
||||
const [linkA, linkB] = await Promise.all([
|
||||
authService.generatePasswordResetLink(emailA),
|
||||
authService.generatePasswordResetLink(emailB),
|
||||
])
|
||||
|
||||
const tokenA = new URL(linkA).searchParams.get('token')!
|
||||
const tokenB = new URL(linkB).searchParams.get('token')!
|
||||
expect(tokenA).toBeTruthy()
|
||||
expect(tokenB).toBeTruthy()
|
||||
expect(tokenA).not.toBe(tokenB)
|
||||
|
||||
const verificationA = await prisma.verification.findFirst({
|
||||
where: { identifier: `reset-password:${tokenA}` },
|
||||
})
|
||||
const verificationB = await prisma.verification.findFirst({
|
||||
where: { identifier: `reset-password:${tokenB}` },
|
||||
})
|
||||
|
||||
expect(verificationA?.value).toBe(resA.user.id)
|
||||
expect(verificationB?.value).toBe(resB.user.id)
|
||||
|
||||
// Reset both passwords concurrently
|
||||
const [resetResA, resetResB] = await Promise.all([
|
||||
authService.resetPassword(tokenA, 'newPasswordA123'),
|
||||
authService.resetPassword(tokenB, 'newPasswordB123'),
|
||||
])
|
||||
|
||||
expect(resetResA.success).toBe(true)
|
||||
expect(resetResB.success).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AsyncLocalStorage } from 'node:async_hooks'
|
||||
import { betterAuth } from 'better-auth'
|
||||
import { prismaAdapter } from 'better-auth/adapters/prisma'
|
||||
import { prisma } from '@shumai/db'
|
||||
@@ -6,6 +7,13 @@ import { inviteService } from '@shumai/core/src/invite/invite'
|
||||
import { createAuthMiddleware } from 'better-auth/api'
|
||||
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
|
||||
|
||||
interface GeneratedResetLink {
|
||||
url: string
|
||||
token: string
|
||||
}
|
||||
|
||||
const resetLinkStorage = new AsyncLocalStorage<GeneratedResetLink>()
|
||||
|
||||
export const auth = betterAuth({
|
||||
database: prismaAdapter(prisma, {
|
||||
provider: 'postgresql',
|
||||
@@ -13,6 +21,15 @@ export const auth = betterAuth({
|
||||
emailAndPassword: {
|
||||
enabled: true,
|
||||
minPasswordLength: 3,
|
||||
revokeSessionsOnPasswordReset: true,
|
||||
resetPasswordTokenExpiresIn: 3600,
|
||||
sendResetPassword: async ({ url, token }) => {
|
||||
const store = resetLinkStorage.getStore()
|
||||
if (store) {
|
||||
store.url = url
|
||||
store.token = token
|
||||
}
|
||||
},
|
||||
},
|
||||
secret: process.env.BETTER_AUTH_SECRET,
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
@@ -122,3 +139,82 @@ export const auth = betterAuth({
|
||||
}),
|
||||
},
|
||||
})
|
||||
|
||||
export class AuthService {
|
||||
constructor(private readonly prismaClient: typeof prisma = prisma) {}
|
||||
|
||||
async generatePasswordResetLink(email: string): Promise<string> {
|
||||
const user = await this.prismaClient.user.findUnique({
|
||||
where: { email },
|
||||
})
|
||||
|
||||
if (!user) {
|
||||
throw new Error(`User with email "${email}" not found`)
|
||||
}
|
||||
|
||||
const context: GeneratedResetLink = { url: '', token: '' }
|
||||
await resetLinkStorage.run(context, async () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const res = await (auth.api.requestPasswordReset as any)({
|
||||
headers: new Headers(),
|
||||
body: {
|
||||
email,
|
||||
redirectTo: '/reset-password',
|
||||
},
|
||||
})
|
||||
|
||||
if (res?.error) {
|
||||
throw new Error(res.error.message || 'Failed to generate reset link')
|
||||
}
|
||||
})
|
||||
|
||||
if (context.token) {
|
||||
// Invalidate any other pending reset tokens for this user
|
||||
await this.prismaClient.verification.deleteMany({
|
||||
where: {
|
||||
value: user.id,
|
||||
identifier: {
|
||||
startsWith: 'reset-password:',
|
||||
not: `reset-password:${context.token}`,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const rawBaseUrl =
|
||||
process.env.BETTER_AUTH_URL ||
|
||||
`http://localhost:${process.env.SHUMAI_SERVER_PORT || '3000'}`
|
||||
const baseUrl = rawBaseUrl.replace(/\/$/, '')
|
||||
return `${baseUrl}/reset-password?token=${context.token}`
|
||||
}
|
||||
|
||||
throw new Error('Failed to generate reset link')
|
||||
}
|
||||
|
||||
async resetPassword(token: string, newPassword: string): Promise<{ success: boolean }> {
|
||||
if (!token || !token.trim()) {
|
||||
throw new Error('Token is required')
|
||||
}
|
||||
|
||||
if (!newPassword || newPassword.length < 3) {
|
||||
throw new Error('Password must be at least 3 characters')
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const res = await (auth.api.resetPassword as any)({
|
||||
headers: new Headers(),
|
||||
body: {
|
||||
token,
|
||||
newPassword,
|
||||
password: newPassword,
|
||||
},
|
||||
})
|
||||
|
||||
if (res?.error) {
|
||||
throw new Error(res.error.message || 'Failed to reset password')
|
||||
}
|
||||
|
||||
return { success: true }
|
||||
}
|
||||
}
|
||||
|
||||
export const authService = new AuthService()
|
||||
|
||||
@@ -502,5 +502,98 @@ describe('AuthzService', () => {
|
||||
}),
|
||||
).rejects.toThrow('User has only project scope')
|
||||
})
|
||||
|
||||
it('allows project-scoped and reviewer participants to edit team-level Kanban tasks', async () => {
|
||||
const creator = await prisma.user.create({
|
||||
data: { name: 'Owner User', email: 'owner-kanban@example.com', password: 'pass' },
|
||||
})
|
||||
const projectScopedUser = await prisma.user.create({
|
||||
data: { name: 'Proj Member', email: 'proj-kanban@example.com', password: 'pass' },
|
||||
})
|
||||
const reviewerUser = await prisma.user.create({
|
||||
data: { name: 'Reviewer User', email: 'rev-kanban@example.com', password: 'pass' },
|
||||
})
|
||||
const unassignedUser = await prisma.user.create({
|
||||
data: { name: 'Unassigned User', email: 'unassigned-kanban@example.com', password: 'pass' },
|
||||
})
|
||||
|
||||
const team = await prisma.team.create({ data: { name: 'Kanban Team' } })
|
||||
const project = await prisma.project.create({ data: { name: 'Project K', teamId: team.id } })
|
||||
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: creator.id, role: 'owner', scope: 'team' },
|
||||
})
|
||||
const tmProj = await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: projectScopedUser.id, role: 'reviewer', scope: 'project' },
|
||||
})
|
||||
await prisma.projectMember.create({
|
||||
data: { projectId: project.id, teamMemberId: tmProj.id, role: 'editor' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: reviewerUser.id, role: 'reviewer', scope: 'team' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: unassignedUser.id, role: 'reviewer', scope: 'project' },
|
||||
})
|
||||
|
||||
// Team-level task (no projectId)
|
||||
const teamTask = await prisma.kanbanTask.create({
|
||||
data: {
|
||||
teamId: team.id,
|
||||
title: 'Team Task for Project Member',
|
||||
creatorId: creator.id,
|
||||
reporterId: creator.id,
|
||||
assigneeId: projectScopedUser.id,
|
||||
},
|
||||
})
|
||||
|
||||
// 1. Project-scoped assignee on team task CAN edit
|
||||
await expect(
|
||||
authzService.hasPermission({
|
||||
type: ResourceType.KanbanTask,
|
||||
id: teamTask.id,
|
||||
user: projectScopedUser,
|
||||
permission: Permission.Edit,
|
||||
}),
|
||||
).resolves.toBeUndefined()
|
||||
|
||||
// 2. Reviewer who is reporter CAN edit
|
||||
const reviewerReportedTask = await prisma.kanbanTask.create({
|
||||
data: {
|
||||
teamId: team.id,
|
||||
title: 'Task Reported by Reviewer',
|
||||
creatorId: creator.id,
|
||||
reporterId: reviewerUser.id,
|
||||
},
|
||||
})
|
||||
await expect(
|
||||
authzService.hasPermission({
|
||||
type: ResourceType.KanbanTask,
|
||||
id: reviewerReportedTask.id,
|
||||
user: reviewerUser,
|
||||
permission: Permission.Edit,
|
||||
}),
|
||||
).resolves.toBeUndefined()
|
||||
|
||||
// 3. Unassigned project-scoped user CANNOT edit team task
|
||||
await expect(
|
||||
authzService.hasPermission({
|
||||
type: ResourceType.KanbanTask,
|
||||
id: teamTask.id,
|
||||
user: unassignedUser,
|
||||
permission: Permission.Edit,
|
||||
}),
|
||||
).rejects.toThrow('User has only project scope')
|
||||
|
||||
// 4. Unassigned reviewer CANNOT edit team task
|
||||
await expect(
|
||||
authzService.hasPermission({
|
||||
type: ResourceType.KanbanTask,
|
||||
id: teamTask.id,
|
||||
user: reviewerUser,
|
||||
permission: Permission.Edit,
|
||||
}),
|
||||
).rejects.toThrow('Permission denied')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
import { prisma, type TeamMemberRole } from '@shumai/db'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
|
||||
@@ -24,6 +24,9 @@ export enum ResourceType {
|
||||
Invite = 'invite',
|
||||
Comment = 'comment',
|
||||
AgentSession = 'agentSession',
|
||||
QuotaRule = 'quotaRule',
|
||||
KanbanGoal = 'kanbanGoal',
|
||||
KanbanTask = 'kanbanTask',
|
||||
}
|
||||
|
||||
export interface AuthzRequest {
|
||||
@@ -33,13 +36,81 @@ export interface AuthzRequest {
|
||||
id: string
|
||||
}
|
||||
|
||||
type RoleDb = typeof prisma | Prisma.TransactionClient
|
||||
|
||||
/**
|
||||
* Resolve a user's effective role for a team/project context, mirroring the
|
||||
* precedence rules enforced by `AuthzService.hasPermission`:
|
||||
*
|
||||
* 1. Project membership (`projectMember.role`) takes precedence inside a project.
|
||||
* 2. Team-scoped members fall back to their team role when no project override exists.
|
||||
* 3. Project-scoped members without a matching project record (or without a
|
||||
* project context) are restricted (`null`).
|
||||
*
|
||||
* Returns `null` for non-members as well, so callers can fail closed.
|
||||
*/
|
||||
export async function resolveEffectiveRole(
|
||||
teamId: string,
|
||||
projectId: string | undefined,
|
||||
userId: string,
|
||||
db: RoleDb = prisma,
|
||||
): Promise<TeamMemberRole | null> {
|
||||
const member = await db.teamMember.findUnique({
|
||||
where: {
|
||||
teamIdUserId: {
|
||||
teamId,
|
||||
userId,
|
||||
},
|
||||
},
|
||||
})
|
||||
if (!member) return null
|
||||
|
||||
// Project membership takes precedence when operating inside a project.
|
||||
if (projectId) {
|
||||
const pm = await db.projectMember.findUnique({
|
||||
where: {
|
||||
projectIdTeamMemberId: {
|
||||
projectId,
|
||||
teamMemberId: member.id,
|
||||
},
|
||||
},
|
||||
})
|
||||
if (pm) return pm.role
|
||||
}
|
||||
|
||||
// Team-scoped members fall back to their team role.
|
||||
if (member.scope === 'team') return member.role
|
||||
|
||||
// Project-scoped members without a matching project record are restricted.
|
||||
return null
|
||||
}
|
||||
|
||||
export class AuthzService {
|
||||
async hasPermission(req: AuthzRequest): Promise<void> {
|
||||
if (!req.user) throw new HTTPException(401, { message: 'User is required' })
|
||||
|
||||
const { teamId, projectId } = await this.resolveContext(req.type, req.id)
|
||||
|
||||
// 1. Check Team Membership
|
||||
// Resolve the user's effective role using the shared precedence rules
|
||||
// (project override -> team role for team-scoped members -> restricted).
|
||||
const role = await resolveEffectiveRole(teamId, projectId, req.user.id)
|
||||
if (role) {
|
||||
try {
|
||||
return this.checkRole(role, req.permission)
|
||||
} catch (err) {
|
||||
// If role check failed (e.g. reviewer requesting Permission.Edit on a KanbanTask where they are assignee/reporter/creator), allow it.
|
||||
if (req.type === ResourceType.KanbanTask && req.permission === Permission.Edit) {
|
||||
const isParticipant = await this.isKanbanTaskParticipant(req.id, req.user.id)
|
||||
if (isParticipant) {
|
||||
return
|
||||
}
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
// No effective role: either not a team member, or a project-scoped member
|
||||
// without access to the resolved project context.
|
||||
const member = await prisma.teamMember.findUnique({
|
||||
where: {
|
||||
teamIdUserId: {
|
||||
@@ -48,40 +119,38 @@ export class AuthzService {
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (!member) throw new HTTPException(403, { message: 'User is not a member of the team' })
|
||||
|
||||
// 2. Check Project Membership first if project context is available
|
||||
if (projectId) {
|
||||
const pm = await prisma.projectMember.findUnique({
|
||||
where: {
|
||||
projectIdTeamMemberId: {
|
||||
projectId: projectId,
|
||||
teamMemberId: member.id,
|
||||
},
|
||||
},
|
||||
})
|
||||
if (pm) {
|
||||
return this.checkRole(pm.role, req.permission)
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Fall back to Team scope checks
|
||||
if (member.scope === 'team') {
|
||||
return this.checkRole(member.role, req.permission)
|
||||
}
|
||||
|
||||
// 4. Scope is Project, and no project-level record exists (or no project context was provided)
|
||||
if (!projectId) {
|
||||
// User has project scope but no project context provided (e.g. Team-level resource)
|
||||
// If it's a team-level resource, project-scoped users can access Read (like ListProjects).
|
||||
// If this is a KanbanTask and user is a team member, check if they are the assignee, reporter, or creator
|
||||
if (req.type === ResourceType.KanbanTask) {
|
||||
if (req.permission === Permission.Read) {
|
||||
return
|
||||
}
|
||||
if (req.permission === Permission.Edit) {
|
||||
const isParticipant = await this.isKanbanTaskParticipant(req.id, req.user.id)
|
||||
if (isParticipant) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Project-scoped member on a team-level resource (no project context):
|
||||
// allow Read (e.g. listing), deny Edit/Admin.
|
||||
if (!projectId && req.permission === Permission.Read) {
|
||||
return
|
||||
}
|
||||
throw new HTTPException(403, { message: 'User has only project scope' })
|
||||
}
|
||||
|
||||
private async isKanbanTaskParticipant(taskId: string, userId: string): Promise<boolean> {
|
||||
const task = await prisma.kanbanTask.findUnique({
|
||||
where: { id: taskId },
|
||||
select: { creatorId: true, reporterId: true, assigneeId: true },
|
||||
})
|
||||
if (!task) return false
|
||||
return task.creatorId === userId || task.reporterId === userId || task.assigneeId === userId
|
||||
}
|
||||
|
||||
private async resolveContext(
|
||||
type: ResourceType,
|
||||
id: string,
|
||||
@@ -226,6 +295,33 @@ export class AuthzService {
|
||||
return { teamId: comment.asset.project.teamId, projectId: comment.asset.projectId! }
|
||||
}
|
||||
|
||||
case ResourceType.QuotaRule: {
|
||||
const rule = await prisma.quotaRule.findUnique({
|
||||
where: { id },
|
||||
select: { teamId: true },
|
||||
})
|
||||
if (!rule) throw new HTTPException(404, { message: 'Quota rule not found' })
|
||||
return { teamId: rule.teamId }
|
||||
}
|
||||
|
||||
case ResourceType.KanbanGoal: {
|
||||
const goal = await prisma.kanbanGoal.findUnique({
|
||||
where: { id },
|
||||
select: { teamId: true },
|
||||
})
|
||||
if (!goal) throw new HTTPException(404, { message: 'Kanban goal not found' })
|
||||
return { teamId: goal.teamId }
|
||||
}
|
||||
|
||||
case ResourceType.KanbanTask: {
|
||||
const task = await prisma.kanbanTask.findUnique({
|
||||
where: { id },
|
||||
select: { teamId: true, projectId: true },
|
||||
})
|
||||
if (!task) throw new HTTPException(404, { message: 'Kanban task not found' })
|
||||
return { teamId: task.teamId, projectId: task.projectId ?? undefined }
|
||||
}
|
||||
|
||||
default:
|
||||
throw new HTTPException(403, { message: `Unsupported resource type: ${type}` })
|
||||
}
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { prisma } from '@shumai/db'
|
||||
import { resolveEffectiveRole } from '@shumai/core/src/authz/authz'
|
||||
|
||||
describe('resolveEffectiveRole', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
async function setupData() {
|
||||
const team = await prisma.team.create({ data: { name: 'Role Team' } })
|
||||
const projectA = await prisma.project.create({
|
||||
data: { name: 'Project A', teamId: team.id },
|
||||
})
|
||||
const projectB = await prisma.project.create({
|
||||
data: { name: 'Project B', teamId: team.id },
|
||||
})
|
||||
|
||||
// Team-scoped owner
|
||||
const owner = await prisma.user.create({ data: { name: 'Owner', email: 'o@x.com' } })
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: owner.id, role: 'owner', scope: 'team' },
|
||||
})
|
||||
|
||||
// Team-scoped reviewer, promoted to project owner in Project A
|
||||
const promoted = await prisma.user.create({ data: { name: 'Promoted', email: 'p@x.com' } })
|
||||
const promotedTm = await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: promoted.id, role: 'reviewer', scope: 'team' },
|
||||
})
|
||||
await prisma.projectMember.create({
|
||||
data: { projectId: projectA.id, teamMemberId: promotedTm.id, role: 'owner' },
|
||||
})
|
||||
|
||||
// Team-scoped editor, demoted to project reviewer in Project A
|
||||
const demoted = await prisma.user.create({ data: { name: 'Demoted', email: 'd@x.com' } })
|
||||
const demotedTm = await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: demoted.id, role: 'editor', scope: 'team' },
|
||||
})
|
||||
await prisma.projectMember.create({
|
||||
data: { projectId: projectA.id, teamMemberId: demotedTm.id, role: 'reviewer' },
|
||||
})
|
||||
|
||||
// Project-scoped member (invited to Project A only, as editor)
|
||||
const guest = await prisma.user.create({ data: { name: 'Guest', email: 'g@x.com' } })
|
||||
const guestTm = await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: guest.id, role: 'reviewer', scope: 'project' },
|
||||
})
|
||||
await prisma.projectMember.create({
|
||||
data: { projectId: projectA.id, teamMemberId: guestTm.id, role: 'editor' },
|
||||
})
|
||||
|
||||
// Non-member
|
||||
const outsider = await prisma.user.create({ data: { name: 'Outsider', email: 'x@x.com' } })
|
||||
|
||||
return { team, projectA, projectB, owner, promoted, demoted, guest, outsider }
|
||||
}
|
||||
|
||||
it('returns the team role for team-scoped members without a project override', async () => {
|
||||
const { team, projectA, owner } = await setupData()
|
||||
await expect(resolveEffectiveRole(team.id, projectA.id, owner.id)).resolves.toBe('owner')
|
||||
await expect(resolveEffectiveRole(team.id, undefined, owner.id)).resolves.toBe('owner')
|
||||
})
|
||||
|
||||
it('prefers the project override over the team role', async () => {
|
||||
const { team, projectA, projectB, promoted, demoted } = await setupData()
|
||||
|
||||
// Promoted: team reviewer -> project owner
|
||||
await expect(resolveEffectiveRole(team.id, projectA.id, promoted.id)).resolves.toBe('owner')
|
||||
// Outside the overridden project, the team role applies
|
||||
await expect(resolveEffectiveRole(team.id, projectB.id, promoted.id)).resolves.toBe('reviewer')
|
||||
|
||||
// Demoted: team editor -> project reviewer
|
||||
await expect(resolveEffectiveRole(team.id, projectA.id, demoted.id)).resolves.toBe('reviewer')
|
||||
await expect(resolveEffectiveRole(team.id, projectB.id, demoted.id)).resolves.toBe('editor')
|
||||
})
|
||||
|
||||
it('resolves the project role for project-scoped members inside their project', async () => {
|
||||
const { team, projectA, guest } = await setupData()
|
||||
await expect(resolveEffectiveRole(team.id, projectA.id, guest.id)).resolves.toBe('editor')
|
||||
})
|
||||
|
||||
it('restricts project-scoped members without a matching project record', async () => {
|
||||
const { team, projectB, guest } = await setupData()
|
||||
await expect(resolveEffectiveRole(team.id, projectB.id, guest.id)).resolves.toBeNull()
|
||||
await expect(resolveEffectiveRole(team.id, undefined, guest.id)).resolves.toBeNull()
|
||||
})
|
||||
|
||||
it('returns null for non-members', async () => {
|
||||
const { team, projectA, outsider } = await setupData()
|
||||
await expect(resolveEffectiveRole(team.id, projectA.id, outsider.id)).resolves.toBeNull()
|
||||
await expect(resolveEffectiveRole(team.id, undefined, outsider.id)).resolves.toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -255,6 +255,61 @@ describe('ChatService', () => {
|
||||
expect(taskPayload?.agent?.imageUrls).toContain('doc_s3_key')
|
||||
})
|
||||
|
||||
it('should enforce agent permissions in startOrContinueChat', async () => {
|
||||
const { team, project } = await setupBasicData()
|
||||
|
||||
// Create an owner-only agent
|
||||
const ownerAgentUser = await prisma.user.create({
|
||||
data: {
|
||||
name: 'Owner Agent User',
|
||||
email: `owner-agent-${Date.now()}@shumai.ai`,
|
||||
type: 'agent',
|
||||
},
|
||||
})
|
||||
const ownerAgent = await prisma.agent.create({
|
||||
data: {
|
||||
id: ownerAgentUser.id,
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
permission: 'owner',
|
||||
config: { provider: 'p', model: 'm' },
|
||||
},
|
||||
})
|
||||
|
||||
// Create an editor user and a reviewer user
|
||||
const editorUser = await prisma.user.create({
|
||||
data: { name: 'Editor User', email: `ed-${Date.now()}@shumai.ai`, password: 'pw' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: editorUser.id, role: 'editor' },
|
||||
})
|
||||
|
||||
const reviewerUser = await prisma.user.create({
|
||||
data: { name: 'Reviewer User', email: `rev-${Date.now()}@shumai.ai`, password: 'pw' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: reviewerUser.id, role: 'reviewer' },
|
||||
})
|
||||
|
||||
// Editor trying to chat with owner-only agent should fail
|
||||
await expect(
|
||||
chatService.startOrContinueChat(editorUser, team.id, {
|
||||
agentId: ownerAgent.id,
|
||||
textPrompt: 'test',
|
||||
projectId: project.id,
|
||||
}),
|
||||
).rejects.toThrow('Permission denied')
|
||||
|
||||
// Reviewer trying to chat with owner-only agent should fail
|
||||
await expect(
|
||||
chatService.startOrContinueChat(reviewerUser, team.id, {
|
||||
agentId: ownerAgent.id,
|
||||
textPrompt: 'test',
|
||||
projectId: project.id,
|
||||
}),
|
||||
).rejects.toThrow('Permission denied')
|
||||
})
|
||||
|
||||
it('should list sessions of a user and only return chat type sessions', async () => {
|
||||
const { user, team, project } = await setupBasicData()
|
||||
|
||||
@@ -688,6 +743,9 @@ describe('ChatService', () => {
|
||||
const otherUser = await prisma.user.create({
|
||||
data: { name: 'Other User', email: `other-${Date.now()}@example.com`, password: 'pw' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: otherUser.id, role: 'reviewer' },
|
||||
})
|
||||
const { sessionId } = await chatService.startOrContinueChat(otherUser, team.id, {
|
||||
agentId: 'test-agent-id',
|
||||
textPrompt: 'hello',
|
||||
@@ -718,4 +776,129 @@ describe('ChatService', () => {
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('project-aware agent permission checks', () => {
|
||||
async function setupProjectRoles() {
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
name: 'Team Roles',
|
||||
settings: { transcode: { videoStrategy: 'best_match' }, chatbotAgentId: 'test-agent-id' },
|
||||
sandbox: { create: {} },
|
||||
},
|
||||
})
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Proj Roles', teamId: team.id },
|
||||
})
|
||||
const rootFolder = await prisma.asset.create({
|
||||
data: { name: 'root', type: 'root', status: 'processed', projectId: project.id },
|
||||
})
|
||||
await prisma.project.update({
|
||||
where: { id: project.id },
|
||||
data: { rootFolderId: rootFolder.id },
|
||||
})
|
||||
|
||||
const createAgent = async (name: string, permission: 'owner' | 'editor' | 'reviewer') => {
|
||||
const agentUser = await prisma.user.create({
|
||||
data: { name, email: `${name}-${Date.now()}@shumai.ai`, type: 'agent' },
|
||||
})
|
||||
return prisma.agent.create({
|
||||
data: {
|
||||
id: agentUser.id,
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
permission,
|
||||
config: { provider: 'openai', model: 'gpt-4' },
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const editorAgent = await createAgent('Editor Agent', 'editor')
|
||||
const ownerAgent = await createAgent('Owner Agent', 'owner')
|
||||
|
||||
// Team editor demoted to project reviewer
|
||||
const demoted = await prisma.user.create({
|
||||
data: { name: 'Demoted', email: `dem-${Date.now()}@x.com`, password: 'pw' },
|
||||
})
|
||||
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' },
|
||||
})
|
||||
|
||||
// Project-scoped member invited as editor
|
||||
const projEditor = await prisma.user.create({
|
||||
data: { name: 'Proj Editor', email: `pe-${Date.now()}@x.com`, password: 'pw' },
|
||||
})
|
||||
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' },
|
||||
})
|
||||
|
||||
// Team reviewer promoted to project owner
|
||||
const promoted = await prisma.user.create({
|
||||
data: { name: 'Promoted', email: `pro-${Date.now()}@x.com`, password: 'pw' },
|
||||
})
|
||||
const promotedTm = await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: promoted.id, role: 'reviewer', scope: 'team' },
|
||||
})
|
||||
await prisma.projectMember.create({
|
||||
data: { projectId: project.id, teamMemberId: promotedTm.id, role: 'owner' },
|
||||
})
|
||||
|
||||
// Plain team reviewer (no project override)
|
||||
const reviewer = await prisma.user.create({
|
||||
data: { name: 'Reviewer', email: `rev-${Date.now()}@x.com`, password: 'pw' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: reviewer.id, role: 'reviewer', scope: 'team' },
|
||||
})
|
||||
|
||||
return { team, project, editorAgent, ownerAgent, demoted, projEditor, promoted, reviewer }
|
||||
}
|
||||
|
||||
it('denies an editor agent to a team editor demoted to project reviewer', async () => {
|
||||
const { team, project, editorAgent, demoted } = await setupProjectRoles()
|
||||
await expect(
|
||||
chatService.startOrContinueChat(demoted, team.id, {
|
||||
agentId: editorAgent.id,
|
||||
textPrompt: 'hello',
|
||||
projectId: project.id,
|
||||
}),
|
||||
).rejects.toThrow(/Insufficient role/)
|
||||
})
|
||||
|
||||
it('allows an editor agent to a project-scoped member invited as editor', async () => {
|
||||
const { team, project, editorAgent, projEditor } = await setupProjectRoles()
|
||||
const { sessionId } = await chatService.startOrContinueChat(projEditor, team.id, {
|
||||
agentId: editorAgent.id,
|
||||
textPrompt: 'hello',
|
||||
projectId: project.id,
|
||||
})
|
||||
expect(sessionId).toBeDefined()
|
||||
})
|
||||
|
||||
it('allows an owner agent to a team reviewer promoted to project owner', async () => {
|
||||
const { team, project, ownerAgent, promoted } = await setupProjectRoles()
|
||||
const { sessionId } = await chatService.startOrContinueChat(promoted, team.id, {
|
||||
agentId: ownerAgent.id,
|
||||
textPrompt: 'hello',
|
||||
projectId: project.id,
|
||||
})
|
||||
expect(sessionId).toBeDefined()
|
||||
})
|
||||
|
||||
it('denies an editor agent to a plain team reviewer', async () => {
|
||||
const { team, project, editorAgent, reviewer } = await setupProjectRoles()
|
||||
await expect(
|
||||
chatService.startOrContinueChat(reviewer, team.id, {
|
||||
agentId: editorAgent.id,
|
||||
textPrompt: 'hello',
|
||||
projectId: project.id,
|
||||
}),
|
||||
).rejects.toThrow(/Insufficient role/)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,11 +1,17 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import {
|
||||
authzService,
|
||||
Permission,
|
||||
ResourceType,
|
||||
resolveEffectiveRole,
|
||||
} from '@shumai/core/src/authz/authz'
|
||||
import { paginateQuery, type PaginatedData } from '@shumai/core/src/pagination'
|
||||
import type { ChatRequest, ChatSessionInfo, ChatMessage } from '@shumai/dtos'
|
||||
import type { SessionTreeEntry } from '@earendil-works/pi-agent-core'
|
||||
import { workflowService } from '@shumai/workflow-core'
|
||||
import { agentService } from '@shumai/core/src/agent/agent'
|
||||
import { getAgentRequiredLevel, getRoleLevel } from '@shumai/core/src/agent/permissions'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
@@ -281,7 +287,10 @@ export class ChatService {
|
||||
let activeSessionId = passedSessionId
|
||||
|
||||
// Ensure AI agent configuration exists
|
||||
const agent = await tx.agent.findUnique({ where: { id: agentId } })
|
||||
const agent = await tx.agent.findUnique({
|
||||
where: { id: agentId },
|
||||
include: { user: true },
|
||||
})
|
||||
if (!agent) {
|
||||
throw new Error(`Agent with ID "${agentId}" not found`)
|
||||
}
|
||||
@@ -289,6 +298,36 @@ export class ChatService {
|
||||
throw new Error(`Agent does not belong to the specified team`)
|
||||
}
|
||||
|
||||
// Check user's permission to use this agent, resolving the effective
|
||||
// role for the project context (projectMember.role takes precedence over
|
||||
// the team role; project-scoped members without project access are denied).
|
||||
const member = await tx.teamMember.findUnique({
|
||||
where: {
|
||||
teamIdUserId: {
|
||||
teamId,
|
||||
userId: user.id,
|
||||
},
|
||||
},
|
||||
})
|
||||
if (!member) {
|
||||
throw new Error('User is not a member of the team')
|
||||
}
|
||||
|
||||
const effectiveRole = await resolveEffectiveRole(teamId, projectId, user.id, tx)
|
||||
if (!effectiveRole) {
|
||||
throw new Error(
|
||||
`Permission denied: Insufficient role to use agent "${agent.user.name}". Minimum required role is "${agent.permission}".`,
|
||||
)
|
||||
}
|
||||
|
||||
const userLevel = getRoleLevel(effectiveRole)
|
||||
const requiredLevel = getAgentRequiredLevel(agent.permission)
|
||||
if (userLevel < requiredLevel) {
|
||||
throw new Error(
|
||||
`Permission denied: Insufficient role to use agent "${agent.user.name}". Minimum required role is "${agent.permission}".`,
|
||||
)
|
||||
}
|
||||
|
||||
if (activeSessionId) {
|
||||
const sessionExists = await tx.agentSession.findUnique({
|
||||
where: { id: activeSessionId },
|
||||
|
||||
@@ -26,3 +26,5 @@ export * from './ai-usage/ai-usage'
|
||||
export * from './watermark/watermark'
|
||||
export * from './gotenberg/gotenberg'
|
||||
export * from './mcp/mcp-service'
|
||||
export * from './quota/quota-service'
|
||||
export * from './kanban/kanban'
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -536,6 +536,109 @@ describe('McpService', () => {
|
||||
expect(allowed.ok).toBe(true)
|
||||
})
|
||||
|
||||
it('uses the effective project role for MCP permission checks', async () => {
|
||||
const server = await service.createServer(teamId, {
|
||||
url: srv.url,
|
||||
permission: 'editor',
|
||||
})
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'MCP Proj', teamId },
|
||||
})
|
||||
|
||||
// Team editor demoted to project reviewer: denied inside the project
|
||||
const demoted = await prisma.user.create({
|
||||
data: { name: 'Demoted MCP', email: `dem-mcp-${Date.now()}@shumai.ai`, type: 'human' },
|
||||
})
|
||||
const demotedTm = await prisma.teamMember.create({
|
||||
data: { teamId, userId: demoted.id, role: 'editor', scope: 'team' },
|
||||
})
|
||||
await prisma.projectMember.create({
|
||||
data: { projectId: project.id, teamMemberId: demotedTm.id, role: 'reviewer' },
|
||||
})
|
||||
|
||||
const denied = await service.callMcpTool(
|
||||
server.id,
|
||||
'echo',
|
||||
{ text: 'x' },
|
||||
{ teamId, userId: demoted.id, projectId: project.id },
|
||||
)
|
||||
expect(denied.ok).toBe(false)
|
||||
expect((denied.content[0] as { text?: string }).text).toContain('Permission denied')
|
||||
|
||||
// Project-scoped member invited as editor: allowed
|
||||
const projEditor = await prisma.user.create({
|
||||
data: { name: 'PE MCP', email: `pe-mcp-${Date.now()}@shumai.ai`, type: 'human' },
|
||||
})
|
||||
const peTm = await prisma.teamMember.create({
|
||||
data: { teamId, userId: projEditor.id, role: 'reviewer', scope: 'project' },
|
||||
})
|
||||
await prisma.projectMember.create({
|
||||
data: { projectId: project.id, teamMemberId: peTm.id, role: 'editor' },
|
||||
})
|
||||
|
||||
const allowed = await service.callMcpTool(
|
||||
server.id,
|
||||
'echo',
|
||||
{ text: 'ok' },
|
||||
{ teamId, userId: projEditor.id, projectId: project.id },
|
||||
)
|
||||
expect(allowed.ok).toBe(true)
|
||||
})
|
||||
|
||||
it('filters assigned MCP servers by the user effective role when building agent tools', async () => {
|
||||
const agent = await seedAgentAndUser(teamId, 'Filtered MCP Agent')
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'MCP Filter Proj', teamId },
|
||||
})
|
||||
|
||||
const reviewerSrv = await startTestMcpServer({
|
||||
tools: standardTestTools(),
|
||||
serverInfo: { name: 'reviewer-only-mcp' },
|
||||
})
|
||||
const editorSrv = await startTestMcpServer({
|
||||
tools: standardTestTools(),
|
||||
serverInfo: { name: 'editor-only-mcp' },
|
||||
})
|
||||
const reviewerServer = await service.createServer(teamId, {
|
||||
url: reviewerSrv.url,
|
||||
permission: 'reviewer',
|
||||
})
|
||||
const editorServer = await service.createServer(teamId, {
|
||||
url: editorSrv.url,
|
||||
permission: 'editor',
|
||||
})
|
||||
await service.refreshServer(reviewerServer.id)
|
||||
await service.refreshServer(editorServer.id)
|
||||
await prisma.agentMcpServer.create({
|
||||
data: { agentId: agent.id, mcpServerId: reviewerServer.id },
|
||||
})
|
||||
await prisma.agentMcpServer.create({
|
||||
data: { agentId: agent.id, mcpServerId: editorServer.id },
|
||||
})
|
||||
|
||||
// Project-scoped member invited as reviewer: only the reviewer server's
|
||||
// tools are attached; the editor server's tools are not even registered.
|
||||
const reviewer = await prisma.user.create({
|
||||
data: { name: 'Filter Reviewer', email: `fr-${Date.now()}@shumai.ai`, type: 'human' },
|
||||
})
|
||||
const reviewerTm = await prisma.teamMember.create({
|
||||
data: { teamId, userId: reviewer.id, role: 'reviewer', scope: 'project' },
|
||||
})
|
||||
await prisma.projectMember.create({
|
||||
data: { projectId: project.id, teamMemberId: reviewerTm.id, role: 'reviewer' },
|
||||
})
|
||||
|
||||
const tools = await service.buildAgentTools(agent.id, teamId, reviewer.id, project.id)
|
||||
const descriptions = tools
|
||||
.map((t) => (t.description ?? '') + (t.name === 'mcp' ? JSON.stringify(t.parameters) : ''))
|
||||
.join('\n')
|
||||
expect(descriptions).toContain('reviewer-only-mcp')
|
||||
expect(descriptions).not.toContain('editor-only-mcp')
|
||||
|
||||
await reviewerSrv.stop()
|
||||
await editorSrv.stop()
|
||||
})
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Per-agent assignment (D6)
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
import { auth } from '@modelcontextprotocol/client'
|
||||
import type { AgentTool, AgentToolResult } from '@earendil-works/pi-agent-core'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { prisma, type TeamMemberRole } from '@shumai/db'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import type {
|
||||
CreateMcpServerRequest,
|
||||
@@ -13,6 +13,8 @@ import type {
|
||||
UpdateMcpServerRequest,
|
||||
} from '@shumai/dtos'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { resolveEffectiveRole } from '@shumai/core/src/authz/authz'
|
||||
import { quotaService } from '@shumai/core/src/quota/quota-service'
|
||||
import { mcpDbStore, type PendingAuth } from './mcp-db-store'
|
||||
import { buildDirectTools, isDirectTool } from './mcp-direct-tools'
|
||||
import { McpOauthProvider, type McpOauthConfig } from './mcp-oauth-provider'
|
||||
@@ -34,6 +36,7 @@ const ROLE_HIERARCHY: Record<string, number> = {
|
||||
export interface McpToolCallContext {
|
||||
teamId: string
|
||||
userId?: string
|
||||
projectId?: string
|
||||
}
|
||||
|
||||
export type McpToolCallContent = AgentToolResult<Record<string, unknown>>['content']
|
||||
@@ -468,16 +471,10 @@ export class McpService {
|
||||
const requiredLevel = ROLE_HIERARCHY[server.permission] || 1
|
||||
|
||||
if (ctx?.userId) {
|
||||
const member = await prisma.teamMember.findUnique({
|
||||
where: {
|
||||
teamIdUserId: {
|
||||
teamId: server.teamId,
|
||||
userId: ctx.userId,
|
||||
},
|
||||
},
|
||||
select: { role: true },
|
||||
})
|
||||
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 effectiveRole = await resolveEffectiveRole(server.teamId, ctx.projectId, ctx.userId)
|
||||
const userLevel = effectiveRole ? ROLE_HIERARCHY[effectiveRole] || 0 : 0
|
||||
if (userLevel < requiredLevel) {
|
||||
return `Permission denied: Insufficient role to use MCP server "${server.name}". Minimum required role is "${server.permission}".`
|
||||
}
|
||||
@@ -533,6 +530,32 @@ export class McpService {
|
||||
return { ok: false, content: [{ type: 'text', text: denied }] }
|
||||
}
|
||||
|
||||
let role: TeamMemberRole | null | undefined = undefined
|
||||
if (ctx?.teamId && ctx?.userId) {
|
||||
role = await resolveEffectiveRole(ctx.teamId, ctx.projectId, ctx.userId)
|
||||
}
|
||||
|
||||
if (ctx?.teamId) {
|
||||
try {
|
||||
await quotaService.checkQuota(
|
||||
{
|
||||
teamId: ctx.teamId,
|
||||
userId: ctx.userId,
|
||||
role,
|
||||
resource: 'agent_mcp_call_count',
|
||||
resourceData: { id: serverId, mcpServerId: serverId },
|
||||
},
|
||||
1,
|
||||
)
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
return {
|
||||
ok: false,
|
||||
content: [{ type: 'text', text: `Quota exceeded: ${message}` }],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const outcome = await this.ensureConnected(serverId)
|
||||
if (outcome.status === 'needs-auth') {
|
||||
return {
|
||||
@@ -559,6 +582,24 @@ export class McpService {
|
||||
|
||||
try {
|
||||
const result = await this.manager.callTool(serverId, toolName, args)
|
||||
|
||||
if (ctx?.teamId) {
|
||||
try {
|
||||
await quotaService.consumeQuota(
|
||||
{
|
||||
teamId: ctx.teamId,
|
||||
userId: ctx.userId,
|
||||
role,
|
||||
resource: 'agent_mcp_call_count',
|
||||
resourceData: { id: serverId, mcpServerId: serverId },
|
||||
},
|
||||
1,
|
||||
)
|
||||
} catch (err) {
|
||||
logger.error({ err }, 'Failed to record quota usage for MCP tool call')
|
||||
}
|
||||
}
|
||||
|
||||
if (result.isError) {
|
||||
const text = result.content.map((c) => ('text' in c ? c.text : '[image]')).join('\n')
|
||||
return {
|
||||
@@ -791,47 +832,65 @@ export class McpService {
|
||||
* Build the agent's MCP AgentTools: the single `mcp` proxy tool plus direct
|
||||
* tools for assigned servers in direct-tools mode. Returns [] when the agent
|
||||
* has no assigned servers (no proxy tool — don't waste LLM context).
|
||||
*
|
||||
* When a user context is provided, servers whose `permission` exceeds the
|
||||
* user's effective project role are filtered out up front, so the model never
|
||||
* sees tools it is not allowed to call (call-time checks remain as a backstop).
|
||||
*/
|
||||
async buildAgentTools(agentId: string, teamId: string, userId?: string): Promise<AgentTool[]> {
|
||||
async buildAgentTools(
|
||||
agentId: string,
|
||||
teamId: string,
|
||||
userId?: string,
|
||||
projectId?: string,
|
||||
): Promise<AgentTool[]> {
|
||||
const assignments = await prisma.agentMcpServer.findMany({
|
||||
where: { agentId },
|
||||
include: { mcpServer: true },
|
||||
})
|
||||
if (assignments.length === 0) return []
|
||||
|
||||
let assignedServers = assignments.map((a) => a.mcpServer)
|
||||
if (userId) {
|
||||
const effectiveRole = await resolveEffectiveRole(teamId, projectId, userId)
|
||||
if (!effectiveRole) return []
|
||||
const userLevel = ROLE_HIERARCHY[effectiveRole] || 0
|
||||
assignedServers = assignedServers.filter(
|
||||
(s) => (ROLE_HIERARCHY[s.permission] || 1) <= userLevel,
|
||||
)
|
||||
}
|
||||
if (assignedServers.length === 0) return []
|
||||
|
||||
// Per-agent tool registry: built fresh for this agent from the persisted
|
||||
// discovery cache (McpServer.tools). It only ever contains the agent's
|
||||
// assigned servers, so unassigned/disabled servers can neither be searched
|
||||
// nor called — no global mutable state to leak through.
|
||||
const registry = new McpToolRegistry()
|
||||
|
||||
const servers = assignments
|
||||
.map((a) => a.mcpServer)
|
||||
.map((s) => {
|
||||
const storedTools = (s.tools ?? []) as PrismaJson.McpToolInfo[]
|
||||
if (storedTools.length > 0) {
|
||||
registry.setTools(
|
||||
s.id,
|
||||
s.name,
|
||||
storedTools.map((t) => ({
|
||||
name: t.name,
|
||||
description: t.description ?? '',
|
||||
...(t.inputSchema !== undefined ? { inputSchema: t.inputSchema } : {}),
|
||||
})),
|
||||
{ excludeTools: s.config?.excludeTools },
|
||||
)
|
||||
}
|
||||
return {
|
||||
id: s.id,
|
||||
name: s.name,
|
||||
instructions: s.instructions ?? null,
|
||||
url: s.url,
|
||||
transport: s.transport,
|
||||
authConfig: (s.authConfig ?? {}) as PrismaJson.McpServerAuthConfig,
|
||||
config: (s.config ?? {}) as PrismaJson.McpServerConfig,
|
||||
status: s.status,
|
||||
}
|
||||
})
|
||||
const servers = assignedServers.map((s) => {
|
||||
const storedTools = (s.tools ?? []) as PrismaJson.McpToolInfo[]
|
||||
if (storedTools.length > 0) {
|
||||
registry.setTools(
|
||||
s.id,
|
||||
s.name,
|
||||
storedTools.map((t) => ({
|
||||
name: t.name,
|
||||
description: t.description ?? '',
|
||||
...(t.inputSchema !== undefined ? { inputSchema: t.inputSchema } : {}),
|
||||
})),
|
||||
{ excludeTools: s.config?.excludeTools },
|
||||
)
|
||||
}
|
||||
return {
|
||||
id: s.id,
|
||||
name: s.name,
|
||||
instructions: s.instructions ?? null,
|
||||
url: s.url,
|
||||
transport: s.transport,
|
||||
authConfig: (s.authConfig ?? {}) as PrismaJson.McpServerAuthConfig,
|
||||
config: (s.config ?? {}) as PrismaJson.McpServerConfig,
|
||||
status: s.status,
|
||||
}
|
||||
})
|
||||
|
||||
const serverNameById = new Map<string, string>()
|
||||
const serverIdByName = new Map<string, string>()
|
||||
@@ -880,7 +939,7 @@ export class McpService {
|
||||
},
|
||||
ensureConnected: (serverId) => this.ensureConnected(serverId, registry),
|
||||
callTool: (serverId, toolName, args) =>
|
||||
this.callMcpTool(serverId, toolName, args, { teamId, userId }),
|
||||
this.callMcpTool(serverId, toolName, args, { teamId, userId, projectId }),
|
||||
authStatus: (serverId) => this.getAuthStatus(serverId),
|
||||
startAuth: (serverId) => this.startAuth(serverId),
|
||||
getInstructions: (serverId) => this.getServerInstructions(serverId),
|
||||
@@ -898,7 +957,7 @@ export class McpService {
|
||||
serverId: server.id,
|
||||
serverName: server.name,
|
||||
callTool: (serverId, toolName, args) =>
|
||||
this.callMcpTool(serverId, toolName, args, { teamId, userId }),
|
||||
this.callMcpTool(serverId, toolName, args, { teamId, userId, projectId }),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -419,7 +419,14 @@ describe('NotificationService', () => {
|
||||
const info = await svc['toNotificationInfo'](
|
||||
await prisma.notification.findUniqueOrThrow({
|
||||
where: { id: n.id },
|
||||
include: { creator: true, team: true, project: true, asset: true, user: true },
|
||||
include: {
|
||||
creator: true,
|
||||
team: true,
|
||||
project: true,
|
||||
asset: true,
|
||||
user: true,
|
||||
kanbanTask: true,
|
||||
},
|
||||
}),
|
||||
null,
|
||||
)
|
||||
@@ -430,4 +437,103 @@ describe('NotificationService', () => {
|
||||
expect(info.asset?.originalWidth).toBe(1280)
|
||||
expect(info.asset?.originalHeight).toBe(720)
|
||||
})
|
||||
|
||||
it('notifyKanbanTaskEvent broadcasts to stakeholders excluding actor and parses mentions', async () => {
|
||||
const tm = await prisma.team.create({ data: { name: 'Team Kanban' } })
|
||||
const u1 = await prisma.user.create({
|
||||
data: { name: 'Actor', email: `actor-${Date.now()}@example.com`, password: 'p' },
|
||||
})
|
||||
const u2 = await prisma.user.create({
|
||||
data: { name: 'Assignee', email: `assignee-${Date.now()}@example.com`, password: 'p' },
|
||||
})
|
||||
const u3 = await prisma.user.create({
|
||||
data: { name: 'Mentioned', email: `mentioned-${Date.now()}@example.com`, password: 'p' },
|
||||
})
|
||||
const task = await prisma.kanbanTask.create({
|
||||
data: {
|
||||
teamId: tm.id,
|
||||
creatorId: u1.id,
|
||||
title: 'Important task',
|
||||
},
|
||||
})
|
||||
|
||||
const svc = notificationService
|
||||
await svc.notifyKanbanTaskEvent({
|
||||
type: NotificationType.kanban_task_comment_created,
|
||||
teamId: tm.id,
|
||||
creatorId: u1.id,
|
||||
kanbanTaskId: task.id,
|
||||
stakeholderIds: [u1.id, u2.id],
|
||||
commentMessage: `Hey <@${u3.id}> please check this`,
|
||||
})
|
||||
|
||||
const notifications = await prisma.notification.findMany({
|
||||
where: { kanbanTaskId: task.id },
|
||||
orderBy: { id: 'asc' },
|
||||
})
|
||||
|
||||
// u1 is actor, should not get notification.
|
||||
// u2 is stakeholder, gets kanban_task_comment_created.
|
||||
// u3 is mentioned, gets mention.
|
||||
expect(notifications).toHaveLength(2)
|
||||
|
||||
const commentNotif = notifications.find(
|
||||
(n) => n.type === NotificationType.kanban_task_comment_created,
|
||||
)
|
||||
expect(commentNotif?.userId).toBe(u2.id)
|
||||
|
||||
const mentionNotif = notifications.find((n) => n.type === NotificationType.mention)
|
||||
expect(mentionNotif?.userId).toBe(u3.id)
|
||||
})
|
||||
|
||||
it('filters kanban notifications based on user preferences', async () => {
|
||||
const tm = await prisma.team.create({ data: { name: 'Team Settings' } })
|
||||
const u1 = await prisma.user.create({
|
||||
data: { name: 'U1', email: `u1-set-${Date.now()}@example.com`, password: 'p' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: tm.id, userId: u1.id, role: 'owner' },
|
||||
})
|
||||
const task = await prisma.kanbanTask.create({
|
||||
data: { teamId: tm.id, creatorId: u1.id, title: 'Task' },
|
||||
})
|
||||
|
||||
await prisma.notification.create({
|
||||
data: {
|
||||
teamId: tm.id,
|
||||
type: NotificationType.kanban_task_created,
|
||||
userId: u1.id,
|
||||
kanbanTaskId: task.id,
|
||||
},
|
||||
})
|
||||
await prisma.notification.create({
|
||||
data: {
|
||||
teamId: tm.id,
|
||||
type: NotificationType.kanban_task_comment_created,
|
||||
userId: u1.id,
|
||||
kanbanTaskId: task.id,
|
||||
},
|
||||
})
|
||||
|
||||
const svc = notificationService
|
||||
// By default both are enabled
|
||||
const listDefault = await svc.list(tm.id, u1.id, {})
|
||||
expect(listDefault.data).toHaveLength(2)
|
||||
|
||||
// Disable kanbanTasks
|
||||
await userMetadataService.upsertMetadata(u1.id, tm.id, 'notification_settings', {
|
||||
comments: true,
|
||||
replies: true,
|
||||
mentions: true,
|
||||
yourUploads: false,
|
||||
otherUploads: true,
|
||||
statusUpdates: true,
|
||||
kanbanTasks: false,
|
||||
kanbanComments: true,
|
||||
})
|
||||
|
||||
const listWithoutTasks = await svc.list(tm.id, u1.id, {})
|
||||
expect(listWithoutTasks.data).toHaveLength(1)
|
||||
expect(listWithoutTasks.data[0].type).toBe(NotificationType.kanban_task_comment_created)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -15,6 +15,74 @@ import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadat
|
||||
const mentionRegex = /<@([^>]+)>/g
|
||||
|
||||
export class NotificationService {
|
||||
async notifyKanbanTaskEvent(params: {
|
||||
type: NotificationType
|
||||
teamId: string
|
||||
projectId?: string | null
|
||||
creatorId: string
|
||||
kanbanTaskId?: string
|
||||
stakeholderIds?: (string | null | undefined)[]
|
||||
targetUserId?: string
|
||||
commentMessage?: string
|
||||
}) {
|
||||
const recipients = new Set<string>()
|
||||
if (params.targetUserId) {
|
||||
recipients.add(params.targetUserId)
|
||||
}
|
||||
if (params.stakeholderIds) {
|
||||
for (const id of params.stakeholderIds) {
|
||||
if (id) recipients.add(id)
|
||||
}
|
||||
}
|
||||
recipients.delete(params.creatorId)
|
||||
|
||||
const promises: Promise<void>[] = []
|
||||
for (const recipientId of recipients) {
|
||||
promises.push(
|
||||
this.createAsync({
|
||||
type: params.type,
|
||||
teamId: params.teamId,
|
||||
projectId: params.projectId ?? undefined,
|
||||
creatorId: params.creatorId,
|
||||
kanbanTaskId: params.kanbanTaskId,
|
||||
userId: recipientId,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
if (params.commentMessage) {
|
||||
const matches = [...params.commentMessage.matchAll(mentionRegex)]
|
||||
const mentionedIds = new Set<string>()
|
||||
|
||||
for (const match of matches) {
|
||||
if (match.length > 1) {
|
||||
const userId = match[1]
|
||||
if (mentionedIds.has(userId)) {
|
||||
continue
|
||||
}
|
||||
mentionedIds.add(userId)
|
||||
|
||||
if (params.creatorId === userId) {
|
||||
continue
|
||||
}
|
||||
|
||||
promises.push(
|
||||
this.createAsync({
|
||||
type: NotificationType.mention,
|
||||
teamId: params.teamId,
|
||||
projectId: params.projectId ?? undefined,
|
||||
creatorId: params.creatorId,
|
||||
kanbanTaskId: params.kanbanTaskId,
|
||||
userId: userId,
|
||||
}),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.all(promises)
|
||||
}
|
||||
|
||||
async create(req: CreateNotificationRequest) {
|
||||
// Note: Do not await this, we fire and forget similarly to Go
|
||||
this.createAsync(req).catch((err) => {
|
||||
@@ -36,6 +104,16 @@ export class NotificationService {
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve ProjectID from KanbanTaskId if missing
|
||||
if (!projectId && req.kanbanTaskId) {
|
||||
const task = await prisma.kanbanTask.findUnique({
|
||||
where: { id: req.kanbanTaskId },
|
||||
})
|
||||
if (task?.projectId) {
|
||||
projectId = task.projectId
|
||||
}
|
||||
}
|
||||
|
||||
// Check project notification settings
|
||||
if (projectId) {
|
||||
const project = await prisma.project.findUnique({
|
||||
@@ -57,6 +135,7 @@ export class NotificationService {
|
||||
creatorId: req.creatorId,
|
||||
assetId: req.assetId,
|
||||
taskId: req.taskId,
|
||||
kanbanTaskId: req.kanbanTaskId,
|
||||
userId: targetUserId,
|
||||
},
|
||||
})
|
||||
@@ -71,7 +150,8 @@ export class NotificationService {
|
||||
// 2. Handle Mentions for Comment/Reply types
|
||||
if (
|
||||
(req.type === NotificationType.comment_created ||
|
||||
req.type === NotificationType.reply_created) &&
|
||||
req.type === NotificationType.reply_created ||
|
||||
req.type === NotificationType.kanban_task_comment_created) &&
|
||||
req.commentMessage
|
||||
) {
|
||||
const matches = [...req.commentMessage.matchAll(mentionRegex)]
|
||||
@@ -128,23 +208,25 @@ export class NotificationService {
|
||||
yourUploads: false,
|
||||
otherUploads: true,
|
||||
statusUpdates: true,
|
||||
kanbanTasks: true,
|
||||
kanbanComments: true,
|
||||
}
|
||||
|
||||
const typeConditions: Prisma.NotificationWhereInput[] = []
|
||||
|
||||
// 1. Comments
|
||||
if (settings.comments) {
|
||||
if (settings.comments ?? true) {
|
||||
typeConditions.push({ type: NotificationType.comment_created, userId: null })
|
||||
}
|
||||
|
||||
// 2. Replies
|
||||
if (settings.replies) {
|
||||
if (settings.replies ?? true) {
|
||||
typeConditions.push({ type: NotificationType.reply_created, userId: userId })
|
||||
typeConditions.push({ type: NotificationType.reply_created, userId: null })
|
||||
}
|
||||
|
||||
// 3. Mentions
|
||||
if (settings.mentions) {
|
||||
if (settings.mentions ?? true) {
|
||||
typeConditions.push({ type: NotificationType.mention, userId: userId })
|
||||
}
|
||||
|
||||
@@ -161,11 +243,35 @@ export class NotificationService {
|
||||
}
|
||||
|
||||
// 5. Status Updates
|
||||
if (settings.statusUpdates) {
|
||||
if (settings.statusUpdates ?? true) {
|
||||
typeConditions.push({ type: NotificationType.metadata_field_updated_status })
|
||||
}
|
||||
|
||||
// 6. Always include team/project join notifications
|
||||
// 6. Kanban Tasks
|
||||
if (settings.kanbanTasks ?? true) {
|
||||
typeConditions.push({
|
||||
type: {
|
||||
in: [
|
||||
NotificationType.kanban_task_created,
|
||||
NotificationType.kanban_task_assigned,
|
||||
NotificationType.kanban_task_status_updated,
|
||||
NotificationType.kanban_task_updated,
|
||||
NotificationType.kanban_task_deleted,
|
||||
],
|
||||
},
|
||||
userId: userId,
|
||||
})
|
||||
}
|
||||
|
||||
// 7. Kanban Comments
|
||||
if (settings.kanbanComments ?? true) {
|
||||
typeConditions.push({
|
||||
type: NotificationType.kanban_task_comment_created,
|
||||
userId: userId,
|
||||
})
|
||||
}
|
||||
|
||||
// 8. Always include team/project join notifications
|
||||
typeConditions.push({ type: NotificationType.new_user_join_team })
|
||||
typeConditions.push({ type: NotificationType.new_user_join_project })
|
||||
|
||||
@@ -193,6 +299,7 @@ export class NotificationService {
|
||||
{
|
||||
OR: [
|
||||
{ type: NotificationType.mention }, // Always allow mentions (targeted)
|
||||
{ userId: userId }, // Direct targeted notifications (e.g. assigned, stakeholder)
|
||||
{ projectId: { in: projectFilter } }, // Only show notifications for projects user is member of
|
||||
],
|
||||
},
|
||||
@@ -270,6 +377,7 @@ export class NotificationService {
|
||||
project: true,
|
||||
asset: true,
|
||||
user: true,
|
||||
kanbanTask: true,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -329,7 +437,14 @@ export class NotificationService {
|
||||
|
||||
private async toNotificationInfo(
|
||||
n: Prisma.NotificationGetPayload<{
|
||||
include: { creator: true; team: true; project: true; asset: true; user: true }
|
||||
include: {
|
||||
creator: true
|
||||
team: true
|
||||
project: true
|
||||
asset: true
|
||||
user: true
|
||||
kanbanTask: true
|
||||
}
|
||||
}>,
|
||||
lastRead: Prisma.NotificationGetPayload<Record<string, never>> | null,
|
||||
): Promise<NotificationInfo> {
|
||||
@@ -368,6 +483,14 @@ export class NotificationService {
|
||||
}
|
||||
}
|
||||
|
||||
if (n.kanbanTask) {
|
||||
info.kanbanTask = {
|
||||
id: n.kanbanTask.id,
|
||||
title: n.kanbanTask.title,
|
||||
status: n.kanbanTask.status,
|
||||
}
|
||||
}
|
||||
|
||||
if (n.asset) {
|
||||
const a = n.asset
|
||||
let previewUrl = ''
|
||||
|
||||
@@ -194,6 +194,57 @@ describe('ProjectService', () => {
|
||||
includeAgents: true,
|
||||
})
|
||||
expect(allMembers).toHaveLength(2)
|
||||
const agentMember = allMembers.find((m) => m.id === bot.id)
|
||||
const humanMember = allMembers.find((m) => m.id === human.id)
|
||||
expect(agentMember?.type).toBe('agent')
|
||||
expect(humanMember?.type).toBe('human')
|
||||
})
|
||||
|
||||
it('filters agent bots by the requester effective project role', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Team Bot Filter' } })
|
||||
const project = await prisma.project.create({ data: { name: 'P2', teamId: team.id } })
|
||||
|
||||
const createChatAgent = async (name: string, permission: 'owner' | 'editor' | 'reviewer') => {
|
||||
const bot = await prisma.user.create({
|
||||
data: { name, email: `${name}-${Date.now()}@example.com`, password: 'pw', type: 'agent' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: bot.id, role: 'editor', scope: 'team' },
|
||||
})
|
||||
await prisma.agent.create({
|
||||
data: {
|
||||
id: bot.id,
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
permission,
|
||||
config: { provider: 'google', model: 'gemini' },
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
await createChatAgent('Reviewer Bot', 'reviewer')
|
||||
await createChatAgent('Editor Bot', 'editor')
|
||||
|
||||
// Project-scoped requester invited as reviewer: sees only reviewer bots
|
||||
const requester = await prisma.user.create({
|
||||
data: { name: 'Req', email: `req-${Date.now()}@example.com`, password: 'pw' },
|
||||
})
|
||||
const requesterTm = await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: requester.id, role: 'reviewer', scope: 'project' },
|
||||
})
|
||||
await prisma.projectMember.create({
|
||||
data: { projectId: project.id, teamMemberId: requesterTm.id, role: 'reviewer' },
|
||||
})
|
||||
|
||||
const members = await projectService.listProjectMembers({
|
||||
projectId: project.id,
|
||||
includeAgents: true,
|
||||
requesterUserId: requester.id,
|
||||
})
|
||||
const agentNames = members.filter((m) => m.id !== requester.id).map((m) => m.name)
|
||||
expect(agentNames).toContain('Reviewer Bot')
|
||||
expect(agentNames).not.toContain('Editor Bot')
|
||||
})
|
||||
|
||||
it('should allow upserting custom role override for team-scoped members via updateMemberRole', async () => {
|
||||
|
||||
@@ -3,6 +3,8 @@ import { Prisma } from '@shumai/db'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { paginateQuery, PaginatedData } from '@shumai/core/src/pagination'
|
||||
import { getAvatarUrl } from '@shumai/core/src/user/avatar'
|
||||
import { getAllowedAgentRoles } from '@shumai/core/src/agent/permissions'
|
||||
import { resolveEffectiveRole } from '@shumai/core/src/authz/authz'
|
||||
import {
|
||||
ServiceCreateProjectRequest,
|
||||
ServiceUpdateProjectRequest,
|
||||
@@ -226,17 +228,35 @@ export class ProjectService {
|
||||
})
|
||||
if (!project) throw new Error('Project not found')
|
||||
|
||||
// When agents are requested, only include the chat agents the requester's
|
||||
// effective project role permits (project override wins; restricted
|
||||
// requesters see no agents at all). Without a requester context, fall back
|
||||
// to including all enabled chat agents (legacy behavior).
|
||||
let agentFilter: Prisma.AgentWhereInput | undefined
|
||||
if (req.includeAgents) {
|
||||
if (req.requesterUserId) {
|
||||
const effectiveRole = await resolveEffectiveRole(
|
||||
project.teamId,
|
||||
req.projectId,
|
||||
req.requesterUserId,
|
||||
)
|
||||
if (effectiveRole) {
|
||||
agentFilter = {
|
||||
type: 'chat' as const,
|
||||
enabled: true,
|
||||
permission: { in: getAllowedAgentRoles(effectiveRole) },
|
||||
}
|
||||
}
|
||||
} else {
|
||||
agentFilter = { type: 'chat' as const, enabled: true }
|
||||
}
|
||||
}
|
||||
|
||||
const userTypeFilter = req.includeAgents
|
||||
? {
|
||||
OR: [
|
||||
{ type: 'human' as const },
|
||||
{
|
||||
type: 'agent' as const,
|
||||
agent: {
|
||||
type: 'chat' as const,
|
||||
enabled: true,
|
||||
},
|
||||
},
|
||||
...(agentFilter ? [{ type: 'agent' as const, agent: agentFilter }] : []),
|
||||
],
|
||||
}
|
||||
: { type: { not: 'agent' as const } }
|
||||
@@ -301,6 +321,7 @@ export class ProjectService {
|
||||
id: m.user.id,
|
||||
name: m.user.name,
|
||||
role: m.role as ProjectUserInfo['role'],
|
||||
type: m.user.type || undefined,
|
||||
image: await getAvatarUrl(m.user.image),
|
||||
scope: m.scope,
|
||||
hasCustomRole: m.hasCustomRole,
|
||||
|
||||
@@ -0,0 +1,972 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { quotaService, QuotaExceededError, wildcardToRegex } from './quota-service'
|
||||
|
||||
describe('QuotaRule Wildcard Matchers', () => {
|
||||
it('correctly matches bash command wildcards', () => {
|
||||
const starRegex = wildcardToRegex('*')
|
||||
expect(starRegex.test('npm install')).toBe(true)
|
||||
expect(starRegex.test('git commit -m "test"')).toBe(true)
|
||||
|
||||
const npmRegex = wildcardToRegex('npm *')
|
||||
expect(npmRegex.test('npm install')).toBe(true)
|
||||
expect(npmRegex.test('npm test')).toBe(true)
|
||||
expect(npmRegex.test('git push')).toBe(false)
|
||||
|
||||
const exactRegex = wildcardToRegex('rm -rf .pi')
|
||||
expect(exactRegex.test('rm -rf .pi')).toBe(true)
|
||||
expect(exactRegex.test('rm -rf /')).toBe(false)
|
||||
})
|
||||
|
||||
it('correctly matches agent tool name wildcards', () => {
|
||||
const starTool = wildcardToRegex('*')
|
||||
expect(starTool.test('analyze_image')).toBe(true)
|
||||
expect(starTool.test('screenshot')).toBe(true)
|
||||
|
||||
const exactTool = wildcardToRegex('analyze_image')
|
||||
expect(exactTool.test('analyze_image')).toBe(true)
|
||||
expect(exactTool.test('screenshot')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('QuotaService', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
it('creates, reads, updates, and deletes quota rules', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Quota Team' },
|
||||
})
|
||||
|
||||
// Create rule
|
||||
const rule = await quotaService.createRule(team.id, {
|
||||
scopeMode: 'all_members',
|
||||
resource: 'agent_total_tokens',
|
||||
limit: 100000,
|
||||
period: '1hour',
|
||||
enabled: true,
|
||||
})
|
||||
|
||||
expect(rule.id).toBeDefined()
|
||||
expect(rule.teamId).toBe(team.id)
|
||||
expect(rule.scopeMode).toBe('all_members')
|
||||
expect(rule.limit).toBe(100000)
|
||||
expect(rule.period).toBe('1hour')
|
||||
|
||||
// Get rule
|
||||
const fetched = await quotaService.getRule(team.id, rule.id)
|
||||
expect(fetched.id).toBe(rule.id)
|
||||
expect(fetched.limit).toBe(100000)
|
||||
|
||||
// List rules
|
||||
const list = await quotaService.listRules(team.id)
|
||||
expect(list.total).toBe(1)
|
||||
expect(list.rules[0].id).toBe(rule.id)
|
||||
|
||||
// Update rule
|
||||
const updated = await quotaService.updateRule(team.id, rule.id, {
|
||||
limit: 200000,
|
||||
enabled: false,
|
||||
})
|
||||
expect(updated.limit).toBe(200000)
|
||||
expect(updated.enabled).toBe(false)
|
||||
|
||||
// Delete rule
|
||||
await quotaService.deleteRule(team.id, rule.id)
|
||||
const afterDelete = await quotaService.listRules(team.id)
|
||||
expect(afterDelete.total).toBe(0)
|
||||
})
|
||||
|
||||
it('validates selected members on rule creation', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Quota Team' },
|
||||
})
|
||||
|
||||
// Missing user should throw 400
|
||||
await expect(
|
||||
quotaService.createRule(team.id, {
|
||||
scopeMode: 'selected_members',
|
||||
userIds: ['non-existent-user-id'],
|
||||
resource: 'agent_cost',
|
||||
limit: 10,
|
||||
period: '1day',
|
||||
}),
|
||||
).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('uses the latest database rule state for every quota check', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Fresh Quota Rule Team' },
|
||||
})
|
||||
|
||||
const rule = await quotaService.createRule(team.id, {
|
||||
scopeMode: 'all_members',
|
||||
resource: 'agent_cost',
|
||||
limit: 10,
|
||||
period: '1hour',
|
||||
})
|
||||
|
||||
const event = {
|
||||
teamId: team.id,
|
||||
resource: 'agent_cost' as const,
|
||||
}
|
||||
|
||||
expect((await quotaService.checkQuota(event)).matchedRules).toHaveLength(1)
|
||||
|
||||
await prisma.quotaRule.update({
|
||||
where: { id: rule.id },
|
||||
data: { enabled: false },
|
||||
})
|
||||
|
||||
expect((await quotaService.checkQuota(event)).matchedRules).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('enforces check and consumes quota for all_members (shared pool)', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Shared Quota Team' },
|
||||
})
|
||||
|
||||
await quotaService.createRule(team.id, {
|
||||
scopeMode: 'all_members',
|
||||
resource: 'agent_total_tokens',
|
||||
limit: 1000,
|
||||
period: '1hour',
|
||||
enabled: true,
|
||||
})
|
||||
|
||||
// Check with 0 before consumption
|
||||
const checkResult = await quotaService.checkQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
resource: 'agent_total_tokens',
|
||||
},
|
||||
0,
|
||||
)
|
||||
expect(checkResult.allowed).toBe(true)
|
||||
|
||||
// Consume 600 tokens
|
||||
await quotaService.consumeQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
resource: 'agent_total_tokens',
|
||||
},
|
||||
600,
|
||||
)
|
||||
|
||||
// Check with 300 tokens (600 + 300 = 900 <= 1000) -> allowed
|
||||
await expect(
|
||||
quotaService.checkQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
resource: 'agent_total_tokens',
|
||||
},
|
||||
300,
|
||||
),
|
||||
).resolves.toEqual(expect.objectContaining({ allowed: true }))
|
||||
|
||||
// Check with 500 tokens (600 + 500 = 1100 > 1000) -> throws QuotaExceededError
|
||||
await expect(
|
||||
quotaService.checkQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
resource: 'agent_total_tokens',
|
||||
},
|
||||
500,
|
||||
),
|
||||
).rejects.toThrow(QuotaExceededError)
|
||||
|
||||
// Consume another 400 tokens -> exactly 1000 consumed
|
||||
await quotaService.consumeQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
resource: 'agent_total_tokens',
|
||||
},
|
||||
400,
|
||||
)
|
||||
|
||||
// Now even checkQuota with 1 token should fail
|
||||
await expect(
|
||||
quotaService.checkQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
resource: 'agent_total_tokens',
|
||||
},
|
||||
1,
|
||||
),
|
||||
).rejects.toThrow(QuotaExceededError)
|
||||
})
|
||||
|
||||
it('enforces each_member scope independently for each member', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Each Member Team' },
|
||||
})
|
||||
|
||||
const userAlice = await prisma.user.create({
|
||||
data: { name: 'Alice', email: 'alice@example.com', password: 'pw' },
|
||||
})
|
||||
|
||||
const userBob = await prisma.user.create({
|
||||
data: { name: 'Bob', email: 'bob@example.com', password: 'pw' },
|
||||
})
|
||||
|
||||
// Create rule: each member with role editor gets 5 MCP calls per 1hour
|
||||
await quotaService.createRule(team.id, {
|
||||
scopeMode: 'each_member',
|
||||
role: 'editor',
|
||||
resource: 'agent_mcp_call_count',
|
||||
resourceData: { id: 'server_1' },
|
||||
limit: 5,
|
||||
period: '1hour',
|
||||
enabled: true,
|
||||
})
|
||||
|
||||
// Alice consumes 5 MCP calls
|
||||
for (let i = 0; i < 5; i++) {
|
||||
await quotaService.consumeQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
userId: userAlice.id,
|
||||
role: 'editor',
|
||||
resource: 'agent_mcp_call_count',
|
||||
resourceData: { id: 'server_1' },
|
||||
},
|
||||
1,
|
||||
)
|
||||
}
|
||||
|
||||
// Alice should be blocked on 6th call
|
||||
await expect(
|
||||
quotaService.checkQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
userId: userAlice.id,
|
||||
role: 'editor',
|
||||
resource: 'agent_mcp_call_count',
|
||||
resourceData: { id: 'server_1' },
|
||||
},
|
||||
1,
|
||||
),
|
||||
).rejects.toThrow(QuotaExceededError)
|
||||
|
||||
// Bob (also an editor) should NOT be blocked (independent tracking)
|
||||
await expect(
|
||||
quotaService.checkQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
userId: userBob.id,
|
||||
role: 'editor',
|
||||
resource: 'agent_mcp_call_count',
|
||||
resourceData: { id: 'server_1' },
|
||||
},
|
||||
1,
|
||||
),
|
||||
).resolves.toEqual(expect.objectContaining({ allowed: true }))
|
||||
|
||||
// Reviewer should not match editor rule
|
||||
const reviewerCheck = await quotaService.checkQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
userId: userBob.id,
|
||||
role: 'reviewer',
|
||||
resource: 'agent_mcp_call_count',
|
||||
resourceData: { id: 'server_1' },
|
||||
},
|
||||
1,
|
||||
)
|
||||
expect(reviewerCheck.matchedRules).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('enforces selected_members scope correctly', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Selected Members Team' },
|
||||
})
|
||||
|
||||
const userSelected = await prisma.user.create({
|
||||
data: { name: 'Selected User', email: 'sel@example.com', password: 'pw' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: userSelected.id, role: 'editor' },
|
||||
})
|
||||
|
||||
const userOther = await prisma.user.create({
|
||||
data: { name: 'Other User', email: 'other@example.com', password: 'pw' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: userOther.id, role: 'editor' },
|
||||
})
|
||||
|
||||
await quotaService.createRule(team.id, {
|
||||
scopeMode: 'selected_members',
|
||||
userIds: [userSelected.id],
|
||||
resource: 'agent_cost',
|
||||
limit: 5,
|
||||
period: '1day',
|
||||
enabled: true,
|
||||
})
|
||||
|
||||
// Selected user consumes 5
|
||||
await quotaService.consumeQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
userId: userSelected.id,
|
||||
resource: 'agent_cost',
|
||||
},
|
||||
5,
|
||||
)
|
||||
|
||||
// Selected user is blocked
|
||||
await expect(
|
||||
quotaService.checkQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
userId: userSelected.id,
|
||||
resource: 'agent_cost',
|
||||
},
|
||||
1,
|
||||
),
|
||||
).rejects.toThrow(QuotaExceededError)
|
||||
|
||||
// Other user does not match the rule -> allowed
|
||||
const otherCheck = await quotaService.checkQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
userId: userOther.id,
|
||||
resource: 'agent_cost',
|
||||
},
|
||||
10,
|
||||
)
|
||||
expect(otherCheck.matchedRules).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('matches bash command wildcard rules', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Bash Quota Team' },
|
||||
})
|
||||
|
||||
await quotaService.createRule(team.id, {
|
||||
scopeMode: 'all_members',
|
||||
resource: 'agent_bash_call_count',
|
||||
resourceData: { match: 'npm *' },
|
||||
limit: 2,
|
||||
period: '1hour',
|
||||
enabled: true,
|
||||
})
|
||||
|
||||
// npm test matches -> consume 1
|
||||
await quotaService.consumeQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
resource: 'agent_bash_call_count',
|
||||
resourceData: { command: 'npm test' },
|
||||
},
|
||||
1,
|
||||
)
|
||||
|
||||
// npm install matches -> consume 1 (total = 2)
|
||||
await quotaService.consumeQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
resource: 'agent_bash_call_count',
|
||||
resourceData: { command: 'npm install' },
|
||||
},
|
||||
1,
|
||||
)
|
||||
|
||||
// 3rd npm command should be blocked
|
||||
await expect(
|
||||
quotaService.checkQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
resource: 'agent_bash_call_count',
|
||||
resourceData: { command: 'npm run build' },
|
||||
},
|
||||
1,
|
||||
),
|
||||
).rejects.toThrow(QuotaExceededError)
|
||||
|
||||
// git command does not match 'npm *' -> allowed
|
||||
await expect(
|
||||
quotaService.checkQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
resource: 'agent_bash_call_count',
|
||||
resourceData: { command: 'git status' },
|
||||
},
|
||||
1,
|
||||
),
|
||||
).resolves.toEqual(expect.objectContaining({ allowed: true }))
|
||||
})
|
||||
|
||||
it('matches agent tool call rules and wildcards', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Tool Quota Team' },
|
||||
})
|
||||
|
||||
await quotaService.createRule(team.id, {
|
||||
scopeMode: 'all_members',
|
||||
resource: 'agent_tool_call_count',
|
||||
resourceData: { name: 'analyze_image' },
|
||||
limit: 1,
|
||||
period: '1hour',
|
||||
enabled: true,
|
||||
})
|
||||
|
||||
// First call to analyze_image
|
||||
await quotaService.consumeQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
resource: 'agent_tool_call_count',
|
||||
resourceData: { name: 'analyze_image' },
|
||||
},
|
||||
1,
|
||||
)
|
||||
|
||||
// 2nd call to analyze_image is blocked
|
||||
await expect(
|
||||
quotaService.checkQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
resource: 'agent_tool_call_count',
|
||||
resourceData: { name: 'analyze_image' },
|
||||
},
|
||||
1,
|
||||
),
|
||||
).rejects.toThrow(QuotaExceededError)
|
||||
|
||||
// Call to create_file does not match -> allowed
|
||||
await expect(
|
||||
quotaService.checkQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
resource: 'agent_tool_call_count',
|
||||
resourceData: { name: 'create_file' },
|
||||
},
|
||||
1,
|
||||
),
|
||||
).resolves.toEqual(expect.objectContaining({ allowed: true }))
|
||||
})
|
||||
|
||||
it('handles period window rollover and resets usage in-place with no history tables', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Window Rollover Team' },
|
||||
})
|
||||
|
||||
const rule = await quotaService.createRule(team.id, {
|
||||
scopeMode: 'all_members',
|
||||
resource: 'agent_cost',
|
||||
limit: 10,
|
||||
period: '1hour',
|
||||
enabled: true,
|
||||
})
|
||||
|
||||
// Simulate an expired period by creating a past QuotaRecord
|
||||
const pastStart = new Date(Date.now() - 2 * 60 * 60 * 1000)
|
||||
const pastEnd = new Date(Date.now() - 1 * 60 * 60 * 1000)
|
||||
|
||||
await prisma.quotaRecord.create({
|
||||
data: {
|
||||
ruleId: rule.id,
|
||||
teamId: team.id,
|
||||
userId: null,
|
||||
periodStart: pastStart,
|
||||
periodEnd: pastEnd,
|
||||
consumed: 10, // fully consumed in past window
|
||||
},
|
||||
})
|
||||
|
||||
// Current check should be ALLOWED because the old window expired
|
||||
await expect(
|
||||
quotaService.checkQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
resource: 'agent_cost',
|
||||
},
|
||||
5,
|
||||
),
|
||||
).resolves.toEqual(expect.objectContaining({ allowed: true }))
|
||||
|
||||
// Consuming now resets the single record in-place
|
||||
await quotaService.consumeQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
resource: 'agent_cost',
|
||||
},
|
||||
5,
|
||||
)
|
||||
|
||||
const records = await prisma.quotaRecord.findMany({
|
||||
where: { ruleId: rule.id },
|
||||
})
|
||||
|
||||
// No extra history records (exactly 1 record row updated in place)
|
||||
expect(records).toHaveLength(1)
|
||||
expect(records[0].consumed).toBe(5)
|
||||
})
|
||||
|
||||
it('lists rule records accurately with lazy reset status', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Records List Team' },
|
||||
})
|
||||
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'Alice Member', email: 'alice.member@example.com', password: 'pw' },
|
||||
})
|
||||
|
||||
await prisma.teamMember.create({
|
||||
data: {
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
role: 'editor',
|
||||
},
|
||||
})
|
||||
|
||||
const rule = await quotaService.createRule(team.id, {
|
||||
scopeMode: 'each_member',
|
||||
resource: 'agent_total_tokens',
|
||||
limit: 50000,
|
||||
period: '1day',
|
||||
enabled: true,
|
||||
})
|
||||
|
||||
// Before any usage: listRuleRecords returns member with consumed: 0, isWindowActive: false
|
||||
const initialRecords = await quotaService.listRuleRecords(team.id, rule.id)
|
||||
expect(initialRecords.total).toBe(1)
|
||||
expect(initialRecords.records[0].userId).toBe(user.id)
|
||||
expect(initialRecords.records[0].consumed).toBe(0)
|
||||
expect(initialRecords.records[0].remaining).toBe(50000)
|
||||
expect(initialRecords.records[0].isWindowActive).toBe(false)
|
||||
|
||||
// Consume 10000 tokens
|
||||
await quotaService.consumeQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
role: 'editor',
|
||||
resource: 'agent_total_tokens',
|
||||
},
|
||||
10000,
|
||||
)
|
||||
|
||||
// After usage: active window with consumed = 10000
|
||||
const activeRecords = await quotaService.listRuleRecords(team.id, rule.id)
|
||||
expect(activeRecords.records[0].consumed).toBe(10000)
|
||||
expect(activeRecords.records[0].remaining).toBe(40000)
|
||||
expect(activeRecords.records[0].isWindowActive).toBe(true)
|
||||
})
|
||||
|
||||
it('resets a shared quota record and starts a fresh window', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Reset Shared Quota Team' },
|
||||
})
|
||||
|
||||
const rule = await quotaService.createRule(team.id, {
|
||||
scopeMode: 'all_members',
|
||||
resource: 'agent_total_tokens',
|
||||
limit: 1000,
|
||||
period: '1hour',
|
||||
})
|
||||
|
||||
await quotaService.consumeQuota({ teamId: team.id, resource: 'agent_total_tokens' }, 500)
|
||||
const beforeReset = await prisma.quotaRecord.findFirst({ where: { ruleId: rule.id } })
|
||||
expect(beforeReset?.consumed).toBe(500)
|
||||
|
||||
const reset = await quotaService.resetRecord(team.id, rule.id, null)
|
||||
expect(reset.userId).toBeNull()
|
||||
expect(reset.consumed).toBe(0)
|
||||
expect(reset.remaining).toBe(1000)
|
||||
expect(reset.percent).toBe(0)
|
||||
expect(reset.isWindowActive).toBe(true)
|
||||
expect(reset.periodStart).toBeDefined()
|
||||
expect(reset.periodEnd).toBeDefined()
|
||||
|
||||
const afterReset = await prisma.quotaRecord.findFirst({ where: { ruleId: rule.id } })
|
||||
expect(afterReset?.consumed).toBe(0)
|
||||
expect(afterReset?.periodStart?.getTime()).toBeGreaterThanOrEqual(
|
||||
beforeReset?.periodStart?.getTime() ?? 0,
|
||||
)
|
||||
})
|
||||
|
||||
it('creates and resets a member quota record before any usage exists', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Reset Member Quota Team' },
|
||||
})
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'Reset Member', email: 'reset-member@example.com', password: 'pw' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: user.id, role: 'editor' },
|
||||
})
|
||||
|
||||
const rule = await quotaService.createRule(team.id, {
|
||||
scopeMode: 'each_member',
|
||||
resource: 'agent_total_tokens',
|
||||
limit: 1000,
|
||||
period: '1day',
|
||||
})
|
||||
|
||||
const reset = await quotaService.resetRecord(team.id, rule.id, user.id)
|
||||
expect(reset.userId).toBe(user.id)
|
||||
expect(reset.consumed).toBe(0)
|
||||
expect(reset.isWindowActive).toBe(true)
|
||||
|
||||
const records = await prisma.quotaRecord.findMany({ where: { ruleId: rule.id } })
|
||||
expect(records).toHaveLength(1)
|
||||
expect(records[0]?.userId).toBe(user.id)
|
||||
expect(records[0]?.consumed).toBe(0)
|
||||
})
|
||||
|
||||
it('rejects reset targets that do not match the quota rule', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Invalid Reset Target Team' },
|
||||
})
|
||||
const editor = await prisma.user.create({
|
||||
data: { name: 'Editor', email: 'invalid-reset-editor@example.com', password: 'pw' },
|
||||
})
|
||||
const reviewer = await prisma.user.create({
|
||||
data: { name: 'Reviewer', email: 'invalid-reset-reviewer@example.com', password: 'pw' },
|
||||
})
|
||||
await prisma.teamMember.createMany({
|
||||
data: [
|
||||
{ teamId: team.id, userId: editor.id, role: 'editor' },
|
||||
{ teamId: team.id, userId: reviewer.id, role: 'reviewer' },
|
||||
],
|
||||
})
|
||||
|
||||
const roleRule = await quotaService.createRule(team.id, {
|
||||
scopeMode: 'each_member',
|
||||
role: 'editor',
|
||||
resource: 'agent_total_tokens',
|
||||
limit: 1000,
|
||||
period: '1hour',
|
||||
})
|
||||
|
||||
await expect(quotaService.resetRecord(team.id, roleRule.id, reviewer.id)).rejects.toThrow(
|
||||
'does not match the rule role',
|
||||
)
|
||||
await expect(quotaService.resetRecord(team.id, roleRule.id, null)).rejects.toThrow(
|
||||
'require a userId',
|
||||
)
|
||||
|
||||
const selectedRule = await quotaService.createRule(team.id, {
|
||||
scopeMode: 'selected_members',
|
||||
userIds: [editor.id],
|
||||
resource: 'agent_total_tokens',
|
||||
limit: 1000,
|
||||
period: '1hour',
|
||||
})
|
||||
await expect(quotaService.resetRecord(team.id, selectedRule.id, reviewer.id)).rejects.toThrow(
|
||||
'not selected by this rule',
|
||||
)
|
||||
})
|
||||
|
||||
it('does not allow resetting a quota rule from another team', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Reset Owner Team' } })
|
||||
const otherTeam = await prisma.team.create({ data: { name: 'Reset Other Team' } })
|
||||
const rule = await quotaService.createRule(team.id, {
|
||||
scopeMode: 'all_members',
|
||||
resource: 'agent_total_tokens',
|
||||
limit: 1000,
|
||||
period: '1hour',
|
||||
})
|
||||
|
||||
await expect(quotaService.resetRecord(otherTeam.id, rule.id, null)).rejects.toThrow(
|
||||
'Quota rule not found',
|
||||
)
|
||||
})
|
||||
|
||||
it('enforces multiple matching rules simultaneously', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Multi Rule Team' },
|
||||
})
|
||||
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'Charlie', email: 'charlie@example.com', password: 'pw' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: user.id, role: 'editor' },
|
||||
})
|
||||
|
||||
// Rule 1: Team overall token limit 10,000 (all_members)
|
||||
await quotaService.createRule(team.id, {
|
||||
scopeMode: 'all_members',
|
||||
resource: 'agent_total_tokens',
|
||||
limit: 10000,
|
||||
period: '1day',
|
||||
enabled: true,
|
||||
})
|
||||
|
||||
// Rule 2: User specific token limit 2,000 (selected_members)
|
||||
await quotaService.createRule(team.id, {
|
||||
scopeMode: 'selected_members',
|
||||
userIds: [user.id],
|
||||
resource: 'agent_total_tokens',
|
||||
limit: 2000,
|
||||
period: '1day',
|
||||
enabled: true,
|
||||
})
|
||||
|
||||
// Consuming 2000 tokens for Charlie
|
||||
await quotaService.consumeQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
resource: 'agent_total_tokens',
|
||||
},
|
||||
2000,
|
||||
)
|
||||
|
||||
// Charlie is blocked by user rule (2000 limit reached)
|
||||
await expect(
|
||||
quotaService.checkQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
resource: 'agent_total_tokens',
|
||||
},
|
||||
100,
|
||||
),
|
||||
).rejects.toThrow(QuotaExceededError)
|
||||
|
||||
// Another user in the same team is NOT blocked by Charlie's limit, only by team limit
|
||||
const userDave = await prisma.user.create({
|
||||
data: { name: 'Dave', email: 'dave@example.com', password: 'pw' },
|
||||
})
|
||||
|
||||
await expect(
|
||||
quotaService.checkQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
userId: userDave.id,
|
||||
resource: 'agent_total_tokens',
|
||||
},
|
||||
1000,
|
||||
),
|
||||
).resolves.toEqual(expect.objectContaining({ allowed: true }))
|
||||
})
|
||||
|
||||
it('rejects selected_members if user is not a member of the team on create', async () => {
|
||||
const team1 = await prisma.team.create({ data: { name: 'Team 1' } })
|
||||
const team2 = await prisma.team.create({ data: { name: 'Team 2' } })
|
||||
|
||||
const userInTeam1 = await prisma.user.create({
|
||||
data: { name: 'Member 1', email: 'm1@example.com', password: 'pw' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team1.id, userId: userInTeam1.id, role: 'editor' },
|
||||
})
|
||||
|
||||
const userInTeam2 = await prisma.user.create({
|
||||
data: { name: 'Member 2', email: 'm2@example.com', password: 'pw' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team2.id, userId: userInTeam2.id, role: 'editor' },
|
||||
})
|
||||
|
||||
// Creating rule on Team 1 with user from Team 2 should throw 400
|
||||
await expect(
|
||||
quotaService.createRule(team1.id, {
|
||||
scopeMode: 'selected_members',
|
||||
userIds: [userInTeam2.id],
|
||||
resource: 'agent_cost',
|
||||
limit: 10,
|
||||
period: '1day',
|
||||
}),
|
||||
).rejects.toThrow('One or more selected users are not members of the team')
|
||||
})
|
||||
|
||||
it('validates merged rule and rejects invalid partial updates', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Validation Team' } })
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'User 1', email: 'u1@example.com', password: 'pw' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: user.id, role: 'editor' },
|
||||
})
|
||||
|
||||
const rule = await quotaService.createRule(team.id, {
|
||||
scopeMode: 'each_member',
|
||||
resource: 'agent_total_tokens',
|
||||
limit: 10000,
|
||||
period: '1hour',
|
||||
})
|
||||
|
||||
// Updating resource to agent_mcp_call_count without resourceData.id should fail validation
|
||||
await expect(
|
||||
quotaService.updateRule(team.id, rule.id, {
|
||||
resource: 'agent_mcp_call_count',
|
||||
}),
|
||||
).rejects.toThrow()
|
||||
|
||||
// Updating scopeMode to selected_members without userIds should fail validation
|
||||
await expect(
|
||||
quotaService.updateRule(team.id, rule.id, {
|
||||
scopeMode: 'selected_members',
|
||||
}),
|
||||
).rejects.toThrow()
|
||||
|
||||
// Updating userIds with a user from outside the team should fail validation
|
||||
const otherUser = await prisma.user.create({
|
||||
data: { name: 'Other User', email: 'other_team@example.com', password: 'pw' },
|
||||
})
|
||||
await expect(
|
||||
quotaService.updateRule(team.id, rule.id, {
|
||||
scopeMode: 'selected_members',
|
||||
userIds: [otherUser.id],
|
||||
}),
|
||||
).rejects.toThrow('One or more selected users are not members of the team')
|
||||
})
|
||||
|
||||
it('resets existing quota records when accounting dimensions change', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Reset Records Team' } })
|
||||
|
||||
const rule = await quotaService.createRule(team.id, {
|
||||
scopeMode: 'all_members',
|
||||
resource: 'agent_total_tokens',
|
||||
limit: 1000,
|
||||
period: '1hour',
|
||||
})
|
||||
|
||||
// Consume 500 tokens
|
||||
await quotaService.consumeQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
resource: 'agent_total_tokens',
|
||||
},
|
||||
500,
|
||||
)
|
||||
|
||||
let records = await prisma.quotaRecord.findMany({ where: { ruleId: rule.id } })
|
||||
expect(records).toHaveLength(1)
|
||||
expect(records[0].consumed).toBe(500)
|
||||
|
||||
// Update resource to agent_cost (limit 10)
|
||||
await quotaService.updateRule(team.id, rule.id, {
|
||||
resource: 'agent_cost',
|
||||
limit: 10,
|
||||
})
|
||||
|
||||
// Records should be reset
|
||||
records = await prisma.quotaRecord.findMany({ where: { ruleId: rule.id } })
|
||||
expect(records).toHaveLength(0)
|
||||
|
||||
// Consume $2 under the new resource
|
||||
await quotaService.consumeQuota(
|
||||
{
|
||||
teamId: team.id,
|
||||
resource: 'agent_cost',
|
||||
},
|
||||
2,
|
||||
)
|
||||
|
||||
records = await prisma.quotaRecord.findMany({ where: { ruleId: rule.id } })
|
||||
expect(records).toHaveLength(1)
|
||||
expect(records[0].consumed).toBe(2)
|
||||
})
|
||||
|
||||
it('handles concurrent first consumption for all_members without creating duplicate records', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Concurrent Quota Team' } })
|
||||
|
||||
const rule = await quotaService.createRule(team.id, {
|
||||
scopeMode: 'all_members',
|
||||
resource: 'agent_total_tokens',
|
||||
limit: 10000,
|
||||
period: '1hour',
|
||||
})
|
||||
|
||||
// Concurrently trigger 5 quota consumption calls for the first time
|
||||
await Promise.all([
|
||||
quotaService.consumeQuota({ teamId: team.id, resource: 'agent_total_tokens' }, 10),
|
||||
quotaService.consumeQuota({ teamId: team.id, resource: 'agent_total_tokens' }, 20),
|
||||
quotaService.consumeQuota({ teamId: team.id, resource: 'agent_total_tokens' }, 30),
|
||||
quotaService.consumeQuota({ teamId: team.id, resource: 'agent_total_tokens' }, 40),
|
||||
quotaService.consumeQuota({ teamId: team.id, resource: 'agent_total_tokens' }, 50),
|
||||
])
|
||||
|
||||
const records = await prisma.quotaRecord.findMany({ where: { ruleId: rule.id } })
|
||||
expect(records).toHaveLength(1)
|
||||
expect(records[0].consumed).toBe(150)
|
||||
})
|
||||
|
||||
it('excludes agents from quota usage records and prevents creating quota rules for agents', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Exclude Agent Team' } })
|
||||
|
||||
// Create human user
|
||||
const humanUser = await prisma.user.create({
|
||||
data: {
|
||||
name: 'Human Member',
|
||||
email: 'human.member@example.com',
|
||||
type: 'human',
|
||||
password: 'pw',
|
||||
},
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: humanUser.id, role: 'reviewer' },
|
||||
})
|
||||
|
||||
// Create agent user and agent
|
||||
const agentUser = await prisma.user.create({
|
||||
data: {
|
||||
name: 'AI Agent Member',
|
||||
email: 'ai.agent@shumai.ai',
|
||||
type: 'agent',
|
||||
},
|
||||
})
|
||||
await prisma.agent.create({
|
||||
data: {
|
||||
id: agentUser.id,
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
config: { provider: 'google', model: 'gemini' },
|
||||
},
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: agentUser.id, role: 'reviewer' },
|
||||
})
|
||||
|
||||
// 1. Quota rule with each_member
|
||||
const eachMemberRule = await quotaService.createRule(team.id, {
|
||||
scopeMode: 'each_member',
|
||||
resource: 'agent_total_tokens',
|
||||
limit: 10000,
|
||||
period: '1hour',
|
||||
enabled: true,
|
||||
})
|
||||
|
||||
// listRuleRecords should ONLY return human members, NOT agents
|
||||
const recordsResult = await quotaService.listRuleRecords(team.id, eachMemberRule.id)
|
||||
expect(recordsResult.total).toBe(1)
|
||||
expect(recordsResult.records).toHaveLength(1)
|
||||
expect(recordsResult.records[0].userId).toBe(humanUser.id)
|
||||
expect(recordsResult.records[0].user?.email).toBe('human.member@example.com')
|
||||
|
||||
// 2. Quota rule with selected_members targeting agentUser should be rejected
|
||||
await expect(
|
||||
quotaService.createRule(team.id, {
|
||||
scopeMode: 'selected_members',
|
||||
userIds: [agentUser.id],
|
||||
resource: 'agent_total_tokens',
|
||||
limit: 5000,
|
||||
period: '1day',
|
||||
}),
|
||||
).rejects.toThrow('One or more selected users are not members of the team')
|
||||
|
||||
// 3. Updating quota rule with selected_members targeting agentUser should be rejected
|
||||
const validSelectedRule = await quotaService.createRule(team.id, {
|
||||
scopeMode: 'selected_members',
|
||||
userIds: [humanUser.id],
|
||||
resource: 'agent_total_tokens',
|
||||
limit: 5000,
|
||||
period: '1day',
|
||||
})
|
||||
|
||||
await expect(
|
||||
quotaService.updateRule(team.id, validSelectedRule.id, {
|
||||
userIds: [agentUser.id],
|
||||
}),
|
||||
).rejects.toThrow('One or more selected users are not members of the team')
|
||||
|
||||
const selectedRecords = await quotaService.listRuleRecords(team.id, validSelectedRule.id)
|
||||
expect(selectedRecords.total).toBe(1)
|
||||
expect(selectedRecords.records[0].userId).toBe(humanUser.id)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,859 @@
|
||||
import {
|
||||
prisma,
|
||||
Prisma,
|
||||
type QuotaPeriod,
|
||||
type QuotaRecord,
|
||||
type QuotaResourceType,
|
||||
type QuotaRule,
|
||||
type TeamMemberRole,
|
||||
} from '@shumai/db'
|
||||
import {
|
||||
type CreateQuotaRuleRequest,
|
||||
type ListQuotaRulesResponse,
|
||||
type QuotaRuleResponse,
|
||||
type ListQuotaRecordsResponse,
|
||||
type QuotaRecordResponse,
|
||||
type UpdateQuotaRuleRequest,
|
||||
normalizeQuotaPeriod,
|
||||
formatQuotaPeriod,
|
||||
mcpResourceDataSchema,
|
||||
bashResourceDataSchema,
|
||||
toolResourceDataSchema,
|
||||
} from '@shumai/dtos'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
|
||||
export class QuotaExceededError extends Error {
|
||||
public readonly policyId: string
|
||||
public readonly resource: string
|
||||
public readonly limit: number
|
||||
public readonly consumed: number
|
||||
public readonly periodEnd: Date
|
||||
|
||||
constructor(params: {
|
||||
policyId: string
|
||||
resource: string
|
||||
limit: number
|
||||
consumed: number
|
||||
periodEnd: Date
|
||||
message?: string
|
||||
}) {
|
||||
const msg =
|
||||
params.message ||
|
||||
`Quota exceeded for ${params.resource}: limit of ${params.limit} reached (currently consumed: ${params.consumed}). Resets at ${params.periodEnd.toISOString()}.`
|
||||
super(msg)
|
||||
this.name = 'QuotaExceededError'
|
||||
this.policyId = params.policyId
|
||||
this.resource = params.resource
|
||||
this.limit = params.limit
|
||||
this.consumed = params.consumed
|
||||
this.periodEnd = params.periodEnd
|
||||
}
|
||||
}
|
||||
|
||||
export interface QuotaEventResourceData {
|
||||
skillId?: string
|
||||
mcpServerId?: string
|
||||
command?: string
|
||||
name?: string
|
||||
toolName?: string
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export interface QuotaEvent {
|
||||
teamId: string
|
||||
userId?: string | null
|
||||
role?: TeamMemberRole | null
|
||||
resource: QuotaResourceType
|
||||
resourceData?: QuotaEventResourceData
|
||||
}
|
||||
|
||||
export function periodToDurationMs(period: QuotaPeriod | string): number {
|
||||
switch (period) {
|
||||
case 'one_hour':
|
||||
case '1hour':
|
||||
return 60 * 60 * 1000
|
||||
case 'five_hours':
|
||||
case '5hour':
|
||||
return 5 * 60 * 60 * 1000
|
||||
case 'one_day':
|
||||
case '1day':
|
||||
return 24 * 60 * 60 * 1000
|
||||
case 'seven_days':
|
||||
case '7day':
|
||||
return 7 * 24 * 60 * 60 * 1000
|
||||
default:
|
||||
return 60 * 60 * 1000
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a wildcard pattern (with * and ?) into a regular expression.
|
||||
*/
|
||||
export function wildcardToRegex(pattern: string): RegExp {
|
||||
const trimmed = pattern.trim()
|
||||
if (trimmed === '*' || trimmed === '') {
|
||||
return /^.*$/s
|
||||
}
|
||||
// Escape regex special chars except * and ?
|
||||
const escaped = trimmed.replace(/[.+^${}()|[\]\\]/g, '\\$&')
|
||||
const regexStr = '^' + escaped.replace(/\*/g, '.*').replace(/\?/g, '.') + '$'
|
||||
return new RegExp(regexStr, 's')
|
||||
}
|
||||
|
||||
function matchesQuotaRule(rule: QuotaRule, event: QuotaEvent): boolean {
|
||||
if (!rule.enabled) return false
|
||||
if (event.teamId !== rule.teamId) return false
|
||||
if (event.resource !== rule.resource) return false
|
||||
|
||||
// Scope check
|
||||
if (rule.scopeMode === 'all_members') {
|
||||
if (rule.role && event.role !== rule.role) return false
|
||||
} else if (rule.scopeMode === 'each_member') {
|
||||
if (!event.userId) return false
|
||||
if (rule.role && event.role !== rule.role) return false
|
||||
} else if (rule.scopeMode === 'selected_members') {
|
||||
if (!event.userId) return false
|
||||
const userIds = Array.isArray(rule.userIds) ? (rule.userIds as string[]) : null
|
||||
if (!userIds || !userIds.includes(event.userId)) return false
|
||||
}
|
||||
|
||||
const resourceData = (rule.resourceData as Record<string, unknown> | null) ?? null
|
||||
|
||||
// Resource data check
|
||||
if (rule.resource === 'agent_mcp_call_count') {
|
||||
const targetId = resourceData?.id ?? resourceData?.mcpServerId
|
||||
const eventMcpId = event.resourceData?.mcpServerId ?? event.resourceData?.id
|
||||
if (targetId && eventMcpId !== targetId) return false
|
||||
} else if (rule.resource === 'agent_bash_call_count' && resourceData?.match) {
|
||||
const bashMatcher = wildcardToRegex(String(resourceData.match))
|
||||
const command = event.resourceData?.command ?? ''
|
||||
if (!bashMatcher.test(command)) return false
|
||||
} else if (
|
||||
rule.resource === 'agent_tool_call_count' &&
|
||||
(resourceData?.name || resourceData?.toolName)
|
||||
) {
|
||||
const toolMatcher = wildcardToRegex(String(resourceData.name ?? resourceData.toolName))
|
||||
const toolName = String(event.resourceData?.name ?? event.resourceData?.toolName ?? '')
|
||||
if (!toolMatcher.test(toolName)) return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
function getQuotaRuleTargetUserId(rule: QuotaRule, event: QuotaEvent): string | null {
|
||||
if (rule.scopeMode === 'all_members') {
|
||||
return null
|
||||
}
|
||||
return event.userId ?? null
|
||||
}
|
||||
|
||||
/* eslint-disable @typescript-eslint/naming-convention */
|
||||
interface RawQuotaRecord {
|
||||
id: string
|
||||
rule_id: string
|
||||
team_id: string
|
||||
user_id: string | null
|
||||
period_start: Date | null
|
||||
period_end: Date | null
|
||||
consumed: number
|
||||
}
|
||||
/* eslint-enable @typescript-eslint/naming-convention */
|
||||
|
||||
export class QuotaService {
|
||||
constructor(private readonly prismaClient: typeof prisma = prisma) {}
|
||||
|
||||
private mapRuleToResponse(rule: QuotaRule, recordsCount?: number): QuotaRuleResponse {
|
||||
const userIds = Array.isArray(rule.userIds) ? (rule.userIds as string[]) : undefined
|
||||
|
||||
return {
|
||||
id: rule.id,
|
||||
teamId: rule.teamId,
|
||||
scopeMode: rule.scopeMode,
|
||||
role: rule.role ?? undefined,
|
||||
userIds,
|
||||
resource: rule.resource,
|
||||
resourceData: (rule.resourceData as Record<string, unknown> | null) ?? undefined,
|
||||
limit: rule.limit,
|
||||
period: formatQuotaPeriod(rule.period) as QuotaRuleResponse['period'],
|
||||
enabled: rule.enabled,
|
||||
recordsCount,
|
||||
createdAt: rule.createdAt.toISOString(),
|
||||
updatedAt: rule.updatedAt.toISOString(),
|
||||
}
|
||||
}
|
||||
|
||||
async createRule(teamId: string, req: CreateQuotaRuleRequest): Promise<QuotaRuleResponse> {
|
||||
if (req.scopeMode === 'selected_members') {
|
||||
if (!req.userIds || req.userIds.length === 0) {
|
||||
throw new HTTPException(400, {
|
||||
message: 'userIds must contain at least one user when scopeMode is "selected_members"',
|
||||
})
|
||||
}
|
||||
const members = await this.prismaClient.teamMember.findMany({
|
||||
where: {
|
||||
teamId,
|
||||
userId: { in: req.userIds },
|
||||
user: { type: 'human' },
|
||||
},
|
||||
select: { userId: true },
|
||||
})
|
||||
if (members.length !== req.userIds.length) {
|
||||
throw new HTTPException(400, {
|
||||
message: 'One or more selected users are not members of the team',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const rule = await this.prismaClient.quotaRule.create({
|
||||
data: {
|
||||
teamId,
|
||||
scopeMode: req.scopeMode,
|
||||
role: req.scopeMode !== 'selected_members' ? (req.role ?? null) : null,
|
||||
userIds:
|
||||
req.scopeMode === 'selected_members' && req.userIds ? req.userIds : Prisma.JsonNull,
|
||||
resource: req.resource,
|
||||
resourceData: req.resourceData ?? Prisma.JsonNull,
|
||||
limit: req.limit,
|
||||
period: normalizeQuotaPeriod(req.period),
|
||||
enabled: req.enabled ?? true,
|
||||
},
|
||||
})
|
||||
|
||||
return this.mapRuleToResponse(rule, 0)
|
||||
}
|
||||
|
||||
async updateRule(
|
||||
teamId: string,
|
||||
ruleId: string,
|
||||
req: UpdateQuotaRuleRequest,
|
||||
): Promise<QuotaRuleResponse> {
|
||||
const existing = await this.prismaClient.quotaRule.findUnique({
|
||||
where: { id: ruleId },
|
||||
})
|
||||
|
||||
if (!existing || existing.teamId !== teamId) {
|
||||
throw new HTTPException(404, { message: 'Quota rule not found' })
|
||||
}
|
||||
|
||||
const effectiveScopeMode = req.scopeMode ?? existing.scopeMode
|
||||
const effectiveRole =
|
||||
effectiveScopeMode === 'selected_members'
|
||||
? null
|
||||
: req.role !== undefined
|
||||
? req.role
|
||||
: existing.role
|
||||
const effectiveUserIds =
|
||||
effectiveScopeMode === 'selected_members'
|
||||
? req.userIds !== undefined
|
||||
? req.userIds
|
||||
: Array.isArray(existing.userIds)
|
||||
? (existing.userIds as string[])
|
||||
: []
|
||||
: null
|
||||
const effectiveResource = req.resource ?? existing.resource
|
||||
const effectiveResourceData =
|
||||
req.resourceData !== undefined
|
||||
? req.resourceData
|
||||
: (existing.resourceData as Record<string, unknown> | null)
|
||||
const effectiveLimit = req.limit ?? existing.limit
|
||||
const effectivePeriod = req.period ? normalizeQuotaPeriod(req.period) : existing.period
|
||||
const effectiveEnabled = req.enabled ?? existing.enabled
|
||||
|
||||
// Validate effective merged state
|
||||
if (effectiveScopeMode === 'selected_members') {
|
||||
if (!effectiveUserIds || effectiveUserIds.length === 0) {
|
||||
throw new HTTPException(400, {
|
||||
message: 'userIds must contain at least one user when scopeMode is "selected_members"',
|
||||
})
|
||||
}
|
||||
const members = await this.prismaClient.teamMember.findMany({
|
||||
where: {
|
||||
teamId,
|
||||
userId: { in: effectiveUserIds },
|
||||
user: { type: 'human' },
|
||||
},
|
||||
select: { userId: true },
|
||||
})
|
||||
if (members.length !== effectiveUserIds.length) {
|
||||
throw new HTTPException(400, {
|
||||
message: 'One or more selected users are not members of the team',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (effectiveResource === 'agent_mcp_call_count') {
|
||||
const res = mcpResourceDataSchema.safeParse(effectiveResourceData)
|
||||
if (!res.success) {
|
||||
throw new HTTPException(400, {
|
||||
message: 'resourceData.id is required for agent_mcp_call_count',
|
||||
})
|
||||
}
|
||||
} else if (effectiveResource === 'agent_bash_call_count') {
|
||||
const res = bashResourceDataSchema.safeParse(effectiveResourceData)
|
||||
if (!res.success) {
|
||||
throw new HTTPException(400, {
|
||||
message: 'resourceData.match is required for agent_bash_call_count',
|
||||
})
|
||||
}
|
||||
} else if (effectiveResource === 'agent_tool_call_count') {
|
||||
const res = toolResourceDataSchema.safeParse(effectiveResourceData)
|
||||
if (!res.success) {
|
||||
throw new HTTPException(400, {
|
||||
message: 'resourceData.name is required for agent_tool_call_count',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (effectiveLimit <= 0) {
|
||||
throw new HTTPException(400, {
|
||||
message: 'Limit must be greater than 0',
|
||||
})
|
||||
}
|
||||
|
||||
const isAccountingDimensionChanged =
|
||||
(req.resource !== undefined && req.resource !== existing.resource) ||
|
||||
(req.period !== undefined && normalizeQuotaPeriod(req.period) !== existing.period) ||
|
||||
(req.scopeMode !== undefined && req.scopeMode !== existing.scopeMode) ||
|
||||
(req.role !== undefined && req.role !== existing.role) ||
|
||||
(req.resourceData !== undefined &&
|
||||
JSON.stringify(req.resourceData) !== JSON.stringify(existing.resourceData))
|
||||
|
||||
const updated = await this.prismaClient.$transaction(async (tx) => {
|
||||
if (isAccountingDimensionChanged) {
|
||||
// Reset all records when accounting dimensions change
|
||||
await tx.quotaRecord.deleteMany({
|
||||
where: { ruleId },
|
||||
})
|
||||
} else if (effectiveScopeMode === 'selected_members' && req.userIds !== undefined) {
|
||||
// Clean up records for removed users if updating userIds
|
||||
if (req.userIds && req.userIds.length > 0) {
|
||||
await tx.quotaRecord.deleteMany({
|
||||
where: {
|
||||
ruleId,
|
||||
userId: { notIn: req.userIds },
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const data: Prisma.QuotaRuleUpdateInput = {
|
||||
scopeMode: effectiveScopeMode,
|
||||
role: effectiveRole,
|
||||
userIds:
|
||||
effectiveScopeMode === 'selected_members' && effectiveUserIds
|
||||
? effectiveUserIds
|
||||
: Prisma.JsonNull,
|
||||
resource: effectiveResource,
|
||||
resourceData: effectiveResourceData ?? Prisma.JsonNull,
|
||||
limit: effectiveLimit,
|
||||
period: effectivePeriod,
|
||||
enabled: effectiveEnabled,
|
||||
}
|
||||
|
||||
return tx.quotaRule.update({
|
||||
where: { id: ruleId },
|
||||
data,
|
||||
})
|
||||
})
|
||||
|
||||
const recordsCount = await this.prismaClient.quotaRecord.count({
|
||||
where: { ruleId },
|
||||
})
|
||||
|
||||
return this.mapRuleToResponse(updated, recordsCount)
|
||||
}
|
||||
|
||||
async deleteRule(teamId: string, ruleId: string): Promise<void> {
|
||||
const existing = await this.prismaClient.quotaRule.findUnique({
|
||||
where: { id: ruleId },
|
||||
})
|
||||
|
||||
if (!existing || existing.teamId !== teamId) {
|
||||
throw new HTTPException(404, { message: 'Quota rule not found' })
|
||||
}
|
||||
|
||||
await this.prismaClient.quotaRule.delete({
|
||||
where: { id: ruleId },
|
||||
})
|
||||
}
|
||||
|
||||
async getRule(teamId: string, ruleId: string): Promise<QuotaRuleResponse> {
|
||||
const rule = await this.prismaClient.quotaRule.findUnique({
|
||||
where: { id: ruleId },
|
||||
})
|
||||
|
||||
if (!rule || rule.teamId !== teamId) {
|
||||
throw new HTTPException(404, { message: 'Quota rule not found' })
|
||||
}
|
||||
|
||||
const recordsCount = await this.prismaClient.quotaRecord.count({
|
||||
where: { ruleId },
|
||||
})
|
||||
|
||||
return this.mapRuleToResponse(rule, recordsCount)
|
||||
}
|
||||
|
||||
async listRules(teamId: string): Promise<ListQuotaRulesResponse> {
|
||||
const rules = await this.prismaClient.quotaRule.findMany({
|
||||
where: { teamId },
|
||||
orderBy: { id: 'desc' },
|
||||
})
|
||||
|
||||
const ruleResponses = await Promise.all(
|
||||
rules.map(async (rule) => {
|
||||
const recordsCount = await this.prismaClient.quotaRecord.count({
|
||||
where: { ruleId: rule.id },
|
||||
})
|
||||
return this.mapRuleToResponse(rule, recordsCount)
|
||||
}),
|
||||
)
|
||||
|
||||
return {
|
||||
rules: ruleResponses,
|
||||
total: ruleResponses.length,
|
||||
}
|
||||
}
|
||||
|
||||
async listRuleRecords(teamId: string, ruleId: string): Promise<ListQuotaRecordsResponse> {
|
||||
const rule = await this.prismaClient.quotaRule.findUnique({
|
||||
where: { id: ruleId },
|
||||
})
|
||||
|
||||
if (!rule || rule.teamId !== teamId) {
|
||||
throw new HTTPException(404, { message: 'Quota rule not found' })
|
||||
}
|
||||
|
||||
const now = new Date()
|
||||
|
||||
if (rule.scopeMode === 'all_members') {
|
||||
const record = await this.prismaClient.quotaRecord.findFirst({
|
||||
where: { ruleId: rule.id, userId: null },
|
||||
})
|
||||
|
||||
const isWindowActive = Boolean(
|
||||
record?.periodStart &&
|
||||
record?.periodEnd &&
|
||||
now >= record.periodStart &&
|
||||
now < record.periodEnd,
|
||||
)
|
||||
|
||||
const consumed = isWindowActive ? (record?.consumed ?? 0) : 0
|
||||
const remaining = Math.max(0, rule.limit - consumed)
|
||||
const percent =
|
||||
rule.limit > 0 ? Math.min(100, Number(((consumed / rule.limit) * 100).toFixed(2))) : 0
|
||||
|
||||
const res: QuotaRecordResponse = {
|
||||
id: record?.id ?? null,
|
||||
ruleId: rule.id,
|
||||
teamId: rule.teamId,
|
||||
userId: null,
|
||||
user: null,
|
||||
periodStart:
|
||||
isWindowActive && record?.periodStart ? record.periodStart.toISOString() : null,
|
||||
periodEnd: isWindowActive && record?.periodEnd ? record.periodEnd.toISOString() : null,
|
||||
consumed,
|
||||
remaining,
|
||||
percent,
|
||||
isWindowActive,
|
||||
}
|
||||
|
||||
return {
|
||||
records: [res],
|
||||
total: 1,
|
||||
}
|
||||
}
|
||||
|
||||
// For each_member or selected_members
|
||||
type MemberTarget = { id: string; name: string; email: string; image?: string | null }
|
||||
let targetUsers: MemberTarget[] = []
|
||||
|
||||
if (rule.scopeMode === 'selected_members') {
|
||||
const userIds = Array.isArray(rule.userIds) ? (rule.userIds as string[]) : []
|
||||
if (userIds.length > 0) {
|
||||
targetUsers = await this.prismaClient.user.findMany({
|
||||
where: { id: { in: userIds }, type: 'human' },
|
||||
select: { id: true, name: true, email: true, image: true },
|
||||
})
|
||||
}
|
||||
} else {
|
||||
// each_member
|
||||
const memberWhere: Prisma.TeamMemberWhereInput = {
|
||||
teamId,
|
||||
user: { type: 'human' },
|
||||
}
|
||||
if (rule.role) {
|
||||
memberWhere.role = rule.role
|
||||
}
|
||||
const members = await this.prismaClient.teamMember.findMany({
|
||||
where: memberWhere,
|
||||
include: {
|
||||
user: {
|
||||
select: { id: true, name: true, email: true, image: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
targetUsers = members.map((m) => m.user)
|
||||
}
|
||||
|
||||
const existingRecords = await this.prismaClient.quotaRecord.findMany({
|
||||
where: {
|
||||
ruleId: rule.id,
|
||||
userId: { in: targetUsers.map((u) => u.id) },
|
||||
},
|
||||
})
|
||||
|
||||
const recordByUserId = new Map<string, QuotaRecord>()
|
||||
for (const r of existingRecords) {
|
||||
if (r.userId) recordByUserId.set(r.userId, r)
|
||||
}
|
||||
|
||||
const records: QuotaRecordResponse[] = targetUsers.map((user) => {
|
||||
const record = recordByUserId.get(user.id)
|
||||
const isWindowActive = Boolean(
|
||||
record?.periodStart &&
|
||||
record?.periodEnd &&
|
||||
now >= record.periodStart &&
|
||||
now < record.periodEnd,
|
||||
)
|
||||
|
||||
const consumed = isWindowActive ? (record?.consumed ?? 0) : 0
|
||||
const remaining = Math.max(0, rule.limit - consumed)
|
||||
const percent =
|
||||
rule.limit > 0 ? Math.min(100, Number(((consumed / rule.limit) * 100).toFixed(2))) : 0
|
||||
|
||||
return {
|
||||
id: record?.id ?? null,
|
||||
ruleId: rule.id,
|
||||
teamId: rule.teamId,
|
||||
userId: user.id,
|
||||
user: {
|
||||
id: user.id,
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
image: user.image ?? null,
|
||||
},
|
||||
periodStart:
|
||||
isWindowActive && record?.periodStart ? record.periodStart.toISOString() : null,
|
||||
periodEnd: isWindowActive && record?.periodEnd ? record.periodEnd.toISOString() : null,
|
||||
consumed,
|
||||
remaining,
|
||||
percent,
|
||||
isWindowActive,
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
records,
|
||||
total: records.length,
|
||||
}
|
||||
}
|
||||
|
||||
async resetRecord(
|
||||
teamId: string,
|
||||
ruleId: string,
|
||||
userId: string | null,
|
||||
): Promise<QuotaRecordResponse> {
|
||||
const rule = await this.prismaClient.quotaRule.findUnique({
|
||||
where: { id: ruleId },
|
||||
})
|
||||
|
||||
if (!rule || rule.teamId !== teamId) {
|
||||
throw new HTTPException(404, { message: 'Quota rule not found' })
|
||||
}
|
||||
|
||||
if (rule.scopeMode === 'all_members' && userId !== null) {
|
||||
throw new HTTPException(400, {
|
||||
message: 'All-members quota records must use a null userId',
|
||||
})
|
||||
}
|
||||
|
||||
if (rule.scopeMode !== 'all_members' && userId === null) {
|
||||
throw new HTTPException(400, {
|
||||
message: 'Member quota records require a userId',
|
||||
})
|
||||
}
|
||||
|
||||
if (userId !== null) {
|
||||
const member = await this.prismaClient.teamMember.findUnique({
|
||||
where: {
|
||||
teamIdUserId: {
|
||||
teamId,
|
||||
userId,
|
||||
},
|
||||
},
|
||||
select: {
|
||||
role: true,
|
||||
user: {
|
||||
select: { type: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (!member || member.user.type !== 'human') {
|
||||
throw new HTTPException(400, {
|
||||
message: 'Quota record user must be a human team member',
|
||||
})
|
||||
}
|
||||
|
||||
if (rule.scopeMode === 'each_member' && rule.role && member.role !== rule.role) {
|
||||
throw new HTTPException(400, {
|
||||
message: 'Quota record user does not match the rule role',
|
||||
})
|
||||
}
|
||||
|
||||
if (rule.scopeMode === 'selected_members') {
|
||||
const userIds = Array.isArray(rule.userIds) ? (rule.userIds as string[]) : []
|
||||
if (!userIds.includes(userId)) {
|
||||
throw new HTTPException(400, {
|
||||
message: 'Quota record user is not selected by this rule',
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await this.prismaClient.$transaction(async (tx) => {
|
||||
// Lock the rule row so reset and first-use record creation are serialized.
|
||||
await tx.$queryRaw`SELECT id FROM quota_rules WHERE id = ${rule.id} FOR UPDATE`
|
||||
|
||||
const periodStart = new Date()
|
||||
const periodEnd = new Date(periodStart.getTime() + periodToDurationMs(rule.period))
|
||||
|
||||
const existingRecord = userId
|
||||
? (
|
||||
await tx.$queryRaw<RawQuotaRecord[]>`
|
||||
SELECT * FROM quota_records
|
||||
WHERE rule_id = ${rule.id} AND user_id = ${userId}
|
||||
FOR UPDATE
|
||||
`
|
||||
)[0]
|
||||
: (
|
||||
await tx.$queryRaw<RawQuotaRecord[]>`
|
||||
SELECT * FROM quota_records
|
||||
WHERE rule_id = ${rule.id} AND user_id IS NULL
|
||||
FOR UPDATE
|
||||
`
|
||||
)[0]
|
||||
|
||||
if (existingRecord) {
|
||||
await tx.quotaRecord.update({
|
||||
where: { id: existingRecord.id },
|
||||
data: {
|
||||
periodStart,
|
||||
periodEnd,
|
||||
consumed: 0,
|
||||
},
|
||||
})
|
||||
} else {
|
||||
await tx.quotaRecord.create({
|
||||
data: {
|
||||
ruleId: rule.id,
|
||||
teamId: rule.teamId,
|
||||
userId,
|
||||
periodStart,
|
||||
periodEnd,
|
||||
consumed: 0,
|
||||
},
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
const records = await this.listRuleRecords(teamId, ruleId)
|
||||
const mappedRecord = records.records.find((record) => record.userId === userId)
|
||||
|
||||
if (!mappedRecord) {
|
||||
throw new HTTPException(404, { message: 'Quota record not found' })
|
||||
}
|
||||
|
||||
return mappedRecord
|
||||
}
|
||||
|
||||
private async findMatchingRules(event: QuotaEvent): Promise<QuotaRule[]> {
|
||||
const rules = await this.prismaClient.quotaRule.findMany({
|
||||
where: {
|
||||
teamId: event.teamId,
|
||||
resource: event.resource,
|
||||
enabled: true,
|
||||
},
|
||||
})
|
||||
|
||||
return rules.filter((rule) => matchesQuotaRule(rule, event))
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluates whether an action is permitted under all active matching quota rules.
|
||||
* Performs an atomic pre-check with SELECT ... FOR UPDATE.
|
||||
* Throws QuotaExceededError if any matching rule is exceeded.
|
||||
*/
|
||||
async checkQuota(
|
||||
event: QuotaEvent,
|
||||
amount: number = 0,
|
||||
): Promise<{ allowed: boolean; matchedRules: QuotaRule[] }> {
|
||||
const rules = await this.findMatchingRules(event)
|
||||
if (rules.length === 0) {
|
||||
return { allowed: true, matchedRules: [] }
|
||||
}
|
||||
|
||||
const now = new Date()
|
||||
|
||||
for (const rule of rules) {
|
||||
const targetUserId = getQuotaRuleTargetUserId(rule, event)
|
||||
|
||||
await this.prismaClient.$transaction(async (tx) => {
|
||||
if (targetUserId === null) {
|
||||
// Serialize all_members record checks/creations on the parent rule row
|
||||
await tx.$queryRaw`SELECT id FROM quota_rules WHERE id = ${rule.id} FOR UPDATE`
|
||||
}
|
||||
|
||||
let rawRecord = targetUserId
|
||||
? ((
|
||||
await tx.$queryRaw<RawQuotaRecord[]>`
|
||||
SELECT * FROM quota_records
|
||||
WHERE rule_id = ${rule.id} AND user_id = ${targetUserId}
|
||||
FOR UPDATE
|
||||
`
|
||||
)[0] ?? null)
|
||||
: ((
|
||||
await tx.$queryRaw<RawQuotaRecord[]>`
|
||||
SELECT * FROM quota_records
|
||||
WHERE rule_id = ${rule.id} AND user_id IS NULL
|
||||
FOR UPDATE
|
||||
`
|
||||
)[0] ?? null)
|
||||
|
||||
if (!rawRecord && targetUserId !== null) {
|
||||
// Lock parent rule on first user record check and re-query
|
||||
await tx.$queryRaw`SELECT id FROM quota_rules WHERE id = ${rule.id} FOR UPDATE`
|
||||
rawRecord =
|
||||
(
|
||||
await tx.$queryRaw<RawQuotaRecord[]>`
|
||||
SELECT * FROM quota_records
|
||||
WHERE rule_id = ${rule.id} AND user_id = ${targetUserId}
|
||||
FOR UPDATE
|
||||
`
|
||||
)[0] ?? null
|
||||
}
|
||||
|
||||
const isWindowActive = Boolean(
|
||||
rawRecord?.period_start &&
|
||||
rawRecord?.period_end &&
|
||||
now >= rawRecord.period_start &&
|
||||
now < rawRecord.period_end,
|
||||
)
|
||||
|
||||
const consumed = isWindowActive ? (rawRecord?.consumed ?? 0) : 0
|
||||
const periodEnd = isWindowActive
|
||||
? rawRecord!.period_end!
|
||||
: new Date(now.getTime() + periodToDurationMs(rule.period))
|
||||
|
||||
if (consumed + amount > rule.limit) {
|
||||
throw new QuotaExceededError({
|
||||
policyId: rule.id,
|
||||
resource: rule.resource,
|
||||
limit: rule.limit,
|
||||
consumed,
|
||||
periodEnd,
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return { allowed: true, matchedRules: rules }
|
||||
}
|
||||
|
||||
/**
|
||||
* Records consumed usage across all matching quota rules.
|
||||
* Lazy resets the period window in-place when previous window has expired.
|
||||
* Uses SELECT ... FOR UPDATE inside transactions for atomic concurrency protection.
|
||||
*/
|
||||
async consumeQuota(event: QuotaEvent, amount: number): Promise<void> {
|
||||
if (amount <= 0) return
|
||||
|
||||
const rules = await this.findMatchingRules(event)
|
||||
if (rules.length === 0) return
|
||||
|
||||
const now = new Date()
|
||||
|
||||
for (const rule of rules) {
|
||||
const targetUserId = getQuotaRuleTargetUserId(rule, event)
|
||||
|
||||
await this.prismaClient.$transaction(async (tx) => {
|
||||
if (targetUserId === null) {
|
||||
// Serialize all_members (shared pool) creations and updates on the parent rule row
|
||||
await tx.$queryRaw`SELECT id FROM quota_rules WHERE id = ${rule.id} FOR UPDATE`
|
||||
}
|
||||
|
||||
let rawRecord = targetUserId
|
||||
? ((
|
||||
await tx.$queryRaw<RawQuotaRecord[]>`
|
||||
SELECT * FROM quota_records
|
||||
WHERE rule_id = ${rule.id} AND user_id = ${targetUserId}
|
||||
FOR UPDATE
|
||||
`
|
||||
)[0] ?? null)
|
||||
: ((
|
||||
await tx.$queryRaw<RawQuotaRecord[]>`
|
||||
SELECT * FROM quota_records
|
||||
WHERE rule_id = ${rule.id} AND user_id IS NULL
|
||||
FOR UPDATE
|
||||
`
|
||||
)[0] ?? null)
|
||||
|
||||
if (!rawRecord && targetUserId !== null) {
|
||||
// Lock parent rule on first user record creation and re-query
|
||||
await tx.$queryRaw`SELECT id FROM quota_rules WHERE id = ${rule.id} FOR UPDATE`
|
||||
rawRecord =
|
||||
(
|
||||
await tx.$queryRaw<RawQuotaRecord[]>`
|
||||
SELECT * FROM quota_records
|
||||
WHERE rule_id = ${rule.id} AND user_id = ${targetUserId}
|
||||
FOR UPDATE
|
||||
`
|
||||
)[0] ?? null
|
||||
}
|
||||
|
||||
const isWindowActive = Boolean(
|
||||
rawRecord?.period_start &&
|
||||
rawRecord?.period_end &&
|
||||
now >= rawRecord.period_start &&
|
||||
now < rawRecord.period_end,
|
||||
)
|
||||
|
||||
if (isWindowActive && rawRecord) {
|
||||
await tx.quotaRecord.update({
|
||||
where: { id: rawRecord.id },
|
||||
data: {
|
||||
consumed: { increment: amount },
|
||||
},
|
||||
})
|
||||
} else {
|
||||
const periodStart = now
|
||||
const periodEnd = new Date(now.getTime() + periodToDurationMs(rule.period))
|
||||
|
||||
if (rawRecord) {
|
||||
await tx.quotaRecord.update({
|
||||
where: { id: rawRecord.id },
|
||||
data: {
|
||||
periodStart,
|
||||
periodEnd,
|
||||
consumed: amount,
|
||||
},
|
||||
})
|
||||
} else {
|
||||
await tx.quotaRecord.create({
|
||||
data: {
|
||||
ruleId: rule.id,
|
||||
teamId: rule.teamId,
|
||||
userId: targetUserId,
|
||||
periodStart,
|
||||
periodEnd,
|
||||
consumed: amount,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const quotaService = new QuotaService()
|
||||
@@ -335,4 +335,161 @@ describe('ShareService', () => {
|
||||
const item = list.data.find((l) => l.id === shareLink.id)
|
||||
expect(item?.creator?.image).toBe('http://s3/avatars/user123-presigned.png')
|
||||
})
|
||||
|
||||
it('hides soft-deleted files from share link and restores them upon file restoration', async () => {
|
||||
const project = await prisma.project.findUniqueOrThrow({ where: { id: projectId } })
|
||||
const file = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'shared-doc.pdf',
|
||||
type: AssetType.file,
|
||||
status: 'processed',
|
||||
projectId,
|
||||
parentId: project.rootFolderId,
|
||||
},
|
||||
})
|
||||
|
||||
const shareLink = await shareService.createShareLink(projectId, {
|
||||
name: 'Doc Share',
|
||||
})
|
||||
|
||||
await shareService.addAssetToShare(shareLink.id, {
|
||||
assetIds: [file.id],
|
||||
})
|
||||
|
||||
// Verify initial state: 1 file in share link
|
||||
const initialChildren = await assetService.listChildren({
|
||||
assetId: shareLink.rootFolderId,
|
||||
assetType: 'file',
|
||||
})
|
||||
expect(initialChildren.data).toHaveLength(1)
|
||||
expect(initialChildren.data[0].name).toBe('shared-doc.pdf')
|
||||
|
||||
const initialShareRoot = await prisma.asset.findUnique({
|
||||
where: { id: shareLink.rootFolderId },
|
||||
})
|
||||
expect(initialShareRoot?.fileCount).toBe(1)
|
||||
|
||||
const symlink = await prisma.asset.findFirst({
|
||||
where: { targetId: file.id, parentId: shareLink.rootFolderId },
|
||||
})
|
||||
expect(symlink).toBeDefined()
|
||||
await expect(shareService.verifyPublicAccess(file.id)).resolves.toBeDefined()
|
||||
await expect(shareService.verifyPublicAccess(symlink!.id)).resolves.toBeDefined()
|
||||
|
||||
// 1. Soft-delete the file (move to trash)
|
||||
await assetService.deleteAssets([file.id])
|
||||
|
||||
// Verify: file should disappear from share link children
|
||||
const afterDeleteChildren = await assetService.listChildren({
|
||||
assetId: shareLink.rootFolderId,
|
||||
assetType: 'file',
|
||||
})
|
||||
expect(afterDeleteChildren.data).toHaveLength(0)
|
||||
|
||||
// Verify: share root fileCount should be decremented to 0
|
||||
const afterDeleteShareRoot = await prisma.asset.findUnique({
|
||||
where: { id: shareLink.rootFolderId },
|
||||
})
|
||||
expect(afterDeleteShareRoot?.fileCount).toBe(0)
|
||||
|
||||
// Verify: public access is rejected
|
||||
await expect(shareService.verifyPublicAccess(file.id)).rejects.toThrow()
|
||||
await expect(shareService.verifyPublicAccess(symlink!.id)).rejects.toThrow()
|
||||
|
||||
// Verify: project's recently-deleted view does NOT list symlinks
|
||||
const recentlyDeleted = await assetService.listChildren({
|
||||
projectId,
|
||||
showDeleted: true,
|
||||
assetType: 'file',
|
||||
})
|
||||
expect(recentlyDeleted.data).toHaveLength(1)
|
||||
expect(recentlyDeleted.data[0].id).toBe(file.id)
|
||||
|
||||
// 2. Restore the file from trash
|
||||
await assetService.restoreAssets([file.id])
|
||||
|
||||
// Verify: file reappears in share link children
|
||||
const afterRestoreChildren = await assetService.listChildren({
|
||||
assetId: shareLink.rootFolderId,
|
||||
assetType: 'file',
|
||||
})
|
||||
expect(afterRestoreChildren.data).toHaveLength(1)
|
||||
expect(afterRestoreChildren.data[0].name).toBe('shared-doc.pdf')
|
||||
|
||||
// Verify: share root fileCount is restored to 1
|
||||
const afterRestoreShareRoot = await prisma.asset.findUnique({
|
||||
where: { id: shareLink.rootFolderId },
|
||||
})
|
||||
expect(afterRestoreShareRoot?.fileCount).toBe(1)
|
||||
|
||||
// Verify: public access works again
|
||||
await expect(shareService.verifyPublicAccess(file.id)).resolves.toBeDefined()
|
||||
await expect(shareService.verifyPublicAccess(symlink!.id)).resolves.toBeDefined()
|
||||
})
|
||||
|
||||
it('hides soft-deleted folders from share link and restores them upon folder restoration', async () => {
|
||||
const project = await prisma.project.findUniqueOrThrow({ where: { id: projectId } })
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'Shared Folder',
|
||||
type: AssetType.folder,
|
||||
status: 'processed',
|
||||
projectId,
|
||||
parentId: project.rootFolderId,
|
||||
},
|
||||
})
|
||||
const childFile = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'inner-file.txt',
|
||||
type: AssetType.file,
|
||||
status: 'processed',
|
||||
projectId,
|
||||
parentId: folder.id,
|
||||
},
|
||||
})
|
||||
|
||||
const shareLink = await shareService.createShareLink(projectId, {
|
||||
name: 'Folder Share',
|
||||
})
|
||||
|
||||
await shareService.addAssetToShare(shareLink.id, {
|
||||
assetIds: [folder.id],
|
||||
})
|
||||
|
||||
// Initial check: folder is in share link
|
||||
const initialChildren = await assetService.listChildren({
|
||||
assetId: shareLink.rootFolderId,
|
||||
assetType: 'folder',
|
||||
})
|
||||
expect(initialChildren.data).toHaveLength(1)
|
||||
expect(initialChildren.data[0].name).toBe('Shared Folder')
|
||||
await expect(shareService.verifyPublicAccess(childFile.id)).resolves.toBeDefined()
|
||||
|
||||
// 1. Soft-delete the folder
|
||||
await assetService.deleteAssets([folder.id])
|
||||
|
||||
// Verify: folder disappears from share link
|
||||
const afterDeleteChildren = await assetService.listChildren({
|
||||
assetId: shareLink.rootFolderId,
|
||||
assetType: 'folder',
|
||||
})
|
||||
expect(afterDeleteChildren.data).toHaveLength(0)
|
||||
|
||||
// Verify: access to child file inside folder is rejected
|
||||
await expect(shareService.verifyPublicAccess(childFile.id)).rejects.toThrow()
|
||||
|
||||
// 2. Restore the folder
|
||||
await assetService.restoreAssets([folder.id])
|
||||
|
||||
// Verify: folder reappears in share link
|
||||
const afterRestoreChildren = await assetService.listChildren({
|
||||
assetId: shareLink.rootFolderId,
|
||||
assetType: 'folder',
|
||||
})
|
||||
expect(afterRestoreChildren.data).toHaveLength(1)
|
||||
expect(afterRestoreChildren.data[0].name).toBe('Shared Folder')
|
||||
|
||||
// Verify: access to child file inside folder is restored
|
||||
await expect(shareService.verifyPublicAccess(childFile.id)).resolves.toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -260,16 +260,17 @@ export class ShareService {
|
||||
WITH RECURSIVE
|
||||
-- Trace ancestors in the real asset tree
|
||||
real_ancestors AS (
|
||||
SELECT id, parent_id, type::text FROM assets WHERE id = ${assetId}
|
||||
SELECT id, parent_id, type::text FROM assets WHERE id = ${assetId} AND is_deleted = false
|
||||
UNION ALL
|
||||
SELECT a.id, a.parent_id, a.type::text FROM assets a
|
||||
INNER JOIN real_ancestors ra ON ra.parent_id = a.id
|
||||
WHERE a.is_deleted = false
|
||||
),
|
||||
-- Find all symlinks pointing to any of these real ancestors
|
||||
found_symlinks AS (
|
||||
SELECT s.id, s.parent_id, s.type::text FROM assets s
|
||||
INNER JOIN real_ancestors ra ON s.target_id = ra.id
|
||||
WHERE s.type = 'symlink'
|
||||
WHERE s.type = 'symlink' AND s.is_deleted = false
|
||||
),
|
||||
-- Combine: start with either real ancestors that are 'share' type, or symlinks that lead to 'share' type
|
||||
search_starts AS (
|
||||
@@ -283,6 +284,7 @@ export class ShareService {
|
||||
UNION ALL
|
||||
SELECT a.id, a.parent_id, a.type::text FROM assets a
|
||||
INNER JOIN share_trace st ON st.parent_id = a.id
|
||||
WHERE a.is_deleted = false
|
||||
)
|
||||
SELECT id as "shareRootId" FROM share_trace WHERE type = 'share' LIMIT 1;
|
||||
`
|
||||
|
||||
@@ -184,6 +184,115 @@ describe('TeamService', () => {
|
||||
expect(allMembers).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('should filter included agents by agent permission and requester role', async () => {
|
||||
const owner = await prisma.user.create({
|
||||
data: { name: 'Owner', email: `owner-${Date.now()}@example.com`, password: 'pw' },
|
||||
})
|
||||
const team = await teamService.createTeam(owner, { name: 'Permission Team' })
|
||||
|
||||
const editor = await prisma.user.create({
|
||||
data: { name: 'Editor', email: `editor-${Date.now()}@example.com`, password: 'pw' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: editor.id, role: 'editor' },
|
||||
})
|
||||
|
||||
const reviewer = await prisma.user.create({
|
||||
data: { name: 'Reviewer', email: `reviewer-${Date.now()}@example.com`, password: 'pw' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: reviewer.id, role: 'reviewer' },
|
||||
})
|
||||
|
||||
// Create 3 agents with different permissions
|
||||
const botReviewer = await prisma.user.create({
|
||||
data: {
|
||||
name: 'Bot All Users',
|
||||
email: `bot-rev-${Date.now()}@shumai.ai`,
|
||||
type: 'agent',
|
||||
agent: {
|
||||
create: {
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
permission: 'reviewer',
|
||||
enabled: true,
|
||||
config: { provider: 'p', model: 'm' },
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
await teamService.joinTeam({ teamId: team.id, userId: botReviewer.id })
|
||||
|
||||
const botEditor = await prisma.user.create({
|
||||
data: {
|
||||
name: 'Bot Editor Only',
|
||||
email: `bot-ed-${Date.now()}@shumai.ai`,
|
||||
type: 'agent',
|
||||
agent: {
|
||||
create: {
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
permission: 'editor',
|
||||
enabled: true,
|
||||
config: { provider: 'p', model: 'm' },
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
await teamService.joinTeam({ teamId: team.id, userId: botEditor.id })
|
||||
|
||||
const botOwner = await prisma.user.create({
|
||||
data: {
|
||||
name: 'Bot Owner Only',
|
||||
email: `bot-own-${Date.now()}@shumai.ai`,
|
||||
type: 'agent',
|
||||
agent: {
|
||||
create: {
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
permission: 'owner',
|
||||
enabled: true,
|
||||
config: { provider: 'p', model: 'm' },
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
await teamService.joinTeam({ teamId: team.id, userId: botOwner.id })
|
||||
|
||||
// Reviewer should only see botReviewer among agents
|
||||
const reviewerMembers = await teamService.getTeamMembers({
|
||||
teamId: team.id,
|
||||
userId: reviewer.id,
|
||||
includeAgents: true,
|
||||
})
|
||||
const reviewerAgentIds = reviewerMembers.filter((m) => m.type === 'agent').map((m) => m.id)
|
||||
expect(reviewerAgentIds).toEqual([botReviewer.id])
|
||||
|
||||
// Editor should see botReviewer and botEditor
|
||||
const editorMembers = await teamService.getTeamMembers({
|
||||
teamId: team.id,
|
||||
userId: editor.id,
|
||||
includeAgents: true,
|
||||
})
|
||||
const editorAgentIds = editorMembers.filter((m) => m.type === 'agent').map((m) => m.id)
|
||||
expect(editorAgentIds).toHaveLength(2)
|
||||
expect(editorAgentIds).toContain(botReviewer.id)
|
||||
expect(editorAgentIds).toContain(botEditor.id)
|
||||
expect(editorAgentIds).not.toContain(botOwner.id)
|
||||
|
||||
// Owner should see all 3 agents
|
||||
const ownerMembers = await teamService.getTeamMembers({
|
||||
teamId: team.id,
|
||||
userId: owner.id,
|
||||
includeAgents: true,
|
||||
})
|
||||
const ownerAgentIds = ownerMembers.filter((m) => m.type === 'agent').map((m) => m.id)
|
||||
expect(ownerAgentIds).toHaveLength(3)
|
||||
expect(ownerAgentIds).toContain(botReviewer.id)
|
||||
expect(ownerAgentIds).toContain(botEditor.id)
|
||||
expect(ownerAgentIds).toContain(botOwner.id)
|
||||
})
|
||||
|
||||
it('should filter members for project-scoped members', async () => {
|
||||
const owner = await prisma.user.create({
|
||||
data: { name: 'Owner', email: `owner-${Date.now()}@example.com`, password: 'pw' },
|
||||
@@ -262,11 +371,12 @@ describe('TeamService', () => {
|
||||
expect(newSettings).toEqual({ theme: 'dark', semanticSearchEnabled: false })
|
||||
|
||||
await teamService.updateSettings(team.id, 'transcode.videoStrategy', 'all')
|
||||
await teamService.updateSettings(team.id, 'transcode.hardwareAcceleration', 'auto')
|
||||
|
||||
const finalSettings = await teamService.getSettings(team.id)
|
||||
expect(finalSettings).toEqual({
|
||||
theme: 'dark',
|
||||
transcode: { videoStrategy: 'all' },
|
||||
transcode: { videoStrategy: 'all', hardwareAcceleration: 'auto' },
|
||||
semanticSearchEnabled: false,
|
||||
})
|
||||
})
|
||||
|
||||
@@ -5,6 +5,7 @@ import { ProviderService, providerService } from '@shumai/core/src/provider/prov
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
import { getAvatarUrl } from '@shumai/core/src/user/avatar'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import { getAllowedAgentRoles } from '@shumai/core/src/agent/permissions'
|
||||
import {
|
||||
ServiceCreateTeamRequest,
|
||||
ServiceGetUserTeamsRequest,
|
||||
@@ -30,7 +31,7 @@ export class TeamService {
|
||||
data: {
|
||||
name: 'Default Team',
|
||||
settings: {
|
||||
transcode: { videoStrategy: 'best_match' },
|
||||
transcode: { videoStrategy: 'best_match', hardwareAcceleration: 'off' },
|
||||
},
|
||||
sandbox: { create: {} },
|
||||
},
|
||||
@@ -188,6 +189,8 @@ export class TeamService {
|
||||
throw new HTTPException(403, { message: 'Requester is not a team member' })
|
||||
}
|
||||
|
||||
const allowedAgentRoles = getAllowedAgentRoles(requester.role)
|
||||
|
||||
const members = await prisma.teamMember.findMany({
|
||||
where: {
|
||||
teamId: req.teamId,
|
||||
@@ -201,6 +204,7 @@ export class TeamService {
|
||||
agent: {
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
permission: { in: allowedAgentRoles },
|
||||
},
|
||||
},
|
||||
],
|
||||
@@ -314,6 +318,12 @@ export class TeamService {
|
||||
}
|
||||
settings.transcode.videoStrategy = value
|
||||
delete settings['transcode.videoStrategy']
|
||||
} else if (key === 'transcode.hardwareAcceleration') {
|
||||
if (!settings.transcode) {
|
||||
settings.transcode = {}
|
||||
}
|
||||
settings.transcode.hardwareAcceleration = value
|
||||
delete settings['transcode.hardwareAcceleration']
|
||||
} else {
|
||||
settings[key] = value
|
||||
}
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { transcodeService, calculatePreviewDimensions } from './transcode'
|
||||
import {
|
||||
transcodeService,
|
||||
calculatePreviewDimensions,
|
||||
getPlatformEncoderCandidates,
|
||||
getDefaultBitrate,
|
||||
getDefaultBitrateBps,
|
||||
calculateMaxBitrate,
|
||||
H264_ENCODER_CONFIGS,
|
||||
} from './transcode'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import * as path from 'path'
|
||||
import * as child_process from 'child_process'
|
||||
@@ -109,6 +117,118 @@ describe('TranscodeService', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('should extract videoBitRate from stream bit_rate or tags or fallback correctly', async () => {
|
||||
/* eslint-disable @typescript-eslint/naming-convention */
|
||||
// 1. Direct video stream bit_rate
|
||||
const output1 = JSON.stringify({
|
||||
format: { duration: '10', bit_rate: '2000000' },
|
||||
streams: [
|
||||
{ codec_type: 'video', width: 1920, height: 1080, bit_rate: '1800000' },
|
||||
{ codec_type: 'audio', bit_rate: '128000' },
|
||||
],
|
||||
})
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
_args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result: { stdout: string; stderr: string },
|
||||
) => void
|
||||
if (typeof cb === 'function') {
|
||||
cb(null, { stdout: output1, stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
const info1 = await transcodeService.getVideoInfo('test1.mp4')
|
||||
expect(info1.videoBitRate).toBe(1800000)
|
||||
|
||||
// 2. Stream BPS tag
|
||||
const output2 = JSON.stringify({
|
||||
format: { duration: '10', bit_rate: '2000000' },
|
||||
streams: [
|
||||
{ codec_type: 'video', width: 1920, height: 1080, tags: { BPS: '1500000' } },
|
||||
{ codec_type: 'audio', bit_rate: '128000' },
|
||||
],
|
||||
})
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
_args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result: { stdout: string; stderr: string },
|
||||
) => void
|
||||
if (typeof cb === 'function') {
|
||||
cb(null, { stdout: output2, stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
const info2 = await transcodeService.getVideoInfo('test2.mp4')
|
||||
expect(info2.videoBitRate).toBe(1500000)
|
||||
|
||||
// 3. Stream NUMBER_OF_BYTES tag
|
||||
const output3 = JSON.stringify({
|
||||
format: { duration: '10', bit_rate: '2000000' },
|
||||
streams: [
|
||||
{ codec_type: 'video', width: 1920, height: 1080, tags: { NUMBER_OF_BYTES: '1000000' } },
|
||||
{ codec_type: 'audio', bit_rate: '128000' },
|
||||
],
|
||||
})
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
_args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result: { stdout: string; stderr: string },
|
||||
) => void
|
||||
if (typeof cb === 'function') {
|
||||
cb(null, { stdout: output3, stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
const info3 = await transcodeService.getVideoInfo('test3.mp4')
|
||||
expect(info3.videoBitRate).toBe(800000) // (1,000,000 * 8) / 10 = 800,000
|
||||
|
||||
// 4. Fallback totalBitrate - audioBitrate
|
||||
const output4 = JSON.stringify({
|
||||
format: { duration: '10', bit_rate: '1000000' },
|
||||
streams: [
|
||||
{ codec_type: 'video', width: 1920, height: 1080 },
|
||||
{ codec_type: 'audio', bit_rate: '128000' },
|
||||
],
|
||||
})
|
||||
/* eslint-enable @typescript-eslint/naming-convention */
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
_args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result: { stdout: string; stderr: string },
|
||||
) => void
|
||||
if (typeof cb === 'function') {
|
||||
cb(null, { stdout: output4, stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
const info4 = await transcodeService.getVideoInfo('test4.mp4')
|
||||
expect(info4.videoBitRate).toBe(872000) // 1,000,000 - 128,000 = 872,000
|
||||
})
|
||||
|
||||
it('should get image info using sharp', async () => {
|
||||
const mockMetadata = {
|
||||
width: 800,
|
||||
@@ -897,4 +1017,509 @@ describe('TranscodeService', () => {
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('Hardware Acceleration & Encoder Resolution', () => {
|
||||
beforeEach(() => {
|
||||
transcodeService.clearEncodersCache()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('should return platform candidates correctly', () => {
|
||||
expect(getPlatformEncoderCandidates('darwin')).toEqual([
|
||||
'h264_videotoolbox',
|
||||
'h264_nvenc',
|
||||
'h264_qsv',
|
||||
'h264_amf',
|
||||
])
|
||||
expect(getPlatformEncoderCandidates('win32')).toEqual(['h264_nvenc', 'h264_qsv', 'h264_amf'])
|
||||
expect(getPlatformEncoderCandidates('linux')).toEqual(['h264_nvenc', 'h264_qsv', 'h264_amf'])
|
||||
})
|
||||
|
||||
it('should calculate default bitrates by resolution height and width correctly', () => {
|
||||
expect(getDefaultBitrateBps(2160, 3840)).toBe(12_000_000)
|
||||
expect(getDefaultBitrate(2160, 3840)).toBe('12000k')
|
||||
expect(getDefaultBitrate(1080, 1920)).toBe('4500k')
|
||||
expect(getDefaultBitrate(720, 1280)).toBe('2500k')
|
||||
expect(getDefaultBitrate(540, 960)).toBe('1200k')
|
||||
expect(getDefaultBitrate(360, 640)).toBe('800k')
|
||||
expect(getDefaultBitrate(180, 320)).toBe('100k')
|
||||
expect(getDefaultBitrate(100, 100)).toBe('100k')
|
||||
})
|
||||
|
||||
it('calculateMaxBitrate should cap bitrate based on sourceVideoBitrate, ceiling, and targetFps', () => {
|
||||
// Default without source bitrate
|
||||
expect(calculateMaxBitrate(720, 1280)).toEqual({
|
||||
maxrate: '2500k',
|
||||
bufsize: '5000k',
|
||||
})
|
||||
|
||||
// With low source bitrate (600k * 1.2 = 720k)
|
||||
expect(calculateMaxBitrate(720, 1280, 600_000)).toEqual({
|
||||
maxrate: '720k',
|
||||
bufsize: '1440k',
|
||||
})
|
||||
|
||||
// With high source bitrate (3000k * 1.2 = 3600k, capped at 2500k)
|
||||
expect(calculateMaxBitrate(720, 1280, 3_000_000)).toEqual({
|
||||
maxrate: '2500k',
|
||||
bufsize: '5000k',
|
||||
})
|
||||
|
||||
// With downsampled targetFps (180p preview @ 0.78 fps: 100k * (0.78/24) = 3.25k -> capped at min 50k)
|
||||
expect(calculateMaxBitrate(180, 320, 600_000, 0.78)).toEqual({
|
||||
maxrate: '50k',
|
||||
bufsize: '100k',
|
||||
})
|
||||
|
||||
// With downsampled targetFps string (180p preview @ 24 fps)
|
||||
expect(calculateMaxBitrate(180, 320, 600_000, 24)).toEqual({
|
||||
maxrate: '100k',
|
||||
bufsize: '200k',
|
||||
})
|
||||
|
||||
// With extremely low source bitrate without targetFps (50k * 1.2 = 60k, minimum floor 100k)
|
||||
expect(calculateMaxBitrate(720, 1280, 50_000)).toEqual({
|
||||
maxrate: '100k',
|
||||
bufsize: '200k',
|
||||
})
|
||||
})
|
||||
|
||||
it('selectH264Encoder should return libx264 when hardwareAcceleration is off', async () => {
|
||||
const encoder = await transcodeService.selectH264Encoder('off')
|
||||
expect(encoder).toEqual(H264_ENCODER_CONFIGS.libx264)
|
||||
expect(child_process.execFile).not.toHaveBeenCalledWith(
|
||||
'ffmpeg',
|
||||
['-encoders'],
|
||||
expect.any(Function),
|
||||
)
|
||||
})
|
||||
|
||||
it('selectH264Encoder should select h264_videotoolbox on darwin when available', async () => {
|
||||
const mockEncodersOutput = `
|
||||
V....D libx264 libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10
|
||||
V....D h264_videotoolbox VideoToolbox H.264 Encoder
|
||||
`
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result: { stdout: string; stderr: string },
|
||||
) => void
|
||||
const argsArr = args as string[] | undefined
|
||||
if (argsArr && argsArr[0] === '-encoders') {
|
||||
cb(null, { stdout: mockEncodersOutput, stderr: '' })
|
||||
} else if (typeof cb === 'function') {
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
|
||||
const encoder = await transcodeService.selectH264Encoder('auto', 'darwin')
|
||||
expect(encoder.name).toBe('h264_videotoolbox')
|
||||
expect(encoder.presetArgs).toEqual(['-q:v', '74'])
|
||||
})
|
||||
|
||||
it('selectH264Encoder should select h264_nvenc on linux when available', async () => {
|
||||
const mockEncodersOutput = `
|
||||
V....D libx264 libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10
|
||||
V....D h264_nvenc NVIDIA NVENC H.264 encoder
|
||||
V....D h264_qsv Intel Quick Sync Video H.264
|
||||
`
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result: { stdout: string; stderr: string },
|
||||
) => void
|
||||
const argsArr = args as string[] | undefined
|
||||
if (argsArr && argsArr[0] === '-encoders') {
|
||||
cb(null, { stdout: mockEncodersOutput, stderr: '' })
|
||||
} else if (typeof cb === 'function') {
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
|
||||
const encoder = await transcodeService.selectH264Encoder('auto', 'linux')
|
||||
expect(encoder.name).toBe('h264_nvenc')
|
||||
expect(encoder.presetArgs).toEqual([
|
||||
'-preset',
|
||||
'p4',
|
||||
'-rc:v',
|
||||
'vbr',
|
||||
'-cq:v',
|
||||
'26',
|
||||
'-b:v',
|
||||
'0',
|
||||
])
|
||||
})
|
||||
|
||||
it('selectH264Encoder should select h264_qsv on linux when nvenc is not available', async () => {
|
||||
const mockEncodersOutput = `
|
||||
V....D libx264 libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10
|
||||
V....D h264_qsv Intel Quick Sync Video H.264
|
||||
`
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result: { stdout: string; stderr: string },
|
||||
) => void
|
||||
const argsArr = args as string[] | undefined
|
||||
if (argsArr && argsArr[0] === '-encoders') {
|
||||
cb(null, { stdout: mockEncodersOutput, stderr: '' })
|
||||
} else if (typeof cb === 'function') {
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
|
||||
const encoder = await transcodeService.selectH264Encoder('auto', 'linux')
|
||||
expect(encoder.name).toBe('h264_qsv')
|
||||
expect(encoder.presetArgs).toEqual(['-preset', 'fast', '-global_quality', '26'])
|
||||
})
|
||||
|
||||
it('selectH264Encoder should select h264_amf on win32 when available', async () => {
|
||||
const mockEncodersOutput = `
|
||||
V....D libx264 libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10
|
||||
V....D h264_amf AMD AMF H.264 Encoder
|
||||
`
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result: { stdout: string; stderr: string },
|
||||
) => void
|
||||
const argsArr = args as string[] | undefined
|
||||
if (argsArr && argsArr[0] === '-encoders') {
|
||||
cb(null, { stdout: mockEncodersOutput, stderr: '' })
|
||||
} else if (typeof cb === 'function') {
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
|
||||
const encoder = await transcodeService.selectH264Encoder('auto', 'win32')
|
||||
expect(encoder.name).toBe('h264_amf')
|
||||
expect(encoder.presetArgs).toEqual([
|
||||
'-quality',
|
||||
'balanced',
|
||||
'-rc',
|
||||
'qvbr',
|
||||
'-qvbr_quality_level',
|
||||
'26',
|
||||
])
|
||||
})
|
||||
|
||||
it('selectH264Encoder should fallback to libx264 when no hw encoder is in ffmpeg build', async () => {
|
||||
const mockEncodersOutput = `
|
||||
V....D libx264 libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10
|
||||
`
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result: { stdout: string; stderr: string },
|
||||
) => void
|
||||
const argsArr = args as string[] | undefined
|
||||
if (argsArr && argsArr[0] === '-encoders') {
|
||||
cb(null, { stdout: mockEncodersOutput, stderr: '' })
|
||||
} else if (typeof cb === 'function') {
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
|
||||
const encoder = await transcodeService.selectH264Encoder('auto', 'linux')
|
||||
expect(encoder.name).toBe('libx264')
|
||||
expect(encoder.presetArgs).toEqual(['-preset', 'fast', '-crf', '26'])
|
||||
})
|
||||
|
||||
it('transcodeVideo with hardwareAcceleration off should use libx264, preset fast, crf 26, maxrate, and yuv420p', async () => {
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
_args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result: { stdout: string; stderr: string },
|
||||
) => void
|
||||
if (typeof cb === 'function') {
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
|
||||
const outputFile = path.join(tempDir, 'out_off.mp4')
|
||||
await transcodeService.transcodeVideo({
|
||||
inputFile: 'input.mp4',
|
||||
outputFile,
|
||||
width: 1280,
|
||||
height: 720,
|
||||
hardwareAcceleration: 'off',
|
||||
sourceVideoBitrate: 600_000,
|
||||
})
|
||||
|
||||
expect(child_process.execFile).toHaveBeenCalledWith(
|
||||
'ffmpeg',
|
||||
expect.arrayContaining([
|
||||
'-c:v',
|
||||
'libx264',
|
||||
'-preset',
|
||||
'fast',
|
||||
'-crf',
|
||||
'26',
|
||||
'-maxrate',
|
||||
'720k',
|
||||
'-bufsize',
|
||||
'1440k',
|
||||
'-pix_fmt',
|
||||
'yuv420p',
|
||||
]),
|
||||
expect.any(Function),
|
||||
)
|
||||
})
|
||||
|
||||
it('transcodeVideo with hardwareAcceleration auto and videotoolbox should use -q:v 74 and -maxrate', async () => {
|
||||
vi.spyOn(transcodeService, 'selectH264Encoder').mockResolvedValue(
|
||||
H264_ENCODER_CONFIGS.h264_videotoolbox,
|
||||
)
|
||||
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
_args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result: { stdout: string; stderr: string },
|
||||
) => void
|
||||
if (typeof cb === 'function') {
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
|
||||
const outputFile = path.join(tempDir, 'out_vt.mp4')
|
||||
await transcodeService.transcodeVideo({
|
||||
inputFile: 'input.mp4',
|
||||
outputFile,
|
||||
width: 1280,
|
||||
height: 720,
|
||||
hardwareAcceleration: 'auto',
|
||||
sourceVideoBitrate: 600_000,
|
||||
})
|
||||
|
||||
expect(child_process.execFile).toHaveBeenCalledWith(
|
||||
'ffmpeg',
|
||||
expect.arrayContaining([
|
||||
'-c:v',
|
||||
'h264_videotoolbox',
|
||||
'-q:v',
|
||||
'74',
|
||||
'-maxrate',
|
||||
'720k',
|
||||
'-bufsize',
|
||||
'1440k',
|
||||
'-pix_fmt',
|
||||
'yuv420p',
|
||||
]),
|
||||
expect.any(Function),
|
||||
)
|
||||
})
|
||||
|
||||
it('transcodeVideo with hardwareAcceleration auto and nvenc should use -preset p4, -rc:v vbr, -cq:v 26, -b:v 0, and -maxrate', async () => {
|
||||
vi.spyOn(transcodeService, 'selectH264Encoder').mockResolvedValue(
|
||||
H264_ENCODER_CONFIGS.h264_nvenc,
|
||||
)
|
||||
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
_args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result: { stdout: string; stderr: string },
|
||||
) => void
|
||||
if (typeof cb === 'function') {
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
|
||||
const outputFile = path.join(tempDir, 'out_nvenc.mp4')
|
||||
await transcodeService.transcodeVideo({
|
||||
inputFile: 'input.mp4',
|
||||
outputFile,
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
hardwareAcceleration: 'auto',
|
||||
sourceVideoBitrate: 1_000_000,
|
||||
})
|
||||
|
||||
expect(child_process.execFile).toHaveBeenCalledWith(
|
||||
'ffmpeg',
|
||||
expect.arrayContaining([
|
||||
'-c:v',
|
||||
'h264_nvenc',
|
||||
'-preset',
|
||||
'p4',
|
||||
'-rc:v',
|
||||
'vbr',
|
||||
'-cq:v',
|
||||
'26',
|
||||
'-b:v',
|
||||
'0',
|
||||
'-maxrate',
|
||||
'1200k',
|
||||
'-bufsize',
|
||||
'2400k',
|
||||
'-pix_fmt',
|
||||
'yuv420p',
|
||||
]),
|
||||
expect.any(Function),
|
||||
)
|
||||
})
|
||||
|
||||
it('transcodeVideo with hardwareAcceleration auto and amf should use -quality balanced, -rc qvbr, -qvbr_quality_level 26, and -maxrate', async () => {
|
||||
vi.spyOn(transcodeService, 'selectH264Encoder').mockResolvedValue(
|
||||
H264_ENCODER_CONFIGS.h264_amf,
|
||||
)
|
||||
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
_args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result: { stdout: string; stderr: string },
|
||||
) => void
|
||||
if (typeof cb === 'function') {
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
|
||||
const outputFile = path.join(tempDir, 'out_amf.mp4')
|
||||
await transcodeService.transcodeVideo({
|
||||
inputFile: 'input.mp4',
|
||||
outputFile,
|
||||
width: 1280,
|
||||
height: 720,
|
||||
hardwareAcceleration: 'auto',
|
||||
sourceVideoBitrate: 600_000,
|
||||
})
|
||||
|
||||
expect(child_process.execFile).toHaveBeenCalledWith(
|
||||
'ffmpeg',
|
||||
expect.arrayContaining([
|
||||
'-c:v',
|
||||
'h264_amf',
|
||||
'-quality',
|
||||
'balanced',
|
||||
'-rc',
|
||||
'qvbr',
|
||||
'-qvbr_quality_level',
|
||||
'26',
|
||||
'-maxrate',
|
||||
'720k',
|
||||
'-bufsize',
|
||||
'1440k',
|
||||
'-pix_fmt',
|
||||
'yuv420p',
|
||||
]),
|
||||
expect.any(Function),
|
||||
)
|
||||
})
|
||||
|
||||
it('transcodeVideo with explicit videoBitrate should use -b:v directly', async () => {
|
||||
vi.mocked(execFile).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
_args: unknown,
|
||||
callback: unknown,
|
||||
): ReturnType<typeof child_process.execFile> => {
|
||||
const cb = callback as (
|
||||
err: Error | null,
|
||||
result: { stdout: string; stderr: string },
|
||||
) => void
|
||||
if (typeof cb === 'function') {
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
}
|
||||
return {} as ReturnType<typeof child_process.execFile>
|
||||
},
|
||||
)
|
||||
|
||||
const outputFile = path.join(tempDir, 'out_explicit.mp4')
|
||||
await transcodeService.transcodeVideo({
|
||||
inputFile: 'input.mp4',
|
||||
outputFile,
|
||||
width: 1280,
|
||||
height: 720,
|
||||
hardwareAcceleration: 'off',
|
||||
videoBitrate: '1500k',
|
||||
})
|
||||
|
||||
expect(child_process.execFile).toHaveBeenCalledWith(
|
||||
'ffmpeg',
|
||||
expect.arrayContaining([
|
||||
'-c:v',
|
||||
'libx264',
|
||||
'-preset',
|
||||
'fast',
|
||||
'-crf',
|
||||
'26',
|
||||
'-b:v',
|
||||
'1500k',
|
||||
'-pix_fmt',
|
||||
'yuv420p',
|
||||
]),
|
||||
expect.any(Function),
|
||||
)
|
||||
expect(child_process.execFile).not.toHaveBeenCalledWith(
|
||||
'ffmpeg',
|
||||
expect.arrayContaining(['-maxrate']),
|
||||
expect.any(Function),
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -91,6 +91,7 @@ export interface MediaMetadata {
|
||||
originalHeight: number
|
||||
duration: number
|
||||
bitRate: number
|
||||
videoBitRate?: number
|
||||
frameRate: number
|
||||
totalFrames: number
|
||||
startTimecode?: string
|
||||
@@ -111,6 +112,113 @@ export interface TranscodeVideoParams {
|
||||
frameRate?: number | string
|
||||
disableAudio?: boolean
|
||||
overlayFile?: string
|
||||
hardwareAcceleration?: 'off' | 'auto'
|
||||
videoBitrate?: string
|
||||
sourceVideoBitrate?: number
|
||||
}
|
||||
|
||||
export interface EncoderConfig {
|
||||
name: string
|
||||
presetArgs: string[]
|
||||
}
|
||||
|
||||
export const H264_ENCODER_CONFIGS: Record<string, EncoderConfig> = {
|
||||
h264_nvenc: {
|
||||
name: 'h264_nvenc',
|
||||
presetArgs: ['-preset', 'p4', '-rc:v', 'vbr', '-cq:v', '26', '-b:v', '0'],
|
||||
},
|
||||
h264_qsv: {
|
||||
name: 'h264_qsv',
|
||||
presetArgs: ['-preset', 'fast', '-global_quality', '26'],
|
||||
},
|
||||
h264_amf: {
|
||||
name: 'h264_amf',
|
||||
presetArgs: ['-quality', 'balanced', '-rc', 'qvbr', '-qvbr_quality_level', '26'],
|
||||
},
|
||||
h264_videotoolbox: {
|
||||
name: 'h264_videotoolbox',
|
||||
presetArgs: ['-q:v', '74'],
|
||||
},
|
||||
libx264: {
|
||||
name: 'libx264',
|
||||
presetArgs: ['-preset', 'fast', '-crf', '26'],
|
||||
},
|
||||
}
|
||||
|
||||
export function getPlatformEncoderCandidates(
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): string[] {
|
||||
switch (platform) {
|
||||
case 'darwin':
|
||||
return ['h264_videotoolbox', 'h264_nvenc', 'h264_qsv', 'h264_amf']
|
||||
case 'win32':
|
||||
return ['h264_nvenc', 'h264_qsv', 'h264_amf']
|
||||
case 'linux':
|
||||
default:
|
||||
return ['h264_nvenc', 'h264_qsv', 'h264_amf']
|
||||
}
|
||||
}
|
||||
|
||||
export function getDefaultBitrateBps(height: number, width?: number): number {
|
||||
const longSide = Math.max(width || 0, height)
|
||||
const shortSide = Math.min(width || height, height)
|
||||
const effectiveHeight = shortSide > 0 ? shortSide : height
|
||||
|
||||
if (effectiveHeight >= 2160 || longSide >= 3840) return 12_000_000
|
||||
if (effectiveHeight >= 1080 || longSide >= 1920) return 4_500_000
|
||||
if (effectiveHeight >= 720 || longSide >= 1280) return 2_500_000
|
||||
if (effectiveHeight >= 540 || longSide >= 960) return 1_200_000
|
||||
if (effectiveHeight >= 360 || longSide >= 640) return 800_000
|
||||
return 100_000
|
||||
}
|
||||
|
||||
export function getDefaultBitrate(height: number, width?: number): string {
|
||||
const bps = getDefaultBitrateBps(height, width)
|
||||
return `${Math.round(bps / 1000)}k`
|
||||
}
|
||||
|
||||
export function calculateMaxBitrate(
|
||||
targetHeight: number,
|
||||
targetWidth?: number,
|
||||
sourceVideoBitrate?: number,
|
||||
targetFps?: number | string,
|
||||
): { maxrate: string; bufsize: string } {
|
||||
let configuredMaxBps = getDefaultBitrateBps(targetHeight, targetWidth)
|
||||
|
||||
// If frame rate is downsampled (e.g. 180p preview with < 24 fps), scale the bitrate ceiling proportionally
|
||||
if (targetFps) {
|
||||
let parsedFps: number | undefined
|
||||
if (typeof targetFps === 'number') {
|
||||
parsedFps = targetFps
|
||||
} else {
|
||||
const parts = targetFps.split('/')
|
||||
if (parts.length === 2) {
|
||||
parsedFps = parseFloat(parts[0]) / parseFloat(parts[1])
|
||||
} else {
|
||||
parsedFps = parseFloat(targetFps)
|
||||
}
|
||||
}
|
||||
if (Number.isFinite(parsedFps) && parsedFps > 0 && parsedFps < 24) {
|
||||
const fpsRatio = Math.max(0.1, parsedFps / 24)
|
||||
configuredMaxBps = Math.max(50_000, Math.round(configuredMaxBps * fpsRatio))
|
||||
}
|
||||
}
|
||||
|
||||
let effectiveMaxBps =
|
||||
sourceVideoBitrate && sourceVideoBitrate > 0
|
||||
? Math.min(configuredMaxBps, Math.round(sourceVideoBitrate * 1.2))
|
||||
: configuredMaxBps
|
||||
|
||||
const minFloor = targetFps ? 50_000 : 100_000
|
||||
effectiveMaxBps = Math.max(minFloor, effectiveMaxBps)
|
||||
|
||||
const maxrateKbps = Math.max(50, Math.round(effectiveMaxBps / 1000))
|
||||
const bufsizeKbps = maxrateKbps * 2
|
||||
|
||||
return {
|
||||
maxrate: `${maxrateKbps}k`,
|
||||
bufsize: `${bufsizeKbps}k`,
|
||||
}
|
||||
}
|
||||
|
||||
export interface ExtractVideoFramesParams {
|
||||
@@ -295,11 +403,38 @@ export class TranscodeService {
|
||||
}
|
||||
const startTimecode = videoStream.tags?.timecode || info.format?.tags?.timecode
|
||||
|
||||
let videoBitRate: number | undefined
|
||||
if (videoStream.bit_rate && parseInt(videoStream.bit_rate, 10) > 0) {
|
||||
videoBitRate = parseInt(videoStream.bit_rate, 10)
|
||||
} else {
|
||||
const bpsTag = videoStream.tags?.BPS || videoStream.tags?.['BPS-eng']
|
||||
if (bpsTag && parseInt(bpsTag, 10) > 0) {
|
||||
videoBitRate = parseInt(bpsTag, 10)
|
||||
} else {
|
||||
const bytesTag =
|
||||
videoStream.tags?.NUMBER_OF_BYTES || videoStream.tags?.['NUMBER_OF_BYTES-eng']
|
||||
if (bytesTag && duration > 0) {
|
||||
videoBitRate = Math.round((parseInt(bytesTag, 10) * 8) / duration)
|
||||
} else {
|
||||
const totalBitrate = parseFloat(info.format.bit_rate)
|
||||
if (Number.isFinite(totalBitrate) && totalBitrate > 0) {
|
||||
const audioBitrate = audioStream?.bit_rate
|
||||
? parseFloat(audioStream.bit_rate)
|
||||
: audioStream
|
||||
? 128_000
|
||||
: 0
|
||||
videoBitRate = Math.max(100_000, Math.round(totalBitrate - audioBitrate))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
originalWidth: videoStream.width,
|
||||
originalHeight: videoStream.height,
|
||||
duration,
|
||||
bitRate: parseFloat(info.format.bit_rate),
|
||||
videoBitRate,
|
||||
frameRate: fps || 30,
|
||||
totalFrames: totalFrames || 0,
|
||||
startTimecode,
|
||||
@@ -373,6 +508,53 @@ export class TranscodeService {
|
||||
}
|
||||
}
|
||||
|
||||
private availableEncodersCache: Set<string> | null = null
|
||||
|
||||
clearEncodersCache(): void {
|
||||
this.availableEncodersCache = null
|
||||
}
|
||||
|
||||
async getAvailableEncoders(): Promise<Set<string>> {
|
||||
if (this.availableEncodersCache) {
|
||||
return this.availableEncodersCache
|
||||
}
|
||||
try {
|
||||
const { stdout } = await execFileAsync('ffmpeg', ['-encoders'])
|
||||
const encoders = new Set<string>()
|
||||
const lines = stdout.split('\n')
|
||||
for (const line of lines) {
|
||||
const match = line.match(/^\s*[A-Z.]{6}\s+([a-zA-Z0-9_-]+)/)
|
||||
if (match) {
|
||||
encoders.add(match[1])
|
||||
}
|
||||
}
|
||||
this.availableEncodersCache = encoders
|
||||
return encoders
|
||||
} catch (err) {
|
||||
console.warn('Failed to probe ffmpeg encoders:', err)
|
||||
return new Set<string>()
|
||||
}
|
||||
}
|
||||
|
||||
async selectH264Encoder(
|
||||
hardwareAcceleration?: 'off' | 'auto',
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): Promise<EncoderConfig> {
|
||||
if (hardwareAcceleration !== 'auto') {
|
||||
return H264_ENCODER_CONFIGS.libx264
|
||||
}
|
||||
|
||||
const available = await this.getAvailableEncoders()
|
||||
const candidates = getPlatformEncoderCandidates(platform)
|
||||
for (const enc of candidates) {
|
||||
if (available.has(enc) && H264_ENCODER_CONFIGS[enc]) {
|
||||
return H264_ENCODER_CONFIGS[enc]
|
||||
}
|
||||
}
|
||||
|
||||
return H264_ENCODER_CONFIGS.libx264
|
||||
}
|
||||
|
||||
async transcodeVideo(params: TranscodeVideoParams): Promise<void> {
|
||||
let filterComplex: string
|
||||
const args: string[] = ['-i', params.inputFile]
|
||||
@@ -420,7 +602,25 @@ export class TranscodeService {
|
||||
args.push('-map', '0:a?')
|
||||
}
|
||||
|
||||
args.push('-c:v', 'libx264', '-preset', 'fast', '-crf', '26')
|
||||
const encoder = await this.selectH264Encoder(params.hardwareAcceleration)
|
||||
args.push('-c:v', encoder.name)
|
||||
if (encoder.presetArgs.length > 0) {
|
||||
args.push(...encoder.presetArgs)
|
||||
}
|
||||
|
||||
if (params.videoBitrate) {
|
||||
args.push('-b:v', params.videoBitrate)
|
||||
} else {
|
||||
const { maxrate, bufsize } = calculateMaxBitrate(
|
||||
params.height,
|
||||
params.width,
|
||||
params.sourceVideoBitrate,
|
||||
params.frameRate,
|
||||
)
|
||||
args.push('-maxrate', maxrate, '-bufsize', bufsize)
|
||||
}
|
||||
|
||||
args.push('-pix_fmt', 'yuv420p')
|
||||
|
||||
if (!params.disableAudio) {
|
||||
args.push('-c:a', 'aac', '-b:a', '128k')
|
||||
|
||||
@@ -190,6 +190,7 @@ describe('UploadService', () => {
|
||||
projectId: projectId,
|
||||
transcode: {
|
||||
videoStrategy: 'best_match',
|
||||
hardwareAcceleration: 'off',
|
||||
sprite: true,
|
||||
poster: true,
|
||||
},
|
||||
|
||||
@@ -303,9 +303,11 @@ export class UploadService {
|
||||
const settings = team.settings as PrismaJson.Settings | null
|
||||
if (isVideo) {
|
||||
const strategy = settings?.transcode?.videoStrategy || 'best_match'
|
||||
const hardwareAcceleration = settings?.transcode?.hardwareAcceleration || 'off'
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await new VideoTranscoder(tx as any, asset.id, team.id, projectId)
|
||||
.setStrategy(strategy)
|
||||
.setHardwareAcceleration(hardwareAcceleration)
|
||||
.withSprite()
|
||||
.withPoster()
|
||||
.submit()
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/db",
|
||||
"version": "0.3.8",
|
||||
"version": "0.4.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "agents" ADD COLUMN "permission" "TeamMemberRole" NOT NULL DEFAULT 'reviewer';
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "QuotaScopeMode" AS ENUM ('all_members', 'each_member', 'selected_members');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "QuotaPeriod" AS ENUM ('1hour', '5hour', '1day', '7day');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "QuotaResourceType" AS ENUM ('agent_total_tokens', 'agent_cost', 'agent_skill_call_count', 'agent_mcp_call_count', 'agent_bash_call_count', 'agent_tool_call_count');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "quota_rules" (
|
||||
"id" TEXT NOT NULL,
|
||||
"team_id" TEXT NOT NULL,
|
||||
"scope_mode" "QuotaScopeMode" NOT NULL,
|
||||
"role" "TeamMemberRole",
|
||||
"user_ids" JSONB,
|
||||
"resource" "QuotaResourceType" NOT NULL,
|
||||
"resource_data" JSONB,
|
||||
"limit" DOUBLE PRECISION NOT NULL,
|
||||
"period" "QuotaPeriod" NOT NULL,
|
||||
"enabled" BOOLEAN NOT NULL DEFAULT true,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "quota_rules_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "quota_records" (
|
||||
"id" TEXT NOT NULL,
|
||||
"rule_id" TEXT NOT NULL,
|
||||
"team_id" TEXT NOT NULL,
|
||||
"user_id" TEXT,
|
||||
"period_start" TIMESTAMP(3),
|
||||
"period_end" TIMESTAMP(3),
|
||||
"consumed" DOUBLE PRECISION NOT NULL DEFAULT 0,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "quota_records_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "quota_rules_team_id_enabled_idx" ON "quota_rules"("team_id", "enabled");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "quota_rules_team_id_resource_idx" ON "quota_rules"("team_id", "resource");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "quota_records_team_id_user_id_idx" ON "quota_records"("team_id", "user_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "quota_records_rule_id_idx" ON "quota_records"("rule_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "quota_records_rule_id_user_id_key" ON "quota_records"("rule_id", "user_id");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "quota_rules" ADD CONSTRAINT "quota_rules_team_id_fkey" FOREIGN KEY ("team_id") REFERENCES "teams"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "quota_records" ADD CONSTRAINT "quota_records_rule_id_fkey" FOREIGN KEY ("rule_id") REFERENCES "quota_rules"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "quota_records" ADD CONSTRAINT "quota_records_team_id_fkey" FOREIGN KEY ("team_id") REFERENCES "teams"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "quota_records" ADD CONSTRAINT "quota_records_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
/*
|
||||
Warnings:
|
||||
|
||||
- The values [agent_skill_call_count] on the enum `QuotaResourceType` will be removed. If these variants are still used in the database, this will fail.
|
||||
|
||||
*/
|
||||
-- AlterEnum
|
||||
BEGIN;
|
||||
CREATE TYPE "QuotaResourceType_new" AS ENUM ('agent_total_tokens', 'agent_cost', 'agent_mcp_call_count', 'agent_bash_call_count', 'agent_tool_call_count');
|
||||
ALTER TABLE "quota_rules" ALTER COLUMN "resource" TYPE "QuotaResourceType_new" USING ("resource"::text::"QuotaResourceType_new");
|
||||
ALTER TYPE "QuotaResourceType" RENAME TO "QuotaResourceType_old";
|
||||
ALTER TYPE "QuotaResourceType_new" RENAME TO "QuotaResourceType";
|
||||
DROP TYPE "public"."QuotaResourceType_old";
|
||||
COMMIT;
|
||||
@@ -0,0 +1,164 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "KanbanTaskStatus" AS ENUM ('TODO', 'READY', 'IN_PROGRESS', 'BLOCKED', 'IN_REVIEW', 'DONE', 'CANCELLED');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "KanbanTaskPriority" AS ENUM ('LOW', 'MEDIUM', 'HIGH', 'URGENT');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "KanbanTaskEventType" AS ENUM ('CREATED', 'STATUS_CHANGED', 'ASSIGNED', 'UNASSIGNED', 'COMMENTED', 'CHANGES_REQUESTED', 'BLOCKED', 'UNBLOCKED', 'PRIORITY_CHANGED', 'GOAL_CHANGED', 'DEPENDENCY_ADDED', 'DEPENDENCY_REMOVED', 'CANCELLED');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "kanban_goals" (
|
||||
"id" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"description" TEXT,
|
||||
"team_id" TEXT NOT NULL,
|
||||
"creator_id" TEXT,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "kanban_goals_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "kanban_tasks" (
|
||||
"id" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"description" TEXT,
|
||||
"is_agent_task" BOOLEAN NOT NULL DEFAULT false,
|
||||
"status" "KanbanTaskStatus" NOT NULL DEFAULT 'TODO',
|
||||
"priority" "KanbanTaskPriority" NOT NULL DEFAULT 'MEDIUM',
|
||||
"start_date" TIMESTAMP(3),
|
||||
"due_date" TIMESTAMP(3),
|
||||
"started_at" TIMESTAMP(3),
|
||||
"completed_at" TIMESTAMP(3),
|
||||
"goal_id" TEXT,
|
||||
"team_id" TEXT NOT NULL,
|
||||
"project_id" TEXT,
|
||||
"creator_id" TEXT NOT NULL,
|
||||
"reporter_id" TEXT,
|
||||
"assignee_id" TEXT,
|
||||
"target_folder_id" TEXT,
|
||||
"sort_index" TEXT,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "kanban_tasks_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "kanban_task_links" (
|
||||
"parent_id" TEXT NOT NULL,
|
||||
"child_id" TEXT NOT NULL,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "kanban_task_links_pkey" PRIMARY KEY ("parent_id","child_id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "kanban_task_comments" (
|
||||
"id" TEXT NOT NULL,
|
||||
"task_id" TEXT NOT NULL,
|
||||
"author_id" TEXT NOT NULL,
|
||||
"body" TEXT NOT NULL,
|
||||
"attachments" JSONB,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "kanban_task_comments_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "kanban_task_events" (
|
||||
"id" TEXT NOT NULL,
|
||||
"task_id" TEXT NOT NULL,
|
||||
"actor_id" TEXT,
|
||||
"type" "KanbanTaskEventType" NOT NULL,
|
||||
"from_status" "KanbanTaskStatus",
|
||||
"to_status" "KanbanTaskStatus",
|
||||
"data" JSONB,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "kanban_task_events_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "kanban_goals_team_id_idx" ON "kanban_goals"("team_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "kanban_tasks_team_id_status_idx" ON "kanban_tasks"("team_id", "status");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "kanban_tasks_team_id_status_sort_index_idx" ON "kanban_tasks"("team_id", "status", "sort_index");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "kanban_tasks_team_id_is_agent_task_status_idx" ON "kanban_tasks"("team_id", "is_agent_task", "status");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "kanban_tasks_team_id_goal_id_status_idx" ON "kanban_tasks"("team_id", "goal_id", "status");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "kanban_tasks_team_id_assignee_id_status_idx" ON "kanban_tasks"("team_id", "assignee_id", "status");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "kanban_tasks_project_id_status_idx" ON "kanban_tasks"("project_id", "status");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "kanban_tasks_sort_index_idx" ON "kanban_tasks"("sort_index");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "kanban_task_links_child_id_idx" ON "kanban_task_links"("child_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "kanban_task_comments_task_id_created_at_idx" ON "kanban_task_comments"("task_id", "created_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "kanban_task_events_task_id_created_at_idx" ON "kanban_task_events"("task_id", "created_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "kanban_task_events_actor_id_created_at_idx" ON "kanban_task_events"("actor_id", "created_at");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "kanban_goals" ADD CONSTRAINT "kanban_goals_team_id_fkey" FOREIGN KEY ("team_id") REFERENCES "teams"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "kanban_goals" ADD CONSTRAINT "kanban_goals_creator_id_fkey" FOREIGN KEY ("creator_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "kanban_tasks" ADD CONSTRAINT "kanban_tasks_goal_id_fkey" FOREIGN KEY ("goal_id") REFERENCES "kanban_goals"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "kanban_tasks" ADD CONSTRAINT "kanban_tasks_team_id_fkey" FOREIGN KEY ("team_id") REFERENCES "teams"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "kanban_tasks" ADD CONSTRAINT "kanban_tasks_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "kanban_tasks" ADD CONSTRAINT "kanban_tasks_creator_id_fkey" FOREIGN KEY ("creator_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "kanban_tasks" ADD CONSTRAINT "kanban_tasks_reporter_id_fkey" FOREIGN KEY ("reporter_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "kanban_tasks" ADD CONSTRAINT "kanban_tasks_assignee_id_fkey" FOREIGN KEY ("assignee_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "kanban_tasks" ADD CONSTRAINT "kanban_tasks_target_folder_id_fkey" FOREIGN KEY ("target_folder_id") REFERENCES "assets"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "kanban_task_links" ADD CONSTRAINT "kanban_task_links_parent_id_fkey" FOREIGN KEY ("parent_id") REFERENCES "kanban_tasks"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "kanban_task_links" ADD CONSTRAINT "kanban_task_links_child_id_fkey" FOREIGN KEY ("child_id") REFERENCES "kanban_tasks"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "kanban_task_comments" ADD CONSTRAINT "kanban_task_comments_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "kanban_tasks"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "kanban_task_comments" ADD CONSTRAINT "kanban_task_comments_author_id_fkey" FOREIGN KEY ("author_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "kanban_task_events" ADD CONSTRAINT "kanban_task_events_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "kanban_tasks"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "kanban_task_events" ADD CONSTRAINT "kanban_task_events_actor_id_fkey" FOREIGN KEY ("actor_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,26 @@
|
||||
-- AlterEnum
|
||||
-- This migration adds more than one value to an enum.
|
||||
-- With PostgreSQL versions 11 and earlier, this is not possible
|
||||
-- in a single migration. This can be worked around by creating
|
||||
-- multiple migrations, each migration adding only one value to
|
||||
-- the enum.
|
||||
|
||||
|
||||
ALTER TYPE "NotificationType" ADD VALUE 'kanban_task_created';
|
||||
ALTER TYPE "NotificationType" ADD VALUE 'kanban_task_assigned';
|
||||
ALTER TYPE "NotificationType" ADD VALUE 'kanban_task_status_updated';
|
||||
ALTER TYPE "NotificationType" ADD VALUE 'kanban_task_updated';
|
||||
ALTER TYPE "NotificationType" ADD VALUE 'kanban_task_deleted';
|
||||
ALTER TYPE "NotificationType" ADD VALUE 'kanban_task_comment_created';
|
||||
|
||||
-- AlterEnum
|
||||
ALTER TYPE "WorkflowTaskType" ADD VALUE 'kanban_agent_run';
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "notifications" ADD COLUMN "kanban_task_id" TEXT;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "notifications_kanban_task_id_idx" ON "notifications"("kanban_task_id");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notifications" ADD CONSTRAINT "notifications_kanban_task_id_fkey" FOREIGN KEY ("kanban_task_id") REFERENCES "kanban_tasks"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
-- AlterTable: Change sort_index column collation to "C" on kanban_tasks
|
||||
ALTER TABLE "kanban_tasks" ALTER COLUMN "sort_index" TYPE TEXT COLLATE "C";
|
||||
|
||||
-- Recreate index on sort_index with "C" collation
|
||||
DROP INDEX IF EXISTS "kanban_tasks_sort_index_idx";
|
||||
CREATE INDEX "kanban_tasks_sort_index_idx" ON "kanban_tasks" ("sort_index" COLLATE "C");
|
||||
|
||||
-- Recreate compound index with "C" collation
|
||||
DROP INDEX IF EXISTS "kanban_tasks_team_id_status_sort_index_idx";
|
||||
CREATE INDEX "kanban_tasks_team_id_status_sort_index_idx" ON "kanban_tasks" ("team_id", "status", "sort_index" COLLATE "C");
|
||||
@@ -0,0 +1,17 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "kanban_task_assets" (
|
||||
"task_id" TEXT NOT NULL,
|
||||
"asset_id" TEXT NOT NULL,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "kanban_task_assets_pkey" PRIMARY KEY ("task_id","asset_id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "kanban_task_assets_asset_id_idx" ON "kanban_task_assets"("asset_id");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "kanban_task_assets" ADD CONSTRAINT "kanban_task_assets_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "kanban_tasks"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "kanban_task_assets" ADD CONSTRAINT "kanban_task_assets_asset_id_fkey" FOREIGN KEY ("asset_id") REFERENCES "assets"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
Warnings:
|
||||
|
||||
- The values [CANCELLED] on the enum `KanbanTaskEventType` will be removed. If these variants are still used in the database, this will fail.
|
||||
- The values [CANCELLED] on the enum `KanbanTaskStatus` will be removed. If these variants are still used in the database, this will fail.
|
||||
|
||||
*/
|
||||
-- AlterEnum
|
||||
BEGIN;
|
||||
CREATE TYPE "KanbanTaskEventType_new" AS ENUM ('CREATED', 'STATUS_CHANGED', 'ASSIGNED', 'UNASSIGNED', 'COMMENTED', 'CHANGES_REQUESTED', 'BLOCKED', 'UNBLOCKED', 'PRIORITY_CHANGED', 'GOAL_CHANGED', 'DEPENDENCY_ADDED', 'DEPENDENCY_REMOVED');
|
||||
ALTER TABLE "kanban_task_events" ALTER COLUMN "type" TYPE "KanbanTaskEventType_new" USING ("type"::text::"KanbanTaskEventType_new");
|
||||
ALTER TYPE "KanbanTaskEventType" RENAME TO "KanbanTaskEventType_old";
|
||||
ALTER TYPE "KanbanTaskEventType_new" RENAME TO "KanbanTaskEventType";
|
||||
DROP TYPE "public"."KanbanTaskEventType_old";
|
||||
COMMIT;
|
||||
|
||||
-- AlterEnum
|
||||
BEGIN;
|
||||
CREATE TYPE "KanbanTaskStatus_new" AS ENUM ('TODO', 'READY', 'IN_PROGRESS', 'BLOCKED', 'IN_REVIEW', 'DONE');
|
||||
ALTER TABLE "public"."kanban_tasks" ALTER COLUMN "status" DROP DEFAULT;
|
||||
ALTER TABLE "kanban_tasks" ALTER COLUMN "status" TYPE "KanbanTaskStatus_new" USING ("status"::text::"KanbanTaskStatus_new");
|
||||
ALTER TABLE "kanban_task_events" ALTER COLUMN "from_status" TYPE "KanbanTaskStatus_new" USING ("from_status"::text::"KanbanTaskStatus_new");
|
||||
ALTER TABLE "kanban_task_events" ALTER COLUMN "to_status" TYPE "KanbanTaskStatus_new" USING ("to_status"::text::"KanbanTaskStatus_new");
|
||||
ALTER TYPE "KanbanTaskStatus" RENAME TO "KanbanTaskStatus_old";
|
||||
ALTER TYPE "KanbanTaskStatus_new" RENAME TO "KanbanTaskStatus";
|
||||
DROP TYPE "public"."KanbanTaskStatus_old";
|
||||
ALTER TABLE "kanban_tasks" ALTER COLUMN "status" SET DEFAULT 'TODO';
|
||||
COMMIT;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user